Skip to content

perf: sync extra wallets apart from the wallet - #1588

Open
ovitrif wants to merge 5 commits into
masterfrom
perf/additional-wallets-own-sync
Open

ovitrif wants to merge 5 commits into
masterfrom
perf/additional-wallets-own-sync

Conversation

@ovitrif

@ovitrif ovitrif commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

Twin: synonymdev/bitkit-android#2255
Dependency: synonymdev/ldk-node#154

Bumps ldk-node to v0.7.0-rc.89, which syncs additional on-chain wallets (Paykit Server accounts, monitored address types) in their own background pass, so they no longer slow down the wallet's own sync. It also fixes that pass hanging for up to a minute after a primary address type change.

Description

  • LightningService.swift: sets additionalWalletSyncIntervalSecs to 60 s, and records each on-chain pass since the node started in a new OnchainSyncTracker.
  • AppViewModel.swift: .onchainWallet now covers only the wallet's own pass, so the restore hold, the empty address type prune and the post-migration sync wait until the wallet's pass and .additionalOnchainWallets have both completed since the node started, and use the lower of the two heights. Without extra wallets the wallet's pass is enough, as before.
  • WalletViewModel.swift: the extra wallets' background pass no longer lowers the shown block height or flips isSyncingWallet, and a manual sync keeps the flag until it returns.
  • project.pbxproj, Package.resolved: rc.89.

Out of Scope

  • After perf: load watch-only accounts after node start #1584, watch-only accounts load after the node starts, so a restore that completes before they load does not wait for them. Monitored address types still load at build. Whichever of the two PRs merges second rebases on the other.

Design

N/A — no UI changes.

Preview

N/A

QA Notes

Setup

Build from this branch (dev, regtest or mainnet). For the restore cases, use a wallet with more than one monitored address type or a Paykit Server account, so the node tracks extra wallets.

Journeys

  • journeys/backup-restore/restore-waits-for-extra-wallets.xml: back up a funded wallet whose Taproot address type stays monitored after switching to Native Segwit, reset, restore; no Received sheet for the old deposit, the balance is right, and old activity is marked seen only after the extra wallets' pass.

Manual Tests

N/A

Automated Checks

  • added OnchainSyncTrackerTests.swift — every on-chain wallet must sync, the lower height counts, and extra wallets added or re-added after a sync wait for their own pass
  • added RestoreSyncGateTests.swift — the restore prune and hold wait for the extra wallets' pass and record their lower height; a Lightning sync does not end the hold
  • added WalletSyncEventTests.swift — the extra wallets' pass leaves the sync flag and chain tip alone; a manual sync keeps the flag
  • updated RNMigrationSyncLifecycleTests.swift — post-migration sync waits for the extra wallets' pass

Evidence

  • iOS Simulator build at dbec1e1 (rc.89) succeeded; E2E passed at 12707af on rc.88, which has the same behaviour, and runs again on this head in CI.
  • restore-waits-for-extra-wallets journey at 9ecf3e3 (rc.87), iPhone 17 Pro simulator, staging regtest, 300 000 sat on the monitored Taproot address: after the restore, no Received sheet opened in over 5 minutes on Home, the savings balance and activity showed the 300 000 sat, and both passes kept completing (the wallet's every ~10 s, the extra wallets' every ~60 s) with no stall. The in-app reset worked.
  • Simulator smoke test at ebfc5f6 (rc.86), iPhone 17 Pro: create a wallet, monitor Taproot, wipe and restore. Both passes reported SyncCompleted at the same height, the extra wallets' pass did not lower it, and the restore reached Home with no Received sheet (that wallet was unfunded).
  • xcodebuildmcp simulator test (OnchainSyncTrackerTests, RestoreSyncGateTests, RNMigrationSyncLifecycleTests, WalletSyncEventTests, WalletViewModelWipeTests) pass at the PR head on the iPhone 17 simulator.

Gaps

  • The app logs nothing when it marks restored activities seen, so the journey checks the order through the missing sheet and the SyncCompleted order, not a log line.

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: high)
  • Review rounds: 10

Bumps ldk-node to 0.7.0-rc.86, which syncs additional wallets in their own pass. They sync every 60 s, and the restore hold, empty address type prune and post-migration sync wait for both passes when the node tracks extra wallets. The extra wallets' background pass neither lowers the shown block height nor flips the wallet sync flag, and a manual sync keeps the flag until it returns.

Verified: xcodebuildmcp simulator test (OnchainSyncTrackerTests, RestoreSyncGateTests, RNMigrationSyncLifecycleTests, WalletSyncEventTests, WalletViewModelWipeTests)
@ovitrif ovitrif added this to the 3.3.0 milestone Dec 4, 2026
@ovitrif ovitrif self-assigned this Dec 4, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 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-04T00:12:42.911636Z ebfc5f6 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ovitrif
ovitrif requested review from a team, ben-kaufman and jvsena42 and removed request for a team December 4, 2026 00:10
@greptile-apps

greptile-apps Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; no actionable defects were found.

Summary

Moves extra on-chain wallets onto a separate, 60-second sync schedule with ldk-node rc.86.

  • Paykit and other extra wallets sync separately from the main wallet.
  • Restore and migration work waits for every required on-chain wallet pass.
  • Extra-wallet sync events leave the main wallet’s sync status and chain tip alone.

No actionable issues found. Tests were not run during this review.

Acknowledged scope: ovitrif explicitly deferred waiting for watch-only accounts loaded after node startup following #1584; whichever PR merges second must rebase.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Primary wallet pass completes] --> C[Record completed height]
  B[Extra-wallet pass completes] --> C
  C --> D{Every required pass recorded?}
  D -->|No| E[Keep restore and migration waiting]
  D -->|Yes| F[Use lowest recorded height]
  F --> G[Allow restore cleanup and post-migration work]
Loading

Reviews (1) · Last reviewed commit: "perf: sync extra wallets apart from the ..." · Reviewed by Greptile

The journey funds a monitored Taproot address, restores from the phrase and checks the restore hold waits for the extra wallets' pass. It matches the Android journey of the same name.

Verified: none (journey file only; driven in a later device run)

@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. Moves the extra wallets (Paykit Server accounts and other derived or monitored wallets) onto ldk-node rc.86's separate AdditionalOnchainWallets pass every 60 s. Restore pruning, the restore activity-seen sweep and the post-migration sync now wait until every on-chain wallet has synced. Reviewed ebfc5f6, full tier, static.

What I checked, and 5 candidates I ruled out

Read in full: OnchainSyncTracker.swift, the LightningService sync hooks (start, event loop, listOnchainWalletAccounts), AppViewModel syncCompleted handling and beginPostMigrationSync, WalletViewModel.applySync* / sync(), the new tests.
Cross-repo contract: read ldk-node at v0.7.0-rc.86 (9ec6e14). AdditionalOnchainWallets is only emitted for a pass that synced at least one wallet (emit_pass_events). Its height is the tip of the synced wallets (emit_onchain_sync_completed). Its interval comes from additional_wallet_sync_interval_secs. Swift's listOnchainWalletAccounts().count > 1 matches loaded_keys() (primary plus loaded extras).
Build: not built. iOS does not build on Linux, and a Bitkit auto review never runs the branch's code here.
CI: SwiftFormat and validate green; Run Tests, Run Integration Tests and build-local still pending when I read them.

Ruled out

  • Restore gate never opens when an extra wallet is configured but its pass fails: the tracker keeps waiting, which is the intended gate. The pass retries every 60 s, and a node restart resets the tracker through start().
  • Extra wallet removed between passes leaves the gate shut: record drops the stale extra height when hasAdditionalWallets is false and counts the primary alone (testExtraWalletsReAddedAfterRemovalWaitForANewPass).
  • Background extra-wallet pass clears the pull-to-refresh spinner: applySyncCompleted ignores .additionalOnchainWallets, and isManualSyncInFlight keeps the primary pass from clearing it mid sync().
  • currentBlockHeight pulled back by the extra wallets' lower tip: their completion no longer writes it.
  • Prune task outliving the test: restorePruneTask is now held and checks for cancellation after the sleep.

Merge confidence: 4/5, static review only (iOS not built here) and the unit and integration jobs had not finished.

Reviewer model: claude-opus-5-5
Reasoning effort: not exposed by this run

rc.87 fixes sync_wallets never returning on VSS-backed nodes, which
stopped the background syncs this PR depends on.

Verified: xcodebuild build of the Bitkit scheme for the iOS Simulator
(arm64) resolves ldk-node 0.7.0-rc.87 and succeeds
@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Bumped ldk-node to v0.7.0-rc.87 in 9ecf3e3. rc.86 could stop all background syncing after a restore because a sync_wallets() call never returned (cause).

