Zane compiler audit — 17 October 2026

Scope and evidence

Audited revision: 41277c73ef24dbf95715c190741ff13ae93077fb. Audit branch: audit/compiler-2026-10-17. This report documents issues only; it contains no implementation changes or remediation proposals.

30 retained findings cover correctness, compilation resource use, runtime behavior, architecture, file structure, tests, diagnostics and tooling. High means wrong behavior, rejected valid input, or a compiler failure that an ordinary program or command reaches; Medium means a functional defect that needs an unusual setup to reach (F10’s cross-context constant cycle, F17’s temporary-name collision), a material robustness/maintenance risk, or a coverage gap; Low means a diagnostic or hygiene defect. Architectural findings are judgments, not claims of demonstrated miscompilation. IDs match the running notebook; F06 was withdrawn after verification.

The audit inspected the parser/desugaring pipeline, semantic passes and ownership analyses, CGT lowering, constant evaluation, LLVM emission, runtime allocation/concurrency, object rewriting, tests, grammar/proof tooling and build/release scripts. Coverage is broad and selective, not a formal verification of every compiler path. No additional finding is claimed merely because a subsystem appears in this scope.

Source was pinned by Git blob SHA. Executable checks used the released v0.14 artifact from run 39043017625, whose toolchain.coda records this exact commit. Artifact ZIP SHA-256: 1850c3f8b20d8809ea6848e10bdf2c686f8085f1818b9b161ed829f560ae71bf, matching the GitHub artifact digest. This provided the shipped compiler and LLVM 19. Earlier reduced LLVM 20 probes are superseded where exact-compiler results are reported below.

Verification performed

Check Result
Existing executable fixtures 42 fixtures, optimized and unoptimized, checking off and on: 168 successful output/status comparisons
Runtime C tests with GCC Nine tests in both checking modes: 18 successful comparisons
Runtime C tests with UBSan Nine successful comparisons, no sanitizer diagnostics
Selected Python proof-tool/profile/CLI/release tests 47 tests: 40 passed, seven skipped for missing Menhir/engine
Engine-only Python tests Ten skipped because the engine/Menhir were unavailable
Offline release-tag recovery tests Passed
Targeted compiler cases Findings below record exact commands/shapes, statuses and limits

The OCaml/Dune compiler suite was not rebuilt or executed through Dune. Lean proofs, generated-file freshness and editor-consumer suites were not rerun because their development toolchains were unavailable. The artifact-based executable checks do not substitute for those checks. Runtime retention and constant-cycle probes used the actual baseline C runtime compiled locally. Source-traced risks were not upgraded to observed failures merely on the strength of a reduced example.

Findings index

ID Severity Finding
F07 High An aggregate-returning main is exported with an incompatible runtime entry signature
F08 High The large-aggregate guard misses function parameters
F13 High Large array lengths truncate at the LLVM boundary and overflow CGT byte arithmetic
F01 High The generic-instantiation limit mistakes finite usage for infinite recursion
F16 High Expanding generic recursive types evade the boxing traversal’s cycle detector
F02 Medium Target selection accepts layouts that the rest of the compiler cannot represent
F18 Medium The –stamp option accepts malformed stamps that the other stamp-taking paths reject
F17 Medium Failed exclusive creation during object rewriting deletes the file that caused the collision
F31 Medium Explicit package-path options reject Unicode package names accepted by source and bare paths.
F09 High Memoized output replay bypasses the compile-time evaluator’s resource budget
F14 High A small incomplete multi-scrutinee match allocates its entire exponential case space
F15 Medium Array ownership metadata expands one entry per element before backend size checks
F05 Medium LLVM compilation resources have no owned lifecycle in the driver API
F25 Medium Whole-program fixed points repeatedly walk all bodies, and repetition analysis runs twice.
F10 Medium Package-constant cycle detection cannot detect a cycle spanning contexts
F11 Medium Drained one-MiB chunks are cached forever with no bound or release path
F30 Medium Overflow fault handlers call stdio.
F21 Medium Lowering is a single oversized recursive dependency cluster.
F22 Medium Generic tree traversal is owned by particular analyses, and duplicated by optimization.
F23 Medium Internal runtime ABI numbers are handwritten independently in C and OCaml.
F24 Medium Semantic phases share an unrestricted mutable state object.
F12 Medium Negative parser tests accept internal compiler errors and signal crashes as correct rejection
F26 Medium Generated-program regression suites force checking mode.
F27 Medium Memory-probe corpus is outside automated regression gates.
F28 Low Golden-file presence decides silently whether a fixture is tested.
F03 Low Diagnostic carets use code-point counts rather than terminal cell widths
F04 Low The diagnostic underline gutter stops aligning at double-digit line numbers
F19 Medium Ambiguity-search timeouts accept NaN and infinity
F20 Low Source excerpts and diagnostic paths emit terminal controls unchanged
F29 Low Identical duration regex assignment is duplicated consecutively.

