Back to Blog
RustTokioasyncCancellationTokenDashMapJoinHandle

The Night the Cancel Stayed Pending: Why a Rust Task Stayed Pending After Cancel

rooagi•
This blog tells the story of a Rust async cancellation bug where a stop request was acknowledged, but the child task kept hanging. The root cause was not Tokio itself, but a `DashMap` guard-lifetime mistake in the cancellation registry: a token lookup held a live guard while the code tried to remove the same entry, which could stall cancellation progress.

The Night the Cancel Stayed Pending: Why a Rust Task Stayed Pending After Cancel

Story

The first hint came from one thing that looks harmless in logs: a stop request was acknowledged, then nothing.

cancel returned. status changed. And yet the child task never finished.

That was the moment the incident turned from “simple timeout” into a full async-cancellation investigation.
The child path looked alive: it had started, it had emitted tool events, and then it silently stopped progressing.
At first glance, it felt like a scheduler join issue. In reality, the story hid a deeper race between lock scope and cancellation observability.

From operations view, everything looked coherent:

  1. request came in,
  2. cancellation was accepted,
  3. the process appeared to move forward,
  4. user waited for completion,
  5. but completion never arrived.

Only one question mattered: where did the signal die?

For readers new to the term, an "inline child" here means a spawned sub-task that runs as part of a parent flow, rather than an independent top-level run. The parent asks for work to continue elsewhere, and the child inherits enough context to continue the same logical operation. That distinction matters because the child has its own async task lifecycle, but it is still tied to the parent cancellation story.

Rendering diagram...

Technical details

0) First, a quick mental model for token.cancel()

This is the point that usually causes confusion, so we treat it first.

Tokio provided the async primitives used throughout this story: select!, task scheduling, JoinHandle, and CancellationToken.

In tokio_util::sync::CancellationToken (or equivalent):

  • token.cancel() broadcasts a cancellation signal.
  • It does not forcibly stop the running future.
  • Any running work must still be written to observe that signal at an await point.

There are two common checks:

  • token.is_cancelled() — immediate boolean snapshot.
  • token.cancelled() — a future that becomes ready when the signal is observed.

So this pattern:

  • calls cancel() in one place (the requester),
  • and expects cancelled() branches in waiting tasks (tokio::select!) to wake.

If the waiting branch cannot run, or the future is stuck on another await, the task may remain pending even though the signal was emitted.

1) Symptom: “Canceled” but still alive

The child run behaved like this:

  • it emitted runtime events
  • a stop was requested
  • cancellation token was called
  • then no final terminal output showed up
  • UI history looked incomplete

In async Rust, this is the hardest class of bug: everything looks initiated, but some future never observes the stop condition.

2) False lead: the scheduler and outcome path

Most teams would suspect queueing or join logic first. We did too.

The child path went through:

  • spawn and scheduling
  • node task execution
  • event emission
  • terminal persistence

The first pass suggested JoinSet and scheduler ordering issues. We changed instrumentation heavily around graph_executor:

  • extra state transitions
  • extra branches in the select loop
  • more outcome logs
  • channel-based handoff experiments

The result was informative, not satisfying: parent runs recovered cleanly, child runs still stalled.

That was the first turning point.

One important design detail from this stage is the JoinHandle wait path.

JoinHandle was used to wait for the child run task itself to terminate, because this is the only strong signal that the spawned async task has fully finished.

In async Rust, this distinction is critical:

  • cancel called = request acknowledged
  • JoinHandle.await = task completion observed

When only the first happens, you can still have a process that appears logically stopped but is actually not converged.

Related Rust primitives we touched:

  • JoinSet groups spawned tasks and lets the scheduler collect completions.
  • JoinHandle is the per-task handle you can await for a concrete finish signal.
  • mpsc was used as an explicit handoff channel for task outcomes when we wanted to remove ambiguity from the join path.

3) Clue in plain sight: cancellation log stopped mid-flight

The logs started giving us a boundary we couldn’t ignore:

  • run cancellation requested
  • token.cancel() was called
  • and right after that, no further cancellation lifecycle logs for registry cleanup

No select branch in the child task was firing after that moment.

This did not mean cancellation didn’t happen. It meant cancellation bookkeeping in the runtime could stop progress before downstream futures observed it.

4) Root cause: map guard lifetime and DashMap mutation

The issue was in the runtime cancel path.

The reason DashMap was there at all is straightforward: the runtime needed a shared registry of run ids to cancellation tokens that could be read and updated from multiple async tasks concurrently. A plain HashMap would require external synchronization; DashMap, a third-party concurrent map crate, gives sharded concurrent access so different tasks can look up or update entries without a single global mutex. It is thread-safe, but that thread-safety still comes with guard semantics you have to respect.

