Repository navigation
perf(crowdnode): stop rescanning full tx history on every restore - #931
Conversation
`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]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughTransaction 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. ChangesTransaction processing
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
DashWallet/Sources/Models/CrowdNode/CrowdNode.swift (1)
127-137: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the redundant
nilinitializer.SwiftLint reports
implicit_optional_initializationonfruitlessRestoreTxCount. 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 valueReplace the three-member tuples with a private type.
SwiftLint reports
large_tuplefor both tuple declarations. Define a privateHostHandlesstruct and use it for the closure result andresolved.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 winRoute the
.syncingtransition through the same funnel.This change is correct. The comment states that direct reload calls race the throttled triggers.
Line 369 in
observeWalletstill callsself.reloadTxsAndShortcuts()directly when the state transitions to.syncing. That call comes from the samesyncModel.$statesink that schedules this debounced work item. A transition into.syncingtherefore produces one unthrottled full pass plus this throttled request, which is the case the new comment describes.Consider sending
txReloadRequestsat Line 369 as well.♻️ Proposed change at Line 369
DWLogger.log("HomeViewModel: Sync started, reloading transactions") - self.reloadTxsAndShortcuts() + self.txReloadRequests.send()Note that
txReloadRequestsdrivesreloadTxsAndShortcuts()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 valueRemove the force unwrap at Line 525.
Dictionary(grouping:by:)never yields an empty value array, soitems.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
performReloadat 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 valueRemove the ineffective
isReloadingguard.
queueis serial, soonTransactionStatusChangedcannot observeisReloading == 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
📒 Files selected for processing (3)
DashWallet/Sources/Models/CrowdNode/CrowdNode.swiftDashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swiftDashWallet/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]>
Problem
The home feed's first transaction load was starved behind CrowdNode's restore.
CrowdNode.restoreState()guards only onsignUpState > .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. EveryrestoreState()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):
getApiAddressConfirmationTx()scanned unbounded whiletryRestoreSignUp()already floored atjanuaryFirst2022Epoch. An API-address confirmation is CrowdNode protocol traffic and cannot predate CrowdNode. This was the restore's expensive half: 1728 rows → 692.walletIdTXO, faulted.transactionand.spendingTransactionon each (~3440 faults), then fed the resulting txid set back through acontainspredicate as wide as the wallet's history.PersistentTxo.walletIdis indexed andPersistentTransactioncarries both inverses.Result
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.syncread ofselectedFiltersfrom inside the home reload pass (performReloadextraction 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'didSetcallsreloadTxDataSource()directly, so a filter tap arriving while a pass was queued would be dropped and silently do nothing. Removed rather than shipped.Testing
dashpayscheme builds cleanxcodebuildsaturating the CPU)🤖 Generated with Claude Code
Summary by CodeRabbit