Correctness and compiler failures

F07 — An aggregate-returning main is exported with an incompatible runtime entry signature

Severity: High.

Location: lib/tst/passes/verb_signatures.ml:793-807; lib/cgt/program.ml:330-381; lib/codegen/emit.ml:1112-1130; runtime/zane.h:50; runtime/main.c:71.

Semantics explicitly permits any main return type. When there are no non-lambda package constants, lowering marks the user’s main itself as the entry; codegen renames that function zane_main without changing its return type. The C runtime declares and calls void zane_main(void). Large aggregate returns need return storage that this caller never supplies. The void startup wrapper is emitted only when constants exist, so unrelated constants change which entry ABI is used.

Evidence and limit: Confirmed using the exact baseline release: Array<I64,10> main builds, then aborts with “a scope was left without draining”. Adding unused Int(1) at package scope makes the program exit 0. The changed entry wrapper explains the behavioral difference.

F08 — The large-aggregate guard misses function parameters

Severity: High.

Location: lib/codegen/big_moves.ml:119-137; lib/codegen/emit.ml:1060-1066.

Big_moves’ final limit check examines only instruction result types and explicitly exempts allocas. Function parameters and signatures are not examined. Emit stores every non-void parameter into an alloca; a store’s result is void, so an exported function taking [65536 x i64] can reach native code generation without the promised diagnostic even if its parameter is otherwise unused.

Evidence and limit: Confirmed with the shipped baseline compiler and bundled LLVM 19: a library function consume(x Array<I64,65536>) emits IR successfully but –object terminates with SIGSEGV, returncode -11.

F13 — Large array lengths truncate at the LLVM boundary and overflow CGT byte arithmetic

Severity: High.

Location: lib/tst/passes/type_decls.ml:427-436; lib/tst/model/ty.ml:40; lib/cgt/nodes.ml:44-61; lib/codegen/emit.ml:49; lib/codegen/frames.ml:27-40.

Number arguments are OCaml ints with no maximum tied to layout. CGT retains n and computes stride*n and frame additions without checked arithmetic. On a 64-bit OCaml runtime, an I64 array with n=2^60 wraps its computed byte size to 0. Separately, Llvm.array_type in the pinned LLVM 19 binding calls LLVMArrayType with Int_val(Count); that C API takes an unsigned 32-bit count, so n=2^32 produces a zero-length LLVM array while CGT offsets/bounds still carry the original n.

Evidence and limit: Confirmed: a library Array<I64,4294967296> parameter emits [0 x i64] with exit 0. The additional arithmetic-overflow path follows from unchecked OCaml-int multiplication; that extreme size was not allocated.

F01 — The generic-instantiation limit mistakes finite usage for infinite recursion

Severity: High.

Location: lib/tst/check/instances.ml:13-15; lib/tst/check/instances.ml:119-131.

instance_counts is keyed only by declaration id and counts every distinct argument set across the entire build. The 65th set is rejected with a claim that the verb’s calls to itself never reach a fixed set. No recursion or call ancestry is inspected. A non-recursive generic called with 65 distinct concrete types hits this limit.

