cli: lower task join operands iteratively
This commit is contained in:
1 parent
8d6792d4f1
commit
b85df6777e
5 files changed
+355
-24
No files matched your search
@@ -519,6 +519,10 @@ The [closing path/lifetime inspection](runtime-value-depth-audit.md#closing-runt
|
||||
|
||||
## Q-061 — Source expression/statement nesting and native recursion
|
||||
|
||||
The paragraphs below record chronological checkpoints. Later repairs supersede
|
||||
earlier failure/OOM findings; the [current inventory](source-expression-depth-audit.md#remaining-work)
|
||||
lists the remaining paths.
|
||||
|
||||
Inspection during Q-059's closing inventory finds native recursion through source expression parsing (`binary`/`unary`), expression queries (`peekType`/`useIn`) and generic expression transformation (`expression`/`walk`). The fixed generic type/instantiation guards do not establish a bound on arbitrary expression or statement nesting. **Unverified:** no expression/statement stack-exhaustion probe has been run in this audit; this entry records inspection risk, not an observed failure or a new acceptance rule.
|
||||
|
||||
Follow-up [expression-depth probes](source-expression-depth-audit.md) now confirm native-stack aborts without JSON diagnostics: 1,024 `not` prefixes fail in lowering; 16,384/65,536 fail earlier in the unary parser. The parser's direct prefix recursion is replaced by explicit continuations with unchanged grammar, AST spans, syntax errors and OOM propagation. Deep parse/format/missing-operand checks pass, but the confirmed lowering failure and other expression/statement paths remain open. The preceding inspection-only statement describes the initial checkpoint, not the current evidence.
|
||||
@@ -551,8 +555,10 @@ The [array-continuation increment](source-expression-depth-audit.md#array-list-a
|
||||
|
||||
The [enum-payload increment](source-expression-depth-audit.md#enum-payload-continuations) preserves lookup/arity-before-arguments, per-payload type/consumption/check order, empty/built-in construction, spans/loans and OOM. Independent shallow/deep/sibling and direct/public allocation tests pass; exact ordinary conformance coverage and final public check/lower parity (1,423/506) pass. The former enum-payload failure at 256 is repaired; nested assert still aborts at 1,024 before and after. Scoped read-only Claude reviews found no semantic defects; 331 core and 66 final supplementary CLI checks pass. Q-061 and Phase 6 remain open, with no semantic or new depth limit change.
|
||||
|
||||
The [boolean builtin increment](source-expression-depth-audit.md#boolean-builtin-operand-continuations) preserves assert/assume arity, non-consuming operands, type/error spans, unsafe registration and emission order, using shared continuations. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 282 focused depth checks pass. Expanded units and 69 supplemental checks pass; read-only Claude core/follow-up reviews found no production defect. Final span/counter unit checks pass. Own/region argument callbacks still abort at 1,024 before and after; remaining callbacks/walks keep Q-061 and Phase 6 open. No new semantic or depth limit changes.
|
||||
The [boolean builtin increment](source-expression-depth-audit.md#boolean-builtin-operand-continuations) preserves assert/assume arity, non-consuming operands, type/error spans, unsafe registration and emission order, using shared continuations. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 282 focused depth checks pass. Expanded units and 69 supplemental checks pass; read-only Claude core/follow-up reviews found no production defect. Final span/counter unit checks pass. At that boolean checkpoint own/region argument callbacks still aborted at 1,024 before and after; remaining callbacks/walks keep Q-061 and Phase 6 open. No new semantic or depth limit changes.
|
||||
|
||||
The [consuming ownership builtin increment](source-expression-depth-audit.md#consuming-ownership-builtin-continuations) preserves own.take/free and region.destroy arity, explicit transfers, type/error priority, emission and OOM separation. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 351 frozen-core CLI checks pass; corrected OOM/expanded units pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews found no production defect. Final `own<bool>` CFG unit comparisons pass. Atomic-new/take pairs and task.join still abort at 1,024. Q-061, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change.
|
||||
The [consuming ownership builtin increment](source-expression-depth-audit.md#consuming-ownership-builtin-continuations) preserves own.take/free and region.destroy arity, explicit transfers, type/error priority, emission and OOM separation. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 351 frozen-core CLI checks pass; corrected OOM/expanded units pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews found no production defect. Final `own<bool>` CFG unit comparisons pass. At that consuming checkpoint atomic-new/take pairs and task.join still aborted at 1,024. Q-061, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change.
|
||||
|
||||
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. Task.join still aborts at 1,024; other callbacks/walks, Q-060 full GC and Phase 6 gates remain open. No semantic/order-default/depth-limit change.
|
||||
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.
|
||||
@@ -792,8 +792,9 @@ Claude's read-only core/follow-up reviews found no production defect
|
||||
`/tmp/aji-consuming-builtin-followup-review.md`). Their fixture gaps were
|
||||
corrected; the final `own<bool>` addition follows the review. Neither reviewer
|
||||
ran tests. Deep mixed errors establish descent and one builtin completion,
|
||||
not completion of every pending call. Separate atomic-new/take pairs accept 16 in both binaries, abort at
|
||||
256 only before, and abort at 1,024 in both; task.join chains still abort at
|
||||
not completion of every pending call. At this consuming checkpoint, separate
|
||||
atomic-new/take pairs accept 16 in both binaries, abort at 256 only before,
|
||||
and abort at 1,024 in both; task.join chains still aborted at
|
||||
1,024 (`consuming-builtin-next-probes.json`). No frame-size explanation is
|
||||
established. Other builtin/place/control and liveness callbacks, Q-060 full GC
|
||||
validation and Phase 6 gates remain open.
|
||||
@@ -841,11 +842,53 @@ uses a function call as its leaf, so signed-literal folding does not erase the
|
||||
first negation.
|
||||
No new whole-expression-suite, arbitrary callback or runtime-depth claim.
|
||||
|
||||
Task.join still aborts at 1,024 before and after
|
||||
At this atomic checkpoint, task.join still aborts at 1,024 before and after
|
||||
(`atomic-operand-next-probes.json`); bounded 16/256 records remain equal.
|
||||
Other builtin/place/control and liveness walks, Q-060 full GC and Phase 6
|
||||
exit gates remain open.
|
||||
|
||||
## Task join operand continuations
|
||||
|
||||
Task.join now uses the shared consuming operand driver (spec 15 §7;
|
||||
spec 04 §33–34): arity precedes children, named linear inputs still require
|
||||
move, the operand receives no type hint, and its task type is checked before
|
||||
emission. Void joins emit without a result; other joins define the same result
|
||||
name/type at the same call span. Tasks remain function-bound; join consumes the
|
||||
handle and returns its loans. Scope/result/Send/effect/verifier/runtime rules,
|
||||
scheduler behavior, AIR, diagnostics, bundle and limits are unchanged.
|
||||
|
||||
`ReferenceTaskJoin` copies the former body and recursively consumes through
|
||||
`ReferenceCalls`; shared leaf/place/type/emission helpers limit independence.
|
||||
Shallow comparisons cover scalar/void/linear/aggregate results, moves,
|
||||
non-values, wrappers and error priority. Raw helper task results containing
|
||||
borrows/tasks/scopes deliberately compare lowering only, not legal programs;
|
||||
spec 04 §33.1 still rejects them. Deep 32,768 helper-call operands and rejected
|
||||
join chains retain exact spans/counts/first errors. Recovering/persistent public
|
||||
OOM sweeps cover scalar/void success and E7003/E7005, with host-error separation
|
||||
and backing cleanup. Work states retain caller-arena lifetime.
|
||||
|
||||
Build/units/format, all 1,793 ordinary conformance cases with exact coverage,
|
||||
frozen public checks/lowerings (1,423/506), lifetime checks (188), related-location
|
||||
checks (409) and CFG-provenance checks (146) pass. Focused CLI passes 522 checks:
|
||||
valid scalar/void joins with call operands and pure/mixed rejected join chains
|
||||
through 65,536, exact formatted positions, source/AIR/fuel checks through 1,024
|
||||
and three schedule seeds through 16. Existing `source/linear/task_loan_join.aji`
|
||||
passes eight schedules; `source/layer7/reject/scope_unjoined.aji` retains E4301.
|
||||
Read-only Claude core/follow-up reviews found no production or fixture defect
|
||||
(`/tmp/aji-task-join-review.md`, `/tmp/aji-task-join-followup-review.md`); stale
|
||||
comment/checkpoint wording is corrected. Neither ran tests. Follow-up inspected
|
||||
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
|
||||
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
|
||||
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.
|
||||
|
||||
## Remaining work
|
||||
|
||||
Follow-up checks accept 16 parenthesized/mixed-call levels but abort
|
||||
@@ -860,7 +903,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 and consuming own/region builtin operands are repaired above. Ordinary atomic operand callbacks are repaired above; task.join still aborts at 1,024 in both binaries. 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 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 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
|
||||
|
||||
@@ -731,8 +731,9 @@ remain unchanged; buffers retain caller-arena lifetime. Corrected OOM and
|
||||
expanded units, all 1,793 ordinary conformance cases, public check/lower parity
|
||||
(1,423/506), targeted linear/nonvalue/inferred-content suites (49/635/302) and
|
||||
351 frozen-core depth checks pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews
|
||||
found no production defect. Final `own<bool>` CFG unit comparisons pass. Atomic-new/take pairs and task.join
|
||||
still abort at 1,024. No semantic/depth-limit change; Q-061, Q-060 full GC
|
||||
found no production defect. Final `own<bool>` CFG unit comparisons pass. At
|
||||
that consuming checkpoint atomic-new/take pairs and task.join still aborted
|
||||
at 1,024. No semantic/depth-limit change; Q-061, Q-060 full GC
|
||||
validation and Phase 6 exit gates remain open.
|
||||
|
||||
### Atomic operand depth increment
|
||||
@@ -747,5 +748,18 @@ depth validation passes 270 checks in two subset runs (57/213), through 65,536
|
||||
for pairs, temporary-loan updates and exact rejections. Mixed chains reach the
|
||||
existing E5101 instruction limit at 65,536; runtime/fuel is checked through
|
||||
1,024. Read-only Claude core/follow-up reviews found no production defect.
|
||||
Task.join still aborts at 1,024. No semantic/order-default/depth-limit change; Q-061, Q-060
|
||||
At that atomic checkpoint task.join still aborted at 1,024. No semantic/order-default/depth-limit change; Q-061, Q-060
|
||||
full GC validation and Phase 6 exit gates remain open.
|
||||
|
||||
### Task join operand depth increment
|
||||
|
||||
The [Q-061 task.join increment](../design/source-expression-depth-audit.md#task-join-operand-continuations)
|
||||
uses consuming continuations, preserving arity/move/type priority, scalar/void
|
||||
emission, spans, loans and host OOM. Build/units/format, all 1,793 ordinary
|
||||
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
|
||||
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.
|
||||
+200
-14
@@ -2424,10 +2424,19 @@ const Lowerer = struct {
|
||||
temps: std.ArrayList([]const u8) = .empty,
|
||||
};
|
||||
const BooleanBuiltin = struct { span: Span, input: ast.Expr, assume: bool };
|
||||
const ConsumingBuiltin = struct { span: Span, input: ast.Expr, operation: enum { take, free, destroy } };
|
||||
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 };
|
||||
|
||||
fn finishConsumingBuiltin(l: *Lowerer, c: *ConsumingBuiltin, o: Value) Error!Value {
|
||||
if (c.operation == .join) {
|
||||
if (o.ty != .task) return l.fail("E7005", c.input.span, "`task.join` takes a `task<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }});
|
||||
const rt = o.ty.task.*;
|
||||
if (rt == .void) {
|
||||
try l.emit(try l.fmt("task.join %{s}", .{o.name}), c.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
return l.def("r", rt, try l.fmt("task.join %{s}", .{o.name}), c.span);
|
||||
}
|
||||
if (c.operation == .take) {
|
||||
if (o.ty != .own) return l.fail("E7005", c.input.span, "`own.take` takes an `own<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(o.ty) }});
|
||||
return l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), c.span);
|
||||
@@ -2502,6 +2511,12 @@ 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.join")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{});
|
||||
const state = try l.arena.create(ConsumingBuiltin);
|
||||
state.* = .{ .span = e.span, .input = args[0], .operation = .join };
|
||||
return .{ .consuming_builtin = state };
|
||||
}
|
||||
if (try l.concurrencyCall(e, p, args)) |v| return .{ .done = v };
|
||||
if (std.mem.startsWith(u8, p, "atomic.")) return switch (try l.prepareAtomic(e, p, args)) {
|
||||
.done => |v| .{ .done = v },
|
||||
@@ -3614,8 +3629,8 @@ 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) }});
|
||||
}
|
||||
|
||||
/// The task and channel operations that are plain calls; null for any
|
||||
/// other path.
|
||||
/// Immediate task/channel/graph dispatch; null for other paths.
|
||||
/// Task.join operands use the shared consuming 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 {
|
||||
@@ -3643,17 +3658,6 @@ const Lowerer = struct {
|
||||
}
|
||||
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.join")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{});
|
||||
const t = try l.consuming(args[0], null);
|
||||
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(t.ty) }});
|
||||
const rt = t.ty.task.*;
|
||||
if (rt == .void) {
|
||||
try l.emit(try l.fmt("task.join %{s}", .{t.name}), e.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
return try l.def("r", rt, try l.fmt("task.join %{s}", .{t.name}), 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");
|
||||
@@ -5438,6 +5442,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.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);
|
||||
if (authority.intrinsicIndex(p)) |ix| {
|
||||
@@ -8861,3 +8866,184 @@ test "public atomic continuation OOM preserves failure separation and arena clea
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Copied pre-continuation task.join operand descent. Other concurrency calls,
|
||||
// leaf/place/type/emission helpers remain shared; this is a shallow lowering oracle.
|
||||
const ReferenceTaskJoin = struct {
|
||||
fn call(l: *Lowerer, e: ast.Expr, args: []const ast.Expr) Error!Value {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{});
|
||||
const t = try ReferenceCalls.consuming(l, args[0], null);
|
||||
if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task<T>`", &.{.{ .name = "found", .value = try l.diagnosticTyText(t.ty) }});
|
||||
const rt = t.ty.task.*;
|
||||
if (rt == .void) {
|
||||
try l.emit(try l.fmt("task.join %{s}", .{t.name}), e.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
return try l.def("r", rt, try l.fmt("task.join %{s}", .{t.name}), e.span);
|
||||
}
|
||||
};
|
||||
|
||||
fn taskJoinTestLowerer(a: Allocator, m: ast.Module, span: Span) !Lowerer {
|
||||
var l = try consumingTestLowerer(a, m, span);
|
||||
const integer: Ty = .{ .int = "i64" };
|
||||
const ti = try l.wrap(.task, integer);
|
||||
const tv = try l.wrap(.task, .void);
|
||||
// Invalid task result forms intentionally test unchanged frontend behavior;
|
||||
// the AIR verifier, not this private lowering fixture, enforces spec 04 §33.1.
|
||||
try l.bindings.appendSlice(a, &.{
|
||||
.{ .name = "ti", .value = "task_integer", .mutable = false, .ty = ti },
|
||||
.{ .name = "tb", .value = "task_boolean", .mutable = false, .ty = try l.wrap(.task, .bool) },
|
||||
.{ .name = "tv", .value = "task_void", .mutable = false, .ty = tv },
|
||||
.{ .name = "to", .value = "task_owner", .mutable = false, .ty = try l.wrap(.task, try l.wrap(.own, integer)) },
|
||||
.{ .name = "tbox", .value = "task_record", .mutable = false, .ty = try l.wrap(.task, l.enumOrStruct("Box", span).?) },
|
||||
.{ .name = "tr", .value = "task_borrow", .mutable = false, .ty = try l.wrap(.task, try l.wrap(.ref, integer)) },
|
||||
.{ .name = "tt", .value = "task_task", .mutable = false, .ty = try l.wrap(.task, ti) },
|
||||
.{ .name = "ts", .value = "task_scope", .mutable = false, .ty = try l.wrap(.task, .scope) },
|
||||
});
|
||||
try l.sigs.put(a, "keep_task", .{ .params = try a.dupe(Ty, &.{ti}), .ret = ti, .air_name = "keep_task", .display_name = "keep_task" });
|
||||
try l.sigs.put(a, "keep_void_task", .{ .params = try a.dupe(Ty, &.{tv}), .ret = tv, .air_name = "keep_void_task", .display_name = "keep_void_task" });
|
||||
return l;
|
||||
}
|
||||
|
||||
fn expectTaskJoinMatches(a: Allocator, m: ast.Module, e: ast.Expr, want: ?Ty) !void {
|
||||
var old = try taskJoinTestLowerer(a, m, e.span);
|
||||
var current = try taskJoinTestLowerer(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 "task join continuations match former moves results CFG and diagnostic priority" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const a = fixture.allocator();
|
||||
const expressions = [_][]const u8{
|
||||
"task.join(move ti)", "task.join(ti)", "task.join(move tb)", "task.join(move tv)",
|
||||
"task.join(move to)", "task.join(move tbox)", "task.join(move tr)", "task.join(move tt)",
|
||||
"task.join(move ts)", "task.join(keep_task(move ti))", "task.join(keep_void_task(move tv))", "task.join(task.join(move tt))",
|
||||
"task.join()", "task.join(unknown, false)", "task.join(unknown)", "task.join(1i64)",
|
||||
"task.join(1)", "task.join(true)", "task.join(move o)", "task.join(o)",
|
||||
"task.join(move n)", "task.join(sc)", "task.join(ref n)", "task.join(mut n)",
|
||||
"task.join(p)", "task.join(stop(b\"xy\"))", "task.join(void_call(b\"xy\"))", "task.join(assert(true))",
|
||||
"task.join(false and bool_id(true))", "task.join(Box { n: 1i64 }.n)", "task.join([true; 2])", "task.join(task.join(move ti))",
|
||||
"task.join(task.join(move tv))",
|
||||
};
|
||||
const forms = [_][]const u8{ "{s}", "task.join({s})", "id({s})", "bool_id({s})", "own.take({s})", "own.free({s})", "not ({s})", "- ({s})", "true and ({s})", "({s}) or false", "[{s}]", "Box {{ n: {s} }}.n", "Choice::some({s})" };
|
||||
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 expectTaskJoinMatches(a, parsed.ok, e, want);
|
||||
};
|
||||
}
|
||||
|
||||
test "deep task join inputs preserve emission spans and innermost failures" {
|
||||
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 join = try consumingTestCallee(a, "task.join");
|
||||
for ([_]bool{ false, true }) |void_result| {
|
||||
const keep: ast.Expr = .{ .span = unaryTestSpan(70_003), .kind = .{ .name = if (void_result) "keep_void_task" else "keep_task" } };
|
||||
var e: ast.Expr = .{ .span = unaryTestSpan(90_000), .kind = .{ .move = if (void_result) "tv" else "ti" } };
|
||||
for (0..count) |i| {
|
||||
const args = try a.dupe(ast.Expr, &.{e});
|
||||
e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = &keep, .type_arg = null, .args = args } } };
|
||||
}
|
||||
const span = unaryTestSpan(100_000);
|
||||
const root: ast.Expr = .{ .span = span, .kind = .{ .call = .{ .callee = join, .type_arg = null, .args = try a.dupe(ast.Expr, &.{e}) } } };
|
||||
var l = try taskJoinTestLowerer(a, m, span);
|
||||
const counter = l.counter;
|
||||
const v = try l.expr(root, null);
|
||||
try std.testing.expect(v.ty.eql(if (void_result) .void else .{ .int = "i64" }));
|
||||
const insts = l.blocks.items[0].insts.items;
|
||||
try std.testing.expectEqual(count + 1, insts.len);
|
||||
try std.testing.expectEqual(counter + count + @intFromBool(!void_result), l.counter);
|
||||
for (insts[0..count], 0..) |inst, i| try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(@intCast(i + 1))), inst.span);
|
||||
try std.testing.expectEqualDeep(@as(?Span, span), insts[count].span);
|
||||
if (void_result) {
|
||||
try std.testing.expectEqualStrings("", v.name);
|
||||
try std.testing.expect(std.mem.startsWith(u8, insts[count].text, "task.join %"));
|
||||
} else try std.testing.expect(std.mem.indexOf(u8, insts[count].text, " = task.join %") != null);
|
||||
}
|
||||
for (0..3) |kind| {
|
||||
const leaf_span = unaryTestSpan(90_000);
|
||||
var e: ast.Expr = .{ .span = leaf_span, .kind = switch (kind) {
|
||||
0 => .{ .name = "unknown" },
|
||||
1 => .{ .boolean = true },
|
||||
else => .{ .move = "ti" },
|
||||
} };
|
||||
for (0..count) |i| {
|
||||
const args = try a.dupe(ast.Expr, &.{e});
|
||||
e = .{ .span = unaryTestSpan(@intCast(i + 1)), .kind = .{ .call = .{ .callee = join, .type_arg = null, .args = args } } };
|
||||
}
|
||||
var l = try taskJoinTestLowerer(a, m, e.span);
|
||||
const counter = l.counter;
|
||||
try std.testing.expectError(error.Lower, l.expr(e, null));
|
||||
try std.testing.expectEqualStrings(if (kind == 0) "E7002" else "E7005", l.problem.?.code);
|
||||
try std.testing.expectEqualDeep(if (kind == 2) unaryTestSpan(1) else leaf_span, l.problem.?.span);
|
||||
try std.testing.expectEqual(@as(usize, if (kind == 0) 0 else 1), l.blocks.items[0].insts.items.len);
|
||||
try std.testing.expectEqual(counter + @intFromBool(kind != 0), l.counter);
|
||||
if (kind == 2) try std.testing.expectEqualDeep(@as(?Span, unaryTestSpan(1)), l.blocks.items[0].insts.items[0].span);
|
||||
}
|
||||
}
|
||||
|
||||
test "public task join continuation OOM remains a host error and frees backing" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const programs = [_][]const u8{
|
||||
"module oom\nfn work() -> i64 effects [] { 42i64 }\nfn main() -> i64 effects [task.spawn] { scope s { let r = task.join(task.spawn(s, work)); return r; } }\n",
|
||||
"module oom\nfn work() -> void effects [] {}\nfn main() -> void effects [task.spawn] { scope s { let t = task.spawn(s, work); task.join(move t); } }\n",
|
||||
"module oom\nfn main() -> i64 effects [] { return task.join(true); }\n",
|
||||
"module oom\nfn work() -> i64 effects [] { 42i64 }\nfn main() -> i64 effects [task.spawn] { scope s { let t = task.spawn(s, work); return task.join(t); } }\n",
|
||||
"module oom\nfn main() -> i64 effects [] { return task.join(unknown, false); }\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(if (index == 3) "E7003" 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -873,6 +873,88 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory:
|
||||
assert cli(command, path, code=1) == expected
|
||||
print(f'atomic operand error priority: {leaf}', flush=True)
|
||||
|
||||
# task.join shares consuming operand continuations. Valid tasks retain their
|
||||
# scope, result/void emission and scheduling; malformed deep joins reject.
|
||||
for void_result in (False, True):
|
||||
for depth in (0, 1, 16, 256, 1024, 16384, 65536):
|
||||
path = root / f'task-join-operand-{void_result}-{depth}.aji'
|
||||
program = 'module depth\nfn id(x: i64) -> i64 effects [] { x }\n'
|
||||
if void_result:
|
||||
program += 'fn work(x: i64) -> void effects [] {}\n'
|
||||
program += 'fn main() -> ' + ('void' if void_result else 'i64') + ' effects [task.spawn] { scope s { '
|
||||
expression = 'task.join(task.spawn(s, ' + ('work' if void_result else 'id') + ', ' + 'id(' * depth + '42i64' + ')' * depth + '))'
|
||||
program += (expression + ';' if void_result else 'let r = ' + expression + '; return r;') + ' } }\n'
|
||||
path.write_text(program)
|
||||
assert cli('check', path) == 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 ', b'task.join ')) for line in lowered.splitlines())
|
||||
assert actual == depth + 7 + int(void_result), (void_result, depth, actual)
|
||||
if depth <= 1024:
|
||||
fuel = 2 * depth + 7
|
||||
options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', fuel)
|
||||
result = cli('run', path, *options)
|
||||
assert json.loads(result) == {'status': 'returned', 'value': None if void_result else 42, 'schedule': {'seed': 7, 'quantum': 1, 'choices': 1}}, result
|
||||
assert json.loads(cli('run', path, '--quantum', 1, '--schedule-seed', 7, '--fuel', fuel - 1, code=5)) == {'status': 'limit_exceeded', 'kind': 'fuel', 'limit': fuel - 1, 'steps': fuel - 1, 'schedule': {'seed': 7, 'quantum': 1, 'choices': 1}}
|
||||
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)
|
||||
assert json.loads(seeded) == {'status': 'returned', 'value': None if void_result else 42, 'schedule': {'seed': seed, 'quantum': 1, 'choices': 1}}
|
||||
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
|
||||
assert cli('check', formatted) == b''
|
||||
assert cli('lower', formatted) == lowered
|
||||
print(f'task join accepted operand depth: void={void_result}', flush=True)
|
||||
|
||||
import re
|
||||
for leaf, code, extra in (
|
||||
('unknown', 'E7002', {}),
|
||||
('true', 'E7005', {'found': 'bool'}),
|
||||
('1', 'E7007', {}),
|
||||
('task.join()', 'E7005', {}),
|
||||
('task.join(unknown, false)', 'E7005', {}),
|
||||
('task.cancelled()', 'E7005', {'found': 'bool'}),
|
||||
('t', 'E7003', {'suggestion': 'move t'}),
|
||||
('move t', 'E7005', {'found': 'i64'}),
|
||||
):
|
||||
for mixed in (False, True):
|
||||
prefix = 'module depth\nfn id(x: i64) -> i64 effects [] { x }\nfn work() -> i64 effects [] { 42i64 }\nfn main() -> i64 effects [task.spawn] { scope s { let t = task.spawn(s, work); return '
|
||||
opening, closing = ('id(task.join(', '))') if mixed else ('task.join(', ')')
|
||||
for depth in (16, 1024, 65536):
|
||||
expression = opening * depth + leaf + closing * depth
|
||||
path = root / f'task-join-reject-{code}-{len(leaf)}-{mixed}-{depth}.aji'
|
||||
path.write_text(prefix + expression + '; } }\n')
|
||||
expected = cli('check', path, code=1)
|
||||
error = json.loads(expected)
|
||||
at = len(opening) * (depth - int(leaf == 'move t'))
|
||||
assert (error['code'], error['file'], error['line'], error['col']) == (code, str(path), 4, len(prefix.split('\n')[-1]) + at + 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 == 'move t':
|
||||
pos = text.rfind('id(' if mixed else 'task.join(')
|
||||
elif leaf == 't':
|
||||
pos = list(re.finditer(r'(?<![A-Za-z0-9_])t(?![A-Za-z0-9_])', text))[-1].start()
|
||||
else:
|
||||
pos = text.index(leaf)
|
||||
assert (formatted_error['code'], formatted_error['file'], formatted_error['line'], formatted_error['col']) == (code, str(formatted), text[:pos].count('\n') + 1, pos - text.rfind('\n', 0, pos)), formatted_error
|
||||
for key, value in extra.items():
|
||||
assert formatted_error[key] == value, formatted_error
|
||||
print(f'task join rejection depth: {leaf}', flush=True)
|
||||
|
||||
# Block/control callbacks remain native. Their existing shallow/deeper
|
||||
# syntax must retain its capacity while expression dispatch is moved out
|
||||
# of the native stack, including explicit-return callback re-entry.
|
||||
|
||||
Reference in new issue
Block a user