Skip to content

Await combinators: cancel+join when cancelled mid-flight (§14.11.1) #421

Closed

Description

@ehartford

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.w implements the combinators. Early-return joins exist: await_all fail-fast (task.w:36-43), await_first losers (71-76), await_any winner path (96-101) — each does remaining.cancel() then let _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_CANCEL then lower_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. Tasks pending[i+1..] are left to the Vec drop. Task-binding drops emit FIBER_CANCEL without 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 defer blocks (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 .await in the unwind path would re-enter the self-cancel machinery).
  • Note: await_all/await_any call result.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

  1. Expose a cleanup-join surface (compiler): add a Task method join_cleanup() (naming open: cancel_join()): semantics = FIBER_CANCEL on the target then FIBER_CLEANUP_AWAIT — exactly the pair lower_single_await's self-cancel path already emits (src/MirLower.w:4871-4884). Wire it like cancel()/is_done(): sema typing in check_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_AWAIT does not re-check self-cancellation (verify in rt/fiber_runtime.w before 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 a std.task surface, not a with_* internal).
  2. Stdlib combinators (lib/std/task.w): in await_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_unjoined on every normal join (the sequential .await loop 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_settled never cancels during normal operation (spec), but the drop contract still applies when the combinator itself is cancelled — same defer.
  3. Defer semantics check: the defer body mutates a captured var and 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).
  4. 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.
  5. 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 :fixpoint between (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; wrap await_all(children) in an async fn, spawn it as comb; after the children are known to be running, comb.cancel() then comb.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-stdout ok.
  • Same shape for await_first (cancel while it waits on the winner) and await_settled (cancel mid-collection).
  • Regression: existing early-return semantics — fail-fast await_all still returns first Err with losers joined (input-order error, §14.11.1); await_any all-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

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 14.11.1.35.

Activity

  1. ehartford commented on Jun 16, 2026

    @ehartford
    ContributorAuthor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions