Skip to content

Implement position-based Task disposition semantics #350

Closed

Description

@ehartford

Implement position-based Task disposition semantics

Summary

The spec now defines Task disposition by syntactic position instead of the old blanket unused-Task rule.

A task expression in statement position is intentional fire-and-forget detachment when both gates pass:

  1. must-observe: the API author has not marked completion/failure as requiring observation.
  2. detach-safety: the compiler proves the task may safely outlive the current scope.

A task bound to a name declares intent to observe; losing that bound handle unused is a compile error. let _ = <Task expression> is not the detach spelling.

Spec

  • docs/with-specification.md §20b.2 Task Disposition (:10375-10403): statement-position task = fire-and-forget, "allowed only when the API does not require observation and the compiler proves the task can safely outlive the current scope"; "When detachment is rejected, the diagnostic must say whether the task is must-observe or whether detach-safety failed, because the remedies are different."
  • docs/with-specification.md §14.7 (:6455-6517): both gates defined; normative diagnostic shapes error[E0801]: task result must be observed (this task is marked must-observe / help: await, cancel, return, store, or otherwise handle the task) and error[E0802]: task cannot be detached safely (task captures data owned by this scope / help: await, cancel, return, or restructure so the task no longer carries scope-bound state out of scope); "An unused bound task handle is a compile error"; "let _ = task is not the fire-and-forget spelling… the compiler rejects let _ = <Task expression> for task values."
  • docs/with-specification.md §14.1 Design Principles.
  • docs/requirements.md 14.1.1.5, 14.7.1.10-14.7.1.22, 20.2.2.1-20.2.2.6.
send_analytics("page_view")        // OK when best-effort and detach-safe
send_invoice(invoice).await?       // OK: observed
let task = warm_cache(key)
cancel(task)                       // OK: explicit cancellation
let task = send_invoice(invoice)   // ERROR if never given a disposition
let _ = send_analytics("page_view")// ERROR: not the detach spelling

Current state