Evidence and limit: Confirmed with the shipped baseline compiler: 65 calls to non-recursive consume(x T Type), using 65 distinct one-field value types, fail on the 65th call with exit 1 and the recursion diagnostic.

F16 — Expanding generic recursive types evade the boxing traversal’s cycle detector

Severity: High.

Location: lib/cgt/type_layout.ml:68-86; lib/tst/passes/type_decls.ml:267-295; lib/tst/passes/type_decls.ml:852-867.

boxed follows inline owning members with a seen list of fully instantiated Ty.t values. A variant such as Grow with a terminating case and a recursive Grow<Array<T,2>> case generates Grow, Grow<Array<T,2>>, Grow<Array<Array<T,2>,2>>, …; neither the holder equality nor the full-type seen test ever matches. Semantic wrong-kind checks stop by declaration id and do not reject this expansion; the distinct-cycle pass covers only Distinct definitions. Asking for this type’s layout can recurse without end until a compiler stack overflow.

Evidence and limit: Confirmed noncompletion: the exact baseline compiler did not finish –kind library –ll for the described Grow parameter within 8 seconds. Traversal/substitution inspection explains the unbounded type expansion. A stack-overflow outcome was not observed.

F02 — Target selection accepts layouts that the rest of the compiler cannot represent

Severity: Medium.

Location: lib/codegen/build.ml:25-42; lib/cgt/nodes.ml:39-61; lib/codegen/frames.ml:12-17; runtime/zane_internal.h:175-188.

target_machine accepts any triple registered by LLVM, including 32-bit targets. CGT fixes pointer size/alignment at 8, handles at 24, payloads at offset 8, scope records at 224 and task headers at 96. No target-width/ABI validation appears before emitting target-specific LLVM types. Object/IR output can use inconsistent offsets; runtime compilation for a 32-bit target fails its fixed-offset static assertions.

Evidence and limit: Confirmed: –ll –target i386-unknown-linux-gnu succeeds and selects a 32-bit pointer data layout. Source inspection establishes the conflicting fixed 64-bit layouts; no 32-bit executable was run.

F18 — The –stamp option accepts malformed stamps that the other stamp-taking paths reject

Severity: Medium.

Location: bin/zanec/zanec.ml:125-132; bin/zanec/zanec.ml:212-220; lib/driver/driver.ml:26-40; lib/cgt/program.ml:233-245.

package_id and –rewrite/–remap validate stamps with Rewrite.is_stamp. –stamp PATH=STAMP checks only the path and that the value is nonempty, then Driver applies it unchanged. Lowering later infers whether a package is stamped from the presence of %, so –stamp geometry=garbage can change the package id while being treated as unstamped by linkage classification. A malformed identity is accepted rather than a usage/build diagnostic.

Evidence and limit: Confirmed: –stamp largeparam=garbage succeeds and emits the symbol !garbagelargeparam$consume(…).

F31 — Explicit package-path options reject Unicode package names accepted by source and bare paths.

Severity: Medium.

Location: bin/zanec/zanec.ml:99-106; bin/zanec/zanec.ml:120-132; bin/zanec/zanec.ml:138-151.

is_package_name accepts ASCII letters/digits only, while the lexer accepts Unicode identifiers and bare directory requests preserve them. A package named bücher passes –check –package /path/bücher but –check –package bücher=/path/bücher exits 1 with “no such directory”, interpreting the whole binding as a filesystem path. The same ASCII restriction applies to explicit –import identities/keys. Confirmed with the shipped baseline compiler.

Evidence and limit: Confirmed: the same bücher package passes with a bare directory path and fails with an explicit Unicode name=directory binding.

F17 — Failed exclusive creation during object rewriting deletes the file that caused the collision

Severity: Medium.

Location: bin/zanec/zanec.ml:358-374.

run_rewrite chooses a temporary name, opens it with Open_excl, and unconditionally Sys.remove’s that name in the Sys_error handler. If exclusive creation itself fails because the name already exists, the compiler never owned that file but deletes it anyway. This contradicts the function’s output-preservation guarantee.

