Skip to content

perf: sync additional wallets apart from the primary - #154

Open
ovitrif wants to merge 22 commits into
mainfrom
perf/additional-wallets-own-sync
Open

ovitrif wants to merge 22 commits into
mainfrom
perf/additional-wallets-own-sync

Conversation

@ovitrif

@ovitrif ovitrif commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #153
Refs:

Description

  • Fixes additional on-chain wallets (monitored address types and derived accounts) slowing every background sync. The primary wallet and every additional wallet ran in one join, so the primary's result waited for the slowest additional wallet. On Bitkit 3.2.0 with five Paykit accounts that meant 10–18 s per sync, and about every third run all of them hit the 40 s deadline together.
  • Adds additional_wallet_sync_interval_secs to BackgroundSyncConfig and RuntimeSyncIntervals (default 80 s, the same as the on-chain default; UDL default 80, so existing binding callers still compile; battery_saving() sets 300 s). The background sync now runs the additional wallets in their own loop, polled side by side with the primary loop, each pass with its own in-flight guard and deadlines. A slow additional pass no longer delays the primary wallet, Lightning sync or fee updates.
  • Electrum: additional wallets sync over their own connection, opened on their first sync and reconnected like the main one. An Electrum server answers a connection's requests in order, so on the shared connection the primary's batches queued behind the additional wallets' (stop gap 1000, batch 100 in Bitkit). Nodes without additional wallets keep two connections.
  • Electrum: the additional wallets sync one after another on their connection, each within its own deadline. electrum-client can lose the wakeup of a call that overlaps another on the same connection, and nothing else uses this connection to read the stuck response, so overlapping calls left a wallet waiting out the whole pass. A wallet that times out gets a new connection before the next one syncs; if none can be had, the rest of the pass fails. The connection is idle between passes, so each pass pings it first (bounded by the sync timeout) and reconnects if the ping fails; if it can't reconnect, the pass fails. An additional wallet removed while the pass connects is skipped.
  • sync_wallets() still syncs every wallet: the primary and additional passes run concurrently, and each applies its results as soon as it finishes. So a newly registered account still gets its first full scan from the sync_wallets() call after registration.
  • SyncCompleted reports each pass on its own: SyncType::OnchainWallet now covers the primary wallet, and the new SyncType::AdditionalOnchainWallets the additional wallets, sent only for a pass that synced at least one of them (none for a node without additional wallets). Its synced_block_height is the lowest tip of the wallets that pass synced. A sync_wallets() call that joins a pass in flight returns once that pass has queued its events, and runs another additional pass when the one it joined did not sync every additional wallet registered when the call started. An app that needs every wallet synced, such as Bitkit's prune after a restore, waits for both when it has additional wallets.
  • Each pass sends its own wallet events, evictions and BalanceChanged. The two passes' event emission is serialized, so BalanceChanged compares against the balance the other pass last reported. Wallet events are deduplicated across passes (the last 1000), so a transaction paying both the primary and an additional wallet is reported once; confirmations are deduplicated per block, so one in a new block after a reorg is reported again, and an eviction lets the receipt of a rebroadcast be reported again. The eviction check runs under a lock together with applying the results, so overlapping passes can't report the same eviction twice. Evictions are now reported even when another wallet in the pass failed.
  • On-chain amounts count every wallet a transaction pays or spends from, including one that has not synced it yet, so the first OnchainTransactionReceived and the payment record carry the full amount.
  • A payment's confirmation depth is counted on the tip of the wallets tracking it, so an additional wallet's older tip no longer keeps a primary-only payment Pending.
  • A sync pass cancelled before it finishes (e.g. while the node stops) fails its waiters, so the next pass starts instead of waiting forever.
  • Fixes sync_wallets() never returning on VSS-backed nodes, which also stopped the background passes waiting on it. A sync VssStore call waited with a nested Handle::block_on on the caller's thread. Under sync_wallets()'s own block_on, that shared the thread's tokio parker and could take the wakeup of the other pass, which runs beside it in the same task, so that pass never resumed. Sync calls now run on the store runtime and wait on a std channel.
  • Bumps the version to 0.7.0-rc.89 (release, cut from 802d36f), regenerates the bindings and updates the mobile guide's SyncType examples.

Trade-off: a payment to an additional account shows up after that account's interval, not the primary's.

Out of Scope

QA Notes

Manual Tests

  • Bitkit mainnet with several Paykit Server accounts, on the twin bump PRs (emulator or simulator) → primary Incremental sync of primary on-chain wallet finished in stays near its no-extras time (~4 s) and no timed out lines for the primary

