cli: index loop-exit edges and reuse negative After queries; fix loop-exit diagnostics (Q-063, Q-064)

This commit is contained in:
dev committed 2026-10-14 18:26:44 +03:00
1 parent 2fb882c704
commit 2d750a0525
15 files changed
+1016 -76

No files matched your search

@@ -118,3 +118,252 @@ instruction, agent bundle or benchmark claim changes. Residual AIR verification
growth for while/match is visible but not assigned a specific cause by these
profiles. Q-063 remains open for implementation decisions and those remaining
measurements; Q-060's composite closure and the B1 gate on P7/P8 are independent.
## First optimization: loop-exit reference index (2026-10-14)
`Lowerer.reaches` now looks up a function-local index instead of scanning all
previously emitted instructions. `emit` indexes references to generated
`after_N` exit names. Keys borrow the instruction text's arena lifetime; the
index resets for each function. It reserves both index and instruction
capacity before publishing either, so metadata OOM cannot leave a phantom
reference or an emitted instruction absent from the index. Queries allocate
nothing. Metadata grows with distinct referenced exit names; arena storage is
released with the caller's arena, not immediately at the function reset.
Inspection and frozen-CLI probes found that the old predicate also counted
calls to functions with colliding names, including references emitted before
the exit block existed, and used only the first substring match per
instruction. These are preserved exactly and logged as
[Q-064](open-questions.md#q-064--loop-exit-reference-search-confuses-function-and-block-names).
Consequently this increment indexes the old reference predicate rather than
changing it to actual CFG-edge reachability. References from unreachable
blocks still count. The frozen control oracle retains the independent old
full scan; it does not share the new query.
Paired Debug measurements use the frozen and changed binaries on CPU 0 with
inherited process affinity, alternating before/after order, two warmups per
binary/shape, and seven measured repetitions per version. All source and AIR
bytes match. Medians for `lower`, at 512 levels:
| Shape | Before | After | Before / after |
|---|---|---|---|
| scope (control) | 0.0927 s | 0.0952 s | 0.97× |
| while | 0.6291 s | 0.1956 s | 3.22× |
| loop | 0.2169 s | 0.1174 s | 1.85× |
| while_live | 1.2246 s | 0.6800 s | 1.80× |
The control is 2.7% slower in this batch; the index has emission overhead and
these finite timings do not establish a statistical bound on that overhead.
Earlier unpinned batches had substantial control timing variation, so they are
not used for the quoted speedups. This removes the repeated full-function
search, not liveness rescans or AIR verification costs, and does not establish
linear whole-pipeline complexity.
Validation:
- `zig build test` exits 0 with the production change and the first two new
index tests; the final additional function-isolation/public-OOM cases and
both index tests pass in a focused `zig test --test-filter 'loop exit'`
run (8/8 including import-discovery tests). The emission test injects every
allocation failure before publication. Public lowering tests inject each
recovering and persistent allocation failure and check full arena release.
- All 1,799 current conformance files pass, terminal exit 0, with exact unique
coverage, no missing/extra/duplicate or nonpassing records.
- All 1,429 public source conformance files plus four function-name collision
probes retain exact `check` and `lower` exit/stdout/stderr: 2,866 comparisons.
- Six finite loop/shield examples, in source and AIR, retain exact run records
and exits at fourteen fuel values: 168 old/new pairs. Valid nested loops
with `break` still return normally; a divergent loop followed by a statement
still rejects E7006, subject to the explicitly preserved Q-064 collision.
- Zig format and diff whitespace checks pass. No new verifier rule needs a
conformance pair: this increment changes metadata, not source/AIR semantics.
Evidence is in `/tmp/aji-q063-reaches/`: `aji-before`,
`conformance.audit.json`, `parity.audit.json`, `runtime-parity.json`,
`clean-before/`, `clean-after/`, `pinned-timings.jsonl` and `pinned-audit.json`.
The old binary hash is recorded above; the measured new Debug binary is
`46a1c15b25e84729ce03d24e04aeead05c4835ddb2355c64dd64f14d248e067a`.
No wall-clock timeout ends a run. No ownership/borrow/resource invariant,
runtime operation, fuel/scheduling rule, diagnostic, feature, normative text,
agent bundle or accepted-depth limit changes. Q-063 remains open for liveness
and shield improvements; Q-064 is a separate correctness follow-up.
## Second optimization: negative After-query reuse (2026-10-14)
`liveAfter` now keeps one stack-local memo while walking outwards through Rest
frames. It reuses a completed **negative subtree After query**, not the answer
to whole-variable liveness. The key includes the immutable control payload's
AST identity/kind and positional span, variable name and construct position.
Supported expression roots are if, match and block; other forms retain the
original traversal. There is no name-only or function-wide result cache.
The proof carried by an entry is narrow: the query entered with `seen=false`,
found the construct and returned no later read. An enclosing unseen traversal
of exactly that subtree can set `seen=true` and resume its existing work stack.
Sibling-arm exclusion and loop-back continuations therefore retain their old
state transitions. A query entered with `seen=true`, an absent construct,
a positive result, another AST node/name/position or a failed query cannot
supply this proof. Statement wrappers seed an expression entry only when their
position checks agree. The existing position-only span policy, including
cross-file position comparisons, is unchanged.
First-use kills, pattern rebinding, enclosing-rest order, loop reads and
assignment queries still run in their original order. The memo resets for each
`liveAfter` invocation, allocates nothing and retains one entry regardless of
source depth. Successful reuse may avoid scratch allocations; every actual
scratch OOM still propagates and clears pending work before any memo publication.
The governing pruned-SSA rule in spec 15 section 4, diagnostics, accepted source,
canonical AIR and interpreter/fuel rules are confirmed unchanged.
### Measurements
Seconds for mutable-match lowering; medians of three measured runs.
| Depth | Before | After | Before / after |
|---|---:|---:|---:|
| 128 | 0.560870 | 0.093792 | 5.98× |
| 256 | 3.991630 | 0.220675 | 18.09× |
| 512 | 30.981500 | 0.635286 | 48.77× |
Other shapes at depth 512:
| Shape | Before | After |
|---|---:|---:|
| scope | 0.093227 | 0.091937 |
| shield | 0.094780 | 0.094081 |
| while | 0.180449 | 0.179080 |
| loop | 0.074227 | 0.074617 |
| match | 0.182518 | 0.183027 |
| while_live | 0.674470 | 0.675189 |
The six depth-512 controls change by at most 1.4% in this batch. The series
contains 126 measured lowerings, 42 warmups and 42 final source/AIR acceptance
checks. These controls do not establish a universal overhead bound.
The paired Debug series compares the frozen first-optimization executable
against this increment on CPU 0: depths 128/256/512, all seven original public
probe shapes, one warmup per case/version and three measured repetitions.
Version order alternates and case order rotates. All generated sources match
the preceding audit's fixtures; every lowering has identical AIR. No builds or
correctness suites run alongside the timed series. The reports retain wall/CPU
and wait4 peak RSS (the latter can include the launcher's pre-exec memory).
These are lowering measurements on one machine, not a portable complexity or
whole-compiler latency bound. Source/AIR acceptance is checked separately.
Repeated ancestor descent is avoided on the audited nested-match path, but
assignment/read queries, positive After queries, unsupported root shapes and
AIR verification still have their prior costs. Q-063 therefore remains open;
shield relations and Q-064 are independent follow-ups.
### Validation and evidence
- Full unit suite: **341/341**, terminal exit 0. Four new tests cover exact
memo keys, already-seen state, statement/expression position mismatch,
pre/post-boundary scratch OOM, frozen Rest-frame comparisons with kills,
competing siblings and loop reads, and 4,096 enclosing control frames with
bounded query scratch. Existing recovering/persistent OOM and frozen
liveness/CFG/error-order tests pass. The focused selection is 9/9 including
five import-discovery tests.
- All **1,799** conformance cases pass with exact unique inventory, no missing,
extra, duplicate or nonpassing records.
- All **1,429** public source conformance inputs and ten new finite positive/
negative probes retain exact old/new `check`/`lower` exits, stdout and stderr:
**2,878 comparisons**. Four Q-064 collisions add eight exact comparisons.
- Eight positive new probes, in source and AIR at fifteen fuel values, retain
**240** exact run-record/exit pairs. They include nested mutation, straight-line
kills, competing-arm reads, loop backedges, continue, shadowing, returns and
independent variables. The negative probes preserve assignment/type errors.
- The existing hosted liveness-depth suite passes **418** CLI checks through
depth 65,536, including formatting, source/AIR, exact fuel and hosted records.
That run used a separately retained production-identical build before a
test-only setup correction; final unit/parity/timing artifacts use the
corrected test source. Both native hashes are retained in the provenance.
- Zig formatting and patch whitespace checks pass. No new verifier rule,
language feature, diagnostic, semantic flag or normative limit is introduced.
Evidence is under `/tmp/aji-q063-review-20261014-se2oa131/liveness/`:
`baseline.json`, `source.json`, `unit-final.log`, `focused.log`,
`conformance-audit.json`, `parity-audit.json`, `runtime-parity.json`,
`collision-parity.json`, `hosted-liveness.log` and `performance/` with sources,
old/new AIR, provenance, warmups, timings, summary and acceptance checks.
Reproduce generated probes with `tools/profile_control_depth.py`; freeze each
Debug binary, pin the launcher to one CPU, and rotate versions on identical
inputs. The exact paired driver is retained as
`/tmp/aji-q063-liveness-performance.py`. No wall-clock timeout ends a command.
## Correctness follow-up: explicit CFG incoming edges (Q-064, 2026-10-14)
The compatibility index in the first optimization deliberately retained the
old textual predicate. Q-064 is now corrected independently: each frontend
block records whether an emitted terminator targets it, using block indices
supplied by the lowering construct. `term` requires an explicit successor
slice; `select` passes its existing outcome records without allocating a new
index. `ret` and `trap` have no successors. The loop-completion query reads the
exit block's bit in constant time. Instruction emission no longer searches
text or allocates a loop-exit hash table.
The bit starts false with each new block and is published only after the
instruction append succeeds. There is no fallible step between publishing a
terminator and recording its edges. Targets exist before emission; no names,
source operands, calls or textual prefixes take part in the query. Edges from
syntactically emitted but disconnected blocks still count, and constant
conditions are not folded. This preserves the prior conservative CFG policy
apart from the naming defects; it does not add reachability analysis.
Two corrected cases demonstrate why the separate correctness change is
needed:
- A helper call `after_2()` inside `loop { after_2(); return 0u64; }` previously
supplied a phantom incoming edge to the loop exit. A following statement now
rejects E7006 `unreachable`, as spec 15 §10 requires. Trap, continue, nested
loops and function-state reset have corresponding rejection fixtures.
- A boolean parameter `after_2` (or the prefix `after_20`) previously masked the
genuine `@after_2` exit later in a conditional branch instruction. A reachable
statement after `while after_2 { return 1u64; }` now accepts. Both boolean
outcomes execute correctly; real break edges remain valid even when the
same helper name occurs.
Validation uses Zig 0.17.0, Debug, with a frozen pre-fix executable containing
both Q-063 optimizations. The complete public corpus, without held-out or
untracked evaluation material, gives:
| Check | Result |
|---|---|
| Unit suite, including emission OOM and recovering/persistent lowering OOM | 342 passed |
| Conformance, including nine new source fixtures | 1,808 passed |
| Pre-existing public sources: exact check/lower exit, stdout and stderr | 2,858 pairs on 1,429 files, no differences |
| New fixture check/lower comparisons | 18 pairs; 14 intentional corrections, four exact |
| Existing finite source/AIR runtime and fuel comparisons | 240 exact pairs |
| Targeted collision/diagnostic/format/package CLI suite | 182 passed |
| Existing diagnostic-reason suite | 236 passed |
| Existing independent-error suite | 234 passed |
| Existing CFG-provenance suite | 146 passed |
| Hosted smoke, including local TCP sockets | passed |
| Zig formatting | passed |
The incoming-edge unit oracle independently parses emitted AIR and obtains
successors from AIR operations for ten programs covering loops, joins, short
circuiting, integer/enum/builtin matches, fallible outcomes, lock, select and
linear aggregate unpacking. It compares every function's block bits with
those parsed successors. The old textual predicate remains frozen in the
control compatibility oracle; the two collisions are tested as deliberate
old/new differences rather than silently changing that oracle.
The targeted CLI suite checks E7006 reason and exact source position,
diagnostic ordering before and after divergence, independent function errors,
canonical formatting, package provenance, both loop-condition outcomes and
source/AIR fuel equality. Five erroneous acceptances now reject; two erroneous
rejections now accept. Other public acceptance, diagnostics, canonical AIR and
finite runtime/fuel behavior are unchanged. AIR format 0 and its verifier and
interpreter semantics are unchanged. No portable performance bound is claimed
for this correctness slice; Q-063's remaining liveness and shield work remains
open.
Reproduction and qualification artifacts are retained in
`/tmp/aji-q064-20261014-x_a6b4gb/`: `baseline.json`, frozen binaries,
`reproduction.json`, `parity.jsonl`, `collision-changes.json`,
`runtime-parity.jsonl`, `parity-audit.json`, `unit-final.log`,
`conformance.jsonl`, CLI-suite logs and `qualification.json` with source and
executable hashes. The reproducible targeted test is
`python3 tests/hosted/source_loop_exit.py`.
+52 -11
View File
@@ -661,17 +661,30 @@ profiled targets accept normally. This is a finite Debug profile, not a
portable timing bound or a whole-compiler complexity proof.
Q-060's full per-step validation is now closed by its composite audit.
Profiling for Q-063 is complete for these paths; optimization remains open.
The recommended first isolated change is explicit loop incoming-edge metadata,
followed by context-correct liveness indexing and a separately reviewed shield
relation optimization. A later optimization needs exact CFG/SSA,
Profiling for Q-063 is complete for these paths. The
[first optimization](control-depth-performance-audit.md#first-optimization-loop-exit-reference-index-2026-10-14)
indexes loop-exit references at instruction emission rather than repeatedly
scanning the whole function. Paired CPU-pinned Debug lowering at 512 levels
improves while by 3.22×, loop by 1.85× and mutable while by 1.80×, with exact
public check/lower and runtime/fuel compatibility. That slice preserved the
legacy reference policy; Q-064 now records its separate correction with
explicit CFG incoming edges.
The [second optimization](control-depth-performance-audit.md#second-optimization-negative-after-query-reuse-2026-10-14)
reuses one completed negative subtree After query while walking enclosing Rest
frames, with AST identity/name/construct guards. Paired Debug mutable-match
lowering at 512 levels falls from 30.982 to 0.635 seconds (48.77×), with 341 unit
tests, 1,799 conformance cases and exact source/AIR/runtime comparisons. This
preserves first-use kills, sibling exclusion and loop reads; it is not a global
variable-liveness cache. Remaining assignment/read/positive-query costs and a
separately reviewed shield relation optimization remain open. A later
optimization needs exact CFG/SSA,
diagnostic-order, host-OOM and runtime/fuel compatibility checks.
No source-depth limit, new diagnostic, verifier rule, AIR instruction or
language semantic change is introduced by recording this limitation.
## Q-064 — Loop-exit reference search confuses function and block names
**Open; confirmed existing frontend diagnostic defect (2026-10-14).** While
**Closed; frontend diagnostic defect corrected (2026-10-14).** While
optimizing Q-063, a frozen pre-change Debug binary at `17cbe3e` accepts this
source in both `lower` and `check`, with exit 0:
@@ -692,9 +705,37 @@ mistakes `call @after_2()` for an incoming reference to that block. Its
first-substring test also allows an earlier non-reference substring in one
instruction to mask a later genuine reference in that same instruction.
The Q-063 reference-index optimization deliberately preserves this behavior;
it does not make the collision a language rule. Replacing the compatibility
index with actual CFG-edge metadata belongs to a separate correctness change,
with source/AIR, naming-collision, unreachable-code and diagnostic-priority
coverage. Evidence is in `/tmp/aji-q063-reaches/collision-*.aji` and the frozen
CLI's output. No native-stack failure or unsafe execution is established here.
The Q-063 reference-index optimization initially preserved this behavior;
it did not make the collision a language rule. The separate correctness fix
replaces that compatibility index with a per-block incoming-edge bit, updated
from explicit target indices only after a terminator is successfully emitted.
Every terminator declares its successors; `select` reuses its existing outcome
metadata. Calls and operand names cannot supply or mask a block edge. The bit
counts syntactic edges, including edges from disconnected blocks; this is not
entry-reachability analysis or constant folding. A host allocation failure
publishes neither the instruction nor its edges.
The other confirmed direction was a false rejection: in
`fn f(after_2: bool) -> u64`, `while after_2 { return 1u64; } return 42u64;`
previously reported E7006 at the reachable return. The operand's earlier
`after_2` substring masked the real exit target in the conditional branch.
This now accepts, returning 42 for `false` and 1 for `true`.
Qualification: 342 unit tests, 1,808 conformance cases (nine new), 182 targeted
CLI checks, plus the diagnostic-reason, independent-error, CFG-provenance and
hosted smoke suites. All 2,858 `check`/`lower` comparisons on 1,429 pre-existing
public sources and 240 runtime/fuel comparisons match the frozen pre-fix
executable exactly. Fourteen of the eighteen new fixture comparisons change
intentionally: five false acceptances reject E7006 `unreachable`, and two
false rejections accept; two valid break cases retain exact output. Diagnostic
priority, source/package positions, formatting, function-local state and host
OOM are covered. Incoming metadata is also checked against independently
parsed AIR successors for ten lowering programs. The frozen textual predicate
remains only in compatibility tests, with its collisions explicitly tested as
old defects.
The [control-depth audit](control-depth-performance-audit.md#correctness-follow-up-explicit-cfg-incoming-edges-q-064-2026-10-14)
records the implementation and evidence in
`/tmp/aji-q064-20261014-x_a6b4gb/`. Spec 15 §10 already requires the corrected
behavior: no new diagnostic, source rule, verifier rule, AIR meaning or runtime
instruction is introduced. Q-063's remaining performance work stays open.