Skip to content

#2049: ownership-validator verdicts in 24 behavior programs fixed at their exact lines; D87 implicit fills observe; std.context arena borrows - #2058

Merged
ehartford merged 10 commits into
mainfrom
fix-2049
Oct 4, 2026
Merged

ehartford merged 10 commits into
mainfrom
fix-2049

Conversation

@ehartford

@ehartford ehartford commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2049. Draft until the battery is green.

All 24 programs now pass both check --validate-ownership and run --debug-alloc on stage1, with the expected stdout. Ten of them allocate nothing, so the allocator has no report to print. Gate is green. drop-audit: 254 cells, 0 regressions. deep-debug-tool-tests now runs --validate-ownership over 22 of the programs (bzip2/zlib are left out because they c_import host libraries).

The validator itself was right in every case but one, which was too strict (cause 9). Everything else was a real MIR or library defect.

# Root cause (file) Programs Fix
1 An implicit fill was lowered as copy of the with binding into a consuming parameter (MirLower lower_call_inner / lower_call_from_arg_nodes; Sema accepted the fill). Under --debug-alloc this was a DOUBLE FREE. behav_implicit_params, _autoref, _method_call, behav_std_context D87 (§7.3a v7.19): an implicit fill observes the binding and never consumes it. Sema (SemaCheck implicit_param_fillable, emit_implicit_param_unfilled) fills only implicit &T, or implicit T when T is Copy. A non-Copy implicit T is an error whose help names both fixes. MirLower lower_implicit_fill reports the contradiction if it ever sees one. std.context: TempArena is now a shared handle that allocates through &self, so implicit &Context can allocate. Tests converted to implicit &Ctx, or to a Copy Ctx where the test is about by-value.
2 Record update { b with f: v } (MirLower lower_record_update) retired the base's drop without moving it, so the base was Init at return. The new value was also not consumed: its temp dropped after it had moved into the result (DOUBLE FREE). behav_record_update, _record_copy, _record_update_large_struct An owned base now moves whole into the update. New field values are consumed.
3 ? pass path read a Copy payload as copy and then blanked the carrier. Validator verdict: "reset of an unmoved local". behav_result, errdefer_basic/_ordering/_question_mark The payload always moves out of the decomposed carrier. The validator also treats a carrier whose payload was vacated as a shell (cause 9).
4 Comparisons lowered non-Copy, non-str operands as move with no reset, so the owner's drop came after the "move". issue51_semantic_compare_dispatch, behav_cstr_from_ptr_to_owned lower_comparison_operand: comparison operands are always read, never moved.
5 unwrap_or_else called its fallback closure as move, while the closure's scope drop still ran on the success arm. behav_1974_eliminator_owned_at_ref_param, behav_unwrap_or_large_str_payload The closure is called through a copy of its place, like every other closure call.
6 Tuple await (t1, t2).await: a cancellation unwind on one task left the not-yet-awaited siblings un-joined, and their drops were already retired. async_tuple_await, behav_async_tuple_await lower_group_await cancels and joins the remaining siblings on unwind, the same way the ? path does.
7 let-else: the fail path dropped the subject only when the type had drop glue, but the success path kept a statement-temp drop for a glue-less non-Copy subject. That left it Init at return on the else path. behav_zlib/bzip2_facade_roundtrip The fail path drops whenever the subject has a cleanup.
8 A diverging tail of a labeled block (return f"...") put its temps in the enclosing frame, so a break to the label dropped an unwritten temp. behav_let_else_break_exits_loop A diverging tail frames its own temps.
9 Validator (MirCore validate_ownership_body): "reset of a never-moved local" fired on a carrier whose sub-place had been moved out. This was a false positive; the leak-at-return rule already handled the partial case. (with 3) Shared mir_local_partially_vacated. Unit test decomposed_reset_verdict in MirValidationTests.
10 =~ regex: nothing dropped Captures, and the $N bindings were scheduled in the function scope (dropped once at exit, after every loop iteration had overwritten them, including on the no-match path). A compiled-Regex condition leaked its Option. The literal cache leaked code+tables (#1036). behav_regex_capture_fstring, behav_regex_language_semantics Captures and bindings are scoped to the branch or loop body. Value/compiled =~ Options are statement temps. std.regex: literal code is owned by a module global that the exit wrapper drops.
11 D52: a const reached as a proxy local after its first use lowered as move NAME. behav_const_consumed_twice_materializes Global proxy locals are read, never moved.
12 join_cleanup on an owned task handle retired the drop but read the handle as a copy, so it was Init at return. behav_task_join_cleanup_consumes_handle The handle moves into the join.

New fixtures. Each one failed on main before the fix (DOUBLE FREE, leak, or a missing diagnostic):

  • test/debug_alloc/da_2049_implicit_fill_observes.w
  • test/debug_alloc/da_2049_context_arena_implicit_borrow.w (arena freed exactly once at scope end)
  • test/debug_alloc/da_2049_record_update_moves_owned_fields.w
  • test/debug_alloc/da_2049_regex_captures_dropped.w
  • test/debug_alloc/da_2049_regex_literal_code_freed_at_exit.w
  • test/compile_errors/err_2049_implicit_non_copy_not_filled.w
  • test/compile_errors/err_2049_implicit_explicit_arg_moves.w
  • test/behavior/behav_2049_implicit_copy_filled_twice.w

This PR does not turn the validator on for every build; that stays with #2043.

Repair after the first battery (3f84f14)

# Root cause (file) Seen as Fix
13 emit_module_runtime_init_fn (src/CodegenTraits.w ~1660) reset the per-function MIR maps but not mir_indirect_value_local_types / mir_ref_capture_local_types, so a module global's runtime initializer inherited the by-address map of the function emitted before it. The default-trait-method synthesizer (~746) had the same omission. contract-view-tests: audit:all "mode-provenance: operand read of an indirect local ... fact=true llvm-pointer=false" Both synthesizers save, clear and restore the two maps. Fixture test/behavior/behav_2049_runtime_init_global_after_facade.w (fails audit:all on main), audited in deep-debug-tool-tests.
14 The regex literal cache was an owning module global in lib/std/regex.w; every program initialized and dropped it, and its drop glue linked pcre2_code_free_8 (and the pcre2 bundle) into regex-free programs. cli-selfhost cross-target tests: "embedded bundle 'pcre2' was built for target darwin_aarch64" No global. Slots are linked through a plain word; Regex.__literal_free_all frees them, and wrap_main_for_exit (src/Codegen.w) calls it only when Sema validated a regex literal. hello-world: no pcre2/regex symbols, 121,920 bytes (122,224 on the installed compiler).
15 =~ (src/MirLower.w, expression/if/while sites) lowered a named compiled Regex through lower_expr: it moved into a statement temporary that died with the condition, so later matches ran against the blank. da_2049_regex_captures_dropped.w failed --validate-all ("move of _1 ... already moved out") The regex operand is read in place, like the subject. The fixture now matches twice and reads re afterwards; deep-debug-tool-tests validates its ownership.

On 3f84f14: :gate, :contract-view-tests, :cli-selfhost-project-tests, :cli-selfhost-edge-tests, :debug-alloc-tests green; :drop-audit 254 cells, 0 regressions.

@ehartford
ehartford added this pull request to stack #2059 October 3, 2026 22:16
ehartford pushed a commit that referenced this pull request Oct 3, 2026
Rebased onto fix-2049 (#2058), which fixed three of the same defects:
- `join_cleanup` on an owned handle: its lowering (the handle moves into
  the join when this frame owns it) is kept; this branch's receiver
  choice and the Sema call set that fed it are removed. Sema still marks
  the binding moved (#1993).
- a cancelled tuple await releasing the tasks it has not reached:
  its lower_group_await is kept; this branch adds only that the pending
  tasks' cancel observes the handle (copy) before the cleanup await takes
  it, and da_2011_tuple_await_unwind_releases_pending.w.
- `?` blanking a live carrier on the pass path: its fix (the pass-path
  payload moves out; the validator's partially-vacated rule) is kept;
  this branch's fail-path reset flush is removed, and
  validate_all_question_mark_fail_path_reset.w stays as a pin.
ehartford pushed a commit that referenced this pull request Oct 3, 2026
Rebased onto fix-2049 (#2058), which fixed three of the same defects:
- `join_cleanup` on an owned handle: its lowering (the handle moves into
  the join when this frame owns it) is kept; this branch's receiver
  choice and the Sema call set that fed it are removed. Sema still marks
  the binding moved (#1993).
- a cancelled tuple await releasing the tasks it has not reached:
  its lower_group_await is kept; this branch adds only that the pending
  tasks' cancel observes the handle (copy) before the cleanup await takes
  it, and da_2011_tuple_await_unwind_releases_pending.w.
- `?` blanking a live carrier on the pass path: its fix (the pass-path
  payload moves out; the validator's partially-vacated rule) is kept;
  this branch's fail-path reset flush is removed, and
  validate_all_question_mark_fail_path_reset.w stays as a pin.
@ehartford
ehartford removed this pull request from stack #2059 October 4, 2026 00:52
@ehartford
ehartford added this pull request to stack #2072 October 4, 2026 00:52
@ehartford
ehartford marked this pull request as ready for review October 4, 2026 14:20
@ehartford
ehartford merged commit 0dc6195 into main Oct 4, 2026
@ehartford
ehartford deleted the fix-2049 branch October 4, 2026 14:21
ehartford added a commit that referenced this pull request Oct 4, 2026
…urn check (#1985); no re-drop when a defer is cancelled during break/continue (#1986); join_cleanup moves the Task (#1990) (#1997)

* A cancellation inside a defer on a break/continue path drops only what is still pending (#1986)

`break`/`continue` (and a gen-loop label exit, goto) leave each scope down
to the target innermost first: its defers, then its drops. The drops
emit_cleanup_to_target emitted for an inner scope stayed in
drop_local_ids (kept for sibling paths), so when a defer of an outer scope
awaited and the fiber was cancelled there, emit_cancelled_return's
emit_drops_for_return walked them again and dropped the inner locals a
second time.

Evidence, da_1986_cancel_in_defer_during_break.w on the fix-916 stage1:
`res_drops=4` (each Res destructor ran twice); --dump-mir of break_parent
showed `bb9: drop(_4) @ drop#10` on the break edge and `bb22: drop(_4) @
drop#13; return` on the cancelled-return edge of the same path; and
`--validate-all`: "drop of _4 reaches a path that never initialized it
(Uninit)" in break_parent and continue_parent. The debug allocator stayed
quiet because Res's Vec was already freed and emptied by the first drop;
the ownership validator caught it.

Fix (MirLower emit_cleanup_to_target): once a scope's drops are emitted on
this path they leave the pending set until the path ends, then are
restored for sibling paths, the way #916 already does for defers. After:
`res_drops=2 after_loop=0 live=0`, `debug-alloc: leak count=0`, and the
validator no longer reports either function.

(--validate-all still reports the fixture's cancel_while_suspended, the
`p.join_cleanup()` byte copy of a Task parameter: filed as #1990, also
present in da_916.)

* A call through a closure, a fn value or a dyn method unwinds its caller on cancellation (#1985)

#916 gave a direct call of a sync fn that may suspend the await's
cancelled-return check. A call MIR cannot resolve to a declaration (a
closure binding, a fn value, a fn-typed parameter or field, a `dyn`
method) got none: the async caller, cancelled while suspended inside the
callee, resumed past the call and dropped its never-written result.
da_1985_cancel_unwinds_through_indirect_callee.w on the fix-916 stage1:
`resumed=5 batch_drops=5` (all five shapes).

The spec rules where the fact lives. §14.3 INVARIANT 5: "`may_suspend` is
part of callable type information for function pointers, closures, trait
and `dyn` callables, callbacks, and every other indirect-call surface",
and "There are no separate `async` and `sync` function types and no trait
split. Callable values still carry whether invoking them may suspend the
current fiber, because indirect calls must be checkable." §12 (closures):
"There is no second closure type ... The compiler tracks which kind a
value is, as it tracks `may_suspend` (§14)"; §22: a "compiler-carried
callable summary: captures, origin sets, ephemerality, and `may_suspend`
facts are carried across closure, function pointer, trait object, and
wrapper boundaries." So it is Sema's callable summary, not a bit in fn
type identity (that would be the second type, and a user-written
`f: fn(...)` parameter would erase it or color it).

Sema (owner, D65):
- While checking, an identifier naming a callable binding records what it
  holds: a callable `let` (every value it takes: initializer and each
  assignment), a parameter of the fn being checked, or a value Sema
  cannot see through (a closure's parameter or a capture of one, a
  global). A fn declaration's name needs no record.
- settle_may_suspend_facts settles closures and trait default bodies in
  the same least fixpoint as fn declarations, the (trait, method) pairs
  whose `dyn` call may suspend (an impl body or the default body may, or
  an impl is interface-only), and then every call/pipeline node that
  reaches a may-suspend callable: the callee value, a `dyn` method, or a
  callable argument handed to a callee that runs on this fiber.
- A parameter's value is its caller's: at the call site it is unknown, so
  the indirect call is checked; for the enclosing body's own fact the
  caller answers (handing a may-suspend callable over is a call that may
  suspend), so `apply(plain, x)` stays unchecked and `apply(susp, x)` is
  checked. A field, element or call result is opaque: it may. The check
  reads the fiber's cancelled-return flag, which only an unwind sets, so
  an over-approximation costs a runtime read, never behavior.
- The on-demand walk the diagnostics use (E0701/E0702) is unchanged; the
  new facts are read only while settling.

MIR: call_may_cancel_return also asks Sema's call_site_may_suspend for the
call's AST node (including DYN_CALL), then the #916 direct-callee path.

Also: update_string_fields_after_aggregate's `count` is an i32 copy, not a
view of self.body (the installed compiler refused the view once the call
graph grew, as #916 saw for struct_field_type).

After: da_1985 `resumed=0 batch_drops=0 live=0`, `debug-alloc: leak
count=0`; da_916 and da_1986 still green; stage1 checks src/main.w; the
async/cancel corpus (61 fixtures) passes on stage1.

* join_cleanup on an owned Task binding moves it into the cleanup await (#1990)

`t.join_cleanup()` / `p.join_cleanup()` on a Task local or parameter
lowered as `_3 = copy _1` and then cancel(copy _3), cleanup-await(copy _3):
a byte copy of the non-Copy handle into a temporary, consumed from the
copy. lower_task_join_cleanup_call (MirLower) had already cancelled the
binding's scheduled drop, so `_1` was never moved or dropped, and the
ownership validator reported "owned local _1 is still Init at return — no
path drops or moves it (a leak)" for every such function (da_916's
cancel_while_suspended among them).

Route: --debug-alloc with WITH_ALLOC_NO_REUSE=1 reports leak count=0 (the
handle is released at run time, through the copy), and --trace-ownership
finish:_1 showed `_1` Init through both calls and at StorageDead: the
MIR never recorded the transfer, the #1944 class (6dc3d82) on the explicit
join_cleanup path.

Fix: an owned Task binding receiver (a `let` or a parameter whose type is
Task, not a view, field or element) is read in place: cancel observes it
by `copy`, the cleanup await takes it by `move`, as emit_drop_entry's
cleanup does since #1944. Any other receiver keeps its materialized
temporary, which the cleanup await now moves. After: --trace-ownership
shows `bb2.term event=move ... _1=Moved` at the cleanup await;
--validate-all is ok on the new pin and on da_916, da_1985, da_1986.

test/phase/validate_all_join_cleanup_moves_task.w (local, parameter, and
a parameter released on an early-return path): red in all three functions
before, `validate-all: ok` now, leak count=0 under the debug allocator.

* join_cleanup consumes its Task: a later use is a use of a moved value, and the validator reads a moved handle as an error (#1993)

`join_cleanup()` cancels the task, awaits its cleanup and frees its result
buffer. Sema typed it as an observer, so `t.join_cleanup(); t.await` was
accepted and the await produced a value from released storage (run
--debug-alloc: an empty string, leak count=0), and --validate-all said ok
over MIR that read `copy _1` after `move _1`.

Sema (owner, D65): join_cleanup on an owned Task binding marks the
receiver moved (mark_moved_if_consumed) and records the call in
join_cleanup_consumed_calls; a later use is the standard "use of moved
value". MirLower's #1990 receiver choice now reads that set instead of
re-deriving it from the AST and the type. A view, field or element
receiver is not consumed (std's `pending[i].join_cleanup()` is unchanged).

Validator (the silent half): mir_read_of_moved_owned_local rejects a copy
or move of an owned local that every path reaching it already moved out,
when the value is not Copy (drop glue, or a Task/ScopedTask handle; a Copy
enum moved twice in a loop is legal transport, mir_test_constant_cleanup).

It found the same shape in every `.await`: lower_single_await passed one
`move task` operand to the park (FIBER_AWAIT), to the self-cancel's
FIBER_CANCEL, to the cleanup await and to the result read, so the handle
was "moved" up to four times on a path. Each path now reads it and takes
it once: the park and cancel observe (copy); the normal path's result read
and the unwind path's cleanup await take it (move). Codegen loads the
handle the same way for either operand kind.

Tests: test/compile_errors/err_1993_task_used_after_join_cleanup.w (red
before: accepted); test/internals/mir_moved_owned_read_test.w (drop glue
moved then read: refused; not moved: ok; Copy moved then read: ok). The
async/cancel/defer corpus (89 files) and the join_cleanup compile_errors
pass on stage1. Validate-all over that corpus went from 29 moved-read
verdicts to 10; the rest are filed with this commit (select lowering's
moves, the tuple-await unwind that never releases the other tasks, and
the spec-vs-#637 question of a use after `.await`).

* An intrinsic call's tag goes on its own call, set before its terminator (#1985 follow-up, #2011)

lower_intrinsic_call terminated the call, then tagged the intrinsic on
`call_arg_starts.len() - 1`, "the last call created". Since #1985 the
terminator can add the cancelled-return check after a call that reaches a
may-suspend closure, so the tag landed on the check's own call and the
real call stayed untagged: `numbers().map(n => double(n).await)` lowered
as a plain call to the `map` symbol, and the D65 validator (#1639)
refused it ("call to symbol 13435 names no function Sema knows ...
intrinsic=0, args=2"); test/spec/spec_ss14_13_await_inside_iterators.w
failed to build on wave-cancel and ran ok on main (da08b14).
`with analyze ... select:stage=mir,kind=call,line=17` on main showed the
same call with intrinsic=53 (VEC_MAP).

The tag now goes on args_id before terminate, so terminate also sees the
real intrinsic and these calls are back to main's behavior. An intrinsic
loop over a may-suspend closure still ignores a cancellation unwind
inside it: filed as #2019 (Sema already records the fact).

* select await takes each task once per arm path; arm temporaries drop in the arm; no default edge to the join (#2011)

validate-all over the select fixtures (behav_async_cancel,
behav_async_cancel_nested_unwind, behav_async_inferred_task_type,
behav_async_select_cancels_parked_recv/send,
behav_async_select_completed_loser_await, da_async_cancel_drops_live):
"read of _3, which every path reaching it already moved out". The
NK_SELECT_AWAIT lowering (MirLower) passed each task's `move` operand to
the select call, to the winner's FIBER_AWAIT, and to both the loser's
FIBER_CANCEL and its cleanup await (trace-ownership: `call (move _3,
move _1)`, `(move _3, const 1)`, `(move _3)`, `(move _3)`).

Each arm path now takes every task exactly once, the discipline #1993
gave `.await`: the select call and a loser's cancel observe (copy); the
winner's await and each loser's cleanup await take (move).

That exposed two more defects on the same lowering, masked by the first
verdict:
- an arm body's temporaries lived in the select's statement frame and
  dropped at the join on every arm's path ("drop of _20 reaches a path
  where it holds no value"): each arm body is now framed and scoped like
  an if branch (#729/#771).
- the winner switch's default edge went straight to the join, which read
  the result no arm wrote (spec_ss14_9_select_await.w one-arm select,
  red on main too: "read of _4 reaches a path that never initialized
  it"). The select returns an arm index; the default edge is unreachable.

Pin: test/phase/validate_all_select_takes_each_task_once.w (red on main's
stage1, validate-all: ok now).

* A cancelled tuple await releases the tasks it has not reached yet (#2011)

`(left, right).await` lowers as one lower_single_await per task, in order.
When the parent was cancelled while suspended on `left`, the unwind
cancelled and joined `left` only; `right` was still owned and nothing
released it. spec_ss14_async_await.w parallel_tuple_await under
--validate-all: "owned local _3 is still Init at return" (the self-cancel
path reached StorageDead(_3)); masked on main by an earlier verdict.

Debug allocator, failing first:
da_2011_tuple_await_unwind_releases_pending.w (parent cancelled while
awaiting `left` of a two-task tuple) printed `live=2` on the pre-fix
stage1: the parent's unwind left fibers running.

Fix (MirLower): lower_single_await takes the tasks a tuple await has not
awaited yet (`pending_tasks[pending_start..]`), and its unwind block
cancels and joins each before the cancelled return, through
emit_cleanup_awaits_from (the tuple `?` path's existing helper, whose
cancel now observes by copy and whose cleanup await takes the handle).
The plain await passes none. After: `resumed=0 live=0`, `debug-alloc:
leak count=0`, validate-all ok on both files.

* `.await` consumes the task: a later read is a use of a moved value (#2011)

The spec's one statement on it is §22 (concurrency.md:1057):
`t.await // OK: consumes the task`. §14.7's `was_cancelled` example reads
the task before awaiting it, and nothing in the specification reads a
task after `.await`. Sema had the opposite rule, with a comment claiming
§14.7 made the task observable after the await; the lowering moves the
handle on the normal path (#1993), so a post-await read was a read of a
released handle that Sema accepted.

Sema (check_expr NK_AWAIT, single and tuple): an awaited owned Task or
ScopedTask binding (a `let` or a parameter of that type, not a view of
one) is marked moved; a later read reports "use of moved value".
ScopedTask awaits like a Task (§14.11.1) and lowers the same way.

Spec tests that pinned the non-conforming behavior, edited to the spec:
- spec_ss14_7_task_is_done.w: the #637 block's `assert(t2.is_done())`
  after `t2.await` is removed; the pre-await is_done assertions stay.
- spec_ss14_7_task_was_cancelled.w: the post-await `was_cancelled()`
  reads are removed (normal and scoped tasks); the cancelled case reads
  `was_cancelled()` before its await, as §14.7's example does.

New: test/compile_errors/err_2011_task_read_after_await.w
(`t.await` then `t.is_done()`), accepted before, "use of moved value"
now.

* #2011's pre-existing validate-all reds, each at its root (#2011)

Red under --validate-all on main's binary as well (verified on the
pre-#916 release and on da08b14's stage1):

1. errdefer_basic/_ordering/_question_mark: "reset of _3 on a path where
   it was never moved". Not errdefer: every `?` over a user enum. The
   failure path's `_0 = move _3` queued a reset of the carrier, and
   emit_pending_resets_since(0, 0, 0) (MirLower lower_question_mark_value)
   emitted it there but left it queued, so the enclosing statement's flush
   blanked the still-live carrier on the pass path too. The failure path
   now flushes the resets its own moves queued (the marks taken at its
   entry), as an if branch does; the earlier statement's resets are still
   emitted, not consumed. Pin: test/phase/validate_all_question_mark_
   fail_path_reset.w (Copy and moved payloads; errdefer).

2. da_gen_push_pipeline_stages: "drop of _4 after a path reaching it moved
   it out". A closure literal passed by value to a GENERIC_CALL method
   (`g.each(x => ..)` in std.generators' `collect` over a `take` stage)
   kept its statement temp's drop after `move _4`. Main fixed the same
   line while this was in flight (a7a30da..0c09d9f: consumed unless
   Sema's signature borrows the parameter); this commit keeps main's fix
   and adds the pin test/phase/validate_all_generic_call_closure_arg_
   moved.w (`nums() |> take(3) |> collect[Vec]()`, red on da08b14).

3. spec_ss14_22_task_ephemerality: "MIR lowering failed". The file never
   imports Task, and `Vec[Task[i32]].new()` passed Sema: the type-level
   reading of a static call's receiver (resolve_type_level_arg_expr, the
   NK_IDENT and NK_INDEX base arms) reported only a private symbol, never
   the §18.1 import gate an annotation reports, and returned 0 silently,
   so MIR failed on a type Sema never resolved (D65: post-Sema invalid MIR
   is a compiler bug). Both arms now report the gate ("'Task' requires an
   explicit import (§18.1)"). The spec test gains `use std.task.Task`, as
   §18.1 requires and the #1955 sweep did for 189 fixtures; new
   test/compile_errors/err_2011_static_receiver_type_arg_unimported.w.

4. spec_ss07_3a_implicit_context (an implicit `Context` fill copied the
   `with` binding into a consuming parameter: a double free under the
   debug allocator once the arena held an allocation) is ruled by D87
   (#2049, main abf9f95): an implicit fill observes and never consumes.

* Battery lane validate-all-async: the async/cancel/defer corpus under every MIR validator (#2011)

These programs run green while their MIR can drop a moved place, read a
released task handle, or skip a release; only `check --validate-all` sees
that, and no lane ran it over them, so #2011's defects shipped unseen.

- `with test --validate-all` (src/main.w run_test_validate_all): before
  building a test meant to compile (not expect-check-fail /
  expect-build-fail / skipped), run `check --validate-all` with the
  fixture's configuration flags (its dump/trace/explain flags dropped,
  they would print in place of the verdict) and fail the test unless it
  reports `validate-all: ok`. The flag was accepted and silently ignored
  before.
- build.w target `validate-all-async` (in the `test` group, so the
  battery runs it): every test/{behavior,spec,debug_alloc,phase} fixture
  whose text names cancel, join_cleanup, await, `defer:`/`defer {`, or
  `async scope` (136 files) through the release compiler's
  `test --validate-all`.

Red on today's main: its stage1 reports `check --validate-all` failures
on async_tuple_await, behav_async_tuple_await,
behav_async_cancel_await_cleans_children, behav_async_cancel,
behav_async_cancel_nested_unwind, behav_async_inferred_task_type,
behav_async_select, behav_async_select_completed_loser_await (and main
has no `test --validate-all`). On this branch's stage1 135 of 136
pass; the one left is spec_ss07_3a_implicit_context (an implicit `T`
fill double-frees; briefed, needs a ruling). A `defer` substring match
pulled in behav_sema_deferred_diagnostic_files; the token is `defer:`.

* Vec map/filter/fold over a may-suspend closure stop at a cancellation unwind; the caller unwinds and releases the partial result (#2019)

`xs.map(n => f(n).await)` (and filter, fold) is a codegen intrinsic that
calls the closure once per element. When the fiber was cancelled while
the closure was suspended, the closure left by its cancellation unwind
with no value; the loop pushed that never-written value, called the
closure again for the next element, and the caller resumed past the call
with the result. da_2019_cancel_inside_intrinsic_closure.w (parent
cancelled inside a map closure and a fold closure; Item has Drop) on the
pre-fix stage1: "debug-alloc: DOUBLE FREE ... second_drop=drop#struct",
the garbage Items freed.

Sema already records the fact (#1985 call_site_may_suspend: the call
hands over a may-suspend closure); MIR read it only for direct, indirect
and dyn calls (D65: read the owner's fact, never re-derive it).
- MirCore: `mir_intrinsic_invokes_closure` names the eager intrinsics that
  invoke a closure on this fiber (VEC_MAP, VEC_FILTER, VEC_FOLD), and a
  per-call `call_may_cancel` mark (Analysis checks its length with the
  other call tables).
- MirLower: for such a call, call_may_cancel_return is Sema's site fact;
  when it holds, the call is marked and gets the cancelled-return check,
  whose unwind edge drops the call's result: it is valid and holds only
  what earlier invocations produced.
- Codegen: for a marked call, after each closure invocation the loop
  reads the fiber's cancelled-return flag and leaves to its exit before
  using that invocation's value (fold keeps the last accumulator).

After: `resumed=0 item_drops=0 live=0`, `debug-alloc: leak count=0`,
validate-all ok; spec_ss14_13_await_inside_iterators passes.

Not covered here, recorded on #2019: a lazy adapter chain
(`xs.iter().map(f).collect()`), where the closure runs inside the
terminal's *_NEXT calls, still double-frees: Sema's fact sits on the
`map(..)` node, not on the terminal that drives it.

* validate-all lane: a fixture's check keeps only its compile-configuring flags (#2011)

The first cut dropped tokens by '--dump'/'--trace'/'--explain' prefixes:
spec-inventory-check read those literals as unspecified CLI flags, and a
trace flag's value (`main:_1`) survived as a stray argument. The
validate-all check now keeps only the flags that configure compilation,
the set the CLI already names (cli_one_liner_known_flag, less help and
allocator tracing) plus --prelude= and --overflow= values.

* A lazy adapter chain over a may-suspend closure stops at a cancellation unwind, whatever drives it (#2019)

`xs.iter().map(n => f(n).await).collect()` double-freed when the fiber was
cancelled inside the closure: the closure runs inside the terminal's
`next` emitters, and Sema's site fact (#1985) sat on the `map(..)` call
that builds the adapter, not on the call that drives it.
da_2019_cancel_inside_lazy_adapter_chain.w on the pre-fix stage1:
"debug-alloc: DOUBLE FREE ... second_drop=drop#struct".

Sema (owner, D65; §14.3 INVARIANT 5, callable type information): a lazy
adapter that holds a closure is a callable value for the suspension
summary. Its type says whether a closure is in the chain
(iterator_type_holds_callable: Map/Filter/FilterMap/TakeWhile/DropWhile/
ZipWith/FlatMap, at any depth); an adapter Sema sees being built answers
from its parts (`xs.iter()` holds none, `.map(f)` holds `f`); a `let`
binding of one chains its values like a callable `let`; a parameter is
its caller's; anything else is opaque. A method call whose receiver is
such an adapter is a call site that may suspend.

MIR: the driving intrinsics (the ITER_* terminals and the adapter
`*_NEXT` calls) read that fact like the eager Vec ones: the call is
marked, gets the cancelled-return check, and the unwind edge drops its
(valid, partial) result. lower_intrinsic_call_with_receiver_operand tags
the intrinsic before its terminator.

Codegen: the mark is read once where the intrinsic call is emitted
(iter_cancel_checks), so the nested `next` emitters see it: after each
closure invocation an adapter's `next` ends the iteration (None) when the
invocation unwound, and a terminal's own closure (fold, reduce, find,
position, any/all/none, for_each, min_by/max_by, partition) leaves its
loop. A fold's accumulator, passed to the invocation that unwound, is
blanked before the exit (eager Vec fold too).

Fixture (ten parents, each cancelled inside the closure): collect, collect
through a binding, next, fold, map+fold, map+reduce, filter+count, find,
any, for_each: `resumed=0 item_drops=0 live=0`, leak count=0,
validate-all ok; it is in the validate-all-async lane by its text. 42
iterator fixtures pass under `test --validate-all`; stage1 checks
src/main.w.

Not expressible today: `for x in xs.iter().map(f)` is refused by Sema
(§13.5: a MapIter is not a `for` iterable).

* One implementation of the fixes this branch shared with #2049

Rebased onto fix-2049 (#2058), which fixed three of the same defects:
- `join_cleanup` on an owned handle: its lowering (the handle moves into
  the join when this frame owns it) is kept; this branch's receiver
  choice and the Sema call set that fed it are removed. Sema still marks
  the binding moved (#1993).
- a cancelled tuple await releasing the tasks it has not reached:
  its lower_group_await is kept; this branch adds only that the pending
  tasks' cancel observes the handle (copy) before the cleanup await takes
  it, and da_2011_tuple_await_unwind_releases_pending.w.
- `?` blanking a live carrier on the pass path: its fix (the pass-path
  payload moves out; the validator's partially-vacated rule) is kept;
  this branch's fail-path reset flush is removed, and
  validate_all_question_mark_fail_path_reset.w stays as a pin.

* Cancellation: the C backend emits the cancelled-return checks; the no-fiber stubs carry them; a type-level builtin is not a suspend site

#1985 places a cancelled-return check after a call that may suspend through
a callable. Three gaps the battery found:

- emit-C had no lowering for FIBER_IS_CANCELLED / WAIT_CANCELLED /
  SET_CANCELLED_RETURN / WAS_CANCELLED_RETURN: the check fell through to an
  ordinary call of whatever the placeholder callee operand named
  (`_4 = StringBuilder_new__41();` in std/thread.w), and the prelude's C
  did not compile (28 of 30 emit-c-smoke cases). The C backend now calls
  the fiber runtime's functions, which runtime/with_runtime.h declares.
- rt_core's thread entry calls its worker through a callable value, so
  rt_core.o now references with_fiber_wait_cancelled and
  with_fiber_set_cancelled_return; rt/fiber_stubs.w did not define them, so
  a link without the fiber runtime failed (cli-selfhost-edge-tests).
- `transmute[T](f)` was a suspend site because it is handed a callable.
  A type-level builtin never invokes its operand.

---------

Co-authored-by: Eric Hartford <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ownership MIR validator reports violations in 24 passing behavior programs (blocks strict validators, #2043)

1 participant