Skip to content

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

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

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

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 13, 2026 •

Copy link
Copy Markdown

✅ Review complete in 3m 56s

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

Review (behavior · pair): 5 findings
    ✅ Claude Sonnet 5.5 · high: 1 finding (29s)
    ✅ Claude Opus 5.5 · high: 3 findings (1m 28s)

Judge: 3 kept · 0 dropped (1m 50s)
    kept: 1 warning · 2 note

Review metadata

Config:

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

Account limits:

  • Claude subscription: weekly 71% (resets 2026-11-17 05:00 UTC)

Judge decisions:

  • Kept: "join_detached_tasks holds the detached_tasks lock while joining, contrary to its doc, and can deadlock a sync loop" (warning): "blocker. The guard from lifecycle.rs:253 lives across every join_next().await at :259, so the doc at :249-250 misstates the code. The hang needs run called on another thread while stop is joining, which the public API allows:
  1. stop drops sync_loop at :243 and starts joining.
  2. A concurrent run starts loop B.
  3. B hits a fork, cancels its token, and blocks on detached_tasks.lock() at sync_coordinator.rs:153.
  4. A stale handle_fork or stop_failed task in the set takes sync_loop, sees B cancelled, and calls stop_locked (lifecycle.rs:291/272), which awaits B.
  5. B waits on the joiner, and the joiner waits on that task.
    No task can proceed, so stop never returns. This is concurrent use of a public API, so the column is normal. The remaining doubt is whether monitor_shutdown is the token that take_if checks. The comment at sync_coordinator.rs:149 suggests it is. The suggested std::mem::take fix matches the doc.
    Refutation confirmed: The guard taken at lifecycle.rs:253 is still held across every join_next().await at :259, which contradicts the doc at :249-250. A loop B that cancels its token at sync_coordinator.rs:150 then blocks on that lock at :153. Meanwhile a detached handle_fork or stop_failed task in the set can take sync_loop, find B's token cancelled, and await B in stop_locked (lifecycle.rs:288/291 or :271/272), so stop() never returns. Rule checked: In Rust, a tokio MutexGuard bound with let lives until the end of its scope, so it stays held across every .await in that scope. Any other task calling lock().await on the same mutex waits until the guard is dropped.
  • Premise "monitor_shutdown cancelled at sync_coordinator.rs:150 is the same token as running.shutdown that handle_fork and stop_failed check with take_if at lifecycle.rs:288 and :271" confirmed. shutdown is a clone of monitor_shutdown (sync_coordinator.rs:130) and is stored as SyncLoop.shutdown (:199-201), so cancelling monitor_shutdown at :150 is what the take_if checks at lifecycle.rs:271 and :288 see."
  • Kept: "The new test fills the internal detached_tasks set itself and never runs the paths that now use it" (note): "note. The test does exercise what its name says: it fails if stop stops joining at lifecycle.rs:245. What it leaves out is the switch from tokio::spawn to the set at sync_coordinator.rs:153 and :195. That is missing test coverage, so it is the improvement row."
  • Kept: "Finished detached tasks stay in the JoinSet until stop is called" (note): "note. Finished entries are reaped only by join_next in stop, so the set grows by one small entry per fork recovery. Forks are rare and each entry is tiny, so this is no practical exhaustion. Calling try_join_next before each spawn would keep the set small."

Timing:

  • Parse: 4.1s
  • Review agents: 122.0s
  • Judge: 110.1s
  • Total: 236.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.

✅ Approved. 1 warning and 2 notes, none of which block.

Caution

Claude subscription has used 71% of its weekly limit, past the 70% mark. It resets 2026-11-17 05:00 UTC.

Once a limit is used up, reviews on that account stop until it resets.

What this does: Before, fork recovery and the cleanup after a failed sync loop ran as untracked background tasks. These could still hold storage after stop returned.


2 notes · not blocking
✨ The new test fills the internal detached_tasks set itself and never runs the paths that now use it
Note, not blocking · Testing · Moderate · dash-spv/src/client/mod.rs:142

Why: The test spawns a task straight into the private detached_tasks field. It never triggers a fork recovery or a failed loop through the client. Reverting both sync_coordinator.rs changes back to tokio::spawn (lines 153 and 195) still passes it, so the fix for the reported lock leak has no test. Only removing self.join_detached_tasks().await at lifecycle.rs:245 makes it fail.

let detached = client.clone();
client.detached_tasks.lock().await.spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
drop(detached);

How to fix it
Add a test that makes the sync loop fail, or emit SyncEvent::ForkDetected, through the mock network or coordinator. Then call stop and assert that Arc::strong_count(&client.storage) == 1.

Checked in the code
On the flagged line: client.detached_tasks.lock().await.spawn(async move { ... drop(detached); }) writes internal state directly

And :195 are the changed spawn sites, and no test drives them

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);
}

  • Create an issue for this
✨ Finished detached tasks stay in the JoinSet until stop is called
Note, not blocking · Performance · Quick fix · dash-spv/src/client/sync_coordinator.rs:153

Why: A JoinSet keeps every finished task until join_next reaps it. Only stop reaps this set. A client that recovers from many forks over a long run without stopping keeps one entry for each recovery. Each entry is small, but the set only grows.

let recovering = client.clone();
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);

How to fix it
Before each spawn, clear finished entries with while tasks.try_join_next().is_some() {}.

Checked in the code
On the flagged line: Spawns a handle_fork task for every ForkDetected event

join_next is called only from join_detached_tasks, which only stop calls

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

Related work: open PRs and issues that may cover the same change. None of them blocks.


What to test

The review model wrote these steps. Check what a step runs before you follow it.

Setup: Run the dash-spv tests and a client against a regtest dashd node, using eval $(python3 contrib/setup-dashd.py).

  1. Run cargo test -p dash-spv stop_waits_for_detached_tasks. Expect it to pass, with the storage Arc strong count at 1 after stop.
  2. Start a client with run, call stop, then open a new DiskStorageManager on the same path. Expect it to open without lock or busy errors.
  3. Trigger a fork on regtest (invalidate a block and mine a competing branch) while the client runs. Expect the client to truncate above the fork height and resume syncing.
  4. Call stop right after a fork is detected. Expect stop to return and is_running to return false, with no sync loop restarted.
  5. Make the sync loop fail, for example by making an event monitor channel fail. Expect on_error to fire and is_running to become false, then stop to return promptly.
  6. Call clear_storage while a fork recovery is in progress. Expect it to complete without hanging and the tip to reset afterwards.
About this review
  • Reviewed ee1b272, round 1
  • 74 changed lines read in 3m 56s
  • Found by claude-sonnet-5-5 and claude-opus-5-5, judged by claude-opus-5-5
  • Tokens: 379k in (195k from cache) · 27k out · about $1.24 at API prices
  • Runner: github-hosted · started after 4m 16s · peak memory 1.4 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.

⚠️ Warning, not blocking · Concurrency · Quick fix

join_detached_tasks holds the detached_tasks lock while joining, contrary to its doc, and can deadlock a sync loop

What goes wrong: The doc says the set is taken out of its lock while joining so a stopping sync loop can still add to it. The code keeps the MutexGuard alive across every join_next().await, so any sync loop that hits a fork or error and calls detached_tasks.lock().await.spawn(..) blocks until the whole join ends. If a pending detached task needs sync_loop, which a concurrent stop() holds while awaiting that blocked loop, none of the three can proceed and stop() never returns.

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 and 18 places read · confirmed with tools

How to fix it
Move the set out of the lock before joining, so the lock is held only briefly: let mut tasks = std::mem::take(&mut *self.detached_tasks.lock().await);. Keep the outer loop so tasks added meanwhile are joined too.

Checked in the code
On the commented line: let mut tasks = self.detached_tasks.lock().await; is a guard that lives to the end of the loop iteration

  • while let Some(result) = tasks.join_next().await awaits with the guard held.
  • while let Some(result) = tasks.join_next().await awaits while that guard is held

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

client.detached_tasks.lock().await.spawn(..) in the sync loop task and :195 detached_tasks.lock().await.spawn(..) both wait for that lock

// which only acts on a loop whose token is cancelled.
monitor_shutdown.cancel();
let recovering = client.clone();
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);
}

stop_locked awaits the loop task while holding sync_loop, and handle_fork and stop_failed take sync_loop themselves

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;
}

Double-checked
Manki tried to disprove this by reading the code and could not. The guard taken at lifecycle.rs:253 is still held across every join_next().await at :259, which contradicts the doc at :249-250. A loop B that cancels its to…

  • Create an issue for this

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