Automated Checks

  • added test_background_sync_keeps_additional_wallets_on_their_own_interval in multi_address_types_tests.rs, on Electrum and Esplora: with a 3600 s additional interval the primary balance syncs in the background while the derived account stays unsynced, then update_sync_intervals with a 10 s additional interval picks it up
  • added additional_wallets_get_their_own_connection_opened_once in electrum.rs
  • added tx_events_dedupe_across_passes_until_reorg and dropped_sync_pass_fails_its_waiters in chain/mod.rs, additional_connection_reconnects_after_a_failed_ping and additional_pass_fails_when_its_connection_cannot_be_replaced in electrum.rs, sent_and_received_counts_wallets_that_have_not_synced_the_tx and tx_tip_height_ignores_wallets_not_tracking_it in bdk-wallet-aggregate
  • added sync_completed_reports_the_synced_scope_tip, sync_requests_skip_wallets_removed_mid_pass and pass_waiters_return_once_its_events_are_queued (with the rerun check for a wallet the joined pass did not sync) in chain/mod.rs, additional_wallets_get_their_own_deadline, timed_out_connection_is_replaced_before_the_next_wallet, timed_out_wallet_gets_its_connection_replaced_before_the_next_wallet, remaining_wallets_fail_unsynced_when_the_connection_cannot_be_replaced and only_a_timeout_replaces_the_additional_connection in electrum.rs
  • added sync_call_keeps_the_wakeups_of_the_futures_beside_it in vss_store.rs: fails on 9ec6e14 and passes with the fix; against a local vss-server, sync_wallets() called 3 times during a 10 s background sync hung on the second call before the fix and passed 6 of 6 runs after it
  • ran a probe of two overlapping calls per round on one electrum-client connection against electrsd: one call never returned in round 2897, the stall the sequential order avoids
  • extended sync_completed_event to check AdditionalOnchainWallets is sent only with an additional wallet
  • ran cargo test --lib, cargo check --features uniffi --tests, cargo test -p bdk-wallet-aggregate, the derived_accounts, events and balance tests in multi_address_types_tests, and the onchain and event tests in integration_tests_rust (with an arm64 electrs; a test that failed while starting its node under parallel load passed when rerun alone)

Models used

  • Planning/scoping: Claude Opus 5.5 (reasoning: medium)
  • Implementation: Claude Opus 5.5 (reasoning: medium), Claude Sonnet 5.5 (reasoning: high), Claude Haiku 5.5 (reasoning: high)
  • Review: Gemini 4 Neon (reasoning: Not exposed), Gemini 4 Neon (reasoning: high), Claude Sonnet 5.5 (reasoning: high), Claude Opus 5.5 (reasoning: medium)
  • Review rounds: 20

Release

The primary wallet and every additional wallet (monitored address types
and derived accounts) ran in one join on one Electrum connection, so the
primary's result waited for the slowest additional wallet, and the
server answered the primary's requests only after theirs. With five
Paykit accounts a sync took 10-18 s and all of them regularly hit the
40 s deadline together.

Additional wallets now sync in their own background loop on
additional_wallet_sync_interval_secs (BackgroundSyncConfig and
RuntimeSyncIntervals, default 80 s), each pass with its own in-flight
guard, and Electrum syncs them over their own connection, opened on
their first sync. sync_wallets() still syncs all wallets, running both
passes concurrently. SyncCompleted fires for the primary pass only; the
eviction check runs under a lock with applying results so overlapping
passes report each eviction once.

Verified: cargo test --lib; cargo check --features uniffi; cargo test
--test multi_address_types_tests derived_accounts (one bitcoind start
flake, passed on rerun)
The primary and additional passes now overlap, so their event emission
is serialized: BalanceChanged compares against the balance the other
pass last reported. SyncCompleted fires after either pass, so apps that
refresh on it see additional-account payments. Evictions are reported
even when another wallet in the pass failed.

Electrum: additional wallets share one connection that the server
answers in order, so every request in a pass gets the deadline of the
whole pass, and the connection, idle between passes, is pinged first
and reconnected if the server or a NAT dropped it.

The background-interval test now covers Esplora too.

Verified: cargo test --lib; cargo check --features uniffi --tests;
cargo test --test multi_address_types_tests derived_accounts (20 pass,
two bitcoind start failures and one Bitcoind reorg test rerun alone)
@ovitrif ovitrif self-assigned this Dec 3, 2026
@ovitrif
ovitrif requested review from a team, ben-kaufman and piotr-iohk and removed request for a team December 3, 2026 15:45
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 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-12-03T15:51:37.670646Z b3ecd09 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: b3ecd09eb3

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

Comment thread src/chain/mod.rs Resolved
Comment thread bindings/ldk_node.udl Resolved

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

