Skip to content

fix(syncing): stop shielded sync off the main thread on every path - #1171

Merged
llbartekll merged 4 commits into
developfrom
fix/shielded-stop-off-main-all-paths
Sep 30, 2026
Merged

llbartekll merged 4 commits into
developfrom
fix/shielded-stop-off-main-all-paths

Conversation

@llbartekll

@llbartekll llbartekll commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

Needs the SDK's async stopShieldedSync() from dashpay/platform#5202, merged into v4.2-dev as 4d3c193abc. #1170, which pinned the blocking call until now, is merged too.

PlatformAddressSyncCoordinator.performStop stopped the shielded sync loop with the SDK's blocking stopShieldedSync(). 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:

  • the loop is not cancelled, so a new pass can start before the host teardown;
  • its trailing events still reach PaymentsLandingViewModel and ShieldedIdentityFundingReadiness.

The other paths (wipe, the Sync Info Stop, the re-stop in performStart) still froze the UI.

What was done?

  • performStop starts the SDK's async stop 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;
    • drains a pass in flight off the main thread.

    It starts whenever a manager exists: a direct syncShieldedNow() pass runs outside the loop, where isShieldedSyncRunning() misses it.

  • The stop is tracked (pendingShieldedStop, the same pattern as identityRecoveryTask), and awaitPendingShieldedStop() waits for it. Callers that wait:

    • SwiftDashSDKWalletRuntime.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, because the SDK refuses startShieldedSync while a stop is in flight. 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. The recovery checks for cancellation after the wait, because leaving the foreground bumps its generation;
    • the wiper, twice:
      • before building each network's deletion backend (deletionBackend(for:)). 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;
      • right before the live manager's synchronous 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.

  • stopBeforeHostShutdownAsync and the stoppingShieldedSync flag from fix(syncing): let the host teardown stop shielded sync off the main thread #1168 are gone, and fullReset calls stopAsync(preservingRecovery:) again. The pin from refactor(syncing): pin the blocking shielded stop in performStop #1170 is replaced by the async call.

Not changed here:

  • A timed-out stop makes the teardown wait twice. fullReset waits about 10 s for the stop to return shutdownIncomplete, then manager.shutdown() quiesces the same pass for up to another 10 s before destroy (the testnet → mainnet column below). All of it is off the main thread, and the second wait gives the pass time to finish before destroy. BackgroundRefreshCoordinator runs 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.
  • Deleting a wallet can still block the main thread behind a running pass. The shielded pass holds the store write lock for its whole note sync, network fetches included, and the SDK's synchronous deleteWallet needs that lock through unregister_wallet. The fix is an off-main deleteWallet in the SDK.
  • After a timed-out stop, restarting on the same manager gives a loop whose passes bail. The quiesce gate stays latched, and 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.
  • Starting the new network still stalls. See Network switch: main thread stalls up to 3.4 s while the new network starts #1169.

How Has This Been Tested?

  • dashpay scheme simulator builds (arm64): 7d0286566 (review follow-ups) and b14ff970e, both against the final fix(swift-sdk): stop shielded sync off the main thread platform#5202 head 4c317120c4, whose Swift SDK sources match v4.2-dev at 4d3c193abc. scripts/a11y_audit.py --check: no new findings.

  • The review follow-ups in 7d0286566 are 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 952fab946 with the SDK at 959ac35dab, 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, dashpay Debug, no sample attached.

    mainnet → testnet testnet → mainnet
    Main-thread stall after the tap none none
    Shielded stop, off main (DWLogger) ok in 1833 ms shutdownIncomplete in 10026 ms
    Host teardown, off main 11 ms 19.3 s: shielded_sync_stop 10.0 s (code 27), destroy 9.3 s
    NETSWITCH … ready 9.3 s 44.0 s
  • Sync Info Stop, then Sync Now, twice:

    • The shielded stop returned ok in 5–6 ms, and the rearm restarted Platform and shielded sync; a shielded pass completed right after.
    • No "stop in progress" error.
    • The stop had already returned when Sync Now ran, so a start overlapping a draining stop was not exercised. performStart waits for the pending stop in that case, and the SDK's refusal is covered by its tests.

Breaking Changes

None.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Wallet resets and deletions now wait for shielded synchronization to finish stopping before proceeding, helping prevent shutdown activity from overlapping with wallet state changes.
    • Shielded synchronization shutdown now proceeds asynchronously, while restarts wait for any pending shutdown to complete.

