Skip to content

fix(dash-spv): make stop wait for the tasks the sync loop detaches - #313

Closed
xdustinface wants to merge 1 commit into
test-base/1178from
test/1178-v770a
Closed

xdustinface wants to merge 1 commit into
test-base/1178from
test/1178-v770a

Conversation

@xdustinface

Copy link
Copy Markdown
Owner

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

  • Those tasks now go into a JoinSet on the client.
  • stop() joins them after releasing the sync_loop lock, which they take themselves. With the loop already taken, they return without acting.

Closes upstream issue 1171

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]>
@manki-review

manki-review Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

✅ Review complete in 8m 11s

Planner (4s)
    feat · 74 lines · 2 agents
    judge effort: medium

Review (behavior · full): 9 findings
    ✅ Claude Opus 5.5 · high: 3 findings (3m 17s)
    ✅ GPT 6.2 Sol · high: 5 findings (2m 26s)
    ✅ Related checks, claim checks, pattern checks and fix checks: 7 of 7 done, 1 finding (2m 19s)
    ✅ Second reads: 1 of 1 done (1m 3s)

Judge: 5 kept · 0 dropped · 4 merged (3m 8s)
    kept: 1 blocker · 2 warnings · 2 suggestions
    sweeps: 1 of 1 done (20s)

Review metadata

Config:

  • Models: reviewer=claude-opus-5-5, judge=claude-opus-5-5
  • Triage: trivial=false, subtle=true, paired=true (planner)
  • Team: Claude Opus 5.5 · high, GPT 6.2 Sol · high
  • Memory: enabled (central)

Account limits:

  • Claude subscription: weekly 37% (resets 2026-11-27 01:00 UTC)
  • ChatGPT subscription: weekly 4% (resets 2026-11-25 01:21 UTC)

Judge decisions:

  • Kept: "join_detached_tasks holds the detached_tasks lock while it awaits tasks, which can deadlock stop against a concurrent run" (blocker): "blocker. The guard taken at dash-spv/src/client/lifecycle.rs:253 stays alive across tasks.join_next().await at :259. The doc comment at :249 says the set is taken out of the lock, but the code does not do that. The deadlock runs like this:
  1. stop() drops sync_loop at :243 and waits for an earlier handle_fork task H while holding the detached_tasks lock.
  2. A concurrent public run() installs loop L3. The FFI docs at dash-spv-ffi/src/client.rs:160-162 tell callers to run it from another thread.
  3. L3 detects a fork, cancels its token and blocks on detached_tasks.lock() at sync_coordinator.rs:153 (or :195 on failure).
  4. H takes the cancelled L3 at lifecycle.rs:288 and awaits L3's task in stop_locked at :328.