Evidence and limit: Source-confirmed exclusive-open failure and unconditional cleanup path. No collision was induced against a user’s file.

Compilation resource use

F09 — Memoized output replay bypasses the compile-time evaluator’s resource budget

Severity: High.

Location: lib/optimize/eval.ml:41-44; lib/optimize/eval.ml:574-594; lib/optimize/eval.ml:602-604; lib/optimize/materialize.ml:10-11.

A cached call replays its entire output list with List.rev_append without spending steps or charging its size. Print adds an output without charging text/list storage, and memo entries have no output-size or total-cache cap. A recursive function that calls its previous level twice and prints once at its base accumulates exponentially many output-list nodes while memoized computation takes only linearly many calls. The materialization cap is applied after evaluation and cannot bound these allocations.

Evidence and limit: Confirmed by budget and memo call paths; intentionally no out-of-memory stress run.

F14 — A small incomplete multi-scrutinee match allocates its entire exponential case space

Severity: High.

Location: lib/tst/check/check.ml:1084-1102.

Exhaustiveness checking materializes the complete Cartesian product as combos, then the complete missing list, before retaining only three examples for the diagnostic. With 30 two-case scrutinees and a single arm this attempts 2^30 combinations from a source program linear in 30. There is no budget or early diagnostic bound on this semantic path.

Evidence and limit: Confirmed by the Cartesian-product construction; no intentionally exhaustive allocation run.

F15 — Array ownership metadata expands one entry per element before backend size checks

Severity: Medium.

Location: lib/cgt/type_layout.ml:158-174; lib/codegen/walks.ml:604-617; lib/codegen/big_moves.ml:44-46.

For an array whose element owns any block, positions builds List.init n and concatenates each element’s positions. This work occurs during lowering, before Big_moves can reject an oversized aggregate, and walks later emit code per position. An array of strings/recursive owned values therefore consumes linear compiler memory and generated walk code in its declared length, even when source describes it in a few tokens.

Evidence and limit: Confirmed source path; no large allocation run.

F05 — LLVM compilation resources have no owned lifecycle in the driver API

Severity: Medium.

Location: lib/codegen/emit.ml:1076-1080; lib/driver/driver.ml:115-129.

Each emit creates a fresh LLVM context and module. Driver.ir, executable and object_file never dispose either. The only dispose_module in codegen disposes a temporary attribute-parsing module. LLVM 19 contexts/modules are wrapped as pointers requiring explicit disposal, so repeated library use retains native compilation storage, including failed compilations. Target machines and builders have binding finalizers and are excluded.

Evidence and limit: Confirmed by all codegen/driver source and LLVM 19.1.7 OCaml bindings. Repeated-process memory growth was not measured.

F25 — Whole-program fixed points repeatedly walk all bodies, and repetition analysis runs twice.

Severity: Medium.

Location: lib/tst/analyses/fixpoint.ml:34-42; lib/tst/analyses/repeats.ml:137-145; lib/tst/analyses/read_only.ml:594-595; lib/tst/analyses/spawns.ml:367-368.

Every summary-growth round walks all bodies. An unfavorably ordered call chain can propagate one edge per round and produce quadratic body visits. Read_only and Spawns independently recompute the same repetition map. Algorithmic cost; no timing claim.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

Runtime behavior

F10 — Package-constant cycle detection cannot detect a cycle spanning contexts

Severity: Medium.

Location: runtime/value.c:89-108; lib/cgt/program.ml:100-104.

Constant_begin detects only state == this context’s id+1. If two contexts begin constants A and B respectively, then each reads the other’s unfinished constant, both wait on the condition variable forever. No context can reach constant_end to wake the other. A constant initializer can invoke spawned work, so pre-main initialization does not exclude this state.

Evidence and limit: Reproduced against actual runtime/value.c: two pthread contexts begin their own states, synchronize on a barrier, then begin the other’s state; process timed out after 3 seconds.

F11 — Drained one-MiB chunks are cached forever with no bound or release path

Severity: Medium.

Location: runtime/arena.c:183-203; runtime/arena.c:235-256; runtime/snapshot.c:130-146.

