Repository navigation
fix: close spark retry hold gaps - #2014
Conversation
- The node path's ask for an invoice clears its restored-at-start mute, as payInvoice does. - A muted outcome claims its payment before its row is written, and the mute stays until then. - A send before Spark's first sync is refused when its list can't be read: spark-sdk 0.28.3 pays a paid invoice again under a new key on the Spark route. - A retry's own failure stays owned across a restart until its row saves. Raised by @pwltr on #2007. Verified: just compile, just test, just lint
- Node sends in flight are counted per invoice, so one that ends no longer releases another still queued, which let a later Spark attempt pay the invoice again. - Before Spark's first sync, a send uses its local list: an invoice it shows paid or pending is not sent again. - A restored send's mute is read before its hold is taken, and a refresh retries an own failure kept from before a restart. Closes #2011 Verified: just compile, just test, just lint
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Verified: none (changelog fragment only)
Regtest APKDownload bitkit-dev-debug universal APK (expires in 30 days). |
talosmachina
left a comment
There was a problem hiding this comment.
No findings. Closes the gaps left in the Spark retry hold: node sends in flight are counted per invoice so one finishing no longer releases another, a send before Spark's first sync reads the local list instead of sending blind, the launch mute is cleared by the node path and read before the hold is taken, and an own failure whose row write failed is kept in the cache across a restart. Reviewed 0027b89 against cc3fde1, full tier (6 files, 257/32).
What I checked, and 5 candidates I ruled out
Read in full: the changed hunks of SparkRepo.kt in context (payInvoice, trySettleUncertainSend, reportListedSend, takeUncertainSend, restoreUncertainSends, earlierLightningSend, the payment event handler, recordActivity, refresh), LightningRepo.kt (earlierNodeSend, the node send path, listPaymentsKeepingSendHashes, keepLdkSendHashes), CacheStore.kt
Call sites traced: earlierLightningSend (only the node send path), restoredAtStart (all six uses), cacheStore.reset() (wipe use case)
Build: not built here; an unprompted review of bitkit-android never builds the branch, so this is reasoned from the code and from CI
CI: build-local green; build-and-test, lint, compose-ui and the local e2e jobs still pending when this was written
Ruled out
- Counter underflow or leak in
ldkSendsInFlight:computeIfPresentdrops the entry at zero, and every read now goes through.keysorcontainsKey. A cancellation insideaddLdkSendHashbeforerunCatchingleaves the key counted, but that was already the case with the set on master. - Pre-sync local read sends an invoice it should hold:
lightningSendreturnsFound(PENDING)for an uncertain or unlisted held send before this branch is reached, so the local read only adds a check. The cross-device case is the stated out-of-scope item. sparkUnsavedOwnFailuressurvives a wipe:WipeWalletUseCasecallscacheStore.reset(), which replaces the wholeAppCacheData, so the moved set is cleared where the in-memory one used to be. Old cache files decode, since the field has a default.- Launch mute read before the hold: a node-path retry whose
earlierLightningSendclearsrestoredAtStartafterisReportedis read on line 734 but beforetakeUncertainSendgets the lock still sees the hold, getsPending, and its outcome stays muted. The window is oneholdRestoreMutexacquisition on a send restored at launch, so I rated it below P1; it is what holds this at 4. - Event during the row write double-reports:
reportListedSendclaimsreportedSendIdsbeforerecordActivitywhen muted, and the event handler'srestoredAtStart.removeunderholdRestoreMutexclaims it otherwise. Either way the secondreportedSendIds.addreturns false.
Merge confidence: 4/5, one race ruled out only narrowly and CI not green yet.
Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the run metadata available to this reviewer does not name an effort level)
jvsena42
left a comment
There was a problem hiding this comment.
Code scan of 0027b89: no HIGH or MEDIUM, and no path to paying an invoice twice. The per-invoice count, the refusal before the first sync and the cache-kept ownership are each at least as conservative as master on the send decision. Three LOWs inline: two reproduced with failing tests, one from reading only.
Out of scope, not inline. canListPayments() is read a second time at :590, after lightningSend at :569. If Spark's first Synced lands between the two reads (on a restored wallet that includes the operator call at :580-585), the send is refused with "Spark could not list its payments" although the list is readable. A retry clears it, and nothing is sent. The merge base refuses the same way (same test, same failure), so it is not from this PR. Reading it once before lightningSend fixes it: test a send whose first sync lands during the invoice check is not refused.
tests (all four fail at 0027b89; with the inline fixes plus the out-of-scope one, SparkRepoTest 250/250 and LightningRepoTest 274/274)
diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
index dccb67448..8572b35ea 100644
--- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
+++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
@@ -1,5 +1,8 @@
package to.bitkit.repositories
+import kotlinx.coroutines.flow.Flow
+import java.io.IOException
+import androidx.datastore.core.DataStore
import app.cash.turbine.test
import breez_sdk_spark.Bolt11InvoiceDetails
import breez_sdk_spark.FeePolicy
@@ -1888,6 +1891,62 @@ class LightningRepoTest : BaseUnitTest() {
assertTrue(events.none { it is Event.PaymentFailed }, "an older node failure failed the Spark retry")
}
+ @Test
+ fun `a node send whose hash write fails releases its in-flight count`() = test {
+ sut = repoWith(CacheStore(failingOnceOnLdkHash("h")))
+ startNodeForTesting()
+ whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true)))
+ whenever(lightningService.listPayments()).thenReturn(emptyList())
+
+ assertTrue(runCatching { sut.payInvoiceWithNode("h").getOrThrow() }.isFailure)
+ verify(lightningService, never()).send(any(), anyOrNull(), anyOrNull(), anyOrNull())
+ whenever(sparkRepo.canSend(1_000uL)).thenReturn(true)
+ whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()))
+ .thenReturn(Result.success("h"))
+
+ val result = sut.payInvoice("h", 1_000uL)
+
+ assertFalse(result.exceptionOrNull() is PaymentPendingException, "a node send that never left held the invoice")
+ verify(sparkRepo).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())
+ }
+
+ @Test
+ fun `a failed hash write's in-flight count is released by the next node send of the invoice`() = test {
+ sut = repoWith(CacheStore(failingOnceOnLdkHash("h")))
+ startNodeForTesting()
+ whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true)))
+ whenever(lightningService.listPayments()).thenReturn(emptyList())
+ whenever(lightningService.send(any(), anyOrNull(), anyOrNull(), anyOrNull()))
+ .thenAnswer { throw AppError("Route not found") }
+
+ assertTrue(runCatching { sut.payInvoiceWithNode("h").getOrThrow() }.isFailure)
+ // The node retries and fails before anything leaves.
+ assertTrue(sut.payInvoiceWithNode("h").isFailure)
+ whenever(sparkRepo.canSend(1_000uL)).thenReturn(true)
+ whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any()))
+ .thenReturn(Result.success("h"))
+
+ val result = sut.payInvoice("h", 1_000uL)
+
+ assertFalse(result.exceptionOrNull() is PaymentPendingException, "a node send that never left held the invoice")
+ verify(sparkRepo).payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())
+ }
+
+ private fun failingOnceOnLdkHash(hash: String): DataStore<AppCacheData> = object : DataStore<AppCacheData> {
+ private val inner = InMemoryDataStore(AppCacheData(ldkSendHashesSeeded = true))
+ private var isArmed = true
+ override val data: Flow<AppCacheData> = inner.data
+ override suspend fun updateData(transform: suspend (t: AppCacheData) -> AppCacheData) =
+ inner.updateData { current ->
+ transform(current).also {
+ if (isArmed && hash in it.ldkSendHashes && hash !in current.ldkSendHashes) {
+ isArmed = false
+ throw IOException("disk full")
+ }
+ }
+ }
+ }
+
private fun nodeSend(hash: String, status: PaymentStatus) = PaymentDetails(
id = hash,
kind = PaymentKind.Bolt11(hash = hash, preimage = null, secret = null, description = null, bolt11 = hash),
diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt
index 492366be2..45ade0777 100644
--- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt
+++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt
@@ -5340,6 +5340,53 @@ class SparkRepoTest : BaseUnitTest() {
)
}
+ @Test
+ fun `an own failure kept in the cache is dropped once its row shows paid`() = test {
+ whenever(sparkService.isConnected).thenReturn(true)
+ whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()))
+ val store = CacheStore(InMemoryDataStore(AppCacheData(sparkUnsavedOwnFailures = setOf("a"))), clock)
+ val own = sentPayment(fees = 3).copy(id = "a", status = PaymentStatus.FAILED)
+ whenever(sparkService.listPayments()).thenReturn(listOf(own))
+ whenever { activityRepo.getActivity(eq("hash"), any()) }
+ .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.SUCCEEDED))))
+ val sut = createSut(store)
+ sut.start(0).getOrThrow()
+ advanceUntilIdle()
+
+ sparkEvents.emit(SdkEvent.Synced)
+ advanceUntilIdle()
+
+ assertEquals(emptySet(), store.data.first().sparkUnsavedOwnFailures)
+ }
+
+ @Test
+ fun `a send whose first sync lands during the invoice check is not refused`() = test {
+ val restored = AppCacheData(sparkHistoryUnseededSince = now.epochSeconds, sparkRestoredAt = now.epochSeconds)
+ val store = CacheStore(InMemoryDataStore(restored), clock)
+ whenever(sparkService.isConnected).thenReturn(true)
+ whenever { sparkService.getInfo() }.thenReturn(info(10_000uL).copy(lastSyncedAt = null))
+ val prepared = prepared(feeSats = 0uL, createdAt = (now.epochSeconds - 600).toULong(), expirySecs = 3_600uL)
+ whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared)
+ whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0))
+ val sut = createSut(store)
+ sut.start(0).getOrThrow()
+ assertFalse(sut.canListPayments())
+ // Spark's first sync lands while the operators are asked about the pre-restore invoice.
+ whenever { sparkService.lightningSendStatus(any()) }.doSuspendableAnswer {
+ whenever { sparkService.getInfo() }
+ .thenReturn(info(10_000uL).copy(lastSyncedAt = now.epochSeconds.toULong()))
+ sparkEvents.emit(SdkEvent.Synced)
+ repeat(100) { if (!sut.canListPayments()) delay(10) }
+ assertTrue(sut.canListPayments(), "the first sync never landed")
+ null
+ }
+
+ val result = sut.payInvoice("lnbc1280n1send", 128uL)
+
+ assertTrue(result.isSuccess, "refused with '${result.exceptionOrNull()}'")
+ verify(sparkService).send(any(), anyOrNull())
+ }
+
/** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */
private suspend fun sentKey(): String =
argumentCaptor<String>().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue
Device gate: listPayments() on a send before the first sync, and one extra cache read per refresh and per saved row.
Reviewer model: claude-fable-5-2 (primary), claude-opus-5-5 (verifier, coordinator)
Reasoning effort: Not exposed
- A node send whose hash write fails or is cancelled releases its in-flight count. - A kept own failure is dropped once its row shows paid or another attempt decides it. - The restored-at-start mute is read while the hold is taken and cleared by a caller under the same lock, so a caller asking again always gets the outcome. - A Spark send reads whether it can list payments once, so a first sync during its checks doesn't refuse it. Raised by @jvsena42 on #2014; tests from his review. Verified: just compile, just test, just lint
pwltr
left a comment
There was a problem hiding this comment.
Reviewed dafb072.
Low: A retry of an unexpired pre-restore invoice can be refused as first sync finishes. SparkRepo.kt:571 captures readiness before SparkRepo.kt:1708 checks it again for the listing. If sync completes between those reads and both the list and the operators show FAILED, the restore guard still rejects the retry using the earlier value at SparkRepo.kt:587. The base reads readiness after the listing and permits this retry. The new first-sync test returns no operator status and misses the FAILED branch.
Low: Cache I/O for deferred Activity bookkeeping can interrupt Spark settlement. If saving the marker throws after either an Activity read failure or an upsert failure (SparkRepo.kt:2172, SparkRepo.kt:2216), the synchronous send returns a storage error before emitting the failure, listed settlement can drop the event after releasing the hold, and the SDK callback can exit before releasing the hold or emitting its outcome (SparkRepo.kt:660, SparkRepo.kt:773, SparkRepo.kt:2121). A failed deletion of a superseded marker during refresh can also skip reconciliation of unrelated holds and the withdrawal journal for that sync (SparkRepo.kt:1503, SparkRepo.kt:2074).
Low: Restoring a metadata backup can log failed Spark attempt IDs if the snapshot captured a marker before its Activity write recovered. The diagnostic copy at BackupRepo.kt:1340 retains sparkUnsavedOwnFailures, and the saved restore log can be attached to a later support request.
Review details
Quick review
Model: Claude Opus 5.5
Reasoning effort: high
General review
Model: GPT-6.2 Sol
Reasoning effort: high
Combined review
Model: GPT-6.2 Sol
Reasoning effort: high
|
Thanks.
Keeping it as is: it only refuses, nothing is sent, and the next attempt reads the synced state and goes through.
Follow-up PR: the marker writes in
Keeping it as is: those ids are random UUIDs that Spark generates per attempt, with no amount, invoice or user data in them. |
|
Merging: approved on dafb072 and CI is green. pwltr's cache-write Low goes to a small follow-up PR. |
|
@pwltr the cache-write Low (making the own-failure marker writes best-effort) will ride with the next Android Spark send change rather than a PR of its own. |
|
@pwltr all three Lows from #2014 (review) are fixed in #2015:
It also closes the node-side release race: a node send recorded while the Spark path releases the invoice's hash keeps it. |
Closes #2011
Refs: #2007
Description
Out of Scope
Design
N/A — no UI changes.
Preview
N/A
QA Notes
Setup
N/A — the cases need concurrent sends, failed storage writes and process kills, covered by unit tests.
Journeys
N/A — no user-visible behaviour change on the happy paths.
Manual Tests
N/A — see Automated Checks.
Automated Checks
LightningRepoTest.kt— a node send that ends keeps the hold of another node send of its invoice still queuedSparkRepoTest.kt— a send before Spark's first sync is refused while its list can't be readSparkRepoTest.kt— a send before Spark's first sync skips an invoice its local list shows paidSparkRepoTest.kt— a send restored at launch reports its outcome once the node path asks for it againSparkRepoTest.kt— Spark's event during the row write of a send settled while closed reports nothingSparkRepoTest.kt— a retry's own failure keeps its details through a failed write and a restartLightningRepoTest.kt— a node send whose hash write fails releases its in-flight count, also when the next node send of the invoice failsSparkRepoTest.kt— a kept own failure is dropped once its row shows paidSparkRepoTest.kt— a send whose first sync lands during the invoice check is not refusedSparkRepoTest.kt— the failed-write test checks the row actually saved afterSyncedSparkRepoTest.kt— the foreground-restart test uses a listed failure, so it exercises the first-start guardEvidence
just compile,just testandjust linton dafb072: all pass.gemini-4-neon-high) of the first commit found one High and two Mediums, fixed in cfebd44: the pre-sync list read now uses its result, the launch mute is read before the hold is taken, and a refresh retries an own failure kept from before a restart.Gaps
None.
Models used
Claude Opus 5.5(reasoning:medium)Claude Opus 5.5(reasoning:medium),Claude Sonnet 5.5(reasoning:high)