On rc.87 the restore-waits-for-extra-wallets journey passes on the iPhone 17 Pro simulator against staging regtest:

  • The wallet had 300 000 sat on the monitored Taproot address.
  • After the restore, no Received sheet opened in over 5 minutes, and the balance showed the deposit.
  • Both passes kept completing on their own intervals: the wallet's every ~10 s, the extra wallets' every ~60 s.

rc.88 fixes the additional wallets' sync pass hanging after a primary address type change.

Verified: iOS Simulator build (arm64) succeeded
@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Bumped ldk-node to 0.7.0-rc.88 in 12707af. rc.88 fixes the additional wallets' sync pass hanging for up to a minute after a primary address type change, which failed multi_address_local E2E on the twin synonymdev/bitkit-android#2255. Root cause: synonymdev/ldk-node#154 comment.

@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Reran build-local: it failed while cloning synonymdev/bitkit-core (curl 56, the network timed out), not on this change.

rc.89 has the same behaviour as rc.88; its additional wallets' sync loop gained tests.

Verified: iOS Simulator build (arm64) succeeded
@ovitrif

ovitrif commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Bumped ldk-node to 0.7.0-rc.89 in dbec1e1. It behaves the same as rc.88; the only change is tests for its additional wallets' sync loop, which the library's release rules require to ship as a new rc.

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code scan at dbec1e1b0: one LOW, posted inline. No HIGH or MEDIUM. The device gate is still to run.

What I checked and found clean:

  • Prune of a funded address type. rc.89 emits .additionalOnchainWallets only when every extra wallet synced (emit_pass_events returns before emitting on any failure). Monitored types are in the build config at restore (LightningService.swift:361), so listOnchainWalletAccounts().count > 1 holds from the first event. The prune keeps a type whose balance read throws.
  • Balance after restore. WalletViewModel still refreshes on every syncCompleted, extras included, and on balanceChanged.
  • Waits that never end.
    • With no extras, the wallet's pass alone opens the gate.
    • start() resets the tracker when the node is not running.
    • The extras' loop ticks immediately at start.
    • A failing extras pass keeps the hold up, as on master, where rc.85 emitted no completion either.
  • Tracker. All access goes through onchainSyncLock. stopNode awaits endEventLoop, so an old loop cannot record after the next start's reset. A late syncCompleted from the wiped wallet now reads nil and is ignored.
  • isSyncingWallet. rc.89 emits no SyncProgress, so only sync() sets the flag. It clears it on success and in the catch, and defer clears isManualSyncInFlight on every exit.
  • Manual sync duration. rc.89 runs the primary and additional scopes concurrently on separate Electrum connections, so syncWallets() takes about max(primary, sum of extras). The device gate measures it.

Performance: relevant, because the PR's purpose is speed and it re-times background work. The device gate measures these, against master (rc.85):

  • wallet pass duration and pull-to-refresh time with 3 monitored types plus at least one Paykit Server account;
  • extras cadence (about 60 s);
  • time for a receive to a monitored non-primary type to show up (about 10 s on master, up to about 60 s here);
  • restore with history on two or more types, through restore-waits-for-extra-wallets.xml.

Device gate (partial): dbec1e1 — not run yet. Pending: journey restore-waits-for-extra-wallets.xml and the perf measurements above. The device result will follow in a second review.