zane_unmap returns every ordinary ZANE_CHUNK mapping to context->spare instead of freeing it. Idle contexts transfer all spares to a global pool, and allocation consumes spares, but no code trims either cache. A temporary scope’s high-water ordinary-chunk footprint remains resident for the rest of the process even after every allocation dies. This is retained free capacity, not an ownership leak.

Evidence and limit: Actual-runtime measurement: 772 KiB RSS before allocation, 132908 KiB at peak, 132908 KiB after draining. The free list retained 128 one-MiB chunks.

F30 — Overflow fault handlers call stdio.

Severity: Medium.

Location: runtime/region.c:129-140; runtime/region.c:150-171; runtime/region.c:270-274.

The POSIX fault handler calls stack_full/too_deep_in, then zane_stop with flushing enabled, then fflush(stdout). fflush is not async-signal-safe and can interact with interrupted stdio state or another thread’s output lock. The commit-failure path already avoids flushing for that lock problem. Source-confirmed call path; no induced deadlock run.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

Architecture and file structure

F21 — Lowering is a single oversized recursive dependency cluster.

Severity: Medium.

Location: lib/cgt/lower.ml:1-1834.

Intrinsic runtime calls, operators, arrays, strings, lambdas, constructors/defaults, ownership, match dispatch, subscripts, ordinary/function-value calls, spawn frames, handlers, expansion and statements share one 1,834-line recursive walk and mutable state. These responsibilities cannot be inspected independently. Architectural judgment.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

F22 — Generic tree traversal is owned by particular analyses, and duplicated by optimization.

Severity: Medium.

Location: lib/tst/analyses/exits.ml:16-61; lib/tst/tst.mli:15-16; lib/cgt/regions.ml:26-148; lib/cgt/cgt.ml:8-9; lib/optimize/fold.ml:23-88.

TST parts/stat_exprs live in Exits; CGT parts/walk/map live in Regions. Both are structural model operations used outside those analyses. Fold duplicates the child/body inventories even though Cgt exposes parts. Architectural judgment and confirmed duplication.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

F23 — Internal runtime ABI numbers are handwritten independently in C and OCaml.

Severity: Medium.

Location: runtime/zane_internal.h:175-188; lib/codegen/frames.ml:11-17; lib/codegen/emit.ml:331-341; lib/codegen/walks.ml:37-48; tests/unit/unit.ml:185-279.

Scope/task sizes, heap/context/handle offsets and class counts are repeated in several modules. C static assertions validate only C constants against C declarations; unit ABI checks read function signatures, not internal-record offsets. No current offset mismatch is alleged. Architectural risk.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

F24 — Semantic phases share an unrestricted mutable state object.

Severity: Medium.

Location: lib/tst/model/env.ml:158-229; lib/tst/semantics.ml:12-33.

Env.t combines name tables, partially defined types, alias state, deferred closures, overload registries, generic queues, counters and instance notes. Every pass receives the same object; stage readiness lives in flags and options. Phase invariants and allowed writes are absent from the type boundary. Architectural judgment.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

Regression-test weaknesses

F12 — Negative parser tests accept internal compiler errors and signal crashes as correct rejection

Severity: Medium.

Location: tests/parser/syntax_test.py:34-36.

assert_rejects checks only returncode != 0. A compiler exit 3 (internal error), abort, or SIGSEGV passes the same assertion as the expected source rejection exit 1, hiding robustness regressions across the rejection cases.

Evidence and limit: Confirmed directly from the test assertion.

F26 — Generated-program regression suites force checking mode.

Severity: Medium.

Location: tests/codegen/dune:14-18; tests/objects/dune:9-13; dev/bin/check-programs:17-19; lib/codegen/emit.ml:390-414.

These suites set ZANE_CHECK=1. The emitted inline drain branch requires checking=0, so it never executes in those runs. Runtime C tests alone do not execute the separate emitted LLVM branch. Confirmed coverage gap; this audit additionally runs the fixtures with checking=0.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

F27 — Memory-probe corpus is outside automated regression gates.

