21 KiB
Control-depth performance audit (Q-063)
Scope and reproduction (2026-10-14)
Q-063 has several independent causes. Repeated liveness queries dominate the mutable-match case, textual incoming-edge searches dominate loop lowering, and shield relations dominate verification. This profiling change does not optimize production code or close Q-063.
The measured binary is a fresh Debug zig build at
17cbe3eb4ea9cf7ec2d811613ebb1b9e3affb976, Zig 0.17.0, SHA-256
527dbce1cdd80d48ed3e5c14c6c6a814aa016e2421fb5e7ffa5260545e5b8216.
Generated fixtures and raw evidence are in
/tmp/aji-q063-profile-20261014-jeo0_cfr/: provenance.json,
timings.jsonl, summary.json, generated .aji/.air, and five
*.profile.json/*.gdb.log pairs. These local artifacts are not versioned.
The harness is retained as tools/profile_control_depth.py:
zig build
python3 tools/profile_control_depth.py --depths 32 64 128 256 512 --repeats 3
The default maximum depth is 256 to keep reproduction practical. It generates
scope/shield nesting, while false, loops with a reachable break at every
level, and integer matches with one nested arm and one empty default arm.
The *_live variants assign x = x + 1u64 at the leaf and return x after
the outer construct. Other variants have one immutable leaf binding and return
zero. These are generated public-language probes, unrelated to evaluation tasks.
Each fixture is lowered, its AIR checked, and its source checked, with three repetitions per command: 315 commands, all exit 0 with empty diagnostics. Repeated lowerings are byte-identical. The retained harness additionally passes a 42-command smoke run at depths 2 and 4, one repetition, all seven shapes. No runtime execution, fuel consumption or scheduler behavior is measured. No wall-clock timeout terminates a command. Timings include process startup, allocator cleanup, and command-specific I/O; the AIR check includes AIR parsing. They are medians on one machine, not portable limits or exact complexity proofs.
Stage timings
Seconds, shown as 128 / 256 / 512 levels:
| Shape | Source lowering | AIR parsing + verification | Full source check |
|---|---|---|---|
| scope | 0.039 / 0.060 / 0.091 | 0.029 / 0.029 / 0.031 | 0.046 / 0.062 / 0.098 |
| shield | 0.041 / 0.069 / 0.092 | 0.093 / 0.363 / 1.991 | 0.109 / 0.412 / 2.034 |
| while | 0.086 / 0.208 / 0.628 | 0.036 / 0.064 / 0.164 | 0.104 / 0.248 / 0.749 |
| loop | 0.039 / 0.062 / 0.141 | 0.027 / 0.044 / 0.079 | 0.045 / 0.080 / 0.190 |
| match | 0.060 / 0.099 / 0.178 | 0.044 / 0.062 / 0.161 | 0.072 / 0.135 / 0.321 |
| while_live | 0.130 / 0.373 / 1.235 | 0.041 / 0.072 / 0.177 | 0.147 / 0.413 / 1.398 |
| match_live | 0.558 / 3.973 / 31.827 | 0.035 / 0.068 / 0.171 | 0.587 / 4.083 / 31.819 |
The mutable-match lowering grows by about 7.1× and 8.0× for successive depth doublings, consistent with cubic work in this fixture. The no-mutation control is much cheaper. Shield lowering stays close to scope lowering while checking the generated AIR reproduces almost the whole source-check cost.
Sampled stacks and source inspection
GDB launches each target as its child, interrupts at roughly 20 ms intervals, records up to 41 frames and resumes until normal exit. All five targets and their debuggers exit normally. These are inclusive stack-presence counts, not additive CPU percentages; debugger overhead and the small samples limit precision. Profiling is separate from the timing matrix.
| Target | Samples | Observed path |
|---|---|---|
| match_live, 256, lower | 195 | liveAfter in 186; liveness.Workspace.query in 188 |
| while, 512, lower | 30 | finishDriveLoop → reaches in 23 |
| while_live, 512, lower | 60 | reaches in 27; liveness query in 22 |
| loop, 512, lower | 6 | reaches in 3; too few for a precise proportion |
| shield, 512, check | 101 | borrow.checkFunction in 96; provenance.State.kill in 49 |
Mutable matches: prepareDriveValueMatch calls carriedLive, which calls
liveAfter for assigned mutable bindings. liveAfter walks enclosing rest
frames and searches their containing statement/expression with a fresh After
cursor. Nested matches therefore revisit ancestor subtrees at many levels.
The stacks and mutation control support this as the principal cause of the
measured cubic behavior. A cache keyed only by variable name would be invalid:
construct position, rest-frame context, rebinding/kills and loop reads matter.
Loops: finishDriveLoop calls reaches for every exit block. This helper
does not traverse a reachability graph: it searches the text of all emitted
instructions for a reference to the target block name. Repeating this for
nested exits produces quadratic worst-case scanning independently of liveness.
The stacks show it dominates the measured no-mutation while lowering. Mutable
while lowering additionally spends substantial time on liveness queries.
Shields: borrow.step records an .inner relation for each new shield
against every live outer shield: n(n−1)/2 facts at maximum depth. Both event
replay and the checking walk apply those relations. provenance.State.kill
scans the whole fact list when a shield ends. For simple nested shields, a
full pop sequence scans lists whose lengths sum to (n³−n)/6 per complete
application of that sequence (22,369,536 fact visits at n=512). This is a
source-derived count, not an instrumented measurement. Relation insertion,
hash-table growth, access checks and replay add cost. A lowerer liveness cache
cannot remove this verifier cost.
Follow-up order
- Replace repeated textual incoming-reference searches for loop exits with explicit incoming-edge metadata. This is the smallest isolated candidate; preserve the helper's actual reference-existence behavior, including references from blocks whose execution is unreachable.
- Design context-correct reuse or indexing for liveness searches, starting with mutable-match ancestor rescans. Preserve pruned SSA sets, first-use kills, rebinding barriers, diagnostics, host-OOM propagation and publication.
- Separately optimize shield relation representation or removal. This changes verifier implementation and needs review of exact shield-order joins, resource handoff, E3002/E4305 priority and deterministic behavior.
Each optimization needs independent positive/negative coverage and exact old/new lowering, diagnostics and observable-runtime comparisons appropriate to its scope. The present work changes only a profiling tool and documentation: no verifier/runtime rule, language feature, accepted-depth limit, diagnostic, 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. 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 testexits 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 focusedzig 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
checkandlowerexit/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
breakstill 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/lowerexits, 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()insideloop { after_2(); return 0u64; }previously supplied a phantom incoming edge to the loop exit. A following statement now rejects E7006unreachable, as spec 15 §10 requires. Trap, continue, nested loops and function-state reset have corresponding rejection fixtures. - A boolean parameter
after_2(or the prefixafter_20) previously masked the genuine@after_2exit later in a conditional branch instruction. A reachable statement afterwhile 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.