From cdb8c0db5d1cb0fbb722c09f0bfbcb66b418f394 Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Tue, 11 Aug 2026 00:33:13 +0300 Subject: [PATCH 1/2] perf(home): coalesce transaction-list reloads instead of queueing them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every reload trigger enqueued its own full pass on the view model's serial queue. A pass costs seconds once the wallet has a few thousand transactions, while the trigger throttle upstream is one second, so during a restore the queue took work faster than it finished it and the backlog grew for as long as the sync wrote rows. Measured on a mainnet restore of a ~6.6k-transaction wallet: 221 passes, 6252s of queued work inside a 17-minute session, and a request-to-render latency that climbed 6s -> 33s -> 122s -> 219s while the transaction count moved only 1537 -> 1854. The home list was rendering history up to three and a half minutes stale, and roughly seven of every eight passes rebuilt a snapshot the next one had already superseded. Gate on a running pass instead: at most one runs, at most one trailing pass is owed, and every trigger in between collapses into that trailing pass. Nothing is lost because the trailing pass reads the store fresh — including the filter selection, so a filter change during a pass still renders the newest selection. --- .../Sources/UI/Home/Views/HomeViewModel.swift | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift index c8935b28d1..b3dde0074b 100644 --- a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift +++ b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift @@ -65,6 +65,16 @@ class HomeViewModel: ObservableObject { /// Tracks whether initial data load has completed (Fix #2) private var hasCompletedInitialLoad: Bool = false + /// A full reload is running on `queue`. Main-thread-owned: every read and + /// write happens inside `reloadTxDataSource`'s main-actor hop or the + /// completion hop at the end of `performReload`. + private var reloadInFlight = false + + /// A reload was requested while one was already running, so the running + /// pass's snapshot is already stale. Exactly one trailing pass is owed — + /// see `reloadTxDataSource`. + private var reloadRequestedWhileInFlight = false + /// Debounce timer for sync state changes to prevent excessive reloads (Fix #4) private var syncStateDebounceWorkItem: DispatchWorkItem? private let syncStateDebounceInterval: TimeInterval = 0.5 @@ -418,6 +428,21 @@ class HomeViewModel: ObservableObject { // once up front, asynchronously, keeps the pass free-running. let dispatch = { @MainActor [weak self] in guard let self else { return } + // Coalesce, never queue. A pass costs seconds once the wallet has + // a few thousand transactions, while the trigger throttle upstream + // is one second — so enqueueing per trigger let `queue` accumulate + // a backlog that grew for as long as the sync wrote rows, each + // queued pass rebuilding a snapshot the next one already + // superseded. (A restore of a large wallet reached ~3.5 minutes of + // queue latency: the list rendered history that old.) At most one + // pass runs and at most one trailing pass is owed; the trailing + // pass reads the store fresh, so dropping the requests in between + // loses nothing. + guard !self.reloadInFlight else { + self.reloadRequestedWhileInFlight = true + return + } + self.reloadInFlight = true // Pair each request with the filter selection that was live when // it was made. Reading it inside the pass instead would let a pass // triggered by one change render a selection the user made after @@ -591,6 +616,16 @@ class HomeViewModel: ObservableObject { if self.hasMasternodeHistory != hasMasternodes { self.hasMasternodeHistory = hasMasternodes } + + // Release the coalescing gate only after this pass's results are + // on screen, then settle whatever changed while it ran. Ordering + // matters: clearing the request flag before re-entering keeps a + // trigger that lands during the trailing pass from being swallowed. + self.reloadInFlight = false + if self.reloadRequestedWhileInFlight { + self.reloadRequestedWhileInFlight = false + self.reloadTxDataSource() + } } } From cd7abaa079a321f5ba056e70a301d5e0ae16d02b Mon Sep 17 00:00:00 2001 From: Roman <51091564+jeanpierreroma@users.noreply.github.com> Date: Tue, 11 Aug 2026 00:33:27 +0300 Subject: [PATCH 2/2] perf(crowdnode): read the restore pass's history once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A restore pass scans the persisted history twice with identical arguments — tryRestoreSignUp, then getApiAddressConfirmationTx. Both walk the same rows to answer questions about the same wallet, and each walk is a SwiftData fetch across the TXO join plus a full decode, paid inline on the calling thread. On a mainnet wallet with ~6.6k transactions each walk took ~12.4s (8.1s fetch, 4.3s decode), so one pass spent ~25s scanning, and the passes repeat whenever the persisted row count moves — which, during a restore, is constantly: 20:37:12 restoring CrowdNode state 20:37:24 CrowdNode scan: fetch 6183 rows in 8536ms, decode in 4286ms 20:37:37 CrowdNode scan: fetch 6183 rows in 8114ms, decode in 4289ms 20:37:37 CrowdNode: account not found withSharedScan serves identical fetchObserved calls made inside it from one fetch and decode, keyed by wallet, network and the scan's arguments. It is deliberately scoped to the pass rather than cached across passes: a row's context and blockHeight change as it confirms without the row count moving, so a longer-lived memo would answer isChainAccepted from stale data. Also corrects the claim on the confirmation scan's floor. It bounds firstSeen, which the SDK stamps when it first observes a row, so on a restored wallet every row is "first seen" now and the floor admits the whole history regardless of chain date — recorded as a TODO rather than fixed here, since bounding on blockTimestamp needs a SwiftData predicate change that has to be verified against the store. --- .../Sources/Models/CrowdNode/CrowdNode.swift | 23 +++++-- .../Services/TransactionObserver.swift | 66 ++++++++++++++++++- 2 files changed, 83 insertions(+), 6 deletions(-) diff --git a/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift b/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift index b340720e22..efe02bb8dc 100644 --- a/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift +++ b/DashWallet/Sources/Models/CrowdNode/CrowdNode.swift @@ -200,8 +200,16 @@ public final class CrowdNode { // MARK: Restoring state extension CrowdNode { func restoreState() { + // The pass scans the persisted history twice with identical arguments + // (`tryRestoreSignUp`, then `getApiAddressConfirmationTx`). On a wallet + // with thousands of transactions that is two full fetch+decode walks + // of the same rows, ~12s each on the calling thread — share one. + TransactionObserver.withSharedScan { performRestoreState() } + } + + private func performRestoreState() { checkAPY() - + if signUpState > SignUpState.notStarted { // Already started/restored return @@ -1049,10 +1057,15 @@ extension CrowdNode { let filter = CoinsToAddressTxFilter(coins: CrowdNode.apiConfirmationDashAmount, address: nil) // account address is unknown at this point let forwardedConfirmationFilter = CrowdNodeAPIConfirmationTxForwarded() // Same floor the signup scan uses: an API-address confirmation is - // CrowdNode protocol traffic, so it cannot predate CrowdNode. Without - // it this walked and decoded the wallet's entire history on the main - // thread during restore — the more expensive of the restore's two - // scans, on a wallet that has no CrowdNode account at all. + // CrowdNode protocol traffic, so it cannot predate CrowdNode. + // + // TODO(crowdnode-restore-floor): the floor bounds `firstSeen`, which + // the SDK stamps from the device clock when it first observes a row — + // so on a restored wallet every row is "first seen" now and the floor + // admits the entire history regardless of its chain date. Bounding on + // `blockTimestamp` (falling back to `firstSeen` while unconfirmed) + // would restore the intent; it needs a SwiftData predicate change that + // has to be verified against the store rather than reasoned about. let observed = TransactionObserver.fetchObserved( firstSeenAtOrAfter: FullCrowdNodeSignUpTxSet.januaryFirst2022Epoch) diff --git a/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift b/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift index b12a4c2a89..79dbfe0d6f 100644 --- a/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift +++ b/DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift @@ -138,12 +138,76 @@ public final class TransactionObserver { resolved = DispatchQueue.main.sync { MainActor.assumeIsolated { handles() } } } guard let resolved else { return [] } - return scan( + let key = SharedScanKey( + walletId: resolved.walletId, + network: resolved.network, + fetchLimit: fetchLimit, + firstSeenAtOrAfter: firstSeenAtOrAfter) + if let shared = sharedScanResult(for: key) { return shared } + let rows = scan( container: resolved.container, walletId: resolved.walletId, network: resolved.network, fetchLimit: fetchLimit, firstSeenAtOrAfter: firstSeenAtOrAfter) + rememberSharedScan(rows, for: key) + return rows + } + + // MARK: Per-pass scan sharing + + /// Identity of one scan's result: the wallet and network it was read for, + /// plus the arguments that shaped the fetch. + private struct SharedScanKey: Hashable { + let walletId: Data + let network: Network + let fetchLimit: Int? + let firstSeenAtOrAfter: UInt64? + } + + private static let sharedScanLock = NSLock() + private static var sharedScanDepth = 0 + private static var sharedScanResults: [SharedScanKey: [ObservedTransaction]] = [:] + + /// Serves identical `fetchObserved` calls made inside `body` from a single + /// fetch + decode. + /// + /// A CrowdNode restore asks the same question twice — `tryRestoreSignUp` + /// and `getApiAddressConfirmationTx` scan with identical arguments — and + /// on a wallet with thousands of transactions each pass cost ~12s of fetch + /// and decode, paid inline by the caller's thread. + /// + /// Scoped to the call rather than cached across passes on purpose: a row's + /// `context` / `blockHeight` change as it confirms without the row count + /// moving, so a longer-lived memo would answer `isChainAccepted` from + /// stale data. + static func withSharedScan(_ body: () throws -> T) rethrows -> T { + sharedScanLock.lock() + sharedScanDepth += 1 + sharedScanLock.unlock() + defer { + sharedScanLock.lock() + sharedScanDepth -= 1 + if sharedScanDepth == 0 { + sharedScanResults.removeAll() + } + sharedScanLock.unlock() + } + return try body() + } + + private static func sharedScanResult(for key: SharedScanKey) -> [ObservedTransaction]? { + sharedScanLock.lock() + defer { sharedScanLock.unlock() } + guard sharedScanDepth > 0 else { return nil } + return sharedScanResults[key] + } + + private static func rememberSharedScan(_ rows: [ObservedTransaction], for key: SharedScanKey) { + sharedScanLock.lock() + defer { sharedScanLock.unlock() } + guard sharedScanDepth > 0 else { return } + sharedScanResults[key] = rows } /// Total persisted transaction count, or nil when the SDK host has no