The cycle never resolves. sync_loop stays locked, so every later lifecycle call hangs too. The trigger is concurrent use of the public API plus a fork driven by the network, so the column is normal. All five blocker tests hold, since the lines involved are new in this PR.
Refutation confirmed: 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 deadlock needs a run that overlaps stop, which the public API allows. In that case loop L3 cancels its token and then blocks on detached_tasks.lock() (lines 153 or 195). Task H takes the cancelled L3 under sync_loop and awaits its task in stop_locked. stop waits for H while holding the lock L3 needs, so each one waits on anoth... Rule checked: A tokio MutexGuard stays held across every .await in its scope, so a task that needs that lock cannot go on until the holder releases it.
Pair refutation confirmed: 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 run() free to install a replacement loop. If the replacement cancels its token on a fork or error before the helper checks it, the helper takes the cancelled replacement and awaits it under sync_loop, while the replacement waits for detached_tasks; neither can finish, and later lifecycle calls waiting on sync_loop also hang. Rule checked: Awaiting a task does not release a mutex guard, so the join deadlocks if the joined task depends on work that needs the same mutex."

  • Kept: "The new test adds a task to the private detached_tasks field itself and never exercises the fork or failure paths" (suggestion): "note. The test does run the changed stop join logic, and it fails if the join at lifecycle.rs:245 is removed. What it misses is coverage of the spawn sites at sync_coordinator.rs:153 and :195. That is missing test coverage, so it is a note."
  • Kept: "Finished detached tasks stay in the JoinSet until stop is called" (suggestion): "note. A Tokio JoinSet keeps each finished entry until it is joined. Here the set gains one small entry per fork recovery or per failed loop, and both events are rare. Nobody would notice the cost, so it is a note."
  • Kept: "A stale shutdown helper can take a replacement loop" (warning): "warning at most, and pre-existing. The selection by is_cancelled() alone at lifecycle.rs:271 and :288 sits on lines this PR does not change. Moving the helpers into a JoinSet neither causes nor exposes the problem, so it fails blocker test 1. If the race is real, the earlier run's fork height gets applied to a replacement loop. Concurrent public run calls can produce that state.
    Refutation confirmed: 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 it finds, including a run-2 loop that just cancelled its own token after detecting a fork. Run 2's handle_fork then finds no loop at line 288 and returns Ok without recovering. In the other order, a stale handle_fork applies run 1's fork height to whatever cancelled loop is stored. Rule checked: A tokio Mutex hands its lock out in FIFO order, and take_if(|r| r.shutdown.is_cancelled()) picks whichever loop is stored when the lock is acquired, not the loop that spawned the helper.
  • Premise "A loop started by a later run can be cancelled before an earlier run's handle_fork or stop_failed task acquires sync_loop, so that helper takes it at lifecycle.rs:271 or :288" confirmed. Suppose a public run() holds sync_loop (lines 37-38). It stops failed loop 1 by awaiting its task (line 46), and that task has already queued its stop_failed behind the lock (line 195). Loop 2 is then spawned at line 132 and stored at line 199 before the lock is released. A ForkDetected event subscribed before startup (line 59), or a monitor failure, lets loop 2 cancel its token right away (line 150 or 175). That can happen on another worker before or as the lock passes to the stale `stop_...
    Pair refutation confirmed: 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 replacement and attempt to truncate the wallet and stored chain at the earlier run’s fork height. Rule checked: A mutex protects the current slot from concurrent access, but checking its cancellation flag does not verify that it still holds the run that spawned the helper.
  • Premise "A loop started by a later run can be cancelled before an earlier run's handle_fork or stop_failed task acquires sync_loop, so that helper takes it at lifecycle.rs:271 or :288" confirmed. A later public run can take the cancelled old loop and install a replacement without joining the old helper, and the replacement can cancel on ForkDetected without taking sync_loop, so the old helper can acquire the lock first and take the replacement."
  • Kept: "Cancelling stop can leave teardown incomplete on retry" (warning): "warning at most, and pre-existing. The take() and stop_locked call at lifecycle.rs:240-241 are unchanged by this PR, so it fails blocker test 1. Whether any caller actually cancels stop is unproven. The FFI path calls it through block_on, which does not cancel it.
    Refutation confirmed: 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 awaiting the loop task (328). If the stop future is dropped in between, a later stop() finds None at 240, only drains detached tasks at 245 and returns without that teardown. Rule checked: In Rust async, dropping a future at an await point cancels it, so work after that await never runs, while state changed before it (here the loop removed with Option::take) stays changed.
  • Premise "A caller drops a stop() future after sync_loop.take() at lifecycle.rs:240 but before stop_locked finishes, and a later stop then skips storage and network teardown" confirmed. DashSpvClient::stop is a public async method of the dash-spv library, so any caller can drop it, for example with tokio::time::timeout, after line 240 and before stop_locked finishes; a later stop then skips teardown. The known consumer dashpay/platform avoids this by running client.stop() in a spawned task so it is never cancelled, and the FFI path uses block_on, so no caller found in these repos triggers it.
    Pair refutation confirmed: 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 skips stop_locked and returns if the detached-task set is empty. Rule checked: Dropping a suspended Rust future prevents its remaining code from running but does not undo mutations it already made.
  • Premise "A caller drops a stop() future after sync_loop.take() at lifecycle.rs:240 but before stop_locked finishes, and a later stop then skips storage and network teardown" confirmed. On a single-threaded runtime, a Rust library caller can await run(), immediately poll stop() until it suspends waiting for the newly spawned loop, then drop it and retry; the FFI wrapper's block_on does not constrain direct Rust callers."

Timing:

  • Parse: 4.7s
  • Review agents: 298.8s
  • Judge: 187.7s
  • Total: 491.2s

Last reviewed ee1b272 · head ee1b272 · up to date

  • Pause automatic reviews
  • Review again
  • Deeper review

@manki-review manki-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 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-5 and gpt-6.2-sol, judged by claude-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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Suggested change
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 253 let mut tasks = self.detached_tasks.lock().await; keeps the guard across tasks.join_…

/// Wait for the tasks the sync loop detached, including any they start in
/// turn. The set is taken out of its lock while joining, so a sync loop
/// stopping meanwhile can still add to it.
async fn join_detached_tasks(&self) {
loop {

The fork arm calls monitor_shutdown.cancel(), then client.detached_tasks.lock().await.spawn(...)

Ok(SyncEvent::ForkDetected { fork_height }) = fork_rx.recv() => {
// Recovering stops this task, so it runs in a task of its own,
// which only acts on a loop whose token is cancelled.
monitor_shutdown.cancel();
let recovering = client.clone();

The error path calls detached_tasks.lock().await.spawn(...) after the token is cancelled

// Stopping waits for this task, so it runs in a task of its own.
let detached_tasks = Arc::clone(&client.detached_tasks);
detached_tasks.lock().await.spawn(async move { client.stop_failed().await });
}
});

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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Warning · Correctness · Moderate

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.

// A loop that failed and still waits for its own stop is done: tear it
// down here, so the client really runs again.
if let Some(failed) = sync_loop.take_if(|running| running.shutdown.is_cancelled()) {
self.stop_locked(failed).await;
}
if sync_loop.is_some() {
return Ok(());

Passes only fork_height to handle_fork, and line 195 calls stop_failed() with no run identity.

client.detached_tasks.lock().await.spawn(async move {
if let Err(e) = recovering.handle_fork(fork_height).await {
tracing::warn!("Error recovering from the fork: {}", e);
}
});

Truncates the wallet using the detached task's fork_height.

let truncated = async {
self.wallet.write().await.truncate_above(fork_height)?;
let mut storage = self.storage.lock().await;
BlockHeaderStorage::truncate_above(&mut *storage, fork_height).await?;
FilterHeaderStorage::truncate_above(&mut *storage, fork_height).await?;
FilterStorage::truncate_above(&mut *storage, fork_height).await?;
BlockStorage::truncate_above(&mut *storage, fork_height).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() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Warning · Reliability · Moderate

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.

shutdown.cancel();
if let Err(e) = task.await {
tracing::warn!("Sync loop task failed: {}", e);
}

Only drains detached helpers when the loop slot is already empty.

self.join_detached_tasks().await;
}
/// Wait for the tasks the sync loop detached, including any they start in

/// storage any more.
pub async fn stop(&self) {
let mut sync_loop = self.sync_loop.lock().await;
if let Some(running) = sync_loop.take() {
self.stop_locked(running).await;
}
drop(sync_loop);

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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

client.detached_tasks.lock().await.spawn(async move {
if let Err(e) = recovering.handle_fork(fork_height).await {
tracing::warn!("Error recovering from the fork: {}", e);
}

Checks Arc::strong_count(&client.storage) rather than reopening the store.

client.stop().await;
assert_eq!(Arc::strong_count(&client.storage), 1);
}
#[tokio::test]

Drives the existing fork test through node.invalidate_block(&replaced_block).

let mut events = wallet.read().await.subscribe_events();
node.invalidate_block(&replaced_block);
for _ in 0..3 {
node.try_rpc_call("generateblock", &[json!(miner_address.to_string()), json!([])])
.expect("generateblock failed");

  • 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✨ 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

while let Some(result) = tasks.join_next().await {
if let Err(e) = result {
tracing::warn!("Detached client task failed: {}", e);
}

  • Create an issue for this
  • Dismiss this finding

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.

2 participants