Skip to content

Spawning >1024 live fibers silently yields Tasks that await to zero (unchecked -1 fiber_id) #995

Closed

Description

@eas4ai

Summary

Spawning more than 1024 concurrently-live fibers silently produces broken Task handles. Awaiting them returns immediately with a zero value instead of diagnosing. Any program that spawns 1025+ tasks before awaiting (e.g. build a Vec[Task], then await_all) gets silently wrong results past index 1023, exit code 0.

Repro (read-only audit probe, seed compiler at 450733e)

use std.builtins.print_i32
use std.task.Task
use std.task.await_all
async fn mark(idx: i32) -> i32: idx + 1
fn build_tasks(n: i32) -> Vec[Task[i32]]:
    var tasks: Vec[Task[i32]] = Vec.new()
    var i = 0
    while i < n:
        tasks.push(mark(i))
        i = i + 1
    tasks
async fn main:
    let results = await_all(build_tasks(1100))
    print_i32(results.len() as i32)  // 1100
    print_i32(results.get(1023))     // 1024 (correct)
    print_i32(results.get(1024))     // 0 (WRONG, expected 1025)
    print_i32(results.get(1099))     // 0 (WRONG, expected 1100)

With 3000 tasks: indices 0..1023 correct, 1024..2999 all read 0. Deterministic across runs, at -O1, single worker (fiber_worker_count = 1) and 8 workers alike. Plain Vec[i32] push/get of 3000 elements is correct, so the container is exonerated; the corruption is in the spawn/await path.

Root-cause chain (all verified by reading + execution)

  1. with_fiber_spawn returns -1 when live_fiber_count >= MAX_FIBERS (1024) (rt/fiber_core_darwin.w:772-774). Spawns 1025+ while earlier fibers are still live hit this.
  2. Codegen stores the raw spawn return into Task.fiber_id with no -1 check, in both spawn emitters (src/CodegenDispatch.w:18362 and 18449-18464).
  3. with_fiber_await(-1) returns immediately: fiber_take_completed(-1) takes nothing, then with_runtime_fiber_is_live(-1) returns 0 (fiber_lookup misses, rt/fiber_core_darwin.w:1031-1038), so await takes the early-return path (rt/fiber_runtime.w:212-215).
  4. Codegen then loads the result from the Task's result buffer, which no fiber ever wrote (fresh-alloc zeros observed) — silent 0.

