Skip to content

recv() on a closed drained channel ignores the -1 status and returns an uninitialized value — define and implement the closed-recv contract (§14.15) #672

Closed

Description

@ehartford

Pre-existing runtime bug, split from #671

#671's compile-side trap (enum-constructor args typed void) is fixed; these runtime failures reproduce on the pre-fix installed compiler via the typed-intermediate spelling, so they are independent and older.

Cell matrix (chan[Option[i32]] / chan[Msg], all on current main AND installed v0.15.1-gf4c1c0047)

Case Result
tx.send(Some(3)) → rx.recv().unwrap().unwrap() == 3 works
tx.send(None) (or typed binding) → rx.recv() outer Option is None — the sent None never arrives
user enum: tx.send(Ping(9)) → recv().unwrap() (no further use) works
user enum: recv().unwrap() then match on the value SIGSEGV (exit 139)

Repros:

fn main:
    let (tx, rx) = chan[Option[i32]](4)
    let e: Option[i32] = None
    tx.send(e)
    let got = rx.recv()
    print_i32(if got.is_some(): 1 else: 0)   // prints 0 — value lost
enum Msg:
    Ping(i32)
    Stop

fn main:
    let (tx2, rx2) = chan[Msg](4)
    let p: Msg = Ping(9)
    tx2.send(p)
    let m = rx2.recv().unwrap()
    match m:
        Ping(v) => assert(v == 9)
        Stop => assert(false)                 // exit 139 before reaching here

Suspected area

The recv-side Option wrapper's "empty/closed" sentinel and/or the CHAN_SEND/CHAN_RECV payload copy for aggregate elements: a None element (tag-carrying 16-byte enum) is indistinguishable from "no value" on arrival, and a received user-enum value is corrupt enough that tag/payload extraction in a match faults while a bare unwrap survives. Look at the CHAN_SEND/CHAN_RECV codegen (CodegenDispatch.w:10259, and the GENERIC_CALL send special case at 12859) plus rt/channel_runtime.w's element copy sizes.

test/behavior/behav_channel_enum_payload.w pins what works today and carries a note to extend to a match when this is fixed.

Activity

  1. ehartford commented on Jul 16, 2026

    @ehartford
    ContributorAuthor

    Correction: the original premise was wrong — channels are healthy

    Root-caused with the channel runtime + codegen sources and probe matrices. rx.recv() returns the element directly (blocking), per §14.15 — there is no Option wrapper; try_recv is the Option-shaped API, and the runtime signals empty via the recv status code, not a value sentinel. Both reported failures were artifacts of probes written against a Rust-shaped contract:

    • "None vanishes": false. recv() returned the None element correctly; the probe's .is_some()/.unwrap() were interrogating a wrapper that doesn't exist. Under the correct contract, send(None) → recv().is_none() round-trips.
    • "recv→match segfaults": the probe called .unwrap() on the received user enum. That should have been a compile error — and the fact that it wasn't is the real bug this issue uncovered.

    What was actually broken — fixed in 83b09fb

    Sema.builtin_intrinsic_method_return_type ended in an unconditional catch-all typing .unwrap() on ANY receiver as the receiver type (legacy accommodation for HashMap.get's raw-encoded optionals). On a plain enum, codegen's OPT_UNWRAP then extracted a phantom Option payload — silent value corruption, surfacing as the segfault. The catch-all now skips enum receivers (Option/Result handle their own unwrap earlier); Msg.unwrap() is now a loud unknown method 'unwrap' for type 'Msg'. Full suite unchanged-green — nothing relied on the leniency. Pinned by err_unwrap_on_plain_enum.w; the healthy channel contract (None round-trip, Some round-trip, recv-then-match on user enums) is pinned by the extended behav_channel_enum_payload.w.

    What remains open in this issue — closed-channel recv contract

    CodegenDispatch's CHAN_RECV handler discards with_channel_recv's status return and loads the out-slot unconditionally. On a closed, drained channel the runtime returns -1 and never writes the slot, so recv() yields an uninitialized value (probe: returned stack garbage 1 for a chan[i32]). §14.15 specifies suspend-on-empty but does not define the closed-channel behavior. Needs a ruling: panic loudly ("recv on closed channel"), or a specified sentinel/contract — silent garbage is the one indefensible option. Retitling this issue to track that decision + implementation.

  2. changed the title [-]Channels lose or corrupt enum element payloads at runtime (None vanishes; recv→match segfaults) (§14.14)[/-] [+]recv() on a closed drained channel ignores the -1 status and returns an uninitialized value — define and implement the closed-recv contract (§14.15)[/+] on Jul 16, 2026
  3. ehartford commented on Jul 16, 2026

    @ehartford
    ContributorAuthor

    Resolved in a9cd93e by BDFL ruling — recorded as decisions.md D10.

    The contract: recv() -> Option[T]. Buffered messages always deliver first (Some); None means closed AND drained — Rust's semantics in Swift's spelling. And Receiver is now for-iterable: for msg in rx: receives until the sender hangs up and falls out with zero ceremony, which deletes the loop's residual Some ritual (the Swift AsyncStream lesson). In fallible contexts the happy path stays bare: rx.recv()?.

    The bug this issue tracked — CHAN_RECV codegen discarding the runtime's -1 status and loading an uninitialized slot — is gone by construction: codegen now writes the element straight into the Option's payload field and derives the tag from the status with a branchless select.

    Why not the alternatives (full reasoning in D10): panic converts normal pipeline teardown into the error machinery and taxes the most common channel idiom; a Go-style zero-value sentinel is silent wrong data and is mechanically unavailable anyway (no universal default for arbitrary T). Reference survey: Rust (Err after drain) and Swift (nil terminates for await) chose the type-honest signal independently; Go needed , ok and range special-casing to patch its sentinel; Zig and Vale ship no channels.

    Pinned by: behav_channel_for_recv.w (worker loop incl. break/continue), behav_channel_close.w (drain-first, double-None), behav_channel_enum_payload.w (Some(None) vs None distinguishable by type, user-enum match through the channel). All in-tree recv call sites migrated. Spec §14.15 updated with the Option contract and the blessed loop.

    Residuals recorded in D10: try_recv remains specified-but-unimplemented and its None will conflate empty-now with closed — needs a three-state answer when implemented; select-over-channels arm binding shape gets reconciled when that lands.

    Gates on a9cd93e: build 0, FIXPOINT, audit:all violations=0, :test all targets ok, test-green/last-green recorded.

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