Repository navigation
fix(syncing): stop shielded sync off the main thread on every path - #1171
Conversation
`performStop` is async and calls `manager.stopShieldedSync()`. Once the SDK adds an async `stopShieldedSync()` overload (dashpay/platform#5201), overload resolution in this async context prefers it, and the call no longer compiles without `await`. The app builds from an unpinned `../platform`, so that SDK merge would break `develop`. The call now goes through an explicit non-async function type, the idiom `SwiftDashSDKHost` already uses for `createWallet`, so it keeps the blocking overload with either SDK. No behavior change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`PlatformAddressSyncCoordinator.performStop` stopped the shielded sync loop with the SDK's blocking `stopShieldedSync()`, which waits on the main actor for up to 10 s for a pass in flight. #1168 skipped that stop on runtime resets only. There the loop kept running until the host teardown, so a new pass could start, and its trailing events were not filtered. The wipe, the Sync Info Stop and the performStart re-stop still froze the UI. performStop now starts the SDK's async stop (dashpay/platform#5201) and does not wait for it, so the teardown still runs in one main-actor turn. The async stop cancels the loop at once, drops the stopping loop's events, and drains a pass in flight off the main thread. The stop is tracked, and awaitPendingShieldedStop() waits for it: - the runtime's fullReset, after the SPV stop (the two drain side by side) and before the host teardown; - performStart and the shielded recovery, before starting the loop again; - the wiper, before the live manager's synchronous deleteWallet, which the SDK refuses beside an admitted async operation. The stop's result and duration go to DWLogger. stopBeforeHostShutdownAsync and the stoppingShieldedSync flag from #1168 are gone; fullReset calls stopAsync(preservingRecovery:) again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (3)
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe coordinator now starts shielded-sync stops asynchronously and tracks pending work. Startup, recovery, full resets, and wallet-deletion paths wait for pending stops where needed. ChangesShielded-sync shutdown
Priority: ⬇️ Low Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Bug fix Suggested reviewers: Merge Risk: ⚪ Minimal · up to The change moves shielded-sync stopping off the main thread and adds lifecycle waits. No concrete new merge-blocking failure was established; existing timeout-related restart and deletion limitations remain. Mergeable subject to normal checks. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The change improves shutdown ordering without an identified expansion of wallet access or deletion permissions. Remaining uncertainty concerns whether the wallet library safely handles timed-out or overlapping stop requests before subsequent operations. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
🔍 Review in progress — actively reviewing now (commit b14ff97) · triage: normal |
Co-Authored-By: Claude Opus 5.5 <[email protected]> # Conflicts: # DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift
romchornyi
left a comment
There was a problem hiding this comment.
Reviewed at b14ff970e (SDK side reviewed separately in dashpay/platform#5202). No blockers — approving. One major item is inline (a one-line fix, worth doing before merge but not blocking). The rest are non-blocking recommendations.
1. Worst-case teardown after a timed-out stop is now ~10 s longer than with #1168. When the pass outlives the drain budget, fullReset waits for the async stop (shutdownIncomplete after ~10 s), then SwiftDashSDKHost.stopAsync → manager.shutdown() quiesces the same pass for another ~10 s — your own table shows 10026 ms + 10.0 s + 9.3 s destroy on testnet → mainnet. It's all off-main, and the second wait does give the still-running pass time to finish before destroy, so it's not wasted — but for BackgroundRefreshCoordinator.stopAndAwaitTeardown ~30 s is right at the background-task budget. Worth a note in the description / a follow-up; the real fix is dashpay/platform#5200.
2. A timed-out stop's result isn't acted on. stopShieldedSync(on:) only logs it. After shutdownIncomplete, performStart / prepareShieldedForRecovery restart the loop on the same manager, set isShieldedRunning = true and recordSyncStarted(), but every pass bails on the latched quiesce gate, so the UI shows a running shielded sync that never updates. You list the latched gate as a pre-existing Rust issue; until that lands, the app could keep the result and force a host rebuild (or refuse to report "running") instead.
3. performStart reads lifecycleGeneration after the new wait. lifecycleGeneration &+= 1; let generation = lifecycleGeneration now comes after up to ~10 s of awaitPendingShieldedStop(), so a prepareForNetworkSwitch / performStop in that window isn't caught by a generation guard; the start runs preflightDevnetStartIfNeeded and SwiftDashSDKHost.shared.start(network:) for the old network before isSelectedWalletScope rejects it. Capturing the generation (or re-checking it) around the wait would close it.
4. Wiper ordering. awaitPendingShieldedStop() runs after deletionBackend(for:), which can build a temporary manager (a registry insert, i.e. the write lock) while the in-flight stop holds the registry's read guard for its whole drain. I didn't confirm whether that lock is writer-preferring, so this may be harmless — but moving the wait in front of deletionBackend(for:) (both at ~615 and ~843) costs nothing and removes the question.
5. The stop now starts on every performStop. Dropping the isShieldedSyncRunning() check is justified (a direct syncShieldedNow() pass isn't seen by it), but it means that after Sync Info Stop the live manager has an admitted async op for the stop's duration: syncShieldedNow() from ShieldedIdentityFundingReadiness.requestFreshSignals() / refreshShieldedBalanceAfterSpend throws walletOperation (swallowed or only logged), and synchronous create/load/delete throw invalidHandle. Usually milliseconds (your 5–6 ms), up to 10 s with a pass in flight.
6. Reuse. awaitPendingShieldedStop repeats the slot-drain loop of cancelAndAwaitIdentityRecovery almost line for line, and the finished stop Task stays in pendingShieldedStop until someone awaits it. A small shared helper (and letting the stop task clear its own slot) would keep the two from drifting.
🤖 Generated with Claude Code
|
|
||
| private func prepareShieldedForRecovery() async throws { | ||
| // The SDK refuses `startShieldedSync` while a stop is in flight. | ||
| await awaitPendingShieldedStop() |
There was a problem hiding this comment.
Major (not blocking the merge): this await can last up to ~10 s, and nothing after it re-checks cancellation before shieldedRecovery.generation is read at the walletManager == nil branch below.
If the app goes to the background during the wait, ShieldedRecoveryController.foregroundChanged(false) bumps the generation and cancels the operation, but isActive stays true and isSuspended stays false. So the generation read after the wait is already the new one, isCurrentSession(generation) passes, and rearmPlatformSync enqueues refresh(.platformSyncRearm) — Platform sync starts in the background from a recovery that was cancelled. Before this PR there was no suspension between the operation starting and that read.
One-line fix: try Task.checkCancellation() right after this await (or capture the generation before it).
There was a problem hiding this comment.
Fixed in 7d02865: try Task.checkCancellation() right after the wait. All three generation bumps in ShieldedRecoveryController (foregroundChanged(isForeground: false), suspendForRuntimeRestart(), stop()) go through cancelTasks(), which cancels this operation, so the check covers each of them.
Review follow-ups for the wait on a pending shielded stop, which can last up to 10 s: - prepareShieldedForRecovery checks cancellation after the wait. Leaving the foreground bumps the recovery generation and cancels the operation, so the generation read after the wait was already the new one, and a cancelled recovery could rearm Platform sync in the background. - performStart takes its lifecycle generation before the wait and re-checks it after, so a network switch or stop during the wait supersedes the start before it reaches host.start for the old network. - deletionBackend awaits the pending stop before building a manager. The stop keeps the SDK's manager registry read-locked for its whole drain, and a temporary manager's configure() registers there synchronously on the main actor, so a wipe could block the UI until the drain ended. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, Roman. Follow-ups are in 7d02865, and the description is updated.
The follow-ups are build-verified only. Backgrounding during the wait, a switch during the wait and a wipe with a stop in flight weren't exercised in the simulator. |
Issue being fixed or feature implemented
Needs the SDK's async
stopShieldedSync()from dashpay/platform#5202, merged intov4.2-devas4d3c193abc. #1170, which pinned the blocking call until now, is merged too.PlatformAddressSyncCoordinator.performStopstopped the shielded sync loop with the SDK's blockingstopShieldedSync(). That call waits on the main actor for up to 10 s for a pass in flight.#1168 skipped that stop on runtime resets and left the loop to the host teardown. Roman's review of #1168 found two problems with that:
PaymentsLandingViewModelandShieldedIdentityFundingReadiness.The other paths (wipe, the Sync Info Stop, the re-stop in
performStart) still froze the UI.What was done?
performStopstarts the SDK's async stop and does not wait for it, so the teardown still runs in one main-actor turn. The async stop:It starts whenever a manager exists: a direct
syncShieldedNow()pass runs outside the loop, whereisShieldedSyncRunning()misses it.The stop is tracked (
pendingShieldedStop, the same pattern asidentityRecoveryTask), andawaitPendingShieldedStop()waits for it. Callers that wait:SwiftDashSDKWalletRuntime.fullReset, after the SPV stop (the two drain side by side) and before the host teardown;performStartand the shielded recovery, before starting the loop again, because the SDK refusesstartShieldedSyncwhile a stop is in flight.performStarttakes its lifecycle generation before the wait and re-checks it after, so a network switch or stop during the wait supersedes the start. The recovery checks for cancellation after the wait, because leaving the foreground bumps its generation;deletionBackend(for:)). The stop keeps the SDK's manager registry read-locked for its whole drain, and a temporary manager'sconfigureregisters there synchronously on the main actor;deleteWallet, which the SDK refuses beside an admitted async operation. Nothing suspends between that wait and the deletions.The stop's result and duration go to DWLogger (
🛡️ SHIELD stop result=… in …ms). The host's shutdown line no longer includes this wait.stopBeforeHostShutdownAsyncand thestoppingShieldedSyncflag from fix(syncing): let the host teardown stop shielded sync off the main thread #1168 are gone, andfullResetcallsstopAsync(preservingRecovery:)again. The pin from refactor(syncing): pin the blocking shielded stop in performStop #1170 is replaced by the async call.Not changed here:
fullResetwaits about 10 s for the stop to returnshutdownIncomplete, thenmanager.shutdown()quiesces the same pass for up to another 10 s beforedestroy(the testnet → mainnet column below). All of it is off the main thread, and the second wait gives the pass time to finish beforedestroy.BackgroundRefreshCoordinatorruns the same teardown (stopAndAwaitTeardown) inside its background task, so this eats into that task's time budget. The fix is platform-wallet: shielded sync stop and manager destroy wait for a whole in-flight pass platform#5200.deleteWalletneeds that lock throughunregister_wallet. The fix is an off-maindeleteWalletin the SDK.start()does not reopen it. This is pre-existing and needs a Rust fix. Until then the app reports shielded sync as running (isShieldedRunning,recordSyncStarted()) while no pass does any work.How Has This Been Tested?
dashpayscheme simulator builds (arm64):7d0286566(review follow-ups) andb14ff970e, both against the final fix(swift-sdk): stop shielded sync off the main thread platform#5202 head4c317120c4, whose Swift SDK sources matchv4.2-devat4d3c193abc.scripts/a11y_audit.py --check: no new findings.The review follow-ups in
7d0286566are build-verified only. Backgrounding during the wait, a switch during the wait and a wipe with a stop in flight were not exercised in the simulator.The SDK side is unit-tested in fix(swift-sdk): stop shielded sync off the main thread platform#5202.
Simulator smoke test of
952fab946with the SDK at959ac35dab, fix(swift-sdk): stop shielded sync off the main thread platform#5202 before its review fixes. Those fixes change which shielded events a stop drops or holds, and refuse manual syncs while it runs; they do not change the paths measured here. iPhone 17 simulator, iOS 26.5,dashpayDebug, nosampleattached.okin 1833 msshutdownIncompletein 10026 msshielded_sync_stop10.0 s (code 27),destroy9.3 sNETSWITCH … readyperformStopfirst waited for the background identity recovery (cancelAndAwaitIdentityRecovery, fix(dashpay): finish a network switch without waiting on the identity recovery #1149).Sync Info Stop, then Sync Now, twice:
okin 5–6 ms, and the rearm restarted Platform and shielded sync; a shielded pass completed right after.performStartwaits for the pending stop in that case, and the SDK's refusal is covered by its tests.Breaking Changes
None.
Checklist:
For repository code-owners and collaborators only
🤖 Generated with Claude Code
Summary by CodeRabbit