Skip to content

fix: hold a redo spark exit rebuild over a waiting leaf - #1892

Merged
ovitrif merged 3 commits into
masterfrom
fix/spark-exit-redo-waiting-leaf
Nov 12, 2026
Merged

ovitrif merged 3 commits into
masterfrom
fix/spark-exit-redo-waiting-leaf

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Twin: iOS PR to follow on feat/breez-spark-lightning.

Description

  • Fixes the emergency exit leaving a waiting leaf unsent after a Redo rebuild.
  • Since Breez SDK 0.28.2 (chore: bump breez sdk to 0.28.2 #1881), a CPFP chain that lost a race comes back from check_recover_funds as Redo, not Valid. The driver never sends a diverged generation again, and its Redo rebuild skipped the hold that keeps a leaf in the exit when a build leaves it waiting. So when one failed chain read made the rebuild's prepare skip a leaf as Unverified, that leaf's steps went unsent until the rest of the exit was done, which can be weeks. Before 0.28.2 the same race went through the lost-race fallback rebuild, which kept that hold.
  • A Redo rebuild that leaves out a waiting leaf the diverged generation recovers is now not adopted. It tries again at the usual rebuild pace for 6 blocks, so a leaf one failed read skipped is built with the rest. After 6 blocks it is adopted as before, with the leaf waiting. A tick that can't read the tip keeps the hold without counting it. The hold runs at that pace even when it follows a funded top-up, with no fee ask on screen, and a prepare that skips every leaf during it doesn't start the waiting leaf's week-long retry clock.
  • The lost-race fallback for a race the SDK still calls Valid stays as it is.

Design

N/A — no UI changes.

Preview

N/A

QA Notes

Automated Checks

  • SparkExitDriverTest:
    • a redo rebuild beside a waiting leaf holds until the leaf reads: a Redo rebuild whose prepare skips leaf-2 as Unverified adopts nothing and sends nothing, then adopts both leaves once leaf-2 reads.
    • a redo rebuild beside a leaf that stays unread adopts after the hold: the hold keeps its start height for 6 blocks, then the rebuild is adopted with leaf-2 waiting.
    • a redo hold after a funded top-up runs at the rebuild pace: a hold whose top-up was adopted leaves the funding phase and doesn't build again before the rebuild interval.
    • an empty prepare during a redo hold leaves the retry clock alone: a prepare that skips every leaf during the hold sets no retry clock; it starts once the hold ends.
    • a redo hold goes on uncounted while the tip cannot be read: a missing tip neither starts nor ends the hold.
    • a redo rebuild of only failed cooperative leaves beside a waiting leaf holds too: the failed-only build is held like any other.
    • a redo after a refund sent spent strikes it once and not again once its rebuild is accepted: a Redo over a refund logged as input-spent strikes the refund once; after the rebuild's refund is accepted, a second Redo does not strike it again. Asked for by @jvsena42 on chore: bump breez sdk to 0.28.2 bitkit-ios#1306 (review).
  • SparkExitRepoTest: a start never lowers a funding index a scan moved past its quote, promised to @coreyphillips on fix: find a restored wallet's exit funding before the next quote #1887.
  • SparkExitRecordTest: the round trip and the defaults now include redoHeldSince.

@ovitrif ovitrif self-assigned this Nov 12, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 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-12T15:44:52.573095Z 4125b72 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4125b72d12

ℹ️ 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".

@greptile-apps

greptile-apps Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The PR affects rebuild timing in Spark emergency exits, not the wider transaction flow.

The PR appears safe to merge, with a non-blocking request to test the remaining hold branches.

Findings

  1. P2 Hold branches lack tests ▶

Summary

Holds a Redo rebuild for up to six blocks when it would leave out a waiting leaf recovered by the previous generation.

  • Redo rebuilds wait briefly when they skip a leaf the old generation can recover.
  • Funding-index tests cover a quote racing with a chain scan.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Build Redo replacement] --> B{Leaves out a waiting leaf from the old recovery?}
  B -->|No| E[Adopt replacement]
  B -->|Yes| C{Readable tip and six blocks elapsed?}
  C -->|Yes| E
  C -->|No| D[Save hold and retry later]
  D --> A
Loading

Reviews (1) · Last reviewed commit: "fix: hold a redo spark exit rebuild over..." · Reviewed by Greptile

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Milestone 3.2.0: this PR fixes the Spark emergency exit, which ships in 3.2.0 with #1886 and the Breez SDK 0.28.2 bump in #1881. It closes no issue, so the milestone sits on this PR.

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Ran the Spark exit unit tests locally on 4125b72: ./gradlew :app:testDevDebugUnitTest --tests 'to.bitkit.repositories.SparkExit*', 308 tests, 0 failures, 2 skipped, including the four added here.

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from 6e1c7a2 (run).

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

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

