Skip to content

perf(crowdnode): stop rescanning full tx history on every restore - #931

Merged
QuantumExplorer merged 2 commits into
developfrom
perf/home-feed-main-thread-contention
Aug 7, 2026
Merged

QuantumExplorer merged 2 commits into
developfrom
perf/home-feed-main-thread-contention

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Problem

The home feed's first transaction load was starved behind CrowdNode's restore.

CrowdNode.restoreState() guards only on signUpState > .notStarted — a state a wallet that never signed up never reaches. So every caller re-ran the full history scan: twice during launch, and again on each entry into the CrowdNode portal. Every restoreState() caller is on the main thread (CrowdNodeModel.swift:28, :142, CrowdNodeWithdrawalRouter.swift:31), so each pass blocked main outright.

From a launch trace: the first reload took 3344 ms against a 1180 ms steady state — the ~2.1 s delta lines up exactly with the CrowdNode window.

Fixes

Measured on a 1756-transaction mainnet wallet (1720 TXO rows):

  1. Memoize a fruitless restore. Keyed to the persisted transaction count, not latched permanently — a restored seed syncing its history in still gets a real scan. Cleared on reset, wipe and wallet switch. Launch restores 2 → 1.
  2. Floor the confirmation scan. getApiAddressConfirmationTx() scanned unbounded while tryRestoreSignUp() already floored at januaryFirst2022Epoch. An API-address confirmation is CrowdNode protocol traffic and cannot predate CrowdNode. This was the restore's expensive half: 1728 rows → 692.
  3. Do the wallet join in the store. It fetched every walletId TXO, faulted .transaction and .spendingTransaction on each (~3440 faults), then fed the resulting txid set back through a contains predicate as wide as the wallet's history. PersistentTxo.walletId is indexed and PersistentTransaction carries both inverses.

Result

before after
restores per launch 2 1
scan rows 692 + 1728 692 + 692
main-thread block ~4 s (2 restores) 0.64–1.95 s (1 restore)
restoring CrowdNode state
CrowdNode scan: fetch 692 rows in 153ms, decode in 207ms
CrowdNode scan: fetch 692 rows in 172ms, decode in 221ms
CrowdNode: account not found

Scan cost varies with launch contention — the same code measured 641 ms on a
warm store and 1954 ms on a cold launch competing with initial sync. The
durable wins are structural rather than a single figure: one restore instead
of two
, and 692 rows instead of 1728 on the second scan.

Also

Drops the DispatchQueue.main.sync read of selectedFilters from inside the home reload pass (performReload extraction accounts for most of the line count — it's re-indentation). Pairing each request with the selection live when it was made is tighter than reading it at pass start, which could render a selection made after the pass began.

What I did not keep

I also tried coalescing redundant reloads. It never fired in measurement — the reloads are sequential triggers spread over time, not concurrent enqueues — and it introduced a real bug: selectedFilters' didSet calls reloadTxDataSource() directly, so a filter tap arriving while a pass was queued would be dropped and silently do nothing. Removed rather than shipped.

Testing

  • dashpay scheme builds clean
  • Launch traces captured on iPhone 16 Plus simulator against a 1756-tx mainnet wallet, before/after, with no concurrent build running (an earlier round's numbers were contaminated by xcodebuild saturating the CPU)
  • Not verified: filter-tap smoke test on device — the simulator was PIN-locked. The change is argued above rather than measured.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Performance
    • Improved transaction scanning and reload performance, especially for larger wallets.
    • Repeated scans with no new transactions are now skipped.
    • Wallet activity filtering and transaction processing are more efficient.
  • Bug Fixes
    • Reduced main-screen delays during transaction reloads.
    • Improved synchronization between wallet updates and displayed activity.
    • API transaction lookups now focus on relevant, recently observed transactions.

`CrowdNode.restoreState()` guards only on `signUpState > .notStarted`, a
state a wallet that never signed up never reaches. Every caller therefore
re-ran the full history scan: twice during launch, and again on each entry
into the CrowdNode portal. Each pass ran on the main thread, because all
`restoreState()` callers are main-thread, so the home feed's first reload
was starved behind it.

Three fixes, measured on a 1756-transaction mainnet wallet:

- Memoize a restore that found no account at all, keyed to the persisted
  transaction count so a restored seed syncing its history in still gets a
  real scan. Launch restores: 2 -> 1.
- Give `getApiAddressConfirmationTx()` the same `januaryFirst2022Epoch`
  floor `tryRestoreSignUp()` already uses — an API-address confirmation is
  CrowdNode protocol traffic and cannot predate CrowdNode. That scan was
  the restore's expensive half: 1728 rows -> 692.
- Do the wallet-scoping join in the store instead of in Swift. It fetched
  every walletId TXO, faulted `.transaction` and `.spendingTransaction` on
  each (~3440 faults), then fed the resulting txid set back through a
  `contains` predicate as wide as the wallet's history. `PersistentTxo.
  walletId` is indexed and `PersistentTransaction` has both inverses.

Main-thread block during launch: ~4s across two restores -> ~0.75s in one.

Also drops the `DispatchQueue.main.sync` read of `selectedFilters` from
inside the home reload pass. Pairing each request with the selection live
when it was made is tighter than reading it at pass start, which could
render a selection made after the pass began.

Co-Authored-By: Claude Opus 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3d7a48c5-1b92-4f54-948d-2d7f9058e92c

📥 Commits

Reviewing files that changed from the base of the PR and between d56e17d and 83014c8.

📒 Files selected for processing (3)
  • DashWallet/Sources/Models/CrowdNode/CrowdNode.swift
  • DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift
  • DashWallet/Sources/UI/Home/Views/HomeViewModel.swift
🚧 Files skipped from review as they are similar to previous changes (3)
  • DashWallet/Sources/Models/CrowdNode/CrowdNode.swift
  • DashWallet/Sources/UI/Home/Views/HomeViewModel.swift
  • DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift

📝 Walkthrough

Walkthrough

Transaction scanning now uses caller-owned contexts and targeted predicates. CrowdNode skips repeated fruitless restores until transaction data changes. Home transaction reloads capture state without blocking the main actor and use shared throttling for sync-triggered reloads.

Changes

Transaction processing

Layer / File(s) Summary
Background transaction scanning
DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift
Transaction observation uses short main-actor state reads, caller-owned contexts, wallet TXO predicates, direct persisted transaction counts, and timing logs.
CrowdNode restore and confirmation filtering
DashWallet/Sources/Models/CrowdNode/CrowdNode.swift
Fruitless restore scans are memoized by persisted transaction count. Reset and active-wallet changes clear the memo. Confirmation lookup applies the protocol start-date filter.
Asynchronous home reload scheduling
DashWallet/Sources/UI/Home/Views/HomeViewModel.swift
Reloads capture filters before queue dispatch, preserve existing processing and UI publication, log elapsed time, and use the throttled reload subject for debounced sync changes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: preventing repeated full transaction-history scans during CrowdNode restore.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/home-feed-main-thread-contention

Comment @coderabbitai help to get the list of available commands.

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

Actionable comments posted: 1

🧹 Nitpick comments (5)
DashWallet/Sources/Models/CrowdNode/CrowdNode.swift (1)

127-137: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the redundant nil initializer.

SwiftLint reports implicit_optional_initialization on fruitlessRestoreTxCount. Remove = nil.

As per coding guidelines, “Follow the applicable language conventions: … SwiftFormat/SwiftLint for Swift.”

Proposed refactor
-    private var fruitlessRestoreTxCount: Int? = nil
+    private var fruitlessRestoreTxCount: Int?
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@DashWallet/Sources/Models/CrowdNode/CrowdNode.swift` around lines 127 - 137,
Remove the redundant explicit nil initializer from the fruitlessRestoreTxCount
property declaration, leaving it as an implicitly initialized optional while
preserving its existing type and behavior.

Sources: Coding guidelines, Linters/SAST tools

DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift (1)

114-127: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Replace the three-member tuples with a private type.

SwiftLint reports large_tuple for both tuple declarations. Define a private HostHandles struct and use it for the closure result and resolved.

As per coding guidelines, “Follow the applicable language conventions: … SwiftFormat/SwiftLint for Swift.”

Proposed refactor
+    private struct HostHandles {
+        let container: ModelContainer
+        let walletId: Data
+        let network: Network
+    }
+
-        let handles = { `@MainActor` () -> (container: ModelContainer, walletId: Data, network: Network)? in
+        let handles = { `@MainActor` () -> HostHandles? in
             // ...
-            return (container, walletId, network)
+            return HostHandles(container: container, walletId: walletId, network: network)
         }
 
-        let resolved: (container: ModelContainer, walletId: Data, network: Network)?
+        let resolved: HostHandles?
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift`
around lines 114 - 127, Define a private HostHandles struct containing
container, walletId, and network, then update the handles closure and resolved
declaration to use HostHandles instead of three-member tuples. Preserve the
existing values and initialization behavior.

Sources: Coding guidelines, Linters/SAST tools

DashWallet/Sources/UI/Home/Views/HomeViewModel.swift (3)

751-756: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Route the .syncing transition through the same funnel.

This change is correct. The comment states that direct reload calls race the throttled triggers.

Line 369 in observeWallet still calls self.reloadTxsAndShortcuts() directly when the state transitions to .syncing. That call comes from the same syncModel.$state sink that schedules this debounced work item. A transition into .syncing therefore produces one unthrottled full pass plus this throttled request, which is the case the new comment describes.

Consider sending txReloadRequests at Line 369 as well.

♻️ Proposed change at Line 369
                     DWLogger.log("HomeViewModel: Sync started, reloading transactions")
-                    self.reloadTxsAndShortcuts()
+                    self.txReloadRequests.send()

Note that txReloadRequests drives reloadTxsAndShortcuts() at Line 299, so shortcut reloading is preserved.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@DashWallet/Sources/UI/Home/Views/HomeViewModel.swift` around lines 751 - 756,
Update the .syncing transition handling in observeWallet to send
txReloadRequests instead of calling reloadTxsAndShortcuts() directly. Preserve
the existing funnel through the txReloadRequests sink so syncing transitions use
the same throttled reload path and retain shortcut reloading.

519-526: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the force unwrap at Line 525.

Dictionary(grouping:by:) never yields an empty value array, so items.first! cannot trap today. SwiftLint still reports it, and a later edit to the grouping input would make it reachable. Bind the first element instead.

♻️ Proposed change
-        let array = groupedItems.map { key, items in
-            TransactionGroup(id: key, date: items.first!.date, items: items)
-        }.sorted { $0.date > $1.date }
+        let array = groupedItems.compactMap { key, items -> TransactionGroup? in
+            guard let first = items.first else { return nil }
+            return TransactionGroup(id: key, date: first.date, items: items)
+        }.sorted { $0.date > $1.date }

SwiftLint also reports cyclomatic complexity 15 for performReload at Line 404. Extracting the shielded and platform interleave blocks into helpers would clear that warning.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@DashWallet/Sources/UI/Home/Views/HomeViewModel.swift` around lines 519 - 526,
In the groupedItems-to-TransactionGroup mapping, replace the force unwrap on
items.first with safe binding and use the bound first item’s date to construct
the group. Also reduce performReload’s cyclomatic complexity by extracting the
shielded and platform interleave logic into focused helper methods while
preserving existing behavior.

Source: Linters/SAST tools


404-407: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Remove the ineffective isReloading guard.

queue is serial, so onTransactionStatusChanged cannot observe isReloading == true. The queue already serializes these mutations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@DashWallet/Sources/UI/Home/Views/HomeViewModel.swift` around lines 404 - 407,
Remove the isReloading assignment and related guard logic from performReload and
onTransactionStatusChanged, relying on the serial queue to synchronize
transaction mutations. Preserve the existing reload and incremental-update
behavior without the ineffective flag.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@DashWallet/Sources/Models/CrowdNode/CrowdNode.swift`:
- Around line 210-215: Update the restore flow around fruitlessRestoreTxCount
and the post-scan transaction count: capture
TransactionObserver.persistedTransactionCount() before tryRestoreSignUp() and
getOnlineAccountAddress() begin, use that captured value for the early
comparison, and store the same value after the scans. Do not recalculate the
count after scanning.

---

Nitpick comments:
In `@DashWallet/Sources/Models/CrowdNode/CrowdNode.swift`:
- Around line 127-137: Remove the redundant explicit nil initializer from the
fruitlessRestoreTxCount property declaration, leaving it as an implicitly
initialized optional while preserving its existing type and behavior.

In `@DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift`:
- Around line 114-127: Define a private HostHandles struct containing container,
walletId, and network, then update the handles closure and resolved declaration
to use HostHandles instead of three-member tuples. Preserve the existing values
and initialization behavior.

In `@DashWallet/Sources/UI/Home/Views/HomeViewModel.swift`:
- Around line 751-756: Update the .syncing transition handling in observeWallet
to send txReloadRequests instead of calling reloadTxsAndShortcuts() directly.
Preserve the existing funnel through the txReloadRequests sink so syncing
transitions use the same throttled reload path and retain shortcut reloading.
- Around line 519-526: In the groupedItems-to-TransactionGroup mapping, replace
the force unwrap on items.first with safe binding and use the bound first item’s
date to construct the group. Also reduce performReload’s cyclomatic complexity
by extracting the shielded and platform interleave logic into focused helper
methods while preserving existing behavior.
- Around line 404-407: Remove the isReloading assignment and related guard logic
from performReload and onTransactionStatusChanged, relying on the serial queue
to synchronize transaction mutations. Preserve the existing reload and
incremental-update behavior without the ineffective flag.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1f283972-c87f-4657-aa5b-d562c6cd28df

📥 Commits

Reviewing files that changed from the base of the PR and between 852f8f3 and d56e17d.

📒 Files selected for processing (3)
  • DashWallet/Sources/Models/CrowdNode/CrowdNode.swift
  • DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift
  • DashWallet/Sources/UI/Home/Views/HomeViewModel.swift

Review catch: the count was read AFTER `tryRestoreSignUp()` and
`getOnlineAccountAddress()` returned, so a save landing mid-restore was
recorded as scanned. The next call would then compare equal and skip,
leaving those rows never inspected. Read it once up front and memoize
that same value.

Also from review: drop the redundant `= nil`
(`implicit_optional_initialization`), replace the three-member tuples with
a private `HostHandles` struct (`large_tuple`), and bind `items.first`
instead of force-unwrapping it when building `TransactionGroup`.

Co-Authored-By: Claude Opus 5 <[email protected]>
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.

1 participant