From c38748db7788fe15459df9f29221a16912338f88 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 11:19:44 +0200 Subject: [PATCH 1/8] feat(wallet): run Add Wallet's create FFI off-main and serialize it on the lifecycle queue Etap B of the Add Wallet freeze fix (a PARTIAL fix - see scope note below). Adopts the SDK's new async createWallet(mnemonic:) overload (platform feat/swift-sdk-async-create-wallet) so the blocking native create - both networks' key derivation + persistence flush, the bulk of the ~5s MainActor freeze - runs on the SDK's dedicated queue instead of the main thread. The overlay's spinner now animates through the create windows. - MnemonicFirstWalletCreation.run takes an async createWallet closure (single version - no sync/async pair); rollback-after-await semantics unchanged and now covered by a suspension-path test. - createAndPersist is async; its three call sites await it. The loadFromPersistor recovery path (recoverPersistedWallet) deliberately stays on the sync SDK overload. - SerialAsyncLifecycleQueue gains a value-returning enqueueAwaitable (same chain, full barrier semantics), and the runtime gains performAddWallet: the interactive add now runs as ONE link of the serial lifecycle chain, so a queued refresh/fullReset can no longer interleave with the multi-network provisioning. The post-add switch stays OUTSIDE the chain (sequential op - nesting would self-await- deadlock the queue). Onboarding's createOrImportWallet deliberately stays off the chain (its launch-time race-by-design is unchanged). - The 100ms overlay-commit sleep STAYS: on the mirror-repair path the first provisioning work is still the other network's synchronous SDK build on the MainActor with no suspension point before it. Scope note: the mirror-network leg's SDK(network:) + configure + loadFromPersistor (~1.6-2s) still blocks the MainActor under the visible overlay - known limitation, candidate for etap C after the new create telemetry (offMain + duration logs) is in. Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 31 +++-- .../SwiftDashSDKWalletRuntime.swift | 36 ++++++ .../Security/Wallets/WalletsViewModel.swift | 23 ++-- .../SwiftDashSDKCoreLifecycleTests.swift | 34 +++++ .../WalletWipeSerialExecutorTests.swift | 117 ++++++++++-------- 5 files changed, 172 insertions(+), 69 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index 1599adfbcc..36a22b86a5 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -68,8 +68,8 @@ enum MnemonicFirstWalletCreation { persistMnemonic: () throws -> Void, retrieveMnemonic: () throws -> String, rollbackMnemonic: () -> Void, - createWallet: () throws -> Wallet - ) throws -> Wallet { + createWallet: () async throws -> Wallet + ) async throws -> Wallet { do { try persistMnemonic() guard try retrieveMnemonic() == mnemonic else { @@ -84,7 +84,7 @@ enum MnemonicFirstWalletCreation { } do { - return try createWallet() + return try await createWallet() } catch { rollbackMnemonic() throw MnemonicFirstWalletCreationError.walletCreation(error) @@ -515,7 +515,7 @@ final class SwiftDashSDKHost { let handles = try await buildRuntime(for: network) let createdWallet: ManagedPlatformWallet do { - createdWallet = try createAndPersist( + createdWallet = try await createAndPersist( mnemonic: mnemonic, manager: handles.manager, network: handles.network, @@ -544,7 +544,7 @@ final class SwiftDashSDKHost { let (targetManager, isTemporary) = try await managerForStoredWalletOperation( network: targetNetwork) do { - _ = try createAndPersist( + _ = try await createAndPersist( mnemonic: mnemonic, manager: targetManager, network: targetNetwork, @@ -580,8 +580,10 @@ final class SwiftDashSDKHost { return createdWallet } - /// Outcome of `addWallet(mnemonic:isImported:)`. - enum AddWalletResult { + /// Outcome of `addWallet(mnemonic:isImported:)`. `Sendable` because it + /// crosses the lifecycle queue's awaitable seam + /// (`SwiftDashSDKWalletRuntime.performAddWallet`). + enum AddWalletResult: Sendable { /// The wallet was created and its mnemonic persisted; the running /// runtime is unchanged (the caller switches to it explicitly). case added(walletId: Data) @@ -635,6 +637,11 @@ final class SwiftDashSDKHost { /// Shares the persist-then-create transaction with /// `createOrImportWallet` (`createAndPersist`); differs only in that it /// uses the LIVE manager and does not publish or set-active. + /// + /// Interactive callers route through + /// `SwiftDashSDKWalletRuntime.performAddWallet`, which runs this method + /// as one link of the serial lifecycle chain so queued refresh/reset + /// operations cannot interleave with the multi-network provisioning. @discardableResult func addWallet(mnemonic: String, isImported: Bool) async throws -> AddWalletResult { let mnemonic = Mnemonic.normalizePhrase(mnemonic) @@ -670,7 +677,7 @@ final class SwiftDashSDKHost { network: targetNetwork) } do { - _ = try createAndPersist( + _ = try await createAndPersist( mnemonic: mnemonic, manager: targetManager, network: targetNetwork, @@ -713,7 +720,7 @@ final class SwiftDashSDKHost { manager: PlatformWalletManager, network: Network, birthHeight: UInt32? - ) throws -> ManagedPlatformWallet { + ) async throws -> ManagedPlatformWallet { let walletId: Data do { // This is the same deterministic id contract used by addWallet's @@ -736,7 +743,7 @@ final class SwiftDashSDKHost { } do { - return try MnemonicFirstWalletCreation.run( + return try await MnemonicFirstWalletCreation.run( mnemonic: mnemonic, persistMnemonic: { try storage.storeMnemonic(mnemonic, for: walletId) @@ -752,7 +759,9 @@ final class SwiftDashSDKHost { } }, createWallet: { - try manager.createWallet( + // Async SDK overload: the blocking native create runs on + // the SDK's dedicated queue, not the main thread. + try await manager.createWallet( mnemonic: mnemonic, network: network, name: "dashwallet", diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift index 5f94e50b73..43349fb73e 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletRuntime.swift @@ -37,6 +37,24 @@ final class SerialAsyncLifecycleQueue { currentTask = task return task } + + /// Value-returning variant: the operation is one link of the same serial + /// chain (full barrier semantics — everything enqueued later waits for + /// it), and its result or error is handed back to the caller through a + /// continuation. The chain itself stays `Task`. + func enqueueAwaitable( + _ operation: @escaping @MainActor () async throws -> T + ) async throws -> T { + try await withCheckedThrowingContinuation { continuation in + enqueue { + do { + continuation.resume(returning: try await operation()) + } catch { + continuation.resume(throwing: error) + } + } + } + } } @objc(DWSwiftDashSDKWalletRuntime) @@ -282,6 +300,24 @@ final class SwiftDashSDKWalletRuntime: NSObject { publishActiveWalletDidChange(reason: "wallet-switch") } + /// Additive wallet provisioning (`SwiftDashSDKHost.addWallet`) as ONE + /// link of the serial lifecycle chain, so a queued `refresh`/`fullReset` + /// can never interleave with the multi-network create. Like + /// `switchNetwork(to:)`, this MUST NOT be called from within a lifecycle + /// operation already running on the chain — it awaits its own enqueued + /// op and would self-await-deadlock the queue. The add flow's post-add + /// `switchWallet` is deliberately a SECOND, sequential chain op (the + /// caller awaits this method first), never nested inside it. + @MainActor + func performAddWallet(mnemonic: String, isImported: Bool) async throws + -> SwiftDashSDKHost.AddWalletResult { + try await lifecycleQueue.enqueueAwaitable { + try await SwiftDashSDKHost.shared.addWallet( + mnemonic: mnemonic, + isImported: isImported) + } + } + /// Validate that `walletId` is a switchable target on the current network: /// the network must be SDK-supported and a mnemonic for `walletId` must be /// persisted in `WalletStorage` — the same keychain surface the host loads diff --git a/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift b/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift index 3f604c5387..9ac0f30e42 100644 --- a/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift +++ b/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift @@ -265,10 +265,11 @@ final class WalletsViewModel: ObservableObject { addInProgress = true defer { addInProgress = false } - // Blocking overlay from the FIRST moment: provisioning is seconds of - // blocking MainActor work (wallet creation FFI on both networks, plus - // the other network's SDK build), and without this phase the app + // Blocking overlay from the FIRST moment: without this phase the app // looked frozen until the post-add switch finally raised the window. + // The create FFI itself now runs off-main (async SDK createWallet), + // but the mirror-network leg still blocks the MainActor for its + // SDK build + loadFromPersistor — TODO(etap-C). WalletLifecycleOverlayPresenter.shared.ensureActive() let state = WalletLifecycleTransitionState.shared guard state.tryBegin(.addingWallet(isImport: isImported)) else { @@ -276,9 +277,12 @@ final class WalletsViewModel: ObservableObject { return nil } // Give UIKit one runloop turn to commit the overlay window before the - // blocking provisioning starts (the Obj-C wipe's 0.1 s dispatch_after - // trick): the phase-apply Task was already enqueued by the sink, and - // both it and the CoreAnimation commit run while this sleeps. + // provisioning starts (the Obj-C wipe's 0.1 s dispatch_after trick). + // Still required even with the off-main create: on the mirror-repair + // path the FIRST provisioning work is the other network's synchronous + // SDK build on the MainActor, with no suspension point before it — + // without this sleep the window would not be committed until that + // block ends. Remove together with etap C. try? await Task.sleep(for: .milliseconds(100)) let opID = String(UUID().uuidString.prefix(8)) @@ -287,7 +291,12 @@ final class WalletsViewModel: ObservableObject { let result: SwiftDashSDKHost.AddWalletResult do { - result = try await SwiftDashSDKHost.shared.addWallet( + // Through the runtime's serial lifecycle chain: a queued + // refresh/fullReset can no longer interleave with the + // multi-network provisioning. The post-add switch below stays + // OUTSIDE the chain (its own sequential op — nesting it here + // would self-await-deadlock the queue). + result = try await SwiftDashSDKWalletRuntime.shared.performAddWallet( mnemonic: normalized, isImported: isImported) } catch { diff --git a/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift b/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift index 2233149827..397557021c 100644 --- a/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift +++ b/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift @@ -78,6 +78,40 @@ final class SwiftDashSDKCoreLifecycleTests: XCTestCase { ]) } + /// The value-returning variant is one link of the same serial chain: + /// its result comes back to the caller, its error propagates, and ops + /// enqueued around it stay strictly ordered. + func testEnqueueAwaitableReturnsValueThrowsAndKeepsChainOrder() async throws { + let queue = SerialAsyncLifecycleQueue() + var events: [String] = [] + + queue.enqueue { events.append("before") } + let value = try await queue.enqueueAwaitable { () async throws -> Int in + events.append("awaitable") + return 41 + } + queue.enqueue { events.append("after") } + + XCTAssertEqual(value, 41) + XCTAssertEqual(events, ["before", "awaitable"]) + + do { + _ = try await queue.enqueueAwaitable { () async throws -> Int in + events.append("throwing") + throw CoreLifecycleTestError.start + } + XCTFail("Expected the enqueued error to propagate") + } catch CoreLifecycleTestError.start { + // Expected — and the chain must survive a thrown link. + } + + _ = try await queue.enqueueAwaitable { () async throws -> Int in + events.append("tail") + return 0 + } + XCTAssertEqual(events, ["before", "awaitable", "after", "throwing", "tail"]) + } + func testProcessCacheReusesValuesPerNetworkAndSeparatesNetworks() { final class Token {} diff --git a/DashWalletTests/WalletWipeSerialExecutorTests.swift b/DashWalletTests/WalletWipeSerialExecutorTests.swift index 9210c6b7a1..d0f520afea 100644 --- a/DashWalletTests/WalletWipeSerialExecutorTests.swift +++ b/DashWalletTests/WalletWipeSerialExecutorTests.swift @@ -512,27 +512,29 @@ final class RecoveryPhraseRoutingTests: XCTestCase { } final class MnemonicFirstWalletCreationTests: XCTestCase { - func testPersistenceFailureDoesNotCreateWallet() { + func testPersistenceFailureDoesNotCreateWallet() async { var storedMnemonic: String? var createCalled = false - XCTAssertThrowsError(try MnemonicFirstWalletCreation.run( - mnemonic: "test mnemonic", - persistMnemonic: { - storedMnemonic = "partially written" - throw WalletLifecycleTestError.mnemonicPersistence - }, - retrieveMnemonic: { - storedMnemonic ?? "" - }, - rollbackMnemonic: { - storedMnemonic = nil - }, - createWallet: { - createCalled = true - return 1 - } - )) { error in + do { + _ = try await MnemonicFirstWalletCreation.run( + mnemonic: "test mnemonic", + persistMnemonic: { + storedMnemonic = "partially written" + throw WalletLifecycleTestError.mnemonicPersistence + }, + retrieveMnemonic: { + storedMnemonic ?? "" + }, + rollbackMnemonic: { + storedMnemonic = nil + }, + createWallet: { + createCalled = true + return 1 + }) + XCTFail("expected mnemonicPersistence") + } catch { guard case MnemonicFirstWalletCreationError.mnemonicPersistence = error else { return XCTFail("unexpected error: \(error)") } @@ -542,11 +544,11 @@ final class MnemonicFirstWalletCreationTests: XCTestCase { XCTAssertNil(storedMnemonic) } - func testMnemonicIsAvailableBeforeWalletCreation() throws { + func testMnemonicIsAvailableBeforeWalletCreation() async throws { let mnemonic = "test mnemonic" var storedMnemonic: String? - let wallet = try MnemonicFirstWalletCreation.run( + let wallet = try await MnemonicFirstWalletCreation.run( mnemonic: mnemonic, persistMnemonic: { storedMnemonic = mnemonic @@ -566,25 +568,27 @@ final class MnemonicFirstWalletCreationTests: XCTestCase { XCTAssertEqual(storedMnemonic, mnemonic) } - func testCreationFailureRemovesProvisionalMnemonicAndPropagatesError() { + func testCreationFailureRemovesProvisionalMnemonicAndPropagatesError() async { let mnemonic = "test mnemonic" var storedMnemonic: String? - XCTAssertThrowsError(try MnemonicFirstWalletCreation.run( - mnemonic: mnemonic, - persistMnemonic: { - storedMnemonic = mnemonic - }, - retrieveMnemonic: { - storedMnemonic ?? "" - }, - rollbackMnemonic: { - storedMnemonic = nil - }, - createWallet: { () throws -> Int in - throw WalletLifecycleTestError.walletCreation - } - )) { error in + do { + _ = try await MnemonicFirstWalletCreation.run( + mnemonic: mnemonic, + persistMnemonic: { + storedMnemonic = mnemonic + }, + retrieveMnemonic: { + storedMnemonic ?? "" + }, + rollbackMnemonic: { + storedMnemonic = nil + }, + createWallet: { () async throws -> Int in + throw WalletLifecycleTestError.walletCreation + }) + XCTFail("expected walletCreation") + } catch { guard case MnemonicFirstWalletCreationError.walletCreation = error else { return XCTFail("unexpected error: \(error)") } @@ -593,25 +597,36 @@ final class MnemonicFirstWalletCreationTests: XCTestCase { XCTAssertNil(storedMnemonic) } - func testCreationFailureRestoresPreviousMnemonic() { + /// The rollback must also run when the failure happens AFTER the async + /// create closure suspended (the off-main SDK create) — same transaction + /// semantics as the old synchronous closure. + func testCreationFailureAfterSuspensionRestoresPreviousMnemonic() async { let previousMnemonic = "previous mnemonic" let replacementMnemonic = "replacement mnemonic" var storedMnemonic: String? = previousMnemonic - XCTAssertThrowsError(try MnemonicFirstWalletCreation.run( - mnemonic: replacementMnemonic, - persistMnemonic: { - storedMnemonic = replacementMnemonic - }, - retrieveMnemonic: { - storedMnemonic ?? "" - }, - rollbackMnemonic: { - storedMnemonic = previousMnemonic - }, - createWallet: { () throws -> Int in - throw WalletLifecycleTestError.walletCreation - })) + do { + _ = try await MnemonicFirstWalletCreation.run( + mnemonic: replacementMnemonic, + persistMnemonic: { + storedMnemonic = replacementMnemonic + }, + retrieveMnemonic: { + storedMnemonic ?? "" + }, + rollbackMnemonic: { + storedMnemonic = previousMnemonic + }, + createWallet: { () async throws -> Int in + await Task.yield() + throw WalletLifecycleTestError.walletCreation + }) + XCTFail("expected walletCreation") + } catch { + guard case MnemonicFirstWalletCreationError.walletCreation = error else { + return XCTFail("unexpected error: \(error)") + } + } XCTAssertEqual(storedMnemonic, previousMnemonic) } From 77163700f4884b0f8da0f404fcdb38410338b47f Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 12:02:16 +0200 Subject: [PATCH 2/8] fix(wallet): keep onboarding's persist-then-create MainActor-atomic Review follow-up (P1): adopting the async SDK create everywhere put a REAL suspension point in the middle of createOrImportWallet's transaction - between the mnemonic persist and the wallet rows appearing. During that window the MainActor could run a concurrently scheduled startIfReady/refresh, which would see the mnemonic (hasSDKWallet) with no wallet rows yet, build a competing runtime, and the two flows could overwrite each other's publish or leak a manager to the deinit fallback teardown. The old sync FFI blocked the MainActor exactly there, so the ordering was NOT unchanged as previously claimed. createAndPersist gains offMainCreate: the interactive add keeps the async overload (safe - performAddWallet serializes it on the lifecycle queue, so refreshes queue behind it), while the onboarding/migration path (createOrImportWallet) forces the SYNC SDK overload via an explicitly typed non-async closure - no suspension between persist and create, restoring the atomic critical section. Onboarding cannot go on the lifecycle queue instead: refresh awaits the key migrator, and the migrator calls createOrImportWallet - enqueueing would self-deadlock. Onboarding therefore still blocks main for the create's duration (as before this PR); its off-main adoption needs its own serialization design and stays out of this etap. Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 62 +++++++++++++++---- 1 file changed, 50 insertions(+), 12 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index 36a22b86a5..dabf5b77a8 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -527,7 +527,10 @@ final class SwiftDashSDKHost { // the scan anchors at the tip. birthHeight: isImported ? Self.importedWalletBirthHeight(for: handles.network) - : nil) + : nil, + // Onboarding is not lifecycle-queue-serialized: keep the + // persist→create critical section MainActor-atomic. + offMainCreate: false) if provisionAcrossSupportedNetworks { let persistedWalletIds = Set(try WalletStorage().listWalletIdsWithMnemonic()) @@ -550,7 +553,8 @@ final class SwiftDashSDKHost { network: targetNetwork, birthHeight: isImported ? Self.importedWalletBirthHeight(for: targetNetwork) - : nil) + : nil, + offMainCreate: false) } catch { if isTemporary { await targetManager.shutdown() } throw error @@ -686,7 +690,11 @@ final class SwiftDashSDKHost { // wallets from that network's tip. birthHeight: isImported ? Self.importedWalletBirthHeight(for: targetNetwork) - : nil) + : nil, + // The interactive add runs as one lifecycle-queue op + // (`performAddWallet`), so refreshes cannot observe the + // suspension the off-main create introduces. + offMainCreate: true) } catch { if isTemporary { await targetManager.shutdown() } throw error @@ -715,11 +723,24 @@ final class SwiftDashSDKHost { /// unsynced headers the SDK falls back to the network's newest /// hardcoded checkpoint), `0` scans from genesis (imported mnemonic /// whose history predates this device). + /// `offMainCreate` picks the SDK create overload. `true` (interactive + /// add): the async overload — the blocking FFI leaves the MainActor, + /// but the transaction gains a REAL suspension point between the + /// mnemonic persist and the wallet rows appearing; safe only when the + /// caller is serialized against runtime refreshes (the add flow runs on + /// the lifecycle queue). `false` (onboarding/migration): the sync + /// overload — no suspension between persist and create, so a + /// concurrently scheduled `startIfReady`/refresh can never observe the + /// half-state (mnemonic present, no wallet rows) and build a competing + /// runtime; `createOrImportWallet` is NOT queue-serialized (the + /// migrator is awaited by refresh itself — enqueueing would deadlock), + /// so it must keep the MainActor-atomic critical section. private func createAndPersist( mnemonic: String, manager: PlatformWalletManager, network: Network, - birthHeight: UInt32? + birthHeight: UInt32?, + offMainCreate: Bool ) async throws -> ManagedPlatformWallet { let walletId: Data do { @@ -759,14 +780,31 @@ final class SwiftDashSDKHost { } }, createWallet: { - // Async SDK overload: the blocking native create runs on - // the SDK's dedicated queue, not the main thread. - try await manager.createWallet( - mnemonic: mnemonic, - network: network, - name: "dashwallet", - createDefaultAccounts: true, - birthHeight: birthHeight) + if offMainCreate { + // Async SDK overload: the blocking native create + // runs on the SDK's dedicated queue, not the main + // thread. + return try await manager.createWallet( + mnemonic: mnemonic, + network: network, + name: "dashwallet", + createDefaultAccounts: true, + birthHeight: birthHeight) + } + // Sync SDK overload, forced by the explicit non-async + // function type (an async context would otherwise + // prefer the async one): blocks the MainActor for the + // whole create, keeping persist→create atomic for the + // unserialized onboarding path. + let syncCreate: () throws -> ManagedPlatformWallet = { + try manager.createWallet( + mnemonic: mnemonic, + network: network, + name: "dashwallet", + createDefaultAccounts: true, + birthHeight: birthHeight) + } + return try syncCreate() }) } catch MnemonicFirstWalletCreationError.mnemonicRoundTripMismatch { Self.logger.error("🪺 HOST :: mnemonic persistence round-trip mismatch") From 3371f6c5b3f3d27cce783c7b710e67d974ff572a Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 14:44:23 +0200 Subject: [PATCH 3/8] feat(wallet): time stages 2-4 and mirror-prep in the runtime bootstrap telemetry Etap C groundwork: stage 1 (SDK init) has had a DWLogger timing since the network-switch fix, but stages 2 (ModelContainer), 3 (configure) and 4 (loadFromPersistor, both the detached-manager and launch paths) only had begin/end markers or nothing - so the ~3s main-thread gap in Add Wallet's mirror leg could not be attributed per stage. Each stage now logs its duration through DWLogger (rolling file -> Share application logs), plus a wall-clock total for the whole mirror preparation in addWallet. Deliberately NOT logged here: Thread.isMainThread after an await on this @MainActor type - it would always print true and prove nothing. The off-main flag appears only where it has evidential value (inside the build-queue block, added with the off-main SDK build commit). Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index dabf5b77a8..e28e336da5 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -677,8 +677,13 @@ final class SwiftDashSDKHost { targetManager = manager isTemporary = false } else { + // Wall-clock only (this line always runs on the MainActor); + // per-stage thread attribution lives in the stage 1-4 logs. + let prepStarted = CFAbsoluteTimeGetCurrent() (targetManager, isTemporary) = try await managerForStoredWalletOperation( network: targetNetwork) + let prepMs = Int((CFAbsoluteTimeGetCurrent() - prepStarted) * 1000) + DWLogger.log("HOST mirror-prep for \(targetNetwork.rawValue) total \(prepMs)ms") } do { _ = try await createAndPersist( @@ -930,11 +935,18 @@ final class SwiftDashSDKHost { let container: ModelContainer do { Self.logger.info("🪺 HOST :: stage 2/4 obtaining ModelContainer for \(network.rawValue, privacy: .public)") + // Timed for the same reason as stage 1: main-thread work whose + // real cost decides whether it ever needs to move off-main. The + // cached (reused) path should be ~0ms; only the first build of a + // network's container in the process pays the store-open cost. + let started = CFAbsoluteTimeGetCurrent() let cached = try modelContainerCache.value(for: network.networkName) { try buildModelContainer(for: network) } + let ms = Int((CFAbsoluteTimeGetCurrent() - started) * 1000) container = cached.value Self.logger.info("🪺 HOST :: stage 2/4 ModelContainer \(cached.reused ? "reused" : "created", privacy: .public) for \(network.rawValue, privacy: .public)") + DWLogger.log("HOST stage 2/4 ModelContainer \(cached.reused ? "reused" : "created") for \(network.rawValue) in \(ms)ms") } catch { Self.logger.error("🪺 HOST :: ModelContainer build failed: \(String(describing: error), privacy: .public)") throw HostError.modelContainerFailed(error) @@ -943,9 +955,11 @@ final class SwiftDashSDKHost { let newManager = PlatformWalletManager() do { Self.logger.info("🪺 HOST :: stage 3/4 configuring manager for \(network.rawValue, privacy: .public)") + let started = CFAbsoluteTimeGetCurrent() try newManager.configure(sdk: newSDK, modelContainer: container) + let ms = Int((CFAbsoluteTimeGetCurrent() - started) * 1000) Self.logger.info("🪺 HOST :: stage 3/4 manager configured for \(network.rawValue, privacy: .public)") - DWLogger.log("HOST stage 3/4 manager configured for \(network.rawValue)") + DWLogger.log("HOST stage 3/4 manager configured for \(network.rawValue) in \(ms)ms") } catch { Self.logger.error("🪺 HOST :: configure failed: \(String(describing: error), privacy: .public)") throw HostError.configureFailed(error) @@ -985,7 +999,13 @@ final class SwiftDashSDKHost { let handles = try makeRuntime(for: network) do { - _ = try handles.manager.loadFromPersistor() + // Stage 4 of the detached-manager bootstrap: cost scales with the + // number of persisted wallets on `network` (bulk FFI + per-wallet + // FFI + keychain unlock), all currently on the main thread. + let started = CFAbsoluteTimeGetCurrent() + let restored = try handles.manager.loadFromPersistor() + let ms = Int((CFAbsoluteTimeGetCurrent() - started) * 1000) + DWLogger.log("HOST stage 4/4 loadFromPersistor for \(network.rawValue) restored=\(restored.count) in \(ms)ms") } catch { // The detached manager is already fully configured; rethrowing // without an explicit shutdown would leave its native teardown to @@ -1002,7 +1022,10 @@ final class SwiftDashSDKHost { manager: PlatformWalletManager, network: Network ) throws -> ManagedPlatformWallet { + let loadStarted = CFAbsoluteTimeGetCurrent() let restored = try manager.loadFromPersistor() + let loadMs = Int((CFAbsoluteTimeGetCurrent() - loadStarted) * 1000) + DWLogger.log("HOST stage 4/4 loadFromPersistor for \(network.rawValue) restored=\(restored.count) in \(loadMs)ms") if let resolved = resolveActiveWallet(in: manager, network: network) { Self.logger.info("🪺 HOST :: reusing persisted wallet; restored=\(restored.count, privacy: .public)") // Off the load path. `PlatformWalletManager` is `@MainActor`, so From 6ae3252aa59a5f621634c33cbb18bd00f4c35e10 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 14:52:33 +0200 Subject: [PATCH 4/8] feat(debug): main-thread stall monitor behind DEBUG MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Single-ping-pong runloop watchdog: a dedicated thread posts ONE block to the main queue and parks on a semaphore; the measured round-trip is the stall duration. The next ping goes out only after the previous one was answered plus a 100ms pause, so at most one ping is ever pending and a single long stall produces exactly one log line after it resolves - never a burst of queued-up reports. Latencies >=250ms (the Instruments microhang floor) log '⏱️ MAINSTALL ~Xms' through DWLogger, landing in the same rolling file as the bootstrap stage timings so stalls can be attributed to a stage by timestamp. This is the measuring instrument for the etap-C acceptance gate (no single stall >=500ms during Add Wallet). DEBUG-only; started from didFinishLaunching. The threshold classifier is a pure function pinned by a unit test (compile-ready; the app test target remains broken repo-wide). Co-Authored-By: Claude Fable 5 --- DashWallet.xcodeproj/project.pbxproj | 6 ++ DashWallet/AppDelegate.m | 5 ++ .../MainThreadStallMonitor.swift | 83 +++++++++++++++++++ .../SwiftDashSDKCoreLifecycleTests.swift | 7 ++ 4 files changed, 101 insertions(+) create mode 100644 DashWallet/Sources/Infrastructure/MainThreadStallMonitor.swift diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index 33d002060e..d54ece2141 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -11,6 +11,7 @@ 026B0383557D0181E034B64E /* SDKIdentityProfileSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E62262597A8B22870184A36 /* SDKIdentityProfileSheet.swift */; }; 02EDCC7635BCD84768554D9C /* StorageModelListViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60A762BDA473947F1A7EF199 /* StorageModelListViews.swift */; }; 02EED2FC7EAC55B96ECEAAD6 /* DWLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 59C18FCF827D815007BAEF29 /* DWLogger.m */; }; + 02EED2FC7EAC55B96ECEAB01 /* MainThreadStallMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59C18FCF827D815007BAEB01 /* MainThreadStallMonitor.swift */; }; 0308E777B29CC6DE1DB30FDD /* PlatformSyncStatusScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A58BF094C42E410DD1A71B6 /* PlatformSyncStatusScreen.swift */; }; 06132521E7B4D21B4A1597E7 /* PlatformSendExecutor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44DCDC3A2B92601BB1E61FD9 /* PlatformSendExecutor.swift */; }; 06E16A070A3C48883BBDA137 /* BIP70InteractiveCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = D36BCF99A4D30077C9C9B0EB /* BIP70InteractiveCoordinator.swift */; }; @@ -665,6 +666,7 @@ 630227C0414D5C74BA95BB8F /* BIP70Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94606903417F75BE99D4B31C /* BIP70Error.swift */; }; 63869E343191C55BDBBEED72 /* SwiftDashSDKInsightClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A7BE8E4519203200CDFB460 /* SwiftDashSDKInsightClient.swift */; }; 66B50619EC898EEE8C8FE13E /* DWLogger.m in Sources */ = {isa = PBXBuildFile; fileRef = 59C18FCF827D815007BAEF29 /* DWLogger.m */; }; + 66B50619EC898EEE8C8FEB01 /* MainThreadStallMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59C18FCF827D815007BAEB01 /* MainThreadStallMonitor.swift */; }; 6715F4CB33E5F472FEC43B7E /* DWParsedPaymentURI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24DC91C11E382E22D1C17F05 /* DWParsedPaymentURI.swift */; }; 6C4AA7FD67FEE5A9E5CF9781 /* WalletsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76AB0835FF44EA88F36991E0 /* WalletsViewModel.swift */; }; 6D5D6EFD5F40D11B2FB6E8A1 /* PaymentsLandingScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = E735446F9E918618E97EDD38 /* PaymentsLandingScreen.swift */; }; @@ -2853,6 +2855,7 @@ 52B5469F5588395FA0668C4B /* SwapTransactionStatusHostingController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapTransactionStatusHostingController.swift; sourceTree = ""; }; 5822AAB9B5EA605FF82B009A /* BIP70PaymentOutputFactory.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BIP70PaymentOutputFactory.swift; sourceTree = ""; }; 59C18FCF827D815007BAEF29 /* DWLogger.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = DWLogger.m; sourceTree = ""; }; + 59C18FCF827D815007BAEB01 /* MainThreadStallMonitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = MainThreadStallMonitor.swift; sourceTree = ""; }; 59C9D64AB542D03FE3704D02 /* ShieldedWithdrawalStore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ShieldedWithdrawalStore.swift; sourceTree = ""; }; 5A1EC0FE2E29A10000000001 /* ShieldedActivityHistory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShieldedActivityHistory.swift; sourceTree = ""; }; 5A1EC0FE2E29A20000000011 /* PlatformAddressActivityStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlatformAddressActivityStore.swift; sourceTree = ""; }; @@ -6177,6 +6180,7 @@ B1700000B1700000B1700001 /* NetworkStatusService.swift */, 7E31813A79237F4E037063AA /* SwiftDashSDK */, 59C18FCF827D815007BAEF29 /* DWLogger.m */, + 59C18FCF827D815007BAEB01 /* MainThreadStallMonitor.swift */, E70A780D1543343311C16402 /* Authentication */, 7FA744C4A6023E26A3B5B860 /* DWLogger.h */, 0448A6769BCF20987BE9960C /* DiagnosticLogExporter.swift */, @@ -10304,6 +10308,7 @@ E5B6555D068FA44028784652 /* SwiftDashSDKWalletState.swift in Sources */, DABF195F497554C7CFE816CA /* WalletEnvironment.swift in Sources */, 02EED2FC7EAC55B96ECEAAD6 /* DWLogger.m in Sources */, + 02EED2FC7EAC55B96ECEAB01 /* MainThreadStallMonitor.swift in Sources */, 4B8A9492829B622FCDAF4F19 /* SecureTimeService.swift in Sources */, B56469D438692B0A0B771EA6 /* PinPromptView.swift in Sources */, A6AAB271A1ADA69C272DA1D4 /* PinPromptPresenter.swift in Sources */, @@ -11329,6 +11334,7 @@ BCBED608CAAABA10839A0ADE /* SwiftDashSDKWalletState.swift in Sources */, BB779AE4D9B43803EAF0CB6F /* WalletEnvironment.swift in Sources */, 66B50619EC898EEE8C8FE13E /* DWLogger.m in Sources */, + 66B50619EC898EEE8C8FEB01 /* MainThreadStallMonitor.swift in Sources */, 94CE86155CB8D4DBCB18F6F7 /* SecureTimeService.swift in Sources */, EB070F38F6A474B4A1A7489F /* PinPromptView.swift in Sources */, 3116F910F54D310002090CBB /* PinPromptPresenter.swift in Sources */, diff --git a/DashWallet/AppDelegate.m b/DashWallet/AppDelegate.m index b912345efc..151e20cd03 100644 --- a/DashWallet/AppDelegate.m +++ b/DashWallet/AppDelegate.m @@ -110,6 +110,11 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( } [DWLogger sharedInstance]; +#if DEBUG + // Etap-C diagnostic: logs main-runloop stalls >=250ms through DWLogger + // so hangs can be attributed to bootstrap stages by timestamp. + [DWMainThreadStallMonitor start]; +#endif /* DEBUG */ [FIRApp configure]; [ExploreDashObjcWrapper configure]; [CurrencyExchangerObjcWrapper startExchangeRateFetching]; diff --git a/DashWallet/Sources/Infrastructure/MainThreadStallMonitor.swift b/DashWallet/Sources/Infrastructure/MainThreadStallMonitor.swift new file mode 100644 index 0000000000..8ac5762a96 --- /dev/null +++ b/DashWallet/Sources/Infrastructure/MainThreadStallMonitor.swift @@ -0,0 +1,83 @@ +// +// Created by Dash Core Group. +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Foundation + +/// DEBUG-only main-runloop stall detector backing the wallet-lifecycle +/// performance work: it turns "the spinner froze" into a `DWLogger` line with +/// a duration, in the same rolling file the stage timings go to, so stalls +/// can be attributed to a bootstrap stage by timestamp. +/// +/// Design: a single ping-pong. The monitor thread posts ONE block to the main +/// queue and parks on a semaphore until the main thread runs it; the measured +/// round-trip IS the stall duration (a healthy runloop answers in +/// microseconds). The next ping is only posted after the previous one was +/// answered, plus a fixed pause — so at most one ping is ever pending, a +/// single long stall produces a single log line after it resolves (never a +/// burst of queued-up reports), and the log line can only underestimate a +/// stall by at most the inter-ping pause. +/// +/// Thresholds follow the Instruments/MetricKit hang convention: report from +/// 250 ms (microhang); the etap-C acceptance gate reads ≥500 ms as a hang. +@objc(DWMainThreadStallMonitor) +final class MainThreadStallMonitor: NSObject { + /// Latencies below this are a healthy runloop; from here up they are + /// logged. Matches the Instruments "microhang" floor. + static let reportThreshold: TimeInterval = 0.25 + /// Pause between an answered ping and the next one. Bounds both the + /// sampling overhead and the maximum underestimate of a stall. + static let interPingPause: TimeInterval = 0.1 + + /// Pure classification, unit-testable without threads: milliseconds to + /// report for a measured ping round-trip, or nil when the latency is + /// below the reporting threshold. + static func stallMilliseconds(forLatency latency: TimeInterval) -> Int? { + guard latency >= reportThreshold else { return nil } + return Int(latency * 1000) + } + + private static var started = false + + /// Idempotent; a no-op outside DEBUG builds. Called once from + /// `application(_:didFinishLaunchingWithOptions:)`. + @objc static func start() { + #if DEBUG + dispatchPrecondition(condition: .onQueue(.main)) + guard !started else { return } + started = true + + let thread = Thread { + while true { + let semaphore = DispatchSemaphore(value: 0) + let pinged = CFAbsoluteTimeGetCurrent() + DispatchQueue.main.async { + semaphore.signal() + } + semaphore.wait() + let latency = CFAbsoluteTimeGetCurrent() - pinged + if let ms = stallMilliseconds(forLatency: latency) { + DWLogger.log("⏱️ MAINSTALL ~\(ms)ms") + } + Thread.sleep(forTimeInterval: interPingPause) + } + } + thread.name = "org.dashfoundation.dash.main-stall-monitor" + thread.qualityOfService = .utility + thread.start() + #endif + } +} diff --git a/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift b/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift index 397557021c..36e8144eeb 100644 --- a/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift +++ b/DashWalletTests/SwiftDashSDKCoreLifecycleTests.swift @@ -112,6 +112,13 @@ final class SwiftDashSDKCoreLifecycleTests: XCTestCase { XCTAssertEqual(events, ["before", "awaitable", "after", "throwing", "tail"]) } + func testStallMonitorClassifiesLatenciesAroundTheMicrohangFloor() { + XCTAssertNil(MainThreadStallMonitor.stallMilliseconds(forLatency: 0.0001)) + XCTAssertNil(MainThreadStallMonitor.stallMilliseconds(forLatency: 0.249)) + XCTAssertEqual(MainThreadStallMonitor.stallMilliseconds(forLatency: 0.25), 250) + XCTAssertEqual(MainThreadStallMonitor.stallMilliseconds(forLatency: 1.512), 1512) + } + func testProcessCacheReusesValuesPerNetworkAndSeparatesNetworks() { final class Token {} From 0c14ce0ceb7b17013f1e1df2f45ba11ad2ab78d0 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 14:55:07 +0200 Subject: [PATCH 5/8] feat(wallet): build the SDK off the main thread in makeRuntime Stage 1 of every runtime bootstrap - SDK(network:), one blocking dash_sdk_create_trusted FFI that assembles the tokio runtime, TLS stack and DapiClient, ~1-2s measured - ran on the MainActor. It was the single largest known main-thread block left in Add Wallet's mirror leg, and the same cost sat on launch, network switch, onboarding and wipe. makeRuntime is now async: stage 1 runs on a dedicated GCD queue (buildSDKOffMain - a plain queue, never Task.detached, because the blocking FFI would park a cooperative-pool thread) and hands the instance back at the suspension point. Safe because SDK is @unchecked Sendable, its init touches nothing main-bound, and after the continuation resumes the instance is only used from the MainActor; a thrown init constructs no object, and SDK.deinit releases the native handle if a later bootstrap stage throws. Stages 2-4 (ModelContainer, configure, loadFromPersistor) deliberately stay on the MainActor - their newly added timings decide whether they ever follow. The stage-1 timing now logs offMain= from inside the queue block, where the flag is actual evidence of where the work ran. Both callers (buildRuntime, managerForStoredWalletOperation) already were async; bootstraps stay serialized by the lifecycle queue, and the suspension sits outside onboarding's persist-to-create atomic section. Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 62 +++++++++++++++---- 1 file changed, 51 insertions(+), 11 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index e28e336da5..afa610e986 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -899,14 +899,59 @@ final class SwiftDashSDKHost { await stopAsync() } - return try makeRuntime(for: network) + return try await makeRuntime(for: network) + } + + /// Dedicated queue parking the blocking SDK construction + /// (`dash_sdk_create_trusted`: tokio runtime + TLS + DapiClient build, + /// ~1-2s). A plain GCD queue, never `Task.detached` — the blocking FFI + /// would park a cooperative-pool thread. Serial on purpose: runtime + /// bootstraps are already serialized by the lifecycle queue, so + /// concurrency here would buy nothing. + private nonisolated static let sdkBuildQueue = DispatchQueue( + label: "org.dashfoundation.dash.sdk-build", + qos: .userInitiated) + + /// Build the `SDK` off the main thread and hand it back at the + /// suspension point. Safe because `SDK` is `@unchecked Sendable`, its + /// init touches nothing main-bound (one blocking FFI plus thread-safe + /// UserDefaults reads), and after the continuation resumes the instance + /// is only ever used from the MainActor. A thrown init constructs no + /// object; once built, `SDK.deinit` releases the native handle if a + /// later bootstrap stage throws. + private nonisolated static func buildSDKOffMain( + network: Network, + platformVersion: UInt32 + ) async throws -> SDK { + try await withCheckedThrowingContinuation { continuation in + sdkBuildQueue.async { + let started = CFAbsoluteTimeGetCurrent() + do { + let sdk = try SDK(network: network, platformVersion: platformVersion) + let ms = Int((CFAbsoluteTimeGetCurrent() - started) * 1000) + // Logged HERE, on the build queue, so offMain= is + // evidence of where the work actually ran — a log after + // the await would always print from the MainActor. + DWLogger.log("HOST stage 1/4 SDK created for \(network.rawValue) in \(ms)ms offMain=\(!Thread.isMainThread)") + continuation.resume(returning: sdk) + } catch { + continuation.resume(throwing: error) + } + } + } } /// Build a configured manager/container pair without replacing the /// published app runtime. Full-device wipe uses this for the inactive /// network so each network-scoped SwiftData store is deleted through a /// manager configured for that same network. - private func makeRuntime(for network: Network) throws -> RuntimeHandles { + /// + /// Async since etap C: stage 1 (SDK construction) runs on + /// [`sdkBuildQueue`] instead of blocking the MainActor; stages 2-4 + /// (ModelContainer, configure, and the caller's loadFromPersistor) + /// stay on the MainActor — their measured cost decides whether they + /// ever follow (see the stage timing logs). + private func makeRuntime(for network: Network) async throws -> RuntimeHandles { guard network != .regtest else { throw HostError.unsupportedNetwork(network) } @@ -917,16 +962,11 @@ final class SwiftDashSDKHost { let newSDK: SDK do { let platformVersion = Self.platformVersion(for: network) - // Timed because it is main-thread work: SDK creation prefetches - // quorums over the network (~1-2s observed). Known stage-1 - // limitation — the switch overlay covers it; the measurement is - // the data for deciding whether to move it off-main later. - let started = CFAbsoluteTimeGetCurrent() - newSDK = try SDK(network: network, platformVersion: platformVersion) - let ms = Int((CFAbsoluteTimeGetCurrent() - started) * 1000) + newSDK = try await Self.buildSDKOffMain( + network: network, + platformVersion: platformVersion) Self.logger.info( "🪺 HOST :: stage 1/4 SDK created for \(network.rawValue, privacy: .public), protocol \(platformVersion == 0 ? "auto-detect" : "pinned v\(platformVersion)", privacy: .public)") - DWLogger.log("HOST stage 1/4 SDK created for \(network.rawValue) in \(ms)ms") } catch { Self.logger.error("🪺 HOST :: SDK init failed: \(String(describing: error), privacy: .public)") throw HostError.sdkInitFailed(error) @@ -997,7 +1037,7 @@ final class SwiftDashSDKHost { return (manager, false) } - let handles = try makeRuntime(for: network) + let handles = try await makeRuntime(for: network) do { // Stage 4 of the detached-manager bootstrap: cost scales with the // number of persisted wallets on `network` (bulk FFI + per-wallet From 1d75953bdaa1cb44dd205950c3be63bf1366292e Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 15:09:41 +0200 Subject: [PATCH 6/8] chore(wallet): drop the 100ms overlay-commit sleep from addWallet Measured gate passed: with the off-main SDK build, every add path's first provisioning work after the cheap duplicate guard is an await into off-main work (the async create, or the mirror leg's off-main SDK build), so the overlay window commits during that suspension. The stall monitor shows no >=250ms gap between 'add begin' and the first suspension in any of the three smoke runs (fresh create, import, already-exists - the last completing in 161ms total with no stall). Co-Authored-By: Claude Fable 5 --- .../Security/Wallets/WalletsViewModel.swift | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift b/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift index 9ac0f30e42..44c076ab3a 100644 --- a/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift +++ b/DashWallet/Sources/UI/Menu/Security/Wallets/WalletsViewModel.swift @@ -267,23 +267,18 @@ final class WalletsViewModel: ObservableObject { // Blocking overlay from the FIRST moment: without this phase the app // looked frozen until the post-add switch finally raised the window. - // The create FFI itself now runs off-main (async SDK createWallet), - // but the mirror-network leg still blocks the MainActor for its - // SDK build + loadFromPersistor — TODO(etap-C). + // No paint-a-frame sleep needed anymore: on EVERY add path the first + // provisioning work after the cheap duplicate guard is an await into + // off-main work (the async create, or the mirror leg's off-main SDK + // build), so the overlay window commits during that suspension — + // confirmed by the stall monitor showing no >=250ms gap between the + // add beginning and its first suspension. WalletLifecycleOverlayPresenter.shared.ensureActive() let state = WalletLifecycleTransitionState.shared guard state.tryBegin(.addingWallet(isImport: isImported)) else { errorMessage = SwiftDashSDKWalletRuntime.SwitchError.switchInProgress.localizedDescription return nil } - // Give UIKit one runloop turn to commit the overlay window before the - // provisioning starts (the Obj-C wipe's 0.1 s dispatch_after trick). - // Still required even with the off-main create: on the mirror-repair - // path the FIRST provisioning work is the other network's synchronous - // SDK build on the MainActor, with no suspension point before it — - // without this sleep the window would not be committed until that - // block ends. Remove together with etap C. - try? await Task.sleep(for: .milliseconds(100)) let opID = String(UUID().uuidString.prefix(8)) let started = CFAbsoluteTimeGetCurrent() From 7da299b188e1d2f03786d882c74d5538ed217d33 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 15:23:34 +0200 Subject: [PATCH 7/8] feat(wallet): adopt the async off-main loadFromPersistor in the bootstrap Stage 4 was the measured culprit of the remaining Add Wallet stalls (~400ms per persisted wallet on the MainActor; 449-1436ms runloop stalls attributed by timestamp). Both bootstrap load sites now await the SDK's async overload (dashpay/platform: swift-sdk async loadFromPersistor), which runs the bulk restore and per-wallet lookups on the SDK's dedicated queue: - managerForStoredWalletOperation (the Add Wallet mirror leg / wipe) - verified: stage 4 in 406ms with NO runloop stall in the add window (previously a 449ms stall at the same wallet count); - loadPersistedWallet (launch/switch/refresh via start(), an async lifecycle-queue op) - kills the 834-1257ms stalls the switch path showed for the same restore. The SDK telemetry confirms the split: 'native load finished in 403ms offMain=true wallets=1' and 'load unlock loop finished in 2ms' - the marker-cached keychain unlock epilogue is negligible on the MainActor, so no further split of the load is warranted. recoverPersistedWallet (reinstall recovery, sync context) deliberately stays on the sync overload - same posture as in etap B. Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDK/SwiftDashSDKHost.swift | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index afa610e986..c7b2f4379e 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -456,7 +456,7 @@ final class SwiftDashSDKHost { let resolvedWallet: ManagedPlatformWallet Self.logger.info("🪺 HOST :: stage 4/4 restoring wallet for \(network.rawValue, privacy: .public)") do { - resolvedWallet = try loadPersistedWallet(manager: handles.manager, network: network) + resolvedWallet = try await loadPersistedWallet(manager: handles.manager, network: network) } catch HostError.walletNotFound { // Reinstall recovery (C6-C): the SwiftData store dies with the app // but WalletStorage mnemonics live in the keychain — rebuild the @@ -1040,10 +1040,12 @@ final class SwiftDashSDKHost { let handles = try await makeRuntime(for: network) do { // Stage 4 of the detached-manager bootstrap: cost scales with the - // number of persisted wallets on `network` (bulk FFI + per-wallet - // FFI + keychain unlock), all currently on the main thread. + // number of persisted wallets on `network` (~400ms per wallet + // measured). The async SDK overload runs the bulk restore and + // per-wallet lookups off-main; only the keychain-unlock epilogue + // remains on the MainActor (timed separately by the SDK). let started = CFAbsoluteTimeGetCurrent() - let restored = try handles.manager.loadFromPersistor() + let restored = try await handles.manager.loadFromPersistor() let ms = Int((CFAbsoluteTimeGetCurrent() - started) * 1000) DWLogger.log("HOST stage 4/4 loadFromPersistor for \(network.rawValue) restored=\(restored.count) in \(ms)ms") } catch { @@ -1058,12 +1060,17 @@ final class SwiftDashSDKHost { return (handles.manager, true) } + /// Async since etap C: the launch/switch/refresh bootstrap awaits the + /// SDK's off-main load (same overload the mirror leg uses), so the + /// ~400ms-per-wallet restore no longer stalls the MainActor. The + /// caller (`start`) is a lifecycle-queue op, so the added suspension + /// cannot interleave with other lifecycle operations. private func loadPersistedWallet( manager: PlatformWalletManager, network: Network - ) throws -> ManagedPlatformWallet { + ) async throws -> ManagedPlatformWallet { let loadStarted = CFAbsoluteTimeGetCurrent() - let restored = try manager.loadFromPersistor() + let restored = try await manager.loadFromPersistor() let loadMs = Int((CFAbsoluteTimeGetCurrent() - loadStarted) * 1000) DWLogger.log("HOST stage 4/4 loadFromPersistor for \(network.rawValue) restored=\(restored.count) in \(loadMs)ms") if let resolved = resolveActiveWallet(in: manager, network: network) { From 121bfbff6ea4c28fb4c15096555ca2d675cdfaa6 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Wed, 26 Aug 2026 18:56:01 +0200 Subject: [PATCH 8/8] chore(voting): await the now-async dpnsActiveContests platform v4.2-dev (post swift-sdk#4483 merge) made dpnsActiveContests async with no sync overload left, so the single call site breaks loudly (SE-0296). One-word adaptation; activeContests() was already async. Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDK/Voting/ContestedNamesService.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift index 0b47ecb8bd..9e13c5c356 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Voting/ContestedNamesService.swift @@ -80,7 +80,7 @@ final class ContestedNamesService { /// reported end time sort last. func activeContests() async throws -> [DPNSContest] { let sdk = try requireSDK() - let contests = try sdk.dpnsActiveContests(limit: Self.activeContestLimit) + let contests = try await sdk.dpnsActiveContests(limit: Self.activeContestLimit) if contests.count >= Int(Self.activeContestLimit) { Self.logger.warning(