Two independent reviews, nothing blocking a merge.

worth doing, does not block

  • A held Redo rebuild in a funded NeedsFunding phase rebuilds every tick (app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt:249). After its top-up is adopted, a held Redo rebuild runs a full prepare and recover on every tick for the whole hold, not once every REBUILD_INTERVAL. The PR says the hold "tries again at the usual rebuild pace". That is true on the Running + isRebuilding path, which isRebuildDue gates in tick, but not here. Path, traced in the code: 1. A Redo check calls rebuild. Its build throws InsufficientCpfpFunds, so askForFunding leaves the record in NeedsFunding with isRebuilding and isRedoRebuild set. 2. The funding confirms. buildOnceFunded adopts it through adoptFunding and falls to else -> build(funded, sdk) (SparkExitDriver.kt:249). The prepare skips leaf-2 as Unverified, so holdingRedo returns the record still in NeedsFunding, with lastBuildAt = now. 3. On the next tick, fundingTopUp took UTXOs totalling at least the shortfall, so fundingShortfallSats is now null and funded = record. That record is neither isFundingWaitingLeaves nor isUnverifiedAsk, so it reaches else -> build(funded, sdk) again. That branch has no isRebuildDue check, so the lastBuildAt the hold set is never read. With the 60 s foreground tick in SparkExitRepo, that is about 60 prepare, export-state-import, recover and CPFP-signing rounds over the 6 blocks. The first buildOnceFunded branch (unfunded Redo) is paced by isRebuildDue, so only the funded branch is affected. Before this PR this path adopted on its first funded build, so it never looped. Nothing broadcasts during the loop, and the hold still ends on height, so the cost is SDK and chain load, not a wrong exit. That is why this is not blocking. Confirmed by reading the code and SparkExitMath.fundingTopUp. I wrote a scratch test for this path in a temp copy, but Gradle could not resolve the GitHub Packages dependencies offline (ldk-node, bitkit-core, breez 0.28.2), so it did not run. A possible fix: in buildOnceFunded, return funded (which keeps the adopted funding) when funded.isRebuilding && funded.redoHeldSince != null && !isRebuildDue(funded), before the else branch. Add a test that ticks a held funded Redo twice inside REBUILD_INTERVAL and asserts one recoverRequests entry. No test covers the hold on this path, or on the cooperative-only branch at line 346.
  • Funded Redo holds bypass the rebuild interval (app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt:382)

@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. A Redo rebuild that drops a waiting leaf the diverged generation still recovers is held (not adopted) for REDO_HOLD_BLOCKS from the first such build, at the rebuild pace. Reviewed 4125b72, full tier, static: Bitkit Android PRs are not built here, so this is reasoned from the code and CI.

What I checked, and 4 candidates I ruled out

Read: SparkExitDriver.build end to end (both adopt sites, the unexitable-leaf and lost-leaf exits), holdingRedo, SparkExitRecord.adopt, the JSON read/write of redoHeldSince, the new driver/repo/record tests
Twin: matches synonymdev/bitkit-ios#1309 (same 6-block window, same guard on the diverged generation's leaves, same uncounted hold without a tip)

Ruled out

  • Stale redoHeldSince leaking into a later Redo: every adopt clears it, and the stall, unverified and fee-bump rebuilds that reset isRedoRebuild only start from a running check, which does not run while isRebuilding, so a hold is always ended by an adopt.
  • Hold blocking a valid generation: keepsValidGenerationOver is checked first and is false for a Redo rebuild, so the hold only ever replaces a generation that is never sent again.
  • Tight rebuild loop while held: the hold stamps lastBuildAt, so isRebuildDue paces it like any rebuild.
  • Reorg below since: height >= since keeps the hold rather than underflowing; it ends once the chain passes since + 6 again.

CI: lint, detekt, build-local green; build-and-test, compose UI and e2e still running at review time.

Merge confidence: 4/5, the unit tests covering the hold were still running in CI and the change was not built here.

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

f742ad0 applies the fixes from @coreyphillips's review of the iOS twin (synonymdev/bitkit-ios#1309), whose two bugs exist here too:

  • A Redo hold after an adopted top-up now runs at the rebuild pace, with no fee ask on screen.
  • An empty prepare during the hold no longer starts the waiting leaf's retry clock.

