Skip to content

fix: close spark retry hold gaps - #2014

Merged
ovitrif merged 4 commits into
masterfrom
fix/spark-retry-hold-gaps
Nov 24, 2026
Merged

ovitrif merged 4 commits into
masterfrom
fix/spark-retry-hold-gaps

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #2011
Refs: #2007

Description

  • Fixes a finishing node send releasing another node send of the same invoice still queued, which let a later Spark attempt drop the kept hash and later pay the invoice again: node sends in flight are now counted per invoice.
  • Fixes a send before Spark's first sync going out while Spark's local list can't be read: it is refused, as master's history read did. Breez spark-sdk 0.28.3 pays an invoice again under a new idempotency key on the Spark route, with no check against earlier payments. A local list that shows the invoice paid or pending now returns that result instead of sending. Raised in fix: spark retry follow-ups #2007 (review).
  • Fixes a send restored at launch staying muted when the node path asks for its invoice again after a relaunch, so a send screen waiting on it never got its outcome: the node path clears the mute, as a Spark send already did. Raised in fix: spark retry follow-ups #2007 (review).
  • Fixes a launch outcome showing when Spark's event arrives during the row write of a send settled while the app was closed: the mute is read while the hold is taken, a caller asking again clears it under the same lock, and a muted outcome claims its payment before the write. Raised in fix: spark retry follow-ups #2007 (review).
  • Fixes a node send whose hash write failed staying counted in flight, which held every later Spark attempt of its invoice until restart. Raised in fix: close spark retry hold gaps #2014 (comment).
  • Fixes a Spark send refused as unable to list its payments when Spark's first sync lands during its checks: it reads that once. Raised in fix: close spark retry hold gaps #2014 (review).
  • Fixes a retry's failure keeping an earlier attempt's fee and time when its Activity write failed and the app restarted before another refresh: the retry's ownership is kept in the cache until its row saves, or until its row shows paid or another attempt decides it. Raised in fix: spark retry follow-ups #2007 (review).

Out of Scope

  • iOS: the matching changes go to a separate bitkit-ios follow-up.
  • A send before the first sync of an invoice another device paid, which Spark's local list doesn't show yet, still goes out, as on master.

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

  • added LightningRepoTest.kt — a node send that ends keeps the hold of another node send of its invoice still queued
  • added SparkRepoTest.kt — a send before Spark's first sync is refused while its list can't be read
  • added SparkRepoTest.kt — a send before Spark's first sync skips an invoice its local list shows paid
  • added SparkRepoTest.kt — a send restored at launch reports its outcome once the node path asks for it again
  • added SparkRepoTest.kt — Spark's event during the row write of a send settled while closed reports nothing
  • added SparkRepoTest.kt — a retry's own failure keeps its details through a failed write and a restart
  • added LightningRepoTest.kt — a node send whose hash write fails releases its in-flight count, also when the next node send of the invoice fails
  • added SparkRepoTest.kt — a kept own failure is dropped once its row shows paid
  • added SparkRepoTest.kt — a send whose first sync lands during the invoice check is not refused
  • updated SparkRepoTest.kt — the failed-write test checks the row actually saved after Synced
  • updated SparkRepoTest.kt — the foreground-restart test uses a listed failure, so it exercises the first-start guard

Evidence

  • ran just compile, just test and just lint on dafb072: all pass.
  • the new tests fail on master's code and pass with this PR.
  • a fresh-context self review (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

  • Planning/scoping: Claude Opus 5.5 (reasoning: medium)
  • Implementation: Claude Opus 5.5 (reasoning: medium), Claude Sonnet 5.5 (reasoning: high)
  • Review: Not performed

- 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
@ovitrif ovitrif self-assigned this Nov 24, 2026
@ovitrif
ovitrif requested review from jvsena42 and pwltr November 24, 2026 14:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T14:32:42.455560Z cfebd44 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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)
@ovitrif ovitrif mentioned this pull request Nov 24, 2026
3 tasks
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from dafb072 (run).

Download bitkit-dev-debug universal APK (expires in 30 days).

@talosmachina talosmachina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: computeIfPresent drops the entry at zero, and every read now goes through .keys or containsKey. A cancellation inside addLdkSendHash before runCatching leaves the key counted, but that was already the case with the set on master.
  • Pre-sync local read sends an invoice it should hold: lightningSend returns Found(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.
  • sparkUnsavedOwnFailures survives a wipe: WipeWalletUseCase calls cacheStore.reset(), which replaces the whole AppCacheData, 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 earlierLightningSend clears restoredAtStart after isReported is read on line 734 but before takeUncertainSend gets the lock still sees the hold, gets Pending, and its outcome stays muted. The window is one holdRestoreMutex acquisition 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: reportListedSend claims reportedSendIds before recordActivity when muted, and the event handler's restoredAtStart.remove under holdRestoreMutex claims it otherwise. Either way the second reportedSendIds.add returns 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 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: ⚠️ not run. The PR asks for no device cases: concurrent sends, failed storage writes and process kills are unit-tested. perf: ⚠️ not measured. Expected in the noise: one extra local 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
@ovitrif

ovitrif commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

@jvsena42

Out of scope, not inline. canListPayments() is read a second time at :590, after lightningSend at :569.

Fixed in dafb072 here as well: the send reads it once before lightningSend, and your test is in.

@ovitrif
ovitrif requested a review from jvsena42 November 24, 2026 15:17

@pwltr pwltr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@ovitrif

ovitrif commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr

Thanks.

Low: A retry of an unexpired pre-restore invoice can be refused as first sync finishes.

Keeping it as is: it only refuses, nothing is sent, and the next attempt reads the synced state and goes through.

Low: Cache I/O for deferred Activity bookkeeping can interrupt Spark settlement.

Follow-up PR: the marker writes in recordActivity and the superseded-marker cleanup in refresh will be best-effort, so a failed cache write can't skip settlement, the hold release or the outcome.

Low: Restoring a metadata backup can log failed Spark attempt IDs

Keeping it as is: those ids are random UUIDs that Spark generates per attempt, with no amount, invoice or user data in them.

@ovitrif

ovitrif commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Merging: approved on dafb072 and CI is green. pwltr's cache-write Low goes to a small follow-up PR.

@ovitrif
ovitrif merged commit ddd0718 into master Nov 24, 2026
23 checks passed
@ovitrif
ovitrif deleted the fix/spark-retry-hold-gaps branch November 24, 2026 15:47
@ovitrif

ovitrif commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

@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.

@ovitrif

ovitrif commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr all three Lows from #2014 (review) are fixed in #2015:

  • Readiness is read once, after the listing, and the first-sync case with an operator FAILED status has its test.
  • The own-failure marker writes are best-effort, so cache I/O no longer interrupts settlement, hold release or a sync's reconciliation.
  • The restore log's cache copy leaves out the Spark attempt ids.

It also closes the node-side release race: a node send recorded while the Spark path releases the invoice's hash keeps it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A finishing LDK send clears another in-flight send of the same invoice

4 participants