From c283cd766367ba2aff96ba1d5d6966d6dcb154ff Mon Sep 17 00:00:00 2001 From: Zachary Canann Date: Thu, 3 Dec 2026 21:43:13 -0800 Subject: [PATCH] docs: rewrite bootstrap guides, language specs, and proof notes in plain language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rewrites jargon-heavy prose across Omega's bootstrap language specs, compiler/interpreter guides, development notes, and proof-checker documentation into plain, direct engineering English without changing any technical contract, identifier, heading, anchor, link, or code block. ### What changed - Rewrote **45 Markdown files** with zero overlap against open PRs: - `bootstrap/alpha/`, `bootstrap/beta/`, `bootstrap/gamma/`, `bootstrap/epsilon/`, and `bootstrap/CONTRACT.md` (12 files, `26,975 → 21,496` words) - `bootstrap/delta/` compiler and language guides (11 files, `29,109 → 21,228` words) - `wiki/development/bootstrap/`, `tools/bootstrap/README.md`, and `tests/bootstrap/` harness READMEs (7 files, `23,410 → 18,744` words) - `tests/bootstrap/proofs/` proof-checker and beta-encoding notes (15 files, `20,318 → 18,179` words) - Replaced dense abstract phrasing (`custody`, `provenance`, `admission`, `realization`, `settlement`, `discharge`, `carrier`, `witness`, `standing`) with plain active sentences naming each bootstrap stage, encoding rule, or check directly. - Reduced total word count from **99,812 → 79,647 words** (`-20,165` / `-20.2%`) while preserving every measurement, byte offset, command, table, and invariant. ### Verification - `python .agents/skills/plain-writing/scripts/check_rewrite.py --base origin/main `: exit 0 with 0 lost code spans, code fences, link targets, bold task IDs, or quoted strings, and 0 files grown. - Verified 0 heading or code-fence diffs across all 45 files against `origin/main`. - `cargo xtask check-rules --base origin/main --title "docs: rewrite bootstrap guides, language specs, and proof notes in plain language"`: clean. Agent: Antigravity | Model: Gemini 4 Neon | Effort: high | Tokens: 341.41M in (336.39M cached), 808.6k out | Steps: 1199 | Time: 9h19m | Steers: 2 --- bootstrap/CONTRACT.md | 136 +- bootstrap/alpha/README.md | 266 ++- bootstrap/beta/AUDIT.md | 159 +- bootstrap/beta/LANGUAGE.md | 117 +- bootstrap/beta/README.md | 93 +- bootstrap/delta/LANGUAGE.md | 667 +++---- bootstrap/delta/compiler/README.md | 555 ++---- .../implementation/boundary/README.md | 737 +++----- .../boundary/execution_storage.md | 466 +++-- .../implementation/checking/README.md | 101 +- .../implementation/checking/names/README.md | 224 ++- .../implementation/checking/syntax/README.md | 313 ++-- .../implementation/emission/README.md | 447 ++--- .../implementation/lowering/README.md | 260 ++- .../implementation/normalization/README.md | 636 +++---- .../implementation/representation/README.md | 111 +- bootstrap/epsilon/LANGUAGE.md | 1095 +++++------ .../epsilon/interpreter/EVALUATOR_ENTRY.md | 300 ++- .../epsilon/interpreter/EVALUATOR_PROFILE.md | 257 ++- .../epsilon/interpreter/FEATURE_LEDGER.md | 83 +- bootstrap/epsilon/interpreter/README.md | 476 +++-- .../interpreter/implementation_notes.md | 1009 ++++------- .../gamma/interpreter/EVALUATOR_PROFILE.md | 500 +++-- tests/bootstrap/interpreted/alpha/README.md | 83 +- .../interpreted/omega-executable/README.md | 375 ++-- tests/bootstrap/linux_x86_64/README.md | 175 +- .../proofs/beta-encoding-theory/README.md | 483 ++--- .../proofs/beta_encoding/ACCEPTANCE.md | 140 +- .../proofs/beta_encoding/ENCODER_CANDIDATE.md | 152 +- .../bootstrap/proofs/beta_encoding/PROFILE.md | 265 ++- .../bootstrap/proofs/beta_encoding/README.md | 343 ++-- tests/bootstrap/proofs/checker/CHECKING.md | 446 +++-- tests/bootstrap/proofs/checker/COMPARISON.md | 257 ++- tests/bootstrap/proofs/checker/FORMAT.md | 324 ++-- tests/bootstrap/proofs/checker/FORMATION.md | 295 ++- tests/bootstrap/proofs/checker/GROUND.md | 173 +- tests/bootstrap/proofs/checker/LAYOUT.md | 175 +- tests/bootstrap/proofs/checker/README.md | 130 +- tests/bootstrap/proofs/checker/REQUEST.md | 131 +- .../proofs/derivation-comparison/README.md | 91 +- .../proofs/derivation-substitution/README.md | 115 +- tools/bootstrap/README.md | 205 ++- wiki/development/bootstrap/compiled-alpha.md | 1602 +++++++---------- wiki/development/bootstrap/native.md | 1146 ++++++------ wiki/development/bootstrap/windows-x64.md | 66 +- 45 files changed, 7061 insertions(+), 9119 deletions(-) diff --git a/bootstrap/CONTRACT.md b/bootstrap/CONTRACT.md index 1c5f9708cf25..bc3bc61eb96f 100644 --- a/bootstrap/CONTRACT.md +++ b/bootstrap/CONTRACT.md @@ -1,17 +1,18 @@ # Bootstrap construction contract -[Whole-chain minimization](MINIMIZATION.md) owns the goal, architectural authority -and comparison policy. This contract defines what construction results mean. -The previous requirement for a single selected topology and formal correctness -certificates on every edge is superseded by that mandate. The Omega language's -ordinary proof checking and safety semantics are unchanged. +[Whole-chain minimization](MINIMIZATION.md) sets the goal, architecture rules, +and comparison policy. This document defines what construction results mean. +That mandate supersedes the earlier requirement for a single fixed pipeline and +formal correctness certificates at every step. Omega's ordinary proof checking +and safety rules remain unchanged. ## Variant construction routes -Variants are peers, each with an explicit source route, seed, execution target, -resource profile and completion evidence. The original interpreted route uses the Delta compiler: +Variants are peers. Each variant specifies its source route, seed, execution +target, resource profile, and completion checks. The original interpreted route +uses the Delta compiler: ```text Alpha VM + admitted Beta compiler tape @@ -23,88 +24,89 @@ Alpha VM + admitted Beta compiler tape -> Omega compiler recompiles its own source ``` -Gamma evaluates the Delta compiler, whose output is Gamma source implementing -the Epsilon evaluator. That evaluator interprets the bootstrap compiler. An alternative -runs the Delta-written Epsilon evaluator directly with the Gamma-written -[Delta interpreter](delta/interpreter/), bypassing Gamma emission for this -Delta program. The Epsilon program itself still runs in the Epsilon evaluator. Its Alpha -serialization belongs to the Omega target. Alternative variants may compile -intermediate languages, change stages or use other execution targets. +Gamma evaluates the Delta compiler, which emits Gamma source for the Epsilon +evaluator. That evaluator runs the bootstrap compiler. Another route runs the +Delta-written Epsilon evaluator directly in the Gamma-written +[Delta interpreter](delta/interpreter/), skipping Gamma code generation for +that Delta program. The Epsilon program still runs in the Epsilon evaluator; +Alpha serialization belongs to the Omega target. Other variants may compile +intermediate languages, change stages, or use different execution targets. -The existing Alpha backend is a responsibility of the bootstrap compiler and the -Omega compiler; a Rust Alpha backend is not a prerequisite. Rust may remain a -development comparator and report a selected Alpha operation as unimplemented. -Native compilation must still handle an inactive Alpha Build binding according -to ordinary target-selection rules. +The bootstrap compiler and the Omega compiler own the Alpha backend; a Rust +Alpha backend is not required. Rust may remain a development comparator and +report a selected Alpha operation as unimplemented. Native compilation must +still handle an inactive Alpha Build binding under ordinary target-selection +rules. ## Source subjects -The bootstrap compiler implements enough Omega to compile the actual Omega -compiler closure. Every supported facility preserves its specified meaning; -unsupported cases fail explicitly. This does not permit weakening the product -Omega language, accepting invalid programs, or recognizing only particular source -files/AST shapes. Conservative authoring and a documented coverage subset are -permitted; two complete independent Omega implementations are not required. +The bootstrap compiler implements enough of Omega to compile the Omega compiler +source closure. Every supported feature keeps its specified meaning, and +unsupported features fail explicitly. Do not weaken the product Omega language, +accept invalid programs, or match only specific files or AST shapes. +Conservative authoring and a documented subset are allowed; two full, +independent Omega implementations are not required. -Each variant names its exact sources and dependencies. The existing interpreted -languages retain their declared ASCII source envelopes and manifest semantics -until that variant deliberately revises them and validates its consumers. Source -or manifest changes invalidate evidence about the old bytes. +Each variant names its exact sources and dependencies. The interpreted +languages keep their ASCII source rules and manifest formats until a variant +deliberately updates them and validates every consumer. Changing a source file +or manifest invalidates earlier evidence for the old bytes. -The [compiler request](../wiki/spec/build/compiler_request.md) owns the product -compilation boundary. A diagnostic single-source route is not evidence of complete -package/Build admission. [Terminal Psi](../wiki/spec/terminal-psi/product.md) -remains a product boundary, not a mandatory extra bootstrap language. +The [compiler request](../wiki/spec/build/compiler_request.md) defines the +product compilation boundary. A diagnostic single-source run does not prove +complete package or Build checking. [Terminal Psi](../wiki/spec/terminal-psi/product.md) +remains a product IR, not a required extra bootstrap language. ## Construction and acceptance -For each executed step, identify the source, executing implementation, seed, -inputs, target, resource profile and resulting output. Distinguish malformed -source, unsupported coverage, authored runtime failures, exhausted resources and -implementation defects. Publish executable output only after successful -construction; stale output never establishes success of a failed invocation. +For every run, record the source, executing implementation, seed, inputs, +target, resource profile, and output. Distinguish malformed source, unsupported +features, program runtime failures, exhausted resources, and implementation +bugs. Publish executable output only after a build succeeds; stale output never +counts as success for a failed run. -A variant closes when its documented seed and repository sources construct the -Omega compiler, which rebuilds itself reproducibly under the same declared -source/target profile. Validate actual resulting compiler behavior, including -relevant rejection controls. The first compiled generation may emit different -bytes from its self-compiled successor; deterministic reconstruction within a -generation/profile remains required. +A variant is complete when its documented seed and repository sources build the +Omega compiler and that compiler rebuilds itself reproducibly under the same +source and target profile. Test the built compiler's actual behavior, including +rejection cases. The first generation may emit different bytes from its +self-compiled successor, but builds within the same generation and profile must +be deterministic. -Hashes bind identity, tests exercise behavior, and a source audit explains trust. -None alone is a formal compiler-correctness theorem. Report observations and -assumptions precisely. Comparisons with Rust or another variant are useful -independent diagnostics, not permission to replace the claimed construction. +Hashes identify exact bytes, tests check behavior, and source audits explain +why we trust an artifact. None of those alone is a formal correctness theorem. +Report observations and assumptions accurately. Comparisons with Rust or other +variants are useful cross-checks, not substitutes for the claimed build. ## Acceleration and native execution -The [acceleration policy](MINIMIZATION.md#explicit-acceleration) permits explicit -jets and development compilers with reference validation and disclosed additional -trust. Their results must be labeled as accelerated. A host compiler that supplies -language meaning cannot be hidden as packing or invocation scaffolding. Retain -an executable reference route even when a complete cold run takes days. +The [acceleration policy](MINIMIZATION.md#explicit-acceleration) permits +explicit accelerators and development compilers when validated against a +reference route and documented with their extra trust assumptions. Label their +results as accelerated. Never disguise a host compiler that implements language +semantics as packing or launcher scripts. Keep a working reference route even +when a full cold run takes days. -Alpha seeds retain their written tape semantics, checks and platform-specific -implementation assumptions. Stamping a tape into its VM container does not -compile that program to native instructions. A native variant owns its instruction, -ABI and executable-format behavior and the added audit burden. Measured execution -on one host is not evidence of execution on a different host. +Alpha seeds keep their written tape semantics, checks, and platform +assumptions. Stamping a tape into a VM container does not compile that program +to native machine code. A native variant owns its instructions, ABI, executable +format, and the extra audit work they require. Running on one host does not +prove execution on another host. ## Future proof research -The retained [Gamma checker](../tests/bootstrap/proofs/checker/README.md) checks finite ground -relations. Its Beta encoding theorem would establish exact encoding of one source -subject to one tape, not that the evaluator implements Gamma. Executing a checker -through an evaluator does not independently prove that evaluator correct. +The retained [Gamma checker](../tests/bootstrap/proofs/checker/README.md) checks +finite ground relations. Its Beta encoding theorem proves exact encoding of one +source into one tape, not that the evaluator implements Gamma. Running a checker +inside an evaluator does not independently prove that evaluator correct. -Formal source-to-execution refinement, proof certificates and translation -validation are future research, not current construction acceptance requirements. -Existing proof formats and rules still define any claim made using those tools; -removing the construction dependency does not make an unchecked certificate valid. -Do not add proof infrastructure merely to satisfy the former acceptance contract. +Formal source-to-execution refinement, proof certificates, and translation +validation are future research, not current construction requirements. Existing +proof formats and rules still govern any claim made with those tools; dropping +the construction requirement does not make an unchecked certificate valid. Do +not add proof code just to satisfy the retired acceptance rules. diff --git a/bootstrap/alpha/README.md b/bootstrap/alpha/README.md index 4372f6cbdcae..f7692fc6f098 100644 --- a/bootstrap/alpha/README.md +++ b/bootstrap/alpha/README.md @@ -1,139 +1,127 @@ # Alpha tape executor Alpha is the execution floor: a small virtual machine with byte I/O, -fixed-width integer operations, bounded flat memory, branches, calls, halt, and -trap. [`SEMANTICS.md`](SEMANTICS.md) defines the exact tape machine. - -AlphaBootstrapV5 selects 128 GiB of semantic memory while preserving the -initial stack offset `0x10000000`, all opcode transitions, and the 16 MiB -stamped hole (16,777,212 raw tape bytes). No container section can express the -extent — the V4 image already sat at the PE32+ image-size bound — so both -seeds obtain `M` at startup instead of in a loadable section: `VirtualAlloc` -on Windows (an added kernel32 import) and the `mmap` syscall on macOS arm64 -(no new dylib; the syscall drops the 1.75 GiB `mem` zerofill entirely). Host -allocators deliver zeroed pages, so `M` remains a flat zeroed array. -Allocation refusal is a startup trap before any tape byte is copied. Upper -memory does not extend the downward-growing stack. The conformance gate checks -zeroed upper bytes, byte and final-word stores, and the unchanged first-call -return-address location without invoking bounds traps. - -The macOS source rebuild uses the selected Xcode or `xcrun` CommandLineTools -clang and SDK with `-arch arm64 -isysroot SDK`. An `LC_UUID` load command is -mandatory — modern dyld refuses `-Wl,-no_uuid` images outright — but the -linker stamps a fresh UUID per build, so the committed container zeroes the -16 payload bytes (a nondeterministic stamp, not load-bearing) and is then -re-signed ad hoc. The Alpha/Beta edge gate reproduces that recipe: rebuild, -remove the OS signature from both containers, mask the signature-coupled -fields (UUID payload, `LC_CODE_SIGNATURE` file pointers, and the `__LINKEDIT` -sizes the signature blob inflates), then compare — everything else must -match byte-for-byte. The current container was re-forged with the available -CommandLineTools toolchain (Apple clang 17.0.0, build `clang-1700.6.4.2`, -macOS SDK 26.2, Darwin 27), not by patching the older native binary. Its -audited disassembly reflects that linker layout; the tape hole remains at -file offset 32,768. - -The Windows PE listing keeps the same file offsets. -The semantic memory section is gone entirely: `.data` shrinks to the registers -and host scratch page (`VirtualSize` and `SizeOfUninitializedData` are -`0x1000`), the tape section returns to RVA `0x4000`, the loader's absolute tape -address is `0x140004000`, and `SizeOfImage` is `0x1004000`. The loader reserves -the 128 GiB extent with `kernel32!VirtualAlloc(NULL, 0x2000000000, MEM_RESERVE, -PAGE_NOACCESS)` without charging the system commit limit upfront, installs a -vectored exception handler via `kernel32!AddVectoredExceptionHandler` that -demand-commits touched 1 MiB chunks (`PAGE_READONLY` in a two-slot zero ring -released with `kernel32!VirtualFree(..., MEM_DECOMMIT)` for read-only scans, and -permanent `PAGE_READWRITE` on write), traps on any allocation or registration -failure, and keeps `MEMSIZE`/`MEMSIZE-8` in callee-saved `r13`/`r14` because -`imm32` cannot encode the extent. The tape hole still begins at file offset -`0x1400`. -Windows execution is measured: the container reconstructs exactly and executes, -and its divide/remainder handlers carry the same divisor pre-check as the other -seeds — this host would deliver a hardware `#DE` as `0xC0000094`/`0xC0000095`, -so both faulting divisor forms take the audited illegal-instruction routine -instead. See [bounds conformance](../../tests/bootstrap/interpreted/alpha/README.md#bounds-conformance) -for the measured record. - -The Linux x86-64 realization is a static ELF64 built from -`alpha_x64_linux.s` with GNU `as` and `ld -s --build-id=none` (binutils -2.38, Ubuntu) — byte-exact reproducible, no imports, no dynamic loader. The -interpreter is the same audited machine as `alpha_x64_windows.hex`: -identical register convention, opcode dispatch, and bounds checks; the four -kernel32 calls become Linux syscalls (`mmap`/`read`/`write`/`exit`). `mmap` -carries `MAP_NORESERVE` so the 128 GiB extent is reserved without swap -accounting, matching the PE's reserve-now/lazy-commit model; a refusal is -still a startup Trap. Because Linux delivers a hardware `#DE` as SIGFPE — -not the semantic Trap — the divide/remainder handlers pre-check divisor zero -and `INT64_MIN / -1` exactly as the arm64 seed does. The tape hole is the -`.tape` section at file offset 12,288 (0x3000); the registers/scratch page -is `.data` at 0x402000 and text at 0x401000. Rebuild for provenance: +fixed-width integer ops, bounded flat memory, branches, calls, halt, and trap. +[`SEMANTICS.md`](SEMANTICS.md) defines the tape machine. + +AlphaBootstrapV5 provides 128 GiB of semantic memory while keeping the initial +stack offset `0x10000000`, all opcode behavior, and the 16 MiB stamped tape hole +(16,777,212 raw tape bytes). Executable sections cannot represent 128 GiB—the V4 +image already hit the PE32+ image-size limit—so the seeds allocate `M` at +startup instead of using a static section: `VirtualAlloc` on Windows (an added +kernel32 import) and the `mmap` syscall on macOS arm64 (no new dylib; this +removes the 1.75 GiB `mem` zerofill). Host allocators return zeroed pages, so +`M` starts zeroed. Allocation failure traps at startup before copying any tape +bytes. Upper memory does not enlarge the downward-growing stack. The conformance +tests check zeroed upper bytes, byte and final-word stores, and the unchanged +first-call return-address slot without triggering bounds traps. + +The macOS rebuild uses Xcode or `xcrun` CommandLineTools clang and SDK with +`-arch arm64 -isysroot SDK`. Modern dyld rejects `-Wl,-no_uuid` binaries, so an +`LC_UUID` load command is required. Because the linker generates a random UUID +each build, the committed binary zeroes those 16 payload bytes and re-signs ad +hoc. The Alpha/Beta test script verifies reproducibility by rebuilding, removing +the OS signature from both binaries, masking signature-coupled fields (UUID +payload, `LC_CODE_SIGNATURE` pointers, and `__LINKEDIT` sizes inflated by the +signature), and comparing every remaining byte. The committed binary was built +with CommandLineTools (Apple clang 17.0.0, build `clang-1700.6.4.2`, macOS SDK +26.2, Darwin 27), not patched from an older binary. Its disassembly reflects that +linker layout; the tape hole stays at file offset 32,768. + +The Windows PE binary keeps the same file offsets. The static memory section is +gone: `.data` shrinks to registers and host scratch (`VirtualSize` and +`SizeOfUninitializedData` are `0x1000`), the tape section moves back to RVA +`0x4000`, the loader's absolute tape address is `0x140004000`, and `SizeOfImage` +is `0x1004000`. At startup, the loader reserves 128 GiB with +`kernel32!VirtualAlloc(NULL, 0x2000000000, MEM_RESERVE, PAGE_NOACCESS)` without +charging system commit upfront, installs a vectored exception handler via +`kernel32!AddVectoredExceptionHandler` that demand-commits 1 MiB chunks +(`PAGE_READONLY` in a two-slot zero ring released with +`kernel32!VirtualFree(..., MEM_DECOMMIT)` for read-only scans, and permanent +`PAGE_READWRITE` on write), traps on any allocation or handler-registration +failure, and stores `MEMSIZE`/`MEMSIZE-8` in callee-saved `r13`/`r14` because +`imm32` cannot encode 128 GiB. The tape hole stays at file offset `0x1400`. +Windows execution is tested: the binary rebuilds identically and runs, and its +divide/remainder handlers pre-check bad divisors just like the other seeds—Windows +would otherwise raise hardware `#DE` as `0xC0000094`/`0xC0000095`—routing both +cases to the audited illegal-instruction trap. See +[bounds conformance](../../tests/bootstrap/interpreted/alpha/README.md#bounds-conformance) +for the measured results. + +The Linux x86-64 binary is a static ELF64 built from `alpha_x64_linux.s` with +GNU `as` and `ld -s --build-id=none` (binutils 2.38, Ubuntu)—byte-exact +reproducible with no imports or dynamic loader. It implements the same audited +VM as `alpha_x64_windows.hex` (same register layout, dispatch, and bounds +checks), replacing the four kernel32 calls with Linux syscalls +(`mmap`/`read`/`write`/`exit`). `mmap` uses `MAP_NORESERVE` to reserve 128 GiB +without swap accounting, matching the Windows lazy-commit design; failure traps +at startup. Because Linux turns hardware `#DE` into SIGFPE instead of Alpha's +Trap, divide and remainder pre-check divisor zero and `INT64_MIN / -1` just like +the arm64 seed. The `.tape` hole sits at file offset 12,288 (0x3000), `.data` at +0x402000, and text at 0x401000. Rebuild with: `as --64 -o a.o alpha_x64_linux.s && ld -s -o alpha_x64_linux --build-id=none -e _start a.o`, -then compare the committed bytes directly. -`tests/bootstrap/interpreted/alpha-beta-edge.sh` runs that clone-serialization check on -Linux x86-64 hosts wherever GNU `as`/`ld` are present. +and compare directly against the committed file. +`tests/bootstrap/interpreted/alpha-beta-edge.sh` runs this check on Linux x86-64 +when GNU `as`/`ld` are installed. -The extent is a startup allocation, so the +Because memory is allocated at startup, the [PE32+ image-size limit of 2 GiB](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format) -no longer bounds it; both containers stay small. The current capacity is not a -language-level restriction on Gamma programs. +no longer caps it, and all containers stay small. The current memory size is not +a Gamma language limit. -Alpha has no textual source language, assembler grammar, type system, or proof -kernel. The selected bootstrap floor consists of an audited native Alpha seed -plus the admitted Beta compiler tape. -It contains no compiler framework or higher-language primitive. Host stamping -packages a raw tape; it does not compile a language. +Alpha has no text syntax, assembler grammar, type system, or proof kernel. The +bootstrap floor is one audited native Alpha seed plus the checked-in Beta +compiler tape, with no compiler framework or higher-level primitives. Host +stamping only embeds a raw tape; it does not compile code. ## Ratified bounds-hardening contract -[SEMANTICS section 8](SEMANTICS.md#8-bounds-and-fixed-capacity) assigns failed -runtime range checks and oversized stamped input to the existing abnormal, -non-resumable Trap. Runtime failure preserves prior stdout; loader failure occurs -before execution and has empty stdout. Neither adds diagnostic bytes, a new -opcode, or a higher-rung resource result. +[SEMANTICS section 8](SEMANTICS.md#8-bounds-and-fixed-capacity) maps failed +runtime range checks and oversized stamped tapes to the existing abnormal, +non-resumable Trap. A runtime trap keeps earlier stdout; a loader failure traps +before execution with empty stdout. Neither adds diagnostic bytes, new opcodes, +or higher-level resource errors. -Both native implementations and the independent reference check complete fetch, -operand, data, and call/return stack ranges, and reject a stamped length above +All native implementations and the independent reference VM check fetch, +operand, data, and call/return stack ranges, and reject stamped lengths above 16,777,212 before copying. Dispatch checks the unsigned Alpha offset before -fetch, then the full instruction width using a 21-byte table. Data and stack -guards use unsigned end-minus-width comparisons; no address can wrap into an -admitted range. The arm64 implementation keeps the fixed extent in a preserved -native register. Neither adds semantic memory, a stack partition, or a new -outcome. The reference also captures a call's target before an overlapping -return-address write, as both native implementations do. - -The macOS source and refreshed disassembly retain the existing container -layout apart from the startup `mmap` sequence in `__text`, the dropped `mem` -zerofill (`__bss` shrinks to the registers page plus the I/O byte), and the -mechanically repacked linkedit tables. On Windows the occupied code extent -grows for the allocation call and register compares; the tape hole, file -offsets, and total container size are unchanged. - -Resolved divergence: the prior committed `alpha_arm64_macos` (SHA-256 -`3a9cc311…`) encoded its startup extent as `movz x1/x23, #0x2000, lsl #32` — -`0x200000000000` (32 TiB) rather than the specified `0x2000000000` (128 GiB). -The container has been re-forged from the corrected -`alpha_arm64_macos.s` on a macOS arm64 host and now carries `movz …, #0x20` -at both immediates; the refreshed disassembly, bound identity constants, and -inventory row below moved together. Re-forge also surfaced two host facts the -recipe above records: the retired container's ad-hoc signature no longer -validated (it could never execute unmodified), and Darwin 27's dyld refuses -images with no `LC_UUID` at all, which is why the shipped bytes now keep a -zeroed-UUID load command. -See [bounds conformance](../../tests/bootstrap/interpreted/alpha/README.md#bounds-conformance) for -tested behavior, observation limits, and the measured Windows execution -record. macOS execution and source rebuild are checked on a macOS host. - -Windows host I/O scratch occupies RVAs `0x3800..0x381f`, immediately after -the 256 eight-byte Alpha registers at `0x3000..0x37ff`; semantic memory is -now the `VirtualAlloc` extent rather than the `.data` that followed it. The two handles use `0x3800` and `0x3808`, the byte buffer -uses `0x3810`, and the count slot uses `0x3818`. The eight-byte count slot is -initially zero; host I/O writes its low four bytes, leaving the high half zero -for the native word read. All storage fits the existing writable zeroed page. -This corrects the former alias with registers 16–19 by relocating eleven -address immediates (22 binary bytes), without adding instructions or capacity. -The [register fixture](../../tests/bootstrap/interpreted/alpha/io-registers.hex) checks initial zero -values, full-word preservation, and direct I/O operands. On Windows it -returns exit 0 with stdout `ABCDEF` for input `AB`, so the host's I/O -scratch no longer aliases registers 16–19 at runtime either. +fetch, then checks the full instruction width via a 21-byte table. Data and +stack checks compare unsigned addresses against end-minus-width so arithmetic +cannot wrap into range. The arm64 seed keeps the memory size in a preserved +register. None adds extra semantic memory, a separate stack partition, or a new +exit outcome. The reference VM captures a call target before writing an +overlapping return address, matching the native seeds. + +The macOS source and disassembly keep the same container layout except for the +startup `mmap` sequence in `__text`, the removed `mem` zerofill (`__bss` shrinks +to the registers page and I/O byte), and repacked linkedit tables. On Windows, +code grows slightly for allocation and register checks; the tape hole, file +offsets, and total file size stay identical. + +Resolved bug: an earlier `alpha_arm64_macos` (SHA-256 `3a9cc311…`) encoded its +memory size as `movz x1/x23, #0x2000, lsl #32`—`0x200000000000` (32 TiB) instead +of `0x2000000000` (128 GiB). Rebuilding from the fixed `alpha_arm64_macos.s` on +macOS arm64 corrected both immediates to `movz …, #0x20`, updating the +disassembly, hash constants, and table below together. That rebuild also showed +that the old binary's ad-hoc signature was invalid (it could not run unmodified) +and that Darwin 27 dyld rejects binaries without `LC_UUID`, which is why the +committed binary keeps a zeroed-UUID load command. See +[bounds conformance](../../tests/bootstrap/interpreted/alpha/README.md#bounds-conformance) +for test coverage, limits, and Windows runs; macOS execution and rebuilds are +checked on a macOS host. + +Windows host I/O scratch lives at RVAs `0x3800..0x381f`, right after the 256 +eight-byte Alpha registers at `0x3000..0x37ff` (semantic memory is now the +`VirtualAlloc` block rather than `.data`). The two handles use `0x3800` and +`0x3808`, the byte buffer uses `0x3810`, and the count slot uses `0x3818`. The +8-byte count slot starts at zero; host I/O writes its low four bytes, leaving +the high half zero for word reads. Everything fits in the existing zeroed page. +Relocating eleven address immediates (22 bytes) fixed an earlier alias with +registers 16–19 without adding instructions or space. The +[register fixture](../../tests/bootstrap/interpreted/alpha/io-registers.hex) +verifies initial zeros, full-word preservation, and direct I/O operands; on +Windows it exits 0 with stdout `ABCDEF` for input `AB`, confirming registers +16–19 are untouched. ## Owned files @@ -149,21 +137,21 @@ alpha_x64_linux.lst committed x86-64 disassembly SEMANTICS.md AlphaBootstrapV5 execution and tape semantics ``` -Host seed selection and tape stamping live under `tools/bootstrap/alpha/`. -`tests/bootstrap/interpreted/alpha/container.sh` validates all three containers' native structure and -the stamping-hole contract on any host. Conformance and the independent reference -VM live under `tests/bootstrap/interpreted/alpha/`. -`tests/bootstrap/interpreted/alpha-beta-edge.sh` checks behavior and optional native-source -provenance. +Seed selection and tape stamping live in `tools/bootstrap/alpha/`. +`tests/bootstrap/interpreted/alpha/container.sh` checks all three containers' +structure and stamping-hole layout on any host. Conformance tests and the +reference VM live in `tests/bootstrap/interpreted/alpha/`. +`tests/bootstrap/interpreted/alpha-beta-edge.sh` verifies behavior and optional +source rebuilds. -Trusted Beta lives under `bootstrap/beta/`. Its readable compiler source -reconstructs the admitted tape byte-identically and supplies the next language -edge to the Gamma evaluator. +Trusted Beta lives in `bootstrap/beta/`. Its readable compiler source rebuilds +the checked-in tape byte-for-byte and supplies the next step to the Gamma +evaluator. ## Retention inventory -The selected native container identities are SHA-256 commitments to the exact -repository bytes, separate from their realization/conformance obligations: +These SHA-256 hashes pin the exact committed container bytes (separate from +their conformance tests): | Container | Bytes | SHA-256 | | --- | ---: | --- | @@ -173,7 +161,7 @@ repository bytes, separate from their realization/conformance obligations: | Retained files | Direct role | Deletion condition | | --- | --- | --- | -| `SEMANTICS.md` | Authoritative Alpha execution and raw-tape relation. | Replace only atomically with a ruled Alpha revision and every consumer. | -| `alpha_arm64_macos`, `alpha_arm64_macos.s`, `alpha_arm64_macos.lst` | Audited macOS arm64 realization, source, and listing. | Delete only with platform retirement or an equally audited replacement. | -| `alpha_x64_windows.exe`, `alpha_x64_windows.hex` | Audited Windows x86-64 realization and listing. | Delete only with platform retirement or an equally audited replacement. | -| `alpha_x64_linux`, `alpha_x64_linux.s`, `alpha_x64_linux.lst` | Audited Linux x86-64 realization, source, and listing. | Delete only with platform retirement or an equally audited replacement. | +| `SEMANTICS.md` | Canonical Alpha execution and raw-tape spec. | Replace only atomically with a new Alpha revision and all consumers. | +| `alpha_arm64_macos`, `alpha_arm64_macos.s`, `alpha_arm64_macos.lst` | Audited macOS arm64 VM, source, and disassembly. | Delete only if the platform is retired or replaced with an equally audited build. | +| `alpha_x64_windows.exe`, `alpha_x64_windows.hex` | Audited Windows x86-64 VM and listing. | Delete only if the platform is retired or replaced with an equally audited build. | +| `alpha_x64_linux`, `alpha_x64_linux.s`, `alpha_x64_linux.lst` | Audited Linux x86-64 VM, source, and disassembly. | Delete only if the platform is retired or replaced with an equally audited build. | diff --git a/bootstrap/beta/AUDIT.md b/bootstrap/beta/AUDIT.md index f449cdd937d2..e927dd8cbb93 100644 --- a/bootstrap/beta/AUDIT.md +++ b/bootstrap/beta/AUDIT.md @@ -1,8 +1,8 @@ # Admitted Beta compiler audit -This document audits the exact Alpha tape that implements the trusted Beta -compiler. It is a finite subject, not a claim that self-reconstruction proves -compiler correctness. +This document audits the Alpha tape that implements the Beta compiler. It checks +one fixed artifact; self-reconstruction alone does not prove compiler +correctness. ## Bound subject @@ -11,16 +11,15 @@ compiler correctness. | `beta_compiler.beta` | 12,536 bytes / 383 lines | `2f9a9f55a2c708731567367380521bfe35b1c13a00a367febd1f9f654c25f320` | | `beta_compiler_bytecode.tape` | 1,773 bytes | `4b1572a5ce406fc5b194e047ac6c5c601c1860261933381443a08c9041b77361` | -The tape partitions exactly into 1,613 instruction bytes at -`0x000..0x64c` and 160 mnemonic-table bytes at `0x64d..0x6ec`. Its readable -source contains 52 exact address assertions, 253 instructions, and 20 `dw` -words. Two names deliberately assert `0x123`: `scan_program` and its entry -loop are the same block. +The tape holds 1,613 instruction bytes at `0x000..0x64c` and 160 mnemonic-table +bytes at `0x64d..0x6ec`. Its source has 52 address assertions, 253 instructions, +and 20 `dw` words. Both `scan_program` and its entry loop intentionally assert +`0x123` because they share the same block. ## Decoded instruction inventory -Every instruction byte decodes under Alpha's written 21-opcode table. No -unknown or truncated opcode occurs. +Every instruction byte decodes under Alpha's 21-opcode table with no unknown or +truncated opcodes. | Instruction | Count | Instruction | Count | Instruction | Count | | --- | ---: | --- | ---: | --- | ---: | @@ -32,90 +31,86 @@ unknown or truncated opcode occurs. | `jlt` | 24 | `jeq` | 19 | `read` | 2 | | `write` | 3 | `call` | 12 | `ret` | 12 | -The counts total 253. Starting at `0`, following branch targets, both arms of -conditionals, call targets, and call continuations reaches all 253 instructions. -Every one of the 89 encoded branch/call targets is an instruction boundary -below `0x64d`; none enters an operand or the data table. +All 253 instructions are reachable from address `0` by following branches, both +arms of conditionals, call targets, and return sites. All 89 branch and call +targets land on instruction boundaries below `0x64d`; none enters an operand or +the mnemonic table. ## Control-flow reconstruction | Range | Routine | Beta responsibility | | --- | --- | --- | -| `0x000..0x122` | entry/read loop | Initialize the fixed profile, validate and retain the complete source byte envelope, invoke the scan, and halt 0. | -| `0x123..0x1e3` | program scan | Select address assertion versus mnemonic, emit opcode/operands, account output, and dispatch `dw`. | -| `0x1e4..0x352` | tokenizer | Skip admitted separators/comments and return an ordinary token, address assertion, or source end. | -| `0x353..0x3d0` | hexadecimal word | Require `0x` and one through sixteen lowercase hexadecimal digits. | -| `0x3d1..0x416` | hexadecimal digits | Accumulate the checked token into the private word scratch. | -| `0x417..0x47e` | hexadecimal nibble | Map `0..9` and `a..f`; reject every other byte. | -| `0x47f..0x54f` | mnemonic lookup | Compare the token with the closed table and return opcode plus operand widths. | -| `0x550..0x631` | operand emission | Require a one/two-digit `r` register or a hexadecimal word and emit its exact little-endian bytes. | -| `0x632..0x64c` | `dw` emission | Account and emit one word through the common operand path. | -| `0x64d..0x6ec` | immutable table | Twenty-one Alpha mnemonics in opcode order plus `dw`, each followed by its NUL-terminated `1`/`8` width string. | - -The call graph is acyclic. Its deepest route is entry → program scan → `dw` → -operand emission → hexadecimal word → hexadecimal digits → hexadecimal nibble: -six live Alpha return addresses, or 48 bytes. Loops use branches, not recursive -calls. - -The shared hexadecimal-word routine checks the token length before reading -its first two bytes and requires both `0` and `x`. Address assertions, control -operands, immediates, and `dw` therefore use the same complete prefix check. -Keeping the former check only in the word-operand caller left address assertions -accepting malformed prefixes such as `qx0:`. That redundant caller block is -removed. Register operands retain their separate `r` prefix check. - -Completion returns status 0. Malformed operands and malformed numeric address -tokens return 7; an unknown mnemonic returns 8; an invalid source byte, -source/output exhaustion, or an unequal address assertion returns 9. A late -failure may already have streamed a prefix, but only status-zero invocation -publishes an artifact. +| `0x000..0x122` | entry/read loop | Initialize limits, validate and buffer all source bytes, run the scan, and halt 0. | +| `0x123..0x1e3` | program scan | Dispatch address assertions vs. mnemonics, emit opcodes/operands, count output bytes, and handle `dw`. | +| `0x1e4..0x352` | tokenizer | Skip separators and comments; return an ordinary token, address assertion, or end-of-source. | +| `0x353..0x3d0` | hexadecimal word | Require `0x` followed by 1 to 16 lowercase hex digits. | +| `0x3d1..0x416` | hexadecimal digits | Parse the checked digits into the 8-byte scratch word. | +| `0x417..0x47e` | hexadecimal nibble | Convert `0..9` and `a..f`; reject all other bytes. | +| `0x47f..0x54f` | mnemonic lookup | Match the token against the table and return its opcode and operand widths. | +| `0x550..0x631` | operand emission | Parse a one/two-digit `r` register or hex word and emit its little-endian bytes. | +| `0x632..0x64c` | `dw` emission | Count and emit one 8-byte word through the shared operand path. | +| `0x64d..0x6ec` | immutable table | 21 Alpha mnemonics in opcode order plus `dw`, each followed by a NUL-terminated `1`/`8` width string. | + +The call graph is acyclic. Its deepest chain is entry -> program scan -> `dw` +-> operand emission -> hexadecimal word -> hexadecimal digits -> hexadecimal +nibble: six live Alpha return addresses (48 bytes). Loops use branches, never +recursion. + +The shared hex-word routine checks token length before reading the first two +bytes and requires both `0` and `x`. Address assertions, branch targets, +immediates, and `dw` all share this check. Previously, checking only in the +word-operand caller let address assertions accept bad prefixes like `qx0:`; the +duplicate caller check has been removed. Register operands keep their separate +`r` prefix check. + +Success exits with status 0. Bad operands or bad address tokens exit 7; unknown +mnemonics exit 8; invalid source bytes, source/output overflow, or mismatched +address assertions exit 9. A late failure may have already written partial bytes +to stdout, so the caller publishes an output file only on status 0. ## Memory and ceilings | Region/value | Exact extent | Reason it is contained | | --- | --- | --- | -| compiler tape | `0x000000..0x0006ed` | Fixed 1,773-byte admitted subject. | -| numeric scratch | `0x080060..0x080068` | One private eight-byte word, disjoint from code and source. | -| source buffer | `0x100000..0x4100000` | Exactly 67,108,864 bytes; each store follows `pointer != end`. | -| successful emitted tape | stdout only | Counted around every opcode/operand/data extent; maximum `0xfffffc` = 16,777,212 bytes. | -| Alpha return stack | down from `0x10000000` | At most six 8-byte entries; no evaluator allocation approaches it. | - -At the source boundary, exactly 67,108,864 bytes are retained and an EOF probe -is performed; one additional byte returns 9 before any out-of-range store. -Source token pointers never leave that retained half-open span. The mnemonic -table and numeric scratch are fixed in-range addresses. The output count is -advanced by the complete width before operand and `dw` emission; equality with -`0xfffffc` is admitted and any greater operand/data extent returns 9 before -those bytes are written. Opcode emission writes its one-byte prefix, advances, -and then checks the same upper bound, so a failing raw process stream can contain -one byte beyond the successful-artifact ceiling. Status-gated invocation never -publishes that prefix. - -The compiler executes no `div` or `mod`, has no computed control target, and -writes semantic memory only in the checked source span and eight-byte scratch. -It therefore cannot reach Alpha's arithmetic or bounds traps under this profile. +| compiler tape | `0x000000..0x0006ed` | Fixed 1,773-byte checked-in program. | +| numeric scratch | `0x080060..0x080068` | Single 8-byte word, disjoint from code and source. | +| source buffer | `0x100000..0x4100000` | Exactly 67,108,864 bytes; every write checks `pointer != end`. | +| successful emitted tape | stdout only | Checked before every opcode, operand, and data write; max `0xfffffc` = 16,777,212 bytes. | +| Alpha return stack | down from `0x10000000` | At most six 8-byte entries; far from any buffer. | + +At the source limit, the compiler buffers 67,108,864 bytes and probes for EOF; +one extra byte exits 9 before any out-of-range write. Token pointers stay inside +that half-open buffer. The mnemonic table and scratch word sit at fixed valid +addresses. For operands and `dw`, the compiler adds the full byte width and +checks against `0xfffffc` before emitting, accepting equality and exiting 9 if +exceeded. Opcode emission writes its one byte, increments the count, and then +checks the same limit, so raw stdout on failure can exceed the limit by one +byte; status-gated callers discard that stream. + +The compiler executes no `div` or `mod`, has no indirect jumps, and writes only +to the bounded source buffer and 8-byte scratch word. It cannot hit Alpha's +arithmetic or bounds traps. ## Source-to-tape correspondence -The retained checks establish complementary facts: +Five scripts verify complementary properties: -1. `root-audit.py` binds both hashes, independently parses the Beta source, - checks all 52 assertions, partitions every emitted byte once, decodes the - raw tape from Alpha's opcode table, validates the mnemonic table, and proves - complete control-flow reachability. -2. `compiler-diamond.sh` runs the independent source-derived Beta relation over - the compiler and example corpus and obtains byte equality with the admitted +1. `root-audit.py` checks both hashes, independently parses the Beta source, + verifies all 52 address assertions, partitions every emitted byte once, + decodes the raw tape against Alpha's opcode table, checks the mnemonic table, + and confirms full control-flow reachability. +2. `compiler-diamond.sh` runs the independent reference assembler on the + compiler and examples and compares output byte-for-byte with the checked-in compiler. -3. `reconstruction.sh` runs the admitted tape itself on the canonical source - and obtains the admitted 1,773 bytes exactly. -4. `register-address-regression.sh` pins the strict grammar, numeric control, - exact/adjacent source and output bounds, and status-gated publication. -5. `word-prefix.sh` exercises 736 exact first-prefix-byte controls across - initial and late assertions, `jmp`, and `dw`, each at EOF and before newline. - It checks status and the exact successful or rejected-prefix output bytes. - -The Python decoder/reference is diagnostic and not a bootstrap premise. The -authority is the finite source/tape pair, this published correspondence, the -written Beta and Alpha semantics, and audit of the admitted Alpha -realizations. Self-reconstruction supplies identity; it does not excuse review -of the 253 decoded operations above. +3. `reconstruction.sh` runs the checked-in tape on the canonical source and + verifies the exact 1,773-byte output. +4. `register-address-regression.sh` tests strict grammar rules, numeric targets, + exact and off-by-one source/output limits, and status-gated publishing. +5. `word-prefix.sh` tests 736 first-byte prefix cases across early and late + assertions, `jmp`, and `dw` at both EOF and newline, checking exit status and + exact output bytes. + +The Python decoder and reference assembler are diagnostic checks, not trusted +bootstrap stages. Trust rests on the small source/tape pair, this audit, the +Beta and Alpha specs, and the Alpha VM audits. Self-reconstruction confirms +identity; it does not replace auditing the 253 decoded instructions above. diff --git a/bootstrap/beta/LANGUAGE.md b/bootstrap/beta/LANGUAGE.md index 91c0c3de6dd7..6e7be3fab454 100644 --- a/bootstrap/beta/LANGUAGE.md +++ b/bootstrap/beta/LANGUAGE.md @@ -1,28 +1,26 @@ # Beta language and encoding -This document defines the source language whose deterministic encoding produces -an Alpha bytecode payload. [`bootstrap/alpha/SEMANTICS.md`](../alpha/SEMANTICS.md) -defines execution of that payload; Beta defines only the -text-to-bytes correspondence. +This document specifies the assembly language that encodes deterministically +into an Alpha bytecode payload. [`bootstrap/alpha/SEMANTICS.md`](../alpha/SEMANTICS.md) +specifies how that payload executes; Beta specifies only the mapping from text +to bytes. -The encoding is a partial function `assemble(P) = T`. `P` must be a -well-formed assembly source below. `T` is the raw platform-independent bytecode -payload stored in a `.tape` file. Stamping a payload into a native seed adds its -four-byte length and host container; neither is part of `assemble` or compiler -identity. +Encoding is a partial function `assemble(P) = T`, where `P` is a valid assembly +source and `T` is the raw, platform-independent bytecode stored in a `.tape` +file. Stamping a payload into a native seed adds its four-byte length and host +executable wrapper; neither belongs to `assemble` or the compiler's identity. ## Lexical form -Assembly source is a byte stream in the bootstrap textual-ASCII envelope. The -only admitted source bytes are horizontal tab (`0x09`), line feed (`0x0A`), -carriage return (`0x0D`), and printable ASCII (`0x20..0x7E`). NUL, DEL, bytes -above `0x7F`, and every other control byte reject before tokenization at their -byte offset. There is no source decoding, BOM, Unicode classification, or -locale-dependent character rule: +Beta source uses the bootstrap textual-ASCII byte set: horizontal tab (`0x09`), +line feed (`0x0A`), carriage return (`0x0D`), and printable ASCII (`0x20..0x7E`). +NUL, DEL, bytes above `0x7F`, and all other control bytes fail before +tokenization at their exact byte offset. Beta does no decoding, BOM handling, +Unicode classification, or locale-dependent checks: - space, tab, CR, LF, and comma separate tokens; -- `;` begins a comment through the next CR, LF, or end of source; and -- separators and comments otherwise have no meaning. +- `;` starts a comment that runs to the next CR, LF, or end of input; +- separators and comments have no other effect. The grammar is: @@ -38,25 +36,25 @@ HEXWORD := '0x' HEXDIGIT{1,16} HEXDIGIT := [0-9a-f] ``` -Leading zeroes are permitted. A `HEXWORD` denotes one unsigned word in -`0..2^64-1`. A `REGISTER` denotes one register in `0..255`. Hexadecimal digits -are lowercase only; uppercase `A..F`, decimal words without `0x`, bare `0x`, -and words wider than sixteen digits reject. Only a complete one- or two-digit -hexadecimal form after `r` is a register. An address assertion emits nothing -and requires its word to equal the current output length exactly. Human block -names belong in comments beside assertions and numeric control operands; Beta -has no symbolic identifiers or resolution. - -`dw` appends its word as exactly eight little-endian bytes. The word width is -Alpha's fixed 64-bit width and never depends on the host. Data is not implicitly -decoded as instructions; ordinary Alpha control flow must jump around embedded -data when it is reachable by address order. Short strings and tables are packed -into words explicitly, with any trailing zero padding visible in source. +Leading zeroes are allowed. A `HEXWORD` is an unsigned 64-bit value in +`0..2^64-1`. A `REGISTER` is a register index in `0..255`. Hex digits must be +lowercase; uppercase `A..F`, decimal numbers without `0x`, bare `0x`, and +numbers longer than sixteen hex digits are rejected. Only a complete one- or +two-digit hex number after `r` counts as a register. An address assertion emits +no bytes and checks that its word equals the current output length. Put block +names in comments beside assertions and branch targets; Beta has no symbolic +names or label resolution. + +`dw` emits its word as eight little-endian bytes. Words are always Alpha's +64-bit width regardless of host architecture. Alpha does not skip embedded data +automatically; control flow must jump past data in reachable address ranges. +Pack short strings and tables into explicit words with any trailing zero padding +visible in source. ## Instructions -Operand kind `r` encodes a hexadecimal register. Operand kind `x` accepts one -`HEXWORD` and encodes it as an eight-byte word/address. +Operand kind `r` takes a hex register and emits one byte. Operand kind `x` takes +one `HEXWORD` and emits an eight-byte little-endian word or address. | Mnemonic | Opcode | Operands | Width | | --- | ---: | --- | ---: | @@ -82,39 +80,37 @@ Operand kind `r` encodes a hexadecimal register. Operand kind `x` accepts one | `call` | `0x13` | `x` | 9 | | `ret` | `0x14` | none | 1 | -Each instruction begins with its one-byte opcode. An `r` operand is its -one-byte register number. An `x` operand is its value as exactly eight bytes, -least significant byte first. +Every instruction starts with its one-byte opcode, followed by each `r` operand +as one byte and each `x` operand as eight little-endian bytes. ## Deterministic one-pass encoding -The compiler starts with an empty output and processes items once in source +The compiler starts with empty output and processes each item once in source order: -1. `a:` requires `a` to equal the current output length and emits nothing; -2. an instruction appends its opcode and encoded operands; and +1. `a:` verifies that `a` equals the current output length and emits nothing; +2. an instruction appends its opcode and encoded operands; 3. `dw w` appends the eight-byte little-endian encoding of `w`. -Every control target is therefore visible directly in source, and each asserted -block address is checked against the bytes that precede it. Consequently a -well-formed source has exactly one encoded payload without a symbol table, -relocation pass, or fixup relation. +Every control target appears directly in source, and every asserted address is +checked against the preceding bytes. A valid source therefore produces one exact +payload with no symbol table, relocation pass, or fixup table. -Malformed text, unknown mnemonics, invalid operands, a mismatched address -assertion, arithmetic overflow, and implementation capacity exhaustion are not -assembly programs and produce no `assemble(P) = T` judgment. The compiler may -have written a stdout prefix before discovering a late failure; invocation -plumbing publishes stdout as an artifact if and only if the compiler returns -status zero. Accepting a malformed input does not extend this language. +Malformed syntax, unknown mnemonics, invalid operands, mismatched address +assertions, arithmetic overflow, and exhausted compiler capacity are invalid and +yield no `assemble(P) = T` result. The compiler may write partial bytes to +stdout before hitting a late error, so the caller publishes stdout as an output +file only when the compiler exits with status 0. Accepting malformed input never +extends the language. -The admitted compiler profile retains at most `0x4000000` source bytes, -and publishes at most `0xfffffc` output bytes. It returns nonzero without -publishing an artifact on exhaustion; its one-pass process stream may contain a -late rejected prefix as described above. +The current compiler holds at most `0x4000000` source bytes and emits at most +`0xfffffc` output bytes. If either limit is exceeded, it exits nonzero and +publishes no output file, though its raw stdout stream may hold a partial prefix +as noted above. ## Canonical assembler reconstruction subject -The current exact subject is small enough for total checked reconstruction: +The compiler itself is small enough for complete audited reconstruction: | Subject fact | Value | | --- | ---: | @@ -122,10 +118,9 @@ The current exact subject is small enough for total checked reconstruction: | Source lines | 383 | | Encoded payload bytes | 1,773 | -An admission certificate must bind the raw source and tape outside the proof -producer, partition every source item and output byte exactly once, check every -address assertion, and prove the persisted tape length. Byte equality then gives -identical Alpha initial programs under the same input and resource profile. By deterministic Alpha -semantics, defined output, halt, trap, resource, and divergence observations -are preserved in lockstep; no stuttering argument is needed for this encoding -edge. +An acceptance check binds the raw source and tape outside the proof tool, +partitions every source item and output byte once, verifies every address +assertion, and checks the tape length. Matching bytes then guarantee identical +Alpha initial programs under the same input and resource limits. Because Alpha +execution is deterministic, output, halt, trap, resource, and divergence +behavior match step for step without needing a stuttering proof. diff --git a/bootstrap/beta/README.md b/bootstrap/beta/README.md index 6e4771a02e53..daf2aa674f7c 100644 --- a/bootstrap/beta/README.md +++ b/bootstrap/beta/README.md @@ -1,18 +1,17 @@ # Beta -Beta is the first trusted language above Alpha. It gives Alpha instructions -human-readable mnemonics, numeric address assertions, hexadecimal operands, and data spelling while -remaining a deliberately small imperative tape-assembly language. +Beta is the first trusted language above Alpha. It is a minimal imperative +assembly language that gives Alpha instructions readable mnemonics, numeric +address assertions, hex operands, and raw word data. -[`LANGUAGE.md`](LANGUAGE.md) defines the exact deterministic relation from one -Beta source byte sequence to one raw Alpha `.tape`. The compiler is the -platform-independent [`beta_compiler_bytecode.tape`](beta_compiler_bytecode.tape), -an admitted Alpha program in the trusted bootstrap chain. Its readable -[`beta_compiler.beta`](beta_compiler.beta) source must -reconstruct that tape byte-for-byte. -The finite [compiler root audit](AUDIT.md) binds its identities, -decoded Alpha inventory, control flow, memory profile, and independent -source-to-tape correspondence. +[`LANGUAGE.md`](LANGUAGE.md) specifies the exact mapping from Beta source bytes +to a raw Alpha `.tape`. The compiler is the platform-independent +[`beta_compiler_bytecode.tape`](beta_compiler_bytecode.tape), a checked-in Alpha +program in the bootstrap chain. Its readable source +[`beta_compiler.beta`](beta_compiler.beta) must reproduce that tape +byte-for-byte. The [compiler root audit](AUDIT.md) records its hashes, decoded +Alpha instruction counts, control flow, memory bounds, and independent +source-to-tape checks. ```text audited native Alpha VM @@ -21,54 +20,50 @@ audited native Alpha VM -> program.tape ``` -The compiler is written in Beta and reconstructs its admitted tape -byte-for-byte. The checked-in tape is the cold-start implementation; the -reconstruction makes its source-level behavior reviewable without introducing -a second platform-native compiler. +The Beta compiler is written in Beta and rebuilds its own checked-in tape +byte-for-byte. The committed tape breaks the cold-start loop, while +self-reconstruction lets humans audit the readable source without adding a +second native compiler. -Gamma's evaluator is written in Beta, so the Alpha-to-Beta and Beta-to-Gamma -edges both depend on this language judgment. Successful compilation yields -Alpha tape whose execution is governed by +Gamma's evaluator is written in Beta, so both the Alpha-to-Beta and +Beta-to-Gamma steps depend on Beta. Compiled Alpha tapes execute under [`bootstrap/alpha/SEMANTICS.md`](../alpha/SEMANTICS.md). ## Beta compiler -The admitted tape is a 1,773-byte Alpha program. -`tests/bootstrap/interpreted/beta/compiler/reconstruction.sh` requires the readable source to -reproduce it byte-for-byte. +The checked-in tape is 1,773 bytes. +`tests/bootstrap/interpreted/beta/compiler/reconstruction.sh` verifies that +compiling the readable source reproduces it byte-for-byte. -The compiler accepts mnemonic opcodes, complete-token lowercase hexadecimal -registers `rH`/`rHH`, `0x`-prefixed lowercase hexadecimal 64-bit words, -numeric address assertions, comments, and fixed-width `dw` data. It -emits in one pass; mnemonic rows carry their NUL-terminated operand-width lists; -and bounded source/output pointers use a documented high-register ABI. It emits -no host container. Current local build -scripts may stamp an emitted tape into a native Alpha seed because the seeds do -not yet load an external tape directly. +The compiler accepts mnemonic opcodes, lowercase hex registers `rH`/`rHH`, +`0x`-prefixed lowercase 64-bit hex words, numeric address assertions, comments, +and 64-bit `dw` data words. It compiles in one pass using a mnemonic table with +NUL-terminated operand-width strings and bounded source/output pointers in high +registers. It emits raw tapes only, not native executables; local build scripts +stamp the emitted tape into a native Alpha seed because the seeds do not yet +load external tape files directly. -The minimized implementation validates source bytes while reading, retains -absolute bounded pointers, shares one hexadecimal parser, checks every authored -address assertion against the running output cursor, and drives operands from -visible NUL-terminated width lists beside each mnemonic. Alpha's specified -zero-initialized register file supplies named persistent state and constants. -The source transport admits 64 MiB so readable prior-rung expansions can pass -through Beta; emitted Alpha remains capped by the exact 16,777,212-byte seed hole. -There is no symbol table, label identity, relocation pass, hash, fixup chain, or -compressed name. Comma removal and new Alpha opcodes remain rejected because -their additional trust cost outweighs the remaining byte savings. -Retained numeric control targets repeat the human block name in a comment beside -the instruction; the corresponding address assertion names that block too. -Comments aid the finite audit but never select target identity or affect encoding. +The minimized compiler validates source bytes while reading, bounds all pointers +explicitly, shares one hex parser, checks every address assertion against the +output cursor, and drives operand encoding from the width string beside each +mnemonic. Alpha's zero-initialized registers hold persistent state and constants. +The compiler buffers up to 64 MiB of source so readable outputs from higher +stages fit, while emitted tapes stay within the 16,777,212-byte seed limit. It +has no symbol table, labels, relocation pass, hashing, fixup chains, or name +compression. Removing commas or adding Alpha opcodes stays rejected because the +extra trust cost outweighs small byte savings. Comments repeat human block names +beside numeric branch targets and address assertions to help auditing without +affecting encoding. -Materialization and disposable builds live under `tools/bootstrap/beta/`. -Reconstruction, the independent compiler, regressions, and examples live under +Build scripts live in `tools/bootstrap/beta/`. Self-reconstruction, the +independent reference compiler, regression tests, and examples live in `tests/bootstrap/interpreted/beta/compiler/`. ## Retention inventory | Retained child | Direct role | Deletion condition | | --- | --- | --- | -| `LANGUAGE.md` | Exact Beta-source-to-Alpha-tape language relation. | Replace only with a versioned contract and synchronized compiler and edge gates. | -| `beta_compiler_bytecode.tape` | Admitted Alpha program implementing the trusted Beta compiler. | Replace atomically with its exact checked relation and reconstruction. | -| `beta_compiler.beta` | Authoritative readable self-reconstruction source. | Delete only if another equally direct reconstruction replaces it. | -| `AUDIT.md` | Finite decoded audit and source-to-tape correspondence for the admitted pair. | Replace only with a stronger audit of the exact admitted subject. | +| `LANGUAGE.md` | Exact Beta-source-to-Alpha-tape specification. | Replace only with a versioned spec and synchronized compiler and tests. | +| `beta_compiler_bytecode.tape` | Checked-in Alpha program implementing the Beta compiler. | Replace atomically with its checked spec and reconstruction. | +| `beta_compiler.beta` | Readable source that rebuilds the compiler tape. | Delete only if an equally direct reconstruction replaces it. | +| `AUDIT.md` | Decoded instruction audit and source-to-tape check for the checked-in pair. | Replace only with a stronger audit of the exact checked-in pair. | diff --git a/bootstrap/delta/LANGUAGE.md b/bootstrap/delta/LANGUAGE.md index b4262f30ca84..6d41b0cdb5f8 100644 --- a/bootstrap/delta/LANGUAGE.md +++ b/bootstrap/delta/LANGUAGE.md @@ -1,33 +1,32 @@ # Delta language -Delta is the typed, pure language used to implement the Epsilon interpreter -and compiler. Two Gamma programs implement Delta. The [interpreter](interpreter/) -evaluates checked expressions, and the [compiler](compiler/) lowers them to -Gamma. Both use the same syntax and type checker. Each implementation has -its own execution limits. +Delta is the typed, pure functional language used to build the Epsilon +interpreter and compiler. Two Gamma programs implement it: the +[interpreter](interpreter/) evaluates checked expressions, and the +[compiler](compiler/) lowers them to Gamma. Both share the same syntax and type +checker, with separate runtime limits. ## Source envelope -Delta source uses the bootstrap textual-ASCII envelope. The only admitted -source bytes are HT, LF, CR, and printable ASCII. NUL, DEL, bytes above `0x7F`, -every other control byte, and a Unicode BOM reject before tokenization at their -exact byte offsets. There is no decoding, normalization, Unicode table, or -host-locale-dependent lexical rule. +Delta source allows only HT, LF, CR, and printable ASCII bytes. NUL, DEL, bytes +above `0x7F`, all other control bytes, and Unicode BOMs reject before lexing at +their exact byte offset. No decoding, normalization, Unicode tables, or +locale-dependent rules exist. -Identifiers and decimal digits use explicit ASCII ranges. Exactly space, tab, -CR, and LF are whitespace. A comment ends at CR, LF, or source end. Literal -escapes, rather than raw non-ASCII source bytes, produce other byte values. +Identifiers and digits use explicit ASCII ranges. Only space, tab, CR, and LF +count as whitespace. Line comments start with `;` and end at CR, LF, or EOF. +Other byte values must be built with literal escapes or `bytes_single`. -An identifier is `[A-Za-z_][A-Za-z0-9_]*`. Type and constructor names begin -with `A..Z`; function, parameter, and local names begin with `a..z` or `_`. -Keywords and the closed `bytes_*` built-ins are reserved. `;` begins a line -comment. An integer literal is an optional `-` followed by one or more ASCII -decimal digits and must fit `Int`. +An identifier matches `[A-Za-z_][A-Za-z0-9_]*`. Type and constructor names +start with `A..Z`; function, parameter, and local names start with `a..z` or +`_`. Keywords and the five `bytes_*` built-ins are reserved. An integer literal +is an optional `-` followed by one or more ASCII decimal digits and must fit +`Int`. ## Program form -A Delta program is a sequence of algebraic-data declarations followed by typed -function declarations: +A Delta program lists algebraic-data declarations followed by typed function +declarations: ```text program := data-declaration* function-declaration+ @@ -51,150 +50,125 @@ expression := INTEGER | CHARACTER | BYTE_STRING | NAME pattern := CONSTRUCTOR | (CONSTRUCTOR NAME*) ``` -A `CHARACTER` is an `Int` spelled with single quotes. For example, `'A'` and -`65` have the same type and value. It contains one printable ASCII byte or one -escape. Use `\'` for apostrophe, `\\` for backslash, and `\t`, `\n`, or `\r` -for tab, LF, or CR. A double quote can be written directly or as `\"`. -Parentheses, space and semicolon inside the quotes are literal bytes. -The closing quote must be followed by whitespace, a parenthesis, a comment, or -source end. Empty, wide, unclosed and malformed spellings are syntax errors -at the opening quote. Whole-source byte validation takes precedence. - -A `BYTE_STRING` is an immutable `Bytes` value written between double quotes. -Its unescaped contents are printable ASCII except double quote and backslash. -The only escapes are `\n`, `\r`, `\t`, `\\`, and `\"`, producing LF, CR, HT, -backslash, and double quote respectively. Empty literals are valid. Raw control -bytes, unknown escapes, a trailing backslash, and a missing closing quote reject -as malformed syntax at the opening quote. Source-envelope byte validation still -precedes token validation, including bytes inside literals. A closed literal -must be followed by whitespace, a parenthesis, a comment, or source end. -Parentheses and semicolons inside quotes are ordinary bytes. - -Byte literals are expressions, never identifiers, type names, call heads, or -match patterns. They have exactly the existing `Bytes` meaning and operations; -there is no implicit conversion to `Int` or a nominal type. Other byte values -remain constructible with `bytes_single`. This small facility serves readable -source emission in the checked Epsilon-to-Delta compiler; it adds no runtime -primitive or new admitted artifact. - -The final source item is a declaration, not an untyped trailing expression. -Declarations are mutually visible, so forward and mutual recursion are legal. -Delta is monomorphic and fully annotated, including every `let` binder. It has -no closures, higher-order -functions, mutation, effects, subtyping, or implicit conversion. Algebraic data -is immutable and nominal. - -`Int` and `Bytes` are the only built-in data types. Every other type and -constructor is declared in source. Functions and constructors support arbitrary -arity; Alpha's register count is not a Delta language limit. - -Delta has four grammar-distinguished namespaces: type names, constructor names, -function names, and local value names. Global declarations are unique within -their namespace: type declarations are unique among types, constructors are -globally unique among constructors because constructor uses are unqualified, -and functions are unique among functions. The same spelling may name a type and a -constructor, or a function and a local value, because the grammar determines -which namespace each occurrence consults. For example, `(data Token (Token -Int))` is well formed, and in `(f f)` the list head denotes the global function -while the argument atom may denote a local `f`. Delta has no function values. - -Parameters, `let` binders, and constructor-pattern binders inhabit the -local-value namespace. No new binder may duplicate a name -in its active lexical environment. Parameters of one function are mutually -unique. A `let` initializer is checked against the binder's declared type in -the outer environment; its binder is active only in the body and may not -duplicate an active parameter, `let`, or -pattern binder. Pattern binders are mutually unique, may not duplicate an -active outer local, and are active only in their match arm. Disjoint arms, -branches, and sibling scopes may -reuse a spelling because their environments are never active together. -Duplicate pattern names reject; they never express an equality constraint. - -Compilation first collects every global declaration and rejects the exact later -declaration of a duplicate in that namespace. It then resolves mutually visible -declaration types and checks bodies with scope-aware local-environment push/pop. -A local conflict is reported at the exact later binder. Lookup never chooses a -first or last row among competing declarations. +A `CHARACTER` is an `Int` written in single quotes: `'A'` and `65` have the +same type and value. It holds one printable ASCII byte or one escape (`\'`, +`\\`, `\t`, `\n`, `\r`, or `\"`; a double quote may also appear unescaped). +Parentheses, space, and semicolon inside quotes are literal bytes. Whitespace, +a parenthesis, a comment, or EOF must follow the closing quote. Empty, wide, +unclosed, or malformed character literals fail as syntax errors at the opening +quote (whole-source byte validation runs first). + +A `BYTE_STRING` is an immutable `Bytes` value in double quotes containing +printable ASCII (except `"` and `\`) and the escapes `\n`, `\r`, `\t`, `\\`, +and `\"`. Empty literals are allowed. Raw control bytes, unknown escapes, +trailing backslashes, and missing closing quotes fail as syntax errors at the +opening quote (after source-byte validation). Whitespace, a parenthesis, a +comment, or EOF must follow the closing quote. Parentheses and semicolons +inside quotes are ordinary bytes. + +Byte literals are expressions only — never identifiers, type names, call heads, +or match patterns. They behave identically to other `Bytes` values with no +implicit conversion to `Int` or nominal types; other byte values use +`bytes_single`. They exist so the Epsilon-to-Delta compiler can emit readable +source without adding runtime primitives or artifact formats. + +Programs end with a declaration, never a trailing expression. Declarations are +mutually visible, allowing forward and mutual recursion. Delta is monomorphic +and fully annotated (including every `let`), with no closures, higher-order +functions, mutation, effects, subtyping, or implicit conversions. Algebraic +data is immutable and nominal. + +`Int` and `Bytes` are the only built-in types; all other types and constructors +are declared in source. Functions and constructors accept arbitrary arity +regardless of Alpha's register count. + +Delta has four grammar-separated namespaces: types, constructors, functions, +and local values. Global names are unique within their namespace (constructors +are globally unique because uses are unqualified). The same spelling may name +both a type and a constructor or a function and a local, because grammar +selects the namespace. For example, `(data Token (Token +Int))` is well formed, and in `(f f)` the head names global function `f` while +the argument names local `f`. Delta has no function values. + +Parameters, `let` binders, and pattern binders share the local namespace, and +shadowing an active local is forbidden. Parameters of a function must be unique. +A `let` checks its initializer in the outer scope, and its binder is active +only in the body. Pattern binders must be unique within the pattern, cannot +shadow outer locals, and live only in their arm; duplicate pattern names are +errors, not equality tests. Disjoint arms, branches, and sibling scopes may +reuse names because they are never active together. + +Compilation collects all global declarations first and rejects any later +duplicate in that namespace. It then resolves declaration types and checks +bodies with scoped local environments, reporting any local conflict at the +later binder. Lookup never silently picks a first or last duplicate. ## Static semantics The checker resolves every type, function, constructor, variable, and pattern -against its declaration. It checks parameter, function, and constructor arity; -operator operands; call arguments; declared result types; match scrutinees; -pattern constructors and bindings; and agreement among every match arm. - -Every match over an algebraic type is exhaustive. Duplicate constructor arms, -a constructor from another type, and a missing constructor -reject the program. A checked Delta program therefore has no dynamic -"no arm matched" value. - -This requirement closes a known correlated oracle defect: the temporary type -checker once omitted exhaustiveness while the interpreter fabricated `Int` -zero when no arm matched. The checker now rejects incomplete coverage and the -interpreter traps on the impossible runtime state as migration hardening, but -their former agreement still demonstrates why a differential cannot establish -a rule both sides omit. The direct compiler remains responsible for the -authoritative static judgment. +against its declaration, verifying arities, operator operands, call arguments, +result types, match scrutinees, pattern constructors and bindings, and arm +result types. + +Every `match` over an algebraic type must be exhaustive: duplicate arms, wrong +type constructors, and missing constructors are rejected, so checked programs +have no runtime "no arm matched" state. + +Historically, a temporary type checker omitted exhaustiveness while the +interpreter returned `Int` zero when no arm matched. Both now enforce it (the +checker rejects incomplete matches and the interpreter traps on impossible +states), illustrating why differential agreement alone cannot prove a rule both +sides omit. The direct compiler is the source of truth for static checking. ## Evaluation -Evaluation is pure, strict, and left-to-right. `if` evaluates only its selected -branch. `match` evaluates its scrutinee once and then its selected arm. A -function call evaluates each argument once from left to right before entering -the callee. Proper tail calls are required: terminating tail recursion cannot -also depend on an implementation return-stack ceiling. - -`Int` is a checked signed 64-bit integer. `eq` and `lt` on integers produce `0` -or `1`; `if` treats zero as false and every other integer as true. - -`Bytes` is an immutable finite byte sequence, not an algebraic list and not a -raw-memory address. The five `bytes_*` forms above are closed built-ins: -`bytes_empty` and `bytes_single` construct; `bytes_length` returns `Int`; -`bytes_get` returns the selected byte as `Int`; and `bytes_concat` joins two -sequences. Every valid `Bytes` has an exact -logical length representable as a nonnegative `Int`. `bytes_empty`, -`bytes_single` preserves that invariant. `bytes_concat` loads -the operands' logical lengths and traps before allocation when their exact -mathematical sum exceeds `INT64_MAX`; otherwise its result stores that exact -sum. `bytes_length` is therefore total over every valid `Bytes`. The compiler -may represent sealed input as a flat view and constructed output as chunks or a -rope, but representation and storage coordinates are never Delta values. - -The authored runtime trap conditions are closed: - -- the mathematical result of signed addition, subtraction, or multiplication - is not representable as `Int`; -- integer division or remainder has a zero divisor, or applies the signed - overflow pair `INT64_MIN` and `-1`; -- `bytes_single` receives a value outside `0..255`; -- `bytes_get` receives a negative or out-of-range index; -- `bytes_concat` would produce a logical length greater than `INT64_MAX`. - -Out-of-range integer literals are static rejection rather than runtime traps. -A malformed private `Bytes` descriptor, an impossible checked state, or replay -disagreement is `InternalFailure`; physical heap, stack, input, or output -exhaustion is `Incomplete`. Neither condition is a Delta trap. - -The compact primitive is required by the compiler customer. Representing the -4 MiB input profile as one `Cons(Int, Bytes)` node per byte would require at -least 64 MiB at the current 16-byte row size, while the existing Delta oracle -has a 16 MiB heap. That mismatch is structural, not an optimization problem. - -Divergence remains divergence. Work is never Delta meaning. An evaluator may -bound work for a diagnostic run, but work-budget exhaustion is an implementation -profile's `Incomplete` result and proves neither rejection nor divergence. +Evaluation is pure, strict, and left-to-right. `if` evaluates only the taken +branch; `match` evaluates its scrutinee once, then the matching arm; calls +evaluate arguments left to right once before entering the callee. Proper tail +calls are required so terminating tail recursion cannot overflow a return stack. + +`Int` is a checked signed 64-bit integer. `eq` and `lt` return `0` or `1`; `if` +treats `0` as false and any nonzero integer as true. + +`Bytes` is an immutable finite byte sequence, not an algebraic list or raw +address. The five `bytes_*` built-ins are closed: `bytes_empty` and +`bytes_single` build sequences, `bytes_length` returns `Int`, `bytes_get` +returns the byte as `Int`, and `bytes_concat` concatenates two sequences. Every +`Bytes` has a nonnegative `Int` logical length: `bytes_empty` and `bytes_single` +maintain this, and `bytes_concat` traps before allocating if the exact sum +exceeds `INT64_MAX`, keeping `bytes_length` total. Implementations may use flat +views for input and chunks or ropes for output without exposing storage layout. + +Authored runtime traps are limited to: + +- signed `+`, `-`, or `*` overflowing `Int`; +- `/` or `%` dividing by zero or computing `INT64_MIN` with `-1`; +- `bytes_single` receiving a value outside `0..255`; +- `bytes_get` receiving a negative or out-of-range index; +- `bytes_concat` exceeding logical length `INT64_MAX`. + +Out-of-range integer literals are compile-time rejections, not runtime traps. A +corrupt private `Bytes` descriptor, impossible checked state, or replay +mismatch is `InternalFailure`; heap, stack, input, or output exhaustion is +`Incomplete`. Neither is a Delta trap. + +The compact `Bytes` primitive is structurally required: representing a 4 MiB +input as `Cons(Int, Bytes)` nodes at 16 bytes each would need 64 MiB on a +16 MiB oracle heap. + +Divergence stays divergence. Step counts are not Delta semantics: an evaluator +may bound steps for diagnostics, returning `Incomplete`, which proves neither +rejection nor divergence. ## Compiler-application profile -Delta itself has no byte-I/O operation. Its source semantics ends at a pure -returned value; a compiler-generated Gamma adapter may join that value to -sealed input and an external observation contract. The adapter -choice is one closed, sealed application-profile ID supplied alongside the -exact Delta source. The ID is part of compilation identity and reconstruction -evidence. It is not Delta syntax, an ambient host flag, a filename convention, -or a property inferred from source names. +Delta has no byte-I/O operations; its semantics ends at a pure return value. A +compiler-generated Gamma adapter connects that value to sealed input and output +rules, selected by a closed application-profile ID sent beside the Delta source. +That ID is part of compilation identity, never Delta syntax, a host flag, or a +filename convention. -The canonical version-1 request is one exact length-delimited byte sequence: +A version-1 request is one length-delimited byte sequence: ```text 0..7 [44 43 52 45 51 01 00 00] (`DCREQ`, version 1, reserved) @@ -203,69 +177,54 @@ The canonical version-1 request is one exact length-delimited byte sequence: 16.. exact Delta-source bytes; exact end of request ``` -The consuming compiler artifact's embedded metadata owns the profile-ID set. -The current version-1 artifact assigns `1` to `ConformanceBytesV1` and `2` -to `ConstructionBytesV1`. Zero and every other ID reject. -A later ID does not require a new envelope version, while a representation -change does. The exact request and selected embedded metadata participate in -compilation identity. Profile facts are never repeated as request claims or -inferred from source, filenames, or ambient invocation state. - -The sealed input presented to the composed compiler artifact continues past -the request's exact end with the bound support section: the packed members of -[`compiler/support/support.gamma.sources`](compiler/support/support.gamma.sources) in manifest -order, under the `GammaComposedV2` composition contract -(`bootstrap/gamma/interpreter/COMPOSED_ARTIFACT.md`). The members are the ordinary -Gamma source the compiler copies into emitted programs - the byte-rope -runtime, sealed-input support, and both generated `main` adapters, each -authored once under `compiler/support/`. Both profiles admit the full four-member -section. ID 1 also accepts its exact original 2,998-byte three-member -section. ID 2 requires its construction member. The compiler verifies each -present member against its bound extent and rolling sum before observing -Delta source; copying during publication is a byte-level walk of the sealed input, -not a host-provided semantic operation. - -`ConformanceBytesV1` selects exact 4,194,304-byte maximum sealed-input and -successful-output extents. It requires `main : Bytes -> Bytes`. Its adapter -reads one sealed input, invokes `main`, preflights the complete returned value, -and publishes exactly those bytes on success. An input or output exceeding the -selected maximum is a profile-owned generated-program observation, not a Delta -trap or compiler-boundary result. These limits are distinct from the -implementing Gamma evaluator's source and sealed-input resources even where -numeric values coincide. - -`ConstructionBytesV1` requires the same typed `main : Bytes -> Bytes`. -It supports compiler-sized source and products with the following inclusive -limits. Delta source and emitted Gamma are compiler resources. Application -input and output are byte extents of the executable produced from that Gamma. +The compiler's embedded metadata defines valid profile IDs: `1` selects +`ConformanceBytesV1` and `2` selects `ConstructionBytesV1`; `0` and all other +IDs reject. Adding an ID keeps envelope version 1, while changing the wire +format requires a new version. Profile facts are never duplicated in the +request or guessed from ambient state. + +Sealed input continues past the request with the bound support section — the +ordered files of [`compiler/support/support.gamma.sources`](compiler/support/support.gamma.sources) +under `GammaComposedV2` (`bootstrap/gamma/interpreter/COMPOSED_ARTIFACT.md`): +the byte-rope runtime, sealed-input support, and both `main` adapters authored +under `compiler/support/`. Both profiles accept the full four-member section; +ID 1 also accepts its original 2,998-byte three-member section, while ID 2 +requires all four. The compiler checks every present member's length and +rolling byte sum before reading Delta source, then copies needed members +byte-for-byte into emitted Gamma. + +`ConformanceBytesV1` caps sealed input and successful output at 4,194,304 bytes +and requires `main : Bytes -> Bytes`. Its adapter reads input, calls `main`, +preflights the returned value, and writes those exact bytes on success. +Exceeding input or output limits is a generated-program runtime status, not a +Delta trap or compiler error, and stays separate from the Gamma evaluator's own +limits. + +`ConstructionBytesV1` also requires `main : Bytes -> Bytes`, widening inclusive +limits for compiler-sized programs: | DCREQ ID | Delta source | Emitted Gamma | Application input | Application output | | --- | ---: | ---: | ---: | ---: | | 1 | 4 MiB | 16,777,212 bytes | 4 MiB | 4 MiB | | 2 | 64 MiB | 128 MiB | 8 MiB | 128 MiB | -The construction adapter checks the input length before calling `main` and -the returned rope length before writing. Its publisher visits concatenation -children in order, skips empty nodes, writes singleton bytes directly and -reads sealed-input views in their original order. Exceeding the input or -output limit returns 253 or 254 respectively with empty stdout. Execution -resources of the selected Gamma host still apply. When running the receipt in -the Gamma interpreter, the four-byte length, Gamma source and sealed input -share its 137,363,456-byte request provision. A maximum-size construction -receipt leaves 3,145,724 bytes for application input in that host. Compiling -the receipt to native code or Alpha tape encounters the backend's separate -image limits. - -Older compiler artifacts retired the former `EpsilonCompilerV1` use of ID 2. -The composed artifact identity determines the ID registry. The current ID 2 -accepts ordinary Delta byte applications only. +The construction adapter checks input length before calling `main` and returned +rope length before writing, walking concatenation children in order, skipping +empty nodes, writing singletons directly, and copying sealed-input views in +order. Exceeding input or output limits exits 253 or 254 with empty stdout. +Gamma host limits still apply: in the Gamma interpreter, the 4-byte length, +Gamma source, and sealed input share its 137,363,456-byte request buffer (so a +max-size construction receipt leaves 3,145,724 bytes for application input). +Compiling to native code or Alpha tape applies the backend's own image limits. + +Older compiler builds retired the former `EpsilonCompilerV1` use of ID 2; the +current ID 2 accepts ordinary Delta byte programs only. ### Conformance observation profile -`ConformanceBytesV1` writes no byte until the complete returned `Bytes` has -passed descriptor, logical-length, traversal, and output-extent preflight. Halt -0 publishes exactly that value. Every recognized failure publishes empty -stdout. The generated-program status block is: +`ConformanceBytesV1` writes nothing until the returned `Bytes` passes +descriptor, length, traversal, and output-size preflight. Status 0 writes that +value; every failure writes empty stdout: ```text 132 Alpha VM illegal-instruction trap @@ -279,203 +238,129 @@ stdout. The generated-program status block is: 255 unassigned and noncanonical ``` -Status 132 is the Alpha VM refusing an illegal instruction, not a Delta -language trap. Status 249 is a deliberate generated-code observation of one of -Delta's closed authored trap conditions. Status 255 remains unavailable so a -shell or harness projection of `-1` cannot imitate an admitted internal -failure. Divergence produces no terminal observation. +Status 132 is an Alpha VM illegal instruction, not a Delta trap. Status 249 is +one of Delta's closed authored traps. Status 255 stays unassigned so `-1` +projections cannot impersonate an internal failure. Divergence produces no exit +status. ## Compiler boundary family -Canonical compiler edges share one boundary discipline: +Canonical compiler boundaries share one rule set: -- halt values `0..3` mean Complete, Reject, Incomplete, and InternalFailure; -- success stdout is the exact canonical output for that edge: Gamma source for - Delta, or raw Alpha tape for an Omega `alpha_bootstrap` product, with no wrapper; -- failure stdout is one canonical 40-byte, `0xFF`-prefixed frame whose tag agrees - with the halt value; and +- exit status `0..3` means Complete, Reject, Incomplete, or InternalFailure; +- success stdout is the exact unwrapped output (Gamma source for Delta, or raw + Alpha tape for an Omega `alpha_bootstrap` product); +- failure stdout is one 40-byte `0xFF`-prefixed frame whose tag matches the + exit status; - unknown, malformed, noncanonical, or mismatched frames reject. -Each accepted-language compiler edge owns its magic, version, -reason/resource/internal tables, and coordinate vocabulary. The Delta compiler -uses `DCOUT` V1, `[FF 44 43 4F 55 54 01 00]`, with coordinate spaces: +Delta uses `DCOUT` V1 (`[FF 44 43 4F 55 54 01 00]`) with coordinate spaces: ```text 0 none, 1 Delta source, 2 emitted payload, 3 internal row, 4 DCREQ, 5 bound support section ``` -`DCREQ` validation precedes Delta lexing, declaration/type/match checking, -selected-profile schema validation, and lowering/emission. The fixed header -and magic/version/reserved bytes precede profile selection; profile selection -precedes the declared source-length provision; and only an admitted length is -followed by exactly that many body bytes, then the exact bound support -section, then one exact-end probe. Consequently -a four-byte length cannot require attacker-selected input consumption before -`Incomplete(source_bytes)`. Unknown profile and source-length exhaustion anchor -at request bytes 8 and 12 respectively. Body truncation and one byte after the -complete sealed input are `malformed_request` at the first missing or trailing -request byte. - -Support-section coordinates are absolute sealed-input offsets, like DCREQ -coordinates. `incomplete_support_section` (code 1) reports an input that ends -before the bound section is complete, anchored at the observed end of input. -`member_mismatch` (code 2) reports a member whose extent-and-byte sum -disagrees with the compiler's bound table, anchored at the member's absolute -sealed-input offset. Both are `Reject` outcomes published atomically as one -DCOUT frame; no partial compilation result precedes them. The same custody -check covers the materialization side: the bound plumbing refuses a missing -or corrupt member file before the compiler's sealed input is even built. - -After an otherwise valid frontend pass, an absent `main` has no coordinate and -a wrong present `main : Bytes -> Bytes` anchors its schema rejection at the -declaration name. - -The future compiler artifact embeds its closed tables. No host table is a -runtime input or semantic authority. Generated-program statuses 248 through -254 remain separate runtime observations, never compiler-boundary cases. +`DCREQ` checking runs before lexing, checking, profile validation, and +emission, in strict order: fixed header, magic/version/reserved bytes, profile +ID, declared source length, exact body bytes, bound support section, and exact +EOF. An oversized length therefore returns `Incomplete(source_bytes)` at byte +12 before reading body bytes. Unknown profile anchors at byte 8. Body +truncation or trailing bytes after the sealed input return `malformed_request` +at the first missing or trailing byte. + +Support-section coordinates are absolute sealed-input offsets. +`incomplete_support_section` (code 1) anchors at observed EOF; +`member_mismatch` (code 2) anchors at the corrupt member's offset. Both return +a single `Reject` frame with no partial output. Materialization scripts check +the same member hashes before assembling sealed input. + +After static checking passes, missing `main` reports coordinate 0 and a wrong +`main : Bytes -> Bytes` signature anchors at the `main` declaration name. + +The compiler embeds all diagnostic tables directly; no external host table acts +as a runtime input. Generated-program statuses 248–254 are runtime outcomes, +never compiler DCOUT frames. ## Compilation requirements -The Gamma-authored Delta compiler must type-check before emission, erase types -into a defined runtime representation, and emit canonical Gamma source. The -selected Beta-authored Gamma evaluator executes that receipt under the required -application profile; Beta alone encodes Alpha. Generated Gamma must support -arbitrary function and constructor arity and preserve proper tail calls. The -Delta compiler may not invoke an external evaluator, add Delta operations to -Gamma or Alpha, interleave direct Alpha emission with Delta checking, or make a -private capacity into Delta semantics. - -The selected compiler source has a staged implementation for arbitrary-field -finite ADTs, including recursive data, plus exhaustive matches, exact global -call signatures, lexical local-scope resolution, and the complete -scalar/nominal type relation. Authored signed arithmetic has checked runtime -lowering, ordinary tail calls survive `if`, `let`, and `match`, and the five -normative `Bytes` operations lower through a private length-bearing rope. -`ConformanceBytesV1` framing, schema validation, and generated execution are -implemented. Strict DCREQ admission publishes canonical DCOUT request -rejections and source-length refusals. Source-envelope, lexical token and -integer-range, structural syntax, duplicate-global, and post-frontend -entry-schema diagnostics also publish canonical DCOUT. Declaration and body -checking publish codes 9 through 18 for local/pattern conflicts, unknown names -and types, type and arity disagreement, duplicate match cases, and incomplete -match coverage. The complete global -census precedes this phase. It accounts for 32,768 authored function -rows, checking an exact duplicate before provisioning each fresh row. A fresh -32,769th function returns `Incomplete` resource code 4 at its name-token start, -limit 32,768 and requested 32,769, before insertion or declaration-type -resolution. Complete grammar/depth checking precedes this count. Generated -helpers and typed metadata copies do not add authored rows. Gamma's selected -function table fits every source admitted by its request extent, independently -of Delta's authored-row count. -The [generated-census gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/generated-function-census/README.md) -executes a complete receipt at the 32,768 authored-function allowance with -additional Gamma runtime helpers. Complete payload admission bounds function -storage, but does not close the other generated-program resources. -The same census accounts for 65,536 authored constructor rows globally across -data declarations. Each fresh constructor advances that count once; payload -fields and resolved metadata copies do not consume additional constructor rows. -Duplicate constructor lookup precedes provision. A fresh 65,537th constructor -returns `Incomplete` resource code 3 at its name-token start, with limit 65,536 -and requested 65,537, before its metadata or trie row is allocated. Duplicate -types reject before any constructor in that declaration is provisioned. -The type-row total includes the two builtins, `Int` and `Bytes`, plus each -fresh nominal declaration. The selected 65,536-row limit therefore admits -65,534 nominal declarations. Annotation occurrences and metadata copies do not -add type rows. Duplicate type lookup precedes provision; a fresh declaration -requesting total row 65,537 returns `Incomplete` resource code 2 at its -type-name start, with limit 65,536 and requested 65,537, before type metadata -or any constructor processing. Builtin identities need no nominal trie entries, -but that representation choice does not increase the selected logical total. -Local environments account for 65,536 active binding rows. Each function -starts with an empty environment; its parameters, active `let` bindings, and -current pattern bindings share this limit. A fresh 65,537th binding returns -`Incomplete` resource code 5 at its name-token start, with limit 65,536 and -requested 65,537, before insertion. Parameter conflict and annotation checks -precede provision. A `let` resolves its annotation, checks conflict, provisions -its body binding, then checks its initializer against the unchanged outer -environment. Pattern outer conflicts and repeated-binder checks precede each -provision. Saved environments restore their counts with their names, so sibling -scopes and disjoint arms do not accumulate bindings. Retained snapshots and -trie nodes do not add active rows; this is not a generated-runtime slot limit. -Declarations, constructors, and fields are visited -in authored order; each parameter's conflict check precedes its own annotation, -parameters precede the result type, and all declarations precede all bodies. -Retained balanced syntax and grammar judgments feed the global census, -signature resolution, complete body typing, and selected-profile validation. -Lowering then completes an expanded Gamma program before the first output byte. -Explicit continuations retain pending children, while the plan records binding -identities and generated expression-list heights. A separate normalizer reuses -fitting subtrees and extracts over-height fragments into generated functions -under a 255-list body budget. Free-binding collection retains each completed -helper body and shares its original binding atoms between helper parameters -and call arguments. Lexical scope and active-name uniqueness make those names -safe in independently scoped Gamma functions. Replacement calls retain the -fragments' evaluation and tail positions. A serializer prints the resulting plan -rather than selecting lowering rules during publication; exact spans supply admitted names -and literal bytes. -Serialization first counts the complete payload without writing, including -the bound support members, profile text, definition separators, and the -entry-owned final LF. Expression nodes cache exact occurrence extents using the serializer's -shared atom and prefix formatting, so preflight need not unfold shared children -again. Rebuilt nodes refresh that summary; extent addition is checked, not -saturated. A count above the selected emitted-Gamma limit returns `Incomplete` -code 12 in emitted-payload coordinate space 2, at that limit, with the exact -complete requested count. Count and publication share formatting ownership; -no partial artifact precedes this refusal. -Negative retained emission counts propagate to completed preflight and report -`InternalFailure` code 2 (`emission_metadata_contradiction`) before publication, -at internal row 0 with zero limit/requested. This row identifies the singleton -complete-program emission record, not the corrupt child or an authored source -location. Positive signed count overflow in private metadata and late replay -disagreement remain raw evaluator failures, not canonical DCOUT outcomes. The +The Gamma-authored Delta compiler must type-check before emitting, erase types +into a defined runtime layout, and output canonical Gamma source for the +Beta-authored Gamma evaluator (Beta alone encodes Alpha). Emitted Gamma must +support arbitrary arity and proper tail calls. The compiler must not call an +external evaluator, extend Gamma or Alpha with Delta ops, interleave Alpha +emission with checking, or turn private limits into Delta semantics. + +The staged compiler implements arbitrary-field finite ADTs (including recursive +data), exhaustive matches, exact call signatures, lexical local scoping, +checked signed arithmetic, tail-call preservation through `if`/`let`/`match`, +and the five `Bytes` operations over a length-bearing rope. +`ConformanceBytesV1` framing, schema checking, and execution work end to end. +DCOUT covers request errors, source-byte and lexical errors, integer range, +syntax, duplicate globals, local/pattern conflicts (codes 9–10), unknown names +and types (11–14), type/arity mismatches (15–16), duplicate/nonexhaustive +matches (17–18), missing `main` (19), and entry schema mismatch (20). + +Before declaration resolution, the global census enforces: + +- **Functions (code 4):** 32,768 fresh authored functions (duplicate check + before limit; 32,769th returns `Incomplete` at its name). Generated helpers + and metadata copies do not count. For profile 1, emitted Gamma fits Gamma's + 2,097,152-row table via the 8-byte-per-declaration payload bound; the + [generated-census gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/generated-function-census/README.md) + executes a 32,768-function receipt with runtime helpers. +- **Constructors (code 3):** 65,536 fresh constructors globally across all data + declarations (duplicate check before limit; 65,537th returns `Incomplete` at + its name before metadata allocation; duplicate types reject first). +- **Types (code 2):** 65,536 total types including `Int` and `Bytes` (65,534 + nominal declarations; duplicate check before limit; 65,537th returns + `Incomplete` at its name before constructor processing). +- **Active locals (code 5):** 65,536 simultaneously active bindings per + function across parameters, `let`s, and pattern binders (conflict/annotation + checks run in their phase order before limit; 65,537th returns `Incomplete` + at its name; saved scopes restore counts so siblings do not accumulate). + +Declarations, constructors, and fields resolve in authored order (parameter +conflicts before annotations, parameters before result, all declarations before +bodies). Lowering builds a complete expanded Gamma plan with explicit +continuations, binding IDs, and expression-list heights before writing output. +Normalization reuses fitting subtrees and extracts over-height fragments into +helpers under Gamma's 255-list body limit, sharing original binding atoms +between helper parameters and call arguments while preserving evaluation and +tail positions. Serialization prints that plan using exact source spans for +names and literals. + +Count-only preflight sums cached node extents plus support members, separators, +and the final LF using checked addition. Exceeding the profile payload cap +returns `Incomplete` code 12 in space 2 at that cap with the exact requested +count before writing any byte. Negative retained counts return +`InternalFailure` code 2 (`emission_metadata_contradiction`) at internal row 0 +(the program record). Positive private-metadata overflow and late replay +mismatches stay raw evaluator failures. The [selected producer's occurrence bound](compiler/implementation/emission/README.md#reachable-byte-count-bound) -keeps profile-1 intermediate and complete emission counts below `2^62`. -The 64 MiB construction source limit lies outside that argument. Extent -addition remains checked for both profiles. -Grammar implements the 1,024-level expression `parse_depth` profile: bodies -start at level 1, expression children including atoms advance by one, and match -arm bodies are at their enclosing match's level plus one. Declaration, parameter, -and pattern structure adds no expression levels. Before judging a level-1,025 -expression, it returns `Incomplete` code 8 at that node's source start, with -limit 1,024 and requested 1,025. Complete balanced parsing precedes this check. -Parsing and grammar share a syntax arena of 114,294,752 bytes in the ordinary -profile. ConstructionBytesV1 provisions 1,073,741,824 bytes for the Delta -programs emitted by the Epsilon compiler. -Its source-owned ledger counts parser nodes, both construction spines, parser -frames, the program root, and grammar work at the selected evaluator's actual -40 bytes per immutable pair. Usage is cumulative across completed lists and -declarations; phase-outcome carriers and later compiler phases are excluded. -Each allocation group is checked before allocation. Refusal returns -`Incomplete` code 7 at the owning source construct (or EOF for the final program -spine), the selected limit, and the exact requested cumulative bytes. With 40-byte pair rows, profile 1 has 32 tail bytes and profile 2 has 24. -A multi-pair allocation group can leave further space unused. Earlier -request, byte, and lexical failures retain precedence, and a reached syntax -refusal stops before any later parse or grammar judgment. -For profile 1 the complete receipt is at most 16,777,212 bytes, inside the -137,363,456-byte request extent. Every completed declaration consumes at -least eight receipt bytes (its parenthesis, `def`, `Int`, and close), so a -generated program carries at most 2,097,151 declarations and fits the -evaluator's 2,097,152-row function census without a compiler-owned refusal. -For profile 2, this receipt-length argument alone does not prove census -containment. Gamma still checks the actual program at admission. -Normalization bounds every generated body at 255 nested expression lists, and -generated lexical scopes stay inside the 68,608-binding normalization -allowance, below the evaluator's 131,072-row environment; fixed runtime and -adapter members are ordinary authored Gamma validated the same way. The -emitted program's own runtime resources (nested call contexts, temporary -values, immutable pairs, and buffered output) belong to that program's -execution: a generated application can still exhaust its evaluator or -diverge, and that failure is never a compiler DCOUT case. The producer's -execution storage and cumulative pair containment are proved by the -[execution-storage audit](compiler/implementation/boundary/execution_storage.md#cumulative-pair-containment): -every admitted profile-1 composition allocates at most 3,092,641,319 pairs, -inside the selected Gamma evaluator's 3,422,447,206-pair arena (90.36%, -329,805,887 pairs of headroom), without reprovisioning. Profile 2's wider 64 MiB -source and 1 GiB syntax limits remain outside that Beta-evaluator pair bound. -The compiler-owned DCOUT outcomes are exactly the resource and -internal tables above; an underlying evaluator failure is never substituted -for one of them. These judgments do not close the Delta edge or establish -complete Delta conformance. The former concatenative-Gamma implementation is -retired; its selected -conformance replacements do not by themselves close this edge. +keeps profile-1 counts below `2^62`; profile 2 lies outside that proof, though +addition remains checked. + +Grammar enforces the 1,024-level expression `parse_depth` limit (code 8): +function bodies start at 1, expression children and match-arm bodies add 1, +and declarations/parameters/patterns add 0; level 1,025 returns `Incomplete` +code 8 at that node's start after balanced parsing completes. Parsing and +grammar also share the cumulative syntax-arena budget (code 7): 114,294,752 +bytes in profile 1 and 1,073,741,824 bytes in ConstructionBytesV1, charging 40 +bytes per Gamma pair (leaving 32 tail bytes in profile 1 and 24 in profile 2) +before each allocation group and anchoring at the owning construct or EOF. + +In profile 1, every emitted receipt is at most 16,777,212 bytes (inside Gamma's +137,363,456-byte request buffer) and holds at most 2,097,151 declarations (at +least 8 bytes each: `(`, `def`, `Int`, `)`), fitting Gamma's 2,097,152-row +table; profile 2 relies on Gamma admission directly. Normalization keeps every +generated body within 255 lists and 68,608 static bindings (inside Gamma's +131,072-row validation environment). Runtime stacks, heap, and output of +generated programs remain those programs' own limits, never compiler DCOUT +frames. The compiler's own storage and profile-1 pair containment are proved in +the [execution-storage audit](compiler/implementation/boundary/execution_storage.md#cumulative-pair-containment) +(at most 3,092,641,319 pairs inside the 3,422,447,206-pair arena, 90.36%, +329,805,887 pairs headroom); profile 2 stays outside that Beta-evaluator pair +bound. Evaluator failures are never substituted for compiler DCOUT frames. The +old concatenative-Gamma compiler is retired; these checks do not by themselves +close the full Delta bootstrap edge. diff --git a/bootstrap/delta/compiler/README.md b/bootstrap/delta/compiler/README.md index 6bd8b2bf3de6..9774478b868e 100644 --- a/bootstrap/delta/compiler/README.md +++ b/bootstrap/delta/compiler/README.md @@ -1,20 +1,20 @@ # Delta compiler -Delta is the typed, pure functional rung above Gamma. It supplies nominal +Delta is the typed, pure functional language above Gamma, providing nominal algebraic data, exhaustive pattern matching, checked signed integers, immutable -bytes, forward and mutual recursion, and proper tail calls. It is deliberately -small and exists to implement the Epsilon evaluator. +bytes, forward and mutual recursion, and proper tail calls. It is kept small to +implement the Epsilon evaluator. -[`../LANGUAGE.md`](../LANGUAGE.md) is normative. The [compiler entry](delta_compiler.gamma) takes a Delta source -request, checks declarations and expression types, and emits Gamma source. -The emitted program can run on the [Gamma interpreter](../../gamma/interpreter/) -or be compiled with either [Gamma backend](../../gamma/compiler/). -The [language stage](../README.md) lists the available implementations. +[`../LANGUAGE.md`](../LANGUAGE.md) is the specification. +[delta_compiler.gamma](delta_compiler.gamma) reads a Delta request, type-checks +declarations and expressions, and emits Gamma source that runs on the +[Gamma interpreter](../../gamma/interpreter/) or compiles with either +[Gamma backend](../../gamma/compiler/). See [the language stage](../README.md) +for available implementations. -The Delta compiler may know only Gamma, Delta, and its exact application -profiles. It may not encode Alpha, parse Epsilon source itself, -invoke a host translator, serialize an interpreter as output, or acquire -general-purpose runtime facilities. +The Delta compiler may know only Gamma, Delta, and its application profiles. It +may not encode Alpha, parse Epsilon, call a host translator, embed an +interpreter in its output, or add general runtime facilities. ## Retention inventory @@ -28,16 +28,15 @@ general-purpose runtime facilities. ## Selected staged Delta compiler -`delta_compiler.gamma` is the canonical request entry of the selected -Gamma-authored Delta stage. It admits DCREQ, runs the shared compiler pipeline, -and publishes either the successful Gamma receipt or an owned failure -frame through the selected Beta-authored Gamma evaluator. -`delta_compiler.composed` binds the complete entry-plus-implementation bytes, -the packed `support/` member bytes (including the original profile-1 prefix), and -evaluator-tape identity under `GammaComposedV2`, not the entry file alone. +`delta_compiler.gamma` is the request entrypoint for the Gamma-authored Delta +compiler. It validates DCREQ, runs the compiler pipeline, and outputs either +Gamma source or a DCOUT failure frame on the Beta-authored Gamma evaluator. +`delta_compiler.composed` binds the full entry-plus-implementation bytes, +packed `support/` bytes (including the profile-1 prefix), and evaluator tape +under `GammaComposedV2`. -Bound edge identities, checked by `tools/bootstrap/delta/compiler_env.sh` -against every materialization and by `tests/bootstrap/interpreted/delta-identity.sh`: +Pinned hashes checked by `tools/bootstrap/delta/compiler_env.sh` and +`tests/bootstrap/interpreted/delta-identity.sh`: | Subject | Bytes | SHA-256 | | --- | ---: | --- | @@ -48,16 +47,14 @@ against every materialization and by `tests/bootstrap/interpreted/delta-identity | Packed canonical closure | 152,411 | `cfa4f2a6f75352d819a83486169bd517ab48ecf90246c561e47a809309ccc25f` | | Packed support section | 4,301 | `439fef90e10007baec81920e84b89f50ad815a27af80499e4240e1dcd55f9243` | -A digest is an identity check on the bytes being compiled, not a proof of the -compiler; historical stress evidence pins the closure identity of its own run. +A digest identifies the exact bytes being compiled, not compiler correctness; +historical stress runs pin their own closure digests. ## Run the application profile checks -Build the native Delta and Gamma tools on Linux x86-64, then run both -public profiles through them. The checks compare the two receipts, validate -rejection coordinates and support custody, and execute generated programs at the input limits and just beyond both output -limits. Add `--full-output` to publish and compare the complete 128 MiB -construction result at its exact limit. +Build the native Delta and Gamma tools on Linux x86-64 and test both profiles +(comparing outputs, rejection coordinates, support checks, input limits, and +output limits; pass `--full-output` to verify the full 128 MiB profile-2 output): ```sh work=$(mktemp -d) @@ -67,371 +64,175 @@ python3 tests/bootstrap/independent/delta_profiles.py "$work/host/program" "$wor ## Source organization -Start at `delta_compiler.gamma`, then follow `implementation/pipeline.gamma`. -The latter sequences source checking, catalogs, typing, profile validation, -complete Gamma lowering, body-height normalization, and emission. Concept-owned -members are grouped below it: - -- `implementation/boundary/`: bounded request admission and DCOUT publication; -- `implementation/checking/`: source tokens, retained syntax and grammar roles, - exact-name catalogs, declarations, expression types, and application schema; -- `implementation/representation/`: the expanded Gamma program, expressions, - binding identities, and generated expression heights; -- `implementation/lowering/`: checked Delta declarations and expressions to - that Gamma plan, including calls, constructors, arithmetic, and matches; -- `implementation/normalization/`: scoped Gamma body-height budgets and - capture-safe extraction of over-height fragments into generated functions; -- `implementation/emission/`: generic Gamma serialization and the bound - support-member custody/copying in `support.gamma`. +Start at `delta_compiler.gamma`, then read `implementation/pipeline.gamma`, +which sequences source checking, global catalogs, typing, profile checks, Gamma +lowering, body-height normalization, and emission: + +- `implementation/boundary/`: DCREQ validation and DCOUT output; +- `implementation/checking/`: lexing, retained syntax and grammar, exact-name + tries, declaration resolution, body typing, and application schema; +- `implementation/representation/`: expanded Gamma program, expressions, + binding IDs, and expression heights; +- `implementation/lowering/`: Delta declarations and expressions lowered to + that Gamma plan (calls, constructors, arithmetic, matches); +- `implementation/normalization/`: 255-list body-height enforcement and + capture-safe helper extraction; +- `implementation/emission/`: Gamma serialization and bound support-member + verification/copying in `support.gamma`. [`checking/syntax/storage.gamma`](implementation/checking/syntax/storage.gamma) -owns the cumulative syntax-byte provision shared by parsing and grammar. -Each syntax allocation group is admitted before construction, at the selected -Gamma pair size, while phase carriers and later compiler objects stay outside -that ledger. The [syntax guide](implementation/checking/syntax/README.md#syntax-storage) -defines exact groups, coordinates, and refusal fields. +tracks the cumulative syntax-byte budget shared by parsing and grammar (40 +bytes per Gamma pair, excluding phase wrappers and later phases; see the +[syntax guide](implementation/checking/syntax/README.md#syntax-storage)). Declaration resolution starts at [`checking/declarations.gamma`](implementation/checking/declarations.gamma). -Its subordinate `checking/declarations/` members separate +Under `checking/declarations/`, [`functions.gamma`](implementation/checking/declarations/functions.gamma) -(parameters and signatures), -[`data.gamma`](implementation/checking/declarations/data.gamma) -(constructors and fields), and -[`types.gamma`](implementation/checking/declarations/types.gamma) -(retained type-node resolution). - -Body typing starts at -[`checking/types.gamma`](implementation/checking/types.gamma), then follows -[`checking/types/`](implementation/checking/types/README.md) for identities, -expression dispatch, branches, bindings, calls, and matches. Continuation -frames belong to the expression dispatcher and each concept's payload owner. +handles parameters and signatures, +[`data.gamma`](implementation/checking/declarations/data.gamma) handles +constructors and fields, and +[`types.gamma`](implementation/checking/declarations/types.gamma) handles +type-node resolution. + +Body typing starts at [`checking/types.gamma`](implementation/checking/types.gamma) +and dispatches into [`checking/types/`](implementation/checking/types/README.md) +for IDs, expressions, branches, bindings, calls, and matches. Global collection starts at [`checking/collection.gamma`](implementation/checking/collection.gamma). -[`checking/names/`](implementation/checking/names/README.md) separates -the private identity cursor, exact prefix navigation, and admitted insertion. -Global census and parameter cataloging share these construction cursors; -downstream phases receive ordinary completed tries and counted environments. -Declaration resolution also starts cursors from the completed census roots, -reusing final nullary metadata and replacing only unresolved typed payloads. +[`checking/names/`](implementation/checking/names/README.md) provides shared +exact-name construction cursors used by global collection, parameter cataloging, +and declaration resolution (which starts from census tries, keeps finished +nullary constructors, and replaces resolved payload/function rows). Downstream +phases receive ordinary tries and counted environments. [`checking/environments.gamma`](implementation/checking/environments.gamma) -owns counted local environments and their shared active-row provision. -Parameter cataloging and body binding keep their role-specific conflict and -annotation order; saved environments carry names and counts together through -initializer, branch, argument, and match-arm continuations. - -Lowering starts at -[`lowering/program.gamma`](implementation/lowering/program.gamma) and completes -every authored function body before publication. The resulting program is defined in -[`representation/gamma.gamma`](implementation/representation/gamma.gamma). -[`normalization/`](implementation/normalization/README.md) then extracts -over-height fragments while retaining evaluation order and binding identity. -[`emission/program.gamma`](implementation/emission/program.gamma) serializes -the resulting Gamma plan; it does not select Delta lowering rules. A count-only -pass through the serializer measures all payload bytes before publication, -including the bound support members and the entry-owned final newline. Above -the selected limit (16,777,212 bytes for profile 1, 128 MiB for profile 2), -the compiler returns DCOUT resource 12 in emitted-payload space at that limit -with the exact complete requested count. Final-child -closes are scalar traversal state, so unary projection chains allocate no -per-projection continuation during publication. Gamma nodes also retain exact -serialization extents built from shared formatting helpers and child summaries; -preflight sums those cached extents without unfolding shared children again. - -`implementation/implementation.gamma.sources` selects all 65 shared members -with exact lengths, digests, and ordered identities. The byte-only source -materializer validates that closed inventory and prefixes the explicitly -selected entry. For the canonical entry, its application marker is therefore -the first declaration. The separate `support/support.gamma.sources` manifest -binds the three runtime/adapter members the same way; its packed bytes are -the sealed-input support section. Callers use the role registry's -`OMEGA_PATH_DELTA_COMPILER_SOURCES`, `OMEGA_PATH_DELTA_COMPILER_SOURCE`, and -`OMEGA_PATH_DELTA_COMPILER_SUPPORT_SOURCES`. -Reading the entrance alone does not reconstruct the compiler. - -The separate `tests/bootstrap/interpreted/delta/staged-compiler/development_driver.gamma` entry -invokes these same shared bytes as an unmarked raw-source transformer whose -sealed input is raw Delta source followed by the same bound support section. -It exists only for frontend/lowering diagnostics and does not select a compiler -application profile. The canonical entry never detects raw source, guesses a -profile from its first byte, or falls back to that diagnostic entry. +manages counted local environments and the 65,536 active-row limit, preserving +each role's conflict/annotation order and carrying names and counts together +across continuations. + +Lowering starts at [`lowering/program.gamma`](implementation/lowering/program.gamma) +and builds a complete [`representation/gamma.gamma`](implementation/representation/gamma.gamma) +plan before writing output. [`normalization/`](implementation/normalization/README.md) +extracts over-height fragments while preserving evaluation order and binding +IDs. [`emission/program.gamma`](implementation/emission/program.gamma) first +counts total payload bytes (including support members and final LF) using +cached node extents without unfolding shared children, refusing outputs over +the profile limit (16,777,212 bytes for profile 1, 128 MiB for profile 2) with +DCOUT resource 12 in payload space 2 before writing a byte. Final-child closes +use a scalar counter, so unary projection chains allocate no continuation +frames. + +`implementation/implementation.gamma.sources` lists all 65 shared files with +exact sizes and hashes; the materializer checks that manifest and prepends the +chosen entrypoint so the application marker comes first. +`support/support.gamma.sources` binds the runtime/adapter files packed into the +sealed-input support section. Scripts use `OMEGA_PATH_DELTA_COMPILER_SOURCES`, +`OMEGA_PATH_DELTA_COMPILER_SOURCE`, and +`OMEGA_PATH_DELTA_COMPILER_SUPPORT_SOURCES`. Reading the entrypoint alone does +not reconstruct the compiler. + +`tests/bootstrap/interpreted/delta/staged-compiler/development_driver.gamma` +runs the same shared files on raw Delta source (plus the bound support section) +for frontend/lowering diagnostics only; the canonical entry never guesses raw +source or falls back to it. ## Implemented semantics -The current stage accepts the Gamma-shaped scalar core, immutable `Bytes`, and -finite data whose constructors carry any finite number of `Int`, `Bytes`, or -known nominal fields, plus exhaustive matches in authored arm order. It assigns -constructor tags in declaration order. A type with one constructor and one -field carries that field directly. With more fields it carries their -right-nested product. A match on either record binds the subject once, -including when every field goes unused. A type with multiple constructors -and at least one payload carries `(pair tag product)`. Its nullary constructors -carry zero padding. A match on that type projects the tag and product once. +The compiler accepts the scalar core, immutable `Bytes`, arbitrary-field finite +data (`Int`, `Bytes`, or nominal fields), and exhaustive matches in authored +arm order. Constructor tags start at 0 in declaration order. A single-constructor +single-field type stores its field directly; multi-field records store a +right-nested product (matches bind the subject once even if fields go unused). +Multi-constructor types with any payload store `(pair tag product)` (nullary +constructors pad with 0); matches project tag and product once. ```text (data Choice (Left) (Right)) ``` -becomes the scalar tag representation `Left = 0`, `Right = 1`. `Option` becomes -`Some 9 = (pair 1 9)` and `None = (pair 0 0)`. A recursive `List` constructor -with head and tail fields becomes `(pair tag (pair head tail))`. A match must contain -exactly one arm for every constructor, but arms may use any authored order and -nullary patterns may be bare or parenthesized. Generated local -names use `$m`, `$p`, and `$v` prefixes. `$` is outside Delta's identifier -alphabet but inside Gamma's, so generated binders cannot capture or be captured -by an authored Delta name. - -Before tokenization or emission, the stage rejects every source byte except HT, -LF, CR, and printable ASCII, exactly matching Delta's textual envelope. A -complete lexical pass then admits identifiers, parentheses, arithmetic operator -tokens, and signed decimal literals. It checks an entire numeric spelling -before its range, so an overflowing prefix with a nondigit suffix is invalid -syntax, not an out-of-range literal. Comments retain CR, LF, and EOF boundaries. -Identifier admission finds the token end and validates its tail in one scan, -leaving whitespace, parentheses, and semicolons for the next scanner step. -Malformed tails still reject at the token start after full envelope admission; -nonidentifier spelling and integer-range checking retain their existing order. -Later name-role checks consume that lexical admission: they check initial -category and exact reserved spelling without scanning identifier tails again. -Only `Int` and `Bytes` can be reserved uppercase names; type positions admit -both builtins while nominal declaration positions exclude them. Prefixes such -as `IntX` remain ordinary identifiers. Nominal existence is still resolved only -after the complete global census. -After lexical admission, a total parser retains exact atom/list spans and ordered -children. An explicit frame stack handles nesting without recursive return -contexts. The complete balanced tree precedes grammar-role checking, so a later -unmatched delimiter wins over an earlier malformed declaration role. Missing -closing parentheses anchor at exact EOF; unmatched closing parentheses anchor -at their own byte. A separate iterative worklist checks declaration, binder, -type-name, expression, and pattern roles. Offending children anchor at their -start, and missing children at the containing closing parenthesis. -Pending grammar batches share parser-owned ordered child spines. Successful -roles tail-dispatch directly, without reversed child copies or per-role success -wrappers; only the complete declaration returns an outcome to the coordinator. -Grammar work entries also retain expression level. Function bodies start at 1; -expression children, including atoms and match arm bodies, advance by one. -Declarations, parameters, and patterns do not add levels. Before a level-1,025 -expression's own grammar judgment, the selected 1,024-level `parse_depth` -profile produces an exact `Incomplete` frame: code 8, source coordinate at that -node's start, limit 1,024, requested 1,025. Complete balanced parsing remains -earlier, and the refusal is not a Delta syntax error. -Only after the complete structural grammar passes does collection consume the -retained program. Collection records every type, -constructor, and function identity, constructor counts, representation shape, -and source coordinates before resolving any declaration type. Duplicate -identities therefore precede declaration-type and body failures. Resolution -then checks fields and signatures against the complete catalogs, followed by -body checking. Census also provisions 32,768 authored `function_rows`: -duplicate lookup precedes each fresh row, and a fresh 32,769th declaration -returns `Incomplete` resource code 4 at its name, before row insertion or any -declaration-type resolution. This count excludes metadata copies and generated -helpers; Gamma's physical function storage is separately bounded by its complete -request extent, as established in the evaluator profile. -The census also counts fresh authored constructors across all data declarations. -The selected profile admits 65,536 rows; a fresh 65,537th name returns `Incomplete` resource -code 3 at that name, with limit/requested 65,536/65,537. Duplicate lookup -precedes provision, and a refused constructor allocates no row metadata. -Payload fields and the later declaration-resolution metadata rebuild do not -advance this count. Constructor tags still restart within each data owner; -the global resource count does not change their representation. -Type-row accounting starts at two for the builtin `Int` and `Bytes` identities -and advances once per fresh nominal declaration. The 65,536 total admits -65,534 nominal declarations, independent of the builtin identities' physical -representation outside the nominal trie. A duplicate type retains code 6; -a fresh over-capacity type returns `Incomplete` resource code 2 at its name, -with limit/requested 65,536/65,537, before its payload-summary traversal, -metadata allocation, or constructor collection. Type annotation occurrences -and resolved metadata copies do not consume new rows. -Declaration resolution visits declarations, constructors, and -fields in authored order. Each function parameter's conflict check precedes its -own type annotation, parameters precede the result type, and the whole -declaration phase precedes all bodies. Failures retain their exact source node -and propagate without converting evaluator failures into compiler judgments. -Entry existence and application schema are checked only after -the complete ordinary frontend succeeds. The entry lookup follows the four -exact `main` bytes in the resolved function trie, including its terminal -presence; a prefix or longer spelling is not an entry. It does not rescan the -source to rediscover that identity. -It requires all nonempty `data` declarations before one or more functions, -exactly one `main`, and unique type, constructor, and function declarations in -their separate namespaces. Exact source-byte names are retained in persistent -bytewise tries whose nodes store only present child edges, so this check has -neither hash collisions, absent-edge trees, nor repeated whole-source lookup. -Type and constructor names may still share a spelling, as required by Delta's -grammar-distinguished namespaces. Insertion builds a missing suffix from its -end toward its start with tail calls. Existing edges are traversed with a -counted ancestor spine, then rebuilt from the inserted terminal outward. -Exact terminal options distinguish a complete key from its prefixes; unchanged -children and prior roots remain persistent. Identifier length no longer adds -one Gamma return context per byte during insertion. - -During the census, separate immutable cursors retain each namespace's current -prefix focus and ancestors across insertions. Exact seek rebuilds departed -prefixes, but a nearby name can reuse its shared prefix without rebuilding the -whole root. Duplicate lookup still precedes row provision, and insertion -occurs only after admission. Successful census completion finishes all three -ordinary roots. Parameter cataloging uses the same cursor helpers for local -names, then finishes the trie retained by its counted environment. Names remain -in authored order; there is no sorting pass, -lookahead past a refusal, mutation, or alternate downstream representation. -Child-list misses reuse their immutable absence carrier. Fresh unary, -nonterminal suffix nodes store their byte tag and child in one pair, without -separate terminal or child-list wrappers. A new sibling or prefix terminal -expands only the affected node; exact lookup and immutable rebuilding preserve -both forms. The [name storage owner](implementation/checking/names/README.md) -states the representation and path-specific allocation argument. - -Declaration resolution retains the census constructor and function indexes -instead of rebuilding both from empty tries. It validates each raw row against -its declaration in authored order. A nullary constructor already carries the -final empty field-type spine, so no replacement is needed. Payload fields and -function signatures still resolve completely before their existing terminal -is replaced through a cursor. Only successful completion finishes the typed -roots; original census roots remain immutable custody evidence throughout. - -The ancestor spine costs one additional immutable pair per traversed existing -edge. It shares prior nodes rather than copying names or introducing a dense -alphabet or hash table. Gamma's cumulative pair arena still bounds physical -construction, and its exhaustion is not yet a compiler-owned resource frame. -This change adds no identifier-length limit or new language/resource code and -does not establish complete compiler resource conformance. - -The frontend validates identifier spelling at declarations, types, parameters, -local binders, constructor patterns, atoms, and application heads. -Keywords, `Int`, `Bytes`, and the five closed `bytes_*` builtin names cannot be -redeclared. Lexical admission scans decimal literals without overflow and admits -exactly `INT64_MIN..INT64_MAX`. Atom typing consumes that completed check; -bare `-` is a valid operator token but remains invalid as an expression atom. -Declaration resolution also rejects repeated parameter -names within a function before body checking begins. - -A retained-node type-checking pass begins each function from the typed parameter -environment retained by the global catalog, then extends the immutable -exact-name trie for `let` bodies and individual match arms. It rejects unknown value atoms, -self-reference from a `let` initializer, and any parameter, `let`, or pattern -binder that duplicates an active local. Immutable roots give lexical pop -without mutation: sibling expressions, branches, and disjoint match arms may -reuse the same spelling. -The pass checks every currently emitted scalar, `Bytes`, and nominal constructor field, -pattern binder, call argument, `let` initializer, operator, conditional, match -arm, and declared result. Function and local names remain -grammar-distinguished namespaces. - -Body checking consumes retained expression and pattern children rather than -reparsing their source structure. Explicit visit/resume continuations retain -pending children and environments without one Gamma call frame per source -nesting level. Ordered resolved constructor field types feed calls and pattern -binders without rescanning annotations. Each completed expression judgment -carries its type or the unchanged canonical failure; program checking succeeds -only after all bodies. No failed child produces a guessed type. The retained -source spans remain the coordinates for names, binders, -argument/type disagreement, and match coverage diagnostics. -The [boundary documentation](implementation/boundary/README.md#body-traversal-and-coordinates) -specifies the traversal order: head before expected arguments, body-let -annotation before conflict and outer initializer, and each complete match arm -before final coverage. These checks do not select a globally smallest offset. - -The complete type-check pass finishes before the first output byte. Emission -therefore consumes that established preflight instead of revalidating data -declarations, parameter annotations, function results, or `let` annotations. -It copies admitted numeric spans without repeating their spelling/range checks. -It consumes retained expression and pattern children through explicit -visit/resume continuations. Source spans supply names and literal bytes, not -reconstructed subtree boundaries. Resume handlers receive the already-popped -depth and previous stack; pending closes and remaining children have separate -concept-owned payloads. -The raw-source development gate requires every rejected program to leave output -empty, including defects after otherwise emit-capable declarations. The -canonical entry instead publishes a complete DCOUT frame for owned failures; -request admission precedes source inspection, and no emitter runs before every -frontend and schema check succeeds. - -Each match check retains its seen constructors in another immutable exact-name -trie. Same-owner validation plus duplicate rejection and exact constructor-count -agreement prove coverage without imposing declaration order. Emission compares -the cached scrutinee tag with each authored arm's actual tag and uses the final -exhaustive arm as the fallback, preserving the existing ordered receipts. - -The global function trie carries each exact declaration's owner, arity, ordered -resolved parameter types, result type, typed parameter environment, and body -coordinate. Its preceding raw census rows retain the parsed declaration node. -Resolution checks the retained owner and name span, resolves the signature from -its child nodes, and advances through the counted declarations without rescanning -the body. -Application heads resolve through the checked table, including -forward and mutual calls, without reparsing the callee signature. Type and -constructor references likewise resolve through metadata catalogs rather than -rescanning the whole source. Every user call, operator, and `if` has an exact -argument count. Undeclared Gamma effects such as -`input`, `read`, and `pair` therefore cannot leak through as Delta calls; an -ordinary Delta function may still deliberately use one of those spellings after -declaring it. Every non-`main` function definition and call receives the -injective `__d_` Gamma prefix, preventing such a declaration from being -captured by Gamma's builtin dispatch. `main` alone retains the name required by -the evaluator. - -Authored addition, subtraction, and multiplication lower to hygienic nested -Gamma lets that evaluate operands once, left-to-right, compute the wrapping -result, and trap if its sign relation or inverse-product check proves signed -overflow. Division and remainder use Gamma's already-identical zero-divisor -and `INT64_MIN / -1` traps. Compiler-generated tag arithmetic is structurally -bounded and does not acquire redundant runtime checks. - -`Bytes` lowers to a private immutable Gamma-pair rope whose outer descriptor -stores the exact logical length. The five closed builtins are statically typed -and call generated helpers named with the capture-proof `$` prefix. Singleton -construction checks `0..255`; lookup checks the complete half-open range and -then traverses in proper tail position; concatenation computes and checks the -logical-length sum before allocating its new rope descriptor. Programs that -mention only the `Bytes` type receive no unused runtime helper. - -`ConformanceBytesV1` now accepts canonical DCREQ framing, validates exact -`main : Bytes -> Bytes`, emits a marked nullary Gamma application adapter, and -owns empty/nonempty publication plus authored-trap, input-extent, and -output-extent statuses. Strict request admission publishes canonical DCOUT for -malformed framing, unknown profiles, and source-length refusal; see -[`implementation/boundary/README.md`](implementation/boundary/README.md). -Owned source failures now include forbidden source byte (code 3), invalid token -spelling and structural grammar (code 4), out-of-range integer literal (5), -duplicate type/constructor/function identity (6/7/8), local and pattern conflicts -(9/10), unknown types and names (11–14), type and arity disagreement (15/16), -duplicate and nonexhaustive match cases (17/18), missing `main` (19), and -application schema mismatch (20). -Missing `main` has no source coordinate; a schema mismatch -anchors at the entry name. Source-byte, total `type_rows`, authored -`function_rows` and `constructor_rows`, active environment, syntax storage, -payload bytes, and expression `parse_depth` refusals -have owned resource frames. An unknown retained typing-continuation kind at -positive depth returns InternalFailure code 1 with its zero-based active-stack -row, through the ordinary phase outcome and canonical publisher. Negative -or zero retained argument counts use the same internal outcome before any -source type/arity diagnosis; valid argument traversal order is unchanged. Negative -emission extents propagate to the complete-program preflight and return -InternalFailure code 2 at internal row 0 before any receipt bytes are written. -That coordinate denotes the singleton program emission record, not a corrupt -child's identity. Positive signed count overflow, late replay disagreement, and -malformed nonpair frames retain raw Gamma failures; other compiler-owned resource -accounting and internal failure publication remain open. Lowering records expanded expression -heights, including generated wrappers. Normalization uses the selected Gamma -evaluator's 255-list body budget, reusing fitting subtrees and extracting whole -over-height fragments into helpers with free established values as arguments. -Fresh capture-parameter identities preserve lexical bindings; calls remain at -the original evaluation positions. Programs whose bodies already fit retain -their exact receipts. This does not guarantee full Gamma-profile admission -throughout Delta's 1,024-level profile: generated helpers, non-tail calls, and -immutable allocations still face separate function, context, and storage limits. -Underlying evaluator failures on those paths are not DCOUT. These -frontend diagnostics do not establish final edge closure. -Calls emitted in tail position remain in Gamma tail position through -`if`, `let`, and lowered `match`; the selected evaluator executes a 100,000-node -construction and traversal in bounded call context. Static acceptance of the -scalar/nominal slice is not full-language admission. - -Run `sh tests/bootstrap/interpreted/delta/staged-compiler/run.sh` for lowering and generated execution, -`sh tests/bootstrap/interpreted/delta/normalization/run.sh` for body-height and capture behavior, -`sh tests/bootstrap/interpreted/delta/request-boundary/run.sh` for exact request outcomes, -`sh tests/bootstrap/interpreted/delta/resource-boundary/run.sh` for authored resource boundaries, -`sh tests/bootstrap/interpreted/delta/frontend-boundary/run.sh` for exact frontend outcomes, and -`sh tests/bootstrap/proofs/composed-artifact.sh` for composed identity and publication. +uses scalar tags `Left = 0`, `Right = 1`. `Option` uses `Some 9 = (pair 1 9)` +and `None = (pair 0 0)`. Recursive `List` uses `(pair tag (pair head tail))`. +Matches must cover every constructor once in any order; nullary patterns may be +bare or parenthesized. Generated locals use `$m`, `$p`, and `$v` prefixes +(`$` is valid in Gamma but not Delta, preventing capture). + +Checking runs in strict phase order: + +1. **Source bytes & lexing:** Rejects any byte outside HT, LF, CR, and + printable ASCII before lexing. Lexing validates identifiers, parentheses, + operator tokens, comments (ending at CR, LF, or EOF), character/byte + literals, and signed decimals (`INT64_MIN..INT64_MAX`, checking full + spelling before range; bare `-` is an operator, not an atom). Identifier + scanning validates tails in one pass, so later name-role checks only inspect + the leading character and exact reserved words (`Int`, `Bytes`, keywords, + and `bytes_*`; extensions like `IntX` are ordinary names). +2. **Parsing & grammar:** An explicit-stack tail loop builds a balanced tree + of exact spans before grammar checks run, so a later unmatched parenthesis + beats an earlier grammar error (missing `)` anchors at EOF; stray `)` at + its byte). An iterative grammar worklist checks declarations, binders, + types, expressions, and patterns using parser child spines and direct tail + dispatch, enforcing the 1,024-level expression `parse_depth` cap (level + 1,025 returns `Incomplete` code 8 at that node's start). +3. **Global collection:** Visits all `data` declarations (required before + functions) and functions in authored order using persistent bytewise tries + (storing only present child edges, with unary nonterminal compression; see + [name storage](implementation/checking/names/README.md)) and prefix-reusing + cursors. Duplicates reject before row limits (codes 6–8). Row limits enforce + 65,536 total types (`Int`, `Bytes`, plus 65,534 nominal declarations — code + 2), 65,536 constructors globally (code 3), and 32,768 authored functions + (code 4), stopping before allocating the over-limit row. +4. **Declaration resolution:** Starts cursors from census roots (keeping + nullary constructors untouched and replacing resolved payload/function rows), + checking declarations, constructors, and fields in authored order. Each + parameter checks conflicts before its annotation, parameters precede the + result type, and all declarations finish before any body runs. +5. **Body checking & profile schema:** Walks retained expression and pattern + nodes via explicit continuations from each function's typed parameter + environment, using immutable exact-name tries for `let` and match scopes + (enforcing 65,536 active bindings and forbidding active shadowing while + allowing reuse in disjoint scopes) and per-match coverage tries. See + [body traversal and coordinates](implementation/boundary/README.md#body-traversal-and-coordinates) + for exact error order. Only after all bodies pass does profile validation + look up exact `main` bytes in the function trie and check + `main : Bytes -> Bytes` (code 19 if missing at coordinate 0, code 20 at + `main` on signature mismatch). + +Every non-`main` function gets the injective `__d_` prefix so Delta names like +`input`, `read`, or `pair` cannot collide with Gamma builtins; `main` keeps its +evaluator name. Checked `+`, `-`, and `*` lower to hygienic nested lets that +evaluate operands left to right once and trap on signed overflow; `/` and `%` +use Gamma's zero-divisor and `INT64_MIN / -1` traps. `Bytes` lowers to an +immutable length-bearing pair rope with `$`-prefixed helpers (omitted when +unused) that check `0..255` in `bytes_single`, half-open bounds in tail-recursive +`bytes_get`, and `INT64_MAX` before allocating in `bytes_concat`. Tail calls +stay in Gamma tail position through `if`, `let`, and `match` (verified on a +100,000-node list in bounded call stack). + +`ConformanceBytesV1` implements DCREQ framing, schema validation, and the +marked nullary Gamma adapter (handling empty/nonempty output, traps, and +input/output extent statuses). DCOUT covers request errors, source/lexical/ +syntax errors (codes 3–5), duplicate globals (6–8), local/pattern conflicts +(9–10), unknown names/types (11–14), type/arity mismatches (15–16), match +errors (17–18), entry/schema errors (19–20), resource limits (source bytes, +`type_rows`, `constructor_rows`, `function_rows`, active environment, syntax +storage, `parse_depth`, payload bytes), and internal contradictions +(`InternalFailure` code 1 for invalid typing continuations at positive depth or +nonpositive argument counts; code 2 for negative emission counts at row 0). +See [`implementation/boundary/README.md`](implementation/boundary/README.md). +Positive metadata overflow, late replay mismatches, and malformed nonpair +frames remain raw evaluator failures and are never translated into DCOUT. + +Normalization enforces Gamma's 255-list body limit while preserving exact +output for programs that already fit. Generated helpers, non-tail calls, and +heap allocations remain subject to Gamma's runtime limits; passing these gates +does not by itself close the full Delta bootstrap edge. + +Test commands: +- `sh tests/bootstrap/interpreted/delta/staged-compiler/run.sh` (lowering and execution) +- `sh tests/bootstrap/interpreted/delta/normalization/run.sh` (body height and capture) +- `sh tests/bootstrap/interpreted/delta/request-boundary/run.sh` (request outcomes) +- `sh tests/bootstrap/interpreted/delta/resource-boundary/run.sh` (resource limits) +- `sh tests/bootstrap/interpreted/delta/frontend-boundary/run.sh` (frontend diagnostics) +- `sh tests/bootstrap/proofs/composed-artifact.sh` (composed identity and publication) diff --git a/bootstrap/delta/compiler/implementation/boundary/README.md b/bootstrap/delta/compiler/implementation/boundary/README.md index b44a786def58..53517baa2f89 100644 --- a/bootstrap/delta/compiler/implementation/boundary/README.md +++ b/bootstrap/delta/compiler/implementation/boundary/README.md @@ -1,35 +1,29 @@ # Delta request boundary -`request.gamma` implements the [selected admission contract](../../../LANGUAGE.md#compilation-requirements). `outcome.gamma` owns the private -failure value, phase-success carrier, and complete DCOUT V1 publication. The -outer `../../delta_compiler.gamma` entry consumes request admission before -invoking the compiler pipeline. No request-admission function writes output or -observes Delta source. Compiler phases return an explicit success carrying the -next phase's data, or the unchanged owned failure. Failure publication returns -the generic Gamma application result -`(pair tag 1)` after writing exactly one frame. - -Admission order is complete 16-byte header, first incorrect magic/version/ -reserved byte, full profile ID, declared source provision, then body extent, -the complete bound support section, and exact end. Profile 1 admits up to -4 MiB of Delta source and profile 2 admits up to 64 MiB. A declared -oversized body yields source incompleteness before reading that body. A truncated fixed header reports its first missing byte even -when an earlier available header byte is incorrect. -The sealed input continues past the request's exact end with the packed -support section — the ordered members of -[`../../support/support.gamma.sources`](../../support/support.gamma.sources). -A body shorter than its declared extent is `malformed_request`; an input that -ends inside the support section is a space-5 `incomplete_support_section` at -the observed end of input; one byte after the complete sealed input is -`malformed_request` at that first trailing offset. -The source view reads the admitted u32 length at offset 12. Its declared end -locates the trailer. Profile 1 accepts the exact original three members or -the complete four members. Profile 2 requires all four. Both forms verify -every present member before observing source. -Request admission itself still reads and provisions the declared length before -checking body extent; no source helper runs on a refused request. - -The implemented request-admission outcomes are: +`request.gamma` implements the [selected admission contract](../../../LANGUAGE.md#compilation-requirements). +`outcome.gamma` defines the compiler failure value, phase-success wrapper, and +DCOUT V1 frame writer. `../../delta_compiler.gamma` validates the request +before invoking the pipeline. Request validation writes no output and never +inspects Delta source. Each phase returns either a success carrying the next +phase's input or the unchanged failure; failure output writes one 40-byte frame +and returns the Gamma application status `(pair tag 1)`. + +Validation runs in strict order: complete 16-byte header, first wrong +magic/version/reserved byte, profile ID, declared source length limit, exact +body bytes, complete bound support section, and exact EOF. Profile 1 allows up +to 4 MiB of Delta source; profile 2 allows up to 64 MiB. An oversized declared +length returns `Incomplete` before reading body bytes. A truncated 16-byte +header reports its first missing byte even if an earlier header byte is wrong. + +Past the request body, sealed input carries the bound support section — the +ordered members of [`../../support/support.gamma.sources`](../../support/support.gamma.sources). +A short body returns `malformed_request`; ending inside the support section +returns space-5 `incomplete_support_section` at EOF; any extra byte after the +sealed input returns `malformed_request` at that offset. Profile 1 accepts the +original three members or all four; profile 2 requires all four. The pipeline +verifies every present member's size and byte sum before reading Delta source. + +Request-admission outcomes: | Tag | Code | Meaning | Request coordinate | Limit/requested | | --- | --- | --- | --- | --- | @@ -39,19 +33,15 @@ The implemented request-admission outcomes are: | 1 Reject | 1 | incomplete_support_section | 5 bound support section: observed end of input | zero/zero | | 1 Reject | 2 | member_mismatch | 5 bound support section: member's absolute sealed-input offset | zero/zero | -The three request rows use coordinate space 4; the two support rows use -coordinate space 5, also absolute sealed-input offsets. `member_mismatch` is -raised by the pipeline's bound-table member validation before any Delta-source -phase, after admission proves the section's extent is present. -The fixed 40-byte frame contains the eight bytes -`ff 44 43 4f 55 54 01 00`, tag at byte 8, space at byte 9, two zero reserved -bytes, little-endian u32 code at byte 12, and little-endian u64 coordinate, -limit, and requested fields at bytes 16, 24, and 32. Tag equals process status. -This is a projection of embedded compiler constants, not a runtime host table. +Request rows use coordinate space 4; support rows use space 5 (both are +absolute sealed-input offsets). `member_mismatch` fires during bound-table +verification before any Delta-source phase. Every 40-byte DCOUT frame contains +magic `ff 44 43 4f 55 54 01 00`, tag at byte 8 (matching exit status), space +at byte 9, two zero bytes, little-endian u32 code at byte 12, and little-endian +u64 coordinate, limit, and requested fields at bytes 16, 24, and 32, built from +embedded constants rather than a host table. -The source envelope, lexical tokens, structural syntax, complete global identity -census, declaration and body typing, and post-frontend entry schema additionally -own these Reject results (tag 1, zero limit/requested): +Frontend and entry-schema rejections (tag 1, limit/requested 0): | Code | Meaning | Coordinate space | Coordinate | | --- | --- | --- | --- | @@ -74,114 +64,68 @@ own these Reject results (tag 1, zero limit/requested): | 19 | missing_entry | 0 none | zero | | 20 | entry_schema_mismatch | 1 Delta source | present `main` declaration name | -Whole-source byte validation precedes token validation. Token validation skips -comments and accepts only parentheses, ASCII identifiers, single-byte arithmetic -operators, signed decimal integers, quoted ASCII integers and byte strings. -A complete decimal spelling is checked -before its range: an oversized digit prefix followed by a nondigit is malformed -syntax, not an out-of-range integer. The first failing token wins before any -global collection, but a forbidden source byte anywhere wins in the earlier -envelope phase. Reserved-word positions and balanced forms still belong to the -structural frontend; a bare minus is a valid operator token, not an integer atom. -An identifier-start byte selects one scan for both the end and tail spelling. -That scan leaves delimiter bytes unconsumed and anchors a malformed tail at -the original token start. Decimal tokens retain complete-spelling-before-range -validation, and the complete envelope still precedes either lexical path. -Successful token checks advance the scanner using scalar ends or rejection -codes. They do not allocate a discarded success pair for every token; the -complete lexical phase still returns the same owned outcome. -Name-role checks consume lexical identifier admission without repeating the -tail scan. They distinguish uppercase nominal names from lower/underscore -value names and reject only exact reserved spellings in that category. -`Int` and `Bytes` remain valid type annotations but not nominal declarations; -their longer identifier extensions are not reserved. No name-role check runs -before the complete lexical pass or changes its failure precedence. - -Balanced parsing precedes grammar-role checking: an unmatched closing delimiter -or missing close is reported before a role defect in an otherwise completed -earlier form. Both traversals are explicit counted worklists. They do not grow -Gamma call depth with source nesting. Grammar then checks declarations and their -children in authored order, with each required list shape checked before its -child roles. A malformed present child anchors at its start; a missing required -child anchors at the encountered closing delimiter; an unfinished form anchors -at exact source EOF. Empty and data-only programs lack the required function -declaration and reject at source EOF. These are explicit phase and coordinate -rules, not a claim that every frontend category chooses the smallest offset. - -Grammar also accounts for `parse_depth` resource. A function body starts -at expression level 1; each expression child, including an atom, is one level -deeper. Match subjects and arm bodies are children of the match expression; -declarations, parameter lists, patterns, and arm wrappers add no levels. Before -judging an expression's grammar, the worklist refuses level 1,025 with halt/tag -2 (`Incomplete`), code 8, coordinate space 1, that node's start, limit 1,024, -and requested 1,025. The check precedes grammar judgment and expansion, not -retained-node or queue-entry allocation. This is a compiler-profile refusal, -not invalid Delta. -It follows complete balanced parsing and the preceding grammar work: a later -unmatched delimiter still precedes depth refusal, and a previously encountered -grammar defect is not replaced by a depth failure at a later node. - -This expression-level accounting is distinct from parenthesis nesting in the -generic parser and from the selected Gamma evaluator's physical heap or stack. -It does not establish successful emission for every input within the selected -depth limit. - -The [syntax storage owner](../checking/syntax/README.md#syntax-storage) separately -accounts for 114,294,752 syntax-arena bytes. Parser nodes, construction -spines, parser frames, the program root, and grammar pending batches consume -their actual 40-byte Gamma pairs cumulatively. Before an allocation group -exceeds the limit, it returns tag 2, code 7, source space 1, and the exact -requested cumulative extent. Parser groups anchor at their atom or list start, -or source extent for the final program spine; grammar groups anchor at the -current construct or sequence child. Request, byte, and lexical admission -remain earlier phases. During parsing or grammar, an earlier reached failure -still wins; an unexamined later defect cannot replace a syntax-storage refusal. -This ledger excludes phase carriers and subsequent compiler-owned objects. -It is not an inference from a raw Gamma heap or stack status. - -Function/constructor applications, constructor patterns, and recognized -arithmetic/Bytes call-like heads retain their argument lists for semantic arity -checking. Their signature/payload disagreements do not become structural syntax -failures. Unknown names, duplicate local binders, and match coverage also remain -semantic judgments after the complete global census. - -Collection visits globals in authored order across their distinct namespaces, -without resolving a declaration type. The complete type/constructor catalogs -and raw function nodes then feed declaration-type resolution; -only its complete typed metadata reaches body checking. A duplicate therefore -precedes unknown declaration types, including an earlier unknown function -parameter or constructor payload type. Declaration resolution visits declarations, -constructors, and fields in authored order. For each function, it visits -parameters in order and checks each parameter's name conflict before resolving -that parameter's annotation; it resolves the result type after all parameters. -An earlier unknown annotation therefore precedes a later parameter conflict, -while a conflicting parameter precedes its own unknown annotation. The entire -declaration phase completes before any body checking, and failures propagate -unchanged through the phase outcome. Schema runs only after the ordinary -frontend accepts: an invalid body cannot turn into missing-entry or -wrong-signature rejection. Empty source is invalid Delta syntax, not an -otherwise valid program missing an entry. Profile 2 and schema code 21 remain -retired. +Whole-source byte validation runs before lexing. Lexing skips comments and +accepts only parentheses, ASCII identifiers, single-byte arithmetic operators, +signed decimal integers, quoted ASCII characters, and byte strings. Decimals +validate full spelling before range (an overflowing prefix followed by a +nondigit is syntax code 4, not code 5); a bare `-` is an operator token. +Identifier scanning checks end and tail in one pass without consuming trailing +delimiters, anchoring malformed tails at token start; successful scans return +scalar ends rather than allocating per-token wrappers. Name-role checks reuse +that lexical pass to separate uppercase nominal names from lowercase/underscore +value names and reject reserved words (`Int` and `Bytes` are valid type +annotations, not nominal declarations; longer extensions are not reserved). + +Balanced parsing finishes before grammar checking, so a stray or missing `)` +beats an earlier grammar error. Both use explicit counted worklists (no Gamma +call recursion proportional to nesting). Grammar checks declarations and +children in authored order, verifying required list shapes before child roles: +invalid children anchor at their start, missing children at the closing `)`, +and unfinished forms or functionless programs at EOF. + +Grammar also tracks `parse_depth`: function bodies start at level 1, every +expression child (including atoms and match-arm bodies) adds 1, and +declarations, parameters, patterns, and arm wrappers add 0. Before checking a +level-1,025 expression, grammar returns tag 2 (`Incomplete`), code 8, space 1, +that node's start, limit 1,024, and requested 1,025. Balanced parsing and +earlier grammar errors take precedence. This compiler-profile limit is separate +from parenthesis nesting and evaluator stack limits. + +The [syntax storage owner](../checking/syntax/README.md#syntax-storage) tracks +the cumulative syntax-arena budget (114,294,752 bytes in profile 1; 40 bytes +per Gamma pair) across parser nodes, spines, frames, the program root, and +grammar batches, excluding phase wrappers and later phases. Before an +allocation group exceeds the budget, it returns tag 2, code 7, space 1, the +owning construct's start (or EOF for the program spine), limit, and exact +requested bytes. Earlier request, byte, lexical, and reached parse/grammar +errors retain precedence. + +Calls, constructors, arithmetic/Bytes forms, and constructor patterns keep +their argument/binder lists through grammar so arity, name, binder, and match +coverage errors stay semantic checks after global collection. + +Global collection records every type, constructor, and function in authored +order without resolving types, so duplicates precede unknown declaration types. +Declaration resolution then visits declarations, constructors, and fields in +authored order: each function parameter checks name conflicts before its own +annotation, and parameters precede the result type (so an earlier unknown +annotation beats a later parameter conflict, while a conflicting parameter +beats its own annotation). All declarations finish before body checking, and +entry schema runs only after all bodies pass (empty source is invalid syntax, +not missing `main`; schema code 21 stays retired). ## Authored global-row provision -The global census accounts for `function_rows` resource. Its logical -counter starts at zero and advances once for each fresh authored function -declaration. Types and constructors do not advance it. Typed metadata rebuilt -after census, emitted runtime functions, and normalization helpers are not -additional authored function rows. +Global collection counts fresh authored declarations across three limits: -The constructor counter also starts at zero and advances once for each fresh -authored constructor, across all data declarations. Its tags remain local to -each data owner, but its resource count is global. Payload fields and the -resolved metadata rebuild consume no additional authored constructor rows. - -The type counter starts at two for `Int` and `Bytes`, then advances once per -fresh nominal declaration. The selected 65,536 total therefore includes -65,534 nominal declarations. Builtins use separate scalar identities, not -nominal trie entries; the logical profile total does not change with that -representation. Type annotation occurrences and resolved metadata copies do -not add rows. +- `function_rows`: starts at 0, increments per fresh authored function + (excluding metadata rebuilds, runtime helpers, and normalization helpers). +- `constructor_rows`: starts at 0, increments per fresh authored constructor + globally across all data declarations (tags remain local per type; payload + fields and metadata rebuilds do not count). +- `type_rows`: starts at 2 for `Int` and `Bytes`, increments per fresh nominal + declaration (so 65,536 total allows 65,534 nominal types; builtins sit + outside the nominal trie without raising the logical total). | Tag | Resource code | Coordinate space | Coordinate | Limit/requested | | --- | --- | --- | --- | --- | @@ -189,171 +133,97 @@ not add rows. | 2 Incomplete | 3 `constructor_rows` | 1 Delta source | fresh constructor-name token start | 65,536 / 65,537 | | 2 Incomplete | 4 `function_rows` | 1 Delta source | fresh function-name token start | 32,768 / 32,769 | -The 32,768th fresh row is admitted. At each function name, exact duplicate -lookup precedes provision: an already-present name rejects with tag 1/code 8, -even when all 32,768 rows are occupied. A fresh 32,769th name instead returns -the resource frame before constructing or inserting its row. Collection then -stops; it does not search later declarations for a preferred failure. Tag 2 -resource code 4 is distinct from tag 1 invalid-syntax code 4. - -The 65,536th fresh constructor is admitted. An already-present constructor -name rejects with tag 1/code 7 even at that full capacity; a fresh 65,537th name -instead produces the resource frame before constructing or inserting its row -metadata. A duplicate data name rejects with tag 1/code 6 before any constructor -in that declaration is provisioned. No counter resets at a data boundary, and -an earlier unknown payload annotation cannot preempt the census outcome. - -At total type capacity, an already-present nominal name still rejects with -tag 1/code 6. A fresh name instead returns the type-resource frame before -payload-summary traversal, type metadata, or any constructor lookup or -provision. Thus a fresh over-capacity type containing a duplicate constructor -produces the type refusal, not tag 1/code 7. Successful data collection advances -the type count once, independently of the number of constructors or fields. - -Complete byte, lexical, balanced-parser, and grammar/depth checks precede this -provision. Declaration-type resolution and every body check follow the complete -census, so an earlier unknown annotation does not preempt the row refusal. -The logical counter does not measure trie nodes, immutable pairs, or bytes, -and it does not change the existing global catalog representation. - -Census construction keeps independent immutable cursors for those three -namespaces. Seeking an exact name may finish departed prefixes of already -admitted rows; it creates no new declaration. Only an absent, admitted row is -committed at the focus. Shared prefixes remain deferred until the cursor moves -away or the complete census finishes its ordinary catalog roots. This reduces -discarded path copies while preserving authored order, exact duplicates, and -every row-provision boundary above. - -The same [`name-construction helpers`](../checking/names/README.md) serve -parameter cataloging. Parameters retain their role-specific conflict, -annotation, and active-row provision order; only their completed name trie and -active count pass to body checking. Cursor reuse changes neither global-row -nor active-environment accounting. - -Declaration resolution initializes cursors from those completed census roots. -It retains a nullary constructor's already-final empty field-type spine after -the usual owner, tag, name-end, and arity assertions. Other constructor fields -and every function signature resolve in authored order before replacing their -existing terminal payload. Child edges and untouched rows remain shared; the -raw roots still supply declaration custody checks. Only the completed phase -publishes typed roots to body checking. Reusing an identical resolved row adds -no shortcut around an annotation or a compiler-owned provision. - -Authored functions, fixed runtime helpers, adapters, and extracted normalization -helpers all occupy Gamma function rows. Each completed declaration consumes at -least eight receipt bytes — its parenthesis, `def`, `Int`, and close — so the -profile-1 16,777,212-byte payload extent keeps the emitted census at or below 2,097,151 -declarations, inside the evaluator's 2,097,152-row table without a -compiler-owned refusal. This does not change Delta's separate authored-row -provision; the remaining generated-program admission bounds are the 255-list -body bound and the 68,608-binding environment allowance that the -[normalization -audit](../normalization/README.md#static-validation-environment-bound) -discharges, and the request extent the payload preflight already enforces. -A physical evaluator failure is not a substitute for any compiler-owned -refusal. +In every namespace, exact duplicate lookup precedes the row limit: an +already-seen name rejects with code 6, 7, or 8 even at full capacity, while a +fresh over-limit name stops immediately with tag 2 before building metadata or +processing constructors (tag 2 code 4 is distinct from tag 1 syntax code 4). +Duplicate data names reject with code 6 before provisioning any constructors. +All byte, lexical, parse, and grammar/depth checks precede collection, and +declaration resolution follows it. + +Collection uses independent immutable prefix cursors via +[`name-construction helpers`](../checking/names/README.md) (shared with +parameter cataloging) to cut discarded path copies while preserving authored +order and every limit above. Declaration resolution starts cursors from those +census roots, keeping nullary constructors intact and replacing only resolved +payload/function terminals while original census roots remain intact for +cross-checks. + +In emitted Gamma, authored functions, runtime helpers, adapters, and extracted +helpers all occupy Gamma function rows. Every completed declaration takes at +least 8 bytes (`(`, `def`, `Int`, `)`), so profile 1's 16,777,212-byte payload +cap keeps emitted declarations at or below 2,097,151 — inside Gamma's +2,097,152-row table without a compiler refusal. Normalization separately proves +the 255-list body cap and 68,608-binding static environment cap +([normalization audit](../normalization/README.md#static-validation-environment-bound)). +Evaluator failures never substitute for compiler-owned refusals. ## Active local-row provision -[`../checking/environments.gamma`](../checking/environments.gamma) owns the -immutable `(active-count, exact-name-trie)` environment. Each function starts -at zero. Successful parameter insertion advances the count, and its completed -signature supplies that same environment to body checking. Lets and pattern -binders extend it once per admitted fresh binding. - -At 65,536 active bindings, the next fresh name returns tag 2, resource code 5, -coordinate space 1, its exact source start, limit 65,536, and requested 65,537. -The check precedes trie insertion and does not allocate a refused binding. -Parameter duplicate lookup and own-annotation resolution precede provision; -body lets resolve annotation, check conflict, provision, then check initializer -against the original outer environment. Patterns check outer conflicts and -within-pattern repetition before provision. Those semantic failures retain -their existing codes rather than becoming resource failures at capacity. - -Continuations save complete environments. Initializers do not see their pending -body binding, and sibling scopes and match arms restore the saved count with -the saved names. Retained roots, metadata copies, and trie nodes do not advance -the active count. Match coverage retains its own exact-name cursor and count. -This bound is compiler-owned active binding accounting, not Gamma's physical -environment capacity or Delta's separate generated local-slot resource. +[`../checking/environments.gamma`](../checking/environments.gamma) tracks the +immutable `(active-count, exact-name-trie)` local environment. Each function +starts at 0, increments per parameter, and extends once per `let` or pattern +binder. + +At 65,536 active bindings, the next fresh name returns tag 2, code 5, space 1, +its source start, limit 65,536, and requested 65,537 before insertion. Semantic +checks precede this limit so they keep their own codes: parameters check +conflicts and own annotations first; `let` checks annotation, conflict, limit, +then initializer in the outer scope; patterns check outer conflicts and +within-pattern duplicates first. Continuations restore saved counts with saved +names across sibling scopes and match arms. Match coverage keeps its own +cursor and count. This limit tracks compiler local scopes, not Gamma's +environment table or physical runtime slots. ## Body traversal and coordinates -Body typing visits retained nodes with explicit continuations and immutable -local environments. It checks functions in authored order after all declaration -signatures succeed. A failed child returns its unchanged failure; later checks -do not replace it with a parent or schema judgment. - -An application resolves its head before checking arguments. It checks each -available expected argument and its type in order, reports a missing argument -when reached, and reports extra arguments only after all expected arguments -pass. It does not check an extra argument's body before reporting arity. All -arity failures anchor at the application start; a constructor used as an atom -anchors at that atom. Argument type mismatches anchor at the argument node. - -An `if` checks its condition, true branch, and false branch in order. A -noninteger condition anchors at the condition; branch-type disagreement anchors -at the false branch. A function result disagreement anchors at its body. -A body `let` resolves its annotation before checking an active-name conflict, -then checks the initializer in the outer environment and only its body in the -extended environment. This differs from declaration parameters, whose conflict -check precedes their own annotation. Initializer disagreement anchors at the -initializer, not its binder or annotation. - -A match checks its subject, then each arm in authored order. A nonnominal -subject is a type mismatch at the subject. Each arm resolves its constructor, -checks owner, payload arity, duplicate-case status, binders, body, and agreement -with preceding arm types, in that order. A wrong owner anchors at the constructor -token; payload arity anchors at the pattern start. A binder conflicting with -the saved outer environment is code 9; a name repeated within this pattern is -code 10. Both anchor at the later binder. An arm-result disagreement anchors at -that arm's body. Only after all arms pass does final constructor coverage -produce code 18 at the match start. These traversal rules, not a global sort of -candidate offsets, select the published failure. +Body checking walks functions in authored order with explicit continuations and +immutable environments, returning the first failure unchanged: + +- **Calls:** Resolve head, check each expected argument and its type in order, + report missing arguments when reached, and report extra arguments only after + all expected arguments pass (without checking extra argument bodies). Arity + errors anchor at the call start (or constructor atom); type mismatches at the + argument node. +- **`if`:** Check condition, true branch, then false branch. Non-`Int` + condition anchors at the condition; branch mismatch at the false branch. + Function return mismatch anchors at the body. +- **`let`:** Resolve annotation, check active-name conflict (opposite of + parameters, which check conflict first), check initializer in the outer + scope (mismatch anchors at the initializer), then check body in the extended + scope. +- **`match`:** Check subject (nonnominal anchors at subject), then each arm in + authored order: resolve constructor, check owner (anchors at constructor), + payload arity (pattern start), duplicate case (constructor), binders (code 9 + for outer conflict, code 10 for in-pattern duplicate, both at later binder), + arm body, and type agreement with earlier arms (arm body). Missing cases + report code 18 at the match start only after all arms pass. ## Retained internal contradictions -The embedded internal table currently implements these bounded branches: +Implemented internal-failure branches: | Tag | Internal code | Meaning | Coordinate space | Coordinate | Limit/requested | | --- | --- | --- | --- | --- | --- | | 3 InternalFailure | 1 | retained_frontend_contradiction | 3 internal row | zero-based active typing-continuation row | zero/zero | | 3 InternalFailure | 2 | emission_metadata_contradiction | 3 internal row | row 0, singleton complete-program emission record | zero/zero | -An unknown typing-continuation kind publishes this failure only after the -frame's pair projections succeed and its depth is positive. The top active -row is `depth - 1`, counted from the bottom of the current stack. This -artifact-owned convention is not a Gamma pair address or cumulative allocation -index. Negative-depth unknown frames and malformed nonpair frames retain their -raw Gamma failures. No evaluator trap is caught or translated into DCOUT. -Argument continuations also require both retained counts to be positive. A -violated count uses code 1 and that same active-frame row before looking up the -expected type or producing an authored type/arity rejection. Negative row -coordinates still assert. This adds no diagnostic code or coordinate convention. -The ordinary phase outcome propagates the owned failure to the existing -publisher before lowering or output. The -[internal-boundary controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/internal-boundary/README.md) -exercise actual dispatch and publication using synthetic retained frames; -those frames are not claimed to arise from admitted Delta source. - -The count-only emission path propagates negative retained extents as the private -sentinel `-1`. The completed program preflight converts that sentinel to code 2 -before resource comparison or the first receipt byte. Its row-zero coordinate -names the program emission record, not the first corrupt expression, a source -offset, or a pair address. Nonnegative representable counts still select exact -payload refusal or ordinary publication. Positive signed overflow, malformed -pair projections, and late count/replay disagreement retain raw evaluator -failures. The internal controls separately exercise this preflight and the -canonical publisher with private retained Gamma plans, not admitted source. +Code 1 fires on an unknown typing-continuation kind (when pair projections +succeed and depth > 0, using row `depth - 1`) or on nonpositive retained +argument counts in argument continuations (before type/arity checks). Negative +depths and nonpair frames stay raw Gamma failures; evaluator traps are never +caught into DCOUT. Code 2 fires when count-only emission sees a negative +retained extent (propagated as `-1`) before payload comparison or writing, +reporting row 0 for the program record. Positive signed overflow, malformed +projections, and late replay mismatches stay raw evaluator failures. Both codes +are exercised with synthetic retained structures in +[internal-boundary controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/internal-boundary/README.md). ## Remaining boundary work ### Resource ownership in the selected producer -The resource identities and limits remain fixed; changing the producer does -not authorize renumbering them. The selected Delta compiler emits Gamma source, -not Alpha instructions. Review the actual owners before treating each historical -resource row as missing implementation: +Resource codes and limits are fixed across producers: | Code | Resource | Selected limit | | --- | --- | ---: | @@ -370,11 +240,8 @@ resource row as missing implementation: | 11 | fixups | 116,508 | | 12 | payload bytes | 16,777,212 (profile 1), 134,217,728 (profile 2) | -Both syntax ledgers charge 40 bytes per pair. Their limits leave 32 and 24 -bytes respectively after the last complete pair. These are selected -compiler-profile provisions, not language restrictions. -Changed provisions require coherent containment, canonical failure, and relevant -exact/adjacent controls. Zero-use resources below do not acquire invented uses. +Syntax budgets charge 40 bytes per pair (leaving 32 tail bytes in profile 1 and +24 in profile 2). These are compiler-profile limits, not Delta language rules. | DCOUT resource | Selected producer ownership | | --- | --- | @@ -386,205 +253,123 @@ exact/adjacent controls. Zero-use resources below do not acquire invented uses. | 9 live local slots, 10 labels, 11 fixups | Zero use in this producer; no physical slot allocator, label table, or fixup table exists. Preserve the identities and limits, without inventing allocations or adjacent refusals. | | 12 payload bytes | Complete Gamma receipt, including runtime, adapter, separators, and final LF. | -The zero-use argument follows the representation, not a search for missing -counter names: [Gamma programs](../representation/gamma.gamma) retain counted -definitions with names, parameter binding atoms, and expression bodies. -[Lowering locals](../lowering/bindings.gamma) retain binding identities, not -physical homes. [Normalization](../normalization/program.gamma) adds ordinary -definitions and parameters; [serialization](../emission/program.gamma) writes -source rather than resolving branches to instruction addresses. Physical Alpha -realization belongs below Delta. For the same reason, internal code 3's -label/fixup contradiction has no producer here. This is nonreachability for this -representation, not retirement of a ratified resource or diagnostic identity. - -The profile-1 payload-size argument bounds every function row, -including fixed runtime, adapters and extracted helpers. The +Because this compiler emits Gamma source rather than Alpha machine code +([Gamma programs](../representation/gamma.gamma), +[lowering bindings](../lowering/bindings.gamma), +[normalization](../normalization/program.gamma), +[serialization](../emission/program.gamma)), it has no physical slot allocator, +label table, or fixup table — so resources 9–11 and internal code 3 are +unreachable rather than missing. + +The profile-1 payload cap bounds generated function rows, and the [normalization audit](../normalization/README.md#height-and-completion-argument) -establishes the 255-list bound for transformed bodies and a conservative -68,608-binding static environment bound, below Gamma's 131,072-row provision. -Fixed runtime and adapter bodies fit independently; these source-level arguments -are not a checked Delta refinement certificate or a compiler-completion bound. -Do not reuse the authored-function resource or physical-slot resource to name -those different counts. Dynamic non-tail contexts, temporary values, immutable -pairs, and application input/output are selected evaluator/runtime resources. -A statically admitted program can still exhaust them or diverge. Correct -classification at those boundaries remains required, but a compiler cannot -promise that every terminating program fits every finite runtime provision. - -The [canonical compiler's execution-storage audit](execution_storage.md) -bounds its call contexts, lexical rows, temporary values, and — for profile 1 -(`ConformanceBytesV1`) — whole-producer cumulative pair allocation across every -admitted composition under the selected Gamma evaluator's 3,422,447,206-pair -arena (at most 3,092,641,319 pairs, 90.36%, with 329,805,887 pairs of headroom -and no reprovisioning required). It does not bound the runtime resources of -generated applications or contain profile 2 (`ConstructionBytesV1`) inside the -128 GiB Beta-written evaluator's pair arena. The -[emission audit](../emission/README.md#publication-traversal-pairs) bounds -serialization's own traversal pairs below the pair arena through the admitted -payload extent; the -[normalization audit](../normalization/README.md#traversal-and-rebuild-pairs) -charges normalizer frames, rebuilds, and per-collection capture merges to -plan-node occurrences; and the -[checking](../checking/README.md#traversal-and-rebuild-pairs) and -[lowering](../lowering/README.md#traversal-and-rebuild-pairs) audits charge -census metadata, resolution rows, typing and lowering continuations, -plan construction, and the shared name-trie/cursor rebuilds per source -occurrence, bounding the produced plan size -`G <= 40*S + 15 + 5*Decoded + 2*Literals`, where `Decoded` counts decoded -literal bytes and `Literals` the literal count. Literal trees add no bindings -or captures; the +proves the 255-list body cap and 68,608-binding static environment cap (inside +Gamma's 131,072-row limit). Runtime stacks, heap, and I/O of generated programs +remain runtime limits, not compiler outcomes. + +The [execution-storage audit](execution_storage.md) bounds the compiler's own +call contexts, lexical rows, temporaries, and profile-1 (`ConformanceBytesV1`) +cumulative pair allocation below the 3,422,447,206-pair arena (at most +3,092,641,319 pairs, 90.36%, 329,805,887 pairs headroom; profile 2 +`ConstructionBytesV1` is not universally contained in the 128 GiB Beta +evaluator). Supporting per-phase audits live in +[emission](../emission/README.md#publication-traversal-pairs), +[normalization](../normalization/README.md#traversal-and-rebuild-pairs), +[checking](../checking/README.md#traversal-and-rebuild-pairs), and +[lowering](../lowering/README.md#traversal-and-rebuild-pairs) (bounding plan +size `G <= 40*S + 15 + 5*Decoded + 2*Literals`, where `Decoded` is decoded +literal bytes and `Literals` is literal count). The [cumulative pair containment proof](execution_storage.md#cumulative-pair-containment) -combines the syntax-ledger budget (`B_syn = 2,857,368` pairs), source-byte -disjointness (`12*N_names + 70*N_lit <= 70*N`), a Heavy-Light decomposition of -the extraction-cut forest (`H <= 1,251` heavy edges with Jensen's inequality on -capture merges), and per-construct single-spend accounting to close profile 1 -universally, backed by +combines `B_syn = 2,857,368`, source-byte disjointness +(`12*N_names + 70*N_lit <= 70*N`), Heavy-Light decomposition (`H <= 1,251` +heavy edges with Jensen's inequality), and per-construct single-spend +accounting, verified by [`tests/bootstrap/interpreted/delta/containment.py`](../../../../../tests/bootstrap/interpreted/delta/containment.py). -Under the retired 40,265,318-pair profile, the +Under the retired 40,265,318-pair arena, the [measured whole-producer study](execution_storage.md#whole-producer-pair-study-measured) -drove each extent to its profile boundary, composed the two ledger-orthogonal -drivers — arithmetic nodes (240 pairs each, capped by the syntax ledger) and -identifier bytes (three pairs each, ledger-free) — and observed a fully -admitted 4,194,288-byte source end in raw halt 252 at exactly 40,265,318 -cumulative pairs, that arena's limit, with no DCOUT row; under the selected -3,422,447,206-pair arena that same corner now completes all producer phases and -refuses with canonical `DCOUT Incomplete` resource 12. +combined arithmetic nodes (240 pairs each) with identifier bytes (3 pairs each) +to hit raw halt 252 on a 4,194,288-byte source; under the current +3,422,447,206-pair arena that corner finishes cleanly with `DCOUT Incomplete` +resource 12. ### Arithmetic allocation probe -At `8148975c62` on macOS arm64, a full-source probe used `n` nullary `Int` -functions named `tree0` through `tree(n-1)`. Each body starts with literal `1` -and repeats `tree = (+ tree tree)` eight times. Its `main : Bytes -> Bytes` -returns its input when `(tree0)` equals 256, otherwise empty bytes. This tests -ordinary checked arithmetic without deep normalization: the production lowering -diagnostic reports height 21 for each tree. - -For 64 trees, the 99,395-byte source (SHA-256 -`3273c285a1e566744be97d57b0a18cce8df0b2e48039659f80c2cad467000e2c`) -compiled through canonical DCREQ profile 1 in 179.839 seconds. Its 3,372,065-byte -receipt (`257ae0f993cefc348dcf8a5d239123763e99783b4334b3b52b60b9e3fd94bb94`) -executed with status zero and exact `00 41 80 ff` output. For 512 trees, the -795,103-byte source (`0b9b7e2ebb16bfdf2958d3791e9e140aa72facfab2a2852b344f360a2509847d`) -returned only canonical DCOUT Incomplete in 159.220 seconds: syntax resource 7, -source coordinate 735,359, limit 114,294,752, requested 114,294,880. Both runs -used selected Gamma, with empty stderr; no evaluator limit was changed. - -This family does not witness a missing heap outcome. Parser and grammar -allocation is exactly `40 * (5,658*n + 140)` bytes, so 504 trees fit the syntax -ledger and 505 cannot complete grammar. Lowering allocates 50,504 pairs per -tree; syntax, tree lowering, and arithmetic typing together use 30,876,188 pairs -at 504 trees, below the retired 40,265,318-pair provision (the selected -evaluator now allocates 3,422,447,206 pairs). That subtotal excludes -catalogs, phase carriers, the fixed main and publication; it is not a complete -heap upper bound. Larger printed receipts can also encounter the existing -payload refusal. Do not keep doubling this family as if a heap failure were -established or required. Remaining allocation work needed a separately justified -source path or a whole-producer bound, not an invented general DCOUT heap code; -the -[whole-producer pair study](execution_storage.md#whole-producer-pair-study-measured) -now supplies that measured endpoint. +At `8148975c62` on macOS arm64, a stress family used `n` nullary `Int` +functions `tree0`..`tree(n-1)`, each starting from `1` and repeating +`tree = (+ tree tree)` eight times (height 21), with `main : Bytes -> Bytes` +returning its input if `(tree0)` equals 256. + +At 64 trees, the 99,395-byte source +(`3273c285a1e566744be97d57b0a18cce8df0b2e48039659f80c2cad467000e2c`) compiled +under DCREQ profile 1 in 179.839s to a 3,372,065-byte receipt +(`257ae0f993cefc348dcf8a5d239123763e99783b4334b3b52b60b9e3fd94bb94`) that ran +with status 0 and output `00 41 80 ff`. At 512 trees, the 795,103-byte source +(`0b9b7e2ebb16bfdf2958d3791e9e140aa72facfab2a2852b344f360a2509847d`) returned +DCOUT `Incomplete` in 159.220s: syntax resource 7, coordinate 735,359, limit +114,294,752, requested 114,294,880. + +Parser and grammar use `40 * (5,658*n + 140)` bytes, so 504 trees fit and 505 +refuse at resource 7 (lowering uses 50,504 pairs per tree; at 504 trees syntax, +lowering, and arithmetic typing total 30,876,188 pairs — below even the retired +40,265,318-pair arena and well inside the current 3,422,447,206-pair arena). +The [whole-producer pair study](execution_storage.md#whole-producer-pair-study-measured) +covers the full-compiler allocation picture instead. ### Wide-constructor allocation probe -A separately justified family stresses declaration width rather than -arithmetic repetition: one `data W` whose single constructor carries 65,000 -`Int` fields, seven functions whose matches each bind all 65,000 fields, one -10,000-parameter function, and an ordinary `Bytes -> Bytes` main. The -3,837,573-byte source (SHA-256 -`acbf6908b5cac63c7dc6ba2852f125a7cbd2f8c3aba6eb4a3b8094ed4cb0c7e4`) stays inside -every authored-row provision — one constructor, one nominal type, nine -functions, at most 65,000 active pattern binders and 10,000 parameters — and -inside the 4-MiB request extent and the 1,024 expression-depth profile. - -Run through canonical DCREQ profile 1 on macOS arm64 under the unchanged -selected evaluator tape and the packed closure pinned in -`tests/bootstrap/interpreted/delta/resource-boundary/compiler.tsv`, compilation ended in 650.7 -seconds with status 2, empty stderr, and only the 40-byte DCOUT frame: -`Incomplete` resource 7, Delta-source coordinate 76,595, limit 114,294,752, -requested 114,294,760. The coordinate is the atom start of the constructor's -19,147th field-type atom: the cumulative ledger still held the complete -balanced parse, and the grammar pending-batch group anchored at that field -carried the request eight bytes past the arena. This is the same canonical -code-7 row the balanced constructions exercise, reached on a different -admitted shape. - -Because the refusal fires in the retained-syntax ledger, census, declaration -resolution, typing, lowering, normalization, and emission never run on this -source. The measurement neither closes the open pair-arena allocation -question for post-frontend phases nor witnesses a missing DCOUT resource; it -is one 650.7-second stress observation, not a bootstrap-chain timing or a -whole-producer bound. +A width-focused stress source had one `data W` constructor with 65,000 `Int` +fields, seven functions matching all 65,000 fields, one 10,000-parameter +function, and a `Bytes -> Bytes` `main` (3,837,573 bytes, SHA-256 +`acbf6908b5cac63c7dc6ba2852f125a7cbd2f8c3aba6eb4a3b8094ed4cb0c7e4`), staying +inside all row, request, and 1,024-depth limits. + +Under profile 1 on macOS arm64 (using the closure pinned in +`tests/bootstrap/interpreted/delta/resource-boundary/compiler.tsv`), it failed +in 650.7s with status 2, empty stderr, and DCOUT `Incomplete` resource 7, +coordinate 76,595 (the 19,147th field-type atom, where grammar's pending batch +crossed the arena by 8 bytes), limit 114,294,752, requested 114,294,760. Later +phases never ran. ### Post-frontend allocation stress frontier -Every measured stress family refuses inside an existing resource row before -post-frontend allocation is stressed: the arithmetic probe ends in resource 7 -(the retained-syntax ledger, coordinate 735,359), the wide-constructor probe -ends in the same ledger at the constructor's 19,147th field-type atom -(coordinate 76,595), and full-width reconstruction ends in resource 12 (the -payload extent). No admitted-source family therefore reaches a post-frontend -allocation boundary; post-frontend pair consumption is bounded universally for profile 1 by the -[execution-storage audit](execution_storage.md#cumulative-pair-containment) -(`<= 3,092,641,319 < 3,422,447,206` pairs across all admitted compositions) -and validated directly by -[`tests/bootstrap/interpreted/delta/containment.py`](../../../../../tests/bootstrap/interpreted/delta/containment.py). -A stress refusal at a post-frontend allocation boundary would need a separately -justified profile-2 source family outside that profile-1 bound. +Every measured profile-1 stress family hits an existing resource limit before +stressing post-frontend allocation: arithmetic and wide-constructor probes hit +resource 7 (coordinates 735,359 and 76,595), and full-width reconstruction hits +resource 12. Profile-1 post-frontend pair allocation is bounded universally by +the [execution-storage audit](execution_storage.md#cumulative-pair-containment) +(`<= 3,092,641,319 < 3,422,447,206` pairs) and tested by +[`tests/bootstrap/interpreted/delta/containment.py`](../../../../../tests/bootstrap/interpreted/delta/containment.py); +stressing post-frontend allocation would require a profile-2 family outside +that bound. ### Producer invariants rather than arbitrary corruption coverage -Declaration metadata's owner and body-start checks in +Owner and body-start assertions in [`checking/types.gamma`](../checking/types.gamma) compare fields built directly -from the same retained declaration by -[`catalog_function_signature`](../checking/declarations/functions.gamma). -The complete immutable typed catalog then reaches body checking. These checks -are useful custody assertions; no admitted-source contradiction has been -demonstrated there. Replacing every private pair projection or assertion with -a synthetic-frame diagnostic is not a finite source-conformance criterion. -Trace a reachable producer/consumer disagreement before adding another guard, -and preserve already-owned outcomes without claiming arbitrary corruption is -canonicalized. Likewise, an unrepresentable expanded byte demand is not -automatically corrupt metadata. The +from the same node by +[`catalog_function_signature`](../checking/declarations/functions.gamma). We do +not turn every internal assertion into a synthetic DCOUT code without a +reachable producer/consumer disagreement. Similarly, the [emission occurrence argument](../emission/README.md#reachable-byte-count-bound) -bounds profile-1 source-generated intermediate and complete byte counts below -`2^62`. The larger construction source limit lies outside that numerical proof. +bounds profile-1 byte counts below `2^62`; profile 2 lies outside that proof. ### Publication and generated admission -After normalization, the shared serializer counts the complete Gamma payload -before publishing its first byte. Above the selected limit it returns tag 2, -resource 12, payload coordinate space 2, that limit as both coordinate and limit, and -the exact full requested count. Bound support members, declaration -separators, and the entry-owned final LF all participate. Count mode writes -nothing; successful publication follows the same formatting decisions. -This closes payload-size refusal, not later internal replay failure or every -generated Gamma admission limit. - -The common layout, IDs, and selected provisions are defined above. No detached -host table participates in execution. Both application profiles use the same request-failure identities. - -Canonical frontend rejection and the owned source-byte, syntax-arena, global-row, -active-environment, parse-depth, and payload-byte refusals -are not full DCOUT or Delta-edge closure. The remaining resource/internal rows -are dispositioned rather than open: the local-slot, label, and fixup rows have -no producer-side request and acquire no invented refusal, internal code 3's -label/fixup contradiction has no producer in this representation, and internal -codes 1 and 2 have canonical producers exercised by the +After normalization, count-only preflight sums the full Gamma payload +(including bound support members, separators, and final LF) without writing. +Exceeding the limit returns tag 2, resource 12, payload space 2, coordinate and +limit equal to the cap, and the exact requested byte count. + +All DCOUT tables are embedded; both profiles share request-failure codes. +Resources 9–11 and internal code 3 are unreachable by construction, while +internal codes 1 and 2 are tested by the [internal-boundary gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/internal-boundary/README.md). -Lowering constructs a complete expanded -Gamma plan before publication, and records the height of every generated -expression. A separate normalizer extracts over-height fragments under the -selected evaluator's 255-list body budget before serialization. It introduces -no new refusal code or profile limit. Profile-1 generated function storage fits by the -request bound, and transformed bodies fit the height and static-environment -bounds; a generated program's non-tail contexts and immutable allocation -remain resources of that program's execution, not a compiler outcome. The -producer's own execution storage and profile-1 cumulative pair containment are -closed by the [execution-storage audit](execution_storage.md#cumulative-pair-containment) -(`<= 3,092,641,319 < 3,422,447,206` pairs); profile 2's 64 MiB / 1 GiB extents -remain outside the 128 GiB Beta-written evaluator's pair bound. Empty-output evaluator -statuses must not be decoded as DCOUT or synthesized into frames by a runner. -The generated ConformanceBytesV1 program's statuses are separately owned by -its adapter. Successful compiler output remains the exact unwrapped Gamma -receipt; the canonical entry explicitly writes the emitter's final LF because -marked Gamma applications do not append a scalar return byte. +Lowering builds a complete height-annotated Gamma plan, normalization trims +bodies to 255 lists without adding refusal codes, and the +[execution-storage audit](execution_storage.md#cumulative-pair-containment) +closes profile-1 pair containment (`<= 3,092,641,319 < 3,422,447,206` pairs; +profile 2's 64 MiB / 1 GiB limits remain outside the 128 GiB Beta evaluator's +pair bound). Runners must never fabricate DCOUT frames from empty-stdout +evaluator exit codes. Generated ConformanceBytesV1 programs own their own +runtime statuses, and successful compilation outputs unwrapped Gamma source +ending with the entry-written final LF. diff --git a/bootstrap/delta/compiler/implementation/boundary/execution_storage.md b/bootstrap/delta/compiler/implementation/boundary/execution_storage.md index d284bf874035..ed0033eb6792 100644 --- a/bootstrap/delta/compiler/implementation/boundary/execution_storage.md +++ b/bootstrap/delta/compiler/implementation/boundary/execution_storage.md @@ -1,58 +1,53 @@ # Canonical compiler execution storage -Every profile-1 (`ConformanceBytesV1`) Delta compilation stays inside the -selected Gamma evaluator's fixed execution storage and its 3,422,447,206-pair -immutable arena, for every admitted source composition, without reprovisioning -the compiler or evaluator. This audit covers the **Gamma program implementing -Delta**, not the Gamma programs it emits; it is a source-level containment -proof against the exact compiler and evaluator bytes, not a machine-checked -refinement certificate. - -The audited subject is the canonical [`delta_compiler.gamma`](../../delta_compiler.gamma) -entry plus the ordered 65-member [`implementation.gamma.sources`](../implementation.gamma.sources) -closure — 152,411 bytes, SHA-256 -`cfa4f2a6f75352d819a83486169bd517ab48ecf90246c561e47a809309ccc25f` — together -with the 4,301-byte four-member [`support.gamma.sources`](../../support/support.gamma.sources) +Every profile-1 (`ConformanceBytesV1`) Delta compile fits inside the Gamma +evaluator's fixed execution storage and its 3,422,447,206-pair arena for any +accepted input, with no compiler or evaluator changes. This audit covers the +**Gamma program implementing Delta**, not the Gamma programs it outputs; it is +a source-level proof against the exact compiler and evaluator bytes, not a +machine-checked certificate. + +The audited artifact is [`delta_compiler.gamma`](../../delta_compiler.gamma) +plus the 65-file [`implementation.gamma.sources`](../implementation.gamma.sources) +closure (152,411 bytes, SHA-256 +`cfa4f2a6f75352d819a83486169bd517ab48ecf90246c561e47a809309ccc25f`) and the +4,301-byte four-member [`support.gamma.sources`](../../support/support.gamma.sources) trailer (`439fef90e10007baec81920e84b89f50ad815a27af80499e4240e1dcd55f9243`) -under the selected +running on the [Gamma evaluator profile](../../../../gamma/interpreter/EVALUATOR_PROFILE.md) (Beta source `a588fd718cd1f86a97f55e2f83368b80c5063f233296b091ec7c1561c768a5a6`, Alpha tape `b2d35f99f8886985306dba1c5bc5309fb2c389b1c80b1fe79b79ed69f7042a0a`). -In [`gamma_evaluator.beta`](../../../../gamma/interpreter/gamma_evaluator.beta) -the immutable pair arena spans `0x20400000..0x2000000000` at 40 bytes per node, -giving exactly `floor(136,897,888,256 / 40) = 3,422,447,206` pairs (earlier -notes cited 3,422,453,760 from before the output buffer ended at `0x20400000`). +In [`gamma_evaluator.beta`](../../../../gamma/interpreter/gamma_evaluator.beta), +the pair arena spans `0x20400000..0x2000000000` at 40 bytes per node, giving +`floor(136,897,888,256 / 40) = 3,422,447,206` pairs (older notes cited +3,422,453,760 before the output buffer ended at `0x20400000`). For profile 1 (`ConformanceBytesV1`: 4 MiB source, 114,294,752-byte syntax -ledger, 16,777,212-byte payload limit), the proof below bounds total cumulative -pair allocation at **3,092,641,319 pairs** (90.36% of the 3,422,447,206-pair -arena, leaving 329,805,887 pairs of headroom). Profile 2 (`ConstructionBytesV1`: -64 MiB source, 1 GiB syntax ledger, 128 MiB payload limit) keeps fixed call, -lexical, and temporary storage inside the evaluator's limits, but its cumulative -pair allocation is **not** universally contained in the 128 GiB Beta-written -evaluator — two constructive admitted witnesses exceed 3,422,447,206 pairs -below. - -Runtime emission is support-member custody, not fixed text encoded in the -emitter. [`support.gamma`](../emission/support.gamma) validates the sealed -input's trailing support section (either the original 2,998-byte three-member -prefix in profile 1 or all four members totaling 4,301 bytes in profiles 1 and -2) with one tail-recursive wrapping byte-sum pass per member before any -Delta-source phase, then copies each member verbatim during publication through -a tail-recursive `write`/`read` walk while count mode advances by the same bound -extent. The three support loops carry at most three locals each and no non-tail -user calls; they add no fixed-source storage beyond the maxima below. - -Sequential binding groups replace 94 nested-let chains containing 309 bindings. -Expanding each group to nested lets recovers the preceding compiler's expression -trees exactly: initializer order, binding scope, tail positions, and user-call -edges are unchanged. The selected Gamma evaluator validates and executes the -grouped syntax directly with no preprocessor. +budget, 16,777,212-byte output cap), total cumulative pair allocation is at +most **3,092,641,319 pairs** (90.36% of the arena, leaving 329,805,887 pairs of +headroom). Profile 2 (`ConstructionBytesV1`: 64 MiB source, 1 GiB syntax +budget, 128 MiB output cap) stays inside the evaluator's call, lexical, and +temporary limits, but its pair allocation is **not** universally contained in +the 128 GiB Beta-written evaluator — two accepted profile-2 inputs below exceed +3,422,447,206 pairs. + +[`support.gamma`](../emission/support.gamma) checks the trailing support +section (either the 2,998-byte three-member prefix in profile 1 or all four +members totaling 4,301 bytes in profiles 1 and 2) with one tail-recursive +byte-sum loop per member before any Delta-source phase, then copies each member +verbatim via a tail-recursive `write`/`read` loop while count mode adds the +same length. Those three loops use at most three locals each and no non-tail +calls, so they do not raise the maxima below. + +Sequential binding groups replace 94 nested-let chains (309 bindings). +Expanding them yields the exact same expression trees, evaluation order, +scopes, tail positions, and call edges; the Gamma evaluator accepts grouped +syntax directly. ## Fixed source and call inventory -The 152,411-byte compiler contains 391 Gamma definitions. Inspecting every body -gives these maxima, including bodies not reached from the canonical `main`: +The 152,411-byte compiler contains 391 Gamma definitions. Maxima across all +bodies (including bodies unreachable from `main`): | Fixed-source quantity | Maximum | Owning body | | --- | ---: | --- | @@ -62,26 +57,23 @@ gives these maxima, including bodies not reached from the canonical `main`: | Formal parameters plus all body bindings | 16 | `lowering_match_arms` | | Pending user calls within one body's expression syntax | 5 | `lowering_projection_definition`, `typing_match_body` | -These are compiler-source counts, independent of Delta input depth, width, -identifier length, or generated-helper count. The fixed 17-list maximum fits -Gamma's 255-list validation provision. Its validator visits bodies separately, -resets the lexical environment at each definition, and never executes callees. - -For execution, a call's arguments are non-tail. An `if` condition and a `let` -initializer are non-tail; their branches/body inherit the containing tail -position. Other primitive operands are non-tail. A user call temporarily owns -one context while evaluating its arguments, even when the eventual call is tail. -The evaluator releases that tail context before reusing the current activation. - -Weight each caller-to-callee edge by the pending enclosing user calls plus one -for a non-tail callee activation. Include each call's temporary argument context -as a local peak. The current source graph has 71 recursive components. Only -three self-recursive functions carry positive-weight cycle edges (five call -sites total): two in `capture_sort`, one in `emit_decimal`, and the two balanced -children of `lowering_literal_tree`. The capture merge passes -(`capture_merge_all`, `capture_merge_pass`) and the support-member loops -(`support_sum_region`, `support_check_members`, `emit_support_bytes`) are -zero-weight tail edges. +These counts are fixed by compiler source and do not grow with Delta input. The +17-list maximum fits Gamma's 255-list validation cap, since the validator +checks each body separately with a fresh lexical environment. + +At runtime, call arguments, `if` conditions, `let` initializers, and primitive +operands are non-tail; `if` branches and `let` bodies inherit tail position. A +user call holds one temporary context while evaluating arguments even for a +tail call, then releases it before reusing the activation. + +Weight each call edge by enclosing pending user calls plus 1 for a non-tail +callee, including each call's temporary argument context as a local peak. Of +the 71 recursive components in the call graph, only three self-recursive +functions have positive-weight cycle edges (five call sites total): two in +`capture_sort`, one in `emit_decimal`, and two in `lowering_literal_tree`. +`capture_merge_all`, `capture_merge_pass`, `support_sum_region`, +`support_check_members`, and `emit_support_bytes` are all zero-weight tail +loops. | Non-tail recursive owner | Decreasing quantity | Conservative additional contexts | | --- | --- | ---: | @@ -89,18 +81,14 @@ zero-weight tail edges. | [`emit_decimal`](../emission/text.gamma) | Recursive calls divide a value at least ten by ten. A positive signed 64-bit value has at most 19 decimal digits. | 18 | | [`lowering_literal_tree`](../lowering/literals.gamma) | Each child has at most `ceil(p / 2)` decoded bytes: `p <= 4,194,304` in profile 1 (22 halvings) or `p <= 67,108,864` in profile 2 (26 halvings). | 22 (profile 1) / 26 (profile 2) | -The sort allowance does not depend on a capture-allocation estimate. Values -below two do not recurse. Trie descent across name bytes, sibling-row scans, -and ancestor rebuilding are tail-driven; name length does not multiply the -sibling-rebuild allowance. The remaining parser, grammar, typing, lowering, -normalization, capture, emission, list, and cursor cycles have only zero-weight -tail edges. +Values below 2 do not recurse in `capture_sort`. Trie descent, sibling scans, +ancestor rebuilds, and all parser, grammar, typing, lowering, normalization, +capture, emission, list, and cursor cycles are tail-recursive. -Removing those three positive-weight self-edges, collapsing zero-weight -recursive components, and propagating maximum weighted demands from local peaks -through the resulting acyclic graph yields an exact fixed call-context overhead -of 18 from `main`. Adding all three recursion allowances — even though their -deepest paths never coexist — gives: +Removing those three self-edges, collapsing tail cycles, and propagating +maximum weighted demand from `main` gives an exact fixed overhead of 18 +contexts. Adding all three recursion bounds (even though they never peak +together) gives: ```text Profile 1 (p <= 4 MiB): @@ -115,94 +103,78 @@ Profile 2 (p <= 64 MiB): ## Lexical and temporary storage In [`gamma_evaluator.beta`](../../../../gamma/interpreter/gamma_evaluator.beta), -`enter_function` installs parameters above the caller's environment; -`bind_let_initializer` adds a binding only after its initializer returns. -Ordinary scope/function completion restores the saved environment count, and -`enter_tail_restart` resets it to the current activation's base. An activation -therefore retains at most its parameters plus all its body's local bindings, -including every binding in a grouped `let`: +`enter_function` installs parameters above the caller's environment, +`bind_let_initializer` binds after the initializer returns, normal returns +restore the saved count, and `enter_tail_restart` resets to the activation +base. Each live activation therefore holds at most its parameters plus body +bindings (including grouped `let` bindings): ```text Profile 1: live lexical rows <= 122 * 16 = 1,952 < 131,072 Profile 2: live lexical rows <= 126 * 16 = 2,016 < 131,072 ``` -Every expression-list level retains at most eleven temporary-value entries: -an ordinary call holds at most its eleven arguments; primitive/`let` handling -uses at most three entries for saved operands, operator, environment count, or -binder coordinates. Validation's `let` handling also uses three. Nested child -evaluation is charged to the next expression level, not hidden in that count. -`prepare_call` records the argument base; parameter installation resets the -value pointer to it, ordinary calls restore it on return, and tail replacement -does not retain previous argument blocks. Allowing one extra result entry per -activation for `enter_function`'s return handling gives: +Each expression-list level holds at most 11 temporary entries (a call's 11 +arguments; primitive and `let` forms use at most 3, and validation `let` uses +3). `prepare_call` saves the argument base, parameter install resets to it, +calls restore it on return, and tail calls reuse it. Adding 1 return slot per +activation for `enter_function`: ```text Profile 1: temporary entries <= 122 * (17 * 11 + 1) = 22,936 < 524,288 Profile 2: temporary entries <= 126 * (17 * 11 + 1) = 23,688 < 524,288 ``` -The validator executes no Gamma bodies, so its one-body requirements are smaller -than these execution bounds. Gamma's existing hidden-Alpha-stack containment -argument continues to apply; no native stack or memory partition is changed. +Validation does not execute bodies, so its needs are smaller. Gamma's existing +Alpha-stack containment argument still holds unchanged. ## Cumulative pair containment -Explicit worklists and immutable plans allocate **pairs cumulatively**; -returning from a call or dropping a worklist does not reclaim them. Earlier -per-phase audits bounded checking, lowering, shared names, normalization, and -emission separately, leaving a coarse quadratic capture envelope -(`60,672*N^2 + ...`) that crossed the pair arena at `N = 238`. That envelope -dropped three structural invariants the compiler already enforces: - -1. **Syntax-ledger budget.** Every balanced list costs 8 parser pairs, every - atom costs 5 parser pairs, and every pending grammar batch costs 4 pairs, - so `P_syn = 8*L_list + 5*A_atom + 1 + 4*G_batch <= B_syn`. In profile 1, - `B_syn = floor(114,294,752 / 40) = 2,857,368` pairs, giving - `S = L_list + A_atom <= floor((B_syn - 1) / 5) = 571,473` syntax nodes. -2. **254-level cut spacing and the 65,536 active-local bound.** Normalization - extracts a helper only at `budget = 1` and restarts it at `budget = 255`. - Every consecutive ancestor-descendant extraction pair along a path is - separated by 254 Gamma expression-list levels, and every helper's parameter - list is a deduplicated subset of the simultaneously active authored locals - (`W <= 65,536`, plus generated bindings handled separately). -3. **Disjoint source bytes and single-spend syntax pairs.** A source byte in - `N <= 4,194,304` cannot belong to both a bound/declared identifier and a - byte-string literal (`N_names + Decoded + 2*Literals <= N`), and charging - each phase per construct against one shared `B_syn` prevents spending the - same syntax pairs six times across incompatible constructs. +The Gamma evaluator allocates **pairs cumulatively** and never reclaims +dropped worklists or plans. Earlier per-phase audits left a coarse quadratic +capture bound (`60,672*N^2 + ...`) that crossed the arena at `N = 238` because +it ignored three invariants the compiler already enforces: + +1. **Syntax-ledger budget.** Lists cost 8 parser pairs, atoms cost 5, and + grammar batches cost 4, so `P_syn = 8*L_list + 5*A_atom + 1 + 4*G_batch <= B_syn`. + In profile 1, `B_syn = floor(114,294,752 / 40) = 2,857,368` pairs, capping + syntax nodes at `S = L_list + A_atom <= floor((B_syn - 1) / 5) = 571,473`. +2. **254-level cut spacing and 65,536 active locals.** Normalization extracts + only at `budget = 1` and restarts at `budget = 255`, spacing consecutive + cuts along a path by 254 Gamma levels. Each helper's parameters are a + deduplicated subset of simultaneously active authored locals (`W <= 65,536`, + plus generated bindings handled separately). +3. **Disjoint source bytes and single-spend syntax pairs.** A byte in + `N <= 4,194,304` cannot be both an identifier and a byte-string literal + (`N_names + Decoded + 2*Literals <= N`), and charging phases per construct + against one shared `B_syn` prevents double-counting incompatible constructs. ### 1. Byte-disjoint name-trie and byte-literal pairs In [`checking/names.gamma`](../checking/names.gamma) and [`checking/names/cursor_navigation.gamma`](../checking/names/cursor_navigation.gamma), -every byte of a processed name is either shared with the cursor prefix (0 -pairs), descended on an existing edge (1 ancestor-spine pair), or built as a -fresh unary suffix (1 pair), so `descended + fresh <= W_b`. Each pushed -ancestor cell is rebuilt at most once across seeks and `finish` (at most 5 -pairs on a branch node, 1 on a unary node), so the per-byte total over a -builder is `descended + fresh + 5*descended <= 6*W_b`. Each bound, declared, or -coverage-committed token participates in at most two name events (`W_n <= 2*N_names`), -tightening the per-byte name term from `34*N` to `12*N_names`. - -In [`lowering/literals.gamma`](../lowering/literals.gamma), a byte literal with -`p >= 1` decoded bytes allocates `2*p + 1` pairs for decoding/reversal, `17*p` -pairs for `$dbs` leaves, and `14*(p - 1)` pairs for `$dbc` internal nodes -(`33*p - 13` pairs; empty literals allocate 12 pairs against their 2 quote -bytes). Its balanced binary tree has height at most `ceil(log2(p)) + 2 <= 23` -in profile 1 and contains zero local references or binders. During -normalization, leaf `$dbs` calls (height 1) never descend. Each of the `p - 1` -internal `$dbc` calls is either descended (24 pairs) and later visited by an -enclosing capture (3 pairs = 27), or extracted at `budget = 1` (22 helper + 3 -capture start + 3 empty finish + 4 parent call-batch + 2 parent merge-list -overhead = 34 pairs, immediately reused at `budget = 255 >= 23` with 0 descent) -and visited once by its own capture (3 pairs = 37). Total lowering plus -normalization and capture for all byte literals is therefore at most -`33*Decoded + 37*Decoded + 12*Literals <= 70*N_lit`. Combining the disjoint -name and literal source spans gives: +each processed name byte is either shared (0 pairs), descended (1 ancestor +pair), or a fresh unary suffix (1 pair), so `descended + fresh <= W_b`. Each +pushed ancestor cell rebuilds at most once across seeks and `finish` (at most 5 +pairs for a branch, 1 for unary), giving `descended + fresh + 5*descended <= 6*W_b`. Each bound, +declared, or coverage-committed token enters at most two name events +(`W_n <= 2*N_names`), cutting the name term from `34*N` to `12*N_names`. + +In [`lowering/literals.gamma`](../lowering/literals.gamma), a literal with +`p >= 1` decoded bytes allocates `2*p + 1` decode/reverse pairs, `17*p` pairs +for `$dbs` leaves, and `14*(p - 1)` pairs for `$dbc` internal nodes (`33*p - 13` +pairs; empty literals take 12 pairs for 2 quote bytes). Its balanced tree has +height at most `ceil(log2(p)) + 2 <= 23` in profile 1 and zero local bindings. +Leaf `$dbs` calls (height 1) never descend. Each of the `p - 1` internal `$dbc` +nodes is either descended (24 pairs) plus visited by an enclosing capture (3 +pairs = 27), or extracted at `budget = 1` (22 helper + 3 start + 3 finish + 4 +call batch + 2 merge overhead = 34 pairs, then reused at `budget = 255 >= 23` +with 0 descent) and visited once by its own capture (3 pairs = 37). Total +literal pairs are at most `33*Decoded + 37*Decoded + 12*Literals <= 70*N_lit`. +Combining disjoint name and literal bytes gives: ```text byte-disjoint pairs <= 12*N_names + 70*N_lit <= 70*N <= 293,601,280 @@ -210,54 +182,49 @@ byte-disjoint pairs <= 12*N_names + 70*N_lit <= 70*N <= 293,601,280 ### 2. Heavy-Light capture-incidence bound -Let `T^+` be the rooted forest of extraction cuts `c` whose subtree contains at -least one authored local-variable reference (`s(c) = R_auth(subtree(c)) >= 1`). -Any cut with `s(c) = 0` captures zero authored variables; any root of `T^+` is a -top-level extraction directly inside an authored function (which never runs -`capture_expression`) because if it had a parent helper `h`, then -`s(h) >= s(c) >= 1` would place `h` in `T^+`. Thus roots of `T^+` contribute -zero to `sum_h E_h`. - -In `T^+`, mark each internal node `h`'s edge to a child `c = heavy(h)` of -maximum `s(c)` as **heavy**, and all other child edges as **light**: - -- **Non-root light cuts.** For every light edge `(p, c)`, `p` has a heavy child - at least as large as `c`, so `s(p) >= 2*s(c)`. Along any authored reference - `r`'s path up `T^+`, `m` non-root light ancestors force `2^m <= s(p_m) <= R_auth <= 571,473`, - so each authored reference crosses at most `floor(log2(571,473)) = 19` - non-root light cuts. -- **Heavy cuts.** All heavy edges `(h, c)` have pairwise-disjoint 254-level - Gamma path segments `seg(h, c)` in the lowered plan (no node of `T^+` enters - an arithmetic guard, pattern initializer, or byte literal because none of - those contain authored variable references). Inspecting every lowering form - in [`lowering/`](../lowering/README.md) shows each `+1` of Gamma depth along - `seg(h, c)` owns at least 9 exclusive syntax pairs: `if` (23), `let` (31), - ordinary call (11), checked arithmetic `+2` depth to right operand (17 + 3 - sibling root = 20, losing at most 1 if the sibling is the top `p'` of another - heavy edge), multi-arm match `+3` depth (at least 27), match arm selector +Let `T^+` be the rooted forest of extraction cuts `c` whose subtree holds at +least one authored local reference (`s(c) = R_auth(subtree(c)) >= 1`). Cuts +with `s(c) = 0` capture no authored locals. Any root of `T^+` sits directly in +an authored function (which never runs `capture_expression`), because any +parent helper `h` would have `s(h) >= s(c) >= 1` and belong to `T^+`. Thus +roots add zero to `sum_h E_h`. + +In `T^+`, mark each internal node `h`'s edge to a child `c = heavy(h)` with +maximum `s(c)` as **heavy**, and all other edges as **light**: + +- **Non-root light cuts.** On any light edge `(p, c)`, `p`'s heavy child has + size at least `s(c)`, so `s(p) >= 2*s(c)`. Along any reference `r`'s path up + `T^+`, `m` non-root light ancestors force `2^m <= s(p_m) <= R_auth <= 571,473`, + so `r` crosses at most `floor(log2(571,473)) = 19` non-root light cuts. +- **Heavy cuts.** Heavy edges `(h, c)` have pairwise-disjoint 254-level Gamma + path segments `seg(h, c)` (no node of `T^+` enters an arithmetic guard, + pattern initializer, or byte literal since none hold authored references). + Checking every form in [`lowering/`](../lowering/README.md) shows each `+1` + Gamma depth along `seg(h, c)` owns at least 9 exclusive syntax pairs: `if` + (23), `let` (31), ordinary call (11), arithmetic `+2` depth to right operand + (17 + 3 sibling root = 20, losing at most 1 if that sibling is another heavy + edge's top `p'`), multi-arm match `+3` depth (at least 27), arm selector (17), pattern binder (`9*k + 15` for `+k` depth), and constructor sibling arg (2 parent spines + 4 grammar batch + 3 sibling root = 9, losing at most 3 if - the sibling is another heavy edge's top `p'`). Because at most `H` siblings - globally can equal another heavy edge's top `p'`, `H` heavy edges consume at + that sibling is another heavy edge's top `p'`). Because at most `H` siblings + globally can equal another heavy edge's top `p'`, `H` heavy edges need at least `(254 * 9 - 3) * H = 2,283 * H` disjoint syntax pairs: ```text H <= floor(B_syn / 2,283) = floor(2,857,368 / 2,283) = 1,251 heavy edges ``` -Each heavy edge `(h, c)` has a distinct parent helper `h` and carries +Each heavy edge `(h, c)` has a distinct parent `h` and carries `|P_c^{auth}| <= 65,536` authored bindings, giving at most -`C_heavy = 1,251 * 65,536 = 81,985,536` heavy authored capture incidences. -Total extraction helpers satisfy `J_nonlit <= floor(B_syn / 8) = 357,171` -(checked across all constructs, including at most 129 extractions per 2,300 -syntax pairs in a 256-field inline-projection match arm) plus -`J_lit <= floor(N / 2) = 2,097,152` (each extracted literal `$dbc` node has -height `>= 2` and owns at least 2 decoded leaves), so `J_total <= 2,454,323` -and `L_k = ceil(log2(J_total + 1)) = 22`. Because the `H` parents of heavy -edges are pairwise distinct, `sum_{h} k_h <= J_total`. By Jensen's inequality -on concave `log2(x + 1)` (whose sum `H * (log2(J / H + 1) + 1)` is strictly -increasing in `H`), heavy capture merges plus `capture_difference` allocate at -most: +`C_heavy = 1,251 * 65,536 = 81,985,536` heavy capture incidences. Total helpers +satisfy `J_nonlit <= floor(B_syn / 8) = 357,171` (including at most 129 cuts +per 2,300 syntax pairs in a 256-field inline-projection arm) plus +`J_lit <= floor(N / 2) = 2,097,152` (each extracted `$dbc` has height `>= 2` and +owns at least 2 decoded leaves), so `J_total <= 2,454,323` and +`L_k = ceil(log2(J_total + 1)) = 22`. Since heavy-edge parents are distinct, +`sum_{h} k_h <= J_total`. Applying Jensen's inequality to concave `log2(x + 1)` +(where `H * (log2(J / H + 1) + 1)` increases with `H`), heavy capture merges +and `capture_difference` allocate at most: ```text heavy capture merge <= 65,536 * H * (2 * (log2(J_total / H + 1) + 1) + 2) @@ -267,14 +234,13 @@ heavy capture merge <= 65,536 * H * (2 * (log2(J_total / H + 1) + 1) + 2) ### 3. Single-spend per-construct bound for all remaining phases -Every syntax pair in `P_syn <= B_syn` belongs to one of 16 disjoint syntax -constructs (charging argument and constructor-field edges to the argument -expression node: `+8` checking, `+22` lowering, `+24` normalization, `+3` -capture traversal). With `R_total <= floor(11*B_syn / 17) = 1,848,885` -(`sort` coefficient `2.5 * 21 + 3 = 55.5`), `O_total <= 571,473` (`sort` -coefficient `2.5 * 20 + 3 = 53.0`), `L_light = 19`, and non-heavy merge factor -`2*L_k + 2 = 46`, checking all 16 constructs against their minimum syntax-pair -cost gives: +Every syntax pair in `P_syn <= B_syn` belongs to one of 16 disjoint construct +classes (charging argument and constructor-field edges to the argument node: +`+8` checking, `+22` lowering, `+24` normalization, `+3` capture). Using +`R_total <= floor(11*B_syn / 17) = 1,848,885` (`sort` factor +`2.5 * 21 + 3 = 55.5`), `O_total <= 571,473` (`sort` factor +`2.5 * 20 + 3 = 53.0`), `L_light = 19`, and non-heavy merge factor +`2*L_k + 2 = 46`: | Construct class | Min syntax pairs | Worst-case non-heavy pairs | Pairs / syntax pair | | --- | ---: | ---: | ---: | @@ -286,19 +252,17 @@ cost gives: | `match` arm | 13.00 | 420.5 | 32.35 | | Other atoms, calls, constructors, `if`, `let`, declarations | 5.00–43.00 | 21.0–305.0 | 4.20–18.60 | -Note that inline pattern projections (`k <= 256` fields) share immutable `second` -tails in lowering, so normalization can expand up to `sum_{i} (b_i - 1) <= 12,288` -descended unary calls per 256-field arm (exhaustively maximized over all -`k in 2..256` and starting budgets `b0 in 1..255` at `k = 256, b0 = 131`, -giving 119.05 pairs per syntax pair — well below the 214.30 maximum). Because -`capture_call_arguments` tail-enters unary calls without allocating frames, -inline projection chains add zero capture-traversal frames. +Inline pattern projections (`k <= 256` fields) share immutable `second` tails +in lowering, so normalization can expand up to `sum_{i} (b_i - 1) <= 12,288` +unary calls per 256-field arm (maximized over `k in 2..256` and `b0 in 1..255` +at `k = 256, b0 = 131`, giving 119.05 pairs per syntax pair — well below +214.30). `capture_call_arguments` tail-enters unary calls without frames, so +inline projections add zero capture frames. ### 4. Profile-1 grand total -Summing every component for any admitted profile-1 Delta source (including -rejected or incomplete compiles, which stop early and allocate at most one -5-pair `compiler_failure` outcome): +Summing all terms for any profile-1 Delta compile (rejected/incomplete compiles +stop early and add at most one 5-pair `compiler_failure` value): | Component | Exact Profile-1 bound (pairs) | Share of arena | | --- | ---: | ---: | @@ -311,47 +275,44 @@ rejected or incomplete compiles, which stop early and allocate at most one | **Selected Gamma evaluator pair arena** | **3,422,447,206** | **100.00%** | | **Proven headroom** | **329,805,887** | **9.64%** | -No admitted profile-1 Delta source — regardless of how identifiers, byte -literals, wide patterns, deep expressions, arithmetic trees, or nested capture -chains are composed — can exhaust the selected Gamma evaluator's -3,422,447,206-pair arena. No reprovisioning of the canonical compiler or Gamma -evaluator is required for profile 1. +No accepted profile-1 input can exhaust the 3,422,447,206-pair arena, regardless +of how identifiers, byte literals, wide patterns, deep expressions, arithmetic, +or nested captures combine. ### Profile 2 (`ConstructionBytesV1`) containment limit -Profile 2 widens source bytes to 64 MiB (`N <= 67,108,864`), syntax storage to -1 GiB (`B_syn = 26,843,545` pairs), and payload bytes to 128 MiB -(`P_payload <= 134,217,728`) to admit compiler-sized generated Delta programs -such as the 29.6 MiB / 650.8 MiB-parse frozen Omega compiler output +Profile 2 raises source to 64 MiB (`N <= 67,108,864`), syntax storage to 1 GiB +(`B_syn = 26,843,545` pairs), and payload to 128 MiB (`P_payload <= 134,217,728`) +for compiler-sized generated Delta programs like the 29.6 MiB / 650.8 MiB-parse +frozen Omega compiler output ([`WIDE_OUTPUT.md`](../../../../../tests/bootstrap/independent/epsilon/WIDE_OUTPUT.md)). -Those wider extents are **not** unconditionally contained inside the 128 GiB -Beta-written Gamma evaluator's 3,422,447,206-pair arena, witnessed by two -admitted profile-2 constructions: +Two accepted profile-2 constructions exceed the 128 GiB Beta-written evaluator's +3,422,447,206-pair arena: -1. **64 MiB byte literal at budget 22:** lowering allocates - `33 * 67,108,864 ~= 2.21e9` pairs and normalization/capture allocates up to - `37 * 67,108,864 ~= 2.48e9` pairs (`~4.7e9 > 3.42e9` pairs). +1. **64 MiB byte literal at budget 22:** lowering takes + `33 * 67,108,864 ~= 2.21e9` pairs and normalization/capture takes up to + `37 * 67,108,864 ~= 2.48e9` pairs (`~4.7e9 > 3.42e9`). 2. **65,535 active locals across 7,845 constructor-spine cuts with 31 sibling - `(+ 1 f65534)` extractions per cut:** fits inside `B_syn = 26,843,545` - (`~1.77e6` pairs for binders/refs + `7,845 * 3,123 ~= 24.5e6` pairs for cuts - and siblings), while six `capture_merge_all` copy passes per cut allocate + `(+ 1 f65534)` extractions per cut:** fits `B_syn = 26,843,545` + (`~1.77e6` pairs for binders/refs + `7,845 * 3,123 ~= 24.5e6` for cuts and + siblings), while six `capture_merge_all` passes per cut take `7,845 * 6 * 2 * 65,535 ~= 6.17e9 > 3.42e9` pairs. Just as [`LANGUAGE.md`](../../../LANGUAGE.md#compilation-requirements) scopes -the `2^62` emission-extent proof and the 2,097,152-row Gamma function-census -proof to profile 1, universal cumulative pair containment on the Beta-written -Gamma evaluator applies to profile 1 (`ConformanceBytesV1`). Shrinking profile -2's syntax arena would refuse the actual Omega-compiler Delta customer; -raw status 252 remains an evaluator failure and is never translated into DCOUT. +the `2^62` byte-count proof and the 2,097,152-row function-table proof to +profile 1, universal pair containment on the Beta-written evaluator applies to +profile 1 (`ConformanceBytesV1`). Shrinking profile 2's syntax arena would +reject the Omega compiler's Delta output; raw status 252 stays an evaluator +failure and is never mapped to DCOUT. ### Live containment and resource-boundary validation (Windows x64) [`tests/bootstrap/interpreted/delta/containment.py`](../../../../../tests/bootstrap/interpreted/delta/containment.py) -validates the unchanged 152,411-byte canonical Delta compiler (`cfa4f2a6…`) and -4,301-byte support section (`439fef90…`) on native Windows 11 Pro x64 using the -audited `alpha_x64_windows.exe` seed (`4bf1f4eb…`), requiring exact 40-byte -`DCOUT` frames and explicitly failing on any empty-stdout raw evaluator status -(248–254). Measured at base revision `7686600ab67e2`: +tests the unchanged 152,411-byte compiler (`cfa4f2a6…`) and 4,301-byte support +section (`439fef90…`) on native Windows 11 Pro x64 using the audited +`alpha_x64_windows.exe` seed (`4bf1f4eb…`), requiring exact 40-byte `DCOUT` +frames and failing on any empty-stdout evaluator status (248–254). Measured at +base revision `7686600ab67e2`: | Suite / host | Verified observations | Result | | --- | --- | --- | @@ -361,26 +322,22 @@ audited `alpha_x64_windows.exe` seed (`4bf1f4eb…`), requiring exact 40-byte | `--host alpha --suite boundaries` | Full exact/adjacent/duplicate boundaries for `source_bytes` (P1/P2), support custody (space 5), `parse_depth` (1,024/1,025), `type_rows` (65,536/65,537/dup), `constructor_rows` (65,536/65,537/dup), `function_rows` (32,768/32,769/dup), `active_env` (65,536/65,537 param/let/pattern), and `syntax_storage` (exact/adjacent parser EOF & grammar transfer) | 25/25 passed | | `--host alpha --suite compositions` | (1) 100 KiB byte literal + 600-field wide match + multi-batch capture merges -> 1,745,032-byte receipt executed 100,000-byte output on selected Gamma evaluator (89.97s); (2) 2,000 active locals × 16 cuts × 15 sibling merges -> 1,066,571-byte receipt executed on selected Gamma evaluator (26.47s); (3) 6,000 locals × 125 cuts × 15 sibling merges -> canonical `DCOUT Incomplete 12`, requested 17,205,164 bytes (120.42s); (4) exact 4,194,290-byte retired-arena corner (3,420,227-byte identifier + 129,000-node balanced `+` tree) -> canonical `DCOUT Incomplete 12`, requested 33,867,321 bytes (327.08s) | 4/4 passed | -The fourth composition reproduces the exact identifier-plus-arithmetic corner -that halted with raw status 252 under the retired 40,265,318-pair arena below; -under the selected arena it completes every producer phase and refuses cleanly -with canonical `DCOUT Incomplete` resource 12. +Composition 4 reproduces the identifier-plus-arithmetic corner that hit raw +status 252 under the retired 40,265,318-pair arena; under the current arena it +finishes every phase and returns `DCOUT Incomplete` resource 12. ### Whole-producer pair study (measured, historical retired profile) -The measurement below is a historical record from the retired 40,265,318-pair -profile on macOS arm64 against the former 147,840-byte compiler closure, -2,998-byte support section, and 8,575-byte evaluator tape; it is kept to show -the observed linear rates and the exact corner composition that motivated -enlarging the pair arena. +This historical measurement from the retired 40,265,318-pair profile on macOS +arm64 (147,840-byte compiler, 2,998-byte support section, 8,575-byte evaluator +tape) records the linear rates and the corner case that drove enlarging the +pair arena. -In that retired-profile -[`gamma_evaluator.beta`](../../../../gamma/interpreter/gamma_evaluator.beta), -register `ra0` was the immutable-pair heap cursor: initialized to `0x10000000`, -preflighted against `ra1 = 0x70000000`, advanced by 40 bytes per pair, and -never decreased. An lldb breakpoint on `h_halt` reading -`((unsigned long*)$x19)[0xa0]` and `[0xa1]` reported the exact cumulative -allocation without modifying the tape, request, compiler, or evaluator. +In that retired [`gamma_evaluator.beta`](../../../../gamma/interpreter/gamma_evaluator.beta), +`ra0` was the monotonic pair cursor from `0x10000000` to `ra1 = 0x70000000` +(40 bytes per pair). An lldb breakpoint on `h_halt` reading +`((unsigned long*)$x19)[0xa0]` and `[0xa1]` captured exact pair counts without +modifying any binary or input. | Profile extent | Worst-shape source | Bytes | Outcome | Cumulative pairs | Retired arena share | | --- | --- | ---: | --- | ---: | ---: | @@ -396,18 +353,15 @@ allocation without modifying the tape, request, compiler, or evaluator. | capture aggregate | 65,535-field reconstruction | 1,704,033 | payload refusal | 36,033,367 | 89.5% | | real customer | Epsilon closure + canonical entry | 628,304 | publish | 1,864,697 | 4.6% | -The extracted rates were linear in their drivers: 240 pairs per checked `+` -node before publication (22 syntax-ledger pairs each) and 3 pairs per name byte -across census, resolution, and typing. Composing a 3,420,227-byte identifier -with a 129,000-node balanced `+` tree (4,194,288 bytes, SHA-256 -`0b588a5376cefaecd8b7556d61464f857f0326df248607f8b6bc0285d605d89a`) drove that -retired arena to its 40,265,318-pair cap and halted with raw status 252. Under -the current 3,422,447,206-pair arena, the universal proof above bounds every -profile-1 composition below 90.4% of the arena, and the live composition gate -above confirms that same corner now terminates in canonical `DCOUT Incomplete` -resource 12. - -Generated Delta applications are different programs. Their recursion and live -storage can still exhaust the selected evaluator or diverge. The compiler's -bounds above must not be applied to those executions, the Epsilon evaluator, or -an arbitrary Gamma source. +Measured rates were linear: 240 pairs per checked `+` node (22 syntax pairs +each) and 3 pairs per name byte across census, resolution, and typing. +Combining a 3,420,227-byte identifier with a 129,000-node balanced `+` tree +(4,194,288 bytes, SHA-256 +`0b588a5376cefaecd8b7556d61464f857f0326df248607f8b6bc0285d605d89a`) hit the +40,265,318-pair cap with raw status 252. Under the current 3,422,447,206-pair +arena, the proof above caps every profile-1 compile below 90.4%, and the live +gate confirms this corner now returns `DCOUT Incomplete` resource 12. + +Generated Delta programs are separate executables whose recursion and heap can +still exhaust the evaluator or diverge. These compiler bounds do not apply to +generated applications, the Epsilon evaluator, or arbitrary Gamma code. diff --git a/bootstrap/delta/compiler/implementation/checking/README.md b/bootstrap/delta/compiler/implementation/checking/README.md index c01d5659fe3f..7268740c66b5 100644 --- a/bootstrap/delta/compiler/implementation/checking/README.md +++ b/bootstrap/delta/compiler/implementation/checking/README.md @@ -1,52 +1,48 @@ # Checked static semantics -The `checking/` tree validates admitted source before lowering. Phase order is -fixed by [pipeline.gamma](../pipeline.gamma): source envelope -([source.gamma](source.gamma)), token admission ([lexical.gamma](lexical.gamma)), -balanced parsing and grammatical roles ([syntax/](syntax/README.md)), the -global identity census ([collection.gamma](collection.gamma)), declaration -resolution ([declarations.gamma](declarations.gamma) and -[declarations/](declarations)), body checking ([types.gamma](types.gamma) and -[types/](types)), and selected-profile validation -([profile.gamma](profile.gamma)). Scoped environments -([environments.gamma](environments.gamma)) and the exact-name tries and cursors -([names.gamma](names.gamma), [names/](names/README.md)) serve the census, -parameter catalogs, match coverage, and lexical scopes. +The `checking/` directory validates accepted Delta source before lowering. +[pipeline.gamma](../pipeline.gamma) fixes the phase order: source byte check +([source.gamma](source.gamma)), tokenization ([lexical.gamma](lexical.gamma)), +balanced parsing and grammar roles ([syntax/](syntax/README.md)), global name +collection ([collection.gamma](collection.gamma)), declaration resolution +([declarations.gamma](declarations.gamma) and [declarations/](declarations)), +body type checking ([types.gamma](types.gamma) and [types/](types)), and +application-profile validation ([profile.gamma](profile.gamma)). Scoped +environments ([environments.gamma](environments.gamma)) and exact-name tries and +cursors ([names.gamma](names.gamma), [names/](names/README.md)) back global +collection, parameter lists, match coverage, and local scopes. ## Traversal and rebuild pairs This audit charges every pair these phases allocate to an earlier-phase -occurrence, in the same style as the +occurrence, matching the style of the [normalization audit](../normalization/README.md#traversal-and-rebuild-pairs). -It does not re-charge the parser or grammar worklist: their retained nodes, -spines, and frames are preflighted under the -[syntax provision](syntax/README.md#syntax-storage), which bounds them below -2,857,368 pairs at 40 bytes each — already inside the 3,422,447,206-pair arena. -Envelope and token admission, accessors, and token predicates allocate no -pairs; each phase's `compiler_complete` or `compiler_failure` outcome is -charged once in the tables below. - -Quantities, each an earlier-phase measure bounded by the admitted source -extent `N <= 4,194,304` bytes: - -- `S` — retained syntax nodes, `S <= min(N, 714,342)` because each node costs - at least four syntax-ledger pairs. -- `D`, `C`, `F`, `P`, `Fd` — data declarations, authored constructors, - functions, parameters, and constructor-field annotations. +Parser and grammar pairs are excluded because the +[syntax storage limit](syntax/README.md#syntax-storage) already caps their +nodes, spines, and frames below 2,857,368 pairs (40 bytes each), well inside the +3,422,447,206-pair arena. Source-byte checking, lexing, accessors, and token +predicates allocate no pairs; each phase's `compiler_complete` or +`compiler_failure` result is charged once below. + +All counts are bounded by the accepted source length `N <= 4,194,304` bytes: + +- `S` — retained syntax nodes, `S <= min(N, 714,342)` since each node costs at + least 4 syntax-ledger pairs. +- `D`, `C`, `F`, `P`, `Fd` — data declarations, constructors, functions, + parameters, and constructor-field annotations. - `I`, `L`, `M`, `U`, `B`, `K`, `A` — `if`, `let`, `match`, arm, - pattern-binder, and application nodes plus checked argument edges. + pattern-binder, and call nodes plus checked argument edges. - `V`, `E_n`, `K_r`, `W_n`, `Q` — name-token occurrences, name events, - resolved-row replacements, total name-event bytes, and trie lookups, as - defined in the [name-trie audit](names/README.md#pair-accounting). + resolved-row replacements, total name-event bytes, and trie lookups, defined + in the [name-trie audit](names/README.md#pair-accounting). -The disjoint occurrence classes sum to at most `S`; edge counts are at most -`S` as well. +Disjoint node classes sum to at most `S`; edge counts are also at most `S`. ### Global census -[collection.gamma](collection.gamma) holds one cursor per global namespace. -Raw rows carry only source coordinates and retained nodes; typed metadata is -built during resolution. +[collection.gamma](collection.gamma) keeps one cursor per global namespace. Raw +rows store source coordinates and retained nodes; resolution builds typed +metadata later. | Site | Pairs | Charged per | | --- | ---: | --- | @@ -61,9 +57,9 @@ built during resolution. ### Declaration resolution -[declarations/](declarations) replaces census rows with typed metadata in -authored order. `identity_cursor_replace` preserves child edges and every -earlier immutable root; lookups are charged through `Q`. +[declarations/](declarations) replaces raw collection rows with typed metadata +in authored order. `identity_cursor_replace` keeps child edges and earlier +immutable roots intact; lookups are charged through `Q`. | Site | Pairs | Charged per | | --- | ---: | --- | @@ -85,12 +81,11 @@ earlier immutable root; lookups are charged through `Q`. ### Body checking -[types/](types) runs the explicit visit/resume machine. A continuation is -`(pair kind (pair payload previous))`; payload owners are listed per row. -Local and constructor name lookups (`local_environment_lookup`, -`find_function_metadata`, `require_constructor_metadata`, -`lookup_type_option`'s nominal find) are charged through `Q`, and every -`local_environment_bind` insertion through the name-event terms. +[types/](types) runs an explicit visit/resume loop. Each continuation frame is +`(pair kind (pair payload previous))`. Name lookups (`local_environment_lookup`, +`find_function_metadata`, `require_constructor_metadata`, and nominal lookup in +`lookup_type_option`) are charged through `Q`; every `local_environment_bind` +insert is charged through the name-event terms. | Site | Pairs | Charged per | | --- | ---: | --- | @@ -109,7 +104,7 @@ Local and constructor name lookups (`local_environment_lookup`, ### Rollup -Summing the site rows gives +Summing the tables gives: ```text checking site pairs @@ -118,18 +113,18 @@ checking site pairs <= 39*S + 36 ``` -(plus the at-most-once `compiler_failure` value, five pairs). +(plus at most one 5-pair `compiler_failure` value). -Name-trie and cursor work is shared with lowering, so it is bounded once in +Lowering shares the name-trie and cursor code, so its total is bounded once in the [name-trie audit](names/README.md#whole-compiler-rollup): ```text name pairs <= 10*S + 46*V + 12*N + 22 ``` -These standalone envelopes are intentionally loose; the +These standalone bounds are intentionally loose. The [cumulative pair containment proof](../boundary/execution_storage.md#cumulative-pair-containment) -combines this single-spend per-construct accounting with source-byte -disjointness and a Heavy-Light decomposition of the extraction-cut forest to -bound every admitted profile-1 composition at most 3,092,641,319 pairs, inside -the selected Gamma evaluator's 3,422,447,206-pair arena. +combines this per-construct accounting with source-byte disjointness and a +Heavy-Light decomposition of the extraction-cut forest to prove every accepted +profile-1 program allocates at most 3,092,641,319 pairs, inside the Gamma +evaluator's 3,422,447,206-pair arena. diff --git a/bootstrap/delta/compiler/implementation/checking/names/README.md b/bootstrap/delta/compiler/implementation/checking/names/README.md index fe15dfbcab43..4c4bdbb817bc 100644 --- a/bootstrap/delta/compiler/implementation/checking/names/README.md +++ b/bootstrap/delta/compiler/implementation/checking/names/README.md @@ -1,87 +1,81 @@ # Exact-name construction cursors -[`../names.gamma`](../names.gamma) owns ordinary exact-name lookup and insertion. -The helpers here share that sparse-trie representation while retaining a -construction focus across consecutive admitted names. They serve these builders: - -- [`../collection.gamma`](../collection.gamma) owns authored-order collection - and global row provision. It keeps separate type, constructor, and function - cursors, then finishes their roots into the ordinary global catalog. -- [`../declarations/functions.gamma`](../declarations/functions.gamma) owns - left-to-right parameter cataloging. It carries a local-name cursor while - resolving parameter annotations and provisioning active rows, then finishes - the ordinary trie in the counted environment used by body checking. +[`../names.gamma`](../names.gamma) implements ordinary exact-name lookup and +insertion. The helpers in this directory share that sparse-trie layout while +keeping a focus cursor across consecutive names for four builders: + +- [`../collection.gamma`](../collection.gamma) collects global declarations in + authored order and checks row limits. It keeps separate type, constructor, and + function cursors, then finishes them into the ordinary global catalog. +- [`../declarations/functions.gamma`](../declarations/functions.gamma) catalogs + function parameters left to right. It updates a local-name cursor while + resolving parameter annotations and checking active-row limits, then finishes + the trie for body checking. - [`../declarations.gamma`](../declarations.gamma) starts from the completed - census tries. It retains already-complete nullary constructor rows, replaces - payload constructor and function rows after their declarations resolve, then - finishes both typed catalogs. Original census roots remain available for - declaration custody checks throughout that pass. -- [`../types/matches.gamma`](../types/matches.gamma) retains a private cursor - for each match's exact coverage set. It commits only after binder checks, - and nested matches retain independent immutable state. Final exhaustiveness - uses the distinct count; no later phase consumes this working trie. - -These builders do not change the name representation delivered to later consumers. - -[`cursor.gamma`](cursor.gamma) defines the private cursor and its endpoint and -finish operations. [`cursor_navigation.gamma`](cursor_navigation.gamma) seeks -an exact source name by retaining its shared prefix, climbing departed parents, -and descending existing byte edges. [`cursor_commit.gamma`](cursor_commit.gamma) -inserts an absent terminal or child only after the caller admits that row, or -replaces an existing terminal after resolution without changing child edges. - -A cursor contains its focus depth, a source coordinate identifying that prefix, -the ordinary sparse trie at the focus, and a counted immutable ancestor spine. -The ancestors retain complete tagged tries, including terminal options and -every live or superseded sibling row. A seek rebuilds -only departed prefixes; a commit leaves common ancestors deferred. Earlier -cursors and finished roots remain immutable and independently usable. - -Seeking does not insert rows. Callers retain their own admission order: global -duplicates precede provision, type provision precedes constructor collection, -and parameter conflicts precede their own annotations and provision. No later -declaration or parameter is examined after failure. Counters, per-type tags, -and exact metadata payloads remain owned by the callers. -Names are compared byte for byte, including prefix endpoints; pair references -never act as truth values or identities. Navigation and long fresh suffixes -use tail loops, not call depth proportional to identifier length. - -This is shared construction working state, not a new name representation or a -source sorting pass. General lookup and insertion in `../names.gamma` remain intact. -The change reduces repeated rebuilding when consecutive authored names share -prefixes; arbitrary name order retains the same semantics without promising -the same allocation savings. It does not raise a Gamma bound or convert a raw -evaluator resource failure into a compiler-owned outcome. + census tries. It keeps complete nullary constructor rows, replaces payload + constructor and function rows once their types resolve, then finishes both + typed catalogs. The original census roots stay available for cross-checks + throughout the pass. +- [`../types/matches.gamma`](../types/matches.gamma) keeps a private cursor for + each match's seen constructors. It commits only after binder checks, and + nested matches keep independent immutable state. Exhaustiveness checks the + distinct count; no later phase reads this trie. + +Downstream phases receive ordinary tries, not cursors. + +[`cursor.gamma`](cursor.gamma) defines the cursor record, endpoint helpers, and +finish logic. [`cursor_navigation.gamma`](cursor_navigation.gamma) moves to an +exact source name by keeping its shared prefix, climbing departed parents, and +descending existing byte edges. [`cursor_commit.gamma`](cursor_commit.gamma) +inserts a missing terminal or child once the caller accepts the row, or replaces +an existing terminal after resolution without altering child edges. + +A cursor holds its focus depth, a source offset naming that prefix, the sparse +trie at the focus, and a counted immutable ancestor spine. Ancestors store +complete tagged tries, including terminal options and all live or superseded +sibling rows. Seeking rebuilds only departed prefixes; committing defers shared +ancestors. Earlier cursors and finished roots remain immutable and usable. + +Seeking never inserts rows. Callers keep their own check order: global +duplicates precede row-limit checks, type limits precede constructor collection, +and parameter conflicts precede annotations and row limits. No later declaration +or parameter runs after an error. Callers keep control of counters, per-type +tags, and metadata payloads. Names compare byte for byte, including prefix +endpoints; pair addresses never act as booleans or IDs. Navigation and long +fresh suffixes use tail loops, so call depth does not grow with identifier +length. + +This cursor is shared working state, not a new trie representation or a sorting +pass. General lookup and insertion in `../names.gamma` stay unchanged. It cuts +rebuilding when consecutive names share prefixes, while arbitrary name order +keeps identical behavior without promising the same savings. It does not raise +any Gamma limit or turn evaluator resource failures into compiler diagnostics. The [customer cost investigation](../../../../../../wiki/drafts/reference/bootstrap_cost_review.md#delta-simplification) -compares prefix reuse with rebuilding from the root on the exact Epsilon source. -It supports retaining the current implementation without expansion, not claiming -that the customer requires it to fit or that boundary conformance is complete. - -Trie tag `0` is absence. Tag `1` carries a terminal option and sparse child -rows. A nonterminal with one edge instead uses `(pair (byte + 2) child)`: one -pair per byte, with no separate absent terminal or singleton child list. Source -identifier bytes cannot collide with the absence or branch tags. Lookup and -ancestor reconstruction read this form directly. Adding a prefix terminal or -sibling expands just that node into the ordinary tag-1 form, preserving its -existing edge. Terminal nodes keep tag 1 even when they -have no children. No node deletion or recompression pass is needed. - -For a fresh length-`L` name subsequently visited and rebuilt during declaration -resolution, the unary path, ancestor spine, and rebuilt unary path cost one -pair per byte each, rather than the former five, one, and five. Branch and -terminal overhead is separate. This is a path-specific allocation argument, -not a bound on the complete compiler or all admitted source shapes. +compares prefix reuse with root rebuilding on the Epsilon source. It supports +keeping this implementation as-is, without claiming the customer needs it to fit +or that boundary compliance is complete. + +Trie tag `0` means empty. Tag `1` holds a terminal option and sparse child rows. +A nonterminal with one child instead uses `(pair (byte + 2) child)`: one pair +per byte, with no empty terminal or singleton child list. Source identifier +bytes cannot collide with tag `0` or `1`. Lookup and ancestor rebuilds read this +form directly. Adding a prefix terminal or sibling expands only that node into +tag `1`, keeping its existing edge. Terminal nodes keep tag `1` even with no +children. No deletion or recompression pass is needed. + +For a fresh length-`L` name later visited and rebuilt during declaration +resolution, the unary path, ancestor spine, and rebuilt unary path each cost 1 +pair per byte instead of 5, 1, and 5. Branch and terminal costs are separate. +This is a per-path argument, not a bound on the full compiler or all inputs. ## Pair accounting -This section charges every pair the shared tries and cursors allocate, in the -same style as the +This section charges every pair allocated by `../names.gamma` and the cursor +helpers, matching the style of the [normalization audit](../../normalization/README.md#traversal-and-rebuild-pairs). -It covers `../names.gamma` and the cursor helpers here; the builders that call -them are listed above. Parser and grammar pairs are not covered — they are -preflighted under the -[syntax provision](../syntax/README.md#syntax-storage), which bounds them below +Parser and grammar pairs are excluded because the +[syntax storage limit](../syntax/README.md#syntax-storage) caps them below 2,857,368 pairs at 40 bytes each. | Site | Pairs | Charged per | @@ -100,48 +94,44 @@ preflighted under the | `identity_cursor_present` | <=1 | presence check | | `empty_identity_cursor` | 4 | builder | -The 5-pair level bound is a rebuilt tag-1 node: two pairs retain its tag and -terminal option, and the replacement prepends one fresh -`(pair stored-byte (pair child rest))` row at three pairs. Replacement no -longer copies each younger sibling over the retained row: exact-byte lookup -stops at the first matching row, so a superseded row stays an unreachable -predecessor inside this version and inside every older immutable snapshot. -The presence precondition still scans the existing rows without allocating, -and absence remains a contradiction. Byte-keyed rows admit at most 63 -children because source identifier bytes are 26 uppercase, 26 lowercase, ten -digits, and underscore ([`../source.gamma`](../source.gamma)); retained -predecessors may lengthen a children list past that count, but a lookup scan -still stops at the newest matching row, so repeated replacement costs its -prepending events, not a rescanned copy per level. +The 5-pair limit for rebuilding a tag-1 branch node comes from 2 pairs for its +tag and terminal option plus 3 pairs to prepend one +`(pair stored-byte (pair child rest))` row. Replacement does not copy younger +siblings over the old row: exact-byte lookup stops at the first matching row, +leaving any superseded row unreachable in the new version while keeping older +immutable snapshots intact. Presence checks scan existing rows without +allocating, and missing rows remain errors. Source identifiers have 63 valid +bytes (26 uppercase, 26 lowercase, 10 digits, underscore; see +[`../source.gamma`](../source.gamma)). Retained predecessors can make a child +list longer than 63, but lookup still stops at the newest match, so repeated +replacements pay only for prepends rather than copying siblings at every level. ### Builder aggregates -Let a builder's name events be its seeks, commits, replaces, or ordinary -inserts, and let `W_b` total the bytes of the names it processes. A cursor -seek departs `depth_before - common` levels and descends -`depth_after - common` existing edges, so over the builder's life -`departed + final depth = descended` exactly. Departed rebuild levels, -descended spine cells, and fresh suffix bytes are therefore each bounded by -`W_b`. An ordinary `name_trie_insert` rebuilds exactly its descended levels, -so the same `W_b` bound applies to a plain insertion sequence. One finish per -builder rebuilds its remaining depth, itself bounded by its last name's bytes. -Each cursor event allocates at most `19 + descended + fresh + 5*departed` -pairs — the cursor record, absent-edge marker, presence check, and commit node -work — and each ordinary insert at most +Call each seek, commit, replace, or plain insert a name event, and let `W_b` be +the total bytes of names a builder processes. A cursor seek leaves +`depth_before - common` levels and descends `depth_after - common` existing +edges, so over a builder's run `departed + final depth = descended` exactly. +Departed rebuilds, descended spine cells, and fresh suffix bytes are each at +most `W_b`. Plain `name_trie_insert` rebuilds exactly its descended levels, so +the same `W_b` bound holds. One finish per builder rebuilds its remaining depth, +at most the last name's length. Each cursor event allocates at most +`19 + descended + fresh + 5*departed` pairs (cursor record, miss marker, +presence check, and commit work), and each plain insert allocates at most `15 + descended + fresh + 5*rebuilt`. ### Whole-compiler rollup -Across every builder, define `V <= S` name-token occurrences that are bound, -declared, or coverage-committed — declaration, parameter, `let`, and pattern -binder names plus match-arm constructor names — where `S` is the retained-node -count and `N <= 4,194,304` the admitted source bytes. Each token participates in at most two events — -census commit then resolution seek for declaration names, catalog commit then -lowering bind for parameters, checking then lowering binds for `let` and -pattern binders, and one coverage seek/commit for arm names — so -`E_n <= 2*V` events total `W_n <= 2*N` name bytes. Resolved-row replacements -`K_r <= V`, builders number `F + M + 5` for `F` functions and `M` matches, -and `Q <= 3*S + 1` lookup evaluations serve every caller. +Across all builders, let `V <= S` be the name-token occurrences that are bound, +declared, or recorded for match coverage (declaration, parameter, `let`, and +pattern binder names, plus match-arm constructors), where `S` is the retained +syntax-node count and `N <= 4,194,304` is the source byte length. Each token +enters at most two events — census commit and resolution seek for declarations, +catalog commit and lowering bind for parameters, checking and lowering binds for +`let` and pattern binders, and one coverage seek/commit for match arms — so +`E_n <= 2*V` events total `W_n <= 2*N` bytes. Resolved-row replacements satisfy +`K_r <= V`, builders total `F + M + 5` for `F` functions and `M` matches, and +lookups total `Q <= 3*S + 1`. ```text name-trie and cursor pairs @@ -150,12 +140,12 @@ name-trie and cursor pairs <= 10*S + 46*V + 12*N + 22 ``` -Because `descended + fresh <= W_b` (each byte of a processed name is shared, -descended, or a fresh suffix) and every pushed ancestor cell is rebuilt at most -once (`departed + final depth = descended`), the per-byte cost is -`descended + fresh + 5*descended <= 6*W_b <= 12*N` (tightening the earlier -`17*W_n = 34*N` envelope). Combined with the syntax-ledger and Heavy-Light -capture bounds in the +Because `descended + fresh <= W_b` (each byte is shared, descended, or a fresh +suffix) and every pushed ancestor cell is rebuilt at most once +(`departed + final depth = descended`), per-byte cost is +`descended + fresh + 5*descended <= 6*W_b <= 12*N`, tightening the earlier +`17*W_n = 34*N` bound. Combined with the syntax-ledger and Heavy-Light capture +bounds in the [cumulative pair containment proof](../../boundary/execution_storage.md#cumulative-pair-containment), -every admitted profile-1 composition stays below the selected Gamma evaluator's +every accepted profile-1 input fits inside the Gamma evaluator's 3,422,447,206-pair arena. diff --git a/bootstrap/delta/compiler/implementation/checking/syntax/README.md b/bootstrap/delta/compiler/implementation/checking/syntax/README.md index ca88834f0ad7..7517848d9e0b 100644 --- a/bootstrap/delta/compiler/implementation/checking/syntax/README.md +++ b/bootstrap/delta/compiler/implementation/checking/syntax/README.md @@ -1,52 +1,50 @@ # Retained Delta syntax -[parse.gamma](parse.gamma) retains balanced source forms. -[grammar.gamma](grammar.gamma) checks their grammatical roles and returns the -same program on success. Neither phase resolves declarations or types, checks -duplicates, or emits output. +[parse.gamma](parse.gamma) parses balanced source forms. +[grammar.gamma](grammar.gamma) checks grammatical roles and returns the same +program on success. Neither phase resolves names or types, checks duplicates, +or writes output. ## Representation -[nodes.gamma](nodes.gamma) owns the shared representation and its accessors: +[nodes.gamma](nodes.gamma) defines the node layout and accessors: ```text node = (pair start (pair after (pair child-count children))) program = (pair top-count top-nodes) ``` -`start` and `after` are exact source coordinates, with `after` exclusive. An -atom has child-count `-1` and children `0`. A list has a nonnegative count and -an ordered raw pair spine of child nodes. The program uses the same counted -spine for top-level forms. Counts govern projections; no branch or integer -comparison inspects pair-reference provenance. Names remain exact source -spans, not copied strings or hashes. +`start` and `after` are exact source byte offsets (`after` exclusive). An atom +has child-count `-1` and children `0`. A list has a nonnegative count and an +ordered pair spine of child nodes. The program uses the same counted spine for +top-level forms. Counts control every projection; no branch or integer check +inspects pair addresses. Names stay as exact source spans, never copied strings +or hashes. -The parser runs one tail-driven loop with an explicit immutable stack. Each -frame retains the opening coordinate, parent count, reversed parent children, -and previous stack. Closing a list restores its children to source order once -and appends the completed node to its parent. Nested Delta forms therefore do -not consume one Gamma return context per source nesting level during parsing. +The parser runs a single tail-recursive loop with an explicit immutable stack. +Each frame holds the opening offset, parent count, reversed parent children, +and previous stack. Closing a list reverses its children into source order once +and attaches the completed node to its parent, so deep nesting never grows +Gamma call depth. ## Syntax storage -The parser and grammar share 114,294,752 syntax bytes in the ordinary profile. -The ConstructionBytesV1 compiler allows 1,073,741,824 bytes. The full frozen -Omega compiler's emitted Delta program requires 650,801,080 bytes for the -parser alone. [Provision](storage.gamma) · [Measured program](../../../../../../tests/bootstrap/independent/epsilon/WIDE_OUTPUT.md) -This producer charges its actual syntax objects at the selected Gamma -evaluator's 40 bytes per immutable pair. It does not charge a historical -32-byte typed-syntax row for a differently represented S-expression node. - -Usage is cumulative: discarded reversed spines and popped parser or grammar -frames are not reclaimed by this evaluator. A scalar travels with parser and -grammar work; restoring a parent scope does not restore an older byte count. -The parser returns a private `(program, used)` carrier, and grammar consumes -it before returning the unchanged ordinary program to census. Phase outcomes -and this custody carrier are not syntax objects. Declaration catalogs, -environments, lowering plans, normalization, and emitted text are separately -owned and do not enter this syntax ledger. - -Each allocation group is preflighted before any member is allocated: +Parsing and grammar share a 114,294,752-byte syntax budget in profile 1, and +1,073,741,824 bytes in ConstructionBytesV1 (the frozen Omega compiler's emitted +Delta program needs 650,801,080 bytes for parsing alone). +[Provision](storage.gamma) · [Measured program](../../../../../../tests/bootstrap/independent/epsilon/WIDE_OUTPUT.md) +This budget charges actual syntax objects at the Gamma evaluator's 40 bytes per +immutable pair, not a historical 32-byte typed-syntax row. + +Usage is cumulative because the evaluator does not reclaim popped frames or +discarded reversed spines. A running byte count travels through parsing and +grammar; leaving a scope never reduces it. The parser returns a private +`(program, used)` wrapper that grammar consumes before returning the plain +program to global collection. Phase results and that wrapper are not charged as +syntax objects. Catalogs, environments, lowering plans, normalization, and +output are tracked separately. + +Each allocation group is checked before any pair in it is allocated: | Parser operation | Pairs | Refusal coordinate | | --- | ---: | --- | @@ -55,74 +53,69 @@ Each allocation group is preflighted before any member is allocated: | Close a list | Child count ordered-spine cells + 3 node pairs + 1 parent-spine cell | Saved opening delimiter | | Finish the program | Top-level count ordered-spine cells + 1 program root | Source extent | -Grammar charges four pairs for each pending batch. A function's initial three -batches are one 12-pair group, and a let's two batches are one eight-pair -group. Other sites allocate one batch. Shape checks precede those allocation -sites; later role judgments do not run after a refusal. A group anchors at the -construct whose work it schedules; a sibling-sequence batch anchors at the -current child. Successful declaration outcomes carry the updated scalar usage -into the next declaration, so completed work does not reset the ledger. - -An over-limit request produces halt/tag 2, resource code 7, source coordinate -space 1, the coordinate above, the active profile’s byte limit, and the exact cumulative -bytes requested for the complete group. At 40-byte granularity, literal -equality with the limit is impossible; the ordinary limit leaves 32 bytes and the construction limit leaves 24 bytes. -Requested bytes are not rounded down or replaced with `limit + 1`. -All counts derive from admitted source extents or fixed object shapes, and -their products and sums fit Gamma's signed scalar range. - -The shared `syntax_reverse_nodes` helper also serves lowering and normalization. -Only its parser calls are charged here; the helper itself does not impose -syntax accounting on unrelated phases. This ledger is not a query of Gamma's -shared heap and cannot relabel physical evaluator exhaustion as DCOUT. +Grammar charges 4 pairs per pending batch. A function's initial three batches +form one 12-pair group, and a `let`'s two batches form one 8-pair group; other +sites allocate one batch. Shape checks run before these allocations, and no +later role checks run after a refusal. Each group anchors at the construct it +schedules, or at the current child for a sibling sequence. Each completed +declaration passes its updated byte total to the next declaration. + +Exceeding the budget returns halt/tag 2, resource code 7, source coordinate +space 1, the anchor coordinate above, the active profile's byte limit, and the +exact cumulative bytes requested for the whole group. At 40 bytes per pair, +exact equality with the limit is impossible (leaving 32 tail bytes in profile 1 +and 24 in profile 2). Requested bytes are never rounded down or replaced with +`limit + 1`. All counts come from accepted source sizes or fixed object shapes +and fit Gamma's signed scalar range. + +`syntax_reverse_nodes` is also called by lowering and normalization, but only +its parser calls are charged to this budget. This ledger tracks syntax pairs +explicitly; it does not query Gamma's heap or turn physical evaluator +exhaustion into DCOUT. ## Grammar and diagnostics -The pipeline completes source-envelope and lexical admission before parsing. -The complete balanced parse precedes grammatical-role checking; grammar -precedes global identity collection. A later unmatched delimiter can therefore -preempt an earlier invalid grammatical role. This is explicit phase ordering, -not a promise to select the globally smallest coordinate across phases. - -The parser reports stray closing delimiters and unexpected source end through -syntax code 4. Grammar reports an offending node at its start, a missing -required child at its enclosing closing delimiter, and an extra child at that -child's start. A program without a required function reports source end. -Within a declaration, enclosing shape checks precede its queued children; -queued roles run in source order before the next declaration. - -The grammar entrance coordinates a counted pending-work spine instead of -recursively checking nested expressions. Count and spine travel as separate -machine arguments. A pending batch is -`(pair role (pair depth (pair remaining (pair nodes rest))))`; `nodes` reuses -the parser's ordered child spine. The current role runs directly, and only -pending siblings or later roles allocate frames. Successful roles tail-dispatch -the next work without allocating `Complete(work)` results, replacement work -wrappers, or reversed child lists. Shape probes use a private scalar result: -`-1` means success, otherwise the value is the exact rejection coordinate. -Only the completed declaration returns an outcome to the program coordinator; -the public grammar entrance still returns the original program or its failure. -Atom-role predicates also expose their scalar success or anchored failure to -the arm coordinator. A bare constructor pattern or one-child parenthesized -pattern can finish its name-role judgment before directly dispatching its body, -without a pending-body frame. Other patterns retain the binder worklist. -The direct path still enters the ordinary expression-role dispatcher, including -its depth provision; it does not bypass body grammar or change error ordering. -Nonexpression roles use depth zero; expression batches preserve expression -levels and inherited match-arm levels. -A function body starts at level 1; expression children -advance by one, including atoms. Match arm bodies use their enclosing match's -level plus one, without counting arm or pattern wrappers. Declarations, -parameters, and patterns do not themselves consume expression levels. - -Before an expression's grammar judgment, level 1,025 produces -`Incomplete(parse_depth)`: halt/tag 2, resource code 8, Delta-source space 1, -the expression's start, limit 1,024, and requested 1,025. Balanced parsing still -completes first, so the retained node already exists when the level is checked. -Pending frames may also already exist; the limit does not preflight their allocation. -Earlier pending grammar failures therefore keep their order, -and the limit check precedes the over-limit node's own grammar failure. -The subordinate files own these roles: +Source-byte validation and lexing finish before parsing. Complete balanced +parsing finishes before grammar checking, and grammar finishes before global +name collection. A later unmatched delimiter therefore wins over an earlier +grammar error; this is fixed phase order, not a global smallest-offset sort. + +The parser reports stray closing parentheses and unexpected EOF with syntax +code 4. Grammar anchors an invalid node at its start, a missing required child +at the enclosing closing parenthesis, and an extra child at that child's start. +A program with no functions reports EOF. Within a declaration, outer shape +checks run before queued children, and queued roles run in source order before +the next declaration. + +Grammar drives a counted pending-work spine instead of recursing on nested +expressions. Count and spine travel as separate arguments. A pending batch is +`(pair role (pair depth (pair remaining (pair nodes rest))))`, where `nodes` +reuses the parser's ordered child spine. The current role runs immediately; +only pending siblings or later roles allocate frames. Passing roles tail-call +the next work directly without building `Complete(work)` wrappers, replacement +work wrappers, or reversed child lists. Shape checks return a private scalar: +`-1` on success, or the exact error offset. Only a finished declaration returns +a phase result to the program loop; the public grammar entry returns the +original program or its failure. + +Atom-role checks also return scalar success or an error offset to the match-arm +handler. A bare or one-child parenthesized constructor pattern finishes its +name check and tail-enters the arm body directly without allocating a +pending-body frame; wider patterns use the binder worklist. This direct path +still runs the normal expression-role dispatcher and depth check, preserving +grammar rules and error order. + +Nonexpression roles use depth 0. A function body starts at expression level 1, +and each expression child (including atoms) adds 1. Match arm bodies take the +enclosing match's level plus 1, without counting arm or pattern wrappers. +Declarations, parameters, and patterns add no levels. + +Before checking an expression's grammar, level 1,025 returns +`Incomplete(parse_depth)`: halt/tag 2, resource code 8, source space 1, the +expression's start offset, limit 1,024, and requested 1,025. Because balanced +parsing already finished, the node and any pending frames already exist when +depth is checked. Earlier pending grammar errors still run first, while the +depth limit beats a grammar error inside the over-limit node itself. | Owner | Roles | | --- | --- | @@ -131,76 +124,66 @@ The subordinate files own these roles: | [expressions.gamma](grammar/expressions.gamma) | Expression atoms, heads, `if`, annotated `let`, `match`, and applications | | [patterns.gamma](grammar/patterns.gamma) | Two-child match arms and constructor patterns | -Names obey the grammar's capitalization and reserved-word rules. Type atoms -admit `Int`, `Bytes`, or a syntactically valid nominal name; whether a nominal -declaration exists is a later question. Pattern binders are validated as names, -without checking conflicts or resolving constructor payloads. +Names follow the grammar's case and reserved-word rules. Type atoms accept +`Int`, `Bytes`, or any valid uppercase name; checking whether a named type +exists happens later. Pattern binders are checked as names only, without +conflict or payload checks. -Ordinary functions, constructors, arithmetic operators, `eq`, `lt`, and the -closed `bytes_*` forms retain variable argument counts here. Their semantic -arity checks remain with body checking; this phase does not turn those failures -into syntax code 4. Bare arithmetic tokens are not expression atoms. Constructor -patterns likewise retain their authored binder counts for later arity checks. +Calls to functions, constructors, arithmetic operators, `eq`, `lt`, and the +`bytes_*` builtins allow arbitrary argument counts during grammar checking. +Arity checks belong to body type checking and do not become syntax code 4. Bare +arithmetic tokens are not valid expression atoms. Constructor patterns likewise +keep their authored binder counts for later arity checks. ## Consumers and remaining work -The retained program is consumed, not discarded after validation: - -- Global collection traverses declaration and constructor nodes, preserving - exact source owners, counts, and declaration-order tags. Raw function rows - retain their function node. -- Declaration resolution consumes retained parameter, result-type, and - constructor-field nodes against the completed global census. Its typed - metadata keeps the downstream format. Unknown declaration types produce - code 11 at that node's start; repeated parameters produce code 9 at the later - name. Declarations, constructors, and fields are visited in authored order. - Each parameter's conflict check precedes its own annotation, all parameters - precede the result, and all declarations precede body checking. Complete or - failure outcomes propagate through these retained-node traversals. -- Body checking consumes retained expression and pattern children, with exact - names and type coordinates carried through its complete/failure outcomes. - It starts from each function's resolved parameter environment and preserves - immutable local environments across disjoint scopes. Explicit continuations - retain pending child results and environments; visits and resumptions are - tail transitions rather than recursive source walks. Constructor metadata - retains ordered resolved field types, so calls and patterns do not rescan - payload annotations. -- Lowering traverses retained declarations, expressions, and pattern children. - Its shared visit/resume machine uses explicit continuation payloads instead - of recursive source-coordinate walks. It completes an expanded Gamma plan - with binding identities and expression-list heights. Atom spans still supply - exact authored names and admitted numeric text; emission prints that plan - without selecting Delta lowering rules. - -The [emitter](../../emission/README.md) remains after the complete static -preflight, as required by +Downstream phases consume the retained syntax tree directly: + +- Global collection walks declaration and constructor nodes, recording exact + source owners, counts, and declaration-order tags. Raw function rows keep + their parsed function node. +- Declaration resolution checks retained parameter, result-type, and + constructor-field nodes against the completed global catalog. Unknown + declaration types report code 11 at the node start; duplicate parameters + report code 9 at the later name. Declarations, constructors, and fields are + visited in authored order: each parameter checks name conflicts before its + type annotation, all parameters precede the result type, and all declarations + precede body checking. +- Body checking walks retained expression and pattern children with explicit + tail-called continuations instead of recursive source walks. It starts from + each function's parameter environment and keeps immutable local scopes across + disjoint branches. Constructor metadata stores ordered resolved field types, + so calls and patterns never rescan payload annotations. +- Lowering walks retained declarations, expressions, and patterns with explicit + continuations and builds an expanded Gamma plan carrying binding IDs and + expression-list heights. Atom spans supply authored names and numeric text; + emission prints that plan without repeating Delta lowering rules. + +The [emitter](../../emission/README.md) runs only after all static checks pass, +as required by the [completed preflight contract](../../../../LANGUAGE.md#compilation-requirements). -Other compiler-owned resource/internal failure propagation and successful -generated-program admission throughout the Delta depth profile remain separate -work. The selected Gamma evaluator caps generated bodies at 255 nested lists; -lowering may add wrappers. A separate -[normalization pass](../../normalization/README.md) uses the recorded expanded -heights to extract over-height fragments. That body-height transform does not -close the separate helper-count, runtime-context, storage, or compiler-owned -resource/internal boundaries. The `parse_depth` refusal is not evidence of -those later properties. +The Gamma evaluator caps generated function bodies at 255 nested lists, while +lowering can add wrapper lists; the separate +[normalization pass](../../normalization/README.md) reads the recorded heights +and extracts over-height fragments into helpers. That transform does not by +itself close helper-count, runtime-context, storage, or compiler-owned +resource/internal boundaries, and a `parse_depth` refusal is not evidence of +those later limits. The [boundary contract](../../boundary/README.md#body-traversal-and-coordinates) -records body diagnostic order and coordinates. Declaration parameters check -conflicts before their annotations; body `let` checks its annotation first and -checks the initializer in the outer environment. Calls consume expected -arguments in order, and matches defer final coverage until every arm succeeds. - -The complete grammar worklist also precedes census `function_rows` provision. -That later logical count admits 32,768 fresh authored functions, with duplicate -lookup before each provision; it does not count syntax nodes or generated -Gamma helpers. Its refusal is not a syntax error or a syntax-arena measurement. - -The explicit parser stack and grammar worklist use ordinary Gamma pairs. -Gamma's immutable arena accounts for cumulative allocations and does not -reclaim abandoned construction spines. The selected 1,024-level compiler -profile is not a Delta language nesting limit or a new Gamma primitive. -Selected evaluator exhaustion remains an evaluator-owned failure; expression -depth accounting does not translate it into guessed compiler resource codes or -establish full Delta resource conformance. Syntax-byte provision has its own -source-owned accounting above; it does not account for every compiler phase. +defines body diagnostic order and coordinates: declaration parameters check +conflicts before annotations, body `let` checks its annotation before conflicts +and checks its initializer in the outer scope, calls check expected arguments +in order, and matches check exhaustiveness only after every arm passes. + +Grammar also finishes before global collection's `function_rows` limit (32,768 +fresh authored functions, with duplicate lookup before limit checks). That +counter excludes syntax nodes and generated Gamma helpers, and its refusal is +neither a syntax error nor a syntax-storage refusal. + +The parser stack and grammar worklist allocate ordinary Gamma pairs in the +evaluator's non-reclaiming arena. The 1,024-level `parse_depth` limit is a +compiler-profile setting, not a Delta language limit or Gamma primitive. +Physical evaluator exhaustion stays an evaluator failure; neither depth +accounting nor the syntax-storage ledger translates it into DCOUT or covers +later compiler phases. diff --git a/bootstrap/delta/compiler/implementation/emission/README.md b/bootstrap/delta/compiler/implementation/emission/README.md index 767461ac8749..0fe4c54aa542 100644 --- a/bootstrap/delta/compiler/implementation/emission/README.md +++ b/bootstrap/delta/compiler/implementation/emission/README.md @@ -1,254 +1,206 @@ # Expanded Gamma serialization -Start at [program.gamma](program.gamma). It serializes the counted, ordered -definitions in a completed [Gamma plan](../representation/README.md), emits -their separators, and selects the existing profile adapter at program end. -[declarations.gamma](declarations.gamma) writes each definition's name, -parameters, and body. [expressions.gamma](expressions.gamma) prints the plan's -ordinary Gamma calls and lets; [atoms.gamma](atoms.gamma) prints its atoms. - -The pipeline finishes the complete frontend, selected-profile schema check, -and [lowering](../lowering/README.md) and -[normalization](../normalization/README.md) of every authored body before -writing the first receipt byte. A count-only serialization then measures the -complete payload using cached expression extents. Emission does not classify -Delta expressions, resolve locals, expand constructors or patterns, or choose -checked-arithmetic guards. Those -decisions are already explicit Gamma structure. +Start at [program.gamma](program.gamma). It prints the counted, ordered +definitions in a completed [Gamma plan](../representation/README.md), inserts +separators, and appends the selected profile adapter at the end. +[declarations.gamma](declarations.gamma) prints each definition's name, +parameters, and body. [expressions.gamma](expressions.gamma) prints calls and +lets; [atoms.gamma](atoms.gamma) prints atoms. + +All static checks, profile validation, [lowering](../lowering/README.md), and +[normalization](../normalization/README.md) finish before any output byte is +written. A count-only pass then sums cached expression extents to measure the +full payload. Emission never classifies Delta constructs, resolves locals, +expands constructors or patterns, or builds arithmetic guards — those are +already explicit Gamma nodes. ## Atom and expression custody -Source atoms retain exact admitted source spans through retained-node -accessors. Serialization may copy those bytes without interpreting their -Delta expression structure. Source binding references reuse the established -binding atom; generated names retain their marker and coordinate. Function -atoms receive the existing injective naming treatment, and fixed words and -integer atoms have dedicated textual encodings. - -Expression serialization uses explicit continuations for pending sibling -arguments and let initializers. Final arguments and let bodies tail-enter with -a scalar pending-close count; unary projection chains allocate no continuation -per projection. This traversal is over Gamma plan nodes, not retained -Delta expression children. Counts govern list projections; continuation depth -is neither source expression depth nor generated Gamma expression-list height. -The plan's height summaries do not change serialization or silently select a -different representation. +Source atoms store exact source spans via retained-node accessors, so the +serializer copies those bytes directly without parsing Delta structure. Source +binding references reuse their binding atom; generated names keep their marker +and coordinate. Function atoms use the injective naming rule, and fixed words +and integers use dedicated text writers. + +Expression printing uses explicit continuations for pending sibling arguments +and let initializers. Final arguments and let bodies tail-call with a scalar +pending-close count, so unary projection chains allocate no continuation frames. +This walk visits Gamma plan nodes, not Delta syntax nodes; counts govern list +projections, and continuation depth is unrelated to source depth or Gamma +expression-list height. Height summaries never alter printing or pick a +different layout. ## Fixed publication text -[text.gamma](text.gamma) owns textual primitives. [support.gamma](support.gamma) -binds the ordered support members of -[`bootstrap/delta/compiler/support/`](../../support/README.md): the byte-rope runtime, -the shared sealed-input runtime, and both generated `main` adapters are authored -once as ordinary readable Gamma files and copied verbatim from the sealed -input's bound support section. The pipeline's runtime selection - which member -a profile emits and where - remains separate from generic expression -serialization. These helpers, definition order, whitespace, hygienic spellings, -and the final publication byte retain the established receipt format. - -Runtime text is ordinary authored Gamma source under `support/`, not emitter -data. Admission checks the section's presence and `compile_admitted_source` -validates every member's extent and byte sum against the bound table before -any Delta-source phase; a missing or corrupt member refuses atomically in -DCOUT space 5 before any output. Count mode advances by each member's bound -extent; publication copies member bytes from the sealed input in order, then -advances the count by the same extent, so counting covers every support byte -alongside every generated byte. The copy allocates no pairs and reads only -the sealed input. The -[staged compiler gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/staged-compiler/run.sh) pins -exact member bytes, receipt counts, and execution. No new Gamma syntax, host -source generator, filename discovery, or semantic parser is involved. Generic -packed-word serialization remains separate. - -Emission entrypoints receive a count/publication flag and running byte count. -The expression entrance chooses cached counting or publication once; recursive -publication does not carry or recheck that flag. Byte loops only write, and -their callers advance the count once for each completely written extent. -[extents.gamma](extents.gamma) supplies the canonical expression-size summary -retained by each Gamma node constructor. Its count-only helpers share atom -spellings and call/let prefixes with publication, adding cached child extents -instead of unfolding shared children. Every rebuilt node recomputes its summary; -reused immutable nodes keep theirs. Count mode adds span and packed-text lengths -without reading or writing their bytes; it does not build a byte rope. -The coordinator includes the entry-owned final LF in both totals. If the full -count exceeds the selected payload limit, it returns DCOUT `Incomplete` -resource 12 in payload space 2 at the limit, with the exact complete count. -No application marker or partial program precedes that refusal. Admitted -publication checks its returned count against the preflight count; disagreement -remains an internal invariant failure, not a resource refusal. - -Preflight accumulation and node summaries use checked nonnegative addition, never -saturation. Negative metadata propagates the private failure sentinel `-1` -through every subsequent count operation. Before publication, the coordinator -turns that result into canonical `InternalFailure` code 2 -(`emission_metadata_contradiction`), internal-row space 3, row 0, with zero -limit/requested. Row 0 identifies the singleton complete-program emission -record; it does not claim to locate the first corrupt child or a source byte. -This is a retained-metadata invariant, not a source-admission refusal. - -Positive signed overflow in private metadata still fails before any wrapped -count can be admitted or published. The source argument below shows why admitted -Delta cannot construct that demand; no additional refusal code is needed for it. -Malformed private projections and late replay disagreement retain raw evaluator -failures. The latter cannot append a failure frame after already written receipt -bytes; its existing raw evaluator failure discards publication. -Serialization summaries cost two additional immutable pairs per Gamma node: -one for the extent and one for the optional unary-word prefix described below. -Full Epsilon recompilation remains a storage regression check. +[text.gamma](text.gamma) handles low-level text output. +[support.gamma](support.gamma) binds the ordered members under +[`bootstrap/delta/compiler/support/`](../../support/README.md): the byte-rope +runtime, sealed-input support, and both `main` adapters live as ordinary Gamma +files and are copied verbatim from the sealed input's trailing support section. +The pipeline decides which members a profile emits and where, keeping runtime +selection out of expression printing while preserving definition order, spacing, +hygienic names, and the trailing LF. + +Runtime text stays authored Gamma source under `support/`, not data baked into +the emitter. Request admission verifies the section's presence, and +`compile_admitted_source` checks every member's length and byte sum against the +bound table before running any Delta-source phase; a missing or corrupt member +fails atomically in DCOUT space 5 with no partial output. Count mode adds each +member's bound length; publication copies member bytes in order from sealed +input and adds the same length, allocating zero pairs. The +[staged compiler gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/staged-compiler/run.sh) +verifies exact member bytes, receipt lengths, and execution. Packed-word +printing stays separate. + +Emission entrypoints take a count/publish flag and a running byte count. +Expression emission checks that flag once at entry; recursive printing never +rechecks it. Byte loops only write, and callers advance the count once per +written span. [extents.gamma](extents.gamma) computes the byte-size summary +stored on every Gamma node constructor, sharing atom spellings and call/let +prefixes with printing and summing cached child extents without unfolding +shared subtrees. Rebuilt nodes recompute their extent; reused nodes keep +theirs. Count mode sums span and packed-word lengths without reading or writing +bytes or building a rope. The coordinator adds the final LF to both totals. If +the total exceeds the profile's payload limit, it returns DCOUT `Incomplete` +resource 12 in payload space 2 with coordinate and limit equal to the cap and +the exact requested byte count, before writing a single byte. Publication +asserts its written total matches the preflight total; any mismatch is an +internal failure, not a resource refusal. + +Preflight and node summaries use checked nonnegative addition, never +saturation. Negative metadata propagates the sentinel `-1` through every later +count operation. Before writing output, the coordinator converts `-1` into +`InternalFailure` code 2 (`emission_metadata_contradiction`), space 3, row 0, +limit/requested 0. Row 0 identifies the complete-program emission record, not a +corrupt child or source offset. + +Positive signed overflow in private metadata still traps before any wrapped +count is accepted or written; the proof below shows profile-1 Delta source +cannot trigger it. Malformed projections and late replay mismatches stay raw +evaluator failures (a late mismatch cannot append a failure frame after bytes +were already written, so evaluator failure discards output). Serialization +summaries cost two extra immutable pairs per Gamma node (extent plus optional +unary-word prefix). Full Epsilon recompilation serves as the storage regression +check. ## Reachable byte-count bound -This is a source-level audit of the selected producer, not a checked refinement -certificate or a promise of sufficient compiler memory/time. Its numerical -conclusion covers profile 1. Let `N` be admitted profile-1 source bytes (`3 <= N <= 4,194,304`); any well-formed complete Delta program is -longer than three bytes. Counts below refer to expanded expression occurrences, -not unique immutable pairs. Thus sharing cannot conceal a larger printed tree. +This source-level audit covers profile 1 (`3 <= N <= 4,194,304` source bytes; +every valid Delta program exceeds 3 bytes). It is not a machine-checked proof +or a memory/time guarantee. Counts below measure expanded expression +occurrences, not unique immutable pairs, so DAG sharing cannot hide a larger +printed tree. The [lowering templates](../lowering/README.md) place each authored expression -child once. Checked arithmetic binds operands instead of copying their trees; -match selectors retain each arm body once. An inlined +child once: checked arithmetic binds operands instead of duplicating subtrees, +and match selectors keep each arm body once. An inline [pattern projection spine](../lowering/matches/bindings.gamma) with `k` binders -prints at most a quadratic number of `first`/`second` calls. Only widths through -256 use that inline form; wider patterns use linear call-site structure and -one shared height-three projection definition. The following conservative -quadratic envelope still bounds both forms, including that fixed definition. -All pattern binders together consume distinct source tokens, so -`sum(k) <= N` and `sum(k*k) <= N*N`. A conservative inventory allows 128 -node/atom occurrences per remaining source token/expression and `4*k*k` per -pattern for expanded projections. Therefore the original program has at most -`M = 128*N + 4*N*N <= 64*N*N` occurrences, including call heads and binders. - -Byte literals are not charged just once as syntax atoms in this inventory. -Their lowering adds at most `5*Decoded + 2*Literals` plan occurrences. Each -decoded byte owns a distinct authored literal byte, and each literal also owns -two quote bytes; charging those occurrences to their disjoint literal-source -spans takes at most five occurrences per such source byte. The existing -128-per-source-byte allowance therefore includes this expansion. Literal -constructors add no local references or binders, so the separate reference and -ancestor-cut bounds below are unchanged. - -Two smaller counts matter for capture. Local-reference occurrences are bounded -by `R = 32*N`: an arithmetic template uses at most eleven generated references, -match wrappers at most two per match, selectors one per arm, and each pattern -initializer one payload reference regardless of projection-chain length. -Authored references add at most `N`. A path has height at most `L = 16*N`: -charge the constant expression wrappers, constructor fields, arm selectors, -pattern lets and projection steps to their distinct source occurrences along -that path. With `E` expression nodes, `F` constructor fields, `A` match arms, -and `B` pattern binders on those constructs, `7*E + F + A + 2*B` covers the -path: seven covers each expression's constant wrappers/comparisons, while the -other terms cover the variable-length spines. Each count is at most `N`, -so this fits the deliberately loose `16*N` allowance. -This strengthens the separate height audit's looser overflow bound. - -Normalization moves original subtrees into helpers; it never copies their -composite structure into both caller and callee. Each extraction starts at a -different original call/let occurrence, so helper count `J <= M`. Charge each -distinct captured parameter to one free local-reference occurrence below its -extraction point. Normalization completes descendant helpers before capturing -the enclosing helper, so this charge must include forwarded call arguments. -Initially each reference has its original expanded-occurrence origin. When an -inner helper captures a binding, assign its replacement-call argument an origin -from one of that binding's references in the extracted subtree. Outer capture -can forward that origin again, but only across an ancestor cut. Its deduplication -selects at most one parameter for each binding at that cut; different captured -bindings cannot claim the same original reference. Thus `(origin, ancestor cut)` -is an injective charge for capture incidences, including forwarded arguments. -Replacement calls have height one and do not introduce further extraction -points. A reference crosses at most `L` ancestor cuts, giving -`C <= R*L <= 512*N*N` without assuming the old capture order. This bounds retained -and intermediate capture incidences, not the work of looking them up or the -cumulative allocation of traversal frames. These counts also bound the -program-wide fresh-identity counter, which now advances only for helper names: -`J <= 64*N*N <= 2^50`; generated names consequently fit within 21 bytes, -without assuming that counter arithmetic was already safe. - -Long source names need a weighted bound, not `N` bytes for every generated -atom. Original source-span spellings total at most `N`: a local reference reuses -its declaration's spelling, but its equal-length use also occupies source bytes. -Across extraction cuts, the original binding spelling is printed as both a -helper parameter and a call argument. Added long-name copies therefore total -at most `2*N*L`. Other generated atoms are short; unchanged body references are -included in the original-occurrence allowance below. Counting fixed syntax generously gives -the following complete-payload envelope: +prints at most a quadratic number of `first`/`second` calls (only widths up to +256 inline; wider patterns use linear calls to one shared height-3 helper). The +conservative quadratic bound below covers both forms. Pattern binders consume +distinct source tokens, so `sum(k) <= N` and `sum(k*k) <= N*N`. Allowing 128 +occurrences per remaining source byte and `4*k*k` per pattern bounds total +original occurrences (including heads and binders) by +`M = 128*N + 4*N*N <= 64*N*N`. + +Byte literals add at most `5*Decoded + 2*Literals` plan occurrences. Each +decoded byte maps to a distinct literal source byte and each literal owns two +quote bytes, costing at most 5 occurrences per literal source byte — well +inside the 128-per-byte allowance. Literal trees add no local references or +binders, so the reference and cut bounds below stay unchanged. + +Local-reference occurrences are at most `R = 32*N`: arithmetic uses at most 11 +generated references, match wrappers at most 2 per match, selectors 1 per arm, +each pattern initializer 1 payload reference regardless of chain length, and +authored references at most `N`. Any path has height at most `L = 16*N`: along +a path with `E` expressions, `F` constructor fields, `A` match arms, and `B` +pattern binders, `7*E + F + A + 2*B` covers constant wrappers plus variable +spines, and each count is at most `N`, fitting `16*N` (tighter than the height +audit's overflow bound). + +Normalization moves subtrees into helpers without duplicating composite trees +into both caller and callee. Each extraction begins at a distinct original +call/let occurrence, so helper count `J <= M`. Charge each captured parameter +to one free local-reference occurrence inside its extracted subtree. Because +descendant helpers finish before their parent's capture, assign each +replacement-call argument an origin from one of that binding's references in +the extracted subtree. Outer capture can forward that origin across an ancestor +cut, deduplicating to at most one parameter per binding at that cut, so no two +captured bindings claim the same original reference. Thus +`(origin, ancestor cut)` injectively charges every capture, including forwarded +arguments. Replacement calls have height 1 and never trigger new cuts. Each +reference crosses at most `L` cuts, giving `C <= R*L <= 512*N*N`. This also +bounds the helper-name counter (`J <= 64*N*N <= 2^50`), keeping generated +names under 21 bytes. + +Long identifiers need a weighted bound rather than `N` bytes per atom. Original +source-span spellings total at most `N` (each local reference reuses its +declaration's spelling, and its equal-length use also occupies source bytes). +At extraction cuts, a captured binding prints once as a helper parameter and +once as a call argument, adding at most `2*N*L` long-name bytes. Generously +charging fixed syntax gives the full payload bound: ```text 64*M + 128*J + 128*C + 2*N*L + N + 4,096 < 2^18 * N^2 <= 2^62 ``` -The 64-byte allowance covers each original occurrence's short atom spelling, -punctuation, annotation, and spacing. Each 128-byte helper allowance covers its -definition and replacement-call framing and names; each capture allowance covers -its parameter declaration and argument. Authored declarations and parameters -are included in the original inventory. Fixed marker, bound support members, -and final LF total less than 4,096 bytes. This is deliberately not a tight size -estimate or a proposed payload provision. - -Capture retains normalized bodies and their original atoms unchanged; -partially normalized programs add subsets of the helper/capture -incidences above. The envelope therefore covers intermediate cached extents as -well as final payloads, not the cumulative sizes of all discarded immutable -copies. Counts are nonnegative sums of those extents and syntax -bytes, so partial sums also fit signed 64-bit arithmetic. The actual publication -profile-1 path runs only after exact preflight admits at most 16,777,212 bytes; its byte -increments and pending closes follow the same immutable formatting structure. -No saturation, fabricated requested count, or new source refusal is necessary. -For profile 2, the same loose quadratic formula at 64 MiB exceeds the signed -64-bit count range, so the profile-1 inequality does not prove overflow -unreachable for all construction sources. The implementation still checks each -extent addition and refuses a payload over the configured limit before writing. -These counts do not establish canonical outcomes for underlying evaluator -exhaustion; serialization's own traversal pairs are bounded +Here 64 bytes per original occurrence covers short spellings, annotations, and +punctuation; 128 bytes per helper covers definition and call framing; 128 bytes +per capture covers parameter and argument framing; and marker, bound support +members, and final LF total under 4,096 bytes. + +Capture leaves normalized bodies and original atoms unchanged, and partially +normalized plans contain subsets of these helper/capture counts, so the bound +covers both intermediate cached extents and final payloads (not discarded +immutable copies). All partial sums are nonnegative and fit signed 64-bit math. +Profile-1 publication runs only after preflight accepts at most 16,777,212 +bytes. For profile 2 (64 MiB source), this loose quadratic formula exceeds +signed 64-bit range and does not rule out overflow, though every extent +addition remains checked and oversized payloads still refuse before writing. +Serialization's own traversal pairs are bounded [below](#publication-traversal-pairs). ### Unary fixed-word prefixes -[unary_words.gamma](unary_words.gamma) caches a compact publication prefix for -one-argument calls whose head is a fixed word of one through seven bytes. The -cache does not select a particular primitive or inspect authored source names. -It encodes the visible low bytes and their length in one nonzero scalar below -2^59; ignored high bytes are masked before encoding. All other call shapes use -ordinary call publication. Zero means no cached prefix, not an empty spelling. - -The expression visitor writes a cached prefix and tail-enters the sole argument -with one more pending close. This skips repeated atom dispatch and argument -dispatch when immutable call nodes occur many times in the expanded output. -The same byte writer emits fixed words on both paths. Counts continue to come -from canonical extents, and the final publication total must still agree. -Every reconstructed node refreshes both summaries; no cache is keyed by pair -address, compiler identity, or source pattern. - -No source-dependent lowering template remains in this directory. Calls, -constructors, bindings, arithmetic, and matches belong under `lowering/`; -durable Gamma plan nodes belong under `representation/`. +[unary_words.gamma](unary_words.gamma) caches a compact prefix for one-argument +calls whose head is a fixed word of 1 to 7 bytes, without special-casing +primitives or inspecting source names. It packs the visible low bytes and their +length into one nonzero scalar below 2^59 (masking ignored high bytes). Zero +means no cached prefix, falling back to ordinary call printing. + +The expression printer writes a cached prefix and tail-enters the single +argument with one more pending close, skipping atom and argument dispatch when +shared call nodes repeat in the output. Both paths share the same byte writer, +counts still come from canonical extents, and the final total must match +preflight. Rebuilt nodes refresh both summaries; nothing is keyed by pair +address, compiler ID, or source pattern. + +No Delta lowering templates live here: calls, constructors, bindings, +arithmetic, and matches live under `lowering/`, and Gamma plan nodes live under +`representation/`. ### Publication traversal pairs -The counts above bound emitted bytes; this bound covers the immutable pairs -serialization itself allocates while producing them. The only pair -allocations in this directory are the pending-work frames in -[expressions.gamma](expressions.gamma): a nonfinal-argument frame costs four -pairs (two frame cells plus a two-pair counted payload), and a pending -let-body frame costs three (two plus one). Final children, unary-word calls, -and the scalar pending-close count allocate none. - -The count-only pass allocates zero pairs: every expression answers through -its cached extent and each fixed or atom spelling advances by its measured -length, so preflight never descends the plan. Publication's byte loops, -decimal, marker, definition, and adapter writers likewise use only `write` -effects, lexical rows, and scalar arithmetic, not pairs. The two summary -pairs per Gamma node belong to plan construction, not to this traversal. - -Publication runs only after exact preflight admits at most `P` bytes including -the final LF. Profile 1 selects 16,777,212; profile 2 selects 134,217,728. Charge each frame to distinct emitted bytes: a -nonfinal argument owns its separator byte and that argument's first emitted -byte, and a `let` owns at least twelve bytes after its opening parenthesis -(`let `, a binder, ` `, `Int`, ` `, the initializer-body separator, and `)`). -An argument's first byte can be another let's opening parenthesis, which is -why the let charge excludes it. Every other charged byte sits inside its own -frame's extent, so the charged sets are disjoint. A shared immutable child -revisited per occurrence simply charges that occurrence's own emitted bytes. -Therefore +The only pairs allocated in this directory are pending-work frames in +[expressions.gamma](expressions.gamma): 4 pairs per nonfinal argument frame (2 +frame cells + 2-pair counted payload) and 3 pairs per pending let-body frame +(2 + 1). Final children, unary-word calls, and pending-close counts allocate +none. + +Count mode allocates zero pairs: expressions return cached extents and fixed +or atom spellings add measured lengths, so preflight never walks the plan. +Byte loops and definition/adapter writers use only `write` effects, locals, and +scalars. The two summary pairs per node belong to plan construction, not +traversal. + +Publication runs only after preflight accepts at most `P` bytes including the +final LF (`16,777,212` for profile 1, `134,217,728` for profile 2). Charge each +frame to disjoint emitted bytes: a nonfinal argument owns its separator byte +and its own first emitted byte; a `let` owns at least 12 bytes after its +opening parenthesis (`let `, binder, ` `, `Int`, ` `, separator, `)`), +excluding the opening parenthesis since an enclosing argument can charge it. +Shared subtrees revisited per occurrence charge that occurrence's emitted +bytes. Hence: ```text traversal pairs <= 4 * floor(P / 2) + 3 * floor(P / 12) @@ -256,38 +208,31 @@ profile 1: at most 37,748,727 pairs profile 2: at most 301,989,886 pairs ``` -Serialization alone therefore cannot exhaust the selected pair arena: it adds -at most the selected number of cumulative pairs to a compilation whose earlier phases are -separately owned. This bounds emission's own traversal, not generated-program -execution; it manufactures no DCOUT outcome and changes no provision. +Serialization therefore cannot exhaust the pair arena on its own. This bounds +emission traversal only, not generated-program execution, and adds no DCOUT +codes or profile limits. ## Validation and remaining boundaries -The [emission gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/emission/README.md) exercises -count/publication agreement, prefix eligibility and fallback, continuation -ordering, and capture preservation on private Gamma-plan controls. These -controls do not claim source admission or executable program semantics. +The [emission gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/emission/README.md) +tests count/publication agreement, prefix caching and fallback, continuation +order, and capture preservation on private Gamma plans. -The staged gate compares exact receipts, executes generated programs, and -exercises nested expressions and wide payloads. Exact Epsilon checking and -execution receipts remain separate full-customer reconstruction gates. A -changed receipt requires explanation, not a relaxed expectation. +The staged gate compares exact receipts, runs generated programs, and tests +nested expressions and wide payloads. Epsilon checking and execution receipts +remain separate customer gates; any changed receipt must be explained rather +than silently updated. The [lowering-plan gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/lowering-plan/README.md) -checks authored expectations against the pre-normalization plan's expanded -body heights. The separate normalizer handles the +checks pre-normalization body heights. The normalizer enforces the [selected Gamma profile](../../../../gamma/interpreter/EVALUATOR_PROFILE.md#exact-capacities) -limit of 255 nested expression lists per generated function body. Serialization -does not make extraction or capture decisions and does not alter those budgets. +limit of 255 nested expression lists per body; serialization never makes +extraction or capture choices. -Plan and continuation pairs consume the selected evaluator's finite immutable -arena. The traversal bound above covers serialization's own frames; combined with -earlier phases, whole-producer profile-1 cumulative allocation is bounded -universally below the selected 3,422,447,206-pair arena by the +Combined with earlier phases, whole-compiler profile-1 pair allocation stays +below the 3,422,447,206-pair arena by the [execution-storage audit](../boundary/execution_storage.md#cumulative-pair-containment) -(`<= 3,092,641,319` pairs). -The compiler-owned resource/internal outcomes are the enumerated DCOUT tables, -and generated-program admission bounds are discharged by the payload extent -and normalization audits. Stack-safe compiler traversal, complete-before-write -planning, and exact receipt preservation still do not close the full Delta -bootstrap edge. +(`<= 3,092,641,319` pairs). Compiler-owned failure outcomes are limited to the +DCOUT tables, and generated-program admission bounds are proved by the payload +and normalization audits. Stack-safe traversal, complete-before-write planning, +and exact output preservation still do not close the full Delta bootstrap edge. diff --git a/bootstrap/delta/compiler/implementation/lowering/README.md b/bootstrap/delta/compiler/implementation/lowering/README.md index 6253cb240ba4..2a1fec3b50ee 100644 --- a/bootstrap/delta/compiler/implementation/lowering/README.md +++ b/bootstrap/delta/compiler/implementation/lowering/README.md @@ -1,20 +1,19 @@ # Checked Delta to expanded Gamma -Start at [program.gamma](program.gamma). It consumes the complete checked -program and resolved catalogs after selected-profile schema validation and -builds every function definition in authored order. Data declarations select -whether one shared projection definition is needed; they emit no Delta types. -No lowering helper publishes receipt bytes. Its result is the complete -[expanded Gamma program](../representation/README.md). - -[expressions.gamma](expressions.gamma) owns the shared visit/resume machine. -Concept-owned helpers handle bindings, applications, constructors, checked -arithmetic, and matches. They consume completed grammar, name, arity, and type -judgments rather than deciding those judgments again. +Start at [program.gamma](program.gamma). After profile validation, it walks the +checked program and resolved catalogs to build every function definition in +authored order. Data declarations only decide whether to add the shared +projection helper; Delta types are erased. No lowering code writes output. The +result is an [expanded Gamma program](../representation/README.md). + +[expressions.gamma](expressions.gamma) runs the shared visit/resume loop. +Submodules handle bindings, calls, constructors, checked arithmetic, and +matches, relying on earlier grammar, name, arity, and type checks instead of +rechecking them. ## Continuations and binding custody -The common operations are: +The shared loop uses: ```text lowering_visit(node, locals, depth, frames, globals) @@ -22,84 +21,79 @@ lowering_resume(value, depth, frames, globals) frame = (pair kind (pair payload previous)) ``` -The resumed value is an expanded Gamma expression. Frame depth counts pending -compiler work, not source depth or generated expression height. Resume pops -exactly one frame before dispatch; handlers receive the decreased depth and -previous stack. Payload owners retain completed child values and the lexical -environment needed for the next child. Counts govern pair-spine projections. +The resumed value is an expanded Gamma expression. `depth` counts pending +compiler work, not source depth or generated expression height. Resume pops one +frame before dispatch and passes the decremented depth and remaining stack to +the handler. Frame payloads hold completed child expressions and the local +environment for the next child. Counts govern pair-spine projections. -[bindings.gamma](bindings.gamma) reuses the existing exact-name trie, storing -original Gamma binding atoms rather than types. Immutable snapshots preserve -lexical scopes; only parameters retain a separate declaration-order spine. A let -initializer is lowered in its outer environment; only the body receives the -new source binding atom. Parameter and pattern references likewise reuse their -established atoms. Looking up that custody does not introduce a second conflict -or type policy after checking. +[bindings.gamma](bindings.gamma) reuses the exact-name trie to map names to +Gamma binding atoms instead of types. Immutable snapshots keep lexical scopes +separate; only parameters also keep a declaration-order spine. A `let` +initializer lowers in the outer environment, while its body sees the new +binding atom. Parameter and pattern references reuse their binding atoms. +Lowering lookup adds no new conflict or type checks after type checking. ## Concept ownership -Application arguments and constructor fields are lowered left to right before -their enclosing Gamma expression is built. Checked arithmetic binds each -operand once before constructing its existing overflow guard; generated marker -and coordinate identities remain shared by the guard's references. +Call arguments and constructor fields lower left to right before building the +enclosing Gamma expression. Checked arithmetic binds each operand once before +building its overflow guard, sharing generated marker and coordinate IDs across +the guard's references. -[matches.gamma](matches.gamma) coordinates the subject and arm bodies. -[matches/arms.gamma](matches/arms.gamma) owns authored arm order, tag selection, -and the final exhaustive fallback. -[matches/bindings.gamma](matches/bindings.gamma) owns pattern binding and -payload projections. The completed subject appears once under its generated -binding; arm bodies use the common continuation machine. Constructor metadata -supplies checked representation and tags. +[matches.gamma](matches.gamma) lowers the subject and arm bodies. +[matches/arms.gamma](matches/arms.gamma) keeps authored arm order, builds tag +tests, and emits the final exhaustive fallback. +[matches/bindings.gamma](matches/bindings.gamma) builds pattern bindings and +payload projections. The subject is evaluated once into a generated binding; +arm bodies run through the shared continuation loop. Constructor metadata +supplies representation shapes and tags. ### Wide payload projections -Patterns with at most 256 fields keep their existing inline projection chains; -each individual chain then has at most 255 Gamma expression lists. Wider -patterns call one ordinary generated Gamma function, `$dp(payload, index)`, -which tail-recursively takes `second` until the index reaches zero. Nonfinal -fields take `first` of that tail; the final field is the unwrapped tail itself. -Indices are generated in `0..arity-1`, so each reached `second` has a pair -under the already-checked product representation. The helper neither allocates -product nodes nor changes field order, provenance, or authored trap behavior. -Its recursive call is proper-tail, but each initializer's initial call consumes -one ordinary runtime context; this is not a promise of unchanged exhaustion -thresholds for arbitrary application stacks. - -The checked data-before-functions order lets `program.gamma` install `$dp` once -when the first constructor wider than 256 fields is encountered. During that -prefix the definition count is zero or one. Later wide constructors reuse it, -even across nominal owners; a wide declaration without a matching use retains -the same small definition instead of requiring another usage-analysis pass. -The helper's two parameters and height-three body are ordinary Gamma structure. -Its reserved name cannot collide with renamed authored functions or generated -`$hN` extraction names. It is not a new primitive, adapter, or language rung. - -This avoids rebuilding and printing quadratic projection chains for wide -patterns. It does not change the product layout or make evaluation of all `k` -fields subquadratic: the runtime still walks each requested prefix. Enclosing -binding chains and wide constructor products still undergo normal height -normalization. Programs whose constructors all fit 256 fields retain their -previous plan and receipt bytes. +Patterns with up to 256 fields keep inline `first`/`second` projection chains, +each at most 255 Gamma expression lists deep. Wider patterns call one shared +generated Gamma function, `$dp(payload, index)`, which tail-recursively applies +`second` until `index` reaches 0. Nonfinal fields take `first` of that tail; the +final field is the tail itself. Because indices run `0..arity-1` on an +already-checked product, every `second` sees a pair. The helper allocates no +product nodes and preserves field order, pair identity, and trap behavior. Its +loop is tail-recursive, though each field initializer's call into `$dp` still +uses one normal runtime call context. + +Because data declarations precede functions, `program.gamma` installs `$dp` +once when it sees the first constructor with more than 256 fields (so the +definition count starts at 0 or 1). All later wide constructors share it across +types; an unused wide constructor still keeps that small definition to avoid an +extra usage pass. `$dp` has two parameters and a height-3 body, and its +reserved name cannot collide with renamed functions or `$hN` helpers. It is +ordinary Gamma, not a new primitive, adapter, or language level. + +Using `$dp` avoids building and printing quadratic projection chains for wide +patterns. It does not change product layout or make projecting all `k` fields +subquadratic at runtime, since each call still walks its prefix. Enclosing +binding chains and wide constructor products still go through height +normalization. Programs whose constructors all have at most 256 fields produce +identical plans and output. Calls, lets, products, and guards are ordinary Gamma plan nodes. Their -constructors compute expanded expression-list heights, including generated -wrappers, and cache exact serialization extents through the serializer's -count-only formatting helpers. The later serializer does not need Delta constructor, pattern, -arithmetic, or lexical-environment knowledge. +constructors compute expanded expression-list heights (including generated +wrappers) and cache exact serialized byte counts via the serializer's +count-only helpers, so serialization needs no knowledge of Delta constructors, +patterns, arithmetic, or local scopes. ## Traversal and rebuild pairs This audit charges every pair lowering allocates to a retained-source -occurrence, in the same style as the +occurrence, matching the [normalization audit](../normalization/README.md#traversal-and-rebuild-pairs). -Gamma constructors cost their fixed shapes: `gamma_node` is four pairs plus -any payload pair and `gamma_call`/`gamma_let` add two; `gamma_word` and -`gamma_generated` cost five, `gamma_first`/`gamma_second` twelve, -`gamma_pair`/`gamma_eq`/`gamma_lt` thirteen, `gamma_if` fourteen, and -`gamma_trap` twenty-one; `gamma_definition`/`gamma_program` are three and -one. Name lookups and `lowering_bind` insertions are charged through the -shared [name-trie audit](../checking/names/README.md#pair-accounting); the -quantities `N`, `S`, `V`, `W_n`, `E_n`, and `Q` are defined in the +Fixed constructor costs: `gamma_node` is 4 pairs plus any payload pair, +`gamma_call`/`gamma_let` add 2, `gamma_word` and `gamma_generated` cost 5, +`gamma_first`/`gamma_second` cost 12, `gamma_pair`/`gamma_eq`/`gamma_lt` cost +13, `gamma_if` costs 14, `gamma_trap` costs 21, `gamma_definition` costs 3, and +`gamma_program` costs 1. Lookups and `lowering_bind` inserts are charged in the +[name-trie audit](../checking/names/README.md#pair-accounting); `N`, `S`, `V`, +`W_n`, `E_n`, and `Q` are defined in the [checking audit](../checking/README.md#traversal-and-rebuild-pairs). | Site | Pairs | Charged per | @@ -126,12 +120,12 @@ quantities `N`, `S`, `V`, `W_n`, `E_n`, and `Q` are defined in the | Shared `$dp` definition + its program cell | <=89 | compilation with a wide constructor | | Local/constructor lookups and binder inserts | name-event terms | per lookup / bound name | -A call-like node with `a` lowered arguments therefore allocates `8*a + 11` -site pairs; a constructor application `22*a + 21`; an arithmetic node 194; -a `let` 17; a `match` at most `64 + 44*U + 41*B`; a function `9 + 6*P_f`; -and the program `F + 2` plus at most 89 for `$dp`. With the disjoint -occurrence classes summing to at most `S` retained nodes and `Ce <= A` -constructor-field edges inside the `A` argument edges, +Per-construct totals: a call-like node with `a` lowered arguments allocates +`8*a + 11` pairs; a constructor application `22*a + 21`; an arithmetic node +194; a `let` 17; a `match` at most `64 + 44*U + 41*B`; a function `9 + 6*P_f`; +and the program `F + 2` plus at most 89 for `$dp`. Since disjoint node classes +sum to at most `S` and constructor-field edges `Ce <= A` sit inside the `A` +argument edges: ```text nonliteral lowering site pairs @@ -141,75 +135,71 @@ nonliteral lowering site pairs <= 200*S + 91 ``` -where `At`, `K`, `Ca`, `R`, `L`, `M`, `U`, `B`, `F`, and `P` count atom, -non-constructor call, constructor-application, arithmetic, `let`, `match`, -arm, pattern-binder, function, and parameter occurrences. +Here `At`, `K`, `Ca`, `R`, `L`, `M`, `U`, `B`, `F`, and `P` count atom, +non-constructor call, constructor-application, arithmetic, `let`, `match`, arm, +pattern-binder, function, and parameter nodes. ### Plan size handed to normalization -The same sites construct the `G` plan-node occurrences the -[normalizer](../normalization/README.md#traversal-and-rebuild-pairs) charges -against. Counting node-producing rows — atoms and shared binding atoms, call -and let nodes, constructor products, arithmetic templates, match contexts, -selector chains, projections and wrapper lets, parameters and the `$dp` -definition — gives the deliberately loose bound +These same sites build the `G` plan-node occurrences that the +[normalizer](../normalization/README.md#traversal-and-rebuild-pairs) traverses. +Counting all node-producing rows (atoms, binding atoms, calls, lets, products, +arithmetic templates, match contexts, selector chains, projections, wrapper +lets, parameters, and `$dp`) gives the deliberately loose bound: ```text G_base <= 40*S + 15 ``` -Byte-literal expansion adds the separately charged nodes below, giving -`G <= 40*S + 15 + 5*Decoded + 2*Literals`. The normalizer machine's -`45*G + 7*F + 1` therefore reduces to an admitted-source -term. That reduction does not itself bound capture merges, which the -normalization audit closes separately through its incidence charge. +Adding byte-literal expansion below gives +`G <= 40*S + 15 + 5*Decoded + 2*Literals`, reducing the normalizer's +`45*G + 7*F + 1` term to source size. Capture merges are bounded separately in +the normalization audit. ## Remaining boundaries -This phase deliberately returns the expanded, pre-normalization plan. The -private lowering-height diagnostic observes those original heights, including -heights above 255. Normal compilation passes the plan to -[normalization](../normalization/README.md) before publication; that separate -owner handles body nesting without changing Delta lowering rules. - -Allocated plan and continuation pairs consume the evaluator's finite immutable -arena; the [traversal-and-rebuild accounting](#traversal-and-rebuild-pairs) -above charges each one to a retained-source occurrence and bounds the produced -plan size `G`. Whole-producer profile-1 arena containment — including -byte-literal compositions — is closed by the +Lowering returns the expanded, pre-normalization plan so the private +lowering-height diagnostic can inspect original heights (including those above +255). Normal compilation passes the plan to +[normalization](../normalization/README.md) before emission, keeping body-depth +rewriting separate from Delta lowering rules. + +Plan and continuation pairs use the evaluator's finite immutable arena. The +[traversal-and-rebuild accounting](#traversal-and-rebuild-pairs) above charges +each pair to a source node and bounds plan size `G`. Whole-compiler profile-1 +arena containment (including byte literals) is proved in the [execution-storage audit](../boundary/execution_storage.md#cumulative-pair-containment) -(`<= 3,092,641,319 < 3,422,447,206` pairs). Generated-program -admission bounds — function census via the payload's eight-bytes-per-declaration -charge, body list depth, and static environments — are discharged by the +(`<= 3,092,641,319 < 3,422,447,206` pairs). Generated-program admission limits +(function count via the 8-byte-per-declaration payload bound, body list depth, +and static environments) are proved in the [normalization audit](../normalization/README.md#remaining-resources). A -generated program's live runtime contexts and cumulative storage remain its -own execution's resources, not compiler outcomes. Exact checking and execution -receipts remain explicit regression obligations. +generated program's runtime contexts and heap remain its own execution limits, +not compiler failures. Exact checking and execution outputs remain regression +checks. ### Byte-literal lowering -A byte literal uses existing `Bytes` constructors rather than a new Gamma node -kind or runtime representation. Lexical admission owns quotes/escapes and the -complete token boundary; lowering reads only that retained span. Empty literals -lower to `bytes_empty`. Nonempty literals decode to an ordered byte spine, then -form a balanced tree of `bytes_single` leaves and `bytes_concat` nodes. Tree -construction returns its unconsumed spine, so no subtree rescans earlier bytes. - -For a literal with `p > 0` decoded bytes, decoding/reversal uses `2*p + 1` -source-level pairs. Leaves use at most 16 pairs, internal concatenations at -most 13, and each tree result one custody pair. A conservative additional -charge is `34*p + 12` pairs and `5*p + 2` Gamma plan nodes per literal, on top of -the earlier source-occurrence envelope. Thus a literal's compressed syntax atom -does not conceal its expansion from resource accounting. With total decoded -bytes `Decoded` and literal count `Literals`, add `33*Decoded + 12*Literals` -(conservatively `34*Decoded + 12*Literals`) to the lowering envelope and -`5*Decoded + 2*Literals` to its plan-node envelope; combined with normalization -and capture, total byte-literal pairs are at most `70*N_lit`, closed with the -rest of profile 1 in +Byte literals lower to existing `Bytes` constructors rather than a new Gamma +node or runtime type. Lexing already validates quotes, escapes, and token +boundaries; lowering reads only the retained span. Empty literals lower to +`bytes_empty`. Nonempty literals decode into an ordered byte spine and build a +balanced binary tree of `bytes_single` leaves and `bytes_concat` internal +nodes. Each recursive call returns the remaining unconsumed spine, so no +subtree rescans earlier bytes. + +For a literal of `p > 0` decoded bytes, decoding and reversal take `2*p + 1` +pairs, leaves take at most 16 pairs, internal concatenations take at most 13, +and each tree result takes 1 wrapper pair. Conservatively charging `34*p + 12` +pairs and `5*p + 2` plan nodes per literal keeps literal expansion visible to +resource accounting. Across total decoded bytes `Decoded` and literal count +`Literals`, this adds `33*Decoded + 12*Literals` (conservatively +`34*Decoded + 12*Literals`) lowering pairs and `5*Decoded + 2*Literals` plan +nodes; combined with normalization and capture, all byte-literal pairs total at +most `70*N_lit`, closed for profile 1 in [`execution_storage.md`](../boundary/execution_storage.md#cumulative-pair-containment). -All source input is limited to 4,194,304 bytes, and decoded bytes cannot exceed -their authored span. Each non-tail tree child has at most `ceil(p/2)` bytes; -the tree therefore adds at most 22 recursive levels. Decode and spine reversal -are tail-recursive. The tree completes before normalization/capture sorting -begins, so these recursive phases do not retain each other's contexts. +Profile-1 source is at most 4,194,304 bytes, and decoded length cannot exceed +source span. Each non-tail tree child handles at most `ceil(p/2)` bytes, adding +at most 22 recursive levels. Decode and spine reversal are tail-recursive. +Literal trees finish before normalization and capture sorting start, so those +recursive phases never stack on top of each other. diff --git a/bootstrap/delta/compiler/implementation/normalization/README.md b/bootstrap/delta/compiler/implementation/normalization/README.md index 2cbecb0941d2..630c2aa534b4 100644 --- a/bootstrap/delta/compiler/implementation/normalization/README.md +++ b/bootstrap/delta/compiler/implementation/normalization/README.md @@ -1,285 +1,233 @@ # Gamma body-height normalization -Start at [program.gamma](program.gamma). Its `normalize_program` entrance sits -between complete [Gamma lowering](../lowering/README.md) and -[serialization](../emission/README.md). It consumes and produces the same -[Gamma program representation](../representation/README.md). It does not parse -Delta, repeat frontend judgments, or write receipt bytes. - -[expressions.gamma](expressions.gamma) coordinates height budgets and the common -visit/resume machine. [arguments.gamma](arguments.gamma) and -[bindings.gamma](bindings.gamma) retain pending call and let children. -[helpers.gamma](helpers.gamma) owns extraction and generated definitions; -[capture.gamma](capture.gamma) collects free bindings under their lexical scopes. - -The selected Gamma evaluator admits at most 255 nested expression lists per -function body. Lowering can exceed that height even when Delta syntax stays -within its separate 1,024-level expression-depth profile. Normalization moves -whole over-height fragments into generated functions, retaining their position -in the original expression's evaluation. +Start at [program.gamma](program.gamma). `normalize_program` runs between +[Gamma lowering](../lowering/README.md) and +[serialization](../emission/README.md), taking and returning the same +[Gamma program representation](../representation/README.md). It never parses +Delta, rechecks types, or writes output. + +[expressions.gamma](expressions.gamma) manages height budgets and the shared +visit/resume loop. [arguments.gamma](arguments.gamma) and +[bindings.gamma](bindings.gamma) hold pending call and let children. +[helpers.gamma](helpers.gamma) extracts over-height fragments into new +definitions; [capture.gamma](capture.gamma) collects free bindings under +lexical scope. + +The Gamma evaluator accepts at most 255 nested expression lists per function +body. Lowering can exceed 255 even when Delta source stays within its +1,024-level expression-depth limit. Normalization moves over-height fragments +into generated helper functions while keeping their exact evaluation position. ## Height budget -`normalization_height_limit` in [program.gamma](program.gamma) owns the selected -255-list budget. Each function body starts with that budget. A subtree whose -recorded height fits the remaining budget is reused unchanged. Otherwise traversal -descends through its Gamma call or let structure with one less level available -to each expression child. - -Rebuilt nodes refresh both expanded height and canonical byte extent through -the ordinary Gamma constructors. Extracted helper calls retain their own -extents. Capture collection leaves the completed body unchanged, preserving -both summaries on its immutable nodes. - -At budget one, an over-height fragment reserves a helper name and restarts -normalization under a fresh budget of 255. Descendant helpers finish first. -Capture then collects free bindings from the completed, height-bounded body, -including arguments to descendant helpers, before appending its definition. -The replacement call passes only already-bound values. Those arguments have height zero, so -the replacement call has height one. The initial program can also contain lowering's -shared projection definition for wide constructors. Its height-three body -already fits; it is not an extraction helper or an authored Delta function. - -No work is moved into a sibling expression or before an enclosing initializer. -The helper call occupies the extracted fragment's exact evaluation position. -Branches remain conditional, earlier arguments still precede later arguments, -and authored computations and traps remain inside the fragment. A call that -replaces a tail-position fragment remains in tail position; the fragment's -original result becomes the helper's result. +`normalization_height_limit` in [program.gamma](program.gamma) sets the +255-list budget. Each function body starts at 255. Any subtree whose recorded +height fits the remaining budget is reused unchanged; otherwise the loop +descends into its call or let children with budget minus 1. + +Rebuilt nodes refresh both height and byte extent via the ordinary Gamma +constructors. Replacement helper calls compute their own extents. Free-binding +collection leaves the completed body and its summaries unchanged. + +At budget 1, an over-height fragment reserves a helper name and restarts +normalization with a fresh budget of 255. Descendant helpers finish first. +Capture then collects free bindings from the finished, height-bounded body +(including arguments passed to descendant helpers) and appends the new +definition. The replacement call passes only already-bound atoms (height 0), so +the call has height 1. Lowering's shared wide-constructor projection helper +(height 3) already fits and is left untouched. + +No computation moves into a sibling or before an enclosing initializer. The +helper call stays in the fragment's exact evaluation slot: branches stay +conditional, argument order and traps stay intact, and a tail-position fragment +becomes a tail call returning the fragment's result. ### Height and completion argument -The [representation constructors](../representation/gamma/expressions.gamma) -assign atoms height zero and calls/lets `1 + max(child heights)`. -The [expression serializer](../emission/expressions.gamma) emits precisely that -expression-list nesting; declaration and parameter-list wrappers are outside -the body. Immutable reuse preserves the summary, and capture collection does -not change the body. - -These height additions cannot overflow for admitted source. Let `N` be source -bytes, at most 4,194,304. There are at most `N` authored expression starts on -any path. Lowering adds at most one level for an ordinary call/let, at most -`N` for a constructor product, seven for arithmetic, and `4 + 3*N` for a -match: three wrapper lets, at most `N` arm selectors plus their comparison -level, and at most `2*N` pattern lets and field projections. Each is bounded -by `16*N` for nonempty source, giving the deliberately loose bound -`16*N*N <= 2^48`, below signed -64-bit overflow. Shared projection prefixes do not increase path height. - -For each visit, order `(height, 255 - budget)` lexicographically. Descending -to an expression child decreases height. Extraction at budget one retains the -original fragment but restarts at budget 255, decreasing the second component. -Finite argument lists and pending frames account for the remaining -visits. Thus the traversal terminates in an unbounded-resource model. By the -same induction, each returned body fits its requested budget: a reused node -already fits, rebuilt children fit budget minus one, and an extracted call has -height one. A helper body is normalized before its definition is appended, -so the bound covers all generated helpers, not only authored functions. -Collecting its free bindings preserves the completed body's height. - -This is a source-level audit argument, not a machine-checked certificate or -a guarantee that the selected evaluator has enough allocation/work resources -to finish every admitted compilation. Byte-extent arithmetic is a separate -summary and is not bounded by this height argument. +[representation constructors](../representation/gamma/expressions.gamma) give +atoms height 0 and calls/lets `1 + max(child heights)`. The +[expression serializer](../emission/expressions.gamma) prints that exact +expression-list nesting (declaration and parameter wrappers sit outside the +body). Reuse keeps summaries intact, and capture does not alter the body. + +Height addition cannot overflow for accepted profile-1 source (`N <= 4,194,304` +bytes). Any path has at most `N` authored expression starts. Lowering adds at +most 1 level for a call/let, `N` for a constructor product, 7 for arithmetic, +and `4 + 3*N` for a match (3 wrapper lets, up to `N` arm selectors plus their +comparison level, and up to `2*N` pattern lets and field projections). Each is +bounded by `16*N`, giving the loose bound `16*N*N <= 2^48`, well below signed +64-bit overflow. Shared projection prefixes do not add path height. + +Order each visit lexicographically by `(height, 255 - budget)`. Descending to a +child lowers `height`; extracting at budget 1 keeps the same node but resets +budget to 255, lowering `255 - budget`. Finite argument lists and pending +frames cover the rest, so traversal terminates. By the same induction, every +returned body fits its budget: reused nodes fit, rebuilt children fit +`budget - 1`, and replacement calls have height 1. Each helper body finishes +normalization before its definition is appended, so the bound holds for all +generated helpers too. + +This is a source-level proof, not a machine-checked certificate or a guarantee +that the evaluator has enough heap/time to finish every input. Byte-extent +arithmetic is proved separately. ## Captured bindings -[capture.gamma](capture.gamma) visits the completed fragment and coordinates -three counted lists: direct references, binders owned inside the fragment, and -argument batches from completed extraction helpers. It leaves the body and -binding atoms unchanged. Global call heads and constants are not captures. - -Binding identity makes one final set difference sufficient. Within a produced -function, each identity has one lexical binder and every reference resolves to -it. A free identity therefore cannot denote an unrelated internal binder in a -sibling or initializer. Source identities are declaration starts; generated -identities are marker/coordinate pairs. Equal spellings in disjoint scopes -remain distinct identities. For example, -`(let value Int (let value Int 1 value) value)` owns both identities and has -no free reference. This argument applies to produced plans, not synthetic trees -that reuse an identity for unrelated binders. - -The collection owners are: - -- [capture/calls.gamma](capture/calls.gamma) traverses ordinary arguments. - Only normalization creates generated marker-104 (`$h`) heads. Descendants - finish before their parent's capture, so these calls already carry sorted - unique binding arguments. Collection retains their existing counted lists; - it does not traverse, sort, or copy their elements. +[capture.gamma](capture.gamma) walks each finished fragment and builds three +counted lists: direct references, binders owned inside the fragment, and +argument batches from already-completed descendant helpers. It leaves the body +and binding atoms untouched. Global call heads and constants are never captured. + +Unique binding IDs make one final set difference sufficient. Within a lowered +function, each ID belongs to one binder and every reference resolves to it, so +a free ID can never match an unrelated binder in a sibling or initializer. +Source IDs are declaration byte offsets; generated IDs are marker/coordinate +pairs. Same-named bindings in disjoint scopes have distinct IDs (for example, +`(let value Int (let value Int 1 value) value)` owns both IDs and captures +nothing). This relies on compiler-built plans, not synthetic trees that reuse +one ID across unrelated binders. + +Capture modules: + +- [capture/calls.gamma](capture/calls.gamma) walks ordinary call arguments. + Only normalization creates marker-104 (`$h`) helper heads. Because + descendants finish before parent capture, their replacement calls already + hold sorted unique binding lists; collection keeps those counted lists + directly without walking, sorting, or copying their elements. - [capture/lets.gamma](capture/lets.gamma) records the binder and visits both - children. Identity-based subtraction replaces saved lexical scope spines. + children; ID subtraction replaces saved lexical scope spines. - [capture/bindings.gamma](capture/bindings.gamma) orders generated bindings - first by marker/coordinate, then source bindings by declaration start. - It never compares pair provenance or source spelling. -- [capture/sets.gamma](capture/sets.gamma) sorts only newly encountered references - and owned binders, unions sorted batches, and subtracts owned identities. - Merge and difference copy consumed prefixes and reuse untouched tails. - Counted-list merge sort uses logarithmic non-tail depth; its element walks - are tail calls. It introduces no tree, map, allocator, or profile. -- [capture/result.gamma](capture/result.gamma) composes those operations. - With no owned binders, it returns the merged batch unchanged. - -One sorted unique list supplies both parameters and replacement-call arguments. -The same permutation is applied to both; all arguments are already-bound atoms, -so reordering them moves no computation or trap. Initializers remain exactly -where lowering placed them. Pair-bearing values keep their provenance. - -Original spelling is safe too. A free binding was active throughout the extracted -fragment. Delta forbids active shadowing, so internal binders cannot conflict -with its spelling, and simultaneously active captures have distinct spellings. -Lowering's source-forbidden `$` names use distinct markers and coordinates. -Each Gamma function is validated independently; capture does not follow global -helper definitions. Only helper names receive fresh `$hN` identities. -Names are allocated in extraction order; definitions are appended in deterministic -completion order, with inner helpers possibly preceding their parents. + first by marker/coordinate, then source bindings by declaration offset, never + inspecting pair addresses or source spellings. +- [capture/sets.gamma](capture/sets.gamma) sorts newly seen references and + owned binders, unions sorted batches, and subtracts owned IDs. Merge and + difference copy only consumed prefixes and share untouched tails. Merge sort + uses logarithmic non-tail depth with tail-recursive element walks. +- [capture/result.gamma](capture/result.gamma) ties these steps together, + returning the merged batch directly when there are no owned binders. + +One sorted unique list supplies both helper parameters and replacement-call +arguments in the same order. Because every argument is an already-bound atom, +reordering moves no computation or trap; initializers stay where lowering +placed them, and pair values keep their identity. + +Original spellings are also safe. Every free binding was active throughout the +fragment: Delta forbids shadowing active locals, so no internal binder can +clash with its spelling, and active captures have distinct spellings. Generated +`$` names use distinct markers and coordinates. Each Gamma function validates +independently, and capture never follows global helper calls. Only helper names +get fresh `$hN` IDs, assigned in extraction order while definitions append in +completion order (inner helpers may precede parents). ### Capture allocation ownership -Splitting descendants before collection avoids rebuilding oversized tails. -Reusing original atoms and bodies avoids fresh parameter atoms and renaming -maps. Batching additionally avoids traversing and rediscovering every reference -in a completed helper's argument list. These are separate changes; none alone -establishes a whole-producer linear bound. - -For the current counted-list implementation, in pairs: - -- Starting a collection allocates three; adding a direct reference allocates - three; adding an owned binder or a completed batch allocates four. -- A nonfinal ordinary argument allocates three continuation/payload pairs; - a let continuation allocates two. -- Union emitting `q` entries allocates `2q + 1`; difference copying - `p` surviving entries allocates `2p + 1`. Unconsumed tails stay shared. -- Sorting `n >= 1` entries allocates at most - `2.5*n*ceil(log2(n)) + 3*n - 2` pairs: at most `2.5*n` per recursion level - for emitted entries, reversals, and split prefixes, plus at most two pairs - per internal node for the split result and union join and one per leaf for - the base result. An earlier statement of this bound used a `+1` linear - coefficient; the split-prefix pair and the union join make the linear term - `3*n - 2` (for example `n = 4` allocates 30 pairs, not 24). Existing helper - batches are not sorted, and an empty list still allocates its one-pair - counted result. - -`capture_finish` prepends the fragment's sorted direct references to its `k` -completed helper batches and merges the `k + 1` sorted lists through -`capture_merge_all`, then subtracts owned binders once. Each tail pass unions -adjacent sorted lists pairwise; a surviving list feeds exactly one union in the -next pass, so an entry occurrence is emitted at most once per pass and at most -`ceil(log2(k + 1))` passes run before one sorted union remains. Union is -associative and commutative on sorted unique lists, so the result is the same -sorted batch the earlier left fold produced; every receipt byte is unchanged. -With `T = R + E` total entry occurrences across the fragment's sorted -references and `k` batches, one collection's merges and input prepend -therefore allocate at most -`(2*T + 2)*ceil(log2(k + 1)) + 2*(k + 1) + 1` pairs: two per emitted entry -plus join, one survivor cons and pass record per pass, and the two-pair input -prepend. When the fragment owns `O` binders, sorting them and running the -final difference add at most `(2.5*ceil(log2(O)) + 3)*O + 2*T + 1` pairs: the -difference is one further pass emitting at most `T` survivors. The previous -left fold's `k*d` product — many batches each rescanning an accumulated union -of up to `d` distinct bindings — is replaced by this per-occurrence -logarithmic term. `d <= T` remains unbounded by the 68,608 -simultaneously-active-environment allowance: fragment-owned binders can be -numerous even though the difference removes them once. - -The aggregate is now closed by the same incidence charge the -[emission audit](../emission/README.md#reachable-byte-count-bound) derives. -A collection runs once per extraction; authored definitions are never -captured. Collections visit disjoint fragment interiors: each collection's -direct references are distinct local-reference occurrences, so -`sum(R) <= 32*N`, and fragment-owned binders are visited only by their -innermost collection, so `sum(O) <= G_binding <= 40*S + 15`: literal -constructors add no binders. Each completed helper -batch is prepended into exactly one parent collection, so `sum(k) <= J`, and -`sum(E)` is the nested helpers' parameter totals — forwarded capture -incidences bounded by the injective `(origin, ancestor cut)` charge at -`C <= R*L <= 512*N*N`. Hence +Splitting descendants first avoids rebuilding oversized tails; reusing atoms +and bodies avoids renaming maps; batching skips re-walking completed helper +argument lists. None of these alone proves a linear whole-compiler bound. + +Exact pair costs for the counted-list implementation: + +- Starting a collection: 3 pairs; adding a direct reference: 3; adding an owned + binder or completed batch: 4. +- Nonfinal ordinary argument continuation/payload: 3 pairs; let continuation: 2. +- Union emitting `q` entries: `2q + 1`; difference copying `p` survivors: + `2p + 1` (unconsumed tails stay shared). +- Sorting `n >= 1` entries: at most `2.5*n*ceil(log2(n)) + 3*n - 2` pairs + (`2.5*n` per recursion level for emitted entries, reversals, and splits, plus + 2 per internal node for split/join and 1 per leaf; an earlier note stated a + `+1` linear term, but split prefixes and union joins make it `3*n - 2`, e.g. + 30 pairs for `n = 4` instead of 24). Existing helper batches are not + re-sorted; an empty list still allocates 1 counted-result pair. + +`capture_finish` prepends sorted direct references to the `k` completed helper +batches, merges the `k + 1` sorted lists pairwise via `capture_merge_all`, and +subtracts owned binders once. Each tail pass unions adjacent pairs, emitting +each entry occurrence at most once per pass over at most `ceil(log2(k + 1))` +passes. Because sorted-list union is associative and commutative, this produces +the exact same sorted batch and output bytes as the old left fold. With +`T = R + E` total entry occurrences across references and `k` batches, merging +and prepending allocate at most +`(2*T + 2)*ceil(log2(k + 1)) + 2*(k + 1) + 1` pairs. Sorting `O` owned binders +and subtracting once add at most `(2.5*ceil(log2(O)) + 3)*O + 2*T + 1` pairs. +This replaces the old left fold's `k*d` rescanning cost with a logarithmic +per-occurrence factor. Note `d` (with `d <= T`) is not capped by the 68,608 active-local +limit, because a fragment can own many disjoint internal binders before the +final difference removes them. + +The program-wide aggregate uses the incidence bound from the +[emission audit](../emission/README.md#reachable-byte-count-bound). Collection +runs once per extraction (never on authored functions) over disjoint interiors: +`sum(R) <= 32*N`, owned binders satisfy `sum(O) <= G_binding <= 40*S + 15` +(byte literals add no binders), each helper batch feeds one parent (`sum(k) <= J`), +and `sum(E)` is bounded by the injective `(origin, ancestor cut)` charge +`C <= R*L <= 512*N*N`. Thus: ```text sum(T) = sum(R) + sum(E) <= 32*N + 512*N*N ``` -Summing the traversal bullets and the complete finish bound over at most -`J <= 64*N*N <= 2^50` collections — with `ceil(log2(R)) <= 27`, -`ceil(log2(G_binding)) <= 25`, and `ceil(log2(J + 1)) <= 51` under the admitted -extents — bounds program-wide capture allocation by +Summing across at most `J <= 64*N*N <= 2^50` collections (with +`ceil(log2(R)) <= 27`, `ceil(log2(G_binding)) <= 25`, and +`ceil(log2(J + 1)) <= 51`) yields: ```text capture pairs <= 60,672*N*N + 5,680*N + 2,980*S + 1,118 + 128*(5*Decoded + 2*Literals) ``` -Here `Decoded` counts decoded literal bytes and `Literals` counts literals; -these are distinct from parameter/let quantities in the source-occurrence -ledger. Overall `G <= 40*S + 15 + 5*Decoded + 2*Literals` can exceed `2^25`; -only the binder-bearing bound is used for the owned-binder sort above. - -Each extraction root is an original plan occurrence. Its helper body restarts -with budget 255 and its replacement call fits budget 1, so that root cannot be -extracted again. Thus `J <= G <= 47*N + 15 <= 64*N*N` for nonempty source, -using `S <= N`, `Decoded <= N`, and `Literals <= N`; the 51-pass bound remains -conservative. Literal subtrees contain no direct references or owned binders, -so they add no capture entries or forwarded lexical incidences. Their added -cost is constant-degree traversal, collection/empty-list metadata, and merging -empty helper batches. Charging 128 pairs per additional literal plan occurrence -covers the fixed metadata, at most two argument continuations, and at most 51 -empty-list merge passes. This deliberately loose charge is kept explicit rather -than hiding literal expansion in the one syntax atom. - -This coarse quadratic envelope already exceeds the 3,422,447,206-pair arena at -`N = 238` because it omits the 254-level extraction spacing, the 65,536 -active-local bound, and the syntax-ledger budget. The +Here `Decoded` is decoded literal bytes and `Literals` is literal count. Full +plan size `G <= 40*S + 15 + 5*Decoded + 2*Literals` can exceed `2^25`, so only +the binder-bearing bound enters the owned-binder sort term. + +Each extraction root is an original plan occurrence; its helper restarts at +budget 255 and its replacement call fits budget 1, so it can never be extracted +twice. Thus `J <= G <= 47*N + 15 <= 64*N*N` (for `S <= N`, `Decoded <= N`, +`Literals <= N`), keeping 51 passes conservative. Literal trees have no +references or owned binders and only pay constant-degree traversal, empty +metadata, and empty-batch merges — conservatively charged at 128 pairs per +extra literal plan node so literal expansion stays explicit. + +That coarse quadratic bound crosses the 3,422,447,206-pair arena at `N = 238` +because it ignores 254-level cut spacing, the 65,536 active-local cap, and the +syntax-ledger limit. The [cumulative pair containment proof](../boundary/execution_storage.md#cumulative-pair-containment) -replaces it with a Heavy-Light decomposition of the extraction-cut forest -(`H <= 1,251` heavy edges with Jensen's inequality on `capture_merge_all`) and -single-spend per-construct accounting, proving every admitted profile-1 -composition allocates at most 3,092,641,319 pairs — 90.36% of the -3,422,447,206-pair arena. - -Earlier checking/lowering frames and rebuilt nodes also allocate or perform -work; the [checking audit](../checking/README.md#traversal-and-rebuild-pairs) -and [lowering audit](../lowering/README.md#traversal-and-rebuild-pairs) charge -each of those pairs per source occurrence, including the produced plan size -`G <= 40*S + 15 + 5*Decoded + 2*Literals` that this section's `45*G + 7*F + 1` consumes. Emission -preflight allocates no pairs, and its publication traversal is separately -bounded below the pair arena by the admitted payload extent (see -[emission](../emission/README.md#publication-traversal-pairs)). The -[traversal and rebuild accounting](#traversal-and-rebuild-pairs) below charges -the normalizer machine per plan-node occurrence. The lexical trie reused by -lowering is another construction pass, not free reuse of checking's stored -environment; its cumulative inserts are charged in the -[name-trie audit](../checking/names/README.md#pair-accounting). These -formulas are source-level accounting, not measured arena peaks or a complete -resource proof. +replaces it with Heavy-Light decomposition (`H <= 1,251` heavy edges plus +Jensen's inequality on `capture_merge_all`) and single-spend per-construct +accounting, proving every profile-1 compile uses at most 3,092,641,319 pairs +(90.36% of the 3,422,447,206-pair arena). + +Checking and lowering pair costs are audited in +[checking](../checking/README.md#traversal-and-rebuild-pairs) and +[lowering](../lowering/README.md#traversal-and-rebuild-pairs), supplying +`G <= 40*S + 15 + 5*Decoded + 2*Literals` to this section's `45*G + 7*F + 1`. +Emission preflight allocates zero pairs, and publication traversal is bounded +in [emission](../emission/README.md#publication-traversal-pairs). Normalizer +frames and rebuilds are counted [below](#traversal-and-rebuild-pairs), and +lowering's lexical-trie inserts are counted in the +[name-trie audit](../checking/names/README.md#pair-accounting). #### Full-width payload refusal -The regression keeps the full-width control's declaration, pattern, and identity -entry, but changes `select` to reconstruct `(Wide field00000 ... field65534)`. -Its 1,704,033 bytes have SHA-256 -`c69598944c34dc0f37187fb67bcf5624b021ac393a8cd8d91f7b967ab84a0945`. -Expression depth is three and active locals are 65,536. Source and syntax fit -their independent provisions. The selected outcome is exact payload refusal, -not publication of a larger Gamma artifact. - -The preceding unbatched collector's nonfinal argument continuation allocated -**five** pairs (two frame, three payload), not six. Counting only product cuts -2 through 257 gives -`5 * sum(j=2..257, 65,535 - 254*j - 1) = 41,780,480` pairs, already above -the retired 40,265,318-pair arena (the current profile allocates -3,422,447,206 pairs). Its first 257 product cuts also required at least -183,609,879,296 binding comparisons. These are source-derived bounds, not -observed evaluator exhaustion or measured durations. - -In the batched route, product helpers prepend small lower-coordinate field -prefixes to shared suffix batches. Generated-first ordering permits payload -bindings to join at the head. Pattern helpers subtract their owned suffix -once, copying the retained field prefix once rather than once per binder. -This removes the demonstrated capture recurrences without a source-specific -accelerator. Lowering separately reuses the existing exact-name trie instead -of making 2,147,450,880 linear binding comparisons for this source. - -The exact requested payload count is independently derived from serialization, -not from a resource lower bound or compiler-produced count: +This stress test keeps the full-width control's declaration, pattern, and +entry, but makes `select` reconstruct `(Wide field00000 ... field65534)` +(1,704,033 bytes, SHA-256 +`c69598944c34dc0f37187fb67bcf5624b021ac393a8cd8d91f7b967ab84a0945`). Expression +depth is 3, active locals are 65,536, and source and syntax fit their limits; +the expected result is exact payload refusal. + +The old unbatched collector's nonfinal argument frame cost **five** pairs (2 +frame + 3 payload), not 6. Just product cuts 2..257 used +`5 * sum(j=2..257, 65,535 - 254*j - 1) = 41,780,480` pairs — exceeding the +retired 40,265,318-pair arena (the current arena holds 3,422,447,206 pairs) — +and at least 183,609,879,296 binding comparisons. + +With batching, product helpers prepend small field prefixes to shared suffix +batches, generated-first order joins payload bindings at the head, and pattern +helpers subtract their owned suffix once (copying the prefix once rather than +per binder). Lowering separately uses the exact-name trie instead of +2,147,450,880 linear comparisons. + +Exact requested payload size derived directly from serialization: | Component | Bytes | | --- | ---: | @@ -290,81 +238,61 @@ not from a resource lower bound or compiler-produced count: | Total requested payload | 477,934,574 | Three match-wrapper lets leave budget 252. Projection helpers have even IDs -0..514; binding-chain helpers have odd IDs 1..515 and capture field prefixes -of length `251 + 254*j`. The final chain starts at field 65,529; its six lets -leave the constructor budget 249. Product helpers 516..773 capture suffixes -starting at `247 + 254*j`. Each family has 258 members (`j = 0..257`). -A nonempty helper adds -`16 + 2*name_length + 2*sum(binding_name_lengths) + 8*arity` bytes, -including its definition LF. Capture order changes none of these lengths. +0..514; binding-chain helpers have odd IDs 1..515 and capture prefixes of +length `251 + 254*j`. The final chain starts at field 65,529, leaving budget +249 for the constructor. Product helpers 516..773 capture suffixes starting at +`247 + 254*j`. Each family has 258 members (`j = 0..257`). Each nonempty helper +adds `16 + 2*name_length + 2*sum(binding_name_lengths) + 8*arity` bytes +(including LF), independent of capture order. The [opt-in resource control](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/resource-boundary/README.md) -uses this exact source and a literal 40-byte DCOUT resource-12 expectation: -coordinate and limit 16,777,212, requested 477,934,574. Its host watchdog is -not a language limit. A successful refusal still does not close allocation -containment for all admitted programs or the Delta refinement edge. - -Canonical compiler SHA-256 -`fbcb9e17b7ce0c75849136086bc5a4b6df4264054be72b5aae6d70325f9d0929` -completed this exact DCREQ/profile-1 fixture on macOS arm64 under an lldb -halt breakpoint: status 2, exactly the expected 40-byte frame, and empty -stderr. The frame's SHA-256 is -`c95d55ef5b5c741bad050d7b870bb66fa9989c44e8e4b5a1e15f6276e74d47d5`. The same -observation read the evaluator's immutable-pair cursor at halt — 36,033,367 -cumulative pairs, 89.5% of the 40,265,318-pair arena — recorded in the -[whole-producer study](../boundary/execution_storage.md#whole-producer-pair-study-measured). -The instrumented run took about 30.5 hours on a heavily loaded host, so it is -completion and allocation evidence for one stress source, not a -bootstrap-chain duration or a controlled speedup comparison. The earlier -direct run of the previous canonical closure finished the identical fixture -in 4,855.704 seconds; the support-member manifest change moved the expected -frame, so that duration does not carry to this compiler. +checks this source against the exact 40-byte DCOUT resource-12 frame: +coordinate and limit 16,777,212, requested 477,934,574. + +Compiler SHA-256 +`fbcb9e17b7ce0c75849136086bc5a4b6df4264054be72b5aae6d70325f9d0929` passed this +DCREQ/profile-1 test on macOS arm64 under an lldb halt breakpoint: status 2, +empty stderr, and the exact 40-byte frame (SHA-256 +`c95d55ef5b5c741bad050d7b870bb66fa9989c44e8e4b5a1e15f6276e74d47d5`), using +36,033,367 cumulative pairs (89.5% of the retired 40,265,318-pair arena; see +[whole-producer study](../boundary/execution_storage.md#whole-producer-pair-study-measured)). +The instrumented run took ~30.5 hours on a heavily loaded host (a prior +uninstrumented run on the older closure took 4,855.704 seconds, before the +support-member manifest changed the expected frame). ### Static validation-environment bound -The selected Delta frontend permits at most 65,536 simultaneously active -parameters, let bindings, and pattern bindings. Lowering preserves their scopes. -Only [checked arithmetic](../lowering/arithmetic.gamma) and -[matches](../lowering/matches.gamma) add local binders: three per arithmetic -expression, three per payload match, or one per nullary match. Products, calls, -and field projections introduce no binders; pattern lets correspond to authored -bindings. Each active generated wrapper belongs to an expression on one source -nesting path, whose admitted depth is at most 1,024. Thus an unnormalized body's -active environment is conservatively bounded by -`65,536 + 3 * 1,024 = 68,608` bindings. - -Extraction preserves that bound. Its distinct parameters replace a subset of -the bindings already active outside the fragment; they do not accompany a -second copy of that environment. Bindings introduced inside the fragment retain -their scopes and are not parameters. This mapping is injective and composes -through nested extraction. An inner helper collects original bindings before -the outer helper is closed; outer collection consumes its argument batch, not its -global head or completed definition. Sibling scopes and let initializers do not retain -bindings introduced only in another child. - -Gamma validates each function independently, restoring the environment after -each let and resetting it between functions. Every authored or extracted body -therefore fits its 131,072-row validation environment. This is a conservative -source-level audit argument, not a claim that 68,608 is attainable or a checked -edge certificate. It does not bound aggregate bindings during non-tail runtime -calls. Fixed runtime and adapter definitions are separate from the transform -and must fit independently. Lowering's shared projection definition likewise -fits independently with two parameters and no local binders. +The Delta frontend allows at most 65,536 simultaneously active parameters, let +bindings, and pattern bindings. Lowering preserves scopes; only +[checked arithmetic](../lowering/arithmetic.gamma) (3 binders) and +[matches](../lowering/matches.gamma) (3 per payload match, 1 per nullary match) +add local binders. Products, calls, and field projections add none; pattern +lets match authored bindings. Because active wrappers sit along a single source +path of depth at most 1,024, an unnormalized body has at most +`65,536 + 3 * 1,024 = 68,608` active bindings. + +Extraction preserves this cap: helper parameters replace a subset of already +active outer bindings rather than duplicating them, internal binders stay +scoped inside the helper, and nested extraction composes injectively (outer +collection reads an inner helper's argument batch, never its body). Sibling +scopes and let initializers never retain bindings from other children. + +Gamma validates each function separately and resets its environment between +functions, so every authored or extracted body fits Gamma's 131,072-row +validation environment. This conservative audit does not bound runtime +non-tail call stacks; fixed runtime/adapter files and lowering's 2-parameter +projection helper fit independently. ## Traversal and rebuild pairs -The visit/resume machine's frames and rebuilt nodes are charged separately -from the capture collections above. Each plan node is visited at most twice -and descended at most once: `normalization_visit` resumes a node whose -recorded height fits its remaining budget and otherwise descends it once; a -node still over height at budget one is revisited once under a fresh 255 -budget as an extraction root, which replaces descent at the shallow budget -rather than adding to it. The extracted node's children are first visited -during that fresh-budget traversal, the replacement call's height one can -never descend, and rebuilt nodes are returned through frames without being -revisited. So every frame, cons, spine cell, and rebuild below is allocated at -most once per plan-node occurrence, and each extraction root is a distinct -occurrence. +Normalizer frames and rebuilt nodes are charged separately from capture. Each +plan node is visited at most twice and descended at most once: +`normalization_visit` returns fitting nodes immediately, otherwise descends +once; at budget 1 an over-height node restarts as an extraction root at budget +255 instead of descending at budget 1. Children are first visited under that +fresh budget, replacement calls (height 1) never descend, and rebuilt nodes are +never revisited. Every frame, cons, spine cell, and rebuild below therefore +occurs at most once per plan-node occurrence. | Site | Pairs | Charged per | | --- | ---: | --- | @@ -380,60 +308,46 @@ occurrence. | Helper-list and definition-spine reversal | 1 | helper / authored definition | | `gamma_program` root | 1 | program | -A descended call with `a` arguments therefore allocates `9*a + 6` pairs, a -descended let allocates 13, and an atom allocates none. With `G` node -occurrences in the completed lowering plan, `J <= G` extraction helpers, and -`F <= 32,768` authored function rows, the machine allocates at most +A descended call with `a` arguments allocates `9*a + 6` pairs, a descended let +allocates 13, and an atom allocates none. For `G` plan-node occurrences, +`J <= G` helpers, `F <= 32,768` authored functions, and `A`, `C`, and `L` +argument edges and descended call/let occurrences (`A + C + L <= 2*G`), the +machine allocates at most: ```text 9*A + 6*C + 13*L + 22*J + 6*F + J + F + 1 <= 45*G + 7*F + 1 ``` -pairs, where `A`, `C`, and `L` are argument edges and descended call and let -occurrences, with `A + C + L <= 2*G`. This charges every normalizer frame and -rebuild to the plan being traversed. `G` is produced by lowering, so the bound -reduces the normalizer term to the earlier-phase plan size; it is not a fixed -byte budget. The capture merge term's aggregate `T` is separately closed by -the incidence charge in the -[capture allocation ownership](#capture-allocation-ownership) section above. +This reduces normalizer machine pairs to lowering's plan size `G`; the capture +merge aggregate `T` is bounded separately under +[capture allocation ownership](#capture-allocation-ownership). ## Phase and receipt boundaries -`prepare_admitted_source` continues to return the pre-normalization plan. -The private lowering-height diagnostic therefore observes the same expanded -heights, including heights above 255. Normal compilation calls -`normalize_program` before `emit_checked_program` publishes any receipt bytes. -The fixed byte helpers and profile adapters retain their existing text. +`prepare_admitted_source` still returns the pre-normalization plan so the +lowering-height diagnostic can inspect raw heights above 255. Normal +compilation runs `normalize_program` before `emit_checked_program` writes +output. Fixed byte helpers and profile adapters stay unchanged. -If every authored body already fits 255, no helper or rewritten subtree is -needed and the existing receipt stays byte-identical. Over-height programs -receive generated definitions as part of the same ordinary Gamma program; -this is not another evaluator, runtime representation, or application profile. +When every authored body already fits 255, no helpers or rewrites occur and +output is byte-identical. Over-height programs simply gain ordinary Gamma +definitions in the same output program. ## Remaining resources -Generated helpers are ordinary declarations, so the emitted program's -admission bounds are the same bounds the rest of the receipt already carries: -the profile-1 16,777,212-byte payload extent places its source under the -evaluator's request extent and, at least eight bytes per completed -declaration, under its 2,097,152-row function table; this transform enforces -the 255-list body bound; and the -[static environment audit](#static-validation-environment-bound) holds every -generated body under the 68,608-binding allowance, below the evaluator's -131,072-row validation environment. Profile 2 can admit larger Gamma receipts, -so its function count must fit the evaluator census separately. Calls -outside tail position can add live contexts to the separate 256-context limit, -and plan construction, captures, and execution consume finite immutable -storage; those are resources of the generated program's own run, not compiler -outcomes. The transform does not introduce a new language refusal, increase a -selected profile bound, or manufacture compiler-owned resource evidence. - -Exact body heights, capture behavior, evaluation and trap order, existing -receipts, and actual Epsilon reconstruction remain validation obligations. +Generated helpers are ordinary Gamma declarations governed by the same +admission limits: profile 1's 16,777,212-byte payload cap stays under Gamma's +request limit and (at least 8 bytes per declaration) under its 2,097,152-row +function table; normalization enforces the 255-list body cap; and the +[static environment audit](#static-validation-environment-bound) keeps every +body under 68,608 bindings (inside Gamma's 131,072-row limit). Profile 2's +larger receipts must fit Gamma's function table separately. Non-tail calls and +heap allocation during a generated program's run belong to that program, not +the compiler. Normalization adds no new failure codes or profile limits. + The [normalization gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/normalization/README.md) -compares production-plan observations with authored expectations, then compiles -and executes the generated Gamma. The separate +verifies body heights, capture behavior, evaluation/trap order, and generated +execution; the [lowering-plan gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/lowering-plan/README.md) -retains its pre-normalization measurements. -The complete Delta edge remains open even when every generated body satisfies -the nesting bound. +keeps its pre-normalization checks. Satisfying the 255-list nesting cap does +not by itself close the full Delta bootstrap edge. diff --git a/bootstrap/delta/compiler/implementation/representation/README.md b/bootstrap/delta/compiler/implementation/representation/README.md index e3953738ceba..168df22552cf 100644 --- a/bootstrap/delta/compiler/implementation/representation/README.md +++ b/bootstrap/delta/compiler/implementation/representation/README.md @@ -1,64 +1,59 @@ # Expanded Gamma program -Start at [gamma.gamma](gamma.gamma). A program owns a counted, authored-order -list of definitions. Each definition retains its function name, ordered -parameter binding atoms, and fully expanded Gamma body. The existing fixed -byte helpers and profile adapters remain separately selected publication text; -they are not reconstructed as authored-function plans. +Start at [gamma.gamma](gamma.gamma). A program holds a counted, authored-order +list of definitions, each with its function name, ordered parameter binding +atoms, and fully expanded Gamma body. Fixed byte helpers and profile adapters +are emitted separately rather than built as function plans. [gamma/expressions.gamma](gamma/expressions.gamma) defines expression nodes and -their constructors. [gamma/names.gamma](gamma/names.gamma) separates admitted -source atoms, source binding identities, function names, generated names, -integer constants, and fixed words. -[gamma/primitives.gamma](gamma/primitives.gamma) builds ordinary Gamma primitive -applications from those nodes; it does not write a textual template. - -An expression retains its kind, expanded expression-list height, serialization -summaries, and kind-specific payload. Atoms have height zero. A call adds one -to the maximum height of its arguments; a let adds one to the maximum of its -initializer and body. This counts generated Gamma lists, including lowering wrappers, not -Delta expression levels or compiler continuation frames. Reused nodes remain -immutable snapshots; height describes their expansion at each occurrence. - -The byte extent likewise describes one complete serialized occurrence, not -unique DAG storage. Construction derives it once from the -[serializer's shared formatting helpers](../emission/extents.gamma) and already -constructed child extents. Those count-only calls write no bytes and make no -Delta lowering decisions. Rebuilding a node after helper extraction refreshes -the extent automatically; free-binding collection retains the completed body -and its summaries unchanged. Checked addition prevents wrapped -summaries. The extent keeps payload preflight from repeatedly unfolding shared -projection tails. Function spelling includes the -selected compilation profile; definition framing, fixed runtime text, and the -entry-owned final LF remain outside expression extents. - -The other serialization summary is an optional compact prefix for unary calls -with short fixed-word heads. [Its emission owner](../emission/unary_words.gamma) -derives it from the call shape and exact visible word bytes; no primitive is -special-cased. Zero selects the ordinary serializer. The two summaries together -cost two immutable pairs per node beyond kind, height, and payload. Accessors -keep that private layout out of lowering and normalization. Reconstruction -refreshes both summaries, while reused nodes retain their immutable values. - -Admitted source atom payloads retain exact source spans through retained-node -accessors. A serializer may copy those bytes; it does not traverse Delta -expressions, classify source constructs, or resolve names. +constructors. [gamma/names.gamma](gamma/names.gamma) separates source atoms, +source binding IDs, function names, generated names, integer constants, and +fixed words. [gamma/primitives.gamma](gamma/primitives.gamma) builds Gamma +primitive calls from those nodes instead of text templates. + +Each expression stores its kind, expanded expression-list height, two +serialization summaries, and kind-specific payload. Atoms have height 0. A call +adds 1 to the maximum height of its arguments; a let adds 1 to the maximum of +its initializer and body. This counts generated Gamma lists, including lowering +wrappers, not Delta expression depth or compiler continuation frames. Reused +nodes are immutable; height records their expanded nesting at each use. + +The byte-extent summary records one complete serialized occurrence, not unique +DAG storage. Constructors compute it once from the +[serializer's shared formatting helpers](../emission/extents.gamma) and child +extents, without writing bytes or running Delta lowering. Rebuilding a node +after helper extraction refreshes the extent automatically; free-binding +collection keeps the completed body and its summaries unchanged. Checked +addition prevents wraparound. Caching this extent stops payload preflight from +repeatedly unfolding shared projection tails. Function spelling depends on the +compilation profile; definition framing, fixed runtime text, and the final LF +stay outside expression extents. + +The second summary is an optional compact prefix for unary calls with short +fixed-word heads. [Its emission helper](../emission/unary_words.gamma) derives +it from the call shape and visible word bytes without special-casing any +primitive. Zero selects ordinary serialization. Both summaries add two +immutable pairs per node beyond kind, height, and payload. Accessors hide this +layout from lowering and normalization. Rebuilt nodes refresh both summaries; +reused nodes keep theirs. + +Source atom payloads hold exact source spans via retained-node accessors. The +serializer copies those bytes directly without walking Delta expressions, +classifying constructs, or resolving names. Source parameters, lets, and pattern binders receive binding atoms. Every -lowered reference reuses its established binding atom, so equal spellings in -disjoint scopes do not erase declaration identity. Lowering-generated bindings -retain an explicit marker and source coordinate. Normalization uses that same -atom form with a marker and program-wide allocated identity for fresh helper -names. Helper parameters and call arguments share the ordered original binding -atoms; the [normalizer's scope argument](../normalization/README.md#captured-bindings) -establishes their spelling safety in independently scoped Gamma functions. -Binding references reuse their established atom; no -comparison observes the numeric provenance of a Gamma pair reference. - -This representation is shared by source-dependent lowering, -[body-height normalization](../normalization/README.md), and Gamma -serialization. Normalization consumes its explicit heights and binding atoms -and produces another program in the same representation. The complete -normalized plan exists before receipt publication. This representation does -not itself establish complete Gamma-profile admission, compiler-owned resource -accounting, or internal-failure publication. +lowered reference reuses its binding atom, so identical names in disjoint scopes +keep distinct declaration identities. Lowering-generated bindings carry a marker +and source coordinate; normalization uses the same atom form with a marker and +program-wide ID for fresh helper names. Helper parameters and call arguments +share the ordered original binding atoms, whose spelling safety in independently +scoped Gamma functions is shown in the +[normalizer's scope proof](../normalization/README.md#captured-bindings). No +comparison inspects the numeric address of a Gamma pair reference. + +Lowering, [body-height normalization](../normalization/README.md), and Gamma +serialization all share this representation. Normalization reads heights and +binding atoms and produces another program in the same form. The complete +normalized plan exists before any output is written. The representation alone +does not prove full Gamma-profile acceptance, compiler resource accounting, or +internal-failure reporting. diff --git a/bootstrap/epsilon/LANGUAGE.md b/bootstrap/epsilon/LANGUAGE.md index 35c3be6281ce..79729c98214e 100644 --- a/bootstrap/epsilon/LANGUAGE.md +++ b/bootstrap/epsilon/LANGUAGE.md @@ -1,25 +1,23 @@ # Epsilon v1 language contract -Epsilon is the closed compiler-host language used to author the first full Omega -compiler, `D`. Its spelling is deliberately familiar to Omega authors, but its -meaning is independent and completely specified here. An Omega document, a -compiler implementation, a historical source file, or an accepted program -cannot add to or amend this contract. +Epsilon is the small compiler-host language used to write the first full Omega +compiler, `D`. Its syntax resembles Omega, but its semantics are independent and +fully specified here. No Omega document, compiler implementation, old source +file, or accepted program can amend this specification. -Epsilon v1 is intentionally small. It has finite nominal data, fixed storage, -checked scalar operations, deterministic state-machine control, and one sealed -byte-I/O capability. It has no packages, heap, proof language, dependent types, -or implicit host services. +Epsilon v1 has finite nominal data, fixed storage, checked scalar math, +deterministic state-machine control, and one sealed byte-I/O capability. It has +no packages, heap, proof language, dependent types, or ambient host services. ## 1. Source and judgments -An Epsilon source closure is presented to the compiler as one finite byte string. -Package resolution and closure membership happen before Epsilon checking. The -closure owner records every member by stable source identity, byte length, and -SHA-256 digest, then packs the members in stable source-identity order. Member -paths are diagnostic locations only; they are not Epsilon names or namespaces. +The compiler receives an Epsilon source closure as one finite byte sequence. +Package resolution and file collection happen beforehand: the caller records +each file's stable ID, byte length, and SHA-256 hash, then concatenates the +files in stable ID order. File paths are for diagnostics only, not Epsilon names +or namespaces. -Epsilon has two judgments: +Epsilon defines two semantic functions: ```text CheckEpsilon(source) @@ -32,59 +30,58 @@ RunEpsilon(program, stdin) | Diverges(stdout_prefixes) ``` -`Reject` is a checking result and occurs before execution. `Exit`, `Trap`, and -`Diverges` are execution results. `stdout` and `stdout_prefix` are exact byte -sequences; `stdout_prefixes` is the ordered finite-prefix trace of a divergent -execution. Divergence means an actual infinite execution, not that a bounded -evaluator ran out of steps. +`Reject` happens during static checking before execution starts. `Exit`, `Trap`, +and `Diverges` are runtime outcomes. `stdout` and `stdout_prefix` are exact byte +sequences; `stdout_prefixes` is the ordered trace of finite prefixes written by +a nonterminating run. Divergence means actual infinite execution, not hitting an +evaluator step limit. -`Incomplete` and `InternalFailure` are outcomes of a compiler, checker, or -bounded evaluator, not Epsilon program results. They grant no Epsilon judgment and -publish no partial artifact. Epsilon v1 has no implicit allocating operation and -therefore no language-level `Exhausted` result. +`Incomplete` and `InternalFailure` are compiler or evaluator outcomes, never +Epsilon program results; they grant no acceptance and publish no partial output. +Because Epsilon v1 has no implicit allocation, it has no language-level +`Exhausted` result. ## 2. Source bytes and tokens -Epsilon source obeys the chain-wide closed textual-ASCII envelope: +Epsilon source accepts only the closed textual-ASCII byte set: ```text HT (0x09), LF (0x0A), CR (0x0D), and printable ASCII (0x20..0x7E) ``` -Every other byte rejects before tokenization at its exact packed byte offset. -There is no source decoding, Unicode normalization, locale-sensitive -classification, or newline rewriting. +Any other byte fails before tokenization at its packed byte offset. Epsilon +performs no encoding conversion, Unicode normalization, locale checks, or +newline rewriting. -Space, tab, CR, and LF are whitespace. A `//` comment continues through the -next CR, LF, or source end. Identifiers match -`[A-Za-z_][A-Za-z0-9_]*`. Decimal digits are exactly `0` through `9`. +Space, tab, CR, and LF are whitespace. A `//` comment runs to the next CR, LF, +or end of input. Identifiers match `[A-Za-z_][A-Za-z0-9_]*`. Decimal digits are +`0` through `9`. -Character literals denote one byte. Their direct content is one printable -ASCII byte other than quote or backslash. String literals denote immutable byte -sequences and admit printable ASCII other than quote and backslash. Both forms -use this closed escape set: +Character literals denote one byte and allow any printable ASCII character +except quote or backslash. String literals denote immutable byte sequences with +the same character set. Both allow only these escapes: ```text \n \r \t \" \\ \xHH ``` -`HH` is exactly two hexadecimal ASCII digits. Unknown escapes reject. -Unterminated character or string literals report their opening quote. +`HH` is exactly two ASCII hex digits. Any other escape rejects. Unterminated +character or string literals report their opening quote offset. -The universally reserved words are: +Reserved words are: ```text boundary trait data case machine transition let return assert true false self mutable i32 u8 never ``` -There are no contextual keywords. In particular, `use`, `in`, `requires`, -`ensures`, `terminates`, `by`, `min`, and `max` are ordinary identifiers. +There are no contextual keywords: `use`, `in`, `requires`, `ensures`, +`terminates`, `by`, `min`, and `max` are ordinary identifiers. ## 3. Grammar -The notation below uses `?`, `*`, and `+` conventionally. Punctuation is -literal. A machine with no return annotation is resultless. +`?`, `*`, and `+` have standard EBNF meanings; punctuation is literal. A +machine without a return type is resultless. ```text program := declaration+ @@ -165,204 +162,161 @@ primary := INT | CHAR | STRING | "true" | "false" | "self" | IDENT | "(" expression ")" ``` -`NAT` is a nonempty decimal integer with no sign. `INT` is a nonempty decimal -integer token; unary `-` is separate. The one magnitude `2147483648` is admitted -only as the operand spelling of `-2147483648`; every other integer token must be -within nonnegative `i32` range. Binary levels associate left. Postfix and unary -bind more tightly than every binary level. - -Every owner-qualified data machine begins with `@mutable self`; a receiverless -owner-qualified machine is not a Epsilon declaration. An unqualified declaration -accepts ordinary parameters only, so `&` in its input list is -`UnexpectedToken` at that byte. Conversely, `)` or an ordinary parameter where -a qualified declaration requires its receiver is `UnexpectedToken` at that -token. - -For `machine Buffer::clear(@mutable self)`, the first input is exactly the mutable -`Buffer` instance. `self` is its fixed reserved binding symbol: it has the -owner's nominal type and storage place, remains active in the machine's states, -and lowers as that receiver rather than as a distinct runtime value. The parser -normalizes an authored `self` expression to the ordinary local-reference path -using the keyword's own source span. Outside a machine that introduced this -binding, `self` therefore follows the existing absent-local rule and is -`UnknownName`; there is no direct contextual-`self` rejection. - -Every machine application has an authored argument list, including `()` for a -zero-parameter unqualified machine or receiver method. Owner-qualified data -machines are invoked only through a receiver postfix such as `buffer.clear()`. -For a data owner, `Owner::name` and `Owner::name(...)` are constructor syntax, -not static-machine syntax. - -The checker classifies a postfix expression by its resolved declaration. A -`place` may contain only field and single-index suffixes rooted at `self`, a -parameter, or a local. A `call` must end in a resolved machine application. A -slice, `.len`, `.as_slice`, constructor, or call is not an assignable place. -Within a transition, a continuation resolves to a state transfer, a complete -expression result, or the explicit empty resultless block. State names and -callable names that would make that resolution ambiguous reject. Every state transfer has an authored argument -list, including `()` for a zero-parameter state. A known bare state is not a -transfer, regardless of its arity, and is `InvalidControlTarget` at the -continuation expression's first byte. A bare known machine and an unqualified -state/machine collision produce the same judgment at that coordinate. These -are distinct source causes with one public rejection; neither arity nor the -published outcome distinguishes them. - -The grammar admits no `use` declaration, attribute, domain annotation, range -type, contract clause, `terminates by` clause, special result binding, -wrapping or saturating placement, generic parameter, or package/module form. +`NAT` is an unsigned nonempty decimal integer. `INT` is a nonempty decimal token +without a sign; unary `-` is separate. The literal `2147483648` is valid only as +`-2147483648`; every other `INT` must fit in nonnegative `i32`. Binary operators +associate left; postfix and unary bind tighter than all binary operators. + +Every owner-qualified data machine must start with `@mutable self`; receiverless +qualified machines are invalid. An unqualified machine accepts only ordinary +parameters, so `&` in its parameter list rejects as `UnexpectedToken` at `&`. +Conversely, `)` or an ordinary parameter where a qualified machine expects a +receiver rejects as `UnexpectedToken` at that token. + +In `machine Buffer::clear(@mutable self)`, the first input is the mutable +`Buffer` receiver. `self` is a reserved binding with the owner's nominal type +and assignable place; it stays in scope inside all states of that machine and +lowers directly to the receiver rather than a copy. The parser lowers `self` +through the ordinary local-lookup path with its source span, so using `self` +outside a receiver machine reports `UnknownName`. + +Every machine call requires parentheses, including `()` for zero arguments. +Owner-qualified data machines are called only with receiver syntax +(`buffer.clear()`). For a data type, `Owner::name` and `Owner::name(...)` are +always sum constructors, never static machine calls. + +The checker classifies postfix expressions using their resolved declarations. A +`place` consists solely of field and single-index accesses rooted at `self`, a +parameter, or a local. A `call` must end in a resolved machine invocation. +Slices, `.len`, `.as_slice`, constructors, and calls are never assignable +places. Inside a transition, a continuation is a state transfer, a complete +expression result, or `{}`. State transfers always require parentheses (`()` for +zero parameters); a bare state name, a bare machine name, or an ambiguous +state/machine name all reject as `InvalidControlTarget` at the continuation's +first byte. + +Epsilon has no `use` statements, attributes, domains, range types, contracts, +`terminates by` clauses, special result bindings, wrapping/saturating operators, +generics, or modules. ## 4. Names, types, and closure checking -Checking is whole-closure and two-pass. After parsing, the first pass performs -one complete scoped identity census before type formation. It collects type -owners, machines, boundary members, fields or cases and their payload names, -machine and state parameters, states, `let` binders, and every syntactic -transition payload binder. Every duplicate-name failure belongs to this -declaration-collection phase. Across all scoped duplicate pairs, -`DuplicateName` reports the first byte of the globally earliest later -declaration. Collection records identities without granting visibility: a -`let` remains unavailable in its initializer, and a transition binder is -visible only in its arm's continuation. - -The second pass resolves types, owners, machines, calls, states, and bodies. -Top-level declarations and states within a machine may be referenced before -their textual declaration. States are direct children of one machine body; -state bodies cannot declare nested states. Therefore packing order affects -coordinates but not valid program meaning. - -Grammar position and qualification select distinct namespaces: - -- boundary traits and data declarations share one type-owner namespace; -- a machine identity is `(optional owner, machine name)`, so a type owner may - share its spelling with an unqualified machine and `parse` differs from - `Parser::parse`; -- boundary members, record fields or sum cases, state labels, and local values - use their exact owner-local scopes; and -- a member name may share its spelling with a local binder because `self.name` - or another postfix `.name` is position-qualified while bare `name` is local. - -Boundary members are externally realized callable identities, not source- -fillable implementation slots. Once collection identifies an authored -qualified machine's owner as a boundary trait, the declaration rejects as -`InvalidBoundary` whether or not its member name exists. Duplicate member -signatures inside the boundary declaration remain `DuplicateName`. Qualified -machine bodies on data owners are ordinary machine identities and must be -unique under that owner. `InvalidBoundary` is anchored at the first byte of the -authored qualified machine declaration and competes with every `DuplicateName` -candidate by smallest packed coordinate in the same collection phase. -Classification requires one unique owner identity. A boundary/data owner -collision contributes `DuplicateName`; qualified bodies under that ambiguous -spelling contribute no inferred owner-kind failure. - -The fixed entry shape has one narrow phase-ownership exception. If the source -contains an authored `Main::main` owner/name candidate, duplicate `Main` and -`Console` owners, `Console` member identities, `Main.console` fields, and exact -`Main::main` declarations are reserved for the type-formation entry judgment -and reject as `InvalidEntry`. This exception exists so malformed reserved entry -support cannot be preempted by the generic census. It does not suppress any -unrelated duplicate, and without an authored entry-name candidate the ordinary -declaration census remains unchanged. - -A sum case and receiver machine under one data owner may share a spelling. -`Owner::name(...)` selects the case namespace, while `value.name(...)` selects -the receiver-machine namespace; neither expected type nor arity chooses between -them. Fields likewise remain position-distinguished, and the existing -field/case member collision rule inside a data declaration is unchanged. - -Epsilon v1 permits no active local shadowing. Machine parameters are active -throughout the invocation. A state parameter is active only in that state body. -A `let` initializer sees the current outer environment; its binder becomes -active only after successful initialization and for the remainder of that entry -or state body. A state parameter or `let` may not reuse an active machine -parameter, state parameter, or earlier local. Entry and distinct state bodies -have disjoint local environments and may reuse spellings. Locals cannot cross a -state transfer except as explicitly evaluated state arguments. - -Transition payload binders are mutually unique within one arm and cannot reuse -an active machine parameter, state parameter, or earlier `let`. They are visible -only in that arm's continuation. Distinct arms are disjoint and may reuse the -same spelling; a sibling-arm reference is `UnknownName`. Every syntactic binder -participates in collection even when later checking finds an unknown case or -wrong payload arity, so an earlier-phase `DuplicateName` may be followed by -`ArityMismatch` after the duplicate is repaired. `DuplicatePattern` applies to -repeated transition selectors or cases, never to repeated binder spellings. - -A `data` declaration is exactly one of: +Checking runs in two whole-closure passes after parsing. First, a scoped name +census collects all type owners, machines, boundary members, fields/cases and +payload names, machine/state parameters, states, `let` bindings, and syntactic +transition payload binders. All duplicate errors happen in this pass, reporting +`DuplicateName` at the first byte of the globally earliest offending re-declaration. +Collection records names without making them visible early: a `let` is not in +scope inside its own initializer, and a transition binder is visible only in its +own arm. + +The second pass checks types, owners, machines, calls, states, and bodies. +Top-level declarations and states within one machine may appear in any order +(states cannot nest inside states), so file packing order changes byte offsets +but never valid program behavior. + +Syntax selects disjoint namespaces: + +- boundary traits and `data` declarations share one type-owner namespace; +- machine identity is `(optional owner, machine name)`, so a type owner and an + unqualified machine may share a name, and `parse` differs from `Parser::parse`; +- boundary members, record fields/sum cases, state names, and locals each use + their own owner-local scope; +- a member name may match a local because `self.name` or `.name` is dot-qualified + while bare `name` is local. + +Boundary members are externally implemented capabilities, not source-defined +bodies. If a qualified machine's owner resolves to a boundary trait, it rejects +as `InvalidBoundary` at the declaration's first byte whether or not the member +exists (competing by smallest offset with `DuplicateName` in the same collection +pass). Duplicate signatures inside a boundary trait are `DuplicateName`. +Qualified machines on data types must be unique under that owner. If a boundary +and a `data` type collide, they report `DuplicateName` and qualified machines on +that ambiguous owner do not also emit `InvalidBoundary`. + +One narrow exception protects entry diagnostics: when source defines a +`Main::main` candidate, duplicate `Main` or `Console` owners, duplicate `Console` +members, duplicate `Main.console` fields, and duplicate `Main::main` +declarations are handled by type formation's entry check and report +`InvalidEntry` instead of `DuplicateName`. Unrelated duplicates still report +normally, and if no `Main::main` exists, normal census rules apply. + +A sum case and a receiver machine on the same `data` type may share a name: +`Owner::name(...)` selects the case, while `value.name(...)` selects the +receiver machine regardless of arity or expected type. Fields and cases still +cannot collide within a `data` declaration. + +Active locals cannot be shadowed. Machine parameters stay active across entry +and all states. State parameters are active only in that state. A `let` +initializer sees outer bindings and activates its own name only for subsequent +statements in that entry or state block. No state parameter or `let` may reuse +an active machine parameter, state parameter, or earlier `let`. Entry and +different state blocks have separate local scopes and may reuse names; locals do +not persist across state transfers except when passed as state arguments. + +Transition payload binders must be unique within an arm and cannot shadow an +active machine parameter, state parameter, or `let`. They are visible only in +their arm's continuation; sibling arms may reuse names, and referencing another +arm's binder is `UnknownName`. Binders enter the name census even if the case is +unknown or has wrong arity, so fixing `DuplicateName` can later reveal +`ArityMismatch`. `DuplicatePattern` applies only to repeated selectors or cases, +never to binder names. + +A `data` declaration is either: - a record containing only named fields; or - a sum containing only named cases with finite payload fields. -An empty declaration is explicitly a zero-field record. It has exactly one -zero-initialized value and is never an empty sum. Mixing fields and cases -rejects as `InvalidDataShape` at the declaration name. Cases may have any -finite payload arity. A sum value's home tag is its case's zero-based -declaration position; the first case is the zero-initialized home case. Foreign -integer correspondences are ordinary mapping machines, not inline case numbers -or layout facts. - -Sum constructors are ordinary values. Epsilon v1 has no record-literal form: -records are established as declared `Main` storage, nested fields, array -elements, parameters, or returned copies, then updated through checked places. -All non-capability parameters and returns have value semantics. - -Every value type is finite and nonrecursive by value. Direct or indirect -recursive records, sums, arrays, or payloads reject. Epsilon has no heap or -recursive reference type. Consequently, `D` represents dynamic compiler -structures in source-declared fixed arrays with `i32` indexes. For example, an -AST node may store a tag and child indexes into `[Node; N]`; `N`, the cursor, -and capacity-failure behavior are authored program state. - -An array length is admitted exactly when its authored `NAT` lies in -`1..2147483647`. Zero rejects as `InvalidArrayLength` at the first byte of its -length literal. A negative spelling is not a `NAT` and therefore fails during -parsing; a positive token above `2147483647` is -`IntegerLiteralOutOfRange`. Whether the selected application profile has enough -physical storage for an admitted array is not type formation and never changes -Epsilon validity. - -`i32` is the ordinary scalar and arithmetic type. `u8` is storage-only: it may -occur in stored data, arrays, and byte views, but arithmetic and comparisons -operate on the zero-extended `i32` read. A store to `u8` requires `0..255` and -otherwise traps as `ByteRange`. - -`never` is a bottom/control type permitted only as a machine return type. It has -no values and is forbidden in fields, payloads, parameters, locals, arrays, and -views. A call returning `never` cannot be bound or assigned. A -semicolon-terminated call is syntactically a statement; when its resolved -result is `never`, it gives the block no normal return. An authored `-> never` -machine admits no normal return or falloff in any entry or state block; it may -transfer state, diverge, or terminate through another `never` call. Every -declared block is checked regardless of reachability. Any later executable -construct in that block rejects as `InvalidTerminal` at its terminating `;` or, -for a transition, its closing `}`. State declarations following the entry -sequence are not executable successors. - -The permitted occurrence is the exact outer machine-return type. Every other -authored `never` occurrence rejects as `TypeMismatch` at the `never` token. - -A `@[T]` is an immutable bounded view. Views may be parameters and locals and -may be passed onward. They cannot occur in stored data, sums, arrays, or return -types. There is no lifetime syntax. Static checking rejects every escaping -view. A forbidden view rejects as `EscapingView` at its outermost forbidden -`&`. That outer placement failure suppresses defects nested inside the view; -children of an admitted parameter or local view are checked normally. - -Type formation constructs these placement, shape, recursion, and unknown-type -candidates against the complete declaration census, then reports the smallest -packed source coordinate independent of traversal order or wire-code number. -Its final whole-program subjudgment validates the entry shape described below; -body/control checking begins only after the complete type-formation phase -succeeds. Candidate identity is exactly `(packed offset, rejection reason)`. -Repeated derivation of one pair merges. Producing two different type-formation -reasons at one exact anchor is a compiler contradiction and therefore -`InternalFailure`, never an arbitrary reason-table tie-break. A compiler may -derive a private equality discriminator from the closed reason table, but no -separately authored kind may disagree with the reason and reason-code order -never supplies priority. +An empty `data` declaration is a zero-field record with one zero-initialized +value (never an empty sum). Mixing fields and cases rejects as `InvalidDataShape` +at the declaration name. Sum cases have zero-based declaration tags, and the +first case is the default zero-initialized variant. Map sums to external +integers with ordinary machines rather than inline discriminants. + +Sum constructors are values. Epsilon v1 has no record literals: records start as +zero-initialized `Main` fields, nested fields, array elements, parameters, or +copies, then mutate via places. All non-capability parameters and returns pass +by value. + +Every value type must be finite and nonrecursive; direct or indirect cycles +through records, sums, arrays, or payloads reject. With no heap or recursive +pointers, `D` stores dynamic structures in fixed arrays indexed by `i32` (for +example `[Node; N]` with authored length `N`, cursors, and overflow handling). + +Array lengths require `NAT` in `1..2147483647`. Zero rejects as +`InvalidArrayLength` at the length literal. Negative tokens fail parsing; +numbers above `2147483647` fail as `IntegerLiteralOutOfRange`. Physical memory +limits of an evaluator profile never affect type validity. + +`i32` is the scalar arithmetic type. `u8` is storage-only (fields, payloads, +arrays, byte views): reading `u8` zero-extends to `i32`, and storing checks +`0..255` at runtime or traps as `ByteRange`. + +`never` is allowed only as a machine's outer return type; any other placement +rejects as `TypeMismatch` at `never`. Calls returning `never` cannot be bound or +assigned. As a semicolon-terminated statement, a `never` call ends normal +control flow for that block. A `-> never` machine allows no normal return or +falloff in entry or any state; it may only transfer state, diverge, or call +another `never` machine. Every block is checked even if unreachable. Any +statement or terminal after a `never` call rejects as `InvalidTerminal` at its +closing `;` or transition `}` (following state declarations are not successors). + +`@[T]` is an immutable bounded view allowed only in parameters and locals (and +passed downward). Storing a view in a field, payload, array, or return type +rejects as `EscapingView` at the outermost forbidden `&`, suppressing errors +nested inside that forbidden view. Views in valid parameter/local positions check +their element types normally. + +Type formation checks placement, shape, recursion, and unknown types against the +complete name census and reports the smallest byte offset regardless of +traversal order or reason code. Its final step validates the entry shape before +body checking starts. A candidate is `(packed offset, rejection reason)`: +identical pairs merge, while two different reasons at the exact same offset are +a compiler bug (`InternalFailure`), never broken by reason-code order. ## 5. Entry and boundary -Every accepted program declares exactly this boundary trait: +Every valid program declares this exact boundary trait: ```text boundary trait Console { @@ -373,141 +327,116 @@ boundary trait Console { } ``` -No other boundary declaration is admitted in v1. `Main` is a record with -exactly one `console: Console` field and any finite program-owned fields. The -entry is exactly: +No other boundary trait is allowed in v1. `Main` must be a record with exactly +one `console: Console` field plus any finite program fields. The entry machine +must be: ```text machine Main::main(@mutable self) ``` -`Console` is a sealed entry capability, not an ordinary named value type. Its -only admitted occurrence is the exact `Main.console` field above. Any other -placement, missing field, duplicate field, or competing entry shape rejects as -`InvalidEntry` through the entry-shape judgment. `InvalidBoundary` remains -owned solely by declaration collection for authored bodies on boundary owners. - -The entry-shape judgment closes inside type formation. It first asks whether an -authored owner/name candidate for `Main::main` exists, before validating that -candidate's signature. If none exists, `MissingEntry` at source extent is the -sole entry verdict; absent `Main`, `Console`, and `Main.console` components do -not add candidates. Once such a candidate exists, every malformed, duplicate, -or competing entry and supporting component is `InvalidEntry`, never -`MissingEntry`. - -An authored defect anchors at the first byte of its offending entry, boundary, -member, data, field, or type construct. A required but absent supporting -component anchors `InvalidEntry` at source extent. Multiple absent components -therefore merge as the same reason/coordinate. The four `Console` members are -an unordered exact identity/signature set, and parameter binder spellings are -nonsemantic. Reordering members or renaming their binders does not change the -entry shape. No synthetic omission coordinate exists. - -It has no value parameters and no return value. Normal falloff exits with code -zero. Every nonzero normal status is expressed by -`self.console.exit_process(code)`. There are no bare read, write, line, or exit -operations and no implicit sugar for the receiver-qualified calls. - -The execution adapter supplies the one `Console` capability and sealed input. -`read_byte` returns the next byte as `0..255`, then returns stable `-1` at EOF. -`console.remaining_input` yields an immutable `@[u8]` over the bytes from the -current cursor through the end of the sealed guest input. Evaluating this -field leaves the cursor in place. Later reads advance the cursor and earlier -views retain their original bounds and bytes. At EOF the view is empty. -Ordinary view indexing, slicing and escape rules apply. The field is available -on the sealed `Console` capability without an authored member declaration. -`write_byte` appends exactly one byte and traps as `ByteRange` outside -`0..255`. `write_line` appends its exact view bytes followed by byte 10. -`exit_process` terminates after all earlier writes with the exact semantic -`i32` code. - -String literals have type `@[u8]` and immutable program-lifetime backing. Their -decoded bytes may be passed directly to `write_line` or any matching parameter. -Character literals have type `i32` and denote their decoded byte. +`Console` is a sealed capability allowed only in `Main.console`. Any other use, +missing/duplicate field, or malformed entry rejects as `InvalidEntry` during +type formation (`InvalidBoundary` applies only to authored bodies on boundary +owners during name collection). + +Type formation's entry check first looks for any authored `Main::main` +declaration. If none exists, it reports only `MissingEntry` at source extent +(omitting `Main` or `Console` adds no extra error). Once a `Main::main` exists, +every missing, duplicate, or malformed entry or support declaration reports +`InvalidEntry`—at the offending construct's first byte for authored defects, or +at source extent for missing components (which merge). The four `Console` +members may appear in any order and use any parameter names. + +`Main::main` takes no extra parameters and returns nothing. Falling off the end +exits with code 0; nonzero exits call `self.console.exit_process(code)`. There +are no bare I/O functions or implicit receiver sugar. + +The runtime supplies `Console` and sealed stdin. `read_byte` returns the next +byte in `0..255` or `-1` at EOF. `console.remaining_input` returns an immutable +`@[u8]` covering bytes from the current cursor to EOF without advancing the +cursor; later reads advance the cursor while earlier views keep their original +bounds and bytes, and EOF yields an empty view. Ordinary view rules apply, and +this field exists on `Console` automatically without being declared. +`write_byte` emits one byte and traps as `ByteRange` outside `0..255`. +`write_line` emits the view's bytes plus LF (byte 10). `exit_process` flushes +prior writes and exits with its exact `i32` code. + +String literals have type `@[u8]` with immutable program-lifetime backing and +pass directly to `write_line`. Character literals have type `i32` with their +decoded byte value. ## 6. Storage and values -Epsilon has no ambient heap, pointer arithmetic, filesystem, environment, clock, -network, threads, process spawning, or foreign memory. All program storage is -visible in source. +Epsilon has no heap, pointer arithmetic, filesystem, environment, clock, +network, threads, child processes, or foreign memory; all storage is visible in +source. -Before entry, the adapter installs `Main.console`; every program-owned `Main` -field is logically zero-initialized. Scalars and array elements are zero; -records recursively use those homes; sums select their first case with zeroed -payload storage. Each machine invocation logically creates unestablished local -slots. Physical implementations may clear those slots, but their values do not -exist until their initializers complete. +Before `Main::main` runs, the runtime installs `Main.console` and logically +zero-initializes all other `Main` fields (zero scalars/arrays, recursive zero +records, and first-case sums with zeroed payloads). Local variables start +uninitialized and exist only after their initializers finish. -Records and sum payloads establish fields in declaration order. Constructor -arguments, call arguments, assignments, and ordinary operands evaluate exactly -once from left to right. Arrays are fixed in length and never allocate. -An indexed assignment evaluates its destination base and index and checks -bounds before evaluating the right side. A failed bounds check suppresses -right-side effects and traps. +Records and sum payloads initialize fields in declaration order. Constructor +arguments, call arguments, assignments, and operands evaluate once left to +right. Arrays have fixed length and never allocate. Indexed assignments evaluate +the base and index and check bounds before evaluating the right-hand side; a +bounds trap skips right-side effects. -Sum construction evaluates each argument exactly once and immediately -establishes its corresponding payload field before evaluating the next -argument. If argument evaluation or field establishment traps or exits, -construction stops and later arguments do not run. Effects already performed -remain observable. In particular, a `u8` payload value outside `0..255` traps as -`ByteRange` before any later argument's effects, trap, or exit. The completed -sum value becomes available only after every payload field is established. - -An array or view access evaluates its base and then its index. An index outside -`0..length-1` traps as `Bounds` before any access. A slice `a[lo..hi]` requires -`0 <= lo <= hi <= length`; otherwise it traps as `Bounds`. `.len` returns an -`i32`. - -`.as_slice` is a field-like contextual postfix admitted only on a complete -fixed-array value that carries a place. It evaluates that receiver exactly once -and returns a non-place immutable `@[T]` view over the array's exact full range -`0..N`; it performs no allocation, copy, or bounds check and cannot trap. A -fixed-array value without a place contributes `InvalidPlace` at the receiver -expression's start. Every other complete receiver type, including an existing -immutable view, contributes `TypeMismatch` at the enclosing postfix -expression's start. An unresolved receiver contributes no `.as_slice` -candidate. An authored record field named `as_slice` remains an ordinary field: -contextual selection occurs only after base-type classification. - -Because postfix suffixes compose, `array.as_slice()` parses as -`(array.as_slice)()` rather than as an alternate spelling of the contextual -operation. The resulting view is not callable, so the additional call suffix -contributes `TypeMismatch` under the ordinary call rule. +Sum constructors evaluate each argument once and immediately write its payload +field before evaluating the next argument. If evaluating or writing a field +traps or exits, construction stops and later arguments never run, while earlier +effects remain visible. In particular, an out-of-range `u8` payload traps as +`ByteRange` before any later argument runs. The sum value exists only after all +fields succeed. + +Array and view indexing evaluates base then index, trapping as `Bounds` outside +`0..length-1`. Slicing `a[lo..hi]` requires `0 <= lo <= hi <= length` or traps +as `Bounds`. `.len` returns `i32`. + +`.as_slice` is valid only on a complete fixed-array value that has an assignable +place. It evaluates the receiver once and returns a non-place immutable `@[T]` +view over `0..N` with no allocation, copy, or trap. A fixed array without a +place rejects as `InvalidPlace` at the receiver's start; any other complete +receiver type (including an existing view) rejects as `TypeMismatch` at the +postfix expression's start. Unresolved receivers add no `.as_slice` error. A +record field named `as_slice` stays an ordinary field because contextual members +apply only after checking the base type. + +Because postfix operators chain, `array.as_slice()` parses as +`(array.as_slice)()` and rejects as `TypeMismatch` because views are not +callable. ## 7. Scalar operations -`i32` is signed two's-complement with range -`-2147483648..2147483647`. Epsilon defines: +`i32` is signed two's-complement (`-2147483648..2147483647`): -- checked `+`, `-`, and `*`, trapping as `Overflow` when the mathematical - result is outside that range; -- `/` truncating toward zero and `%` with the dividend's sign; -- `DivisionByZero` for a zero divisor; -- `SignedDivisionOverflow` for `-2147483648 / -1` (and its remainder form); -- shifts whose count must be in `0..31`, otherwise `ShiftCount`; `<<` wraps in - the 32-bit representation and `>>` is arithmetic; -- bitwise `&`, `^`, and `|` on the 32-bit representation; and -- comparisons returning exactly `0` or `1`. +- `+`, `-`, and `*` trap as `Overflow` outside `i32` range; +- `/` truncates toward zero and `%` keeps the dividend's sign; +- dividing or taking remainder by zero traps as `DivisionByZero`; +- `-2147483648 / -1` (and remainder) traps as `SignedDivisionOverflow`; +- shifts require a count in `0..31` or trap as `ShiftCount`; `<<` wraps in 32 + bits and `>>` is arithmetic; +- `&`, `^`, and `|` operate bitwise on 32 bits; +- comparisons return `0` or `1`. -There is no implicit truth conversion. `true` is `1` and `false` is `0`. -`&&` and `||` evaluate the left operand first, require each evaluated operand -to be exactly zero or one, and short-circuit. Any other Boolean-context value -traps as `NonBoolean`. `assert` uses the same Boolean check; false traps as -`Assertion`. +There is no implicit truthiness: `true` is `1` and `false` is `0`. `&&` and `||` +evaluate left to right, short-circuit, and trap as `NonBoolean` on any evaluated +operand other than `0` or `1`. `assert` checks the same Boolean rule and traps +as `Assertion` on `0`. -`min` and `max` have no privileged meaning. Authors may declare ordinary -machines with those names. +`min` and `max` are ordinary identifiers with no special meaning. ## 8. Machines, states, and transitions -Named decision: `epsilon-expression-arm-results`, settled 2026-11-03. -Transition arms use Omega-like expression results rather than an optional -arm-level `return expression?`. A value expression returns that value; a -value-returning machine continuation forwards its normal result. `{}` is the -explicit resultless completion, not a general statement block or a new value -type. State applications retain their existing same-invocation transfer rule. +Named decision: `epsilon-expression-arm-results` (2026-11-03). Transition arms +evaluate to expression results like Omega instead of using arm-level +`return expression?`. A value expression returns that value; a value-returning +machine call forwards its result; `{}` marks explicit resultless completion (not +a general block or value type); state calls keep same-invocation transfer +semantics. ```text transition code { @@ -517,179 +446,132 @@ transition code { } ``` -Here `compute` and `fallback` return the enclosing machine's result type. A -resultless machine can instead use `_ -> {}`. Ordinary block-level -`return expression?;` remains unchanged; `-> return` and `-> return expression` -are retired arm forms, not alternate spellings. Parsing an expression arm does -not use the old nullable-return probe to inspect the following pattern. - -Unqualified calls bind value parameters. Every owner-qualified data-machine -call additionally binds its first input to the receiver's mutable data place; -the declaration spelling `@mutable self` has exactly the owning data type. All -effects are committed before return. Recursion and state cycles are permitted; -Epsilon v1 does not require a termination annotation. - -Callable identity resolves before arity or type checking. A data-owner -`Owner::name(...)` considers only sum cases, while `value.name(...)` considers -only receiver machines and a bare `name(...)` considers only unqualified -machines. Statement position, expected result type, argument arity, and -declaration order never select a callable namespace. A uniquely resolved -constructor is not a call statement or control target. An unqualified state and machine that both match one -transition continuation, a known bare state, and a known bare machine all -reject as `InvalidControlTarget` at that continuation expression's first byte. -These distinct causes deliberately share one judgment. A bare state retains no -state application or first-class reference: no application was authored, and -state labels are not values. A bare machine may retain the general callable -reference already used by machine resolution without becoming an application. - -Body and control checking is one finite premise DAG, not traversal-driven error -recovery. Every authored child judgment is visited and derives its independent -candidate even when its parent cannot be formed. The candidate set may be -reduced online to the smallest coordinate without physically retaining later -losers. A failed child, whether it -contributes a candidate or no semantic fact, does not satisfy a parent premise -and is never replaced by an error type, guessed `i32`, place, or callable. A -parent success or rejection candidate exists exactly when every fact consumed -by that rule has resolved. - -Callable resolution and argument checking branch after the callable spelling -is resolved and admitted for the current expression, statement, or control -context. Arity consumes that admitted callable and the authored argument count, -but not argument facts; argument expressions are checked independently and an -`ArityMismatch` may therefore coexist with a failure inside an argument. -Argument-type comparison additionally consumes arity success and the complete -argument facts, and only that join can produce the call result. An identity -inadmissible in the current context contributes `InvalidControlTarget` or -`TypeMismatch` without also contributing arity or argument-type failures, while -its authored argument expressions remain independently checked. - -A complete expression result is exactly a value with its type and optional -place, a resultless call, or a `never` call. A place-required judgment consumes -only a complete value result. A value with no place contributes `InvalidPlace`; -an unresolved expression cannot. A resultless call used where a value is -required contributes `TypeMismatch`. When it is a direct machine or constructor -argument, that failure anchors at the authored argument expression's first byte, -including an outer grouping `(`. A `never` call is admitted only as an exact -semicolon-terminated statement or an admitted machine continuation; embedding -it in another expression contributes `InvalidTerminal`, and any later -executable construct in the same block also contributes `InvalidTerminal` at -its terminating delimiter. A grouped `never` argument retains the exact -mispositioned call-head anchor rather than the surrounding group. No mutability -discriminator exists: immutable views and other nonassignable values simply -carry no place. - -Projection rules consume complete base and index/bound facts. An absent member -on any complete base contributes `UnknownName` at the member spelling. A known -member of the wrong kind, a known contextual member on an unsupported receiver, -or a non-`i32` required index or bound contributes `TypeMismatch` at the -enclosing postfix expression's start. The fixed-array `.as_slice` relation is -the one contextual exception requiring a place fact: a supported array type -without that fact contributes `InvalidPlace` rather than `TypeMismatch`. - -Body/control anchors are otherwise exact. Unary, binary, call, constructor, -and postfix relational failures use the enclosing expression start; arity uses -the application start. `InvalidPlace` uses the left-side place start or the -receiver start of a place-requiring contextual postfix. A `let`, -assignment, `assert`, return, or transition value-type relation uses the -initializer, assigned value, asserted expression, returned expression, or -transition subject start respectively. A required but absent return value uses -the `return` keyword. `InvalidControlTarget` uses the continuation expression -start. `InvalidTerminal` uses the mispositioned `never` call, or the terminating -`;`/`}` of the first later executable construct after a successful `never` -statement. - -All admitted body/control candidates merge by smallest packed source -coordinate. Repeated derivation of the same reason at the same coordinate is -one candidate. No two simultaneously derivable distinct reasons may share one -coordinate by construction. Finding such a pair after applying the premise DAG -is a compiler contradiction and produces outer `InternalFailure`, never a -Epsilon rejection chosen by reason-code order. Every relation consuming a call's -result category is blocked by that call's arity failure because the result -exists only after its arity and argument-type join succeeds. Runtime short- -circuiting, transition selection, and source traversal do not suppress static -checking of authored child expressions or arms. - -Every machine entry and every declared state block has only local exit effects: +Here `compute` and `fallback` return the enclosing machine's return type; a +resultless machine can use `_ -> {}`. Block-level `return expression?;` is +unchanged, while `-> return` and `-> return expression` are retired. Parsing +expression arms no longer peeks ahead to distinguish nullable returns from the +next pattern. + +Unqualified calls pass arguments by value. Owner-qualified data machines also +bind `@mutable self` to the receiver's mutable place. Side effects commit before +return. Recursion and state cycles are allowed with no termination annotations. + +Callable resolution precedes arity and type checks: `Owner::name(...)` looks up +only sum cases, `value.name(...)` looks up only receiver machines, and bare +`name(...)` looks up only unqualified machines. Context, return type, arity, and +declaration order never switch namespaces. Constructors are never call +statements or control targets. In a transition continuation, an ambiguous +state/machine name, a bare state name, or a bare machine name all reject as +`InvalidControlTarget` at the continuation's first byte (bare states record no +state reference, while bare machines may retain callable lookup without forming +a call). + +Body and control checking forms a finite dependency DAG rather than ad-hoc error +recovery. Every child expression is checked independently even if its parent +fails, and the checker can keep only the smallest-offset error online. A failed +child supplies no fake error type, guessed `i32`, place, or callable; a parent +rule fires only when all child facts it needs succeed. + +Once a call head resolves and fits its context, arity checks run independently +of argument typing, so `ArityMismatch` can coexist with an error inside an +argument. Argument type checks require both arity success and complete argument +facts, and only then produce the call's result. A wrong-context target reports +`InvalidControlTarget` or `TypeMismatch` without checking arity or argument +types, though argument expressions still check on their own. + +A complete expression yields a value (with type and optional place), a +resultless call, or a `never` call. Place-requiring operations accept only +complete values and report `InvalidPlace` when no place exists (unresolved +expressions do not). Using a resultless call as a value reports `TypeMismatch`—at +the argument expression's first byte (including outer `(`) when passed directly +as a machine or constructor argument. A `never` call is valid only as a +semicolon-terminated statement or a machine continuation; embedding it anywhere +else reports `InvalidTerminal` (at the call head even if grouped), and any later +executable construct in the same block reports `InvalidTerminal` at its closing +`;` or `}`. Immutable views simply carry no place. + +Projections require complete base and index/bound facts. Missing members report +`UnknownName` at the member name; wrong member kinds, unsupported contextual +receivers, or non-`i32` indexes/bounds report `TypeMismatch` at the enclosing +postfix start. `.as_slice` is the one contextual member requiring a place, +reporting `InvalidPlace` on a non-place fixed array. + +All other body/control errors use exact anchors: enclosing expression start for +unary/binary/call/constructor/postfix errors; application start for arity; left +side or receiver start for `InvalidPlace`; initializer, right side, asserted +expression, returned expression, or subject start for `let`, assignment, +`assert`, return, and transition type mismatches; `return` for a missing return +value; continuation start for `InvalidControlTarget`; and the misplaced `never` +call or following statement's `;`/`}` for `InvalidTerminal`. + +All body/control errors merge by smallest packed offset; identical +`(offset, reason)` pairs collapse, and two distinct reasons at the same offset +are a compiler bug (`InternalFailure`), never broken by reason-code order. An +arity failure blocks any parent rule that depends on the call's result. Runtime +short-circuiting and branch selection never skip static checking of any child. + +Every entry and state block has one local exit effect: ```text Falloff | ReturnNone | ReturnValue(type) | NoNormalReturn | StateTransfer(state) ``` -A resultless machine admits `Falloff`, `ReturnNone`, `NoNormalReturn`, and -`StateTransfer`. A machine returning `T` admits a structurally compatible -`ReturnValue(T)`, `NoNormalReturn`, and `StateTransfer`. A `never` machine -admits only `NoNormalReturn` and `StateTransfer`. An incompatible falloff is -`TypeMismatch` at the exact closing `}` of the entry or state body. Every block -is checked independently, including unused states; return validation performs -no reachability traversal, cycle detection, or termination proof. - -State declarations are control labels inside one machine invocation. State -arguments initialize their parameters simultaneously. A transition evaluates -its subject exactly once, then inspects arms in source order. It evaluates only -the selected continuation and its arguments. Each arm has one local exit -effect. A state application is `StateTransfer` and is compatible with every -machine category because every target state is checked under that same machine -category. A resultless machine continuation becomes `Falloff` if it returns; a -`never` machine continuation is `NoNormalReturn`; and a value-returning machine -continuation forwards `ReturnValue(type)` and must match the enclosing machine's -declared result. Other value expressions have the same `ReturnValue(type)` exit -without an explicit `return` keyword. The empty `{}` continuation has -`ReturnNone`; it is valid only for a resultless machine, and a mismatch anchors -at the opening `{`. A value-result mismatch anchors at the expression's first -byte. No continuation runs after a selected machine call completes. These rules -introduce neither general expression statements nor fall-through into another -arm or state. `never` and state-transfer outcomes keep their existing meanings. - -A transition has at least one arm. Its grammar admits at most one `_`, only as -the final arm. After parsing a wildcard arm the next token must therefore be -`}`; another pattern, including another `_`, is `UnexpectedToken` at that next -token. Wildcards do not participate in `DuplicatePattern`, whose scope remains -repeated scalar selectors and exact sum cases. - -A sum transition must name every case exactly once or end with `_`; this is a -static rule and the `or` is inclusive. Naming every current case and retaining -a final `_` is legal, so adding a case does not invalidate an untouched -transition. A scalar transition may select an integer, a quoted byte or a -Boolean, with an optional final `_`. If no scalar arm matches, execution traps as -`NonExhaustiveTransition`. - -Pattern names resolve before semantic checks. An unknown owner or case is -`UnknownName` at that name. A known boundary or record owner used where a sum -case is required, a scalar selector used with a sum subject, a case used with a -scalar subject, or a case from a different nominal sum is `TypeMismatch` at the -pattern's first byte. An incompatible pattern contributes no duplicate or -payload-arity candidate. - -A subject-compatible scalar selector or exact case claims its semantic identity -before payload arity is checked. A later occurrence of that identity is solely -`DuplicatePattern` at the later pattern's first byte, even when the earlier -unique case subsequently fails arity. A unique case with the wrong payload -binder count is solely `ArityMismatch` at its pattern's first byte. Only a -unique, category-compatible, arity-compatible pattern supplies complete pattern -and typed-binder facts. - -Scalar selector identity is the validated `i32` value, never its token spelling: -`false`, `0`, and `00` are one selector, and `true`, `1`, and `001` are one -selector. A quoted byte selects its decoded value. For example, `'/'`, -`'\x2F'` and `47` all select 47. Mixing these spellings in one transition -reports `DuplicatePattern` at the second selector. Negative patterns are not -grammatical because unary `-` is not part of `nonwildcard_pattern`; `-1 ->` is `UnexpectedToken` at `-`. Out-of-range -positive integer tokens reject before semantic selector identity is formed. - -Static sum coverage consumes a complete sum subject and completed pattern -premises. If neither every case nor a final wildcard covers the sum, -`NonexhaustiveSum` anchors at the transition subject's first byte. A failed -category, duplicate, or arity premise suppresses coverage; after that defect is -repaired, missing coverage may become the next rejection. This deliberate -two-round diagnosis is premise ordering, not traversal-dependent recovery. - -The subject of a scalar transition is not a Boolean context. For example, `7` -against only `true` and `false` arms produces `NonExhaustiveTransition`, not -`NonBoolean`. `NonBoolean` applies only to `&&`, `||`, and `assert`. +Resultless machines allow `Falloff`, `ReturnNone`, `NoNormalReturn`, and +`StateTransfer`. Machines returning `T` allow matching `ReturnValue(T)`, +`NoNormalReturn`, and `StateTransfer`. `never` machines allow only +`NoNormalReturn` and `StateTransfer`. Disallowed falloff rejects as +`TypeMismatch` at the block's closing `}`. Every block (including unreachable +states) checks locally with no reachability or termination analysis. + +States are control labels within one machine invocation; arguments bind +simultaneously on transfer. A transition evaluates its subject once, matches +arms in source order, and runs only the matching continuation. State transfers +yield `StateTransfer` and fit any machine return type because every state checks +against the enclosing machine's return type. Resultless machine continuations +yield `Falloff`; `never` continuations yield `NoNormalReturn`; value-returning +machine continuations and value expressions yield `ReturnValue(type)` and must +match the machine's return type (mismatches anchor at the expression start). `{}` +yields `ReturnNone` and is valid only in resultless machines (mismatches anchor +at `{`). Nothing runs after a continuation finishes; arms never fall through. + +A transition has at least one arm and at most one `_`, which must be last. Any +pattern after `_` (including another `_`) rejects as `UnexpectedToken` at that +token. Wildcards never trigger `DuplicatePattern`. + +A sum transition must either name every case once or end with `_` (inclusive +`or`, so keeping a trailing `_` after listing all cases stays valid). Scalar +transitions match integers, quoted bytes, or Booleans with an optional final +`_`; an unmatched scalar traps at runtime as `NonExhaustiveTransition`. + +Pattern names resolve first: unknown owners or cases report `UnknownName` at the +name. Non-sum owners, scalar patterns on sums, case patterns on scalars, or +cases from another sum report `TypeMismatch` at the pattern's first byte and +skip duplicate/arity checks. + +Compatible scalar selectors and sum cases claim semantic identity before arity +checks. A repeated identity reports `DuplicatePattern` at the later pattern even +if the first occurrence fails arity; a unique case with wrong binder count +reports `ArityMismatch` at the pattern start. Only a unique, type-compatible, +arity-valid pattern supplies typed payload binders. + +Scalar selector identity is the `i32` value, not its spelling: `false`, `0`, and +`00` are identical; `true`, `1`, and `001` are identical; `'/'`, `'\x2F'`, and +`47` all mean 47. Mixing them in one transition reports `DuplicatePattern` at +the second one. Negative patterns are disallowed because unary `-` is excluded +from `nonwildcard_pattern`, so `-1 ->` rejects as `UnexpectedToken` at `-`. +Out-of-range integer tokens reject before selector checking. + +Sum exhaustiveness runs only when the subject and all pattern checks succeed; +missing cases report `NonexhaustiveSum` at the subject's first byte. A pattern +type, duplicate, or arity error suppresses exhaustiveness until repaired. + +Scalar transitions are not Boolean contexts: matching `7` against `true` and +`false` traps as `NonExhaustiveTransition`, not `NonBoolean` (which applies only +to `&&`, `||`, and `assert`). ## 9. Closed rejection and trap identities -`EpsilonRejectReason` is this closed nominal set: +`EpsilonRejectReason` is this fixed enum: ```text InvalidSourceByte InvalidToken InvalidCharacterLiteral @@ -703,28 +585,26 @@ EscapingView InvalidControlTarget InvalidTerminal DuplicatePattern NonexhaustiveSum ``` -Checking phases are lexical, parse, declaration collection, type formation, -then body/control checking. The earliest packed offset within the earliest -failing phase is reported. Type-formation and body/control candidates have -separate carriers and are never compared by coordinate. Coordinates are exact: - -- an invalid source byte, token, escape, name, type, place, pattern, or control - target reports its first byte; -- an unterminated literal reports its opening quote; -- an unexpected end, missing entry, absent required entry component, or other - whole-program omission reports the source extent; -- a duplicate reports the later declaration; -- an invalid boundary body reports the first byte of its authored qualified - machine declaration; and -- an invalid mixed data shape reports its declaration name, a zero array length - reports its length literal, a standalone value-position `u8` or misplaced - `never` reports that type token, and a forbidden view reports its outermost - forbidden `&`; and -- a body error follows the premise-DAG relation anchors in section 8 rather - than a compiler traversal or statement-wide fallback. - -The Epsilon checking reason-code table is explicit and is not derived from a -Delta constructor order: +Checking runs in five phases: lexical, parse, declaration collection, type +formation, and body/control checking. The checker reports the earliest offset in +the earliest failing phase. Type-formation and body/control errors stay in +separate buckets and never compete by offset. Anchors are exact: + +- invalid source bytes, tokens, escapes, names, types, places, patterns, and + control targets anchor at their first byte; +- unterminated literals anchor at their opening quote; +- unexpected EOF, missing entry, and missing entry components anchor at source + extent; +- duplicates anchor at the later declaration; +- invalid boundary bodies anchor at the qualified machine declaration's first + byte; +- mixed data shapes anchor at the declaration name, zero array lengths at the + length literal, standalone `u8` or misplaced `never` at that type token, and + forbidden views at the outermost forbidden `&`; +- body errors follow the exact anchors in section 8. + +Wire reason codes are fixed explicitly and never depend on implementation enum +order: ```text 1 InvalidSourceByte 2 InvalidToken @@ -742,12 +622,10 @@ Delta constructor order: 25 DuplicatePattern 26 NonexhaustiveSum ``` -Zero and unknown codes are noncanonical. Reordering an implementation sum does -not change this table. The final evaluator observation profile must preserve a -total bijection over the exact closed reason set. Changing that set requires an -explicit language and observation-profile decision. +Zero and unlisted codes are invalid. Changing this table requires an explicit +spec and observation-format update. -`TrapKind` is exactly: +`TrapKind` is: ```text Overflow @@ -761,105 +639,88 @@ Assertion NonExhaustiveTransition ``` -The Epsilon v1 runtime trap codes are 1 through 9 in that displayed order. This -is an explicit execution-profile table rather than declaration-order identity. -A trap preserves the exact stdout prefix written before the fault. +Wire trap codes are 1 through 9 in this exact order. A trap keeps the exact +stdout bytes written before it occurred. ## 10. Resource classification -Epsilon distinguishes three kinds of bounds. - -Source-visible semantic bounds include every array length, the fixed storage -chosen by `D`, `i32` and `u8` widths, first-case sum homes, and all authored -capacity/failure logic. Enlarging `[Node; N]` produces a different `D` source -subject, not a different Epsilon language. - -Execution-profile bounds include sealed stdin, Alpha memory and return-stack -capacities, evaluator output bytes, and a finite observation-step budget. -They are recorded with the checked evaluator run but cannot change Epsilon -meaning. - -Private implementation budgets include parser tables, syntax arenas, symbol -tables, output buffers, recursion stacks, and temporary proof or lowering -storage. Exhausting any execution-profile or private budget yields outer -`Incomplete(resource, limit, requested, coordinate?)` before publication. A -detected evaluator contradiction yields outer `InternalFailure`. Neither is an -Epsilon rejection, trap, divergence verdict, or partial successful observation. - -Interpreted Epsilon has no separate admission limit on hypothetical fully -expanded storage. Declared array extents constrain valid indexes and values; -they do not require a dense allocation or a logical byte-layout analysis. -Sparse zero homes, immutable sharing, and updates must preserve those exact -source semantics, including independence of copied values and view identity. - -The selected execution profile accounts for the storage its implementation -actually consumes, including retained snapshots, temporary construction, and -cumulative allocation where the lower evaluator cannot reclaim storage. -A small logical array does not bound repeated-update allocation, and a large -logical array does not imply that its untouched cells were allocated. -Resource counters, address calculations, and storage accesses must be checked -before operations that could overflow or exceed backing storage. Exhaustion -must reach the outer failure boundary above, not unchecked access or a partial -successful artifact. The profile specifies its counters and deterministic -refusal witnesses; diagnostic execution alone does not establish containment. - -These bounds do not substitute for independent evaluator refinement or the -lower chain's memory-safety obligations. No new source rejection, Epsilon trap, -or general-purpose storage facility follows from a private representation. - -Epsilon v1 imposes no small semantic maximum such as 128 declarations, 64 -locals, four parameters, three case fields, or 1,024 states. A compiler may -have such a finite private ceiling only if it reports it fail-closed as -`Incomplete`. +Epsilon separates three kinds of limits: + +Source-visible semantic bounds cover array lengths, `D`'s fixed buffers, `i32`/ +`u8` widths, default first-case sums, and explicit capacity checks in source. +Changing `[Node; N]` creates a new `D` program, not a new language. + +Execution-profile bounds cover sealed stdin size, Alpha memory and call-stack +limits, output buffer size, and optional step limits. They are documented per +evaluator build and never change Epsilon semantics. + +Private implementation budgets cover parser tables, AST arenas, symbol tables, +output buffers, recursion stacks, and temporary lowering memory. Hitting any +profile or private limit produces outer +`Incomplete(resource, limit, requested, coordinate?)` before output is +published; an internal checker/evaluator contradiction yields `InternalFailure`. +Neither is an Epsilon rejection, trap, divergence, or partial success. + +Interpreted Epsilon imposes no separate static limit on hypothetical dense +memory. Array lengths bound valid indexes and values without requiring dense +allocation; sparse zero defaults and immutable sharing must preserve exact value +isolation and view behavior. + +An evaluator profile accounts for actual memory consumed—retained snapshots, +temporary values, and append-only allocations where storage is not freed. A +small array can still exhaust memory under repeated updates, and a huge array +need not allocate untouched elements. All counters, offsets, and accesses must +be checked before overflowing or exceeding backing memory so exhaustion triggers +outer `Incomplete` instead of unchecked access or partial output. + +Resource bounds never replace independent conformance checks or lower-chain +memory safety, and private storage tricks never add new source rejections or +traps. + +Epsilon v1 sets no small language caps (such as 128 declarations, 64 locals, 4 +parameters, 3 case fields, or 1,024 states). Any finite implementation limit +must fail closed as `Incomplete`. ## 11. Evaluator application and observation boundary -The Delta-written Epsilon evaluator implements the two judgments from section -1. It checks one exact Epsilon source closure before execution and then runs the -accepted program over one sealed stdin byte sequence. Divergence is represented -by actual nontermination of the evaluator, not by a returned staging value or a -work limit. +The Delta-written evaluator implements section 1: it checks one Epsilon source +closure, then runs the accepted program on one sealed stdin sequence. Divergence +means actual nontermination, not a returned sentinel or step limit. -The final physical request and observation envelope remains open until the -evaluator executes every Epsilon construct and Console effect. That envelope -must bind the exact evaluator artifact, source closure, stdin, resource profile, -and complete `RunEpsilon` observation without host parsing or policy. A private -`Unsupported` result is permitted only while developing an incomplete evaluator; -it grants no Epsilon judgment and cannot appear in a selected edge. +The physical request/observation envelope must bind the exact evaluator binary, +source closure, stdin, resource profile, and full `RunEpsilon` result without +host parsing or policy. A private `Unsupported` result is allowed only during +development and never in a shipped entry. -Epsilon has no Alpha backend. In particular, the evaluator owns no Alpha -instruction representation, label/fixup pass, tape serializer, or emitted-tape -capacity. An Epsilon program may write arbitrary bytes through its sealed -Console capability. The Epsilon-written Omega compiler D uses that ordinary -program behavior to publish an Alpha tape only because `alpha_bootstrap` is an -Omega compilation target implemented by D. +Epsilon has no Alpha backend: the evaluator has no Alpha instructions, fixup +pass, tape serializer, or tape buffer. Programs simply write bytes through +`Console`; `D` emits Alpha tapes only because `alpha_bootstrap` is an Omega +target implemented inside `D`. -The required evaluator-correctness relation is: +Evaluator correctness requires: ```text accepted Epsilon source + sealed stdin + evaluator execution -> the evaluator observation equals RunEpsilon(source, stdin) ``` -The checker reconstructs Epsilon meaning independently. The evaluator may use -private execution representations, but may not invoke an Epsilon compiler, -Alpha assembler, host compiler, or another semantic stage to determine program -behavior. Agreement with another implementation is diagnostic and never -replaces checked evaluator refinement. +Independent checks derive Epsilon behavior directly from this spec. The +evaluator may use private runtime structures, but may not shell out to an +Epsilon compiler, Alpha assembler, host compiler, or another semantic stage. +Agreement with another implementation is a useful cross-check, not a substitute +for spec-based verification. ## 12. Conformance and change control -A conforming implementation provides: +A conforming implementation supplies: -1. positive and negative coverage of this grammar and every closed reason; -2. exact byte-coordinate, trap, evaluation-order, and I/O tests; -3. whole-closure forward-reference and fixed-storage controls; -4. private-budget controls proving evaluator exhaustion publishes no Epsilon - observation; and -5. direct checked evaluator refinement with mutations of the source, stdin, - resource profile, and observation. +1. positive and negative tests for this grammar and every rejection reason; +2. exact byte-offset, trap, evaluation-order, and I/O tests; +3. whole-closure forward-reference and fixed-storage tests; +4. resource-limit tests proving exhaustion emits no Epsilon observation; +5. independent refinement tests mutating source, stdin, profile, and output. -No existing Epsilon corpus is authoritative. The former translator and samples -were deleted, and no compatibility behavior survives through Git history. -Future syntax or semantics enter Epsilon only through an explicit contract -revision justified by the concrete needs and total assurance cost of `D`. +No legacy Epsilon corpus defines the language: the old translator and samples +were deleted and carry no backward-compatibility weight. New syntax or semantics +require an explicit spec update justified by `D`'s concrete needs and total +audit cost. diff --git a/bootstrap/epsilon/interpreter/EVALUATOR_ENTRY.md b/bootstrap/epsilon/interpreter/EVALUATOR_ENTRY.md index ceb8028e0c90..696552d8e389 100644 --- a/bootstrap/epsilon/interpreter/EVALUATOR_ENTRY.md +++ b/bootstrap/epsilon/interpreter/EVALUATOR_ENTRY.md @@ -1,22 +1,20 @@ # Epsilon evaluator entry: canonical request and observation envelope -This document defines the evaluator's realized entry boundary for the selected -lower chain and derives its explicit resource, request, and observation -profile. It satisfies the EPSILON-EVALUATOR entry obligation: one explicit -profile, exact and adjacent refusals, every lower-chain resource refusal -carried to the section-10 outer `Incomplete`, and no Epsilon observation on -any resource or transport refusal. The private diagnostic adapter -(`tests/bootstrap/interpreted/omega-executable/execution_driver.delta`, profiled -in [EVALUATOR_PROFILE.md](EVALUATOR_PROFILE.md)) is not this boundary; it -remains the development transport only. - -The evaluator is unchanged: this document's edge wraps the same packed -`epsilon_compiler.delta.sources` closure whose checking and execution the -diagnostic profile records. What changes is the boundary. The diagnostic -adapter owns a private request frame and private observation tags; the -canonical entry owns a versioned request envelope, an artifact binding, an -exact stdin section, a canonical observation grammar, and a refusal frame that -no observation can produce. +This document specifies the canonical entry interface for the Epsilon evaluator +on the selected lower chain and records its resource, request, and observation +limits. It fulfills the EPSILON-EVALUATOR entry requirement: one explicit +profile, exact and off-by-one refusals, every lower-chain resource failure +mapped to section 10's outer `Incomplete`, and zero Epsilon output on any +resource or transport refusal. The development driver +(`tests/bootstrap/interpreted/omega-executable/execution_driver.delta`, documented +in [EVALUATOR_PROFILE.md](EVALUATOR_PROFILE.md)) is separate and for diagnostics +only. + +Both entries wrap the same packed `epsilon_compiler.delta.sources` library whose +checking and runtime behavior the diagnostic profile measures. Only the outer +framing differs: the diagnostic driver uses private tags, while the canonical +entry enforces a versioned request header, artifact hash check, exact stdin +slice, canonical observation format, and an unmistakable refusal frame. ## Selected composition @@ -28,23 +26,21 @@ no observation can produce. | Delta support section | 4,301 | `439fef90e10007baec81920e84b89f50ad815a27af80499e4240e1dcd55f9243` | | canonical evaluator receipt | 709,282 | `f32f34b45b3feae12683bcbb54e2160eb1d22c07c70e159d0226468b9e65664d` | -The entry embeds the digest of the evaluator's ordered library sources. To build -the executable Delta subject, concatenate the packed library and -[`bootstrap/epsilon/interpreter.delta`](../interpreter.delta) in that order. The -entry sits beside the library directory so the digest covers exactly the library; -compiling that subject with the bound Delta support section through the bound -Delta compiler (`DCREQ`, profile 1, `ConformanceBytesV1`) reconstructs exactly -the canonical receipt. [The materializer](../../../tools/bootstrap/epsilon/evaluator_env.sh) -checks the entry, library and receipt identities. The [portable envelope -profile](../../../tests/bootstrap/interpreted/epsilon/README.md) checks the -entry's refusals on wire requests. The first declaration in the receipt is -`(def $application () Int 1)`, so the Gamma evaluator classifies it as an -application program. +The entry embeds the SHA-256 hash of the packed library. To build the Delta +input, concatenate the packed library and +[`bootstrap/epsilon/interpreter.delta`](../interpreter.delta) in order. Keeping +the entry beside the library directory ensures the hash covers only the library; +compiling that combined source with the Delta support section via the Delta +compiler (`DCREQ`, profile 1, `ConformanceBytesV1`) reproduces this exact +receipt. [The materializer](../../../tools/bootstrap/epsilon/evaluator_env.sh) +verifies the entry, library, and receipt hashes. The +[portable envelope profile](../../../tests/bootstrap/interpreted/epsilon/README.md) +tests wire-request refusals. Because the receipt begins with +`(def $application () Int 1)`, Gamma runs it in application mode. ## Request: EREQ v1 -The edge consumes one Gamma evaluator request whose sealed input is the -complete EREQ envelope: +The entry takes one Gamma request whose sealed input is an EREQ envelope: ```text 0..4 little-endian u32 receipt length = 709,282 @@ -65,17 +61,17 @@ complete EREQ envelope: 52.. exact source closure bytes, then exact stdin bytes, then exact end ``` -Validation order is fixed: extent `>= 52`, identity, profile, length high -bits, closure identity, source extent, stdin extent, exact end. A violation -publishes the EEOUT refusal frame below and never reaches the evaluator. +The entry validates fields in fixed order: length `>= 52`, identity bytes, +profile, clear high bits on lengths, closure hash, source length, stdin length, +and exact end of input. Any failure emits an EEOUT refusal frame without +invoking the evaluator. ## Publication classes -A status-zero invocation publishes exactly the entry's returned rope, whose -first byte selects one of two disjoint classes — neither class is producible -by the other: +On exit status 0, stdout is the entry's returned rope. Its first byte selects +one of two disjoint formats that can never collide: -**Canonical observations** (the complete `RunEpsilon` observation): +**Canonical observations** (the complete `RunEpsilon` result): | Tag | Result | Payload | | --- | --- | --- | @@ -83,8 +79,8 @@ by the other: | `01` | Trap | one closed trap-kind byte, then exact stdout prefix | | `02` | Reject | one closed rejection-reason byte, then four-byte little-endian source coordinate | -**Refusal frames**, always exactly 40 bytes, identity -`FF 45 45 4F 55 54 01 00` ("EEOUT" version 1) then: +**Refusal frames**, always 40 bytes starting with `FF 45 45 4F 55 54 01 00` +("EEOUT" version 1): ```text u8 outcome (1 = request refusal, 3 = internal failure) @@ -98,31 +94,26 @@ u32 code (outcome 1: 1 short_header, 2 identity_or_reserved, u64 coordinate, u64 limit, u64 requested, little-endian ``` -`coordinate` is the offending request offset for outcome 1 — the header -extent for `short_header`, the first differing byte for -`identity_or_reserved` and `artifact_mismatch`, the field offset for -`unknown_profile`, `length_high_bit`, and `section_extent`, and the first -trailing byte for `trailing_input`. `section_extent` additionally reports -`limit` = bytes remaining for that section and `requested` = the declared -length; all other v1 frames carry zero `limit`/`requested`. For outcome 3, -`coordinate` is the evaluator's reported diagnostic source coordinate. - -The layout mirrors the lower chain's `DCOUT` outcome frame so the family -stays machine-distinguishable: a refusal frame's `FF` lead cannot be an -observation tag, and no observation tag can be `FF`. - -Internal contradictions — `EpsilonEvaluatorSliceInternal` — publish EEOUT -outcome 3, not an observation: a staging internal is not an Epsilon judgment. - -**Incomplete transport outcomes.** The evaluator program cannot intercept a -lower-chain refusal: the generated `ConformanceBytesV1` adapter refuses an -oversized sealed input or output before or after `main` runs, and evaluator -context, stack, or pair exhaustion halts the process outright. These paths -therefore publish no bytes. At the edge boundary a nonzero status with empty -stdout is the section-10 outer `Incomplete(resource, limit, requested, -coordinate?)` — never an Epsilon observation, never an EEOUT frame, and never -a partial stdout. The status and the requester's own submitted extents carry -the fields: +For outcome 1, `coordinate` is the offending request byte offset: header length +for `short_header`, first differing byte for `identity_or_reserved` and +`artifact_mismatch`, field offset for `unknown_profile`, `length_high_bit`, and +`section_extent`, and first extra byte for `trailing_input`. `section_extent` +also sets `limit` to the remaining bytes and `requested` to the declared length; +all other v1 frames zero `limit` and `requested`. For outcome 3, `coordinate` is +the evaluator's diagnostic source offset. + +This layout mirrors the lower chain's `DCOUT` frame: its leading `FF` byte can +never match an observation tag, and no observation tag uses `FF`. + +Internal evaluator bugs (`EpsilonEvaluatorSliceInternal`) emit EEOUT outcome 3, +never an Epsilon observation. + +**Incomplete transport outcomes.** The evaluator cannot catch lower-chain limits: +the `ConformanceBytesV1` adapter rejects oversized sealed input or output +outside `main`, and context, stack, or pair exhaustion kills the process +immediately with empty stdout. A nonzero exit status with empty stdout therefore +maps to section 10's outer `Incomplete(resource, limit, requested, coordinate?)` +—never an Epsilon observation, EEOUT frame, or partial stdout: | Status | Resource | Limit | Requested | Coordinate | | ---: | --- | ---: | --- | --- | @@ -131,127 +122,104 @@ the fields: | 253 | sealed input bytes | 4,194,304 | the exact submitted sealed-input extent | none | | 254 | published observation bytes | 4,194,304 | 4,194,305 — the refused byte | none | -For the execution-side counters the transport cannot carry the program's -complete demand, so `requested` reports the refused unit — the least demand -the bound refuses — not a projected total. The sealed-input refusal instead -reports the exact submitted extent, which the requester itself knows. One -status can back several counters; the dominated-counter derivations in the -resource table below name the resource that actually binds in this -composition. The 256-context bound trips before the 524,288-entry value stack -or the 131,072 environment rows, and the adapter's 4,194,304-byte input and -output bounds trip before the evaluator's own 16 MiB transport bounds — a -request beyond 137,363,456 bytes is refused before the adapter sees its input -and classifies as `Incomplete(complete request, 137,363,456, submitted request -extent)` under the same status 253. A changed evaluator or adapter -composition must re-derive which counter behind each status binds first; the -mapping above belongs to this exact receipt. - -**Internal failure.** Every other process observation carries section 10's -`InternalFailure`: a nonzero status outside the four named above (248 -evaluator internal, 249 authored trap in the evaluator's own Delta code, 132 -Alpha VM illegal instruction, or an unassigned value), a status-zero -invocation with empty stdout or an unassigned lead byte, or a nonzero status -with nonempty stdout. None is an Epsilon judgment, a partial observation, or -an EEOUT frame. - -The classification is complete and disjoint: every process observation of -this edge is exactly one of a canonical observation, an EEOUT refusal frame, -an `Incomplete` transport outcome, or `InternalFailure`. No evaluator-internal -budget is added — the envelope classifies every named refusal path, so the -fallback clause of the board item does not apply, and no hypothetical -dense-storage sizing pass is introduced. +For execution counters, the transport cannot report total program demand, so +`requested` records the first refused unit rather than a projected total. For +sealed input, `requested` is the submitted size known by the caller. Where one +exit status covers multiple counters, the resource table below identifies which +limit trips first in this build: the 256-context cap trips before the +524,288-entry value stack or 131,072 environment rows, and the adapter's +4,194,304-byte input/output caps trip before Gamma's larger buffers. A request +larger than 137,363,456 bytes fails before the adapter runs and maps to +`Incomplete(complete request, 137,363,456, submitted request extent)` under +status 253. Changing the evaluator or adapter requires re-checking which counter +binds first. + +**Internal failure.** Any other process result maps to section 10's +`InternalFailure`: any other nonzero status (248 evaluator internal, 249 Delta +trap in the evaluator, 132 Alpha illegal instruction, or unknown codes), status +0 with empty stdout or an unknown tag byte, or a nonzero status with nonempty +stdout. None is an Epsilon result or EEOUT frame. + +These four classes partition all possible process outcomes cleanly: canonical +observation, EEOUT refusal, `Incomplete`, or `InternalFailure`. No internal +budget layer or hypothetical dense-storage pass is added. ## Exact resource counters -The entry owns no internal budget; every dynamic resource remains a counter -of the selected lower chain, now charged against the canonical receipt. +The entry adds no internal budget; every runtime limit comes from the lower +chain running the canonical receipt: | Counter | Owner | Limit | Refusal | Witness | | --- | --- | ---: | --- | --- | -| complete request | Gamma evaluator | 137,363,456 bytes | `Incomplete` via status 253, empty stdout | adjacent pinned by [EVALUATOR_PROFILE.md](EVALUATOR_PROFILE.md) and `tests/bootstrap/proofs` boundary gates | -| sealed input | `ConformanceBytesV1` adapter | 4,194,304 bytes | `Incomplete` via status 253, empty stdout | exact/adjacent executed in [`tests/bootstrap/interpreted/epsilon/evaluator-entry/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/evaluator-entry/README.md) | -| EREQ envelope fields | canonical entry | fixed 52-byte header, declared sections, exact end | EEOUT outcome 1 | exact/adjacent executed in the same gate | -| published observation | `ConformanceBytesV1` adapter | 4,194,304 bytes | `Incomplete` via status 254, empty stdout | adjacent pinned by [`tests/bootstrap/interpreted/delta/staged-compiler/run.sh`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/staged-compiler/run.sh) | -| cumulative immutable pairs | Gamma evaluator | 3,422,453,760 nodes | `Incomplete` via status 252, empty stdout | boundary no longer executable in gate time; [`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) crosses the entire retired V4 arena and [`tests/bootstrap/interpreted/epsilon/pair-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/pair-boundary/README.md) retains the refused fixture for opt-in execution | -| live call contexts | Gamma evaluator | 256 contexts | `Incomplete` via status 250, empty stdout | exact/adjacent executed in the entry gate: 34 nested calls admitted, the 35th refused | -| temporary value stack | Gamma evaluator | 524,288 entries | `Incomplete` via status 250, empty stdout | dominated by the context bound | -| lexical environment rows | Gamma evaluator | 131,072 rows | `Incomplete` via status 250, empty stdout | dominated likewise | - -Effective Epsilon-facing extents follow directly: `source + stdin <= -4,194,252` bytes inside one 4,194,304-byte sealed input after the 52-byte -header, and a published `Exit` observation carries at most 4,194,299 stdout -bytes after its five-byte tag/code header. +| complete request | Gamma evaluator | 137,363,456 bytes | `Incomplete` via status 253, empty stdout | adjacent test in [EVALUATOR_PROFILE.md](EVALUATOR_PROFILE.md) and `tests/bootstrap/proofs` boundary gates | +| sealed input | `ConformanceBytesV1` adapter | 4,194,304 bytes | `Incomplete` via status 253, empty stdout | exact and adjacent tests in [`tests/bootstrap/interpreted/epsilon/evaluator-entry/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/evaluator-entry/README.md) | +| EREQ envelope fields | canonical entry | fixed 52-byte header, declared sections, exact end | EEOUT outcome 1 | exact and adjacent tests in the same gate | +| published observation | `ConformanceBytesV1` adapter | 4,194,304 bytes | `Incomplete` via status 254, empty stdout | adjacent test in [`tests/bootstrap/interpreted/delta/staged-compiler/run.sh`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/staged-compiler/run.sh) | +| cumulative immutable pairs | Gamma evaluator | 3,422,453,760 nodes | `Incomplete` via status 252, empty stdout | exact limit too slow for gate time; [`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) crosses the retired V4 arena and [`tests/bootstrap/interpreted/epsilon/pair-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/pair-boundary/README.md) keeps the refused test opt-in | +| live call contexts | Gamma evaluator | 256 contexts | `Incomplete` via status 250, empty stdout | exact and adjacent tests in entry gate: 34 nested calls pass, 35th fails | +| temporary value stack | Gamma evaluator | 524,288 entries | `Incomplete` via status 250, empty stdout | dominated by the context cap | +| lexical environment rows | Gamma evaluator | 131,072 rows | `Incomplete` via status 250, empty stdout | dominated by the context cap | + +After the 52-byte EREQ header, `source + stdin <= 4,194,252` bytes fits inside +the 4,194,304-byte sealed input, and an `Exit` result carries up to 4,194,299 +stdout bytes after its five-byte header. ## Storage account -The canonical and diagnostic entries use the same evaluator storage: every Delta value is a node in the evaluator's -cumulative immutable pair arena, sparse runtime storage keeps declared extents -exact without dense allocation (`O(log E)` new nodes per indexed update, -sharing every untouched sibling), and declared bounds and value semantics stay -exact under cumulative per-update allocation. The canonical receipt adds only -the entry's fixed header checks and one cursor into the sealed input. -The cursor starts at the admitted stdin offset. Each read advances toward the -end of the request. Opening stdin costs the same number of pairs for an empty -stream and a full one. - -In one Linux x86-64 run, a program read the first two bytes of a 1 MiB -stdin, wrote the first byte (`Q`) and exited with the second (`7`). The -native evaluator built from revision `b95769558667` took 1.376 seconds and -peaked at 181,156 KiB RSS. The native evaluator built with the cursor took -0.129 seconds and peaked at 26,492 KiB. Both returned `000700000051` for the -same program and input. Only the evaluator identity differed in the request. -These times cover one invocation on a shared host. +Both entries share the same evaluator storage: every Delta value sits in Gamma's +append-only pair arena, sparse arrays keep declared extents without dense +allocation (`O(log E)` new nodes per write, sharing untouched siblings), and +bounds/value rules hold under cumulative allocation. The canonical entry adds +only header validation and one cursor into the sealed input starting at the +stdin offset. Opening stdin allocates the same fixed pair count whether stdin is +empty or full. + +On Linux x86-64, a test program read two bytes from a 1 MiB stdin, printed the +first (`Q`), and exited with the second (`7`). The older native evaluator +(`b95769558667`) took 1.376 s and 181,156 KiB peak RSS; with the input cursor, +it took 0.129 s and 26,492 KiB peak RSS. Both returned `000700000051` (single +shared-host runs; only the evaluator hash differed). The [pair-boundary test](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/pair-boundary/README.md) -exercises cumulative allocation through repeated sparse-array writes. An -earlier macOS arm64 run reached its 40,265,319th pair during execution -and returned status 252 with empty stdout and stderr in 4,250.673 seconds. +drives pair allocation via repeated sparse-array writes. On macOS arm64, an +earlier run hit its 40,265,319th pair and exited 252 with empty stdout and +stderr in 4,250.673 seconds. ## Refusal witnesses The [archived entry gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/evaluator-entry/README.md) -records these request and execution boundaries. Its admitted Console programs -use the historical `@` spelling. Replay those programs with the current `&` -spelling to exercise the same execution boundaries. +tests these boundaries. Its Console fixtures use the old `@` syntax; update them +to `&` to replay them now. | Boundary | Exact (admitted) | Adjacent (refused) | | --- | --- | --- | -| sealed input extent | 4,194,304-byte EREQ: admitted past the adapter, then EEOUT `trailing_input` at 52 | 4,194,305-byte EREQ: `Incomplete` via status 253, empty stdout | -| EREQ header | 52-byte header, zero-section request: admitted | 51-byte header: EEOUT `short_header` at coordinate = extent | -| identity | all 8 bytes exact: admitted | each adjacent identity byte: EEOUT `identity_or_reserved` at its offset | -| profile | profile 1: admitted | profiles 0, 2, 2^32-1: EEOUT `unknown_profile` at 8 | -| length high bit | high bits clear: admitted | high bit set: EEOUT `length_high_bit` at 15 or 19 | -| closure identity | bound digest: admitted | each adjacent digest byte: EEOUT `artifact_mismatch` at 20 + index | -| section extents | declared = remaining: admitted | declared one beyond: EEOUT `section_extent` at 12 or 16 | -| exact end | no trailing bytes: admitted | one trailing byte: EEOUT `trailing_input` at first extra offset | -| live call contexts | 34 nested non-tail machine calls: `Exit` 34, stdout `A` | the 35th nested call: `Incomplete` via status 250, empty stdout | - -Every refusal in the gate publishes either the exact EEOUT frame above or an -`Incomplete` transport outcome — a lower-chain nonzero status with empty -stdout; none publishes a canonical observation. +| sealed input extent | 4,194,304-byte EREQ: passes adapter, then EEOUT `trailing_input` at 52 | 4,194,305-byte EREQ: `Incomplete` via status 253, empty stdout | +| EREQ header | 52-byte header, zero-section request: passes | 51-byte header: EEOUT `short_header` at coordinate = extent | +| identity | all 8 bytes exact: passes | each differing byte: EEOUT `identity_or_reserved` at its offset | +| profile | profile 1: passes | profiles 0, 2, 2^32-1: EEOUT `unknown_profile` at 8 | +| length high bit | high bits clear: passes | high bit set: EEOUT `length_high_bit` at 15 or 19 | +| closure identity | matching digest: passes | each differing byte: EEOUT `artifact_mismatch` at 20 + index | +| section extents | declared = remaining: passes | declared one past remaining: EEOUT `section_extent` at 12 or 16 | +| exact end | no trailing bytes: passes | one trailing byte: EEOUT `trailing_input` at first extra offset | +| live call contexts | 34 nested non-tail machine calls: `Exit` 34, stdout `A` | 35th nested call: `Incomplete` via status 250, empty stdout | + +Every refusal above emits either an exact EEOUT frame or an `Incomplete` nonzero +exit with empty stdout—never a canonical observation. ## What remains open -This document discharges the evaluator-entry leg: a realized section-11 -envelope, its resource profile, deterministic refusal witnesses, the carry of -every lower-chain refusal to the outer `Incomplete`, and the rule that no -resource, transport, or request refusal publishes an Epsilon observation. The -envelope binds the exact evaluator artifact, the exact source closure, the -sealed stdin, this profile, and the complete -`RunEpsilon` observation without host parsing or policy, within the construct -coverage the evaluator currently implements. The last two legs are now -covered by these gates. The following measurements describe an earlier -compiler and evaluator composition. +This document completes the entry requirement: a section-11 envelope, resource +profile, deterministic refusal tests, lower-chain refusal mapping to outer +`Incomplete`, and zero Epsilon output on refusals. The envelope binds the exact +evaluator, source closure, stdin, profile, and `RunEpsilon` observation without +host parsing or policy for all constructs the evaluator supports. The following +earlier-revision test runs cover the remaining legs: [`tests/bootstrap/interpreted/epsilon/d-composition/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/d-composition/README.md) -checks and executes the whole 569,920-byte D closure — all eight manifested -members — through this canonical edge, including D's own -`OmegaScalarCompiler::compile` publishing the exact emitted Alpha tape, and -records the checking-versus-execution allocation split (8e63b21300), while +checks and runs the full 569,920-byte, eight-file D closure—including +`OmegaScalarCompiler::compile` emitting the exact Alpha tape and recording the +checking/execution allocation split (8e63b21300)—while [`tests/bootstrap/interpreted/epsilon/refinement/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/refinement/README.md) -refines `RunEpsilon` over the exact D closure member sources: the -contract-derived model's observations agree with this edge byte-for-byte on -the same eight customers, with discriminating member mutations spanning -every member (fc23c46e4f). What remains under EPSILON-EVALUATOR is the -standing conformance clause: witnessed checking/runtime defects are -corrected when a D slice or contract control witnesses one, and none is -recorded. +checks byte-for-byte agreement with `RunEpsilon` across all eight files and +mutations (fc23c46e4f). Only the standing conformance rule remains under +EPSILON-EVALUATOR: fix any checking or runtime bug that a D run or test exposes +(none is currently known). diff --git a/bootstrap/epsilon/interpreter/EVALUATOR_PROFILE.md b/bootstrap/epsilon/interpreter/EVALUATOR_PROFILE.md index d73471bdb3fa..da7f514d4eaf 100644 --- a/bootstrap/epsilon/interpreter/EVALUATOR_PROFILE.md +++ b/bootstrap/epsilon/interpreter/EVALUATOR_PROFILE.md @@ -1,22 +1,19 @@ # Epsilon evaluator edge profile -This document derives the explicit resource, request, and observation profile -of the currently composed Epsilon evaluator edge against the selected lower -chain: the Beta-authored Gamma evaluator executing a Delta-compiled -`ConformanceBytesV1` receipt under `GammaComposedV2`. It satisfies the -EPSILON-EVALUATOR obligation to name one explicit profile with exact and -adjacent refusals; every refusal below publishes no Epsilon observation. - -The profile covers the *diagnostic* edge: the private tagged result produced -by the bound execution driver. The realized section-11 request and -observation envelope is now -[`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md): the same packed closure plus the -bound canonical entry source compiles to the canonical receipt that consumes -the EREQ envelope and publishes canonical observations or EEOUT refusal -frames. This document remains the diagnostic edge's record; the entry -document carries the canonical profile. Nothing in either grants an Epsilon -judgment beyond the evaluator's checked coverage, adds an Epsilon language -bound, or restores an Epsilon Alpha backend. +This document records the resource, request, and observation limits of the +diagnostic Epsilon evaluator running on the lower chain: the Beta-written Gamma +evaluator executing a Delta-compiled `ConformanceBytesV1` receipt under +`GammaComposedV2`. It fulfills the EPSILON-EVALUATOR requirement to document one +explicit profile with exact and off-by-one refusals; no refusal below produces +an Epsilon result. + +This profile covers only the *diagnostic* entry: the private tagged format used +by the development execution driver. The canonical section-11 request and +observation interface lives in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md), where +the same packed closure plus the canonical entry source builds a receipt that +reads EREQ envelopes and emits canonical observations or EEOUT refusal frames. +Neither document extends Epsilon beyond what the evaluator checks, adds an +Epsilon language limit, or restores an Epsilon Alpha backend. ## Selected composition @@ -28,21 +25,19 @@ bound, or restores an Epsilon Alpha backend. | Delta support section | 4,301 | `439fef90e10007baec81920e84b89f50ad815a27af80499e4240e1dcd55f9243` | | reconstructed evaluator receipt | 701,880 | `f1388f3008bb1a13ae1b6e726508f9d491dcee4f1dfbc4ec95be2489f0b71e91` | -Compilation of the packed evaluator plus driver plus the bound support -section through the bound Delta compiler (`DCREQ`, profile 1) reconstructs -exactly the receipt. The [materializer](../../../tools/bootstrap/epsilon/evaluator_env.sh) -checks the library, driver and receipt identities. On macOS -arm64 the reconstruction took 222.770 seconds at the measured revision; that -is a host measurement, not a profile bound. +Compiling the packed evaluator, execution driver, and support section with the +Delta compiler (`DCREQ`, profile 1) reproduces this exact receipt. The +[materializer](../../../tools/bootstrap/epsilon/evaluator_env.sh) verifies the +library, driver, and receipt hashes. On macOS arm64, reconstruction took 222.770 +seconds at the measured revision (a host timing, not a limit). -The receipt's first declaration is `(def $application () Int 1)`, so the -Gamma evaluator classifies it as an application program: its failures map to -the generated-program status block, and its published bytes are exactly its -declared result buffer. +Because the receipt begins with `(def $application () Int 1)`, the Gamma +evaluator runs it as an application: failures map to the generated-program exit +codes, and stdout carries the returned result buffer. ## Request -The edge consumes one Gamma evaluator request: +The evaluator reads one Gamma request: ```text 0..4 little-endian u32 receipt length = 701,880 @@ -54,17 +49,16 @@ The edge consumes one Gamma evaluator request: ... all remaining bytes as sealed stdin ``` -The evaluator realizes the receipt's sealed input as a lazy tag-3 rope view; -the driver validates `frame >= 4` bytes and `declared length <= frame - 4`, -then forms a checked `EpsilonSourceView` over `frame[4 .. 4 + length)` and -starts the Console cursor at `4 + length` in that same frame. A frame -that fails either check produces the private `MalformedRequest` tag `05` - -an ordinary published diagnostic result of the private adapter contract, not -an Epsilon rejection, trap, or resource verdict. +The Gamma evaluator passes sealed input as a lazy tag-3 rope view. The driver +checks `frame >= 4` and `declared length <= frame - 4`, creates a checked +`EpsilonSourceView` over `frame[4 .. 4 + length)`, and places the Console input +cursor at `4 + length`. Failing either check emits the private +`MalformedRequest` tag `05`—a normal driver diagnostic, not an Epsilon +rejection, trap, or resource error. ## Observation -A status-zero invocation publishes exactly the driver's returned rope: +When the process exits 0, stdout contains the driver's returned rope: | Tag | Result | Payload | | --- | --- | --- | @@ -74,69 +68,64 @@ A status-zero invocation publishes exactly the driver's returned rope: | `03` | Internal | four-byte source offset | | `05` | MalformedRequest | none | -Every refusal below returns a nonzero process status with empty stdout: no -tagged result, no partial stdout, and therefore no Epsilon observation of -any kind. Divergence is actual evaluator nontermination; the selected -profile has no observation-step counter, consistent with section 11. +Every refusal below exits nonzero with empty stdout—no tag, no partial stdout, +and no Epsilon observation. Consistent with section 11, this profile has no step +limit; nonterminating programs diverge. ## Exact resource counters -The evaluator owns no internal budget today; every dynamic resource is a -counter of the selected lower chain, consumed by the running receipt. Each -counter names its owner, limit, refusal observation, and witness. +The evaluator adds no internal budget; every runtime limit comes from the lower +chain running the receipt: | Counter | Owner | Limit | Refusal | Witness | | --- | --- | ---: | --- | --- | -| complete request | Gamma evaluator | 137,363,456 bytes | status 253, empty stdout | adjacent pinned by the Gamma request-extent gates (the V4-era 16,777,217-byte witness predates AlphaBootstrapV5) | -| sealed input | `ConformanceBytesV1` adapter | 4,194,304 bytes | status 253, empty stdout | exact/adjacent executed below | -| driver frame fields | private driver | `frame >= 4`, `length <= frame - 4` | tag `05` | exact/adjacent executed below | -| published observation | `ConformanceBytesV1` adapter | 4,194,304 bytes | status 254, empty stdout | adjacent refusal pinned by [`tests/bootstrap/interpreted/delta/staged-compiler/run.sh`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/staged-compiler/run.sh) (`bytes_concat` doubling over a 2,097,153-byte input) | -| cumulative immutable pairs | Gamma evaluator | 3,422,453,760 nodes | status 252, empty stdout | exact boundary no longer executable in gate time; [`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) crosses the retired V4 arena and the evaluator-level exhaustion fixture is retained opt-in below | -| live call contexts | Gamma evaluator | 256 contexts | status 250, empty stdout | exact/adjacent executed below | -| temporary value stack | Gamma evaluator | 524,288 entries | status 250, empty stdout | dominated by the context bound in this composition | -| lexical environment rows | Gamma evaluator | 131,072 rows | status 250, empty stdout | dominated likewise | -| nested source lists | Gamma evaluator census | 255 levels | status 3 at census, before the marker classifies | fixed property of the admitted receipt source | -| buffered output | Gamma evaluator | 135,266,304 bytes | status 254, empty stdout | unreachable here: the adapter's tighter output bound always refuses first | - -Two bounds therefore dominate this composition by construction: - -- The adapter's 4,194,304-byte sealed-input bound binds before the request - extent can: the largest admitted request is `4 + 701,880 + 4,194,304 = - 4,896,188` bytes, far below 137,363,456. The request extent refuses only - requests the adapter would already refuse, so it is a dominated outer - bound - still pinned by the executed adjacent witness. -- The adapter's 4,194,304-byte output bound binds before the evaluator's - 135,266,304-byte buffered-output limit for the same reason. - -Effective Epsilon-facing extents follow directly: `source + stdin <= -4,194,300` bytes, and a published `Exit` observation carries at most -4,194,299 stdout bytes after its five-byte tag/code header. +| complete request | Gamma evaluator | 137,363,456 bytes | status 253, empty stdout | adjacent test in Gamma request-extent gates (the V4 16,777,217-byte run predates AlphaBootstrapV5) | +| sealed input | `ConformanceBytesV1` adapter | 4,194,304 bytes | status 253, empty stdout | exact and adjacent runs below | +| driver frame fields | private driver | `frame >= 4`, `length <= frame - 4` | tag `05` | exact and adjacent runs below | +| published observation | `ConformanceBytesV1` adapter | 4,194,304 bytes | status 254, empty stdout | adjacent test in [`tests/bootstrap/interpreted/delta/staged-compiler/run.sh`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/staged-compiler/run.sh) (`bytes_concat` doubling a 2,097,153-byte input) | +| cumulative immutable pairs | Gamma evaluator | 3,422,453,760 nodes | status 252, empty stdout | exact limit too slow for gate time; [`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) crosses the retired V4 arena and the evaluator exhaustion test stays opt-in below | +| live call contexts | Gamma evaluator | 256 contexts | status 250, empty stdout | exact and adjacent runs below | +| temporary value stack | Gamma evaluator | 524,288 entries | status 250, empty stdout | dominated by the context cap here | +| lexical environment rows | Gamma evaluator | 131,072 rows | status 250, empty stdout | dominated by the context cap here | +| nested source lists | Gamma evaluator census | 255 levels | status 3 at census, before application mode | fixed property of the checked receipt | +| buffered output | Gamma evaluator | 135,266,304 bytes | status 254, empty stdout | unreachable: the adapter's smaller output cap triggers first | + +Two adapter limits always bind before the Gamma evaluator's outer limits: + +- The 4,194,304-byte sealed-input cap limits total accepted requests to + `4 + 701,880 + 4,194,304 = 4,896,188` bytes, far below Gamma's 137,363,456 + bytes. Gamma's outer request limit only catches frames the adapter would + already refuse, though it stays tested. +- The 4,194,304-byte output cap always triggers before Gamma's 135,266,304-byte + output buffer fills. + +Therefore, Epsilon inputs satisfy `source + stdin <= +4,194,300` bytes, and a published `Exit` result holds at most 4,194,299 stdout +bytes after its five-byte header. ## Storage account -Under [section 10](../LANGUAGE.md#10-resource-classification), the profile -accounts for what the evaluator actually allocates, not for hypothetical -dense storage. The receipt realizes every Delta value - syntax nodes, -checked ledgers, runtime roots, values, snapshots, views, the input cursor and -output ropes - as nodes in the evaluator's cumulative immutable pair arena. -Gamma cannot reclaim pairs, so demand is the sum of checking-phase and -execution-phase allocations. - -Sparse runtime storage keeps declared extents exact without dense -allocation: - -- `epsilon_runtime_array_index_valid` enforces the declared extent `E in - 1..2147483647` on every access; unwritten indexes read the typed zero home - and allocate nothing. -- An indexed store first reads the selected path, validating its extent, - split points and leaf. Reconstruction uses the same immutable parent - snapshots. `epsilon_runtime_array_insert` rebuilds at most 31 midpoint - partitions and shares the untouched sibling at each split. A run of empty - siblings is represented by one checked interval around its occupied branch. -- Record field updates rebuild a path in an AVL tree ordered by checked - field identity. Each update copies O(log F) nodes for F stored fields. - -The workload measurements below used the earlier 721,484-byte diagnostic receipt on macOS arm64. +Under [section 10](../LANGUAGE.md#10-resource-classification), this profile +tracks actual evaluator allocations rather than hypothetical dense memory. Every +Delta value—AST nodes, checked tables, runtime roots, snapshots, views, the +input cursor, and output ropes—lives in Gamma's append-only immutable pair +arena. Because Gamma never frees pairs, total demand is checking allocations +plus execution allocations. + +Sparse runtime arrays preserve declared lengths without dense allocation: + +- `epsilon_runtime_array_index_valid` checks the declared extent + `E in 1..2147483647` on every access; unwritten indexes return typed zero + without allocating. +- Indexed writes validate the path's extent, split points, and leaf, then + rebuild only that path using immutable snapshots. + `epsilon_runtime_array_insert` updates at most 31 midpoint splits and shares + every untouched sibling. Contiguous empty siblings compress into a single + checked interval around the occupied branch. +- Record field updates rebuild one path in an AVL tree keyed by checked field + identity, copying O(log F) nodes for F stored fields. + +These macOS arm64 timings used the earlier 721,484-byte diagnostic receipt: | Workload | Observation | Time | | --- | --- | ---: | @@ -144,72 +133,56 @@ The workload measurements below used the earlier 721,484-byte diagnostic receipt | `[i32; 2147483647]`, 5,001 scattered updates then `values[0] == 0` | `00` + exit 0 + stdout `B` | 151.25 s | | `[i32; 4]`, 20,001 sequential updates then exact final cells | `00` + exit 0 + stdout `A` | 505.66 s | -The first workload cannot execute under any dense realization - the declared -extent alone would exceed the arena - so its exact result demonstrates the -sparse account. The last two show declared bounds and value semantics -remaining exact under cumulative per-update allocation. Their refusal mode -is pair-arena exhaustion: `status 252` with empty stdout, the same boundary -[`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) -executes at the whole-node maximum and one -beyond. The direct evaluator-level 252 witness is now executed: -[`tests/bootstrap/interpreted/epsilon/pair-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/pair-boundary/README.md) -runs a bounded sparse-write loop as the admitted control beside its -unbounded counterpart, which drove the canonical evaluator receipt's -execution phase to the refused 40,265,319th pair node — status 252, empty -stdout, empty stderr, 4,250.673 seconds on macOS arm64. The derivation -above predicted the boundary; the gate now records the refusal. +The first run proves sparse storage because a dense `[i32; 2147483647]` cannot +fit in the pair arena. The other two confirm that bounds and value semantics +stay intact under repeated updates. Exhausting the pair arena exits with +`status 252` and empty stdout—the same boundary tested in +[`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md). +The opt-in test [`tests/bootstrap/interpreted/epsilon/pair-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/pair-boundary/README.md) +pairs a passing bounded loop with an unbounded write loop that hit the +40,265,319th pair on the canonical receipt (status 252, empty stdout/stderr, +4,250.673 s on macOS arm64), confirming the predicted failure mode. ## Refusal witnesses -The recorded macOS arm64 timings below used the earlier 721,484-byte diagnostic receipt. +These macOS arm64 timings also used the earlier 721,484-byte diagnostic receipt: | Boundary | Exact (admitted) | Adjacent (refused) | | --- | --- | --- | | sealed input extent | `4,194,304`-byte frame: status 0, tagged `02` rejection of the empty declared source (the ~4.19M-byte stdin rope fits the arena) in 664.88 s | `4,194,305`-byte frame: status 253, empty stdout in 1.42 s | -| request extent | 137,363,456-byte request frame admitted past the extent check; the tighter adapter bound always refuses first in this composition | 137,363,457-byte request frame: status 253, empty stdout (pinned by the Gamma profile; the recorded 16,777,216/16,777,217-byte executions are V4-era measurements) | -| driver source-length field | declared length equal to the remaining frame: executes to `00` + exit 0 + `A` | declared length one beyond the remaining frame: tag `05` | +| request extent | 137,363,456-byte request frame passes the extent check; the smaller adapter cap refuses first here | 137,363,457-byte request frame: status 253, empty stdout (from the Gamma profile; 16,777,216/16,777,217-byte runs were V4-era) | +| driver source-length field | declared length equal to remaining frame: `00` + exit 0 + `A` | declared length one past remaining frame: tag `05` | | live call contexts | 34 nested non-tail machine calls: `00` + exit 34 + `A` | 35 nested calls: status 250, empty stdout, ~1.6 s | -Each Epsilon invocation used several Gamma contexts in that run. The -256-context bound admitted 34 nested machine calls and refused the 35th -before any observation. It is not an Epsilon language limit; a different -receipt may shift it. +Because each Epsilon call uses several Gamma contexts, the 256-context cap +allowed 34 nested calls and refused the 35th before producing output. This is a +receipt limit, not an Epsilon language cap, and may change if the receipt +changes. -Refusals inherited from the lower chain rather than re-executed on this -diagnostic receipt: the -adapter output extent (254) and authored-trap (249) statuses are pinned by +Lower-chain refusals verified elsewhere rather than re-run on this receipt: +adapter output overflow (254) and program traps (249) are tested in [`tests/bootstrap/interpreted/delta/staged-compiler/run.sh`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/staged-compiler/run.sh); -the pair-arena maximum (252) is pinned -exact/adjacent by [`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) -and executed directly at the canonical evaluator edge by +pair exhaustion (252) is tested in +[`tests/bootstrap/proofs/heap-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) +and at the canonical evaluator edge in [`tests/bootstrap/interpreted/epsilon/pair-boundary/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/pair-boundary/README.md); -evaluator-owned statuses 1, -2, 3, 4, and 248 belong to scalar, pre-application, and unclassified paths -of [`bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md`](../../gamma/interpreter/EVALUATOR_PROFILE.md), -and status 132 remains the -Alpha VM's illegal-instruction refusal, never an Epsilon outcome. +statuses 1, 2, 3, 4, and 248 belong to +[`bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md`](../../gamma/interpreter/EVALUATOR_PROFILE.md); +and status 132 is Alpha's illegal-instruction trap, never an Epsilon result. ## What remains open -This profile discharges the derivation leg only: one explicit -resource/request/observation profile, its counters, deterministic refusal -witnesses, and the rule that every resource or transport refusal publishes -no Epsilon observation. The evaluator-entry leg is now realized separately -in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md): a versioned EREQ request -envelope, canonical observation grammar, and EEOUT refusal frame bound to a -canonical receipt, still within the evaluator's current construct coverage. -That document also carries each lower-chain refusal status to the outer -`Incomplete` at the edge boundary; the envelope classifies every named -refusal path, so no evaluator-internal budget layer was needed. The last two -legs are now exercised gates on that unchanged canonical composition: +This document covers only the diagnostic profile: its counters, exact/adjacent +refusal tests, and guarantee that resource/transport refusals emit no Epsilon +output. The canonical entry lives in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md) +(EREQ v1 requests, canonical observations, EEOUT refusal frames, and mapping +every lower-chain refusal to outer `Incomplete` without needing an internal +budget layer). Two test suites exercise that canonical build: [`tests/bootstrap/interpreted/epsilon/d-composition/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/d-composition/README.md) -checks and executes the whole 569,920-byte D closure — all eight manifested -members — through the canonical edge, including D's own -`OmegaScalarCompiler::compile` publishing the exact emitted Alpha tape -(8e63b21300), and +checks and runs the full 569,920-byte, eight-file D closure—including +`OmegaScalarCompiler::compile` emitting the exact Alpha tape (8e63b21300)—and [`tests/bootstrap/interpreted/epsilon/refinement/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/refinement/README.md) -refines `RunEpsilon` over the exact D closure member sources byte-for-byte -with discriminating member mutations spanning every member (fc23c46e4f). -What remains under EPSILON-EVALUATOR is the standing conformance clause: -witnessed checking/runtime defects are corrected when a D slice or contract -control witnesses one, and none is recorded. +checks byte-for-byte agreement with `RunEpsilon` over the D closure and member +mutations (fc23c46e4f). Only the standing conformance rule remains under +EPSILON-EVALUATOR: fix any checking or runtime bug that a D run or test exposes +(none is currently known). diff --git a/bootstrap/epsilon/interpreter/FEATURE_LEDGER.md b/bootstrap/epsilon/interpreter/FEATURE_LEDGER.md index 7ce8c7d3eeae..7b28ce349313 100644 --- a/bootstrap/epsilon/interpreter/FEATURE_LEDGER.md +++ b/bootstrap/epsilon/interpreter/FEATURE_LEDGER.md @@ -1,64 +1,59 @@ # Epsilon feature ledger -Epsilon is justified by the smallest robust surface needed to author the -Epsilon-written full Omega compiler source closure `D` and execute it with the -Delta-written Epsilon evaluator. +Epsilon exists to provide the smallest solid language needed to write the full +Omega compiler closure `D` and run it in the Delta-written Epsilon evaluator. -[`../LANGUAGE.md`](../LANGUAGE.md) is the normative Epsilon v1 contract. -This ledger is rationale and change control, not a second specification or a -vote by historical samples. A future facility belongs to Epsilon only when at -least one of these holds and the normative contract is revised explicitly: +[`../LANGUAGE.md`](../LANGUAGE.md) is the canonical Epsilon v1 specification. +This file records feature rationale and change control; it is neither a second +spec nor a vote by old samples. Add a feature to Epsilon only by explicitly +revising the spec when at least one of these holds: -1. the Epsilon-written Omega compiler closure `D` requires it; -2. implementing or compiling `D` coherently requires it; -3. it materially reduces total implementation or assurance cost without - weakening deterministic failure, resource, or safety behavior. +1. the Epsilon-written Omega compiler closure `D` needs it; +2. implementing or compiling `D` cleanly needs it; +3. it substantially cuts total implementation or audit cost without weakening + deterministic failure, resource, or safety guarantees. ## Retained baseline - deterministic byte input and artifact/diagnostic output; -- explicit process termination and failure; -- finite nominal data, sums, records, arrays, and bounded views, including the - allocation-free adapter from a place-valued fixed array to its full - immutable view; -- zero-field records and positive fixed-array lengths with target capacity kept - outside language validity; -- profile-owned static-storage refusal with an exact-or-bounded canonical - witness rather than target-dependent type validity or arbitrary-precision - source arithmetic; +- explicit process exit and trap failure; +- finite nominal data, sums, records, fixed arrays, and bounded views, including + zero-copy conversion from a place-valued fixed array to its full immutable + view; +- zero-field records and positive fixed-array lengths, keeping target memory + limits separate from language validity; +- profile-owned static-storage refusal with an exact or bounded test value + instead of target-dependent type validity or arbitrary-precision source math; - checked integer arithmetic sufficient for compiler indexing and layout; - deterministic control flow, calls, and recursion with five locally checked block-exit effects, no reachability-dependent validity, and explicit resource - ceilings; -- free machines plus owner-qualified data methods whose mandatory first input + limits; +- free machines and owner-qualified data methods whose required first parameter is the owning mutable instance; reserved `self` is that ordinary receiver - binding, not a second value model or an owner-qualified static facility; -- enough source custody to consume the exact package-resolved closure `D`; -- deterministic execution under the selected evaluator profile. + binding, not a separate value model or static method mechanism; +- source handling sufficient to consume the package-resolved closure `D`; +- deterministic execution under the chosen evaluator profile. ## Not implied -Implementing an Omega operation does not automatically add the corresponding -surface to Epsilon. Private paired-word arithmetic, layout records, checked -indexes, or provider tables may remain implementation techniques. Epsilon does -not acquire Omega's proof language, dependent authoring surface, general -boundary-trait system, package model, optimizer, or runtime merely because the -compiler it produces implements those facilities for Omega programs. Epsilon's -closed `boundary trait Console` spelling denotes only the four sealed byte-I/O -operations fixed by its own contract. +Supporting an Omega feature in the compiler does not add that feature to +Epsilon. Helper techniques like paired-word math, layout records, checked +indexes, or provider tables can stay private implementation code. Epsilon does +not inherit Omega's proof language, dependent types, general boundary traits, +package system, optimizer, or runtime just because `D` compiles them for Omega. +Epsilon's closed `boundary trait Console` covers only the four fixed byte-I/O +operations in its spec. ## Decision method -For each candidate: +For every proposed feature: -- cite the exact canonical compiler or `C` use; -- compare a Epsilon-language facility with a private implementation technique; -- state resource and rejection behavior; -- retain lower-rung meaning and mutation controls; -- remove the candidate when the motivating source disappears. +- cite the exact canonical compiler or `C` call site that needs it; +- compare adding an Epsilon language feature against a private helper; +- specify its resource limits and rejection errors; +- keep lower-stage semantics and mutation tests intact; +- remove the feature if its motivating code is removed. -The former Epsilon-to-Delta bridge and versioned native-publication matrix are -deleted. New progress is measured against the -Delta-written Epsilon evaluator, exact closure `D`, and Omega's -`alpha_bootstrap` product edge—not a growing sequence of private snapshot -formats. +The old Epsilon-to-Delta bridge and versioned native-publication matrix are +gone. Measure progress against the Delta-written Epsilon evaluator, exact +closure `D`, and Omega's `alpha_bootstrap` target—not private snapshot formats. diff --git a/bootstrap/epsilon/interpreter/README.md b/bootstrap/epsilon/interpreter/README.md index 8afc0f20341f..1912e532bbcc 100644 --- a/bootstrap/epsilon/interpreter/README.md +++ b/bootstrap/epsilon/interpreter/README.md @@ -1,26 +1,26 @@ # Epsilon interpreter -The Delta modules in this directory check and execute Epsilon programs. The -[entry](../interpreter.delta) receives the source and stdin and publishes the -result. The [compiler](../compiler/) also uses the frontend to check source -before it emits Delta. +The Delta modules in this directory check and run Epsilon programs. The +[entry](../interpreter.delta) reads source and stdin and emits the result. The +[compiler](../compiler/) shares this frontend to check source before emitting +Delta. -[`../LANGUAGE.md`](../LANGUAGE.md) is the normative Epsilon v1 contract. -It is self-contained: a compiler, sample corpus, historical implementation, or -Omega document cannot amend Epsilon by acceptance. +[`../LANGUAGE.md`](../LANGUAGE.md) is the canonical Epsilon v1 spec. It stands +alone: no compiler, sample corpus, old implementation, or Omega document can +alter Epsilon by accepting different code. The ratified [expression-arm result rule](../LANGUAGE.md#8-machines-states-and-transitions) -aligns transition values and terminal call results with Omega, with `{}` for -resultless completion. The current evaluator and admitted source closure still -use the earlier arm-return profile. Their coordinated migration and identity -revalidation are deferred under **OMEGA-D** in [TASKS_BOOTSTRAP.md](../../../TASKS_BOOTSTRAP.md); -this documentation decision changes no admitted artifact or proof identity. - -Declaration identity, type formation, body/control premise dependencies, and -entry diagnostics belong to the [language contract](../LANGUAGE.md#4-names-types-and-closure-checking). -Its [resource classification](../LANGUAGE.md#10-resource-classification) separates -valid source from bounded realization; implementation status below does not -amend either contract. +matches Omega for transition values and terminal call results, using `{}` for +resultless completion. The current evaluator and checked-in source still use +the older arm-return syntax; migrating them and re-verifying hashes is tracked +under **OMEGA-D** in [TASKS_BOOTSTRAP.md](../../../TASKS_BOOTSTRAP.md) and +changes no current artifact hash. + +Declaration identity, type formation, body/control rules, and entry checks are +specified in the [language contract](../LANGUAGE.md#4-names-types-and-closure-checking). +Its [resource classification](../LANGUAGE.md#10-resource-classification) +separates valid source from bounded execution limits; implementation status +below never changes those rules. ## Construction edges @@ -33,228 +33,193 @@ Remaining: bootstrap compiler + Omega compiler source + alpha_bootstrap └─ first Omega compiler tape ``` -The existing composition runs Epsilon and compiles exercised scalar Omega -programs to Alpha tapes. It has not constructed the Omega compiler from its -source. The [bootstrap compiler](../../omega/compiler/README.md) records implemented -coverage and explicit refusals; the [compiled VM peer](../../../wiki/development/bootstrap/compiled-alpha.md) -records its source construction and trust inputs. The first Omega compiler -must then rebuild the same Omega compiler source reproducibly. +This chain runs Epsilon and compiles tested scalar Omega programs to Alpha +tapes, but it does not yet build the full Omega compiler from source. The +[bootstrap compiler](../../omega/compiler/README.md) lists implemented features +and explicit refusals; the [compiled VM peer](../../../wiki/development/bootstrap/compiled-alpha.md) +documents its build and trust inputs. Once built, the first Omega compiler must +rebuild its own source reproducibly. ## Implementation status -- [`FEATURE_LEDGER.md`](FEATURE_LEDGER.md) records Epsilon feature rationale and - change control. -- [`epsilon_compiler.delta`](epsilon_compiler.delta) is the in-progress - Delta-written evaluator's entry; `epsilon_compiler.delta.sources` orders the - concept-owned authoring members into one exact Delta translation unit. - The source currently - contains final compiler material through complete parsing, the - source-shaped identity census including receiver-only qualified-machine - syntax, structural type formation including final reserved entry-shape - judgment, the source-backed resolution catalog, ordered local-value - resolution, exact scalar and aggregate value/place facts, one generalized - callable ledger, direct - qualified applications, grouped/unqualified machine applications and - discarded postfix-statement category admission in settled non-continuation - contexts, ordinary named receiver binding for `self`, named-data - receiver applications, exact sealed-`Console` receiver applications, and - explicit transition state applications with state/machine collision - rejection and separate state completion custody, transition subject, - resolved-case, complete payload-binder, and retained sum-coverage facts, - settled field/index/slice projection failures, scalar and argument- - `never` category joins, let/assignment/assert and explicit-return relations, - first-following-statement terminal flow. - Bare-state-transfer checks, receiver-only qualified machines, resultless-argument - anchors, entry diagnostics, and transition-pattern diagnostics are implemented. - Every grammar-level expression, statement, control, and Console form has a - staging execution path; there is no private `Unsupported` fallback. This is - not complete conformance or checked evaluator refinement. Remaining work is - contract-derived checking/runtime conformance and resource-contained storage - realization. - The canonical evaluator boundary and `main` are realized by - [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md): the packed closure plus the bound - [`interpreter.delta`](../interpreter.delta) - source compiles to the canonical receipt that consumes the EREQ envelope and - publishes canonical observations or EEOUT refusal frames within the - evaluator's current construct coverage. Complete-D composition and - `RunEpsilon` refinement over the exact D closure member sources share - each base execution in - [`tests/bootstrap/interpreted/epsilon/d-composition/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/d-composition/README.md). - The independent model and synthetic language corpus remain in +- [`FEATURE_LEDGER.md`](FEATURE_LEDGER.md) tracks feature rationale and change + control. +- [`epsilon_compiler.delta`](epsilon_compiler.delta) is the Delta evaluator's + library entry; `epsilon_compiler.delta.sources` orders its files into one + Delta translation unit. It currently implements full parsing, scoped name + collection (including receiver-only qualified machines), type formation + (including entry-shape checks), the resolution catalog, ordered local + resolution, scalar/aggregate value and place tracking, a unified callable + table, direct qualified calls, grouped/unqualified machine calls, discarded + call statements, ordinary receiver binding for `self`, named-data and + `Console` receiver calls, explicit state transfers (rejecting state/machine + name collisions), transition subjects, case/binder/coverage checks, field/ + index/slice checks, scalar and argument `never` checks, let/assign/assert/ + return checks, and post-`never` dead-code checks. Bare state transfers, + receiver-only qualified machines, resultless-argument anchors, entry checks, + and transition-pattern errors are all implemented. Every grammar construct has + an execution path with no `Unsupported` fallback. Remaining work is full + spec-derived conformance testing and resource-bounded storage. The canonical + entry and `main` live in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md): combining + the packed library with [`interpreter.delta`](../interpreter.delta) builds the + canonical receipt that parses EREQ requests and emits canonical observations or + EEOUT refusal frames. Full-D execution and `RunEpsilon` comparison share base + runs in + [`tests/bootstrap/interpreted/epsilon/d-composition/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/d-composition/README.md), + while the independent reference model and synthetic tests live in [`tests/bootstrap/interpreted/epsilon/refinement/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/refinement/README.md). - The - current fact pass does enforce contextual receiver/result relation and - separate array-view extra-call rejection. - The [execution status](#validation-and-completion) below describes the - staging executor and its remaining conformance obligations. + The checker also enforces contextual receiver/result types and rejects + `array.as_slice()`. See [execution status](#validation-and-completion) for + details. -The real evaluator edge owns its contract-derived positive/negative suite. +The canonical evaluator owns its spec-derived positive and negative test suite. ## Boundaries -- Epsilon is independent of Omega even when spelling overlaps. -- The Epsilon evaluator is written in Delta. Its Gamma receipt can execute - through the Gamma evaluator or the source-built Gamma compiler's Alpha tape. -- The Epsilon-written bootstrap compiler must support enough specified Omega - to construct the Omega-written compiler. Its current scalar subset is not - that complete source construction. -- All fixed capacities are source-visible bounds, explicit profile parameters, - or private budgets whose exhaustion is `Incomplete` and publishes no tape. -- Shell and Python may invoke tests or stamp tapes. They may not parse, lower, - manufacture semantic evidence, or become compiler stages. -- The Rust compiler remains a comparator, not a producer in the canonical - sequence. - -Active work is tracked in -[`../../TASKS_BOOTSTRAP.md`](../../../TASKS_BOOTSTRAP.md). +- Epsilon is independent of Omega even where syntax overlaps. +- The Epsilon evaluator is written in Delta. Its Gamma output runs either in the + Gamma evaluator or as an Alpha tape from the source-built Gamma compiler. +- The Epsilon-written bootstrap compiler must support enough Omega to build the + Omega-written compiler; today's scalar subset is not yet enough. +- Every fixed limit is either a source-visible bound, an explicit profile limit, + or a private budget whose exhaustion returns `Incomplete` and emits no tape. +- Shell and Python scripts may run tests or stamp tapes; they may not parse, + lower, synthesize semantic data, or act as compiler stages. +- The Rust compiler is a comparator only, never a build step in the bootstrap + chain. + +Active work is tracked in [`../../TASKS_BOOTSTRAP.md`](../../../TASKS_BOOTSTRAP.md). ## Retention inventory | Retained child | Canonical role | Deletion condition | | --- | --- | --- | -| `../LANGUAGE.md` and `FEATURE_LEDGER.md` | Normative contract and feature/change rationale. | Replace only with synchronized contracts and customer gates. | -| `EVALUATOR_PROFILE.md` | Derived resource/request/observation profile of the composed diagnostic edge against the selected lower chain, with exact/adjacent refusal witnesses. | Replace only with a re-derived profile on a changed diagnostic composition. | -| `EVALUATOR_ENTRY.md` | Realized section-11 request/observation envelope, canonical receipt composition, and its derived resource profile. | Replace only with a synchronized final-envelope revision on a changed canonical composition. | -| `epsilon_compiler.delta` and `epsilon_compiler.delta.sources` | Evaluator entry and exact ordered Delta source closure. | Replace only atomically with an admitted immediate-predecessor evaluator edge. | -| Concept-owned source files and folders below | Checking, execution, and shared representations within that closure. | Replace while preserving the exact compiler customer and required conformance evidence. | +| `../LANGUAGE.md` and `FEATURE_LEDGER.md` | Canonical spec and feature/change rationale. | Replace only with synchronized specs and tests. | +| `EVALUATOR_PROFILE.md` | Resource, request, and observation profile of the diagnostic entry on the lower chain, with exact/adjacent refusal tests. | Replace only when re-derived for a changed diagnostic build. | +| `EVALUATOR_ENTRY.md` | Section-11 request/observation envelope, canonical receipt build, and resource profile. | Replace only with an updated envelope for a changed canonical build. | +| `epsilon_compiler.delta` and `epsilon_compiler.delta.sources` | Evaluator library entry and exact ordered Delta file list. | Replace only atomically with a new evaluator stage. | +| Source files and folders below | Checking, execution, and shared data types within that closure. | Replace while keeping the compiler customer and conformance tests passing. | -Proposed programs without a compiler or a contract-derived test role are not -retained as tests. +Do not retain example programs that lack a compiler or spec-test purpose. ## Epsilon evaluator source guide Start at [`epsilon_compiler.delta`](epsilon_compiler.delta). Its -`epsilon_evaluate_entry_slice` accepts source and sealed input, checks the source, -distinguishes rejection from internal failure, and starts the checked entry -invocation. This library entrance is the evaluator's semantic core, not the -physical request boundary; the canonical `main` is -[`interpreter.delta`](../interpreter.delta) -and this file still exposes no artifact on its own. -The [private execution driver](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/interpreted-omega-experiment/README.md#private-execution-observations) -preserves full `i32` exit codes, trap kinds and stdout prefixes, and rejection -reasons and coordinates in distinct tagged results. Its transport is not a new -normative Epsilon request or observation envelope. -[`EVALUATOR_PROFILE.md`](EVALUATOR_PROFILE.md) derives that edge's explicit -resource, request, and observation profile against the selected lower chain, -including the exact/adjacent refusal witnesses and the sparse-storage account. -The canonical evaluator `main` and request/observation envelope are realized -separately: [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md) defines EREQ v1, the -canonical observation grammar, the EEOUT refusal frame, the carry of every -lower-chain refusal status to the outer `Incomplete`, and the bound -canonical receipt, gated by +`epsilon_evaluate_entry_slice` takes source and stdin, checks the source, +separates source rejections from internal errors, and runs entry execution. That +function is the semantic core, not the wire entry; the canonical `main` is +[`interpreter.delta`](../interpreter.delta), and this library produces no +executable on its own. The +[private execution driver](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/interpreted-omega-experiment/README.md#private-execution-observations) +preserves full `i32` exit codes, trap kinds, stdout prefixes, and rejection +reasons/offsets using private diagnostic tags (not a canonical Epsilon format). +[`EVALUATOR_PROFILE.md`](EVALUATOR_PROFILE.md) records that diagnostic build's +resource limits, refusal tests, and sparse storage. +[`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md) defines the canonical `main`, EREQ v1 +envelope, canonical observations, EEOUT refusal frame, lower-chain `Incomplete` +mapping, and canonical receipt, tested by [`tests/bootstrap/interpreted/epsilon/evaluator-entry/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/evaluator-entry/README.md). ## Follow the program | Area | Entrance and ownership | | --- | --- | -| Compiler source | [`source.delta`](source.delta) validates byte windows and owns source-relative reads. [`representations/source.delta`](representations/source.delta) defines their private representation; runtime views and Console bytes are separate. | -| Checking | [`checking/check.delta`](checking/check.delta) sequences parsing and checking. Its subfolders own declarations, types, catalogs, resolution, calls, expressions, and control judgments. | -| Lexical validation | [`lexical/validation.delta`](lexical/validation.delta) validates source bytes and lexical forms; [`tokens.delta`](lexical/tokens.delta) provides syntax-token lookahead. | -| Parsing | [`parsing/machine_declarations.delta`](parsing/machine_declarations.delta) assembles the program from declarations. Sibling files own expressions, transitions, statements, blocks, and data declarations. | -| Execution | [`execution/invocation.delta`](execution/invocation.delta) selects the entry and resumes states. [`control/blocks.delta`](execution/control/blocks.delta) coordinates statements and terminal control. | -| Calls | [`execution/calls.delta`](execution/calls.delta) dispatches checked callable identities. [`calls/receivers.delta`](execution/calls/receivers.delta) selects the receiver place; [`arguments.delta`](execution/arguments.delta) captures value arguments; [`calls/parameters.delta`](execution/calls/parameters.delta) installs and releases callee homes. | -| Expressions | [`execution/expressions.delta`](execution/expressions.delta) dispatches expression forms and carries effects into scalar operations, calls, and storage access. | -| Sums | [`execution/sums/construction.delta`](execution/sums/construction.delta) captures checked constructor payloads; [`defaults.delta`](execution/sums/defaults.delta) normalizes lazy zero sums. [`transitions.delta`](execution/sums/transitions.delta) selects checked cases; [`bindings.delta`](execution/sums/bindings.delta) establishes independent arm-local payload homes. | -| Runtime references | [`execution/references.delta`](execution/references.delta) prepares the shared index and complete linear fallback. [`rows.delta`](execution/references/rows.delta) sequences expression ledgers; [`control_rows.delta`](execution/references/control_rows.delta) selects state, subject, and completed-pattern records. [`construction.delta`](execution/references/construction.delta) owns interval insertion, [`buckets.delta`](execution/references/buckets.delta) preserves typed ledger order, and [`lookup.delta`](execution/references/lookup.delta) delegates exact queries. | -| Projections | [`execution/projections/fields.delta`](execution/projections/fields.delta) selects checked record fields and contextual array/view members; [`indexes.delta`](execution/projections/indexes.delta) evaluates indexes and checks bounds before access. | -| Views | [`execution/views/slices.delta`](execution/views/slices.delta) sequences base and bound evaluation. [`backing.delta`](execution/views/backing.delta) reads ultimate backing and implements place-only `.as_slice`; [`strings.delta`](execution/views/strings.delta) decodes literal bytes. | -| Storage | [`execution/storage/homes.delta`](execution/storage/homes.delta) owns runtime roots, reads, writes, and reclamation. [`places.delta`](execution/storage/places.delta) walks projection paths; [`children.delta`](execution/storage/children.delta) selects record-field or indexed-array access. [`arrays.delta`](execution/storage/arrays.delta) validates array extents and delegates to [`arrays/lookup.delta`](execution/storage/arrays/lookup.delta) and [`arrays/updates.delta`](execution/storage/arrays/updates.delta). [`liveness.delta`](execution/storage/liveness.delta) retains backing roots needed by surviving state views. | -| Console | [`execution/console.delta`](execution/console.delta) sequences argument effects and selects the operation. [`console/input.delta`](execution/console/input.delta) advances sealed input; [`console/output.delta`](execution/console/output.delta) owns byte/line output and exit. | -| Runtime operations | [`execution/statements.delta`](execution/statements.delta) applies statements. `scalars/` and `control/` own scalar operations and block/state control. | -| Shared representations | [`representations/`](representations) groups syntax, parsing outcomes, checked facts, diagnostics, and execution values by concept. | - -The 96 authoring members have at most 450 lines each; the root entrance has 26. -Files end at complete top-level Delta forms. They are not independent Delta -modules: they share one translation unit and the language gains no imports. -The binary-operator and scalar-outcome declarations have separate shared leaf -owners so the independent compiler's pure target needs no Epsilon syntax tree -or evaluator dispatch. The ordered packed translation unit remains byte-exact. +| Compiler source | [`source.delta`](source.delta) validates byte windows and reads source-relative bytes. [`representations/source.delta`](representations/source.delta) defines the private view type; runtime views and Console bytes stay separate. | +| Checking | [`checking/check.delta`](checking/check.delta) runs parsing and checking in order. Subfolders handle declarations, types, catalogs, resolution, calls, expressions, and control flow. | +| Lexical validation | [`lexical/validation.delta`](lexical/validation.delta) checks source bytes and tokens; [`tokens.delta`](lexical/tokens.delta) provides syntax-token lookahead. | +| Parsing | [`parsing/machine_declarations.delta`](parsing/machine_declarations.delta) parses top-level declarations. Sibling files parse expressions, transitions, statements, blocks, and data declarations. | +| Execution | [`execution/invocation.delta`](execution/invocation.delta) starts entry and switches states. [`control/blocks.delta`](execution/control/blocks.delta) runs statements and terminal control. | +| Calls | [`execution/calls.delta`](execution/calls.delta) dispatches checked calls. [`calls/receivers.delta`](execution/calls/receivers.delta) resolves receiver places; [`arguments.delta`](execution/arguments.delta) evaluates arguments; [`calls/parameters.delta`](execution/calls/parameters.delta) binds and frees callee locals. | +| Expressions | [`execution/expressions.delta`](execution/expressions.delta) evaluates expressions and threads side effects through operators, calls, and storage reads. | +| Sums | [`execution/sums/construction.delta`](execution/sums/construction.delta) evaluates constructor payloads; [`defaults.delta`](execution/sums/defaults.delta) creates lazy zero sums. [`transitions.delta`](execution/sums/transitions.delta) picks matching cases; [`bindings.delta`](execution/sums/bindings.delta) creates independent arm-local payload bindings. | +| Runtime references | [`execution/references.delta`](execution/references.delta) builds the lookup index and linear fallback. [`rows.delta`](execution/references/rows.delta) threads expression tables; [`control_rows.delta`](execution/references/control_rows.delta) looks up state, subject, and pattern records. [`construction.delta`](execution/references/construction.delta) inserts into the interval tree, [`buckets.delta`](execution/references/buckets.delta) preserves table order, and [`lookup.delta`](execution/references/lookup.delta) runs exact queries. | +| Projections | [`execution/projections/fields.delta`](execution/projections/fields.delta) reads checked record fields and contextual array/view members; [`indexes.delta`](execution/projections/indexes.delta) checks index bounds before reading. | +| Views | [`execution/views/slices.delta`](execution/views/slices.delta) evaluates slice bases and bounds. [`backing.delta`](execution/views/backing.delta) reads backing storage and handles place-only `.as_slice`; [`strings.delta`](execution/views/strings.delta) decodes string literals. | +| Storage | [`execution/storage/homes.delta`](execution/storage/homes.delta) manages runtime roots, reads, writes, and cleanup. [`places.delta`](execution/storage/places.delta) walks field/index paths; [`children.delta`](execution/storage/children.delta) handles record-field and array-index access. [`arrays.delta`](execution/storage/arrays.delta) validates array bounds and calls [`arrays/lookup.delta`](execution/storage/arrays/lookup.delta) and [`arrays/updates.delta`](execution/storage/arrays/updates.delta). [`liveness.delta`](execution/storage/liveness.delta) keeps roots still referenced by live state views. | +| Console | [`execution/console.delta`](execution/console.delta) evaluates arguments and dispatches Console calls. [`console/input.delta`](execution/console/input.delta) advances stdin; [`console/output.delta`](execution/console/output.delta) handles byte/line writes and exit. | +| Runtime operations | [`execution/statements.delta`](execution/statements.delta) runs statements. `scalars/` and `control/` implement scalar ops and block/state flow. | +| Shared representations | [`representations/`](representations) defines syntax trees, parse results, checked facts, diagnostics, and runtime values. | + +Each of the 96 source files has at most 450 lines; the entry file has 26. Every +file ends on a top-level Delta definition. They are concatenated into one +translation unit, not separate modules (Delta has no imports). Binary operators +and scalar outcomes live in leaf files so the separate compiler's pure target +needs no Epsilon AST or evaluator dispatch. ## Exact source closure -[`epsilon_compiler.delta.sources`](epsilon_compiler.delta.sources) is the -ordered source authority. Its `DeltaSourceClosureV1` rows bind a stable member -identity, byte length, SHA-256 digest, and relative path. Declaration order is -explicit. Directory enumeration never selects order; forward definitions share -the same translation unit. - -`mbx xtask source-closure` checks those -rows, closed ASCII source bytes, canonical nonsymlink member paths, and exact -source inventory, then concatenates bytes without separators. It does not parse -or lower Delta. Bootstrap callers use `OMEGA_PATH_EPSILON_EVALUATOR_SOURCES` -from the shared role registry rather than reading the entrance as the full source. - -The packed evaluator is 12,209 lines / 622,547 bytes, SHA-256 -`ea40be3725182119158e0a8ecd72ff72dcba5aa42be2488cd6cb0503b7f55639`. -The manifest itself is 16,780 bytes, SHA-256 -`f99a4552727b91c99a3e6294538a0208435b09532cd6c2cdc3321e0eca1a3065`; -`tools/bootstrap/epsilon/evaluator_env.sh` checks both identities against every -materialization. The [portable envelope profile](../../../tests/bootstrap/interpreted/epsilon/README.md) -checks refusals for each byte of the claimed closure digest. -A digest is an identity check on the bytes being evaluated, not a proof that -the evaluator implements Epsilon. - -The public entry appends [interpreter.delta](../interpreter.delta) to the -packed evaluator. The Delta compiler produces a 709,282-byte Gamma program -from that source. The [entry contract](EVALUATOR_ENTRY.md) gives its identity -and request format. One [executable test](../../../tests/bootstrap/interpreted/omega-executable/README.md) -appends its own diagnostic driver to exercise a private frame instead. - -When editing a member, update its manifest length and digest; change membership -explicitly when adding or removing source. Update exact test identities only -after reviewing the semantic change and its generated receipt. - -Compiler source is a bounded view over existing Delta `Bytes`, not a newly -constructed byte tree. `epsilon_source_view` admits the origin before subtracting -it from the backing length, then checks the window extent. `epsilon_source_byte` -requires a factory-established view and checks its relative index before adding -the origin. Invalid reads retain ordinary Delta `Bytes` failure; they never -substitute a dummy byte or expose the private header or sealed stdin. No new -Delta or Gamma primitive is involved. - -Raw-source checking and evaluation entrances wrap the complete byte sequence; -their view-taking counterparts share the same checking and execution judgments. -The framed driver selects only its source window. Syntax, checked facts, and -diagnostics keep source-relative offsets, independent of the backing origin. -Invocation contexts retain that view for name lookup and string decoding, while -Console starts at the first input byte after the source and advances to the -end of the same request. A read at the end returns EOF. Both entries validate -the source extent before creating the cursor. Output, decoded literals and -Epsilon runtime views retain their existing byte storage. - -Runtime reference lookup uses a derivative index, not a replacement checked -program. Entry builds an immutable interval tree over source-start coordinates. -Each branch retains its canonical midpoint, calculated and checked during -construction. Lookup validates that the saved split lies inside the current -interval and descends without recomputing midpoint division. -Each leaf retains separate ordered local, field, callable, state-application, -transition-subject, and completed-pattern ledgers. Original lookup helpers still -own exact kind/span matching and progress precedence. Callable grouping is -normalized before bucket selection; other queries retain their exact targets. -State rows preserve both Complete and Resolved records, while only Complete -pattern records enter the index. Missing completion cannot become executable. -All invocations share the tree, never their local values or roots. Invalid build -premises retain all six original query ledgers, including incomplete pattern -facts, in a linear fallback. Coverage remains in the unchanged checking ledger -and has no runtime query. Construction allocates logarithmic paths in the -existing Gamma pair arena; it neither enlarges that profile nor establishes -Epsilon's final physical storage bounds. A cached split adds one integer payload -to each branch; it does not add a separate tree level or change leaf identity. -Current Delta constructor lowering represents that payload with one additional -Gamma pair per branch reconstruction, including paths superseded by later inserts. +[`epsilon_compiler.delta.sources`](epsilon_compiler.delta.sources) defines the +exact file order. Its `DeltaSourceClosureV1` rows list each file's stable ID, +byte length, SHA-256 hash, and relative path. Declaration order is explicit, +never taken from directory listing; forward references share the same +translation unit. + +`mbx xtask source-closure` verifies each row, checks ASCII-only bytes and +non-symlink paths, checks there are no unlisted files, and concatenates the +bytes without separators. It never parses or compiles Delta. Callers read +`OMEGA_PATH_EPSILON_EVALUATOR_SOURCES` from the shared registry instead of +treating the entry file as the whole program. + +The packed library is 12,209 lines / 622,547 bytes (SHA-256 +`ea40be3725182119158e0a8ecd72ff72dcba5aa42be2488cd6cb0503b7f55639`). The manifest +is 16,780 bytes (SHA-256 +`f99a4552727b91c99a3e6294538a0208435b09532cd6c2cdc3321e0eca1a3065`). +`tools/bootstrap/epsilon/evaluator_env.sh` verifies both hashes on every build. +The [portable envelope profile](../../../tests/bootstrap/interpreted/epsilon/README.md) +checks mismatch refusals for every byte of the closure hash. A hash verifies +byte identity, not that the evaluator implements Epsilon correctly. + +The public entry appends [interpreter.delta](../interpreter.delta) to the packed +library. Compiling that with Delta produces a 709,282-byte Gamma receipt; see +the [entry contract](EVALUATOR_ENTRY.md) for its hash and request format. One +[executable test](../../../tests/bootstrap/interpreted/omega-executable/README.md) +appends its own diagnostic driver for private-frame tests instead. + +When editing a file, update its length and SHA-256 in the manifest; add or +remove rows explicitly when changing files. Update test hashes only after +reviewing the semantic change and rebuilt receipt. + +Compiler source is a bounded window over existing Delta `Bytes`, not a copied +byte tree. `epsilon_source_view` validates the start offset and length against +the backing sequence; `epsilon_source_byte` requires a validated view and checks +its relative index before adding the origin. Out-of-bounds reads fail via normal +Delta `Bytes` checks without returning dummy bytes or exposing headers or stdin. +No new Delta or Gamma primitive is needed. + +Raw-source entries wrap the full byte sequence and share the exact same checking +and execution logic as view-based entries. The framed driver slices out only the +source window; AST spans, checked facts, and error offsets stay source-relative. +Execution keeps that view for name lookups and string decoding, while Console +reads stdin starting right after the source window through the end of the +request, returning EOF at the end. Both entries validate source bounds before +creating the cursor. Output, decoded strings, and runtime views keep their +existing byte storage. + +Runtime lookups use a read-only index built at entry, not a rewritten AST. Entry +constructs an immutable interval tree keyed by source start offset, caching each +branch's validated midpoint so lookups descend without recomputing division. +Each leaf stores separate ordered lists for locals, fields, callables, state +calls, transition subjects, and completed patterns, while existing helpers keep +exact kind/span matching and precedence. Grouped call heads normalize before +lookup; all other queries match exact targets. State lists keep both Complete +and Resolved rows, while pattern lists keep only Complete rows so incomplete +patterns cannot execute. Invocations share the tree without sharing locals or +roots. Invalid build inputs fall back to linear search over all six original +lists (including incomplete patterns). Sum coverage stays in the checking ledger +and is never queried at runtime. Building the tree allocates logarithmic paths +in Gamma's pair arena without changing profile limits. Each cached midpoint adds +one integer payload (one extra Gamma pair per reconstructed branch). ## Validation and completion -Call checking reuses the newest resolved-callable fact only when its kind and -both span endpoints identify the current application. Children are checked -first; receiver and unqualified callable resolution then prepend that exact -fact. A resolved callable head has no value result to find, so this case avoids -searching the accumulated whole-source expression ledger. Other heads retain -the original value-category lookup and diagnostic ordering. This adds no index, -cache, representation, or language/profile change. The -[checking controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/checking/README.md) cover nested -same-start calls, grouped/local value heads, and independent argument errors. +Call checking reuses the newest resolved-callable fact when its kind and start/ +end span match the current call. Because children check first, receiver and +unqualified resolution prepend that exact row; a resolved callable head has no +value result, skipping a full-program ledger scan. Other call heads keep normal +value lookup and error order, with no new cache, index, or language change. The +[checking controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/checking/README.md) +test nested same-start calls, grouped/local value heads, and independent +argument errors. From the repository root: @@ -274,54 +239,43 @@ sh tests/bootstrap/interpreted/epsilon/d-composition/run.sh sh tests/bootstrap/interpreted/delta/staged-compiler/run.sh ``` -[Implementation notes](implementation_notes.md) describe the supported checking -and execution slices and their conformance controls. -The staging executor supports unqualified calls, value/resultless returns, -effect-threaded expressions, record/fixed-array/sum value copies, nested receiver -places, and independent recursive invocation homes. Runtime places distinguish -instances by root identifier and checked field/index path. Scope exit releases -local roots without reusing their identifiers, retaining backing roots still -referenced by views passed to the next state. Views retain literal, live-place, -or existing snapshot backing and expose no assignable place; strings, range -slices, `.as_slice`, indexing, lengths, and all four -Console operations execute in this staging path. Sparse typed zero homes avoid -eager array allocation; they do not establish the final application's physical -storage profile. Record fields share immutable AVL subtrees keyed by checked declaration coordinates. -A write of the existing integer value preserves the root, including a sparse -zero default. The write still checks its destination, range and index. -The projection entrance admits only a data-owned field and carries its owner -start/end, member start/end, and field type into runtime storage. Comparisons -check member coordinates first, then both owner coordinates; they do not unpack -syntax declarations or compare names. The original checked ledger remains the -authority. The type supplies zero defaults, not identity, and root identifiers -still distinguish runtime instances. Replacing two syntax payloads with four -coordinates and a type adds three Gamma payload pairs per new projection; -existing projections and immutable child lists remain shared. There is no new -index, primitive, or resource provision. -The [complete-D comparison](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/omega-parser/README.md#field-identity-comparison) -supports retaining this representation: both runs pass, with 43.25% less -wall time and 0.40% more cumulative pair allocation in the measured pair. -Those results are customer-specific and include concurrent-run caveats. -The [field controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/runtime-invariants/README.md) isolate -all four coordinates and reject invalid projection owners and sum cases. -Record snapshots and nested-place updates retain their ordinary execution tests; -array children use an immutable interval tree keyed by element index. Reads and -updates traverse at most 31 partitions, independent of the number of populated -elements, and updates share untouched branches. Parent reconstruction has its -own stack, separate from either child representation. The -[array-storage gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/array-storage/README.md) covers an -ordinary fill/read workload and private malformed-path controls. -Sum constructors, first-case zero defaults, checked case -transitions, and copied payload binders have staging execution paths. The -[immediate payload establishment rule](../LANGUAGE.md#epsilon-constructor-payload-establishment-order) -traps as `ByteRange` at a failing byte payload before later arguments run, -preserving earlier output. This is not full evaluator completion. Remaining -conformance obligations and final composition with D remain open. -The [runtime-invariant controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/runtime-invariants/README.md) -exercise internal-failure defenses with synthetic state that bypasses checking; -they do not claim additional admitted Epsilon behavior or final publication. -The [source-window controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/source-views/README.md) compare -raw and bounded source routes, source-relative diagnostics, validated extents, -and failure before publication for invalid internal source indexes. -[LANGUAGE.md](../LANGUAGE.md) governs semantics; -[TASKS_BOOTSTRAP.md](../../../TASKS_BOOTSTRAP.md) owns remaining work. +[Implementation notes](implementation_notes.md) detail the checking and runtime +coverage and conformance plans. The executor handles unqualified calls, value +and resultless returns, effect-ordered expressions, record/array/sum value +copies, nested receiver places, and independent recursive call frames. Runtime +places track root ID plus checked field/index paths. Scope exit drops local +roots without reusing IDs while keeping roots referenced by views passed to the +next state. Views reference literal, live-place, or snapshot backing and are +never assignable; strings, slices, `.as_slice`, indexing, lengths, and all four +Console operations work. Sparse zero defaults avoid dense array allocation +without changing physical profile bounds. Record fields live in immutable AVL +trees keyed by checked declaration coordinates; writing an unchanged integer +reuses the root (even for sparse zero defaults) after checking place, range, and +index. Field projections accept only data-owned fields and pass owner start/end, +member start/end, and field type into runtime storage. Comparisons check member +coordinates then owner coordinates without unpacking AST nodes or comparing +strings; the checked ledger remains the source of truth, the type supplies zero +defaults, and root IDs separate instances. Carrying four coordinates and a type +instead of two AST pointers adds three Gamma pairs per new projection while +keeping existing nodes shared and adding no index or primitive. The +[complete-D comparison](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/omega-parser/README.md#field-identity-comparison) +measured 43.25% less wall time with 0.40% more pair allocations (customer-specific, +with concurrent-run caveats). The +[field controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/runtime-invariants/README.md) +test all four coordinates and reject invalid owners and sum cases. Arrays use an +immutable interval tree keyed by index: reads and writes touch at most 31 +partitions regardless of populated elements, sharing untouched branches, with a +separate stack for parent reconstruction. The +[array-storage gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/array-storage/README.md) +tests fill/read workloads and malformed-path checks. Sum constructors, +first-case defaults, case transitions, and copied payload binders all execute; +the [immediate payload establishment rule](../LANGUAGE.md#epsilon-constructor-payload-establishment-order) +traps as `ByteRange` on an out-of-range byte payload before later arguments run, +preserving earlier output. Conformance tests and final D composition remain +tracked. The +[runtime-invariant controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/runtime-invariants/README.md) +test internal-failure checks with synthetic unchecked state; the +[source-window controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/source-views/README.md) +compare raw vs. windowed source handling, source-relative offsets, and +out-of-bounds failures. [LANGUAGE.md](../LANGUAGE.md) defines semantics; +[TASKS_BOOTSTRAP.md](../../../TASKS_BOOTSTRAP.md) tracks remaining work. diff --git a/bootstrap/epsilon/interpreter/implementation_notes.md b/bootstrap/epsilon/interpreter/implementation_notes.md index 4af729f0c33f..07a72d584350 100644 --- a/bootstrap/epsilon/interpreter/implementation_notes.md +++ b/bootstrap/epsilon/interpreter/implementation_notes.md @@ -1,528 +1,308 @@ # Epsilon evaluator implementation notes -See [the source guide](README.md) for the evaluator entrance, phase ownership, -and ordered source manifest. These notes describe implemented semantics, -diagnostic contracts, validation, and remaining completion requirements. +See [the source guide](README.md) for the entry point, phase layout, and file +manifest. These notes cover implemented semantics, diagnostic rules, validation, +and remaining work. -The canonical evaluator owned here accepts and executes Epsilon and is -implemented in Delta: +This Delta-written evaluator checks and runs Epsilon programs: ```text Gamma evaluator + Delta-written Epsilon evaluator + exact Epsilon source -> Epsilon execution ``` -The incomplete implementation retains the exact rejection/outcome sums, complete lexical phase, native syntax -representation, allocation-free syntax-token scanner, complete type and -expression parser, transition-pattern/control parser, body/state parser, -top-level declaration/program parser, complete source-shaped identity -census, complete structural type formation, a source-backed resolution -catalog, ordered local-value resolution, scalar/aggregate value-place facts, -and deterministic body-candidate promotion. -It validates every source byte -before scanning all tokens and literals, returns the exact lexical reason and packed -offset, and retains no host-generated token ledger. Syntax nodes are recursive -Delta values with exact source spans rather than byte-rope records or numeric -arena references. The scanner rescans one token at a time only after the -complete lexical phase succeeds. Its token start, code, end, and literal value -are immediate `Int` results: lookahead may repeat bounded scanning work, but it -authors no transient token objects into the generated program's fixed immutable -heap. The current pre-migration evaluator still parses the retired arm-level -`return expression?` with scalar lookahead for a following `pattern ->` prefix. -The ratified [expression-arm contract](../LANGUAGE.md#8-machines-states-and-transitions) -instead returns expression results directly and forwards normal call results; -its parser, checking, execution and independent-model migration remains under -**OMEGA-D** in [TASKS_BOOTSTRAP.md](../../../TASKS_BOOTSTRAP.md). Parser success -wrappers contain only their native AST value and no duplicated cursor or span. -The closure deliberately still has no `main` of its own: the canonical -evaluator `main` is the bound edge source -[`bootstrap/epsilon/interpreter.delta`](../interpreter.delta), -appended after the packed closure to form the canonical Delta subject. Its -receipt, EREQ request envelope, canonical observation grammar, and EEOUT -refusal frame are defined in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md) and -executed by `tests/bootstrap/interpreted/epsilon/evaluator-entry/run.sh`. The staging execution -path starts from `Main::main` accepted by the current -checking pipeline; the remaining conformance obligations below still apply. -Local, machine-parameter, state-parameter, and transition-payload bindings retain -exact checked declaration identity while their roots distinguish invocations. -Ordinary values are immutable scalar, record, fixed-array, or sum snapshots; view -values retain a descriptor for their backing and range. Places retain a root -identifier, an ordered field/index path, and the leaf's storage type. -Field paths use the checked owner and member identities, not copied type spans -or source spellings. Same-type sibling fields and different array elements -therefore remain distinct instances. - -Record and array snapshots share immutable sparse children. An unwritten child -uses its declared zero home without allocating the full array or record tree. -Record children retain a list of exact checked field identities. Array children -retain their declared extent and an immutable sparse interval tree over indexes. -An empty tree supplies the typed zero; a compressed leaf stores one index/value; -a branch splits its current interval at the canonical midpoint. A window stores -the interval of a branch whose intervening siblings are empty. Reads and updates -validate that the interval is a strict midpoint descendant and that the stored -branch belongs there, even when the requested index lies outside the window. -Within the branch, only the visited path needs validation. Updates reconstruct only that path and share other branches. At most -31 partitions cover every admitted positive `i32` extent. Projection-parent -reconstruction uses a separate stack, never an array or record child list. -Assignment replaces the selected subtree, including all its descendants; -binding or returning an aggregate value does not alias its source root. Root -identifiers are monotonic. Invocation completion removes callee roots without rewinding the -identifier counter or changing surviving caller-owned roots. State transfer -removes old block bindings but retains roots referenced by captured view -arguments, surviving machine bindings, or receiver custody. Later transfers -reconsider retained roots, so an expired view does not keep its backing forever. -This is a staging storage representation, not a complete application storage -realization or a discharge of the physical resource profile. - -Grouped/local reads and `assert` use the same scalar evaluator as -`Console.write_byte` and `Console.exit_process` arguments. Argument arithmetic -or bounds traps precede publication, byte-range checks, and process exit. Output -prefixes survive exact exit, arithmetic, shift-count, `ByteRange`, and -`Assertion` trap outcomes. Every scalar operator, including short-circuit -Boolean logic, bitwise operations, shifts, division, and remainder, executes. -Byte reads zero-extend to `i32`; byte stores trap as `ByteRange` outside `0..255` -without committing an update. Assignment selects its complete place once before -evaluating the right side. Indexed stores check bounds before that right side, -then write through the selected path into the post-RHS store. Indexed reads of -places use the post-index store; projections of ordinary values retain their -captured snapshots. - -Views retain an ultimate backing and an element range, never another view -variable's home. String literals decode the closed escape set into immutable -byte backing. `.as_slice` retains the selected array place over its exact full -range without copying or establishing new array storage. Ordinary slices of -non-place array values instead share the existing immutable snapshot. Subviews -compose offsets against the same backing. Slice evaluation runs the base, low, -and high expressions in order before checking the complete range; omitted -bounds use zero and the base length. Place-backed view indexes read from the -post-index store. View indexes never expose a place, including for aggregate -elements. -Local view facts likewise carry no place despite their private descriptor home. - -All four Console operations have staging execution paths. `read_byte` uses one -sealed input cursor shared by calls and states, returns each byte as `i32`, and -returns stable `-1` at EOF. Root allocation and reclamation preserve that cursor. -`write_line` evaluates its view argument before reading the exact view bytes -and appending LF; argument traps retain the preceding output without emitting -the line. `write_byte` and `exit_process` retain their existing effect ordering. -The diagnostic driver accepts a private source-length/source/stdin frame. A -validated source view references the source window in the existing Delta byte -sequence. Console reads stdin from the following byte through the end of that -same sequence. Source-relative reads stay within the source window and preserve -packed coordinates. -This test transport is -not the final evaluator request or observation profile. Its result has an -explicit private tag: exit carries the full signed `i32` code and stdout; -trap carries the closed trap kind and exact output prefix; rejection carries -the closed reason and exact source offset. Internal failure and malformed -private input have separate tags; the retired staging tag 4 stays unassigned. -This avoids collapsing exits modulo 256 or discarding checking evidence. The +The implementation covers all rejection/outcome types, full lexing, native AST +values, an allocation-free token scanner, full type/expression/transition/body/ +declaration parsing, scoped name collection, structural type formation, the +resolution catalog, ordered local resolution, scalar/aggregate value-place +tracking, and deterministic body-error selection. Lexing validates every source +byte before scanning tokens and literals, returning the exact reason and packed +offset with no host-generated token list. AST nodes are recursive Delta values +with exact source spans rather than byte ropes or numeric arena IDs. The scanner +rescans one token at a time after lexing succeeds and returns start, code, end, +and literal value as immediate `Int` values: lookahead repeats bounded work +instead of allocating transient token objects in the immutable heap. The parser +still accepts the retired arm-level `return expression?` with scalar lookahead +for `pattern ->`. Under the ratified +[expression-arm contract](../LANGUAGE.md#8-machines-states-and-transitions), +arms return expression values directly and forward call results; migrating the +parser, checker, executor, and reference model is tracked under **OMEGA-D** in +[TASKS_BOOTSTRAP.md](../../../TASKS_BOOTSTRAP.md). Parse results wrap only the +AST node with no extra cursor or span copies. This library defines no `main`; +[`bootstrap/epsilon/interpreter.delta`](../interpreter.delta) appends `main` to +the packed library. Its receipt, EREQ request format, canonical observations, +and EEOUT refusal frames are specified in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md) +and tested by `tests/bootstrap/interpreted/epsilon/evaluator-entry/run.sh`. +Execution starts at `Main::main` after checking succeeds; the conformance checks +below still apply. + +Local, machine-parameter, state-parameter, and transition-payload bindings keep +their checked declaration identities while runtime roots separate invocations. +Ordinary values are immutable scalar, record, array, or sum snapshots; views +store a backing descriptor and range. Places store a root ID, field/index path, +and leaf storage type. Field paths use checked owner and member identities +rather than strings or spans, so sibling fields of the same type and distinct +array elements stay separate. + +Record and array snapshots share immutable sparse children; unwritten cells +return typed zeros without allocating full trees. Records store checked field +identities. Arrays store their length and an immutable sparse interval tree over +indexes: an empty tree returns typed zero, a leaf holds one index/value, a +branch splits at the midpoint, and a compressed window spans a branch whose +intervening siblings are empty. Reads and writes verify that every visited +window is a strict midpoint descendant and owns its branch even when the target +index is outside the window, rebuilding only the updated path and sharing all +other branches. At most 31 splits cover any positive `i32` length. Parent +reconstruction uses its own stack, separate from array or record child trees. +Assignment replaces the target subtree; copying or returning aggregates never +aliases the source root. Root IDs increase monotonically: call return drops +callee roots without reusing IDs or touching caller roots. State transfer drops +old block locals while keeping roots referenced by view arguments, machine +parameters, or `self`, and later transfers re-check liveness so expired views do +not pin storage forever. This is a staging storage layout, not a final physical +storage profile. + +Grouped/local reads and `assert` share the scalar evaluator used by +`Console.write_byte` and `Console.exit_process`. Argument arithmetic or bounds +traps fire before output, byte-range checks, or exit, keeping all prior stdout +on exit, arithmetic, shift, `ByteRange`, and `Assertion` traps. All scalar +operators—including short-circuit Booleans, bitwise ops, shifts, division, and +remainder—are implemented. Byte reads zero-extend to `i32`; byte writes trap as +`ByteRange` outside `0..255` without mutating storage. Assignments resolve the +full left-hand place before evaluating the right-hand side; indexed writes check +bounds before running the right-hand side, then write into the post-RHS store. +Indexed reads of places read from the post-index store, while projections of +ordinary values read from their captured snapshots. + +Views store their underlying backing and element range, never another view +variable. String literals decode the closed escape set into immutable bytes. +`.as_slice` borrows the array place over its full range without copying; slicing +a non-place array shares its immutable snapshot. Subviews compose offsets +against the same backing. Slicing evaluates base, low, and high in order before +checking bounds (defaulting to 0 and length). Indexing a place-backed view reads +from the post-index store. View elements and local views never expose an +assignable place. + +All four Console calls execute. `read_byte` advances one sealed input cursor +shared across calls and states, returning `0..255` as `i32` or `-1` at EOF; root +allocation and cleanup preserve that cursor. `write_line` evaluates its view +argument before emitting bytes plus LF, preserving prior output if evaluation +traps. `write_byte` and `exit_process` keep the same effect order. The +diagnostic driver reads a private source-length/source/stdin frame, slicing the +source window in place and reading stdin from the remaining bytes while keeping +source-relative offsets. That diagnostic transport uses private result tags: +exit carries signed `i32` and stdout, trap carries trap kind and stdout prefix, +reject carries reason and source offset, internal errors and malformed inputs +use separate tags, and retired tag 4 stays unused (preventing exit-code +truncation mod 256 or lost diagnostics). See the [execution gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/interpreted-omega-experiment/README.md#private-execution-observations) -documents the exact byte layout. Outer Gamma failures are not converted into -these diagnostic results. - -One checked invocation context drives the same statement/block evaluator for -entry and states. Block falloff retains locals, storage, and output before -terminal execution. Scalar transitions consume the checked subject and pattern -ledgers; only the selected continuation executes, with unmatched scalar subjects -trapping as `NonExhaustiveTransition`. State arguments evaluate left-to-right -against the old bindings and capture all values before reclaiming unneeded block -roots and installing new parameter homes. Transfers preserve machine-parameter -roots and receiver identity and resume the target state through a tail call. -Explicit resultless return, state falloff, and supported Console write/exit -continuations complete the current invocation without executing unused states. - -Ordinary machine calls use checked callable identities. A receiver call selects -its complete place before evaluating ordinary arguments left-to-right. Each -argument captures its value before the next argument's effects; callee -parameters and locals receive independent roots. Nested receiver calls share -the selected live place, including fields and indexed records, rather than -copying a receiver out and writing it back on return. Unqualified and receiver -machines support recursion, scalar/record/array/sum value returns, resultless -falloff/return, and explicit exit/trap propagation. Ordinary completion releases -callee roots and returns a value without a place; committed effects on caller -storage survive. Expression outcomes carry committed storage and -output through arithmetic, arguments, indexes, right sides, returns, and -transition subjects. Only the outer entry adapter turns ordinary completion -into process exit; recursive `self.main()` retains the existing receiver. - -Sum construction enters through `execution/sums/construction.delta` and consumes -the exact checked constructor owner and case, never a receiver-machine lookup. -Arguments evaluate left-to-right and capture immutable payload snapshots in -declaration order. `sums/defaults.delta` normalizes an unwritten named sum only -when its checked owner is available: the first declared case receives typed -zero payloads, with nested records, arrays, and sums remaining lazy. Concrete -sum values retain exact owner/case identity and independent payload values. - -`sums/transitions.delta` evaluates the subject once and selects the first -matching complete checked case or wildcard. Missing admitted sum coverage is -an internal contradiction, not the scalar unmatched-subject trap. -`sums/bindings.delta` establishes fresh payload homes only for the selected arm; -lookup uses exact pattern and binder-declaration identity. Mutating a record or -array binder does not mutate the original subject. A view captured from a -binder array retains that independent backing across state transfer through the -ordinary root-liveness rule; unused binder roots are reclaimed normally. - -Constructor arguments immediately establish their corresponding payload fields -under the [constructor payload establishment rule](../LANGUAGE.md#epsilon-constructor-payload-establishment-order). -A byte payload outside `0..255` traps as `ByteRange`, preserving effects from -preceding arguments and from evaluating the failing argument itself. Later -arguments do not run: their storage mutations, Console output, traps, and exits -cannot precede this failure. Successful aggregate arguments still capture -immutable snapshots before later arguments run. - -Impossible checked states produce internal failure, not `Unsupported`: a -non-call control target, a missing ordinary field reference, a view represented -as aggregate storage, or a logical operator sent directly to the nonlogical -scalar helper. Control failures identify the normalized core's start; missing -field facts identify the complete projection's start; malformed aggregate views -identify their type's start. The pure scalar helper has no source coordinate -and uses the existing internal-offset fallback of zero. These failures carry no -buffered stdout into the private observation. Execution outcomes retain no -`Unsupported` constructor or propagation arm: every implemented branch returns -an ordinary value/control outcome, exit, trap, or detected internal failure. - -These storage, view, sum, and call operations also do not establish that the -complete Omega D source executes. Every -grammar form now parses, including boundary/data/machine declarations, -qualified-only receiver forms, states, and exact nonempty whole-program -exhaustion. Receiver-only qualified-machine syntax, ordinary named -`self` binding, and disjoint constructor/method selection are implemented. -Unqualified, named-data receiver, and exact -sealed-boundary applications now retain source identity and settled result -facts; explicit state applications and state/machine collision classification -are retained separately. Transition subjects, resolved patterns, typed payload -binders, and sum coverage now have separate exact custody. Grammar-owned -final wildcard and four-stage pattern judgment are implemented: subject -admission precedes semantic identity ownership, duplicate identity precedes -payload arity, and coverage follows completed pattern premises. Bare-state -judgment and resultless-argument anchor are implemented within the language's -premise-DAG composition. Five local block-exit effects, exact after-`never` -delimiters, falloff checks, and machine-continuation categories are implemented; -full body/control conformance remains unclosed. -Source-backed `.as_slice` receiver/result facts and separate extra-call -rejection for the resulting array view are implemented. Its execution route -retains only a place-backed full view, as described above. -All grammar-level execution forms have staging implementations. This does not -prove their semantics: contract-derived conformance and independent refinement -remain required. The evaluator boundary and `main` are now realized by -[`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md) within current construct coverage. -Complete Omega D composition and independent `RunEpsilon` refinement are now -exercised gates — [`tests/bootstrap/interpreted/epsilon/d-composition/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/d-composition/README.md) -runs the full eight-member D closure through the canonical edge, including -`OmegaScalarCompiler::compile` emitting the exact Alpha tape, and compares -the same base executions against the contract-derived model in -[`tests/bootstrap/interpreted/epsilon/refinement/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/refinement/README.md). -The synthetic language corpus runs separately there. Resource containment beyond the derived -lower-chain profile remains an implementation gap. New execution work -must name a concrete failing program or required conformance/refinement -obligation, not assume an unspecified syntax form is unimplemented. -The entry-diagnostic and profile-independent structural type-formation judgments -are implemented. The [resource contract](../LANGUAGE.md#10-resource-classification) -requires containment of actual evaluator demand, including cumulative immutable -Gamma allocation, not a separate hypothetical dense-storage admission pass. -The sparse representation preserves declared bounds but does not establish -final-profile containment; composition includes independent execution -refinement over the exact D closure member sources, while -final-profile containment remains undischarged by these runs. The canonical -request/observation edge is realized under `EVALUATOR_ENTRY.md`; the standing -conformance clause there still governs witnessed defects, so no validation -may describe the surface as closed. +for byte layout; outer Gamma failures never convert into these tags. + +One invocation loop runs statements and blocks for both entry and states, +retaining locals, storage, and output up to the terminal. Scalar transitions use +checked subject and pattern tables, executing only the matched arm and trapping +as `NonExhaustiveTransition` if none matches. State transfers evaluate arguments +left to right against old bindings, drop dead block roots, bind new state +parameters, preserve machine parameters and receiver, and tail-call the target +state. Resultless return, falloff, and Console write/exit continuations end the +invocation without touching other states. + +Machine calls dispatch by checked callable ID. Receiver calls resolve the full +receiver place before evaluating arguments left to right; each argument captures +its value before the next runs, and callee parameters/locals get fresh roots. +Nested receiver calls mutate the live receiver place directly instead of +copy-in/copy-out. Both free and receiver machines support recursion, value +returns, resultless returns/falloff, and exit/trap propagation. Returning drops +callee roots and returns a non-place value while keeping caller storage updates. +Expression evaluation threads storage and stdout through operators, arguments, +indexes, assignments, returns, and transition subjects. Only the outer entry +wrapper turns normal completion into process exit; recursive `self.main()` keeps +its receiver. + +Sum constructors run through `execution/sums/construction.delta` using checked +owner/case IDs (never receiver lookup), evaluating arguments left to right and +capturing immutable payload snapshots. `sums/defaults.delta` builds lazy +first-case zero sums when the checked owner is known. Concrete sums store exact +owner/case IDs and independent payloads. `sums/transitions.delta` evaluates the +subject once and picks the first matching case or wildcard (missing sum coverage +at runtime is an internal error, not a scalar trap). `sums/bindings.delta` binds +fresh arm-local payload copies keyed by pattern and binder ID: mutating a binder +does not mutate the subject, and a view taken from a binder array keeps that +backing across state transfers via normal root liveness. + +Constructor arguments write each payload field immediately under the +[constructor payload establishment rule](../LANGUAGE.md#epsilon-constructor-payload-establishment-order): +an out-of-range `u8` payload traps as `ByteRange` immediately, keeping earlier +effects and skipping later arguments, while valid aggregates capture immutable +snapshots before later arguments run. + +Impossible checked states fail as internal errors rather than `Unsupported`: +non-call control targets, missing field refs, views stored as aggregates, or +logical operators passed to the non-logical scalar helper. Offsets point to the +normalized core, full projection, or type start (or 0 in the pure scalar +helper), with no buffered stdout emitted. No `Unsupported` branch remains in +execution. + +All grammar constructs parse and have staging execution paths—including +boundary/data/machine declarations, receiver-only qualified machines, states, +nonempty EOF checks, ordinary `self` bindings, disjoint constructor/method +lookup, unqualified/receiver/boundary calls, explicit state transfers, +state/machine collision errors, four-stage transition-pattern checks, final +wildcards, bare-state checks, resultless-argument anchors, five local block-exit +effects, post-`never` checks, `.as_slice`, and `array.as_slice()` rejection. +Staging execution alone does not prove full spec conformance: the canonical +entry in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md), full eight-file Omega D +execution in +[`tests/bootstrap/interpreted/epsilon/d-composition/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/d-composition/README.md) +(including `OmegaScalarCompiler::compile` emitting the Alpha tape), and +spec-model comparison in +[`tests/bootstrap/interpreted/epsilon/refinement/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/refinement/README.md) +exercise current coverage, while resource containment beyond the lower-chain +profile remains open. New work must cite a concrete failing program or spec +requirement. Entry diagnostics and structural type formation are implemented; +the [resource contract](../LANGUAGE.md#10-resource-classification) requires +accounting for actual cumulative Gamma allocation rather than a hypothetical +dense-storage pass. The standing conformance clause in `EVALUATOR_ENTRY.md` +still applies to any witnessed bug. The [closure-checking contract](../LANGUAGE.md#4-names-types-and-closure-checking) -owns collection namespaces, ordinary locals, transition-arm binders, and exact -same-phase `InvalidBoundary`/`DuplicateName` ordering. The implemented census -first collects every owner row and exact qualified machine identity from source -spans, then scans member, parameter, state, let, and transition-binder scopes. -It compares authored bytes exactly, keeps local identities source-shaped, -collects transition binders independently of later case and arity validity, -and returns the globally earliest declaration-start failure. Member-pair and -payload census folds retain the earliest candidate in a tail accumulator, so -wide records do not consume one Gamma call context per field. The declaration -fold likewise finishes each declaration's owner, machine, boundary, and contents -checks before advancing; pending minima do not accumulate across declarations. -The local census likewise carries its earliest candidate and active names in a -tail scan, so body width does not retain one recursive frame per local. -The syntax-selected case and receiver-method namespaces are disjoint. -The entry-shape judgment owns duplicate custody for -`Main`, `Console`, `Main.console`, `Console` members, and exact `Main::main` -only when an authored `Main::main` candidate -exists. Every unrelated duplicate remains in the ordinary census. Any ordinary duplicate owner -row is ambiguous, including same-kind duplication, so it contributes no -inferred owner kind and admits no machine to a data-owner callable registry -until repaired. - -State-name comparisons, duplicate selection, and state-local scope census use -tail folds. A machine with many states does not retain one pending minimum -operation per state; the earliest candidate and its existing tie behavior stay -explicit in the accumulator. This is required by the current Omega D parser's -786 authored states, not a new Epsilon state-count limit. - -Type formation walks every authored type after that census with an explicit -stored/parameter/local/return/nested placement. It derives array-length, -mixed-data, standalone-value `u8`, misplaced-`never`, forbidden-view, sealed- -`Console`, unknown-name, and recursive-value candidates independently, -suppressing the complete child subtree of a forbidden view. Stored `u8` and -`u8` nested beneath an array or view remain valid; a standalone parameter, -local, or return does not. One candidate merge chooses only by packed source -coordinate and treats a distinct same-anchor reason as an internal -contradiction. Accepted programs retain explicit source-ordered record/sum rows -so `data X {}` is concretely a zero-field record, plus all direct data- -containment edges. Recursion checks each edge with a visited-owner graph walk, -marking every edge in a value cycle at its named-reference coordinate without -expanding every path through a shared acyclic graph. Candidate identity is now -exactly its reason and packed coordinate; same-anchor reason equality derives -from the total reason mapping rather than a parallel integer discriminator. -The recursive-edge candidate fold reverses its search spine and accumulates -right-associated minima. Each reachability query still uses the unchanged full -edge graph; edge count no longer retains one pending return per query. This -does not bound the separate depth of a reachability search through owner types. -The member-type candidate fold reverses the member spine and merges each -candidate on the left of the accumulated result. This preserves the original -right-associated conflict behavior with bounded call depth. Declaration and -statement type-formation folds use the same ordering, so an earlier declaration -does not retain a pending merge while a later machine body is checked. State -type formation also reverses only the list spine and preserves exactly -`min(parameters, min(body, suffix))`. Conflict precedence makes reassociation -invalid even when ordinary distinct-coordinate errors would select the same -minimum. State width therefore consumes no pending return frame per state. -The [checking-invariant controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/checking-invariants/README.md) -pin this association with synthetic overlapping coordinates. They test the -private candidate algebra, not acceptance of an Epsilon source with those spans. -Data-shape selection and catalog unknown-owner selection likewise reverse only -their declaration traversal spine and retain the original merge ordering. -The winning candidate is promoted after successful census. Final type- -formation entry subjudgment runs before that promotion: no authored -`Main::main` owner/name candidate yields only `MissingEntry` at source extent; -once one exists, every malformed or -absent supporting component is `InvalidEntry`. The Console, Main, and entry -declaration scans retain their original forward seen flags in tail folds. -Every candidate inside those scans has reason `InvalidEntry`, so their minimum -is associative and a forward accumulator cannot introduce a conflict. Missing -components are still considered at the end, and defects never short-circuit -later checks. Entry facts do not enter the later body/control candidate carrier. -The retained expression facts now support -the implemented local block-exit pass. Remaining body/control judgments, -application storage realization, and complete execution remain open. - -The resolution catalog retains one row per formed top-level declaration and -keeps members, cases, bodies, and states inside their original AST owner. It -classifies qualified machine owners without numeric node IDs, provides exact -owner/machine/member/state lookups, and compares types structurally using -nominal name equality and semantic array lengths. Constructor and receiver- -machine lookup are structurally distinct by syntax. The language permits shared owner/ -name spellings and removes direct qualified static-machine selection. An -unqualified receiver remains a syntax rejection at its `&`; every qualified -machine must begin with its receiver, and a receiverless qualified declaration -is rejected at the first nonreceiver token. An unresolved qualified machine -declaration owner contributes `UnknownName` at that owner spelling even when -unused. A -neutral minimum-coordinate bucket deduplicates one reason/coordinate and -retains distinct ties for the eventual internal-contradiction promotion; -traversal and rejection-reason codes never choose between them. - -Ordered local resolution then walks every expression-bearing entry, state, and -transition position. Machine parameters remain active across the invocation; -state parameters and lets remain body-local; entry locals never leak into a -state; and transition binders exist only in their own continuation. Each body -precollects its pending lets without granting visibility, so a current or later -let reference contributes `UseBeforeInitialization` while a genuinely absent -value name contributes `UnknownName`. Successful references retain their exact -parameter, let statement, or pattern/binder declaration and are keyed by -expression constructor plus exact span; a postfix node therefore cannot borrow -the fact for its same-start base. Call heads, discarded postfix statements, and -transition continuations now carry distinct expression-use facts rather than -one overloaded non-value bit. This is durable identity custody for typing and -execution, not a partial acceptance judgment. - -The same expression walk now retains complete settled result facts -without introducing a second recursive checker. Integer, character, and -Boolean literals are `i32`; strings are immutable `&[u8]`; and resolved -parameter/local reads retain their value type and optional storage place. -Assignable values retain their storage type; immutable views carry no place. -Reading `u8` storage yields `i32` while preserving a `u8` place for -the later store check. Groups preserve the complete value/place result; -negation and every binary operator consume complete `i32` operands and produce -a non-place `i32`. Their resultless/`never` branches are retained independently -at enclosing-relation or exact-call anchors, and a missing sibling never -manufactures an operator mismatch or result. - -The current source retains direct qualified constructors before context, -arity, or argument typing; static data-machine custody is absent. The -generalized ledger retains -unqualified machine applications in ordinary, nested-call-head, and postfix- -statement positions, including arbitrarily grouped bare-name heads. -Constructor and machine lookups remain independent, and the semantic machine -lookup admits only a catalog row already resolved beneath a data owner. -Authored arguments are walked as siblings; arity depends only on admitted -identity and count; and the type join waits for every required value fact. A -compatible constructor yields its nominal non-place value. Free machines retain -their declared value, resultless, or `never` fact through the unqualified path. -Stored constructor payload `u8` accepts an `i32` value and leaves range -enforcement to runtime `ByteRange`. A bare resolved machine in an ordinary -value position contributes `TypeMismatch` at the qualified expression -start. Unqualified machine lookup precedes local-value fallback because call -grammar selects that namespace; a genuinely absent head retains the local -`UnknownName`/`UseBeforeInitialization` premise, while a completed noncallable -local is `TypeMismatch` at the application. One admitted-signature join owns -arity, complete argument typing, and value/resultless/`never` production for -direct-qualified, unqualified, data-receiver, and sealed-boundary spellings. -The authored `self` token is an ordinary name expression. A receiver-bearing -qualified data machine installs an ordinary named receiver binding with its -owner's nominal value and storage-place type; states inherit that binding, and -an undeclared `self` follows ordinary `UnknownName` resolution. -Grouped named-receiver heads preserve exact data-machine or boundary-member -custody before receiver-place and signature checks. Same-spelled record fields -fall back to ordinary field custody and call syntax selects a receiver machine; -the language likewise permits a same-spelled case because constructor syntax is disjoint. -Chained resultless/`never` receivers retain their category/terminal failures. -Grouped bare-qualified call heads now transfer machine custody to the exact -outer application; a completed constructor or machine application followed by -another suffix remains an ordinary noncallable base. Discarded postfix -statements carry their outer anchor through grouping and select an unqualified -machine before local fallback. Only exact machine custody with authored -application syntax is category-admitted. Constructors, bare machines, known -qualified fields/boundary members, and complete noncallable values fail before -arity/type checking; an admitted machine with a missing result gains no -dependent mismatch. Value/resultless machine results may be discarded, while -a successful `never` result remains input to the later block-flow judgment. -The bare head and outer application intentionally retain distinct exact-AST -callable rows; execution must query the exact application row and must not treat -every ledger row as an executable call. -Bare state spelling and the remaining transition judgments stay open as -described below. - -Explicit transition applications now join the enclosing machine's state -namespace with the global unqualified-machine namespace before arity or -argument typing. A dual match is `InvalidControlTarget` and retains neither -target. A state-only explicit application retains exactly one exact-AST state -row, resolved on incomplete/failed parameter premises and complete only after -the all-value join; state custody is neither callable custody nor an expression -result. Machine-only and qualified/receiver/boundary applications preserve the -existing callable ledger. Grouping normalizes lookup without changing the -authored continuation anchor, and state/local spelling reuse selects the state -only in this exact control syntax. Constructors, bare machine selectors, -static receiver spellings, and complete field/scalar values receive category -failures before dependent checking; same-spelled authored fields remain fields -without call syntax. The transition contract requires authored argument syntax for every state -transfer: a state-only bare spelling contributes `InvalidControlTarget` at the -continuation start without entering the state-application ledger. That branch -is implemented. Machine-continuation exit effects are implemented as -local block facts and require no reachability pass. - -An invalid noncallable application has no result fact to propagate through -outer grouping. Transition admission therefore inspects its ungrouped call -shape and the completed base result before deriving `InvalidControlTarget`. -The rejection keeps the authored continuation start, including an outer `(`; -grouping cannot turn a rejected target into an accepted continuation. An -unresolved base still supplies no inferred target failure. - -Each complete transition subject is retained once as scalar `i32` or one exact -nominal sum owner after the ordinary result category relation. Pattern -resolution is source-shaped and independent across arms: scalar selectors have -semantic `i32` identity, qualified cases retain exact owner/member custody, and -subject-owner compatibility grants semantic pattern identity before payload -arity gates complete pattern custody. A later repeated admitted identity is -`DuplicatePattern` even if the first occurrence later fails arity. `true` and -`1` are one selector, as are `false` and `0`, independent of leading zeros. -Only a complete case pattern supplies positional payload types and places to -its binder locals; `u8` payloads therefore read as `i32` while retaining -their storage type. Distinct name-resolved, subject-admitted, identity- -owned, and complete facts replace the former broad `Resolved | Complete` -progress. Every continuation remains independently -checked, and each sum transition retains complete, missing, or unresolved -coverage. Transition grammar admits one optional final wildcard; a following -pattern is `UnexpectedToken`, while a redundant final wildcard remains legal. -Missing complete sum coverage is `NonexhaustiveSum` at the subject after every -pattern premise completes. These branches are implemented. - -Named-record projection retains both the exact owner declaration and authored -field for later ordinal/layout recovery. A field inherits a place only from a -place-valued base, and storage `u8` reads as value `i32` without losing its -`u8` place. Array indexes follow the same rule; immutable-view indexes never -produce a place. Array/view `.len` is non-place `i32`, and complete range -slices produce a non-place immutable view. Present indexes and bounds require -complete `i32` facts, but bounds remain runtime `Bounds` checks rather than -static folding. A field selector in call-head position is classified against -its complete receiver before ordinary field fallback. Record fields literally -named `len` or `as_slice` remain ordinary fields because contextual array/view -members are selected only after base-type classification. - -The same selector classifier owns settled negative projection: an absent -ordinary member is `UnknownName` at its spelling; a known case, machine, or -boundary member used as a value selector is `TypeMismatch`; contextual names -on unsupported complete receivers are `TypeMismatch`; and resultless/`never` -bases retain category/terminal failures. Grouped call heads reuse the same -classifier before the separate call suffix. Binary, index, and slice relations -require complete nonterminal results from every operand, including each present -slice bound, before a resultless child can produce a parent `TypeMismatch`. -An unresolved or `never` sibling cannot satisfy that join. Mispositioned `never` -remains an independent child failure at its exact call head. Unsupported-base -and non-`i32` relations additionally require every consumed value fact. Missing -siblings therefore manufacture no parent relation or result. Static index/slice -checking still imposes no range judgment. - -The fact pass follows the closure-checking contract by producing no parent fact or dependent diagnostic -while a consumed child premise is absent. Admitted callable arity is a sibling -judgment and can therefore coexist with an independently failing -argument, while result typing waits for complete compatible values. A separate -call suffix on a complete ordinary value or resultless result is `TypeMismatch`; -an embedded `never` result is `InvalidTerminal`. The contract gives every -direct authored argument its independently anchored category branch regardless of -enclosing-callee admission and arity. The argument contract fixes resultless `TypeMismatch` at -the authored argument expression start, including outer grouping, while grouped `never` -retains its exact call-head anchor. This direct-argument rule does not make -a nested binary/index/slice mismatch independent of that expression's own -complete-premise join. Both rules are implemented. Let and -`assert` -relations consume only complete values. Assignment checks its left value/place -and right value branches independently, and compares against the retained -storage type only after both facts exist; this admits `i32` establishment into -`u8` storage without treating its zero-extended read type as the place type. - -The enclosing machine's optional return type now reaches entry, state, and arm -returns. Explicit absence/value relations use exact anchors and category -premises without resolving the expression twice. A source-shaped statement -flow fact retains a successful standalone `never` result, diagnoses its first -following executable construct at the exact terminating delimiter, and still -visits every later authored child. A transition after `never` therefore still -checks its subject expression, patterns, and continuation expressions, but -derives neither transition-subject admission nor sum coverage: those parent -judgments require an open statement sequence. A complete record-valued subject -cannot displace the transition's `InvalidTerminal` with a parent `TypeMismatch`; -an independent unknown child name still contributes its own `UnknownName`. -Suppressed continuation heads still resolve unqualified spellings and qualified -owners/members. Receiver-member lookup requires a complete receiver value type. -Known states, machines, constructors, fields, and contextual spellings retain -no dependent control-admission or arity judgment; a missing spelling retains -its exact `UnknownName` anchor. Groups do not suppress that lookup, and all -authored argument expressions remain independently checked. -The five-effect carrier settles local -falloff, explicit returns, machine continuations, `never` calls, and state -transfers without a reachability/fixed-point pass. Remaining transition/control -candidates still require the rest of the premise DAG. The completed body -candidate bucket now promotes no candidate to acceptance, one exact reason to -rejection, and a distinct same-coordinate reason tie to internal failure while -the separate fact-producing entry remains available to diagnostic probes. The -fact pass now -implements accepted receiver/result, exact contextual failures, and -`array.as_slice()` value-call rejection; the closure-checking contract still fixes how the remaining -nested failure candidates compose. This foundation does not claim final -acceptance or runtime realization. +governs namespaces, locals, transition binders, and same-phase +`InvalidBoundary`/`DuplicateName` ordering. The name census collects all type +owners and qualified machine IDs first, then checks member, parameter, state, +let, and transition-binder scopes by exact bytes, returning the earliest +declaration-start error. Member, payload, declaration, local, and state folds +all keep the earliest error in a tail accumulator so wide records, wide blocks, +and machines with many states (like Omega D's 786-state parser) do not consume +one Gamma call frame per item. Case and receiver-method namespaces are disjoint. +When an authored `Main::main` candidate exists, duplicate `Main`, `Console`, +`Main.console`, `Console` members, and `Main::main` defer to the entry check; +unrelated duplicates stay in the ordinary census, and ambiguous owners infer no +boundary or data kind. + +Type formation walks every authored type after the census with explicit +placement context (stored, parameter, local, return, nested). It derives +array-length, mixed-data, standalone `u8`, misplaced `never`, forbidden view +(suppressing nested errors inside the view), sealed `Console`, unknown name, and +recursive-value errors independently, merging by packed offset and treating +distinct reasons at the same offset as an internal error. Accepted programs keep +explicit record/sum rows (so `data X {}` is a zero-field record) and direct +containment edges. Recursion checks each edge with a visited-owner walk, marking +every cycle edge without expanding shared acyclic subgraphs. Candidate identity +is `(reason, offset)` with equality derived from the reason table rather than a +separate discriminator. Recursion, member, declaration, statement, state, +data-shape, and unknown-owner folds reverse their input spines and merge right +to left (`min(parameters, min(body, suffix))`) to keep bounded call depth while +preserving exact conflict associativity, pinned by the +[checking-invariant controls](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/checking-invariants/README.md). +Type formation ends with the entry check: without an authored `Main::main`, it +returns only `MissingEntry` at source extent; once one exists, all missing or +malformed entry pieces return `InvalidEntry` via tail-recursive scans that never +short-circuit. Entry facts stay separate from body/control errors. + +The resolution catalog stores one row per top-level declaration, keeping +members, cases, bodies, and states in their original AST nodes. It classifies +qualified machine owners without numeric node IDs, supports exact lookups, and +compares types by nominal name and semantic array length. Constructor and +receiver-machine lookups are separated by syntax; unqualified receivers reject +at `&`, receiverless qualified machines reject at the first nonreceiver token, +and unresolved qualified machine owners report `UnknownName` even if unused. A +neutral minimum-offset bucket deduplicates identical `(reason, offset)` pairs +and flags distinct ties as internal errors without using traversal or reason +order to break ties. + +Ordered local resolution walks every entry, state, and transition expression. +Machine parameters stay in scope across states; state parameters and lets stay +body-local; entry locals never leak into states; transition binders stay +arm-local. Each body precollects pending lets so referencing a current or later +let reports `UseBeforeInitialization` while missing names report `UnknownName`. +Resolved refs key by expression kind plus exact span so postfix nodes never +borrow their base's fact. Call heads, discarded statements, and transition +continuations keep distinct expression-use facts. + +The same expression pass derives complete value/place facts without a second +recursive checker. Integer, char, and Boolean literals are `i32`; strings are +immutable `&[u8]`; parameter/local reads keep value type and optional place +(immutable views have no place; `u8` reads as `i32` while keeping a `u8` place). +Groups preserve value/place; unary `-` and binary ops require `i32` operands and +yield non-place `i32`, keeping resultless/`never` errors independent and never +inventing mismatches when a sibling failed. + +Direct qualified constructors, unqualified calls (including grouped heads and +discarded statements), data-receiver calls, and sealed-`Console` calls all share +one callable table and signature-checking join. Constructors and machines stay +separate by syntax; arguments check independently; arity depends only on the +admitted target and count; and result typing waits for all argument values. +Stored `u8` constructor payloads accept `i32` (range-checked at runtime as +`ByteRange`). Bare resolved machines in value positions report `TypeMismatch`. +In call position, unqualified machines resolve before locals; absent heads keep +local `UnknownName`/`UseBeforeInitialization`, while noncallable locals report +`TypeMismatch`. `self` resolves as an ordinary named binding installed by +receiver machines (inherited by states, `UnknownName` outside). Same-spelled +record fields fall back to fields unless called, and same-spelled sum cases stay +disjoint. Bare heads and outer calls keep separate callable rows so execution +queries only the exact call node. + +Explicit transition applications check both the enclosing machine's states and +unqualified machines before arity or argument typing: matching both rejects as +`InvalidControlTarget`; matching only a state stores a separate state-call row +(not a callable or value); matching a machine or receiver/boundary call uses the +callable table. Grouping normalizes lookup without changing the anchor. Bare +states, bare machines, constructors, static receiver spellings, and noncallable +values reject before arity/type checks; grouping an invalid call head keeps the +outer `(` anchor and never hides `InvalidControlTarget`. + +Transition subjects resolve to `i32` or a nominal sum. Patterns check +independently per arm: scalar selectors compare by `i32` value (`true`/`1` and +`false`/`0`, ignoring leading zeros), qualified cases keep owner/member IDs, +compatible patterns claim identity before arity checks (so repeats report +`DuplicatePattern` even if the first fails arity), and only complete case +patterns type their payload binders (`u8` reads as `i32` with a `u8` place). +Four progress levels replace the old `Resolved | Complete` split. Grammar allows +at most one final wildcard (a pattern after `_` is `UnexpectedToken`; redundant +final `_` is valid); missing sum coverage reports `NonexhaustiveSum` at the +subject once all patterns finish. + +Record projections keep owner and field IDs, inheriting places from place bases +(`u8` reads as `i32` with a `u8` place). Array indexing follows the same rule; +view indexing never yields a place. `.len` yields non-place `i32`, and slices +yield immutable views; indexes and bounds require `i32` and check range at +runtime (`Bounds`). Call-head field selectors classify against the receiver +before field fallback; record fields literally named `len` or `as_slice` stay +ordinary fields. Missing members report `UnknownName`; wrong member kinds, +unsupported contextual receivers, and non-`i32` indexes/bounds report +`TypeMismatch`; resultless/`never` bases keep their category/terminal errors. +Binary, index, and slice checks wait for complete nonterminal operands before +firing parent `TypeMismatch`; misplaced `never` anchors at its call head. + +Following the dependency DAG, no parent fact or error fires while a child fact +is missing. Direct call/constructor arguments anchor resultless `TypeMismatch` +at the argument start (including outer `(`) and grouped `never` at its call head +independently of callee admission or arity. `let` and `assert` require complete +values; assignment checks left place and right value independently before +comparing against the stored type (allowing `i32` into `u8`). + +The enclosing machine's return type propagates to entry, state, and arm returns. +A standalone `never` statement flags the first following executable construct at +its terminating delimiter while still checking all later children; a transition +after `never` checks its subject, patterns, and continuations without deriving +subject admission or sum coverage (preventing a parent `TypeMismatch` from +masking `InvalidTerminal`, while keeping independent `UnknownName` errors). +Suppressed continuation heads still resolve names and check arguments without +running control-admission or arity checks. Five local block-exit effects handle +falloff, returns, machine continuations, `never` calls, and state transfers +without reachability analysis. The body candidate bucket promotes zero errors to +acceptance, one error to rejection, and same-offset reason ties to internal +failure. `.as_slice` receiver checks and `array.as_slice()` rejection are +implemented. ## Contract-derived conformance plan -This is the compact case matrix for the eventual adjacent executable gate. It -derives from [`../LANGUAGE.md`](../LANGUAGE.md); the full -matrix must execute through the Delta-written evaluator, compiled by the -selected Gamma-authored Delta compiler under `ConformanceBytesV1`. The -canonical request/observation profile is realized by -[`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md). - -The current implementation requires a receiver on every qualified data -machine, allows case/receiver-method spelling reuse, normalizes `self` through -ordinary binding lookup, and rejects a direct static-machine spelling. The -matrix below describes that selected behavior. +This compact matrix derives from [`../LANGUAGE.md`](../LANGUAGE.md) for +execution through the Delta-written evaluator compiled under +`ConformanceBytesV1` with [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md). It matches +the current language rules: mandatory receivers on qualified data machines, +case/receiver-method name reuse, ordinary `self` lookup, and no static +receiver-machine calls. | Area | Positive controls | Negative controls and exact obligation | | --- | --- | --- | @@ -531,135 +311,96 @@ matrix below describes that selected behavior. | Declaration census | owner/unqualified-machine spelling reuse; qualified versus unqualified machine distinction; case/receiver-method spelling reuse; member/local reuse; local reuse across entry, distinct states, and sibling transition arms | boundary/data owner collision; duplicate exact machine/member/payload/parameter/state/let/transition binder; active machine/state/local/binder shadowing; globally earliest declaration-start coordinate across `DuplicateName` and `InvalidBoundary`; ambiguous owner contributes no inferred boundary kind | | Type and body checking | forward owners/machines/states; empty and nonempty records; finite sums/arrays; views only in admitted positions; unordered exact `Console` member signatures; complete scalar and sum transitions, including redundant final wildcard | zero-array, mixed-data, misplaced-`never`, escaping-view, and sealed-`Console` cases; absent/malformed/duplicate/competing entry shapes; category/semantic-duplicate/arity/missing-coverage transitions; every reason from `UnknownType` through `NonexhaustiveSum`, at its exact structural anchor; no reason-table tie-break | -Declaration-census rows already settled by the third line include these discriminator pairs: - -- a type owner and an unqualified machine may share a spelling, while boundary - and data owners may not; -- `parse` and receiver method `Owner::parse` are distinct machine identities, - while two exact machine owner/name pairs conflict; -- a case and receiver method under one data owner may share a spelling because - constructor and receiver syntax select different namespaces; -- fields and cases share their data-owner member scope, but a member and bare - local may share a spelling; -- machine parameters conflict in the entry and every state body; state - parameters and lets conflict only in their active body; and -- entry and sibling state bodies may reuse local spellings. - -The census requires separate transition-binder controls: sibling arms may reuse a spelling, -while one arm cannot reference another arm's binder (`UnknownName`); duplicate -binders within one arm and collisions with each active outer-local class are -`DuplicateName`. An unknown case or wrong payload arity does not suppress that -earlier census, so the suite also pins the two-round -`DuplicateName`-then-`UnknownName` result for an unknown case and the -`DuplicateName`-then-`ArityMismatch` result for a known case with the wrong -payload arity. Mixed collection controls cover both source orderings of -unrelated `DuplicateName` and `InvalidBoundary`, plus a boundary/data-ambiguous -owner that produces only its duplicate until repaired. - -The language makes the type-formation gate finite and exact. Positive controls include -lengths 1 and `INT32_MAX`, one zero-field record value, stored or nested `u8`, -`never` only as the outer return type, views only as parameter/local roots, and -`Console` only at `Main.console`. Negative controls include zero at its length -literal, mixed data at its declaration name, standalone parameter/local/return -`u8`, every misplaced `never`, every forbidden outer view, and every other -`Console` placement. Nested defects beneath a forbidden view do -not displace its outer `EscapingView`; structurally impossible same-anchor -reason collisions are internal contradictions. Planned storage-profile controls cover -an unused oversized type, nested and disjoint individually excessive arrays, -one reachable decisive array with its length-literal coordinate, and -aggregate-only record/sum/root exhaustion with no coordinate. Exact demands -remain exact; larger demands use `INT64_MAX` witness. Both storage -refusals require `requested > limit` and publish no Epsilon observation. Adjacent controls -exercise zero-sized multiplication, exact `INT64_MAX`, and the first larger -demand without taking a Delta trap. - -Transition controls cover a pattern after `_`, a repeated `_`, and an -exhaustive sum with a redundant final wildcard; category-incompatible scalar -and case patterns; duplicate cases before payload arity; and missing sum -coverage at the subject. Scalar identity controls pair `true` with `1`, `false` -with `0`, and decimal spellings with leading zeros. Two-round controls repair a -category, duplicate, or arity failure and then expose the previously suppressed -`NonexhaustiveSum`. Scalar misses remain executable -`NonExhaustiveTransition` traps rather than static rejections. - -Resolution-catalog, local-resolution, and expression-fact controls remain -planned as retained executable gates rather than claimed default execution: -forward data -owners, unknown qualified owners, same-spelled type and unqualified machine, -distinct qualified/unqualified machines, case/receiver-method reuse, -mandatory parentheses on zero-parameter machine calls, state-name reuse across -separate machines, parameter and ordered let visibility, -`UseBeforeInitialization` versus `UnknownName`, entry/state -isolation, arm-local binder visibility, exact same-start postfix separation, -literal/read/group/arithmetic facts, record-field custody, `u8` read/place -splitting, array-place versus immutable-view indexing, every optional slice- -bound shape, `.len`, ordinary named receiver binding for reserved `self`, grouped named-data and -sealed-`Console` receiver calls, authored-field fallback, same-spelled -field/machine call selection, direct-static-machine refusal, receiver -place refusal, unknown receiver members, and chained resultless/`never` -receiver failures. Array-view conformance adds a -place-valued fixed array and computed `array[i()].as_slice` positive case; -view `.as_slice` as `TypeMismatch`; a non-place array result as `InvalidPlace`; -the parsed extra-call form `array.as_slice()` as `TypeMismatch`; an ordinary -record field named `as_slice`; and `f().as_slice = x` producing only the inner -receiver `InvalidPlace` under premise closure. Constructor and receiver-machine -rows remain structurally distinct by syntax; no body context, arity, or expected -type selects between namespaces. Controls cover nullary and payload cases, -same-spelled case/receiver-machine and field/receiver-machine positive cases, an -unqualified receiver at its `&`, explicit `()` on a zero-parameter machine, and -a direct receiver-machine spelling that cannot act as a static call. Transition conformance adds -distinct bare zero-parameter state, bare parameterized state, bare machine, and -state/machine-collision controls; all share `InvalidControlTarget` at the -continuation start while only the machine-only case retains callable custody. -Premise-DAG controls include unresolved callee versus place checking, -wrong arity alongside an independently failing argument, resultless/`never` -value use, projection reason/anchors, and exact let/assignment/assert/return -relations. Argument conformance adds valid, wrong-arity, unknown/inadmissible-callee, constructor, -and grouped resultless/`never` argument controls, including the absence of a -distinct-reason coordinate tie. Block-exit conformance adds every local block category/effect, -unused states, closed cycles, resultless/`never`/value continuation calls, and -exact after-`never` delimiter and falloff-brace controls. The language specifies -`.as_slice` receiver validity and once-evaluation. - -Runtime conformance must execute all nine settled traps—`Overflow`, -`DivisionByZero`, `SignedDivisionOverflow`, `ShiftCount`, `ByteRange`, `Bounds`, -`NonBoolean`, `Assertion`, and `NonExhaustiveTransition`—and preserve the exact -stdout prefix before each trap. Resource conformance is parameterized by the -selected evaluator profile rather than invented constants: for every source, -storage, recursion/step, and output bound, exercise the exact admitted boundary -and its adjacent refusal and prove that exhaustion publishes no Epsilon -observation. +Name-census pairs covered by row 3: + +- a type owner and an unqualified machine may share a name, while boundary and + data owners may not; +- `parse` and `Owner::parse` are distinct machines, while duplicate owner/name + pairs collide; +- a case and receiver method on one data owner may share a name; +- fields and cases share the data-owner member scope, while a member and local + may share a name; +- machine parameters collide across entry and all states; state parameters and + lets collide only in their own body; +- entry and sibling states may reuse local names. + +Transition-binder tests check sibling-arm reuse, cross-arm `UnknownName`, and +in-arm or outer-scope `DuplicateName`. Because binders collect before case/arity +checks, two-round tests pin `DuplicateName` before `UnknownName` and +`DuplicateName` before `ArityMismatch`. Mixed tests check both source orders of +`DuplicateName` and `InvalidBoundary`, plus an ambiguous owner reporting only +its duplicate. + +Type-formation tests cover lengths 1 and `INT32_MAX`, zero-field records, stored +or nested `u8`, `never` only as outer return type, views only as parameter/local +roots, and `Console` only at `Main.console`. Negative cases cover zero length, +mixed data, standalone `u8`, misplaced `never`, forbidden outer views +(suppressing nested errors under `EscapingView`), other `Console` placements, +and internal-error reason collisions. Storage-profile controls test unused large +types, excessive arrays, decisive array coordinates, aggregate-only exhaustion, +`INT64_MAX` capping, `requested > limit` refusals with no Epsilon output, and +overflow-safe zero-size and `INT64_MAX` multiplication without Delta traps. + +Transition tests cover patterns after `_`, repeated `_`, exhaustive sums with +redundant `_`, mismatched scalar/case patterns, duplicate cases before arity, +missing coverage at the subject, scalar equivalence (`true`/`1`, `false`/`0`, +leading zeros), two-round `NonexhaustiveSum` reveal after fixing earlier pattern +errors, and runtime `NonExhaustiveTransition` for unmatched scalars. + +Catalog, local-resolution, and expression-fact tests cover forward owners, +unknown qualified owners, owner/machine name reuse, qualified vs. unqualified +machines, case/method reuse, mandatory `()` on zero-arg calls, state reuse +across machines, parameter/let visibility, `UseBeforeInitialization` vs. +`UnknownName`, entry/state isolation, arm-local binders, same-start postfix +nodes, literal/read/group/math facts, record fields, `u8` read/place splitting, +array vs. view indexing, slice bounds, `.len`, `self` receiver binding, grouped +data/`Console` receiver calls, field fallback, field/method call selection, +static-machine rejection, receiver place checks, unknown members, and chained +resultless/`never` receivers. Array-view tests add place-valued arrays, +`array[i()].as_slice`, view `.as_slice` (`TypeMismatch`), non-place array +(`InvalidPlace`), `array.as_slice()` (`TypeMismatch`), record field `as_slice`, +and `f().as_slice = x` reporting only the inner `InvalidPlace`. Constructor vs. +method tests cover nullary/payload cases, same-name case/method and +field/method, unqualified `&`, explicit `()`, and static receiver rejection. +Transition tests add bare zero-arg state, bare parameterized state, bare +machine, and state/machine collision (all `InvalidControlTarget`, only bare +machine keeping callable lookup). Dependency-DAG tests cover unresolved callee +vs. place, wrong arity alongside failing argument, resultless/`never` value use, +projection anchors, let/assign/assert/return checks, grouped argument anchors +without reason ties, and all local block-exit effects, unused states, cycles, +continuation calls, post-`never` delimiters, falloff braces, and once-evaluated +`.as_slice`. + +Runtime tests must trigger all nine traps—`Overflow`, `DivisionByZero`, +`SignedDivisionOverflow`, `ShiftCount`, `ByteRange`, `Bounds`, `NonBoolean`, +`Assertion`, and `NonExhaustiveTransition`—preserving exact prior stdout. +Resource tests are parameterized by the active profile and verify exact admitted +and off-by-one refused limits for source, storage, recursion/steps, and output +with zero Epsilon output on exhaustion. ## Completion state -- the evaluator closure selected by `epsilon_compiler.delta.sources` is - complete against [`../LANGUAGE.md`](../LANGUAGE.md) and compiles through the - selected Delta and Gamma route into the canonical receipt; -- the physical request and observation profile is realized as the section-11 - EREQ envelope with canonical observations and EEOUT refusal frames - ([`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md); the diagnostic edge's derived - profile stays in [`EVALUATOR_PROFILE.md`](EVALUATOR_PROFILE.md)); -- composition with the exact Epsilon-written Omega D source is exercised by +- `epsilon_compiler.delta.sources` matches [`../LANGUAGE.md`](../LANGUAGE.md) + and compiles through Delta and Gamma into the canonical receipt; +- the section-11 EREQ envelope, canonical observations, and EEOUT refusal frames + are implemented in [`EVALUATOR_ENTRY.md`](EVALUATOR_ENTRY.md) (the + diagnostic profile stays in [`EVALUATOR_PROFILE.md`](EVALUATOR_PROFILE.md)); +- full Omega D execution runs in [`tests/bootstrap/interpreted/epsilon/d-composition/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/d-composition/README.md); -- the independent reconstruction of `CheckEpsilon`/`RunEpsilon` lives under - [`tests/bootstrap/interpreted/epsilon/refinement/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/refinement/README.md) and - checks direct `RunEpsilon` refinement and negative mutations byte-for-byte; -- validating every Epsilon expression, statement, state, trap, and Console - execution rule remains the standing conformance clause — implemented - dispatch paths do not establish refinement, and witnessed checking/runtime - defects are corrected when a D slice or contract control witnesses one. - -Any new validation placed here must reconstruct the Delta-written evaluator's -execution of Epsilon. Alpha target emission belongs to Omega D and C, not this -owner. - -The active migration order lives in +- the independent `CheckEpsilon`/`RunEpsilon` model lives in + [`tests/bootstrap/interpreted/epsilon/refinement/`](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/epsilon/refinement/README.md) + and checks byte-for-byte agreement and negative mutations; +- checking every expression, statement, state, trap, and Console rule remains + governed by the standing conformance clause: fix any bug a D slice or test + exposes. + +New validation here must test the Delta evaluator executing Epsilon; Alpha code +generation belongs to Omega D and C. Active migration work is tracked in [`TASKS_BOOTSTRAP.md`](../../../TASKS_BOOTSTRAP.md). ## Deletion condition -This implementation owner is retained because its exact path is part of the -canonical bootstrap-chain contract. Delete any child subtree that does not reconstruct, -implement, or test -`manifested Delta evaluator closure + Epsilon source → RunEpsilon`; replace the owner only -atomically with a changed, explicitly ruled bootstrap-chain topology. +Keep this directory because its path is part of the canonical bootstrap chain. +Delete any child that does not build, implement, or test +`manifested Delta evaluator closure + Epsilon source → RunEpsilon`; replace this +directory only atomically under an explicit bootstrap-topology change. diff --git a/bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md b/bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md index 68abe84e03b5..b5e043ba2d76 100644 --- a/bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md +++ b/bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md @@ -2,7 +2,7 @@ ## Request -The evaluator consumes one exact byte stream: +The evaluator reads one exact byte stream: ```text 0..4 little-endian u32 Gamma source length @@ -10,51 +10,53 @@ The evaluator consumes one exact byte stream: ... all remaining bytes as sealed input ``` -The complete request is capped at 137,363,456 bytes (the selected 131 MiB -evaluator frame). Source accepts HT, LF, CR, and printable ASCII only. +A complete request is capped at 137,363,456 bytes (the 131 MiB evaluator frame). +Source accepts only HT, LF, CR, and printable ASCII. ## Observation -Every `write` is buffered inside the evaluator. A scalar `main` preserves the -Gamma transformer convention: its value must be `0..255`, is appended to the -buffer, the complete buffer is published, and status zero is returned. +Every `write` appends to an internal output buffer. A scalar `main` follows the +Gamma transformer convention: its result must lie in `0..255`, is appended to +the buffer, the full buffer is written to stdout, and the process exits with +status 0. -An application source begins with the exact first declaration -`(def $application () Int 1)` and returns `(pair status publish)` from `main`. -The validated marker selects application failure ownership before execution. -Both result fields must be scalar, `status` must be `0..254`, and `publish` must -be zero or one. Status zero requires publication. A nonzero published result -requires a nonempty buffer, making publication reconstructible from the process -observation. A discarded result must have nonzero status. The evaluator -validates the complete result before either flushing or discarding the buffer. +An application program starts with `(def $application () Int 1)` as its first +declaration and returns `(pair status publish)` from `main`. That marker enables +application exit codes before execution begins. Both fields must be scalars, +`status` must be in `0..254`, and `publish` must be 0 or 1. Status 0 requires +publication. A nonzero published result requires a nonempty buffer so the caller +can distinguish publication from discard using stdout alone. A discarded result +must have nonzero status. The evaluator checks both fields before flushing or +discarding the buffer. -Before a valid application result is returned, evaluator-owned statuses are: +Before an application returns a valid result, the evaluator uses these exit +codes: | Status | Meaning | | ---: | --- | | 0 | Complete scalar transformer. | | 1 | Invalid request or Gamma source. | -| 2 | Authored trap while evaluating reached code. | -| 3 | Incomplete bounded storage. | -| 4 | Internal evaluator contradiction. | - -Evaluator failures expose no stdout. A valid application result selects its own -declared status. Status-zero stdout, including empty stdout, and nonempty -nonzero stdout are authoritative publication; empty nonzero stdout is a -discarded outcome. Invocation plumbing applies only that generic predicate and -does not decode application statuses or bytes. - -After a validated application marker, evaluator failures map to the generic -generated-program block: internal or unclassified evaluator failure is 248, -authored trap is 249, value/environment/call-stack exhaustion is 250, immutable -pair exhaustion is 252, request extent is 253, and buffered-output extent is -254. Status 251 is reserved for a detected memory-containment violation; no -checked evaluator path currently produces it. Invalid Gamma source remains -status 1 before application execution. +| 2 | Program trap during execution. | +| 3 | Exhausted evaluator memory or stack limit. | +| 4 | Internal evaluator bug. | + +Evaluator failures emit no stdout. A valid application result exits with its +returned status. Status-0 stdout (including empty stdout) and nonempty nonzero +stdout count as published output; empty nonzero stdout is a discarded result. +Launcher scripts check only that rule and never parse application statuses or +output bytes. + +Once the application marker is validated, evaluator failures map to the +generated-program status block: 248 for internal or unclassified failure, 249 +for a program trap, 250 for value/environment/call-stack exhaustion, 252 for +immutable-pair exhaustion, 253 for request size overflow, and 254 for output +buffer overflow. Status 251 is reserved for memory-containment violations; no +checked path currently triggers it. Invalid Gamma source still returns status 1 +before application execution starts. ## Private partition -The current evaluator uses these Alpha memory regions: +The evaluator partitions Alpha memory as follows: ```text 0x01100000..0x01500000 lexical environment rows @@ -67,25 +69,22 @@ The current evaluator uses these Alpha memory regions: 0x20400000..0x2000000000 immutable pair nodes ``` -The retired `0x00100000..0x01100000` request and `0x0e000000..0x0efffffc` -output regions are unused. The selected AlphaBootstrapV5 realization provides -128 GiB of memory. The Alpha -tape occupies low memory and the hidden Alpha call stack still grows down -from `0x10000000` — the same address the request region starts at; the stack -uses only the bytes strictly below its origin, so request writes can never -meet it. Pairs grow upward from `0x20400000`, above the output buffer. The -function partition occupies part of the former pair region. The environment -uses the space between the former request end and the value stack, including -the former function partition at `0x01200000..0x01300000`. Every evaluator-owned -extent is preflighted before use; the hidden Alpha stack is discharged by the -containment argument below. +The old `0x00100000..0x01100000` request region and `0x0e000000..0x0efffffc` +output region are unused. AlphaBootstrapV5 supplies 128 GiB of memory. The Alpha +tape sits in low memory and the Alpha call stack grows downward from +`0x10000000` (the start of the request buffer); because the stack only touches +bytes strictly below `0x10000000`, it never collides with request writes. Pairs +grow upward from `0x20400000` above the output buffer. Functions occupy part of +the old pair region. The environment fills the space between the old request end +and the value stack, including the former function table at +`0x01200000..0x01300000`. The evaluator bounds-checks every region before +writing; the containment argument below bounds the Alpha call stack. ## Exact capacities -All counts below belong to this evaluator profile, not to Gamma's language -semantics. An operation that would exceed one of them halts with status 3 -before the offending store or write. Equality with an end address is admitted; -only an extent beyond the end is refused. +These limits belong to this evaluator profile, not to Gamma's language spec. +Exceeding any limit halts with status 3 before the offending write. Matching an +end address exactly is allowed; going past it fails. | Resource | Retained representation | Maximum | | --- | --- | ---: | @@ -99,243 +98,204 @@ only an extent beyond the end is refused. | immutable pairs | five-word `(marker, left, left kind, right, right kind)` nodes | 3,422,447,206 pairs | | buffered output | bytes published after result validation | 135,266,304 bytes | -The request maximum includes its four-byte length. Consequently a source with -no sealed input is at most 137,363,452 bytes. An exact-size request receives one -EOF probe and proceeds; one additional byte selects status 3 before framing. -A declared source extent outside the retained request is malformed framing and -selects status 1 instead. - -Function and environment insertion preflight the next count before deriving a -row address. The value stack preflights the complete 16-byte next entry. Pair -allocation preflights the complete 40-byte node; its arena has 16 unusable tail -bytes after the maximum whole-node count. Output preflights each buffered byte. -A scalar transformer may emit at most 135,266,303 bytes with `write` before its -final byte. An application result may publish all 135,266,304 buffered bytes. - -The 2,097,152 five-word function rows occupy `0x04000000..0x09000000` in -authored declaration order. A separate sorted index of 2,097,152 eight-byte row -pointers occupies `0x09000000..0x0a000000`, inside the same function partition. -Lookup compares name length and then exact name bytes by binary search; it -does not change declaration order, the retained `main` row, or first-declaration -application-marker ownership. Census checks duplicates before the selected -function-count preflight. After admitting and completing a row, insertion -shifts only initialized index entries and stores its pointer at an index no -greater than 2,097,151. Lookup reads only the initialized prefix. The last -physical row's last word starts at `0x08fffff8`; the last index slot starts at -`0x09fffff8`. Both writes end exactly at their respective region boundaries. -The region uses previously unused Alpha memory and remains below the hidden -stack's exclusive upper bound; pair storage, buffered output, and request -bytes sit entirely above the stack origin and do not change containment. - -Under the V4 request bound, exhaustion of this table was unreachable. At the -V5 frame a source can hold more than 2,097,152 declarations: census still -consumes at least eight distinct bytes per completed row (the declaration's -parenthesis, `def`, `Int`, and close), so a request larger than -`8 * 2,097,152 = 16,777,216` source bytes could exceed the physical table. -The count preflight is now the live controlling boundary and refuses the -next row before its store, selecting status 3. Exercising it requires a -request of more than 16 MiB of declarations; sorted-index insertion's -quadratic pointer movement then dominates the run, so this boundary is -discharged by the preflight argument rather than an executable adjacent -case. -This admits generated helpers beyond the former 65,536-function ceiling without -an AST, another compiler pass, or a separate generated-function refusal. -Sorted-index insertion still has quadratic worst-case pointer movement for -reverse-ordered names; the enlarged capacity does not remove that cost. - -Environment row 131,071 starts at `0x014fffe0`; its final word starts at -`0x014ffff8` and ends exactly at the value-stack boundary. Request insertion -occupies `0x10000000..0x18300000` — above the hidden stack's exclusive bound — -including its non-storing EOF probe, and cannot reach this region. The additional -rows use previously unused memory without increasing Alpha RAM or moving any -other live region. Static validation resets this environment for every function -and visits unreachable bodies; runtime non-tail calls retain caller rows, -whereas tail calls replace the current activation. +The request limit includes the four-byte length header, so a source with empty +stdin can be at most 137,363,452 bytes. An exact-size request performs one EOF +check and succeeds; one extra byte exits with status 3 before parsing. A +declared source length past the actual request size is a framing error and exits +with status 1. + +Function and environment insertions check the next count before computing a row +address. The value stack checks the full 16-byte entry before pushing. Pair +allocation checks the full 40-byte node; 16 tail bytes remain unused after the +maximum whole-node count. Output checks each buffered byte. A scalar transformer +can emit up to 135,266,303 bytes via `write` before its return byte; an +application can flush all 135,266,304 buffered bytes. + +The 2,097,152 five-word function rows live at `0x04000000..0x09000000` in +declaration order. A sorted index of 2,097,152 eight-byte row pointers lives at +`0x09000000..0x0a000000`. Lookup binary-searches by name length and then exact +bytes without altering declaration order, the `main` entry, or first-declaration +application detection. Census rejects duplicates before checking the function +count limit. After storing a row, insertion shifts only initialized index slots +and writes at index `<= 2,097,151`. Lookup reads only the initialized prefix. +The last row's final word starts at `0x08fffff8` and the last index slot starts +at `0x09fffff8`, ending right on their region boundaries. This partition uses +formerly unused memory below the Alpha stack, while pairs, output, and requests +remain above the stack origin. + +Under the V4 request cap, this function table could not fill up. Under the V5 +frame, a source can exceed 2,097,152 declarations: each declaration takes at +least 8 bytes (`(`, `def`, `Int`, `)`, etc.), so sources above +`8 * 2,097,152 = 16,777,216` bytes can hit the table cap. The count check stops +the next row before writing and exits with status 3. Testing that boundary +directly takes over 16 MiB of declarations and hits quadratic insertion shifts, +so the check is verified by inspection rather than an executable test. Raising +the ceiling past 65,536 functions allows generated helpers without adding an AST +or another compiler pass. Sorted-index insertion stays quadratic for +reverse-sorted names. + +Environment row 131,071 starts at `0x014fffe0` and its final word starts at +`0x014ffff8`, ending right at the value stack. Request reads stay in +`0x10000000..0x18300000` above the Alpha stack (including the EOF probe) and +cannot touch this region. Adding environment rows uses unused memory without +growing Alpha RAM or shifting other regions. Validation clears the environment +between functions and still checks unreachable bodies; at runtime, non-tail +calls keep caller bindings while tail calls reuse the current frame. The [Delta generated-environment control](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/delta/resource-boundary/README.md#generated-validation-environments) -requires this headroom: 65,534 authored parameters plus three checked-arithmetic -bindings exceeded the former 65,536-row provision even though Delta admitted -the source. This fixes that measured admission gap, not all generated-Gamma -admission or runtime exhaustion. Environment name lookup remains linear. - -The 256-context cap is stronger than the physical function-frame arena: `main` -owns one frame and each live non-tail context can own one more, so at most 257 -frames are reachable. Proper-tail calls release their temporary context and -reuse the current frame. The physical frame-end check remains defensive and -also selects status 3, but cannot be the first exhausted resource under this -profile. +motivated this increase: 65,534 parameters plus three checked-arithmetic +bindings exceeded the old 65,536-row limit even though Delta accepted the +source. This closes that gap without ruling out other generated-Gamma limits. +Environment lookup remains linear. + +The 256-context cap is tighter than the physical activation-frame region: `main` +takes one frame and each active non-tail context adds one, capping reachable +frames at 257. Proper tail calls release their temporary context and reuse the +current frame. The physical frame-end check remains as a status-3 safeguard but +cannot trigger first. ## Containment argument -Declaration census bounds every expression body to 255 nested lists before -validation or evaluation. Validation recurses only over that bounded syntax; -it does not enter called bodies. During evaluation, ordinary call depth is -bounded by the 256 live contexts, while tail `if`, tail `let`, and tail calls -loop or reuse the current activation. - -Grouped `let` validation and execution loop over binding rows. They retain one -saved outer scope and only the current initializer's name coordinates; completed -initializers do not accumulate temporary-value entries or native return addresses. -Each binding still occupies its ordinary lexical row. A group's initializer has -three authored enclosing lists (the `let`, binding list, and binding row), while -its final expression has one. Census measures these actual lists. The binding -helper adds one pending native call while evaluating an initializer; reserve two -additional return addresses per expression level in the bound below. - -Function-index search, comparison, and insertion use bounded loops, not -recursive calls. The evaluator's Alpha call graph has no other recursive cycle. -A conservative bound of 18 live Alpha return addresses per expression level -per active Gamma frame, plus 512 fixed helper slots, is -`18 * 256 * 257 + 512 = 1,184,768` return addresses, or 9,478,144 bytes. The -highest lower-memory allocation ends at the context rows' `0x02000000`, -leaving 96 MiB between the deepest live return address and the stack origin — -the stack's first store lands at `0x0ffffff8`, strictly below the request base -`0x10000000`, so upper regions cannot alias the hidden stack either. -The pair arena starts at `0x20400000` and grows upward, while -every live return address is strictly below it. Its complete-node preflight -keeps all pair stores below Alpha's `0x2000000000` memory end. Pair projection -requires the retained pair kind, an allocated aligned node in this same upper -arena, and its marker; integer values do not acquire pointer provenance by -matching a relocated address. - -Every other memory access is based on one of the preflighted extents above, a -source/input span within the retained request, a fixed table inside the tape, -or a fixed-size row selected by an already bounded count. Runtime `/` and `%` -precheck zero and `INT64_MIN / -1`, translating both Alpha arithmetic traps to -status 2. Thus no admitted evaluator execution reaches an Alpha bounds trap or -exposes an Alpha arithmetic trap as a Gamma outcome. Gamma has no time or work -bound; a nonterminating program diverges. - -The selected implementation is -[`gamma_evaluator.beta`](gamma_evaluator.beta), a 1,662-line, -48,303-byte addressed Beta program assembling to an 8,447-byte Alpha tape. Its -current SHA-256 identities are: +Census limits every expression body to 255 nested lists before validation or +execution. Validation recurses only over that bounded syntax without entering +callees. Execution limits non-tail call depth to 256 live contexts, while tail +`if`, tail `let`, and tail calls loop or reuse the current frame. + +Grouped `let` validation and evaluation loop over bindings, saving only the +outer scope and current initializer name span; finished initializers do not pile +up value-stack entries or return addresses. Each binding still uses one +environment row. A group initializer sits inside three lists (`let`, binding +list, binding row) while the body expression sits inside one; census counts +these actual lists. Evaluating an initializer adds one native call, so we +reserve two extra return addresses per expression level below. + +Function-index search, comparison, and insertion are loops, not recursion, and +the evaluator has no other recursive cycles. Allowing a conservative 18 Alpha +return addresses per expression level per active Gamma frame plus 512 helper +slots gives `18 * 256 * 257 + 512 = 1,184,768` return addresses (9,478,144 +bytes). Lower memory ends at `0x02000000` (the context rows), leaving 96 MiB +below the stack origin. The first stack store lands at `0x0ffffff8`, strictly +below the request buffer at `0x10000000`, so upper regions never overlap the +stack. The pair arena starts at `0x20400000` and grows upward above every stack +slot, with complete-node checks keeping all writes below Alpha's `0x2000000000` +end. Pair projection checks the pair kind tag, aligned address inside the pair +arena, and marker word, so arbitrary integers cannot forge pair pointers. + +Every other memory access uses a checked region bound, a source/input span +inside the request, a fixed table in the tape, or a row indexed by a bounded +count. Runtime `/` and `%` pre-check zero divisors and `INT64_MIN / -1`, +converting both Alpha traps to status 2. No valid run can hit an Alpha bounds +trap or leak an Alpha arithmetic trap. Gamma has no step limit; nonterminating +programs diverge. + +The evaluator implementation is [`gamma_evaluator.beta`](gamma_evaluator.beta) +(1,662 lines, 48,303 bytes), assembling to an 8,447-byte Alpha tape: ```text Beta source a588fd718cd1f86a97f55e2f83368b80c5063f233296b091ec7c1561c768a5a6 Alpha tape b2d35f99f8886985306dba1c5bc5309fb2c389b1c80b1fe79b79ed69f7042a0a ``` -The tokenizer and expression parser share one character reader. It packs one -to eight decoded bytes into one little-endian integer. A printable ASCII -byte, `\n` or `\s` contributes one byte. Function, -parameter and let names must be symbols. These checks also run inside unused -functions before the program executes. - -The list-head classifier reads at most eight bytes from the token and compares -the packed word with the 15 intrinsic spellings in class order. Gamma rejects -NUL throughout the source before tokenization, so zero padding preserves exact -spelling and length. Longer heads go directly to function lookup. - -Proper-tail execution, static validation of unreachable bodies, exact resource -outcomes, bounded output, profile-owned arithmetic traps, and provenance-tagged -immutable-pair allocation are implemented. Buffered scalar transformation and -generic application publication share this one selected evaluator. The gate -pins exact source and tape identities, former function ceilings and the -controlling exact/adjacent request extent, plus exact/adjacent environment, -syntax-depth, and call-context boundaries; the fixed identity makes the remaining -arithmetic extent arguments above reviewable against one immutable subject -rather than a host model. - -The separate [heap-boundary gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) -executes ordinary Gamma allocation loops past the entire retired V4 arena -under scalar and application publication; the 3.4-billion-node exact boundary -is no longer executable in gate time. It also crosses the -previous 20,132,659-pair ceiling. This profile increase is driven by the actual -complete-D parser customer: the prior evaluator exhausted its immutable heap -with raw application status 252 before publishing the twelve-invocation result. -It does not change Gamma meaning, allocate an unbounded heap, or convert an -outer evaluator failure into an Epsilon observation. +The tokenizer and parser share one character reader that packs 1 to 8 decoded +bytes into a little-endian integer. Printable ASCII, `\n`, and `\s` each add one +byte. Function, parameter, and `let` names must be symbols; these checks run on +unused functions before execution too. + +The list-head classifier reads up to 8 bytes from the token and compares that +packed word against the 15 built-in names in order. Because Gamma rejects NUL +bytes before tokenization, zero padding preserves exact spelling and length. +Longer names go straight to function lookup. + +This evaluator implements proper tail calls, static checking of unreachable +bodies, exact resource exit codes, buffered output, checked arithmetic traps, +and tagged immutable pairs for both scalar transformers and applications. Tests +pin exact source and tape hashes, old function ceilings, and exact/off-by-one +request, environment, syntax-depth, and call-context limits; pinning one fixed +binary lets reviewers audit the remaining arithmetic bounds directly. + +The [heap-boundary gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/heap-boundary/README.md) +runs Gamma allocation loops past the entire retired V4 arena (and past the +earlier 20,132,659-pair cap) under both scalar and application modes; reaching +the full 3.4-billion-node limit takes too long for normal tests. The complete-D +parser drove this capacity increase after exhausting the old pair heap with +status 252 before finishing its twelve-invocation run. Enlarging the arena does +not change Gamma semantics, make memory unbounded, or turn evaluator failures +into Epsilon results. ## Nested-call boundary and the Delta checker -`BOOTSTRAP-AUTHORING-READABILITY` asked whether the Gamma-written Delta -checker's hand-built continuation frames should be replaced by direct -recursion. The measured boundary of this profile decides it: a non-tail -`descend` recursion completes at 256 live contexts and is refused at 257 -(status 3, or the generic application status 250), while a proper-tail -control completes 4,096 levels in constant space. Solving the containment -inequality above for a raised cap gives `18 * 256 * (N+1) + 512 <= -2,097,152`, so at most 454 contexts fit the hidden-stack margin — below the -Delta customer's admitted expression depth of 1,024. No context-cap -increase under this memory map serves the customer. (Under AlphaBootstrapV5 -the same inequality over the new 96 MiB stack margin admits about 2,728 -contexts — the arithmetic changed, the priced decision below stands.) - -The two enabling routes were priced without restructuring the customer. -Under the former map, region rebalance (moving buffered output out of the -stack margin) would have admitted about 2,274 contexts, but required a -rebuilt evaluator tape, re-pinned -identity records in this profile, `tools/bootstrap/gamma/evaluator_env.sh`, +`BOOTSTRAP-AUTHORING-READABILITY` asked whether we could replace the +Gamma-written Delta checker's explicit continuation frames with direct +recursion. This profile's limits answer no: non-tail `descend` succeeds at 256 +live contexts and fails at 257 (status 3, or status 250 for applications), while +tail calls run 4,096 levels in constant space. Under the old memory map, +`18 * 256 * (N+1) + 512 <= 2,097,152` capped the stack margin at 454 contexts—well +below Delta's 1,024-level expression depth. (Under AlphaBootstrapV5's 96 MiB +stack margin, the inequality allows about 2,728 contexts, but the cost decision +below still stands.) + +We priced two ways to enable direct recursion without changing the Delta +checker. Moving buffered output out of the stack margin under the old map would +have allowed ~2,274 contexts, but required rebuilding the evaluator tape, +updating hashes across this doc, `tools/bootstrap/gamma/evaluator_env.sh`, `tests/bootstrap/proofs/heap-boundary/evaluator.tsv`, and -`bootstrap/delta/compiler/delta_compiler.composed`, re-derived exact/adjacent -context and environment controls, a new subject for the Beta-encoding -proof, and a permanent coupling of Delta's `parse_depth` to this profile's -context cap — an over-depth Delta program would then surface as raw status -250 rather than a compiler-owned refusal. Evaluator-owned continuation -records remove the bound entirely at the largest audit burden of the -three and are dominated for this customer. - -The stack comparison is therefore decided on priced costs: the -source-level explicit continuation frames in the Delta checker are -retained. They are already built, audited, and passing the complete -Epsilon closure, and every enabling route must be paid in full before a -direct-recursion rewrite could even be measured. A source-only -direct-recursion rewrite of `checking/types/branches.gamma` was already -attempted and fails at depth 256 under this profile; do not repeat it. +`bootstrap/delta/compiler/delta_compiler.composed`, re-verifying context and +environment bounds, re-proving the Beta encoding, and coupling Delta's +`parse_depth` to the evaluator's context cap (turning over-depth Delta programs +into raw status 250 instead of a compiler diagnostic). Heap-allocated +continuation frames inside the evaluator remove the cap entirely but add even +more audit cost. + +We therefore keep explicit continuation frames in the Delta checker. They are +already built, audited, and passing on the full Epsilon closure, whereas any +enabling route costs full rework upfront before direct recursion can even be +tested. A direct-recursion rewrite of `checking/types/branches.gamma` was +already tried and failed at depth 256; do not retry it. ## Expression scanning -Retain structural scanning for the +Keep structural scanning for the [complete-D customer](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/omega-parser/README.md#gamma-scanning-review). -`skip_expression` has four call sites: declaration census, false tail `if`, -and the two ordinary `if` paths. Census establishes the syntax-depth bound; -ordinary evaluation must leave the cursor after the complete expression. -A true tail `if` already avoids scanning its unused alternative because -activation return restores the caller's cursor. These scans cannot simply be -deleted without replacing those obligations. - -An expression-end index could eliminate repeated skipping, but function rows -alone do not describe nested expressions. A dense four-byte offset per possible -request byte would require 64 MiB; a sparse representation would need its own -lookup and capacity argument. Either adds initialized-entry, matching-close, -source-span, and partition-containment obligations, plus changed source/tape -pins and reconstruction and failure controls. It need not change the Alpha -seed or add a proof rule, but encoding equality would still not prove Gamma -semantics. No measured customer failure currently warrants those additions. - -The punctuation helpers now compare the token's first byte directly. The -existing tokenizer isolates parentheses as singleton tokens and gives character -literals an apostrophe prefix, so this preserves the full token test without a -second lexer or index. Both 30-byte helper slots and every control address stay -fixed; only 36 tape bytes change. That punctuation change left the ordinary name -and keyword comparisons in place. - -The punctuation calls have a nonempty source token: `need_token` rejects EOF, -and the census checks `next_token`'s success before calling either helper. -The classification entry is the sole unchecked `next_token` call: census has -already required a nullary `main` and validation has succeeded before it resets -the cursor to the start of that nonempty source. Its first token is therefore -the already-censused opening parenthesis. EOF leaves old token registers in -place, but no punctuation call uses them after EOF. Prefix controls check that -sealed parentheses or the exact missing suffix cannot complete truncated -ordinary/application sources, including character literals and grouped lets. - -On Linux x86-64, the complete Delta-to-Epsilon diagnostic receipt reconstructed -byte-identically: the prior evaluator used 349.620 CPU / 354.968 wall seconds; -the direct punctuation version used 335.574 CPU / 339.061 wall seconds. These -are single observations (about 4% less CPU), not a portable speed guarantee. -A 10,000-call microbenchmark improved by about 29%, which is not representative -of the complete receipt. The full Gamma fixture matrix, including grouped lets, -name lookup, environment and depth boundaries, rejection, and augmentation, -also passed. The 33,330-byte source-authored Gamma compiler -(SHA-256 `7b439ef26f2cb8a27bb9c0a2b4d5bfca6e7efeed0a5bdf9d798c04b65370b946`) -constructed the same 457,252-byte compiler tape -(`71f6650f8201294e6654217f38fcd431fd8daaa233e0330c5da29e9819ad7e71`): -47.263 seconds versus 62.362 seconds on the prior evaluator, again single -observations. No expression-end index or new storage partition was introduced. - -Historical full-subject proof measurements remain bound to the exact source -and tape at `d19361fe4deae73e1b488a940a872fec1ed885cb`; their old hashes and -certificate figures were not transferred to this evaluator. That optional -research is not a prerequisite for source construction. +`skip_expression` has four callers: census, false tail `if`, and both branches +of non-tail `if`. Census enforces the nesting-depth limit, and non-tail +evaluation must advance the cursor past the whole expression. True tail `if` +already skips scanning its dead branch because returning restores the caller's +cursor. Deleting these scans would drop those guarantees. + +An expression-end index would avoid rescanning, but function rows alone do not +cover nested expressions. A dense 4-byte table per request byte would cost 64 +MiB; a sparse table needs its own lookup and bounds proof. Either adds +initialization, brace-matching, span, and partition checks plus new source/tape +hashes and tests—and encoding proofs still would not prove Gamma semantics. No +current bottleneck justifies that complexity. + +The punctuation helpers now check only the token's first byte. Because the +tokenizer already emits single-character tokens for parentheses and prefixes +character literals with `'`, this keeps identical behavior with no extra lexer +or index. Both 30-byte helper slots and all branch targets stay fixed; only 36 +tape bytes changed, and name/keyword comparisons stayed unchanged. + +Every punctuation call operates on a nonempty token: `need_token` rejects EOF, +and census checks `next_token` before calling either helper. The classifier's +single unchecked `next_token` runs only after census has required a nullary +`main` and validation has passed, so resetting to byte 0 guarantees the opening +`(` is present. EOF leaves old token registers intact, but no punctuation helper +reads them after EOF. Truncation tests confirm that sealed parentheses or +missing suffixes cannot complete cut-off scalar or application programs, +including character literals and grouped lets. + +On Linux x86-64, the Delta-to-Epsilon diagnostic receipt rebuilt +byte-identically: 335.574 CPU / 339.061 wall seconds with direct punctuation +versus 349.620 CPU / 354.968 wall seconds before (~4% less CPU, single run, not +a portable guarantee). A 10,000-call microbenchmark sped up by ~29% (not +representative of full builds). All Gamma tests passed, and the 33,330-byte +Gamma compiler (`7b439ef26f2cb8a27bb9c0a2b4d5bfca6e7efeed0a5bdf9d798c04b65370b946`) +built the identical 457,252-byte tape +(`71f6650f8201294e6654217f38fcd431fd8daaa233e0330c5da29e9819ad7e71`) in 47.263 s +versus 62.362 s previously (single runs). No expression-end index or memory +partition was added. + +Older proof measurements apply only to the exact source and tape at +`d19361fe4deae73e1b488a940a872fec1ed885cb`; their hashes and certificate counts +do not carry over to this evaluator, and that optional research does not block +source builds. diff --git a/tests/bootstrap/interpreted/alpha/README.md b/tests/bootstrap/interpreted/alpha/README.md index cc0dabec1639..9e647df99d9d 100644 --- a/tests/bootstrap/interpreted/alpha/README.md +++ b/tests/bootstrap/interpreted/alpha/README.md @@ -1,83 +1,32 @@ # Alpha tests -These tests exercise the Alpha VM semantics and its independent reference. The -audited VM implementations and normative semantics remain in `bootstrap/alpha/`. +These tests check the Alpha VM specification and its independent reference interpreter. The audited VM binaries and spec live in `bootstrap/alpha/`. | Retained child/files | Role | Deletion condition | | --- | --- | --- | -| `conformance.sh` | Pins every Alpha opcode and the selected seed profile. | Delete only when a stronger executable conformance gate subsumes every case. | -| `container.sh`, `container.py` | Validates both audited seed containers as native executables on every host: bound identity for the non-host seed too, PE32+/Mach-O structure, hole offset equal to the tape section's raw extent, and the stamped-artifact contract. | Delete only when an identity or provenance gate covers the same native-container contract. | -| `bounds.py` | Hand-encoded bounds cases shared by native and reference checks. | Delete when stronger conformance controls subsume these exact/adjacent observations. | -| `native_exit.py` | Runs a stamped seed through a native subprocess and reduces its raw exit DWORD to the POSIX surface, restoring byte-level exit expectations on MSYS hosts whose shell collapses every other sign-bit-set code to 127. | Delete when no seed-executing host normalizes process exit codes this way. | -| `io-registers.hex` | Shared raw-tape regression for host scratch/register isolation. | Delete when stronger I/O conformance checks subsume its full-word and operand controls. | -| `parity.sh` | On Linux x86-64, runs the conformance opcode battery plus the diamond edge corpus through both the committed `alpha_x64_linux` container and the independent reference, failing on any exit-code or stdout disagreement. | Delete when the reference interpreter is deleted, or when host-seed agreement coverage reaches the Linux container another way. | -| `reference/` | Independent VM differential checks. | Delete when checked native correspondence subsumes the diagnostic. | -| `tape-assembly/` | Off-chain assembler reconstruction, differential, grammar, and example tests. | Delete with the tool or when stronger checked coverage subsumes every relation. | +| `conformance.sh` | Tests every Alpha opcode and the selected seed profile. | Delete when a stronger executable suite covers every case. | +| `container.sh`, `container.py` | Validates both audited seed containers on every host: checks expected hash/size (including the non-host seed), PE32+/Mach-O layout, tape hole offset matching section extent, and stamped output rules. | Delete when an identity or build check covers these container rules. | +| `bounds.py` | Hand-encoded bounds tests shared by native and reference checks. | Delete when stronger tests cover these exact and off-by-one cases. | +| `native_exit.py` | Runs a stamped seed in a native subprocess and maps its raw exit DWORD to a POSIX exit code, restoring byte-level checks on MSYS hosts that collapse other sign-bit-set codes to 127. | Delete when no host running the seed alters exit codes this way. | +| `io-registers.hex` | Shared raw-tape regression test for host scratch and register isolation. | Delete when stronger I/O tests cover its full-word and operand checks. | +| `parity.sh` | On Linux x86-64, runs the opcode suite and diamond edge cases on both `alpha_x64_linux` and the reference, failing on any exit-code or stdout mismatch. | Delete when the reference is removed or another check covers Linux parity. | +| `reference/` | Independent VM differential tests. | Delete when verified native equivalence replaces this diagnostic. | +| `tape-assembly/` | Off-chain assembler rebuild, differential, grammar, and example tests. | Delete with the tool or when stronger tests cover every rule. | ## Bounds conformance -`sh tests/bootstrap/interpreted/alpha/conformance.sh` runs the native bounds cases through Python 3; -`sh tests/bootstrap/interpreted/alpha/reference/diamond-py.sh` runs the same short cases against the -independent reference. Both commands work from the repository root on macOS -arm64, Windows x64 with Git Bash, and Linux x86-64 with Python 3 and the -existing bootstrap tools. -The native runner stamps copies directly to test hostile embedded lengths that -the normal stamper correctly refuses. It compares exact stdout (including empty -bytes), empty stderr, and native illegal-instruction termination rather than -accepting arbitrary process failures. A 300-second per-case watchdog fails, -never counts as a semantic Trap. +`sh tests/bootstrap/interpreted/alpha/conformance.sh` runs the native bounds tests via Python 3; `sh tests/bootstrap/interpreted/alpha/reference/diamond-py.sh` runs the same short cases on the reference. Both work from the repository root on macOS arm64, Windows x64 (Git Bash), and Linux x86-64 using Python 3 and the bootstrap tools. The native runner stamps copies directly to test invalid embedded lengths that the normal stamper rejects. It checks exact stdout (including empty output), empty stderr, and illegal-instruction termination instead of accepting arbitrary crashes. A 300-second timeout fails the test and never counts as a Trap. -Coverage includes all 21 instruction widths at the semantic memory end, adjacent -missing operands, invalid/wrapping targets and data addresses, unaligned and -full-word round trips, untaken invalid targets, ordinary mutable code, overlapping -call operands/return storage, and loader extents. An exact-end non-control -instruction can still trap on the following fetch; its external observation -alone cannot prove the preceding effect occurred. Review the native width tables -and handlers alongside these controls. +Tests cover all 21 instruction widths at the end of memory, adjacent missing operands, invalid or wrapping jump targets and data addresses, unaligned and full-word round trips, untaken invalid jumps, mutable code, overlapping call operands and return storage, and loader limits. Because a non-control instruction at the exact end of memory can still trap on the next fetch, external output alone cannot prove its effect ran; review the native width tables and handlers alongside these tests. -Native-only full-profile loops check the last legal push at `sp = 8`, the next -push at zero, the last legal return word, the next return at `MEMSIZE`, and a -valid call after returning to `sp = MEMSIZE`. They use 33,554,432 calls or -201,326,592 returns, not a reduced profile or debugger-modified stack pointer. -Run these alone with `python3 tests/bootstrap/interpreted/alpha/bounds.py --stack-only`. The reference -excludes these large loops explicitly; it still checks return without a preceding -call, access above the stack origin, and overlapping call storage. +Native-only full-profile loops test the last legal push at `sp = 8`, the next push at zero, the last legal return word, the next return at `MEMSIZE`, and a valid call after returning to `sp = MEMSIZE`. They run 33,554,432 calls or 201,326,592 returns directly, without a reduced profile or modified stack pointer. Run them alone with `python3 tests/bootstrap/interpreted/alpha/bounds.py --stack-only`. The reference skips these large loops, though it still checks returning without a prior call, accessing above the stack origin, and overlapping call storage. -macOS arm64 and Linux x86-64 execution are validated for the identities in the -[seed inventory](../../../../bootstrap/alpha/README.md#retention-inventory). -These tests do not discharge native correspondence proofs. +macOS arm64 and Linux x86-64 runs are verified for the binaries in the [seed inventory](../../../../bootstrap/alpha/README.md#retention-inventory). These tests do not prove native equivalence to the spec. -Windows x64 execution is measured on Git Bash with the selected seed: -`bounds.py` passes 78/78 native cases, the Beta reconstruction tape reproduces -its compiler byte-identically, `io-registers.hex` returns 0 with stdout -`ABCDEF` for input `AB`, and all 34 `conformance.sh` cases pass. The former -`div_zero_trap`/`div_ovf_trap` divergence — the hardware divide faults -`0xC0000094`/`0xC0000095` surfacing instead of the audited illegal-instruction -routine — is closed by the divisor pre-check the PE seed now shares with the -Linux and arm64 seeds, so every trap class reports `0xC000001D` (132 through -the shell). +Windows x64 is measured under Git Bash with the selected seed: `bounds.py` passes 78/78 native cases, the Beta rebuild reproduces its compiler byte for byte, `io-registers.hex` exits 0 with stdout `ABCDEF` for input `AB`, and all 34 `conformance.sh` cases pass. Previously, `div_zero_trap` and `div_ovf_trap` diverged because hardware divide faults (`0xC0000094`/`0xC0000095`) surfaced instead of the illegal-instruction handler. The PE seed now shares the divisor pre-check used by the Linux and arm64 seeds, so every trap reports `0xC000001D` (132 in the shell). -Git Bash still normalizes the raw exit DWORD: every sign-bit-set code other -than `0xC000001D` observes as 127, so a halt whose register sign-extends -(`div_neg` = 253, `mod_neg`/`read_eof` = 255, the diamond's `jlt_signed`) -hides its authored byte behind `$?`. The cases' VM result was always correct — -PowerShell reads `$LASTEXITCODE = -3` for `-7/2` — the loss was the MSYS -shell's observation. `conformance.sh` and `diamond-py.sh` therefore run the -stamped container through `native_exit.py` on these hosts -(`ALPHA_SEED_EXIT_COLLAPSED` in `seed_env.sh`): a Windows-native subprocess -sees the real DWORD, which the helper reduces to the POSIX surface — 132 for -the audited `0xC000001D` trap, the raw DWORD for any foreign exception (so a -leaked `0xC0000094` can never alias a legal expectation), and the authored -low byte otherwise. +Git Bash still alters raw exit DWORDs: any sign-bit-set code besides `0xC000001D` appears as 127, so a halt whose register sign-extends (`div_neg` = 253, `mod_neg`/`read_eof` = 255, or the diamond's `jlt_signed`) loses its real byte in `$?`. The VM result was always right—PowerShell reads `$LASTEXITCODE = -3` for `-7/2`—only MSYS hid it. `conformance.sh` and `diamond-py.sh` therefore run the stamped binary via `native_exit.py` on these hosts (`ALPHA_SEED_EXIT_COLLAPSED` in `seed_env.sh`): a Windows-native subprocess reads the real DWORD and returns 132 for `0xC000001D`, the raw DWORD for any unexpected exception (so a leaked `0xC0000094` never matches a valid exit), and the low byte otherwise. ## Register isolation -The same two shell gates include `io-registers.hex`: a 438-byte raw tape with -comments, not assembler output. Given stdin `AB`, it must exit zero with exact -stdout `ABCDEF`. It checks registers 16–19 start at zero, retain distinct 64-bit -sentinels across read/write/EOF through another register, preserve their own -values when used as write operands, and receive EOF when used as read operands. -This catches the Windows seed's former overlap of those registers with its host -handles, byte buffer, and count slot. The native conformance gate pins the result; -the reference gate independently compares it. The fixture passes on macOS arm64, -Windows x64, and the Python reference. +Both shell scripts run `io-registers.hex`, a 438-byte hand-written raw tape with comments. Given stdin `AB`, it must exit 0 with stdout `ABCDEF`. It checks that registers 16–19 start at zero, keep distinct 64-bit values across read, write, and EOF on another register, keep their values when used as write operands, and receive EOF when used as read operands. This catches an earlier bug where the Windows seed overlapped those registers with its host handles, byte buffer, and count slot. Both native and reference tests check the result, passing on macOS arm64, Windows x64, and the Python reference. diff --git a/tests/bootstrap/interpreted/omega-executable/README.md b/tests/bootstrap/interpreted/omega-executable/README.md index d1e137fabae7..102f3d1710dd 100644 --- a/tests/bootstrap/interpreted/omega-executable/README.md +++ b/tests/bootstrap/interpreted/omega-executable/README.md @@ -1,25 +1,24 @@ # Omega source to an Alpha executable -This gate connects the manifested Epsilon-written bootstrap compiler to -its existing parser and Alpha tape encoder through the real request route: -the gate frames the canonical OCREQ V1 request (one application package -snapshotting [program.omg](../../conformance/omega/program.omg) as a single `.omg` regular file, -empty edges, `alpha_bootstrap_tape` product on the `alpha_bootstrap` profile, -bound SHA-256 subject commitment), and -[main_ocreq.epsilon](../../conformance/omega/main_ocreq.epsilon) runs the bootstrap compiler's -`OmegaRequestStructure::check` shape passes, extracts the root package's single -`.omg` member, compiles it, and publishes the unwrapped artifact on `Complete` -or exactly one OCOUT V1 frame on failure. The admitted slice is -`alpha_bootstrap_tape` plus a single-source application root; shape-valid -requests outside it refuse `malformed_request` at the first out-of-slice -coordinate. The target's ProgramEntry contract names the entry machine `main`, -so entry selection is bound by the route, not by an adapter-supplied spelling. -The emitted tape halts Alpha with the selected machine's return value. The -expected result is [42](../../conformance/omega/expected.txt). - -The test-owned [execution driver](execution_driver.delta) frames the Epsilon -source and sealed stdin for the interpreted Omega gate. `--diagnostic` keeps the retired raw-source adapter -([main.epsilon](../../conformance/omega/main.epsilon)) reachable for refusal coverage: +This gate connects the Epsilon-written bootstrap compiler to its parser and +Alpha tape encoder through the request pipeline. The gate builds a canonical +OCREQ V1 request: one application package containing +[program.omg](../../conformance/omega/program.omg) as a single `.omg` file, +empty edges, the `alpha_bootstrap_tape` product on the `alpha_bootstrap` profile, +and a SHA-256 input digest. [main_ocreq.epsilon](../../conformance/omega/main_ocreq.epsilon) +runs the compiler's `OmegaRequestStructure::check` validation, extracts the root +package's single `.omg` file, compiles it, and outputs the unwrapped tape on +`Complete` or a single OCOUT V1 frame on failure. Only `alpha_bootstrap_tape` +with a single-file application root is supported; otherwise valid requests fail +with `malformed_request` at the first unsupported offset. The target's +ProgramEntry rule fixes the entry machine name to `main`, so the route—not an +adapter—selects the entry. The emitted tape halts Alpha with `main`'s return +value, expected to be [42](../../conformance/omega/expected.txt). + +The test [execution driver](execution_driver.delta) frames the Epsilon source +and sealed stdin for the interpreted Omega gate. Passing `--diagnostic` keeps +the retired raw-source adapter ([main.epsilon](../../conformance/omega/main.epsilon)) +available for refusal tests: `python3 gate.py "$OUTPUT_DIR" "$OMEGA_PATH_EPSILON_EXECUTION_DRIVER" --diagnostic`. From the repository root on macOS arm64, Linux x86-64, or Windows x64 with Git Bash: @@ -28,92 +27,88 @@ From the repository root on macOS arm64, Linux x86-64, or Windows x64 with Git B sh tests/bootstrap/interpreted/omega-executable/run.sh ``` -The gate requires Python 3, the selected checked-in Alpha seed and the existing -shell tools; macOS also requires `codesign`. It stamps the separately admitted -[Beta tape](../../../../bootstrap/beta/AUDIT.md) into the selected Alpha container, -rebuilds Beta from source, and uses the rebuilt compiler to -construct the Gamma evaluator from source, and compares both tapes exactly -with their bound artifacts. It executes those constructed bytes to reconstruct -the Epsilon execution receipt through the Gamma-written Delta compiler, checks -the Epsilon-written bootstrap compiler plus its request-route entry, -seals the source into the canonical request, and stamps and executes only the -actual successful output. -No Rust compiler, host parser, host typechecker, or host code generator supplies -the program's meaning. The packing and stamping helpers remain trusted byte -transport. Python frames, invokes, compares, and stores bytes. The separate -[Alpha-to-Beta gate](../alpha-beta-edge.sh) also checks native-container source -provenance; this ordinary executable gate does not rebuild the native seed. - -Outputs live in ignored `build/omega-executable/`, including `program.tape` and -`program.exe`. The executable is the host's Alpha VM container carrying the -emitted tape, not direct native lowering of the Omega body. The evaluator and -packed implementation files remain there for inspection. A failed compilation -does not replace the last successful tape; prior files are not evidence of a -new successful run. The command's successful final result is the acceptance gate. - -The evaluator reconstruction has a 1,800-second watchdog, compiler execution has -14,400 seconds by default, and the emitted program has 30 seconds. Expiration -kills the invoked process tree and is not an Omega result. Set -`OMEGA_EXECUTABLE_RECEIPT_SECONDS` to a positive number for another -reconstruction allowance and `OMEGA_EXECUTABLE_OBSERVATION_SECONDS` for another -compiler observation allowance; both receipts stay pinned to the selected gate -identity regardless of the allowance. `OMEGA_EXECUTABLE_BUILD_DIR` selects a -different output directory. These are host controls, not language semantics. +The gate needs Python 3, the checked-in Alpha seed, and standard shell tools +(plus `codesign` on macOS). It stamps the trusted +[Beta tape](../../../../bootstrap/beta/AUDIT.md) into the Alpha container, +rebuilds Beta from source, uses the rebuilt Beta to build the Gamma evaluator +from source, and checks both tapes byte for byte against their pinned hashes. +It then runs those binaries to rebuild the Epsilon execution output through +the Gamma-written Delta compiler, verifies the Epsilon-written bootstrap +compiler and its request entry, packs the Omega source into the request, and +stamps and runs the output only if compilation succeeds. No Rust compiler or +host parser, typechecker, or code generator runs here. Shell and Python helpers +only pack, stamp, run, compare, and save bytes. The separate +[Alpha-to-Beta gate](../alpha-beta-edge.sh) checks how the native seed binary +was built; this gate does not rebuild the seed. + +Outputs go to ignored `build/omega-executable/`, including `program.tape` and +`program.exe` (the host Alpha VM carrying the emitted tape, not native machine +code lowered from Omega). Intermediate evaluator and source files stay there for +inspection. A failed build never overwrites the previous tape, so stale files +never count as a passing run; only the command's final exit status decides. + +Default timeouts are 1,800 seconds for evaluator rebuilding, 14,400 seconds for +compiling Omega, and 30 seconds for running the emitted program. A timeout kills +the child process tree and fails the test. Override them with positive values in +`OMEGA_EXECUTABLE_RECEIPT_SECONDS` and `OMEGA_EXECUTABLE_OBSERVATION_SECONDS` +(the pinned hashes still apply), and set `OMEGA_EXECUTABLE_BUILD_DIR` to change +the output directory. ## Current compiler slice [The bootstrap compiler's coverage and storage contract](../../../../bootstrap/omega/compiler/README.md) -is authoritative for this gate. It admits a nullary `u8` entry and checked -`u8`, `u32`, bounded-literal `u64`, `bool`, and `u32 in Trapping` values through parameters, locals, -free calls and same-owner parameterized transfers. Runtime comparisons and -short-circuit Boolean control preserve those types. All bodies and arms are -checked before emission; reentrant ordinary-call graphs and unsupported -facilities refuse without publishing a partial tape. Copy records, zero-established -affine locals, projected field writes, Unit completion and scoped record-reference -parameters now support the actual SourceUnit clear helper. Arithmetic includes proved -unsigned operations, checked Trapping `u32` add/subtract/multiply and `u64` -add/subtract, and Wrapping `u64` add/subtract/multiply. The compiler README specifies the precise storage and loan boundaries. - -The source-built compiled peer also exposes `--omega-control`. It takes exact -identifier and numeric digit declarations from the real lexer source and appends -[lexer_controls.omg](../../conformance/omega/lexer_controls.omg), which exercises ASCII interval edges -and high `u32` inputs, every byte against four numeric bases, and digit values -at both ends of the decimal, uppercase and lowercase ranges. [controls_control.epsilon](../../conformance/omega/controls_control.epsilon) -compiles that input plus generic parallel-transfer, comparison, short-circuit, -and refusal/reset controls. The harness executes every emitted artifact through -the Alpha seed. The compiler has no special case for this customer. - -The peer's `--omega-storage` customer extracts exact SourceId, SourceUnit, -ModulePath and clear/append/read declarations from the actual source package, -then appends [storage_controls.omg](../../conformance/omega/storage_controls.omg). -[controls_storage.epsilon](../../conformance/omega/controls_storage.epsilon) checks that program plus -11 generic storage programs, 36 explicit refusals and a reset program; the -harness executes all 13 published artifacts. The real helpers retain their -zero/full behavior and byte values while explicitly stating the guarded private -bounds. Companion programs check captured index evaluation, pure guarded entry -requirements, incoming-reference forwarding, and disjoint mutation. Negative -controls include an overlapping mutating call in an earlier argument of the -same expression, stale entry facts, mutating guards and local-backed tail loans. -These internal single-source customers do not claim full package admission. - -The route selects `main` — the machine name `alpha_bootstrap::ProgramEntry` -binds. Another source can be exercised without changing compiler code: +is the source of truth for this gate. It accepts a nullary `u8` entry and checked +`u8`, `u32`, bounded-literal `u64`, `bool`, and `u32 in Trapping` values in +parameters, locals, free calls, and same-owner parameterized transfers, along +with runtime comparisons and short-circuit Boolean logic. The compiler checks +every body and arm before emitting code; recursive ordinary calls and +unsupported constructs fail without writing a partial tape. Copy records, +zero-initialized affine locals, field writes, Unit completion, and scoped +record-reference parameters support the real SourceUnit clear helper. Arithmetic +covers proved unsigned ops, checked Trapping `u32` add/sub/mul and `u64` +add/sub, and Wrapping `u64` add/sub/mul. See the compiler README for exact +storage and borrow rules. + +The compiled peer also provides `--omega-control`. It pulls the exact identifier +and digit declarations from the real lexer source and appends +[lexer_controls.omg](../../conformance/omega/lexer_controls.omg) to test ASCII +boundary values, high `u32` inputs, all bytes across four numeric bases, and +digit values at both ends of decimal, uppercase, and lowercase ranges. +[controls_control.epsilon](../../conformance/omega/controls_control.epsilon) +compiles that program plus parallel-transfer, comparison, short-circuit, and +refusal/reset tests, and runs every emitted tape on the Alpha seed. The compiler +has no special cases for this test. + +The peer's `--omega-storage` test extracts the exact SourceId, SourceUnit, +ModulePath, and clear/append/read declarations from the source package and +appends [storage_controls.omg](../../conformance/omega/storage_controls.omg). +[controls_storage.epsilon](../../conformance/omega/controls_storage.epsilon) +tests that program along with 11 generic storage programs, 36 rejections, and a +reset test, then runs all 13 emitted tapes. The real helpers keep their zero and +full behavior and byte values while stating their guarded bounds explicitly. +Companion tests check captured index evaluation, pure guarded entry checks, +reference forwarding, and disjoint mutation. Negative tests cover overlapping +mutating calls in an earlier argument, stale entry facts, mutating guards, and +local-backed tail borrows. These single-file tests do not cover full package +support. + +The route selects `main` (the machine bound by `alpha_bootstrap::ProgramEntry`). +You can test another Omega file without changing the compiler: ```sh sh tests/bootstrap/interpreted/omega-executable/run.sh --source path/to/program.omg --expect 7 ``` `--expect-compile 1` expects a compiler rejection; `--expect-compile 2` expects -an unsupported form. Both require an exact failure outcome: the request route -publishes one closed OCOUT frame, the diagnostic lane publishes no tape. -The harness owns those diagnostic statuses; they are not new OCOUT wire numbers. -Resource and internal failures remain distinct from successful compilation. +an unsupported construct. Both require exact failure output: one closed OCOUT +frame on the request route, or no tape on the diagnostic route. Those exit codes +belong to the test harness, not the OCOUT wire format. Resource and internal +errors stay distinct from successful builds. -Every invocation first reconstructs the same pinned Epsilon execution receipt — -identical request, identical 719,068-byte output — so -`OMEGA_EXECUTABLE_RECEIPT_CACHE=` lets the controls matrix share one -reconstruction; cached bytes still face the pinned identity check, and -`OMEGA_EXECUTABLE_RECEIPT_SECONDS` bounds a cold reconstruction. +Every run rebuilds the same pinned 719,068-byte Epsilon execution output from +the same request. Set `OMEGA_EXECUTABLE_RECEIPT_CACHE=` to share one +rebuild across the test matrix; cached bytes are still hash-checked, and +`OMEGA_EXECUTABLE_RECEIPT_SECONDS` still bounds a cold rebuild. ## Regression controls @@ -130,8 +125,8 @@ sh tests/bootstrap/interpreted/omega-executable/run.sh --controls-i sh tests/bootstrap/interpreted/omega-executable/run.sh --controls-j ``` -The ordinary Epsilon controls reuse one compiler across eighty-three -invocations split among [controls.epsilon](../../conformance/omega/controls.epsilon), +These ten suites reuse one compiler instance across 83 cases split across +[controls.epsilon](../../conformance/omega/controls.epsilon), [controls_b.epsilon](../../conformance/omega/controls_b.epsilon), [controls_c.epsilon](../../conformance/omega/controls_c.epsilon), [controls_d.epsilon](../../conformance/omega/controls_d.epsilon), @@ -140,48 +135,39 @@ invocations split among [controls.epsilon](../../conformance/omega/controls.epsi [controls_g.epsilon](../../conformance/omega/controls_g.epsilon), [controls_h.epsilon](../../conformance/omega/controls_h.epsilon), [controls_i.epsilon](../../conformance/omega/controls_i.epsilon), and -[controls_j.epsilon](../../conformance/omega/controls_j.epsilon): zero and maximum byte results, -folded integral arithmetic and explicit anonymous bitwise/shift refusals, -multiple declarations and selection of a non-first entry, duplicate names, -missing entry, out-of-range and oversized decimal values, an out-of-range -expression operand, overflow, underflow, division and modulo by zero, -out-of-width and overflowing shifts, an invalid unselected body, unsupported -path, `-` unary, and other expressions and return types, a -body containing only nested declarations, digit separators, malformed syntax, and successful -reuse after failures; then checked control flow: call statements and grouped -terminal calls between machines with exact emitted-tape assertions, -subjectless and literal-subject transitions into nested machines, folded -Boolean subjects through the comparison, logical, and `!` operators, a -folded Boolean refused at the `u8` terminal, carrier-class rejections at -operators (`&&` on anonymous numbers, `<` against a Boolean, `!` on a number, `==` -across classes), a forward-declared callee, nested-machine name -resolution, unresolved call -and state targets, call and transition arity mismatches, an empty authored -state, an unmatched subject, duplicate authored state names, an unreachable -statement after a transition block, receiver and `self` call paths, a supported -parameterized transfer, first-match selection in a multi-arm subjectless block, a -non-Boolean subjectless condition, an -integer arm under a Boolean subject, refused fractional anonymous division, -unsupported shift and bitwise expressions, an ungrouped terminal call, two sequential call -statements, a wildcard arm ahead of a matching literal arm, and a Boolean arm -under an integer subject. -Every rejection requires an empty unsealed -tape. A final exact literal byte comparison precedes execution of the actual -emitted tape; the expected bytes are never used as the executable input. - -The split is an evaluator-run boundary, not a compiler one: each invocation -is a fresh evaluation. It predates the V5 pair-arena growth — the retired -40,265,318-node arena, refused with status 252, could not retain even an -eighteen-invocation half of the matrix — and remains the bounded evaluated -form. Each part carries a bounded run of controls and ends with the same -`20 + 22` success compile, byte `67`, and tape publication, so every run -checks the same observation and executes the same emitted program. +[controls_j.epsilon](../../conformance/omega/controls_j.epsilon). They cover: +zero and max byte outputs; constant-folded arithmetic and rejected anonymous +bitwise/shift ops; multiple declarations and non-first entry selection; +duplicate names and missing entry; out-of-range and oversized decimals; +overflow, underflow, division and modulo by zero; out-of-width and overflowing +shifts; invalid unselected bodies; unsupported paths, unary `-`, expressions, +and return types; bodies with only nested declarations; digit separators; bad +syntax; and compiler reuse after errors. Control-flow tests cover call +statements and grouped terminal calls with exact tape checks; subjectless and +literal-subject transitions into nested machines; folded Boolean comparisons, +logical ops, and `!`; folded Booleans rejected at `u8` return; operator type +mismatches (`&&` on anonymous numbers, `<` with a Boolean, `!` on a number, +`==` across types); forward callees; nested name lookup; unresolved call/state +targets; arity mismatches; empty states; unmatched subjects; duplicate state +names; unreachable code after a transition; receiver and `self` calls; +parameterized transfers; first-match ordering; non-Boolean guards; mismatched +arm types; fractional anonymous division; unsupported shifts/bitwise ops; +ungrouped terminal calls; sequential call statements; and wildcard arms before +literal arms. Every rejection must leave the tape empty and unsealed. Before +running each emitted tape, the harness compares its bytes against the expected +literal tape (it never executes the expected bytes directly). + +The ten-way split exists for evaluator memory limits, not compiler limits: each +suite runs in a fresh evaluator process. It predates the V5 pair-arena expansion +(the old 40,265,318-node arena hit status 252 before finishing half the matrix). +Every part finishes with the same `20 + 22` build, byte `67`, and tape check, +verifying the same output and running the emitted program. ## Bound customer entries -Every entry the harness may select is bound: `main_ocreq.epsilon`, -`main.epsilon`, and the ten controls files are gate-local inputs packed on -top of the bound member closure, never part of the manifested members. +Every selectable entry file is pinned: `main_ocreq.epsilon`, `main.epsilon`, and +the ten control files are test inputs prepended on top of the compiler bundle, +never part of its source manifest. | Entry | Bytes | SHA-256 | | --- | ---: | --- | @@ -198,72 +184,63 @@ top of the bound member closure, never part of the manifested members. | `controls_i.epsilon` | 3,780 | `8db11826d19b81e865a0be017c65ab986608152fa3c502ab0bb16147c1238f8a` | | `controls_j.epsilon` | 5,611 | `42f1efcdf9f86ac7432e7ee8da79410ae3cdfe04304c57a0f164c37354acc145` | -`tools/bootstrap/omega/compiler_env.sh` checks every entry identity before -each packing and `tests/bootstrap/interpreted/omega-identity.sh` covers the refusals. The -customer is the bound compiler closure followed by the selected entry. Each -execution reports its concatenated size and digest; those observations do not -introduce a second table of source identities. +`tools/bootstrap/omega/compiler_env.sh` verifies each entry's hash before +packing, and `tests/bootstrap/interpreted/omega-identity.sh` tests failure cases. +Each run appends the chosen entry to the pinned compiler bundle and prints the +combined size and digest without maintaining a second hash table. ## Execution boundary -This is a component-level source-to-executable regression, not the final +This is a component-level regression test, not the final [standalone compiler interface](../../../../wiki/spec/build/compiler_request.md). -It uses the existing private Epsilon execution observation format. It does not -implement package resolution, Build evaluation, general ProgramEntry -selection beyond the target's bound `main` name, general Omega checking, or a -compiler-refinement proof. `main_ocreq.epsilon` is the gate's entry: the real -OCREQ/OCOUT route for the `alpha_bootstrap_tape` slice, bound like every -other selectable entry. `main.epsilon` remains bound for the `--diagnostic` -raw-source lane. - -The additional [controls_values.epsilon](../../conformance/omega/controls_values.epsilon) customer uses -an internal selected-entry boundary to check parameter/local/call lowering and -negative cases, then publishes length-framed artifacts for actual Alpha -execution. `python3 tests/bootstrap/compiled_vm/source_test.py --omega-values` -constructs its source-only semantic producer path. Each invocation stores the -exact packed compiler, complete customer, request and observation; historical -measurements remain bound to their original sources. This customer is separate -from the public OCREQ admission checks. - - -The source-built peer's `--omega-utf8` customer extracts `DecodedScalar` and -`decode_scalar` verbatim from the real lexer, alongside the real SourceUnit -append/read declarations. [utf8_controls.omg](../../conformance/omega/utf8_controls.omg) checks 28 -valid/invalid UTF-8 boundaries and an absent large index. The companion -[controls_arithmetic.epsilon](../../conformance/omega/controls_arithmetic.epsilon) checks arithmetic -limits, six abnormal overflow/underflow traps, left-value capture across a -mutating right operand, short-circuit suppression, reference forwarding and -refusal recovery. Wrapping controls exercise all 64 bits, preserve the left -value across a mutating right call, and reject mixed-policy operands and -implicit qualification changes. The nested crash controls cover declared -and inferred routes, disconnected helpers, cyclic transfers, contract order -and refusal recovery. The terminal-call cases exercise precedence, -grouping, nested calls, left-to-right argument evaluation, skipped and selected -crashes, loans, blocking markers and entry preconditions. An unsupported -indexed carrier returns a coverage refusal. An unknown name in a checked -scalar operand remains a source error. Each refusal leaves the tape empty -and unsealed. Transition predicates also exercise keyword-spelled local names, -lookup in an uncalled machine and Boolean literal selection. - -The carrier-cast batches compare the combined and parenthesized domain additions, -execute a mutating operand once, and trap on overflow after preserving a full -unsigned 64-bit value. - -Each batch uses a fresh evaluator process to bound cumulative allocation. The first receives -the full decoder source. Each refusal batch reuses one compiler instance and -ends with a successful compilation. The host stamps and runs every -published tape, distinguishing Linux SIGILL from a normal process exit. - +It uses the private Epsilon output format and does not implement package +resolution, Build evaluation, general ProgramEntry selection beyond `main`, full +Omega checking, or a refinement proof. `main_ocreq.epsilon` is the main entry +for the `alpha_bootstrap_tape` OCREQ/OCOUT slice; `main.epsilon` stays pinned +for `--diagnostic`. + +[controls_values.epsilon](../../conformance/omega/controls_values.epsilon) uses +an internal entry selector to test parameter, local, and call lowering plus +negative cases, emitting length-framed tapes for Alpha execution. +`python3 tests/bootstrap/compiled_vm/source_test.py --omega-values` builds that +path from source and saves the packed compiler, input, request, and output +(historical timings stay tied to their original sources). This test is separate +from public OCREQ validation. + +The peer's `--omega-utf8` test copies `DecodedScalar` and `decode_scalar` +verbatim from the real lexer along with SourceUnit's append/read declarations. +[utf8_controls.omg](../../conformance/omega/utf8_controls.omg) tests 28 valid +and invalid UTF-8 cases plus an out-of-range index. +[controls_arithmetic.epsilon](../../conformance/omega/controls_arithmetic.epsilon) +tests arithmetic limits, six overflow/underflow traps, left-operand capture +across a mutating right operand, short-circuiting, reference forwarding, and +recovery after errors. Wrapping tests cover all 64 bits, preserve the left value +across a mutating right call, and reject mixed policies and implicit casts. +Nested crash tests cover declared and inferred routes, disconnected helpers, +cyclic transfers, contract ordering, and recovery. Terminal-call tests cover +precedence, grouping, nested calls, left-to-right argument order, skipped and +taken crashes, borrows, blocking markers, and entry preconditions. Unsupported +indexed types return a coverage refusal; unknown names in checked scalar +operands stay source errors. Every rejection leaves the tape empty and unsealed. +Transition predicates also test keyword-spelled locals, lookups in uncalled +machines, and Boolean literal selection. + +Type-cast batches compare combined and parenthesized domain additions, run a +mutating operand once, and trap on overflow while preserving full 64-bit +unsigned values. + +Each batch uses a fresh evaluator process to cap memory use. The first receives +the full decoder source; each refusal batch reuses one compiler instance and +ends with a valid build. The harness stamps and runs every emitted tape, +distinguishing Linux SIGILL from normal exits. -Ordered subjectless Boolean predicates are also exercised by `tests/bootstrap/independent/directory_names.py --case predicate-effects-ordered` -against an executable construction entry. The `predicate-*` cases check the -product's three-field `same_type_form` guard shape over scalar fields with each -answer-changing mutation, first-match order, once-only and short-circuit guard -evaluation, checked nested arrivals, and rejection of ill-typed unselected arms. -Every refusal requires an exact outcome and no Alpha tape. Coverage through a -wildcard or literal `true` is supported; more general coverage proofs return -`Incomplete`. The `sum-equality-*` controls exercise case comparisons with the -product's original enum declarations. Four execute the complete -`static_integer_is_valid` machine from a separate source unit, covering an -exact unsuffixed integer, an inexact integer, missing digits and a suffix. +tests ordered subjectless Boolean predicates against an executable compiler. The +`predicate-*` cases test the product's three-field `same_type_form` guard with +each answer-changing mutation, first-match order, single and short-circuit guard +evaluation, checked nested arrivals, and ill-typed unselected arms. Every +refusal requires an exact error and no tape. Coverage via a wildcard or literal +`true` works; broader coverage proofs return `Incomplete`. The `sum-equality-*` +cases test case comparisons on the product's enum declarations. Four run the +complete `static_integer_is_valid` machine from a separate source unit on an +exact unsuffixed integer, an inexact integer, missing digits, and a suffix. diff --git a/tests/bootstrap/linux_x86_64/README.md b/tests/bootstrap/linux_x86_64/README.md index e0c6113be1e1..266f8a4587d3 100644 --- a/tests/bootstrap/linux_x86_64/README.md +++ b/tests/bootstrap/linux_x86_64/README.md @@ -1,43 +1,41 @@ # Cold bootstrap test launcher for Linux x86-64 -Run the checked-in binary with the source tree and a new output directory. -The default `gamma-compiler` takes Gamma source on stdin and writes a -standalone Linux x86-64 executable on stdout. +Run the checked-in binary with the repository root and a new output directory. +By default it builds `gamma-compiler`, which reads Gamma source on stdin and writes a +standalone Linux x86-64 executable to stdout. ```sh tests/bootstrap/linux_x86_64/bootstrap . /tmp/omega-gamma ``` -The command runs offline with an empty `PATH`. It needs Linux x86-64, space -for the stage files, permission to execute programs in the new directory, -and the virtual memory provision of the Alpha seed. +This runs offline with an empty `PATH`. It requires Linux x86-64, disk space +for intermediate stage files, execute permission in the output directory, +and the same virtual memory setup as the Alpha seed. ### Build a supplied Gamma program in the same command -A third argument supplies one complete Gamma source file. The driver snapshots -its bytes in `program.gamma` before constructing the compilers, then runs -`gamma-compiler` on that snapshot. Successful compilation publishes the native -`program` executable. An invalid program leaves the rebuilt Gamma compiler -available and returns the producer's failure status. +Pass a third argument to supply a complete Gamma source file. The driver copies +its bytes to `program.gamma` before building the compilers, then runs +`gamma-compiler` on that copy. If compilation succeeds, it writes the native +`program` executable. If the program is invalid, the rebuilt Gamma compiler +remains available and the driver exits with the compiler's error status. ### Build the Delta compiler from its source tree -Use `--delta` to read the Delta compiler entry and the implementation manifest -from the supplied source root. Each member path resolves relative to the -manifest. The driver writes the entry and the members in the declared order -with no separator. It saves the result as `program.gamma` and compiles it to -`program`. +Pass `--delta` to read the Delta compiler entry and its source manifest +from the source root. Each member path resolves relative to the manifest. +The driver joins the entry and members in order with no separator, saves the +result as `program.gamma`, and compiles it to `program`. ```sh tests/bootstrap/linux_x86_64/bootstrap --delta . /tmp/omega-delta ``` -The driver checks the manifest header and row format, strictly increasing -identities, unique relative Gamma paths, regular member files, source text -bytes and each member's declared length. It rejects symlinks in member paths. -It checks the spelling of each digest. To verify the SHA-256 values and the -full source inventory independently, materialize the same input and compare -it with the driver's snapshot. +The driver validates the manifest header and row format, strictly increasing +IDs, unique relative Gamma paths, regular files, source bytes, and each +member's declared length. It rejects symlinks in member paths and checks the +format of each digest. To verify SHA-256 hashes and the full file list +independently, pack the same input with `xtask` and compare it to the driver's copy: ```sh mbx xtask source-closure bootstrap/delta/compiler/implementation/implementation.gamma.sources \ @@ -49,96 +47,91 @@ cmp /tmp/audited-delta.gamma /tmp/omega-delta/program.gamma ### Compile Gamma source emitted by the supplied program -A final optional argument supplies input to the `program` built in the previous -step. The driver saves the bytes in `program.input`, runs `program` on them, -then gives its successful output to the rebuilt Gamma compiler. The output -directory retains the intermediate bytes as `producer.output`. When Gamma -accepts them it writes the native executable `successor`. +Pass a final optional argument to supply stdin for the `program` built in the +previous step. The driver saves those bytes in `program.input`, runs `program` +on them, and feeds its output to the rebuilt Gamma compiler. It saves the +intermediate output as `producer.output`. When Gamma accepts it, the driver +writes the native executable `successor`. For example, the Delta compiler can emit the Gamma source for the Epsilon -evaluator. This invocation takes its canonical Delta compilation request. +evaluator from a canonical Delta compilation request: ```sh tests/bootstrap/linux_x86_64/bootstrap --delta . /tmp/omega-epsilon /path/to/epsilon-request.bin ``` -That request contains the 16-byte DCREQ header, the ordered Delta source of +That request packs the 16-byte DCREQ header, the ordered Delta source of the Epsilon evaluator and its entry, and the Gamma support bytes. The [successor test](../../../wiki/development/bootstrap/native.md#native-successor-customers) writes -this input to `build/independent-successors/epsilon-request.bin`. A source -distribution can supply the same file alongside the checkout. The invocation -uses those bytes directly and runs offline. The native `successor` already -contains the Gamma program, so its stdin starts at the sealed `EEREQ` header. +this file to `build/independent-successors/epsilon-request.bin`, or a source +archive can provide it alongside the checkout. The command reads those bytes +directly offline. Because the native `successor` already embeds the Gamma +program, its stdin starts at the sealed `EEREQ` header. [Epsilon evaluation request](../../../bootstrap/epsilon/interpreter/EVALUATOR_ENTRY.md) ### Run the compiled Alpha tape route -Pass `--alpha` before the source root to run the same construction with -the Gamma-to-Alpha backend. For example, build the Epsilon evaluator from -the same Delta source tree and request as above. +Pass `--alpha` before the source root to use the Gamma-to-Alpha backend +instead of native ELF. For example, to build the Epsilon evaluator from +the same Delta source tree and request: ```sh tests/bootstrap/linux_x86_64/bootstrap --alpha --delta . /tmp/omega-epsilon-alpha /path/to/epsilon-request.bin ``` -The Gamma compiler source uses `gamma/compiler/alpha/alpha_backend.gamma`. The driver -stamps its output into the original Linux Alpha seed at every executable -stage. The evaluator emits `gamma0.tape`. Two self-compilations produce -`gamma1.tape` and `gamma2.tape`. The driver compares all three stamped -executables byte for byte. The resulting `gamma-compiler` accepts ordinary Gamma source -on stdin and writes Alpha tape. The optional inputs produce `program.tape` -and `successor.tape`, together with the independently executable `program` -and `successor`. For the illustrated inputs those are the Delta compiler and -Epsilon evaluator. Run `successor` with the same sealed Epsilon request as -the native route. Each output tape must fit the seed's 16 MiB field including -its four-byte length. [Compiled VM](../../../wiki/development/bootstrap/compiled-alpha.md) +This selects `gamma/compiler/alpha/alpha_backend.gamma` and stamps every +generated tape into the Linux Alpha seed. The evaluator produces `gamma0.tape`, +and two self-rebuilds produce `gamma1.tape` and `gamma2.tape`. The driver verifies +that all three stamped executables match byte for byte. The final `gamma-compiler` +reads Gamma source on stdin and writes an Alpha tape. With optional inputs, the +driver also writes `program.tape` and `successor.tape`, along with runnable +`program` and `successor` executables (the Delta compiler and Epsilon evaluator +above). Run `successor` with the same sealed Epsilon request used on the native +route. Each tape must fit inside the seed's 16 MiB slot, including its four-byte +length. [Compiled VM](../../../wiki/development/bootstrap/compiled-alpha.md) ## Follow the construction -1. The binary carries the audited Linux Alpha executable and the admitted - 1,773-byte Beta tape. Its assembly source includes both parts of the +1. The driver embeds the audited Linux Alpha executable and the trusted + 1,773-byte Beta tape. Its assembly source includes both halves of the original ELF around the 16 MiB zero-filled tape section. The driver - restores that section as a sparse file, inserts the tape and runs the - resulting `beta-seed` on `beta_compiler.beta`. Every byte of its output - must match the admitted tape before the rebuilt Beta can run. + recreates that section as a sparse file, stamps the tape, and runs + `beta-seed` on `beta_compiler.beta`. Every output byte must match the + trusted tape before the rebuilt Beta is allowed to run. 2. The rebuilt Beta compiles `gamma_evaluator.beta` to `gamma.tape`. The - driver puts those produced bytes in the same Alpha executable to obtain + driver stamps that tape into the same Alpha executable to build `gamma-evaluator`. -3. The driver joins `gamma/compiler/compiler.gamma`, `gamma/compiler/frontend.gamma` - and the selected backend with one newline between files. The native route - uses `gamma/compiler/linux_x86_64/native.gamma`. The Alpha route uses - `gamma/compiler/alpha/alpha_backend.gamma`. The driver writes - the four-byte little-endian source length, those exact source bytes and - a second copy as input for the Gamma program. The evaluator runs this - request and produces the first compiler, `gamma0`, after stamping its tape - when the Alpha target is selected. -4. `gamma0` reads the joined Gamma source and emits `gamma1`. That compiler - reads the same source and emits the final executable. The driver compares - both rebuilds byte for byte before publishing `gamma-compiler`. The - output directory retains the tapes, compiler request and each constructed - executable for inspection. - -Each producer writes to a blocking pipe. The driver checks the disk writes -and waits for the producer before renaming a completed stage. A failed -command leaves the newly created directory available for diagnosis, including -any `stage.partial`. A fresh invocation requires its own new directory. +3. The driver joins `gamma/compiler/compiler.gamma`, `gamma/compiler/frontend.gamma`, + and the chosen backend (`gamma/compiler/linux_x86_64/native.gamma` for native + or `gamma/compiler/alpha/alpha_backend.gamma` for Alpha) with single newlines. + It writes the four-byte little-endian source length, that joined source, and + a second copy as input. The evaluator runs this request to emit `gamma0` + (stamping its tape on the Alpha route). +4. `gamma0` compiles the joined Gamma source to `gamma1`, which compiles the + same source again to produce the final executable. The driver checks that + both rebuilds match byte for byte before publishing `gamma-compiler`. All + intermediate tapes, requests, and executables stay in the output directory + for inspection. + +Each stage writes to a blocking pipe. The driver checks disk writes and waits +for each child process to finish before renaming its output. If a run fails, +the new output directory stays on disk for debugging, including any +`stage.partial` file. Every new run requires a fresh directory. ## Audit the native entry -The Linux kernel, the checked-in driver, its embedded Alpha and Beta, and the -five supplied source files are the inputs for constructing the Gamma compiler. -Self-reconstruction checks the Beta bytes. The finite Beta audit and Alpha -semantics explain what those bytes do. The driver handles file I/O, process -invocation, framing, byte comparisons and optional Delta manifest assembly. -A replacement driver can substitute stages, so its executable is also part -of the native trust root. +Constructing the Gamma compiler depends only on the Linux kernel, the +checked-in driver, its embedded Alpha and Beta binaries, and the five supplied +source files. Rebuilding Beta from source checks the Beta bytes; the Beta audit +and Alpha spec explain what they do. The driver only handles file I/O, process +spawning, framing, byte comparisons, and optional Delta manifest packing. Because +a modified driver could swap stages, its binary is part of the native trust root. [Alpha](../../../bootstrap/alpha/README.md) · [Beta audit](../../../bootstrap/beta/AUDIT.md) · [Gamma compiler](../../../wiki/development/bootstrap/native.md) -The test launcher is freestanding C with an assembly entry for Linux system calls. -For a source-to-binary comparison, run this command from the repository root -using GCC 14.2.0 and GNU binutils 2.44. These development tools participate -when reproducing the driver itself. The checked-in binary needs only the OS -during compiler construction. +The launcher is freestanding C with an assembly entry point for Linux syscalls. +To verify the binary from source, run this command from the repository root +with GCC 14.2.0 and GNU binutils 2.44 (these tools are only needed to rebuild +the driver itself, not during compiler construction): ```sh gcc -std=c11 -Os -ffreestanding -fno-stack-protector -fno-asynchronous-unwind-tables \ @@ -147,13 +140,13 @@ gcc -std=c11 -Os -ffreestanding -fno-stack-protector -fno-asynchronous-unwind-ta cmp /tmp/omega-bootstrap tests/bootstrap/linux_x86_64/bootstrap ``` -For a function-labeled disassembly, omit `,-s` from the linker option and run -`objdump -d /tmp/omega-bootstrap`. Its `.text` bytes match the stripped build. +To inspect labeled functions, drop `,-s` from the linker flags and run +`objdump -d /tmp/omega-bootstrap`; its `.text` bytes match the stripped binary. -The Linux test supplies the five compiler source files, checks every stamped image -against the audited seed, checks each static executable, compiles two changed -Gamma programs, runs both on changed bytes and exercises malformed inputs. -Run `python3 tests/bootstrap/linux-seed-construction.py` for native images and +The Linux test script checks every stamped image against the audited seed, +verifies each static executable, compiles two modified Gamma programs, runs +them on different inputs, and tests malformed inputs. Run +`python3 tests/bootstrap/linux-seed-construction.py` for native images or `python3 tests/bootstrap/linux-seed-construction.py --alpha` for Alpha tapes. -Add `--delta` to either test command to exercise the canonical Delta source -tree, malformed manifests, and compilation and execution of a Delta customer. +Add `--delta` to also test the Delta source tree, malformed manifests, and +compiling and running a Delta program. diff --git a/tests/bootstrap/proofs/beta-encoding-theory/README.md b/tests/bootstrap/proofs/beta-encoding-theory/README.md index 0ef920251f3e..5646d09ed310 100644 --- a/tests/bootstrap/proofs/beta-encoding-theory/README.md +++ b/tests/bootstrap/proofs/beta-encoding-theory/README.md @@ -1,124 +1,100 @@ # Finite Beta encoding theory diagnostics -Run `sh tests/bootstrap/proofs/beta-encoding-theory/run.sh` from the repository root on -macOS arm64 or Linux x86-64, or Windows x64 Git Bash, with Python 3 available as `python3`. -The same command applies on both hosts; PowerShell is not required. -Missing Python explicitly skips; unsupported hosts fail with status 2. -The gate prints the executing host. A result on one host does not establish -execution on the other. - -For the bounded full-subject representation probe, run -`sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --subject-shape` on either supported -host. This selects [subject_shape.py](subject_shape.py), not the finite-equation -suite. It checks separately encoded copies of the entire current evaluator -source and tape as ByteLists, then requires an exact rejection after changing -the first source byte in the witness. Both rows are literal reflexivity claims; -the final root is tape-list reflexivity, **not** `encode_Beta(source) = tape`. -Host code constructs diagnostic records only. Theory bytes still come from the -pinned Gamma emitter, and all owner/witness rows pass the ordinary checker. -The 900-second per-invocation watchdog grants no verdict on timeout. - -The runner prints exact subject identities, request bytes, term counts, checking -work, and elapsed time. At total subject length N, two separately represented -spines require `4*N+13` work: index3, two row checks, two comparisons costing -`4*N+4`, and four final-root transitions. These expectations are derived before -execution, not learned from output. This measures one full-size prerequisite, -not certificate production, Beta semantics, or full encoding-proof feasibility. -See the [cost investigation](../../../../wiki/drafts/reference/bootstrap_cost_review.md). - -`sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --counter-cost` selects the separate -[counter recipe probe](counter_cost.py). It reuses the existing literal successor -derivations, interns identical ground records across them, and reuses identical -proof rows after remapping their backward references. It performs no theory -interpretation, Beta parsing, or search for alternative proofs. Small combined -requests check 1, 24, and 257 consecutive increments; the last crosses the byte -carry boundary. A corrupted final endpoint must reject after the valid prefix. -The work ledger uses the existing counter recipe's row costs, charging one -combined proof index/root and charging each retained row once. - -The final measurement constructs the same shared recipe for one increment per -raw evaluator source byte. It prints term/row/byte counts and the derived work, -but does **not** invoke the checker on that oversized request. This tests one -proposed source-counter strategy, not a lower bound for all encoders. Neither -the small checked examples nor the large constructed table proves source length, -source traversal, or Beta encoding. Retain this probe only while deciding that -strategy; it is not another compulsory component gate or production producer. - -`sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --full-subject` selects the -[full-subject production gate](full_subject.py) and, unlike the other modes, -runs on hosts with python3 and the historical Git objects — no evaluator seed -is materialized. The -checked-in stepper replays the complete untrusted derivation for the pinned -subjects over the sha256-pinned theory reconstruction and requires the -recorded table, per-rule row, depth, and request figures exactly. The mode -also prints the retained-role census — which proof rules, theory functions, -and constructors the certificate actually uses — and still states diagnostic -production only: the certificate has to be produced through the selected -chain and checked under the exact profile. See -[PROFILE.md](../beta_encoding/PROFILE.md) for the -measured figures. The source and tape are fixed to `d19361fe4deae73e1b488a940a872fec1ed885cb` -and independently hash-checked. These measurements are historical research, -not admission of the current evaluator. Missing Git/history fails explicitly; -there is no current-source fallback or implicit fetch. +Run `sh tests/bootstrap/proofs/beta-encoding-theory/run.sh` from the repository +root on macOS arm64, Linux x86-64, or Windows x64 (Git Bash) with `python3`. +PowerShell is not needed. Missing Python skips explicitly; unsupported hosts +exit with status 2. The gate prints the host name; passing on one host does not +verify another. + +Run `sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --subject-shape` to +run [subject_shape.py](subject_shape.py) instead of the finite-equation suite. +It checks separate ByteList copies of the current evaluator source and tape, +then verifies rejection after flipping the first witness source byte. Both proof +rows are reflexivity claims; the final root is tape-list reflexivity, **not** +`encode_Beta(source) = tape`. Host code builds only diagnostic records; theory +bytes come from the pinned Gamma emitter, and every term passes the ordinary +checker. Its 900-second watchdog never grants a verdict on timeout. + +The runner prints subject hashes, request bytes, term counts, work, and elapsed +time. For total length N, two separate spines take `4*N+13` work (index 3, two +row checks, two comparisons costing `4*N+4`, and four root steps), derived +before running. This measures one full-size prerequisite, not proof production, +Beta semantics, or full encoding feasibility; see the +[cost investigation](../../../../wiki/drafts/reference/bootstrap_cost_review.md). + +`sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --counter-cost` runs the +[counter recipe probe](counter_cost.py), which interns identical ground records +and reuses proof rows across literal successor derivations without interpreting +the theory, parsing Beta, or searching for proofs. Small requests check 1, 24, +and 257 increments (crossing the byte carry boundary), plus a corrupted final +endpoint that must fail after the valid prefix. Work charges one combined index +and root plus each retained row once. + +Its final step builds the shared recipe for one increment per evaluator source +byte and prints counts and derived work without invoking the checker on that +oversized request. This tests one source-counter design, not a general lower +bound, and proves neither source length nor Beta encoding. Keep this probe only +while evaluating that strategy; it is not a required gate or production tool. + +`sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --full-subject` runs the +[full-subject production gate](full_subject.py) on any host with python3 and the +historical Git objects — no evaluator seed is needed. The checked-in stepper +replays the full derivation for the pinned subjects over the SHA-256-pinned +theory reconstruction and checks the recorded table, rule, depth, and byte +counts exactly. It also prints the retained-role census (which rules, functions, +and constructors the certificate uses). This proves diagnostic production only; +the certificate must still be produced through the bootstrap chain and checked +under the exact profile. See [PROFILE.md](../beta_encoding/PROFILE.md) for the +numbers. Both subjects are fixed to `d19361fe4deae73e1b488a940a872fec1ed885cb` +and hash-checked; they are historical research, not admission of the current +evaluator. Missing Git history fails explicitly with no fallback or fetch. `sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --produce-request PATH` -materializes the certificate artifact itself: the same host-side -production plus the recorded extent/digest pin, then an atomic write of -the complete 135,485,028-byte framed request to PATH. The file is the -untrusted derivation input the -[check gate](https://github.com/CathedralOS/Omega/tree/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/beta-encoding-check) frames for the evaluator — producing -it grants no admission. - -`sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --mutations` selects the -[mutation-control leg](mutations.py) and, like the default gate, needs a -native evaluator host. It rebuilds the complete full-subject certificate -with the checked-in stepper, then requires the checker to publish exact -owned rejections for corruptions across the -[ACCEPTANCE.md](../beta_encoding/ACCEPTANCE.md) -taxonomy: a positive unmutated control, theory clause-body identity, -source- and tape-side instance roots, an unknown rule tag, clause ordinal -range and case errors, a swapped substitution environment, wrong and -self-referential premises, a term arity count, the owner/witness partition -joint, claimed endpoints, both final-root selections, and two rows -following a valid prefix. Expected diagnostics carry the coordinate and -code conventions from -[CHECKING.md](../checker/CHECKING.md). On any host -with python3, `python3 mutations.py --self-test` reproduces the -certificate and verifies vector construction without asserting verdicts. - -The shell entry resolves bootstrap roles, materializes both complete source -closures, and invokes `materialize_gamma_evaluator` for the selected -Beta-authored evaluator. All test logic uses Python's standard library. -For a prepared directory containing `producer.gamma`, `checker.gamma`, and the -materialized `evaluator`, use +runs the same host-side production and digest check, then atomically writes the +135,485,028-byte framed request to PATH. That file is untrusted input for the +[check gate](https://github.com/CathedralOS/Omega/tree/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/beta-encoding-check) +and grants no acceptance by itself. + +`sh tests/bootstrap/proofs/beta-encoding-theory/run.sh --mutations` runs the +[mutation-control leg](mutations.py) on a native evaluator host. It rebuilds the +full-subject certificate with the stepper and requires exact checker rejections +across the [ACCEPTANCE.md](../beta_encoding/ACCEPTANCE.md) taxonomy: unmutated +control, theory clause body, source/tape roots, unknown rule tag, clause ordinal +range/case errors, swapped substitution bindings, wrong/self premises, term +arity, owner/witness partition boundary, claimed endpoints, final-root +selection, and two bad rows after a valid prefix, using the offsets and codes in +[CHECKING.md](../checker/CHECKING.md). On any python3 host, +`python3 mutations.py --self-test` verifies vector construction without running +the checker. + +The shell script resolves bootstrap roles, packs both source closures, and calls +`materialize_gamma_evaluator`. All test scripts use only Python's standard +library. Given a prepared directory holding `producer.gamma`, `checker.gamma`, +and `evaluator`, run `python3 -B tests/bootstrap/proofs/beta-encoding-theory/gate.py PREPARED_DIRECTORY` -(or `python -B` on Windows when that names Python 3). The Python runner does -not reconstruct or replace the evaluator. Both entrypoints propagate failures. - -The bound [producer entry](main.gamma) — 211 bytes, SHA-256 -`35577d248b7745f3a6f4d2615e81bb8aae40cb8608d5fbda0be55978b544b373`, recorded -in `tests/bootstrap/proofs/sources_env.sh` and checked by -`require_beta_encoding_producer_entry_identity` before it packs on the bound -member bytes — calls ordinary Gamma -[`beta_encoding_theory`](../beta_encoding/theory/theory.gamma) -only for empty input. Its marked application result publishes bytes without a -scalar terminator. Three nonempty inputs require status 1 and empty stdout and -stderr. The exact producer composition is pinned in [source.tsv](source.tsv). -The unmodified checking entry and its bound identity are reused from -[derivation-checking](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-checking/README.md), checked here by -`require_derivation_checking_entry_identity` before packing. - -The emitted complete GTH1 section contains the full error-valued Beta encoder -theory. Its byte -length and SHA-256 must match [theory.tsv](theory.tsv) and the independently -authored fixed layout in [identity.py](identity.py); a second Gamma invocation -must emit identical bytes. The host layout computes only a diagnostic length -and digest. Every checker request uses actual Gamma stdout as its theory, -except the explicitly corrupted copy in one negative control. No host-produced -package is admitted as checker input. Identity is not a proof rule or artifact -admission, and these fixtures contain no general Beta parser or proof producer. - -The finite equations transcribe [Beta's language contract](../../../../bootstrap/beta/LANGUAGE.md): +(or `python -B` on Windows when that runs Python 3). The Python runner never +rebuilds or replaces the evaluator, and both scripts propagate failures. + +The pinned [producer entry](main.gamma) — 211 bytes, SHA-256 +`35577d248b7745f3a6f4d2615e81bb8aae40cb8608d5fbda0be55978b544b373`, verified by +`require_beta_encoding_producer_entry_identity` in +`tests/bootstrap/proofs/sources_env.sh` — calls +[`beta_encoding_theory`](../beta_encoding/theory/theory.gamma) only on empty +input and writes raw bytes via Gamma's marked result. Three nonempty inputs must +exit with status 1 and empty stdout/stderr. [source.tsv](source.tsv) pins the +producer composition. The unmodified checking entry comes from +[derivation-checking](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-checking/README.md), +verified by `require_derivation_checking_entry_identity`. + +The emitted GTH1 section holds the full error-valued Beta encoder theory. Its +length and SHA-256 must match [theory.tsv](theory.tsv) and the independent +layout in [identity.py](identity.py), and a second Gamma run must match +byte-for-byte. Host code computes only a diagnostic hash; every checker request +uses actual Gamma stdout as its theory (except the one corrupted negative test). +No host-built theory is fed to the checker, and hash checks neither act as proof +rules nor provide a general Beta parser or prover. + +The finite equations mirror [Beta's language contract](../../../../bootstrap/beta/LANGUAGE.md): | Fixture family | Positive equations | Explicit proof rows | Expected work | | --- | ---: | ---: | ---: | @@ -133,171 +109,110 @@ The finite equations transcribe [Beta's language contract](../../../../bootstrap | [Unsigned byte comparison](ordering/bytes.py), twelve requests | 12 | 19 per request | 204–1,284 | | [Unsigned word comparison](ordering/words.py), thirty requests | 30 | 177 per request | 2,004–10,644 | -Each family uses a separate checker request. All rows, including those unused -by the final owner equation, must check. Lexical coverage retains every byte of -source admission, separators, comment endings, and lowercase hex classification. -Every nibble pair joins through an explicit public-to-helper Unfold, -helper-to-byte Unfold, and Transitivity. Every byte is split both ways. Composed -roundtrips add two split Unfolds, Congruence using their two ordered premises, -and a final Transitivity; the checker never implicitly normalizes arguments. -Word cases include zero, maximum, the highest bit, two varied byte patterns, -and a single nonzero byte in each of all eight positions. The expected byte -lists are authored least-significant byte first. - -Counter cases explicitly state both eight-byte input and expected result. -They cover zero, a varied no-carry value, two sets of carry lengths one through -seven with varied unaffected bytes, crossing the highest bit, maximum minus one -to maximum, and maximum to `Overflow`. A successful result is `WordValue(Word)`; -the maximum must never wrap to `WordValue(0)`. Four requests of 128 equations -cover every clause of the internal byte increment and maximum predicate. The -internal byte increment wraps 255 to zero; the public word successor selects -Overflow before an eight-byte wrapped value can become its result. - -The fixed carry derivation writes each helper Unfold, predicate Unfold, two -Reflexivity rows for the choice branches, ordered choice Congruence, choice -Unfold, two Transitivity rows, and a Transitivity connecting that helper to the -public root. The selected successful branch then supplies byte increment -Unfold, seven byte Reflexivity rows, eight-argument Word Congruence, unary -WordValue Congruence, and final Transitivity. These are finite authored proof -families over the listed literals; no code reads theory clauses to infer a -rewrite, recursively normalizes terms, or constructs a proof of arbitrary input. - -Ordering has three results: `Less`, `Equal`, and `Greater`. The fixed nibble -table covers all 256 pairs. Twelve byte examples include equal values, zero, -maximum, a higher nibble opposing the lower nibble, a matching higher nibble -requiring lower-nibble comparison, and values on either side of the unsigned -high bit. Thirty word examples include equal zero/maximum/varied words, both -directions across the high bit, and each highest differing byte position in -both directions. Lower bytes deliberately oppose the highest difference while -higher bytes agree. Separate literal rows compare the exact Beta source limit -`0x4000000` and output limit `0xfffffc`, and the adjacent values on each side, -against those limit words. These are numeric comparisons, not source or output -accounting judgments. - -The [fixed ordering recipes](ordering/proofs.py) explicitly unfold both nibble -splits, both public/helper nibble comparisons, and every choice. They supply -ordered Congruence and Transitivity rows for each argument rewrite. A byte -proof always normalizes both nibble comparisons. A word proof always supplies -all eight byte proofs, then seven fixed bottom-up ordering choices, then the -two word entrance unfoldings and their composition. Nothing inspects emitted -definitions to select a rewrite, searches for proofs, or recursively normalizes -arbitrary terms. Word and byte owner outcomes are separately stated literals. - -Negative controls preserve the lexical wrong answers, wrong clauses, altered -formed body, and wrong owner root. New controls corrupt join answers and -clauses, swap high/low results, omit the helper step, corrupt transitivity, -swap congruence premises, and attempt case selection before normalization. -Word controls reverse byte order, shorten and lengthen the output list, lose -the high bit, truncate the maximum, corrupt each byte position, and select an -invalid clause. Expected rejection coordinates come from physical record -sizes, never decoded or learned checker observations. - -The 181 vectors also include seven-field and nine-field Word constructor -applications. These are physically complete records that must reject during -ground admission with code 8 at the argument-count field, independently of -the separate seven-byte and nine-byte output-list mutations. - -Counter mutations corrupt the clause in every byte-helper batch, attempt choice -selection before normalizing its predicate, omit choice Congruence, substitute -the wrong condition premise, omit increment normalization, and corrupt each -result byte in a carry-three and highest-bit-crossing derivation. The maximum -case explicitly rejects a proposed wrapped zero result. Their exact failure -coordinates use the authored record lengths, including earlier valid rows. - -Ordering adds 32 mutation controls. They reverse a nibble answer, attempt to -skip its helper, select wrong nibble and word clauses, reverse high-nibble -priority, interpret the high bit as a sign bit, ignore the highest differing -word byte, omit normalization or Congruence, swap ordered premises, and change -the owner root after an otherwise valid proof. All 106 earlier vectors remain. - -The work expectations follow the generic checker accounting. Every batch pays -`P+1` for its proof index and four for its final root. Lexical clause walks cost -`4*(1+...+256)`; row/index/nullary substitution overhead is five per row, with -three extra units for each of sixteen Hex results. Splits use the same nullary -overhead and two complete byte clause walks. Each join costs `high+low+24`: -public unfolding costs `high+11`, helper unfolding `low+6`, and Transitivity -seven. Each composed roundtrip costs `2*byte+high+low+54`, including eleven -units for its two-premise Congruence and seven for final Transitivity. Each -word Unfold costs 70: one row reservation, one clause walk, eighteen template -index units, 34 substitution transitions, and sixteen variable ground-comparison -transitions. Shared closed ground references make each structural endpoint -comparison exactly two units. These are independently derived expectations; -the runner requires the exact tag-7 count/work observation. - -For counter byte helpers, each row costs `byte+6`; a 128-row request adds 129 -for indexing and four for the root. Public word unfolding costs 46: one row, -one clause, ten index units, eighteen substitution transitions, and sixteen -variable comparison transitions. Each lower carry-helper unfolding costs 80: -one row, one clause, sixteen index units, 46 substitution transitions across -22 child edges, and sixteen variable comparison transitions. Its highest-byte -counterpart costs 63, with fifteen index units and thirty transitions across -fourteen edges. Repeated variable templates under the same ground reference -use the invocation-local memo; each of eight distinct variable templates still -requires its first two-unit ground comparison. - -A predicate row costs `byte+6`; the two branch Reflexivity rows cost six, -choice Congruence sixteen, choice unfolding eight for False or nine for True, -and the three Transitivity rows cost 21. Successful final normalization costs -`byte+81`: byte unfolding, seven Reflexivity rows (21), Word Congruence (41), -WordValue Congruence (six), and final Transitivity (seven). Including the proof -index and root, an input carrying `c=0..6` bytes and then incrementing byte `b` -uses `21+9*c` proof rows and `290+402*c+2*b` work. Carrying seven bytes uses -84 rows and `3087+2*b` work. Maximum overflow uses 73 rows and 3,251 work. -These equations were fixed from checker/source accounting before execution. - -For ordering, each nibble pair `(l,r)` uses three rows costing `l+r+24` before -index/root work. A normalized high- or low-nibble comparison of bytes `(a,b)` -uses seven rows costing `a+b+l+r+54`. The byte definition Unfold costs 38: -one row, one clause, ten template-index units, 22 substitution transitions -across ten child edges, and four variable comparison transitions. Its two -variable templates each incur one ground comparison; later occurrences reuse -the invocation-local memo. The ordering choice costs six for Less, nine for -Equal, or eight for Greater, including its row and clause walk. Its Equal -clause compares the bound lower result; the other two have constant bodies. - -Let `q(L)=6`, `q(E)=9`, and `q(G)=8`. A nineteen-row byte proof has row work -`B(a,b)=2*a+2*b+ah+al+bh+bl+171+q(high_order)`, where the four nibble values -come from the finite split cases. Its exact checker work adds 24 for its index -and final root. Word public unfolding costs 51: one row, one clause, eleven -index units, twenty substitution transitions, and eighteen variable comparison -transitions. Right-word unfolding costs 128: one row, one clause, 32 index -units, 62 substitution transitions across thirty edges, and 32 variable -comparison transitions. All sixteen variable templates are distinct even when -their ground bytes coincide. - -Each of the seven word choice levels costs `18+q(byte_order)`: binary -Congruence eleven, choice unfolding, and Transitivity seven. Two entrance -Transitivity rows cost fourteen. Thus every word request has 177 proof rows -and exact work `375 + sum(B(left[i],right[i]), i=0..7) + -sum(18+q(byte_order[i]), i=1..7)`. The constant 375 includes both entrance -unfoldings, their Transitivity rows, proof indexing, and final root comparison. -This gives 2,004 work for equal zero words and 10,644 for equal maximum words. -Ordering requests contain at most 531 ground terms, 768 proof rows, 10,757 work, -and 121,144 request bytes. All formulas and expected failures were fixed from -the checker rules and source templates before runtime observations. - -Rejections require the exact 33-byte owned diagnostic, process zero, and empty -stderr. Timeouts and process failures never count as proof results. Request -sizes and elapsed times are printed per vector; none establishes full-certificate -size or runtime. This gate proves only these finite equations under the complete -emitted theory; generic formation checks every encoder clause on every request. - -The [encoder fixtures](encoder.py) now also exercise encoder functions 58..107 -directly: 198 equations across fifteen batches covering the lexical predicates, -choosers, state/fragment accessors, list operations, admission, hexadecimal -parsing, the token automaton's steps and folds, classification, emission, -dispatch, scan flush and finalization, and two tiny end-to-end `encode` calls -(one valid, one rejected). They are produced by -[stepper.py](stepper.py), the generic formed-theory stepper that replays ground -applications through their stated clauses and emits ordinary certificate rows — -not a Beta parser or proof search. Seven encoder-range mutation vectors require -exact owned rejections: wrong clause, wrong result, forward premises, swapped -transitivity, an unconcluded root, and an empty proof table. - -These still do not close the complete obligation: the full-subject -`encode_Beta(S, 0x4000000, 0xfffffc) = Success(T)` derivation for the selected -evaluator measures 3,182,484 rows and 135,451,492 request bytes — 16.1 times -the request provision — so it is produced and measured but not admissible. -Accepted artifact custody remains outside this gate's claim. See the -[complete encoding acceptance](../beta_encoding/ACCEPTANCE.md) -and the [cost review](../../../../wiki/drafts/reference/bootstrap_cost_review.md). +Each family runs in its own checker request, checking every row including unused +ones. Lexical tests cover all 256 bytes for source admission, separators, +comment endings, and lowercase hex. Nibble joins use public-to-helper Unfold, +helper-to-byte Unfold, and Transitivity; splits cover every byte both ways; +round trips add two split Unfolds, two-premise Congruence, and Transitivity +because the checker never normalizes arguments implicitly. Word tests cover +zero, max, high bit, two mixed patterns, and a single nonzero byte in each of +all eight positions, least-significant byte first. + +Counter tests state both input and output words: zero, no-carry, two sets of +carry lengths 1..7, crossing the high bit, max minus one to max, and max to +`Overflow`. Success is `WordValue(Word)`; max never wraps to `WordValue(0)`. +Four 128-row batches cover every clause of byte increment and max-byte check +(the internal byte increment wraps 255 to 0, while public word successor returns +Overflow first). Each carry proof explicitly writes helper Unfold, predicate +Unfold, two branch Reflexivities, choice Congruence, choice Unfold, and +Transitivity steps, followed on success by byte increment Unfold, seven byte +Reflexivities, eight-argument Word Congruence, WordValue Congruence, and final +Transitivity. All proofs are fixed authored tables with no clause inspection or +search. + +Ordering returns `Less`, `Equal`, or `Greater`. Nibble tests cover all 256 +pairs; 12 byte tests cover equality, 0, 255, opposing nibbles, tied high +nibbles, and the high bit; 30 word tests cover equal words, both directions +across the high bit, every highest differing byte with opposing lower bytes, and +numeric comparisons around Beta's source limit `0x4000000` and output limit +`0xfffffc`. [ordering/proofs.py](ordering/proofs.py) unfolds all splits, nibble +comparisons, and choices with explicit Congruence and Transitivity rows: byte +proofs normalize both nibble comparisons, and word proofs prove all eight bytes +plus seven bottom-up choices plus both word unfoldings, with no search or clause +inspection. + +Negative tests keep wrong lexical answers, wrong clauses, altered bodies, and +wrong roots; add corrupted joins, swapped high/low splits, skipped helpers, bad +transitivity, swapped congruence premises, and unnormalized case selection; and +corrupt word byte order, list lengths, high bits, max values, each byte slot, +and invalid clauses. Expected failure offsets come from wire record sizes, never +from checker output. The 181 vectors also include 7- and 9-field Word records +that must fail ground validation with code 8 at the argument-count field +(separate from 7- and 9-byte output-list mutations). Counter negatives corrupt +helper clauses, skip condition normalization or choice Congruence, swap +condition premises, skip increment normalization, corrupt every result byte, and +reject wrapped zero for max. Ordering adds 32 negatives (keeping all 106 earlier +vectors): flipped nibble answers, skipped helpers, bad clauses, flipped nibble +priority, signed high-bit interpretation, ignored highest differing byte, +skipped normalization/Congruence, swapped premises, and altered final roots. + +Expected work counts come directly from checker accounting. Every batch pays +`P+1` for proof indexing and 4 for root checks. Lexical walks cost +`4*(1+...+256)` plus 5 per row and 3 extra per 16 Hex results; splits pay the +same nullary overhead plus two byte walks. Joins cost `high+low+24` (public +`high+11`, helper `low+6`, Transitivity 7); round trips cost +`2*byte+high+low+54` (adding 11 for Congruence and 7 for Transitivity). Each +word Unfold costs 70 (1 row, 1 clause, 18 index, 34 substitution, 16 variable +comparison); shared ground IDs make each structural check cost 2. The runner +checks the exact tag-7 count and work output. + +Counter byte helpers cost `byte+6` per row (+129 index, +4 root per 128-row +batch). Public word Unfold costs 46 (1 row, 1 clause, 10 index, 18 substitution, +16 variable checks); lower carry helpers cost 80 (1, 1, 16, 46 over 22 edges, +16); the top-byte helper costs 63 (1, 1, 15, 30 over 14 edges, 16). Repeated +variable templates hit the local memo after each of the eight variables pays its +initial 2-unit comparison. A predicate row costs `byte+6`, two branch +Reflexivities 6, choice Congruence 16, choice Unfold 8 (False) or 9 (True), and +three Transitivity rows 21. Final normalization costs `byte+81` (byte Unfold, 7 +Reflexivities = 21, Word Congruence = 41, WordValue Congruence = 6, Transitivity += 7). Including index and root, carrying `c=0..6` bytes and incrementing byte +`b` uses `21+9*c` rows and `290+402*c+2*b` work; carrying 7 bytes uses 84 rows +and `3087+2*b` work; max overflow uses 73 rows and 3,251 work. + +In ordering, each nibble pair `(l,r)` uses 3 rows costing `l+r+24`; a normalized +high/low nibble comparison of `(a,b)` uses 7 rows costing `a+b+l+r+54`. Byte +Unfold costs 38 (1 row, 1 clause, 10 index, 22 substitution over 10 edges, 4 +variable checks). Ordering choice costs 6 (Less), 9 (Equal, checking the bound +lower result), or 8 (Greater). With `q(L)=6`, `q(E)=9`, `q(G)=8`, a 19-row byte +proof has row work `B(a,b)=2*a+2*b+ah+al+bh+bl+171+q(high_order)` plus 24 for +index and root. Public word Unfold costs 51 (1, 1, 11, 20, 18); right-word +Unfold costs 128 (1, 1, 32, 62 over 30 edges, 32) because all 16 variable +templates are distinct. Each of seven word-choice levels costs +`18+q(byte_order)` (Congruence 11, choice Unfold, Transitivity 7), plus 14 for +two entrance Transitivity rows. Every word request has 177 rows and exact work +`375 + sum(B(left[i],right[i]), i=0..7) + sum(18+q(byte_order[i]), i=1..7)` +(2,004 for equal zero words, 10,644 for equal max words). Ordering requests stay +within 531 ground terms, 768 rows, 10,757 work, and 121,144 bytes. All formulas +were fixed before execution. + +Rejections require the exact 33-byte diagnostic, exit status 0, and empty +stderr; timeouts and process crashes never count as verdicts. Printed sizes and +times do not establish full-certificate size or speed. This gate proves only +these finite equations under the full theory (formation checks every clause on +every request). + +[encoder.py](encoder.py) exercises encoder functions 58..107 directly across 15 +batches (198 equations): lexical predicates, choosers, state/fragment accessors, +list ops, admission, hex parsing, token automaton steps/folds, classification, +emission, dispatch, scan flush/finalization, and two tiny `encode` calls (one +valid, one rejected). [stepper.py](stepper.py) generates these rows by replaying +ground calls through their clauses (not a parser or proof searcher). Seven +encoder mutations verify exact rejections for wrong clause, wrong result, +forward premise, swapped transitivity, unconcluded root, and empty proof table. + +These finite tests do not complete the full proof requirement: the full-subject +`encode_Beta(S, 0x4000000, 0xfffffc) = Success(T)` derivation measures 3,182,484 +rows and 135,451,492 request bytes (16.1× the earlier request limit), so it is +measured rather than accepted here. Artifact acceptance stays outside this gate; +see [complete encoding acceptance](../beta_encoding/ACCEPTANCE.md) and the +[cost review](../../../../wiki/drafts/reference/bootstrap_cost_review.md). diff --git a/tests/bootstrap/proofs/beta_encoding/ACCEPTANCE.md b/tests/bootstrap/proofs/beta_encoding/ACCEPTANCE.md index ee0c74d4724a..8e592170942a 100644 --- a/tests/bootstrap/proofs/beta_encoding/ACCEPTANCE.md +++ b/tests/bootstrap/proofs/beta_encoding/ACCEPTANCE.md @@ -1,86 +1,88 @@ # Complete Beta encoding acceptance -This is an optional research acceptance, outside the bootstrap construction -MVP. Existing full-subject measurements concern the source and tape at -`d19361fe4deae73e1b488a940a872fec1ed885cb`; they do not certify a later evaluator. +This optional research target sits outside the bootstrap construction MVP. +Existing full-subject measurements apply only to the source and tape at +`d19361fe4deae73e1b488a940a872fec1ed885cb`; they do not certify later +evaluators. -The first complete certificate establishes the independently reconstructed root: +The first complete certificate proves the independently reconstructed root: ```text encode_Beta(S, source_limit, output_limit) = Success(T) ``` -`S` is the entire selected Gamma evaluator's raw Beta source, including comments -and whitespace; `T` is its entire persisted Alpha tape. The -[evaluator profile](../../../../bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md) owns current identities. -The artifact owner fixes both subjects, the complete transparent Beta definition -package, encoding profile, and root independently of the certificate producer. -Neither a formed theory nor a producer-supplied theory identity authenticates -the definitions as Beta. +`S` is the selected Gamma evaluator's entire raw Beta source (including comments +and whitespace), and `T` is its persisted Alpha tape. The +[evaluator profile](../../../../bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md) +tracks current hashes. The artifact owner fixes both subjects, the full Beta +definition package, the resource profile, and the root independently of the +certificate producer. Neither a formed theory nor a producer-supplied hash +proves the definitions match Beta. ## Meaning of success -The encoder is an ordinary total error-valued definition, not a primitive -invoking Beta. `Success(T)` holds exactly for valid bounded source encoding -those bytes under [Beta's complete language](../../../../bootstrap/beta/LANGUAGE.md). -There is no unchecked well-formedness premise. Invalid source and exhausted -encoding capacity are distinct results; neither is generic checker Incomplete. - -The theorem projects admission and encoding from Beta's partial relation. It -need not reproduce rejected stdout prefixes, process status, diagnostic payloads, -or invalid-byte coordinates through successful traversal. That projection does -not change the compiler's envelope-first, exact-offset failure contract. -Every raw byte, malformed form, limit, and EOF obligation still belongs to the -total definitions. No unexamined suffix may reach Success. - -The complete theory covers ASCII, separators, comments, EOF, complete-token -lowercase registers/words, all 21 opcode/operand/width rows, little-endian words, -`dw`, address assertions, malformed input, source/output provisions, arithmetic -overflow, and exact/adjacent exhaustion. Do not formalize only cases occurring -in the customer. Fixed finite constructor words may represent limits without -unary millions; no trusted arithmetic, assembler, or hash shortcut is introduced. - -Equal tapes have identical deterministic Alpha behavior under the same input -and resource profile. This is not a proof that the Beta-written evaluator -implements Gamma. Byte comparison, assembler agreement, a digest, or an isolated -instruction proof cannot discharge the complete encoding root. +The encoder is a total error-valued definition, not a primitive calling Beta. +`Success(T)` holds if and only if valid bounded source encodes to those bytes +under [Beta's complete language](../../../../bootstrap/beta/LANGUAGE.md), with +no unchecked well-formedness premise. Invalid source and exhausted capacity are +distinct theory values, neither equal to checker Incomplete. + +This theorem captures admission and encoding from Beta's partial relation; it +need not reproduce rejected stdout prefixes, exit codes, diagnostic payloads, or +invalid-byte offsets on failing inputs. That does not relax the compiler's +envelope-first, exact-offset failure contract. Every raw byte, bad form, limit, +and EOF check stays in the total definitions, so no unexamined suffix can yield +Success. + +The complete theory covers ASCII, separators, comments, EOF, lowercase registers +and words, all 21 opcode/operand/width rows, little-endian words, `dw`, address +assertions, malformed inputs, source/output limits, overflow, and exact/adjacent +exhaustion — not only cases used by this subject. Fixed constructor words +represent limits without unary millions; no trusted arithmetic, assembler, or +hash shortcut is allowed. + +Equal tapes behave identically under Alpha for the same input and limits. This +does not prove the Beta-written evaluator implements Gamma. Byte comparisons, +assembler agreement, digests, or isolated instruction proofs cannot replace the +full encoding root. ## Composition and custody -The [generic checker](../checker/README.md) owns conservative definitions and -explicit equality rules. Artifact-specific definitions, independent root -reconstruction, and untrusted production stay here. Definitions are source-owned -and production runs through the selected chain, not a host semantic script. - -Closed intermediate equalities may retain source tails, encoder states, and -output fragments. Their composition establishes source and tape adjacency -separately, zero initial offsets, agreed intermediate states, exact endpoints, -and complete exhaustion. Trivia and assertions consume source but emit no bytes. -Cuts are witnesses; the owner fixes the composition theorem and endpoints. -There is no gap, overlap, dropped assertion, or historical two-pass label/fixup -requirement. Recursive definitions consume unchanged immediate constructor -children; a computed cursor is not a structural-decrease witness. - -Accepted closure retains exact owner, theory, checker, source/tape subjects, -profiles, derivation, and admissions. Each retained proof rule requires actual -full-certificate use, positive/mutation controls, and measured size consequences. -Unused convenience rules should not enlarge the checker. +The [generic checker](../checker/README.md) handles conservative definitions and +equality rules. Artifact definitions, independent root reconstruction, and +untrusted proof production stay here. Definitions are source-owned, and +production runs through the selected bootstrap chain, not a host script. + +Closed intermediate equalities may pass source tails, encoder states, and output +fragments. Composing them proves source/tape adjacency separately, zero initial +offsets, matching states, exact endpoints, and full input consumption. Trivia +and assertions consume source without emitting bytes. Cut points act as proof +hints while the owner fixes the composition theorem and endpoints. There are no +gaps, overlaps, dropped assertions, or two-pass fixups. Recursive definitions +consume unchanged immediate constructor children; a computed cursor never proves +structural decrease. + +Accepted closure pins the owner, theory, checker, source/tape subjects, +profiles, derivation, and checker outputs. Every kept proof rule needs full +certificate use, positive/mutation tests, and measured size impact; unused +convenience rules should not enlarge the checker. ## Acceptance and feasibility -Full-subject mutations cover source, tape, assertions, theory identity, rules, -clauses, substitution, premises, sorts, arities, partition joints, endpoints, -and final-root selection. Invalid or exhausted input cannot accept after a valid -prefix. Small generic rule tests are not this acceptance gate. - -Measure exact certificate/request bytes, retained proof state, comparison and -substitution scratch, semantic stack, cumulative allocation, production and -checking time. The checker's profile is distinct from Gamma's; raw evaluator -failures, host timeouts, and short observations are not proof verdicts. A complete -profile must fit all conjunctive requirements, not just the output tape. - -If proofs are too large, compare sharing and checked closed-lemma composition -before adding rules. A weaker root, unchecked recursion, trusted assembly rule, -or host stage requires [owner escalation](../../../../bootstrap/MINIMIZATION.md#owner-escalation). -The [encoder candidate](ENCODER_CANDIDATE.md) records the paused integration -approach; it is neither an accepted theory nor demonstrated resource fit. +Full-subject mutations must cover source, tape, assertions, theory identity, +rules, clauses, substitution, premises, sorts, arities, partition joints, +endpoints, and final-root selection. Invalid or exhausted input must never pass +after a valid prefix. Small generic rule tests do not meet this gate. + +Measure exact certificate/request bytes, live proof state, comparison and +substitution scratch, stack depth, cumulative pair allocation, and runtime. The +checker profile is distinct from Gamma's; evaluator crashes, timeouts, and +truncated outputs are never verdicts. A profile must satisfy all limits +together, not only tape size. + +If certificates grow too large, compare sharing and closed-lemma composition +before adding rules. Weakening the root, allowing unchecked recursion, adding a +trusted assembly rule, or adding a host stage requires +[owner escalation](../../../../bootstrap/MINIMIZATION.md#owner-escalation). The +[encoder candidate](ENCODER_CANDIDATE.md) records the paused design; it is +neither an accepted theory nor a proven resource fit. diff --git a/tests/bootstrap/proofs/beta_encoding/ENCODER_CANDIDATE.md b/tests/bootstrap/proofs/beta_encoding/ENCODER_CANDIDATE.md index aae781a89390..d6ade83afe38 100644 --- a/tests/bootstrap/proofs/beta_encoding/ENCODER_CANDIDATE.md +++ b/tests/bootstrap/proofs/beta_encoding/ENCODER_CANDIDATE.md @@ -1,36 +1,35 @@ # Paused complete encoder candidate -This temporary engineering note preserves one concrete integration candidate -for the [complete encoding subject](ACCEPTANCE.md). It is not current Beta -semantics, a demonstrated resource fit, or permission for isolated helper work. -Remove it when an integrated source-owned encoder supersedes the recipe, or an -explicitly assessed replacement strategy displaces it while preserving the -research proof objective. This is outside the bootstrap construction MVP. -Implementation status belongs on the bootstrap board. +This temporary note records one concrete integration design for the +[complete encoding subject](ACCEPTANCE.md). It is not current Beta semantics, a +proven resource fit, or authorization for isolated helper work. Delete it once +an integrated source-owned encoder or a better-evaluated design replaces it while +keeping the research proof goal. It sits outside the bootstrap construction MVP; +implementation status lives on the bootstrap board. ## Proposed computation -One total encoder entrance sequences complete raw-source envelope/capacity -admission, token-at-a-time scanning, one EOF flush with no pending operands, -and successful output-fragment flattening. The checker validates explicit -equalities; it does not run the encoder. Root reconstruction owns raw source, -tape, limits, and theory independently of proof production. +One total encoder entry runs raw-source envelope and capacity admission, +token-by-token scanning, an EOF flush requiring no pending operands, and +output-fragment flattening. The checker verifies explicit equalities rather than +running the encoder. Root reconstruction fixes the raw source, tape, limits, and +theory independently of proof production. -Use a mechanical raw-byte tree `Empty | Leaf(Byte) | Join(Source, Source)`, -not token- or instruction-selected partition boundaries. Recursion consumes an -unchanged immediate child. Incoming state carries comment mode, reversed pending -token, operand expectation, checked output count, and sticky failure, but no -completed-token list or accumulated output history. +Represent raw source as a mechanical byte tree +`Empty | Leaf(Byte) | Join(Source, Source)`, never split on token or instruction +boundaries. Recursion consumes an unchanged immediate child. Incoming state +holds comment mode, reversed pending token, operand expectation, checked output +count, and sticky failure — without a completed-token list or output history. -Valid tokens have at most 19 bytes including an assertion colon. This is not a -malformed-token resource bound: absent early rejection, pending tokens and their -reversals may span the complete admitted source. Cost and containment must cover -that case without inventing a token-capacity language outcome. +Valid tokens are at most 19 bytes including an assertion colon. That is not a +malformed-token cap: without early rejection, pending tokens and reversals can +span the entire admitted source, so cost and memory bounds must cover that case +without inventing a token-length language error. -Each scan result contains outgoing state and a fragment: -`Empty | Chunk(ByteList) | Join(Fragment, Fragment)`. A token emits at most eight -bytes; source joins combine fragments in source order while threading only state. -No empty-join simplifier is required. At final success: +Each scan step returns an updated state and a fragment +`Empty | Chunk(ByteList) | Join(Fragment, Fragment)`. One token emits at most +eight bytes; source joins combine fragments in source order while threading only +state, with no empty-join simplifier needed. On success: ```text flatten(Empty, tail) = tail @@ -38,15 +37,16 @@ flatten(Chunk(bytes), tail) = append(bytes, tail) flatten(Join(left, right), tail) = flatten(left, flatten(right, tail)) ``` -Append recurses on the unchanged list tail, flatten on unchanged fragment children. -Each output byte is appended once rather than once per source ancestor; explicit -flattening, projection, congruence, and root-equality proofs still cost work. +Append recurses on the unchanged list tail, and flatten on unchanged fragment +children. Each output byte appends once rather than once per source ancestor, +though flattening, projection, congruence, and root-equality proofs still cost +work. ## Token transitions -Retain complete-token register/HEXWORD parsers and explicit reversal, including -leading zeroes, lowercase spelling, width, and full exhaustion. Do not introduce -a separate character-recognizer framework. +Keep complete-token register and HEXWORD parsers with explicit reversal, +including leading zeroes, lowercase spelling, exact width, and full input +consumption, without adding a separate character-recognizer framework. | Expectation | Token | Next | | --- | --- | --- | @@ -56,52 +56,50 @@ a separate character-recognizer framework. | RX | Register | X | | RRX | Register | RX | -In Ready, all 21 mnemonic rows select exact opcode and expectation; emit the -opcode immediately, including operand-free `ret`. `dw` selects X without an -opcode. Assertions are legal only in Ready, equal the current output count, -and emit nothing. Unknown/inappropriate forms are Invalid. Registers emit one -byte; words use the shared eight-byte little-endian serializer. - -Intermediate fragments are not publication, so later wrong/missing operands -prevent Success without a whole-instruction buffer. Check nonwrapping count -growth and output capacity at each emission, retaining sticky exhaustion; -EOF-only checking could replace an earlier capacity refusal with a later syntax -failure. Separators flush tokens; semicolon flushes then enters comment mode; -CR/LF end comments. EOF flushes once and requires Ready, also after comments. -Complete envelope admission includes late comment bytes after a parser defect. -The total failure-selection equations still require audit against the selected -profile; this candidate does not amend compiler diagnostic precedence. +In Ready, all 21 mnemonics choose exact opcode and expectation and emit the +opcode immediately (including operand-free `ret`). `dw` enters X without an +opcode. Assertions are valid only in Ready, must equal the current output count, +and emit nothing. Unknown or misplaced tokens produce Invalid. Registers emit +one byte; words use the shared eight-byte little-endian serializer. + +Because intermediate fragments are not final output, later wrong or missing +operands block Success without a whole-instruction buffer. Check nonwrapping +count growth and output capacity on every emission, keeping sticky exhaustion; +checking only at EOF could mask an earlier capacity error behind a later syntax +error. Separators flush tokens; semicolons flush and enter comment mode; CR and +LF end comments. EOF flushes once and requires Ready, even after comments. Full +envelope admission still checks late comment bytes after a parser error. Total +failure-precedence equations still need audit against the chosen profile; this +note does not change compiler diagnostic precedence. ## Continuation condition -Pause isolated helper and provision expansion until one complete definition -package and integrated recipe has a defensible feasibility account. Cost all -theory declarations (including unused clauses), owner source/tape/limits/root, -admission, scan joins and projections, reversals/parsers, opcode dispatch, -serialization, count/limit/assertion checks, failure propagation, fragments, -flattening, equality, framing, cumulative allocation, depth, and execution time. -State-dependent composition cannot assume that shared local token facts eliminate -its work. Distinguish measured costs, algebraic recipe scenarios, and missing -quantities; there is no established complete cost or justified larger profile. - -Use the existing theory entrance with source admission, token recognition, -instruction/emission transitions, and output composition as subordinate owners. -Keep arithmetic shared and create files only when actual definitions require -them. Select a coherent profile only after the complete package and recipe -expose all costs and their sharing assumptions. Package completion alone does -not close the source-owned certificate, mutation/resource controls, or admission. -The pause does not abandon P1, authorize a new language/checker rule or host -producer, or block independent bootstrap work. Ordinary engineering choices -remain engineering choices, not unresolved language decisions. - -The [cost review](../../../../wiki/drafts/reference/bootstrap_cost_review.md) now carries a -derived integrated ledger for this candidate against the historical 47,756-byte -subject at `d19361fe4deae73e1b488a940a872fec1ed885cb`. Measured there: the -state census (17,130 distinct leaf states with -count in state, 1,521 without), the shared successor counter at 2,122,796 -work and 4,667,320 request bytes, and the ~675,017 physical work ceiling under -the selected pair arena. Its verdict: this architecture removes the physically -blocking history carriage — the required direction — but every derivable -scenario still lands an order of magnitude over the selected provisions, so -the pause stands until the complete package and integrated recipe pin the -coefficients that remain extrapolated. +Pause isolated helper and budget expansion until one complete definition package +and integrated proof recipe has a defensible feasibility budget. Account for +every theory declaration (including unused clauses), owner source/tape/limits +and root, admission, scan joins and projections, reversals and parsers, opcode +dispatch, serialization, count/limit/assertion checks, error propagation, +fragments, flattening, equality, framing, cumulative allocation, depth, and +runtime. State-dependent composition cannot assume shared local token proofs +erase its cost. Separate measured numbers, algebraic projections, and missing +quantities; no complete cost or larger budget is justified yet. + +Keep the existing theory entry point with source admission, token recognition, +instruction/emission transitions, and output composition as helper modules. Keep +arithmetic shared and add files only when definitions need them. Pick a coherent +budget only after the complete package and recipe expose all costs and sharing +assumptions. Finishing the package alone does not close the source-owned +certificate, mutation/resource tests, or acceptance. Pausing neither abandons P1 +nor authorizes new language rules, checker rules, or host producers, nor blocks +other bootstrap work. Ordinary engineering choices stay engineering choices, not +language questions. + +The [cost review](../../../../wiki/drafts/reference/bootstrap_cost_review.md) +holds a derived ledger for this design on the historical 47,756-byte subject at +`d19361fe4deae73e1b488a940a872fec1ed885cb`: the state census (17,130 distinct +leaf states with count in state, 1,521 without), the shared successor counter +(2,122,796 work and 4,667,320 request bytes), and the ~675,017 work ceiling +under the old pair arena. Its verdict: removing output-history carriage is the +right direction, but every derived scenario still exceeds the selected budgets +by an order of magnitude, so the pause stands until the complete package and +recipe pin the extrapolated coefficients. diff --git a/tests/bootstrap/proofs/beta_encoding/PROFILE.md b/tests/bootstrap/proofs/beta_encoding/PROFILE.md index 992bfe3edec6..eb170fdbc978 100644 --- a/tests/bootstrap/proofs/beta_encoding/PROFILE.md +++ b/tests/bootstrap/proofs/beta_encoding/PROFILE.md @@ -2,48 +2,43 @@ [Theory and ownership](README.md) | [Executable gate](../beta-encoding-theory/README.md) -This profile covers the current source-owned theory emitter and finite -diagnostic equations. It is not a profile for the certificate producer or -the accepted whole-source artifact. +This profile covers the source-owned theory emitter and finite diagnostic +equations. It does not profile the certificate producer or the accepted +whole-source artifact. ## Emitter -The marked test entry plus the exact thirty-two-member source closure is 3,415 -lines, 130,574 bytes, SHA-256 -`821150c880278ed80c03a3fb0d6a49127fcb2fa6aa158e1baa89d2bd952fd56e`. -Its only admitted input is empty; framing occupies 130,578 bytes. Nonempty input -returns status 1 without publishing output. The fixed emitted section is -116,900 bytes, SHA-256 -`6bbdd15abac8060a9c5718f58944f758c5c647c1aae827d92f61231b01c3987c`. -The test-owned pins bind these exact bytes; they are diagnostic custody checks, -not arithmetic operations, checker rules, or artifact authority. - -The composition has 126 Gamma functions, maximum arity ten, twelve nested -expression-body lists, and at most 440 simultaneously active bindings in the -generated automaton-clause emitter. -All constructor, clause, function, variable, cell, and administrative-word loops -are tail calls with fixed finite iteration counts. The emitter allocates no -pairs; its marked entry allocates one outcome pair. - -A source call-path audit allows seventeen contexts and eighteen frames, -including pending calls while arguments are evaluated. Ignoring tail-call -savings, the longest acyclic function route has fifteen functions, through the -theory/vocabulary/encoder-vocabulary/scalar-constructor/word writers. Pending -classification while a clause call is being prepared is also included. Tail-only -self loops do not accumulate contexts. Thus `18 * 450 = 8100` binding rows -suffice. Allow sixteen argument/helper slots per expression level and thirteen -levels per frame: at most `18 * 13 * 16 + 32 = 3776` temporary entries, below -the evaluator's 524,288. -These are conservative source bounds, not measured runtime peaks. A changed -closure or entry requires a fresh audit. +The marked test entry plus the 32-member source closure is 3,415 lines and +130,574 bytes (SHA-256 +`821150c880278ed80c03a3fb0d6a49127fcb2fa6aa158e1baa89d2bd952fd56e`). It accepts +only empty input (130,578 framed bytes); nonempty input exits with status 1 and +empty output. The emitted section is 116,900 bytes (SHA-256 +`6bbdd15abac8060a9c5718f58944f758c5c647c1aae827d92f61231b01c3987c`). Test pins +check these exact bytes for integrity; they are not arithmetic operations, +checker rules, or artifact authentication. + +The emitter has 126 Gamma functions, max arity 10, at most 12 nested body lists, +and at most 440 active bindings in the generated automaton-clause emitter. All +constructor, clause, function, variable, cell, and header loops are tail calls +with fixed finite counts. The emitter allocates zero pairs; its marked entry +allocates one result pair. + +A static call-path audit needs at most 17 call contexts and 18 frames, counting +pending calls during argument evaluation. Ignoring tail calls, the longest +acyclic call chain is 15 functions through the theory, vocabulary, +encoder-vocabulary, scalar-constructor, and word writers, plus pending +classification during clause calls; tail-only self-loops add no contexts. Thus +`18 * 450 = 8100` binding rows suffice. Allowing 16 slots per expression level +and 13 levels per frame gives at most `18 * 13 * 16 + 32 = 3776` temporaries, +well below the evaluator's 524,288 limit. These are conservative static bounds, +not runtime peaks; any change to the closure or entry needs a fresh audit. ## Checked finite requests -The generic checker diagnostic is 63,512 bytes under -the [existing checking profile](../checker/CHECKING.md). -The emitted theory has `S=18, C=361, A=40, F=107, W=29224`; its formation work -estimate is 163,160. Every supplied clause and proof row is checked, including -ones not used by the final root. +The generic checker diagnostic is 63,512 bytes under the +[existing checking profile](../checker/CHECKING.md). The emitted theory has +`S=18, C=361, A=40, F=107, W=29224` and a formation work estimate of 163,160. +Every clause and proof row is checked, including unused ones. | Positive batch | Proof rows | Required cumulative checking work | | --- | ---: | ---: | @@ -73,62 +68,55 @@ ones not used by the final root. | Tiny end-to-end encode, valid | 7,657 | 123,466 | | Tiny end-to-end encode, rejected | 6,145 | 100,183 | -The encoder batches are produced by -[stepper.py](../beta-encoding-theory/stepper.py), the generic -formed-theory stepper that replays ground applications through their stated -clauses and emits the ordinary certificate rows. Their equations are declared -in [encoder.py](../beta-encoding-theory/encoder.py); every -batch is checked by the unchanged generic checker. The largest encoder request -is 418,156 bytes (the valid end-to-end encode). - -The [gate's work derivations](../beta-encoding-theory/README.md) -count clause selection, indexing, every visit/resumption, ground comparisons, -explicit rules, and final-root checks independently of observed output. A Word -unfolding includes seventeen template visits, seventeen resumptions, and sixteen -ground-comparison transitions; none of its eight fields is an unchecked byte copy. - -The largest request is 188,888 bytes and the largest ground table has 1,552 -rows, both in the round-trip batch. Including checker source and framing gives -252,396 bytes. Across these finite families, the generic cumulative pair bound -is at most `63752 + 137781 * 48 + 128 = 6677368`, below the selected arena's -3,422,453,760 pairs. Each vector is a separate evaluator invocation; these figures -do not claim that unrelated certificates can reset accounting mid-request. -Malformed Word arities and semantic corruptions must publish exact owned -rejections. A timeout, evaluator failure, or short observation is not a verdict. - -The counter cases explicitly compose carry selection and increment through -ordinary proof rules. The maximum-Word case proves Overflow, not a resource -refusal or a wrapped successful value. These finite requests fit the current -checking profile; they do not establish the cost of a full-source certificate. - -Ordering cases compare all 256 nibble pairs, literal byte priority examples, -and complete words including every highest-differing byte position and exact/ -adjacent Beta capacity words. The word recipe explicitly normalizes all eight -byte comparisons before composing the ordering chain; even a decisive high byte -does not hide unchecked fixture rows. The ordering requests use at most -144,996 bytes, 531 ground terms, 768 proof rows, and 10,757 checking work. - -On macOS arm64, the full gate passed two identical emissions, three nonempty-input -producer refusals, and all 181 exact checker diagnostics. Emission took -2.453..3.035 seconds; the exhaustive nibble-ordering batch took 14.221 seconds. -The twelve byte-comparison cases took 9.520..9.701 seconds and the thirty -word-comparison cases took 10.329..10.739 seconds. These are scoped -observations, not semantic limits or portable -performance guarantees. +[stepper.py](../beta-encoding-theory/stepper.py) generates the encoder batches +by replaying ground calls from [encoder.py](../beta-encoding-theory/encoder.py) +through their clauses into ordinary certificate rows, checked by the unchanged +generic checker. The largest encoder request is 418,156 bytes (valid end-to-end +encode). + +The [gate's work derivations](../beta-encoding-theory/README.md) derive clause +selection, indexing, visit/resume steps, ground comparisons, rule checks, and +root checks independently of runtime output. One Word unfolding takes 17 +template visits, 17 resumptions, and 16 ground comparisons; none of its eight +bytes is copied unchecked. + +Among the non-encoder batches, the round-trip batch is largest at 188,888 bytes +and 1,552 ground terms (252,396 framed bytes with checker source). Across these +finite families, the pair bound stays at most +`63752 + 137781 * 48 + 128 = 6677368`, well inside the 3,422,453,760-pair arena. +Each vector runs in its own evaluator process; accounting never resets +mid-request. Bad Word arities and semantic corruptions must return exact +checker rejections; timeouts, evaluator failures, and truncated outputs are +never verdicts. + +Counter proofs compose carry selection and increment via ordinary rules. The +max-Word case proves Overflow rather than wrapping or hitting a resource error. +These finite requests fit the checking profile without establishing the cost of +a full-source certificate. + +Ordering proofs cover all 256 nibble pairs, byte priority cases, and full words +covering every highest differing byte plus exact/adjacent Beta capacity limits. +Word proofs normalize all eight byte comparisons before combining them, so a +decisive high byte never hides unchecked rows. Ordering requests use at most +144,996 bytes, 531 ground terms, 768 proof rows, and 10,757 work. + +On macOS arm64, the gate passed two identical emissions, three nonempty-input +refusals, and all 181 checker diagnostics: emission took 2.453..3.035 s, +exhaustive nibble ordering 14.221 s, the 12 byte comparisons 9.520..9.701 s, +and the 30 word comparisons 10.329..10.739 s. These are scoped observations, +not semantic limits or portable speed guarantees. ## Full-subject certificate measurement -The following figures remain bound to the exact Gamma source and tape at -`d19361fe4deae73e1b488a940a872fec1ed885cb`. The reproduction tool reads and -hash-checks those historical Git artifacts. No measurement below was repinned -to the current evaluator, and none gates ordinary bootstrap construction. +The measurements below apply only to the historical Gamma source and tape at +`d19361fe4deae73e1b488a940a872fec1ed885cb`, read and hash-checked directly from +Git. None was repinned to the current evaluator, and none gates ordinary +bootstrap work. -The same stepper independently reconstructed the owner-fixed proposition -`encode_Beta(S, 0x4000000, 0xfffffc) = Success(T)` for the complete historical -subject — the 47,756-byte evaluator Beta source as a midpoint-split Source -tree (22,339 interned owner terms; the tree shares identical subtrees) and -the 8,575-byte persisted tape — and produced the complete untrusted -derivation in 24.1 seconds at ~2.8GB peak RSS on macOS arm64: +The stepper reconstructed `encode_Beta(S, 0x4000000, 0xfffffc) = Success(T)` for +that historical subject — the 47,756-byte Beta source as a midpoint-split Source +tree (22,339 interned owner terms) and the 8,575-byte tape — and produced the +full untrusted derivation in 24.1 s at ~2.8 GB peak RSS on macOS arm64: | Quantity | Measured | | --- | ---: | @@ -140,61 +128,46 @@ derivation in 24.1 seconds at ~2.8GB peak RSS on macOS arm64: | Total request bytes | 135,451,492 — inside the selected 136,314,880-byte request extent | | Projected checker work | ~45-52M — ~70-80 times the 655,360 provision and the ~675,017 pair ceiling | -The derivation value is exactly `Success(T)` for the real tape. Every figure -above was reproduced exactly from the checked-in stepper at `6a1751fe08` on -macOS arm64 (24.2 seconds), including owner/witness counts, the per-rule row -totals — which contain no symmetry rows — and the 204 maximum premise depth -(a premise-free row counts depth one). The same figures were reproduced a -second time on Linux x86-64 at `87d8b22713ff` under Python 3.10: the -sha256-pinned host-side theory reconstruction, the midpoint-split owner -proposition, and the full emission completed in 23.8 seconds at ~2.3 GiB peak -RSS with byte-identical section sizes and per-rule totals. -The gated mode `tests/bootstrap/proofs/beta-encoding-theory/run.sh --full-subject` -reproduces the production on any host with python3 — no evaluator seed is -materialized — pinning the theory reconstruction, both subject identities, -and every emitted figure so the run fails loudly on drift. Under its -documented floor-half midpoint partition the owner table measures 22,253 -terms / 532,144 bytes and the complete request 135,485,028 bytes -(3,182,974 rows: 1,018,733 unfold / 1,157,751 transitivity / 936,662 -congruence / 69,828 reflexivity / 0 symmetry, maximum premise depth 204, -~30 seconds and ~2.3 GiB on Linux x86-64), a ~0.03% table-size difference -from the first production above, whose ad-hoc partition detail was not -retained; the same equation derives under both, and both fit the selected -provisions. The mode also emits the retained-role census the audit needs: -every proof rule appears except symmetry, all 107 theory functions unfold, -359 of 361 constructors appear in terms (S_EMPTY and A_EXHAUSTED do not — -this subject has no empty spans and its admission never exhausts), and -1,911 of the 2,811 declared clauses appear as unfolding premises. The -retained-role audit is resolved: symmetry stays as one of the five -owner-fixed rules; the single never-unfolded member — the TokenClass -chooser, function 62 — had no clause-body caller and was removed; S_EMPTY -and A_EXHAUSTED stay as the Source base case and the contract-required -distinct exhaustion admission; and the unexercised clauses remain because -function totality over malformed input is part of the complete-theory -contract. -The same gap blocks production through the selected chain: the certificate -exceeded the evaluator's former 16,777,212-byte buffered-output provision; -the AlphaBootstrapV5 provision is 135,266,304 bytes. -Owner decision `beta-encoding-certificate-admission` settles admission on the -native-backing route, recorded at the -[checking ledger](../checker/CHECKING.md#complete-generic-execution-provision); -the buffered-output provision is one of the extents that grows with it. -The coupled provisions that ledger selects are landed: the checker's -`implementation/admission/extents.gamma` admits requests up to the -136,314,880-byte request extent, which the 135,485,028-byte request fits; -`implementation/comparison/session.gamma` carries the 67,108,864-unit work -counter; and the AlphaBootstrapV5 extent supply frames the request in the -137,363,456-byte evaluator frame and admits 3,422,453,760 pair nodes, above -the selected 3,387,293,850-pair arena. A complete checking run under these -provisions remains unexecuted: the projected work uses the measured -13.9-16.5 work/row across the checked encoder batches, and the 2026-09-27 -macOS arm64 evaluator run reached the 43,200-second host timeout without -`Checked`. -This is one straightforward producer shape, not a lower bound; -the [cost review](../../../../wiki/drafts/reference/bootstrap_cost_review.md) records the -named reduction levers and confirms the remaining shortfall is structural. - -Windows runtime validation is unavailable in this session. The gate documents -the same shell/Python entrypoint for Windows x64 (Git Bash), macOS arm64, and Linux x86-64. -Full-source certificate acceptance remains open on the resource routes named -in the cost review. +The derived result is `Success(T)` for the real tape. The checked-in stepper +reproduced every number at `6a1751fe08` on macOS arm64 (24.2 s, 0 symmetry rows, +max premise depth 204 where a premise-free row has depth 1), and again on Linux +x86-64 at `87d8b22713ff` under Python 3.10 (23.8 s, ~2.3 GiB peak RSS, +byte-identical sizes and row counts). Running +`tests/bootstrap/proofs/beta-encoding-theory/run.sh --full-subject` reproduces +production on any python3 host without an evaluator seed, pinning the theory +reconstruction, subject hashes, and all counts to catch drift. With its +floor-half midpoint split, the owner table has 22,253 terms / 532,144 bytes and +the complete request is 135,485,028 bytes (3,182,974 rows: 1,018,733 unfold / +1,157,751 transitivity / 936,662 congruence / 69,828 reflexivity / 0 symmetry, +max depth 204, ~30 s and ~2.3 GiB on Linux x86-64) — a ~0.03% size difference +from the first run's unpinned split, deriving the same equation within the +chosen limits. + +The census from that run resolved the retained-role audit: every rule except +symmetry appears, all 107 theory functions unfold, 359 of 361 constructors +appear (S_EMPTY and A_EXHAUSTED do not), and 1,911 of 2,811 clauses unfold. +Symmetry stays as one of the five core rules; the uncalled TokenClass chooser +(function 62) was removed; S_EMPTY and A_EXHAUSTED stay for the Source base case +and distinct exhaustion results; and unexercised clauses stay for totality on +malformed inputs. + +The certificate also exceeded the evaluator's former 16,777,212-byte output cap; +AlphaBootstrapV5 raised that cap to 135,266,304 bytes. Owner decision +`beta-encoding-certificate-admission` chose larger native memory backing +([checking ledger](../checker/CHECKING.md#complete-generic-execution-provision)). +All coupled limits are now landed: `implementation/admission/extents.gamma` +allows 136,314,880-byte requests (fitting the 135,485,028-byte request), +`implementation/comparison/session.gamma` sets the 67,108,864-unit work cap, and +AlphaBootstrapV5 supplies the 137,363,456-byte evaluator frame and +3,422,453,760 pair nodes (above the 3,387,293,850-pair bound). A full checking +run still has not finished: projected work comes from 13.9–16.5 work/row on the +encoder batches, and the 2026-09-27 macOS arm64 run hit the 43,200-second +timeout without reaching `Checked`. This producer is one straightforward design, +not a lower bound; the +[cost review](../../../../wiki/drafts/reference/bootstrap_cost_review.md) lists +reduction options and confirms the remaining gap is structural. + +Windows runtime validation was not run in this session; the gate shares one +shell/Python entry point for Windows x64 (Git Bash), macOS arm64, and Linux +x86-64. Full-source certificate acceptance remains open on the routes in the +cost review. diff --git a/tests/bootstrap/proofs/beta_encoding/README.md b/tests/bootstrap/proofs/beta_encoding/README.md index 51a375a32282..8341b5756f33 100644 --- a/tests/bootstrap/proofs/beta_encoding/README.md +++ b/tests/bootstrap/proofs/beta_encoding/README.md @@ -1,57 +1,49 @@ # Beta encoding theory -[theory/theory.gamma](theory/theory.gamma) emits the source-owned transparent -Beta definitions: byte classification, nibble conversion, fixed-width words, -their little-endian byte lists, checked counter increment, unsigned comparison, -and the complete error-valued encoder over the raw source tree. -It does not emit an assembler, owner-root reconstruction, or whole-source -certificate. - -The [complete encoding contract](ACCEPTANCE.md) -fixes the acceptance target: the entire selected Gamma evaluator's raw Beta -source and persisted Alpha tape under the complete error-valued encoder. -Keep artifact-specific definitions and eventual root reconstruction/proof -production here, separate from the [generic checker](../checker/README.md). -Formation and generic proof success do not make a partial or producer-selected -Beta theory authoritative. +[theory/theory.gamma](theory/theory.gamma) emits the source-owned Beta encoder +definitions: byte classification, nibble conversion, fixed-width words, +little-endian byte lists, checked counter increment, unsigned comparison, and +the complete error-valued encoder over the raw source tree. It does not emit an +assembler, root reconstruction, or full-source certificate. + +The [complete encoding contract](ACCEPTANCE.md) sets the target: the selected +Gamma evaluator's full Beta source and persisted Alpha tape under the complete +error-valued encoder. Artifact-specific definitions, root reconstruction, and +proof production stay here, separate from the [generic checker](../checker/README.md). +Passing formation or generic proof checking does not prove that a partial or +producer-chosen theory matches Beta. ## Source organization -The current [source closure](theory/theory.gamma.sources) is ordinary -Gamma, executed by the selected Beta-authored Gamma evaluator. The entrance -orders vocabulary and function definitions; `vocabulary.gamma` owns sorts and -constructors, `definitions.gamma` sequences the lexical, nibble, word, and -counter definitions, and their subordinate files own the individual equations. -`definitions/counters.gamma` orders byte helpers, result selection, carry -stages, and the public successor; `definitions/counters/` owns those pieces -and their fixed template writers. -`definitions/ordering.gamma` orders nibble, byte, and word comparisons; -`definitions/ordering/` owns those equations. `definitions/encoding.gamma` -orders the fifty encoder definitions after function 57, and -`definitions/encoding/` owns the individual equations. Shared -administrative-field and template writers live in `encoding/`, not in either -arithmetic component. -The checker receives Gamma-emitted package bytes, not host-generated -definitions. No new checker primitive is introduced. - -The packed member closure materializes 3,408 lines / 130,363 bytes, SHA-256 -`632871b5c22c22a0ba397ad4dc6054af797a364f789570e6b25be08840b41ddf`. -The manifest itself is 5,536 bytes, SHA-256 -`f93d98315b2197d81babcc8b3345a1df0e4eb219bf7e5c3288132ec2d3fe2e5d`; -`tests/bootstrap/proofs/sources_env.sh` checks both identities against every -materialization. The [archived identity tests](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/proofs-identity.sh) record the refusal cases. -A digest is an identity check on the member bytes, not artifact authority for -the theory. +The [source closure](theory/theory.gamma.sources) is ordinary Gamma run by the +selected Beta-authored evaluator. The entry file sequences vocabulary and +definitions: `vocabulary.gamma` declares sorts and constructors; +`definitions.gamma` orders lexical, nibble, word, and counter definitions; +`definitions/counters.gamma` and `definitions/counters/` implement byte helpers, +result selection, carry stages, and successor; `definitions/ordering.gamma` and +`definitions/ordering/` implement nibble, byte, and word comparison; +`definitions/encoding.gamma` and `definitions/encoding/` implement the 50 +encoder functions after function 57; and `encoding/` holds shared wire-field and +template writers. The checker consumes Gamma-emitted bytes rather than +host-generated definitions, with no new checker primitive. + +Packing the closure yields 3,408 lines / 130,363 bytes (SHA-256 +`632871b5c22c22a0ba397ad4dc6054af797a364f789570e6b25be08840b41ddf`). The manifest +is 5,536 bytes (SHA-256 +`f93d98315b2197d81babcc8b3345a1df0e4eb219bf7e5c3288132ec2d3fe2e5d`). +`tests/bootstrap/proofs/sources_env.sh` checks both hashes on every assembly; +the [archived identity tests](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/proofs-identity.sh) +record refusal cases. A hash verifies source bytes, not theory authenticity. ## Constructor vocabulary -Byte is a finite free-constructor sort, not a checker integer. Its 256 nullary -constructors denote exactly the 256 byte values. Nibble likewise has sixteen -nullary constructors. This keeps byte classification to one explicit case step -without unary numeric spines, invalid byte inhabitants, or trusted arithmetic. -Constructor row identities only name symbols; the calculus cannot add them or -infer a numeric ordering from them. The future source/tape owner must map raw -bytes to these exact constructors independently of the certificate producer. +Byte is a finite free-constructor sort, not a checker integer: its 256 nullary +constructors represent byte values 0..255, and Nibble has 16 nullary +constructors. This lets byte classification run in one case step without unary +counters, invalid inhabitants, or trusted arithmetic. Constructor IDs only name +symbols; the calculus cannot add or compare them numerically. The artifact owner +must map raw source and tape bytes to these exact constructors independently of +the certificate producer. | Sort | Identity | Constructors, in exact wire order | | --- | ---: | --- | @@ -74,17 +66,15 @@ bytes to these exact constructors independently of the certificate producer. | TokenClass | 17 | TEmpty 352, TInvalid 353, TDw 354, TRegister 355 takes Byte, TWord 356 takes Word, TAssert 357 takes Word, TMnemonic 358 takes Byte opcode and Expect. | | EncodeResult | 18 | RInvalid 359; RExhausted 360; RSuccess 361 takes one ByteList. | -Every constructor term is finite. Word has exactly the unsigned 64-bit value -domain: eight independent Byte positions, with no shorter, wider, or sign-tagged -inhabitants. It is not a Gamma integer and no checker arithmetic interprets it. -ByteList is a free finite list, suitable for source and tape without a unary -numeric counter. Raw-byte/word custody still belongs to the future artifact owner. +Every constructor term is finite. Word represents the exact unsigned 64-bit +domain as eight Byte fields (no shorter, wider, or signed forms) without Gamma +integer arithmetic. ByteList is a free finite list for source and tape bytes. +Mapping raw bytes and words remains the artifact owner's responsibility. ## Lexical definitions -The first four functions each take one Byte, select argument zero in mode 1, -and have exactly 256 clauses in Byte-constructor order. Their bodies contain -only constructors, never recursion or assumptions. +Functions 1..4 each take one Byte, match argument zero in mode 1, and list 256 +constructor-only clauses in Byte order with no recursion or assumptions. | Function identity | Result | Definition from the Beta contract | | ---: | --- | --- | @@ -93,11 +83,10 @@ only constructors, never recursion or assumptions. | 3 `comment_end` | Bool | True for LF and CR. EOF is not a byte. | | 4 `hex_digit` | HexResult | Hex(0..9) for `0`..`9`, Hex(10..15) for `a`..`f`, otherwise NoHex. | -These are independent properties: a printable uppercase letter is admitted -source but not a hexadecimal digit. A semicolon starts a comment; it is neither -a separator nor a comment ending. The eventual encoder must check the source -envelope even inside comments, handle the semicolon and EOF, and require whole -tokens. Classification alone cannot establish any of those scanning claims. +These predicates are independent: printable uppercase letters are valid source +bytes but not hex digits, and a semicolon starts a comment without being a +separator or comment ending. The encoder must still enforce the source envelope +inside comments, handle semicolons and EOF, and require whole tokens. ## Nibbles and words @@ -109,32 +98,27 @@ tokens. Classification alone cannot establish any of those scanning claims. | 23 `low_nibble` | `Byte -> Nibble` | Select the low four-bit value by a complete 256-case table. | | 24 `word_bytes` | `Word -> ByteList` | Preserve all eight Word children in low-to-high list order, ending in Nil. | -Each helper has sixteen constructor-only clauses; function 21 has sixteen -clauses calling strictly earlier helpers. Its high-nibble parent slot is -unbound, and its low-nibble argument remains slot 1. Splitting a byte introduces -no primitive division or remainder: the checker sees only constructor cases. - -`word_bytes(Word(b0,b1,b2,b3,b4,b5,b6,b7))` has one clause, producing the exact -list `Cons(b0, Cons(b1, ... Cons(b7, Nil)))`. Its eight variables are the immediate -Word children in slots 1..8. Its templates list those variables first, then Nil, -then eight Cons applications with strictly backward references. This is a total -definition for all 2^64 constructor words, not a customer-specific byte pattern. -It supplies the fixed-width serialization needed by every Beta `x` operand and -`dw`, but not their token parser or complete encoder. - -Unfolding `byte_from_nibbles` yields a helper application, not a silently -evaluated byte. A round-trip proof must supply both nibble equalities, congruence -to replace the join arguments, the two defining steps for the join, and their -explicit transitive composition. Likewise `word_bytes` preserves any defined -applications inside its Word argument rather than normalizing them implicitly. +Each helper has 16 constructor-only clauses; function 21 has 16 clauses calling +strictly earlier helpers, with its matched high-nibble slot unbound and low +nibble in slot 1. Byte splitting uses pure constructor lookup with no division +or remainder primitive. + +`word_bytes(Word(b0,b1,b2,b3,b4,b5,b6,b7))` has one clause producing +`Cons(b0, Cons(b1, ... Cons(b7, Nil)))` from slots 1..8, listing those variables +first, then Nil, then eight Cons rows. This total definition covers all 2^64 +words and handles fixed-width serialization for Beta `x` operands and `dw`. + +Unfolding `byte_from_nibbles` produces a helper call rather than evaluating to a +byte immediately. Round-trip proofs must give both nibble equalities, +congruence, both join unfoldings, and transitivity. Likewise, `word_bytes` keeps +unevaluated expressions inside its Word fields. ## Checked counters -The encoder needs exact source and output lengths for capacity checks and -address assertions. `word_successor` returns `WordValue(w + 1)` for every Word -below `2^64 - 1`, and `Overflow` at that maximum. This is unsigned arithmetic -over the fixed eight-byte representation, not Gamma's signed comparison or -wrapping integer arithmetic. Crossing the highest signed bit remains a success. +`word_successor` supports exact source/output length checks and address +assertions, returning `WordValue(w + 1)` for every Word below `2^64 - 1` and +`Overflow` at the maximum. It performs unsigned arithmetic on eight bytes, never +Gamma's signed or wrapping arithmetic, so crossing the high bit succeeds. | Function identity | Signature | Defining behavior | | --- | --- | --- | @@ -144,27 +128,21 @@ wrapping integer arithmetic. Crossing the highest signed bit remains a success. | 28..35 | `(Byte b0, ..., Byte b7) -> WordResult` | Carry stages for positions 7 down to 0, respectively. | | 36 `word_successor` | `Word -> WordResult` | Decompose all eight bytes and begin carry propagation at position zero. | -A carry stage checks whether its byte is maximal. If not, it increments that -byte, preserves every other position, and returns WordValue. Otherwise it passes -zero in that position to the earlier, higher-position helper. Carry beyond -position seven returns Overflow. The eight fixed stages need no recursive word -spine; all function dependencies point backward. Only the private byte helper -wraps: the public result never silently wraps a maximal Word to zero. +Each carry stage checks whether its byte is 255. If not, it increments that +byte, keeps the other seven, and returns WordValue. Otherwise it passes zero in +that position to the earlier higher-byte helper; carry past byte 7 returns +Overflow. All eight stages depend strictly backward with no recursion, and the +public function never silently wraps a maximal Word to zero. -Explicit derivations must rewrite the Boolean condition before selecting a -branch, then unfold the selected continuation. Unchosen branches need no -normalization. Overflow here is an ordinary value in the Beta theory, distinct -from the generic checker's resource refusal: neither asserts that an exhausted -checker has proved a result. Checked increment does not by itself establish -complete limit enforcement or source/token traversal. +Proofs must rewrite the Boolean condition before unfolding the chosen branch; +unchosen branches need no normalization. Overflow is an ordinary theory value, +distinct from a checker resource error. ## Unsigned comparison -`word_compare(left, right)` returns Less, Equal, or Greater over the full -unsigned 64-bit Word domain. Address assertions need Equal; source/output -capacity checks need to distinguish Less from Equal and Greater. The comparison -does not use Gamma's signed ordering, subtract words, or wrap a difference. -The highest bit therefore has ordinary positive unsigned weight. +`word_compare(left, right)` returns Less, Equal, or Greater over all unsigned +64-bit Words for address assertions and capacity checks. It never uses Gamma's +signed ordering or wrapping subtraction, so the high bit has positive weight. | Function identity | Signature | Defining behavior | | --- | --- | --- | @@ -175,122 +153,91 @@ The highest bit therefore has ordinary positive unsigned weight. | 56 `word_compare_right` | `(Byte left0, ..., Byte left7, Word right) -> Ordering` | Decompose right and combine the eight byte comparisons. | | 57 `word_compare` | `(Word left, Word right) -> Ordering` | Decompose left, then call the right-word helper. | -Nibble helpers enumerate all 256 ordered pairs. Byte comparison reuses the -existing high/low nibble definitions; word comparison examines byte seven down -to byte zero. The first differing position decides the result, regardless of -opposing lower positions. Equal requires every position to agree. Although -Word stores bytes least-significant first for serialization, comparison priority -runs in the opposite direction. - -The two word clauses expose each operand's eight fields through ordinary -constructor matching. No nested pattern, integer primitive, or new proof rule -is introduced. Before selecting an `ordering_then` clause, an explicit -derivation must rewrite its high argument to an Ordering constructor. These -definitions supply comparison, not the still-missing encoder state transitions -that enforce the actual source/output limits. +Nibble helpers enumerate all 256 ordered pairs, byte comparison reuses nibble +splits, and word comparison checks byte 7 down to byte 0 (reverse of storage +order), deciding at the highest differing byte and returning Equal only when all +eight match. Both word clauses use standard constructor matching with no nested +patterns, integer primitives, or new proof rules. Proofs must normalize the high +argument of `ordering_then` to an Ordering constructor before unfolding it. ## Encoding and execution boundary `beta_encoding_theory()` writes one complete `GTH1` section and returns scalar -zero to its caller. It has no parameters and reads no input. There is no -production artifact-admitting `main`; the test entry rejects nonempty input -before emission and returns Gamma's marked application result to publish bytes -without an extra scalar terminator. The exact closure and that entry are pinned -by the [theory gate](../beta-encoding-theory/README.md). - -The section has eighteen sorts, 361 constructors, and 107 functions. The -vocabulary and outer fields occupy 4,508 bytes; lexical functions occupy -33,200; sixteen fixed-high helpers occupy 8,640; the public join occupies 800; -the split functions occupy 16,440; and word serialization occupies 348. Counter -byte helpers occupy 16,440 bytes, result selection 92, carry stages 2,896, and -the public successor 188. Ordering adds 8,640 bytes of fixed-left nibble -helpers, 800 for public nibble comparison, 124 for result selection, 224 for -byte comparison, 628 for the right-word helper, and 208 for public word -comparison. The error-valued encoder definitions 58..107 occupy 22,724 bytes, -including the 47-state token automaton and the encode entrypoint. Thus the -exact section is 116,900 bytes. All administrative fields fit u31; -none supplies semantic integer constants or operations. [PROFILE.md](PROFILE.md) -records the current source bounds and scoped measurements, separate from -full-certificate acceptance. +zero without parameters or input. No production artifact-admitting `main` +exists; the test entry rejects nonempty input and uses Gamma's marked result to +write bytes without a terminator. The [theory gate](../beta-encoding-theory/README.md) +pins the closure and entry. + +The section contains 18 sorts, 361 constructors, and 107 functions in 116,900 +bytes: vocabulary/header 4,508; lexical 33,200; high-nibble helpers 8,640; +public join 800; nibble splits 16,440; word serialization 348; counter byte +helpers 16,440; result chooser 92; carry stages 2,896; public successor 188; +ordering nibble helpers 8,640; public nibble compare 800; ordering chooser 124; +byte compare 224; right-word helper 628; public word compare 208; and encoder +functions 58..107 (including the 47-state token automaton and encode entry) +22,724. All header fields fit u31 and never act as theory integers. +[PROFILE.md](PROFILE.md) records static bounds and test measurements. ## Definition package -[definition_package.bin](definition_package.bin) commits the emitted package -itself: the exact 116,900-byte theory section `theory.gamma` writes under the -selected evaluator, SHA-256 -`6bbdd15abac8060a9c5718f58944f758c5c647c1aae827d92f61231b01c3987c`. The -checker request envelope's theory section is exactly these bytes -([REQUEST.md](../checker/REQUEST.md)), so this file is the owner-fixed -definition package the [acceptance contract](ACCEPTANCE.md) fixes -independently of the certificate producer. It is not host-authored: the -host-side mirror reproduces the evaluator emission byte-for-byte, and -`tests/bootstrap/proofs/sources_env.sh` binds the file to the same identity -(`require_beta_encoding_definition_package_identity`). A digest is an identity -check on the package bytes, not a proof of the encoded source. +[definition_package.bin](definition_package.bin) stores the exact 116,900-byte +theory section written by `theory.gamma` under the selected evaluator (SHA-256 +`6bbdd15abac8060a9c5718f58944f758c5c647c1aae827d92f61231b01c3987c`). Because the +request envelope's theory section uses these exact bytes +([REQUEST.md](../checker/REQUEST.md)), this file is the owner-fixed definition +package from [ACCEPTANCE.md](ACCEPTANCE.md). The host mirror reproduces it +byte-for-byte, and `tests/bootstrap/proofs/sources_env.sh` pins it via +`require_beta_encoding_definition_package_identity`. A hash checks package +bytes, not the encoded source. ## Certificate request -The produced certificate request — the check request the +The full certificate request consumed by the [certificate-check gate](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/beta-encoding-check/README.md) -consumes — binds at 135,485,028 bytes, SHA-256 +is pinned at 135,485,028 bytes, SHA-256 `7c0e3bf230a2675a170ea77dc6962ef6aa7c03ce15248b27475c7c6a3e592908` (`require_beta_encoding_certificate_request_identity` in -`tests/bootstrap/proofs/sources_env.sh`). The bytes are produced, not -committed: the stepper edge reproduces them from the bound theory and checker -closures, and the producing gate's full-subject record carries the same -identity. A digest is an identity check on the produced bytes, not a proof of -the derivation the certificate claims. The check edge's disclosed admission -record — the checker's 17-byte `Checked` observation — binds its proof-row -count in the producing record; its measured work field lands with the first -native run and binds then. +`tests/bootstrap/proofs/sources_env.sh`). It is generated rather than committed: +the stepper reproduces it from the pinned theory and checker closures. A hash +checks produced bytes, not proof validity. The check gate's 17-byte `Checked` +result fixes its proof-row count in the producing record; its measured work +field binds on the first native run. ## Error-valued encoder definitions Functions 58..107 implement the complete encoder over the Source tree: list -reversal and flattening, per-byte and whole-source admission, hexadecimal -token shifting, the 47-state token automaton with end-of-token classification, -comment and separator scanning, operand-expectation dispatch, counted output -emission, and the `encode(Source, source_limit, output_limit)` entrypoint -returning `RInvalid`, `RExhausted`, or `RSuccess` of the flattened tape bytes. -Every clause is ordinary constructor case analysis over the vocabulary above; -all function dependencies point backward, and no clause reads input. The -`definitions/encoding/` files are generated by -`tests/bootstrap/proofs/beta-encoding-theory/emit_gamma.py` from the independently -restated declarations in `tests/bootstrap/proofs/beta-encoding-theory/encoding.py`; the -generated text calls only the checked-in literal emitters, so the emitted -bytes match the independent package exactly. - -A complete theory is not a complete certificate: the artifact owner must still -fix the raw Beta source and persisted Alpha tape subjects, reconstruct the -owner-fixed proposition, and produce an explicit proof within the selected -resource profile. The measured feasibility blocker for the integrated route is -recorded in [TASKS_BOOTSTRAP.md](../../../../TASKS_BOOTSTRAP.md). - -Generic formation checks every declaration and every clause, including unused -rows; explicit derivations check classifications, nibble operations and their -composition, word serialization, checked increment, and unsigned ordering against -independent literal expectations. Exact package identity and those checks complement source -audit, but do not discharge the full Beta root. +reversal/flattening, per-byte and whole-source admission, hex token shifting, +the 47-state token automaton and classification, comment/separator scanning, +operand dispatch, counted emission, and +`encode(Source, source_limit, output_limit)` returning `RInvalid`, `RExhausted`, +or `RSuccess`. Every clause uses ordinary constructor matching with backward +dependencies and no input reads. +`tests/bootstrap/proofs/beta-encoding-theory/emit_gamma.py` generates +`definitions/encoding/` from +`tests/bootstrap/proofs/beta-encoding-theory/encoding.py` using checked-in +literal emitters, matching the independent package byte-for-byte. + +A complete theory is not a complete certificate: the owner must still fix the +raw source and tape, reconstruct the proposition, and verify an explicit proof +within the chosen resource budget. See +[TASKS_BOOTSTRAP.md](../../../../TASKS_BOOTSTRAP.md) for the feasibility +blocker. Generic formation checks every declaration and clause (including unused +ones), and finite derivations test lexical, nibble, word, counter, and ordering +equations against independent literals; these support source audit without +proving the full Beta root. ## Remaining encoder dependency -The definitions now cover the remaining checked arithmetic: hexadecimal -parsing, token and operand state, the complete mnemonic table, address -assertions, failure values, and exact source/output limits and exhaustion. -Structural recursion consumes an unchanged immediate source tail, using -earlier total helpers for state changes; the only mode-1 self-calls are the -structural recursions in functions 69, 70, 71, 73, 81, and 103. - -Equation-level evidence now exists: the theory gate checks 198 encoder -equations across all encoder functions 58..107, including tiny end-to-end -encodes, through the ordinary checker. The generic stepper has also -independently reconstructed the owner-fixed proposition over the complete -selected subject and produced the full untrusted derivation — 3,182,484 -rows and 135,451,492 request bytes, 16.1 times the 8,388,608-byte provision it -was measured against — so -the certificate is produced and measured, the provisions to admit it are -selected, and the 136,314,880-byte request extent is landed in the Alpha -checker. [PROFILE.md](PROFILE.md) records the complete -measurements; the residual routes are the owner-level decisions named in the -cost review. Do not let producer-supplied definitions choose the -meaning of the artifact being accepted. +The theory now covers hex parsing, token/operand state, all mnemonics, address +assertions, failure values, and exact source/output limits. Structural recursion +consumes an unchanged immediate child while earlier total helpers update state; +the only mode-1 self-calls are functions 69, 70, 71, 73, 81, and 103. + +The theory gate verifies 198 equations across functions 58..107 (including tiny +end-to-end encodes) using the ordinary checker. The stepper also reconstructed +the full historical proposition and emitted the complete derivation (3,182,484 +rows, 135,451,492 request bytes — 16.1× the old 8,388,608-byte limit). The +larger 136,314,880-byte request cap is now landed in the Alpha checker, and +[PROFILE.md](PROFILE.md) records the measurements; remaining options are the +owner-level routes in the cost review. Never let a producer choose the +definitions for an artifact being accepted. diff --git a/tests/bootstrap/proofs/checker/CHECKING.md b/tests/bootstrap/proofs/checker/CHECKING.md index fee5eea9809b..c56ebb45804a 100644 --- a/tests/bootstrap/proofs/checker/CHECKING.md +++ b/tests/bootstrap/proofs/checker/CHECKING.md @@ -2,259 +2,237 @@ [Format](FORMAT.md) | [Comparison](COMPARISON.md) | [Substitution](SUBSTITUTION.md) | [Calculus](README.md) -`check_derivation()` is the generic ordinary-Gamma entrance. It checks the whole -supplied proof table and its final conclusion against the owner root. It does -not authenticate an artifact's theory or reconstruct its proposition. The full -Beta definition package, owner-fixed encoding proposition, complete certificate, -and admitted artifact closure remain separate acceptance requirements. +`check_derivation()` is the generic ordinary-Gamma entry point. It checks every +row of the proof table and verifies that the final row matches the owner root. +It does not authenticate the theory or reconstruct the proposition. The full +Beta definition package, owner-fixed proposition, complete certificate, and +artifact closure remain separate acceptance steps. ## One request, one ordered proof scan -Call `check_derivation_ground()` and forward any failure unchanged. Only Grounded -permits proof processing. The retained proof-table offset comes from physical -layout, not a supplied pointer. Let `P` be its row count. Reject zero with code -12 `derivation` at the count field before initializing comparison or indexing. - -Initialize one comparison session for the request. Reserve `P+1` work units at -the proof-count coordinate before building a balanced physical row-offset index. -Physical indexing does not admit future premises. Visit every row in order, -including unused rows, retaining only the latest session returned by each call. -Before checking a row, reserve one unit at its rule field (`record+4`). Check -left and then right global term references (`record+8`, `record+12`), then require -their inferred sorts to agree. Invalid references reject with code 12 at their -own fields; sort mismatch rejects at the right field. Sorts come from checked -symbol signatures, not proof-supplied annotations or term expansion. - -Earlier admission failures precede all proof errors. The per-row reservation -precedes that row's semantic checks. A rejected or incomplete operation ends -the request; no Boolean or resumable session may become Checked. +Call `check_derivation_ground()` first and pass any failure through unchanged. +Only Grounded allows proof checking. Read the proof-table offset saved by layout +checking, never a certificate-supplied pointer. Let `P` be the proof row count. +Reject zero with code 12 `derivation` at the count field before starting +comparison or indexing. + +Start one comparison session for the request. Reserve `P+1` work units at the +proof-count offset before building a balanced physical row-offset index. +Indexing does not allow forward references. Scan every row in order, including +unused rows, keeping only the latest session returned by each step. Before +checking a row, reserve one unit at its rule field (`record+4`). Validate the +left and then right global term IDs (`record+8`, `record+12`), then verify their +inferred sorts match. Bad IDs fail with code 12 at their own fields; sort +mismatches fail at the right field. Sorts come from checked symbol signatures, +never proof annotations or term expansion. + +Earlier stage failures take priority over all proof errors, and each row's work +reservation runs before its semantic checks. Any rejected or incomplete step +ends the request immediately; no Boolean or resumable session can reach Checked. ## Rule order and failure coordinates -Rule tags and record shapes have already passed layout. A premise identity must -be in `1..current_row-1` before any lookup/projection. The physical index cannot -authorize self, forward, zero, missing, or cyclic premises. An invalid premise -rejects with code 12 at that premise-reference field. +Rule tags and record shapes already passed layout checking. Each premise ID must +lie in `1..current_row-1` before lookup; the physical index never allows self, +forward, zero, missing, or cyclic premises. An invalid premise fails with code +12 at that premise-reference field. -Structural requirements call the ground comparator with both diagnostic -coordinates set to the field owning that requirement. Forward owned failures -unchanged; map Compared false to rejection code 12 at that field. Thread the -returned session only when the requirement succeeds. Do not cache proof-derived -equality as structural equality. +For each structural check, call the ground comparator with both offsets set to +the field that requires the equality. Pass checker failures through unchanged, +and turn Compared false into rejection code 12 at that field. Thread the +returned session forward only on success. Never cache proof-derived equalities +in the structural memo. -1. **Reflexivity:** compare the two claimed sides structurally. Difference belongs - to the right field. +1. **Reflexivity:** compare both claimed sides structurally; mismatch fails at + the right field. 2. **Symmetry:** validate the premise at `record+16`; compare claimed left with - premise right, then claimed right with premise left. Differences belong to - the claimed left and right fields, respectively. -3. **Transitivity:** validate the first premise (`record+16`), then the second - (`record+20`), before structural comparisons. Compare claimed left with first - left, first right with second left, then claimed right with second right. - Differences belong respectively to the claimed left, second-premise, and - claimed right fields. -4. **Congruence:** require matching application tags, then symbols; either - mismatch belongs to the right field. Require the stated premise count - (`record+16`) to equal the application arity; mismatch belongs to the count. - For each ordered premise field at `record+20+4*position`, reserve one unit - there before validating its backward reference. Compare left argument with - premise left, then right argument with premise right; both requirements belong - to that premise field. An earlier argument error precedes later premise - validation. Zero-arity congruence is valid with zero premises. -5. **Unfolding:** call `compare_unfolded_terms` using the claimed references, - local clause ordinal at `record+16`, and their actual field coordinates. - Preserve its code 10 clause/head failures and resource failures. Map Compared - false to code 12 at the claimed right field. No case selection or body - evaluation is inferred from earlier equalities. + premise right, then claimed right with premise left. Mismatches fail at the + claimed left and right fields, respectively. +3. **Transitivity:** validate the first premise (`record+16`) and second premise + (`record+20`) before any comparison. Compare claimed left with first left, + first right with second left, then claimed right with second right. + Mismatches fail at the claimed left, second-premise, and claimed right + fields, respectively. +4. **Congruence:** require matching application tags, then matching symbols; + either mismatch fails at the right field. Require the premise count + (`record+16`) to equal the application arity; mismatch fails at the count + field. For each premise field at `record+20+4*position`, reserve one unit at + that field before validating its backward reference, then compare left + argument with premise left and right argument with premise right (both owned + by that premise field). Earlier argument errors precede later premise + validation. Zero-arity congruence succeeds with zero premises. +5. **Unfolding:** call `compare_unfolded_terms` with the claimed IDs, local + clause ordinal at `record+16`, and their actual field offsets. Keep its code + 10 clause/head failures and resource failures; map Compared false to code 12 + at the claimed right field. Earlier equalities never drive case selection or + evaluation. After all rows pass, compare owner left with the last row's left, then owner -right with its right. Each requirement belongs to that last row's corresponding -field. Orientation matters. Structurally identical duplicate or witness rows -may conclude the owner root, but cannot redefine it. There is no selectable -conclusion index and no acceptance of a valid prefix followed by an invalid row. +right with the last row's right, reporting mismatches at the last row's matching +field. Orientation matters. Structurally equal duplicate or witness rows may +conclude the owner root without redefining it. Producers cannot pick a +conclusion row or accept a valid prefix followed by a bad row. ## Result and soundness boundary -Success is tag 7 `Checked`, payload `(pair P work)`. Accessors -`derivation_proof_count(payload)` and `derivation_steps(payload)` expose those -scalars. Rejected/Incomplete retain the existing four-field failure payload. -No session is returned from Checked. A diagnostic entry publishes tag 7 plus -the two u64 little-endian values (17 bytes), or a failure tag plus its four u64 -fields (33 bytes). Process zero alone is not success: the complete owned -observation must be consumed. No artifact-admitting production `main` is supplied. - -Induction over checked rows establishes soundness under the formed theory: -reflexivity uses structural identity; symmetry and transitivity use only checked -earlier equations with structurally matched endpoints; congruence uses the same -typed symbol and a checked equation for every ordered argument; unfolding uses -exactly a formed defining equation under checked substitution. Formation has -already established a conservative total theory. Final structural comparisons -transfer the last checked equation to the owner root without changing it. - -This proves a ground equality under the supplied theory, not that the supplied -theory is the intended Beta encoder or that its root names the selected raw -source and tape. Artifact ownership must establish those facts independently. -All five rules remain subject to actual use and mutation controls in the full -encoding certificate; these generic tests do not complete P1. +Success returns tag 7 `Checked` with payload `(pair P work)`, read via +`derivation_proof_count(payload)` and `derivation_steps(payload)`. Rejected and +Incomplete keep the four-field failure payload, and Checked returns no session. +Diagnostic entries write tag 7 plus two little-endian u64 values (17 bytes), or +a failure tag plus four u64 fields (33 bytes). Exit status zero alone does not +prove success: callers must read the full diagnostic output. No +artifact-admitting production `main` exists here. + +Induction over checked rows proves soundness under the formed theory: +reflexivity checks structural identity; symmetry and transitivity reuse earlier +checked equations with structurally matched endpoints; congruence matches the +same typed symbol with a checked equation per argument; and unfolding applies a +formed defining equation under checked substitution. Theory formation already +proved the theory conservative and total. The final comparisons transfer the +last equation to the owner root unchanged. + +This establishes ground equality under the supplied theory, not that the theory +is the intended Beta encoder or that the root names the selected source and +tape. The artifact owner must verify those facts separately. All five rules +still depend on actual use and mutation tests in the full encoding certificate; +generic tests alone do not finish P1. ## Rule census on the complete certificate -`tests/bootstrap/proofs/beta-encoding-theory/run.sh --full-subject` reproduces the -complete derivation on any python3 host and counts each rule's emitted rows. -Measured census: 1,018,733 unfolding, 1,157,751 transitivity, 936,662 -congruence, 69,828 reflexivity, and 0 symmetry rows; maximum premise depth 204 -against the 256 bound. - -All five rules are retained; the checker-leg of the retained-role decision is -closed here. Symmetry is a primitive of the ground-equality calculus this -checker implements, not a certificate-shaped convenience: the generic -entrance checks arbitrary supplied derivations over a formed theory, and an -equational derivation over this theory can have symmetric instances the -producer happened not to emit. Removing it would narrow the checkable -derivation class to this certificate's footprint while saving 555 source -bytes — a caliber-fidelity loss with no admission benefit, since the unused -rule costs nothing in the request or the provisions. Its controls already -run in the checking gate: `positive` accepts a symmetry step and a -five-rule connected derivation, `relations` mutates both endpoint fields, -`references` mutates its premise row reference, and `resources` bounds a -32,768-deep symmetry proof dag — real test weight, not dead rows. - -The encoding members of the same audit are decided in -`tests/bootstrap/proofs/beta_encoding`: the TokenClass chooser, the only theory -member no clause body could ever call, is removed and the remaining -unexercised members (S_EMPTY, A_EXHAUSTED, the 900 never-premised clauses) -are retained for contract-visible reasons — the Source base case, the -distinct exhaustion admission, and function totality on malformed input. +`tests/bootstrap/proofs/beta-encoding-theory/run.sh --full-subject` reproduces +the full derivation on any python3 host and counts emitted rows per rule: +1,018,733 unfolding, 1,157,751 transitivity, 936,662 congruence, 69,828 +reflexivity, and 0 symmetry rows, with maximum premise depth 204 against the 256 +limit. + +All five rules stay, closing the checker side of the retained-role audit. +Symmetry is a core rule of the ground-equality calculus, not a +certificate-specific shortcut: the generic checker accepts arbitrary derivations +over any formed theory, including proofs that use symmetry even though this +producer did not emit any. Dropping it would narrow the calculus to one +producer's footprint to save 555 source bytes while adding zero checking +benefit, since unused rules cost nothing at runtime. Its tests already run in +the checking gate: `positive` checks a symmetry step and a five-rule derivation, +`relations` corrupts both endpoints, `references` corrupts its premise ID, and +`resources` tests a 32,768-deep symmetry DAG. + +The theory-side audit is decided in `tests/bootstrap/proofs/beta_encoding`: the +TokenClass chooser (the only theory function no clause could call) was removed, +while S_EMPTY, A_EXHAUSTED, and the 900 unexercised clauses remain for contract +reasons (the Source base case, distinct exhaustion results, and totality on +malformed input). ## Complete generic execution provision -Outer admission limits the exact checker request to 136,314,880 bytes (130 -MiB), the least whole-MiB extent above the measured complete certificate -request of 135,451,492. It leaves room in Gamma's 137,363,456-byte (131 MiB) -evaluator frame for the pinned checker source and four-byte source length. The -canonical closure and diagnostic compositions are measured by their -manifests/pins; the whole artifact owner must retain its exact entry -composition and verify this framing requirement. -The [checking diagnostic](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-checking/source.tsv) -is 1,391 lines and 63,512 bytes; an exact-limit checker input yields +Outer framing caps requests at 136,314,880 bytes (130 MiB), the smallest whole +MiB above the measured 135,451,492-byte full certificate request. That leaves +room inside Gamma's 137,363,456-byte (131 MiB) evaluator frame for the pinned +checker source and four-byte length prefix. Canonical and diagnostic +compositions are pinned by manifests; the artifact owner must keep its exact +entry composition and verify this framing fit. The +[checking diagnostic](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-checking/source.tsv) +is 1,391 lines and 63,512 bytes, so a max-size request takes `4 + 63,512 + 136,314,880 = 136,382,496` framed bytes. -Formation retains its independent 65,536-sort and 8,388,608-work-estimate -preflights. The physical extent bounds payload words below 34,078,720 (< 2^26), -global ground terms and proof rows below 8,519,680 (< 2^24), and -— since the estimate's `4W` term still bounds theory words `W <= 2^21` — a -clause's templates below 2^20. Arity and -all child/premise counts are physically bounded before loops; there is no extra -arbitrary arity or logical-depth cutoff. Ground/template/proof references are -indexed, not repeatedly found in linked tables. Index building uses at most -24 native levels; memo insertion at most 47, the ground memo's `[0,N*N)` key -space, while a clause's template memo stays within 44 levels. Row and premise -scans and explicit -comparison/substitution continuations are tail calls. A variable's ground -comparison adds one bounded suspension, not recursion through template depth; -the finite helper nesting remains below Gamma's 256 call-context rows. - -The selected diagnostic composition has 208 functions, at most 15 nested body -lists, arity 10, and 11 simultaneously active bindings per function. These are -source measurements, not input-dependent provisions. A source call-path audit -allows 57 call-context rows and 58 active function frames, including `main`. -It counts pending outer calls during argument evaluation as well as suspended -non-tail calls. The longest conservative path allows three proof/premise -suspensions, two contexts entering ground comparison, two entering memo insertion, -47 recursive memo levels, two deepest preparation contexts, and the one `main` -suspension. Other positive-depth cycles are bounded index building (24), sort -marking (16), and fixed function/clause/template layout nesting (four). -All proof scans and logical term traversals have tail-only cycles. - -Thus active environments need at most `58*11 = 638` binding rows, below 65,536. -For temporary values, allow 16 entries per expression level (ten arguments plus -helper saves), 16 levels per frame (15 body lists plus return handling), and -32 fixed entries: `58*16*16+32 = 14,880`, below 524,288. The evaluator resets -argument temporaries and environments on tail-frame reuse. These conservative -source/evaluator bounds are not claimed runtime peak measurements. A different -checker entry or changed implementation must recheck its function, syntax, -binding, context, and temporary-value bounds before artifact acceptance. - -All work after Grounded shares the same 67,108,864-unit counter (2^26): -proof-index setup, -row checks, congruence premises, clause/index setup, and every comparison and -substitution transition. No rule restarts or rolls back the session. Live -pending frames and completed memo insertions are bounded by consumed units; -discarded local memos and replaced frames still count toward allocation. -These provisions are adjustable engineering choices, not calculus restrictions. - -Owner decision `beta-encoding-certificate-admission` selects more native -backing over a checker composition rule for the complete Beta-encoding -certificate. The five rules of [FORMAT.md](FORMAT.md#certificate-section-gce1) -stay as they are and admission grows the provisions instead, so no certificate -is admitted under a premise the checker did not derive in its own table. -**GAMMA-DERIVATION-CHECKER** rederived the bounds of this ledger at the -measured extent and selects the three coupled provisions: the 136,314,880-byte -request extent and the 137,363,456-byte evaluator frame that holds it with the -63,516-byte source framing; the 67,108,864-unit work counter, ~28% above the -44.2-52.5M projection (the measured 13.9-16.5 work/row over 3,182,484 rows); -and the 3,387,293,850-pair arena this ledger implies. The deeper memo key -spaces move the amortized constant to 50 pairs per unit. The ~129 MiB frame, -~45-52M work, and ~2.17-2.50G-pair figures were measurement targets; these are -the selected provisions. They no longer fit a static image, so the Alpha -realization supplies the extents — the `M` startup extent, and in the same -leg a buffered-output provision covering the 134,800,268-byte certificate -against 16,777,212 today. The provisions take effect there; the recorded -bounds already hold at the selected extent. - -Extent supply landed (AlphaBootstrapV5): both audited seeds obtain `M` at -startup — `VirtualAlloc` on Windows x64, `svc #0x80` anonymous `mmap` on -macOS arm64 — over `MEMSIZE = 0x2000000000` (128 GiB). The evaluator now -frames the complete request at `0x10000000..0x18300000`, buffers -135,266,304 output bytes at `0x18300000..0x20400000` (above the -134,800,268-byte certificate), and admits 3,422,453,760 pair nodes at -`0x20400000..0x2000000000` (above the selected 3,387,293,850 bound). The -work counter was already a 64-bit budget and needs no extent. Seed -identities are repinned in `tools/bootstrap/alpha/seed_env.sh`; the -evaluator source/tape identities in `tools/bootstrap/gamma/evaluator_env.sh`. -No opcode transition moved; `M` remains a flat zeroed array and execution -stays a function of tape and input alone. Checker-side, -`implementation/admission/extents.gamma` applies the same 136,314,880-byte -request bound and `implementation/comparison/session.gamma`'s -`comparison_limit` carries the 67,108,864-unit work counter — the earlier -8,388,608-byte and 655,360-unit figures predated this ledger's selection -and refused the recorded request at admission and at session reservation. - -Recorded consequences of the larger extents: the exact/adjacent pair -boundary is no longer executable in gate time, so -`tests/bootstrap/proofs/heap-boundary` and `tests/bootstrap/interpreted/epsilon/pair-boundary` now witness -the retired-V4-arena crossing and keep the refusal fixture pinned for -opt-in execution; the function census's 2,097,152-row physical table is -reachable in principle within the request frame, so the count preflight is -now the live controlling boundary (its quadratic index insertion keeps it -outside practical gate time). Native acceptance (Windows, macOS, QEMU) is -required for the derived containers and remains to run on those hosts. - -The complete cumulative pair bound is -`31,850,522 + 67,108,864*50 + 128 = 3,387,293,850` — the selected arena -provision. The first term covers formation and Grounded: -`2W+3N+32S+26` under `W <= 2^21`, `N < 8,519,680`, `S <= 65,536`. `P+1` units pay -for `3P-1` index pairs, reservation carriers, and bounded proof context setup. -Each row/premise unit pays for its own reservation and any constant coordination -carriers; structural comparison and substitution charge their own operations. -The [amortized traversal argument](COMPARISON.md#amortized-allocation-argument) -establishes 50 pairs per unit across charged operations, not per individual -transition: a memo-path insertion allocates at most 94 pairs over its one -charged unit, and the at-least-42-credit entry per pending level keeps -completed calls nonnegative. The once-per-request 128-pair allowance covers the -at-most-44-pair -unfinished-prefix deficit, session setup, final Checked or failure publication, -and constant boundary carriers, not repeated row costs. The implementation must -enumerate its allocations against this ledger. - -Actual proof setup uses `3P+4` pairs: four reservation carriers, `3P-1` index -pairs, and one context pair. Row and premise coordination each add at most -eight pairs to their own unit: four reservation carriers and four for a direct -failure or congruence completion. All checks and projections otherwise use -scalars or existing carriers. Initial session setup uses seven fixed pairs; -final Checked uses two, or a terminal requirement failure uses four. Existing -comparison/substitution allocations remain charged to their own transitions. - -Only the final diagnostic writes output: 17 or 33 bytes, well within the selected -Gamma output provision. An outer evaluator refusal, trap, host timeout, or short -observation is never a proof result. Full-certificate size, storage, depth, and -time measurements and an artifact-specific accepted profile remain required. +Formation keeps its 65,536-sort and 8,388,608-work preflights. Request size +bounds payload words below 34,078,720 (< 2^26), ground terms and proof rows +below 8,519,680 (< 2^24), and — via formation's `4W` bound (`W <= 2^21`) — a +clause's templates below 2^20. Arity and child/premise counts are physically +bounded before loops, with no extra arity or logical-depth cutoff. Lookups use +balanced indexes rather than linked lists. Index building takes at most 24 +native stack frames, ground memo insertion at most 47 (for `[0,N*N)`), and +clause template memos at most 44. Row and premise loops and comparison or +substitution continuations are tail calls. A variable's ground comparison adds +one bounded suspension rather than recursing through template depth, staying +well below Gamma's 256 call-context limit. + +The diagnostic composition has 208 functions, at most 15 nested body lists, +maximum arity 10, and at most 11 live bindings per function (source properties, +not input limits). A static call-path audit needs at most 57 call contexts and +58 active frames including `main`, counting pending outer calls during argument +evaluation and suspended non-tail calls. The worst path includes three +proof/premise suspensions, two contexts entering ground comparison, two entering +memo insertion, 47 recursive memo levels, two preparation contexts, and one +`main` suspension. Other non-tail cycles are bounded: index building (24), sort +marking (16), and fixed layout nesting (4). All proof scans and term traversals +are tail-recursive. + +Active environments therefore need at most `58*11 = 638` binding rows (under +65,536). Allowing 16 temporaries per expression level (ten arguments plus helper +saves), 16 levels per frame (15 body lists plus return handling), and 32 fixed +entries gives `58*16*16+32 = 14,880` temporaries (under 524,288). Tail-frame +reuse resets argument temporaries and environments. These are conservative +static bounds, not runtime peaks; any changed entry or implementation must +re-audit these bounds before acceptance. + +All post-Grounded work shares one 67,108,864-unit (2^26) counter covering proof +indexing, row checks, congruence premises, clause and template indexing, and +every comparison and substitution step. No rule resets or rolls back the +session. Live pending frames and completed memo entries stay bounded by consumed +units; dropped local memos and replaced frames still count toward allocation. +These caps are adjustable engineering budgets, not calculus rules. + +Owner decision `beta-encoding-certificate-admission` chose larger native memory +backing over adding a composition rule for the full Beta certificate. The five +rules in [FORMAT.md](FORMAT.md#certificate-section-gce1) stay unchanged while +resource budgets grow, so no certificate relies on a premise the checker did not +derive in its own table. **GAMMA-DERIVATION-CHECKER** rederived this ledger at +the measured size and chose three coupled budgets: the 136,314,880-byte request +cap (fitting the 137,363,456-byte evaluator frame with 63,516 bytes of source +framing); the 67,108,864-unit work cap (~28% above the 44.2–52.5M projection +from 13.9–16.5 work/row across 3,182,484 rows); and the 3,387,293,850-pair arena +implied by the ledger (deeper memo trees raise the amortized constant to 50 +pairs/unit). The earlier ~129 MiB, ~45–52M work, and ~2.17–2.50G-pair figures +were measurement estimates; these are the chosen limits. Because they exceed a +static binary image, Alpha allocates `M` at startup and raises buffered output +to cover the 134,800,268-byte certificate (up from 16,777,212 bytes). + +That allocation landed in AlphaBootstrapV5: both audited seeds allocate `M` at +startup (`VirtualAlloc` on Windows x64, `svc #0x80` anonymous `mmap` on macOS +arm64) over `MEMSIZE = 0x2000000000` (128 GiB). The evaluator now frames the +full request at `0x10000000..0x18300000`, buffers 135,266,304 output bytes at +`0x18300000..0x20400000` (above the 134,800,268-byte certificate), and holds +3,422,453,760 pair nodes at `0x20400000..0x2000000000` (above the 3,387,293,850 +bound). The work counter was already 64-bit. Seed hashes are repinned in +`tools/bootstrap/alpha/seed_env.sh`, and evaluator hashes in +`tools/bootstrap/gamma/evaluator_env.sh`. No opcode changed; `M` stays a flat +zeroed array and execution depends only on tape and input. In the checker, +`implementation/admission/extents.gamma` enforces the 136,314,880-byte request +cap and `implementation/comparison/session.gamma`'s `comparison_limit` enforces +the 67,108,864-unit cap (replacing the old 8,388,608-byte and 655,360-unit caps +that rejected the full request). + +Consequences of the larger memory layout: exact pair-boundary tests no longer +finish within gate time, so `tests/bootstrap/proofs/heap-boundary` and +`tests/bootstrap/interpreted/epsilon/pair-boundary` now test crossing the old V4 +arena limit while keeping the full refusal fixture for opt-in runs. The +2,097,152-row function table is now reachable in theory within the request +frame, making the count preflight the active bound (quadratic index insertion +keeps it outside gate time). Native acceptance runs on Windows, macOS, and QEMU +are still required for the derived containers. + +The total pair bound is `31,850,522 + 67,108,864*50 + 128 = 3,387,293,850`, +matching the arena budget. The first term covers formation and Grounded: +`2W+3N+32S+26` under `W <= 2^21`, `N < 8,519,680`, `S <= 65,536`. `P+1` units +pay for `3P-1` index pairs, reservation pairs, and proof context setup. Each +row or premise unit covers its reservation and constant coordination pairs, +while comparison and substitution charge their own steps. The +[amortized traversal argument](COMPARISON.md#amortized-allocation-argument) +proves 50 pairs per unit overall (not per single step): a memo insert allocates +up to 94 pairs on one unit, while at least 42 credits per pending level keep +completed calls nonnegative. The fixed 128-pair allowance covers one unfinished +prefix (up to 44 pairs), session setup, final Checked or failure output, and +boundary pairs — never repeated per row. The implementation must check its +allocations against this ledger. + +Actual proof setup allocates `3P+4` pairs: four reservation pairs, `3P-1` index +pairs, and one context pair. Row and premise steps add at most eight pairs to +their unit (four for reservation and four for a direct failure or congruence +completion); all other checks use scalars or existing pairs. Session setup uses +seven pairs, final Checked uses two, and terminal failure uses four. Comparison +and substitution stay charged to their own steps. + +Only the final diagnostic writes output: 17 or 33 bytes, far below Gamma's +output cap. Outer evaluator refusals, traps, host timeouts, and truncated +outputs are never proof results. Full-certificate size, memory, depth, and time +measurements plus an artifact-specific profile are still required. diff --git a/tests/bootstrap/proofs/checker/COMPARISON.md b/tests/bootstrap/proofs/checker/COMPARISON.md index 259d489cce70..19bf205869d2 100644 --- a/tests/bootstrap/proofs/checker/COMPARISON.md +++ b/tests/bootstrap/proofs/checker/COMPARISON.md @@ -2,104 +2,99 @@ [Ground terms](GROUND.md) | [Inner format](FORMAT.md#comparison-and-finite-execution) | [Calculus](README.md) -This component compares the syntax of validated ground terms. It does not -interpret definitions, substitute templates, check proof rows, or accept a -certificate. Structurally different terms may still be provably equal under the -formed theory: `identity(zero)` and `zero` are different syntax here. +This module compares the syntax of validated ground terms. It does not evaluate +definitions, substitute templates, check proof rows, or accept certificates. +Syntactically different terms may still be provably equal in the formed theory: +`identity(zero)` and `zero` are not structurally equal here. ## Source-owned comparison session -`comparison_start(grounded)` creates one private session retaining the exact -Grounded payload, zero consumed steps, and an empty completed-comparison memo. +`comparison_start(grounded)` creates a private session holding the Grounded +payload, zero consumed steps, and an empty completed-comparison memo. `compare_ground_terms(session, left, right, left_coordinate, right_coordinate)` -compares two global term identities in that session's owner-plus-witness tables. -Coordinates are supplied by the source-owned caller for its checked request -fields; they do not authorize reads or change term identity. - -The caller initializes once per checked request and threads each returned session -into the next call. Gamma's immutable pairs do not enforce linear use: reusing -an old session or starting another would repeat allocations without retaining -the cumulative counter. The [proof coordinator](CHECKING.md) enforces this -invariant. Neither sessions nor their internal fields are certificate data. -After a rejected or incomplete result, abandon the request; there is no returned -continuation to resume as though the failed comparison succeeded. - -Validate the left identity and then the right identity with checked global -lookup before any identity shortcut, memo lookup, or charged transition. An -invalid identity selects tag 1, code 9 `comparison_reference`, the corresponding -supplied coordinate, and zero limit/requested. This validation also precedes -step exhaustion. Equal invalid integers, including zero, are not reflexivity. +compares two global term IDs in that session's owner-plus-witness tables. The +caller supplies byte offsets for its request fields; those offsets only label +errors and never authorize reads or alter term identity. + +The caller initializes one session per request and threads each returned session +into the next call. Because Gamma's immutable pairs do not enforce linear use, +reusing an old session or creating a second one would repeat allocations without +preserving the step counter; the [proof coordinator](CHECKING.md) enforces +single-session threading. Sessions and their fields are internal, never +certificate data. After any rejected or incomplete result, stop processing the +request; no continuation exists to resume past a failed comparison. + +Check the left ID and then the right ID via global lookup before any identity +shortcut, memo lookup, or charged step. An invalid ID fails with tag 1, code 9 +`comparison_reference`, the matching caller offset, and zero for limit and +requested. ID validation runs even if the step budget is already exhausted. Two +equal invalid integers (including zero) do not trigger reflexivity. ## Comparison and completed memo -For a valid pair, compare identical scalar identities first, then look for a -completed memo entry. Otherwise compare application tag, then symbol identity. -A differing tag or symbol establishes structural difference immediately. Equal -heads have the same arity and sorts under the already checked signatures. -Compare all children in argument order. No definition-order restriction is -imposed on ground applications, and no function is silently evaluated. - -Use explicit depth-first pending frames. A frame retains the parent comparison -identity, the next child cursors, remaining children, and the preceding stack. -Visits and resumptions are tail calls; logical tree depth never becomes native -call depth. On a differing child, discard the pending stack and return false. -Already completed child entries may remain in the session, but no unfinished -ancestor is added. No in-progress or interrupted operation can mean equal. - -Let `N` be the session's complete ground count. A memo key encodes both ordered -identities as `(left-1)*N+(right-1)`. Ground admission ensures -`1 <= N < 8,519,680` (< 2^24), so this encoding is injective and lies in -`0..N*N-1`, below 2^47. Reversing a pair is a different key; this is not a hash -or a pair address. -Use a sparse immutable tagged tree over `[0,N*N)`, splitting the known range -in half. Empty and true leaves are shared tagged pairs. Insert true only after -all children agree (or immediately for equal nullary heads). Identical identity -and memo shortcuts do not insert again. Tree descent is bounded by 47 edges; -updates may use bounded native recursion without recursive term expansion. - -Backward ground references strictly decrease both child identities. They rule -out pending comparison cycles, while completed memoization preserves sharing -even for separately encoded DAGs. False entries are not needed for soundness; -repeated failed comparisons still consume the shared work budget. +For valid IDs, check equal scalar IDs first, then check the completed memo. +Otherwise compare application tag, then symbol ID. A mismatch in tag or symbol +returns false immediately. Matching heads already have identical arity and sorts +from validated signatures. Compare children in argument order without applying +definition-order restrictions or evaluating functions. + +Traversal uses explicit depth-first pending frames storing parent IDs, next +child cursors, remaining child count, and the previous stack. Visits and +resumptions are tail calls, so logical term depth never uses native stack depth. +When a child differs, discard the pending stack and return false. Completed +child entries may stay in the memo, but never record an unfinished ancestor. An +in-progress or interrupted call never counts as equal. + +Let `N` be the total ground-term count. A memo key encodes an ordered pair as +`(left-1)*N+(right-1)`. Ground validation guarantees `1 <= N < 8,519,680` +(< 2^24), so keys are injective in `0..N*N-1` (below 2^47). Reversing the pair +produces a different key; keys are never hashes or pair addresses. Store the +memo as a sparse immutable tagged tree over `[0,N*N)` that halves the range at +each level, with shared tagged pairs for empty and true leaves. Insert true only +after all children match (or immediately for equal nullary heads); skip +insertion on identity or memo hits. Descent takes at most 47 edges, so updates +use bounded native recursion without expanding terms. + +Strictly backward ground references prevent comparison cycles, and the completed +memo preserves sharing across separately encoded DAGs. Storing false entries is +not needed for soundness; repeated failed comparisons still pay the work budget. ## Work and allocation provision -Each `visit` and `resume` transition checks and increments the session's consumed -steps before performing its work. This includes the terminal resume of an empty -stack. A same-identity or completed-memo comparison therefore consumes two steps. -A head mismatch consumes one. Every child comparison follows the same rules; -completion of a pending parent is a charged resume, not an unchecked insertion. - -The private limit is 67,108,864 cumulative transitions per session. -Attempting another transition when that count is exhausted selects tag 2, -resource 4 `checking_work`, the current call's original left coordinate, -limit 67,108,864, and requested 67,108,865. No Boolean result or session escapes on -exhaustion, including exhaustion between a successful visit and terminal resume. -This is an adjustable implementation provision, not a calculus restriction. -Measure the complete Beta certificate before claiming that this profile fits it. - -A memo update copies at most 47 internal nodes at two pairs each; helpers must -not allocate an extra carrier per tree level. The cumulative bound is amortized, -not the maximum allocation of one transition: 50 pairs per consumed work unit -plus 128 once-per-request pairs. Combined with formation and ground admission, -`31,850,522 + 67,108,864*50 + 128 = 3,387,293,850` pairs is the selected arena -provision. This counts unreachable allocations, not just live storage. - -The current implementation uses seven setup pairs: three for the shared context, -two shared memo constants, and two for the initial session. A charged transition -allocates either a memo path of at most 94 pairs, a four-pair pending frame, or a -four-pair terminal result including its replacement session; those branches do -not allocate together within one transition. ID checks and all other helpers -are scalar-only. Terminal failure uses four reserved pairs. A completed-parent -insertion and the subsequent resume are separately charged transitions. +Every `visit` and `resume` step checks and increments the session's step counter +before doing work, including the final resume of an empty stack. A same-ID or +memo-hit comparison therefore costs two steps, and a head mismatch costs one. +Every child comparison follows the same rules, and completing a pending parent +is a charged resume rather than a free memo insert. + +The private budget is 67,108,864 cumulative steps per session. Exceeding it +returns tag 2, resource 4 `checking_work`, the call's original left offset, +limit 67,108,864, and requested 67,108,865. No Boolean or session escapes on +exhaustion, including exhaustion between a successful visit and its final +resume. This cap is an adjustable implementation choice, not a calculus rule; +measure the complete Beta certificate before claiming this budget fits it. + +A memo update copies at most 47 internal nodes (two pairs each); helpers must +not allocate extra wrappers per level. The cumulative pair bound is amortized +across charged work: 50 pairs per work unit plus 128 fixed pairs per request. +With formation and ground validation, +`31,850,522 + 67,108,864*50 + 128 = 3,387,293,850` pairs matches the Gamma arena +budget. Unreachable pairs count toward this total. + +The implementation uses seven setup pairs: three for the shared context, two for +shared memo constants, and two for the initial session. Each charged transition +allocates at most one of: a memo path (up to 94 pairs), a four-pair pending +frame, or a four-pair final result with its updated session. ID checks and all +other helpers allocate nothing. Terminal failure uses four reserved pairs. +Parent memo insertion and the following resume are separately charged steps. ### Amortized allocation argument -The expensive insertion cannot repeat independently of the traversal that -prepares it. Count every allocated pair, including abandoned frames and local -memos. Define accounting credit as `50*consumed_units - allocated_pairs`, excluding -once-per-request setup/failure carriers. This is a proof quantity, not runtime -state. The following bounds also include substitution's reservation carriers: +Expensive memo inserts cannot happen without the traversal steps that build up +to them. Counting every allocated pair (including dropped frames and local +memos), define credit as `50*consumed_units - allocated_pairs`, excluding fixed +setup and failure pairs. This is a proof invariant, not runtime state. The table +below includes substitution's reservation pairs: | Transition branch | Ground pairs | Template pairs | | --- | ---: | ---: | @@ -108,56 +103,52 @@ state. The following bounds also include substitution's reservation carriers: | Identity/completed-memo shortcut | 0 | 4 | | Head mismatch or terminal successful resume | 4 | 8 | -At entry to a visit at pending depth `d`, credit is at least `42*d`; at entry -to a resume it is at least `42*(d-1)`. A child-entry transition earns at least -42 credits before increasing depth. Leaf insertion spends at most 44 before -resuming at the same depth. Parent completion spends at most 44 before resuming -one level lower. Advancing to another child earns at least 42 before visiting at -the same depth. Shortcuts earn at least 46; a terminal resume earns at least 42 -and returns with nonnegative credit. Mismatch also terminates with nonnegative -credit. These cases cover arbitrary arity, repeated DAG visits, and immutable -frame replacement, not just unary or successful inputs. +At entry to a visit at pending depth `d`, credit is at least `42*d`; at entry to +a resume it is at least `42*(d-1)`. Entering children earns at least 42 credits +before raising depth. Leaf insertion spends at most 44 before resuming at the +same depth, and parent completion spends at most 44 before resuming one level +lower. Advancing to the next child earns at least 42 at the same depth. +Shortcuts earn at least 46, and a terminal resume earns at least 42 and returns +with nonnegative credit. Mismatches also end with nonnegative credit. This holds +for arbitrary arity, shared DAG visits, and immutable frame updates, not only +unary or matching terms. A substituted variable suspends its visit after allocating four reservation -pairs, retaining 46 credits. Ground comparison starts at its own depth zero; -any interrupted prefix has deficit at most 44, covered by those 46. A completed -ground call returns nonnegative credit; the subsequent at-most-88-pair local -insertion then leaves at most 38 of the permitted template-visit deficit. -Ground never -calls substitution, so there is no unbounded nesting of suspended deficits. -Dropping a local memo does not refund allocation or reset credit. - -Thus any charged traversal prefix has deficit at most 44, and every completed -call has nonnegative credit. Positive bulk reservations, proof indexes, rows, -and premises allocate at most eight pairs per unit under their separate source -ledgers, so do not introduce deficits. The fixed 128 pairs cover the single -unfinished-prefix deficit, seven session-setup pairs, and terminal outcome and -boundary carriers, including an uncharged refusal. Failure stops checking; -there is no per-call or per-row renewal of this allowance. A future allocation -or control-flow change must reestablish these inequalities before using this bound. - -Live pending depth and completed memo entries are each bounded by consumed -steps; a comparison pair has at most the admitted ground depth. There is no -additional logical-depth cutoff or unbounded lookup in a linked memo list. -Host watchdogs and outer evaluator failures are not owned comparison outcomes. -[Checked substitution](SUBSTITUTION.md) shares this counter and adds positive -bulk reservations for clause scans and template indexes; a bulk refusal reports -the exact `used+amount`, which may exceed the limit by more than one. -Its local memo is separate from the ground memo. [Proof processing](CHECKING.md) -also charges its index, rows, and ordered congruence premises to this counter. +pairs, keeping 46 credits. Ground comparison starts at depth zero, so any +interrupted prefix has deficit at most 44, covered by those 46 credits. A +completed ground call returns nonnegative credit, and the local memo insert +(at most 88 pairs) leaves at most 38 of the allowed template-visit deficit. +Because ground comparison never calls substitution, suspended deficits cannot +nest arbitrarily. Dropping a local memo never refunds pairs or resets credit. + +Every charged prefix therefore has deficit at most 44, and every completed call +has nonnegative credit. Bulk reservations, proof indexes, rows, and premises +allocate at most eight pairs per unit under their own budgets, creating no +deficit. The fixed 128 pairs cover one unfinished-prefix deficit, seven setup +pairs, and final result or refusal pairs. Checking stops on failure, so this +allowance is never renewed per call or row. Any future allocation or control-flow +change must re-prove these inequalities. + +Live stack depth and completed memo entries are bounded by consumed steps, and +comparison pairs stay within ground term depth. There is no extra depth cutoff +or linear scan of a memo list. Host watchdogs and evaluator crashes are not +comparison results. [Checked substitution](SUBSTITUTION.md) shares this counter +and adds bulk reservations for clause scans and template indexes; a bulk refusal +reports exact `used+amount`, which may exceed the limit by more than one. Its +local memo stays separate from the ground memo. [Proof processing](CHECKING.md) +also charges its index, rows, and congruence premises to this counter. ## Private results and diagnostics -Success is tag 6 `Compared`, with payload `(pair equal session)`. `equal` is -scalar 0 or 1, not a proof judgment. `comparison_equal(payload)` and -`comparison_session(payload)` own those projections; `comparison_steps(session)` -returns the consumed step count. A false result still returns the current session -so source-owned coordination can continue without resetting work or memo state. - -Diagnostic entries first call `check_derivation_ground()` and forward failures -unchanged. After successful admission they select explicit source-owned comparison -calls. Each Compared observation is tag 6 plus Boolean and consumed steps as two -little-endian u64 words (17 bytes); failures are tag 1/2 plus the existing four -u64 fields (33 bytes). A diagnostic may publish a documented sequence of these -observations, but process status zero only attests that diagnostic publication. -No proof-accepting production `main` is supplied. +Success returns tag 6 `Compared` with payload `(pair equal session)`, where +`equal` is scalar 0 or 1 (not a proof verdict). `comparison_equal(payload)` and +`comparison_session(payload)` read those fields, and `comparison_steps(session)` +reads the step count. A false result still returns the updated session so the +caller can keep going without resetting work or memo state. + +Diagnostic entries call `check_derivation_ground()` first, passing failures +through unchanged, then run explicit comparison calls. Each Compared result +writes tag 6 plus Boolean and consumed steps as two little-endian u64 words (17 +bytes); failures write tag 1 or 2 plus four u64 words (33 bytes). A diagnostic +may emit several results in order, and exit status zero means only that those +diagnostics were written. No proof-accepting production `main` exists here. diff --git a/tests/bootstrap/proofs/checker/FORMAT.md b/tests/bootstrap/proofs/checker/FORMAT.md index b30f02aac5cb..e73895fbd258 100644 --- a/tests/bootstrap/proofs/checker/FORMAT.md +++ b/tests/bootstrap/proofs/checker/FORMAT.md @@ -2,37 +2,38 @@ [Envelope](REQUEST.md) | [Checker](README.md) | [Full subject](../beta_encoding/ACCEPTANCE.md) -This is the concrete inner encoding, not an accepted checker or certificate. -The [layout admission](LAYOUT.md) traverses physical fields and -[theory formation](FORMATION.md) checks conservative definitions. -[Ground checking](GROUND.md) validates owner/witness term tables and root sorts. -[Structural comparison](COMPARISON.md) compares validated term syntax with -session-scoped memoization. [Checked substitution](SUBSTITUTION.md) compares a -stated clause body under syntax-derived bindings. [Proof checking](CHECKING.md) -checks all rows and the final root under a combined generic profile. The complete -Beta theory, whole-Beta certificate, and artifact-specific acceptance remain open. +This document defines the binary inner format, not an accepted checker or +certificate. [Layout admission](LAYOUT.md) scans physical fields, +[theory formation](FORMATION.md) checks conservative definitions, +[ground checking](GROUND.md) validates owner and witness term tables and root +sorts, [structural comparison](COMPARISON.md) compares term syntax with +session-scoped memoization, [checked substitution](SUBSTITUTION.md) verifies a +clause body under syntax-derived bindings, and [proof checking](CHECKING.md) +verifies every proof row and the owner root under a combined generic budget. The +full Beta theory, complete Beta certificate, and artifact acceptance remain +separate steps. ## Common physical representation -Each section starts with its four literal magic bytes. Every subsequent field -is a four-byte little-endian unsigned word with its high bit clear, including -tags, counts, references, and record lengths. No padding, optional fields, -names, strings, digests, or extension records occur. These administrative words -do not provide arithmetic operations or integer constants to the theory. - -`record(fields...)` means a word containing the number of following payload -words, followed by those exact words. Nested records count their own length -word as part of the enclosing payload. `table` means a count followed by that -many records. The listed fields consume the exact record or section; unknown -tags, extra fields, incomplete words, and trailing bytes reject. - -All row identities are implicit one-based positions. Zero is not a row -reference. Counts and explicitly zero-based argument/variable positions may -be zero. There are no producer-assigned row identities to alias or redefine. -Counts are checked against remaining physical extent before iteration or -allocation; a record payload fits only when its word count is no greater than -the remaining byte count divided by four. Advance its end only after that -subtractive check. Nested record ends cannot escape their containing record. +Each section begins with four literal magic bytes. Every remaining field is a +four-byte little-endian unsigned word with its high bit clear, including tags, +counts, references, and record lengths. The format contains no padding, optional +fields, names, strings, digests, or extensions. These wire words do not add +arithmetic or integer constants to the theory. + +`record(fields...)` means a length word giving the number of payload words that +follow, followed by those exact words. Nested records include their own length +word in the enclosing payload count. `table` means a row count followed by that +many records. Fields must consume each record and section completely; unknown +tags, extra fields, partial words, and trailing bytes fail. + +All row IDs are implicit one-based positions; zero is never a valid row +reference. Counts and zero-based argument or variable positions may be zero. +Producers cannot assign row IDs, so they cannot alias or redefine rows. Check +every count against remaining bytes before looping or allocating: a record +payload fits only when its word count is at most remaining bytes divided by +four. Advance the cursor only after that subtraction check. Nested records +cannot extend past their enclosing record. ## Theory section: `GTH1` @@ -46,10 +47,10 @@ function_table exact end ``` -Sort identities are `1..sort_count`; at least one is required. Constructors -and functions have separate identity spaces distinguished by application tags. -Their identity is their exact position in this owner-controlled theory, not -a textual name or a certificate claim about a name. +Sort IDs are `1..sort_count`, with at least one sort required. Constructors and +functions use separate ID spaces distinguished by application tags. Their ID is +their position in this owner-supplied theory, never a textual name or +certificate claim. A constructor record contains: @@ -64,13 +65,13 @@ result_sort, argument_count, argument_sorts[argument_count], mode, selected_argument, clause_table ``` -Mode 0 is the single nonrecursive variable clause; `selected_argument` must be -zero and there must be exactly one clause. Mode 1 is constructor case analysis; -`selected_argument` is a zero-based argument index strictly below the arity. -Its clauses occur in increasing constructor identity order and cover exactly -the constructors returning that argument's sort. There is no empty case over -an uninhabited sort: formation establishes finite inhabitation of every sort. -Any other mode rejects. +Mode 0 is a single nonrecursive variable clause: `selected_argument` must be zero +and there must be exactly one clause. Mode 1 is constructor case analysis: +`selected_argument` is a zero-based argument index below the arity, and clauses +appear in increasing constructor ID order covering every constructor that +returns that argument's sort. Empty case splits over uninhabited sorts are +disallowed because formation requires every sort to have a finite inhabitant. +Any other mode fails. A clause record contains: @@ -78,19 +79,19 @@ A clause record contains: constructor, template_table, body ``` -For mode 0, `constructor` must be zero. For mode 1, it names the constructor -matched by this clause. `body` names a row in this clause's nonempty template -table. All template rows are checked, whether reachable from `body` or not. +In mode 0, `constructor` must be zero. In mode 1, it names the matched +constructor. `body` names a row in this clause's nonempty template table. Every +template row is checked, even if `body` does not reach it. ### Clause-local variables and templates -An arity-`a` mode-0 clause binds variable slots `0..a-1` to the corresponding -arguments, with the signature's sorts. In a mode-1 clause selecting argument -`s`, slots `0..a-1` except `s` bind the other arguments; slot `s` is **unbound**. -For a constructor with `k` fields, slots `a..a+k-1` bind its immediate children -in field order, with the constructor's argument sorts. No other slot is bound. -Thus patterns are linear by construction; there is no encoded renaming map, -nested pattern, repeated binder, or way to bind the matched parent as a child. +An arity-`a` mode-0 clause binds variable slots `0..a-1` to the function +arguments with their declared sorts. A mode-1 clause matching argument `s` binds +slots `0..a-1` except `s` to the other arguments; slot `s` is **unbound**. For a +constructor with `k` fields, slots `a..a+k-1` bind its immediate children in +field order with the constructor's argument sorts. No other slot is bound. +Patterns are linear by construction, with no renaming map, nested pattern, +repeated binder, or binding to the matched parent. Each template row is one of: @@ -100,22 +101,22 @@ record(1, constructor, argument_count, children[argument_count]) record(2, function, argument_count, children[argument_count]) ``` -Template children refer strictly backward within this clause's table. They -cannot refer to a different clause, an owner ground term, or a certificate term. -Slots resolve only in this clause's binding environment. Sorts are inferred -from that environment and the theory signatures, never supplied as unchecked -row annotations. Applications have exact declared arity and argument sorts; -the body has the defining function's result sort. - -Function applications in function `f` may name a function below `f`. A self-call -may name `f` only in mode 1, and its selected child must be a variable row naming -one of this clause's immediate constructor-child slots of the selected sort. -A smaller template row number is not evidence of structural decrease. Calls -above `f`, self-calls in mode 0, and reconstructed or computed selected values -reject. These checks apply to unused template rows too. The -[formation argument](FORMATION.md#conservative-definition-soundness) -also requires declared sorts and their finite inhabitation; physical decoding -alone does not admit the theory. +Template children refer strictly backward within the same clause's table and +cannot reference another clause, an owner term, or a certificate term. Slots +resolve only in this clause's environment. Sorts are inferred from that +environment and theory signatures, never from unchecked annotations. +Applications must match declared arity and argument sorts, and the body must +match the function's result sort. + +Calls in function `f` may target any function below `f`. A direct self-call to +`f` is allowed only in mode 1, and its selected argument must be a variable row +naming an immediate constructor-child slot of the selected sort. A smaller +template row number does not prove structural decrease. Calls above `f`, mode-0 +self-calls, and computed or reconstructed selected arguments fail. These rules +apply to unused template rows as well. The +[formation argument](FORMATION.md#conservative-definition-soundness) also +requires declared sorts to be finitely inhabited; physical decoding alone does +not validate a theory. ## Proposition section: `GPR1` @@ -126,19 +127,19 @@ left, right exact end ``` -The table contains only constructor or function application records, with the -same tags 1 and 2 and field order as template applications. Variables are -forbidden. Each child refers strictly backward in this table. The two root -references name rows in this table with the same inferred sort. Every row must -be a well-sorted ground term, even if the root does not reach it. +The table holds only constructor and function application records (tags 1 and 2, +same field order as templates); variables are forbidden. Children refer strictly +backward within this table. Both root fields reference rows in this table with +the same inferred sort. Every row must be a well-sorted ground term, even if the +root never reaches it. -The artifact owner independently fixes this entire section and the theory -section. In the first complete customer, they encode the exact proposition -`encode_Beta(S, source_limit, output_limit) = Success(T)`. Raw source and tape -bytes, word values, and bounds are ordinary constructor terms under that -theory; no byte-string literal, host assembler result, or hash becomes a -trusted checker operation. Exact source/tape custody remains the artifact -owner's responsibility outside this generic format. +The artifact owner supplies this entire section and the theory section +independently. For the first complete target, they encode +`encode_Beta(S, source_limit, output_limit) = Success(T)`. Source and tape +bytes, words, and limits are ordinary constructor terms in that theory; no byte +literal, host assembler output, or hash becomes a trusted checker operation. +Verifying the source and tape remains the artifact owner's job outside this +generic format. ## Certificate section: `GCE1` @@ -149,17 +150,16 @@ proof_table exact end ``` -Let `R` be the owner term count. Witness term row `i` has global term reference -`R+i`; the sum must fit the administrative word. Its application children may -name any owner term or an earlier witness term, hence lie in `1..R+i-1`. -This read-only extension preserves owner term identities and prevents the root -from depending on producer-owned rows. The kind, arity, and sort checks are -identical to owner ground terms. Sharing and duplicate structural terms are -both legal; this format is not a unique serialization of mathematical trees. +Let `R` be the owner term count. Witness row `i` has global ID `R+i`, which must +fit the administrative word. Its children may reference any owner term or +earlier witness term (`1..R+i-1`). This read-only extension preserves owner term +IDs and stops the owner root from depending on producer rows. Kind, arity, and +sort checks match owner ground terms. Both sharing and duplicate terms are +legal; the format does not enforce a single canonical DAG. -Every proof row starts with `rule, left, right`, where both term references -name well-sorted ground terms in the complete owner-plus-witness table and have -the same sort. Rule payloads are: +Every proof row starts with `rule, left, right`, where both term IDs name +well-sorted ground terms of the same sort in the combined owner-plus-witness +table. Rule payloads are: | Rule | Exact record payload | Required relation | | --- | --- | --- | @@ -169,85 +169,80 @@ the same sort. Rule payloads are: | 4 Congruence | `4, left, right, count, premises[count]` | Same application tag and symbol on both sides; count equals their arity; each ordered earlier premise relates the corresponding arguments. | | 5 Unfolding | `5, left, right, clause` | Left applies a formed function; its one-based local clause matches syntactically, and its body under the derived binding equals right. | -Premises are proof-row identities strictly below the current row, not term -identities. Every supplied proof row is checked, including unused rows. The -proof table is nonempty and its **last** row must conclude the owner root in -the stated orientation. There is no producer-selected root index or unchecked -premise. Root comparison is structural, not equality of row numbers. - -For unfolding, mode 0 binds all left arguments. Mode 1 first requires the -selected left argument to be an explicit constructor application of the stated -clause; its children supply that clause's child slots. A defined application -is not silently evaluated to choose a clause. Compare the claimed right term -against the template under precisely this environment, without creating a new -variable or normalizing either side. This derives the substitution from checked -syntax rather than trusting a supplied substitution or expanding an entire -intermediate tree. +Premises are proof-row IDs strictly below the current row, never term IDs. Every +proof row is checked, including unused rows. The proof table must be nonempty, +and its **last** row must conclude the owner root in the exact orientation. +Producers cannot pick a conclusion row or leave a premise unchecked. Root +matching is structural, not row-ID equality. + +In unfolding, mode 0 binds every argument of the left call. Mode 1 first +requires the selected argument of the left call to be an explicit constructor +application matching the stated clause; its children fill the clause's child +slots. Defined functions are never evaluated silently to choose a clause. The +checker compares the right term against the template under that exact binding +without inventing variables or normalizing either side, deriving the +substitution from checked syntax instead of trusting a supplied map or expanding +an intermediate tree. ## Comparison and finite execution -Structural equality compares application tags, symbol identities, and ordered -children, without interpreting definitions. Validated identical scalar term -references in the same request may shortcut that comparison. Gamma pair -addresses and hash equality never establish semantic equality. Completed -comparison memo entries must include both term identities; template comparison -also includes clause and substitution environment identity. An in-progress or -budget-interrupted comparison cannot populate a successful memo entry. - -Decode with explicit cursors and table indexes. Do not repeatedly scan a linked -list for arbitrary row lookup or copy every sealed-input byte into a pair. -Comparison and substitution use bounded explicit worklists, preserving DAG -sharing; recursively expanding two separately encoded shared trees can require -exponential work. The recorded historical subject has byte-list representations -with 47,756- and 8,575-element spines. Gamma's source syntax -and native call-depth limits must not become the logical term-depth limit. - -The implementation must publish a concrete, adjustable profile before accepting -proofs: request and table extents, arity, logical depth, live worklists, memo -entries, cumulative work, cumulative pair allocation, and output. Dropping an -immutable worklist does not reclaim Gamma pairs. Charge allocations across the -whole request, including indexes, helper results, comparisons, and substitutions; -reserve enough evaluator space to publish an owned refusal. Validate counts -before resource-dependent loops, and resource availability before the operation. -An outer trap, timeout, or evaluator refusal is never a checker judgment. - -The 130 MiB request provision was selected from the measured complete encoding -certificate, not the other way around; the certificate, not this format's -small examples, set it. Private provisions were adjusted without weakening the -owner root or introducing trusted arithmetic. Rule retention remains conditional -on actual use and mutation controls in that complete certificate. +Structural equality compares application tags, symbol IDs, and ordered children +without evaluating definitions. Identical validated scalar term IDs in the same +request may shortcut directly. Gamma pair addresses and hashes never establish +equality. Completed ground memo entries key on both term IDs; template memos +also depend on clause and binding environment. An in-progress or interrupted +comparison must never enter a completed memo. + +Decode with explicit cursors and row indexes instead of repeatedly scanning +linked lists or copying input bytes into pairs. Comparison and substitution use +explicit bounded worklists to preserve DAG sharing, avoiding exponential blowup +on separately encoded shared trees. The historical subject includes byte lists +with 47,756- and 8,575-element spines, so Gamma's syntax and call-depth limits +must not cap logical term depth. + +The implementation must document concrete, adjustable limits before accepting +proofs: request and table sizes, arity, depth, live worklists, memos, cumulative +work, cumulative pair allocation, and output. Dropping an immutable worklist +does not free Gamma pairs. Charge allocations across the entire request +(indexes, helpers, comparisons, substitutions) and leave space to write an +explicit refusal. Validate counts before loops and check resource limits before +doing work. Outer traps, timeouts, and evaluator failures are never checker +verdicts. + +The 130 MiB request limit was sized for the measured complete encoding +certificate rather than these small examples. Adjusting private limits never +weakens the owner root or adds trusted arithmetic. Keeping each rule still +depends on actual use and mutation tests in that complete certificate. ## Decoder and checker acceptance controls -Physical decoding must reject truncated/high-bit words, record extent escapes, -wrong tags, mismatched counts, surplus fields, and unconsumed section bytes. -Formation controls include uninhabited sorts, wrong arity/sort, cross-clause or -unbound variables, missing/duplicate cases, forward calls, and nondecreasing -self-calls, including errors in unused rows. - -Term controls cover zero, forward, cyclic, and cross-owner references; variable -tags in ground tables; deep source spines; and separately encoded shared DAGs. -Proof controls cover every rule's positive and corrupt premises, unmatched -clauses, substituted environments, wrong final roots, and failures after valid -prefixes. Every published resource needs exact and adjacent controls with no -acceptance on exhaustion. These are full-checker implementation requirements, -not recorded semantic test results. The outer and layout gates establish only -their respective physical-input contracts; the formation gate establishes the -theory contract. The ground gate checks term validity and root sorts, not a -ground equality proof. The comparison gate distinguishes structural agreement -from theory equality and checks cumulative session exhaustion; it does not -discharge a supplied proof row. -The substitution gate checks one stated unfolding and its cumulative work; -it does not validate the proof table or enforce the final root. -The checking gate exercises the whole generic derivation and final root. Its -Checked result is not authentication of an artifact's theory or proposition. +Layout tests must reject truncated or high-bit words, record overflows, unknown +tags, wrong counts, extra fields, and trailing section bytes. Formation tests +cover uninhabited sorts, wrong arity or sort, cross-clause or unbound variables, +missing or duplicate cases, forward calls, and nondecreasing self-calls, +including errors in unused rows. + +Ground-term tests cover zero, forward, cyclic, and cross-owner references, +variable tags in ground tables, deep spines, and separately encoded shared DAGs. +Proof tests cover every rule's valid and corrupted premises, unmatched clauses, +wrong substitutions, wrong final roots, and errors after valid prefixes. Every +resource limit needs exact and adjacent boundary tests with no acceptance on +exhaustion. These are full-checker requirements, not a claim of completed +semantic runs. Outer and layout gates verify only their physical contracts; the +formation gate verifies theory formation; the ground gate validates terms and +root sorts without checking equality; the comparison gate separates structural +equality from theory equality and tests session exhaustion without checking +proof rows; the substitution gate tests single unfoldings and cumulative work +without checking proof tables or the owner root; and the checking gate tests +full generic derivations and the final root without authenticating an artifact's +theory or proposition. ### Hand-worked field-layout example -The following three sections describe a sort with constructors `zero`, `next`, -and the nonrecursive function `identity(x) = x`. Names are explanatory only. -Each displayed integer is one encoded word; parentheses here expand with -`record(...)` as defined above, and table counts are explicit: +These three sections define one sort with constructors `zero` and `next`, and +nonrecursive function `identity(x) = x` (names are explanatory only). Each +integer is one encoded word; `record(...)` expands as defined above, and table +counts are explicit: ```text "GTH1", 1, 2, @@ -266,11 +261,10 @@ Each displayed integer is one encoded word; parentheses here expand with record(5, 3, 2, 1) ``` -The clause and function payload lengths are 6 and 13 words. Section lengths -are 100, 72, and 32 bytes, making a 228-byte outer request. The intended root is -`identity(next(zero)) = next(zero)`; the one unfolding row substitutes owner -term 2 for slot 0. The formation and ground gates check this theory and its -ground terms but do not validate the unfolding row or accept the equality. -The substitution gate checks this unfolding in isolation; the checking gate -checks its proof row and final root. Neither replaces the full Beta encoding -certificate. +Clause and function payloads are 6 and 13 words; section sizes are 100, 72, and +32 bytes, giving a 228-byte request. The root claims +`identity(next(zero)) = next(zero)`, and the single unfolding row binds slot 0 +to owner term 2. Formation and ground gates validate this theory and its ground +terms without checking the proof row; the substitution gate checks the unfolding +alone; the checking gate verifies the proof row and final root. None of them +replaces the complete Beta encoding certificate. diff --git a/tests/bootstrap/proofs/checker/FORMATION.md b/tests/bootstrap/proofs/checker/FORMATION.md index 01ecfdf69a5e..7c6bd13ad776 100644 --- a/tests/bootstrap/proofs/checker/FORMATION.md +++ b/tests/bootstrap/proofs/checker/FORMATION.md @@ -3,183 +3,174 @@ [Inner format](FORMAT.md) | [Layout](LAYOUT.md) | [Soundness argument](FORMATION.md#conservative-definition-soundness) `form_derivation_theory()` checks the owner-supplied constructor and function -definitions after physical layout admission. It does not validate the ground -term tables, proof rows, or root equality. A formed theory is not an accepted -proof, nor evidence that the definitions faithfully formalize Beta. +definitions after layout checking passes. It does not check ground-term tables, +proof rows, or root equality. A valid formed theory does not mean a proof is +accepted or that the definitions faithfully model Beta. ## Admission and private provision -First call `admit_derivation_layout()` and forward any failure unchanged. -Only its tag 3 permits reading theory fields without repeating physical checks. -The sort count `S` at request offset 28 must be positive. Zero selects rejection -code 7 at that field. Counts above 65,536 select resource code 2 `theory_sorts`, -with coordinate 28, limit 65,536, and the actual requested count. +Call `admit_derivation_layout()` first and pass any failure through unchanged. +Only tag 3 allows reading theory fields without repeating layout checks. The +sort count `S` at offset 28 must be positive: zero fails with rejection code 7 +at offset 28, and counts above 65,536 fail with resource code 2 `theory_sorts`, +offset 28, limit 65,536, and the requested count. -Before allocating indexes, census the constructor and function tables. Let `C` -and `F` be their counts, `A` the sum of constructor arities, and `W` the theory -payload word count after its four magic bytes. Apply this conservative work -estimate: +Before building indexes, scan the constructor and function tables to compute a +work estimate. Let `C` and `F` be their counts, `A` the sum of constructor +arities, and `W` the theory payload word count after the four magic bytes: ```text E = (S + 1) * (C + A) + F * C + 4 * W + S ``` -An estimate above 8,388,608 selects resource code 3 `formation_work_bound`, -coordinate 28, limit 8,388,608, and the exact estimate `E`. Equality proceeds. -This check precedes semantic signature errors. It bounds named row/field -processing visits: inhabitation passes, constructor-catalog scans for case -definitions, ordinary indexing/validation passes, and a final sort scan. A -visit may include bounded indexed lookup; `E` is not a count of Gamma or Alpha -instructions, elapsed time, or every internal tree-descent iteration. - -The admitted request bounds `W`, `C`, `F`, and `A` below 2^26 by raw size, and -the estimate's `4W` term then keeps `W <= 2^21` regardless of the request -extent; the separate sort check bounds `S` by 2^16. The entire estimate fits signed 64-bit arithmetic, -including requests that exceed the provision. No wrapping estimate or truncated -diagnostic is permitted. These provisions are adjustable implementation choices, -not restrictions on conservative definitions. The whole-Beta certificate still -has to demonstrate suitable end-to-end provisions before proof acceptance. +If `E` exceeds 8,388,608, fail with resource code 3 `formation_work_bound`, +offset 28, limit 8,388,608, and exact estimate `E`. Equality passes. This +preflight runs before semantic signature checks and bounds major row/field +passes: inhabitation loops, constructor scans for case definitions, indexing and +validation passes, and a final sort check. Each visit may perform bounded index +lookups; `E` does not count Gamma or Alpha instructions, wall time, or every +tree-descent step. + +Raw request size bounds `W`, `C`, `F`, and `A` below 2^26, the `4W` term keeps +`W <= 2^21` regardless of request size, and the sort check caps `S` at 2^16. The +full estimate fits signed 64-bit arithmetic even when it exceeds the limit, so +estimates never wrap or truncate. These limits are adjustable implementation +choices, not restrictions on conservative definitions. The full Beta certificate +still needs suitable end-to-end budgets before acceptance. ## Deterministic semantic checks After the preflight, build immutable indexes for the constructor and function -records. Check all constructor signatures in declaration order, followed by -all function signatures in declaration order. Within a signature, check the -result sort and then argument sorts in field order. Every sort reference must -lie in `1..S`; failure selects its own field coordinate. Signature checking -precedes inhabitation and all clause/body checking. +records. Check all constructor signatures in declaration order, then all +function signatures in declaration order. Within each signature, check the +result sort first and then argument sorts in field order. Every sort reference +must fall in `1..S`; any failure reports that field's offset. Signature checks +finish before inhabitation and clause checking begin. ### Finite constructor inhabitants -Start with no inhabited sorts. In constructor order, mark a constructor's result -sort when all its argument sorts are marked; nullary constructors mark their -sort immediately. A mark is visible to later constructors in the same pass. -Repeat while a pass adds marks and not all sorts are marked. There are at most -`S` successful marks and `S+1` passes. If a pass adds none while a sort is still -unmarked, reject at the sort-count field, offset 28. Recursive constructors -alone cannot establish a finite inhabitant. No equality axiom is introduced. +Start with all sorts unmarked. In constructor order, mark a constructor's result +sort whenever all its argument sorts are already marked; nullary constructors +mark their sort on the first pass. Marks become visible immediately within the +same pass. Repeat while a pass adds at least one mark and unmarked sorts remain +(at most `S` marks and `S+1` passes). If a pass adds no mark while an unmarked +sort remains, reject at offset 28 (the sort-count field). Recursive constructors +alone cannot prove a finite inhabitant. No equality axioms are added. ### Clauses and template scopes -Process functions in declaration order. For mode 0, require selected argument -zero, then exactly one clause, then constructor zero in that clause. Failures -belong to the selected-argument, clause-count, and clause-constructor fields, -respectively. For mode 1, require the selected index below the function arity; -failure belongs to the selected-argument field. Scan the constructor -catalog once in identity order, consuming one clause for every constructor -returning the selected argument sort. Validate that clause before continuing -the catalog scan. Missing clauses reject at the clause-count field; wrong -constructor identities reject at the current clause's constructor field. -After the catalog ends, any extra clause rejects at its constructor field. -Thus an earlier clause error precedes a later missing or extra case. - -Each clause requires a nonempty template table, indexed within that clause -only. Reject an empty table at its count field. Visit every template row in -table order, including rows unused by the body. Variable slots follow FORMAT's -implicit environment: other arguments retain their zero-based slots, the -selected parent is unbound, and constructor children occupy the slots starting -at the function arity. An unbound slot rejects at its slot field. - -For an application, check the symbol reference first, then the function-order -restriction, then exact signature arity, then children in argument order. -An arity mismatch rejects at the application's argument-count field. -Each child must be a positive reference below the current local template row; -check its inferred sort against that argument's declared sort. A bad reference -or argument sort rejects at that child-reference field. Sorts of already checked -rows come from their bound slot or referenced symbol signature, not an unchecked -annotation or recursively expanded term. Duplicate structural rows are allowed. - -A function reference above the current function rejects at its symbol field. -A direct self-call also rejects there in mode 0. In mode 1, after all arguments -pass, require the selected child to be a variable row naming an unchanged -immediate constructor-child slot. Its sort has already been checked against -the selected parameter sort. A computed expression, reconstructed parent, -unselected parameter, or matched-parent slot cannot witness decrease; reject -at the self-call's selected child-reference field. A smaller row identity alone -does not prove termination. - -Finally, the body reference must name a row in this local nonempty table and -have the function result sort. Reject either defect at the body-reference -field. No later function, other clause, ground term, or certificate row can -supply a variable binding, premise, or template reference. - -All semantic failures use tag 1, code 7 `theory_formation`, their specified -request coordinate, and zero limit/requested. No partial formed context escapes -on failure. Resource outcomes use existing tag 2 with the fields above. +Check functions in declaration order. For mode 0, require selected argument +zero, exactly one clause, and constructor zero in that clause; failures report +the selected-argument, clause-count, and clause-constructor fields, +respectively. For mode 1, require the selected argument index to be below the +function arity, failing at the selected-argument field. Scan the constructor +table once in ID order, consuming one clause for each constructor returning the +selected sort and checking that clause before continuing. Missing clauses fail +at the clause-count field; wrong constructor IDs fail at that clause's +constructor field. Any extra clause after the scan finishes fails at its +constructor field. Earlier clause errors therefore take priority over later +missing or extra cases. + +Each clause must have a nonempty local template table; an empty table fails at +its count field. Check every template row in order, including rows unused by the +body. Variable slots use FORMAT's implicit environment: other arguments keep +their zero-based slots, the selected argument is unbound, and constructor +children take slots starting at the function arity. Unbound slots fail at the +slot field. + +For each application, check the symbol reference, function-order rule, exact +arity, and children in argument order. Wrong arity fails at the argument-count +field. Each child must be a positive reference strictly below the current +template row, with an inferred sort matching the declared argument sort; either +error fails at that child-reference field. Checked row sorts come from the bound +slot or symbol signature, never unchecked annotations or expanded terms. +Duplicate rows are allowed. + +Calling a function above the current function fails at the symbol field. Direct +self-calls also fail there in mode 0. In mode 1, after all arguments pass, the +selected argument of a self-call must be a variable row naming an unchanged +immediate constructor-child slot (its sort was already checked against the +selected parameter sort). Computed expressions, reconstructed parents, +unselected parameters, and the matched-parent slot cannot prove decrease and +fail at the selected child-reference field. A smaller row ID alone does not +prove termination. + +Finally, the body reference must name a row in this clause's template table and +have the function's result sort; either failure reports the body-reference +field. No later function, other clause, ground term, or proof row can supply a +variable binding, premise, or template reference. + +All semantic failures return tag 1, code 7 `theory_formation`, the failing +request offset, and zero for limit and requested. No partial formed state +escapes on failure. Resource failures return tag 2 with the fields above. ## Indexed representation and containment -A row index is `(pair count tree)`. Its nonempty tree is balanced by splitting -the known count into `floor(count/2)` left rows and the remaining right rows. -A leaf is its scalar record-start offset; an internal node is a pair of child -trees. Count zero has scalar tree zero. Lookup validates the scalar row identity -before descending; Gamma pair references are never tested as integers. - -Build from the sequential sealed records once; a builder returns a tree and -the next cursor. A nonempty `n`-row build uses `3n-2` pairs plus its one index -pair; an empty index uses two. Lookup allocates none and has at most 21 tree -edges under the admitted request bound. Template indexes are clause-local and -may become unreachable after checking, but their allocations still count. - -Sort marks use a sparse immutable balanced tree over `1..S`: shared -`Empty=(pair 0 0)`, shared `True=(pair 1 0)`, and occupied internal nodes -`(pair 1 (pair left right))`. Inspect scalar tags and the known tree range before -projecting children; never compare a pair with scalar zero. Each sort changes -from absent to present at most once. An update copies at most 16 internal nodes, -two pairs each, and reuses the shared true leaf. Bounded native recursion, -not allocated rebuild frames, carries the update path. The two shared constants -belong to the fixed allocation allowance. - -The implementation's cumulative allocation must stay below -`8W + 32S + 128` pairs, including indexes, clause contexts, pass results, and -terminal outcomes. This is below 18,874,496 pairs for the admitted extents, -within the selected Gamma arena of 3,387,293,850. Scalar field validation must not -allocate a result tuple per visit. Balanced-tree recursion follows logarithmic -index height; row, argument, constructor, and pass scans are tail calls. -The [complete generic checking ledger](CHECKING.md#complete-generic-execution-provision) -accounts for the additional stages without resetting cumulative allocation. -The [ground-term stage](GROUND.md#work-allocation-and-depth) accounts for its -indexes and checking state cumulatively with this formation ledger. - -For the cumulative ledger, let `T` be all template rows, `K` all clauses, and -`M` the number of newly marked sorts. Index construction uses at most -`3(C+F+T)+4` pairs: only the two global indexes can be empty, since an empty -template table rejects before building. Function/clause contexts use -`2F+2K`; pass carriers use at most `M+1 <= C+1`; mark paths use at most -`32M <= 32S`. Shared mark constants, the retained layout/context, and a terminal -outcome add eleven pairs. Thus the actual bound is -`4C+5F+3T+2K+32S+16`. The wire has at least -`W >= 3C+6F+3T+4K`, so this is at most `2W+32S+16`, below the allowance above. -These counts include allocations that become unreachable: Gamma does not -reclaim them during this evaluation. +A row index is `(pair count tree)`. Nonempty trees balance by splitting `count` +into `floor(count/2)` left rows and the remaining right rows. Leaves store +scalar record-start offsets; internal nodes store pairs of child trees. An empty +index uses scalar tree zero. Lookup validates the scalar row ID before +descending and never tests Gamma pair references as integers. + +Build each index once from the sequential records; the builder returns a tree +and the next cursor. A nonempty `n`-row index allocates `3n-2` pairs plus one +wrapper pair; an empty index allocates two. Lookups allocate nothing and follow +at most 21 tree edges under the request cap. Clause-local template indexes +become unreachable after checking, but their allocations still count. + +Sort marks use a sparse immutable balanced tree over `1..S`, with shared +`Empty=(pair 0 0)`, shared `True=(pair 1 0)`, and internal nodes +`(pair 1 (pair left right))`. Always inspect scalar tags and the known range +before projecting children; never compare a pair with scalar zero. Each sort +flips from absent to present at most once, copying at most 16 internal nodes +(two pairs each) and reusing the shared true leaf. Bounded native recursion +handles updates without allocated rebuild frames. Both shared constants sit in +the fixed allocation allowance. + +Cumulative allocation must stay below `8W + 32S + 128` pairs, covering indexes, +clause state, pass results, and final outcomes (under 18,874,496 pairs for +admitted sizes, within the 3,387,293,850-pair Gamma arena). Scalar field checks +must not allocate a tuple per visit. Balanced-tree recursion stays logarithmic; +row, argument, constructor, and pass scans are tail calls. The +[complete generic checking ledger](CHECKING.md#complete-generic-execution-provision) +and [ground-term stage](GROUND.md#work-allocation-and-depth) add later +allocations cumulatively without resetting this count. + +Let `T` be total template rows, `K` total clauses, and `M` newly marked sorts. +Index building uses at most `3(C+F+T)+4` pairs (only the two global indexes can +be empty because empty template tables reject before building). Function and +clause contexts use `2F+2K`, pass wrappers at most `M+1 <= C+1`, and mark paths +at most `32M <= 32S`. Shared constants, retained layout/context, and the final +outcome add 11 pairs, giving at most `4C+5F+3T+2K+32S+16`. Since the wire layout +satisfies `W >= 3C+6F+3T+4K`, actual allocation is at most `2W+32S+16`, well +below the allowance. Unreachable pairs still count because Gamma does not +reclaim memory during evaluation. ## Conservative-definition soundness -Constructor sorts denote freely generated finite trees. Finite inhabitation -ensures every declared sort has such a value. Complete disjoint constructor -cases and sorted linear pattern variables make each function single-valued. -Earlier-function calls decrease definition order; a direct self-call decreases -the selected finite tree by consuming an unchanged immediate child. Their -lexicographic measure proves totality. Fresh functions therefore extend the -free constructor model conservatively rather than equating distinct constructors. -An acyclic term table alone does not prove function termination. There are no -equality axioms, arbitrary assumptions, binders, higher-order terms, mutual -recursive definitions, or unchecked recursive equations in this calculus. +Constructor sorts represent freely generated finite trees. Finite inhabitation +guarantees every sort has a value. Complete, disjoint constructor cases and +sorted linear pattern variables make every function single-valued. Calls to +earlier functions decrease definition order, and direct self-calls decrease the +selected tree by passing an unchanged immediate child; this lexicographic +measure proves totality. New functions therefore extend the free constructor +model conservatively without equating distinct constructors. Acyclic term tables +alone do not prove termination. The calculus contains no equality axioms, +assumptions, binders, higher-order terms, mutual recursion, or unchecked +recursive equations. ## Private formed outcome -Success is `(pair 4 payload)`, where payload is -`(pair frame (pair S (pair constructors functions)))`. `frame` retains the exact -three section ends from layout admission, and the two indexes retain all -constructor/function record starts. The payload accessors are `formed_frame`, -`formed_sort_count`, `formed_constructors`, and `formed_functions`; -`formation_index_count` reads an index count. `formation_index_lookup` returns -scalar zero for an invalid identity before descending. -This custody is private to the selected checker source, not a producer-supplied -claim or an artifact authentication mechanism. - -The diagnostic entry publishes tag 4 followed by the three section ends and -`S,C,F`, each as an eight-byte little-endian word. Failures publish their tag -and the four existing failure fields as eight-byte words, preserving large work -estimates. Process status zero means only that this owned diagnostic was -published. There is no production proof-accepting `main`. +Success returns `(pair 4 payload)`, where payload is +`(pair frame (pair S (pair constructors functions)))`. `frame` keeps the three +section ends from layout checking, and the two indexes hold all constructor and +function record offsets. Accessors are `formed_frame`, `formed_sort_count`, +`formed_constructors`, and `formed_functions`; `formation_index_count` reads an +index size, and `formation_index_lookup` returns scalar zero for invalid IDs +before descending. This structure is private to the checker source and does not +authenticate an artifact. + +The diagnostic entry writes tag 4 followed by the three section ends and `S,C,F` +as little-endian u64 words. Failures write their tag and four u64 fields so +large work estimates fit without truncation. Exit status zero means only that +the diagnostic output was written. No production proof-accepting `main` exists. diff --git a/tests/bootstrap/proofs/checker/GROUND.md b/tests/bootstrap/proofs/checker/GROUND.md index 061d698f9aec..40eca1b61be1 100644 --- a/tests/bootstrap/proofs/checker/GROUND.md +++ b/tests/bootstrap/proofs/checker/GROUND.md @@ -2,107 +2,106 @@ [Inner format](FORMAT.md) | [Theory formation](FORMATION.md) | [Calculus](README.md) -`check_derivation_ground()` extends theory formation with sorted owner and -witness term tables and a well-sorted owner root. It does not compare the root -terms for equality, check proof rows, unfold definitions, or authenticate the -theory/proposition. Its `Grounded` result is not proof acceptance. +`check_derivation_ground()` runs theory formation and then validates the owner +and witness ground-term tables plus the owner root. It does not check whether +the root terms are equal, verify proof rows, unfold definitions, or verify the +authenticity of the theory or proposition. A `Grounded` result does not mean the +proof was accepted. ## Admission and check order -Call `form_derivation_theory()` first and forward any failure unchanged. Only -tag 4 permits the following work. Physical layout has already checked every -word and record in all three sections, including the still-unchecked proof rows. +Call `form_derivation_theory()` first and pass any failure through unchanged. +Only tag 4 allows ground checking to proceed. Layout checking has already +verified every word and record across all three sections, including the +still-unchecked proof rows. -Build separate immutable row-offset indexes for the owner and witness tables, -using the same balanced representation as formation. Table count fields are at -`theory_end + 4` and `proposition_end + 4`, respectively. These offsets come from -the retained formed frame, never from certificate-provided section pointers. -Then validate in this order: +Build two separate immutable row-offset indexes for the owner and witness +tables using the same balanced tree as theory formation. Read the table counts +at `theory_end + 4` and `proposition_end + 4` using offsets from the saved +framed result, never from certificate-supplied pointers. Then check items in +this order: -1. Every owner term, in row order, including unused terms. -2. The owner root's left reference, then its right reference, then their sorts. -3. Every witness term, in row order, including unused terms. +1. Every owner term in row order, including unused terms. +2. The owner root's left reference, right reference, and matching sorts. +3. Every witness term in row order, including unused terms. -For each application, check the symbol reference in the tag-selected constructor -or function index before its exact arity, then check children in argument order. -An invalid symbol rejects at its symbol field; wrong arity rejects at its +For each application, look up the symbol in the tag-selected constructor or +function index, check exact arity, and check children in argument order. An +invalid symbol fails at the symbol field; wrong arity fails at the argument-count field. For each child, check the reference before its inferred -sort; either failure belongs to that child-reference field. Variables and -unknown tags are already rejected by physical layout. All formed functions may -occur in ground terms: definition-order and structural-decrease restrictions -apply to definitions, not to closed applications of admitted functions. - -Let `R` be the owner count and `V` the witness count. Owner row `i` may reference -only `1..i-1`. Witness row `j` has global identity `R+j` and may reference only -`1..R+j-1`, routing references `1..R` to the immutable owner index and the rest -to witness identity `reference-R`. Zero, self, forward, and cyclic references -reject. Witness identities cannot redefine owner rows or supply a missing owner -child. Both tables share the same formed symbol signatures, but neither can -refer to clause-local template rows as a separate identity space. - -Each previously checked child's result sort comes directly from its checked -symbol signature; no recursive expansion or unchecked sort annotation is used. -Duplicate structural rows and repeated children are legal. This stage does not -equate distinct row identities or normalize function applications. - -The two root fields are at `proposition_end-8` and `proposition_end-4`. Each must -reference `1..R`, even if a witness would have the requested identity. An invalid -root reference rejects at its own field. A root-sort mismatch rejects at the -right field, after both references pass. An empty owner table therefore rejects -at the left root field. Distinct, same-sorted roots are allowed here: the later -derivation must justify their equality. - -All new semantic failures are tag 1, code 8 `ground_terms`, the specified -request-byte coordinate, and zero limit/requested. Earlier physical, theory, -and resource failures retain their original fields. No partial ground context -escapes on failure. +sort; either error fails at that child-reference field. Layout checking already +rejected variables and unknown tags. Any formed function may appear in ground +terms: definition-order and structural-decrease rules apply only to definitions, +not to closed calls of valid functions. + +Let `R` be the owner term count and `V` the witness term count. Owner row `i` +can reference only `1..i-1`. Witness row `j` has global ID `R+j` and can +reference only `1..R+j-1`; lookups in `1..R` go to the immutable owner index +and the rest go to witness ID `reference-R`. Zero, self, forward, and cyclic +references fail. Witness rows cannot redefine owner rows or fill in a missing +owner child. Both tables use the formed symbol signatures, and neither can +reference clause-local template rows. + +Each checked child's result sort comes directly from its symbol signature, with +no recursive expansion or unchecked sort annotations. Duplicate rows and +repeated children are valid. This stage does not equate distinct row IDs or +evaluate functions. + +The two root fields sit at `proposition_end-8` and `proposition_end-4`. Both +must reference `1..R`, even if a witness row holds that ID. An invalid root +reference fails at its own field. A sort mismatch fails at the right field once +both references pass. An empty owner table therefore fails at the left root +field. Distinct roots of the same sort are valid here; the proof must justify +their equality later. + +All new semantic errors return tag 1, code 8 `ground_terms`, the failing +request-byte offset, and zero for limit and requested. Earlier layout, theory, +and resource errors keep their original fields. No partial ground state escapes +on failure. ## Work, allocation, and depth -There is no additional arbitrary term-count or logical-depth cutoff in this -stage. The admitted request extent already bounds `N=R+V` below 8,519,680 -(< 2^24): each ground record has at least four words including its length. -Thus the global -identity sum fits the administrative u31 word. A physical index is built once; -row and child scans are tail calls. Index descent has at most 24 edges, and -symbol lookup at most the formation index bound of 21. Logical term depth does -not consume native recursion or allocate an expanded tree. - -Writing `H` for the total number of ground child-reference fields, validation -visits `N` rows and `H` children, with bounded index lookups at each visit, plus -constant root checks. Index building visits linearly many tree nodes. There is -no linked-list lookup, repeated full-table search, per-child result allocation, -or semantic evaluation. The request extent bounds both `N` and `H` before any -such loop or allocation. These are structural work bounds, not host timeouts. - -The two indexes allocate at most `3N+4` pairs, including temporary build -carriers; one shared checking context uses two pairs, and success or rejection -uses at most four. Thus this stage adds at most `3N+10` cumulative pairs. Together -with formation's actual ledger, the request uses at most -`2W+3N+32S+26`, where `W` and `S` retain their formation meanings. This is below -31,850,522 pairs under the independent admitted bounds (`W <= 2^21`, -`N < 8,519,680`, `S <= 65,536`), within the selected Gamma -arena of 3,387,293,850. Unreachable pairs still count. The +This stage adds no arbitrary term-count or depth cutoff. The request size limit +already bounds `N=R+V` below 8,519,680 (< 2^24) because each ground record uses +at least four words including its length, so the global ID sum fits in a u31 +word. Each index is built once; row and child loops are tail calls. Index lookup +takes at most 24 tree steps, and symbol lookup at most the formation bound of +21. Logical term depth does not use native recursion or allocate expanded trees. + +With `H` total child-reference fields, validation visits `N` rows and `H` +children with bounded index lookups, plus constant-time root checks. Index +building visits linearly many nodes. The checker performs no linked-list scans, +repeated table searches, per-child allocations, or term evaluation. The request +size bounds `N` and `H` before any loop or allocation runs. These are structural +work bounds, not host timeouts. + +The two indexes allocate at most `3N+4` pairs including temporary build pairs; +the shared checking context uses two pairs, and the final result uses at most +four. This stage adds at most `3N+10` cumulative pairs. Combined with theory +formation, the request uses at most `2W+3N+32S+26` pairs, where `W` and `S` keep +their formation meanings. Under the independent bounds (`W <= 2^21`, +`N < 8,519,680`, `S <= 65,536`), this stays below 31,850,522 pairs inside the +3,387,293,850-pair Gamma arena. Unreachable pairs still count. The [combined checking ledger](CHECKING.md#complete-generic-execution-provision) -includes later comparison, substitution, and proof stages. -The provisions remain adjustable implementation choices, not calculus laws. -The [comparison session](COMPARISON.md#work-and-allocation-provision) adds its -completed-pair memo and pending frames to this cumulative allocation ledger. +adds later comparison, substitution, and proof stages, and the +[comparison session](COMPARISON.md#work-and-allocation-provision) adds its +completed-pair memo and pending frames. These limits are adjustable +implementation choices, not calculus rules. ## Private grounded outcome -Success is `(pair 5 payload)`, with payload +Success returns `(pair 5 payload)`, where payload is `(pair formed (pair owners (pair witnesses proof_table)))`. `formed` is the -existing formed payload; the two indexes retain separate owner/witness custody. -`proof_table` is the physical proof-count field immediately after the witness -rows, not an index or a claim that those proofs are valid. The payload accessors +formed-theory payload; the two indexes keep owner and witness rows separate. +`proof_table` is the byte offset of the proof-count field right after the +witness rows, not an index or a claim that the proofs are valid. The accessors are `grounded_theory`, `grounded_owner_terms`, `grounded_witness_terms`, and `grounded_proof_table`. `grounded_term_lookup(payload, identity)` routes global -term identities through the two retained indexes; invalid identities return -scalar zero before descent. - -The diagnostic entry publishes tag 5 followed by eight little-endian u64 words: -the three frame ends, `R`, `V`, left root, right root, and proof-table offset. -Failures publish tag 1/2 and their four existing u64 fields. Process status zero -only means an owned diagnostic was published. No production proof-accepting -`main` is introduced. +IDs through the two indexes and returns scalar zero for invalid IDs before +descending. + +The diagnostic entry writes tag 5 followed by eight little-endian u64 words: the +three section ends, `R`, `V`, left root, right root, and proof-table offset. +Failures write tag 1 or 2 plus their four u64 fields. Exit status zero means +only that the diagnostic output was written. No production proof-accepting +`main` exists here. diff --git a/tests/bootstrap/proofs/checker/LAYOUT.md b/tests/bootstrap/proofs/checker/LAYOUT.md index 6e31a79be371..6f9e4dc3d5ef 100644 --- a/tests/bootstrap/proofs/checker/LAYOUT.md +++ b/tests/bootstrap/proofs/checker/LAYOUT.md @@ -2,105 +2,104 @@ [Physical format and later semantic checks](FORMAT.md) | [Outer admission](REQUEST.md) -`admit_derivation_layout()` composes outer admission with physical traversal of -all three inner sections. It does not form a theory, resolve references, infer -sorts, validate proof rules, or compare the owner root. A physically decoded -layout is not evidence that any equality holds. - -The outer outcome is returned unchanged on rejection or capacity refusal. On -outer success, traverse theory, proposition, and certificate in that order, -finishing one section before starting the next. Within a section: - -1. Require its four magic bytes; a shorter section fails at its end. Compare - magic bytes in order, selecting the first differing byte. -2. Require a whole number of four-byte payload words. A partial word fails at - its first byte, before inspecting the preceding words' high bits. -3. Inspect every payload word's high byte in increasing offset order. A set - high bit fails at that byte, before traversing grammar fields. -4. Traverse the format's records and fields, requiring each record and the - section to end exactly. Unknown mode, term, and rule tags fail at their - tag field. Surplus fields fail at the first unconsumed cursor. - -Every coordinate is relative to the complete sealed request, including its -24-byte outer header. All inner physical failures use outer rejection tag 1 -and code 6 `inner_layout`; limit and requested are zero. Earlier errors are -not replaced by later errors in another section. +`admit_derivation_layout()` runs outer framing and then scans the binary layout +of all three inner sections. It does not check theory semantics, resolve +references, infer sorts, verify proof rules, or compare the owner root. Passing +layout checking does not prove any equality. + +If outer framing rejects or hits a capacity limit, return that result unchanged. +Otherwise scan the theory, proposition, and certificate sections in order, +finishing each before starting the next. Within each section: + +1. Check the four magic bytes; a shorter section fails at its end. Compare magic + bytes in order and report the first mismatch. +2. Require a whole number of four-byte payload words. A trailing partial word + fails at its first byte, before high-bit checks run. +3. Check the high byte of every payload word in offset order. A set high bit + fails at that byte, before grammar traversal begins. +4. Walk all records and fields, requiring each record and the section to end + exactly. Unknown mode, term, and rule tags fail at the tag field. Extra + fields fail at the first unconsumed byte. + +All offsets are relative to the complete sealed request, including its 24-byte +outer header. Every inner layout error returns rejection tag 1, code 6 +`inner_layout`, and zero for limit and requested. Earlier errors take priority +over later errors in subsequent sections. ## Extent checks -Before reading a fixed group of fields, require the group to fit its containing -extent; a short group fails at that containing end. Read a record length only -after checking its word fits. Compare its payload count with remaining bytes -divided by four before computing its end; an impossible extent fails at the -record's length field. Every nested end stays within its containing record. - -For a table, check that its count is no greater than the remaining bytes divided -by four before entering the row loop. This lower bound accounts for one length -word per record, not a claim that every row's fields are valid. An impossible -count fails at the count field. Each iteration then consumes one complete, -checked record. Argument and premise vectors similarly check their counts -against the remaining whole-word extent before advancing; impossible vector -counts fail at their count field. Grammar traversal follows physical field -order after each such preflight. - -The fixed groups, and therefore missing-field precedence, are explicit: - -- A constructor/function signature first requires its result sort and argument - count together, then its argument vector. -- A function next requires and checks the mode word **before** requiring its - selected-argument word and then its clause table. -- A clause requires its constructor word, then its template table, then its - body word. A proposition requires both root words together after its table. -- A term or proof record first requires and validates its tag word. Only a - known tag permits checking its remaining fields. A variable then requires - its slot word; an application requires symbol and argument count together, - then the argument vector. -- A known proof rule next requires both conclusion references together. +Before reading a fixed group of fields, check that the group fits in the +enclosing boundary; otherwise fail at that boundary end. Read a record length +only after verifying its word fits. Compare its payload word count against +remaining bytes divided by four before computing its end; an out-of-bounds count +fails at the length field. Nested records cannot cross their enclosing record. + +Before entering a table loop, check that the row count is at most remaining +bytes divided by four. That lower bound checks space for one length word per +record, not field validity. An impossible count fails at the count field. Each +iteration then consumes one checked record. Argument and premise lists likewise +check their counts against remaining whole words before advancing, failing at +the count field if too large. Field traversal follows wire order after each +check. + +Fixed field groups define missing-field precedence explicitly: + +- Constructor and function signatures require result sort and argument count + together, then the argument list. +- Functions next read and check the mode word **before** requiring the + selected-argument word and clause table. +- Clauses require constructor word, template table, then body word. Propositions + require both root words together after the term table. +- Term and proof records read and validate their tag word first; only a known + tag allows checking remaining fields. Variables then require a slot word; + applications require symbol and argument count together, then the argument + list. +- A valid proof rule next requires both conclusion references together. Reflexivity has no further fields; symmetry and unfolding require one word; transitivity requires both premises together; congruence requires its count - word followed by the premise vector. + word followed by the premise list. - Every other count, length, or sort-count field is a one-word group. -Thus a one-word term record with unknown tag 9 fails at the tag, not its end; -one with known application tag 1 fails at its end for the missing header. +A one-word term record with unknown tag 9 therefore fails at the tag field, not +its end; one with known application tag 1 fails at its end for the missing +header. -The word scan checks even fields that later prove surplus or unreachable. No -record body, reference vector, or final proof prefix can hide a high-bit word. -Logical term depth never controls Gamma call depth: child references are -physical words here, not recursive requests to decode a tree. +The word scan checks even fields that turn out to be extra or unreachable, so +no record body, reference list, or trailing proof prefix can hide a high-bit +word. Logical term depth never drives Gamma call depth because child references +are flat words here, not recursive tree decodes. ## Private outcome and storage -On success, return tag 3 `Layout` with the same three section-end payload fields -as tag 0 `Framed`. This retains the original immutable input spans, not copied -term records or a semantic index. Only tag 3 permits a consumer to rely on -physical inner traversal; no production proof-accepting entry is supplied. - -Scanning helpers use scalar cursors. A nonnegative result is the next cursor; -a negative result encodes the failure coordinate as `-(coordinate + 1)`. -Callers must branch on failure before reading, adding, or advancing. These -private scalars never become term identities or theory arithmetic. - -The scans allocate no pairs and emit no bytes. The successful outer admission -allocates three pairs; layout success wraps its existing payload in one pair, -while a subsequent inner failure allocates four rejection pairs. Thus this -component uses at most seven pairs, without per-word or per-row allocation. -All row loops consume bounded input; nesting follows the fixed wire grammar, -not arbitrary input-provided recursion. The [complete generic profile](CHECKING.md) -separately budgets indexes, formation, comparisons, substitutions, and proof -state; this physical traversal alone does not establish that full profile. +Success returns tag 3 `Layout` with the same three section-end offsets as tag 0 +`Framed`. This keeps the original immutable input spans without copying records +or building semantic indexes. Only tag 3 lets later stages rely on verified +physical layout; no production proof-accepting entry exists here. + +Scanning helpers pass scalar cursors. A nonnegative value is the next cursor; a +negative value encodes a failure offset as `-(coordinate + 1)`. Callers must +check for failure before reading, adding, or advancing. These internal scalars +never become term IDs or theory arithmetic. + +Scanning allocates no pairs and writes no bytes. Outer framing allocates three +pairs; layout success wraps that payload in one pair, and an inner failure +allocates four rejection pairs. This stage therefore uses at most seven pairs +total, with no per-word or per-row allocation. All row loops consume bounded +input, and nesting follows the fixed wire grammar rather than input-controlled +recursion. The [complete generic profile](CHECKING.md) budgets indexes, theory +formation, comparison, substitution, and proof state separately; layout checking +alone does not establish that profile. ## Deliberately deferred checks -Zero sort or reference values, empty proof/template tables, incorrect clause -cardinality, unbound slots, cyclic or forward references, wrong argument sorts, -and false rule conclusions can have a physical layout. They must fail the -later formation, [ground checking](GROUND.md), or derivation stage, and are not -accepted proofs here. -Unknown tags, illegal variable tags in ground records, wrong physical field -counts, and record escapes are already physical errors. - -The diagnostic test entry must preserve this distinction, including positive -layout controls whose semantics are deliberately invalid. It reports exact -owned outcomes, not a compiler artifact or proof verdict. Outer evaluator -failures and host timeouts are not layout outcomes. +Zero sort or reference values, empty proof or template tables, wrong clause +counts, unbound slots, cyclic or forward references, wrong argument sorts, and +false rule conclusions can all pass layout checking. They must fail in later +formation, [ground checking](GROUND.md), or proof checking, and are not accepted +here. Unknown tags, variable tags in ground tables, wrong field counts, and +record overflows are already physical errors. + +Diagnostic tests must preserve this boundary, including positive layout cases +whose semantics are invalid. Diagnostics report structured checker results, not +compiler artifacts or proof verdicts. Outer evaluator failures and host timeouts +are not layout results. diff --git a/tests/bootstrap/proofs/checker/README.md b/tests/bootstrap/proofs/checker/README.md index d81b5bdab609..a5cbe23a6080 100644 --- a/tests/bootstrap/proofs/checker/README.md +++ b/tests/bootstrap/proofs/checker/README.md @@ -1,81 +1,79 @@ # Gamma derivation checker implementation -[checker.gamma](implementation/checker.gamma) is the generic proof entrance: -admit the ground context, check every explicit proof row, then require the final -equation to match the owner root. Its `derivation/` helpers own indexed premise -custody, individual rules, and final-root checking. One comparison session carries -all post-admission work through the request. `Checked` establishes only that -supplied ground equality under the supplied theory, not artifact authority. -The full Beta definition package and encoding certificate remain unfinished; -the separate [Beta theory](../beta_encoding/README.md) supplies the initial -artifact-specific definitions without extending the generic checker. +[checker.gamma](implementation/checker.gamma) is the generic proof entry point: +it validates the ground terms, checks every proof row, and requires the final +equation to match the owner root. Helpers in `derivation/` handle indexed +premises, individual rules, and final-root checks. One comparison session tracks +all post-ground work for the request. `Checked` proves only the supplied ground +equality under the supplied theory, not artifact authenticity. The full Beta +definition package and encoding certificate remain unfinished; the separate +[Beta theory](../beta_encoding/README.md) provides the artifact-specific +definitions without extending the generic checker. -[ground.gamma](implementation/ground.gamma) is the ground-term entrance: -form the theory, check owner terms and root sorts, then check witness terms. -Its helpers keep owner and witness identities separate and validate applications +[ground.gamma](implementation/ground.gamma) is the ground-term entry point: it +forms the theory, validates owner terms and root sorts, and then checks witness +terms. Its helpers keep owner and witness IDs separate and check applications without expanding terms. [formation.gamma](implementation/formation.gamma) -admits the physical layout and checks conservative definitions. -Its subordinate files own signature checks, finite inhabitation, function cases, -clause scopes, and decreasing recursion. [layout.gamma](implementation/layout.gamma) -composes [outer admission](implementation/admission.gamma) with traversal of -theory, proposition, and certificate records. The manifest selects the exact -implementation bytes. +checks physical layout and conservative definitions; its helper files check +signatures, finite inhabitation, function cases, clause scopes, and structural +decrease. [layout.gamma](implementation/layout.gamma) combines +[outer admission](implementation/admission.gamma) with scanning of theory, +proposition, and certificate records. The manifest selects the exact source +bytes. [`implementation.gamma.sources`](implementation/implementation.gamma.sources) -is the ordered source authority: repacking it materializes 1,365 lines / -62,357 bytes, SHA-256 -`382531b910429c7111c2bc9e7dcce7e96394c45fa0a89b624debd061b69422b2`. -The manifest itself is 9,046 bytes, SHA-256 +lists the canonical source order: packing it produces 1,365 lines / 62,357 +bytes, SHA-256 +`382531b910429c7111c2bc9e7dcce7e96394c45fa0a89b624debd061b69422b2`. The manifest +itself is 9,046 bytes, SHA-256 `21ba1a712dd68e3492abb46d435a906fab8bbc49b67557d13910512e2c975f5b`; -`tests/bootstrap/proofs/sources_env.sh` checks both identities against every -materialization. The [archived identity tests](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/proofs-identity.sh) record the refusal cases. -A digest is an identity check on the member bytes, not a proof of the checker -or of any certificate it accepts. +`tests/bootstrap/proofs/sources_env.sh` verifies both digests on every assembly. +The [archived identity tests](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/proofs-identity.sh) +record the refusal cases. A digest verifies member bytes, not the checker or any +certificate it accepts. -After ground validation, [comparison.gamma](implementation/comparison.gamma) -exposes a session API for structural term comparisons. Its helpers own explicit -pending frames, completed-pair memoization, and cumulative work accounting. -Structural difference is not a rejection of a derivable equality. -[substitution.gamma](implementation/substitution.gamma) checks a stated function -clause using syntax-derived bindings, an explicit pending stack, and a separate -invocation-local template memo. It shares cumulative work with ground comparison -without inserting theory equalities into the structural memo. The proof -coordinator uses these operations only for the explicit supplied rules. +After ground checking, [comparison.gamma](implementation/comparison.gamma) +provides a session API for structural term comparison. Its helpers manage +explicit pending frames, completed-pair memoization, and cumulative work +accounting. Structural inequality does not mean two terms cannot be proved +equal. [substitution.gamma](implementation/substitution.gamma) verifies a stated +function clause using syntax-derived bindings, an explicit pending stack, and an +invocation-local template memo. It shares the work budget with ground comparison +without adding theory equalities to the structural memo. The proof checker calls +these operations only for explicit proof rules. -Outer admission returns `Framed`, `Rejected`, or `Incomplete`. Inner traversal -returns `Layout` only after checking all physical fields; neither success grants -theory validity, subject authority, or proof acceptance. Theory checking returns -`Formed` with retained constructor/function indexes, but does not check ground -terms, proof rows, root equality, or the authority of a Beta theory. Ground -checking returns `Grounded` only after validating both term tables and the -owner root's references/sorts; it does not establish the equality. There is -deliberately no artifact-admitting production `main`. The -[outer](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-admission/README.md), +Outer framing returns `Framed`, `Rejected`, or `Incomplete`. Layout scanning +returns `Layout` only after checking every physical field; neither proves theory +validity, subject authenticity, or proof acceptance. Theory formation returns +`Formed` with constructor and function indexes, without checking ground terms, +proof rows, root equality, or Beta theory authenticity. Ground checking returns +`Grounded` after validating both term tables and the owner root's references and +sorts, without proving equality. No artifact-admitting production `main` exists. +The [outer](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-admission/README.md), [layout](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-layout/README.md), [formation](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-formation/README.md), [ground](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-ground/README.md), [comparison](../derivation-comparison/README.md), [substitution](../derivation-substitution/README.md), and -[checking](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-checking/README.md) gates supply -separate diagnostic entries and exercise the actual ordinary-Gamma source. +[checking](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/gamma/derivation-checking/README.md) +gates supply separate diagnostic entry points and test the ordinary-Gamma +source directly. -The [inner format](FORMAT.md) specifies the theory, clause-local templates, -owner-root terms, witness terms, and explicit proof rows. The -[layout contract](LAYOUT.md) defines the physical traversal and failure order; -the [formation contract](FORMATION.md) defines theory checks, indexed storage, -failure order, and the component's work/allocation bounds. The -[ground contract](GROUND.md) specifies term validation and cumulative allocation -through that stage. The [comparison contract](COMPARISON.md) specifies syntax -comparison and source-owned session threading. The -[substitution contract](SUBSTITUTION.md) specifies clause matching, binding custody, -and charged template traversal. The [checking contract](CHECKING.md) specifies -proof rules, final-root enforcement, soundness under the formed theory, and the -combined generic resource profile. Artifact-specific measurements and acceptance -remain unfinished. -The [complete encoding contract](../beta_encoding/ACCEPTANCE.md) owns the first -artifact-specific acceptance target. Small admission or rule tests cannot replace -it. This checker searches for no proofs, discovers no artifact obligation, runs -no compiler, and decides no deployment policy. It admits only the explicit finite -ground rules required by that customer; quantifiers, induction, open lemma -schemas, coinduction, and Alpha transition-system rules are outside this checker. -Moving it into Gamma does not prove or remove the trusted Gamma evaluator. +The [inner format](FORMAT.md) defines theory, clause templates, owner-root +terms, witness terms, and proof rows. The [layout contract](LAYOUT.md) defines +physical scanning and error precedence. The [formation contract](FORMATION.md) +defines theory checks, indexed storage, error precedence, and resource bounds. +The [ground contract](GROUND.md) defines term validation and cumulative +allocation through that stage. The [comparison contract](COMPARISON.md) defines +syntax comparison and session threading. The +[substitution contract](SUBSTITUTION.md) defines clause matching, bindings, and +charged template traversal. The [checking contract](CHECKING.md) defines proof +rules, final-root checks, soundness under the formed theory, and the combined +resource budget. Artifact-specific measurements and acceptance remain open. The +[complete encoding contract](../beta_encoding/ACCEPTANCE.md) defines the first +artifact-specific target; small rule tests cannot replace it. This checker does +not search for proofs, discover obligations, run a compiler, or decide +deployment policy. It accepts only the finite ground rules that target needs; +quantifiers, induction, open lemma schemas, coinduction, and Alpha transition +rules are out of scope. Implementing it in Gamma neither proves nor removes the +trusted Gamma evaluator. diff --git a/tests/bootstrap/proofs/checker/REQUEST.md b/tests/bootstrap/proofs/checker/REQUEST.md index dff8e660a31e..8c8dbba72477 100644 --- a/tests/bootstrap/proofs/checker/REQUEST.md +++ b/tests/bootstrap/proofs/checker/REQUEST.md @@ -1,21 +1,20 @@ # Derivation-checker request envelope -This defines the outer admission layer for the +This document specifies the outer framing layer for the [ground equality checker design](README.md). -The [inner theory, proposition, and certificate formats](FORMAT.md) have a -separate [physical layout traversal](LAYOUT.md) and -[conservative theory formation](FORMATION.md), followed by -[ground-term validation](GROUND.md). [Structural comparison](COMPARISON.md) -operates on that validated input, and [checked substitution](SUBSTITUTION.md) -checks one stated unfolding. [Explicit proof checking](CHECKING.md) validates all -rows and the final owner root under its combined generic execution provision. -**Framed is not proof acceptance.** No canonical checker -entry or accepted artifact is supplied by this layer. +The [inner theory, proposition, and certificate formats](FORMAT.md) go through +[physical layout traversal](LAYOUT.md), [conservative theory formation](FORMATION.md), +and [ground-term validation](GROUND.md). [Structural comparison](COMPARISON.md) +compares validated terms, [checked substitution](SUBSTITUTION.md) verifies one +clause unfolding, and [explicit proof checking](CHECKING.md) checks all proof +rows and the owner root under a combined resource budget. **Framed is not proof +acceptance.** This layer supplies no canonical checker entry point or accepted +artifact. ## Byte framing All offsets are relative to one immutable Gamma sealed input, not to the Gamma -source or its four-byte evaluator frame. The envelope is: +source or its four-byte evaluator frame. The envelope layout is: | Offset | Width | Meaning | | ---: | ---: | --- | @@ -29,72 +28,68 @@ source or its four-byte evaluator frame. The envelope is: | next | certificate length | Exact certificate bytes, followed by exact end | Lengths are little-endian unsigned words with the high bit clear. They are -administrative extents in `0..2^31-1`, not numeric values in the proof theory. -Empty sections are physically framed; their eventual inner decoders must decide -whether they are valid. Unknown inner tags cannot be accepted on the strength of -outer framing. - -The caller responsible for the artifact independently supplies the theory and -proposition sections. A certificate producer supplies only the third section. -Concatenation alone provides no authentication or subject authority. The later -artifact owner must retain and verify the exact first two sections before -interpreting a generic checker result as evidence about that artifact; a -certificate-provided digest cannot replace this ownership check. +header sizes in `0..2^31-1`, not numbers in the proof theory. Empty sections +pass outer framing; inner decoders decide whether they are valid. Unknown inner +tags are never accepted based on outer framing. + +The artifact owner supplies the theory and proposition sections independently; +the certificate producer supplies only the third section. Concatenating them +does not authenticate the subject. The artifact owner must verify the first two +sections before treating a generic checker result as proof about an artifact; a +digest inside the certificate cannot replace that check. ## Deterministic admission -`admit_derivation_request()` reads the current sealed input and returns a private -owned outcome without writing bytes. Checks occur in this order: +`admit_derivation_request()` reads the sealed input and returns a private +result without writing bytes. It checks in this order: -1. A request shorter than 24 bytes is rejected at its extent. -2. Check the eight identity bytes in increasing offset order, then the reserved - bytes at 20 through 23 in increasing order. -3. Check the high length bytes at 11, 15, and 19 in that order before decoding. -4. Compare each section length against its remaining input extent, in section - order. Only a fitting section advances the cursor. Then require exact end. -5. Apply the request-byte provision to the structurally exact whole envelope. +1. Reject any request shorter than 24 bytes at its byte length. +2. Check the eight header identity bytes (0..7) in order, then reserved bytes + 20..23 in order. +3. Check the high length bytes at 11, 15, and 19 in order before decoding. +4. Check each section length against remaining input bytes in section order, + advancing the cursor only when it fits, then require exact end of input. +5. Apply the request-byte cap to the complete, structurally exact envelope. -Section ends are computed only after the subtractive remaining-extent check. -No declared length controls input consumption, allocation, or an unchecked -sum. A short request claiming a huge section is malformed, not a capacity -refusal. The envelope does not read section contents or allocate a row per -section byte. +Each section end is computed only after checking remaining bytes by subtraction. +No declared length drives input reads, allocation, or unchecked addition. A +short request claiming a huge section is malformed, not a capacity error. Outer +framing neither reads section contents nor allocates per section byte. -The private outcomes are: +Private result tags: | Tag | Payload | | ---: | --- | -| 0 Framed | Three ordered section-end offsets; the first start is 24 and each later start is the preceding end. | -| 1 Rejected | Rejection code, request-byte coordinate, zero limit, zero requested. | -| 2 Incomplete | Resource code, request-byte coordinate, limit, requested. | - -Rejection codes are 1 `short_header` (coordinate input extent), 2 -`identity_or_reserved` (first offending byte), 3 `length_high_bit` (offending high -byte), 4 `section_extent` (the section's length-field start), and 5 -`trailing_input` (first trailing byte). Resource code 1 is `request_bytes`: -coordinate and limit 136,314,880; requested is the exact sealed-input length. -These are admission-layer outcomes, not compiler-boundary or proof judgments. - -The provision is 130 MiB, the least whole-MiB extent above the measured -135,451,492-byte complete certificate request, and sits within the selected -Gamma evaluator frame of 131 MiB together with checker source and framing. This is a private -implementation provision, adjustable with measured certificate requirements; -it does not restrict the calculus. Its exact and adjacent extents are tested. -The [generic checking profile](CHECKING.md#complete-generic-execution-provision) -accounts for source framing and underlying evaluator requirements. The artifact -owner must still measure the full Beta certificate under its exact entry/profile. -An outer evaluator refusal, trap, or host timeout is not an admission result. +| 0 Framed | Three ordered section-end offsets; section 1 starts at 24 and each later section starts at the previous end. | +| 1 Rejected | Rejection code, request-byte offset, zero limit, zero requested. | +| 2 Incomplete | Resource code, request-byte offset, limit, requested. | + +Rejection codes are 1 `short_header` (offset is input length), 2 +`identity_or_reserved` (first bad byte), 3 `length_high_bit` (offending high +byte), 4 `section_extent` (start of that section's length field), and 5 +`trailing_input` (first trailing byte). Resource code 1 is `request_bytes`, with +offset and limit 136,314,880 and requested equal to the sealed-input length. +These are framing results, not compiler-boundary or proof verdicts. + +The 130 MiB cap is the smallest whole MiB above the measured 135,451,492-byte +complete certificate request and fits inside the 131 MiB Gamma evaluator frame +along with the checker source and framing. This cap is an adjustable +implementation budget, not a calculus limit. Both exact and adjacent sizes are +tested. The [generic checking profile](CHECKING.md#complete-generic-execution-provision) +accounts for source framing and evaluator limits. The artifact owner must still +measure the full Beta certificate under its exact entry point and profile. An +outer evaluator refusal, trap, or host timeout is never a framing result. ## Private representation -An outcome is `(pair tag payload)`. A framed payload is -`(pair theory_end (pair proposition_end certificate_end))`; a failure payload -is `(pair code (pair coordinate (pair limit requested)))`. Named accessors own -these projections. Only tag 0 permits reading section ends. Failure outcomes -do not preserve earlier partial section cursors as valid custody. - -The production entrance and helpers live in `implementation/`, selected by -`implementation.gamma.sources`. Tests provide their own explicit diagnostic -entry; no host script extracts, parses, or replaces production functions. -The generic `check_derivation` entrance supplies an owned proof result, but there -is no artifact-admitting production `main` or accepted Beta certificate here. +Every result is `(pair tag payload)`. A framed payload is +`(pair theory_end (pair proposition_end certificate_end))`; a failure payload is +`(pair code (pair coordinate (pair limit requested)))`. Named accessors read +these fields. Only tag 0 allows reading section ends; failure results never +expose partial section cursors as valid. + +The production entry point and helpers live in `implementation/`, listed by +`implementation.gamma.sources`. Tests supply separate diagnostic entry points; +no host script extracts, parses, or replaces production functions. The generic +`check_derivation` entry point returns a structured proof result, but no +artifact-admitting production `main` or accepted Beta certificate lives here. diff --git a/tests/bootstrap/proofs/derivation-comparison/README.md b/tests/bootstrap/proofs/derivation-comparison/README.md index ec3f5fe291e6..ef1be09a57cb 100644 --- a/tests/bootstrap/proofs/derivation-comparison/README.md +++ b/tests/bootstrap/proofs/derivation-comparison/README.md @@ -1,17 +1,16 @@ # Structural comparison gate -Run `sh tests/bootstrap/proofs/derivation-comparison/run.sh` from the repository root on -macOS arm64 or Linux x86-64, or Windows x64 in Git Bash. Python 3 and the selected checked-in -Alpha seed are required; macOS also requires `codesign`. Windows runtime -validation is not implied by this portable entrypoint. +Run `sh tests/bootstrap/proofs/derivation-comparison/run.sh` from the repository +root on macOS arm64, Linux x86-64, or Windows x64 (Git Bash). Python 3 and the +selected checked-in Alpha seed are required; macOS also requires `codesign`. +Providing a portable entry point does not imply Windows runtime validation. -The contract is [COMPARISON.md](../checker/COMPARISON.md). -The gate materializes the complete canonical checker implementation once. Each -source is the exact concatenation of `diagnostic.gamma`, one whole named file -in `entries/`, and that implementation. `source.tsv` pins every composition in -the explicit `fixtures.py` entry order. The gate-local prefix files are bound -in `tests/bootstrap/proofs/sources_env.sh` and checked by -`require_derivation_comparison_prefixes_identity` before packing: +This gate tests [COMPARISON.md](../checker/COMPARISON.md). It assembles the +canonical checker implementation once; each test program concatenates +`diagnostic.gamma`, one file from `entries/`, and that implementation. +`source.tsv` pins each composition in `fixtures.py` order. The gate-local +prefix files are pinned in `tests/bootstrap/proofs/sources_env.sh` and verified +by `require_derivation_comparison_prefixes_identity` before packing: | file | bytes | SHA-256 | | --- | --- | --- | @@ -25,49 +24,47 @@ in `tests/bootstrap/proofs/sources_env.sh` and checked by | `entries/session.gamma` | 368 | `8f1ea6dd838b0c770cdfc56d745a1bfa7f493fef677118378d376bc103a47a4b` | | `entries/witness.gamma` | 349 | `2ba9d62188b05e802231ab0da5be0add5751e866bb2b4a2342d1a7019ccc0375` | -No functions are extracted. Host code -only authors literal wire fields, frames inputs, and compares exact observations; -it never traverses terms to decide equality or produces a semantic proof. +No functions are extracted. Host code only encodes literal wire fields, frames +inputs, and checks exact output bytes; it never walks terms to decide equality +or builds semantic proofs. -Each entry first admits Grounded and forwards earlier failures unchanged. -Compared is tag 6 plus Boolean and cumulative steps as two little-endian u64 -words: 17 bytes. A failure is tag 1/2 plus four u64 words: 33 bytes. Process zero -and empty stderr are required. A false Compared result is ordinary structural -difference, not a rejection. Definitions are not evaluated: `identity(zero)` -and `zero` differ here even though a later unfolding proof could equate them. +Every entry checks Grounded first and passes earlier failures through unchanged. +Compared outputs tag 6 plus Boolean and cumulative steps as two little-endian +u64 words (17 bytes); failures output tag 1 or 2 plus four u64 words (33 bytes). +Exit status zero and empty stderr are required. A false Compared result means +the terms differ syntactically, not a rejection. Definitions are not evaluated: +`identity(zero)` and `zero` differ here even though unfolding can equate them. -The source-owned entries are: +Test entries: | Entry | Comparison sequence | | --- | --- | -| `root` | Checked owner left/right roots; one observation. | +| `root` | Checked owner left/right roots; one output. | | `session` | Roots, repeated ordered pair, reversed pair; one threaded session. | -| `witness` | Left owner root versus last global identity, repeated and reversed. | +| `witness` | Left owner root vs. last global ID, repeated and reversed. | | `retention` | Fixed `(6,7)`, `(3,4)`, `(6,7)`, `(4,3)`; cumulative 6/8/12/16 steps prove child memo retention and no false-parent memo. | -| `invalid` | Checked root values 1/2/3 select test operands 0/N+1/1; one failing call at literal caller coordinates 701/709. | -| `budget` | A seeded reservation reaches 67,108,858, then three same-ID calls land on 67,108,864; right root1 selects invalid IDs, root2 the next valid call. Publishes exact-bound result, then failure. | -| `resume` | A seeded reservation and one same-ID call reach 67,108,862, one head mismatch reaches 67,108,863; the next visit fits but terminal resume refuses. | -| `pending` | A seeded reservation and one same-ID call reach 67,108,862, then two distinct unary parents with one shared child; parent and child visits fit, pending-parent resume refuses. | +| `invalid` | Checked root values 1/2/3 select operands 0/N+1/1; one failing call at literal offsets 701/709. | +| `budget` | Seeded reservation reaches 67,108,858, then three same-ID calls reach 67,108,864; right root 1 picks invalid IDs, root 2 picks the next valid call. Outputs exact-bound result, then failure. | +| `resume` | Seeded reservation plus one same-ID call reach 67,108,862, one head mismatch reaches 67,108,863; the next visit fits, then terminal resume fails. | +| `pending` | Seeded reservation plus one same-ID call reach 67,108,862, then two distinct unary parents share one child; parent and child visits fit, then parent resume fails. | -Every returned session is threaded forward. No call continues after failure or -restarts a session within a request. Invalid identities are checked before -identity shortcuts and exhausted counters. The last two controls publish no -Boolean or session for the interrupted comparison; `resume` publishes only its -earlier mismatch before that failure. Test-selector roots add no request fields -and are not part of the production comparison interface. +Every returned session threads forward without restarting or continuing after +failure. Invalid IDs reject before identity shortcuts and exhausted budgets. +The last two entries emit no Boolean or session for the interrupted call; +`resume` emits only its earlier mismatch before failing. Selector roots add no +request fields and are not part of the production comparison API. -There are 39 literal vectors, each executed once: 33 small vectors use -60-second host watchdogs; six larger controls use 600 seconds. -The Gamma entries retain their in-process repeated comparisons and session reuse. -Large inputs include two distinct 46,484-node chains (92,968 transitions) and -separately encoded 1,024-level shared DAGs (4,094 transitions). These counts -follow the documented visit/resume schedule: two per unary node; the shared -nullary base costs two and each additional binary level costs four because its -second child is memoized. No recursive host expansion or comparison is used. +The gate runs 39 vectors once each: 33 small vectors with 60-second watchdogs +and six larger ones with 600-second watchdogs. The Gamma entries keep their +in-process repeated comparisons and session reuse. Large inputs include two +distinct 46,484-node chains (92,968 steps) and separately encoded 1,024-level +shared DAGs (4,094 steps), matching the visit/resume cost model: two steps per +unary node, two for the shared nullary base, and four per binary level because +the second child hits the memo. Neither host code nor the checker recursively +expands trees. -Coverage includes ordered children, same-head false suffixes, tag/symbol -mismatch, duplicate structure, cross-owner/witness keys, reversed ordered memo -keys, failed-parent custody, and earlier physical/formation/ground failures. -Host timeouts and outer evaluator failures are not comparison judgments. This -gate does not implement substitution, validate proof rows, or accept the full -Beta encoding certificate. +Coverage spans ordered children, same-head differing suffixes, tag and symbol +mismatches, duplicate subtrees, cross-owner/witness keys, reversed memo keys, +unrecorded failed parents, and earlier layout, formation, and ground failures. +Host timeouts and evaluator crashes are not comparison verdicts. This gate does +not test substitution, verify proof rows, or accept the full Beta certificate. diff --git a/tests/bootstrap/proofs/derivation-substitution/README.md b/tests/bootstrap/proofs/derivation-substitution/README.md index 8167dfc07720..86142690fe8f 100644 --- a/tests/bootstrap/proofs/derivation-substitution/README.md +++ b/tests/bootstrap/proofs/derivation-substitution/README.md @@ -1,17 +1,16 @@ # Checked template substitution gate -Run `sh tests/bootstrap/proofs/derivation-substitution/run.sh` from the repository root on -macOS arm64 or Linux x86-64, or Windows x64 in Git Bash. Python 3 and the selected checked-in Alpha -seed are required; macOS additionally needs `codesign`. Windows runtime validation -is not implied by this portable entrypoint. +Run `sh tests/bootstrap/proofs/derivation-substitution/run.sh` from the repository +root on macOS arm64, Linux x86-64, or Windows x64 (Git Bash). Python 3 and the +selected checked-in Alpha seed are required; macOS also requires `codesign`. +Providing a portable entry point does not imply Windows runtime validation. -The contract is [SUBSTITUTION.md](../checker/SUBSTITUTION.md), -following [COMPARISON.md](../checker/COMPARISON.md). -The gate materializes the complete production closure once. Each diagnostic is -the exact concatenation of `diagnostic.gamma`, a whole `entries/.gamma`, -and that closure. `source.tsv` pins each composition in `fixtures.py` order. -The gate-local prefix files are bound in -`tests/bootstrap/proofs/sources_env.sh` and checked by +This gate tests [SUBSTITUTION.md](../checker/SUBSTITUTION.md) on top of +[COMPARISON.md](../checker/COMPARISON.md). It assembles the production checker +once; each diagnostic concatenates `diagnostic.gamma`, one `entries/.gamma` +file, and that closure. `source.tsv` pins each composition in `fixtures.py` +order. Gate-local prefix files are pinned in +`tests/bootstrap/proofs/sources_env.sh` and verified by `require_derivation_substitution_prefixes_identity` before packing: | file | bytes | SHA-256 | @@ -27,59 +26,59 @@ The gate-local prefix files are bound in | `entries/session.gamma` | 1,003 | `65f9a5a88735fc72aa8baba81500738305ff5e8d1515300bed0cad39eb090201` | | `entries/witness.gamma` | 306 | `5b199af8fd19f3f93c5235182b32917d250ffb978845a18937da92d08f5fd860` | -Host code reuses only the layout gate's literal field encoder; it does not -decode terms, construct binding maps, perform substitution, or decide equality. +Host code reuses only the layout gate's literal field encoder; it never decodes +terms, builds binding maps, substitutes templates, or decides equality. -All entries first call the real ground-admission stage and forward failures. -One session is created and threaded forward; no failed session is resumed. -Compared observations are tag 6 followed by Boolean and cumulative work as two -little-endian u64 values (17 bytes). Rejected/Incomplete observations are tag 1/2 -and four u64 fields (33 bytes). Process zero and empty stderr are required. -False means the substituted template differs structurally, not malformed proof -data. Proof semantics remain unchecked, but physical proof errors still reject. +Every entry calls ground validation first and passes failures through unchanged, +then threads one session forward without resuming failed sessions. Compared +outputs tag 6 plus Boolean and cumulative work as two little-endian u64 values +(17 bytes); Rejected and Incomplete output tag 1 or 2 plus four u64 fields (33 +bytes). Exit status zero and empty stderr are required. False means the +substituted template differs syntactically, not malformed proof data. Proof +semantics stay unchecked, though physical proof layout errors still reject. -The explicit entries and caller coordinates are: +Test entries and caller offsets: | Entry | Source-owned calls | | --- | --- | -| `root`, `case` | Unfold checked owner roots using ordinal 1 or ordinal 2. Coordinates are 901/902/903 for left/right/clause. | -| `clause` | Same roots; ordinal is right-root identity minus 1, testing invalid local ordinals. | -| `invalid` | Checked root selectors 1/2/3 choose operands 0/N+1/1, then make one unfolding call. | -| `witness` | Unfold global N against N−1, selecting the final witness function and preceding witness target. | -| `session` | Unfold 2→1; structurally compare 2/1; unfold 4→1 then 4→3. Expected cumulative outcomes true 7 / false 8 / false 13 / true 20. | -| `retention` | Unfold 6→7, compare ground 3/4, unfold 6→7 again. Expected false 14 / true 16 / false 28. | -| `bulk` | Right-root selector 1 starts empty, 2 reserves 67108864, 3 reserves 1; left-root selector chooses the next amount at coordinate 907. | -| `budget` | Reserve a fixed amount, then unfold identity 2→1; selectors 5/6 replace the left/right operand with 0. Successful exact unfolding is followed by a one-unit reserve at 907. | +| `root`, `case` | Unfold checked owner roots with ordinal 1 or 2; offsets 901/902/903 for left/right/clause. | +| `clause` | Same roots with ordinal equal to right-root ID minus 1, testing invalid local ordinals. | +| `invalid` | Checked root selectors 1/2/3 pick operands 0/N+1/1, then run one unfolding call. | +| `witness` | Unfold global N against N−1 (final witness function against preceding witness target). | +| `session` | Unfold 2→1; structurally compare 2/1; unfold 4→1 then 4→3. Expected cumulative outcomes: true 7 / false 8 / false 13 / true 20. | +| `retention` | Unfold 6→7, compare ground 3/4, unfold 6→7 again. Expected: false 14 / true 16 / false 28. | +| `bulk` | Right-root selector 1 starts empty, 2 reserves 67108864, 3 reserves 1; left-root selector picks the next amount at offset 907. | +| `budget` | Reserve a fixed amount, then unfold identity 2→1; selectors 5/6 replace left/right operand with 0. An exact-limit unfolding is followed by a 1-unit reserve at 907. | -Bulk left-root selectors 1..8 choose respectively `0`, `-1`, `2147483648`, -`2147483647`, `67108864`, `67108865`, `1`, and `INT64_MIN`. Invalid amounts reject -with code 11 even after exhaustion. A maximum valid amount after one consumed -unit requests 2,147,483,648 without truncation. These selectors are explicit test -coordination over already checked root identities, not a new request format. +Bulk left-root selectors 1..8 pass `0`, `-1`, `2147483648`, `2147483647`, +`67108864`, `67108865`, `1`, and `INT64_MIN`. Invalid amounts reject with code +11 even after exhaustion. Requesting the maximum valid amount after one used +unit reports 2,147,483,648 without truncation. These selectors coordinate tests +over checked root IDs and do not change the request format. -Step derivations are independent of the implementation: +Expected step counts, derived directly from the spec: -- A mode-zero identity with one variable row costs ordinal 1 + index 2 + template - visit/resume 2 + ground identity comparison 2 = 7. A constant costs 5. -- A mode-one ordinal 2 variable costs 8; its constructor identity may instead be 3. - A two-row table whose body uses an unselected parameter costs 9. -- A false template retains completed ground-child memo entries, but each new - unfolding has fresh clause/binding-local memo state. Definitional equality - must never populate the structural `(left,right)` memo. -- Pre-reservation 67108857 permits identity unfolding to finish at 67108864. At 67108858, - the variable's ground comparison finishes at the limit but template terminal - resume refuses. At 67108863, the index bulk request is exactly 67108866; at 67108864, - clause scanning refuses at clause coordinate 903. Invalid IDs still reject first. -- A 46,484-row unary template with variable base costs `3T+4 = 139456`; the request - is 1,859,508 bytes. A 1,024-row shared binary DAG costs `5T+2 = 5122`; its request - is 49,312 bytes. Neither path expands a logical tree on the host or native stack. +- Mode-0 identity with one variable row costs 7: ordinal 1 + index 2 + template + visit/resume 2 + ground identity check 2. A constant costs 5. +- Mode-1 ordinal-2 variable costs 8 (constructor ID may be 3); a two-row table + using an unselected parameter costs 9. +- A false template keeps completed ground-child memo entries, while each new + unfolding starts a fresh clause/binding-local memo. Definitional equality + never populates the structural `(left,right)` memo. +- Pre-reserving 67108857 lets identity unfolding finish at 67108864. At + 67108858, variable comparison reaches the limit and final template resume + fails. At 67108863, index bulk reservation requests 67108866; at 67108864, + clause scanning fails at offset 903. Invalid IDs still reject first. +- A 46,484-row unary template with variable base costs `3T+4 = 139456` + (1,859,508-byte request); a 1,024-row shared binary DAG costs `5T+2 = 5122` + (49,312-byte request). Neither expands trees on host or native stacks. -There are 59 vectors, each executed once: 57 small vectors use a -60-second host watchdog; the two larger vectors use 600 seconds. -The Gamma entries retain their in-process unfolding and comparison session reuse. -These are watchdogs, not language bounds or owned refusals. Coverage includes -mode 0 / mode 1, local clause ordinals, unchanged child and other-parameter bindings, -incorrect target children, constructor/function heads, cross-space row-number -collisions, environment changes, witness custody, physical-error forwarding, -and semantically invalid but physically complete proof rows. This gate does not -validate derivations or accept the complete Beta encoding certificate. +The gate runs 59 vectors once each: 57 small vectors with 60-second watchdogs +and two large ones with 600-second watchdogs. The Gamma entries keep in-process +unfolding and session reuse. Watchdogs are host limits, not language bounds or +checker refusals. Coverage spans mode 0 and mode 1, local clause ordinals, +constructor-child and other-parameter bindings, wrong target children, +constructor/function heads, cross-space ID collisions, environment changes, +witness rows, layout-error forwarding, and semantically invalid but physically +valid proof rows. This gate does not check full proofs or accept the Beta +encoding certificate. diff --git a/tools/bootstrap/README.md b/tools/bootstrap/README.md index 6a9b9022e153..cc172a878357 100644 --- a/tools/bootstrap/README.md +++ b/tools/bootstrap/README.md @@ -1,9 +1,9 @@ # Bootstrap-chain tooling -This directory holds replaceable scripts that run the bootstrap chain, write -tapes, build exact artifacts and check the chain's layout. It holds no -language semantics, compiler source, proof, canonical artifact or test corpus. -These temporary host scripts fall under the +This directory holds replaceable helper scripts that run the bootstrap chain, +stamp tapes, pack artifacts, and check repository layout. It contains no +language rules, compiler source, proofs, canonical artifacts, or test suites. +These temporary host scripts follow the [whole-chain minimization contract](../../bootstrap/MINIMIZATION.md). ```sh @@ -11,113 +11,110 @@ sh tools/bootstrap/check-chain-hygiene.sh sh tests/bootstrap/interpreted/alpha-beta-edge.sh --edge ``` -The second command, kept with the cross-rung tests, checks the finished part -of the chain: the audited Alpha seed's behavior and an exact rebuild of the -trusted Beta compiler. No wrapper calls it a full chain run or prints status -for compiler edges that do not exist. +The second command lives with the cross-stage tests and checks the finished +part of the chain: the audited Alpha seed's behavior and a byte-exact rebuild +of the trusted Beta compiler. No script claims to run a full chain or reports +status for compiler stages that do not exist yet. `tools/bootstrap/alpha/seed_env.sh` pins the exact size and SHA-256 of the audited Alpha container chosen in `bootstrap/alpha/README.md`; -`stamp_seed` refuses any other bytes. -`tools/bootstrap/beta/artifact_env.sh` pins the exact size and SHA-256 of -`beta_compiler.beta` and `beta_compiler_bytecode.tape` and refuses any -other bytes; these identities are audited in +`stamp_seed` rejects any other bytes. +`tools/bootstrap/beta/artifact_env.sh` pins `beta_compiler.beta` and +`beta_compiler_bytecode.tape` the same way; those files are audited in `bootstrap/beta/AUDIT.md` and decoded by `tests/bootstrap/interpreted/beta/compiler/root-audit.py`. `tools/bootstrap/gamma/evaluator_env.sh` pins `gamma_evaluator.beta` and -`gamma_evaluator_bytecode.tape` the same way against -`bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md`. A matching digest checks -identity; it is not a proof. - -`tools/bootstrap/delta/compiler_env.sh` pins the Delta edge's request entry, -source manifest, ordered support-member manifest, `GammaComposedV2` record, -repacked canonical closure and packed support section the same way against -`bootstrap/delta/compiler/README.md` and `delta_compiler.composed`. It -checks that the record names the chosen evaluator tape, packed closure -and packed support section. It also pins the staged-compiler gate's -`development_driver.gamma` diagnostic entry, packed on top of the pinned -member bytes. The archived [_Delta identity test_](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/delta-identity.sh) records its refusal cases. -`tools/bootstrap/epsilon/evaluator_env.sh` pins the -`epsilon_compiler.delta.sources` manifest and repacked evaluator closure -against `bootstrap/epsilon/interpreter/README.md`. Both refuse before writing if -the bytes differ from the pins, including a changed manifest or member. The Epsilon file also pins the interpreted Omega executable gate’s private `execution_driver.delta` -slice adapter and the evaluator receipt identity that the pinned Delta edge -rebuilds from the pinned evaluator, driver and support section; -the archived [Epsilon identity test](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/epsilon-identity.sh) records the driver and receipt refusals -and every consuming gate's record. - -`tools/bootstrap/omega/compiler_env.sh` pins the -`omega_compiler.epsilon.sources` manifest and repacked D closure against -`bootstrap/omega/compiler/README.md` the same way. It also pins the -entries the omega-parser, omega-outcome, omega-request and omega-executable -gates append on top of the pinned member bytes, and -the omega-request gate's canonical sealed request fixture; each gate's -README records its own. The same file pins D's OCREQ request entry, -`program.omg`: the canonical 180-byte Omega source the request compiles, -SHA-256 `9cc2d065cf33e3a9de241d061f407665892f7171a431936a0e5ad9e5d3eeea85`. -It is a separate input fed to the pinned customer entry as sealed bytes, -not a manifest member. - -The archived [identity gates](https://github.com/CathedralOS/Omega/tree/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap) checked the exact bytes written -and that corrupted or truncated bytes are refused, against the pins. They -checked the records of the programs that use the bytes, but never grep -documentation for copies of the hashes or byte counts: a pin repeated in -prose proves nothing new. The cited audit and profile documents explain each -artifact and its obligations. - -`check-chain-hygiene.sh` verifies the Alpha and Beta artifacts and the -declared compiler source closures. It checks that their manifest members and -bootstrap steps omit the Rust producer. The Delta interpreter's ordered source -list and the Epsilon compiler and runtime lists must resolve to source files -under their respective language directories. Alpha and Beta have flat seed -directories. Gamma, Delta, Epsilon and Omega keep implementations under their -language. The Linux launcher and proof experiments live under -[bootstrap tests](../../tests/bootstrap/). The [route reports](../../wiki/development/bootstrap/) record measured results. - -The gate inspects tracked and untracked non-ignored files in a checkout, -or the files present in a source archive. Empty owner directories left by a -move are ignored. `sh tests/bootstrap/interpreted/chain-hygiene.sh` exercises -both forms and checks that a new implementation can coexist with the tested -routes. - -`mbx xtask source-closure MANIFEST OUTPUT` checks source members, in the order -the manifest gives, and concatenates them. `GammaSourceClosureV1` selects -`.gamma` members for the Delta compiler and its runtime support; `DeltaSourceClosureV1` selects `.delta` members for the Epsilon -evaluator; `EpsilonSourceClosureV1` selects `.epsilon` members for Omega D. All use -the same rows: identity, length, digest and canonical relative path. The -manifest's directory must list every source file in it: a missing, extra, -wrong-language, stale or symlinked member is rejected before the output is -replaced. `--prefix ENTRY` puts one non-member entry file, a marked entry or -a gate's diagnostic header, before the packed members. It must be a regular file with the manifest's source suffix; a wrong -language, symlink, non-regular path or forbidden bytes are rejected first. Walking the directory only checks -membership, never choosing or ordering inputs. - -`paths.sh` exports the canonical path of each chosen directory. It may name -future compiler artifacts before they exist; the layout check does not treat -them as present. The [proof test helper](../../tests/bootstrap/proofs/sources_env.sh) -owns the paths and identity checks for the optional proof experiments. -Shell scripts only invoke things and can be replaced. Source-closure packing, -the Alpha Windows listing forge and Gamma evaluator runs are xtask commands. -None of them may parse an accepted language, lower code, invent proof -premises or decide admission. - -The subdirectories hold sourceable scripts that write artifacts, or explicit -artifact build commands. Tests in `tests/` use them; canonical -artifacts stay in their language's directory. +`gamma_evaluator_bytecode.tape` against +`bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md`. Matching digests check file +identity, not correctness. + +`tools/bootstrap/delta/compiler_env.sh` pins the Delta compiler's request entry, +source manifest, ordered support manifest, `GammaComposedV2` record, +packed source bundle, and packed support section against +`bootstrap/delta/compiler/README.md` and `delta_compiler.composed`. It verifies +that the record names the chosen evaluator tape, source bundle, and support +section, and also pins the staged-compiler test's `development_driver.gamma` +diagnostic entry on top of those members. The archived +[_Delta identity test_](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/delta-identity.sh) +lists its refusal cases. + +`tools/bootstrap/epsilon/evaluator_env.sh` pins +`epsilon_compiler.delta.sources` and the packed evaluator bundle against +`bootstrap/epsilon/interpreter/README.md`. Both helpers abort before writing if +any byte, manifest, or member differs. The Epsilon helper also pins the +interpreted Omega executable test's private `execution_driver.delta` adapter +and the evaluator output hash rebuilt by the pinned Delta stage. The archived +[Epsilon identity test](https://github.com/CathedralOS/Omega/blob/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap/epsilon-identity.sh) +records those driver and output refusals and every consuming test's record. + +`tools/bootstrap/omega/compiler_env.sh` pins +`omega_compiler.epsilon.sources` and the packed D bundle against +`bootstrap/omega/compiler/README.md`. It also pins the entry files appended by +the omega-parser, omega-outcome, omega-request, and omega-executable tests, plus +the omega-request test's canonical sealed request fixture (each test's README +documents its own). The same script pins D's OCREQ input file, `program.omg` +(180 bytes, SHA-256 `9cc2d065cf33e3a9de241d061f407665892f7171a431936a0e5ad9e5d3eeea85`), +which is passed as sealed stdin rather than listed in the manifest. + +The archived +[identity gates](https://github.com/CathedralOS/Omega/tree/86090d7aadaf54c24d3470dfe259b52a5ba85e68/_recycling/tests/bootstrap) +verified exact output bytes and rejected corrupted or truncated inputs against +these pins. They checked records produced by the programs that consume the +bytes, never by grepping docs for copied hashes or sizes. The linked audit and +profile docs describe each artifact and its requirements. + +`check-chain-hygiene.sh` checks the Alpha and Beta artifacts and all declared +compiler source bundles. It verifies that manifest members and bootstrap steps +omit the Rust compiler, and that the Delta interpreter's source list and +Epsilon compiler and runtime lists resolve to files inside their own language +directories. Alpha and Beta use flat seed directories; Gamma, Delta, Epsilon, +and Omega keep implementations under their language directories. The Linux +launcher and proof experiments live in [bootstrap tests](../../tests/bootstrap/). +[Route reports](../../wiki/development/bootstrap/) record measured results. + +The hygiene check inspects tracked and untracked non-ignored files in a +checkout, or all files in a source archive, ignoring empty directories left by +moves. `sh tests/bootstrap/interpreted/chain-hygiene.sh` tests both modes and +confirms that a new implementation can coexist with existing routes. + +`mbx xtask source-closure MANIFEST OUTPUT` validates source files in manifest +order and concatenates them. `GammaSourceClosureV1` packs `.gamma` files for +the Delta compiler and runtime support; `DeltaSourceClosureV1` packs `.delta` +files for the Epsilon evaluator; `EpsilonSourceClosureV1` packs `.epsilon` +files for Omega D. Each row lists an ID, byte length, digest, and relative +path. The manifest must list every source file in its directory; missing, +extra, wrong-language, stale, or symlinked files fail before overwriting the +output. `--prefix ENTRY` prepends one non-member entry file (a marked entry or +diagnostic header) that must be a regular file with the matching suffix and no +forbidden bytes. Directory scanning only verifies completeness—it never chooses +or orders inputs. + +`paths.sh` exports canonical paths for each directory. It may name future +artifacts before they exist; the layout check does not require them to be +present. The [proof test helper](../../tests/bootstrap/proofs/sources_env.sh) +handles paths and identity checks for optional proof experiments. Shell scripts +only launch tools and can be replaced. Source-bundle packing, forging the +Windows Alpha binary, and running the Gamma evaluator are `xtask` commands. +None of these helpers may parse an accepted language, lower code, invent proof +premises, or decide language acceptance. + +Subdirectories contain sourceable scripts for building or verifying artifacts. +Tests under `tests/` call them, while canonical artifacts stay in their +language directories. ## Retention and deletion | Child/files | Present consumer | Deletion condition | | --- | --- | --- | -| `paths.sh` | Alpha, Beta, Gamma, Delta, Epsilon, Omega, and topology gates that share exact owner paths | Absorb the remaining locators into a single cheaper canonical invocation mechanism, then delete this file and update every consumer atomically. | -| `check-chain-hygiene.sh` | Checks language ownership, closed artifact identities and omission of the Rust producer from declared routes. | Replace it when another gate verifies the same inventories, identities and dependencies. | -| `alpha/` | Alpha seed selection and tape stamping used by current tests and tools. | Delete only when every caller has an equally direct canonical invocation. | -| `beta/` | Trusted Beta compiler materialization with the bound-identity check, and disposable program builds. | Delete only when every caller has an equally direct canonical invocation. | -| `gamma/evaluator_env.sh` | Selected Beta-authored functional Gamma evaluator materialization. | Delete only when every caller has an equally direct canonical invocation. | -| `delta/compiler_env.sh` | Bound identity and canonical closure materialization for the Gamma-authored Delta compiler, plus the bound staged-compiler development driver entry. | Delete only when every caller has an equally direct canonical invocation. | -| `epsilon/evaluator_env.sh` | Bound identity and canonical closure materialization for the Delta-authored Epsilon evaluator. | Delete only when every caller has an equally direct canonical invocation. | -| `omega/compiler_env.sh` | Bound identity and canonical closure materialization for the Epsilon-written Omega compiler D. | Delete only when every caller has an equally direct canonical invocation. | -| `mbx xtask source-closure` | Byte-exact assembly of the Gamma-written Delta compiler, Delta-written Epsilon evaluator, and Epsilon-written Omega compiler source closures. | Delete only when the selected lower compilers accept the same canonical member closures directly. | - -The retired `verify-lattice.sh`, `test-paths.sh`, old bootstrap-role -wrapper, future-artifact locators, root compiler cache and receipt profiles -checked nothing of their own. They remain in Git history. +| `paths.sh` | Alpha, Beta, Gamma, Delta, Epsilon, Omega, and layout tests that share canonical paths. | Move remaining paths into a single simpler runner, delete this file, and update all callers together. | +| `check-chain-hygiene.sh` | Checks language layout, pinned artifact hashes, and that declared routes omit the Rust compiler. | Replace when another check verifies the same inventories, hashes, and dependencies. | +| `alpha/` | Alpha seed selection and tape stamping for tests and tools. | Delete only when every caller has an equally direct runner. | +| `beta/` | Trusted Beta compiler setup with hash verification, plus disposable builds. | Delete only when every caller has an equally direct runner. | +| `gamma/evaluator_env.sh` | Setup for the Beta-written Gamma evaluator. | Delete only when every caller has an equally direct runner. | +| `delta/compiler_env.sh` | Hash verification and source packing for the Gamma-written Delta compiler and its staged-compiler diagnostic entry. | Delete only when every caller has an equally direct runner. | +| `epsilon/evaluator_env.sh` | Hash verification and source packing for the Delta-written Epsilon evaluator. | Delete only when every caller has an equally direct runner. | +| `omega/compiler_env.sh` | Hash verification and source packing for the Epsilon-written Omega compiler D. | Delete only when every caller has an equally direct runner. | +| `mbx xtask source-closure` | Byte-exact source packing for the Delta compiler, Epsilon evaluator, and Omega compiler bundles. | Delete only when the lower compilers read the same source manifests directly. | + +The retired `verify-lattice.sh`, `test-paths.sh`, old bootstrap-role wrapper, +future-artifact paths, root compiler cache, and receipt profiles tested nothing +of their own and remain in Git history. diff --git a/wiki/development/bootstrap/compiled-alpha.md b/wiki/development/bootstrap/compiled-alpha.md index 9a39b55ef037..abaf9912f32d 100644 --- a/wiki/development/bootstrap/compiled-alpha.md +++ b/wiki/development/bootstrap/compiled-alpha.md @@ -1,69 +1,68 @@ # Compiled VM experiment -This peer removes the Gamma interpretation layer after constructing a Gamma -compiler from source. [`../../../bootstrap/gamma/compiler/compiler.gamma`](../../../bootstrap/gamma/compiler/compiler.gamma) and -[`../../../bootstrap/gamma/compiler/frontend.gamma`](../../../bootstrap/gamma/compiler/frontend.gamma), with the -[`Alpha backend`](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma), compile Gamma to independent Alpha tapes. -Their first customer is the existing Gamma-written Delta compiler, which -constructs the Delta-written Epsilon evaluator. Its Gamma receipt is compiled -to another independent tape and runs the Epsilon-written bootstrap compiler. -No variant is selected by this experiment. - -The source construction starts from the checked-in native -[Alpha seed](../../../bootstrap/alpha/README.md), the separately admitted -[Beta compiler tape](../../../bootstrap/beta/AUDIT.md), and the host OS. It stamps that tape -into Alpha, reconstructs Beta from its source, and uses the reconstructed Beta -compiler to construct the Gamma evaluator from Beta source. Both tapes must -match their bound artifacts exactly. The constructed Gamma evaluator then runs -the authored Gamma compiler on its own source to construct `compiler0`. -`compiler0` and its successor each rebuild that source; all three resulting -tapes must be identical. Beta self-reconstruction is evidence about the admitted -seed; it does not derive the initial Beta tape from nothing. +This route removes Gamma interpretation after building a Gamma compiler from +source. [`../../../bootstrap/gamma/compiler/compiler.gamma`](../../../bootstrap/gamma/compiler/compiler.gamma) +and [`../../../bootstrap/gamma/compiler/frontend.gamma`](../../../bootstrap/gamma/compiler/frontend.gamma), +paired with the [`Alpha backend`](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma), +compile Gamma to standalone Alpha tapes. Their first target is the Gamma-written +Delta compiler, which builds the Delta-written Epsilon evaluator; compiling that +Gamma output to an Alpha tape runs the Epsilon-written bootstrap compiler. This +experiment does not select a final route. + +Cold construction starts from the checked-in native +[Alpha seed](../../../bootstrap/alpha/README.md), the trusted +[Beta compiler tape](../../../bootstrap/beta/AUDIT.md), and the host OS. It +stamps that tape into Alpha, rebuilds Beta from source, and uses the rebuilt +Beta to build the Gamma evaluator from source; both tapes must match their +pinned hashes byte for byte. The Gamma evaluator then compiles the Gamma +compiler source to produce `compiler0`, and two self-rebuilds must produce three +identical tapes. Rebuilding Beta checks the trusted seed—it does not derive the +initial Beta tape from nothing. ## Run -From the repository root on Linux x86-64, construct the Alpha-tape Gamma compiler in a new output directory: +From the repository root on Linux x86-64, build the Alpha-tape Gamma compiler +into a fresh directory: ```sh tests/bootstrap/linux_x86_64/bootstrap --alpha . /tmp/omega-gamma-alpha /tmp/omega-gamma-alpha/gamma-compiler < source.gamma > program.tape ``` -The native driver feeds the seed and each reconstructed compiler directly. [Linux construction and inputs](../../../tests/bootstrap/linux_x86_64/README.md) +The native driver feeds the seed and each rebuilt compiler directly. +[Linux construction and inputs](../../../tests/bootstrap/linux_x86_64/README.md) ### Run the public Omega lexer on Alpha -The public Omega lexer now fits in the audited Linux x86-64 Alpha seed. Two -compiler changes can be measured independently on the same 58,733-byte -Epsilon program. The Epsilon compiler shares the code that propagates exits, -traps and internal failures. The Gamma Alpha backend shares the code that -pushes and pops a value on its evaluation stack. +The public Omega lexer fits inside the audited Linux x86-64 Alpha seed thanks to +two independent changes measured on the same 58,733-byte Epsilon program: the +Epsilon compiler shares exit/trap/internal outcome handling, and the Gamma Alpha +backend shares evaluation-stack push and pop helpers. | Epsilon emission | Gamma source bytes | Original Gamma backend | Compact Gamma backend | | --- | ---: | ---: | ---: | | Original | 2,827,892 | 32,158,739 bytes of calculated layout; refused | 15,449,892-byte tape | | Shared outcome handling | 1,594,506 | 15,120,299-byte tape | **7,342,855-byte tape** | -Each published tape ran the original 148-byte batch and returned the expected -465 bytes for all 23 cases. The observation includes Epsilon exit 42 and agrees -with both the evaluator and the native executable. The smallest tape leaves -9,434,357 bytes in the seed. [Lexer cases and expected bytes](../../../tests/bootstrap/independent/epsilon/lexer_scan_test.py) - -A separate cold run copied only `bootstrap/` into a new source root and ran the -external Linux launcher with an empty `PATH`. From the admitted seed it built -the native Gamma, Delta and Epsilon compilers. A byte packer read the Epsilon -compiler's own source and runtime lists. The compiled Epsilon program used -its standard entry. The cold Gamma compiler also built the Alpha-targeting -compiler that emitted the 7,342,855-byte tape. Stamping that tape into the seed -reproduced the 465-byte observation. [Source lists and commands](../../../bootstrap/epsilon/compiler/README.md) - -The old encoding repeated a 69-byte stack push at 209,820 sites and a -32-byte pop at 179,121 sites. The Alpha backend now calls three leaf routines -with nine-byte Alpha calls. One pushes the current word and its tag. The other -two pop into the left or right operand register pair. The push still checks the -frame bound before writing. Each routine returns before a source call, a tail -jump or the next stack operation, so the maximum remains one temporary return -address in addition to the active Gamma calls. Native code still inlines these operations. +Each emitted tape ran the 148-byte batch and returned the expected 465 bytes +across all 23 cases (including Epsilon exit 42), matching both the evaluator and +the native binary. The smallest tape leaves 9,434,357 bytes free in the seed. +[Lexer cases and expected bytes](../../../tests/bootstrap/independent/epsilon/lexer_scan_test.py) + +A cold run copied only `bootstrap/` into a new tree and ran the Linux launcher +with an empty `PATH`. From the seed it built the native Gamma, Delta, and +Epsilon compilers; a packer read the Epsilon compiler's source and runtime lists, +the compiled Epsilon program ran with its standard entry, and the cold Gamma +compiler built the Alpha-targeting compiler that emitted the 7,342,855-byte tape. +Stamping that tape reproduced the 465-byte output. +[Source lists and commands](../../../bootstrap/epsilon/compiler/README.md) + +The old encoding inlined a 69-byte push at 209,820 sites and a 32-byte pop at +179,121 sites. The Alpha backend now calls three leaf helpers via nine-byte +Alpha calls: one pushes the word and tag (checking frame bounds first), and two +pop into the left or right operand register pair. Each helper returns before any +source call, tail jump, or next stack op, adding at most one temporary return +address above active Gamma calls. Native code still inlines these ops. [Alpha assembler](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) | Public lexer artifact | Bytes | SHA-256 | @@ -75,100 +74,85 @@ address in addition to the active Gamma calls. Native code still inlines these o | Compact backend, shared Epsilon outcomes | 7,342,855 | `f445ec71096c3be69d78a00aba2402130f196998248e977466865fcc924e5e30` | | Lexer output | 465 | `7d7a561d217ec1ce599a203fb8290b907c2582883c98dc71541c5bd0633f31aa` | -Starting from the admitted Beta tape, the launcher constructed the 227,471-byte -Gamma compiler tape and reproduced it twice (SHA-256 -`76d58ec432aa1f0d2e1c4471f5a99a7240ea900af672722bcde317f4e32cfca2`). -It passed the 47 portable Gamma checks. At 131,072 active source calls the -test published both expected bytes. One more call returned 250 with empty -output. The 17-case string scanner also ran on Alpha in 4,025,521 tape bytes. +From the trusted Beta tape, the launcher built the 227,471-byte Gamma compiler +tape and reproduced it twice (`76d58ec432aa1f0d2e1c4471f5a99a7240ea900af672722bcde317f4e32cfca2`), +passing all 47 portable Gamma checks. At 131,072 active source calls it wrote +both expected bytes; one more call returned 250 with empty output. The 17-case +string scanner also ran on Alpha in 4,025,521 tape bytes. -To rebuild this customer from its Epsilon source and execute the lexer -checks, run `python3 tests/bootstrap/independent/successor_test.py --compile-epsilon`. -The route writes the public Gamma receipt, Alpha tape and observations under -`build/independent-successors/compiled-epsilon/`. +To rebuild this lexer from Epsilon and run its checks, execute +`python3 tests/bootstrap/independent/successor_test.py --compile-epsilon`. +Outputs go under `build/independent-successors/compiled-epsilon/`. ### Running the whole Omega constructor on one tape -The cold launcher used the original Gamma evaluator to compile the -43,315-byte Alpha-targeting compiler source, SHA-256 -`afee5b7c75679386d30e483d4a627aeeca617f9c3de2dd637adc0474277cc007`. -It produced a 207,681-byte compiler tape. Running that tape on its own -source and repeating with its successor gave three byte-identical tapes, -SHA-256 `c3274d349b53511e4a8bcd8624927d1d2aee3052f1212ed113234255f650f7e1`. - -The Gamma-to-Alpha compiler assembled the 25,733,081-byte Gamma constructor -from `bcf71f0bbfc` into one 11,976,860-byte tape, SHA-256 -`172bd421b5c2cf334a7a5688c843e1e9dc24cefe11d7bb2b25a9d514ad17d491`. -A seed-built Linux executable of the Gamma-to-Alpha compiler emitted this -tape. The Alpha seed then ran the resulting constructor and both product -tapes below. The uncompressed instructions occupy 57,004,893 bytes. The stamped program -starts with a 340-byte Alpha decoder and a 3,840-byte dictionary. The seed -runs the decoder itself. Programs that fit the seed directly keep their -plain Alpha instructions. The Alpha backend grew from 3,681 to 11,814 bytes. -Across the entire Gamma-to-Alpha compiler, authored source grew from 35,082 -to 43,315 bytes. Its own Alpha tape grew from 176,772 to 207,681 bytes. -Both the old and new compilers emitted the same tape for the old compiler -source at `980fa9c6a6c` (SHA-256 -`940396e8eb92b1599996a5b1d9ad1df3bf04b5d6e9ceae10a984de0472d4f4c8`). Using the original Gamma interpreter to -run the final constructor avoids this packing algorithm. - -The seed ran the packed constructor on a 111-byte Omega package. It -produced the expected 22-byte Alpha tape, SHA-256 -`25c789ed6ce473847a1dc82854aad7b59d3ff336d4ed73a64a56c540b5d78384`, -which exited 42 on the seed. On the 828-byte two-package wire decoder the -same constructor produced a 1,607-byte tape, SHA-256 -`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`. -That tape exited 42 with empty stdout and stderr. Removing the package edge -returned guest exit 1 at byte 11. Appending a byte returned framing refusal 3. [Same package on original Gamma](../../../tests/bootstrap/independent/WHOLE_REQUEST.md#running-the-compiled-omega-constructor-as-gamma-on-the-seed) - -For a large program the compiler takes up to 240 instructions seen twice -among the first 4,096. Each becomes one byte in the encoded stream. Tokens -1 through 11 introduce that many literal instruction bytes, and tokens -16 through 255 select a 16-byte dictionary record. The first byte of each -record is the instruction's original length. Only the compiler builds -the dictionary. The seed runs ordinary load, store and branch instructions -to copy the indicated bytes into `[0x28000000, 0x30000000)`. The output -buffer ends at the first address and the pair heap starts at the second. -The decoder checks the stream end, dictionary indexes, copy lengths and -destination end before restoring its registers and jumping to the program. - -The compiler resolves each branch and call for this interval while preserving -literal integers, including integers equal to an old branch address. An -independent expansion of the measured tape matched the original instructions, -with exactly the placement offset added to all 3,484,036 branch and call -addresses. The complete encoded tape must fit the original stamp even when -the expanded instructions fit the separate code interval. Source validation -still precedes publication, including functions that are never called. +The cold launcher used the Gamma evaluator to compile the 43,315-byte +Alpha-targeting compiler source (`afee5b7c75679386d30e483d4a627aeeca617f9c3de2dd637adc0474277cc007`) +into a 207,681-byte tape; two self-rebuilds produced three identical tapes +(`c3274d349b53511e4a8bcd8624927d1d2aee3052f1212ed113234255f650f7e1`). + +A seed-built Linux binary of the Gamma-to-Alpha compiler assembled the +25,733,081-byte Gamma constructor from `bcf71f0bbfc` into an 11,976,860-byte +packed tape (`172bd421b5c2cf334a7a5688c843e1e9dc24cefe11d7bb2b25a9d514ad17d491`), +whose uncompressed instructions span 57,004,893 bytes. The stamped tape begins +with a 340-byte Alpha decoder and a 3,840-byte dictionary run directly by the +seed; smaller programs stay uncompressed. The Alpha backend grew from 3,681 to +11,814 bytes, total compiler source grew from 35,082 to 43,315 bytes, and its +tape grew from 176,772 to 207,681 bytes. Old and new compilers still emitted the +same tape for the old source at `980fa9c6a6c` +(`940396e8eb92b1599996a5b1d9ad1df3bf04b5d6e9ceae10a984de0472d4f4c8`). Running the +final constructor on the Gamma interpreter avoids this packing step. + +On the seed, the packed constructor compiled a 111-byte Omega package to the +expected 22-byte Alpha tape (`25c789ed6ce473847a1dc82854aad7b59d3ff336d4ed73a64a56c540b5d78384`), +which exited 42. On the 828-byte two-package wire decoder it emitted a +1,607-byte tape (`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`) +that exited 42 with empty stdout/stderr; removing the dependency edge returned +guest exit 1 at byte 11, and appending a byte returned framing refusal 3. +[Same package on original Gamma](../../../tests/bootstrap/independent/WHOLE_REQUEST.md#running-the-compiled-omega-constructor-as-gamma-on-the-seed) + +For large programs, the compiler picks up to 240 instructions seen twice among +the first 4,096 and encodes each as one byte. Tokens 1–11 introduce that many +literal instruction bytes; tokens 16–255 select a 16-byte dictionary entry whose +first byte is the instruction length. Only the compiler builds the dictionary. +The seed unpacks bytes into `[0x28000000, 0x30000000)` (between the output +buffer and pair heap), checking stream end, dictionary indexes, copy lengths, +and destination end before restoring registers and jumping to the code. + +The compiler relocates branches and calls for this range without altering +literal integers (even integers matching an old branch address). Independent +expansion matched the original instructions with the exact base offset added to +all 3,484,036 branch and call targets. The encoded tape must still fit the +16 MiB stamp limit, and source validation still checks every function (including +unused ones) before output. [Alpha encoder and decoder](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) · [Seed instructions](../../../bootstrap/alpha/SEMANTICS.md#5-transition-rules) -To build and run the constructor through the normal Alpha launcher, use the -`omega.gamma` produced by the whole-constructor construction and an empty -output directory. The genuine standalone wire customer checks the resulting -tape and its missing-edge and framing controls. +To build and test the constructor with the Alpha launcher using `omega.gamma` +and a fresh output directory: ```sh tests/bootstrap/linux_x86_64/bootstrap --alpha . /tmp/omega-packed-alpha /path/to/omega.gamma python3 tests/bootstrap/independent/product_wire.py /tmp/omega-packed-wire --constructor /tmp/omega-packed-alpha/program ``` -To exercise the packed entry without assembling the Omega constructor, run +To test packed output without building the full Omega constructor, run `python3 tests/bootstrap/compiled_vm/source_test.py --compiler-only --large-alpha`. -The control compiles 700 unused arithmetic definitions and a forward call. -Its 21,467,587 ordinary instruction bytes produced a 5,030,606-byte tape. -The stamped program matched byte output, a guest refusal and an arithmetic -trap. The compiler rejected an invalid call in the last declaration. [Source](../../../tests/bootstrap/compiled_vm/source_test.py) · +It compiles 700 unused arithmetic definitions and a forward call (21,467,587 +expanded bytes packed into 5,030,606 bytes), verifying byte output, guest +refusal, an arithmetic trap, and rejection of an invalid call in the last +declaration. +[Source](../../../tests/bootstrap/compiled_vm/source_test.py) · [Whole-constructor input](../../../tests/bootstrap/independent/WHOLE_REQUEST.md) #### Building the packed constructor entirely on Alpha -The Alpha-hosted Epsilon and Delta compilers at `c6d64f0f3c4` translated -the 899,962-byte Epsilon-written Omega compiler into 26,354,274 bytes of -Gamma. The Gamma-to-Alpha compiler from `770c184573c` assembled that Gamma -on the seed. The original Gamma evaluator and two successive compiler -generations each built the same 207,681-byte compiler tape from its -43,315-byte source. The shell launcher stamped the tapes and connected -their input and output files. [Reproduce the Epsilon and Delta stages](../../../tests/bootstrap/independent/WHOLE_REQUEST.md#running-the-compiled-omega-constructor-as-gamma-on-the-seed) +At `c6d64f0f3c4`, Alpha-hosted Epsilon and Delta compilers translated the +899,962-byte Epsilon-written Omega compiler into 26,354,274 bytes of Gamma, and +the `770c184573c` Gamma-to-Alpha compiler assembled it on the seed. All three +compiler generations matched byte for byte (207,681 bytes from 43,315 source +bytes), while the shell launcher only stamped tapes and wired files. +[Reproduce the Epsilon and Delta stages](../../../tests/bootstrap/independent/WHOLE_REQUEST.md#running-the-compiled-omega-constructor-as-gamma-on-the-seed) | Artifact | Bytes | SHA-256 | | --- | ---: | --- | @@ -176,27 +160,24 @@ their input and output files. [Reproduce the Epsilon and Delta stages](../../../ | Alpha-produced Gamma input | 26,354,274 | `215cd20cbc51fcdff281fb1075c474fc0afe3f4d1b89d141c18a974da6cd19cd` | | Packed constructor tape | 12,074,120 | `c5d2041b9e8ecc5bb39fd008f5a13d1973c9dd46ae39c24370ec92229bd6d694` | -This final compilation used 1,412.64 CPU seconds and peaked at 4,888,848 KiB. -The independent reader recovered 58,526,320 ordinary instruction bytes and -normalized 3,574,727 branch and call addresses, giving SHA-256 -`90b2236bc647b67539ed0a54db989c53bbec621168a3bf726481ff3431ff7be1`. +Final assembly used 1,412.64 CPU seconds and 4,888,848 KiB peak RSS. The +independent reader expanded 58,526,320 instruction bytes and rebased 3,574,727 +jump/call targets (`90b2236bc647b67539ed0a54db989c53bbec621168a3bf726481ff3431ff7be1`). -On the 111-byte Omega package the packed constructor produced the same -22-byte tape as the original Gamma interpreter. On the 828-byte two-package -wire decoder, it emitted the 1,607-byte tape -`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`. -Both tapes exited 42 on the seed with empty stdout and stderr. Removing the -wire package dependency returned guest exit 1 at byte 11. Appending a -trailing byte returned the five-byte framing refusal, guest exit 3. +The packed constructor produced the same 22-byte tape on the 111-byte Omega +package and the same 1,607-byte tape +(`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`) on the +828-byte wire decoder; both exited 42 with empty output. Removing the wire +dependency returned guest exit 1 at byte 11, and appending a byte returned the +five-byte framing refusal (guest exit 3). #### Comparing the same constructor on Alpha and Linux -At `980fa9c6a6c` the Epsilon-written Omega compiler handled typed -forward-call parameters and qualified sum cases in transition result arms. Packing its -manifest and appending the normal construction entry reproduced its complete -934,574-byte source. Seed-built Linux-hosted tools produced the Gamma input. -The Alpha and Linux backends then assembled that input for their respective -runtimes. +At `980fa9c6a6c`, the Epsilon-written Omega compiler added typed forward-call +parameters and qualified sum cases in transition result arms. Packing its +manifest with the construction entry yielded 934,574 source bytes; seed-built +Linux tools generated the Gamma input, and both Alpha and Linux backends +assembled it. [Compiler manifest](https://github.com/CathedralOS/Omega/blob/980fa9c6a6c/bootstrap/omega/compiler/omega_compiler.epsilon.sources) · [Construction entry](../../../bootstrap/omega/construct_omega.epsilon) @@ -207,28 +188,24 @@ runtimes. | Packed Alpha tape | 12,359,478 | `554b7ee19a07cfe50a6d8eed1cfc56911768553b1a19c7c2c6080047d63f88c3` | | Linux x86-64 executable | 56,615,863 | `2fe8ba0c5e1fa254c2c83e673c3f7495f4e673cfc5fc4fe8cde52593c981bdfe` | -The independent tape reader expanded 58,805,184 instruction bytes and -rebased 3,596,175 jump and call targets to a code base of zero, giving SHA-256 -`a6c236eb3db6002e3622b4b987f32cdf808bb6c525338882c098e857fcf77577`. -The Alpha seed ran the packed constructor on the same 111-byte package as -the Linux executable. Their 27 output bytes matched, including the 22-byte -Alpha tape `25c789ed6ce473847a1dc82854aad7b59d3ff336d4ed73a64a56c540b5d78384`. -The resulting tape exited 42 on the seed with empty stdout and stderr. The -Alpha constructor returned the exact five-byte guest exit 3 for the -trailing-byte wire package. +The tape reader expanded 58,805,184 bytes and rebased 3,596,175 jump/call +targets to base zero (`a6c236eb3db6002e3622b4b987f32cdf808bb6c525338882c098e857fcf77577`). +On the 111-byte package, the Alpha seed and Linux executable emitted identical +27-byte output (including the 22-byte tape +`25c789ed6ce473847a1dc82854aad7b59d3ff336d4ed73a64a56c540b5d78384`), which exited +42 with empty output. On the trailing-byte wire package, Alpha returned the +exact five-byte guest exit 3. #### Checking the expanded instructions -The hosted Omega reader checks instruction widths and subtracts the code base -from absolute branch and call targets. Its standard output contains ordinary -Alpha instruction bytes. On success, standard error gives the expanded byte -count and the number of rebased transfers. A nonzero exit means the tape failed -validation, and any partial output must be discarded. The seed-only compiler -conformance test keeps an independent Python reader so it can run without a -hosted Omega compiler. +The hosted Omega reader validates instruction widths, subtracts the code base +from absolute jump/call targets, writes ordinary Alpha bytes to stdout, and +prints expanded byte and rebased-target counts to stderr. Any nonzero exit means +validation failed and partial stdout must be discarded. The seed-only compiler +test keeps an independent Python reader so it needs no hosted Omega compiler. -From the repository root, build the inspector once. Its executable accepts a -packed tape on standard input. Hash the ordinary instructions after it succeeds. +Build the inspector once from the repository root, pipe a packed tape into it, +and hash the output on success: ```sh inspector_dir=$(mktemp -d) @@ -242,16 +219,14 @@ inspector="$inspector_dir/omega-program" ``` Run `python3 tests/bootstrap/compiled_vm/packed_tape/test.py "$inspector"` to -check every opcode, relocated operands, malformed input and plain-file mismatches. +test every opcode, relocated operands, malformed inputs, and mismatches. -The historical 11,976,860-byte tape expanded to 57,004,893 ordinary bytes, -including 3,484,036 targets, with SHA-256 -`bc0af6bd305ffc11ab70a416de08811e849a2ddefdb54525472e425ec9fdf66a`. +The 11,976,860-byte historical tape expanded to 57,004,893 bytes with 3,484,036 +targets (`bc0af6bd305ffc11ab70a416de08811e849a2ddefdb54525472e425ec9fdf66a`). -To compare every instruction against a separate straight assembly, make a -temporary copy of the Alpha backend that publishes the ordinary instruction -list at address zero. Its oversized output serves as a measurement file. -Use the same Gamma customer for both assemblies. +To diff every instruction against a straight assembly at address zero, create a +temporary Alpha backend copy that outputs the uncompressed list for the same +Gamma file: ```sh audit_dir=$(mktemp -d) @@ -271,19 +246,17 @@ python3 tests/bootstrap/compiled_vm/packed_tape.py --inspector "$inspector" \ ### Earlier single-tape size limits -The 27,177,694-byte Gamma constructor (SHA-256 -`b2160c526041d7d695bbe133f0ef4cb9d3b2f403a5cf901e0b9cd625e5f9454f`) -exceeds the audited seed’s **16,777,212-byte tape limit** with the Alpha -backend at `43e334bc2b0`. Its 245,493 `pair` expressions alone need -**35,350,992 bytes**. Each expression emits 117 bytes to check the heap, -store both tagged operands and return a tagged pair, plus three nine-byte -stack-helper calls. The Linux-hosted Alpha compiler produced 750 bytes for -`(def main () Int 0)` and 923 for `(def main () Int (pair 0 0))`. The -173-byte difference includes one extra 29-byte literal. [Alpha backend](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) +At `43e334bc2b0`, the 27,177,694-byte Gamma constructor +(`b2160c526041d7d695bbe133f0ef4cb9d3b2f403a5cf901e0b9cd625e5f9454f`) exceeded the +seed's **16,777,212-byte tape limit**. Its 245,493 `pair` expressions alone took +**35,350,992 bytes** (117 bytes for heap check, store, and tagging plus three +9-byte stack-helper calls). The Linux-hosted Alpha compiler emitted 750 bytes +for `(def main () Int 0)` and 923 bytes for `(def main () Int (pair 0 0))` (the +173-byte difference includes one 29-byte literal). +[Alpha backend](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) -To reproduce the lower bound on that exact Gamma file, count the expression -heads after removing comments. This artifact contains no quoted character -literals after comment removal. +To reproduce that lower bound (the file has no character literals after stripping +comments): ```sh python3 - "$OMEGA_GAMMA" <<'PYCODE' @@ -295,26 +268,24 @@ print(pairs, pairs * 144) PYCODE ``` -Counting all emitted instruction widths across 7,768 definitions gives a -**calculated layout of 125,445,123 bytes**. The same accounting matched -published customer, Delta and Epsilon tapes of 16,422, 638,297 and -3,798,810 bytes. The production backend checks the limit before publication. -On the audited Linux seed, a padded tape of exactly 16,777,212 bytes exited -42. Changing only its length word to 16,777,213 triggered `SIGILL` before -its first instruction, with empty output. [Seed loader](../../../bootstrap/alpha/alpha_x64_linux.s) +Summing instruction widths across all 7,768 definitions gave a **calculated +layout of 125,445,123 bytes** (matching emitted test, Delta, and Epsilon tapes +of 16,422, 638,297, and 3,798,810 bytes). The backend checks the limit before +writing: on the Linux seed, a 16,777,212-byte tape exited 42, while setting its +length word to 16,777,213 triggered `SIGILL` before the first instruction with +empty output. [Seed loader](../../../bootstrap/alpha/alpha_x64_linux.s) -The Linux-native compiler built from that same Gamma source accepted an -828-byte linked Omega request. Its 1,607-byte Alpha product -(`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`) -ran on the audited seed and exited 42 with empty output. +Built natively on Linux, that same Gamma constructor accepted an 828-byte linked +Omega request and emitted a 1,607-byte Alpha tape +(`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`) that exited +42 on the seed with empty output. ### Sharing Alpha pair allocation -At #4577 the Alpha backend emitted the 117-byte allocation body once, -followed by a one-byte return. Each `pair` site called the body for nine -bytes. It popped the right operand, popped the left operand and pushed the -result at the call site, so the allocation and stack helpers each used one -return address. A tape with `N` pair expressions changed by `118 - 108 × N` bytes. +At #4577, the Alpha backend emitted the 117-byte pair allocator once with a +one-byte return and called it from each `pair` site (9 bytes). It popped both +operands and pushed the result at the call site, keeping one return address per +helper. Tapes with `N` pair sites changed by `118 - 108 × N` bytes. | Gamma program | Pair sites | Old tape bytes | New tape bytes | | --- | ---: | ---: | ---: | @@ -322,29 +293,25 @@ return address. A tape with `N` pair expressions changed by `118 - 108 × N` byt | Epsilon evaluator | 2,492 | 3,798,810 | 3,529,792 | | Public Omega lexer (original Gamma input above) | 27,626 | 15,449,892 | 12,466,402 | -The smaller public lexer tape (SHA-256 -`37a9e1d5cfa497496f6fbfb70437ef93abd1ffd43d4063b74f14a42c87fab92f`) -ran all 23 cases on the audited seed and reproduced the same 465 bytes. - -For the frozen whole constructor above, the calculated layout falls from -125,445,123 to **98,931,997 bytes**. A lower bound needs just two expression -counts from the same source. Its 245,493 `pair` sites cost 36 bytes each -and its 221,110 `second` sites cost 63 bytes each. Together they require -22,767,678 bytes before their operands, already above the seed limit. - -Three cold Gamma compiler generations produced the same 208,153-byte -Alpha tape (SHA-256 -`4bf3d6225a5bb8639ae773ed53ac022762915ddccdcd94a9ecb25dd15ef4673d`). -The Linux-hosted emitter reproduced those bytes. The resulting compiler -passed 34 Gamma observations and rejected 16 invalid programs. Pair -allocation at the last admitted call frame succeeded. One additional -frame returned 250 and discarded the buffered output. The Epsilon -evaluator matched seven wire observations, including stdin and guest traps. +The 12,466,402-byte lexer tape +(`37a9e1d5cfa497496f6fbfb70437ef93abd1ffd43d4063b74f14a42c87fab92f`) reproduced +the same 465 bytes across all 23 cases on the seed. + +On the frozen constructor, calculated layout dropped from 125,445,123 to +**98,931,997 bytes**—still above the seed limit because its 245,493 `pair` sites +(36 bytes each) and 221,110 `second` sites (63 bytes each) alone needed +22,767,678 bytes before operands. + +Three cold Gamma compiler generations produced identical 208,153-byte tapes +(`4bf3d6225a5bb8639ae773ed53ac022762915ddccdcd94a9ecb25dd15ef4673d`), matched by +Linux, passing 34 Gamma tests and 16 rejections. Pair allocation succeeded at +the last allowed call frame and returned 250 with empty output one frame deeper; +the Epsilon evaluator matched seven wire tests (including stdin and guest traps). ### Pair projections and frame slots on Alpha -On the linked public Omega lexer from #4558, sharing all three pair -operations and the frame-slot loads and stores reduced the tape again. +On the #4558 public Omega lexer, sharing all three pair operations (`pair`, +`first`, `second`) plus tagged frame-slot loads and stores shrank the tape again: | Alpha backend on the same 1,575,418-byte Gamma source | Published tape bytes | | --- | ---: | @@ -352,175 +319,141 @@ operations and the frame-slot loads and stores reduced the tape again. | Single call for `pair`, `first` and `second` | 4,650,419 | | Also share tagged frame-slot loads and stores | **3,718,385** | -Each tape ran all 23 lexer cases and returned the same 465 bytes on the -audited seed. The final tape's SHA-256 is -`536bf79af57a78bb2cf5872a987e5d08a50a0f1694ac3085d74136681b811ea6`. -The pair helpers pop their operands, allocate or check the pair, then jump -to the existing stack push. Its return goes straight to the caller. -The frame-slot helpers take a full byte offset in register 10. They read -or write both the value and its tag. Emitting the shared routines grows -the scalar-only `(def main () Int 0)` tape from 868 to 1,129 bytes. [Alpha assembler](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) - -For the frozen 27,177,694-byte constructor above, the calculated layout -falls from 98,931,997 to 74,702,984 bytes with the pair changes, then to -**60,276,870 bytes** with the frame-slot changes. Sharing more helpers can -reduce that further. Even if every literal, pair operation and local slot -read or binding used just one nine-byte Alpha call, those 1,904,960 sites -alone would occupy 17,144,640 bytes. Fitting the 16,777,212-byte seed -would require some of those source operations to take fewer bytes or to -share a single call across multiple operations. - -Starting from Alpha and Beta with an empty PATH produced three identical -178,112-byte Gamma compiler tapes (SHA-256 -`4f56a6e5b1004595c91dc89120c3d5f266d679168e0ed169ee42b4f46252e1a2`). -A Linux-hosted compiler reproduced the same bytes. The new compiler ran -both projections at the last admitted Gamma frame and preserved tagged -local reads after a tail call with 258 arguments. - -The Alpha-hosted Epsilon evaluator also ran the 58,917-byte Epsilon-written -Omega lexer from the #4558 measurement directly. Rebuilding each evaluator -tape and interpreting the 148-byte batch were timed separately. Both used -the same 726,582-byte evaluator Gamma source and the same fixed seed. +Every tape reproduced the 465-byte lexer result on the seed (final tape SHA-256 +`536bf79af57a78bb2cf5872a987e5d08a50a0f1694ac3085d74136681b811ea6`). Pair helpers +pop operands, allocate or check the pair, and tail-jump to stack push so it +returns directly to the caller. Frame-slot helpers take a byte offset in +register 10 and load/store both value and tag. Emitting the shared routines grew +`(def main () Int 0)` from 868 to 1,129 bytes. +[Alpha assembler](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) + +On the frozen 27,177,694-byte constructor, calculated layout fell from +98,931,997 to 74,702,984 bytes (pair ops) and then to **60,276,870 bytes** +(frame slots). Even if every literal, pair op, and local read/binding took a +single nine-byte call, those 1,904,960 sites alone would need 17,144,640 bytes— +above the 16,777,212-byte seed limit without smaller encodings or multi-op +calls. + +Cold builds with empty `PATH` produced three identical 178,112-byte Gamma +compiler tapes (`4f56a6e5b1004595c91dc89120c3d5f266d679168e0ed169ee42b4f46252e1a2`), +matching Linux, passing both projections at max call depth and preserving tagged +local reads after a 258-argument tail call. + +The Alpha-hosted Epsilon evaluator also interpreted the 58,917-byte #4558 lexer +directly from the same 726,582-byte evaluator Gamma source: | Alpha backend | Evaluator tape bytes | Emit CPU seconds | Emit peak KiB | Run lexer CPU seconds | Run lexer peak KiB | | --- | ---: | ---: | ---: | ---: | ---: | | Shared allocation (#4577) | 3,529,792 | 10.63 | 236,540 | 31.91 | 52,796 | | Shared pair operations and frame slots | 2,267,080 | 8.70 | 192,528 | 17.41 | 52,028 | -The same evaluator also interpreted the live 58,127-byte lexer from -`0a0b233a152` in 21.05 CPU seconds (52,220 KiB peak RSS). All 23 cases -matched, including distinct refusal coordinates for malformed escapes. -The 465-byte result had SHA-256 -`7d7a561d217ec1ce599a203fb8290b907c2582883c98dc71541c5bd0633f31aa`. +It also ran the live 58,127-byte lexer from `0a0b233a152` in 21.05 CPU seconds +(52,220 KiB peak RSS), matching all 23 cases and error offsets with 465-byte +SHA-256 `7d7a561d217ec1ce599a203fb8290b907c2582883c98dc71541c5bd0633f31aa`. [Lexer source and cases](../../../tests/bootstrap/independent/epsilon/lexer_scan_test.py) ### Compile the product wire decoder through Epsilon on Alpha -The Alpha-hosted Epsilon evaluator interpreted the complete 873,205-byte -Omega construction program and compiled a two-package Omega application. -Its 323-byte `wire/codec.omg` decoded zero, mixed bytes and all bits set. -The caller's 1,607-byte Alpha tape ran on the audited seed and exited 42 -with empty output. Removing the dependency edge preserved both source units -and returned Exit 1 at byte 11, the caller’s import. [Product codec](../../../source/foundation/wire/codec.omg) · [Caller](../../../tests/bootstrap/conformance/omega/wire_word.omg) - -The constructor and Epsilon source list came from `d3a79047ce09` (#4542). -The retained constructor SHA-256 was -`8bdbb90999c6b62a04754a3d452966b4903af74179fbc113fdc910a628d27401`. -Repacking that revision reproduced both EEREQs byte for byte, including -the evaluator closure digest -`7b214d058c086ffcf5e5481e5dd08e4e6f47275ae07a4cb2cb6b4d26764b1bae`. -At `d00a570048e` (#4589), emitting the 2,267,080-byte evaluator tape -from its Gamma source took 8.70 CPU seconds and 192,528 KiB peak RSS. -The following measurements start at evaluator invocation. +The Alpha-hosted Epsilon evaluator ran the 873,205-byte Omega compiler program +to compile a two-package Omega app whose 323-byte `wire/codec.omg` decoded zero, +mixed bytes, and all-ones. The caller's 1,607-byte Alpha tape exited 42 with +empty output on the seed; removing the dependency edge returned Exit 1 at byte +11 (the caller's import). +[Product codec](../../../source/foundation/wire/codec.omg) · [Caller](../../../tests/bootstrap/conformance/omega/wire_word.omg) + +The constructor and source list came from `d3a79047ce09` (#4542; constructor +SHA-256 `8bdbb90999c6b62a04754a3d452966b4903af74179fbc113fdc910a628d27401`), +reproducing both EEREQs and evaluator digest +`7b214d058c086ffcf5e5481e5dd08e4e6f47275ae07a4cb2cb6b4d26764b1bae`. At +`d00a570048e` (#4589), emitting the 2,267,080-byte evaluator tape took 8.70 CPU +seconds (192,528 KiB peak RSS). Timings below start at evaluator launch: | Omega input | EEREQ bytes | EEREQ SHA-256 | CPU seconds | Peak KiB | | --- | ---: | --- | ---: | ---: | | Linked, 828 bytes | 874,085 | `83cdc63dfcecb7470adf783c2d4ddf6113ef0e17264d1b3f283626177de16fd8` | 866.64 | 1,576,788 | | Missing edge, 808 bytes | 874,065 | `c6bf88ab9e069e7275e5da6f21b075805ccf9183dfeb9a7c9f4b75ad13e6507a` | 705.31 | 1,195,000 | -The linked tape had SHA-256 -`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`. -The missing-edge observation was `00010000000b000000`. A separate replay -through the frozen Linux-native constructor, SHA-256 -`ccc6eb867203f3250e9025e8f616d07e8b2253582b34499201ffe9e4ce4cb21b`, -produced the same two observations byte for byte. [Wire test and earlier Linux results](../../../tests/bootstrap/independent/WHOLE_REQUEST.md#product-wire-package-through-the-construction-entry) +The linked tape matched +`f5ac1bf6ddc9158a4164a644c9342f73cc6c6698c93773e32dfe035176e3a371`, and the +missing-edge output was `00010000000b000000`—both identical to the frozen +Linux-native constructor (`ccc6eb867203f3250e9025e8f616d07e8b2253582b34499201ffe9e4ce4cb21b`). +[Wire test and earlier Linux results](../../../tests/bootstrap/independent/WHOLE_REQUEST.md#product-wire-package-through-the-construction-entry) ### Compare a production request operation across evaluator hosts The [Request.clear test](../../../tests/bootstrap/independent/request_clear.py) -takes the production `Request` declaration and `clear` machine byte for byte -from [the request package](../../../source/subsystems/compiler/request/request.omg). -Its caller sets both metadata words and the last byte of the 64 KiB request -buffer. After calling `clear`, it checks both words are zero and uses the -preserved byte as the exit code. +copies the production `Request` type and `clear` machine verbatim from +[the request package](../../../source/subsystems/compiler/request/request.omg). +Its caller sets both metadata words and the last byte of the 64 KiB buffer, +calls `clear`, verifies both words are zero, and returns that last byte as exit +code. -Build the Linux and Alpha Epsilon evaluators from the same Delta request, -then pass both executables to the test. [Linux construction](../../../tests/bootstrap/linux_x86_64/README.md#run-the-compiled-alpha-tape-route) +Build the Linux and Alpha Epsilon evaluators from the same Delta request and +compare them: +[Linux construction](../../../tests/bootstrap/linux_x86_64/README.md#run-the-compiled-alpha-tape-route) ```sh python3 tests/bootstrap/independent/request_clear.py /tmp/omega-epsilon/successor \ --compare-with /tmp/omega-epsilon-alpha/successor --timeout 1200 ``` -The test sends the same sealed request to both evaluators, prints executable -and observation identities, compares every output byte, then runs the common -Alpha tape and requires exit 42 with empty output. The timeout applies to -each evaluator separately. +The script sends one sealed request to both evaluators, compares every output +byte, and runs the resulting Alpha tape expecting exit 42 with empty output +(timeout applies per evaluator). -At `e488ba404bf` on Linux x86-64, the checked-in Linux construction driver -built the Alpha-hosted evaluator from the seed and admitted Beta tape in -192.870 seconds. All three Gamma compiler tapes matched. The constructed -Delta compiler emitted the same 726,601-byte evaluator Gamma source as the -native route. Its SHA-256 was -`1d3a700d970acda04ee4699c19bf03a3654eb481a46755399d0daf759fe030af`. -The Alpha backend compiled it into a 7,844,855-byte evaluator tape. +At `e488ba404bf` on Linux x86-64, the launcher built the Alpha-hosted evaluator +in 192.870 seconds. All three Gamma compiler tapes matched, Delta emitted the +same 726,601-byte Gamma source (`1d3a700d970acda04ee4699c19bf03a3654eb481a46755399d0daf759fe030af`) +as the native route, and Alpha compiled it to a 7,844,855-byte tape. | Epsilon evaluator | Executable SHA-256 | Elapsed for the same request | | --- | --- | ---: | | Freshly seed-built Alpha host | `fefb42b13bf9ba1a3eb87e7d810f9441d2f73ed0119544438eb910db33c7bace` | 664.705 s | | Reused native Linux host | `80226b25de03c6608638a1c6a35f4d0fcbc23a3dd1445aa474fb9a34194907f8` | 118.177 s | -Both evaluators received the same 842,218-byte request, SHA-256 -`3f534a4a2c566fae357899a4fbb15994314bac581e278a5d1b5b717779a946a8`. -Each published the same 1,355-byte observation, SHA-256 -`e267db6d2e9b3a39e3cb1207452ce08d74345037892aa723ba162c160c021b45`. -The 1,350-byte program in that observation ran on Alpha with exit 42 and empty -output. The elapsed times cover one invocation per evaluator on a shared -machine. The customer exercises `clear` and its caller. Request staging and -decoding have separate tests. - -The bootstrap compiler with checked word arithmetic occupies 845,978 bytes. -Repeating this comparison with that compiler changed the request to 848,897 -bytes (SHA-256 `8f344dc65c26b3bbc388acb53ed32085ec942160f8fc3809f0ec03f16bcfc928`). -Both evaluators again published exactly the 1,355-byte observation above. -The resulting 1,350-byte program exited 42 on Alpha. +On the same 842,218-byte request (`3f534a4a2c566fae357899a4fbb15994314bac581e278a5d1b5b717779a946a8`), +both evaluators emitted the identical 1,355-byte output +(`e267db6d2e9b3a39e3cb1207452ce08d74345037892aa723ba162c160c021b45`), whose +1,350-byte Alpha program exited 42 with empty output. With the 845,978-byte +checked-word-arithmetic compiler (848,897-byte request +`8f344dc65c26b3bbc388acb53ed32085ec942160f8fc3809f0ec03f16bcfc928`), both again +emitted that exact 1,355-byte output. Timings are single shared-host runs, and +staging/decoding are tested separately. The [whole construction input](../../../tests/bootstrap/independent/WHOLE_REQUEST.md) -exercises all product sources and the evaluator’s sealed-input provision. +tests all product sources and sealed input. ### Stage and read a byte with the native Omega constructor -For the complete request storage unit, pass a compiled construction executable. -The test frames `main.omg` and the unchanged `request.omg` as two source files -in one package. +Pass a compiled constructor binary to test the full request storage unit +(`main.omg` plus unchanged `request.omg` in one package): ```sh python3 tests/bootstrap/independent/request_clear.py --staging-constructor /path/to/constructor --timeout 1800 ``` -The caller stages 42 and reads byte zero. Changing only the read offset to one -produces an Alpha Trap (Linux SIGILL). Changing only the staged byte to `true` -produces a compile-time rejection at that token. On the 2,082-byte product -unit, the two executable cases each produced 2,071 bytes of Alpha tape and the -rejection pointed at arena byte 143. The test recomputes the token coordinate -from the current caller and construction frame. A fourth caller starts at full -capacity. Staging one more byte must advance `observed` to 65,537, keep -`length` at 65,536 and preserve the last stored byte. - -The Linux x86-64 constructor built from Omega compiler revision -`807099e8790` compiled the complete 2,082-byte request unit (SHA-256 -`bdc293370165c8cc6b92de1e17e77d261956f2a70bc6683e276dc47f15dde4c1`). -The 883,526-byte Epsilon source includes the public construction entry. Its -SHA-256 was `6fcc6d17e45ab53205f964f16cbfb0d21591812339fa411ff773c46b6ed13031`. -The Epsilon compiler and storage runtime from the head of PR #4584 -(`d7b67e70954`), the Delta construction profile and the Gamma Linux backend -produced the 55,348,424-byte constructor (SHA-256 `381c4b2bc372ac0f0e23ad001a3e89f541cb6f80cc434934ab1f8912105ac175`). +The caller stages 42 and reads byte 0. Reading byte 1 triggers an Alpha Trap +(Linux SIGILL); staging `true` fails at compile time at that token (arena byte +143 on the 2,082-byte unit; both runnable cases emitted 2,071-byte tapes). A +fourth caller starts at capacity (65,536) and checks that staging one more byte +advances `observed` to 65,537 while keeping `length` at 65,536 and preserving +the last stored byte. + +The Linux x86-64 constructor from `807099e8790` (883,526-byte Epsilon source +`6fcc6d17e45ab53205f964f16cbfb0d21591812339fa411ff773c46b6ed13031`, compiled with +PR #4584 `d7b67e70954` into a 55,348,424-byte ELF +`381c4b2bc372ac0f0e23ad001a3e89f541cb6f80cc434934ab1f8912105ac175`) compiled the +2,082-byte request unit (`bdc293370165c8cc6b92de1e17e77d261956f2a70bc6683e276dc47f15dde4c1`). [Build a native constructor](../../../tests/bootstrap/independent/WHOLE_REQUEST.md#build-from-the-seed) -For the `stage-first` caller, the constructor read a 2,382-byte packet -(SHA-256 `b355eff899789463165edc9a2188016808eb1aa3d27b41d19793a140ec1a2cfb`). -It published 2,076 bytes (SHA-256 -`42ce29ec6fd6873db56be0da0599f1b7d26e563e529f58d4e8ba34cce5e2a2ec`). -The 2,071-byte tape following the five-byte success header had SHA-256 -`955589ac5af9b1a49df301d6f0953e6cb03b20e6208476a0de2815b82e214c27`. -The checked-in Alpha seed ran it and exited 42 with empty output. - -Changing the staged argument from `42` to `true` gave the constructor a -2,384-byte packet (SHA-256 -`a03975bc9eed13c327c855ec3622816d1b198de029fb0b97c66142215ce40717`). -It returned exactly `00010000008f000000`, a rejection at byte 143, the first -byte of `true`. The independent Epsilon model ran the same compiler source -and matched both complete observations byte for byte. +For `stage-first` (2,382-byte packet +`b355eff899789463165edc9a2188016808eb1aa3d27b41d19793a140ec1a2cfb`), it emitted +2,076 bytes (`42ce29ec6fd6873db56be0da0599f1b7d26e563e529f58d4e8ba34cce5e2a2ec`; +2,071-byte tape `955589ac5af9b1a49df301d6f0953e6cb03b20e6208476a0de2815b82e214c27`) +that exited 42 with empty output on the Alpha seed. Changing `42` to `true` +(2,384-byte packet `a03975bc9eed13c327c855ec3622816d1b198de029fb0b97c66142215ce40717`) +returned `00010000008f000000` (rejection at byte 143, the start of `true`). The +independent Epsilon model matched both outputs byte for byte. | Native constructor input | CPU seconds | Peak RSS (KiB) | | --- | ---: | ---: | @@ -529,7 +462,9 @@ and matched both complete observations byte for byte. ## Host checks -On an executable Alpha seed host, Python and shell drive the differential tests. The [Python Gamma compiler](../../../tests/bootstrap/compiled_vm/gamma.py) supplies an independent implementation for comparison and for the explicit `--accelerated` test mode. +On a host that runs the Alpha seed, Python and shell drive the differential +tests. The [Python Gamma compiler](../../../tests/bootstrap/compiled_vm/gamma.py) +provides an independent comparator and the `--accelerated` dev mode. ```sh # Seed construction, compiler fixed point, Delta/Epsilon, and an Omega program. @@ -554,52 +489,41 @@ python3 tests/bootstrap/compiled_vm/test.py --omega --omega-timeout 1800 python3 tests/bootstrap/compiled_vm/test.py --omega-controls --omega-timeout 1800 ``` -Source construction artifacts and the exact source/request bytes go to ignored -`build/source-gamma-reference/`; the accelerated source run uses -`build/source-gamma-accelerated/`. Host-compiler tests use `build/compiled-vm/`. -`source_test.py --seconds N` sets a positive watchdog for compiler construction, -self-rebuilds, source compilation and Omega execution. These invocations wait -for completion by default. -A refused source compilation publishes no bytes. Malformed source deliberately -traps with status 249; negative controls require that status and empty output. -Other runtime statuses fail the gate. - -Tests use the existing closure packer, identity checks, and platform seed -stamper. The host frames byte requests and compares observations; -Gamma, Delta, Epsilon, and Omega execution happens in the generated tapes or the -explicitly identified reference evaluator. The short Beta reconstruction shell -commands wait for completion. A timeout makes no language judgment. The Omega allowance is -adjustable because checking the complete compiler is a materially larger -workload. - -The constructed Gamma compiler writes raw Alpha code. Stamp the tape using -[`seed_env.sh`](../../../tools/bootstrap/alpha/seed_env.sh). The executable accepts -only the source program's sealed input, without the reference Gamma evaluator's -four-byte source-length envelope. Invalid source leaves an existing output -artifact untouched. Successful compilation replaces it atomically. +Outputs go to ignored `build/source-gamma-reference/`, +`build/source-gamma-accelerated/`, and `build/compiled-vm/`. `source_test.py --seconds N` +sets a watchdog timeout (default waits to completion). Rejected source must exit +249 with empty output; any other failure fails the test. + +Tests reuse the standard closure packer, hash checks, and seed stamper. Host +scripts only frame inputs and compare outputs—all Gamma, Delta, Epsilon, and +Omega code runs in generated tapes or the reference evaluator. Timeouts never +count as language results. + +The Gamma compiler writes raw Alpha code; stamp it with +[`seed_env.sh`](../../../tools/bootstrap/alpha/seed_env.sh). Stamped programs +read only sealed stdin (without the Gamma evaluator's four-byte length prefix). +Failed builds leave existing outputs untouched; valid builds replace them +atomically. ## Meaning and storage -[`../../../bootstrap/2_gamma/LANGUAGE.md`](../../../bootstrap/gamma/LANGUAGE.md) governs the source language. -The compiler validates every function and both branches before publishing code. -It supports wrapping words, checked scalar boundaries, immutable pairs, -sequential grouped bindings, mutually visible functions, proper tail calls, -sealed byte input, and atomic buffered publication. Primitive names can be -ordinary bindings; list heads retain their primitive meanings. Numeric and -character tokens are literals, not supported declaration names. The reserved -application declaration must have its documented nullary form and cannot be -called as a user function. Unsupported or malformed source fails compilation. - -Every value occupies a word plus an unforgeable scalar/pair tag. Pairs occupy -four words. A function frame holds its arguments, saved caller frame pointer, -and statically assigned lexical slots; expression temporaries follow the frame. -Non-tail calls use Alpha's return stack. A tail call evaluates all arguments, -moves them over the old frame, restores the caller frame pointer, and jumps to -the callee. Its return address and call depth remain unchanged, including calls -between functions of different arities. Pair allocation is monotonic; there is -no garbage collector. - -The generated runtime owns disjoint regions of Alpha's 128 GiB address space: +[`../../../bootstrap/2_gamma/LANGUAGE.md`](../../../bootstrap/gamma/LANGUAGE.md) +defines Gamma. The compiler validates every function and branch before emitting +code. It supports wrapping words, checked scalars, immutable pairs, sequential +grouped bindings, mutually recursive functions, proper tail calls, sealed byte +input, and atomic buffered output. Primitive names work as ordinary bindings +while list heads keep primitive meanings; numeric and character tokens are +literals, not names. The reserved application declaration must take zero args +and cannot be called as a user function. Invalid source fails compilation. + +Each value is a word plus an unforgeable scalar/pair tag; pairs take four words. +Frames store arguments, saved caller frame pointer, and lexical slots, followed +by expression temporaries. Non-tail calls use Alpha's return stack; tail calls +evaluate arguments, overwrite the old frame, restore the caller frame pointer, +and jump directly without growing call depth (even across arities). Pair +allocation is bump-only with no GC. + +The generated runtime splits Alpha's 128 GiB address space into disjoint regions: | Region | Half-open address range | Boundary behavior | | --- | --- | --- | @@ -611,485 +535,290 @@ The generated runtime owns disjoint regions of Alpha's 128 GiB address space: | Expanded code (packed tape only) | `0x28000000 .. 0x30000000` | The decoder checks each copy and verifies the final length | | Immutable pairs | `0x30000000 .. 0x2000000000` | Check every 32-byte allocation | -Ordinary authored traps exit 2; storage limits exit 3. Application traps and -frame/heap/input/output limits use 249/250/252/253/254. Pair handles cannot be -forged by arithmetic or read from input; scalar operators reject tagged words. -The limits are this implementation's physical profile, not a claim to reproduce -the reference evaluator's resource envelope. Physical host memory remains an -execution dependency, just as it is for the reference seed. +Program traps exit 2; storage limits exit 3. Application traps and +frame/heap/input/output overflows exit 249/250/252/253/254. Pair handles cannot +be forged via arithmetic or input, and scalar ops reject tagged pairs. These +bounds are this backend's profile, not the reference evaluator's; physical RAM +remains a host dependency. ## Evidence and remaining work -On Linux x86-64 at repository base `c930a0075d7`, the focused `--epsilon` run -passed 30 byte-exact native differential observations and 15 rejected-source -controls. These include 100,001 tail swaps, mixed-arity and pair-valued tail -calls, caller-frame preservation, scalar/tag traps, overflow division, lexical -refusals, and atomic application publication. Nine additional native controls -exercise exact and adjacent storage boundaries under a reduced compiled test -profile. CLI refusal also preserves an existing output artifact. - -The 147,840-byte Delta compiler closure produced a 1,184,046-byte Alpha tape. -It compiled a real Delta Bytes duplication program into a 3,082-byte Gamma -receipt identical to the reference evaluator's result. The receipt compiled to -Alpha and duplicated empty, ASCII, and all-byte inputs correctly. - -The same compiled Delta compiler reconstructed the complete canonical Epsilon -evaluator receipt: 729,060 bytes, SHA-256 -`bec9011e5216557a59ba701ac2a4112774e5f48240c729b95ffc8297f704c368`. -That is the existing bound receipt identity, not a newly substituted artifact. -Compiling it produced 7,876,070 Alpha bytes. Its Console exit, stdin, trap with -stdout prefix, rejected-source, and malformed-envelope observations passed. -Reconstruction took 11–17 seconds in contended functional runs; these are not -comparative performance benchmarks. - -A separate cross-variant run used the exact 622,933-byte request from a fresh -reference reconstruction (SHA-256 -`6386d0d5729a320e73b9865809751ae2962865f4ebc1b3472f2e828de9ab7f76`). -Compiled Delta produced the same 721,484-byte Epsilon execution-adapter receipt, -SHA-256 `71a016f53f63501760e3a10632d86c9561aa0e8387b794b074d98ce98a823082`. -This is actual byte correspondence, not a comparison between the two different -Epsilon entry receipts. Its contended 8.708-second execution and the reference's -354.968 seconds are not a controlled speedup measurement. - -The complete 591,392-byte bootstrap compiler plus existing OCREQ entry then ran -under compiled Epsilon. The existing 180-byte Omega fixture compiled to 50 Alpha -bytes; executing that tape exited 42 with empty stdout and stderr. The first -60-second observation allowance was insufficient; a 300-second run completed in -95.329 seconds. This demonstrates an accelerated construction through a real -Omega executable. No Omega compiler self-rebuild has been demonstrated here. - -The then-current `tests/bootstrap/conformance/omega/controls_b.epsilon` customer also -passed through compiled Epsilon with the complete bootstrap compiler (575,227 -source bytes). It then accepted six changed modulo, shift, and bitwise programs, -rejects the out-of-range literal 256 while asserting an unfinalized empty tape, -then successfully recompiles 42 on the same compiler instance. The published -observation matched the existing expected `C` plus 22-byte Alpha tape exactly; -that tape also executed with exit 42 and no output. This eight-invocation run -completed in 159.692 seconds under a 300-second allowance. Later review found -that those anonymous operator acceptances were wrong Omega semantics; this -historical passing observation is not correctness evidence for them. The current -compiler refuses those forms, and its corrected customer passed in 139.663 -seconds through source-built Epsilon with the same exact reset artifact and -exit 42. That observation used bootstrap compiler SHA-256 -`f765c26d704c41552739e32fc592232edcf814f5d57ee3990e92660aacb6152f`. The default smaller-customer Omega watchdog -is now 1,800 seconds; `--omega-timeout` retains an explicit experimental override. +At base `c930a0075d7` on Linux x86-64, `--epsilon` passed 30 differential tests +and 15 source rejections (100,001 tail swaps, mixed-arity and pair tail calls, +caller-frame preservation, tag traps, division overflow, lexical errors, and +atomic output), plus nine storage-boundary tests under a reduced profile and a +CLI refusal check preserving existing output. + +The 147,840-byte Delta compiler produced a 1,184,046-byte Alpha tape that +compiled a Delta Bytes duplicator to a 3,082-byte Gamma file matching the +reference evaluator; compiling that file to Alpha duplicated empty, ASCII, and +all-byte inputs. + +Compiled Delta rebuilt the pinned 729,060-byte canonical Epsilon evaluator +(`bec9011e5216557a59ba701ac2a4112774e5f48240c729b95ffc8297f704c368`) in 11–17s +(contended, not benchmarked), which compiled to 7,876,070 Alpha bytes and passed +Console exit, stdin, trap-with-stdout, refusal, and malformed-envelope tests. + +On the 622,933-byte request (`6386d0d5729a320e73b9865809751ae2962865f4ebc1b3472f2e828de9ab7f76`), +compiled Delta produced the identical 721,484-byte Epsilon execution-adapter +output (`71a016f53f63501760e3a10632d86c9561aa0e8387b794b074d98ce98a823082`) in +8.708s vs 354.968s on the reference (uncontrolled runs). + +Running the 591,392-byte bootstrap compiler plus OCREQ entry under compiled +Epsilon compiled the 180-byte Omega fixture to 50 Alpha bytes (exit 42, empty +output) in 95.329s under a 300s limit. No Omega self-rebuild is shown here. + +The earlier `tests/bootstrap/conformance/omega/controls_b.epsilon` suite ran on +compiled Epsilon (575,227-byte compiler) in 159.692s, testing six bitwise/shift +cases, rejecting literal 256 with empty tape, and recompiling 42 (`C` + 22-byte +tape -> exit 42). Later review found those anonymous bitwise/shift forms invalid +in Omega; the current compiler (`f765c26d704c41552739e32fc592232edcf814f5d57ee3990e92660aacb6152f`) +rejects them, and its updated suite passed in 139.663s with the same reset tape. +Default Omega timeout is now 1,800s (`--omega-timeout` overrides it). ## Source compiler implementation and evidence -The frontend retains immutable syntax nodes and source spans for names. It -uses an explicit list stack with the same 255-list authored nesting boundary -as the reference implementation. Decimal words accumulate modulo 2^64; -comments end at either CR or LF; character literals preserve the language's -restricted escapes. All source bytes, including comments, are validated. - -The backend first censuses declarations and parameter scopes. It counts lexical -slots by traversing expression positions, then compiles through an explicit -action stack. Every function and branch is visited, including unreachable code. -The lowering calls named target operations such as `i_add` and `i_jeq`. Their -encoders prepend little-endian fields. Reading them backwards gives each -label its distance from the code end, which the compiler saves in an AVL map. -After validation and the capacity check, the writer encodes jump targets and -outputs the fields in program order. Function and local name lookup compares -exact source spans in lists. - -The small integer tags in `c_kind` name syntax, not source shapes: -`1=def`, `2=Int`, `3=main`, `4=$application`, `5=if`, `6=let`, -`7..11=+,-,*,/,%`, `12=eq`, `13=lt`, `14=pair`, `15=read`, `16=write`, -`17=first`, `18=second`, `19=input`. All other names remain source spans. -The Alpha assembler writes the existing Alpha opcodes. A label marks a -position between emitted fields. Label identifiers 1..13 belong to runtime -helpers, function identifiers start at 100, and subsequent labels follow them. - -In the original Alpha construction, the two source files totaled 33,329 bytes -(851 lines). One joining newline brought the executed source to 33,330 bytes, SHA-256 -`7b439ef26f2cb8a27bb9c0a2b4d5bfca6e7efeed0a5bdf9d798c04b65370b946`. -On Linux x86-64 its actual reference construction completed in 62.362 seconds. -It produced a 457,252-byte compiler tape, SHA-256 -`71f6650f8201294e6654217f38fcd431fd8daaa233e0330c5da29e9819ad7e71`. -Both subsequent self-rebuilds were byte-identical, as was the independently -Python-produced tape. The source-built compiler passed 32 native differential -controls and 15 source refusals, including a legal binder named `let` that -caught an earlier incorrect traversal of binding records as expressions. - -The downstream execution below used an initial 31,890-byte spelling with decimal -ASCII operands in keyword tests (source SHA-256 -`584d3d94e903998defa96d417f65ff43a98630b55211c66a0ca01fa46287c79b`). -Its reference construction took 62.386 seconds. Rewriting those operands as -readable character literals preserved the parsed program, and the final actual -reference construction reproduced the same compiler tape exactly. Thus the -following customers consumed the same executable as the final source produces. - -The source-built compiler constructed the real Delta compiler tape and the -complete Epsilon evaluator tape. Both were byte-identical to the independently -Python-produced tapes described above. The Delta compiler took 9.705 seconds to -compile from Gamma source; it produced the exact 3,082-byte Bytes customer -receipt. It reconstructed the bound Epsilon receipt in 9.875 seconds, and the -compiled Epsilon exit, stdin, trap, rejection, and malformed-envelope controls -passed. The complete 591,392-byte bootstrap compiler then compiled the existing -180-byte Omega fixture to a 50-byte Alpha program; executing it exited 42. This -last stage took 105.255 seconds. These are contended functional timings, not -comparative benchmarks. - -Completing the bootstrap compiler's needed Omega coverage and obtaining -reproducible Omega compiler self-rebuilds remain delivery work. The Gamma -compiler fixed point does not establish an Omega compiler fixed point. - -The parameter/local/call customer can be requested with -`python3 tests/bootstrap/compiled_vm/source_test.py --omega-values`. It executes the -current manifested bootstrap compiler, verifies source-owned refusals and -executes the actual emitted tapes. The older modulo/shift/bitwise observation -above is historical only: those anonymous forms lacked the required carrier -meaning and are now explicit coverage refusals. It is not evidence that the -older compiler preserved their Omega semantics. - -An earlier values-customer snapshot ran through the source-built Epsilon tape in -1,050.206 seconds. Nine emitted Alpha executables returned the expected values; -30 source-owned refusals checked empty, unfinalized publication and reset. -The complete Epsilon customer was 601,461 bytes, SHA-256 -`0465ac3c9ee18d7f59b62a4cf1ca7d8323a5c0324e9ac7f6fdeaea76cad64c32`. -The separately reconstructed Epsilon tape retains SHA-256 -`5f12d53066179df5e92929ab7a41933a2ed3c0234400d9c7b3cda8718a469c12`. -These are functional observations under concurrent machine load, not controlled -performance comparisons. The bootstrap compiler still cannot construct the -Omega compiler source closure or demonstrate its self-rebuild. - -The changed legacy `controls`, `controls_c`, and `controls_d` bodies completed -with their exact reset tapes in a shared invocation (603,476-byte customer, -SHA-256 `64f98ca7aff4e1f651a3a347ea4cc3f955d74795b50370d2eb0088fa43e75a36`). -Each emitted tape executed with exit 42. That invocation then exposed the -previously unsupported ungrouped terminal call in `controls_i`; it was not a -successful complete batch. The repaired parser reused call-expression retention -instead of changing that witness. The unchanged `controls_i` body, four -structural-overload/duplicate refusals, a bare nested parameterized call and -reset then passed in 420.248 seconds. This 604,432-byte customer had SHA-256 -`601f5013b8ff23c35f934fe5da184ea85e10ed4af187b4439f609b29754adf41`; -its three emitted artifacts executed with exits 42, 47, 43. - -After restoring each body's diagnostic anchor following declaration census, -the final 598,333-byte compiler closure has SHA-256 -`0c402370392af73910cf6caa05b0198dd7ccf0820397e26b85367a1dfcec9f72`. -Its focused early-body refusal checked canonical source coordinate 0 and empty -publication, then reset and emitted an actual executable returning 43. That -600,677-byte customer, SHA-256 -`20ffacd689a6712f78070ccde506f14a4abe5f9edaaa3f4f9189893b05a620ed`, -passed in 76.013 seconds. The older observations above retain their own input -identities; the entire matrix was not rerun after this diagnostic-only repair. - +The frontend keeps immutable AST nodes and source spans, enforcing the 255-level +list-nesting limit with an explicit stack. Decimal words wrap modulo 2^64, +comments end at CR or LF, character literals check escapes, and all bytes +(including comments) are validated. + +The backend collects declarations and parameter scopes, counts lexical slots, +and compiles with an explicit action stack, visiting every function and branch +(including dead code). Lowering emits target ops like `i_add` and `i_jeq`, +prepending little-endian fields; a backward pass records label distances from +code end in an AVL tree, checks capacity, patches jump targets, and emits bytes +in order. Name lookup compares source spans in lists. + +Integer tags in `c_kind` identify keywords and primitives: `1=def`, `2=Int`, +`3=main`, `4=$application`, `5=if`, `6=let`, `7..11=+,-,*,/,%`, `12=eq`, +`13=lt`, `14=pair`, `15=read`, `16=write`, `17=first`, `18=second`, `19=input`; +other names stay spans. Labels 1–13 are runtime helpers, functions start at 100, +and remaining labels follow. + +In the initial Alpha build, the two files totaled 33,329 bytes (851 lines; +33,330 bytes joined, `7b439ef26f2cb8a27bb9c0a2b4d5bfca6e7efeed0a5bdf9d798c04b65370b946`). +Cold construction on Linux took 62.362s and produced a 457,252-byte tape +(`71f6650f8201294e6654217f38fcd431fd8daaa233e0330c5da29e9819ad7e71`), matching +both self-rebuilds and Python, passing 32 differential tests and 15 rejections +(including a valid binder named `let`). + +Downstream runs below used an earlier 31,890-byte version with decimal ASCII +constants (`584d3d94e903998defa96d417f65ff43a98630b55211c66a0ca01fa46287c79b`, +built in 62.386s); replacing them with character literals produced the identical +compiler tape. + +That source-built compiler built the same Delta compiler tape (9.705s; emitted +the 3,082-byte Bytes output) and Epsilon evaluator tape (9.875s; passed Console +checks) as Python, and compiled the 180-byte Omega fixture via the 591,392-byte +bootstrap compiler in 105.255s (50-byte tape -> exit 42; contended timings). + +Full Omega coverage and reproducible Omega self-rebuilds remain open—a Gamma +fixed point is not an Omega fixed point. + +Run `python3 tests/bootstrap/compiled_vm/source_test.py --omega-values` to test +parameter, local, and call lowering and execute emitted tapes. The older +anonymous modulo/shift/bitwise results above are historical only; those forms +are now unsupported coverage refusals. + +An earlier `--omega-values` run took 1,050.206s on Epsilon tape +`5f12d53066179df5e92929ab7a41933a2ed3c0234400d9c7b3cda8718a469c12` (601,461-byte +source `0465ac3c9ee18d7f59b62a4cf1ca7d8323a5c0324e9ac7f6fdeaea76cad64c32`), +passing 9 tapes and 30 rejections with reset. + +Updated `controls`, `controls_c`, and `controls_d` passed with reset tapes +(603,476 bytes, `64f98ca7aff4e1f651a3a347ea4cc3f955d74795b50370d2eb0088fa43e75a36`, +exit 42), then hit an unsupported ungrouped terminal call in `controls_i`. After +fixing the parser to retain call expressions, unchanged `controls_i`, four +overload/duplicate rejections, a nested parameterized call, and reset passed in +420.248s (604,432 bytes, `601f5013b8ff23c35f934fe5da184ea85e10ed4af187b4439f609b29754adf41`; +tapes exited 42, 47, 43). + +Restoring per-body diagnostic offsets after declaration census gave the +598,333-byte compiler (`0c402370392af73910cf6caa05b0198dd7ccf0820397e26b85367a1dfcec9f72`). +A focused early-body rejection checked offset 0 and empty output, then reset and +emitted exit 43 in 76.013s (600,677 bytes, +`20ffacd689a6712f78070ccde506f14a4abe5f9edaaa3f4f9189893b05a620ed`). ## Compiler-source lexer customer -`--omega-control` constructs and executes the real lexer identifier predicates, -with their bodies and signatures unchanged, through the source-built Epsilon -tape above. The wrapper uses explicit `as +Trapping` casts and tests both -predicates across ASCII boundaries and the upper half of `u32`. - -The source-built runtime control runs to completion by default. It accepts an -optional `--seconds` limit. The development route uses `--omega-timeout` -and defaults to 7,200 seconds for this control. A timeout leaves the -Omega result open. Additional -source-owned cases check staged parallel transfers, skipped looping Boolean -operands, nested calls/comparisons, domain casts, refusals and compiler reuse. -This extends the bootstrap compiler toward an actual successor source unit; -it does not construct the complete Omega compiler. - -A canonical explicit-domain smoke completed in 478.167 seconds and emitted a -2,153-byte Alpha program that exited 42 without output. Its Epsilon source was -644,808 bytes, SHA-256 -`449d795abd68930a95fc0f08ee190caa3bfb2519465851e96b693370f8a09b7a`, -including bootstrap compiler -`7f0540c05d1c31033f3164dc1fb0c552d41ae2e57764451387c2618e47de46e3`. -The exact 1,341-byte Omega customer had SHA-256 -`d26ea6de810d23de785af5b4cfc9a7490b865431ddedf181b878343879268117`; -its tape had SHA-256 -`58a5d2ff0e45242e9382c7f940fdfede2089742152d8bb747a61b633e7ccf0b7`. -This observation predates the final public crash-ceiling and visibility checks. - -An earlier grouped run failed at its short-circuit call-expression customer -(Epsilon exit 12 after 1,114.986 seconds). Its two preceding tapes executed, -but the earlier lexer wrapper also omitted required explicit domain casts; -that acceptance is not conformance evidence. The repaired parser preserves -expression context around nested calls instead of weakening the looping-RHS -witness. Historical observations remain bound to their own source bytes. - - -The later boundary/control invocation used a 653,357-byte Epsilon source, -SHA-256 `6863d967b67ff9311dd6f121348cb9e725e287bcfd325ce54c0d4e46b923c621`, -including compiler `6459924a185619f637f16166b10b1f29e274692c3c4f7580fd7bc1e2032d22bf`. -All 25 source-owned refusal checks completed, including public crash-ceiling -propagation in both declaration orders and empty/unfinalized output. Its first -six emitted tapes were separately executed with exits `42, 42, 43, 44, 45, 46` -and empty output. These cover the real lexer boundaries, parallel transfers, -skipped infinite Boolean operands, upper-u32 comparisons, nested calls and -explicit domain casts. The 4,352-byte real lexer customer has SHA-256 -`169002a5c460e9af180c4f3954fc28fd601132b131164483d459fe3cbda38c33`; -its 6,095-byte tape has SHA-256 -`925bed6ed031e0d3ed5ddbb0c4f21fa2771cb7912e002c73755076784a924f59`. - -That invocation is still a **failed complete matrix**: its final public/plain -positive exposed a missing call-primary path for a transition subject and -returned Epsilon exit 90. The whole 9,063-byte observation has SHA-256 -`4253b9bb07f6debeb0f1db968f55ce7fe699667aafc222be23b21708139f4bbe`. -Elapsed time was 2,644.870 seconds, including roughly 208 seconds paused to -avoid exceeding the shared 32 GiB memory budget; it is not a benchmark. -The exact positive was retained while the shared parser path was repaired. - -Separately, the 35-invocation parser customer reached its complete `A` marker -before the legacy batch stopped at an unchanged leading-`!1` refusal witness. -That 677,942-byte Epsilon source has SHA-256 -`7b0c364de404419b64eedc5f5b502635ede0a00af78ba62347756fa084e060cd`; -the failed batch took 623.514 seconds and returned Epsilon exit 2 plus `A`. -The repaired parser routes statement-leading unary prefixes through the shared -expression machinery. Neither failed batch is promoted to evidence for later -source bytes; the following focused observations establish the final repairs. - - -The repaired parser and legacy acceptance batch passed in 2,011.789 seconds: -37 parser invocations and 65 bootstrap compiler invocations completed with -native and Epsilon exit 0 and empty stderr. It used the 644,910-byte compiler -`5609861565dfbc77b8fb5586189f8dee2d490b267627b1bb9d35520ecbd682f7` -and a 686,637-byte complete Epsilon source, -`887c48bba803aeb7f08670a56c2eaf3b193b5b075d15864e57b497ac615fb5fd`. -The original parser, runtime prefix/public checks and baseline/legacy fixture -bodies were bound to Git `6710c426bccfff359e4f283d42d2e739c2547c6e`. -Its 728-byte observation has SHA-256 -`b58537980b677917b92bbac2ca570ffc2c6aef1823086b955543c46d6880c44b`. -All nine emitted programs executed without output: the terminal-prefix and -skipped-loop program exited 43, the public/plain transition-call program exited -47, and all seven baseline/legacy reset tapes exited 42. The public checks also -covered transitive Trap ceilings, refusal coordinates, retired visibility syntax -and reuse after refusal. This was focused validation of the repaired paths, -not a rerun of the earlier complete boundary matrix. - -A final refusal-classification repair distinguishes an unsupported visible -global terminal target from a genuinely missing target. The current 645,486-byte -compiler has SHA-256 -`ec5caf34674af271f408e03bdbe77608b445c306956a0dc1064a41792141f377`. -Its three-invocation focused customer passed in 166.294 seconds: the visible -global target returned Incomplete, the missing target returned Reject, both -retained exact target coordinates and empty/unfinalized tape, then the reused -compiler emitted a 22-byte program that actually exited 49 without output. -The 647,792-byte complete Epsilon source has SHA-256 -`cd0bad694b6a6c4622c2dc8578b1faa2ae930ec0b647ed640038bf1523b7a299`; -the tape has SHA-256 -`5d6986842b024c50356357ef47eb431838ba94157e40091d2b998e7046db3373`. -The retained runtime fixture now includes that refusal as its 26th case. Earlier -full and focused observations retain their own compiler identities; they are -not reported as reruns on these final bytes. +`--omega-control` compiles and runs the real lexer identifier predicates +unchanged on the source-built Epsilon tape, using `as +Trapping` casts across +ASCII boundaries and high `u32` values. + +The source-built test runs to completion by default (`--seconds` sets a limit; +dev mode `--omega-timeout` defaults to 7,200s). Extra tests check parallel +transfers, skipped looping Boolean operands, nested calls/comparisons, domain +casts, rejections, and compiler reuse. + +An explicit-domain smoke run finished in 478.167s, emitting a 2,153-byte tape +(`58a5d2ff0e45242e9382c7f940fdfede2089742152d8bb747a61b633e7ccf0b7`) that exited +42 (644,808-byte Epsilon source +`449d795abd68930a95fc0f08ee190caa3bfb2519465851e96b693370f8a09b7a`, compiler +`7f0540c05d1c31033f3164dc1fb0c552d41ae2e57764451387c2618e47de46e3`, 1,341-byte +Omega input `d26ea6de810d23de785af5b4cfc9a7490b865431ddedf181b878343879268117`), +predating final crash-ceiling and visibility checks. + +An earlier grouped run failed on a short-circuit call expression (Epsilon exit +12 after 1,114.986s) and omitted required domain casts; fixing the parser kept +expression context around nested calls without weakening the test. + +A later run (653,357-byte source +`6863d967b67ff9311dd6f121348cb9e725e287bcfd325ce54c0d4e46b923c621`, compiler +`6459924a185619f637f16166b10b1f29e274692c3c4f7580fd7bc1e2032d22bf`) passed all 25 +rejections (including crash-ceiling propagation) and six tapes exiting +`42, 42, 43, 44, 45, 46` (4,352-byte lexer input +`169002a5c460e9af180c4f3954fc28fd601132b131164483d459fe3cbda38c33`; 6,095-byte +tape `925bed6ed031e0d3ed5ddbb0c4f21fa2771cb7912e002c73755076784a924f59`), but was +still a **failed complete matrix**—its final case hit a missing transition +subject call path (Epsilon exit 90; 9,063-byte output +`4253b9bb07f6debeb0f1db968f55ce7fe699667aafc222be23b21708139f4bbe`; 2,644.870s +including ~208s paused for the 32 GiB host memory cap). + +Separately, a 35-case parser suite reached `A` before stopping on a leading-`!1` +rejection (677,942-byte source +`7b0c364de404419b64eedc5f5b502635ede0a00af78ba62347756fa084e060cd`, 623.514s, +exit 2 + `A`). Routing statement-leading unary prefixes through the shared +expression parser fixed this. + +The fixed parser and legacy batch passed in 2,011.789s: 37 parser and 65 +compiler runs exited 0 with empty stderr (644,910-byte compiler +`5609861565dfbc77b8fb5586189f8dee2d490b267627b1bb9d35520ecbd682f7`, 686,637-byte +source `887c48bba803aeb7f08670a56c2eaf3b193b5b075d15864e57b497ac615fb5fd`, Git +`6710c426bccfff359e4f283d42d2e739c2547c6e`, 728-byte output +`b58537980b677917b92bbac2ca570ffc2c6aef1823086b955543c46d6880c44b`). All nine +tapes ran cleanly (43, 47, and seven 42 resets). + +A final classification fix distinguishes unsupported visible global targets +(`Incomplete`) from missing targets (`Reject`). The 645,486-byte compiler +(`ec5caf34674af271f408e03bdbe77608b445c306956a0dc1064a41792141f377`) passed its +three-case check in 166.294s (647,792-byte source +`cd0bad694b6a6c4622c2dc8578b1faa2ae930ec0b647ed640038bf1523b7a299`, 22-byte tape +`5d6986842b024c50356357ef47eb431838ba94157e40091d2b998e7046db3373` -> exit 49), +now retained as the 26th refusal case. ## Records and scoped references toward SourceUnit -`--omega-storage` compiles the actual SourceId, SourceUnit and -`source_unit_clear` declarations, followed by a small caller, and executes the -result. The bootstrap compiler now has checked record storage, copy-value -transport, field writes, scoped shared/mutable reference parameters, independent -Unit completion and a bounded default-domain solver. Its detailed supported -semantics and refusals remain in [the compiler contract](../../../bootstrap/omega/compiler/README.md). -That observation closed one actual successor helper; the complete Omega -compiler remained unfinished. The later append/read customer below extends it. -The integrated compiler source grows -from 645,486 to 706,044 bytes (60,558 bytes, about 9.4%), including the shared -parser extensions. This is the audit cost of generic record/place support, not -a claim that the complete construction is now smaller or optimal. - -The first successful source-owned clear observation took 234.069 seconds. It -used compiler 699,956 bytes, -`de2a5daf3598b488d91fdd5581a29a9354bdacad974fd1e0c0d467345b32f236`, -and complete Epsilon source 702,129 bytes, -`3f153e4867db19bfe543e3881129061a798ff51b64fe62826823f73b7c1173cd`. -The exact 780-byte Omega program had SHA-256 -`dd163843c7ab778f828e1ae384a2bbb2e78fef125b036045b9c36ba70c6ed2d0`. -Its 1,206-byte Alpha tape, -`9226c731f5b9ede9eab633ffd240f3f07b9fe7dfea50fa406676f6478c8eb1a6`, -executed with exit 42 and empty output. The caller first establishes a SourceUnit, -sets length/retention fields, then checks the helper's three field updates. -It does not yet execute a nonzero array-element preservation check. - -A separate focused storage invocation passed in 698.231 seconds: shared reads, -copy independence under field mutation, zero/mutable scalar locals, thirteen -refusal cases and compiler reuse. Its exact Epsilon source was 704,912 bytes, -`5d505a3a9ba0b39e0887aad3810c4991141703082abb25be2737c29aec21e0cb`. -All five tapes executed with exits 44, 45, 0, 2 and 59 and empty output. -The 1,382-byte observation, -`73fe5a3f8a033b3a2d5bb5293a54805a97cc83ca7fedffa2e7dd0ce7ed8fff2e`, -also matched the existing independent Epsilon model byte for byte. That model -was a development comparison, not part of the source-owned construction. -Both observations used the already source-constructed Epsilon tape +`--omega-storage` compiles and runs the real SourceId, SourceUnit, and +`source_unit_clear` declarations with a small caller. The compiler now supports +record storage, copy values, field writes, scoped shared/mutable reference +parameters, Unit completion, and a bounded default-domain solver +([compiler contract](../../../bootstrap/omega/compiler/README.md)). Adding +generic record/place support grew the compiler from 645,486 to 706,044 bytes +(+60,558 bytes, ~9.4%). + +The first source-owned clear run took 234.069s (699,956-byte compiler +`de2a5daf3598b488d91fdd5581a29a9354bdacad974fd1e0c0d467345b32f236`, 702,129-byte +Epsilon source `3f153e4867db19bfe543e3881129061a798ff51b64fe62826823f73b7c1173cd`, +780-byte Omega program `dd163843c7ab778f828e1ae384a2bbb2e78fef125b036045b9c36ba70c6ed2d0`, +1,206-byte tape `9226c731f5b9ede9eab633ffd240f3f07b9fe7dfea50fa406676f6478c8eb1a6` +-> exit 42). It verified `clear`'s three field resets without yet checking +nonzero array elements. + +A separate storage run passed in 698.231s (704,912-byte source +`5d505a3a9ba0b39e0887aad3810c4991141703082abb25be2737c29aec21e0cb`, 1,382-byte +output `73fe5a3f8a033b3a2d5bb5293a54805a97cc83ca7fedffa2e7dd0ce7ed8fff2e` matching +the independent dev model), running five tapes (exits 44, 45, 0, 2, 59) and 13 +rejections on Epsilon tape `5f12d53066179df5e92929ab7a41933a2ed3c0234400d9c7b3cda8718a469c12`. -Later nested-literal parsing and additional refusal repairs have separate source -identities; these observations are not promoted to validation of later bytes. - -Failures remain useful evidence: an initial Epsilon source check caught a local -name shadowing a machine parameter; a later Omega refusal at byte 243 exposed -an inherited scalar-only parameter flag check on `&mut SourceUnit`. Both were -repaired without rewriting the actual helper. A prior unlocated refusal does -not establish a cause. The Rust development comparator independently refused -`SourceId { value: 77 as +Trapping }` because its domain pass did not use the -field's expected carrier. This is a comparator limitation against the specified -contextual landing rule, not evidence authorizing implicit qualification; the -exact source remains retained while that separate compiler repair proceeds. - -On the later 706,044-byte compiler -`9f6abccac3ceab338541d78a77e912388146a51e3d60f0ebd326013cec670baa`, -the independent Epsilon model completed the retained storage fixture in 19.222 -seconds. Its complete source was 714,065 bytes, -`77f05d47606f51828a04fc98e21999c13d540d15d7acfb0882b59684fe77d2e1`; -the 5,162-byte observation had SHA-256 -`abea3e5f8b8e983f909974ccbaee614979c531027682a942eb54fb0cfc64726d`. -All nine development-produced tapes executed with the expected exits -42, 43, 44, 45, 46, 0, 2, 48 and 59. Sixteen refusals include a later overlapping -read, nested invariant violation, carrier-invalid requirement bound, unsupported -array equivalence and compiler reset. This is development evidence only; -source-owned execution of this final expanded storage fixture is recorded separately. - - -The final 59-invocation parser customer passed through the same source-built -Epsilon executable in 2,396.104 seconds on Linux x86-64. The exact 744,089-byte -source had SHA-256 -`b5c761c1711dbf9c210d5aab44fc4255c8e8bff85b787f79377ce4c1872df40c`, -joining compiler `9f6abccac3ceab338541d78a77e912388146a51e3d60f0ebd326013cec670baa` -with the 38,045-byte entry -`50ec5053fd956e9291355246b64d741da8914130767538877e25599b33112385`. -Native status was zero, stderr empty and the exact observation was -`000000000041` (Epsilon Exit(0), then `A`). The retained checks include actual -SourceUnit rows, borrow-before-cast ownership, nested and returned records, -field calls preserving outer arguments, bounded-context refusal and reset. -All compiler and fixture bytes were checked against Git -`d1ebbb8e459e879f296a0abbb95ed963934aee77`; captured transport/runtime identities -were unchanged after execution. No interrupted run or timeout supplied this result. - -Final source-owned storage acceptance also passed on that frozen compiler and -Git revision: 1,750.770 seconds for the Epsilon invocation, native status zero, -empty stderr, and the exact 5,162-byte observation shown above. Every retained -refusal asserted an empty, unfinalized tape; all nine published artifacts then -executed with their expected exits and empty output. The actual SourceUnit -customer remained the same 780 bytes throughout. These wall times describe -individual runs on a shared host, not a controlled performance comparison. - -The separately repaired Rust development comparator -`37b4f2188d46c0e12096a3dcfc6af629d124706d6c6050dacfb9a99bc6e61518` -subsequently accepted that unchanged SourceUnit source through checked lowering -and CanonicalTerminalArtifact in 320.101 seconds. This supplies independent -admission/lowering correspondence, not native/Psi runtime evidence or a semantic -stage in the bootstrap chain. - - -The compiler source is composed in order from `../../../bootstrap/gamma/compiler/compiler.gamma`, -`../../../bootstrap/gamma/compiler/frontend.gamma`, and `../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma`. Shared frontend and lowering remain -one semantic owner; `../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma` is an alternative realization, -not an additional stage in this peer. Source composition changes function IDs -and therefore compiler bytes; earlier source/tape identities above remain -historical evidence for their exact recorded inputs. The Alpha backend retains -the audited seed-hole limit; native output has its own buffered-image limit. - -After that split, a fresh cold construction used the 33,605-byte composed -source (`8cc6f6ce3d29ff38a7f94c48857ac6036f0fe09110a442087ebbbb98d48cee86`) -to produce a 458,402-byte tape -(`25b8c1875dd866f885654c5344a16153f3a434eff9555196657f5f0249ef1af1`). -Both Alpha-executed rebuilds matched exactly, and the 32 semantic/15 refusal -controls passed. Reference construction took 89.270 seconds on a shared host; -it is a functional observation. The independent peer's native executable of -this same compiler source separately emitted the identical Alpha tape. +Early failures caught parameter shadowing in Epsilon and an old scalar-only flag +check on `&mut SourceUnit` (byte 243), both fixed without changing the helper. +The Rust comparator separately rejected `SourceId { value: 77 as +Trapping }` +because its domain pass ignored expected field types—a Rust bug, not an implicit +cast rule. + +On the 706,044-byte compiler +(`9f6abccac3ceab338541d78a77e912388146a51e3d60f0ebd326013cec670baa`), the dev +model finished the expanded storage suite in 19.222s (714,065-byte source +`77f05d47606f51828a04fc98e21999c13d540d15d7acfb0882b59684fe77d2e1`, 5,162-byte +output `abea3e5f8b8e983f909974ccbaee614979c531027682a942eb54fb0cfc64726d`), running +nine tapes (exits 42, 43, 44, 45, 46, 0, 2, 48, 59) and 16 rejections. + +The 59-case parser suite passed on the source-built Epsilon binary in 2,396.104s +(744,089-byte source `b5c761c1711dbf9c210d5aab44fc4255c8e8bff85b787f79377ce4c1872df40c` += compiler `9f6abccac3ceab338541d78a77e912388146a51e3d60f0ebd326013cec670baa` + +38,045-byte entry `50ec5053fd956e9291355246b64d741da8914130767538877e25599b33112385`, +output `000000000041` = Exit(0) + `A`, Git `d1ebbb8e459e879f296a0abbb95ed963934aee77`). +Final source-owned storage acceptance also passed on that exact revision in +1,750.770s, matching the 5,162-byte output above and all nine tapes. + +The repaired Rust comparator +(`37b4f2188d46c0e12096a3dcfc6af629d124706d6c6050dacfb9a99bc6e61518`) later +accepted the unchanged 780-byte SourceUnit program through checked lowering and +CanonicalTerminalArtifact in 320.101s (independent front-end check only, not a +bootstrap stage). + +The compiler joins `../../../bootstrap/gamma/compiler/compiler.gamma`, +`../../../bootstrap/gamma/compiler/frontend.gamma`, and +`../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma` in order; +`../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma` is an alternative +backend, not a separate stage. After splitting these files, cold construction of +the 33,605-byte source (`8cc6f6ce3d29ff38a7f94c48857ac6036f0fe09110a442087ebbbb98d48cee86`) +took 89.270s and produced a 458,402-byte tape +(`25b8c1875dd866f885654c5344a16153f3a434eff9555196657f5f0249ef1af1`), matching +both Alpha self-rebuilds and the native compiler, passing 32 semantic and 15 +rejection tests. ## Explicit storage contracts through actual append/read helpers -The expanded storage customer compiles the actual SourceUnit clear/append/read -and ModulePath append declarations. Their private helper requirements now state -the existing guarded upper bounds, and shared/mutable array-shell views express -the intended plain-byte access. The executable checks empty/final/full append, -absent reads, retained flags and bytes, ModulePath capacity, and clear's canary. -The generic controls retain both a disjoint mutation that preserves the bound -and an earlier-argument mutation that invalidates it within one expression. - -The final source-owned Epsilon observation passed in 3411.948 seconds, -with all 13 emitted Alpha executables producing their expected result and empty -output. All 36 refusal/reset checks passed without publishing a partial tape. -The complete 12,666-byte observation matches the independent model byte-for-byte: -`2cea12d28e8fad007802cac92f6c2838e387b387f9cbe22d68cbb1e627a5a7a6`. -The model took 17.808 seconds; it is a development comparison, not a construction -stage. Captured execution inputs remained unchanged. - -The bootstrap compiler is 749,173 bytes, -`4b94fda7d672b3b27173077cdf57075824c0ecc6c56275338936a9c65b39a896`; -the complete Epsilon customer is 763,256 bytes, -`ab66dc787783d86a11e9705352f1843efac5ffd77a9c1db7f7b217b66662d42c`. -The exact extracted Omega program is 3,729 bytes, -`1db5ce53884cb7e02bc4bb2968ff985875448425562eefd1eae47cabbfedaac4`; -its 6,099-byte tape is -`03b0acfdf8ba67b365856bc7ac3667d841c27a1e0e4e843cc2c0242001bf8d93`. -This uses the already source-constructed 16,789,856-byte Epsilon executable -`09e43db0cfe48e8217fec1d571d5e8f9e5e15ed0ef29d4aea884d77acf473eab` -and 617,354-byte Epsilon source -`4a8c97f9ad8f3ef5bae6c2f9a1c72f3433405e6e79610169b03b03a74217fd8e`. -It is actual reference execution, not a fresh cold Gamma reconstruction. - -The compiler closure grew 34,773 bytes from the preceding indexed-storage -milestone. The cost covers shared requirement parsing, checked arrival bounds, -exact-range mutation tracking, bounded addition and safe incoming-reference -transfer. It does not establish full package construction or reproducible -Omega self-compilation; record/enum arrays, larger storage and broader language -facilities remain necessary for the complete compiler source. The separate -103-invocation parser model suite passed on identical parser inputs in 7.584 -seconds; this receipt does not claim a source-owned rerun of that entire suite. - -The subsequent directory relocation was integrated without changing any -compiler member, parser fixture, actual SourceUnit declaration or runtime byte. -The relocated model invocation passed the same 13 executables and 36 refusals -in 18.921 seconds, producing the identical complete request, observation and -tapes. Closure, identity and path checks were rerun after relocation. The -source-owned receipt above retains its original pre-relocation input custody; -it is not presented as a second reference execution. An earlier interrupted -invocation produced no completed receipt and supplies no acceptance claim. +The expanded storage suite compiles the real SourceUnit clear/append/read and +ModulePath append helpers. Their private helper contracts now state their +guarded upper bounds, and array-shell views give plain-byte access. The built +tape tests empty/final/full appends, missing reads, flags and bytes, ModulePath +capacity, and `clear`'s canary, while generic tests check disjoint vs +invalidating earlier-argument mutations. + +The source-owned Epsilon run finished in 3411.948s, running all 13 emitted tapes +and 36 rejections/resets with zero partial output. Its 12,666-byte result +(`2cea12d28e8fad007802cac92f6c2838e387b387f9cbe22d68cbb1e627a5a7a6`) matched the +dev model (17.808s) byte for byte. + +Identities: 749,173-byte compiler (`4b94fda7d672b3b27173077cdf57075824c0ecc6c56275338936a9c65b39a896`), +763,256-byte Epsilon suite (`ab66dc787783d86a11e9705352f1843efac5ffd77a9c1db7f7b217b66662d42c`), +3,729-byte Omega program (`1db5ce53884cb7e02bc4bb2968ff985875448425562eefd1eae47cabbfedaac4`), +6,099-byte tape (`03b0acfdf8ba67b365856bc7ac3667d841c27a1e0e4e843cc2c0242001bf8d93`), +reusing the 16,789,856-byte Epsilon binary (`09e43db0cfe48e8217fec1d571d5e8f9e5e15ed0ef29d4aea884d77acf473eab`) +from 617,354-byte source (`4a8c97f9ad8f3ef5bae6c2f9a1c72f3433405e6e79610169b03b03a74217fd8e`). + +The compiler grew 34,773 bytes for requirement parsing, checked arrival bounds, +range mutation tracking, bounded addition, and safe incoming-reference transfer. +Record/enum arrays and broader features remain open for full self-hosting. A +103-case parser model run passed in 7.584s (not rerun natively). Later directory +relocation changed no source or runtime bytes; the model re-passed in 18.921s +with identical outputs, while the source-owned run keeps its pre-relocation +source record. ### Native Epsilon correspondence for the same storage customer -The independent peer's already source-constructed native Epsilon evaluator ran -the exact frozen PR2722 request in 907.570 seconds. All 13 emitted Alpha -executables and 36 refusal controls passed; the complete observation and every -tape matched the Alpha-VM receipt above byte-for-byte. This checks an actual -Omega-compiler source helper customer, not complete Omega product construction. - -The 767,037-byte request has SHA-256 -`1bce7413e7085408fd052a0cb786ff08f3f2f99bee2e69e6a8a5f633e1a81048`. Compiler, customer and -Delta-closure identities are the same as above. The reused native executable -is 26,119,826 bytes, -`b1cc4441a52ec91feae60d958ada4c400122ce070a2ec66bdd8982c16bbfe2e0`, -constructed in [PR2719](https://github.com/CathedralOS/Omega/pull/2719). Its -729,060-byte canonical evaluator-entry Gamma receipt is -`bec9011e5216557a59ba701ac2a4112774e5f48240c729b95ffc8297f704c368`, -identical to the earlier Alpha-VM evaluator's receipt. This invocation reused -that constructed runtime; it is not another cold construction. - -Both realizations use the shared monotonic 32-byte pair allocation with no -garbage collection. A nonstopping sample observed a native high-water RSS of -16,436,004 KiB and 16,803,601,088 allocated pair bytes; the final maximum RSS -was not recorded. No resource failure, budget change or source mutation occurred. -The 907.570-second native and 3,411.948-second VM observations ran on a shared -host at different times; these are functional timings, not a controlled -performance benchmark. Stronger assurance and the remaining native construction -work stay explicit in [the independent peer](native.md). +The source-built native Epsilon binary from +[PR2719](https://github.com/CathedralOS/Omega/pull/2719) (26,119,826 bytes, +`b1cc4441a52ec91feae60d958ada4c400122ce070a2ec66bdd8982c16bbfe2e0`, from the same +729,060-byte Gamma source `bec9011e5216557a59ba701ac2a4112774e5f48240c729b95ffc8297f704c368`) +ran the exact 767,037-byte PR2722 request +(`1bce7413e7085408fd052a0cb786ff08f3f2f99bee2e69e6a8a5f633e1a81048`) in 907.570s, +matching all 13 tapes and 36 rejections from the Alpha VM run byte for byte. +Both backends used monotonic 32-byte pair allocation without GC. A sample +observed 16,436,004 KiB RSS and 16,803,601,088 allocated pair bytes (final peak +RSS unrecorded). The 907.570s native and 3,411.948s VM timings were separate +shared-host runs, not controlled benchmarks. See [the independent peer](native.md) +for remaining native work. ## Actual UTF-8 decoder through checked arithmetic -The bootstrap compiler constructs the real `decode_scalar` declaration with its -SourceUnit append/read dependencies. Its emitted Alpha program passes 28 UTF-8 -boundary cases, including malformed continuations, overlong sequences, -surrogates, truncation and the Unicode ceiling. Checked Trapping arithmetic -preserves operand order and realizes overflow/underflow as an abnormal Trap; -ordinary incoming-reference forwarding retains argument loans. Named value -variants replace the touched numeric realization tags. - -The final source-owned run uses the same already constructed native Epsilon -runtime described above, with four fresh evaluator processes. All 13 emitted -artifacts match the independent model byte-for-byte and execute independently: -five terminate with Alpha's Linux SIGILL Trap, the other eight return their -expected values. All 14 refusal controls and the final reset canary pass. Only -batch zero compiles the full decoder customer; the other batches use small -generic sources. Batch three retains a success, every refusal and the final -successful reset in one compiler instance. Each invocation checks the complete -Epsilon source before execution; previous-source tapes alone are not acceptance -for this corrected compiler. +The bootstrap compiler now builds `decode_scalar` with its SourceUnit +append/read dependencies. Its Alpha tape passes 28 UTF-8 cases (bad +continuations, overlong sequences, surrogates, truncation, and Unicode max). +Checked Trapping arithmetic preserves operand order and traps on +overflow/underflow; reference forwarding keeps argument borrows, and named value +variants replace numeric tags. + +The reused native Epsilon binary ran four fresh processes to check all 13 tapes +(matching the model byte for byte: five Alpha SIGILL traps and eight normal +exits), 14 rejections, and the final reset. Batch 0 builds the full decoder; +batches 1–3 use small generic sources (batch 3 tests success, all rejections, +and reset in one compiler instance). | Batch | Emitted artifacts | Native Epsilon seconds | Maximum child RSS (KiB) | | --- | ---: | ---: | ---: | @@ -1098,114 +827,78 @@ for this corrected compiler. | 2 | 3 | 324.005 | 6,488,740 | | 3 | 2 | 153.049 | 3,270,436 | -Native Epsilon time totals 1612.651 seconds. These are functional observations -on a shared host, not a controlled benchmark or a fresh cold reconstruction. -Inputs stayed unchanged and no final batch needed a resource interruption. -The independent model passed in 46.762 seconds. The storage model regression -passed in 15.500 seconds with all 13 prior tapes and the complete observation -unchanged; that regression is a model result, not another native storage run. -Compiler identity/corruption controls and four source-closure tests also passed. - -Frozen source checkpoint: `8f27a2b7f65f4f8554a2a96d3c4fe014cbfd1408`. -The compiler is 764,081 bytes, -`2d7602e4e1e63822be65b950ccb4170c9dfddcc6de8344f9ab0729209133a681`; -the complete Epsilon customer is 775,834 bytes, -`8107bea7fa2f8c6370d706037f1cb2418d99493c1239a0201452c957320a9434`. -The extracted Omega source is 12,406 bytes, -`7f89108d7c2191eb7a932159dcec418943b37d672beef81843342787e45e01f8`; -its 31,279-byte decoder tape is -`ea7052722e423ccd4f6133432482879dd725b6f878d896a649181028dcd92af8`. -The validation driver retains the selector and request framing in -[test.py](../../../tests/bootstrap/compiled_vm/test.py); all batches use that same compiler and Epsilon customer. -The existing native successor invocation now exposes this customer with -`python3 tests/bootstrap/independent/successor_test.py --omega-utf8 --seconds 14400`. -Its default route reconstructs predecessors first; the measurements above reused -the already constructed evaluator and do not claim a new cold invocation. +Total native time was 1612.651s (shared-host runs, no interruptions). The dev +model passed in 46.762s, the storage model regression passed in 15.500s, and +identity/closure tests passed. + +Checkpoint `8f27a2b7f65f4f8554a2a96d3c4fe014cbfd1408`: 764,081-byte compiler +(`2d7602e4e1e63822be65b950ccb4170c9dfddcc6de8344f9ab0729209133a681`), 775,834-byte +Epsilon suite (`8107bea7fa2f8c6370d706037f1cb2418d99493c1239a0201452c957320a9434`), +12,406-byte Omega source (`7f89108d7c2191eb7a932159dcec418943b37d672beef81843342787e45e01f8`), +31,279-byte decoder tape (`ea7052722e423ccd4f6133432482879dd725b6f878d896a649181028dcd92af8`). +Driver framing lives in [test.py](../../../tests/bootstrap/compiled_vm/test.py), +also exposed as `python3 tests/bootstrap/independent/successor_test.py --omega-utf8 --seconds 14400`. - Batch 0 observation: `169b7abb2b2e44dddb65606f27b3568ed40a6e8116c69e79ee230ae3ba404e58`. - Batch 1 observation: `f9d78d1b0218c548e48a566feb882deba731ae6364c38a9516254f2d634cb1fb`. - Batch 2 observation: `209d389076b3fc9dd63512d1b941a512c319cc5caa6ac8b03ce4e0fdb6db962d`. - Batch 3 observation: `6cdc45313a524911f6d744ba70e0f2211811d3804cc72fa628cb935e79207c07`. -An earlier monolithic driver invocation on the superseded 760,804-byte compiler -`9b2ed3c5c7921e504f672324ca1b6510bf4be519d260d8506be369e1b79f8ece` -was gracefully interrupted after 1,387.703 seconds near the shared 32 GiB host -limit. Its child maximum RSS was 32,207,012 KiB, with no OOM event and no completed -observation. This was a host-resource interruption, not a semantic rejection or -completed bootstrap. That old compiler subsequently completed the isolated -decoder batch in 933.007 seconds at 21,028,664 KiB maximum RSS. Those receipts -remain historical, separate from the final four-batch acceptance above. -Fresh processes bound cumulative validation allocation; they do not guarantee -that any larger single compiler-source customer will fit this host. - -The corrected compiler adds 14,908 source bytes over the prior storage milestone. -Unsupported indexed carriers remain coverage refusals rather than invented byte -mismatches, and a coverage fallback cannot overwrite a diagnosed source error. -The actual decoder uses canonical casts and explicit literal qualification. -This is construction of an actual compiler-source component, not complete Omega -compiler construction or reproducible self-rebuild. Full modules, sums and -broader compiler-source facilities remain delivery work. +An earlier monolithic run on the 760,804-byte compiler +(`9b2ed3c5c7921e504f672324ca1b6510bf4be519d260d8506be369e1b79f8ece`) was stopped +gracefully at 1,387.703s near the 32 GiB host limit (32,207,012 KiB RSS, no OOM, +no output); that compiler later finished the isolated decoder batch in 933.007s +(21,028,664 KiB RSS). Separate processes cap cumulative validation memory but do +not guarantee larger single inputs will fit. + +This update added 14,908 compiler bytes; unsupported indexed types return +coverage refusals without masking diagnosed source errors. Full modules, sums, +and Omega self-rebuilds remain open. ## Following an instruction through both assemblers -For a register addition, the shared lowering calls `i_add`. Alpha writes -opcode 3 and two register indices in one three-byte field. Linux x86-64 -loads the same two slots, appends `48 01 d8` for `add rax,rbx`, then stores -the result. Each field adds its own width to the label positions used by -later jumps. A jump holds the label identity until publication. - -For `(def main () Int 42)`, the generated input loop checks whether the read -returned EOF. At Alpha tape offset `0x48`, the bytes `10 00 01` compare -registers 0 and 1 for equality. The next eight bytes encode the destination -`0xa1` in little-endian order. In the ELF, `48 39 d8` compares the same values. The -instruction at `0x40019e` is `0f 84 d6 00 00 00`, a jump on equality. -Adding its signed displacement of 214 to the following address, `0x4001a4`, -gives `0x40027a`. Both destinations start the call after the input loop. -The loop's backward jump encodes `e9 c4 fe ff ff` at `0x400275`. -Its displacement of −316 returns to the read at `0x40013e`, corresponding -to Alpha tape offset `0x3c`. -See the [Alpha assembler](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) and [native assembler](../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma). - -At `a59d45e8bd77`, field layout still emitted absolute native jumps. Its -source-built native compiler was 1,543,898 bytes, -SHA-256 `04c864bd27c5ae5fb5870b2fb1339c63d7caf29541d53af3fbb8dc0f2e3eea89`. -Two native self-rebuilds produced those same bytes. It compiled the -35,123-byte Alpha-targeting compiler source into a native executable. That -executable built the 456,334-byte Alpha compiler tape, and the tape rebuilt -itself byte for byte (SHA-256 `d9620222d49ba7b5604bfd516751fe93b5ddfb78521fc5aff0538c88518e5629`). - -Both assemblers reproduced the existing Delta compiler and Epsilon evaluator -images from the Gamma sources constructed at `b95769558667`. The table gives -each output size and the peak resident memory Linux reported for its compiler -process. Each run used an already constructed native compiler executable. -Both versions compiled the same input bytes on the same host. +For register addition, shared lowering calls `i_add`. Alpha writes opcode 3 and +two register indexes in three bytes; Linux x86-64 loads both slots, emits +`48 01 d8` (`add rax,rbx`), and stores the result. Each field contributes its +byte width to label offsets, and jumps store label IDs until output. + +For `(def main () Int 42)`, the input loop checks for EOF. At Alpha offset +`0x48`, `10 00 01` compares registers 0 and 1, followed by eight-byte +little-endian destination `0xa1`. In ELF, `48 39 d8` compares the values, and +`0f 84 d6 00 00 00` at `0x40019e` jumps +214 bytes from `0x4001a4` to `0x40027a` +(past the loop). The backward jump `e9 c4 fe ff ff` at `0x400275` jumps −316 +bytes to `0x40013e` (Alpha `0x3c`). +See [Alpha assembler](../../../bootstrap/gamma/compiler/alpha/alpha_backend.gamma) +and [native assembler](../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma). + +At `a59d45e8bd77` (still using absolute native jumps), the native compiler was +1,543,898 bytes (`04c864bd27c5ae5fb5870b2fb1339c63d7caf29541d53af3fbb8dc0f2e3eea89`, +matching two self-rebuilds) and built the 35,123-byte Alpha compiler into a +456,334-byte tape (`d9620222d49ba7b5604bfd516751fe93b5ddfb78521fc5aff0538c88518e5629`) +that matched its own self-rebuild. + +Both assemblers rebuilt Delta and Epsilon from `b95769558667` Gamma sources +using already built native compilers on the same host: | Gamma source | Alpha tape bytes | Peak KiB, old → new | Linux ELF bytes | Peak KiB, old → new | | --- | ---: | ---: | ---: | ---: | | Delta compiler (151,525 bytes) | 1,219,139 | 101,248 → 66,560 | 3,984,546 | 104,064 → 120,320 | | Epsilon evaluator (729,060 bytes) | 7,876,070 | 645,504 → 417,408 | 26,119,826 | 663,552 → 771,584 | -The native assembler often records several fields for one operation. Its -higher compiler memory use on both sources is a cost of this representation. -Both Delta images produced the same 3,082-byte receipt. Both Epsilon images -ran the frozen bootstrap compiler on the Omega fixture, produced the same -50-byte Alpha program, and that program exited 42. The full product request -exceeded the evaluator's 4 MiB input limit and returned 253 with empty output. - +Recording multiple fields per native op raised native compiler RSS. Both Delta +binaries emitted the 3,082-byte output, and both Epsilon binaries compiled the +Omega fixture to the 50-byte tape (exit 42). The full product request exceeded +the 4 MiB input limit and exited 253 with empty output. ### Direct Linux branches -The native assembler can jump on the condition the Gamma lowering requested. -A conditional transfer uses one six-byte x86 instruction after the register -comparison. A direct call or unconditional jump takes five bytes. The -earlier encoding used an inverse condition followed by a twelve-byte -absolute jump. The field writer now computes signed distances for x86 and -continues to compute absolute offsets for Alpha. +The native assembler now emits six-byte conditional branches and five-byte +direct calls/unconditional jumps using signed x86 displacements (replacing an +inverted condition plus twelve-byte absolute jump), while Alpha keeps absolute +offsets. -The following paired measurements used already constructed Linux compiler -executables. Delta had identical source at `b95769558667` and `124129cd2d6`. -The two Epsilon versions had different source. Every Alpha output matched -the earlier assembler byte for byte. +Paired runs using built Linux compilers (Delta unchanged across `b95769558667` +and `124129cd2d6`; Epsilon updated; all Alpha outputs byte-identical): | Gamma source | Absolute ELF bytes | Relative ELF bytes | Peak compiler KiB, absolute → relative | Branch and call destinations checked | | --- | ---: | ---: | ---: | ---: | @@ -1213,44 +906,29 @@ the earlier assembler byte for byte. | Epsilon at `b95769558667` | 26,119,826 | 25,322,912 | 771,584 → 746,924 | 100,900 | | Epsilon at `124129cd2d6` | 26,075,468 | 25,280,528 | 770,176 → 745,516 | 100,648 | -Across these executables the largest backward and forward displacements -were −25,319,803 and +25,312,592 bytes. The direct native compiler reproduced its own -1,484,898-byte ELF from 40,323 source bytes. The extra target-width and -target-value functions brought the Alpha compiler source to 35,337 bytes -and its own tape to 457,463 bytes, an increase of 1,129 tape bytes. -Both native Epsilon versions ran their corresponding bootstrap compiler -fixture under each encoding and produced the same 50-byte program. It -exited 42 in all four runs. +Largest backward/forward displacements were −25,319,803 and +25,312,592 bytes. +The native compiler rebuilt its 1,484,898-byte ELF from 40,323 source bytes; +extra target helpers grew the Alpha compiler to 35,337 source bytes and 457,463 +tape bytes (+1,129 bytes). All four Epsilon runs produced the same 50-byte tape +(exit 42). ## Earlier nominal-case construction interruption -The candidate bootstrap compiler at `501411f37fe18b55b4e068811c36258f318b002b` -adds nullary copy sums for the unchanged source-Psi `NumericBase` declaration and -`lexer_digit_in_base` helper. Its 6,797-byte lexer customer checks all 256 raw -bytes against four independently authored base predicates, alongside identifier -boundaries. The independent model produced and executed 17 Alpha tapes and -passed 36 refusal/reset controls in 21.620 seconds. The storage model regression -retained all 13 earlier tapes and the complete observation in 18.887 seconds. -These are model results, not completed source-owned construction evidence. - -The reused native Epsilon evaluator `b1cc4441…fe2e0` began the same complete -793,158-byte Epsilon customer, with compiler closure 778,742 bytes, -`f250f98315032419393d2a297cf5ff892bcfddb95346cf62f2cc32a2019659c5`. -Its request was `aacf5003762b373cad3cb5dc6c52a21cd834eb25be0a0c7fe586a0fb8d12c5c3`. -The observation was interrupted after 1,009.487 seconds when estimated -unreclaimable headroom on the shared 32 GiB host crossed the predeclared 1.5 GB -guard. The child maximum RSS was 22,525,132 KiB; no observation was published -and no OOM event occurred. This is a host-resource interruption, not a source -rejection, completed native result, or evidence that the architecture is -infeasible. No fresh cold construction was attempted. - -Review also corrected one negative from unsupported brace syntax to a parsed -payload declaration. The corrected payload-layout refusal and subsequent default -reset passed a separate 11.655-second model run, asserting one parsed payload -field and the declaration-anchored refusal. The interrupted native request kept -its original bytes and cannot establish that corrected layout boundary. -The subsequent bounded native invocation completed on the actual classifier, -corrected payload/default reset and two-package source-set construction. Its -current source identities, execution results and measured whole-compiler refusal -are recorded in [the bootstrap compiler](../../../bootstrap/omega/compiler/README.md#executed-nominal-values-and-source-set-construction). -The interrupted observation above remains tied to its original bytes. +At `501411f37fe18b55b4e068811c36258f318b002b`, the bootstrap compiler added +nullary copy sums for `NumericBase` and `lexer_digit_in_base`. On its 6,797-byte +lexer test (256 bytes across four bases plus identifier edges), the dev model +ran 17 Alpha tapes and 36 rejections/resets in 21.620s and re-passed the storage +regression in 18.887s (model results only). + +The reused native Epsilon binary (`b1cc4441…fe2e0`) started the 793,158-byte +suite (778,742-byte compiler `f250f98315032419393d2a297cf5ff892bcfddb95346cf62f2cc32a2019659c5`, +request `aacf5003762b373cad3cb5dc6c52a21cd834eb25be0a0c7fe586a0fb8d12c5c3`), but +stopped at 1,009.487s when free headroom on the 32 GiB host fell below the +1.5 GB guard (22,525,132 KiB RSS, no OOM, no output). This was a host-memory +stop, not a language failure. + +Review also replaced an unsupported-syntax negative test with a parsed payload +declaration; that rejection and reset passed an 11.655s model run. A later +bounded native run completed the classifier, corrected payload/default reset, +and two-package build; see +[the bootstrap compiler](../../../bootstrap/omega/compiler/README.md#executed-nominal-values-and-source-set-construction). diff --git a/wiki/development/bootstrap/native.md b/wiki/development/bootstrap/native.md index 7d5bf14402af..2d958b4e4dfb 100644 --- a/wiki/development/bootstrap/native.md +++ b/wiki/development/bootstrap/native.md @@ -1,205 +1,196 @@ # Standalone-language construction experiment -This peer constructs standalone Linux x86-64 compiler executables from Gamma -source. Generated successors execute their own native instructions and Linux -system calls: they carry no Alpha interpreter, seed container, bytecode dispatch -loop, or host compiler. The first customer is the actual Gamma compiler from -[the shared Gamma compiler](../../../bootstrap/gamma/compiler/), compiled into a native executable -that emits the ordinary Alpha compiler tape. +This route builds standalone Linux x86-64 compiler executables directly from Gamma +source. Generated binaries execute native x86-64 instructions and Linux syscalls +directly—no Alpha interpreter, seed container, bytecode loop, or host compiler +runs inside them. The first target built this way is the +[shared Gamma compiler](../../../bootstrap/gamma/compiler/) itself, compiled into +a native executable that emits the standard Alpha compiler tape. -`../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma` supplies the assembler for the shared Gamma lowering. The -compiler source concatenates these three files in order. +`../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma` supplies the native assembler for the shared Gamma lowering. The +compiler source concatenates three files in order: -1. `../../../bootstrap/gamma/compiler/compiler.gamma` owns declaration validation, scoped expression +1. `../../../bootstrap/gamma/compiler/compiler.gamma` handles declaration validation, scoped expression lowering, tagged values, call frames, runtime checks, and label resolution. -2. `../../../bootstrap/gamma/compiler/frontend.gamma` owns the Gamma source grammar and parsing. -3. `../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma` emits ELF64 headers, startup, and native instruction sequences. +2. `../../../bootstrap/gamma/compiler/frontend.gamma` implements the Gamma grammar and parser. +3. `../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma` emits ELF64 headers, startup code, and x86-64 instructions. -No source text is rewritten or recognized as a special customer. The same -frontend and lowering serve the Alpha and native realizations. Each named -operation appends its native fields, and labels identify positions in the code. -The compiler validates all functions and branches before buffered publication. -The public [Gamma semantics](../../../bootstrap/gamma/LANGUAGE.md) and existing -compiler's explicit accepted subset govern both realizations. +No source text is rewritten or special-cased. The same frontend and lowering +drive both the Alpha and native backends. Each named operation appends its +target bytes, and labels mark code positions. The compiler validates every +function and branch before writing output. [Gamma semantics](../../../bootstrap/gamma/LANGUAGE.md) +and the compiler's accepted subset govern both backends. ## Delta syntax for the emitted Omega compiler The Epsilon compiler emitted a complete 18,365,364-byte Delta program with its storage runtime and entry (SHA-256 -`f662e1a8007b819bd02fc1571d6314e49c1fac9785247ed58e278a16ca46dcab`). -It contains 7,774 top-level forms, 468,044 lists and 1,172,126 atoms. -Applying the parser's production allocation ledger gives 384,199,320 bytes -for balanced parsing. A diagnostic build that reported the ledger after -grammar measured 529,276,120 bytes in total, including 145,076,800 for -grammar. +`f662e1a8007b819bd02fc1571d6314e49c1fac9785247ed58e278a16ca46dcab`), +containing 7,774 top-level forms, 468,044 lists, and 1,172,126 atoms. +The parser's allocation model charges 384,199,320 bytes for balanced parsing; +a diagnostic build measured 529,276,120 bytes total, including 145,076,800 +bytes for grammar. [Syntax representation and charges](../../../bootstrap/delta/compiler/implementation/checking/syntax/README.md) -The ConstructionBytesV1 Delta compiler now provisions 1 GiB for syntax. On -this program it completed grammar, resolution, type checking and lowering. -With the earlier 16,777,212-byte Gamma output limit, its emission preflight -returned code 12 in emitted-payload space and requested 26,398,215 bytes. +The ConstructionBytesV1 Delta compiler now reserves 1 GiB for syntax and +completed grammar, resolution, type checking, and lowering on this program. +Under the older 16,777,212-byte Gamma output cap, emission preflight returned +code 12 and requested 26,398,215 bytes. [Emission preflight](../../../bootstrap/delta/compiler/implementation/pipeline.gamma) The frozen 4,107,257-byte Omega signature-checking program -(`3a726430d1e02a312dba9a8d68ec54331a474f1dab671c5e6ad3bc394ebebbc6`) takes -90,118,000 bytes to parse and 31,712,800 for grammar. Its original 114,294,752-byte syntax provision ran out -during grammar at byte 3,132,226. With the construction provision the compiler -published 5,819,889 bytes of Gamma (SHA-256 -`5bfd4417a851ca411730364a88935511494847cd8a80392e110ec895273a1e11`). -The reconstructed Gamma interpreter ran that receipt. Its eight-byte -observation, `002a000000010200`, matched both direct Delta execution and -the Epsilon evaluator, including guest exit 42. +(`3a726430d1e02a312dba9a8d68ec54331a474f1dab671c5e6ad3bc394ebebbc6`) needs +90,118,000 bytes to parse and 31,712,800 bytes for grammar. The older +114,294,752-byte syntax budget ran out during grammar at byte 3,132,226. With +the construction budget, the compiler emitted 5,819,889 bytes of Gamma (SHA-256 +`5bfd4417a851ca411730364a88935511494847cd8a80392e110ec895273a1e11`). The +rebuilt Gamma interpreter ran that output and produced `002a000000010200` +(including guest exit 42), matching both direct Delta execution and the Epsilon +evaluator. [Signature customer](../../../tests/bootstrap/independent/epsilon/signature_main.epsilon) -To exercise the last complete parser frame and the next frame in each profile, +To test the last valid parser frame and the next frame in each profile, run `python3 tests/bootstrap/independent/delta_syntax.py DELTA_EXECUTABLE PACKED_SUPPORT`. ## Construction and acceptance -On Linux x86-64, build the native Gamma compiler in a new output directory: +On Linux x86-64, build the native Gamma compiler in a fresh output directory: ```sh tests/bootstrap/linux_x86_64/bootstrap . /tmp/omega-gamma-native ``` -The checked-in driver takes the five source inputs described in the [Linux construction guide](../../../tests/bootstrap/linux_x86_64/README.md). +The checked-in driver reads the five source inputs described in the +[Linux construction guide](../../../tests/bootstrap/linux_x86_64/README.md). ## Host checks -The native suite reconstructs the compiler, compares the generations, and exercises its Alpha-targeting customer: +The native test suite rebuilds the compiler, verifies self-rebuild identity, +and compiles the Alpha-targeting compiler with it: ```sh python3 tests/bootstrap/independent/source_test.py ``` -The cold route starts with the audited Alpha seed and separately admitted Beta -tape from `interpreted.md`. It reconstructs Beta from source byte for byte, -constructs the Gamma evaluator from Beta source byte for byte, then executes the -native compiler source through that evaluator. This constructs `compiler0.elf`. -Its successors rebuild the native compiler source into identical `compiler1.elf` -and `compiler2.elf`. These executions require neither the evaluator nor Alpha. - -The native compiler then compiles the actual Alpha-targeting Gamma compiler -source into another ELF executable. That executable emits the Alpha compiler -tape from its real source; the stamped tape reconstructs the same tape exactly. -Each realization runs the existing 32 semantic and 15 rejected-source controls, -including wrapping arithmetic, signed division, scalar/pair separation, mixed -arity proper tail calls, complete source validation, sealed input, and atomic -publication. Five additional native controls cover exact/adjacent emitted-image -capacity and returned mapping/read/write errors. Capacity exhaustion returns 254 -with no image, distinctly from a source refusal. The compiler fixed point is an intermediate construction check, -not the final Omega acceptance. - -The test suite's `--accelerated` mode uses the Python Gamma compiler as a development comparator. The offline command above uses the Gamma evaluator constructed by Beta. - -Artifacts, exact requests, and `report.json` go to ignored +The cold build starts from the audited Alpha seed and trusted Beta tape from +`interpreted.md`. It rebuilds Beta from source byte for byte, builds the Gamma +evaluator from Beta source byte for byte, and runs the native compiler source +on that evaluator to produce `compiler0.elf`. Two native self-rebuilds produce +byte-identical `compiler1.elf` and `compiler2.elf` without the evaluator or +Alpha. + +The native compiler then compiles the Alpha-targeting Gamma compiler source +into a native ELF binary. That binary emits the Alpha compiler tape from source, +and stamping and running that tape reproduces the same tape byte for byte. Both +backends run all 32 semantic tests and 15 source-rejection tests (wrapping +arithmetic, signed division, scalar/pair separation, mixed-arity tail calls, +full validation, sealed input, and atomic output). Five extra native tests check +exact and off-by-one image size limits plus `mmap`, read, and write errors. +Running out of output space exits 254 with no file written, distinct from a +source error. A compiler fixed point is an intermediate milestone, not final +Omega acceptance. + +Passing `--accelerated` runs the Python Gamma compiler as a development +comparator; the default command uses the Beta-built Gamma evaluator. + +Outputs, requests, and `report.json` go to ignored `build/independent-native-reference/` (or `-accelerated`). `--seconds N` sets a -positive process watchdog. A timeout is an observation failure. A source refusal -must exit 249 without output. Successful compiler results are complete images; -the harness writes retained artifacts only after successful construction. +process timeout (timeouts fail the test). Rejected source must exit 249 with +empty output. The harness saves output binaries only after a full successful +build. ## Runtime and audit boundary -The ELF has one read/execute load segment and no dynamic interpreter or shared -libraries. Startup zeros 256 word slots on the process stack and reserves a -128-GiB private anonymous virtual region using `mmap(MAP_NORESERVE)`. Host `r14` -points to the register slots and `r15` to that region. Every instruction loads -its known slots into scratch registers, computes directly, and stores its result. -Native calls and returns use the process stack; source tail calls use native -jumps. Decimal emission constants carry their exact little-endian hex bytes in -comments for review. +Each ELF has a single read/execute `LOAD` segment and no dynamic linker or +shared libraries. Startup clears 256 word slots on the stack and reserves a +128 GiB private anonymous region via `mmap(MAP_NORESERVE)`. `r14` holds the +register slots and `r15` holds the memory base. Instructions load slots into +scratch registers, compute directly, and write results back. Native calls use +the process stack; tail calls jump directly. Decimal emission constants carry +their little-endian hex bytes in comments for review. The shared compiler's disjoint frame, sealed-input, buffered-output, immutable -pair and call-depth guards remain authoritative. Pair handles retain a separate -unforgeable tag. The backend receives memory operations only through the -compiler's checked lowering. The 128-MiB output limit includes the 128-byte -ELF header and 88-byte startup. -The Alpha backend separately retains its audited 16-MiB seed-hole limit. - -The Linux runtime reuses the first 8 MiB of its pair area. At allocation, -both operands are still on the tagged value stack. When the area fills, the -runtime walks that stack and copies reachable young pairs into the rest of -the area. It then visits the children of each copy. A forwarding address -preserves shared children. Older pairs are immutable, so they cannot point -back into a later allocation batch. - -When the promoted region has grown by at least 64 MiB and doubled its -surviving size since the last full scan, the Linux runtime traces it as well. -It copies live pairs into the unused upper half of the arena, then copies -them back to the old base. Once the promoted region reaches the midpoint, -the runtime uses the whole remaining capacity for nursery survivors. The -lifetime allocation limit counts each full nursery once. The seed-construction -test keeps a shared tree alive while discarding successive 290,000-pair -lists, and checks the last permitted allocation against its adjacent refusal. - -On the same 25,733,081-byte Gamma source for the Epsilon-written Omega -compiler at `bcf71f0bbfc`, peak resident memory for native code generation -fell from 4,660,772 to 1,690,456 KiB. The resulting constructor checked the -same Omega package lacking its required process provider in 27,232 KiB, -down from 354,848 KiB. Both returned the same nine bytes, reporting the -missing provider at source byte 904. +pair, and call-depth guards stay in force. Pair handles keep an unforgeable tag, +and the backend only receives memory ops through checked lowering. The 128 MiB +output cap includes the 128-byte ELF header and 88-byte startup code; the Alpha +backend keeps its 16 MiB seed-hole limit. + +The Linux runtime reuses the first 8 MiB of its pair arena as a nursery. At +allocation, both operands remain on the tagged value stack. When the nursery +fills, the runtime scans the stack, copies reachable young pairs into the +promoted area, and scans their children using forwarding pointers to preserve +sharing. Because older pairs are immutable, they never point into newer batches. + +When the promoted area grows by at least 64 MiB and doubles its live size since +the last full collection, the runtime runs a full copying collection: it copies +live pairs into the upper half of the arena and copies them back to the base. +Once the promoted area passes the midpoint, the remaining space holds nursery +survivors. The lifetime allocation limit counts each full nursery once. The +seed-construction test keeps a shared tree live while discarding repeated +290,000-pair lists and checks the last allowed allocation against the next +refusal. + +On the 25,733,081-byte Gamma source for the Epsilon-written Omega compiler at +`bcf71f0bbfc`, peak RSS for native code generation dropped from 4,660,772 to +1,690,456 KiB. Running the resulting compiler on an Omega package missing its +process provider dropped from 354,848 to 27,232 KiB, returning the same nine +bytes reporting the missing provider at source byte 904. [Allocation code](../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma) · [Seed-construction tests](../../../tests/bootstrap/linux-seed-construction.py) -Storage limits and authored traps retain the shared compiler's distinct statuses. -Returned `mmap`, read or write system-call errors exit 3. Host signals can -terminate execution separately: a pipe with no reader has the ordinary default -`SIGPIPE` behavior, rather than guaranteeing status 3. Physical memory and sufficient -process stack remain host dependencies; `MAP_NORESERVE` does not promise physical -memory availability. With the shared 131,072 call-depth limit, native return -addresses use at most 1,048,592 bytes plus the 2,048-byte register file and one -8-byte I/O scratch slot. Existing source bounds protect Gamma data accesses; -this experiment does not claim a machine-checked implementation proof. - -A generated call site uses a five-byte native call for a Gamma primitive, -a push or a pop. Frame-slot access passes the byte offset in register 11 -to a shared load or store routine. A tail call passes its argument word count -to a loop that copies them in their original order. The compiler generates the -same tag checks and allocation bounds in these shared routines. A primitive -can call a stack routine or the buffered writer, so at most two helper return -addresses are live beneath a Gamma call. The call-depth test executes the -last admitted frame and checks the adjacent refusal on both compiled targets. +Storage limits and program traps keep their distinct exit codes. `mmap`, read, +or write syscall errors exit 3. OS signals still terminate normally (for +example, a broken pipe triggers `SIGPIPE` instead of exiting 3). Physical RAM +and stack space remain host requirements because `MAP_NORESERVE` does not +guarantee physical pages. With the 131,072 call-depth limit, native return +addresses take at most 1,048,592 bytes plus the 2,048-byte register file and an +8-byte I/O scratch slot. Source bounds guard Gamma memory accesses; this +experiment does not claim a machine-checked implementation proof. + +Each generated call site uses a five-byte native call for a Gamma primitive, +push, or pop. Frame-slot access passes the byte offset in register 11 to a +shared load or store helper. Tail calls pass their argument count to a shared +copy loop that preserves order. Shared helpers keep the same tag and bounds +checks. Because a primitive may call a stack helper or buffered writer, at most +two helper return addresses sit below a Gamma call. The call-depth test runs the +last allowed frame and verifies rejection on the next frame for both backends. [Shared operations](../../../bootstrap/gamma/compiler/compiler.gamma) · [Native helpers](../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma) -The shared Gamma compiler indexes declarations with the same balanced tree it -uses for assembler labels. Function keys compare identifier length, then their -exact source bytes. Duplicate names reject on insertion. The compiler still -checks and emits each body in source order, including unused bodies and forward -calls. The 26,398,215-byte constructor source has 7,597 functions and 103,173 -calls. Scanning the old declaration list required 733,309,253 name comparisons -at those calls. Each unsuccessful comparison allocated a new list tail, consuming -more than 23 GB on the native host. The indexed lookup traverses the tree -without allocating list tails. [Gamma source](../../../bootstrap/gamma/compiler/compiler.gamma) - -The native assembler uses x86-64 direct branches and calls. For `i_jz`, -`test rax,rax` sets the flags and `0f 84` jumps on zero. The next four -bytes hold a signed displacement from the end of that instruction. To -compute it, the assembler subtracts the target's distance from the code -end from the number of bytes following the field. Zero selects the following -instruction. Positive and negative displacements select later and earlier -addresses. The distance between any two positions in a 128 MiB image fits -within the signed 32-bit range. Calls and unconditional jumps use the same -calculation. +The shared Gamma compiler indexes declarations in the same balanced tree used +for assembler labels, ordering keys by identifier length then exact bytes and +rejecting duplicates on insertion. It still checks and emits bodies in source +order, including unused functions and forward calls. The 26,398,215-byte +constructor source has 7,597 functions and 103,173 calls; the old linear scan +needed 733,309,253 name comparisons and allocated a list tail on every miss, +burning over 23 GB on Linux. Tree lookup avoids those allocations. +[Gamma source](../../../bootstrap/gamma/compiler/compiler.gamma) + +The native assembler emits direct x86-64 branches and calls. For `i_jz`, +`test rax,rax` sets flags and `0f 84` jumps on zero with a four-byte signed +displacement from the end of the instruction, computed by subtracting the +target's distance from code end from the bytes remaining after the field. Zero +targets the next instruction; positive and negative values jump forward or +backward. Every offset inside a 128 MiB image fits in signed 32-bit range. +Calls and unconditional jumps use the same formula. [Native assembler](../../../bootstrap/gamma/compiler/linux_x86_64/native.gamma) ## Delivery continuation -No peer is selected by this experiment. The remaining delivery path is to use -native Gamma to construct the actual bootstrap compiler implementation, then -compile the shared Omega product source outside this directory and reproduce -its self-rebuild. Source/compiler/runtime size, execution and memory costs, and -failure observations must stay tied to their exact source closures. Intermediate -self-hosting and small language controls do not complete that path. Additional -facilities must serve that actual successor; a second source recognizer, -precomputed compiler image, or proof-certificate subsystem is not part of it. +No route is selected yet. The remaining work is to use native Gamma to build +the bootstrap compiler, compile the shared Omega product compiler outside this +directory, and reproduce its self-rebuild. Sizes, runtime/memory costs, and +failures must stay tied to exact source bundles. Intermediate self-hosting and +small tests do not finish this goal. New features must serve that compiler; +second parsers, prebuilt compiler binaries, and proof-certificate systems are +out of scope. ## Construction evidence -Before the assembler refactor, a Linux x86-64 cold run constructed the -following source closures and artifacts. Two native compiler rebuilds matched byte for byte; the native Alpha -compiler's output also matched its Alpha-executed self-rebuild. The disclosed -Python-assisted development route independently produced the same native image. +Before the assembler refactor, a Linux x86-64 cold run built these artifacts. +Both native rebuilds matched byte for byte, the native Alpha compiler matched +its Alpha self-rebuild, and the Python-assisted route produced the same native +binary. | Subject | Bytes | SHA-256 | | --- | ---: | --- | @@ -209,19 +200,17 @@ Python-assisted development route independently produced the same native image. | Native Alpha compiler ELF | 1,453,814 | `c157f919ea2cc0b53f2826e817262ff8217233be77f114d5910facb108867a06` | | Alpha compiler tape | 458,402 | `25b8c1875dd866f885654c5344a16153f3a434eff9555196657f5f0249ef1af1` | -All 32 semantic and 15 refused-source observations passed for each realization, -along with all five native capacity and returned-system-call-error controls. -Reference construction took 155.649 seconds; the largest child-process resident -set reported by Linux `getrusage` across the complete run was 48,384 KiB. This is -a measured largest child RSS, not total simultaneous memory or the 128-GiB -virtual reservation. These are functional observations on a shared host, not a -controlled speed comparison or a compiler-correctness proof. None constructs -the Omega compiler source or closes its self-rebuild acceptance. +All 32 semantic tests, 15 rejection tests, and five native capacity and syscall +error tests passed on each backend. Cold construction took 155.649 seconds with +a peak child RSS (`getrusage`) of 48,384 KiB (single largest child, not combined +memory or the 128 GiB virtual reservation). These are shared-host test runs, not +benchmarks or correctness proofs, and they do not build or self-host the Omega +compiler. ## Native successor customers -The next construction check uses the real Delta compiler and Epsilon evaluator, -then optionally runs the actual bootstrap Omega compiler on its existing fixture: +The next test builds the Delta compiler and Epsilon evaluator natively, and +optionally runs the bootstrap Omega compiler on its fixture: ```sh python3 tests/bootstrap/independent/successor_test.py --omega @@ -231,28 +220,25 @@ python3 tests/bootstrap/independent/successor_test.py --omega python3 tests/bootstrap/independent/successor_test.py --reuse-constructed --omega ``` -Default execution first repeats the cold construction above. Reuse does not -invoke another compiler; it accepts only the retained reference construction -whose exact source and executable match. The retained differential Gamma -evaluator must also match a freshly stamped image of the audited Alpha seed -and the bound Gamma tape reconstructed during cold construction. This extra -stamping is an identity check, not a semantic construction shortcut. The test -compiles Delta to native ELF, -compares its real Bytes-transformer receipt with the constructed Gamma evaluator, -and executes the native receipt on empty, ASCII and all-byte inputs. Native Delta -then reconstructs the bound canonical Epsilon Gamma receipt, and native Gamma -compiles that receipt to ELF. Existing Console exit/stdin/trap/refusal and -malformed-envelope controls run unchanged. Both peers share these actual -customers; the compiled VM peer retains Alpha stamping by default. - -This is a construction steppingstone: Epsilon remains the existing evaluator, -including its explicitly documented [implementation profile](../../../bootstrap/epsilon/interpreter/README.md). -The bootstrap compiler's Epsilon source still executes through that evaluator. -These results do not establish a standalone compiled bootstrap compiler, the -full normative Epsilon language, or an Omega compiler self-rebuild. - -A retained-source-constructed-compiler run passed all those customers and the -Omega fixture with these identities: +By default this repeats the cold build. `--reuse-constructed` verifies that the +saved reference compiler matches its source and ELF hashes instead of invoking +another compiler, and verifies the saved Gamma evaluator against a freshly +stamped image of the Alpha seed and Gamma tape. The test compiles Delta to +native ELF, compares its Bytes-transformer output with the Gamma evaluator, and +runs the native output on empty, ASCII, and all-byte inputs. Native Delta then +rebuilds the pinned Epsilon Gamma output, and native Gamma compiles it to ELF +and runs all Console exit, stdin, trap, refusal, and malformed-envelope tests. +Both routes share these inputs; the compiled VM route stamps Alpha tapes by +default. + +This is a steppingstone: Epsilon still runs via the existing evaluator and its +[implementation profile](../../../bootstrap/epsilon/interpreter/README.md), and +the bootstrap compiler still runs inside that evaluator. These results do not +prove a compiled bootstrap compiler, full Epsilon support, or an Omega +self-rebuild. + +A run reusing the source-built native compiler passed all stages and the Omega +fixture with these hashes: | Subject | Bytes | SHA-256 | | --- | ---: | --- | @@ -263,124 +249,105 @@ Omega fixture with these identities: | Exact Epsilon/Omega request | 734,042 | `326a8730e5aacf0880e638adaf16ecadbc5ae367c1318316d0885e001bba9e02` | | Emitted Omega Alpha program | 50 | `7f22a6c26b9c2876da3ccba9c62fe1cc071cde61fb31399b0d35fb1fa7ca9cae` | -The Epsilon image exceeds Alpha's 16-MiB seed hole and serves the native backend's -larger image profile. The exact request includes the 714,400-byte bootstrap -compiler (`30e6ea13e8ccab73633af4887dfb3d5ef00d1c25a114f01496aa2290cd6c9511`) -and the existing OCREQ entry. It produced a 55-byte Epsilon observation; the -actual emitted program executed with exit 42 and empty output. That Omega stage -took 41.196 seconds. The largest child RSS across successor construction and -execution was 663,552 KiB. These are individual shared-host functional runs, -not a controlled performance comparison. - -Exact sources, requests, artifacts and stage checkpoints go to ignored -`build/independent-successors/`. The current invocation starts a fresh preflight checkpoint with its PID and -start time before construction or identity checks. The report names passed -stages before starting the next, and marks the complete run passed only after -all requested checks. -A surviving `running` checkpoint is incomplete evidence. Invocation watchdogs -retain the existing customer-specific limits; `--seconds` bounds native Gamma -compilation and the optional Omega observation, while smaller controls retain -60-second process watchdogs. Host processes and resources remain execution -dependencies as documented above. - -The next compiler's source encoder now uses Delta byte literals rather than -packed numeric text templates. Run its facility and actual encoder controls -with `successor_test.py --literals` (and optionally `--omega`). The encoder -consumes existing semantic name/input records; this remains an encoding module, -now used by the checked scalar lowering below. Its emitted Delta function is compiled -to native code and executed; generated-function runtime needs shared semantic -types, not the Epsilon parser or expression/state dispatcher. - -The changed Delta closure is 151,525 bytes, -`de94946dd946c90c3311dba52aa4622a3c80a18866d5483531de1312cc62e0c6`. -Its native ELF is 3,984,546 bytes, -`fce5a6eb20973f6801309579b336b111e38d22d1cedb388b2fa35b4f86671a39`; -source-owned Alpha construction produced 1,219,139 tape bytes, -`6fde052af5b348f3b83f29635aaaedbd6959343352da3a3af1442000a102b1d0`, -matching the independent development producer. A focused all-escape/1,024-byte -literal and malformed twin agreed byte for byte through the selected Gamma -evaluator and Alpha Delta; the positive generated program also executed as -Alpha. Seven literal positives, ten malformed literals, three role/type refusals, -and the actual encoder/compiled-output controls passed. Existing frontend, -request, and Alpha customer controls passed; the canonical Epsilon receipt, -native Epsilon image and Omega fixture artifact above remained byte-identical. -These observations do not discharge the auditability debt or the existing open -whole-compiler cumulative arena-containment obligation. +The Epsilon ELF exceeds Alpha's 16 MiB hole and relies on the native backend's +larger limit. The request packs the 714,400-byte bootstrap compiler +(`30e6ea13e8ccab73633af4887dfb3d5ef00d1c25a114f01496aa2290cd6c9511`) and the +OCREQ entry, producing a 55-byte result whose emitted program exited 42 with +empty output. That Omega step took 41.196 seconds; peak child RSS across the +run was 663,552 KiB (shared-host test run, not a benchmark). + +Inputs, artifacts, and stage checkpoints go to ignored +`build/independent-successors/`. Each run writes a fresh preflight checkpoint +with its PID and start time, logs each completed stage, and marks the run passed +only when every requested check finishes. A leftover `running` checkpoint means +the run did not finish. `--seconds` bounds native Gamma compilation and the +optional Omega run; smaller checks keep 60-second timeouts. + +The next compiler's source encoder now emits Delta byte literals instead of +packed numeric text templates. Run its tests with `successor_test.py --literals` +(optionally with `--omega`). The encoder reads existing semantic name/input +records and is used by the scalar lowering below. Its generated Delta function +compiles to native code and runs using only shared semantic types—no Epsilon +parser or dispatcher. + +The updated Delta bundle is 151,525 bytes +(`de94946dd946c90c3311dba52aa4622a3c80a18866d5483531de1312cc62e0c6`). Its native +ELF is 3,984,546 bytes +(`fce5a6eb20973f6801309579b336b111e38d22d1cedb388b2fa35b4f86671a39`), and the +source-built Alpha tape is 1,219,139 bytes +(`6fde052af5b348f3b83f29635aaaedbd6959343352da3a3af1442000a102b1d0`), matching +the independent development compiler. An all-escape 1,024-byte literal and its +malformed twin matched byte for byte on the Gamma evaluator and Alpha Delta, +and the valid output ran on Alpha. Seven valid literals, ten malformed literals, +three role/type rejections, and all encoder tests passed, while the canonical +Epsilon output, native Epsilon binary, and Omega fixture stayed byte-identical. +These runs do not settle the auditability debt or whole-compiler arena-containment +requirements. The [shared native correspondence record](compiled-alpha.md#native-epsilon-correspondence-for-the-same-storage-customer) -now includes the full frozen SourceUnit storage customer through this same -native Epsilon evaluator: all 13 executable artifacts and 36 refusals matched -the Alpha VM observation. That record owns exact input/artifact provenance, -reused-runtime disclosure, allocation samples and shared-host timing limits; -it is stronger evaluator workload evidence, not compiled-Epsilon or Omega -self-rebuild acceptance. +also covers the frozen SourceUnit storage suite on this same native Epsilon +evaluator: all 13 runnable tapes and 36 rejections matched the Alpha VM run. +That page records exact hashes, reused-binary details, allocation samples, and +timing limits; it is evaluator test coverage, not compiled-Epsilon or Omega +self-rebuild proof. ## Checked Epsilon compilation -`successor_test.py --compile-epsilon --literals --omega` constructs a -Delta-written compiler using the source-constructed native predecessors, then -compiles and executes the complete unchanged production -`source-to-tokens/byte_classes.epsilon` with its `OmegaNumericBase` declaration. This is a compiled source -customer: the generated executable contains direct functions and lifted states, -with no Epsilon parser, checker, expression tree or AST dispatcher in its runtime. -The default invocation repeats cold construction; `--reuse-constructed` retains -the earlier explicitly checked reuse meaning. - -The compiler first applies the complete existing Epsilon body-checking boundary, -including its [legacy arm-return admission profile](../../../bootstrap/epsilon/interpreter/README.md). -It then lowers -every machine and state body, including unreachable bodies. The current pure -capability is scalar and payload-free enum parameters, literals, checked scalar -operators, free calls, scalar returns, and scalar or explicitly exhaustive enum -state transitions. Parameter identity and call/control -identity come from the checker's retained records. Storage reads/writes, -receiver access, Console operations, payload-bearing sums, enum returns, -enum wildcards, arrays, views and ordinary statements -remain explicit `unsupported` results. Invalid source returns `rejected` with -the existing reason and packed offset; contradictions return `internal`. -Success is `compiled` followed by a newline and one complete Delta module. -Rejected, unsupported and internal responses contain no module. This is an experimental module compiler, -not a standalone compiled bootstrap compiler or full Epsilon implementation. - -Pure functions use direct `Int` parameters under the checked Epsilon scalar -contract and a named scalar/resultless/trap/internal outcome. Literal and typed -parameter reads lower directly; operations that can trap retain outcome -propagation and short-circuit evaluation order. The shared Epsilon I32 helpers -own overflow, division, remainder, shifts and bitwise meaning. Delta primitive -failure is not an Epsilon trap. The storage runtime wraps these scalar results -when a stored expression uses one of the shared arithmetic leaves. Omega's -full-u64 `Wrapping` customers are not implemented by this I32 capability. -Named `EvaluateBoth`, `ShortOnTrue` and `ShortOnFalse` compiler cases express -eager and short-circuit control. - -Extracting the shared binary operator and scalar outcome declarations preserved -the 617,354-byte Epsilon source and the canonical Gamma and native evaluator -artifacts measured for that experiment. +`successor_test.py --compile-epsilon --literals --omega` builds a Delta-written +Epsilon compiler using the source-built native tools, then compiles and runs +the unchanged production `source-to-tokens/byte_classes.epsilon` with its +`OmegaNumericBase` declaration. The generated binary contains direct functions +and lifted states, with no Epsilon parser, checker, expression tree, or AST +dispatcher. By default it runs a cold build; `--reuse-constructed` verifies and +reuses the saved predecessors. + +The compiler runs the full Epsilon body checker first, including its +[legacy arm-return rules](../../../bootstrap/epsilon/interpreter/README.md), +then lowers every machine and state body (including unreachable ones). Pure +mode handles scalar and payload-free enum parameters, literals, checked scalar +ops, free calls, scalar returns, and scalar or exhaustive enum transitions, +using the checker's saved parameter and call records. Storage reads/writes, +receiver access, Console ops, payload sums, enum returns, enum wildcards, +arrays, views, and statements return `unsupported`. Invalid source returns +`rejected` with the reason and offset; internal contradictions return +`internal`. Success returns `compiled`, a newline, and a complete Delta module; +error responses emit no module. This is an experimental module compiler, not a +complete Epsilon or bootstrap compiler. + +Pure functions take direct `Int` parameters and return a scalar, resultless, +trap, or internal outcome. Literals and parameter reads lower directly; trapping +ops preserve outcome propagation and short-circuit order. Shared Epsilon I32 +helpers handle overflow, division, remainder, shifts, and bitwise ops (Delta +primitive failure is not an Epsilon trap). The storage runtime wraps these +scalar results when stored expressions call shared arithmetic leaves. Omega's +64-bit `Wrapping` operations are outside this I32 subset. Compiler cases +`EvaluateBoth`, `ShortOnTrue`, and `ShortOnFalse` express eager and +short-circuit evaluation. + +Extracting shared binary operators and scalar outcomes kept the 617,354-byte +Epsilon source and its canonical Gamma and native evaluator outputs unchanged. The [test source packer](../../../tests/bootstrap/independent/epsilon/composition.py) -takes whole files from the verified Epsilon manifest in declaration order. -The Epsilon-to-Delta compiler uses the source view, representations, lexer, -parser and checker. Its literal emitter also uses the byte decoder in -`execution/views/strings.delta`. The reference evaluator includes the -remaining execution functions and its entry. Compiled programs receive the runtime files required by -their calling convention. The Delta compiler checks each assembled program. - -The PR2737 scalar milestone first compiled four lexical machines. An initial implementation threaded generic runtime values and stores through -every scalar node. Its lexical target was 123,827 Delta source bytes and -5,308,895 native bytes, with 68,837 bytes of fixed runtime. The direct scalar -lowering reduced the marginal generated functions to 11,105 bytes and the -native target to 882,941 bytes; its shared runtime is 5,429 bytes. These are -source/artifact sizes, not runtime speed measurements. Exact current identities, -requests, Gamma receipts, images and observations are retained in -`build/independent-successors/compiled-epsilon/`. - -The focused customer checks all 256 byte values against the canonical Epsilon -evaluator and an independent expected observation. Twenty scalar controls cover -call/state arguments, I32 overflow, division/remainder traps, shift bounds, -logical guards/short-circuiting, scalar transition fallthrough, comparisons and -bitwise operations. Invalid-name and valid unsupported twins cover refusal -publication; empty input and byte 255 distinguish EOF. These controls do not discharge the native auditability debt above -or the remaining path through actual storage/Console customers, the complete -bootstrap compiler, shared Omega compiler and Omega self-rebuild. +concatenates whole files from the Epsilon manifest in order. The Epsilon-to-Delta +compiler includes the source view, representations, lexer, parser, checker, and +(for literals) the byte decoder in `execution/views/strings.delta`. The +reference evaluator adds the execution functions and entry; compiled programs +link the runtime files for their calling convention, and Delta checks every +assembled program. + +The PR2737 scalar milestone first compiled four lexical machines. An early +prototype threaded generic values and stores through every scalar node (123,827 +Delta bytes, 5,308,895 native bytes, 68,837-byte runtime). Direct scalar +lowering cut the generated functions to 11,105 bytes, the native ELF to 882,941 +bytes, and the shared runtime to 5,429 bytes (size measurements only, not speed +benchmarks). Outputs stay under `build/independent-successors/compiled-epsilon/`. + +The lexical test checks all 256 byte values against the Epsilon evaluator and +expected bytes. Twenty scalar tests check call/state arguments, I32 overflow, +division/remainder traps, shift bounds, logical guards and short-circuiting, +scalar transition fallthrough, comparisons, and bitwise ops. Invalid-name and +unsupported twins verify error output; empty input and byte 255 distinguish EOF. +These tests do not close native auditability debt or the remaining path to +storage/Console code, the full bootstrap compiler, and Omega self-rebuilds. | PR2737 scalar artifact (historical) | Bytes | SHA-256 | | --- | ---: | --- | @@ -390,38 +357,32 @@ bootstrap compiler, shared Omega compiler and Omega self-rebuild. | Generated lexical functions | 11,105 | `feb75abbca7ec4ad5d97a676f2e065edfab3c9f5e7bdcc03d5d10ade71b7a5ea` | | Lexical native ELF | 882,941 | `d54ea84617373d07691ea6d8bf166e78d10ace940a39c3c1fce9c679ca43aac7` | -Validation retained the complete cold run, including native/Alpha compiler -controls and the Omega fixture. Final shared-file separators were revalidated -with explicit predecessor reuse, and the named-control refinement repeated the -focused compiled customer and all its controls. The last focused run took -45.526 seconds with 716,928 KiB maximum child RSS on the shared host. Cold native -compiler construction took 149.653 seconds and rebuilt byte-identically twice. -These observations are functional receipts, not controlled speed comparisons. - -The next customer includes all five production lexical machines (2,520 bytes) -and the exact 100-byte `OmegaNumericBase` declaration. It accepts raw ASCII -scalar values: binary `48..49`, octal `48..55`, decimal `48..57`, and hexadecimal -also `65..70` and `97..102`. The source-Psi helper has the same predicate on -the tested `0..255` range, while its `u32 in Trapping` domain remains distinct -from Epsilon's `i32` domain. Test adapters retain their own observation wires. - -The compiler emits named Delta enum declarations and direct matches. Typed -callee parameters guide argument lowering, including enum transport through -machine parameters, lifted states and free calls. Generated parameter/state -names retain authored names plus lexical coordinates, such as -`ep_local_1407_base` and `ep_state_1655_binary`. Nominal declarations precede -target functions even when the authored Epsilon declaration follows them. -Composition concatenates complete owners; it performs no host AST extraction. - -All 256 raw bytes across four bases and 1,024 forwarded cases agree between -native, source-owned Alpha, canonical Epsilon and independent expected output. -Empty-input and byte-255 controls distinguish EOF. Two negative sources reject -as `TypeMismatch`: distinct owners with identical case spellings, and enum -equality under Epsilon's scalar-only comparison rule. Three reference-valid -sources return `unsupported` for payloads, enum returns and enum wildcards, -without emitting partial type/function text. Wildcard expansion remains a -deliberate boundary; explicit exhaustive matches lower each continuation once. -This customer exercises no storage/default initialization. +Validation included a full cold run (native/Alpha compiler checks and the Omega +fixture), followed by reused-predecessor runs for final file-separator and +control changes. The last focused run took 45.526 seconds with 716,928 KiB peak +child RSS; cold native compiler construction took 149.653 seconds and rebuilt +byte-identically twice (functional runs, not speed comparisons). + +The next test adds all five production lexical machines (2,520 bytes) and the +100-byte `OmegaNumericBase` enum. It checks raw ASCII scalars: binary `48..49`, +octal `48..55`, decimal `48..57`, and hex adding `65..70` and `97..102`. The +source-Psi helper matches on `0..255`, though its `u32 in Trapping` domain +differs from Epsilon's `i32`. Test adapters keep their own output formats. + +The compiler emits named Delta enums and direct matches. Callee parameter types +drive argument lowering across machine parameters, lifted states, and free +calls. Generated names keep source names plus offsets (such as +`ep_local_1407_base` and `ep_state_1655_binary`), and nominal declarations are +emitted before functions even when declared later in Epsilon. Composition joins +whole source files without host AST extraction. + +All 256 bytes across four bases and 1,024 forwarded cases match across native, +Alpha, Epsilon evaluator, and expected bytes; empty input and byte 255 verify +EOF. Two negative cases fail with `TypeMismatch` (different enums with the same +case name, and enum equality under Epsilon's scalar-only rule). Three valid +sources return `unsupported` (payloads, enum returns, and enum wildcards) with +no partial output; exhaustive matches avoid duplicating continuations. This +test uses no storage or default initialization. | Complete lexical customer artifact | Bytes | SHA-256 | | --- | ---: | --- | @@ -432,43 +393,38 @@ This customer exercises no storage/default initialization. | Alpha tape | 403,669 | `e92be2d814063d4e84e8f3a79f7c73f823f31a445eff80dec6027eefcccbf3f4` | | Complete observation | 3,072 | `ff892de42bfed3f900a8adc303fa93a1f2cf91f6033986638e49ea36bc9d1597` | -The 5,429-byte arithmetic runtime remains unchanged. Source, requests, receipts, -images, refusals and the final invocation report remain under -`build/independent-successors/compiled-epsilon/`. The next construction boundary -is the actual receiver/storage operations used by the bootstrap compiler; -neither this module nor its successful controls completes Epsilon or the whole -bootstrap/Omega self-rebuild goal. - -The final invocation used `--reuse-constructed --literals --compile-epsilon ---omega`, explicitly checking retained cold predecessor identities. Source-closure -and Epsilon identity/refusal gates, the updated literal encoder, all scalar and -nominal controls, unchanged canonical Epsilon artifacts, and the Omega smoke -fixture passed. It took 166.949 seconds with 748,544 KiB maximum child RSS on the -shared host. Earlier cold receipts remain historical evidence for their exact -sources; this invocation does not claim a new cold seed run or controlled timing. +The 5,429-byte arithmetic runtime stayed unchanged, and outputs remain in +`build/independent-successors/compiled-epsilon/`. The next step is receiver and +storage operations used by the bootstrap compiler; this module does not finish +Epsilon or Omega self-rebuilds. + +That run used `--reuse-constructed --literals --compile-epsilon --omega` after +verifying saved cold predecessor hashes, passing all source-bundle, identity, +literal, scalar, nominal, canonical Epsilon, and Omega smoke checks in 166.949 +seconds with 748,544 KiB peak child RSS. Earlier cold results stay tied to their +own sources. Receiver methods and views now compile to direct Delta functions over the -existing Epsilon storage primitives. The complete 23,678-byte production -`request_and_utf8.epsilon` owner, including all ten request framing, structure -and UTF-8 machines, constructs a standalone native program. Its six request -and Unicode observations agree exactly with the constructed Epsilon evaluator. - -Parameters and local variables have live homes. Lifted states retain machine -parameter homes and the ultimate array roots borrowed by transferred views. -Assignments evaluate the destination before the value; call arguments retain -their snapshots and order. Record and array copies, indexing, slices, lengths, -short circuiting and the three byte/exit Console primitives share the reference -runtime's leaf operations. Generated programs contain no source parser or AST -execution dispatcher. The supplied runtime declarations still include syntax -types required by their shared metadata representation. - -Each statement has a named tail continuation carrying home identifiers and -effects. This prevents both duplicated successor text and excessive expression -nesting; the seed's existing expression-depth bound remains unchanged. A -300,000-transfer native execution retains a local array through a view and -exits 42 with the expected output. It takes 14.968 seconds and peaks at -1,058,456 KiB in this observation. This exercises tail control, not bounded -heap usage: the common persistent storage implementation still allocates. +Epsilon storage primitives. The full 23,678-byte production +`request_and_utf8.epsilon` (ten request framing, structure, and UTF-8 machines) +compiles to a standalone native binary whose six request and Unicode outputs +match the Epsilon evaluator byte for byte. + +Parameters and locals get live storage homes, and lifted states keep machine +parameter homes plus the backing array roots of transferred views. Assignments +evaluate the destination before the value; call arguments preserve snapshots and +evaluation order. Record and array copies, indexing, slices, lengths, +short-circuiting, and the three Console byte/exit ops share the reference +runtime's leaf functions. Generated binaries include no parser or AST +dispatcher, though the runtime still includes syntax types needed for shared +metadata. + +Each statement lowers to a named tail continuation carrying live homes and +effects, preventing code duplication and deep expression nesting within the +seed's expression-depth limit. A 300,000-transfer native stress test keeps a +local array live through a view and exits 42 with expected output in 14.968 +seconds (1,058,456 KiB peak RSS). This verifies tail control, not bounded heap +use—the shared persistent store still allocates. | Receiver construction artifact | Bytes | SHA-256 | | --- | ---: | --- | @@ -477,214 +433,182 @@ heap usage: the common persistent storage implementation still allocates. | Request/UTF8 test program source | 61,490 | `f3337980f94a8e0043de63d137ac4920983df537477c18540027562833067eb3` | | Request/UTF8 native ELF | 61,440,709 | `db153206dad893ac51a2137a4bef9ee8620e4f2f0ea6de1b7ad426b2b4419c2a` | -The full invocation repeats the scalar and nominal controls, including the -unchanged Alpha lexical artifact, then compares six production-module and three -storage observations against the constructed evaluator. The storage program -also checks parameter mutation, argument snapshots, sibling fields, record and -array copies, live view backing, and preserved output on bounds traps and EOF. -Its longer native transfer path is a separate stress observation. Receipts are -under `build/independent-storage-blocks/`; retained earlier failures show the -successor-duplication and expression-depth defects that these continuations fix. -Final source cleanup reproduces the same tested compiler and customer native -images, with distinct source receipts recorded there. - -This invocation explicitly reuses the verified cold Gamma, Delta and Epsilon -predecessors. Extracting shared primitive leaves preserves the complete -617,354-byte evaluator source and its previously constructed artifact. It adds -no compiler or assembler to the construction seed. Valid source outside the -implemented calling conventions still produces an explicit unsupported result -with no partial module. The full 808,585-byte bootstrap compiler construction -source now reaches the lexer's nominal diagnostic parameter at coordinate -64,677, beyond the previous first slice parameter at 38,291. Nominal values in -stored methods and Console text output remain subsequent implementation work; -this is a completed receiver/view capability, not an Omega compiler self-build. +The full run repeats all scalar and nominal checks (including the Alpha lexical +tape), then compares six production-module and three storage cases against the +evaluator—testing parameter mutation, argument snapshots, sibling fields, +record/array copies, live views, and preserved output on bounds traps and EOF. +Results live in `build/independent-storage-blocks/` alongside earlier failure +logs showing the duplication and depth bugs fixed by continuations. Final source +cleanup reproduced the same compiler and target binaries. + +This run reuses verified cold Gamma, Delta, and Epsilon binaries; extracting +shared leaf functions kept the 617,354-byte evaluator source and binary +unchanged and added nothing to the seed. Valid code outside supported calling +conventions still returns `unsupported` with no partial output. On the full +808,585-byte bootstrap compiler source, compilation now reaches the lexer's +nominal diagnostic parameter at byte 64,677 (up from the first slice parameter +at byte 38,291). Stored nominal values and Console text output remain to do. ### Passing values into receiver methods and states -The compiled Epsilon lexer can now pass its diagnostic code through a method -and retain it while transferring to two states. A receiver method or state -takes an immutable snapshot of each argument, in source order, then allocates -its parameter homes. The same operation carries records, arrays, sums and -views. A view still refers to its original backing array. At this checkpoint a free function -taking a Delta enum could receive a checked nullary constructor directly. - -On the 825,064-byte bootstrap compiler and construction entry at -`b95769558667` (SHA-256 -`48f1b654605d1828c37af6e4472f2135367ecad1fc2435f2ef4919d862ab855f`), -the native compiler previously stopped at the diagnostic parameter of -`OmegaLexScan::reject`, byte 64,899. It now reaches byte 66,755, where -`set_keyword` passes the constructed `OmegaTokenKind::Keyword` to `emit`. -At this checkpoint, the compiler stopped before constructing that receiver argument. +The compiled Epsilon lexer can now pass its diagnostic code into a method and +preserve it across two state transfers. A receiver method or state snapshots +each argument in source order, then allocates parameter homes—handling records, +arrays, sums, and views (views keep their original backing array). At this +checkpoint a free function taking a Delta enum could receive a checked nullary +constructor directly. + +On the 825,064-byte bootstrap compiler and entry at `b95769558667` (SHA-256 +`48f1b654605d1828c37af6e4472f2135367ecad1fc2435f2ef4919d862ab855f`), the native +compiler advanced from the diagnostic parameter of `OmegaLexScan::reject` (byte +64,899) to byte 66,755, where `set_keyword` passes a constructed +`OmegaTokenKind::Keyword` to `emit`. `python3 tests/bootstrap/independent/successor_test.py --reuse-constructed --compile-epsilon` -uses the verified native predecessors to exercise argument passing. The storage -fixture passes a record as its first argument, mutates that same record in a -later argument, and checks the original value after a state transfer. The unchanged -lexer methods also run both valid and invalid diagnostic spans. The wrong-owner -twin substitutes the scanner's token kind for its diagnostic code. +tests this using verified native predecessors: passing a record as the first +argument, mutating it in a later argument, and verifying the original value +after a state transfer, plus running the lexer methods with valid and invalid +diagnostic spans (the wrong-owner twin passes a token kind as a diagnostic code). ### Constructing a lexer token kind -The native Epsilon compiler now constructs the lexer's `OmegaTokenKind::Keyword` -in a receiver call. A runtime sum carries its resolved case and payload. The -case's exact source span identifies its declaration within the checked source. -A transition checks that the case belongs to its expected owner before it reads -the payload. This removes the separate owner declaration from every stored sum. - -The lexer fixture runs the production `set_keyword` and `emit` methods. Its -compiled method returns the stored token kind, and the target driver checks the -start and end of the authored `Keyword` case. Substituting another owner's -`As` constructor produces the same type error in the native compiler and the -source-built evaluator. A receiver can also return an array snapshot after its -parameter homes are released. Constructing a case with payload arguments in a -compiled receiver still reports the source coordinate. - -At this checkpoint the 825,064-byte compiler at `b95769558667` reached byte 67,414. The -834,350-byte compiler at `720b1a10712f` reaches byte 67,681. Both stop at the -same string literal, `"as"`, passed to `span_equals`. The shared evaluator -packs to 616,982 bytes, down from 617,419. +The native Epsilon compiler now constructs `OmegaTokenKind::Keyword` inside a +receiver call. Runtime sums store their resolved case span and payload; before +reading a payload, a transition checks that the case belongs to the expected +enum, removing the separate owner record from every stored sum. + +The lexer test runs production `set_keyword` and `emit`, returns the stored +token kind, and checks the start and end offsets of `Keyword`. Passing another +enum's `As` case produces the same type error in both the compiler and +evaluator. Receivers can also return array snapshots after freeing parameter +homes. Payload constructors in compiled receivers still report their source +offset as unsupported. + +At this checkpoint the 825,064-byte compiler at `b95769558667` reached byte +67,414 and the 834,350-byte compiler at `720b1a10712f` reached byte 67,681—both +stopping at the `"as"` string literal passed to `span_equals`. The packed +evaluator shrank from 617,419 to 616,982 bytes. ### Compiling the keyword classifier’s string literals -The native Epsilon compiler compiles the complete `OmegaLexScan::classify_keyword` -method. Its calls to `span_equals` receive immutable views of the authored -strings. The emitted Delta preserves ordinary quoted spellings, including -shared escapes. For Epsilon’s hexadecimal escape it decodes the string with -the checked evaluator’s decoder and emits a balanced tree of ordinary -`bytes_single` and `bytes_concat` expressions. - -The compiled lexer stores the authored cases `As` and `Copy` for those two -keywords and classifies `aside` as an identifier. The same fixture checks empty and sliced literal -views and a bounds trap. A separate compiled program writes all 256 values of a -hex-escaped literal. Its complete output agrees with the constructed evaluator. - -On the frozen 825,064-byte source at `b95769558667`, compilation advances from -byte 67,414 to 85,007, where `OmegaLexScan::consume_digits` passes the stored -`self.numeric_base` to the free function `omega_digit_in_base`. The compiler’s -composed Delta grows from 760,383 to 762,106 bytes. The storage runtime grows -by 393 bytes. The experiment composes that runtime and a driver with the emitted -module before Delta and Gamma construct the target executable. +The native Epsilon compiler now compiles the full `OmegaLexScan::classify_keyword` +method, passing immutable string views to `span_equals`. Ordinary quoted strings +and shared escapes emit directly as Delta strings; Epsilon hex escapes decode +through the evaluator's decoder into a balanced tree of `bytes_single` and +`bytes_concat` calls. + +The compiled lexer produces `As` and `Copy` for those keywords, classifies +`aside` as an identifier, tests empty and sliced views plus a bounds trap, and +a separate compiled program writes all 256 byte values from a hex-escaped +literal matching the evaluator byte for byte. + +On the frozen 825,064-byte source at `b95769558667`, compilation advanced from +byte 67,414 to 85,007, where `OmegaLexScan::consume_digits` passes +`self.numeric_base` to the free function `omega_digit_in_base`. The compiler's +Delta source grew from 760,383 to 762,106 bytes and the storage runtime grew by +393 bytes; the harness links the runtime and driver with the emitted module +before compiling through Delta and Gamma. ### Calling the numeric lexer with a stored enum -The native Epsilon compiler uses one calling convention throughout a module -with a nonempty receiver machine. Each machine receives immutable argument values, allocates -mutable homes, and carries the current store and output. Receiver methods -also receive the authored receiver's place. Free machines take no receiver. -Pure modules continue to use direct scalar functions and named Delta enum -types, including the Alpha-tape lexical customer. - -A stored nominal transition evaluates its subject once. An explicit nullary -case must match both endpoints of a member of the checked declaration. A sparse -zero with no children selects the first member when its owner matches the -declaration. Compiled type descriptors retain use-site coordinates and the -declaration’s name span, including after an array copy. The compiler also -checks the absence of payloads. The selected -member's source start identifies its arm. These checks precede the wildcard -so an invalid runtime value yields an internal diagnostic. - -The production `consume_digits` and `scan_number` methods now run with their -authored calls to `omega_digit_in_base`. The scanner fixture checks all four -bases, an exponent, a missing exponent and a hex integer. A second argument -mutates the field read by the first argument. A copied array passes through a -free machine and keeps its original value. The constructed evaluator agrees -with the compiled entry. A same-spelling case from a different owner fails -source checking at the call. The target-interface controls also supply -malformed cases, wrong owners and children on sparse values. - -Two prototypes used the same 44,706-byte scanner and target driver at -`7c9569ea1d7`. Both passed the scanner and all twelve direct target-interface -controls. The typed adapter preserved the named Delta enum across free calls. -The shared convention compiled free machines in the storage module with the -same store and output as methods. +Modules with a nonempty receiver machine now share one calling convention: each +machine takes immutable arguments, allocates mutable homes, and threads the +current store and output; receiver methods also take the receiver's place, while +free machines do not. Pure modules keep direct scalar functions and named Delta +enums (including the Alpha-tape lexical test). + +A stored nominal transition evaluates its subject once. Explicit nullary cases +must match both endpoints of a declared member; a sparse zero with no children +picks the first member when the owner matches. Compiled type descriptors keep +use-site coordinates and the declaration's name span (even after array copies), +and check that no payload is attached. These checks run before any wildcard so +invalid runtime values report an internal error. + +Production `consume_digits` and `scan_number` now run with their calls to +`omega_digit_in_base`. The scanner test checks all four bases, exponents, +missing exponents, hex integers, argument-order mutation, and copied arrays +passed to free machines, matching the evaluator. A same-named case from another +enum fails type checking, and direct interface tests pass malformed cases, wrong +owners, and children on sparse values. + +Two prototypes ran on the 44,706-byte scanner and driver at `7c9569ea1d7`, both +passing the scanner and all twelve interface checks. The typed adapter kept +named Delta enums across free calls; the shared convention compiled free +machines with the same store/output convention as methods. | Prototype | Compiler Delta source | Generated scanner module | Native scanner with test driver | | --- | ---: | ---: | ---: | | Typed adapter | 766,900 bytes | 216,890 bytes | 13,121,786 bytes | | Shared storage calling convention | 762,566 bytes | 274,206 bytes | 17,512,547 bytes | -For the complete 54,840-byte numeric scanner, native-hosted and Alpha-hosted -Gamma compilers both constructed the same 11,912,696-byte Alpha tape -(SHA-256 `3848a7ed048f4f8a96e03b760526b95f4706872b527715dde94b925c5124527b`). -It left 4,864,516 bytes in the unchanged seed. The tape and the 38,193,583-byte -native executable matched on all thirteen inputs, including the malformed -target values. The constructed Epsilon evaluator and the independent model -also ran the authored scanner to exit 42. - -With the representations at `1830ef8ec8e`, the repository fixture has 55,030 -source bytes. Its 38,264,464-byte native executable also passes the authored -entry and thirteen direct value controls. - -The landed compiler also handles the checked wildcard and gives free machines -their own receiver-free signature. Its Delta composition is 763,595 bytes. -The storage runtime is 93,995 bytes. The pure runtime is 5,429 bytes. -On the frozen 825,064-byte compiler at `b95769558667`, the previous compiler -stopped at byte 85,007. A control inserts one known unsupported constructor -after the frozen lexer's last machine at byte 108,029. The new compiler reaches -that constructor at byte 108,141. The lexer itself is unchanged. The complete -numeric scanner also compiles and runs as a separate executable. [Scanner -fixture](../../../tests/bootstrap/independent/epsilon/lexer_digits_main.epsilon) +For the 54,840-byte numeric scanner, native and Alpha Gamma compilers both +emitted the same 11,912,696-byte Alpha tape (SHA-256 +`3848a7ed048f4f8a96e03b760526b95f4706872b527715dde94b925c5124527b`, leaving +4,864,516 bytes free in the seed). The tape and the 38,193,583-byte native ELF +agreed on all 13 inputs, including malformed values; the Epsilon evaluator and +independent model also exited 42. + +At `1830ef8ec8e`, the 55,030-byte fixture builds a 38,264,464-byte native ELF +that passes the scanner and all 13 direct value checks. + +The landed compiler adds checked wildcards and receiver-free signatures for free +machines (763,595 Delta bytes, 93,995-byte storage runtime, 5,429-byte pure +runtime). On the frozen 825,064-byte compiler at `b95769558667`, it advances +from byte 85,007 past the last lexer machine at byte 108,029 to an injected +unsupported constructor at byte 108,141 without modifying the lexer. +[Scanner fixture](../../../tests/bootstrap/independent/epsilon/lexer_digits_main.epsilon) ### Public Omega lexer observations -The compiled-Epsilon gate exercises `OmegaLexScan::scan_at` and -`OmegaLexScan::validate_lexical` in the complete production `source-to-tokens/scan.epsilon`. -The customer includes the production lexical classification file, the UTF-8 -validator and its lexical types. For each of 23 input records it reports the -selected token or diagnostic, byte coordinates, decoded length, and the result -of validating the whole source. The cases include malformed UTF-8 after a -valid token, nested comments, invalid escapes and an out-of-range cursor. -The source evaluator and compiled Linux x86-64 program returned the same -465-byte observation, including Epsilon exit 42 (SHA-256 -`7d7a561d217ec1ce599a203fb8290b907c2582883c98dc71541c5bd0633f31aa`). - -`scan_string` has a smaller dependency closure. One emitted Gamma receipt -builds both its Linux x86-64 executable and its Alpha tape. Both and the -source-built evaluator returned the expected 175 bytes across 17 positive -and negative cases. Passing the diagnostic enum to the token classifier -also makes both Epsilon frontends reject the same call offset before code -publication. [Cases and exact output layout](../../../tests/bootstrap/independent/epsilon/lexer_scan_test.py) - -The measured run reused the source-built native Gamma and Delta executables. -Recompiling the current Delta source and the bound evaluator request reproduced -those predecessor artifacts byte for byte. The 610,797-byte Delta-written -Epsilon compiler was rebuilt. Its 795,622-byte Gamma receipt produces a -28,071,326-byte native executable and an 8,947,202-byte Alpha tape. Both -compiler hosts emitted identical Delta for the 16,466-byte string customer -and returned the same wrong-owner refusal at byte 14,793. A separate attempt -to compile the full public source on the Alpha-hosted Epsilon compiler reached -its 600-second wall-clock limit under shared host load before publishing a -module. The string customer's -727,812-byte Gamma receipt produced a 26,900,281-byte native executable and an -8,391,472-byte Alpha tape. - -The 58,733-byte public customer produced a 2,827,892-byte Gamma receipt and -a 103,247,790-byte native executable. Alpha's production compiler returned -249 with empty output for the same receipt. A separate diagnostic copy of its publisher -reported 32,158,739 bytes of computed layout for that receipt. Alpha's -stamped seed accepts 16,777,212 tape bytes. The same diagnostic measured the -smaller string tape at exactly its published length. A later Alpha backend -fits both customers in the fixed seed. The gate now requires both tapes to -execute and reproduce the same observations. [Public lexer on Alpha](compiled-alpha.md#run-the-public-omega-lexer-on-alpha) +The compiled-Epsilon gate runs `OmegaLexScan::scan_at` and +`OmegaLexScan::validate_lexical` from production `source-to-tokens/scan.epsilon`, +along with the production character classes, UTF-8 validator, and lexical types. +Across 23 inputs (including bad UTF-8 after a valid token, nested comments, +invalid escapes, and an out-of-range cursor), it reports token/diagnostic kinds, +byte spans, decoded lengths, and whole-source validation. Both the evaluator and +compiled Linux x86-64 binary returned the same 465 bytes, including Epsilon exit +42 (SHA-256 `7d7a561d217ec1ce599a203fb8290b907c2582883c98dc71541c5bd0633f31aa`). + +`scan_string` has a smaller closure: one Gamma output builds both a Linux +x86-64 ELF and an Alpha tape, and both match the evaluator on all 17 cases (175 +bytes). Passing a diagnostic enum to the token classifier fails at the same call +offset in both frontends before code emission. +[Cases and exact output layout](../../../tests/bootstrap/independent/epsilon/lexer_scan_test.py) + +That run reused source-built native Gamma and Delta binaries (recompiling Delta +and the evaluator matched byte for byte) and rebuilt the 610,797-byte Epsilon +compiler. Its 795,622-byte Gamma output builds a 28,071,326-byte native ELF and +an 8,947,202-byte Alpha tape. Both compiler hosts emitted identical Delta for +the 16,466-byte string scanner and failed at byte 14,793 on the wrong-owner +test. Compiling the full public lexer on the Alpha-hosted Epsilon compiler hit +its 600-second wall-clock timeout under host load. The string scanner's +727,812-byte Gamma output built a 26,900,281-byte native ELF and an 8,391,472-byte +Alpha tape. + +The 58,733-byte public lexer produced a 2,827,892-byte Gamma file and a +103,247,790-byte native ELF. Alpha's older backend exited 249 with empty output +because its calculated layout was 32,158,739 bytes—exceeding the seed's +16,777,212-byte limit (the same diagnostic measured the string tape at its exact +length). A later Alpha backend fits both in the seed, and the gate now requires +both tapes to run and match native outputs. +[Public lexer on Alpha](compiled-alpha.md#run-the-public-omega-lexer-on-alpha) Run `python3 tests/bootstrap/independent/successor_test.py --compile-epsilon` -from the repository root on Linux x86-64. `--reuse-constructed` reuses the -verified Gamma predecessor. Look under `build/independent-successors/compiled-epsilon/` -for the authored sources, emitted Delta, common Gamma receipts, native images, -Alpha tape, input, expected bytes, actual outputs and `result.json`. +from the repository root on Linux x86-64 (pass `--reuse-constructed` to reuse +the verified Gamma binary). Outputs, inputs, images, tapes, and `result.json` +go to `build/independent-successors/compiled-epsilon/`. ### Shared Epsilon continuations and the stock Alpha seed -The compiled public lexer now executes all 23 cases on the stock Alpha seed. -The Linux x86-64 target, Alpha target and source-built Epsilon evaluator -returned the same 465 bytes, including exit 42. The batch checks individual -tokens, whole-source lexical validation and rejection coordinates. +The compiled public lexer runs all 23 cases on the unmodified Alpha seed, +returning the same 465 bytes (including exit 42) across Linux x86-64, Alpha, and +the Epsilon evaluator—checking tokens, whole-source validation, and error +offsets. -The Epsilon compiler emits one successful arm per value, scalar or statement -continuation. The other arm forwards the complete stopped outcome. Shared -Delta functions perform the constructor matching and preserve the exit code, -trap, output prefix or internal source coordinate. The following runs used -the same Epsilon lexer source, input and stock Delta and Gamma predecessors. +The Epsilon compiler emits only the success arm per value, scalar, or statement +continuation and forwards all non-success outcomes through shared Delta helpers +that preserve exit codes, traps, stdout prefixes, and internal coordinates. +Measured on the same lexer source, input, and stock Delta and Gamma compilers: | Public lexer artifact | Earlier lowering | Shared continuations | | --- | ---: | ---: | @@ -694,95 +618,79 @@ the same Epsilon lexer source, input and stock Delta and Gamma predecessors. | Linux x86-64 executable | 103,247,790 bytes | 48,731,647 bytes | | Production Alpha publisher | Exit 249 and empty output | Exit 0 and 15,120,299 tape bytes | -The new Gamma program has SHA-256 -`267f3b49246d8593e9fc467bee36bc3b82715dedb3e3e397e7757e02234cd8d3`. -The Alpha tape has SHA-256 -`c0cf4b55c846f46910f32ed5061416e68b66916e4e500acc09c13496721c50d6`. -The gate now requires both lexer customers to publish runnable tapes and -compares their output bytes with the same expected records as the native -programs. [Public lexer cases](../../../tests/bootstrap/independent/epsilon/lexer_scan_test.py) - -A second customer executes the Omega compiler's state signature checker. Its -146,904-byte Epsilon source retains the production data declarations and 59 -complete machine declarations from checking, layout, lexical scanning and -name resolution. The test supplies a syntax row with one state. The checker -accepts its implicit Unit return and stores type 2. Setting the same row's -explicit return marker without a formed type makes the checker return 0. -The source-built evaluator and 102,548,039-byte Linux executable both emitted -`00 2a 00 00 00 01 02 00`. - -The same 3,315,409-byte Gamma program has SHA-256 -`651e79d34e6484d3c5994571895f729668cc9f512088c8e97bb9d4cfe291083e`. -With the compact Gamma-to-Alpha backend it produces a 15,398,168-byte tape -with SHA-256 `e9343bc5219ff0dd30766b242ba3cc2091f5ca788bdc353741bc6d9cb2c73f0a`. -That tape returned the identical eight bytes on the seed. The customer enters -the checker with prepared syntax. Constructing the full Omega compiler from its -Epsilon sources remains open. [Signature customer](../../../tests/bootstrap/independent/epsilon/signature_main.epsilon) - -The earlier Epsilon compiler emitted 4,013,215 bytes for that same signature -customer, including the storage marker. Its matching runtime and entry made a -4,107,257-byte Delta program. The stock Delta producer admitted the input and -returned status 2 with a 40-byte DCOUT at program byte 3,132,226. Syntax +The new Gamma file has SHA-256 +`267f3b49246d8593e9fc467bee36bc3b82715dedb3e3e397e7757e02234cd8d3`, and the Alpha +tape has SHA-256 +`c0cf4b55c846f46910f32ed5061416e68b66916e4e500acc09c13496721c50d6`. The gate now +requires both lexer tapes to execute and match native outputs. +[Public lexer cases](../../../tests/bootstrap/independent/epsilon/lexer_scan_test.py) + +A second test compiles the Omega compiler's state signature checker (146,904 +Epsilon bytes containing production data types and 59 machines from checking, +layout, lexing, and name resolution). Given a syntax row with one state, the +checker accepts its implicit Unit return (storing type 2) and returns 0 when an +explicit return marker lacks a type. Both the evaluator and the 102,548,039-byte +Linux ELF emitted `00 2a 00 00 00 01 02 00`. + +Its 3,315,409-byte Gamma file (`651e79d34e6484d3c5994571895f729668cc9f512088c8e97bb9d4cfe291083e`) +compiles with the compact Alpha backend to a 15,398,168-byte tape +(`e9343bc5219ff0dd30766b242ba3cc2091f5ca788bdc353741bc6d9cb2c73f0a`) that +produces the exact same eight bytes on the seed. This test feeds prepared syntax +directly; building the full Omega compiler from Epsilon remains open. +[Signature customer](../../../tests/bootstrap/independent/epsilon/signature_main.epsilon) + +Earlier lowering emitted 4,013,215 bytes (4,107,257 Delta bytes with runtime and +entry, SHA-256 `3a726430d1e02a312dba9a8d68ec54331a474f1dab671c5e6ad3bc394ebebbc6`), +causing stock Delta to exit 2 with a 40-byte DCOUT at byte 3,132,226 when syntax storage (space 1, code 7) requested 114,294,800 bytes against a 114,294,752-byte -limit. Shared continuations brought the program to 2,386,951 bytes including -runtime and entry. The same stock Delta producer then published the Gamma -program executed above. The old Delta program's SHA-256 is -`3a726430d1e02a312dba9a8d68ec54331a474f1dab671c5e6ad3bc394ebebbc6`. +limit. Shared continuations cut the Delta program to 2,386,951 bytes, which +compiled cleanly to the Gamma file above. ### Full bootstrap compiler source -A separate run gave the compiled Epsilon frontend the complete 845,978-byte -bootstrap compiler plus its 6,118-byte construction entry. The 852,096-byte -source had SHA-256 `01565beaf9f51478a156fa9b9ca997f5808b06ef39db66a41e4baf644ff59225`. -The stock frontend built from `35e76509787` ran for 1,500 seconds on the -shared host. The revised frontend ran for the last 125 seconds of that same -wall-clock budget. Neither had published a Delta module or diagnostic when -stopped. The unequal budgets leave their relative speed unmeasured. This step -compiles the Epsilon implementation of the bootstrap compiler. Supplying Omega -product source to the resulting compiler would be a subsequent step. +A separate test fed the 845,978-byte bootstrap compiler plus its 6,118-byte +entry (852,096 bytes total, SHA-256 +`01565beaf9f51478a156fa9b9ca997f5808b06ef39db66a41e4baf644ff59225`) to the +compiled Epsilon frontend. The `35e76509787` frontend ran for 1,500 seconds and +the revised frontend ran for the final 125 seconds of that wall-clock budget; +neither produced a Delta module or error before stopping, leaving relative speed +unmeasured. Running Omega source through the resulting compiler would be a +later step. ### Finding checked references while compiling the whole application -The compiled Epsilon frontend reached the stock Delta byte publisher on -the complete 852,096-byte Omega compiler and construction entry described -above. Ordinary publication returned status 254, with empty stdout and -stderr, after 56.45 CPU seconds, 64.86 wall seconds and 3,035,040 KiB peak RSS. -This status identifies a result over the 4 MiB publication limit. It gives -no exact module length. - -On the preceding compiler from `e45acdff0a9`, half-second instruction-pointer -samples on that input located the cost in lowering. The 741 native function -prologues were matched to the 741 function declarations in order in the -source-built Gamma receipt. Between elapsed seconds 50.72 and 150.73, -191 of 200 samples were in reference-list searches or the expression and -pattern identity functions those searches call. The profiler stopped the -original process at 157.84 wall seconds with no output. - -The compiler now builds the interpreter's source-coordinate index once after -checking and queries it for local, field, callable and control references. -The index limits each search to the applicable start coordinate and retains -the original exact identity and lookup order within the bucket. The native -compiler built by the stock predecessors was 28,537,595 bytes, SHA-256 -`414290b92745283ba88be370a5e4342a9aae1e1766734e058da220ef249d72ab`. -The public lexer emitted the same 1,104,979-byte compiled observation as -before. The grouped receiver control checks a call and its projections with -a shared start and an enclosing expression with a different start. +The compiled Epsilon frontend reached Delta's byte publisher on that same +852,096-byte source, exiting 254 (empty stdout/stderr) after 56.45 CPU seconds +(64.86 wall seconds, 3,035,040 KiB peak RSS), indicating the output exceeded the +4 MiB limit without reporting its exact size. + +On the earlier `e45acdff0a9` compiler, half-second IP samples matched against +the 741 function prologues in the Gamma file showed 191 of 200 samples between +50.72s and 150.73s spent in reference-list scans and their expression/pattern +equality helpers (stopped at 157.84s with no output). + +The compiler now indexes references by source coordinate once after checking and +queries that index for local, field, callable, and control lookups while keeping +exact identity and bucket order. The rebuilt native compiler is 28,537,595 bytes +(SHA-256 `414290b92745283ba88be370a5e4342a9aae1e1766734e058da220ef249d72ab`) and +emitted the identical 1,104,979-byte public lexer output. The grouped receiver +test covers a call and projections sharing a start offset inside an outer +expression with a different start. [Stored receiver test](../../../tests/bootstrap/independent/epsilon/storage_main.epsilon) ### Allocation before the parser's first declaration -The Omega parser calls `validate_lexical` on each source unit before parsing -its declarations. A small Epsilon caller passed `self.console.remaining_input` -to that production method and returned `self.scan.accepted`. Another called -only the production UTF-8 validator and returned its `valid` field. Both read -the sealed input directly. [Parser](../../../bootstrap/omega/compiler/parser.epsilon) · [Scanner](../../../bootstrap/omega/compiler/source-to-tokens/scan.epsilon) +The Omega parser runs `validate_lexical` on each source unit before parsing +declarations. Two small Epsilon drivers read `self.console.remaining_input` +directly—one calling `validate_lexical` and returning `self.scan.accepted`, the +other calling only the UTF-8 validator and returning `valid`. +[Parser](../../../bootstrap/omega/compiler/parser.epsilon) · [Scanner](../../../bootstrap/omega/compiler/source-to-tokens/scan.epsilon) -These are Linux peak RSS measurements from native Gamma and Delta and compiled -Epsilon. Both versions ran the same Epsilon bytes, first with the compiler from -`e82b9824a5e`, then with machine parameter homes allocated before the -state-local root floor. Each input was ASCII space except for the marked -substitutions. The UTF-8 caller was 5,125 bytes (`babc79def616…`), and the -lexical caller was 54,857 bytes (`1371b7a16bc8…`). +These Linux peak RSS numbers compare the `e82b9824a5e` compiler with allocating +machine parameter homes before the state-local root floor (using native Gamma +and Delta and compiled Epsilon). Inputs are ASCII spaces except where noted; +the UTF-8 driver is 5,125 bytes (`babc79def616…`) and the lexical driver is +54,857 bytes (`1371b7a16bc8…`). | Caller and input | Earlier peak KiB | Revised peak KiB | Guest exit | | --- | ---: | ---: | ---: | @@ -792,8 +700,8 @@ lexical caller was 54,857 bytes (`1371b7a16bc8…`). | Full lexical validation, 8,192 bytes with first byte FF | 32,308 | 31,320 | 0 | | Full lexical validation, 8,192 bytes with last byte FF | 86,424 | 73,240 | 0 | -The last two inputs have identical lengths and fail in the UTF-8 pass. Moving -the invalid byte to the end exercises more state transfers before returning. -Live Epsilon bindings are released during those transfers, while the generated -Gamma program advances its pair allocation pointer on every allocation. +The last two inputs have the same length and fail in UTF-8 validation; moving +the invalid byte to the end triggers more state transfers. Epsilon bindings are +freed on transfer, while the generated Gamma code still bumps its pair pointer +on every allocation. [State storage](../../../bootstrap/epsilon/compiler/runtime/storage.delta) · [Gamma pair allocation](../../../bootstrap/gamma/compiler/compiler.gamma) diff --git a/wiki/development/bootstrap/windows-x64.md b/wiki/development/bootstrap/windows-x64.md index 9054c77e5fc0..5a9ad2622f31 100644 --- a/wiki/development/bootstrap/windows-x64.md +++ b/wiki/development/bootstrap/windows-x64.md @@ -1,22 +1,22 @@ # Windows x64 bootstrap gate observations -The Alpha, Beta, Gamma, Delta, Epsilon, and `omega-*` bootstrap customer gates ran on Windows 11 Pro x64 through Git Bash from the audited Windows PE Alpha seed (`alpha_x64_windows.exe`) and the admitted Beta compiler tape, with no Wine layer, no Python semantic compiler, and no Rust semantic stage. Every portable and compiled-VM rung from Alpha through Omega `program.omg` (OCREQ V1) and `omega-controls` produced byte-exact artifacts and expected exit statuses on the native Windows host. +The Alpha, Beta, Gamma, Delta, Epsilon, and `omega-*` bootstrap tests ran on Windows 11 Pro x64 under Git Bash from the audited Windows PE Alpha seed (`alpha_x64_windows.exe`) and trusted Beta compiler tape—without Wine, a Python semantic compiler, or any Rust compiler stage. Every portable and compiled-VM stage from Alpha through Omega `program.omg` (OCREQ V1) and `omega-controls` produced byte-exact outputs and expected exit codes natively on Windows. ## Windows Alpha seed lazy-commit repair -The previous Windows PE seed (`e2556e507167…`) called `VirtualAlloc(NULL, 0x2000000000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)` at startup. Unlike Linux `mmap(..., MAP_NORESERVE)` and macOS `mmap`, Windows charges the entire 128 GiB `MEM_COMMIT` allocation against the system commit limit (RAM plus pagefile) before executing a single instruction. On this 128 GiB RAM desktop with an 8 GiB pagefile and ~65 GiB committed by active workloads (~71 GiB free commit), `VirtualAlloc` failed with `ERROR_COMMITMENT_LIMIT` (1455) and trapped at startup (`0xC000001D`, shell exit 132) even on a two-byte `halt` tape. +The earlier Windows PE seed (`e2556e507167…`) called `VirtualAlloc(NULL, 0x2000000000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)` at startup. Unlike Linux `mmap(..., MAP_NORESERVE)` and macOS `mmap`, Windows charges the full 128 GiB `MEM_COMMIT` upfront against the system commit limit (RAM plus pagefile) before running a single instruction. On this 128 GiB desktop with an 8 GiB pagefile and ~65 GiB already committed (~71 GiB free), `VirtualAlloc` failed with `ERROR_COMMITMENT_LIMIT` (1455) and trapped at startup (`0xC000001D`, shell exit 132) even for a two-byte `halt` tape. -`bootstrap/alpha/alpha_x64_windows.hex` now reserves the 128 GiB extent with `VirtualAlloc(NULL, 0x2000000000, MEM_RESERVE, PAGE_NOACCESS)` (zero upfront commit charge) and installs a vectored exception handler (`AddVectoredExceptionHandler`) that demand-commits touched 1 MiB zeroed chunks: +`bootstrap/alpha/alpha_x64_windows.hex` now reserves the 128 GiB region with `VirtualAlloc(NULL, 0x2000000000, MEM_RESERVE, PAGE_NOACCESS)` (zero upfront commit) and installs a vectored exception handler (`AddVectoredExceptionHandler`) that commits touched 1 MiB zeroed chunks on demand: -- Read faults inside `[mem_base, mem_base + 0x2000000000)` use a two-slot `PAGE_READONLY` zero ring (2 MiB maximum commit across all 128 GiB, releasing the older slot via `VirtualFree(..., 0x100000, MEM_DECOMMIT)` and handling unaligned 8-byte reads across 1 MiB boundaries). -- Write faults remove any matching slot from the read-only ring and permanently commit the 1 MiB chunk as `PAGE_READWRITE`. -- Any `VirtualAlloc` or handler registration failure executes `ud2` (`0xC000001D`), preserving the audited startup/runtime Trap surface. +- Read faults inside `[mem_base, mem_base + 0x2000000000)` use a two-slot `PAGE_READONLY` zero ring (at most 2 MiB committed across all 128 GiB, releasing the older slot with `VirtualFree(..., 0x100000, MEM_DECOMMIT)` and supporting unaligned 8-byte reads across 1 MiB boundaries). +- Write faults evict any matching slot from the read-only ring and permanently commit that 1 MiB chunk as `PAGE_READWRITE`. +- Any `VirtualAlloc` or handler-registration failure executes `ud2` (`0xC000001D`), keeping the expected startup and runtime trap behavior. -Re-forged through `cargo xtask alpha-forge`, the container stays 16,782,336 bytes with unchanged PE section layout and `.tape` hole at file offset `0x1400` (5,120), SHA-256 `4bf1f4ebc5d5daf4f4ad5636d8778650c88bc439940223f143e072f8d657fe60`. +Rebuilt with `cargo xtask alpha-forge`, the container stays 16,782,336 bytes with the same PE section layout and `.tape` hole at file offset `0x1400` (5,120), SHA-256 `4bf1f4ebc5d5daf4f4ad5636d8778650c88bc439940223f143e072f8d657fe60`. ## Host environment and prerequisites -All measurements below ran at base revision `4001493820e8772c02f558aed6f511c12cc94f0c` with the lazy-commit Windows Alpha seed and Git Bash portability fixes in this change. +All measurements below ran on base revision `4001493820e8772c02f558aed6f511c12cc94f0c` with the lazy-commit Windows Alpha seed and Git Bash fixes in this change. | Component | Measured environment | | --- | --- | @@ -29,10 +29,10 @@ All measurements below ran at base revision `4001493820e8772c02f558aed6f511c12cc ### Resource prerequisites on Windows x64 -- **Commit charge:** With lazy commit, individual Alpha/Beta/Gamma/Delta/Epsilon runs commit only touched pages (for example, ~14–43 MiB for the Beta-written Gamma interpreter, ~65 MiB for 64 MiB Beta source bounds, ~134 MiB for `program.omg` OCREQ compilation on the Alpha-compiled Epsilon evaluator, and ~1.3 GiB for `--large-alpha`). A 128 GiB free commit limit is no longer required. -- **Disk space:** Temporary `build/` directories hold stamped 16 MiB PE containers per generated executable (~240 MiB for `build/source-gamma-reference`, ~50 MiB per `portable.py` directory, and ~50 MiB for `omega-executable`). Keep at least 1 GiB free when running multiple gates concurrently. -- **Git long paths:** `tests/bootstrap/interpreted/chain-hygiene.sh` initializes a temporary checkout under `%TEMP%`, which pushes nested `source-rust/` paths past Windows `MAX_PATH` (260 bytes) unless `core.longpaths true` is set on the fixture repository. -- **Native tools:** Git Bash provides POSIX `sh`, `dd`, `cmp`, `sha256sum`, and `cygpath`; Windows-native `python3` reads raw Win32 exit DWORDs (`tests/bootstrap/interpreted/alpha/native_exit.py`) and runs `tests/bootstrap/compiled.py` helpers. +- **Commit charge:** Lazy commit charges only touched pages (~14–43 MiB for the Beta-written Gamma interpreter, ~65 MiB for 64 MiB Beta source limits, ~134 MiB for `program.omg` OCREQ compilation on the Alpha-compiled Epsilon evaluator, and ~1.3 GiB for `--large-alpha`). A 128 GiB free commit limit is no longer needed. +- **Disk space:** Temporary `build/` folders store stamped 16 MiB PE containers per generated executable (~240 MiB for `build/source-gamma-reference`, ~50 MiB per `portable.py` directory, and ~50 MiB for `omega-executable`). Keep at least 1 GiB free when running multiple suites concurrently. +- **Git long paths:** `tests/bootstrap/interpreted/chain-hygiene.sh` creates a temporary checkout under `%TEMP%`, which pushes nested `source-rust/` paths past Windows `MAX_PATH` (260 bytes) unless `core.longpaths true` is set on the fixture repo. +- **Native tools:** Git Bash supplies POSIX `sh`, `dd`, `cmp`, `sha256sum`, and `cygpath`; Windows-native `python3` reads raw Win32 exit DWORDs (`tests/bootstrap/interpreted/alpha/native_exit.py`) and runs `tests/bootstrap/compiled.py` helpers. ## Gate observations @@ -43,7 +43,7 @@ All measurements below ran at base revision `4001493820e8772c02f558aed6f511c12cc | `sh tools/bootstrap/check-chain-hygiene.sh` | `rust producer omission: omitted (186 members, 724 steps, 0 findings)`; `bootstrap chain topology and path hygiene OK` | | `sh tests/bootstrap/interpreted/chain-hygiene.sh` | Passed all archive, checkout, peer, flat-layout, gate-prefix, and Rust-producer omission cases | | `cargo test -p xtask alpha_forge` / `source_closure` | `alpha_forge` 3/3 passed (including `windows_listing_reproduces_the_committed_seed`); `source_closure` 4/4 passed | -| `sh tests/bootstrap/interpreted/alpha-beta-edge.sh` | **VERIFIED:** forge provenance OK; PE/Mach-O/ELF container structure OK; `alpha conformance` 34/34 passed; `Alpha bounds (native)` 78/78 passed (including 128 GiB `ret-stack-*` and `call-stack-*`); Beta reconstruction byte-exact; root audit 12,536 -> 1,773 bytes; word-prefix 736/736 passed | +| `sh tests/bootstrap/interpreted/alpha-beta-edge.sh` | **VERIFIED:** forge source check OK; PE/Mach-O/ELF container layout OK; `alpha conformance` 34/34 passed; `Alpha bounds (native)` 78/78 passed (including 128 GiB `ret-stack-*` and `call-stack-*`); Beta rebuild byte-exact; root audit 12,536 -> 1,773 bytes; word-prefix 736/736 passed | | `sh tests/bootstrap/interpreted/alpha/reference/diamond-py.sh` | Seed diamond 10/10 passed; reference bounds 72/72 passed | | `sh tests/bootstrap/interpreted/beta/compiler/compiler-diamond.sh` | Compiler diamond 6/6 passed | | `sh tests/bootstrap/interpreted/beta/compiler/register-address-regression.sh` | Passed (1,773-byte compiler, including 64 MiB source/output bounds) | @@ -52,18 +52,18 @@ All measurements below ran at base revision `4001493820e8772c02f558aed6f511c12cc | Gate command (run via Git Bash) | Observed result | | --- | --- | -| `python3 tests/bootstrap/conformance/check.py gamma build/win64-delta-gamma/reference` | `gamma: 69 passed, 0 failed` on the seed-reconstructed Beta-written Gamma evaluator | -| `python3 tests/bootstrap/interpreted/delta/interpreter.py build/win64-delta-gamma --host gamma` | 49/49 direct Delta interpreter observations passed on the Beta-written Gamma evaluator (102,210 Gamma bytes, SHA-256 `81cb5ba8610a…`) | -| `python3 tests/bootstrap/compiled_vm/source_test.py --large-alpha --compiler-only` | `compiler0 = compiler1 = compiler2` byte-exact (207,681-byte Alpha tape, SHA-256 `c3274d349b53…`, 34.890s); 40/40 differential controls, 33/33 rejections, call-depth (131,072 frames), and 5,030,606-byte packed large-Alpha tape (>16 MiB expanded, 3 guest outcomes + late refusal) passed | -| `python3 tests/bootstrap/interpreted/delta/interpreter.py build/win64-delta-alpha --host alpha --runner build/source-gamma-reference/compiler2 --epsilon` | Compiled to 342,133-byte Alpha tape (SHA-256 `e9136c37270b…`, 2.47s); 49/49 Delta observations, 5/5 Epsilon language observations, and 14/14 Epsilon syntax controls passed | -| `python3 tests/bootstrap/interpreted/delta/containment.py ... --host gamma --suite quick` / `--suite epsilon` (at `7686600ab67e2`) | 8/8 quick boundary controls passed (Profile 1 & 2 `source_bytes`, support custody space 5, exact `parse_depth` 1,024 compiled/executed and 1,025 `Incomplete 8`); actual 622,011-byte Epsilon sources compiled to exact bound 700,335-byte Gamma receipt (`b2e5836d46ba…`) and passed 19/19 Epsilon observations in 405.75s | -| `python3 tests/bootstrap/interpreted/delta/containment.py ... --host alpha --runner build/source-gamma-reference/compiler2 --suite boundaries` / `--suite compositions` / `--suite epsilon` (at `7686600ab67e2`) | 25/25 full resource boundaries (`source_bytes`, space 5 custody, `parse_depth`, `type_rows`, `constructor_rows`, `function_rows`, `active_env`, `syntax_storage`), 4/4 multi-axis compositions (100 KiB literal + 600-field wide match executed; 2,000 × 16 × 15 heavy-light executed; 6,000 × 125 × 15 -> `DCOUT 12` at 17,205,164 B; 4.19 MiB retired-arena corner -> `DCOUT 12` at 33,867,321 B), and 1/1 bound Epsilon receipt + 19/19 observations (55.75s) passed with zero raw status-252 failures | +| `python3 tests/bootstrap/conformance/check.py gamma build/win64-delta-gamma/reference` | `gamma: 69 passed, 0 failed` on the seed-rebuilt Beta-written Gamma evaluator | +| `python3 tests/bootstrap/interpreted/delta/interpreter.py build/win64-delta-gamma --host gamma` | 49/49 direct Delta interpreter tests passed on the Beta-written Gamma evaluator (102,210 Gamma bytes, SHA-256 `81cb5ba8610a…`) | +| `python3 tests/bootstrap/compiled_vm/source_test.py --large-alpha --compiler-only` | `compiler0 = compiler1 = compiler2` byte-exact (207,681-byte Alpha tape, SHA-256 `c3274d349b53…`, 34.890s); 40/40 differential tests, 33/33 rejections, call-depth (131,072 frames), and 5,030,606-byte packed large-Alpha tape (>16 MiB expanded, 3 guest outcomes + late refusal) passed | +| `python3 tests/bootstrap/interpreted/delta/interpreter.py build/win64-delta-alpha --host alpha --runner build/source-gamma-reference/compiler2 --epsilon` | Compiled to 342,133-byte Alpha tape (SHA-256 `e9136c37270b…`, 2.47s); 49/49 Delta tests, 5/5 Epsilon language tests, and 14/14 Epsilon syntax tests passed | +| `python3 tests/bootstrap/interpreted/delta/containment.py ... --host gamma --suite quick` / `--suite epsilon` (at `7686600ab67e2`) | 8/8 quick boundary tests passed (Profile 1 & 2 `source_bytes`, support-ownership space 5, exact `parse_depth` 1,024 compiled/executed and 1,025 `Incomplete 8`); 622,011-byte Epsilon source compiled to the exact pinned 700,335-byte Gamma output (`b2e5836d46ba…`) and passed 19/19 Epsilon tests in 405.75s | +| `python3 tests/bootstrap/interpreted/delta/containment.py ... --host alpha --runner build/source-gamma-reference/compiler2 --suite boundaries` / `--suite compositions` / `--suite epsilon` (at `7686600ab67e2`) | 25/25 resource boundaries (`source_bytes`, space 5 ownership, `parse_depth`, `type_rows`, `constructor_rows`, `function_rows`, `active_env`, `syntax_storage`), 4/4 combined cases (100 KiB literal + 600-field wide match ran; 2,000 × 16 × 15 heavy-light ran; 6,000 × 125 × 15 -> `DCOUT 12` at 17,205,164 B; 4.19 MiB retired-arena corner -> `DCOUT 12` at 33,867,321 B), and 1/1 pinned Epsilon output + 19/19 tests (55.75s) passed with zero raw status-252 failures | ### Epsilon customer gates | Gate command (run via Git Bash) | Observed result | | --- | --- | -| `python3 tests/bootstrap/interpreted/epsilon/portable.py build/win64-epsilon-cold` | Constructed canonical 700,335-byte Gamma receipt (SHA-256 `b2e5836d46ba4d5c7c745803ed10a368d26cdca5834a376c47a5c37faccb9d5a`) on the Beta-written Gamma evaluator in 345.984s; `language` 5/5 passed | +| `python3 tests/bootstrap/interpreted/epsilon/portable.py build/win64-epsilon-cold` | Built canonical 700,335-byte Gamma output (SHA-256 `b2e5836d46ba4d5c7c745803ed10a368d26cdca5834a376c47a5c37faccb9d5a`) on the Beta-written Gamma evaluator in 345.984s; `language` 5/5 passed | | `python3 tests/bootstrap/interpreted/epsilon/portable.py build/win64-epsilon-syntax --receipt build/win64-epsilon-cold/evaluator.gamma --profile syntax-controls` | `syntax-controls` 14/14 passed | | `python3 tests/bootstrap/interpreted/epsilon/portable.py build/win64-epsilon-envelope --receipt build/win64-epsilon-cold/evaluator.gamma --profile envelope` | `envelope` 49/49 passed | | `python3 tests/bootstrap/interpreted/epsilon/portable.py build/win64-epsilon-historical --receipt build/win64-epsilon-cold/evaluator.gamma --profile historical-at` | `historical-at` 2/5 passed; the 3 `@` cases returned `02 02 a7 00 00 00` (invalid token at source byte 167), matching Linux x86-64 byte for byte | @@ -75,32 +75,32 @@ All measurements below ran at base revision `4001493820e8772c02f558aed6f511c12cc | Gate / route (run via Git Bash) | Observed result | | --- | --- | | `sh tests/bootstrap/interpreted/omega-executable/run.sh --identity` | `Omega executable: identity legs green; execution legs need a seed host` | -| `sh tests/bootstrap/interpreted/omega-executable/run.sh` (Beta-written Gamma interpreter, 256 live call contexts) | Beta/Gamma reconstruction byte-exact; reconstructed the bound 692,938-byte Epsilon execution receipt (`cc781abb4ea5bfd276afd316223215bf4b0054ee4ed7b825a85c6fc213b1fb90`) in 343.688s (status 0); evaluating the 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` customer on the 381-byte canonical OCREQ V1 `program.omg` request exited with evaluator status **250** (`StackExhausted`, empty stdout/stderr) after 1,800.922s | -| `python3 tests/bootstrap/compiled_vm/source_test.py --omega` (seed-built Gamma-to-Alpha compiler, 131,072 Gamma frames, same Windows x64 Alpha seed) | Rebuilt `compiler0 = compiler1 = compiler2` (30.046s), passed 40+33 Gamma controls, Delta customer (152,411 -> 491,064 Alpha bytes `c98cbbd5…` in 5.188s; 3,082-byte receipt `bbd8d7fa…` in 0.078s matching Gamma interpreter), Epsilon customer (identical 700,335-byte receipt `b2e5836d…` in 21.437s -> 2,181,525 Alpha bytes `19227a38…`), and compiled the exact same 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` customer on OCREQ V1 `program.omg` into a 50-byte Alpha tape (`7f22a6c26b9c2876da3ccba9c62fe1cc071cde61fb31399b0d35fb1fa7ca9cae`) in 303.969s, stamped into `alpha_x64_windows.exe` and executed to **exit 42** | -| `python3 tests/bootstrap/conformance/check.py omega ...` (driving the seed-built Alpha Epsilon evaluator on `program.omg`) | `omega: 1 passed, 0 failed` (exit 42, empty stdout/stderr) | +| `sh tests/bootstrap/interpreted/omega-executable/run.sh` (Beta-written Gamma interpreter, 256 live call contexts) | Beta and Gamma rebuilds byte-exact; rebuilt the pinned 692,938-byte Epsilon execution output (`cc781abb4ea5bfd276afd316223215bf4b0054ee4ed7b825a85c6fc213b1fb90`) in 343.688s (status 0); running the 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` bundle on the 381-byte canonical OCREQ V1 `program.omg` request exited with evaluator status **250** (`StackExhausted`, empty stdout/stderr) after 1,800.922s | +| `python3 tests/bootstrap/compiled_vm/source_test.py --omega` (seed-built Gamma-to-Alpha compiler, 131,072 Gamma frames, same Windows x64 Alpha seed) | Rebuilt `compiler0 = compiler1 = compiler2` (30.046s), passed 40+33 Gamma tests, Delta test (152,411 -> 491,064 Alpha bytes `c98cbbd5…` in 5.188s; 3,082-byte output `bbd8d7fa…` in 0.078s matching Gamma interpreter), Epsilon test (identical 700,335-byte output `b2e5836d…` in 21.437s -> 2,181,525 Alpha bytes `19227a38…`), and compiled the same 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` bundle on OCREQ V1 `program.omg` to a 50-byte Alpha tape (`7f22a6c26b9c2876da3ccba9c62fe1cc071cde61fb31399b0d35fb1fa7ca9cae`) in 303.969s, stamped into `alpha_x64_windows.exe` and executed to **exit 42** | +| `python3 tests/bootstrap/conformance/check.py omega ...` (running the seed-built Alpha Epsilon evaluator on `program.omg`) | `omega: 1 passed, 0 failed` (exit 42, empty stdout/stderr) | | `omega-controls` (`controls_b.epsilon`, 1,200,986 Epsilon bytes on seed-built Alpha Epsilon evaluator) | Emitted exact 22-byte Alpha tape -> **exit 42** in 338.766s | ### Recorded limit -The status-250 exit in `tests/bootstrap/interpreted/omega-executable/run.sh` is the Beta-written Gamma interpreter's fixed 256-context / stack boundary (`bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md`) reached by the current 1,198,182-byte `omega_compiler.epsilon` closure, not a Windows-host defect. The same 1,217,225-byte customer and 381-byte OCREQ V1 request compile and run to exit 42 on the same Windows x64 Alpha seed when Gamma runs through the seed-built Alpha backend (131,072 frames). +The status-250 exit in `tests/bootstrap/interpreted/omega-executable/run.sh` comes from the Beta-written Gamma interpreter's fixed 256-context stack limit (`bootstrap/gamma/interpreter/EVALUATOR_PROFILE.md`), which the 1,198,182-byte `omega_compiler.epsilon` bundle exceeds—not from a Windows host bug. The same 1,217,225-byte compiler and 381-byte OCREQ V1 request compile and exit 42 on the same Windows x64 Alpha seed when Gamma runs through the seed-built Alpha backend (131,072 frames). ## Standalone native Windows x64 PE32+ Gamma route -`bootstrap/gamma/compiler/windows_x86_64/native.gamma` emits standalone Windows x64 PE32+ console executables directly from the shared Gamma compiler (`compiler.gamma` + `frontend.gamma`), with no Alpha VM, Wine, host C/Rust compiler, or linker in generated programs. Each emitted PE32+ image imports only eight `KERNEL32.dll` routines (`GetStdHandle`, `ReadFile`, `WriteFile`, `GetLastError`, `VirtualAlloc`, `VirtualFree`, `AddVectoredExceptionHandler`, `ExitProcess`), reserves a 128 GiB arena with the same 1 MiB demand-committing VEH handler as `alpha_x64_windows.hex` (2-slot `PAGE_READONLY` zero ring on reads, permanent `PAGE_READWRITE` commit on writes, exit 3 on commit or I/O error), uses the shared 8 MiB young-gen copying pair collector and 4 KiB buffered stdio, reserves a 4 MiB PE stack for 131,072 Gamma call frames, and enforces a 128 MiB emitted-image cap (`i_limit` = 134,215,857 code bytes, returning exit 254 with no output on overflow). +`bootstrap/gamma/compiler/windows_x86_64/native.gamma` emits standalone Windows x64 PE32+ console executables directly from the shared Gamma compiler (`compiler.gamma` + `frontend.gamma`), with no Alpha VM, Wine, C/Rust compiler, or linker in the output. Each PE32+ binary imports only eight `KERNEL32.dll` functions (`GetStdHandle`, `ReadFile`, `WriteFile`, `GetLastError`, `VirtualAlloc`, `VirtualFree`, `AddVectoredExceptionHandler`, `ExitProcess`). It reserves a 128 GiB arena using the same 1 MiB lazy-commit VEH handler as `alpha_x64_windows.hex` (two-slot `PAGE_READONLY` zero ring on reads, permanent `PAGE_READWRITE` commit on writes, exit 3 on commit or I/O failure), uses the shared 8 MiB nursery copying pair collector and 4 KiB buffered stdio, reserves a 4 MiB PE stack for 131,072 Gamma frames, and caps emitted code at 128 MiB (`i_limit` = 134,215,857 code bytes, exiting 254 with no output on overflow). -Cold construction starts from the audited Windows Alpha seed (`alpha_x64_windows.exe`), the admitted Beta tape, and the Beta-written Gamma evaluator (`41705ff6d8711` base plus `windows_x86_64/native.gamma` on the same Windows 11 Pro x64 host above): +Cold builds start from the audited Windows Alpha seed (`alpha_x64_windows.exe`), the trusted Beta tape, and the Beta-written Gamma evaluator (`41705ff6d8711` base plus `windows_x86_64/native.gamma` on the same Windows 11 Pro x64 host): | Gate command (run via Git Bash / PowerShell) | Observed result | | --- | --- | -| `python3 tests/bootstrap/independent/source_test.py` | Cold `compiler0.exe` = `compiler1.exe` = `compiler2.exe` byte-exact (56,512 Gamma bytes `585ce07da089…` -> 278,016 PE bytes `7e2c7d8acd24…`, cold build 112.125s); 40/40 differential semantic controls, 33/33 source rejections, 131,072 call-depth controls, 4/4 Windows boundary controls (exact/adjacent image capacity + invalid stdin/stdout handles -> exit 3); native Alpha-compiler customer (43,315 Gamma bytes -> 246,272 PE bytes `b43d359fed97…`) emitted the byte-exact 207,681-byte Alpha compiler tape (`c3274d349b53…`), rebuilt identically on the Alpha seed, and passed 40/40 + 33/33 controls | -| `python3 tests/bootstrap/independent/successor_test.py --reuse-constructed --literals --compile-epsilon --omega` | Native Delta compiler (152,411 Gamma bytes -> 508,928 PE bytes `2821e086e955…` in 0.688s; 3,082-byte receipt `bbd8d7fa…` in 0.219s matching Gamma evaluator); byte-literals + Epsilon source encoder (7 positive, 10 malformed, 3 role/type refusals); native Epsilon evaluator reconstructed canonical 700,335-byte Gamma receipt (`b2e5836d46ba…`) in 2.688s -> 1,931,776 PE bytes (`b8203e1281ce…`); native Epsilon-to-Delta compiler (650,640 Delta bytes -> 3,244,032 PE bytes `50f69b584a9b…`) passed all lexical, 20 scalar, 3 refusal, enum (+ Alpha tape), request/UTF-8, 300,000-transfer storage, digits, console-lines (+ Alpha tape), compiler-signature (+ Alpha tape), 17-case string scanner (+ Alpha tape), and 23-case public lexer (+ Alpha tape, 465-byte observation `7d7a561d217e…`) checks; native Epsilon evaluator compiled 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` on OCREQ V1 `program.omg` into the exact 50-byte Alpha tape (`7f22a6c26b9c…`) -> **exit 42** in **46.719s** | -| `python3 tests/bootstrap/independent/epsilon/payload_sums_test.py --host build/win-host` | 6/6 passed (`positive-all`, `trap-second-arg`, `trap-middle-arg`, 2 negative twins, pure-mode unsupported control) matching the native Windows Epsilon evaluator byte-for-byte | -| `python3 tests/bootstrap/independent/epsilon/indexed_receivers_test.py --host build/win-host` | 7/7 passed (`positive-all`, 4 `IndexRange`/`ByteRange` trap-ordering cases, 2 negative receiver twins) matching the native Windows Epsilon evaluator byte-for-byte | -| `python3 tests/bootstrap/independent/successor_test.py --reuse-constructed --compile-epsilon --compile-omega` | On rebased `4cf4b67f39749` (post-#7819 `machine`-only closure, 1,264,976 Epsilon bytes `f9a3279d92f9…`), compiled through Profile-2 native Epsilon-to-Delta (`3,354,624` PE bytes `463c26529442…`) -> `18,508,462` linked Delta bytes (`2312cc67c5b1…`, 3,944 `def`s, 29.078s) -> `26,141,933` Gamma bytes (`e62dbcbf6982…`, 41.094s) -> `58,216,448` standalone Windows PE32+ bytes (`5be36e64b04b…`, 49.938s; total 120.110s). Executed on canonical OCREQ V1 `program.omg` in **1.922s** (byte-exact 50-byte Alpha tape `7f22a6c26b9c…` -> **exit 42**, 24.3× faster than the 46.719s pre-#7819 native Epsilon evaluator and 158.2× faster than the 303.969s Alpha VM evaluator), plus 7/7 positive/negative controls (`return-43` -> exit 43 in 0.578s; `empty`, `truncated-header`, `bad-magic`, `trailing-byte`, `bad-program-type`, `syntax-error` refusals with no partial tape publication) and all `--compile-epsilon` controls | +| `python3 tests/bootstrap/independent/source_test.py` | Cold `compiler0.exe` = `compiler1.exe` = `compiler2.exe` byte-exact (56,512 Gamma bytes `585ce07da089…` -> 278,016 PE bytes `7e2c7d8acd24…`, cold build 112.125s); 40/40 differential tests, 33/33 source rejections, 131,072 call-depth checks, 4/4 Windows boundary tests (exact/adjacent image capacity + invalid stdin/stdout handles -> exit 3); native Alpha-compiler build (43,315 Gamma bytes -> 246,272 PE bytes `b43d359fed97…`) emitted the byte-exact 207,681-byte Alpha compiler tape (`c3274d349b53…`), rebuilt identically on the Alpha seed, and passed 40/40 + 33/33 checks | +| `python3 tests/bootstrap/independent/successor_test.py --reuse-constructed --literals --compile-epsilon --omega` | Native Delta compiler (152,411 Gamma bytes -> 508,928 PE bytes `2821e086e955…` in 0.688s; 3,082-byte output `bbd8d7fa…` in 0.219s matching Gamma evaluator); byte-literals + Epsilon source encoder (7 positive, 10 malformed, 3 role/type refusals); native Epsilon evaluator rebuilt canonical 700,335-byte Gamma output (`b2e5836d46ba…`) in 2.688s -> 1,931,776 PE bytes (`b8203e1281ce…`); native Epsilon-to-Delta compiler (650,640 Delta bytes -> 3,244,032 PE bytes `50f69b584a9b…`) passed all lexical, 20 scalar, 3 refusal, enum (+ Alpha tape), request/UTF-8, 300,000-transfer storage, digits, console-lines (+ Alpha tape), compiler-signature (+ Alpha tape), 17-case string scanner (+ Alpha tape), and 23-case public lexer (+ Alpha tape, 465-byte output `7d7a561d217e…`) checks; native Epsilon evaluator compiled 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` on OCREQ V1 `program.omg` to the exact 50-byte Alpha tape (`7f22a6c26b9c…`) -> **exit 42** in **46.719s** | +| `python3 tests/bootstrap/independent/epsilon/payload_sums_test.py --host build/win-host` | 6/6 passed (`positive-all`, `trap-second-arg`, `trap-middle-arg`, 2 negative twins, pure-mode unsupported test), matching the native Windows Epsilon evaluator byte for byte | +| `python3 tests/bootstrap/independent/epsilon/indexed_receivers_test.py --host build/win-host` | 7/7 passed (`positive-all`, 4 `IndexRange`/`ByteRange` trap-ordering cases, 2 negative receiver twins), matching the native Windows Epsilon evaluator byte for byte | +| `python3 tests/bootstrap/independent/successor_test.py --reuse-constructed --compile-epsilon --compile-omega` | On rebased `4cf4b67f39749` (post-#7819 `machine`-only bundle, 1,264,976 Epsilon bytes `f9a3279d92f9…`), compiled through Profile-2 native Epsilon-to-Delta (`3,354,624` PE bytes `463c26529442…`) -> `18,508,462` linked Delta bytes (`2312cc67c5b1…`, 3,944 `def`s, 29.078s) -> `26,141,933` Gamma bytes (`e62dbcbf6982…`, 41.094s) -> `58,216,448` standalone Windows PE32+ bytes (`5be36e64b04b…`, 49.938s; total 120.110s). Ran canonical OCREQ V1 `program.omg` in **1.922s** (byte-exact 50-byte Alpha tape `7f22a6c26b9c…` -> **exit 42**, 24.3× faster than the 46.719s pre-#7819 native Epsilon evaluator and 158.2× faster than the 303.969s Alpha VM evaluator), plus 7/7 positive/negative tests (`return-43` -> exit 43 in 0.578s; `empty`, `truncated-header`, `bad-magic`, `trailing-byte`, `bad-program-type`, `syntax-error` refusals with no partial tape output) and all `--compile-epsilon` checks | ### Compiled Omega lowering comparison on Windows x64 -Lowering total receiver/local field chains directly through `epsilon_compiled_place_field` + `epsilon_compiled_read`, writing total non-view places directly via `epsilon_compiled_write_place` without a redundant pre-read, forwarding total scalar literals directly in stored arguments/assignments/`let`/indexes/slices/transitions, and inlining up to six statements per stored block chunk (eliminating per-statement `ep_block_*` and zero-statement `ep_block_end_*` wrapper functions) reduced both emitted size and runtime on the same 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` input (`ff2563aefbdb2` base, same Windows 11 Pro x64 host): +Four lowering changes cut both generated size and runtime on the same 1,217,225-byte `omega_compiler.epsilon` + `main_ocreq.epsilon` input (`ff2563aefbdb2` base, same Windows 11 Pro x64 host): lowering total receiver/local field chains directly with `epsilon_compiled_place_field` + `epsilon_compiled_read`; writing total non-view places directly with `epsilon_compiled_write_place` without a redundant pre-read; forwarding total scalar literals directly in stored arguments, assignments, `let`, indexes, slices, and transitions; and inlining up to six statements per stored block chunk (removing per-statement `ep_block_*` and empty `ep_block_end_*` wrappers). | Measurement (1,217,225-byte Omega OCREQ closure) | Baseline lowering (`ff2563aefbdb2`) | Revised lowering | Change | | --- | ---: | ---: | ---: | @@ -111,4 +111,4 @@ Lowering total receiver/local field chains directly through `epsilon_compiled_pl | End-to-end compile time (Epsilon + Delta P2 + Gamma PE32+) | 354.749s | 128.860s | 2.75× faster | | `omega-ocreq.exe` on `program.omg` (50-byte Alpha tape -> exit 42) | 6.266s | 2.313s | 2.71× faster (20.2× vs evaluator, 131.4× vs Alpha VM) | -Trust boundary: the compiled `omega-ocreq.exe` executable is constructed entirely from the audited Windows Alpha seed (`alpha_x64_windows.exe`), the admitted Beta tape, the Beta-written Gamma evaluator, and repository-owned Gamma/Delta/Epsilon sources; Python and `xtask` only pack declared manifests, frame DCREQ headers, stamp emitted Alpha tapes, and check observations. +Trust boundary: `omega-ocreq.exe` is built solely from the audited Windows Alpha seed (`alpha_x64_windows.exe`), the trusted Beta tape, the Beta-written Gamma evaluator, and repository Gamma/Delta/Epsilon sources. Python and `xtask` only pack manifests, frame DCREQ headers, stamp Alpha tapes, and check results.