From 268bc36f2257255ed1dbc174fcc528161619b1ea Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Mon, 26 Oct 2026 13:41:03 +0100 Subject: [PATCH 1/5] fix(swift-sdk): run the asset-lock catch-up on a large-stack thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `catchUpStuckAssetLocks` drives `asset_lock_manager_catch_up_blocking` from a detached task, i.e. on a cooperative-pool thread with a 512 KB stack. The `resume_asset_lock` future that call blocks on is large enough to overflow it: with a dev-profile FFI the app faults in the stack guard (EXC_BAD_ACCESS, "Could not determine thread index for stack guard region") on every launch that finds a Built/Broadcast asset lock, before the lock can be resumed. Run the blocking FFI call on a dedicated Thread with a 16 MB stack and wait for it; the task still parks for the duration as before. Reproduced on iOS Simulator with dashwallet-ios after killing the app mid Core → Shielded drain; with this change the lock is caught up and the resume completes. Co-Authored-By: Claude Fable 5.1 --- .../PlatformWalletManager.swift | 34 +++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index 5c86e8bce11..75e02347522 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -2558,6 +2558,26 @@ public class PlatformWalletManager: ObservableObject { /// `assetLockInputContested`; the terminal `assetLockInputConflict` is /// reserved with no emitter and is matched so it would surface intact /// if that ever changes. + private final class LargeStackResultBox: @unchecked Sendable { + var value: T? + } + + /// Runs `body` synchronously on a dedicated thread with a 16 MB stack and + /// returns its result. See the note in `runCatchUp`. + nonisolated private static func runOnLargeStack(_ body: @escaping @Sendable () -> T) -> T { + let box = LargeStackResultBox() + let done = DispatchSemaphore(value: 0) + let thread = Thread { + box.value = body() + done.signal() + } + thread.stackSize = 16 << 20 + thread.name = "swift-sdk.asset-lock-catch-up" + thread.start() + done.wait() + return box.value! + } + nonisolated private static func runCatchUp(assetLockManager: ManagedAssetLockManager, txid: Data, vout: UInt32) -> PlatformWalletError? { // Build the txid tuple inline so the Task body captures only // Sendable values. @@ -2573,10 +2593,18 @@ public class PlatformWalletManager: ObservableObject { // the production resume path uses. Wrapping the raw struct in // `PlatformWalletResult` frees the Rust-owned message when the // wrapper deinits — the raw struct must never be dropped bare. + // The detached task runs on Swift's cooperative pool, whose threads + // have a 512 KB stack. The `resume_asset_lock` future that + // `block_on` drives inside this call is large enough (a dev-profile + // build overflows it on the first frame) to fault in the stack guard + // at launch whenever a Built/Broadcast lock exists. Run the blocking + // call on a thread with a generous stack of its own. + let txidTupleCopy = txidTuple let result = PlatformWalletResult( - asset_lock_manager_catch_up_blocking( - assetLockManager.handle, &txidTuple, vout, 300 - ) + Self.runOnLargeStack { + var tuple = txidTupleCopy + return asset_lock_manager_catch_up_blocking(assetLockManager.handle, &tuple, vout, 300) + } ) // Timeouts and proof-wait failures (catch-up // `errorWalletOperation`) are expected during normal From 1cbcc32f8b58ff27878ddbbd4ce645716421621d Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Tue, 27 Oct 2026 11:02:28 +0100 Subject: [PATCH 2/5] fix(platform-wallet): poll the asset-lock resume FFIs on a big-stack thread `asset_lock_manager_catch_up_blocking` and `asset_lock_manager_resume` polled `resume_asset_lock` with a bare `runtime().block_on(...)` on the host's calling thread. Swift calls the catch-up from `Task.detached` at every launch, on a ~512 KB cooperative stack. A dev-profile build of the poll chain needs ~600 KB, so the app faulted in the stack guard on every launch that found a Built/Broadcast lock. A release build needs ~120 KB and is not affected today. Run both polls inside `run_on_big_stack_thread`, as the Sync Now entry points do since #4033; `block_on_worker` does not apply because the future borrows the manager and the outpoint. A failed thread spawn is returned as ErrorWalletOperation. Reverts the earlier swift-sdk workaround on this branch, which ran the catch-up on a large-stack Thread: the fix now lives in the FFI and covers every host. Co-Authored-By: Claude Opus 5.5 --- .../src/asset_lock/sync.rs | 47 +++++++++++++++++-- .../PlatformWalletManager.swift | 34 ++------------ 2 files changed, 45 insertions(+), 36 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs index 80b739f2435..f3ccb5bd365 100644 --- a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs +++ b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs @@ -2,7 +2,7 @@ use crate::error::*; use crate::handle::*; -use crate::runtime::runtime; +use crate::runtime::{run_on_big_stack_thread, runtime}; use crate::{check_ptr, unwrap_option_or_return, unwrap_result_or_return}; use platform_wallet::PlatformWalletError; use std::ffi::CString; @@ -200,9 +200,22 @@ pub unsafe extern "C" fn asset_lock_manager_resume( let timeout = resume_timeout(timeout_secs); let option = ASSET_LOCK_MANAGER_STORAGE.with_item(handle, |manager| { - runtime().block_on(manager.resume_asset_lock(&out_point, forwarded(timeout))) + // Big-stack polling, NOT bare `runtime().block_on`, for the same + // reason as `asset_lock_manager_catch_up_blocking` below. + run_on_big_stack_thread(|| { + runtime().block_on(manager.resume_asset_lock(&out_point, forwarded(timeout))) + }) }); - let result = unwrap_option_or_return!(option); + let spawned = unwrap_option_or_return!(option); + let result = match spawned { + Ok(result) => result, + Err(e) => { + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorWalletOperation, + format!("failed to spawn big-stack thread for asset-lock resume: {e}"), + ); + } + }; let (proof, path) = unwrap_result_or_return!(result); let bytes = unwrap_result_or_return!(dpp::bincode::encode_to_vec( &proof, @@ -275,9 +288,19 @@ pub unsafe extern "C" fn asset_lock_manager_catch_up_blocking( ); let option = ASSET_LOCK_MANAGER_STORAGE.with_item(handle, |manager| { - runtime().block_on(manager.resume_asset_lock(&out_point, forwarded(timeout))) + // Big-stack polling, NOT bare `runtime().block_on`: hosts call this + // from dispatch/concurrency threads with ~512 KB of stack, and an + // unoptimized build of the `resume_asset_lock` poll chain needs + // ~600 KB (a release build ~120 KB), a SIGBUS in the stack guard on + // every launch that finds a Built/Broadcast lock. Same remedy as the + // Sync Now entry points. `run_on_big_stack_thread` rather than + // `block_on_worker` because the future borrows `manager` and + // `out_point`, so it is not `'static`. + run_on_big_stack_thread(|| { + runtime().block_on(manager.resume_asset_lock(&out_point, forwarded(timeout))) + }) }); - let result = match option { + let spawned = match option { Some(r) => r, None => { tracing::warn!( @@ -290,6 +313,20 @@ pub unsafe extern "C" fn asset_lock_manager_catch_up_blocking( ); } }; + let result = match spawned { + Ok(result) => result, + Err(e) => { + tracing::warn!( + outpoint = %out_point, + error = %e, + "asset_lock_manager_catch_up_blocking: failed to spawn big-stack thread" + ); + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorWalletOperation, + format!("failed to spawn big-stack thread for asset-lock catch-up: {e}"), + ); + } + }; match result { Ok(_) => { tracing::info!( diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index 75e02347522..5c86e8bce11 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -2558,26 +2558,6 @@ public class PlatformWalletManager: ObservableObject { /// `assetLockInputContested`; the terminal `assetLockInputConflict` is /// reserved with no emitter and is matched so it would surface intact /// if that ever changes. - private final class LargeStackResultBox: @unchecked Sendable { - var value: T? - } - - /// Runs `body` synchronously on a dedicated thread with a 16 MB stack and - /// returns its result. See the note in `runCatchUp`. - nonisolated private static func runOnLargeStack(_ body: @escaping @Sendable () -> T) -> T { - let box = LargeStackResultBox() - let done = DispatchSemaphore(value: 0) - let thread = Thread { - box.value = body() - done.signal() - } - thread.stackSize = 16 << 20 - thread.name = "swift-sdk.asset-lock-catch-up" - thread.start() - done.wait() - return box.value! - } - nonisolated private static func runCatchUp(assetLockManager: ManagedAssetLockManager, txid: Data, vout: UInt32) -> PlatformWalletError? { // Build the txid tuple inline so the Task body captures only // Sendable values. @@ -2593,18 +2573,10 @@ public class PlatformWalletManager: ObservableObject { // the production resume path uses. Wrapping the raw struct in // `PlatformWalletResult` frees the Rust-owned message when the // wrapper deinits — the raw struct must never be dropped bare. - // The detached task runs on Swift's cooperative pool, whose threads - // have a 512 KB stack. The `resume_asset_lock` future that - // `block_on` drives inside this call is large enough (a dev-profile - // build overflows it on the first frame) to fault in the stack guard - // at launch whenever a Built/Broadcast lock exists. Run the blocking - // call on a thread with a generous stack of its own. - let txidTupleCopy = txidTuple let result = PlatformWalletResult( - Self.runOnLargeStack { - var tuple = txidTupleCopy - return asset_lock_manager_catch_up_blocking(assetLockManager.handle, &tuple, vout, 300) - } + asset_lock_manager_catch_up_blocking( + assetLockManager.handle, &txidTuple, vout, 300 + ) ) // Timeouts and proof-wait failures (catch-up // `errorWalletOperation`) are expected during normal From 7e477ca965b9c20b59d1f8e69c0c0b5e2a5e1208 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Tue, 27 Oct 2026 15:26:37 +0100 Subject: [PATCH 3/5] test(platform-wallet): carry timeout probe records back from the big-stack thread `forwarded(timeout)` now runs inside `run_on_big_stack_thread`, so its thread-local `timeout_probe` records landed on the spawned thread while the exported-path tests read them on the calling thread and saw nothing. `resume_on_big_stack` wraps the helper for both resume polls; under `cfg(test)` it takes the records on the big-stack thread and appends them on the caller's, keeping `forwarded` in argument position and the probe per-test. Production code is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/asset_lock/sync.rs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs index f3ccb5bd365..fc5eafaa28c 100644 --- a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs +++ b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs @@ -78,6 +78,33 @@ mod timeout_probe { pub(super) fn take() -> Vec> { RECORDED.with(|recorded| recorded.borrow_mut().drain(..).collect()) } + + /// Append records taken on another thread, keeping their order. + pub(super) fn extend(records: Vec>) { + RECORDED.with(|recorded| recorded.borrow_mut().extend(records)); + } +} + +/// [`run_on_big_stack_thread`] for the `resume_asset_lock` polls below. +/// +/// Under `cfg(test)` it also carries the timeout probe's records back to +/// the calling thread: they are thread-local, `forwarded` runs on the big +/// stack, and the tests read them on the thread that called the exported +/// entry point. +fn resume_on_big_stack(f: impl FnOnce() -> T + Send) -> std::io::Result { + #[cfg(test)] + { + let (value, recorded) = run_on_big_stack_thread(|| { + let value = f(); + (value, timeout_probe::take()) + })?; + timeout_probe::extend(recorded); + Ok(value) + } + #[cfg(not(test))] + { + run_on_big_stack_thread(f) + } } /// Pass-through that records the bound under `cfg(test)`. @@ -202,7 +229,7 @@ pub unsafe extern "C" fn asset_lock_manager_resume( let option = ASSET_LOCK_MANAGER_STORAGE.with_item(handle, |manager| { // Big-stack polling, NOT bare `runtime().block_on`, for the same // reason as `asset_lock_manager_catch_up_blocking` below. - run_on_big_stack_thread(|| { + resume_on_big_stack(|| { runtime().block_on(manager.resume_asset_lock(&out_point, forwarded(timeout))) }) }); @@ -296,7 +323,7 @@ pub unsafe extern "C" fn asset_lock_manager_catch_up_blocking( // Sync Now entry points. `run_on_big_stack_thread` rather than // `block_on_worker` because the future borrows `manager` and // `out_point`, so it is not `'static`. - run_on_big_stack_thread(|| { + resume_on_big_stack(|| { runtime().block_on(manager.resume_asset_lock(&out_point, forwarded(timeout))) }) }); From 4e32be5806e04890cf595511af00d255f506f4e1 Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Tue, 27 Oct 2026 17:08:39 +0100 Subject: [PATCH 4/5] docs(platform-wallet): describe the big-stack poll in the resume FFI docs The resume entry points no longer poll on the caller's thread. The caller blocks while the poll runs on a scoped 8 MiB thread, so the doc comments now say that instead of naming a bare runtime().block_on. Co-Authored-By: Claude Opus 5.5 --- .../src/asset_lock/sync.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs index fc5eafaa28c..913df27b8d1 100644 --- a/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs +++ b/packages/rs-platform-wallet-ffi/src/asset_lock/sync.rs @@ -189,9 +189,10 @@ fn parse_outpoint(txid: *const [u8; 32], vout: u32) -> dashcore::OutPoint { /// from then on no proof for this transaction can arrive. The wait /// cannot see that happen — it wakes on lock events and re-reads the /// tracked funding transaction only — so an unbounded wait is a -/// `Notify` loop with no terminating event, which under the -/// `runtime().block_on(...)` below pins the calling host thread -/// permanently rather than merely delaying an answer. +/// `Notify` loop with no terminating event, which pins the calling +/// host thread permanently rather than merely delaying an answer: the +/// caller blocks until the big-stack thread polling the resume below +/// returns. /// /// Expiry is non-destructive: the tracked row keeps its status, so a /// proof arriving afterwards is returned by the very next resume @@ -270,8 +271,9 @@ pub unsafe extern "C" fn asset_lock_manager_resume( /// /// Returns `ok` on a successful proof resolution, an error on /// timeout / wait failure. The Swift caller is expected to schedule -/// this on a background queue — `runtime().block_on(...)` parks the -/// calling thread for the duration of the wait. +/// this on a background queue: the calling thread blocks for the +/// duration of the wait while the resume is polled on a big-stack +/// thread. /// /// # Timeouts /// @@ -501,9 +503,9 @@ mod tests { /// Drive [`asset_lock_manager_resume`] against a live manager and report /// the bound it forwarded alongside its result code. /// - /// Called from the plain test thread: the entry point does its own - /// `runtime().block_on(...)`, exactly as the host thread does, and nesting - /// that inside an outer `block_on` would abort. + /// Called from the plain test thread: the exported entry point blocks + /// synchronously while `resume_asset_lock` is polled on the scoped + /// big-stack thread. Do not invoke it from an outer `block_on`. fn resume_extern_with( handle: Handle, timeout_secs: u64, From 9038a518ff82c1b659344ab1d1ff83cda1aa8f7b Mon Sep 17 00:00:00 2001 From: Bartosz Rozwarski Date: Tue, 27 Oct 2026 18:33:44 +0100 Subject: [PATCH 5/5] docs(swift-sdk): describe the big-stack poll in catchUpBlocking's doc The catch-up FFI no longer runs a bare runtime().block_on on the caller's thread. The caller blocks while Rust polls the resume on its own big-stack thread, and the doc comment now says so. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWallet/AssetLock/ManagedAssetLockManager.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift index 549257ea450..2a43261fab3 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/AssetLock/ManagedAssetLockManager.swift @@ -296,9 +296,10 @@ public final class ManagedAssetLockManager: @unchecked Sendable { /// proofBytes` lands on the `PersistentAssetLock` row, the UI /// observes it through `@Query`, no Swift-side state to plumb. /// - /// Blocking: the Rust `runtime().block_on(...)` parks the calling - /// thread for up to `timeoutSeconds`. Callers MUST schedule this - /// on a background queue / `Task.detached`. + /// Blocking: the Rust side polls the resume on its own big-stack + /// thread while this call blocks the calling thread for up to + /// `timeoutSeconds`. Callers MUST schedule this on a background + /// queue / `Task.detached`. public func catchUpBlocking( txid: Data, vout: UInt32 = 0,