Language atlas
uni5 Zig Kernel Audit
Date: 2026-04-08 Branch: agent/z6-spectral/vlam-run Build status: Clean build, all tests pass (zig build + zig build test)
Architecture Overview
uni5 is a self-contained TLC (Ternary Lambda Calculus) combinator-graph kernel. The pipeline is: lambda terms (trit strings) -> parse -> Kiselyov bracket abstraction -> combinator graph on a flat heap -> lazy graph reduction -> readback to lambda (optional) -> serialize to combinator trits for persistence.
The system is designed for an evolutionary loop: ingest bytes through a kernel term, measure fitness (|term| + residual), mutate/crossover/select, merge survivors, repeat.
File-by-File Audit
Core Pipeline (complete, tested, working)
term.zig – De Bruijn lambda calculus terms with let extension. - Data: Term = union(enum) { lam, app, var_, let } – pointer-based tree. - Status: Complete. Structural equality, constructors, all clean. - No TODOs.
parser.zig – TLC ternary encoding: parse trit strings to Term and back. - Encoding: 0 = Lam, 1 = App, 20 + nat = Var, 21 = Let, 22 = reserved. - Self-delimiting natural encoding for de Bruijn indices. - Status: Complete. Round-trip tested against Python reference fixtures. - No TODOs.
combinator.zig – Flat heap of combinator graph nodes. - Data: Heap backed by ArrayList(Node), Node = union(enum) { comb: Tag, app: App }. - 12 combinator tags: S, K, I, B, C, R, T, D, F, M, Y, Cons. - Interned singletons for each tag. In-place mutation via set(). reset() for reuse. - Status: Complete. Well-tested.
clapp.zig – Smart application (construction-time combinator rewrites). - Ports Tromp’s non-qOpt clapp() rewrites: K I -> F, B K -> D, C I -> T, etc. - 8 rewrite rules that fire before anything hits the reducer. - Status: Complete.
kiselyov.zig – Lambda -> combinator graph via Kiselyov bracket abstraction. - Bit-packed UseList (u64) tracks variable usage across binders. - Y-template recognition: detects (lambda x. x x)(lambda x. f(x x)) -> Y f. - Let desugaring: let M N -> App(Lam(N), M) at convert time. - Status: Complete. Tested against all standard combinators + E_REF fixture.
reduce.zig – Lazy graph reducer (spine-based, in-place rewriting). - All 12 combinators dispatched: I(1), K(2), F(2), T(2), D(3), B(3), C(3), R(3), Cons(3), S(3), M(1), Y(1). - Y unfolds lazily: Y f -> f (Y f) with a new app cell pointing back at Y. - Fuel-limited. Returns WHNF. - Status: Complete. Tested including omega divergence detection.
readback.zig – Combinator graph -> lambda term -> beta-normal form. - Expands each combinator to its canonical lambda definition. - Full beta-normalizer (shift/subst/step, ported from Python). - Status: Complete. Used for readback in the CLI –eval path. - Note: Slow for large terms (single-step reducer). Not used in the hot path.
serialize.zig – Direct combinator graph trit encoding (no lambda roundtrip). - Encoding: 0 X Y = app, 1 DDD = combinator (3 fixed base-3 digits). - v0 tree-expands DAGs (loses sharing). 2 reserved for v1 back-references. - graphSize (sharing-aware) and treeSize (expansion count). - Status: Complete. Round-trip tested.
Evolutionary Machinery (complete, tested, working)
dna.zig – Genetic operators on combinator graphs. - 4 operators: point_mutation, deletion, inversion, duplication. - Tree-uniform selection (shared subgraphs get proportional exposure). - Path-copying immutable update. - Crossover: pairwise subtree swap between two organisms. - Status: Complete. Well-tested including sharing preservation.
lgg.zig – Structural intersection (merge) + hash-cons CSE. - simpleIntersect: where two graphs diverge, emit I. - Properties: idempotent, commutative, associative (semilattice meet). - hashConsCSE: bottom-up deduplication of structurally-identical subgraphs. - merge = intersectAll + CSE. - Status: Complete. Semilattice properties tested.
search.zig – Phase 1 fixpoint combinator search (parallel). - Enumerates lambda terms by constructor count, filters by self-application, trit count, and semantic fixpoint check. - Parallel via atomic work-stealing with 1024-candidate chunks. - Status: Complete. Y_REF passes isFixpointCandidate.
ingest.zig – Streaming byte ingestion in combinator space. - Worker holds kernel + byte_builder compiled once, reused per byte. - Byte encoding: 9-lambda CPS tuple (lambda f. f b7 b6 … b0), bits as K/F. - Step: reduceWHNF(app(app(kernel, state), byte_graph)). - Status: Complete. Tested with identity and second-projection kernels.
train_loop.zig – Full epoch orchestrator. - Corpus mmap, chunking, parallel workers, crossover pass, shortest-N selection, merge via lgg, multi-epoch loop. - Status: Complete. End-to-end tested on tiny corpora (2 epochs, 3 workers).
Bootstrap (the critical path)
bootstrap.zig – Bootstrap term construction. - Env struct for named-binder lambda construction with auto de Bruijn indexing. - Scott-encoded data types: Z, succ, Leaf, Branch. - Two bootstrap variants:
- Trie bootstrap (
buildTrieInitialState,buildTrieKernel):- Depth-8 binary trie with Scott Peano nats at leaves.
- Initial state: let-chain building
leaf_z, thenl1throughl8. - Kernel: destructures byte into 8 bits, walks trie 8 levels, increments leaf, rebuilds path with let-sharing.
- STATUS: BROKEN. Comments at line 178-191 explicitly document the bug: “destroys structure when iterated: after a handful of bytes the state collapses to a 3-node combinator salad. Root cause is unknown as of U5-4.”
- Tracked as U5-12.
- Cons-list stub (
buildConsInitialState,buildConsKernel):- Initial state: I (empty list sentinel).
- Kernel:
lambda s. lambda b. lambda f. ((f b) s)– cons prepend. - STATUS: WORKING. This is the active default (
buildInitialState = buildConsInitialState). - Grows linearly per byte (~20 combinator nodes/byte). Fine for small runs.
CLI (main.zig)
- Commands: –eval, –bench, –bench-e-ref, –graph-stats, –bootstrap-stats, –search-phase1, –train-loop.
- Status: Complete. All commands functional.
Tests
- 3 external test files: test_parser.zig, test_e_ref.zig, test_let.zig.
- All inline tests in source files.
- The historical test suite reported a reduction of the 82-trit reference term. Passing that case does not establish self-interpretation.
- All tests pass clean.
The Bug: Trie Kernel Structure Collapse (U5-12)
Symptoms
The trie bootstrap compiles and its initial state is valid, but after ingesting even a single byte, the state collapses from a structured depth-8 trie into an unrecognizable small combinator expression. The test output shows:
[U5-12 real kernel 1 byte] (I ((D (: (((B ((B D) T)) (D T)) K))) (((I F) (D (T K))) (I (D (T K))))))
This is ~20 nodes of combinator salad, not the expected depth-8 trie (~500+ nodes). The trie structure is completely destroyed on the first byte ingestion.
Root Cause Analysis
The trie kernel is a complex 39-binder lambda term that: 1. Destructures the byte into 8 Church booleans 2. Walks the trie 8 levels deep using each bit to select a branch 3. Finds the leaf, increments its counter 4. Rebuilds the path back up with let-sharing
The most likely failure points:
Bit selection direction.
buildPickAndDescendusesbit r l(bit selects between r and l), but the “other” binding usesbit l r. If the bit semantics are K=true=select-first, thenbit r lselects r when true and l when false. Meanwhile the rebuild usesbit (Branch other inner) (Branch inner other). There may be a left/right confusion between the walk-down path and the rebuild-up path.Scott encoding mismatch. The state is
Branch x y = lambda l. lambda b. b x y, and the kernel destructures asstate placeholder handler. If the Branch encoding puts the branch handler second (lambda l. lambda b. b x y), thenstate z handlerpasses z as the leaf handler and handler as the branch handler – correct. But if the let-chain wrapping changes the shape after Kiselyov compilation, the arguments may land in wrong positions.let-sharing breaks under graph rewriting. The rebuild uses extensive let-bindings to avoid exponential blowup. These desugar to App(Lam, rhs) during Kiselyov, which the graph reducer then reduces. If the in-place graph rewriting of the reducer clobbers shared nodes, the sharing-based rebuild would produce garbage.
De Bruijn index miscalculation in the nested binder stack. The kernel has ~39 binders (4 constructor lets + 2 lambda params + 8 bit lambdas + 8*3 level handlers + 8 other-lets + 1 n-lambda + 8 inner-lets). A single off-by-one in any of these would silently produce a term that compiles but computes wrong.
The diagnostic tests show: - Identity rebuild kernel (1 level): WORKS. State trits preserved exactly. - Two-level identity rebuild: PARTIALLY WORKS. State trits change from 34 to 44 (grows instead of being identity), suggesting the two-level rebuild introduces extra structure. - Real trie kernel: COLLAPSES.
The progression from “works at 1 level” to “partially broken at 2 levels” to “completely broken at 8 levels” points toward a compounding error in the rebuild path, most likely the bit-direction/other-selection logic in buildLevelHandler / buildPickAndDescend / rebuildLevel.
What the Two-Level Diagnostic Reveals
The two-level test shows state_trits=34 but result_trits=44. Since this is an identity rebuild (no increment, just destructure-and-reconstruct), any size change means structure is being added or rewritten incorrectly. The extra 10 trits suggest one of the inner Branch reconstructions is wrapping an extra layer or duplicating a subtree.
What Works
- Full pipeline: Parse -> Kiselyov -> Reduce -> Readback. Verified against Python E_REF oracle (3 test cases, 500K fuel).
- Cons-list bootstrap: End-to-end functional. Workers ingest bytes, state grows monotonically, distinct corpora produce distinct states, crossover and merge work, multi-epoch loop runs.
- All evolutionary machinery: dna, lgg, serialize, train_loop – tested and functional.
- CLI: All 7 commands work.
- 12-combinator reducer: All reduction rules correct, Y lazy unfold works.
What is Broken
- Trie kernel structure collapse (U5-12). The depth-8 trie bootstrap destroys its own state on the first byte ingestion. The cons-list stub works around this but provides no prediction capability (uniform 8-bit residual).
What Needs to Be Built
To fix U5-12 (trie kernel)
Isolate the two-level rebuild bug. The identity rebuild adds 10 trits at depth 2. Instrument the combinator graph before and after reduction to find which Branch reconstruction goes wrong.
Check bit-direction semantics. Verify that
bit r lin buildPickAndDescend selects the correct child, and that the rebuild’sbit (Branch other inner) (Branch inner other)reconstructs the correct parent. K=true should select its first argument; F=false should select its second.Check Scott encoding consistency. Ensure that when the kernel does
state z handler, the z lands in the leaf-handler position and handler lands in the branch-handler position of the Scott-encoded Branch/Leaf.Add a depth-1 trie test. Build a minimal Branch(Leaf(Z), Leaf(Z)) state, apply the trie kernel with a known bit pattern, verify the output is Branch(Leaf(Succ Z), Leaf(Z)) or its mirror.
To reach a working byte-by-byte predictor
- Fix U5-12 (trie kernel computes correct state updates).
- Add prediction output: kernel returns (new_state, prediction) pair.
- Measure actual residual: compare prediction distribution to observed byte.
- Wire residual into the fitness function: p = |term| + sum(residual).
- Switch buildInitialState/buildKernel from cons-stub to trie.
Performance path (not blocking)
- serialize.zig v1: DAG back-references (
2prefix) to preserve sharing through round-trips. - Heap compaction / GC between epochs.
- SIMD-friendly heap layout for the reducer hot path.
Summary
In the April 2026 branch snapshot, the author reported a clean build across 14 source files and passing tests. The evolutionary loop ran end to end on the cons-list bootstrap stub.
The reported blocker for the depth-eight trie was loss of state structure during reduction. The reconstruction inside the bit-path handler was a candidate cause. This note does not establish the current status of that historical build.
Cite this page
Richard Hoekstra. uni5 Zig Kernel Audit. https://richardhoekstra.nl/atlas/zig_audit.html