llbartekll and others added 2 commits September 29, 2026 17:56
`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]>
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 27b13467-495b-4a50-bda1-21523e3a35d0

📥 Commits

Reviewing files that changed from the base of the PR and between aa31025 and b14ff97.

📒 Files selected for processing (3)
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift
  • DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The 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.

Changes

Shielded-sync shutdown

Layer / File(s) Summary
Track and start shielded-sync stops
DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift
The coordinator chains asynchronous stop tasks. It starts a stop whenever a manager is available and removes the separate host-teardown stop entry point.
Wait before restarting shielded sync
DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift
Recovery and startup wait for pending stops before starting the shielded loop or continuing startup.
Wait before reset and wallet deletion
DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift, DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift
Full resets and wallet-deletion paths wait for pending shielded stops before clearing or deleting wallet state.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: jeanpierreroma

Merge Risk: ⚪ Minimal · up to b14ff

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 Review

Security architecture risk: 🔵 Low · up to b14ff

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The relevant exposure is wallet-manager lifetime and local wallet-state integrity on an installation. Full-wipe consumers already span stored mainnet, testnet, and applicable devnet material; the changed deletion code adds waiting without expanding that target inventory.

Trust Boundaries and Controls

  • observed — Coordinator teardown cancels shielded subscriptions before initiating stopping, then detaches balances and clears manager references. The host separately awaits manager.shutdown before clearing its owning references. These are application-side controls against stale observations and premature native-resource release, not proof of the SDK's post-timeout guarantees.

Resilience and Maintainability Implications

  • observed — Deletion failure remains contained: per-wallet application cleanup follows successful SDK deletion, logical deletion propagates failures and shuts down owned temporary managers, and a failed full wipe preserves global application state for retry rather than declaring success.

Hardening Proposals

  • proposed — Validate and document the SDK lifecycle contract for timeout, other stop errors, overlapping requests, deletion admission, and final shutdown. Explicitly distinguish request completion from quiescence when defining which result permits destructive operations.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: moving shielded-sync shutdown off the main thread across all relevant paths.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

❤️ Share

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

@thepastaclaw

thepastaclaw commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🔍 Review in progress — actively reviewing now (commit b14ff97) · triage: normal

@llbartekll
llbartekll changed the base branch from fix/pin-blocking-shielded-stop to develop September 30, 2026 08:46
Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift
@llbartekll
llbartekll marked this pull request as ready for review September 30, 2026 09:50

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

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()

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.

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).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
@llbartekll

Copy link
Copy Markdown
Collaborator Author

Thanks, Roman. Follow-ups are in 7d02865, and the description is updated.

  1. Double wait after a timed-out stop: agreed. It's now under Not changed here, with the background-task note; the fix is platform-wallet: shielded sync stop and manager destroy wait for a whole in-flight pass platform#5200.

  2. Timed-out result not acted on: agreed. It's the latched quiesce gate the description already lists (pre-existing; start() doesn't reopen it), and I added the symptom you describe there. I'd rather fix the gate in Rust than rebuild the host from the app in this PR.

  3. lifecycleGeneration after the wait: fixed. performStart takes the generation before the wait and re-checks it after, so a switch or stop during the wait supersedes the start before preflightDevnetStartIfNeeded / host.start.

  4. Wiper ordering: fixed, and it wasn't harmless.

    • with_item holds the registry's read guard across the whole block_on(quiesce()), and a temporary manager's configure() takes the write side (PLATFORM_WALLET_MANAGER_STORAGE.insert) synchronously on the main actor. A writer waits for a held reader whatever the policy.
    • On your question: parking_lot's RwLock is task-fair, so while that writer waits, new readers park too.
    • The wipe processes the live network last, so it built the other networks' temporary managers while the stop could still be draining.

    deletionBackend(for:) now awaits the pending stop first. The waits right before the synchronous deletions stay, because building a backend suspends.

  5. Refusals while the stop runs: acknowledged, no change. It's the SDK's admission rule for any async operation on the manager, the same one the async stopSpv() (fix(swift-sdk): stop SPV off the main thread platform#4994, used since fix(syncing): stop Core SPV off the main thread #1154) triggers. With no pass in flight, the stop took 5–6 ms in the smoke test.

  6. Shared helper: agreed on the drift risk. I kept it out of this PR so the diff stays on the stop.

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.

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