Repository navigation
Description
Await combinators: cancel+join when cancelled mid-flight (§14.11.1)
Summary
The §14.11.1 collection combinators (await_all, await_first, await_any, await_settled) honor the cancel+join contract on their normal early-return paths, but if the combinator itself is cancelled/dropped mid-flight, its not-yet-awaited tasks are only cancelled (or merely dropped), never joined, before the combinator unwinds. The spec requires cancel and join before unwinding, so callers can rely on losers having actually stopped.
Spec
§14.11.1 Collection Await, cancellation/drop contract:
- If a combinator returns early (winner found or fail-fast trigger), it cancels all remaining owned tasks and joins them before return.
- If the combinator itself is cancelled/dropped mid-flight, it cancels remaining owned tasks and joins them before unwinding.
Latency note (same section): "cancels and joins" means the combinator does not return until every losing task has actually stopped; cancellation is cooperative (§14.7).
Current state
lib/std/task.wimplements the combinators. Early-return joins exist:await_allfail-fast (task.w:36-43),await_firstlosers (71-76),await_anywinner path (96-101) — each doesremaining.cancel()thenlet _joined = remaining.await.- Mid-flight cancellation path: when the combinator's fiber is cancelled while suspended in
pending.get(i).await, the await lowering (MirBuilder.lower_single_await,src/MirLower.w:4832-4925) takes the self-cancel branch: it cancels + cleanup-joins only the task currently being awaited (FIBER_CANCELthenlower_cleanup_await→FIBER_CLEANUP_AWAIT, 4871-4884), sets cancelled-return, runs defers/drops (emit_defers_for_return/emit_drops_for_return, 4923-4924), and returns. Taskspending[i+1..]are left to theVecdrop. Task-binding drops emitFIBER_CANCELwithout a join (DropKind.DK_TASK_EPHEMERAL,src/MirLower.w:285-289), and Vec-element tasks get no per-element cancel at all — so remaining tasks are cancelled-at-best, never joined, violating the contract. - Crucially, the unwind path does run
deferblocks (4923) — so a defer-based cleanup inside the combinator bodies will execute on mid-flight cancellation. That is the fix's hook. - Task surface methods today:
.await,cancel(),is_done()(sema:src/SemaCheck.w:10431-10440); there is no user-facing "join for cleanup" that is safe to call while the current fiber is already cancelled (a plain.awaitin the unwind path would re-enter the self-cancel machinery). - Note:
await_all/await_anycallresult.err().unwrap()(task.w:43,103) —Result.err()is missing (Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6) #393), so the fallible overloads may not even instantiate today; verify while testing.
Implementation plan
- Expose a cleanup-join surface (compiler): add a
Taskmethodjoin_cleanup()(naming open:cancel_join()): semantics =FIBER_CANCELon the target thenFIBER_CLEANUP_AWAIT— exactly the pairlower_single_await's self-cancel path already emits (src/MirLower.w:4871-4884). Wire it likecancel()/is_done(): sema typing incheck_method_call(src/SemaCheck.w:10431-10440, returns void, zero args, requires awaitable task value) and MIR lowering that emits the two intrinsics against the receiver. It must be legal when the calling fiber is itself cancelled —FIBER_CLEANUP_AWAITdoes not re-check self-cancellation (verify inrt/fiber_runtime.wbefore relying on it; if it does, add a runtime entry that waits without the check). Document it as the §14.11.1 cleanup primitive (it is astd.tasksurface, not awith_*internal). - Stdlib combinators (
lib/std/task.w): inawait_all(both overloads),await_first,await_any,await_settled:- track progress in a
var next_unjoined: i32; - install
defer:while next_unjoined < total: pending.get(next_unjoined).join_cleanup(); next_unjoined = next_unjoined + 1; - advance
next_unjoinedon every normal join (the sequential.awaitloop and the existing early-return join loops), so the defer is a no-op on all normal exits and only does work when the combinator unwinds mid-flight. await_settlednever cancels during normal operation (spec), but the drop contract still applies when the combinator itself is cancelled — same defer.
- track progress in a
- Defer semantics check: the defer body mutates a captured
varand loops — confirm defer capture rules allow this in async fns (if not, hoist the state into a small struct and fix the gap loudly rather than working around it). - Ordering/latency: join in input order (matches the §14.11.1 aggregation guarantees); the combinator's unwind blocks until every loser reaches a suspension point — that is the spec'd cooperative-cancellation latency, not a bug.
- Scope:
lib/std/task.w+ the new method wiring in src/. No rt symbol additions expected (both intrinsics exist); if a new runtime entry is needed (step 1 verification), follow the bootstrap order rules — rt change in its own commit before any consumer,with build :fixpointbetween (AGENTS.md Bootstrap Rules).
Edge cases: combinator cancelled before its first await (defer joins everything); cancelled between child completions (current i already consumed — next_unjoined must only count unconsumed tasks); empty input (defer no-op; await_first([]) panic path is todo(...) at task.w:67 — its panic behavior is #544's scope); double-join safety (join_cleanup after a task already awaited must be a no-op — cleanup-await on a completed fiber; verify rt behavior).
Test plan
Deterministic async behavior tests (channels/atomics, no raw sleeps for correctness):
test/behavior/behav_await_all_cancelled_joins.w: spawn N children that loop on a channel/cancellation check and set a per-child "exited" Atomic flag on the way out; wrapawait_all(children)in an async fn, spawn it ascomb; after the children are known to be running,comb.cancel()thencomb.await(join the combinator); assert all N exited flags are set at that point — proving the combinator did not unwind before its losers stopped. Expect-stdoutok.- Same shape for
await_first(cancel while it waits on the winner) andawait_settled(cancel mid-collection). - Regression: existing early-return semantics — fail-fast
await_allstill returns first Err with losers joined (input-order error, §14.11.1);await_anyall-fail aggregates errors in input order. - If
Result.err()blocks instantiation of the fallible overloads (Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6) #393), land that first or test via the infallible overloads and gate the fallible tests on Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6) #393.
Acceptance criteria
- Cancelling a combinator task mid-flight cancels AND joins every remaining owned child before the combinator's fiber unwinds (observable via the exited-flag test)
- Normal-path behavior and result ordering unchanged
- New cleanup-join surface documented in
lib/std/async/docs (README/await_*.md mention the drop contract implementation) - with build && with build :fixpoint && with build :test pass
Dependencies
- Soft dependency: Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6) #393 (
Result.err()used byawait_all/await_anyat task.w:43,103). - Related: Bug: todo()/unreachable() lower to LLVM unreachable, not a panic (§29.10, §4.10, §14.11.1) #544 (
todo()panic semantics —await_firstempty-input stable panic message depends on it).
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 14.11.1.35.
Activity
ehartford commentedon Jun 16, 2026
Implemented in f915adf. Await combinators now track unjoined owned tasks and use a defer-backed Task.join_cleanup() cleanup path so cancellation/drop of the combinator cancels and cleanup-joins remaining children before unwind. Added compiler support for join_cleanup(), impl-trait generic argument binding needed by the combinators, Vec.is_empty lowering, docs updates, and positive/negative tests. Verification passed with project seed/release commands: build, fixpoint, full test suite, and explicit test-green. Follow-up filed separately as #595 for generic helper inference with Vec[Task[T]].