The registry was constructed as part of runtime state, roughly as:

DashMap<RunId, CancellationToken>

or the equivalent shared handle in the runtime service. The intent was:

  • store one token per run
  • let cancellation look up the token by run id
  • let worker/task code check the same token lineage for stop signals

Simplified before-state:

if let Some(token) = cancellation_tokens.get(&run_id) {
    token.value().cancel();
    cancellation_tokens.remove(&run_id);
}

That reads clean in pseudocode, but in Rust those two lines share a subtle lifetime.
The read guard from get() was still active when remove() tried to mutate the same map.

In a concurrent map with lock semantics, this is a deadlock pattern in practice.

The key detail is that DashMap::get() does not just hand you a copy of the value. It returns a guard tied to the shard lock. As long as that guard is alive, the shard is considered borrowed. Calling remove() on the same entry while that guard is still in scope asks the same map to take a conflicting write path on an entry that is already guarded.

That is why this looked harmless in code review but stalled in practice:

  • get() acquired a read guard
  • the guard stayed alive through cancel() and into remove()
  • remove() tried to take the write path
  • the cancellation flow could block while still inside the cancellation routine itself

This is the part that makes the bug less obvious: nothing in the code looks like a loop or an explicit deadlock. It only appears when a shared concurrent registry, a live guard, and a cancellation routine all overlap in the same async path.

After that point, the cancellation story split:

  • token state had changed,
  • but the run path that needed a cleanly observed terminal transition no longer flowed.

5) Fix: shrink guard scope, clone before mutate

The fix is a standard Rust rule made explicit:

let token = self
    .cancellation_tokens
    .get(&run_id)
    .map(|entry| entry.value().clone());

if let Some(token) = token {
    token.cancel();
    let removed = self.cancellation_tokens.remove(&run_id).is_some();
    // log removal + completion
}

Two important effects:

  • no map mutation while the read guard is alive
  • cancellation bookkeeping can complete deterministically

This was the decisive fix for the “stop acknowledged but no finish” behavior.

6) Why the failure looked more complex than it was

After the DashMap fix, we still saw “missing history” in one area.

From a Rust perspective, this was expected:

  • there were now clean signals that the child task actually completed,
  • but the output stream used by the caller was assembled later from persisted run data.

So the remaining issue was no longer “the task never exited,” it was:

  • “the caller is reading a different object than the one containing events.”

Why this happens in Rust async systems:

  • runtime emits events from worker tasks into an async stream-like path,
  • another layer drains/merges that stream asynchronously for caller consumption,
  • if producer completion and consumer assembly are not aligned, output can look incomplete even though producer completion is correct.

In other words, task completion is necessary but not sufficient for user-visible output correctness.

Why this bug was technically interesting in Rust terms

It is a reminder that async bugs are often composition bugs:

  • tokio::select! can only wake when its awaited branches can resolve
  • CancellationToken::cancel() is signal emission, not preemption
  • lock-lifetime mistakes can suppress that signal path indirectly
  • and observability must exist at branch boundaries, not just at API edges

In our case, all four conditions had to be fixed in sequence for the story to resolve.

Lifecycle tracing: from caller to runtime

The most practical way to debug this class is to trace one stop request end-to-end:

  1. the caller requests cancellation
  2. the caller reaches the native runtime binding
  3. N-API handle forwards to native runtime service cancel
  4. runtime transitions token + run registry state
  5. worker observes cancellation and saves terminal state
  6. caller waits on true task termination before treating the run as finished

This trace is what made the bug falsifiable.

For readers new to the term, N-API is the Node.js native addon interface that lets JavaScript code call into native Rust code through a stable boundary.

Rust-adjacent checklists

N-API object lifecycle

  • keep handle identity stable across in-flight calls
  • avoid assuming reload/rebuild instantly updates existing bound objects
  • provide awaitable termination waits so callers do not race on “best effort” completion
  • use explicit terminal enums (cancelled) for reliable status handoff

Caller / runtime handoff

  • keep the cancellation registry separate from the task handle registry
  • avoid mixing signal emission with completion observation
  • keep async boundaries explicit so a caller can distinguish “cancel requested” from “task finished”

Final lessons

  1. Lock scope bugs can masquerade as async cancellation bugs.
  2. Cancellation requires explicit observability points in every long-running await path.
  3. If one layer says “cancel complete,” the next layer must still prove it in its own state machine.
  4. JoinHandle is a completion proof, not a cancellation mechanism.
  5. Debugging async flow is often about proving where it stops polling, not where it starts.

The root cause was narrow, but the path to it was not. It required reading the entire Rust cancellation lifecycle as a single distributed state machine—and proving, step by step, where the signal died.

References