Reviewer model: claude-fable-5-2 (primary review), claude-opus-5-5 (verification)
Reasoning effort: Not exposed for the primary review; low for verification (from the verifier's session setting)

// After a seed restore, the first on-chain sync has now discovered the historical txs.
// Mark them seen so they don't pop a "Received" sheet, and lift the restore suppression. #588
if syncType == .onchainWallet, beginCompletingPendingRestoreActivitySeen() {
if let allWalletsSyncedHeight, beginCompletingPendingRestoreActivitySeen() {

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.

LOW: a payment received while the extra wallets are still on their first scan after a restore loses its Received sheet until it confirms.

This line now waits for the extra wallets' first pass as well as the wallet's own. rc.89 runs the two on separate loops, so the wallet keeps polling every 10 s while the extras' first full scan is still running.

  • A new payment found by one of those later wallet passes reaches .onchainTransactionReceived, and holdReceiveDuringRestore holds it (:2211).
  • When the extras' pass opens this gate, beginCompletingPendingRestoreActivitySeen (:1910) clears it as history with restoreHeldReceives.removeAll().
  • The sweep cutoff is the restore start, so the payment is not marked seen either. The sheet only shows on .onchainTransactionConfirmed (:2225).

On master (rc.85) the single combined pass opened the gate, and a 10 s tick during that pass joined it instead of starting a new pass. Only the restore scan's own receives were dropped, and a payment arriving later was picked up by the next pass, after the gate, and presented.

This only happens on wallets with extra wallets (monitored address types, Paykit Server accounts). Balance and activity are correct.

Fix: drop the held receives at the wallet's own first pass after the restore, not when the gate opens:

// handleLdkNodeEvent, .syncCompleted, before this gate
if syncType == .onchainWallet, SettingsViewModel.shared.pendingRestoreActivitySeen, !isCompletingRestoreHold,
   !hasDroppedRestoreScanReceives
{
    restoreHeldReceives.removeAll()
    hasDroppedRestoreScanReceives = true
}

In beginCompletingPendingRestoreActivitySeen, only removeAll() when !hasDroppedRestoreScanReceives, then reset the flag. The assertion at RestoreSyncGateTests.swift:45 then expects isEmpty.

A trade-off with this fix: receives coming from the extras' own first pass are no longer all dropped. Confirmed history still stays quiet through the restore-tip check. A mempool transaction to an extra wallet at restore time could show a sheet. Tagging held receives by wallet would avoid that, but the event carries no account.

On Android, synonymdev/bitkit-android#2255 widens the same window differently. NotifyPaymentReceivedHandler suppresses while pendingRestoreActivitySeen is set, which now lasts until the extras' pass, and nothing is shown again afterwards. Master also suppressed, but only for the first combined pass.

Reproduction
diff --git a/BitkitTests/RestoreSyncGateTests.swift b/BitkitTests/RestoreSyncGateTests.swift
--- a/BitkitTests/RestoreSyncGateTests.swift
+++ b/BitkitTests/RestoreSyncGateTests.swift
@@ -64,6 +64,33 @@ final class RestoreSyncGateTests: XCTestCase {
         XCTAssertEqual(app.restoreHeldReceives.count, 1)
     }
 
+    func testReceiveAfterTheWalletPassIsPresentedWhenTheExtraWalletsPassOpensTheGate() async throws {
+        SettingsViewModel.shared.pendingRestoreActivitySeenSince = 1
+        let app = try makeApp()
+        XCTAssertTrue(app.holdReceiveDuringRestore(txid: "history", amountSats: 1000))
+
+        // The wallet's own pass ends the restore scan; the extra wallets' first scan is still running.
+        sync(app, .onchainWallet, height: 100)
+        XCTAssertNil(Bitkit.LightningService.shared.allOnchainWalletsSyncedHeight)
+
+        // A later wallet pass, inside the hold, sees a new payment.
+        XCTAssertTrue(app.holdReceiveDuringRestore(txid: "new", amountSats: 1000))
+
+        // The extra wallets' pass opens the gate: the same steps as the `.additionalOnchainWallets` syncCompleted handler,
+        // with a spy in place of the received sheet.
+        Bitkit.LightningService.shared.recordOnchainSync(.additionalOnchainWallets, height: 98, hasAdditionalWallets: true)
+        let height = try XCTUnwrap(Bitkit.LightningService.shared.allOnchainWalletsSyncedHeight)
+        XCTAssertTrue(app.beginCompletingPendingRestoreActivitySeen())
+        var presented: [String] = []
+        await app.completePendingRestoreActivitySeen(
+            syncedBlockHeight: height,
+            markAllSeen: { _ in true },
+            presentReceive: { txid, _ in presented.append(txid) }
+        )
+
+        XCTAssertEqual(presented, ["new"], "a receive held after the wallet's own pass must be presented when the gate opens")
+    }
+

xcodebuild test -project Bitkit.xcodeproj -scheme Bitkit -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:BitkitTests/RestoreSyncGateTests

At dbec1e1b0:

RestoreSyncGateTests.swift:91: error: XCTAssertEqual failed: ("[]") is not equal to ("["new"]") - a receive held after the wallet's own pass must be presented when the gate opens

With the fix above it passes, and so do all 13 RestoreActivitySeenSuppressionTests.

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.

3 participants