2 findings (1 P1, 1 P2). Splits additional on-chain wallets into their own sync loop and Electrum connection so they stop delaying the primary. Reviewed b3ecd09, full tier, static: talos-pr-run refused to build it on this box (it could not confirm the author's permission and fails closed), so nothing was compiled or run here.

What I checked, and 5 candidates I ruled out

Read in full: the diff of src/chain/mod.rs, src/chain/electrum.rs, src/chain/esplora.rs, src/config.rs, bindings/ldk_node.udl, plus check_evicted_transactions, collect_additional_sync_requests, apply_additional_sync_results, reconnect_client, Node::sync_wallets, Node::update_sync_intervals, Wallet::get_balance_for_address_type
Consumers traced: Event::SyncCompleted handling in synonymdev/bitkit-android (AppViewModel.handleSyncCompleted, LightningRepo.pruneEmptyAddressTypesAfterRestore) and synonymdev/bitkit-ios (AppViewModel .syncCompleted, SettingsViewModel.pruneEmptyAddressTypesAfterRestore)
CI: one check on this head, mobile-builds-unwind, green; the Rust test workflow did not report on this PR

Ruled out

  • Same eviction reported twice by overlapping passes: apply_wallet_sync_results takes sync_apply_lock around the before/after unconfirmed snapshot, so each pass sees only the txids its own updates removed.
  • Two concurrent first syncs opening two additional connections: OnceCell::get_or_try_init runs one initializer; the unit test covers the second call returning the same Arc.
  • BalanceChanged racing between passes: sync_events_lock is held from event processing through check_and_emit_balance_update, and the balance is recomputed under it.
  • Binding callers breaking on the new field: the UDL default of 80 keeps existing BackgroundSyncConfig/RuntimeSyncIntervals constructors compiling.
  • Reconnect failure on the idle connection wedging the pass: a failed ping-then-reconnect leaves the old client in place, the pass fails on its own deadline and the next ping retries.
  • Cold reader: the P1 stood; it agreed the event carries no scope and that an unscanned account reads 0.

Merge confidence: 3/5, one P1 on the SyncCompleted contract.

Reviewer model: claude-opus-5-5
Reasoning effort: low

Comment thread src/chain/mod.rs Resolved
Comment thread src/chain/electrum.rs Resolved
Verified: ./bindgen.sh regenerated the bindings and the Swift xcframework; swift package compute-checksum of LDKNodeFFI.xcframework.zip matches Package.swift

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

QA review

Scope: changes since b3ecd09, including the affected sync and event paths, at b39917a. Baseline: the completed review of b3ecd09 (merge base a5c32cf unchanged).

4 actionable findings — resolve or provide an evidence-backed rebuttal.

SyncCompleted for a background pass is now emitted only after both scopes have succeeded and every current additional wallet has synced, including one registered at runtime. Coalesced and empty passes are skipped so they do not emit that event again. Transaction events are deduped across passes, and a confirmation in a new block is reported again. sync_wallets() emits one completion after both scopes return success. Release 0.7.0-rc.86 matches the changelog and the Swift, Kotlin, and Python bindings, which now include additional_wallet_sync_interval_secs with the UDL default of 80.

Validation: source inspection of the follow-up diff and the new unit tests sync_completed_waits_for_both_scopes and tx_events_dedupe_across_passes_until_reorg. Those tests were not executed here; the crate requires Rust 1.85 and this environment has Rust 1.83, with no prebuilt dependencies. The author's Bitkit mainnet manual check was not run. Background scheduling, Electrum connection recovery, Esplora scan deadlines, and the existing regression tests are inherited from the baseline.

Earlier findings reconciled at this revision: 4 still present, 3 verified fixed.

Findings

  • [MEDIUM] Emit the full cross-wallet amount when deduplicating a transaction event — inline at src/chain/mod.rs:664. Still present from an earlier unpublished review.
  • [MEDIUM] Clear the additional sync guard when an Electrum ping is interrupted — inline at src/chain/electrum.rs:917. Still present from an earlier unpublished review.
  • [MEDIUM] Use the primary wallet tip to settle primary-only payments — inline at src/chain/mod.rs:1248. Still present from an earlier unpublished review.
  • [MEDIUM] Keep slow additional-wallet persistence off the primary sync loop — inline at src/chain/mod.rs:1309. Still present from an earlier unpublished review.

Reviewer model: grok-4.7
Reasoning effort: xhigh

Comment thread src/chain/mod.rs Resolved
Comment thread src/chain/electrum.rs Resolved
Comment thread src/chain/mod.rs Resolved
Comment thread src/chain/mod.rs Outdated
error: sync_error,
skipped,
} = esplora_chain_source.sync_onchain_wallet(Arc::clone(&wallet), scope).await;
let mut events_state = self.sync_events.lock().await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[MEDIUM] Keep slow additional-wallet persistence off the primary sync loop

If an additional pass is persisting wallet events when the primary pass finishes fetching, the primary waits on sync_events_lock. Each event serializes the whole queue and awaits its store write under that lock. With VSS, those writes can wait on remote I/O and retries, and the primary loop cannot reach its next Lightning or fee update while it waits. Keep balance transitions ordered while keeping additional-wallet persistence off the primary loop’s critical path. This finding is based on source analysis. Live VSS timing remains unmeasured. Primary loop scheduling Event queue persistence VSS write implementation

Still present at b39917a (first reported at b3ecd09): sync_onchain_wallet_with_events holds sync_events across process_wallet_events (src/chain/mod.rs:1309 for Esplora and :1420 for Electrum). process_wallet_events awaits EventQueue::add_event, and add_event awaits persist_queue's KVStore write (src/event.rs:1001-1008 and :1040-1048). The primary loop handles the on-chain tick, fee update, and Lightning sync as arms of one select (src/chain/mod.rs:1240-1260), so an additional pass persisting events blocks that loop even though the scan loops themselves are separate (src/chain/mod.rs:1098-1116). The follow-up does not move the awaited write off this lock. This is source analysis; live VSS timing was not measured. A focused issue search found no matching ticket, and this item has no PR thread.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Keeping this one as is. The additional pass holds the lock across store writes only when it emits something: a new transaction or eviction for an additional wallet, or a balance change (check_and_emit_balance_update writes only then). The primary loop already awaits the same add_event writes for its own events inline. Before this PR the primary waited for the whole additional fetch (10–40 s with five accounts) plus those writes; now it waits at most for those writes. Moving them off the lock would need another way to keep BalanceChanged ordered, which I'd rather not add without a measured VSS stall.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Still keeping it as is at 9ec6e14. Only the event emission holds sync_events, not the additional wallets' scan or apply, and it serializes the two passes so BalanceChanged compares against the balance the other pass last reported. Moving the store write off it would need another way to order those events. If VSS write times show it delaying the primary loop on devices, it can follow in its own PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Still keeping it as is at 05b2405. The stall fixed in rc.87 was not a slow write under this lock. The SyncCompleted write had finished, and the pass holding sync_events never got its wakeup back. With that fixed, the lock is held only for the emission's own store writes, as before. If VSS write times on devices show those delaying the primary loop, it can follow in its own PR.

…ts' tip and release cancelled sync waiters

