Skip to content

fix: spark follow-ups - #1957

Merged
ovitrif merged 101 commits into
masterfrom
fix/spark-follow-ups
Nov 24, 2026
Merged

ovitrif merged 101 commits into
masterfrom
fix/spark-follow-ups

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1802
Closes #1819
Closes #1840
Closes #1848
Closes #1919
Closes #1976
Closes #1983
Closes #1982
Closes #1984
Closes #1986
Twin: synonymdev/bitkit-ios#1355

This PR closes the remaining Spark follow-ups from bitkit-android#1946. It also carries the Android side of three iOS issues:

Description

  • Move to Spark keeps running after its screen closes. A new app-scoped MoveToSparkManager holds the move and its outcome. Pressing Back during a move no longer cancels the wait. Opening the screen again shows the same move. When a closed screen's cleanup runs late, it leaves a reopened screen's quote alone. A wallet wipe drops the move, so the next wallet starts on a new quote. A move waiting on its payment reads the node's stored payment again while it waits, so a missed outcome still ends it. Spending and Lightning Connections keep offering Move to Spark while a move is kept for its result, also once too little is left to move again.
  • A move's payment hash is persisted and backed up. It is stored in CacheStore, so after a restart the move is still recognised: no received notice, and it stays a Move to Spark row. The metadata backup carries the hashes as moveToSparkPaymentHashes, as bitkit-ios does: lowercase hex, sorted, left out when there are none, and read as none when the value is not a list of strings. A restore adds them to the device's own.
  • Tests for MoveToSparkRepo.move(). They cover:
    • the fee cap passed to payInvoiceOverLdk and the fee reported back
    • a failure matched by payment id
    • a payment with no outcome before the timeout
    • the hash surviving a restart
  • A move to Spark shows in Activity as "Move to Spark". The row and the detail screen reuse the transfer row's icon and layout. They show it as outgoing, with the moved amount plus the routing fee. A pending or failed move keeps the row, with Pending or Failed as its subtitle and the usual pending or failed icon. Moves list under Other, with transfers, and not under Sent. Both apps build it the same way; a later design can restyle it.
  • A Lightning invoice is not sent again through Spark while an earlier Spark attempt on it is unresolved. An attempt is unresolved while it is in Spark's send call, and after it until Spark settles it or its invoice expires, also when Spark took it but its list doesn't show it yet. Until Spark settles or fails it, the payment shows as pending: a retry is refused as pending on both rails. A failure Spark dates no more than 10 s before the send's start, the room left for Spark's clock to differ from the phone's, is the send's own: it ends the send at once, marks its row failed, tells the send screen and allows a retry. The start is the time already saved just before the send, and it is saved at least 11 s past every failure Spark dated for the invoice that the app knows from Spark's list, its events or a send's result, so an earlier attempt's failure never reads as a retry's own; nothing new is stored. A send is refused before anything goes out when Spark's list can't be read to date it. After a restore, before Spark syncs, a Spark send of a pre-restore invoice the Spark operators show failed is refused until Spark syncs, as nothing can date that failure yet. A failure Spark dates earlier is an earlier attempt's, and it changes nothing: the settled-send lookup reads no failure and the Activity row stays pending, so an earlier attempt's late failure leaves the send held; at the invoice's expiry it fails the send's row in place, which keeps its own amount and fee (bitkit-android#1848). The same holds for any failure while the send is still in Spark's send call, which its result settles, and for another attempt's failure while Spark lists the retry it took as pending or paid. Otherwise a send in doubt ends on its success, or once its invoice expired and Spark synced, or reported a failure, since; that also marks its row failed and tells the send screen. When Spark lists several attempts on one invoice, only the one that decides it writes the row: a success over a pending one over a failure, the latest on a tie. This matches bitkit-ios. A send that returns pending reads a settled outcome again once the send screen tracks it, so an outcome handled between the two still resolves it, and the pending screen then shows Sent; only that send's own contact is attached, so a payment the send screen moved on to keeps its contact.
  • The claim poll stops quoting once Spark says the early claim is waiting. It then watches for the deposit to leave the unclaimed list and shows Adding. The early claim is capped at the fee the user approved, never above the one the swiped quote showed, also when a max transfer's swipe prices it again, so Spark claims any later offer within it by itself, and one above it waits for the claim at maturity. This is the Android side of bitkit-ios#1264.
  • Unimportable stored exit data no longer blocks exit backups. This covers stored data that doesn't decode, and data that Spark rejects as invalid input. That data is kept unchanged under SPARK_EXIT_REJECTED_ plus the first 16 hex digits of its SHA-256, as bitkit-ios does in the same VSS store, and the fresh export is uploaded. Each copy has its own key, so none replaces another, and a copy already kept is not uploaded again. A staged restore is dropped only when it holds that same data. Restored data that Spark rejects as invalid input is set aside the same way before the upload: the stored backup when it still holds that data, otherwise a new backup envelope around it. Then it is dropped instead of being retried on every start, and the stored backup is merged into Spark before the upload, so exit data another device stored is never replaced. Dropping a rejected staged copy asks for the stored backup to be merged again, and every upload merges it until one merge succeeds, also after a failed attempt. Stored data Spark can't import is replaced only when it is still the stored one after it was set aside. A staged restore is compared and dropped under the same lock that stages and imports it, so a restore retried meanwhile keeps its new copy. A restore that finds stored exit data it can't read sets it aside the same way and reports the exit data as not restored. Any other error still blocks the upload. The restore's cache log leaves out the move hashes. This is the Android side of bitkit-ios#1268.
  • The Spark strings are translated in every locale. This adds the missing keys and refreshes the ones whose English changed. lightning__setting_up__step_seen, lightning__setting_up__step_sent and lightning__spending_confirm__up_to are not in English, so they are not added.
  • The liveness comment in LightningRepo.kt is reworded (bitkit-android#1919).
  • bitkit-ios#1321 needs no Android change. release.yml already fails early on a blank key, and release-internal.yml leaves the key optional on purpose.
  • A restore reports exit data Spark rejects as not restored (bitkit-android#1976, from bitkit-android#1979). The restore connects Spark itself and imports the staged exit data at once, so onboarding lists it as not restored when Spark rejects it. Spark's events are collected before the restore connects it, and staging and importing share one lock.
  • The earlier retry hold and its saved journal are removed (bitkit-android#1983). The rule above makes the per-attempt ids, taken retries, clock-skew windows and row-writer journal unnecessary, so a retry Spark took can no longer stay held past its invoice's expiry.

Out of Scope

Design

N/A — no design available. The row reuses the existing Lightning-era Transfer activity row (component, icon, layout), titled "Move to Spark"; a later design can restyle it.

Preview

Activity shows a move as one outgoing Move to Spark row, and its detail shows the moved amount, the routing fee and the transfer icon:

row2x.mp4

QA Notes

Setup

  • Journey J1: the local Spark regtest from bitkit-android#1774's QA Notes. That is the spark profile of bitkit-docker, plus a dev build pointed at it, with one channel to the SSP.
  • Preview:
    • A dev build of this PR, on a fresh regtest wallet with dev mode on.
    • The build carried a local-only hook that is not in this PR. After Dev Settings → Generate Test Activities, it marks one generated Lightning send as a move.

Journeys

  • J1: updated move-to-spark.xml — after the move, Activity lists a "Move to Spark" transfer row with the moved amount plus the routing fee, and its detail is titled "Move to Spark"

Manual Tests

N/A

Automated Checks

  • added MoveToSparkRepoTest.kt — the move pays capped at the quoted fee and reports the fee paid, matches a failure by payment id, reports a payment with no outcome in time as in flight, and keeps a move's hash after a restart, and a move whose outcome was missed while the node was down reads it once the node is back
  • added MoveToSparkViewModelTest.kt cases — leaving during a move keeps it and shows it again, leaving while it's in flight keeps waiting, leaving after it settled quotes anew, a closed screen's late cleanup leaves a reopened screen's quote, wiping the wallet drops an in-flight move and quotes anew
  • added AppViewModelSendFlowTest.kt cases: a pending Spark send whose success was handled before it was tracked resolves as sent, and leaves the next send's contact alone
  • added a SparkFundingViewModelTest.kt case: a max transfer's swipe approves no higher Instant claim fee than the one shown
  • added SparkRepoTest.kt cases — the claim poll stops quoting once Spark waits for the early claim and shows Adding once it claims; a failure listed or reported while a send is in doubt or in Spark's send call is no settled send event, and an earlier attempt's late failure event leaves a send in doubt pending, refused and with no failed row, also when Spark took the retry; a retry Spark took stays held while Spark lists only an earlier attempt's failure; a send whose caller was cancelled inside Spark's send call ends at its invoice's expiry without a restart; an older attempt's failure event leaves the row of a later failed attempt; a send Spark refuses for its balance stays in flight until its hold is cleared; a sync while the poll settles a send in doubt reports its failure once; a send's own failure the poll settled first is reported once when Spark's event follows; a retry Spark never lists reports its failure at expiry past an earlier failure already reported; a retry read as pending while the poll settles a send keeps its own success event; a retry that enters Spark's send call as the poll settles a send never shows the earlier send's failure and keeps its saved expiry; a retry that enters Spark's send call while a failure event is handled keeps its hold and saved send, and never shows the earlier failure; a send in doubt ends at once on its own failure, and a retry then sends again; a send in doubt fails its row and reports its failure once its invoice expires with only an earlier failure listed; a send that failed lets a retry of its invoice send again; a retry's success decides its Activity row over an earlier attempt's failure; an uncertain retry's row stays pending after a restart while Spark lists only its older failure; a held send whose own failure the launch sync lists frees its invoice even when the next read of Spark's list fails; a retry started 5 s after an earlier attempt's failure stays held while Spark lists only that failure, and at expiry fails its own row in place, also through the next start's sync; a send is refused before it goes out while Spark can't list its payments; a send held while a sync writes its list is not settled from that list; an unsynced Spark refuses a pre-restore invoice the operators show failed and sends one they show no send of; dropping rejected staged exit data asks for the stored backup to be merged again; staged exit data Spark rejects reads as rejected while other import failures stay pending
  • added BackupRepoTest.kt cases — stored exit data that Spark can't import, or that doesn't parse, is kept apart and the upload goes through; each copy goes under its own digest key and never the plain key, and a copy already kept is not uploaded again; a restore sets aside exit data it can't read and reports it not restored; a rejected staged copy merges a stored backup another device replaced before the upload, also on the next upload after a failed merge, and stored data replaced while unreadable data was set aside is merged first; staged exit data Spark rejects is set aside as the stored backup that holds it, or on its own once the stored one moved on, and dropped; other merge errors still block it; the metadata backup carries the move hashes lowercase and sorted, leaves them out with none, and a restore adds them to the device's
  • added BackupJsonTest.kt case — move hashes read from a list of strings, and any other value reads as none
  • added ActivityListViewModelTest.kt case — a move, failed too, lists under Other and not under Sent
  • added LightningConnectionsViewModelTest.kt case — a move kept for its result keeps Move to Spark offered once nothing is left to move
  • updated WipeWalletUseCaseTest.kt — a wipe resets the Move to Spark manager
  • updated NotifyPaymentReceivedHandlerTest.kt and AppViewModelSendFlowTest.kt — the move check is now a suspend call

Evidence

  • Preview: tested on an Android emulator (Pixel profile, 896 × 1994, 320 dpi) at 001af49fc, with the local hook.
    • All Activity showed the marked send as Move to Spark, outgoing, at 733,712, which is 733,585 plus a 127 sat fee. It had the purple transfer icon.
    • Its detail was titled Move to Spark and showed fee 127.
    • 114f3a88c adds the pending and failed move rows and lists moves under Other. Unit tests cover those; the Preview doesn't show them.
  • Checks: just compile, just test, detekt and lintDevDebug pass.

Gaps

  • J1 on the local Spark stack was not run for this PR: a real move, Back during a move, and the row after a real move. The unit tests above cover Back during a move. The Preview shows the row on generated data.

Models used

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

A late failure event of an earlier attempt no longer ends the hold of an uncertain retry of the same invoice. After a waiting early claim, the Instant claim poll stops quoting and only watches for the claim. Also rewords the spark send liveness comment.
Stub the now-suspending move check in the send flow tests, drop translations
of two keys English marks untranslatable, wrap long lines, and add the
Activity row to the move-to-spark journey.

Verified: detekt, lintDevDebug, MoveToSparkRepoTest, BackupRepoTest, AppViewModelSendFlowTest, MoveToSparkViewModelTest
A closed Move to Spark screen's late cleanup no longer clears the quote of a
screen opened after it. Skipping unimportable stored exit data drops a staged
restore only when it holds that same data.

Verified: detekt, BackupRepoTest, MoveToSparkViewModelTest, SparkRepoTest, MoveToSparkRepoTest
@ovitrif ovitrif added this to the 3.2.0 milestone Nov 17, 2026
@ovitrif ovitrif self-assigned this Nov 17, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 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-17T14:36:35.051920Z 8b6dfd7 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.

@ovitrif
ovitrif requested review from a team, ben-kaufman and pwltr and removed request for a team November 17, 2026 14:34
@ovitrif ovitrif removed this from the 3.2.0 milestone Nov 17, 2026
@greptile-apps

greptile-apps Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[High impact] The PR reaches payment tracking, wallet activity, Spark claiming, and exit-backup workflows.

Clear the move manager during wallet wipe before merging.

Findings

  1. P1 Old move survives wallet wipe ▶
  2. P2 Portuguese messages contain broken words ▶

Summary

This PR keeps Move to Spark running after its screen closes and remembers move hashes across restarts.

  • A Move to Spark payment keeps running after its screen closes.
  • Move to Spark payments appear as one outgoing Activity entry.
  • Spark claim polling waits for an early claim instead of asking for more quotes.
  • An earlier Spark payment failure no longer ends a retry’s hold.
  • Unimportable Spark exit data no longer blocks a fresh backup upload.
  • Spark screens and wallet notices have translated text across the app’s locales.
  • The Lightning liveness note and move-payment tests are updated.

Acknowledged behavior: ovitrif explicitly describes the missing restored send time and the decision to let failure events end that hold after restart.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Screen[Move screen] --> Manager[App-scoped move manager]
  Manager --> Repo[Move repository]
  Repo --> Cache[Persist move hash]
  Repo --> LDK[Send over Lightning]
  LDK --> Outcome[Wait for payment outcome]
  Outcome --> Manager
  Cache --> Activity[Move title and icon in Activity]
  Wipe[Wallet wipe] --> Stores[Clear wallet stores and node]
  Wipe -. Missing reset .-> Manager
Loading

Reviews (1) · Last reviewed commit: "fix: keep staged exit data and a reopene..." · Reviewed by Greptile

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from 33f1958 (run).

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

Back up move to Spark hashes in the metadata envelope as bitkit-ios does
(lowercase, sorted, left out when empty, read leniently) and merge them on
restore. Set unimportable exit data aside under SPARK_EXIT_REJECTED, keeping
the first copy and a different one under its digest. List moves under Other,
not Sent, and keep a pending or failed move's row with its status.

Verified: just test, just lint
@ovitrif

ovitrif commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 114f3a88c to match bitkit-ios on three points:

  • Move hashes in the metadata backup: they ride as moveToSparkPaymentHashes (lowercase, sorted, left out when empty, read as none when unreadable), and a restore adds them to the device's own.
  • Exit set-aside key: unimportable exit data now goes under SPARK_EXIT_REJECTED, the key bitkit-ios uses in the same store. A copy already kept is never replaced; a different one goes under the key plus the first 16 hex digits of its SHA-256.
  • Move rows: moves list under Other and not Sent, and a pending or failed move keeps its row with Pending or Failed as its subtitle.

An earlier attempt's late failure now returns before it is recorded, so the
uncertain retry's Activity row stays pending, as on bitkit-ios. The
move-to-spark journey takes the iOS wording for its last steps.

Verified: just test, just lint
@ovitrif

ovitrif commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 97b31e1c6. A late failure from an earlier attempt now returns before it is recorded, so a retry still in doubt keeps its Activity row pending, as on bitkit-ios. The move-to-spark journey also takes the iOS wording for its last two steps.

@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 in the paths I read. Spark follow-ups: moves to Spark are kept in the cache and backup so Activity shows each as one move, the move screen's state now lives in a singleton MoveToSparkManager, unimportable Spark exit backups are set aside, an older failure no longer settles an uncertain retry, and QuickPay re-checks its limits at dispatch. Reviewed 114f3a8, static: per the Bitkit track rules this branch was not built here.

What I checked, and 4 candidates I ruled out

Read: MoveToSparkRepo, MoveToSparkManager, MoveToSparkViewModel, CacheStore.addMoveToSparkHash, BackupPayloads (LenientStringListSerializer), the BackupRepo exit-backup and restore hunks, the SparkRepo hunks (uncertain sends, early claim wait, mergeRemoteExitBackup), ActivityListViewModel, ActivityRow / ActivityIcon / ActivityDetailScreen.
Not read in full: the middle of the QuickPayRepo diff (LNURL admission and the dispatch path), and the tests.

Ruled out

  • Hash case mismatch: every write and read of moveToSparkHashes lowercases, including restore merge and isMoveToSpark.
  • A move lost on process death before payment: the hash is persisted before payAndWait, so a restart still hides both legs.
  • Rejected exit backup overwritten: setAsideRejectedExitBackup never replaces an existing copy and suffixes a different one with its SHA-256 prefix.
  • Screen reset cancelling a running move: reset returns while isMoveInFlight, and a newer screen token blocks an older screen's reset.

Merge confidence: 3/5, part of the diff (QuickPay dispatch, tests) was not read, so this is the ceiling whatever the reviewed paths showed.

Verified: just compile, just test, just lint
@ovitrif

ovitrif commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed f7184ed: three changes, each to match synonymdev/bitkit-ios#1355.

  • Retry hold allows for clock skew. A late Spark failure counts as an earlier attempt's only when it is dated more than 10 s before the retry started. A failure within that window is the retry's own and ends its hold.
  • Restored exit data that Spark rejects is set aside. Before each exit backup upload, Spark tries the staged restore again. When it rejects the data as invalid input, the stored backup is set aside if it still holds that data. Otherwise the staged data is set aside in a new backup envelope. Then the staged file is dropped and the fresh export uploads.
  • Each rejected copy has its own key. Rejected copies go under SPARK_EXIT_REJECTED_ plus the first 16 hex digits of their SHA-256, and the plain key is never written.

New cases in SparkRepoTest.kt and BackupRepoTest.kt cover all three. The clock-skew case fails without the margin.

@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 at f7184ed: no findings.

f7184ed already closes the one candidate that survived verification, the late-failure compare with no clock-skew margin. isEarlierFailureOfUncertainSend now allows RAIL_CLOCK_SKEW_SECONDS = 10 (SparkRepo.kt:1787), as iOS does. I reproduced the old behaviour with a unit test before the push: a phone clock 3 s ahead of Spark dropped the send's own PaymentFailed, leaving the send screen pending and the invoice refused until it expired. The 10 s margin makes it pass, and the older-failure cases still hold.

What I checked:

  • Double pay. reset() is skipped while isMoveInFlight, and start() doesn't quote while it keeps an outcome. Done(InFlight) offers only OK, so no path from the UI quotes over a running move. A restart mid-move re-quotes with a new invoice, and the pending HTLC lowers movableSats. The fee cap is still feeCapMsat(quote.feeSats), now tested.
  • Backup. Spark and Move to Spark aren't in v3.1.1, so there's no installed format. The new field is read as null from old envelopes and ignored by old apps (ignoreUnknownKeys). LenientStringListSerializer returns empty for malformed values. Restore takes the union of lowercased hashes. Wipe resets CacheStore (WipeWalletUseCase.kt:122).
  • Exit set-aside (f7184ed). Rejected staged exit data is copied aside under a digest-keyed SPARK_EXIT_REJECTED_* key before discardStagedExitState deletes it. The delete happens only when the file still holds the same data, so a failed set-aside keeps the staged file for the next upload. A transient import failure stays Pending.
  • Cancellation. It propagates through the move and the exit paths. quoteJob is touched only from the main thread, and generation checks guard the state writes.
  • iOS twin. synonymdev/bitkit-ios#1355 already had the skew margin and a synchronous move-hash read.

perf: mildly relevant. After Spark reports Waiting, the claim poll does one listUnclaimedDeposits per 5 s tick instead of a list plus a quote. Each Activity row now runs its own moveToSparkHashes collector.

Device gate (partial): f7184ed — not run yet; pending: transfer/move-to-spark.xml with Back during a move and reopen, Activity rows and details for a done, pending and failed move, and Activity scroll frame timing with 100+ rows. Device results and the final review type follow in a second review.

@ovitrif

ovitrif commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed ab895d2: two changes, each to match synonymdev/bitkit-ios#1355.

  • A retry's send time survives a restart. It is stored with the in-doubt send, so after a restart a late failure from an earlier attempt still can't end the retry's hold or mark its row failed. Sends kept before this change have no send time, and their own failure still ends the hold.
  • A restore sets aside exit data it can't read. The data goes under its digest key, and the restore completes instead of reporting the exit category as failed.

New cases in SparkRepoTest.kt and BackupRepoTest.kt cover both. The restart case fails without the stored send time.

Verified: just format, just compile, just test, just lint
@ovitrif

ovitrif commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

cc0cc6c: a failure event no longer drops a retry's hold. The event checked the hold, then read Spark's list and wrote the row before ending the hold and the saved send for the invoice, so a retry that entered Spark's send call in between lost both. The event now checks again under the restore lock right before ending them, as the poll does since 5f79ba2.

Verified: just format, just compile, just test, just lint
The sync that records Spark's list now settles each held send from that
same list, so a send whose own failure Spark lists frees its invoice at
launch even when the next read of Spark's list fails.

Verified: just format, just compile, just test, just lint
pwltr
pwltr previously requested changes Nov 21, 2026

@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 d20d1c7. Spark's ten-second clock allowance in SparkRepo.kt:1535 can match a previous attempt's failure to a different attempt on the same invoice. For example, the first attempt fails, the user retries five seconds later, and the retry loses its response while history still shows only the first failure.

Medium: The poll and the delayed failure callback can both release the live retry's hold and saved send (SparkRepo.kt:688, SparkRepo.kt:741, SparkRepo.kt:1990, SparkRepo.kt:2009). That allows another submission, including over a Lightning channel, while Spark may still finish the retry.

Medium: The pending-screen lookup can independently use that first failure before the hold is cleared (SparkRepo.kt:1518, AppViewModel.kt:7991, AppViewModel.kt:8022). It reports the retry as failed, clears its pending contact context and stops tracking it on the Pending screen. Bind failure to the attempt before releasing the invoice or resolving the screen.

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

A retry's saved start is floored 11 s past every failure Spark dated for
its invoice, or past now when Spark's list can't be read, so an earlier
attempt's failure inside the clock margin never reads as the retry's own.
A failure only fails an existing send row in place, so at expiry the
retry's row keeps its own amount and fee.

Verified: just format, just compile, just test, just lint
@ovitrif

ovitrif commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr the clock-margin case from your review of synonymdev/bitkit-ios#1355 applies here too, as this PR uses the same date rule. Fixed in 8573baf:

  • A retry's saved start is now at least 11 s past every failure Spark dated for its invoice that the app knows, from Spark's list, its payment events or the send's own result. In your case (A starts at 995 and fails, B starts at 1000), B's start is saved past A's failure, so A's failure no longer ends B's hold or replaces B's amount and fee.
  • At expiry, with only A's failure listed, B's row fails in place and keeps its own details, also when a later sync lists A's failure again.
  • The floor is still only the saved start, so nothing new is persisted, and a restart reads it back.

The remaining gap is a retry starting before the app knows the earlier attempt's failure. It can't happen:

  • An attempt whose outcome is unknown keeps its hold until Spark lists or settles it, so a retry can't start before. Only errors that guarantee nothing reached Spark clear the hold: an expired invoice, a short balance, and the deadline and exit checks before the call.
  • A failure learned in an earlier run is read from Spark's list at the retry. When that list can't be read, the start is saved past now, so any failure Spark could already have dated falls before it.

Also in 2372752: the launch sync now settles a held send from the list it just read, so a send whose own failure Spark lists frees its invoice even when the next read of the list fails.

Covered by new cases in SparkRepoTest.kt.

@ovitrif

ovitrif commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

The poll and the delayed failure callback can both release the live retry's hold and saved send

The pending-screen lookup can independently use that first failure before the hold is cleared

@pwltr addressed in 8573baf, which this comment explains. A retry's saved start is now at least 11 s past the earlier attempt's failure, so in your five-second case that failure reads as the earlier attempt's on every path that reads it: the poll, the failure event, and the pending-screen lookup. The retry stays held and pending until its own outcome or its invoice's expiry.

The sync settles only the holds taken before it read Spark's list, so a
send held while it writes activity is never settled from that older list.
A send whose start can't be dated because Spark can't list its payments
is refused before anything goes out, instead of saving a start past now
that made its own failure read as an earlier attempt's.

Verified: just format, just compile, just test, just lint
After a restore, before Spark syncs, its list can't date an earlier
attempt the operators show failed, and a send must start past that
failure, so a Spark send of such an invoice is refused until Spark syncs.
An invoice the operators show no send of still sends.

Verified: just format, just compile, just test, just lint
@ovitrif

ovitrif commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed ff2687e: after a restore, before Spark syncs, a Spark send of a pre-restore invoice that the Spark operators show failed is now refused until Spark syncs. Spark's list can't yet date that earlier failure, and a send must start past it so the failure never reads as its own. An invoice the operators show no send of still sends, and the node's rail is unchanged. This matches bitkit-ios.

@ovitrif

ovitrif commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

@jvsena42 this PR is frozen at ff2687e, with CI green. From here only a finding that could lose money or pay twice gets a fix in this PR; anything else goes to one follow-up PR after the merge. Requesting your review on this head.

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

Delta review of the 31 commits since my approval at ec4051d, now at ff2687ee9: no HIGH or MEDIUM, two LOWs inline, and a third as a reply on my earlier thread at SparkRepo.kt:800, which the redesign in 904e629 reopened.

Checked and clean:

  • No double pay: a send starts at least 11 s past every failure Spark lists for the hash (sendStartedAt, :1990-1997) and is refused if the list can't be read; a retry can't start while an earlier attempt is pending and unexpired, or held.
  • An older attempt's event doesn't settle a retry (guards at :2048, :2054-2057, :2068, :2095, :1543).
  • Every hold is bounded by invoice expiry; a send whose caller was cancelled is now restored on the next Synced event, not only on restart.
  • One lock (holdRestoreMutex), five sites, none nested, so no deadlock. Leaving flight is NonCancellable.
  • Wipe clears memory and cached holds (:327-329, WipeWalletUseCase.kt:124).
  • iOS twin synonymdev/bitkit-ios#1355: the HIGH from fa92ad3 (attempt at 995, retry at 1000) is absent here, because 8573bafc7 moves the retry's start to 1006. The startup item is fixed by 237275212, and the attempt-id and row-writer items don't apply since that layer was removed.

The delta has no string or journey changes. It is performance-relevant, since it re-times background work: the extra sync per send (inline) and the hold poll.

Device gate (partial): ff2687ee9 — not run yet; pending: on the local Spark stack, a Spark Lightning send that settles at once (count syncWallet calls per send in the app log against ec4051d), force-stop while a send is Pending and relaunch after it settles, and a failed send followed by a retry. Device results and the final review type follow in a second review.

Reviewer model: claude-fable-5-2 (primary), claude-opus-5-5 (verification)
Reasoning effort: Not exposed

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

Medium candidate: A quick retry's own failure can stay pending until its invoice expires. SparkRepo.kt:1996 puts the retry's saved start 11 seconds past the earlier attempt's failure, so when Spark dates the retry's failure no later than that earlier one, SparkRepo.kt:1558 reads it as the earlier attempt's and SparkRepo.kt:704 can't settle the send before expiry; both rails read the invoice as pending meanwhile. Whether Spark can give the two failures the same timestamp would settle this; telling the attempts apart by payment ID rather than by timestamp would remove the case.

Medium candidate: An older failure that the pre-send history read didn't show can still be read as the live retry's own failure, when it first appears after the send call returns and the retry isn't listed yet (SparkRepo.kt:1558, SparkRepo.kt:704, AppViewModel.kt:8013). The retry's hold is then released and the invoice can be paid over the node. On one device the unlisted-send hold and the recorded failure times guard against this, so it mainly concerns the same wallet open on another device. SparkRepoTest.kt:3778 covers this case only while the call is still in flight.

Medium candidate: QuickPay can stay pending when Spark reports a send's failure during the send call and then returns that same payment as failed. SparkRepo.kt:2048 holds back the failure event, SparkRepo.kt:633 returns the hash as sent, and QuickPayRepo.kt:483 waits for a completion that only the next reconcile brings. Passing the returned failure on to QuickPay would end it right away.

Low: SparkRepo.kt:585 checks the Paykit request before SparkRepo.kt:592 reads Spark's history, and afterwards only the deadline and exit state are checked again, so a request revoked during that read is still paid once. Reading the history before that check would close the gap.

Low: A send saved as uncertain by a build from before this PR is restored with its saved time as its start (SparkRepo.kt:776), without the margin past earlier failures that new sends get, so a listed earlier failure can release a retry that is still live. Only unreleased builds wrote that format, so this affects test installs only.

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

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

Device results at ff2687ee9. Approving: nothing above LOW came out of the code scan or the device gate. The three LOWs stay open: the two inline threads at SparkRepo.kt:1558 and :633, and my reopened thread at :800. Each can be fixed here or moved to a follow-up issue, whichever you prefer. Please reply on each thread saying which, with the issue link for a follow-up.

What the device showed:

  • J1 move-to-spark.xml: all 9 actions held. The move took 394,600 with a quoted fee of 2 and a paid fee of 0. Swipe → Moved took 12.1 s, and payInvoice → PaymentSuccessful took 3.7 s. The channel closed and Spending shows only "Spark via Breez" at 394,600. The Activity row and detail read "Move to Spark" −394,600, which is the moved amount plus the fee actually paid (0), not the quoted 2.
  • The extra sync (:633 thread) reproduces on device. Two runs per build, each send 65,273 sats, counting operator query_all_transfers in the ~76 s after the swipe: the head has 4 syncs, one of them 10 s after the Sent line on a send that had already shown "Bitcoin Sent"; ec4051d has 3 and no +10 s sync.
  • The settled-while-closed case (:800 thread) reproduces for failures only. A send that failed while the app was closed shows the "Payment Failed" toast at the next launch. One that succeeded updates its row silently. I edited the thread with the log lines.
  • A failed Spark send followed by a retry works on both routes, the Retry button and reopening the same lightning: URI. Each invoice ends with one Sent row and no Failed or Pending row left behind.
  • After 2 minutes idle on Home, a send reached the Sent line ~3.5–4 s after confirm and "Bitcoin Sent" in 6.9 s. Without the idle period it took 2.2–3.0 s and 6.4–9.1 s, so the idle period adds no slowdown.

Device gate: ff2687ee9 (comparison build ec4051d) — local Spark stack (bitkit-docker spark profile), Gate_Throwaway emulator, dev debug with the local-stack build settings. journeys: 1 passed (move-to-spark.xml); manual: 4 cases run, settled-while-closed reproduced for failures only; perf: +1 Spark sync per settled send (4 vs 3 per window), send after 2 min idle 3.5–4 s to the Sent line, no slowdown; l10n: no UI text changed in the delta; iOS: not run (no journey changes in the delta).
⚠️ Not verified on device: the fast-phone-clock case (:1558 thread). It rests on the unit test.
Skipped — covered by CI at ff2687ee9: unit tests, lint, detekt, compose UI tests and the local e2e suites (all green).
perf: +1 sync per settled Spark send (4 vs 3 per window against ec4051d); idle-then-send 3.5–4 s to the Sent line

Leaf swaps fail on this local operator, so every Spark send used an amount that matched an exact sum of leaves.

Reviewer model: claude-fable-5-2 (runbook), Sonnet (driver; requested alias, run metadata not yet read), claude-opus-5-5 (coordination)
Reasoning effort: Not exposed

A retry's success event could end its hold while Spark's list was read, with the list holding only an earlier
attempt's failure, so the send read as failed until the next read: Paykit could remove the paid request's proof
and the send screen could show the paid send as failed. Both lookups now take the hold before the list, so a
send held then stays pending unless that same list shows its own outcome, and Paykit settles a proof the node
failed from its one Spark read instead of reading Spark again.

Verified: just format, just compile, just test, just lint
@ovitrif

ovitrif commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 33f1958, the Android side of the Medium on the twin, synonymdev/bitkit-ios#1355 (review): a retry's success event could end its hold while Spark's list was read, with the list showing only an earlier attempt's failure. The send then read as failed, so Paykit could remove the paid request's proof and the send screen could show the paid send as failed.

  • lightningSend and settledSendEvent read the hold before the list. A send held at that point stays pending unless that same list shows its own outcome.
  • Paykit settles a proof the node failed from its one Spark read instead of reading Spark a second time.
  • New tests in SparkRepoTest.kt and PaykitPaymentProofRepoTest.kt fail without the change.

@jvsena42 this PR is now frozen at 33f1958. It changes only this race since ff2687e, which you reviewed.

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

Spark retry settlement needs a redesign because the failure timestamp can match more than one attempt on the same invoice. Bind outcomes to a stable attempt ID, or keep an ambiguous retry held until Spark identifies its outcome or the invoice expires.

Reviewed 33f1958.

Medium candidate: A previously unseen failure could release a live Spark retry. If Spark first lists only the earlier attempt's failure after the retry leaves the SDK call, and the failure falls within the clock margin, SparkRepo.kt:704 and SparkRepo.kt:1558 can treat it as the retry's own and release the hold before expiry. That can let the node submit the same invoice while the Spark retry is still live. The open question is whether Spark can return this sequence for the same wallet on two devices.

Low: A Paykit identity change during the history read at SparkRepo.kt:592 can leave the payment eligible to submit at SparkRepo.kt:609 after its request context has been cleared. Read history before the final request permission check.

Low: Activity can keep the first failed attempt's amount, fee, and timestamp after a newer retry fails. If the retry's Pending row was never saved, SparkRepo.kt:2126 preserves the older Failed row even when the callback or history has already selected the retry's failure. Keep the row's details when the failure is ambiguous and update them when the newer attempt is known.

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

@jvsena42

Copy link
Copy Markdown
Member

Delta review of 33f1958c7 ("spark retry success during a list read stays pending"): no findings, and my approval carries over.

  • The fix holds. lightningSend (SparkRepo.kt:1614-1616) and settledSendEvent (:1538, :1545) now read the hold through sendHoldStart before the list, so a retry's PaymentSucceeded that removes the hold during a listPayments() no longer turns a paid send into FAILED. Every changed branch only turns FAILED/NotFound into PENDING, so the send gate at :567-573 can only refuse more, never pay twice.
  • reconcileLightningProof reuses its single Spark read (PaykitPaymentProofRepo.kt:1489-1507). A proof still completes only on COMPLETED with a preimage matching the hash, and the second read that could drop a paid request's proof is gone.
  • The three open LOWs are unchanged: the sync is still at :633/:666, the fast-clock comparison at :1558 with the event guard now at :2053-2056, and the launch report at :737. My thread's anchor at :800 is now historical.

Device gate (partial): 33f1958c7 — of the cases I drove at ff2687ee9, only the failed-send-then-retry case (Retry button and reopening the invoice) goes through the changed code (SparkRepo.kt:567, AppViewModel.kt:8013/:8434). I'll re-run that case on a 33f1958c7 build. J1, the sync count and the force-stop cases don't touch the delta, so their results stand.

@ovitrif

ovitrif commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr @jvsena42

From here on this PR takes only fixes for findings that can lose money or pay twice. Every other finding gets a reply in its thread and goes to one follow-up PR per app after the merge. The same holds for synonymdev/bitkit-ios#1355.

Why: the PRs stacked on this one are already approved and wait on this base: synonymdev/bitkit-ios#1373 and synonymdev/bitkit-ios#1380, and on Android #1967 and #1985. Every extra round pushes them out again, and the review cycles here have run for too many days. Merging the base lets the rest merge without more cycles.

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

Device results at 33f1958c7. The approval stands, with the three LOW threads still open.

The delta changes the retry path, so I re-ran the failed-send-then-retry case on a 33f1958c7 build. Same local Spark stack, new wallet.

  • Retry button, hold invoice 253 sats: Pending → fail → "Payment Failed" → Retry → swipe → Pending → claim → "Bitcoin Sent". PaymentSuccessful carries the failed attempt's paymentId (87ccf131…). Activity has one "Sent −256" row and no Failed or Pending row.
  • Reopening the same lightning: URI, hold invoice 65,273 sats: fail → reopen → Confirm in 6.1 s → swipe → claim → "Bitcoin Sent". Activity has one "Sent −65,536" row.
  • No "Refused", "Skipped Spark send" or "Failed to pay" lines, and the crash buffer is empty.

Device gate: 33f1958c7 — retry case: 2 of 2 routes passed. J1, the sync count and the force-stop cases stand from ff2687ee9, since the delta doesn't touch their paths (delta review: #issuecomment-7102841420). perf: unchanged from ff2687ee9 (+1 sync per settled send); l10n: no UI text changed.

@ovitrif

ovitrif commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Merging this PR: it is approved on the current head with a device run, and CI is green.

@pwltr your last review on 33f1958 goes to the follow-up PR, not here: the stack of approved PRs on top of this one waits on it. That covers binding the retry outcome to a stable attempt ID and the two Lows (history read before the request check, the activity row details on a retry failure). The remaining Medium needs the same wallet sending the same invoice from two devices at once.

@ovitrif ovitrif mentioned this pull request Nov 24, 2026
3 tasks
@ovitrif

ovitrif commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr your reviews at 33f1958 (#1957 (review)) and ff2687e (#1957 (review)) are addressed in #2007:

  • Design point and the Medium on a newly listed failure releasing a live retry: outcomes are bound to a stable attempt id. Each Spark send passes a fresh idempotency key, which spark-sdk 0.28.3 keeps as the transfer id and Payment.id on both the Spark and SSP routes, and it is saved with the hold before the call. Only a failure with that id ends the hold early; any other failure leaves the retry pending until a paid listing or the invoice's expiry.
  • ff2687e Mediums on a quick retry's own failure dated at or before the earlier one, and on an older failure read as the retry's own: same fix, no timestamps are compared now.
  • Paykit permission check vs history read: the pre-send history read is gone, as it only dated the send.
  • Activity row keeping the first failed attempt's details: the retry's own failure now writes its amount, fee and time.
  • QuickPay pending when the send call returns the failure: the returned failure writes the row and reports once.
  • Old-format uncertain sends: a hold without an attempt id waits for a paid attempt or expiry.

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