Severity: Medium.

Location: tests/memory-probes/run:33-48; docs/memory-semantics-findings.md:11-24; justfile:52-56.

The test-compiler suite excludes memory-probes. Its runner overwrites committed outputs, records rejection/build errors and plain/optimized differences, and does not fail on those outcomes. Some behaviors have separate golden coverage; the probe corpus itself is not a gate.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

F28 — Golden-file presence decides silently whether a fixture is tested.

Severity: Low.

Location: tests/gen/gen_rules.ml:83-92; tests/gen/gen_rules.ml:139-141; tests/codegen/README.md:5-12.

The generator enumerates golden names, not fixtures. A fixture without a golden is ignored; deleting its last golden removes its tests without an orphan-fixture error. The generated-rule freshness check cannot establish fixture coverage.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

Diagnostics and small tooling defects

F03 — Diagnostic carets use code-point counts rather than terminal cell widths

Severity: Low.

Location: lib/diagnostic/render.ml:12-44.

visual_col_of_idx and expand_tabs count every UTF-8 leading byte as one column. Combining marks occupy zero cells and wide CJK/emoji commonly occupy two. Diagnostics after such text (including string literals before an error) point at the wrong displayed column.

Evidence and limit: Confirmed by algorithm inspection.

F04 — The diagnostic underline gutter stops aligning at double-digit line numbers

Severity: Low.

Location: lib/diagnostic/render.ml:84-93.

The source row uses %d | but the caret row always starts |. At line 10 and beyond the caret row begins one or more cells to the left of the source text.

Evidence and limit: Confirmed by format strings.

F19 — Ambiguity-search timeouts accept NaN and infinity

Severity: Medium.

Location: tools/ambiguity/profiles.py:66-94; tools/ambiguity/engine/config.ml:181-184; tools/ambiguity/engine/search.ml:388.

parse_duration checks only seconds < 0 after conversion. Numeric TOML nan/inf and sufficiently large digit strings pass. Config.settings likewise checks only value < 0 for –timeout, whereas it explicitly checks finiteness for max_frontier_ratio. A non-finite timeout reaches deadline arithmetic and no longer represents the requested finite search bound.

Evidence and limit: Python reproduction: parse_duration(float(‘nan’)), parse_duration(float(‘inf’)) and parse_duration(‘9’*400) returned non-finite values without error.

F20 — Source excerpts and diagnostic paths emit terminal controls unchanged

Severity: Low.

Location: lib/diagnostic/render.ml:84-100.

The renderer copies the source line and filename directly into terminal output; expand_tabs changes tabs only. A literal or path containing ESC/OSC/CSI controls is interpreted by the terminal instead of being displayed as source text. This can alter or erase the diagnostic and has effects beyond its visible characters.

Evidence and limit: Confirmed raw-output path; no control sequences were executed in the user terminal.

F29 — Identical duration regex assignment is duplicated consecutively.

Severity: Low.

Location: tools/ambiguity/profiles.py:32-33.

DURATION_PART is assigned the identical re.compile expression on two consecutive lines. This is a duplicated parser-rule declaration with no behavioral benefit.

Evidence and limit: Source inspection; architectural judgments and coverage findings describe their evidence in the finding.

Verification corrections

F06, the original uppercase-Unicode package-alias concern, is withdrawn: both the ASCII and Unicode uppercase examples were rejected by the grammar. F31 concerns a different, reproduced inconsistency in explicit package-path options.

The initial F05 notebook entry also included target-machine ownership. LLVM 19 binding inspection showed finalizers for target machines and builders; the retained finding covers contexts and modules only.

A 128-byte-alignment allocator probe was excluded because current compiler layouts do not require that alignment. No existing ABI-offset mismatch, proof unsoundness, or failing existing executable fixture is alleged.

Binding references used for ownership and array counts

The external binding checks used the pinned release line: LLVM 19.1.7 llvm_ocaml.c and target_ocaml.c. These establish the explicit context/module disposal API, automatic target-machine/builder finalizers, and the LLVMArrayType call used by the OCaml array constructor.