Skip to content

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

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

ovitrif wants to merge 16 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 still share their one connection, so every request in an additional pass gets the deadline of the whole pass: every additional wallet's own deadline added up. One slow account no longer pushes the others past their deadlines. 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.
  • Bumps the version to 0.7.0-rc.86, 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_pass_gets_every_wallets_deadline in electrum.rs
  • 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)
  • Review: Claude Sonnet 5.5 (reasoning: high), Claude Opus 5.5 (reasoning: medium), Gemini 4 Neon (reasoning: high)
  • Review rounds: 13

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.

…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
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