docs: Q-063 profiling audit and harness, record Q-064
This commit is contained in:
1 parent
17cbe3eb4e
commit
2fb882c704
3 files changed
+269
-5
No files matched your search
@@ -0,0 +1,120 @@
|
|||||||
|
# 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`](../../tools/profile_control_depth.py):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
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
|
||||||
|
|
||||||
|
1. 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.
|
||||||
|
2. 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.
|
||||||
|
3. 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.
|
||||||
@@ -649,11 +649,52 @@ levels, 108 s at 4,096 (then the ordinary E5101), and no result after more than
|
|||||||
ten minutes and about 480 MB at 16,384, where the agent stopped it. No
|
ten minutes and about 480 MB at 16,384, where the agent stopped it. No
|
||||||
native-stack aborts or observed correctness defects. This
|
native-stack aborts or observed correctness defects. This
|
||||||
tracks resilience to adversarial source input separately from Q-061's repaired
|
tracks resilience to adversarial source input separately from Q-061's repaired
|
||||||
stack-exhaustion defect. Repeated scans of the remaining AST for live variables
|
stack-exhaustion defect.
|
||||||
are a suspected cause, not a profiled explanation of all four results.
|
|
||||||
|
|
||||||
Defer liveness caching or a broader `lower.zig` refactor until after Q-060's
|
The [2026-10-14 stage timings and sampled stacks](control-depth-performance-audit.md)
|
||||||
full per-step GC validation. A later optimization needs profiling and exact
|
separate three causes: repeated enclosing-rest liveness searches dominate
|
||||||
CFG/SSA, diagnostic-order, host-OOM and runtime/fuel compatibility checks.
|
mutable-match lowering (about 8× work per depth doubling at 256–512); textual
|
||||||
|
incoming-block-reference scans in `Lowerer.reaches` dominate no-mutation while
|
||||||
|
lowering and also appear for loop; shield relation maintenance dominates AIR
|
||||||
|
verification, independently of liveness. All 315 timed commands and five
|
||||||
|
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,
|
||||||
|
diagnostic-order, host-OOM and runtime/fuel compatibility checks.
|
||||||
No source-depth limit, new diagnostic, verifier rule, AIR instruction or
|
No source-depth limit, new diagnostic, verifier rule, AIR instruction or
|
||||||
language semantic change is introduced by recording this limitation.
|
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
|
||||||
|
optimizing Q-063, a frozen pre-change Debug binary at `17cbe3e` accepts this
|
||||||
|
source in both `lower` and `check`, with exit 0:
|
||||||
|
|
||||||
|
```aji
|
||||||
|
module probe
|
||||||
|
fn after_2() -> void effects [] {}
|
||||||
|
fn main() -> u64 effects [] {
|
||||||
|
loop { after_2(); return 0u64; }
|
||||||
|
return 1u64;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Changing only the helper's name to `after_3` makes both commands reject the
|
||||||
|
statement after the loop with E7006 `unreachable`. Spec 15 §10 requires E7006
|
||||||
|
for expressions after unconditional divergence. The old `Lowerer.reaches`
|
||||||
|
searches instruction text for a generated exit name (`after_2` here), and
|
||||||
|
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.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Profile Q-063 through lower, check-AIR and check-source; never terminate a run by time."""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import resource
|
||||||
|
import statistics
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
KINDS = ('scope', 'shield', 'while', 'loop', 'match', 'while_live', 'match_live')
|
||||||
|
REPO = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def source(kind, depth):
|
||||||
|
leaf = 'let x: u8 = 1; '
|
||||||
|
live = kind.endswith('_live')
|
||||||
|
if live:
|
||||||
|
leaf = 'x = x + 1u64; '
|
||||||
|
if kind == 'scope':
|
||||||
|
body = 'scope s { ' * depth + leaf + '} ' * depth
|
||||||
|
elif kind == 'shield':
|
||||||
|
body = 'shield { ' * depth + leaf + '} ' * depth
|
||||||
|
elif kind in ('while', 'while_live'):
|
||||||
|
body = 'while false { ' * depth + leaf + '} ' * depth
|
||||||
|
elif kind == 'loop':
|
||||||
|
body = 'loop { ' * depth + 'break; ' + '} break; ' * (depth - 1) + '} '
|
||||||
|
else:
|
||||||
|
body = 'match 0u8 { 0 => { ' * depth + leaf + '} _ => {} } ' * depth
|
||||||
|
return ('module probe\nfn main() -> u64 effects [] { '
|
||||||
|
+ ('var x: u64 = 0u64; ' if live else '') + body
|
||||||
|
+ ('return x;' if live else 'return 0u64;') + ' }\n')
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--aji', type=Path, default=REPO / 'zig-out/bin/aji')
|
||||||
|
parser.add_argument('--out', type=Path, help='new directory for sources, AIR, records and provenance')
|
||||||
|
parser.add_argument('--depths', type=int, nargs='+', default=[32, 64, 128, 256])
|
||||||
|
parser.add_argument('--kinds', choices=KINDS, nargs='+', default=list(KINDS))
|
||||||
|
parser.add_argument('--repeats', type=int, default=3)
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.repeats < 1 or any(d < 1 for d in args.depths):
|
||||||
|
parser.error('depths and repeats must be positive')
|
||||||
|
if args.out:
|
||||||
|
root = args.out.resolve()
|
||||||
|
root.mkdir(parents=True, exist_ok=False)
|
||||||
|
else:
|
||||||
|
root = Path(tempfile.mkdtemp(prefix='aji-control-profile-'))
|
||||||
|
binary = args.aji.resolve()
|
||||||
|
metadata = {
|
||||||
|
'head': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=REPO, text=True).strip(),
|
||||||
|
'binary': str(binary), 'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest(),
|
||||||
|
'depths': args.depths, 'kinds': args.kinds, 'repeats': args.repeats,
|
||||||
|
}
|
||||||
|
(root / 'provenance.json').write_text(json.dumps(metadata, indent=2) + '\n')
|
||||||
|
print(f'Artifacts: {root}', flush=True)
|
||||||
|
summary = []
|
||||||
|
with (root / 'timings.jsonl').open('w') as log:
|
||||||
|
for kind in args.kinds:
|
||||||
|
for depth in args.depths:
|
||||||
|
src = root / f'{kind}-{depth}.aji'
|
||||||
|
src.write_text(source(kind, depth))
|
||||||
|
air = src.with_suffix('.air')
|
||||||
|
for stage, command, path in [('lower', 'lower', src), ('verify_air', 'check', air), ('check', 'check', src)]:
|
||||||
|
samples = []
|
||||||
|
for repeat in range(args.repeats):
|
||||||
|
before = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||||
|
started = time.perf_counter()
|
||||||
|
result = subprocess.run([str(binary), command, str(path)], capture_output=True)
|
||||||
|
elapsed = time.perf_counter() - started
|
||||||
|
after = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||||
|
row = dict(kind=kind, depth=depth, stage=stage, repeat=repeat,
|
||||||
|
wall_s=elapsed, cpu_s=after.ru_utime + after.ru_stime - before.ru_utime - before.ru_stime,
|
||||||
|
exit_code=result.returncode)
|
||||||
|
log.write(json.dumps(row) + '\n')
|
||||||
|
log.flush()
|
||||||
|
if result.returncode or result.stderr or (stage != 'lower' and result.stdout):
|
||||||
|
(root / 'failure.stdout').write_bytes(result.stdout)
|
||||||
|
(root / 'failure.stderr').write_bytes(result.stderr)
|
||||||
|
raise RuntimeError(f'{kind}/{depth}/{stage} did not accept cleanly: exit {result.returncode}')
|
||||||
|
if stage == 'lower':
|
||||||
|
if repeat and air.read_bytes() != result.stdout:
|
||||||
|
raise RuntimeError('repeated lowering produced different AIR')
|
||||||
|
air.write_bytes(result.stdout)
|
||||||
|
samples.append(row)
|
||||||
|
item = dict(kind=kind, depth=depth, stage=stage,
|
||||||
|
median_s=statistics.median(r['wall_s'] for r in samples),
|
||||||
|
median_cpu_s=statistics.median(r['cpu_s'] for r in samples))
|
||||||
|
summary.append(item)
|
||||||
|
print(json.dumps(item), flush=True)
|
||||||
|
(root / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
|
||||||
|
inputs = {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
|
||||||
|
for p in sorted(root.iterdir()) if p.suffix in ('.aji', '.air')}
|
||||||
|
(root / 'inputs.sha256.json').write_text(json.dumps(inputs, indent=2) + '\n')
|
||||||
|
(root / 'complete.json').write_text(json.dumps({'exit_code': 0, 'runs': len(summary) * args.repeats}) + '\n')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Reference in new issue
Block a user