Repository navigation
fix: pubky swaps route follow-ups - #1923
Conversation
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 09d69f73a7
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
[High impact] The PR reaches swap payment, claim recovery, and Spark contact-send routing. Reset the saved restore records on wallet replacement before merging, so a second restore does not skip unfinished swaps. FindingsSummaryThis PR improves swap retries, contact matching, restore retries, and claim recovery.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Commit swap] --> B[Save unfinished swap]
B --> C[Pay hold invoice]
C --> D[Wait for claim or hold failure]
D -->|Hold fails| E[Stop and remove saved swap]
D -->|Claim broadcasts or wait expires| F[Poll in background]
F -->|Claim confirms or swap fails| E
G[Node starts] --> H[Read saved unfinished swaps]
H --> F
Reviews (1) · Last reviewed commit: "feat: resume unfinished swaps until thei..." · Reviewed by Greptile |
Regtest APKDownload bitkit-dev-debug universal APK (expires in 30 days). |
talosmachina
left a comment
There was a problem hiding this comment.
1 finding (1 P2). Stops the swap claim poll on a failed hold payment, narrows the Spark-pending block on the swap fallback to this contact, guards against a second swap after backing out of Confirm, keeps the contact on a retry, retries partial restores and persists unfinished swaps across starts. Reviewed 09d69f7, full tier, static.
What I checked, and 5 candidates I ruled out
Read in full: the diff of every file under app/src/main, proceedWithSwapRoutedPayment, finishSwapRoutedPayment, handlePaymentFailed, onConfirmPay, hideSheet, SparkRepo.withdraw, BackupRepo metadata backup and restore, WipeWalletUseCase.wipeLocal.
Cross-repo: bitkit-core pubky_swaps advance_swap, restore_swaps, store::load, claim.rs state reporting.
CI: build-and-test, lint and Greptile green at review time; e2e jobs were still running.
Not built or run here: per the repo's track rules this review reasons from the code and CI only.
Ruled out
- Hold-failure select fires on a cleared screen:
invokeOnCompletioncompletesholdFailedonly when the cause is null, andfinishSwapRoutedPaymentcancelsholdFailurein itsfinally, so a cancel keeps the poll running, as the new test asserts. - Two loops advancing one swap:
advancingdedupes per id,resumeUnfinishedSwapsskips ids inclaiming, and bitkit-core also serialisesadvance_swapper swap id behindadvancing_lock. showCommittedSwapblocking the next send: it is keyed onsendStateGeneration, whichhideSheetand a new send bump, and cleared on every failure path that reachesclearCommittedSwaporreleaseFailedSwapHold.- Contact match on a pending withdrawal with no journal:
address == nullis treated as settling here, so an unknown destination still refuses the fallback (the conservative side). - Restore marking a failed chunk read:
restoredProvidersis only extended after every chunk returned, so a throw leaves all providers to be asked again.
Merge confidence: 4/5, one P2 off the normal send path; the send-flow changes are covered by the new AppViewModelSendFlowTest cases.
Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed
coreyphillips
left a comment
There was a problem hiding this comment.
Two independent reviews.
needs changing before merge
- Source changes bypass the committed-swap guard (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7487). Changing funding sources during a pending swap commit can still pay the contact twice. Back out to Amount, select Savings and then Spending, obtain a fresh quote, and let the first commit return before confirming again. Source changes increment
sendStateGeneration, so this check ignores the first committed swap. I reproduced two hold payments using the unchanged source-switch, commit and guard methods with external calls stubbed. - Failed swap retries retain a consumed private payment list (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7431). A swap using a versioned private payment list cannot be retried after its hold payment fails. This helper skips contacts without an incoming payment request, which includes every swap route. Retrying then consumes the restored context's already-consumed list version and fails with
PaymentListAlreadyConsumed. I reproduced that rejection using the unchanged consume and release methods. The new retry test masks it by stubbing both consumes as successful.
worth doing, does not block
- A swap whose hold fails outside awaitClaim stays tracked and polled until timeout (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7359-7367).
commitnow records every committed swap inunfinishedPubkySwaps, but only theawaitClaimpaths remove it, so two failure paths leave the swap tracked and advancing every 30 s until bitkit-core gives up. First,proceedWithSwapRoutedPaymentreturns early when decoding the hold invoice fails, or whenpayInvoicefails synchronously with anything butPaymentPendingException(AppViewModel.kt:7335-7338 and 7359-7367).LightningRepo.payInvoicecan fail synchronously, for example inrequireWalletRestoreCompleteorearlierNodeSend.awaitClaimnever runs on those paths, so the swap stays in the list.resumeUnfinishedSwapsthen advances it every 30 s on each node start. Second, after the 10 minute claim wait runs out,advanceInBackgroundloops with no hold-failure watch.CONFIRMATION_TIMEOUTis gone, andreleaseFailedSwapHold(AppViewModel.kt:7506) clears the send state but never stops that loop or untracks the swap. So a late hold failure now polls for longer than the roughly 70 minutes #1920 complained about. In bitkit-core rc15,claim::next_stepreportsAwaitingLockupfor an unfunded swap untiltip >= timeout_block_height, about 144 blocks plus slack. That is roughly a day on mainnet, and on regtest it lasts until enough blocks are mined. Each advance loads the mnemonic and opens an Electrum connection. No funds are at risk. Confirmed by reading: the repo's onlyuntrackcallers areawaitClaimOnceandawaitConfirmation, and neither early-return path reaches them. Possible fix: have the repo drop a swap on a known hold failure (from the early returns and fromreleaseFailedSwapHold), and cancel its background loop too. - Swap restore state outlives a wallet wipe and skips providers on a later restore (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:87-91).
restoredProvidersandreportedSwapslive in the@SingletonPubkySwapsRouteRepofor the whole process.WipeWalletUseCaseneither resets them nor restarts the process. So a restore, then a wipe, then another restore in the same process filters out every provider the first restore read in full, configuredEnv.pubkySwapsProvidersincluded (PubkySwapsRouteRepo.kt:158). If all candidates are filtered,restoreSwapsreturns empty with no incomplete providers, and the second wallet's in-flight swaps at those providers are never rebuilt.reportedSwapswould also hide the same swap ids if the same seed is restored again. Separately,restorePubkySwapsnow collects a flow that never completes, launched untracked onviewModelScope(WalletViewModel.kt:582-583). The first restore's collector keeps running after the wipe, and a second restore adds another, so both rerunpubkySwapsRestoreon every contact change. Confirmed by reading the wipe path and the repo. I didn't drive it on a device. This mostly affects QA and dev restore loops, but those are where this flag is used. Clearing this state on wipe, or scoping it to one restore run, would fix it. - Every restore attempt reveals a fresh on-chain address, even when nothing is restored (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:160).
restoreSwapscallslightningRepo.newAddress(), which calls LDK'sonchainPayment().newAddress()and reveals the next address, whenever any provider is left to ask (PubkySwapsRouteRepo.kt:160). Before this PR that happened once per wallet restore. Now it happens up to 3 times per contact-set change for the rest of the session, because the flow reruns on every change and retries incomplete providers. A provider that stays offline is retried on every contact change, adding up to three unused addresses each time. Enough unused revealed addresses ahead of a real receive address could push that address past the wallet's stop gap on a later seed restore. Reusing one payout address for the life of the flow avoids this. - Provider restore caches survive wallet replacement (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:158-159). A later wallet restore in the same process skips providers already read for the previous wallet. The singleton retains
restoredProvidersandreportedSwapsacross wallet wipes. Restoring another seed with overlapping contacts therefore misses its swaps until the process restarts. I reproduced this with two seed values and a cleared wallet cache: only the first seed reached the restore backend. - Late hold failures do not stop background claim polling (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:274-284). A hold payment failing after the 10-minute claim timeout leaves background polling running. The completion handler is disposed before the background loop starts, and that loop receives no hold-failure signal. I reproduced another advance call and an unchanged
unfinishedPubkySwapsentry after completing the failure signal following timeout. With a stalled regtest chain, polling continues and resumes on subsequent node starts.
|
@coreyphillips all seven points are fixed in 276df10:
The guard now keys on the send session, which only a new send bumps, not on
A swap that paid nothing now releases the contact's private list whether or not a payment request is involved, both inside the claim wait and on a hold failure after it. The retry test now consumes and releases statefully, as
The read providers and reported swaps now live in one restore run, not in the singleton. A wipe calls
One payout address per restore run, revealed on its first restore only. |
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 1 new commit (276df10). Nothing blocking remains.
addressed
- Swap restore state outlives a wallet wipe and skips providers on a later restore (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:87-91). Fixed: restoredProviders and reportedSwaps now live in a RestoreRun created per flow (PubkySwapsRouteRepo.kt:137-161, 413-417). resetForWipe (164-168), called from WipeWalletUseCase.kt:105, bumps
wipes, which ends the flow. WalletViewModel.kt:585-586 cancels an earlier collector before starting another. I confirmed this by reading the code. I couldn't run the unit tests here because the private GitHub Packages dependencies don't resolve. - Every restore attempt reveals a fresh on-chain address, even when nothing is restored (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:160). Fixed: PubkySwapsRouteRepo.kt:181 reveals the payout address only on a run's first restore and reuses it on every retry and contact change. The new test
restoredSwaps reveals one payout address for all its restoreschecks a single newAddress across six restores. I read it but couldn't run it here. - Source changes bypass the committed-swap guard (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7487). Fixed: showCommittedSwap (AppViewModel.kt:7494) now matches on sendSession. Only resetSendState bumps it (8605), and every new-recipient path goes through resetSendState. The source switches at 4552-4567 and 4809 bump only sendStateGeneration, so they no longer get past the guard. proceedWithPayment checks the guard first for every pay method (6784), which covers the Savings on-chain route too.
- Failed swap retries retain a consumed private payment list (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7431). Fixed: releaseSwapPrivatePaymentList (AppViewModel.kt:7505-7508) releases whenever a private payment context exists, with or without a payment request. It runs from finishSwapRoutedPayment (7446) and releaseFailedSwapHold (7521). PrivatePaykitRepo.releasePrivatePaymentListVersion resets consumedVersion, so the retry's consume succeeds, and the retry test now models consume and release statefully.
- Provider restore caches survive wallet replacement (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:158-159). Fixed: Same change as point 2: the provider and swap sets belong to one RestoreRun (PubkySwapsRouteRepo.kt:139, 178, 206, 210-211), and a wipe ends that run through resetForWipe. A restore after a wipe starts empty and asks every provider again.
- Late hold failures do not stop background claim polling (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:274-284). Fixed: When the claim wait times out, awaitClaimOnce registers the background loop in
advancing(PubkySwapsRouteRepo.kt:303, 310-320) before finishSwapRoutedPayment returns. A later PaymentFailed for the still-pending hold reaches releaseFailedSwapHold, and its dropFailedSwap (326-329) cancels that loop and untracks the swap. Both the repo test and the VM test cover this, though I couldn't run them here.
still open
- A swap whose hold fails outside awaitClaim stays tracked and polled until timeout (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7359-7367).
commitnow records every committed swap inunfinishedPubkySwaps, but only theawaitClaimpaths remove it, so two failure paths leave the swap tracked and advancing every 30 s until bitkit-core gives up. First,proceedWithSwapRoutedPaymentreturns early when decoding the hold invoice fails, or whenpayInvoicefails synchronously with anything butPaymentPendingException(AppViewModel.kt:7335-7338 and 7359-7367).LightningRepo.payInvoicecan fail synchronously, for example inrequireWalletRestoreCompleteorearlierNodeSend.awaitClaimnever runs on those paths, so the swap stays in the list.resumeUnfinishedSwapsthen advances it every 30 s on each node start. Second, after the 10 minute claim wait runs out,advanceInBackgroundloops with no hold-failure watch.CONFIRMATION_TIMEOUTis gone, andreleaseFailedSwapHold(AppViewModel.kt:7506) clears the send state but never stops that loop or untracks the swap. So a late hold failure now polls for longer than the roughly 70 minutes #1920 complained about. In bitkit-core rc15,claim::next_stepreportsAwaitingLockupfor an unfunded swap untiltip >= timeout_block_height, about 144 blocks plus slack. That is roughly a day on mainnet, and on regtest it lasts until enough blocks are mined. Each advance loads the mnemonic and opens an Electrum connection. No funds are at risk. Confirmed by reading: the repo's onlyuntrackcallers areawaitClaimOnceandawaitConfirmation, and neither early-return path reaches them. Possible fix: have the repo drop a swap on a known hold failure (from the early returns and fromreleaseFailedSwapHold), and cancel its background loop too. Claude still sees it: The two paths you listed are fixed: decode failure at AppViewModel.kt:7345, synchronous payInvoice failure at 7374-7375, and late failure through releaseFailedSwapHold at 7517-7522. A hold that fails before payInvoice returns is still tracked, though. track() is skipped at 7385-7386, so handlePaymentFailed (2993) never reaches releaseFailedSwapHold, and the LightningPaymentFailedError branch only clears swapIdsByHoldHash (7443). On Main.immediate, theasyncin awaitSwapClaim that would callawaitClaimis cancelled before it starts; I reproduced that with a standalone coroutine check copying awaitSwapClaim. Calling dropFailedSwap in that branch would close it. Separately, a swap resumed after an app restart is never dropped when its hold fails, because swapIdsByHoldHash only lives in memory.
new since the last review
worth doing, does not block
- A hold failing after the Send sheet is closed restores its contact anyway (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7524-7531)
- Claim waits already running at wipe time start new background polling (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:164-168)
- Dismissed swap sends restore stale contact state (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7524-7529)
@coreyphillips out of scope: tracked in #1927, because this PR is approved, a push would void that, and no funds are at risk: it's extra polling behind the debug-only |
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after replies, with no new commit since 276df10. Nothing blocking remains.
still open
- A swap whose hold fails outside awaitClaim stays tracked and polled until timeout (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7359-7367).
commitnow records every committed swap inunfinishedPubkySwaps, but only theawaitClaimpaths remove it, so two failure paths leave the swap tracked and advancing every 30 s until bitkit-core gives up. First,proceedWithSwapRoutedPaymentreturns early when decoding the hold invoice fails, or whenpayInvoicefails synchronously with anything butPaymentPendingException(AppViewModel.kt:7335-7338 and 7359-7367).LightningRepo.payInvoicecan fail synchronously, for example inrequireWalletRestoreCompleteorearlierNodeSend.awaitClaimnever runs on those paths, so the swap stays in the list.resumeUnfinishedSwapsthen advances it every 30 s on each node start. Second, after the 10 minute claim wait runs out,advanceInBackgroundloops with no hold-failure watch.CONFIRMATION_TIMEOUTis gone, andreleaseFailedSwapHold(AppViewModel.kt:7506) clears the send state but never stops that loop or untracks the swap. So a late hold failure now polls for longer than the roughly 70 minutes #1920 complained about. In bitkit-core rc15,claim::next_stepreportsAwaitingLockupfor an unfunded swap untiltip >= timeout_block_height, about 144 blocks plus slack. That is roughly a day on mainnet, and on regtest it lasts until enough blocks are mined. Each advance loads the mnemonic and opens an Electrum connection. No funds are at risk. Confirmed by reading: the repo's onlyuntrackcallers areawaitClaimOnceandawaitConfirmation, and neither early-return path reaches them. Possible fix: have the repo drop a swap on a known hold failure (from the early returns and fromreleaseFailedSwapHold), and cancel its background loop too. Codex still sees it: The direct failure paths already calldropFailedSwap, but failure before pending registration can bypass cleanup at AppViewModel.kt:2993, and restart loses the hold-hash mapping. The 05:48:01 reply acknowledges these remaining cases and defers them to #1927; it does not settle them. - A hold failing after the Send sheet is closed restores its contact anyway (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7524-7531). Because the restore now checks the send session instead of the generation, a swap's contact is restored after the Send sheet is closed, and an unrelated payment can then be tagged with that contact. restoreSwapContact (AppViewModel.kt:7459-7464) and releaseFailedSwapHold (7524-7531) used to bail out when sendStateGeneration had moved on, and hideSheet bumps the generation (8868). They now compare sendSession, which hideSheet leaves alone. Example sequence: 1. Send A is a plain Lightning payment with no contact. It goes to Pending and the user closes the sheet. 2. Send B is a swap to a contact. It goes to Pending and the user closes the sheet. No new send starts. 3. B's hold payment fails. releaseFailedSwapHold sets activeContactPaymentContext to B's context, with no Send sheet open. 4. A settles. handlePaymentSuccessful calls syncContactForActivity(A) (9383-9401). A has no pending context, so it falls back to activeContactPaymentContext and tags A's activity with B's contact. I found this by reading the code; I could not run the tests here. The existing dismissal tests (
swap route claim failure after dismissal keeps the next send openand the others) always open a new send through resetSendState before the failure, so they don't cover this case. Bumping sendSession in hideSheet would restore the old behaviour without weakening the in-sheet guard from point 4. The code is unchanged.restoreSwapContact(AppViewModel.kt:7459-7464) andreleaseFailedSwapHold(7524-7531) still comparesendSession, andhideSheet(8867-8868) bumps onlysendStateGeneration. The reply defers this to #1925, which concedes the point rather than rebutting it. The contact restore is new in this PR, so the regression is this PR's own. - Claim waits already running at wipe time start new background polling (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:164-168). resetForWipe cancels the
advancingloops, but not theawaitClaimjobs started on the repo scope (PubkySwapsRouteRepo.kt:265-276), so a claim wait that was running at wipe time keeps going. Both the send flow and the restore collector'slaunch { awaitClaim(it) }(WalletViewModel.kt:594-596) start these jobs. After the wipe the keychain is empty, so each advance fails with MnemonicNotFound. pollClaim treats that as retryable and polls every 2 s. When the 10 minute wait ends, awaitClaimOnce calls advanceInBackground (303), which adds a fresh loop to the map resetForWipe just cleared. That loop polls every 30 s until a new wallet's mnemonic exists. The cost is wasted work and log noise, not funds. It does contradict the reply that a wipe ends the run's background swaps. I found this by reading the code. Cancelling the claim jobs in resetForWipe, or checkingwipesbefore advanceInBackground, would close it. The code is unchanged.resetForWipe(PubkySwapsRouteRepo.kt:164-168) cancels onlyadvancing. Thescope.asyncclaim waits (265-276) survive the wipe, andawaitClaimOncestill callsadvanceInBackgroundon timeout (303) without checkingwipes. The reply defers this to #1926 and does not dispute it. - Dismissed swap sends restore stale contact state (app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt:7524-7529). A hold failure after dismissing Pending can block later incoming payment requests.
hideSheet()increments onlysendStateGeneration, so the new session check restoresactiveContactPaymentContextfor the dismissed send.isPaymentRequestPresentationBlocked()then suppresses incoming requests despite no send sheet being open. Isolated checks confirmed this regression in both restoration helpers against the previous revision. The code is unchanged: hold failures after the sheet is dismissed still restoreactiveContactPaymentContextthrough thesendSessioncheck at AppViewModel.kt:7460 and 7526. The reply defers this to #1925, which concedes the point.
new since the last review
worth doing, does not block
- Later restore passes re-track and re-poll swaps committed in the same session (app/src/main/java/to/bitkit/repositories/PubkySwapsRouteRepo.kt:208)
Closes #1920
Closes #1921
Closes #1922
Closes #1836
Closes #1837
Closes #1829
Closes #1835
Follow-up to #1732: the non-blocking points from its review.
Description
Out of Scope
payInvoicereturns, or after an app restart, leaving its swap polled: bug: early or post-restart hold failures keep the swap polled #1927 (review).QA Notes
Automated Checks
AppViewModelSendFlowTest,PubkySwapsRouteRepoTest,SparkRepoTest,PaykitRouteRepoTest,WalletViewModelTestandWipeWalletUseCaseTest; the bug tests fail before their fix.just compile,just testandjust lint: pass.Manual Tests
PUBKY_SWAPS_ROUTESflag, and these changes are in failure, retry and restore paths the unit tests drive.