Why this is severe

  • Violates No Silent Fallbacks: three layers (runtime spawn, codegen Task construction, await) each silently accept the failure instead of diagnosing. A loud spawn-capacity diagnostic (or blocking/growing slot table) at any one layer would fix the silence.
  • The 1024-live-fiber ceiling itself may be legitimate as a default, but exceeding it must fail loudly, never produce value-corrupting handles.
  • with_runtime_fiber_is_completed documents (§14.7/Task.is_done() returns false after .await (await appears to invalidate the handle) #637, rt/fiber_core_darwin.w:1008-1012) that unresolvable handles name finished tasks — a -1 pseudo-handle abuses that contract from the other direction.

Suggested fix (owner's call)

  • Check the spawn return in codegen (or a spawn wrapper): on -1, emit a loud diagnostic (capacity exceeded) rather than minting a Task. And/or make with_fiber_await diagnose an unknown fiber id instead of early-returning 0.
  • Consider whether the slot table should grow / block instead of failing at 1024 live fibers.

Audit provenance

Found during read-only end-to-end audit (T-task-runtime leg) while diagnosing await_all truncation; logged in .audit/source-review-log.md.

Activity

  1. eas4ai commented on Sep 3, 2026

    @eas4ai
    ContributorAuthor

    Second failure mode from the same root cause, verified by execution: the Result-typed await_all (and by inspection await_first/await_any, which share the task_first_completed readiness scan) HANGS instead of returning zeros. await_all over 1100 all-Ok Task[Result[i32, str]] never prints: task_first_completed requires completion_sequence > 0 (lib/std/task.w:43), which a -1 pseudo-handle never gets (with_runtime_fiber_completion_sequence misses lookup, returns 0), so ready < 0 forever; once the 1024 real fibers drain, with_runtime_has_fibers() == 0 makes task_wait_for_progress a no-op and the while pending.len() > 0 loop spins forever (lib/std/task.w:77-83). Observed: 60s timeout, zero output, rc=124 (seed stage1 -O1 at 450733e). So past the spawn cap, infallible await_all/await_settled silently corrupt while Result await_all/await_first/await_any livelock — one loud spawn diagnostic fixes all five.

  2. ehartford commented on Sep 16, 2026

    @ehartford
    Contributor

    Review: reproduced (both failure modes)

    Verdict. Established on current main. Spawning 1100 tasks before awaiting yields correct results for indices 0..1023 and zeros for 1024..1099 with exit 0. The Result-typed await_all over the same 1100 tasks never returns (killed by a 30 s timeout), as the follow-up comment describes. A 1000-task control is correct. The root-cause chain in the report matches the source at HEAD line for line.

    Tested revision and compiler

    item value
    source main @ 5809ac1 (2026-09-14); rt/fiber_core_darwin.w, rt/fiber_runtime.w, lib/std/task.w unchanged since 450733e except the least-ceremony sweep
    compiler with build of 5809ac1 in a detached worktree, self-reports with v0.15.2.1
    platform macOS Darwin 25.6.0, arm64; default fiber_worker_count (1)

    Probes

    use std.task.Task
    use std.task.await_all
    async fn mark(idx: i32) -> i32: idx + 1
    fn build_tasks(n: i32) -> Vec[Task[i32]]:
        var tasks: Vec[Task[i32]] = Vec.new()
        for i in 0..n:
            tasks.push(mark(i))
        tasks
    async fn main:
        let results = await_all(build_tasks(1100))
        print(f"len={results.len()} r1023={results.get(1023)} r1024={results.get(1024)} r1099={results.get(1099)}")
    
    program result
    above (1100 tasks) len=1100 r1023=1024 r1024=0 r1099=0, rc 0 (expected 1025 and 1100)
    same with Result[i32, str] tasks and match await_all(...) no output, rc 124 after 30 s
    control: 1000 tasks len=1000 r999=1000, rc 0

    Source (each step observed)

    1. Capacity: rt/fiber_core_darwin.w:51 MAX_FIBERS = 1024; :770-778 with_fiber_spawn returns -1 when live_fiber_count >= MAX_FIBERS or no slot is free.
    2. Unchecked handle: src/CodegenDispatch.w:18100-18103 and :18187-18199 store the spawn return straight into Task.fiber_id with no test for -1.
    3. Await accepts it: rt/fiber_runtime.w:200-215: fiber_take_completed(-1) takes nothing, then with_runtime_fiber_is_live(-1) == 0 takes the "already finished" early return; the result buffer was never written, so the caller reads its zero fill.
    4. Livelock variant: lib/std/task.w:36-42 task_first_completed requires with_runtime_fiber_completion_sequence(fiber_id) > 0, which a -1 handle never satisfies, so the Result combinators spin once the real fibers drain.

    Spec

    The specification sets no fiber-count limit (no MAX_FIBERS, "1024", or "live fibers" text), and §14.19 documents only stack size, pool size, and worker count as configuration. So a 1024 ceiling is an implementation choice, which is fine, but exceeding it must fail loudly. AGENTS.md §No Silent Fallbacks applies at three layers here (runtime, codegen, await). The #637 contract that "unresolvable handles name finished tasks" (with_runtime_fiber_is_completed, rt/fiber_core_darwin.w:1008-1012) is what turns a failed spawn into a silently-finished task.

    Related PRs

    None since 450733e touch the spawn path, the codegen Task construction, or task.w. #981 (this queue) removed the only stdlib-level batching helper that could have kept callers under the cap.

    Would I champion a fix? Yes; one loud check at spawn fixes all five combinators.

    Acceptance criteria:

    1. A failed with_fiber_spawn (-1) never becomes a Task: codegen (or a runtime spawn wrapper) panics with a message naming the live-fiber capacity and the configured limit, or the runtime blocks/grows instead of failing. Either is acceptable; silence is not.
    2. Independently, with_fiber_await on a handle that is neither live nor completed panics rather than returning; the Task.is_done() returns false after .await (await appears to invalidate the handle) #637 contract is narrowed to handles that were once live.
    3. The 1100-task probe either prints r1024=1025 r1099=1100 (grow/block) or fails with the capacity diagnostic; the Result variant does the same instead of hanging.
    4. A behaviour test at MAX_FIBERS + 1 live tasks for await_all (both overloads), await_first, await_any, await_settled.
    5. If the ceiling stays, document it in §14.19 next to fiber_pool_size (maintainer-authored).

    Untested

    fiber_worker_count = 8 was not re-run (the reporter did; the cap is global, so the outcome should not differ). Linux and Windows not executed.

  3. ehartford commented on Oct 25, 2026

    @ehartford
    Contributor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): reproduced.

    $ cat main.w
    use std.task.Task
    use std.task.await_all
    async fn mark(idx: i32) -> i32: idx + 1
    fn main:
        var tasks: List[Task[i32]] = List.new()
        for i in 0..1100: tasks.push(mark(i))
        let results = await_all(tasks)
        var zeros = 0
        for i in 0..results.len():
            if results[i] == 0: zeros += 1
        print(f"results {results.len()}, zeros {zeros}, last {results[1099]}")
    $ with run main.w
    results 1100, zeros 76, last 0
    rc=0
    

    pre-release: silently wrong results from an ordinary task fan-out; at minimum the failed spawn must be loud.

  4. ehartford commented on Oct 25, 2026

    @ehartford
    Contributor

    Fixed on main by c5fdc17 (#2688), merged through stack 5 whose seed-driven battery was green on its top (gate, uat and survey all green). Regression test: test/behavior/behav_995_spawn_past_live_task_limit.w.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions