Repository navigation
fix(dash-spv): make stop wait for the tasks the sync loop detaches - #313
xdustinface wants to merge 1 commit into
Conversation
The sync loop runs fork recovery and the stop of a failed loop in detached tasks, each holding a client clone and with it the storage and its lock file. `stop` did not wait for them, so it could return while they still held the lock. They now go into a `JoinSet` that `stop` joins after releasing the `sync_loop` lock. Closes upstream issue 1171 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
✅ Review complete in 8m 11s Planner (4s) Review (behavior · full): 9 findings Judge: 5 kept · 0 dropped · 4 merged (3m 8s) Review metadataConfig:
Account limits:
Judge decisions:
The cycle never resolves.
Timing:
Last reviewed
|
There was a problem hiding this comment.
🔴 Changes requested: 1 blocker, plus 2 warnings and 2 suggestions in threads.
What blocks: A stop() that races a run() from another thread can hang the client for good. join_detached_tasks holds the detached_tasks lock while it waits for a fork-recovery task, and that task can wait on a new loop which is itself blocked on the same lock. After that, every later run, stop and is_running blocks on sync_loop.
About this review
- Reviewed
ee1b272, round 1 - 74 changed lines read in 8m 11s
- Found by
claude-opus-5-5andgpt-6.2-sol, judged byclaude-opus-5-5 - Tokens: 2.5M in (2.0M from cache) · 89k out · about $4.14 at API prices
- Runner: github-hosted · started after 11m 2s · peak memory 3.5 GiB of 15.6 GiB
- How Manki reviews
| /// stopping meanwhile can still add to it. | ||
| async fn join_detached_tasks(&self) { | ||
| loop { | ||
| let mut tasks = self.detached_tasks.lock().await; |
There was a problem hiding this comment.
🚫 Blocker · Concurrency · Quick fix
join_detached_tasks holds the detached_tasks lock while it awaits tasks, which can deadlock stop against a concurrent run
What goes wrong: The doc comment says the set is taken out of its lock while joining, but the code keeps the MutexGuard across join_next().await, so nothing can add to the set until the join finishes. Here is a sequence that deadlocks: a fork spawns handle_fork task H. stop() releases sync_loop and blocks in the join, waiting for H.
| let mut tasks = self.detached_tasks.lock().await; | |
| let mut tasks = std::mem::take(&mut *self.detached_tasks.lock().await); |
How to fix it, why, and 25 places read · confirmed with tools
How to fix it
Move the JoinSet out of the mutex before joining, so the lock is held only for the swap. Keep the outer loop: it is what picks up tasks added while the join runs.
Why it matters
A concurrent run() (the FFI docs tell callers to call it from another thread) starts loop L3. L3 hits a fork or an error, cancels its token and blocks on detached_tasks.lock(). H then takes the cancelled L3 and waits in stop_locked for L3's task. Each one waits on another: stop waits for H, H waits for L3, and L3 waits for the lock stop holds. sync_loop stays locked, so every later run, stop and is_running hangs too.
Checked in the code
On the commented line: let mut tasks = self.detached_tasks.lock().await; keeps the guard alive through the while let Some(result) = tasks.join_next().await at 259 Takes self.detached_tasks.lock().await, and line 259 awaits tasks.join_next() with that guard still held.
- Doc says
The set is taken out of its lock while joining, so a sync loop stopping meanwhile can still add to it - Comment
The set is taken out of its lock while joining, but line 253let mut tasks = self.detached_tasks.lock().await;keeps the guard acrosstasks.join_…
rust-dashcore/dash-spv/src/client/lifecycle.rs
Lines 247 to 252 in ee1b272
The fork arm calls monitor_shutdown.cancel(), then client.detached_tasks.lock().await.spawn(...)
rust-dashcore/dash-spv/src/client/sync_coordinator.rs
Lines 147 to 151 in ee1b272
The error path calls detached_tasks.lock().await.spawn(...) after the token is cancelled
rust-dashcore/dash-spv/src/client/sync_coordinator.rs
Lines 193 to 197 in ee1b272
dash-spv/src/client/lifecycle.rs:287:let mut sync_loop = self.sync_loop.lock().await;dash-spv/src/client/lifecycle.rs:288:let Some(forked) = sync_loop.take_if(|running| running.shutdown.is_cancelled()) else {dash-spv/src/client/lifecycle.rs:289-293:handle_forklockssync_loop, takes any cancelled loop and callsstop_locked, which awaits that loop's taskdash-spv-ffi/src/client.rs:160-162: Tells callers to rundash_spv_ffi_client_runfrom another thread, sorunandstopcan overlapdash-spv/src/client/core.rs:119: Saysrunandstopnever overlap.dash-spv/src/client/lifecycle.rs:243: Callsdrop(sync_loop)before the detached-task drain.dash-spv/src/client/sync_coordinator.rs:153: Waits for the same task-set lock on the fork path, and line 195 waits for it on the failure path.dash-spv/src/client/lifecycle.rs:270:let mut sync_loop = self.sync_loop.lock().await;dash-spv/src/client/lifecycle.rs:271: And dash-spv/src/client/lifecycle.rs:288 allow a detached helper to take whichever loop currently has a cancelled token.dash-spv/src/client/lifecycle.rs:328: Awaitstaskwhile the caller still holdssync_loop.dash-spv/src/sync/sync_coordinator.rs:286:let Some(mut run) = self.run.take() elsetakes the set out of its owner beforerun.tasks.join_next().awaitat line 297dash-spv/src/network/manager.rs:1898: CommentDrain tasks while holding the lock. connect_to_peer() already uses select! with the cancellation token when acquiring this lock, so no deadlock can o…dash-spv/src/network/manager.rs:391: The adder takes the lock insidetokio::select! { guard = self.tasks.lock() => guard, _ = self.shutdown_token.cancelled() => ... }dash-spv/src/client/lifecycle.rs:259:while let Some(result) = tasks.join_next().await {dash-spv/src/client/lifecycle.rs:239:let mut sync_loop = self.sync_loop.lock().await;dash-spv/src/client/sync_coordinator.rs:36:pub async fn run(&self) -> Result<()> {dash-spv/src/client/sync_coordinator.rs:37:let mut sync_loop = self.sync_loop.lock().await;dash-spv/src/client/sync_coordinator.rs:199:*sync_loop = Some(SyncLoop {dash-spv/src/client/sync_coordinator.rs:175:monitor_shutdown.cancel();
Double-checked
Manki tried to disprove this by reading the code and could not. The doc comment says the set is taken out of its lock while joining, but join_detached_tasks keeps the detached_tasks guard across join_next().await. The…
Second check, on another model
Double-checked. After a fork queues a recovery helper, stop() can release sync_loop and begin joining that helper under the detached_tasks lock, leaving a concurrent r…
- Create an issue for this
| use std::pin::Pin; | ||
| use std::sync::Arc; | ||
| use tokio::sync::{Mutex, RwLock}; | ||
| use tokio::task::JoinSet; |
There was a problem hiding this comment.
A stale shutdown helper can take a replacement loop
This is on line 271. A comment on that line is not possible, so the thread is elsewhere in the file.
What goes wrong: Both helpers check whether the current loop is cancelled, not whether it is the loop that spawned them. A delayed stop_failed from an earlier run can take a replacement that just detected a fork, leaving its actual recovery helper with no loop to recover. A delayed handle_fork can likewise apply an earlier run's fork height to a cancelled replacement.
How to fix it and 22 places read · confirmed with tools
How to fix it
Pass the originating run's identity to both helpers and take the active loop only when that identity matches and its token is cancelled.
Checked in the code
On the flagged line: And dash-spv/src/client/lifecycle.rs:288 both use take_if(|running| running.shutdown.is_cancelled()).
Lets run_locked take a failed loop and continue to startup.
rust-dashcore/dash-spv/src/client/sync_coordinator.rs
Lines 43 to 49 in ee1b272
Passes only fork_height to handle_fork, and line 195 calls stop_failed() with no run identity.
rust-dashcore/dash-spv/src/client/sync_coordinator.rs
Lines 152 to 157 in ee1b272
Truncates the wallet using the detached task's fork_height.
rust-dashcore/dash-spv/src/client/lifecycle.rs
Lines 297 to 303 in ee1b272
dash-spv/src/client/sync_coordinator.rs:195:detached_tasks.lock().await.spawn(async move { client.stop_failed().await });dash-spv/src/client/lifecycle.rs:288:let Some(forked) = sync_loop.take_if(|running| running.shutdown.is_cancelled()) else {dash-spv/src/client/lifecycle.rs:289:return Ok(());dash-spv/src/client/sync_coordinator.rs:36:pub async fn run(&self) -> Result<()> {dash-spv/src/client/sync_coordinator.rs:37:let mut sync_loop = self.sync_loop.lock().await;dash-spv/src/client/sync_coordinator.rs:59:let mut fork_rx = self.subscribe_sync_events().await;dash-spv/src/client/sync_coordinator.rs:132:let task = tokio::spawn(async move {dash-spv/src/client/sync_coordinator.rs:147:Ok(SyncEvent::ForkDetected { fork_height }) = fork_rx.recv() => {dash-spv/src/client/sync_coordinator.rs:150:monitor_shutdown.cancel();dash-spv/src/client/sync_coordinator.rs:175:monitor_shutdown.cancel();dash-spv/src/client/sync_coordinator.rs:199:*sync_loop = Some(SyncLoop {dash-spv/src/client/lifecycle.rs:328:if let Err(e) = task.await {dash-spv/src/sync/block_headers/sync_manager.rs:127:self.handle_headers_pipeline(&hashed_headers, requests).awaitdash-spv/src/client/lifecycle.rs:272:self.stop_locked(failed).await;
Double-checked
Manki tried to disprove this by reading the code and could not. The defect is real: neither stop_failed nor handle_fork checks which run created it. A delayed stop_failed from run 1 takes and stops any cancelled loop…
Second check, on another model
Double-checked. A stale stop_failed can remove and stop the cancelled replacement, leaving its fork handler with no loop to recover. A stale handle_fork can instead take the r…
- Create an issue for this
| /// storage any more. | ||
| pub async fn stop(&self) { | ||
| let mut sync_loop = self.sync_loop.lock().await; | ||
| if let Some(running) = sync_loop.take() { |
There was a problem hiding this comment.
Cancelling stop can leave teardown incomplete on retry
What goes wrong: If a caller times out stop after it takes the loop but before teardown finishes, a later stop sees None and skips stop_locked. It can return without shutting down the coordinator, stopping the network, or persisting storage.
How to fix it and 20 places read · confirmed with tools
How to fix it
Keep teardown owned by the client once it starts and store its completion state so later stop calls can wait for the same teardown.
Checked in the code
On the commented line: Removes the loop with sync_loop.take() before awaiting stop_locked.
Awaits the loop task before shutting down the coordinator at line 334, the network at line 339, and storage at line 344.
rust-dashcore/dash-spv/src/client/lifecycle.rs
Lines 327 to 331 in ee1b272
Only drains detached helpers when the loop slot is already empty.
rust-dashcore/dash-spv/src/client/lifecycle.rs
Lines 244 to 248 in ee1b272
rust-dashcore/dash-spv/src/client/lifecycle.rs
Lines 237 to 244 in ee1b272
dash-spv/src/client/lifecycle.rs:334:if let Err(e) = self.sync_coordinator.lock().await.shutdown().await {dash-spv/src/client/lifecycle.rs:339:self.network.lock().await.stop().await;dash-spv/src/client/lifecycle.rs:344:storage.stop().await;dash-spv/Cargo.toml:3:description = "Dash SPV (Simplified Payment Verification) client library"dash-spv/src/lib.rs:82:pub use client::{ClientConfig, DashSpvClient, DevnetConfig, EventHandler};dash-spv/src/client/sync_coordinator.rs:36:pub async fn run(&self) -> Result<()> {dash-spv/src/client/sync_coordinator.rs:132:let task = tokio::spawn(async move {dash-spv/src/client/sync_coordinator.rs:199:*sync_loop = Some(SyncLoop {dash-spv/src/client/sync_coordinator.rs:204:Ok(())dash-spv/src/client/lifecycle.rs:255:if tasks.is_empty() {
In a related repository: dashpay/platform:packages/rs-platform-wallet/src/spv/runtime.rs:682, dashpay/platform:packages/rs-platform-wallet/src/spv/runtime.rs:684, dashpay/platform:packages/rs-platform-wallet/src/spv/runtime.rs:690, dashpay/platform:packages/rs-platform-wallet/src/spv/runtime.rs:698
Double-checked
Manki tried to disprove this by reading the code and could not. stop() takes the loop out of its slot at line 240 before awaiting stop_locked, whose coordinator, network and storage shutdown (334-344) run only after awaitin…
Second check, on another model
Double-checked. If stop() is dropped while waiting for the sync-loop task, the slot stays empty and teardown never reaches the coordinator, network, or storage. A retry skip…
- Create an issue for this
| client.run().await.expect("client must start"); | ||
|
|
||
| let detached = client.clone(); | ||
| client.detached_tasks.lock().await.spawn(async move { |
There was a problem hiding this comment.
✨ Suggestion, not blocking · Testing · Moderate
The new test adds a task to the private detached_tasks field itself and never exercises the fork or failure paths
Why: The test spawns a sleeping task straight into client.detached_tasks, so it only checks that stop joins the set. Reverting sync_coordinator.rs:153 or sync_coordinator.rs:195 back to tokio::spawn still lets it pass, and those are the paths the fix exists for. Only the removal of the join_detached_tasks() call at lifecycle.rs:245 makes it fail.
How to fix it and 8 places read
How to fix it
Drive the real paths: emit SyncEvent::ForkDetected, or make a monitor fail, through the mock network or sync coordinator, then call stop() and assert Arc::strong_count(&client.storage) == 1.
Checked in the code
On the commented line: client.detached_tasks.lock().await.spawn(async move { tokio::time::sleep(...).await; drop(detached); }); Directly calls client.detached_tasks.lock().await.spawn, and line 143 releases the task after a fixed 100 ms sleep.
- And :195 are the changed spawn sites, and the test reaches neither
- And dash-spv/src/client/sync_coordinator.rs:195 are the two production registration paths the synthetic task bypasses.
rust-dashcore/dash-spv/src/client/sync_coordinator.rs
Lines 152 to 156 in ee1b272
Checks Arc::strong_count(&client.storage) rather than reopening the store.
rust-dashcore/dash-spv/src/client/mod.rs
Lines 147 to 151 in ee1b272
Drives the existing fork test through node.invalidate_block(&replaced_block).
rust-dashcore/dash-spv/tests/dashd_sync/tests_fork.rs
Lines 69 to 73 in ee1b272
dash-spv/src/client/lifecycle.rs:245:self.join_detached_tasks().await;dash-spv/src/client/sync_coordinator.rs:195:detached_tasks.lock().await.spawn(async move { client.stop_failed().await });
- Create an issue for this
- Dismiss this finding
|
|
||
| tokio::spawn(async move { | ||
| if let Err(e) = client.handle_fork(fork_height).await { | ||
| client.detached_tasks.lock().await.spawn(async move { |
There was a problem hiding this comment.
✨ Suggestion, not blocking · Performance · Quick fix
Finished detached tasks stay in the JoinSet until stop is called
Why: A JoinSet keeps each finished task's entry until join_next collects it, and only stop calls join_detached_tasks. A client that runs for a long time keeps one small entry per fork recovery and per failed-loop stop. Forks are rare, so the cost is small.
How to fix it and 2 places read
How to fix it
Drain finished entries with try_join_next() in a loop each time a task is spawned into the set.
Checked in the code
On the commented line: And :195 add to the set on each fork or failure
join_next is reached only from stop at 245
rust-dashcore/dash-spv/src/client/lifecycle.rs
Lines 258 to 262 in ee1b272
- Create an issue for this
- Dismiss this finding
Replay of upstream PR 1178 at its initial state, for testing Manki reviews.
The sync loop runs fork recovery (
handle_fork) and the stop of a failed loop (stop_failed) in detached tasks. Each holds a client clone, and with it the storage and its lock file.stop()didn't wait for them, so it could return while they still held the lock (upstream platform issue 5381).JoinSeton the client.stop()joins them after releasing thesync_looplock, which they take themselves. With the loop already taken, they return without acting.Closes upstream issue 1171