Files
aji/docs/design/source-expression-depth-audit.md
T

291 lines
17 KiB
Markdown

# Source expression depth audit
This non-normative audit tracks Q-061 independently of the resolved compiler
type-traversal inventory (Q-059). It uses finite generated/public source only;
it does not set an expression-depth acceptance limit or report model outcomes.
## Confirmed baseline failures
On the Debug CLI preceding the unary-parser repair (code at `fb80413`),
`fn main() -> bool effects [] { return not … false; }` accepts 16 prefixes.
At 1,024 prefixes, checking aborts in `Lowerer.expr`, with repeated `.not`
operand calls. At 16,384 and 65,536 prefixes, it aborts earlier in
`Parser.unary`. Each failing check exits by signal (observed return code -6)
without a stdout diagnostic. These are observed native-stack failures, not
language rejection rules. Stderr reports a segmentation fault at the recursive
entry/operand call, followed by repeated native frames of that function.
The ignored evidence is under `.zig-cache/contract-gate/type-depth/`:
`expression-depth-before.json`, `prefix-not-*.stdout` and `prefix-not-*.stderr`.
No wall-clock timeout terminates these probes.
## Unary parser continuations
The parser records `-`, `not`, `*` and inline borrow prefixes in an explicit
pending list, parses the terminal operand and rebuilds the nodes inside out.
`move` remains a terminal name form. A borrow still parses its operand through
unary only when the next token is `*`; otherwise it uses postfix directly.
This preserves the existing place boundary, rather than admitting new spellings
such as `ref -value`, `mut not value` or `ref move value`.
Each rebuilt node retains its own start and the final operand end, including
comments, newlines and file provenance. AST node order, operator association,
postfix precedence and syntax failure positions are unchanged. Pending metadata
is host compiler storage and is released on completion/error. Allocation failure
still propagates OutOfMemory; no partial AST escapes, new code or depth rejection
is introduced. AIR, verifier ownership/borrow rules, runtime evaluation, fuel,
effects and source/reference bundle text are unchanged.
An independent shallow copy of the old unary derivation checks 448 combinations
of prefixes and successful/failed operands. It compares complete ASTs, failure
records, token cursors and last-consumed positions. Its shared postfix parser is
outside that oracle's scope. Separate tests parse 32,768 mixed prefix groups
including borrowed dereferences, inspect every node/span iteratively and check a
missing operand at the deepest position. A failing-allocator test covers all
arena backing requests in a longer chain, including pending-list growth and
output construction, and verifies complete release.
Syntax-only CLI probes format 1,024/16,384/65,536 `not` prefixes successfully
and idempotently, retaining every prefix. Missing-operand checks at
16,384/65,536 prefixes emit exactly one E7001 with independently computed
line/column and expected/found fields. These do **not** establish successful
deep lowering or execution. The permanent `source_grammar.py` suite includes
those formatting/diagnostic regressions at all three depths, with the same
syntax diagnostic across check/lower/run/report/explore/fmt.
Validation: build, units and format checks pass; all 1,793 ordinary conformance
cases pass with exact unique corpus coverage. Old/new public source checks and
successful lowerings are byte-identical (1,423/506). The grammar integration
suite passes 312 checks; the formatter suite passes 6,078 checks over 1,469 files
(1,414 parsed, 55 syntax-error fixtures, 782 identical successful AIR outputs).
These are compiler regressions, not a model-capability measurement or full GC
validation.
## Unary lowering and addressability continuations
Direct `.not`, `.neg`, `.deref` and `.cast` operand descent now records explicit
lowering continuations. Negative zero constants still precede their operands;
loads, boolean operations, checked subtraction and casts resume afterwards.
The special negative-literal magnitude rule remains separate, including
`-128i8` and the overflow from negating that value. Cast target validation still
precedes operand lowering; narrowing advice, atomic-load E4202 and operand
type/failure positions are unchanged. `peekType` skips a leading negation spine
without allocating; other recursive query paths are outside this repair.
The first intermediate full 16,384-prefix check exposes another native-stack
failure, in the preliminary `markExpr` walk, before the new expression handler
is reached. Its record/frame excerpt is retained as
`source-address-mark-before.json`. Addressability now uses a separate worklist
for blocks, statements, expressions, roots and pending sibling slices. It
preserves root-bound-before-base order, left/right and statement/tail order,
callee/argument order and the final split_at root visit. The old skipped select
and lock-place inputs stay skipped; storage policy is not extended here.
Both worklists are host metadata, released on error/completion; finished values
and addressability facts retain their caller-arena lifetime. OOM propagates
without a source diagnostic or public partial AIR. The verifier's load/borrow,
initialization and atomic-access rules, runtime operations, ownership, lexical
ends, effects and source/AIR formats are unchanged. Borrowed scalar reads remain
valid; slice/array dereference and implicit atomic reads retain their existing
E7006/E4202 failures. No acceptance limit, code, feature or bundle text is added.
An independent old unary derivation checks 3,072 shallow context combinations,
including divergent operands, signed boundaries, borrowed/atomic values and
invalid targets. It compares values, complete instruction/span/constant records,
names/counters and diagnostics. It shares the unchanged non-unary handlers and
query implementation, so it is not an independent oracle for those paths.
Separate 32,768-node cases inspect inside-out boolean/cast spans, outside-in
negative zeros and inside-out subtractions, and inner dereference rejection.
The allocation test fails every arena backing request and compares complete
emitted instruction prefixes, no output publication and full arena release.
An independent old addressability walk compares 17 shallow fixtures, including
roots/bounds, branches, aggregates, calls, loops, scopes and skipped inputs.
32,768 mixed expression/block levels and every failing backing allocation are
tested separately. Full generated checks/lowerings now accept 65,536 typed
scalar boolean/negative/cast nodes, with independently counted instructions;
direct malformed dereference spines reject E7005 at their inner position.
These do not prove that every expression/query path is bounded.
The permanent `source_expression_depth.py` CI suite checks deep full lowering,
exact instruction counts, source/AIR and hosted results, fuel boundaries and
signed-minimum overflow. Baseline/current runtime records match exactly in 47
deterministic/hosted pairs. Full ordinary conformance passes 1,793 unique cases
with exact corpus coverage; units and Zig format checks pass. Q-060's full
per-step validation remains separate.
Final CLI validation passes 114 expression-depth checks, 635 non-value operand
checks, 33 atomic-access checks, 312 grammar checks and the existing 6,078
formatter checks. All 1,423 public source checks and 506 successful lowerings
retain byte-identical old/new results with fixed baseline/current executables.
## Expression type-query continuations
On `dd73b84`, `( * … 1i64 ) as i64` at 16,384 dereferences aborts in
`peekType`, before the expected ordinary type error. Its stdout is empty and
stderr repeats dereference-query frames. The retained baseline evidence is
`unary-cast-deref-query-16384.json/.stdout/.stderr`; the repaired check returns
one E7005 at line 2, column 32,805 without stderr
(`expression-query-repaired-cli.json`).
Expression and built-in result queries now share an explicit continuation
worklist. It preserves left-before-right fallback, first-known match arm,
first array element, branch-tail policy, field/len classification, callee
priority and built-in argument/borrow handling. Negation, shift, block and
if-tail queries use loop transitions. Queries remain best-effort: type-output
OOM already returned unknown, and continuation-allocation OOM now does too,
without a diagnostic. This adds host metadata requests; allocation counts and
failure-index classifications are not claimed identical. Pending storage is
released, and type nodes keep their caller-arena lifetime.
The query's callee callbacks also exposed recursive `expressionPath` and
bounded `dotted`. Both now walk field chains iteratively. `expressionPath`
allocates one complete string rather than every ancestor prefix; direct names
and invalid roots allocate nothing. Successful path bytes, the existing
64-byte built-in lookup buffer and null-result policy are retained. Partial
buffer contents on null are private and need not match the old implementation.
An independent copy of the old expression/built-in descent compares 703
shallow combinations. Name/signature/type lookup and callee path helpers are
shared, so this oracle does not independently validate those helpers. Separate
tests cover 32,768 structural/built-in expression levels, 16,384 fallback
levels, 65,536 callee fields and allocation-error cleanup without diagnostics
or emitted instructions. The permanent CLI suite adds cast/dereference and
deep unknown-callee rejection across check/lower/run/report/explore. These
helper fixtures do not establish arbitrary deep source acceptance.
Final build/units/Zig format checks and all 1,793 ordinary conformance cases
pass with exact unique corpus coverage (`source-expression-query-conformance.jsonl`
and its audit). The expression-depth/non-value/atomic-access suites pass
139/635/33 checks; formatter integration passes 6,078 checks. Fixed old/new
executables retain exact exit/stdout/stderr on all 1,423 public source checks
and 506 successful lowerings. These are compiler regressions, not completed
per-step GC validation or a model-capability measurement.
No normative rule, source/AIR format, feature, error code, bundle text,
ownership/runtime behavior or acceptance limit changes. Q-061's other paths
remain open; this increment has no fresh Claude review.
## Expected-use query continuations
After the preceding query repair, `let n = 1; return - … n;` in an i64 function accepts
16 and 1,024 negations, but at 16,384 aborts in `useIn` while inferring the
unsuffixed binding's type. The failing check returns -6 with empty stdout and
repeated `useIn` frames. Evidence is retained as `inferred-use-depth-before.json`
and `inferred-use-neg-16384.stdout/.stderr`. This confirms the next expected-use
query failure independently of the repaired `peekType` path.
`useIn`, `usesInStmt` and `usesInBlock` now share an explicit request worklist.
It retains first-known use, left/right and call-argument order, condition/then/
else order, statement-before-tail order, return hints and cast hint removal.
Comparison/shift right-hand hints and the second for bound are queried only
after the earlier use fails. The outer `inferUses` rest cursor and top-level
let rebinding barrier are unchanged; nested blocks and skipped expression/
statement kinds retain their original policy. No new inference is introduced.
The requests are host metadata, released on success/error; hint type nodes
retain their caller-arena lifetime. As in other best-effort type queries,
metadata OOM produces unknown without a diagnostic or instructions. This adds
allocation requests and does not promise identical failure-index outcomes.
Plain unary descent is a loop without work allocations. Runtime memory,
ownership, fuel and verifier rules are unchanged; no normative rule, format,
feature, error code, source/reference bundle or acceptance limit is added.
The independent old expected-use descent and outer cursor compare 967 shallow
expression, statement/block and two-scope combinations. Name/signature/type
queries are shared and outside that oracle's independence. Separate tests cover
32,768 unary and mixed branch/call groups, 32,768 nested statement blocks,
deferred-hint allocation traps and every worklist backing-allocation failure.
They check complete cleanup and no query diagnostic/output; helper fixtures do
not establish arbitrary deep source acceptance.
The baseline 16,384-negation source now accepts without stdout/stderr
(`inferred-use-depth-repaired.json`). Permanent CLI tests check inferred
negations through 65,536, exact instruction counts and fuel/source/AIR/hosted
results through 1,024. Cast-cleared context still returns E7007 at the unsuffixed
initializer through 65,536 negations across check/lower/run/report/explore.
Final build/unit/format checks and all 1,793 ordinary conformance cases pass
with exact unique corpus coverage (`source-use-query-conformance.jsonl` and its
audit). The permanent expression-depth suite passes 186 checks; non-value and
independent-error suites pass 635/234 checks. These do not complete Q-060's
per-step GC validation or measure model capability.
Fixed pre/post executables retain exact exit/stdout/stderr for all 1,423 public
source checks and 506 successful lowerings (`source-use-query-cli-compatibility.json`).
## Binary operand lowering continuations
The preceding follow-up probes accept 16 levels but abort at
1,024, with empty stdout, in three independent paths: a left-associated
`1i64 + … + 1i64` chain in `Lowerer.binary`; nested parentheses in the parser's
primary/postfix expression path; and a unary chain in a specialized generic
function body in `generics.expression`/`walk`. Evidence is retained as
`post-use-query-depth-probes.json` and `post-use-*.stdout/.stderr`. These are
observed native failures, not normative depth rejections.
Unary and binary scalar operands now share one continuation driver. Eager
operators retain operand-type selection, left lowering/check before right,
post-operand operator validation and exact instruction/span/name order. This
also removes native re-entry on alternating unary/binary trees. Non-operand
handlers remain outside this repair.
Boolean continuations preserve short-circuit lowering: validate left, emit
the short constant, create RHS/join blocks and the join parameter, branch,
lower/check right, branch to the stored join and resume there. Runtime still
evaluates right only when needed; both operands are lowered and type checked.
Negative zero order, signed-minimum literal handling, cast checks, atomic
diagnostics and iref identity rules remain unchanged. Host worklist OOM
propagates without a query diagnostic or public partial AIR; its metadata is
released while generated values retain their caller-arena lifetime. Allocation
counts/failure-index outcomes are not promised identical.
The independent old scalar derivation now covers binary rules as well as
unary descent. It compares 6,048 binary/wrapper/context combinations, in
addition to the existing unary cases: values/errors, blocks, parameters,
instructions/spans, counter, current block and features. Name/type/query and
non-operand handlers are shared, outside this oracle's independence. Separate
tests cover 32,768 left/right arithmetic nodes, 32,768 alternating groups,
16,384 boolean/unary groups in both orientations, and every backing-allocation
failure on numeric and boolean fixtures with exact complete block prefixes and
full cleanup. These helper tests do not assert arbitrary source acceptance.
The old 1,024-addition source now accepts, as do full arithmetic checks and
lowerings through 65,536 operations. Boolean chains accept at 1,024; at 16,384
both and/or now reach the existing E5101 block limit (spec 08 §7), with
`limit: blocks per function`, `max: 16384`, `found: 32769`, rather than aborting.
The raw source checks are retained in `binary-lowering-repaired-depth.json`
and `binary-repaired-*.stdout/.stderr`. The permanent CLI suite checks exact
instruction counts, fuel boundaries, values/profiles/source-to-AIR parity,
the block-limit refusal, and skipped/executed RHS division traps. Trap source
locations are checked separately; plain AIR has no source map.
Build/unit/Zig format checks and all 1,793 ordinary conformance cases pass
with exact unique corpus coverage (`source-binary-lowering-conformance.jsonl`
and its audit). The permanent expression-depth suite passes 360 checks.
Non-value/independent-error CLI suites pass 635/234 checks;
fixed pre/post executables retain exact exit/stdout/stderr on all 1,423 public
source checks and 506 successful lowerings
(`source-binary-lowering-cli-compatibility.json`). These do not establish full
GC validation or a model-capability result.
No normative rule, source/AIR format, feature, error code, bundle text, runtime
instruction, ownership rule or acceptance limit changes. Q-061 remains open.
## Remaining work
Current follow-up checks still abort with empty stdout at 1,024 parenthesized
levels and 1,024 generic unary levels (`binary-followup-depth-probes.json` and
`binary-followup-*.stdout/.stderr`). Parenthesized parsing and generic expression
transformation require separate repairs.
Inspection of the generic transformation also finds a recursive qualified-path
callback (`generics.path`). Its deep full-source behavior is unverified here;
it belongs in that repair's callback inventory, rather than Q-059's type scope.
Other expression/block handlers and their complete depth behavior need further
auditing. The formatter's expression-marking traversal already uses a worklist,
as inspected and exercised by the deep syntax-only probes. Q-061 and Phase 6
remain open; Q-060's unfinished full GC validation is independent. No fresh
Claude review covers these expression increments.