Two new tests in SparkExitDriverTest cover them, and both fail without the fix. The Spark exit tests and detekt pass locally.

Re-review is needed only because of this push: 4125b72...f742ad0

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

No findings.

  • The hold can't stall an exit on mainnet. The tip read and the SDK share one backend (Env.sparkChainServiceUrl(BITCOIN) is the only EsploraSparkExitChain read host). So a hold with no readable tip needs that host to serve the SDK's prepare/recover while failing /blocks/tip/height on every due build. A transient tip failure only moves the start or the expiry to the next build.
  • A held record can't be fee-bumped. payHigherFeeLocked refuses while isRebuilding, so isRedoRebuild isn't cleared mid-hold and no diverged generation re-enters the send path.
  • f742ad0e5: the hold moves to Running only when fundingShortfallSats == null. Both funding branches are paced by isRebuildDue, which closes coreyphillips's every-tick note. The hold check runs before isWaiting, so an empty prepare doesn't start the retry clock.
  • No new send path: held builds sign CPFP transactions that are discarded. Strikes are computed only in adopt. redoHeldSince persists, so process death resumes the hold. Lost-leaf detection still runs before the hold.

The iOS twin synonymdev/bitkit-ios#1309 uses the same predicate.

Device gate: no device check needed: it needs a lost CPFP race plus a skipped leaf, which no journey can force; SparkExitDriverTest is the evidence. perf: up to about 6 extra prepare/recover rounds per Redo episode at the 10-minute pace.

Reviewer model: Claude Fable 5.2 (claude-fable-5-2), Claude Opus 5.5 (claude-opus-5-5)
Reasoning effort: not exposed

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

6e1c7a2 adds the two cases Greptile asked for: a Redo hold while the tip can't be read, and a hold over a build of only failed cooperative leaves. Test-only.

Re-review is needed only because of this push: f742ad0...6e1c7a2

@ovitrif
ovitrif requested a review from jvsena42 November 12, 2026 16:23
@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@coreyphillips both points in #1892 (review) are addressed:

  • Funded hold looping in buildOnceFunded: f742ad0 switches a held Redo whose top-up is covered to running, so the isRebuildDue-gated path paces it. a redo hold after a funded top-up runs at the rebuild pace ticks it twice inside the rebuild interval and asserts no second recover. It fails without the fix.
  • No test on the cooperative-only branch: 6e1c7a2 adds a redo rebuild of only failed cooperative leaves beside a waiting leaf holds too, plus the missing-tip case.

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

Rechecked after 2 new commits (f742ad0, 6e1c7a2). Nothing blocking remains.

addressed

  • A held Redo rebuild in a funded NeedsFunding phase rebuilds every tick (app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt:249). Fixed: holdingRedo now sets phase = Running when record.fundingShortfallSats == null (SparkExitDriver.kt:385-386). After adoptFunding, fundingTopUp only returns UTXOs totalling at least the shortfall, so the shortfall is null. The next tick therefore takes the Running if record.isRebuilding branch, which returns early unless isRebuildDue (line 169, lines 1221-1224). It no longer reaches else -> build(funded, sdk) at line 249. I confirmed this by reading the code. a redo hold after a funded top-up runs at the rebuild pace asserts Phase.Running and no second recover inside the interval. Both assertions fail without the change. Gradle could not resolve bitkit-core or breez 0.28.2 offline, so I did not run it.
  • Funded Redo holds bypass the rebuild interval (app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt:382). Fixed: This is the same path as point 1. The hold no longer leaves a covered record in NeedsFunding (SparkExitDriver.kt:385). That means the unconditional build(funded, sdk) at line 249 is reached only on the tick the top-up is adopted. Later ticks are gated by isRebuildDue at line 169. I traced it through fundingTopUp and fundingShortfallSats. The new driver test ticks twice at the same now and checks that recoverRequests does not grow.

new since the last review

worth doing, does not block

  • Unfunded Redo hold keeps a stale fee ask on screen though the build was paid (app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt:385)

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@jvsena42 thanks. Your approval is on f742ad0; this repo needs one on the last push, so I re-requested you on 6e1c7a2. That commit only adds the two tests Greptile asked for: f742ad0...6e1c7a2

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Merging: CI is green and @coreyphillips and @jvsena42 approved, with no open threads. The deferred point about the stale fee ask on an unfunded Redo hold is tracked in #1894.

@ovitrif
ovitrif merged commit 0ce6452 into master Nov 12, 2026
23 checks passed
@ovitrif
ovitrif deleted the fix/spark-exit-redo-waiting-leaf branch November 12, 2026 16:52
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.

4 participants