Verified: cargo test --lib, cargo test -p bdk-wallet-aggregate
Verified: ./bindgen.sh rebuilt the Swift xcframework; swift package compute-checksum of LDKNodeFFI.xcframework.zip matches Package.swift
@ovitrif
ovitrif requested a review from piotr-iohk December 3, 2026 18:09

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

QA review

Scope: changes since b39917a, including affected code paths and prior findings, at 4e86a45. Baseline: previous QA review.

No new actionable code findings.

A dropped Electrum or Esplora on-chain pass now fails its waiters with WalletOperationFailed and returns that scope to Completed, so the next pass can start. A pass that finishes still publishes the same success or failure as before. sent_and_received adds every loaded wallet's indexed sends and receives for a transaction another wallet has already applied. BDK 2.2.0 (bdk_chain 0.23.3) counts a received output from the script index without the transaction being applied, and counts a spend only when that previous output was already scanned. Confirmation depth uses the oldest checkpoint among wallets whose canonical graph already contains the transaction, so a primary-only payment can reach Succeeded while an additional wallet that does not have it is still behind. An output whose script is outside that wallet's revealed and lookahead index is still omitted until that wallet syncs.

Validation: Source inspection at 4e86a45, including those BDK crate sources. Cargo tests were not run. The only published check on this revision is mobile-builds-unwind, which does not exercise these paths. No v0.7.0-rc.86 GitHub release exists, so the updated Swift checksum was not compared to an xcframework. Changelog, Cargo versions, and UniFFI sources are unchanged since b39917a. The author's Bitkit mainnet sync-timing check was not run.

Suggested additional test cases:

  • Rust, bdk-wallet-aggregate: apply a transaction only on wallet A, with one of its outputs already in wallet B's script index. sent_and_received includes B's output. With that script absent from B's index, B adds nothing.
  • Rust, payment status: primary tip is at least the confirmation height plus ANTI_REORG_DELAY, and an additional wallet's tip is older. The payment is Succeeded when only the primary has the transaction, and stays Pending when the additional wallet also has it and its tip is still short of the threshold.

Earlier findings reconciled at this revision: 1 still present, 3 verified fixed.

Existing concerns

  • [MEDIUM] Keep slow additional-wallet persistence off the primary sync loop — Review thread #154 (comment) is open. The author replied that the lock stays because the additional pass holds it only while emitting, and that moving the write off the lock needs another way to order BalanceChanged. The mechanism is unchanged at 4e86a45. After either scope's fetch returns, sync_onchain_wallet_with_events holds sync_events across process_wallet_events. add_event awaits persist_queue's KVStore write before it returns. The primary loop's on-chain, fee, and Lightning work are arms of one select, so an additional pass inside that awaited write keeps the primary arm from returning to the next fee or Lightning tick. The scan loops themselves stay separate. This is source analysis; live VSS timing was not measured. A focused issue search, including closed issues, for additional-wallet persistence returned #152 and #117. Neither is this lock, and there is no matching ticket.

Reviewer model: grok-4.7
Reasoning effort: xhigh

…e connection

Verified: cargo test --lib, cargo test -p bdk-wallet-aggregate
Verified: swift package compute-checksum matches Package.swift (44db2715…)
Verified: cargo test --test multi_address_types_tests test_background_sync_keeps_additional_wallets_on_their_own_interval
…emoved mid-pass

A pass now finishes, waking calls that joined it, only after it queued its events. Requests skip additional wallets removed while the pass connects, and the pass deadline adds up every additional wallet's own deadline.

Verified: cargo test --lib
Verified: swift package compute-checksum matches Package.swift (19760142…)
@ovitrif

ovitrif commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed c7422fe..12e9048 after Gemini Neon self-review rounds on the head:

  • SyncCompleted reports each pass: OnchainWallet for the primary wallet, the new AdditionalOnchainWallets for the additional wallets.
  • A sync_wallets() call that joins a pass in flight returns once that pass has queued its events.
  • The idle additional Electrum connection's ping and reconnect are bounded by the sync timeout; a pass that can't reconnect fails.
  • An additional wallet removed while a pass connects is skipped, and an additional pass's deadline adds up every wallet's own deadline.
  • Bindings and the 0.7.0-rc.86 xcframework checksum are regenerated.

Tests: cargo test --lib, cargo test -p bdk-wallet-aggregate, and the events, derived_accounts, balance and restart tests in multi_address_types_tests plus the onchain and event tests in integration_tests_rust pass.

@ovitrif
ovitrif requested a review from piotr-iohk December 3, 2026 20:55

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

QA review

Scope: changes since 4e86a454, including affected code paths and prior findings, at 12e9048. Baseline: previous review.

1 actionable finding — resolve or provide an evidence-backed rebuttal.

An additional-wallet pass can report synced_block_height from a wallet registered after that pass chose its accounts. Inherited coverage still covers cross-wallet amounts, cross-pass event dedup, background scheduling, and Esplora scan scoping.

Validation: source inspection of the follow-up delta. I did not run cargo test, the Bitkit manual check in the PR description, or a checksum comparison of the Swift xcframework zip.

Suggested additional test cases:

  • Electrum and Esplora: while an additional pass is fetching, register a second derived account, then let that pass apply a higher tip only to the account it snapshotted. Expected: SyncCompleted for AdditionalOnchainWallets uses the snapshotted account's new tip, and sync_wallets() after the registration does not return until a pass has applied the new account.

Earlier findings reconciled at this revision: 1 still present.

