Skip to content

Generic async function monomorphization silently returns wrong values #558

Closed

Description

@ehartford

Summary

Generic async function monomorphization silently generates the wrong result.
The earlier std.task collection-instantiation failures are fixed; the remaining
bug is a smaller and more serious async-generic codegen failure.

Minimal reproduction

use std.task

async fn plain(n: i32) -> i32: n

async fn first_of[T](a: Task[T]) -> T: a.await

fn main:
    print_i32(first_of(plain(10)).await)

Actual behavior

On the current compiler this program compiles and runs, but prints 0.
The identical monomorphic helper returns and prints 10.

Earlier investigation reached this seam only after fixing generic async
signature handling, at which point codegen crashed in task/fiber lowering.
That crash is gone, but successful compilation now emits silently wrong code.

Resolved scope

  • Vec[Task[T]] now satisfies the std.task collection helper signatures.
  • await_first, await_all, and await_any instantiate without leaking an
    unresolved T from embedded stdlib code.
  • await_first is a plain function returning T under §14.11; the conforming call
    is await_first(tasks), not await_first(tasks).await.
  • Empty await_first input reaches the documented
    “await_first: empty input” panic.

The old issue title and original trailing-await repro described those resolved
problems and no longer identify the live defect.

Investigation map

Start at generic specialization and async body lowering:

  • Codegen.monomorphize_generic_call_core
  • FIBER_AWAIT emission in CodegenDispatch.w
  • AsyncLower task result storage/restoration

The fix must identify the exact specialization or task-result type/state that
becomes wrong. Returning a default value, stubbing the body, or rejecting only
this spelling is not acceptable.

Acceptance criteria

  • The generic reproduction prints 10.
  • Generic async functions work for at least one non-i32 result and a nested
    Task[T] use.
  • The monomorphic control remains correct.
  • A regression test distinguishes the returned value from T's default.
  • If correct code cannot be generated, compilation fails loudly instead of
    emitting a wrong result.
  • Full build, fixpoint, audit, and test gates pass.

Related

#489's generic async combinator-consumption coverage depends on this seam.

Activity

  1. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Status update (skepticism pass, 2026-07-02): PARTIAL progress on HEAD. The four errors incl. embedded-std internal leakage (std/task.w unknown 'T') are down to ONE clean call-site error: await requires a Task value at await_first(tasks).await with tasks: Vec[Task[i32]]. Remaining work: infer T through the await_first signature so the returned Task awaits (stdlib contract; §14.11-adjacent).

  2. ehartford commented on Jul 3, 2026

    @ehartford
    ContributorAuthor

    Complete root-cause map from this cycle (fix attempted, then deliberately backed out — details below so the next cycle starts warm):

    Sema side (root-caused to exact lines, fix verified in isolation): async GENERIC fns exit collect_fn_decl at the tp_count > 0 early return (SemaDecl.w ~:1369-1381) BEFORE both the async Task-wrap of the sig return (:1434-1440) and the task_fns.insert (:1467). So check_generic_call types await_first(tasks) as bare T=i32 (resolve_generic_return_type_node on the declared ret node, never consulting FnFlags.ASYNC), and .await's expr_is_awaitable_task_value misses on both legs → the single 'await requires a Task value' error. T-inference through impl IntoIter[Task[T]] is NOT the problem (binds fine). Two-part fix that WORKS at check level: (1) in check_generic_call, wrap resolved_ret in Task[...] via ensure_generic_inst_type when (fn_meta_flags(meta) / FnFlags.ASYNC) % 2 == 1, before the specialization-cache insert; (2) in collect_fn_decl's tp_count>0 branch, task_fns.insert(fn_name, 1) for async fns.

    Why it's backed out: with check unblocked, the construct reaches codegen and the COMPILER SIGSEGVs (exit 139, no diagnostic) monomorphizing the async generic — llvm::StructType::getTypeAtIndex at address 0x10, the same null-struct-GEP signature as #595, but in the async-generic/fiber-lowering seam (the #595 structural-unification fix does not cover it; the crash reproduces with a plain user-written async fn wrap[T](v: Vec[Task[T]]) -> T, no impl-trait needed). Accept-then-compiler-crash is worse than today's misleading-but-clean check error, so the sema fix waits for the codegen side.

    Remaining work (the real issue): make codegen monomorphization of ASYNC generic fns sound — the mono body's await/task-struct GEP gets a null LLVM type. Entry points: Codegen.monomorphize_generic_call_core + the FIBER_AWAIT emission (CodegenDispatch.w ~:9013) + AsyncLower interplay. Then re-apply the two sema edits verbatim from this comment.

  3. ehartford commented on Jul 3, 2026

    @ehartford
    ContributorAuthor

    Cross-ref from coverage sweep #489: this same bug (generic async fn cannot be awaited — await requires a Task value because the generic async return isn't Task-wrapped) BLOCKS all §14.11 combinator consumption tests. Minimized repro: async fn first_of[T](a: Task[T]) -> T: a.await then first_of(plain(10)).await → 'await requires a Task value' + 'return type mismatch'. Monomorphic async (-> Vec[i32]) awaits fine; only GENERIC async fails — exactly the sema Task-wrap gap this issue documents (the fix is written+verified but exposed a codegen SIGSEGV, hence deferred). #489 depends on this.

  4. changed the title [-]Bug: std.task await_first generic Task collection signatures do not instantiate[/-] [+]Generic async function monomorphization silently returns wrong values[/+] on Jul 15, 2026
  5. ehartford commented on Jul 15, 2026

    @ehartford
    ContributorAuthor

    Fixed in 1838206e.

    Root cause was a three-part contract break in generic async specialization:

    • generic declarations returned before recording async behavior metadata, so concrete specializations were not recognized as async;
    • concrete MIR codegen compiled the body against the signature's Task[T] return instead of the body's T return, then direct-called that body instead of spawning a fiber;
    • ordinary async parameters were classified with the synchronous share-place ABI even though they escape into the spawned fiber. For a nested Task, that made MIR emit await_owns=0, so codegen did not free the awaited result buffer.

    The fix records behavior metadata before generic early returns and on concrete symbols, unwraps Task[T] for concrete async bodies, routes generic calls through the normal async spawn path, defers unbound generic async method declarations, and treats ordinary async by-value parameters as owned captures. Explicit references and read/mut receivers remain borrowed and produce ephemeral tasks. Existing channel/Rc fixtures now spell the required move at those ownership transfers.

    Evidence:

    • with build: stage1, stage2, and release passed at -O1
    • with build :fixpoint: FIXPOINT
    • analyze src/main.w audit:all: 2,175,204 facts, 0 violations
    • drop audit matrix: 25 cells, 0 fail
    • debug allocator generic async fixture: leak count 0
    • full with build :test: exit 0 (including 864 behavior, 703 compile-error, 209 spec, and 36 phase files)
    • :test-green and :last-green: recorded successfully
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