src/SemaCheck.w still implements the old model:

  • Statement position is unconditionally rejected. In check_block, src/SemaCheck.w:4384-4387: statement-position task values that are not scoped-task values emit self.emit_error("E0801: unused Task value", stmt). There is no must-observe gate (no must_observe marking exists anywhere in src/ or the spec'd attribute surface) and no detach-safety gate wired here. The discard check uses expr_is_task_value (:1841) and expr_is_scoped_task_value (:1907, which whitelists scope.track(...) calls and scoped-task bindings).
  • let _ = task is only a warning. check_let_binding, src/SemaCheck.w:4501-4502: self.emit_warning("`let _ = ...` on a Task immediately cancels it", node). The spec requires rejection.
  • No unused-bound-handle check. Binding a task and never using it is accepted; sema tracks binding_decl_nodes/binding_value_nodes (:4507-4508) but has no used-flag audit at scope exit.
  • Detach-safety building blocks already exist (the detach-safety gate is largely assembled, not invented): expr_creates_ephemeral_task (src/SemaCheck.w:2309), expr_is_ephemeral_task (:2514), check_ephemeral_task_arg_escape (:2537), check_ephemeral_task_storage (:2549); Sema.ephemeral_task_binding_nodes (src/Sema.w:490).
  • MIR drop machinery distinguishes task dispositions: DropKind.DK_TASK_DETACHED = 2 / DK_TASK_EPHEMERAL = 3 (src/Mir.w:315-316); task_drop_kind_for_binding (src/MirLower.w:253-258) selects by ephemeral_task_binding_nodes; emit_drop_entry (src/MirLower.w:279-295) lowers DK_TASK_DETACHED → MirIntrinsic.FIBER_DETACH_CANCEL and DK_TASK_EPHEMERAL → FIBER_CANCEL + cleanup-await. Note: all existing drop paths cancel — there is no "keep running with no handle" lowering yet; the detached-fiber bookkeeping exists in rt/fiber_runtime.w:38-40 (detached_fiber_ids/detached_result_bufs).

That contradicts the updated spec.

Expected behavior

  • Bare task statement is accepted when the task is not must-observe and detach-safety proves it can safely outlive the current scope.
  • Bare task statement is a hard error when must-observe fails, with a diagnostic that says the task result/failure must be observed.
  • Bare task statement is a hard error when detach-safety fails, with a diagnostic that says the task cannot be detached safely and identifies scope-bound/ephemeral state when possible.
  • let task = ... requires a valid disposition: await, cancel, return, store when non-ephemeral, track in async scope, or equivalent.
  • An unused bound task handle is a compile error.
  • let _ = <Task expression> is not the fire-and-forget spelling and should be rejected for task values. Use statement position for permitted detachment or bind and cancel(task) for cancellation.

Implementation plan

  1. must-observe marking surface (design decision needed first). The spec says "the API author has not marked the task's completion or failure as requiring observation" but names no syntax. Propose @[must_observe] on the async fn/Task-returning fn declaration, parsed like existing attributes (@[sealed]/@[flags] precedent in src/Parser.w), stored as a signature flag in src/Sema.w next to the sig effect tables (sig_param_view_origins area, :268). Functions returning Result-typed tasks are the natural candidates for the marker but the gate must be explicit, not inferred. Confirm spelling with the maintainer before implementing; file a spec patch if the attribute name is adopted.
  2. Statement-position gates (src/SemaCheck.w:4384-4387). Replace the unconditional E0801: unused Task value with:
    • if callee signature is must-observe → error[E0801]: task result must be observed, secondary label this task is marked must-observe, help await, cancel, return, store, or otherwise handle the task (spec §14.7 wording);
    • else if detach-safety fails → error[E0802]: task cannot be detached safely, label task captures data owned by this scope, help per spec. Detach-safety = expr_creates_ephemeral_task(stmt) == 0 and the task's captures contain no allocator-borrowed/scope-bound resources (reuse expr_is_ephemeral_task/check_ephemeral_task_storage predicates; in v1 ephemerality is the detach-safety proxy);
    • else → accepted: record the statement node in a new detached_task_stmt_nodes set on Sema for MIR lowering.
  3. Detached lowering (src/MirLower.w). For recorded detached statements, lower the discarded task value to a true detach (fiber keeps running, handle dropped) instead of the cancel-on-drop path. Requires a FIBER_DETACH MIR intrinsic alongside FIBER_DETACH_CANCEL (src/Mir.w:240) and a runtime entry in rt/fiber_runtime.w that moves the fiber into the existing detached bookkeeping without setting the cancel flag. Bootstrap hazard: runtime export first, consumer second — commit 1 adds the rt/ function (old link path still green), commit 2 wires the intrinsic/lowering, each independently passing with build :fixpoint (AGENTS.md "Never change Link.w and runtime files in the same commit" discipline applies to the rt export ordering).
  4. Reject let _ = task (src/SemaCheck.w:4501-4502). Upgrade emit_warning to emit_error: `let _ = ...` is not the detach spelling for Task values; use statement position to detach, or bind and `cancel(task)`. Per CLAUDE.md's design principle this is acceptable ceremony because the discard matters (a dropped Task cancels it).
  5. Unused bound handle check. Track per-binding use: when an ident referencing a task binding is checked (check_expr ident path), insert into a task_binding_used set. At scope pop in check_block, for each task-typed binding (type_is_task, already consulted at :4514-4516) declared in the scope and never used: error: unused Task handle 'name'; binding a task declares intent to observe it, help listing the valid dispositions. Scoped tasks (scope.track) and _-named bindings are exempt (the latter now rejected earlier by step 4). Deterministic iteration: walk the scope's binding list in declaration order, not a map.
  6. Diagnostics text must distinguish the two gates (§20b.2: "the diagnostic must say whether the task is must-observe or whether detach-safety failed").

Phasing: steps 4-5 are independent of 1-3 and can land first (pure sema). Step 2's acceptance path is the behavior change that needs step 3's lowering in the same release to avoid silently cancelling "detached" work — do not ship step 2 accepting statements that step 3 still lowers as cancel-on-drop (that would be a silent behavior lie).

Test plan

test/compile_errors/:

  • err_task_must_observe_statement.w — statement call to a @[must_observe] task fn; //! expect-check-fail: task result must be observed.
  • err_task_detach_unsafe_statement.w — statement-position task capturing &local; //! expect-check-fail: cannot be detached safely.
  • err_task_let_underscore.w — let _ = async_work(); //! expect-check-fail: not the detach spelling.
  • err_task_unused_bound_handle.w — let t = async_work() never used; //! expect-check-fail: unused Task handle.
  • Update any existing fixtures asserting the old unconditional E0801: unused Task value text.

test/behavior/:

  • behav_task_detach_statement.w (//! expect-stdout) — permitted fire-and-forget: non-ephemeral, non-must-observe task in statement position; program proves the detached fiber actually ran (e.g. side effect through a channel/atomic before main exits) and that it was not cancelled.
  • behav_task_dispositions.w — each valid disposition compiles and runs: await, cancel(task), return to caller, scope.track.

test/spec/:

  • spec_ss20b_2_task_disposition.w — the §20b.2 table of OK forms as one runnable file.

Acceptance criteria

  • Statement-position tasks pass/fail the two gates independently, with gate-specific E0801/E0802 diagnostics matching §14.7 wording.
  • Accepted statement-position tasks are truly detached at runtime (run to completion, not cancelled).
  • let _ = <Task> is a hard error; unused bound task handles are hard errors; all valid dispositions accepted.
  • rt changes land as export-first/consumer-second commits, each passing fixpoint.
  • with build && with build :fixpoint && with build :test pass; with build :test-green recorded.

Dependencies

Traceability

Original spec references (preserved): docs/with-specification.md §14.1 Design Principles, §14.7 Task[T], §20b.2 Task Disposition; docs/requirements.md 14.1.1.5, 14.7.1.10-14.7.1.22, 20.2.2.1-20.2.2.6.

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Implemented in 084e816 and 1f07a05.

    Summary:

    • Added a non-canceling fiber detach runtime handoff.
    • Implemented §14.7 position-based Task disposition: allowed statement-position creation detaches only after must-observe and detach-safety checks, existing Task handles in statement position are rejected, bound Task handles must be observed before scope exit, and let _ = <Task> is rejected as a discard spelling.
    • Lowered accepted detached Task statements through MIR to with_fiber_detach; Task.cancel() continues to use the canceling handoff.
    • Added positive and negative coverage for detach, must-observe rejection, detach-safety rejection, let _, unused bound handles, no_suspend cleanup, and unsafe ephemeral-task assertion behavior.

    Verification passed on the rebased main:

    • with build
    • with build :fixpoint
    • with build :test
    • with build :test-green
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