Findings

  • [MEDIUM] Report additional sync height from the wallets that pass synced — inline at src/chain/mod.rs:713.

Existing concerns

  • [MEDIUM] Keep slow additional-wallet persistence off the primary sync loop — Review thread #154 (comment) is open. GitHub marks its anchor outdated. The author replied that the lock stays, because moving the store write off it would need another way to order BalanceChanged. At 12e9048, emit_pass_events takes sync_events and holds that guard across process_wallet_events, the SyncCompleted write, and check_and_emit_balance_update. add_event awaits persist_queue's KVStore write, and a VSS store retries put_object inside that write. The additional background loop and the primary loop both call sync_onchain_wallet_with_events. The primary loop's on-chain sync, fee update, and Lightning sync are arms of one select, so an additional pass inside that awaited write keeps the primary arm from returning to the next fee or Lightning tick. The scan loops themselves stay separate. This is source analysis; live VSS timing was not measured. A focused issue search, including closed issues, returned #152, #117, and #99 (the peer-store lock). None is this sync lock, and there is no matching ticket.

Reviewer model: grok-4.7
Reasoning effort: xhigh

Comment thread src/chain/mod.rs Resolved
…w wallets

SyncCompleted reports the lowest tip of the wallets the pass synced. A call that joined an additional pass runs another when that pass did not sync every additional wallet registered when the call started.

Verified: cargo test --lib
Verified: swift package compute-checksum matches Package.swift (4f4f2b0f…)
@ovitrif

ovitrif commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 12e9048..9ec6e14 after a Gemini Neon self-review on the head: SyncCompleted for AdditionalOnchainWallets reports the lowest tip of the wallets that pass synced, and a sync_wallets() call that joins an additional pass reruns it for wallets registered after that pass read its accounts. The 0.7.0-rc.86 checksum is regenerated.

Tests: cargo test --lib, and the events, derived_accounts, balance and restart tests in multi_address_types_tests plus the onchain and event tests in integration_tests_rust pass.

@ovitrif
ovitrif requested a review from piotr-iohk December 3, 2026 22:01

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

QA review

Scope: changes since 12e9048, including affected code paths, at 9ec6e14. Baseline: previous review.

No new actionable code findings.

SyncCompleted uses the lowest tip of the wallets that pass applied, so a wallet that pass did not sync no longer lowers the height. A sync_wallets or background additional sync that joins an in-flight pass runs one more pass when that pass missed a wallet already registered at the start of the call. A joined call does not replace the record of the pass that ran, and waiters are still released only after that pass queues its events.

Validation: source inspection of this delta and the Electrum and Esplora sync entry points it calls. cargo test was not run. The new unit tests check tip_height_of and the synced-account record; they do not drive the two-iteration loop. No GitHub release named v0.7.0-rc.86 is published (latest listed is v0.7.0-rc.85), so the updated Swift checksum was not compared to a release asset.

Suggested additional test cases:

  • While an additional sync pass is in flight and has already chosen its wallets, register another derived account and call sync_wallets. The call returns only after a later pass has applied that account, and that later AdditionalOnchainWallets event reports the lowest tip of the wallets that pass applied.

Earlier findings reconciled at this revision: 1 still present, 1 verified fixed.

Existing concerns

  • [MEDIUM] Keep slow additional-wallet persistence off the primary sync loop — Review thread #154 (comment) is unresolved. GitHub marks its anchor outdated. The author replied in #154 (comment) that the lock stays, because the additional pass holds it only while emitting and moving the store write off it would need another way to order BalanceChanged. The mechanism is unchanged at 9ec6e14. emit_pass_events takes sync_events and that named guard is still in scope across the later awaits: rustc 1.83.0 (90b35a623 2024-11-26) compiled a named Drop guard and printed after last use, later statement, then dropped. process_wallet_events also borrows the guard for its whole await. add_event awaits persist_queue, and a VSS store awaits write_internal, whose fenced_retry repeats put_object. The additional background loop and the primary loop both call sync_onchain_wallet_with_events. The primary loop's on-chain sync, fee update, and Lightning sync are arms of one select, so an additional pass inside that awaited write keeps the primary arm from returning to the next fee or Lightning tick. The scan loops themselves stay separate. This is source analysis; live VSS timing was not measured. A focused issue search, including closed issues, for sync_events, additional-wallet, and primary sync loop returned #153 and #152. Neither is this lock, and there is no matching ticket.

Reviewer model: grok-4.7
Reasoning effort: xhigh

@ovitrif

ovitrif commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Published v0.7.0-rc.86 from the reviewed head 9ec6e14, since the latest review found nothing new; the Bitkit bump PRs pin it. The Package.swift checksum at the tag matches the uploaded LDKNodeFFI.xcframework.zip. This PR still merges on approval.

@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Holding this PR: a device run of rc.86 in synonymdev/bitkit-android#2255 hit an on-chain sync stall.

On an Android emulator (regtest, Electrum, one additional Taproot wallet), right after a restore, the app called sync_wallets() just after start():

  • Its primary and additional passes logged finished in 227ms and finished in 71ms, then emitted no SyncCompleted, and sync_wallets() never returned.
  • Their pass guards were never released. The next primary tick and additional tick both logged [ldk_node::chain::electrum:302] Sync in progress, skipping. and stayed parked on recv(), so the background loop stopped. On-chain, Lightning and fee-rate sync all stopped for the rest of the run (5 minutes).
  • Earlier starts on the same build synced normally, so it depends on timing.

Since this PR, the pass guard covers event emission (report_pass). So whatever stalls between the finished in log and pass.finish() now stops every on-chain pass, not just that call's events. That window includes the node-metrics write, emit_pass_events holding sync_events across EventQueue::add_event (a store write), tip_height_of and get_balances.

Next: thread stacks from a stalled run, plus a regression test that calls sync_wallets() from a plain thread while background sync runs (the integration tests run with background sync off). The fix will ship as rc.87.

…them

A sync VssStore call waited with Handle::block_on on the caller's
thread. Called from async code that itself runs under a block_on on
that thread, as Node::sync_wallets does, the nested block_on shares the
thread's tokio parker and can take the wakeup of a future joined beside
it. Since the primary and additional wallet passes run concurrently in
one task, the primary pass's SyncCompleted write could finish while the
additional pass sat in a sync node metrics write; the primary pass was
never polled again, held the pass and the event lock, and every later
sync waited on it.

Sync calls now spawn onto the store runtime and wait on a std channel,
which leaves tokio's parker alone.

Verified: cargo test --lib sync_call_keeps_the_wakeups fails 3/3 on
9ec6e14 and passes with the fix; cargo test --lib io::vss_store (26
passed); against a local vss-server, a test running sync_wallets 3x
during background sync hung on the second call before the fix and
passed 6/6 attempts with it (before moving the spawn into
block_in_place, which only orders the two)
Verified: ./bindgen.sh on this tree (exit 0, generated bindings
unchanged); shasum of LDKNodeFFI.xcframework.zip matches Package.swift
@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 0966797 and released as v0.7.0-rc.87. This is the cause of the sync_wallets() stall reported above.

A sync VssStore call waited with block_in_place(|| internal_runtime.handle().block_on(fut)) on the caller's thread. sync_wallets() already runs under Runtime::block_on on that thread, and the primary and additional passes run side by side in that one task. The two block_ons share the thread's tokio parker.

What happened in the stall:

  1. The primary pass was waiting on its SyncCompleted write while holding the event lock.
  2. The additional pass made its sync node metrics write.
  3. The primary's write finished during that call. The nested block_on took the wakeup meant for the outer one.
  4. The primary pass was never polled again. The additional pass waited on the event lock, and every later pass waited on both.

It reproduces against a local vss-server: sync_wallets() called 3 times during a 10 s background sync hangs on the second call. With the fs store it never hangs.

Sync calls now spawn onto the store runtime and wait on a std channel, which leaves tokio's parker alone. sync_call_keeps_the_wakeups_of_the_futures_beside_it fails on 9ec6e14 and passes with the fix. The VSS repro passes 6 of 6 runs.

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

QA review

Scope: changes since 9ec6e14, including affected code paths, at 05b2405. Baseline: previous review.

No new actionable code findings.

Sync VssStore reads, writes, removes, and lists run on the store runtime, and the caller waits on a std channel. That wait does not use the caller's tokio parker, so a metrics write during sync_wallets no longer consumes the wakeup of the pass polled beside it. 0.7.0-rc.87 matches across the crate, lockfile, changelog, Kotlin and Python versions, and Package.swift. Tag v0.7.0-rc.87 points at this commit, and the Package.swift checksum matches the release digest of LDKNodeFFI.xcframework.zip.

Validation: At this revision, cargo test --lib connection_tests passed (first_write_reuses_the_read_connection and sync_call_keeps_the_wakeups_of_the_futures_beside_it). Chain-sync behavior from the baseline is unchanged in this delta and stays inherited.

Earlier findings reconciled at this revision: 1 still present.

Existing concerns

  • [MEDIUM] Keep slow additional-wallet persistence off the primary sync loop — Review thread #154 (comment) is unresolved. GitHub marks its anchor outdated. The latest reply, #154 (comment), keeps the lock so BalanceChanged stays ordered. The mechanism is unchanged at 05b2405. src/chain/mod.rs is identical to 9ec6e14. emit_pass_events takes sync_events and borrows that guard across process_wallet_events, which awaits add_event. rustc 1.83.0 (90b35a623 2024-11-26) compiled a named Drop guard and printed after last use, later statement, then dropped, so the same guard is still alive through the later SyncCompleted and balance awaits. add_event awaits persist_queue's KVStore write. The async VSS write awaits write_internal, whose fenced_retry repeats put_object. A balance change then calls sync write_node_metrics, and KVStoreSync::write waits in block_on_store_runtime before returning. The rc.87 edit replaces Handle::block_on with that std-channel wait for sync reads, writes, removes, and lists. It leaves the caller inside emit_pass_events until the write finishes. The additional loop and the primary loop run under one join. The primary on-chain sync, fee update, and Lightning sync are arms of one select, so an additional pass inside that write keeps the primary arm from returning to the next fee or Lightning tick. The scan itself stays outside the lock. This is source analysis. Live VSS timing was not measured. A focused issue search for sync_events returned total_count 0 and incomplete_results false. Issues 152 and 153 are node-build time and combined-sync duration, and neither is this lock.

Reviewer model: grok-4.7
Reasoning effort: xhigh

electrum-client can lose the wakeup of a call that overlaps another on
the same connection: the reader wakes the next waiter while it still
holds the reader lock, so the waiter goes back to an untimed wait until
a later call reads its response. Nothing else uses the additional
wallets' connection, so after a primary address type change the stuck
wallet waited out the whole pass deadline, about a minute in Bitkit,
and sync_wallets with it.

The additional wallets now sync in turn, each within its own deadline.
A timed-out wallet's connection is replaced before the next wallet or
pass uses it, and the remaining wallets fail if it cannot be.

