From c5d0d09a81d2bbb072f750b639023d8034376ca5 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 11 Oct 2026 17:34:08 +0300 Subject: [PATCH] cli: lower task spawn arguments iteratively --- docs/design/open-questions.md | 4 +- docs/design/source-expression-depth-audit.md | 67 ++++- docs/plan/phase-6-source-language.md | 21 +- src/frontend/lower.zig | 275 +++++++++++++++++-- tests/hosted/source_expression_depth.py | 106 +++++++ 5 files changed, 442 insertions(+), 31 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index cf11470..3edf949 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -561,4 +561,6 @@ The [consuming ownership builtin increment](source-expression-depth-audit.md#con The [atomic operand increment](source-expression-depth-audit.md#atomic-operand-continuations) preserves new/take and ordinary update operand rules, cell/ordering/type priority, temporary loans, emission and host OOM separation through shared continuations. Build/units/format, all 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 33/635/234 targeted checks pass. Focused depth validation passes 270 checks in two subset runs (57/213), including exact rejections and temporary-loan updates through 65,536; mixed chains reach the existing E5101 instruction limit, with runtime/fuel checked through 1,024. Read-only Claude core/follow-up reviews found no production defect. At that checkpoint task.join still aborted at 1,024; other callbacks/walks, Q-060 full GC and Phase 6 gates remain open. No semantic/order-default/depth-limit change. -The [task.join increment](source-expression-depth-audit.md#task-join-operand-continuations) preserves consuming/type/result/void rules, spans, loans and host OOM through the shared driver. Build/units/format, exact ordinary conformance coverage, public check/lower parity, lifetime/related/CFG checks and 522 focused CLI checks pass, with valid call operands and exact rejections through 65,536 and runtime/fuel through 1,024. Read-only Claude core/follow-up reviews found no production or fixture defect. A valid 16-level alternating join/spawn probe still aborts at 256 before/after, confirming the next spawn-argument callback. Other callbacks/walks, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change. +The [task.join increment](source-expression-depth-audit.md#task-join-operand-continuations) preserves consuming/type/result/void rules, spans, loans and host OOM through the shared driver. Build/units/format, exact ordinary conformance coverage, public check/lower parity, lifetime/related/CFG checks and 522 focused CLI checks pass, with valid call operands and exact rejections through 65,536 and runtime/fuel through 1,024. Read-only Claude core/follow-up reviews found no production or fixture defect. At that checkpoint a valid 16-level alternating join/spawn probe still aborted at 256 before/after, confirming the next spawn-argument callback. Other callbacks/walks, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change. + +The [spawn increment](source-expression-depth-audit.md#task-spawn-argument-continuations) preserves scope/worker/arity/per-argument priority, moves, bound loans, emission and host OOM with shared continuations. Build/units/format, exact ordinary conformance coverage, public check/lower parity and lifetime/related/CFG/static-worker checks pass. The focused gate completes 497 distinct CLI checks across split runs, with original/formatted lower parity through 65,536, scalar/pair check through 65,536, mixed check through 32,768 then existing E5101, runtime/source-AIR/fuel through 1,024 and rejected positions through 65,536. Read-only Claude core/final follow-up reviews found no production or fixture defect, within their recorded scope. Nested mutex.make/take still aborts at 256/1,024 before/after and is next. Graph/place/control/liveness and multi-result callbacks, Q-060 full GC and Phase 6 exit gates remain open; no semantic/depth-limit change. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index d4a7439..ae37f8a 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -337,8 +337,8 @@ fresh caller-arena nodes. Entries never point into copied union payloads or queue entries. Type/pattern/binding handling, source spans and generic Copy transfer flags retain their original policy. Calls have explicit stages: transform type_arg, resolve/check the callee, transform it, then process -arguments in order, with the existing static-worker exception for task.spawn's -second argument. Constructors resolve their named type before their fields. +arguments in order, with the existing substitution of a bound static function +in task.spawn's second argument. Constructors resolve their named type before their fields. Nested instantiation/type queries keep their unchanged depth-64 guards, instance/key limits and public error policy; no expression-depth limit is added. @@ -881,7 +881,7 @@ current lower.zig and the diff, not full CLI/docs or evidence artifacts; its file tools could not open the core report in /tmp. The initial unit fixture aliased its destination while copying a child; child copying now precedes assignment. -The next finite probe alternates join/spawn in one scope, with scalar arguments +At this join checkpoint, the next probe alternates join/spawn in one scope, with scalar arguments and one live child at a time. It accepts 16 levels but aborts at 256/1,024 in both frozen binaries (`task-join-next-probes.json`). Spawn-argument callbacks, multi-result task.join_cancel inputs and other graph/place/control/liveness @@ -889,6 +889,61 @@ walks retain native callback entry with depth unverified beyond these probes. Q-060 full GC and Phase 6 exit gates remain open. No whole-frontend or arbitrary runtime-depth claim. +## Task spawn argument continuations + +Task.spawn arguments now share the expression driver (spec 15 §7; +spec 04 §33–35). Scope identity and worker signature are saved before children. +Minimum arity, scope, named worker, borrowed-result rejection and full arity +retain their priority. Each argument then checks inline borrow/bytes, explicit +consumption, hinted expression type and parameter type before appending its +name. Zero and multiple arguments emit only after completion. Bound loans +remain lent until join; scope lifetime, Send/result/effect/verifier/runtime/ +scheduler rules and explicit transfers are unchanged. No diagnostic, feature, +AIR/format/bundle/limit or ownership/concurrency rule changes. + +Copied `ReferenceTaskSpawn` consumes through the former recursive oracle; +shared leaf/place/type/emission helpers limit independence. Shallow forms +cover zero/multiple/qualified workers, bound borrows, owners, scope shadowing, +CFG/non-values and early/late errors. Deep 32,768 scalar/pair chains retain +scope/name/span/order facts; late unknown/inline-borrow failures emit only +preceding constants. Recovering/persistent public OOM sweeps cover two valid +baselines and E7002/E7003/E7005/E7006 without partial AIR or false diagnostics, +with actual backing cleanup. Work states/buffers retain caller-arena lifetime. + +Build/units/format, all 1,793 ordinary conformance cases with exact coverage, +frozen public checks/lowerings (1,423/506), lifetime/related/CFG/static-worker +checks (188/409/146/25) pass. The focused CLI gate completes 497 distinct checks +across split runs: the first process ended with exit 143 after three accepted +and five rejected families (329 completed checks); a terminal-success follow-up +covers the other seven rejected families (168). No cause for that interruption +is established. Scalar/pair chains check through 65,536; mixed chains check +through 32,768 and reach existing E5101 at 65,536 (`found: 327685` main +instructions; the whole module has 327686). All three lower and format through +65,536 with exact AIR parity; a second check on formatted accepted input +is limited to 1,024. Quantum-one seed-7 run/fuel/source-AIR checks reach +1,024; seeds 0/1 additionally reach 16. Twelve rejected families check exact +code/fields/positions and identical check/lower/run/report/explore JSON through +65,536, including formatted positions. These are task.spawn checks, not a +whole-expression-suite or arbitrary control/liveness/runtime-depth claim. + +Valid bound-loan/join examples remain covered by +`source/linear/task_loan_join.aji` and the source/AIR pair +`buffers/task_loan_join`; unjoined scope exit remains E4301 in +`source/layer7/reject/scope_unjoined.aji`. Claude's read-only +core review found no production defect; its formatted-leaf and count concerns +are now covered by executed CLI checks. Pending buffers remain arena-owned +until arena destruction, rather than being physically freed by list deinit. +The test-only unchecked field and reserved worker name were corrected; +all 473 shallow forms parse. Read-only final follow-up found no production +or fixture defect, relying on the core review plus the final diff, driver and +generic-worker code; it did not re-audit every consumer or run tests. Its exit, +formatted-check bound and schedule-seed wording suggestions are integrated. + +The next finite probe, nested `mutex.take(mutex.make(...))`, accepts at 16 +but aborts at 256/1,024 with no JSON before and after this spawn repair. +`task-spawn-next-probes.json` and matching raw stdout/stderr retain the evidence. +Mutex operands are the next confirmed callback repair; other walks remain open. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -903,7 +958,7 @@ includes a confirmed lowerer failure and inspection-only risks: | Production path | Evidence and next scope | |---|---| | Parser `ifExpr`, block/statement and match/arm expression entry | Native callback re-entry remains. Bounded block/if regression probes above pass; arbitrary and alternating control/statement depth is unverified. | -| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field, array and enum-payload descent are repaired above. Boolean, consuming own/region, atomic and task.join operands are repaired above. Alternating join/spawn still aborts at 256 in both binaries. Spawn arguments and multi-result task.join_cancel inputs retain native callback entry. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. | +| Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field, array and enum-payload descent are repaired above. Boolean, consuming own/region, atomic, task.join and spawn operands are repaired above. Mutex make/take callbacks independently abort at 256/1,024 before and after the spawn repair. Multi-result task.join_cancel inputs and other graph/place/control callbacks retain native entry. Other callback depth remains unverified; include alternating scalar/non-scalar expressions. | | Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, `blockAssigns`/`stmtAssigns`/`exprAssigns`, match/select helpers) | Recursive AST walks inspected; audit their callers and finite deep inputs separately. | The formatter's expression-marking traversal already uses a worklist, as @@ -912,5 +967,5 @@ claim every listed callback fails, or that all other paths have been cleared. Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is independent. The five reviewed increments now have a scoped external review; the host-OOM follow-up and intermediate repairs have no separate review. -The struct/value-field, array and enum-payload increments have the scoped -reviews recorded above. +The struct/value-field, array, enum-payload, task.join and task.spawn +increments have the scoped reviews recorded above. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index d6ee417..1407e2d 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -760,6 +760,25 @@ conformance cases, public check/lower parity (1,423/506), lifetime/related/CFG checks (188/409/146) and 522 focused CLI checks pass. Valid scalar/void call operands and rejected join chains reach 65,536; runtime/fuel reaches 1,024. Read-only Claude core/follow-up reviews found no production or fixture defect. -Alternating join/spawn still aborts at 256 before/after; its +At that join checkpoint alternating join/spawn still aborts at 256 before/after; its argument callbacks and other walks keep Q-061 open. No semantic/depth-limit change; Q-060 full GC and Phase 6 exit gates remain open. + +### Task spawn argument depth increment + +The [Q-061 spawn increment](../design/source-expression-depth-audit.md#task-spawn-argument-continuations) +preserves scope/worker/arity and per-argument checking, explicit consumption, +bound loans, CFG/emission and host OOM through shared continuations. +Build/units/format, exact ordinary conformance coverage, public check/lower +parity and lifetime/related/CFG/static-worker checks pass. The focused gate +completes 497 distinct CLI checks across an interrupted first run and a +terminal-success remaining-family run. Scalar/pair checks and all-family +lower/fmt AIR parity reach 65,536; mixed checks reach 32,768, then existing +E5101 at 65,536. Runtime/source-AIR/fuel checks reach 1,024; rejected family +positions reach 65,536; formatted accepted checks are repeated only through +1,024. Runtime uses quantum one/seed 7, with extra seeds 0/1 through 16. +Read-only Claude core/final follow-up reviews found no production or fixture +defect within their recorded scope. Nested mutex.make/take still aborts at +256/1,024 before/after and is next. Remaining graph/place/control/liveness and +multi-result callbacks keep Q-061 open; no semantic/depth-limit change. Q-060 +full GC and Phase 6 exit gates remain open. diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index 7acd618..17d651f 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -2018,6 +2018,7 @@ const Lowerer = struct { .boolean_builtin => |c| l.operandExprPrepared(e, null, .{ .boolean_builtin = c }), .consuming_builtin => |c| l.operandExprPrepared(e, null, .{ .consuming_builtin = c }), .atomic => |c| l.operandExprPrepared(e, null, .{ .atomic = c }), + .spawn => |c| l.operandExprPrepared(e, null, .{ .spawn = c }), }, .if_expr => |x| return l.ifExpr(e.span, x.*, want), .block => |b| { @@ -2063,6 +2064,7 @@ const Lowerer = struct { boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin, atomic: *AtomicOperand, + spawn_argument: *SpawnCall, }; var pending: std.ArrayList(Frame) = .empty; defer pending.deinit(l.arena); @@ -2090,6 +2092,18 @@ const Lowerer = struct { want = pt; continue; }, + .spawn => |c| { + prepared = .none; + if (c.index == c.args.len) break try l.finishSpawn(c); + const a = c.args[c.index]; + // Task loans are bound until join, never temporary call borrows. + if (a.kind == .borrow or a.kind == .bytes) return l.invalid(.invalid_borrow, a.span, "a borrow lent to a task stays lent until the join: bind it first (`mut part = …;`) and pass the name", &.{}); + try l.checkConsumingName(a); + try pending.append(l.arena, .{ .spawn_argument = c }); + e = a; + want = c.sig.params[c.index]; + continue; + }, .structure => |c| { prepared = .none; if (c.index == c.fields.len) break try l.finishStruct(c); @@ -2213,6 +2227,7 @@ const Lowerer = struct { .boolean_builtin => |c| prepared = .{ .boolean_builtin = c }, .consuming_builtin => |c| prepared = .{ .consuming_builtin = c }, .atomic => |c| prepared = .{ .atomic = c }, + .spawn => |c| prepared = .{ .spawn = c }, }, .variant => |x| switch (try l.prepareVariant(e, x.@"enum", x.name, &.{})) { .done => |v| break v, @@ -2314,6 +2329,14 @@ const Lowerer = struct { want = null; continue :evaluate; }, + .spawn_argument => |c| { + try l.checkOperandTy(c.args[c.index].span, v.ty, c.sig.params[c.index]); + try c.names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (c.index == 0) "" else ", ", v.name })); + c.index += 1; + prepared = .{ .spawn = c }; + want = null; + continue :evaluate; + }, .struct_field => |c| { try l.checkOperandTy(c.current_span, v.ty, c.current_ty); try c.names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (c.index == 0) "" else ", ", v.name })); @@ -2411,6 +2434,7 @@ const Lowerer = struct { boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin, atomic: *AtomicOperand, + spawn: *SpawnCall, }; const OrdinaryCall = struct { @@ -2425,7 +2449,7 @@ const Lowerer = struct { }; const BooleanBuiltin = struct { span: Span, input: ast.Expr, assume: bool }; const ConsumingBuiltin = struct { span: Span, input: ast.Expr, operation: enum { take, free, destroy, join } }; - const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin, atomic: *AtomicOperand }; + const CallDispatch = union(enum) { done: Value, ordinary: *OrdinaryCall, variant: *VariantConstruction, boolean_builtin: *BooleanBuiltin, consuming_builtin: *ConsumingBuiltin, atomic: *AtomicOperand, spawn: *SpawnCall }; fn finishConsumingBuiltin(l: *Lowerer, c: *ConsumingBuiltin, o: Value) Error!Value { if (c.operation == .join) { @@ -2456,6 +2480,7 @@ const Lowerer = struct { .boolean_builtin => |c| l.operandExprPrepared(e, null, .{ .boolean_builtin = c }), .consuming_builtin => |c| l.operandExprPrepared(e, null, .{ .consuming_builtin = c }), .atomic => |c| l.operandExprPrepared(e, null, .{ .atomic = c }), + .spawn => |c| l.operandExprPrepared(e, null, .{ .spawn = c }), }; } @@ -2511,6 +2536,7 @@ const Lowerer = struct { try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); return .{ .done = .{ .name = "", .ty = .void } }; } + if (std.mem.eql(u8, p, "task.spawn")) return .{ .spawn = try l.prepareSpawn(e, args) }; if (std.mem.eql(u8, p, "task.join")) { if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{}); const state = try l.arena.create(ConsumingBuiltin); @@ -3629,35 +3655,42 @@ const Lowerer = struct { return l.fail("E7005", a.span, try l.fmt("{s} is expected here", .{what}), &.{.{ .name = "found", .value = try l.diagnosticTyText(b.ty) }}); } + const SpawnCall = struct { + span: Span, + scope_name: []const u8, + sig: FnSig, + args: []const ast.Expr, + index: usize = 0, + names: std.ArrayList(u8) = .empty, + }; + + fn prepareSpawn(l: *Lowerer, e: ast.Expr, args: []const ast.Expr) Error!*SpawnCall { + if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{}); + const sb = try l.bindingOf(args[0], "a task scope"); + if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = try l.diagnosticTyText(sb.ty) }}); + const scope_name = sb.value; + const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{}); + const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname); + if (sig.ret.isBorrow()) return l.invalid(.invalid_borrow_return, e.span, "a spawned function cannot return a borrow (reserved: task_borrow_returns)", &.{.{ .name = "function", .value = sig.display_name }}); + const fargs = args[2..]; + if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } }); + const state = try l.arena.create(SpawnCall); + state.* = .{ .span = e.span, .scope_name = scope_name, .sig = sig, .args = fargs }; + return state; + } + + fn finishSpawn(l: *Lowerer, c: *const SpawnCall) Error!Value { + return l.def("t", try l.wrap(.task, c.sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ c.scope_name, c.sig.air_name, c.names.items }), c.span); + } + /// Immediate task/channel/graph dispatch; null for other paths. - /// Task.join operands use the shared consuming driver instead. + /// Spawn/join operands use the shared expression driver instead. fn concurrencyCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!?Value { const eq = struct { fn f(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } }.f; - if (eq(p, "task.spawn")) { - if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{}); - const sb = try l.bindingOf(args[0], "a task scope"); - if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = try l.diagnosticTyText(sb.ty) }}); - const scope_name = sb.value; - const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{}); - const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname); - if (sig.ret.isBorrow()) return l.invalid(.invalid_borrow_return, e.span, "a spawned function cannot return a borrow (reserved: task_borrow_returns)", &.{.{ .name = "function", .value = sig.display_name }}); - const fargs = args[2..]; - if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } }); - var names: std.ArrayList(u8) = .empty; - for (fargs, sig.params, 0..) |a, pt, i| { - // A borrow is lent to the task until its join, so it is bound - // by the program, not made for the call (spec 15 §7). - if (a.kind == .borrow or a.kind == .bytes) return l.invalid(.invalid_borrow, a.span, "a borrow lent to a task stays lent until the join: bind it first (`mut part = …;`) and pass the name", &.{}); - const v = try l.consuming(a, pt); - try l.checkOperandTy(a.span, v.ty, pt); - try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); - } - return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, sig.air_name, names.items }), e.span); - } if (eq(p, "task.cancel")) { if (args.len != 1) return l.fail("E7005", e.span, "`task.cancel` takes one task, by name", &.{}); const b = try l.bindingOf(args[0], "a task"); @@ -5442,6 +5475,7 @@ const ReferenceCalls = struct { try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); return .{ .name = "", .ty = .void }; } + if (std.mem.eql(u8, p, "task.spawn")) return ReferenceTaskSpawn.call(l, e, args); if (std.mem.eql(u8, p, "task.join")) return ReferenceTaskJoin.call(l, e, args); if (try l.concurrencyCall(e, p, args)) |v| return v; if (std.mem.startsWith(u8, p, "atomic.")) return ReferenceAtomics.call(l, e, p, args); @@ -9047,3 +9081,198 @@ test "public task join continuation OOM remains a host error and frees backing" } } } + +// Copied pre-continuation spawn argument descent; leaf/place/type/emission helpers remain shared. +const ReferenceTaskSpawn = struct { + fn call(l: *Lowerer, e: ast.Expr, args: []const ast.Expr) Error!Value { + if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{}); + const sb = try l.bindingOf(args[0], "a task scope"); + if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = try l.diagnosticTyText(sb.ty) }}); + const scope_name = sb.value; + const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{}); + const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname); + if (sig.ret.isBorrow()) return l.invalid(.invalid_borrow_return, e.span, "a spawned function cannot return a borrow (reserved: task_borrow_returns)", &.{.{ .name = "function", .value = sig.display_name }}); + const fargs = args[2..]; + if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } }); + var names: std.ArrayList(u8) = .empty; + for (fargs, sig.params, 0..) |a, pt, i| { + // A borrow is lent to the task until its join, so it is bound + // by the program, not made for the call (spec 15 §7). + if (a.kind == .borrow or a.kind == .bytes) return l.invalid(.invalid_borrow, a.span, "a borrow lent to a task stays lent until the join: bind it first (`mut part = …;`) and pass the name", &.{}); + const v = try ReferenceCalls.consuming(l, a, pt); + try l.checkOperandTy(a.span, v.ty, pt); + try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); + } + return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, sig.air_name, names.items }), e.span); + } +}; + +fn taskSpawnTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer { + var l = try consumingTestLowerer(a, m, span); + const integer: Ty = .{ .int = "i64" }; + try l.sigs.put(a, "no_args", .{ .params = &.{}, .ret = integer, .air_name = "no_args", .display_name = "no_args" }); + try l.sigs.put(a, "empty", .{ .params = &.{}, .ret = .void, .air_name = "empty", .display_name = "empty" }); + try l.sigs.put(a, "write", .{ .params = try a.dupe(Ty, &.{try l.wrap(.mut, integer)}), .ret = integer, .air_name = "write", .display_name = "write" }); + try l.bindings.append(a, .{ .name = "pm", .value = "exclusive_loan", .mutable = false, .ty = try l.wrap(.mut, integer), .kind = .borrow }); + try l.borrow_parents.put(a, "exclusive_loan", "input"); + return l; +} + +fn expectTaskSpawnMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty) !void { + var old = try taskSpawnTestLowerer(a, m, e.span); + var current = try taskSpawnTestLowerer(a, m, e.span); + const expected = ReferenceOperands.expr(&old, e, want); + const actual = current.expr(e, want); + if (expected) |v| { + const result = try actual; + try std.testing.expectEqualStrings(v.name, result.name); + try std.testing.expect(v.ty.eql(result.ty)); + } else |err| try std.testing.expectError(err, actual); + try std.testing.expectEqualDeep(old.problem, current.problem); + try std.testing.expectEqualDeep(old.unimpl, current.unimpl); + try std.testing.expectEqualDeep(old.blocks.items, current.blocks.items); + try std.testing.expectEqualDeep(old.allocs.items, current.allocs.items); + try std.testing.expectEqualDeep(old.constants.items, current.constants.items); + try std.testing.expectEqualDeep(old.bindings.items, current.bindings.items); + try std.testing.expectEqual(old.counter, current.counter); + try std.testing.expectEqual(old.cur, current.cur); + try std.testing.expectEqualDeep(old.uses, current.uses); + try std.testing.expectEqual(old.linear_enabled, current.linear_enabled); + try std.testing.expectEqual(old.in_constant, current.in_constant); + try std.testing.expectEqual(old.borrow_parents.count(), current.borrow_parents.count()); + var parents = old.borrow_parents.iterator(); + while (parents.next()) |item| try std.testing.expectEqualStrings(item.value_ptr.*, current.borrow_parents.get(item.key_ptr.*).?); +} + +test "spawn continuations match former scope worker argument loan CFG and error priority" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const expressions = [_][]const u8{ + "task.spawn(sc, id, 1)", "task.spawn(sc, id, n)", "task.spawn(sc, no_args)", "task.spawn(sc, empty)", + "task.spawn(sc, pair, id(1i64), id(n))", "task.spawn(sc, bool_id, true and bool_id(false))", "task.spawn(sc, read, p)", "task.spawn(sc, write, pm)", + "task.spawn(sc, take, move o)", "task.spawn(sc, box_id, Box { n: 1i64 })", "task.spawn(sc, ns.id, n)", "task.spawn(sc, std.test.id, 1i64)", + "task.spawn(sc, id, { let sc: i64 = 3i64; id(sc) })", "task.spawn(sc, id, if true { 1i64 } else { 2i64 })", "task.spawn()", "task.spawn(unknown)", + "task.spawn(unknown, missing, true)", "task.spawn(n, unknown, true)", "task.spawn(1i64, id, true)", "task.spawn(move sc, id, 1i64)", + "task.spawn(sc, id(n), unknown)", "task.spawn(sc, missing, unknown)", "task.spawn(sc, retained)", "task.spawn(sc, retained, unknown, true)", + "task.spawn(sc, id)", "task.spawn(sc, id, unknown, false)", "task.spawn(sc, id, unknown)", "task.spawn(sc, id, true)", + "task.spawn(sc, id, ref unknown)", "task.spawn(sc, id, b\"xy\")", "task.spawn(sc, read, ref n)", "task.spawn(sc, write, mut n)", + "task.spawn(sc, bytes, b\"xy\")", "task.spawn(sc, take, o)", "task.spawn(sc, take, move n)", "task.spawn(sc, id, stop(b\"xy\"))", + "task.spawn(sc, id, void_call(b\"xy\"))", "task.spawn(sc, pair, unknown, ref unknown)", "task.spawn(sc, pair, true, ref unknown)", "task.spawn(sc, pair, id(n), ref unknown)", + "task.spawn(sc, pair, id(n), b\"xy\")", "task.spawn(sc, pair, id(n), unknown)", "task.spawn(sc, id, task.join(task.spawn(sc, id, id(n))))", + }; + const forms = [_][]const u8{ "{s}", "task.join({s})", "task.spawn(sc, id, {s})", "id({s})", "own.free({s})", "not ({s})", "- ({s})", "true and ({s})", "({s}) or false", "[{s}]", "Box {{ n: {s} }}.n" }; + inline for (forms) |form| for (expressions) |text| { + const parsed = try parse_mod.parse(a, try std.fmt.allocPrint(a, "{s}fn f() -> void effects [] {{ return {s}; }}", .{ fieldTestDeclarations, try std.fmt.allocPrint(a, form, .{text}) })); + try std.testing.expect(parsed == .ok); + const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + for ([_]?Ty{ null, .bool, .{ .int = "i64" } }) |want| try expectTaskSpawnMatches(a, parsed.ok, e, want); + }; +} + +test "deep alternating spawn join preserves left to right arguments scope names and spans" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const m = (try parse_mod.parse(a, fieldTestDeclarations)).ok; + const count = 32_768; + const spawn = try consumingTestCallee(a, "task.spawn"); + const join = try consumingTestCallee(a, "task.join"); + const scope: ast.Expr = .{ .span = unaryTestSpan(70_003), .kind = .{ .name = "sc" } }; + const identity: ast.Expr = .{ .span = unaryTestSpan(70_004), .kind = .{ .name = "id" } }; + const pair: ast.Expr = .{ .span = unaryTestSpan(70_005), .kind = .{ .name = "pair" } }; + for ([_]bool{ false, true }) |multiple| { + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .int = .{ .text = "1i64" } } }; + for (0..count) |i| { + const first: ast.Expr = .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .int = .{ .text = "2i64" } } }; + const args = if (multiple) try a.dupe(ast.Expr, &.{ scope, pair, first, e }) else try a.dupe(ast.Expr, &.{ scope, identity, e }); + const started: ast.Expr = .{ .span = unaryTestSpan(@intCast(2 * i + 1)), .kind = .{ .call = .{ .callee = spawn, .type_arg = null, .args = args } } }; + const joined = try a.dupe(ast.Expr, &.{started}); + e = .{ .span = unaryTestSpan(@intCast(2 * i + 2)), .kind = .{ .call = .{ .callee = join, .type_arg = null, .args = joined } } }; + } + var l = try taskSpawnTestLowerer(a, m, e.span); + const counter = l.counter; + const v = try l.expr(e, null); + try std.testing.expect(v.ty.eql(.{ .int = "i64" })); + const prefix: usize = if (multiple) count else 0; + const insts = l.blocks.items[0].insts.items; + try std.testing.expectEqual(prefix + 2 * count + 1, insts.len); + try std.testing.expectEqual(counter + insts.len, l.counter); + if (multiple) for (insts[0..count], 0..) |inst, i| { + try std.testing.expect(std.mem.indexOf(u8, inst.text, " = const.i64 2") != null); + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(100_000 + count - i - 1))), inst.span); + }; + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(90_000)), insts[prefix].span); + for (0..count) |i| { + try std.testing.expect(std.mem.indexOf(u8, insts[prefix + 2 * i + 1].text, if (multiple) " = task.spawn %scope_input, @pair(" else " = task.spawn %scope_input, @id(") != null); + try std.testing.expect(std.mem.indexOf(u8, insts[prefix + 2 * i + 2].text, " = task.join %") != null); + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(2 * i + 1))), insts[prefix + 2 * i + 1].span); + try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(2 * i + 2))), insts[prefix + 2 * i + 2].span); + } + } + for ([_]bool{ false, true }) |inline_borrow| { + const place: ast.Expr = .{ .span = unaryTestSpan(90_001), .kind = .{ .name = "n" } }; + var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = if (inline_borrow) .{ .borrow = .{ .mutable = false, .unchecked = false, .place = &place } } else .{ .name = "unknown" } }; + for (0..count) |i| { + const first: ast.Expr = .{ .span = unaryTestSpan(@intCast(100_000 + i)), .kind = .{ .int = .{ .text = "2i64" } } }; + const args = try a.dupe(ast.Expr, &.{ scope, pair, first, e }); + const started: ast.Expr = .{ .span = unaryTestSpan(@intCast(2 * i + 1)), .kind = .{ .call = .{ .callee = spawn, .type_arg = null, .args = args } } }; + const joined = try a.dupe(ast.Expr, &.{started}); + e = .{ .span = unaryTestSpan(@intCast(2 * i + 2)), .kind = .{ .call = .{ .callee = join, .type_arg = null, .args = joined } } }; + } + var l = try taskSpawnTestLowerer(a, m, e.span); + const counter = l.counter; + try std.testing.expectError(error.Lower, l.expr(e, null)); + try std.testing.expectEqualStrings(if (inline_borrow) "E7006" else "E7002", l.problem.?.code); + try std.testing.expectEqualDeep(unaryTestSpan(90_000), l.problem.?.span); + try std.testing.expectEqual(count, l.blocks.items[0].insts.items.len); + try std.testing.expectEqual(counter + count, l.counter); + } +} + +test "public spawn continuations propagate OOM without partial AIR and free backing" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const programs = [_][]const u8{ + "module oom\nfn id(x: i64) -> i64 effects [] { x }\nfn main() -> i64 effects [task.spawn] { scope s { return task.join(task.spawn(s, id, task.join(task.spawn(s, id, 42i64)))); } }\n", + "module oom\nfn read(p: ref) -> i64 effects [] { *p }\nfn main() -> i64 effects [task.spawn] { var n: i64 = 42i64; { ref p = n; scope s { let t = task.spawn(s, read, p); let r = task.join(move t); } } return n; }\n", + "module oom\nfn id(x: i64) -> i64 effects [] { x }\nfn main() -> void effects [task.spawn] { scope s { let t = task.spawn(s, id, unknown); } }\n", + "module oom\nfn take(x: own) -> i64 effects [] { own.take(move x) }\nfn main(heap: cap) -> void effects [mem.alloc, task.spawn] { let x = own.new(1i64, heap) or trap; scope s { let t = task.spawn(s, take, x); } }\n", + "module oom\nfn pair(a: i64, b: i64) -> i64 effects [] { a + b }\nfn main() -> void effects [task.spawn] { var n: i64 = 1i64; scope s { let t = task.spawn(s, pair, n, ref n); } }\n", + "module oom\nfn id(x: i64) -> i64 effects [] { x }\nfn main() -> void effects [task.spawn] { scope s { let t = task.spawn(s, id, unknown, true); } }\n", + }; + for (programs, 0..) |program, index| { + const parsed = try parse_mod.parse(fixture.allocator(), program); + try std.testing.expect(parsed == .ok); + const baseline = try lower(fixture.allocator(), parsed.ok); + if (index < 2) try std.testing.expect(baseline == .ok) else { + try std.testing.expect(baseline == .err); + try std.testing.expectEqualStrings(switch (index) { + 2 => "E7002", + 3 => "E7003", + 4 => "E7006", + else => "E7005", + }, baseline.err.code); + } + for ([_]bool{ false, true }) |persistent| { + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 1024); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_at }); + var output: std.heap.ArenaAllocator = .init(if (persistent) failing.allocator() else std.testing.allocator); + var recovering: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at }; + const result = lower(if (persistent) output.allocator() else recovering.allocator(), parsed.ok); + output.deinit(); + if (persistent) try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + const failed = if (persistent) failing.has_induced_failure else recovering.failed; + if (failed) { + try std.testing.expectError(error.OutOfMemory, result); + if (!persistent) try std.testing.expectEqual(fail_at + 1, recovering.attempts); + } else { + try std.testing.expect(std.meta.activeTag(try result) == std.meta.activeTag(baseline)); + break; + } + } + } + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index d612f11..af477ee 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -955,6 +955,112 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: assert formatted_error[key] == value, formatted_error print(f'task join rejection depth: {leaf}', flush=True) + # Spawn arguments preserve per-argument checking and loans until join. + # These valid chains keep at most one child outstanding in the same scope. + for kind in ('spawn-join', 'spawn-pair', 'spawn-mixed'): + for depth in (0, 1, 16, 256, 1024, 16384, 32768, 65536): + if depth == 32768 and kind != 'spawn-mixed': + continue + path = root / f'{kind}-{depth}.aji' + if kind == 'spawn-pair': + worker = 'fn pair(a: i64, b: i64) -> i64 effects [] { b }\n' + expression = 'task.join(task.spawn(s, pair, 2i64, ' * depth + '42i64' + '))' * depth + instructions, fuel, value = 3 * depth + 5, 4 * depth + 4, 42 + elif kind == 'spawn-mixed': + worker = 'fn id(x: i64) -> i64 effects [] { x }\n' + expression = 'task.join(task.spawn(s, id, id(- ' * depth + 'id(42i64)' + ')))' * depth + instructions, fuel, value = 5 * depth + 6, 7 * depth + 6, 42 if depth % 2 == 0 else -42 + else: + worker = 'fn id(x: i64) -> i64 effects [] { x }\n' + expression = 'task.join(task.spawn(s, id, ' * depth + '42i64' + '))' * depth + instructions, fuel, value = 2 * depth + 5, 3 * depth + 4, 42 + path.write_text('module depth\n' + worker + 'fn main() -> i64 effects [task.spawn] { scope s { return ' + expression + '; } }\n') + limited = kind == 'spawn-mixed' and depth == 65536 + checked = cli('check', path, code=1 if limited else 0) + if limited: + error = json.loads(checked) + assert (error['code'], error['limit'], error['max'], error['found']) == ('E5101', 'instructions per function', 262144, 327685), error + for command in ('run', 'report', 'explore'): + assert cli(command, path, code=1) == checked + else: + assert checked == b'' + lowered = cli('lower', path) + actual = sum((line.lstrip().startswith(b'%') and b' = ' in line) or line.strip().startswith((b'ret', b'task.scope.end ')) for line in lowered.splitlines()) + assert actual == instructions, (kind, depth, actual, instructions) + if depth <= 1024: + options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel) + result = cli('run', path, *options) + record = {'status': 'returned', 'value': value} + exhausted = {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1} + if depth: + schedule = {'seed': 7, 'quantum': 1, 'choices': depth} + record['schedule'] = schedule + exhausted['schedule'] = schedule + assert json.loads(result) == record, result + assert json.loads(cli('run', path, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == exhausted + air = path.with_suffix('.air') + air.write_bytes(lowered) + assert cli('run', air, *options) == result + if depth <= 16: + for seed in (0, 1): + options = ('--quantum', 1, '--schedule-seed', seed, '--fuel', fuel) + seeded = cli('run', path, *options) + if depth: + record['schedule'] = {'seed': seed, 'quantum': 1, 'choices': depth} + assert json.loads(seeded) == record + assert cli('run', air, *options) == seeded + formatted = path.with_suffix('.formatted.aji') + output = cli('fmt', path) + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + # Exact AIR parity avoids a second expensive deep verifier walk. + assert cli('lower', formatted) == lowered + if depth <= 1024: + assert cli('check', formatted) == b'' + print(f'spawn argument accepted depth: {kind}', flush=True) + + for leaf, code, offset, extra in ( + ('unknown', 'E7002', 0, {}), + ('true', 'E7005', 0, {'found': 'bool'}), + ('ref n', 'E7006', 0, {'reason': 'invalid_borrow'}), + ('b"xy"', 'E7006', 0, {'reason': 'invalid_borrow'}), + ('task.spawn(s, id)', 'E7005', 0, {'expected': '1', 'found': '0'}), + ('task.spawn(s, missing, unknown)', 'E7002', len('task.spawn(s, '), {}), + ('task.spawn(n, missing, unknown)', 'E7005', len('task.spawn('), {'found': 'i64'}), + ('task.spawn(s, retained)', 'E7006', 0, {'reason': 'invalid_borrow_return'}), + ('task.spawn(s, pair, unknown, ref n)', 'E7002', len('task.spawn(s, pair, '), {}), + ('task.spawn(s, pair, id(1i64), ref n)', 'E7006', len('task.spawn(s, pair, id(1i64), '), {'reason': 'invalid_borrow'}), + ('t', 'E7003', 0, {'suggestion': 'move t'}), + ('move t', 'E7005', 0, {'expected': 'i64', 'found': 'task'}), + ): + for depth in (16, 1024, 65536): + prefix = 'module depth\nfn id(x: i64) -> i64 effects [] { x }\nfn pair(a: i64, b: i64) -> i64 effects [] { b }\nfn retained(p: ref) -> ref from p effects [] { p }\nfn main() -> i64 effects [task.spawn] { var n: i64 = 1i64; scope s { let t = task.spawn(s, id, 0i64); return ' + opening = 'task.join(task.spawn(s, id, ' + expression = opening * depth + leaf + '))' * depth + path = root / f'spawn-argument-reject-{code}-{len(leaf)}-{offset}-{depth}.aji' + path.write_text(prefix + expression + '; } }\n') + expected = cli('check', path, code=1) + error = json.loads(expected) + assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 5, len(prefix.split('\n')[-1]) + len(opening) * depth + offset + 1), error + for key, value in extra.items(): + assert error[key] == value, error + for command in ('lower', 'run', 'report', 'explore'): + assert cli(command, path, code=1) == expected + formatted = path.with_suffix('.formatted.aji') + output = cli('fmt', path) + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + formatted_error = json.loads(cli('check', formatted, code=1)) + text = output.decode() + if leaf == 't': + pos = list(re.finditer(r'(?