Verified: cargo test --lib chain:: (57 pass); multi_address_types_tests
derived_accounts (23 pass, serial); a probe of two overlapping calls on
one electrum-client connection stalled in round 2897
Verified: ./bindgen.sh on this tree (exit 0); shasum of
LDKNodeFFI.xcframework.zip matches Package.swift
@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Released 0.7.0-rc.88 with a fix for the Bitkit E2E failure on rc.87 (multi_address_local): after a primary address type change, sync_wallets stayed blocked on the additional pass.

Root cause: electrum-client 0.24.1 can lose the wakeup of a call that overlaps another call on the same connection. The reading thread wakes the next waiter while it still holds the reader lock, so the waiter's try_lock fails and it waits, with no timeout, for a later call to read its response. On the main connection that later call comes within about 10 s. Nothing else uses the additional wallets' connection, so the stuck wallet waited out the whole pass deadline, about a minute with Bitkit's settings.

  • A probe of two overlapping calls per round on one connection against electrsd stalled in round 2897.
  • Fix in 983050a: additional wallets sync one after another, each within its own deadline. A wallet that times out gets a new connection before the next one syncs.

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

QA review

Scope: changes since 05b2405, including affected code paths, at 91b1784. Baseline: previous review.

No new actionable code findings.

Additional Electrum wallets now sync one after another on their connection, each with its own deadline. electrum-client 0.24.1 can lose a second in-flight call's reader wakeup and leave it waiting until a later read; a timed-out call stays on the old client, and the next wallet uses a replacement connection. If that reconnect fails, the rest of the pass fails. Results still go through the existing apply path. Inherited coverage is the previously reviewed VSS wakeup fix, sync completion and joined-pass behavior, removal skipping, confirmation depth, cross-wallet amounts, event dedup, background intervals, and Esplora scanning. Version files agree on 0.7.0-rc.88. GitHub's recorded digest of the v0.7.0-rc.88 LDKNodeFFI.xcframework.zip matches Package.swift, and the tag resolves to 91b1784.

Validation: This review did not run cargo test. The author reports cargo test --lib chain:: (57 passed) and a probe where two overlapping calls on one connection stalled. timed_out_connection_is_replaced_before_the_next_wallet calls replace_connection directly and does not drive two wallets through the sync loop. The xcframework zip was not downloaded to recompute its hash.

Suggested additional test cases

  • Electrum test server, two additional wallets. Leave the first wallet's request unanswered until its deadline, then accept new connections. The first wallet times out, the second wallet's requests arrive on a new connection and only after the first call is no longer in flight on the old one, and the pass returns within that wallet's deadline plus one reconnect deadline.
  • Same setup with reconnect refused. The second wallet is ConnectionFailed and the server receives no request for it.

Earlier findings reconciled at this revision: 1 still present.

Existing concerns

  • [MEDIUM] Keep slow additional-wallet persistence off the primary sync loop — Review thread #154 (comment) is unresolved. GraphQL reviewThreads reports isResolved false and isOutdated true. The latest reply, #154 (comment), keeps the lock so BalanceChanged stays ordered. The mechanism is unchanged at 91b1784: git diff --stat 05b2405 91b1784 for src/chain/mod.rs, src/event.rs, src/io/vss_store.rs, and src/lib.rs is empty. emit_pass_events takes sync_events at src/chain/mod.rs:1550 and process_wallet_events borrows that guard for its whole await at src/chain/mod.rs:1554-1563. rustc 1.83.0 (90b35a623 2024-11-26) --edition 2021, the same edition as Cargo.toml, compiled a named guard borrowed across one await, then a later statement and a second await. The run printed touch, later statement, Pending, Pending, and dropped only when that suspended future was dropped, so the same guard is still alive through emit_onchain_sync_completed at src/chain/mod.rs:1591 and check_and_emit_balance_update at src/chain/mod.rs:1632-1639. process_wallet_events awaits event_queue.add_event at src/chain/mod.rs:805, src/chain/mod.rs:825, src/chain/mod.rs:853, and src/chain/mod.rs:884. src/event.rs:1014 awaits persist_queue, and src/event.rs:1047-1054 awaits KVStore::write. The async VSS write at src/io/vss_store.rs:560-574 spawns write_internal and awaits it. src/io/vss_store.rs:841-848 calls fenced_retry (src/io/vss_store.rs:261) around client.put_object with WRITE_ATTEMPT_TIMEOUT of 30s at src/io/vss_store.rs:79. A balance change awaits add_event at src/lib.rs:2547-2556 and then calls write_node_metrics at src/lib.rs:2566. src/io/utils.rs:303-309 calls KVStoreSync::write, and the VSS sync write at src/io/vss_store.rs:471 waits in block_on_store_runtime at src/io/vss_store.rs:408-416. src/chain/mod.rs:1253-1271 joins the two loops. src/chain/mod.rs:1300-1308 runs the additional pass. src/chain/mod.rs:1349-1413 keeps the primary on-chain sync, fee update, and Lightning sync in one select, so an additional pass inside that awaited write keeps the primary arm from returning to the next fee or Lightning tick. The scan itself stays outside the lock. This is source analysis. Live VSS timing was not measured. A focused issue search q=repo:synonymdev/ldk-node sync_events returned total_count 0 and incomplete_results false. The Electrum ordering change since 05b2405 does not acquire this lock.

Reviewer model: grok-4.7
Reasoning effort: xhigh

Moves the loop into sync_additional_wallets_in_turn, unchanged, so tests can drive it with fake syncs: a timed-out wallet gets its connection replaced, with the client it used, before the next wallet syncs; when replacing fails the remaining wallets fail without being synced; other errors replace nothing.

Verified: cargo test --lib chain:: (60 passed), cargo clippy --lib --tests (no new warnings)
Verified: ./bindgen.sh on this tree (the archive step segfaulted once and passed on rerun); shasum of LDKNodeFFI.xcframework.zip matches Package.swift
@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

@piotr-iohk I added the loop test your QA review suggested, in 36b7ce4. The additional wallets' loop now lives in sync_additional_wallets_in_turn, with no behaviour change, so tests can drive it with fake syncs:

  • timed_out_wallet_gets_its_connection_replaced_before_the_next_wallet: after the first wallet times out, the connection is replaced before the second wallet syncs, and the replaced client is the one the timed-out call used, even when the connection moved to another client in the meantime.
  • remaining_wallets_fail_unsynced_when_the_connection_cannot_be_replaced: when replacing fails, the remaining wallets get ConnectionFailed and are never synced.
  • only_a_timeout_replaces_the_additional_connection: any other error leaves the connection alone.

Together with timed_out_connection_is_replaced_before_the_next_wallet, which opens the new connection, this covers both cases. Released as 0.7.0-rc.89, with the same behaviour as rc.88.

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

QA review

Scope: changes since 91b1784, including affected code paths, at 802d36f. Baseline: previous review. 91b1784 is an ancestor of the reviewed head, and the base and merge base (a5c32cf) are unchanged. Coverage of the unchanged VSS, sync-completion, event-dedup, background-sync and Esplora surfaces is inherited from that baseline.

No new actionable code findings.

The delta has two commits. The first moves the Electrum loop that syncs the additional wallets one at a time out of sync_onchain_wallet_inner into a generic sync_additional_wallets_in_turn and adds unit tests for it. The second releases 0.7.0-rc.89. The loop's behaviour is the same as before:

  • Each wallet takes one connection snapshot.
  • Each wallet keeps its own deadline and batch size.
  • Only WalletOperationTimeout triggers replace_connection, and it replaces the client the timed-out call used.
  • If replacement fails, the remaining wallets get ConnectionFailed without being synced.
  • The per-wallet warning log is kept.

The pre-pass ping and replace_connection themselves did not change.

The release bump is consistent across Cargo.toml, Cargo.lock, both Kotlin gradle.properties files, pyproject.toml and Package.swift. The Package.swift checksum matches the digest GitHub reports for the v0.7.0-rc.89 LDKNodeFFI.xcframework.zip asset, and the tag resolves to the reviewed head. The zip itself was not downloaded and re-hashed.

Validation: cargo test --lib chain::electrum at 802d36f passed 24/24. That includes the new timed_out_wallet_gets_its_connection_replaced_before_the_next_wallet, remaining_wallets_fail_unsynced_when_the_connection_cannot_be_replaced and only_a_timeout_replaces_the_additional_connection. rustfmt --check is clean on src/chain/electrum.rs. The build used ELECTRSD_SKIP_DOWNLOAD/BITCOIND_SKIP_DOWNLOAD because the electrsd build script could not download binaries in the sandbox. Integration tests (bitcoind/electrs) were not run, so the timeout-and-replace path has not been exercised against a real Electrum server in this pass.

Earlier findings reconciled at this revision: 1 still present.

Existing concerns

  • [MEDIUM] Keep slow additional-wallet persistence off the primary sync loop — The mechanism is unchanged at 802d36f. git diff --stat 91b1784 802d36f for src/chain/mod.rs, src/event.rs, src/io/vss_store.rs, src/lib.rs and src/io/utils.rs is empty. The only code change since the last reviewed head extracts the additional Electrum loop into sync_additional_wallets_in_turn in src/chain/electrum.rs, and that code does not take sync_events. sync_onchain_wallet_with_events takes sync_events at src/chain/mod.rs:1550, a line the PR adds (diff hunk @@ -1061,3 +1528,23 @@ against a5c32cf). It holds that guard across the awaited process_wallet_events (src/chain/mod.rs:1554-1563), emit_onchain_sync_completed (src/chain/mod.rs:1591) and check_and_emit_balance_update (src/chain/mod.rs:1632-1639). EventQueue::add_event awaits persist_queue (src/event.rs:1014), which awaits KVStore::write (src/event.rs:1047-1054). The async VSS write spawns write_internal and awaits it (src/io/vss_store.rs:560-576), and write_internal retries put_object through fenced_retry with a 30 s WRITE_ATTEMPT_TIMEOUT (src/io/vss_store.rs:79 and :845-848). The additional loop (src/chain/mod.rs:1300-1308) and the primary loop are polled under one tokio::join! (src/chain/mod.rs:1253-1271). The primary on-chain sync, fee update and Lightning sync are arms of one select (src/chain/mod.rs:1349-1413), so while an additional pass holds the lock inside a slow write, the primary arm cannot get back to the next fee or Lightning tick. Review thread #154 (comment) is still unresolved (isResolved false, isOutdated true). The author's latest reply (#154 (comment)) keeps the lock to preserve BalanceChanged ordering and defers any change to a follow-up PR if device VSS timings show a delay. No material new evidence since the 91b1784 report, so this is a reference to an existing concern, not a new inline finding. This is source analysis; live VSS timing was not measured.

Reviewer model: claude-opus-5-5
Reasoning effort: high

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.

perf: additional wallets slow every background sync and time out together

3 participants