Skip to content

Latest commit

 

History

History
1341 lines (1097 loc) · 73.5 KB

CODE_REVIEW.md

File metadata and controls

1341 lines (1097 loc) · 73.5 KB

Code review — expanded experimental Bend implementation

2026-10-20 · Codex, with fresh-context reviewer /root/bend_native_fresh_review · base e3ffa95653d0913af81029a95bbdcfb2072fda7d plus the expanded uncommitted port. No unresolved implementation finding in the inspected scope. This was a read-only source review with small existing- artifact probes, not independent execution of the full release matrix.

Coverage: independent Bend BLAKE3, limbs/fixed arithmetic, draw effects, nonlinear samplers, BLIP/count/decimal codecs, canonical charts, batch and selection plans; boxed native-runtime ownership and callback reentry; shared C frontend wiring; Nix source/CLI/FFI separation; the changed Rust, C, Lua and JS sampler benchmarks and whole-process output controls. The reviewer inspected pinned generated runtime ownership/setup, not just handwritten marshalling. It did not audit all generated strip literals manually; exact all-strip and MPFR regeneration controls supply that evidence.

DCR-001 (medium severity, high confidence; resolved): the newly added installed SDK consumer expected cursor 8 after seed42/d20, and compared a qualified generated JS constructor with an unqualified tag. Independent LuaJIT execution returns value18 at cursor4. The corrected fixture compares semantic limbs and expects cursor4; the reviewer independently passed it against the installed coherent facade. The generator was not changed to satisfy a wrong expectation.

The author separately reproduced and fixed invalid seek/restore status drift and premature written mutation on invalid geometric/count-format input. The reviewer revalidated the pure Prepare→opaque Ready→Sample/Format transfer: prepared lists remain owned under the evaluator gate, are transferred rather than recomputed, and invalid parameters precede caller metadata mutation. Existing shared geometric FFI expectations now also run against Bend.

DCR-002 (medium severity, high confidence; resolved): the new required deadline fixture depended on the patched profiler, but only CI/profile shells declared it. The default-shell dependency assertion failed before correction and passes after declaring the same patched package. Git is now an explicit test tool, rather than an accidental inherited executable. The actual normal-shell runtime deadline fixture also passed; the reviewer verified the dependency correction but did not repeat that run.

DCR-003 (low severity, high confidence; resolved): the new statistical helper trusted Lua's length operator and ipairs to establish array density. A hole could admit only a prefix of cumulative counts or silently shorten values. Dense production samples were unaffected. Persistent hole/extra-key controls failed before correction; raw positive-integer key validation and numeric-slot traversal now reject malformed arrays. All 45 model controls pass.

The statistical follow-up also corrected the CLI's null: custom normal samples are integer-rounded, so continuous-normal moments/CDF targets were wrong. Independent 512-bit MPFR checks confirm the seven rounded references and numerical variance. The reviewer verified preserved same-sample measurements, envelope calculations and source linkage. Corrected CLI analyses are explicitly exploratory/post-diagnostic; seed81002 prefix/extension/core observations overlap. The separately predeclared seed81032 core holdout has its own conditional seven-point check, not a pooled confidence claim. No generator change or new probability/security proof followed from this diagnosis. The parent owns the million-value runs and corrected 81-check statistics; the reviewer did not rerun them.

Supplementary source review verified that the deadline patch changes only admission/defaulting, forwarding the existing process-runner option and stored metadata. It verified that exactly the 31 original timed-out identities are selected for a separate versioned repair run, excluding all 14 original noisy cases. All original observations remain retained; one timeout occurred on the engine's permitted second attempt. Neither the patch nor repair approves an epoch or changes workloads, retry policy or noise tolerances. Deadline tests exercise a direct child; descendant-process cancellation was not established.

Limits: per-sample value hashes are checked, but only the final timed sampler cursor is reported; whole-CLI preflight checks SHA-256 and full state, while timed children check output fold/status and suppress stderr. These are finite controls, not collision-resistant proofs of all executed work. No sanitizer, allocation-failure injection, multithread/fork/unload stress, native non-x86_64 execution or new probability/security theorem was performed by the reviewer. Runtime high-water reuse is not a complete live-allocation leak census. The parent owns full current-suite, isolated SDK/package and timing verification; source review is not production-promotion approval.


Previous review — production Ziggurat and exact SIMD

2026-10-09 · Codex, with fresh-context reviewer /root/ziggurat_production_review · base 89b2213664f5 plus the production migration. Supplementary finding DCR-001 is resolved after corrected-source revalidation. This is a scoped review, not whole-library clearance or a mathematical distribution proof.

Coverage: all five kernels, table/distribution/CLI wiring, schema-v3 rejection and cross-language continuation, Rust and Zig batch/source-error transitions, AVX2 integer arithmetic and CPU/OS guards, module packaging, frozen acceptance controls, and the statistical/performance/proof evidence boundaries.

The reviewer independently passed all 36 Rust library tests, a no-default- features compile check, 347,075 Zig LuaJIT-FFI batch checks, and all 2,305 frozen production checks across LuaJIT, Zig, Rust, Lean and Roc. It used explicit existing CLI artifacts and an isolated Rust build target; it did not change project sources or shared build outputs.

The author repaired a stale Kani scalar-model boundary exposed by parameter caching, then passed both affected positive contracts and designated negative controls. The review checked the model and receipts but did not independently rerun the solver. Successful nonlinear arithmetic and SIMD equivalence remain outside those proofs. Roc's newly inconsistent backend-mode validation was also reproduced and repaired before this review; all three modes now preserve the shared scalar contract, with a portable fallback in Roc.

DCR-001, medium severity/high confidence: generic integer conversion clamps normalized tails into ±2^53 before range rejection, contradicting the new conditioning contract even on valid narrow CLI ranges. The reviewer reproduced it independently through the Zig C ABI in scalar and all batch modes. The new 40-assertion shared endpoint control failed in all five implementations before the correction. Every core now guards the exact half-away rejection threshold before conversion. Supplementary review passed the rebuilt-artifact matrix, half-tie adjacency controls and an independently derived seed171 rejection through the real Rust DRBG and direct AVX2 path. Reviewed source hashes stayed unchanged during those checks; no additional implementation finding remains. The same correction closes the inherited legacy scalar admission gap beyond ±2^53, with pre-read refusal and unchanged output/cursor controls.

Native review execution covered Linux x86_64. The reviewer did not rerun the full Nix gate, heavy statistics/MPFR generation, pre-AVX emulation or native Darwin/Windows/aarch64 tests. The proposed global distribution-error bound is still unproved. See the production report for exact measurements, controls and final release-gate evidence.


Previous review — isolated fixed-point Ziggurat experiment

Follow-up, 2026-10-08: the same independent reviewer passed all nine new edge/chunk work-oracle counts and 80,229 production batch value/cursor/rejection/ error checks against the rebuilt experimental library. AUTO/SCALAR call the production batch ABI; expected checksums come from independent scalar arrays. It also passed the new finite directed-MPFR certificate and verified both threshold/height corruption controls fail at their intended assertions. All 1,022 initially excluded point fixtures now have resolved ideal signs; eight signed wedge cases differ from the compiled candidate. This does not certify a whole-domain CDF bound. Review corrected a strict rounding endpoint and linked the LN2 enclosure to the compiled ln(2) result. A proposed global error-budget argument remains provisional, with hybrid-reference and rounding lemmas separate from the executed finite certificates. Production remains unchanged; the report retains 62 additional timing cases, including the permitted retry's noisy first attempt. Exact shipment CI is checked separately. The final statistical audit also restricts the calibrated families to the 32 unpaired scalar/candidate cells; the finite paired control has no joint- independence theorem and remains diagnostic only. The unchanged 48-way DKW and 100,000-way count allocations are conservative for those 32 cells and 8,208 count checks under IID target-law nulls. Thresholds and data were not changed to obtain this correction.

Initial checkpoint:

2026-10-08 · Codex, with fresh-context reviewer /root/ziggurat_review · base a758c902143f. No unresolved actionable defect in the reviewed experiment. This is not clearance to change the production sampler or deterministic stream.

The reviewer independently passed five directed tests, 6,700 scripted MPFR acceptance decisions, the arithmetic oracle, and 24 separate work checksums. It reproduced a skipped-work benchmark that originally passed, then verified the same mutation failed after expected checksums came from an external FFI array loop. Three other corrections cover mantissa-sensitive logarithm inputs, sandbox shebang execution and portable OS-specific benchmark clocks. Statistical reporting now distinguishes two alpha budgets instead of implying one global budget. No thresholds were relaxed.

The final claims audit mechanically recomputed all 12 CDF maxima, tail counts, standardized moment ranges, all timing medians/ratios, and the 96M-output accounting from retained receipts. Repeating the same deterministic campaign reproduced its results; it adds no independent draws to the stated sample count.

Limits: 1,022 near-boundary decision cases were explicitly excluded; sampled MPFR errors are not universal bounds. The reviewer did not independently rerun the parent's heavy statistics, timing, full suite or native non-Linux checks. The parent passed the required focused gate and all 42 default suites in the hermetic Nix check, plus the separate 60,000-iteration deep JIT differential. It measured 96M outputs and retained 54 raw timing receipts, with no production wiring changed. Exact shipment CI is verified separately. See the experiment report for numerical, statistical and performance scope and remaining promotion gates.


Previous review — first production-linked distribution proof certificates

2026-10-07 · Codex, with fresh-context reviewer /root/fresh_distribution_proof_review · base 17461cf plus the proof milestone. No mathematical correctness or vacuity defect was found in the stated domain. This is a scoped proof review, not a whole-library correctness or security claim.

The reviewer read the full proof modules, independently restated headline contracts, witness and mutation controls, production arithmetic/sampler/source definitions, suite integration, Nix dependency/consumer packaging and claims. It independently passed the bounded proof gate, all 21 standard-axiom audits, three production mutations after original-code specificity checks, and the installed compiled-artifact consumer. The ordinary core runtime and CLI build closures contained no proof/mathlib dependency.

Two low findings were reproduced and fixed: the documented .#proofs shell was absent on supported Darwin, and the constant-uniform mutant emitted an expected unused-draw warning. The shell now sits outside the Linux-only Roc block, with an all-supported-system assertion in package-split. The mutant disables only its intentional unused-variable linter and retains warnings-as-errors otherwise. The parent reran the proof gate and shell/package checks after these remedies.

Certified: actual 62-step fixed division and its rounding remainder; actual fractional/nonzero-uniform output existence/value and universal CDF bounds; actual direct geometric preparation, decoded-source/strict-threshold linkage, finite-fuel success/failure laws and public sampleWith CDF bound. Geometric coverage is canonical fixed p in [1/2,1), with R available independent trials. Failure mass is separate, not silently normalized away.

The parent passed all 41 FAST suites and the unchanged full five-way Bash CLI oracle, the 60,000-iteration deep JIT differential, and standalone Nix proof, package-split and installed library-consumer checks. Native execution here is Linux x86_64; Darwin/ARM64 shell checks are evaluation-only. Exact shipment CI is required separately.

Limits: smaller geometric probabilities and other nonlinear laws, cursor-derived stateful fuel/read exhaustion, bounded integer rejection, decimal parsing/output, universal other-language equivalence, cryptographic source security and compiler correctness remain open. Standard Lean axioms and hash-pinned precompiled mathlib are explicit trust boundaries. See the certificate report for exact bounds and assumptions. The broader distribution-proof plan stays open.


Previous review — Roc production CLI, native ABI and five-way acceptance

2026-10-04 · Codex, with fresh-context reviewer /root/roc_production_review · base eb81a21, 53 staged paths plus a separately reviewed one-line test fix. No confirmed production correctness/security finding in the inspected scope. The reviewer inspected all staged paths and independently checked installed FFI reentry/refusal behavior, Lean/Roc entropy and sink failures, source/header identity, ELF protection and empty library runtime reference sets.

The review identified one validation weakness: explicitly selected Lua scripts went through a compiled-artifact no-libm inspection. The parent corrected the shared Bash branch. A live, unused math.log(1) fixture passed all 85 assertions before the correction and failed only that audit afterward. The reviewer independently checked the actual selector/source scan. Clean LuaJIT, Zig, Rust, Lean and Roc then each passed the same 85 assertions, 12 DRBG controls and full 186-case matrix, with no implementation-specific numerical expectations.

The complete serial Nix gate passed all 40 FAST suites and all 11 CI-manifest targets plus package-split before that test-only follow-up. The parent also reran the complete default root suite afterward: all 40 suites passed against the current installed production artifacts. The separate deep kernel JIT/interpreter comparison matched over 60,000 iterations. Additional maintained controls cover 196 Roc expectations, 5,461 native FFI assertions plus 193 forced-hot callback checks, static four-thread/reentrant consumers, optimized allocation guards, 100 help cases, 1,870 continuation checks across all 25 implementation directions and 275 streaming checks. The 13 benchmark workloads passed five-way output digests; concurrent-build timings are diagnostic only and support no throughput claim.

The complete shared-test requirement exposed three Lean I/O failures hidden by its previous reduced path: empty entropy lacked source context, and buffered about and chart writes could report success on /dev/full. The strengthened common body caught those failures without changing its expected results; the I/O adapter fixes now pass it. Supplementary FFI/proof tests remain additive.

Limits: native Roc execution is Linux x86_64 only; ARM64 packaging is not runtime certification. AUTO batching is currently scalar, and Roc's allocator remains fail-stop on OOM. Capacity bounds storage, not rejection work; decimal conversion can be quadratic. No cryptographic proof, sanitizer campaign or new performance claim follows from this review. One reviewer nix develop attempt failed before execution with a transient space error; direct installed-artifact checks passed. Exact pushed-commit CI is required after this local review.


Previous review — Roc bounded sampling and admission

2026-10-04 · Codex, with fresh-context reviewer /root/roc_boundary_review · base 5dcd84f, five staged source/test paths. No actionable findings in scope. The complete 37-suite FAST run and installed consumers passed. The reviewer independently reran 178 repository expectations, seven additional pure controls, 1,372 native geometric comparisons, 108 sampler-admission cases and 83 chart cases. Deliberately false expectations and a perturbed verdict failed.

The parent reran the full 1,574-assertion native campaign, verified the unchanged reviewed diff, and checked that all four installed production modules matched the reviewed source exactly. Geometry checks include capacity refusals, precise request traces, source failures, late BLIP headers and arbitrary-width results; admission checks distinguish invalid parameters from unsupported numeric domains.

Limits: capacity bounds storage, not rejection work or exact allocator peak. Draw.run_with does not return the advanced source on error; effectful adapters must retain actual consumption per request. Selected dynamic capacity witnesses must join the maintained native gate. This does not clear the separate prototype ABI, CLI, Batch or Selection code, cryptographic correctness, or other platforms. Shared Bash CLI assertions and expected results remain unchanged.


Previous review — Roc canonical unsigned count codecs

2026-10-04 · Codex, with fresh-context reviewer /root/roc_count_codec_review · base b08dc43, five staged codec/test paths. No actionable findings in scope. The maintained gate passed 166 expectations and 2,115 comparisons against the actual Zig Count C ABI, including exactly 192 accepted encodings. The complete 37-suite FAST run and installed source/native consumers passed; the source library has no runtime references.

The reviewer independently exhausted all 65,792 one- and two-byte inputs, checked exact numeric hex for a 32,768-byte magnitude and refused overflowing U64 length prefixes. Its deliberately wrong consumer expectation failed with status 1 and no output. The parent reran these native controls and verified the unchanged reviewed diff and byte-identical installed Count module.

Limits: this is finite codec evidence, not a cryptographic proof or public Roc CLI/C ABI clearance. Decimal conversion remains width-dependent and potentially quadratic. The malformed shell corpus requires quiet nonzero rejection, not exactly status 1; direct expectations separately check Invalid returns. Native execution is Linux x86_64 only. Shared Bash CLI expectations are unchanged.


Previous review — Roc canonical chart model

2026-10-04 · Codex, with fresh-context reviewer /root/roc_chart_review · base e4d6fd7, staged chart checkpoint. No confirmed findings in this scope. The reviewer read all six curve operations, their admission/arithmetic bounds, the existing Lua geometry oracle, changed tests and installed consumers. It independently checked the exact installed modules and empty source-package reference set, and corroborated the full 37-suite FAST run and 138 Roc expects.

The maintained gate compares 196 exact height/bounds/stem witnesses and 14 refusals. The reviewer added 29 isolated direct-Fixed boundary predicates, passing both expectations and optimized Linux x86_64 execution with a runtime-supplied extreme exponent. A deliberately false chart expectation failed with status 1. The reviewed diff hash stayed unchanged throughout.

Limits: these are finite compatibility and boundary witnesses, not independent density-accuracy proofs. The deep-mode kernel_jit_diff was not run. Production Roc CLI/public ABI, chart surfaces/codecs, cryptographic proofs and other-platform execution were excluded. The shared Bash CLI assertions and expected values remain unchanged; core coverage does not substitute for them.


Previous review — Roc native platform and ELF packaging

2026-10-04 · Codex, with fresh-context reviewer /root/roc_native_platform_review · base f1ee208, staged native checkpoint. No confirmed findings in this scope. The reviewer independently ran the native platform suite twice, using repository sources and the installed source package. Both passed the raw-writer refusal, four patched architecture/relocation controls, exact LuaJIT FFI results, allocation guards and actual ELF loader protections.

The full 37-suite run passed. Cleanup's eight in-memory adapter checks and all-system flake evaluation passed; the installed source package has no runtime references. The reviewer reran the native checks and corroborated the full-suite logs, rather than claiming a second complete run. The sandbox cleanup defect was fixed before review: explicit RAM Trash selection avoids an unwritable HOME, and an EXIT trap can no longer conceal a failed move.

The actual pinned CGlue and generated header agree on allocator signatures, list layout and owned-argument transfer. C transports bytes and owns memory; Roc computes values and drops returned output lists. Relocatable pointer constants are protected by GNU_RELRO without TEXTREL or writable executable segments.

Limits: native execution is Linux x86_64; aarch64 checks establish object emission only. Finite allocation witnesses do not prove concurrency, all failure paths or full zeroization. Production Roc ABI/CLI, charts and mathematical proof were excluded. Roc's eventual CLI must pass the same Bash assertions and expected results as every other implementation.


Previous review — independent Roc core and decimal codecs

The 2026-10-04 Decimal follow-up found no confirmed new defect. It checked the pure parser/formatter, probability grammar, safe-integer bounds, test admission controls and installed source-package imports. All 3,072 raw-byte substitution cases matched LuaJIT, including valid specificity cases, NUL and malformed UTF-8. Additional formatting boundaries and refusal controls passed. Six input growth witnesses through two million bytes passed; their startup-inclusive resource measurements are diagnostics, not a leak or complexity proof.

The default gate runs 127 expectations and 969 native codec comparisons alongside the existing core checks; the current full 35-suite snapshot passed. The source-library closure still has no references. This follow-up uses the same LuaJIT compatibility oracle and establishes Linux x86_64 execution only. Production Roc CLI/C ABI and shared CLI acceptance remain open.

Initial pure-core review

2026-10-04 · Codex, with fresh-context reviewer /root/roc_core_review · base ab6fa76, staged official-upstream Roc core. No confirmed new defect in the inspected core, kernel tests or pure-source package. This does not approve an unfinished Roc production CLI or C ABI.

All eight production modules were read and rechecked against live source. Independent runtime oracles pin Fixed values, official BLAKE3 vectors, DRBG seeks, nonlinear and integer samplers, arbitrary-width geometric BLIP and byte cursors. Custom beta shapes cover gamma's alpha<1 branch. Source-package references were empty: no runtime compiler or CLI dependency.

Reviewer probes checked malformed source replies, pre-read parameter validation, BLIP length boundaries through 125,000 bytes, magnitudes through 2^128, and DRBG bytes around the 2^38 block-counter carry and 2^53 cursor ceiling. Forced rejection probes through 800,000 retries retained about 1 MiB process RSS and exact read counts. These are finite, startup-inclusive diagnostic observations, not formal proofs, allocator leak proofs or historical benchmarks. The useful 22 source/domain/count controls now also run in the default core gate.

Limits: native execution is Linux x86_64 only. Production Roc CLI/C ABI, entropy, charts, all-direction continuation, statistics and end-to-end benchmarks remain open. Decimal count conversion is known quadratic. Existing scalar cosine and capped fraction-conversion behavior were not mistaken for new Roc regressions. Roc CLI acceptance must run the same Bash assertions and expected results as every other implementation; kernel coverage is additional, not a substitute.


Historical review — BLAKE3 DRBG milestone

Date: 2026-08-04 Scope: the repository after the LuaJIT BLAKE3/OS-entropy migration, with particular attention to bin/random, lib/blake3.lua, and their controls. Result: no critical findings remain. Five warnings and two advisories were fixed during the review; two warnings and two advisories remain below.

1. Inconsistent, incomplete, or undefined functionality

  • Fixed — WARNING: true-random wide ranges assembled 7–8 source bytes in a Lua number and silently lost low bits beyond 2^53. bin/random:354-383 now performs exact big-endian uint64_t assembly and the same unbiased rejection arithmetic as deterministic mode. tests/drbg_test:173-185 independently pins the result from known source bytes.
  • Fixed — WARNING: endpoints could each be exact while their inclusive span was not. The CLI now rejects spans above 2^53 rather than sampling a rounded range, with an exact-maximum specificity check.
  • Fixed — WARNING: aggregate weighted totals could exceed the exact range even when each input weight passed validation, and an all-zero table exited successfully without selecting anything. Both cases now fail explicitly.
  • Fixed — WARNING: logarithmic distributions mapped an exact zero u32 to 1e-6 instead of the discrete generator's smallest positive value, 2^-32. The endpoint and its independently injected /dev/zero control now agree.

2. Inadequate test coverage

  • Remaining — WARNING: Linux getrandom success is exercised by ordinary CLI tests, and explicit-source EOF is covered, but EINTR, ENOSYS, EAGAIN, getentropy fallback, and BCryptGenRandom cannot currently be forced from the public interface. A future injectable syscall adapter would make these branches mechanically testable without weakening production behavior.
  • Remaining — WARNING: the Windows entropy branch at bin/random:304-315 has no Windows CI leg; the Nix package itself declares Unix platforms. Verify it on actual Windows LuaJIT before advertising that implementation as proven.

3. Futile test coverage

No remaining finding. Re-blessed snapshots are not the sole authority: all 35 official BLAKE3 cases, a four-seed Zig-stdlib reference at seven structural lengths, replay, source exhaustion, byte consumption, and range arithmetic are separate controls. Mutating a BLAKE3 IV word, KDF context, seed grammar, and wide-draw endianness made the intended suites fail.

4. Fast test coverage

The DRBG reference invokes zig run four times, but Zig's cache keeps the full suite near two seconds locally. No sleep or timing-based entropy assertion was added. No finding.

5. Superfluous or duplicated functionality

  • Advisory: deterministic and true-random u64 assembly/rejection have small parallel implementations (bin/random:163-210, 354-383). Factoring them through callbacks would reduce duplication but add calls in a hot path; the explicit parallel code is acceptable while the tests pin both paths.

6. Suboptimal, inconcise, or disorganized code

main remains large, but its size predates this migration and its mode branches are explicit. The new seed, DRBG, and entropy sections are cohesive. No new finding.

7. Algorithmic complexity

Seed parsing is O(32n), bounded by command-line input size. BLAKE3 and output generation are linear. Rejection sampling has the expected constant average cost. No finding.

8. Files without clear purpose

The new files have distinct roles: vendored producer, immutable upstream fixture, official-vector runner, CLI contract suite, and independent Zig reference. No finding.

9. Not leveraging language features

  • Remaining — ADVISORY: very large raw/hex output is materialized in full, and the vendored BLAKE3 API represents output as hex before conversion back to bytes. Chunked string.buffer/FFI output would lower peak memory, but is a performance improvement rather than a correctness requirement for ordinary CLI counts.

10. Memory safety and resource leaks

  • Fixed — ADVISORY: the new test initially sourced a personal absolute-path helper. It now has a hermetic private capture directory with trap cleanup.
  • Remaining — ADVISORY: an explicit entropy file remains open for the life of the process. The CLI performs one operation and exits, so the OS closes it; an embeddable/library API should add explicit reader cleanup ownership.

11. FFI boundary correctness

The OS FFI loops preserve partial reads, retry EINTR, enforce getentropy's 256-byte limit, fail on zero/short reads, and check BCrypt status. The planned project Zig/C FFI has not been implemented yet and was not reviewed here.

12. Error handling gaps

  • Fixed — WARNING: negative --count previously succeeded as an empty loop; count now uses exact safe-integer parsing and rejects negative values.
  • Fixed — ADVISORY: entropy-source open/EOF failures now carry an Error: entropy ... diagnostic and never fall back after an explicitly selected source fails.

13. Database access patterns

Not applicable; the project has no database.


Zig/C milestone addendum

Date: 2026-08-04 Scope: the pure Zig DRBG/distribution core, public C ABI, C CLI, shared LuaJIT oracle, package surfaces, statistics harness, and cross-target controls. Method: thirteen independent review passes covering functionality, coverage, test validity, security, performance, reliability, architecture, maintainability, API design, developer operations, dependencies, test strategy, and product completeness. Result: all reproduced critical findings were fixed. The remaining findings are explicit limitations or post-shipment engineering work, not silent correctness blockers.

1. Functionality and cross-platform behavior

  • Fixed — CRITICAL: both CLIs now switch Windows stdout to binary mode, so LF bytes in deterministic/raw output are not expanded by the Microsoft CRT. The C path also normalizes CRLF stdin items; the Lua oracle does the same.
  • Fixed — WARNING: .exe suffixes participate in nrandomz/drandomz argv[0] dispatch, and repeated selection of the same distribution is idempotent.
  • Remaining — WARNING: Windows ARM64 is compiled and its PE machine field is checked, but no Windows ARM64 runtime is available. Windows x86_64 is executed under Wine in CI and compared byte-for-byte with the Lua oracle.

2. Coverage adequacy

  • Fixed: a real C11 consumer now checks struct layout, statuses, callbacks, state replay, every public symbol, malformed values, and numeric limits.
  • Fixed: scripted byte sources force both u32 and u64 rejection retries, exact-divisor paths, and failure on a retry. Beta vectors and statistics cover the distinct alpha < 1 gamma branch.
  • Remaining — WARNING: syscall-level EINTR/ENOSYS/EAGAIN/getentropy and native BCrypt failure branches need an injectable platform adapter for deterministic branch coverage.

3. Test validity / non-vacuity

  • Fixed — WARNING: Lua/C differentials now require both processes to exit zero and emit nonempty bytes before comparison. Cross payloads similarly validate every framed case's status and byte count.
  • Fixed — WARNING: --test uses executable probes that prove invocation and success/failure propagation. LuaJIT 5.1's encoded POSIX wait status is decoded before os.exit; the installed C self-test runs the actual suite.
  • Fixed: uniform and log-normal evaluators gained deliberately bad sensitivity fixtures. Seven bad generators must now be rejected.

4. Security

  • Fixed: --true-random overrides the frontend-specific seed environment (DRANDOM_SEED for LuaJIT, DRANDOMZ_SEED for C) and rejects deterministic conflicts. Each frontend ignores the other's variable, giving security-sensitive callers an explicit fail-safe entropy mode without cross-frontend namespace coupling.
  • Fixed: panic-capable fixed arithmetic was removed from the public ABI. Public conversions and samplers validate canonical values/domains and return statuses; extreme log-normal input now returns RANDOMZ_NUMERIC_ERROR rather than aborting the embedding process.
  • Fixed: the header documents single-thread/fork clone semantics and state sensitivity; randomz_drbg_zeroize provides a non-optimizable wipe.
  • Remaining — ADVISORY: the CLI does not attempt comprehensive secure erasure across every early-return path; applications still own seed/key lifetime and must use the zeroize API.

5. Performance and scalability

  • Remaining — WARNING: small deterministic sampler draws reconstruct a keyed BLAKE3 XOF and cross C→Zig→C→Zig per 4/8-byte draw. A buffered source or prepared/batch sampler ABI is the principal optimization opportunity.
  • Mitigated — WARNING: Poisson's exact sum-of-exponentials algorithm is linear in lambda. The public ABI now caps its exponent/resource domain; a transformed-rejection large-lambda implementation remains post-shipment.
  • Remaining — ADVISORY: hex/base64 use per-character stdio and ./stats retains distribution samples in Lua tables. Neither affects correctness at the documented default sizes.

6. Reliability and error handling

  • Fixed — WARNING: raw, hex, base64, text, choose, shuffle, and weighted paths all flush/check stdout. Auto-seeded deterministic mode refuses to emit output when its replay seed cannot be written to stderr.
  • Fixed: callback status identities are preserved for known randomz_status values; unknown nonzero failures map to entropy/source error.

7. Architecture

  • Fixed: the ReleaseSafe randomz test graph imports a separately ReleaseSafe fixed module rather than a ReleaseFast dependency.
  • Fixed: the public boundary now contains checked constructors, conversions, samplers, and state operations; the raw invariant-dependent arithmetic kernel remains internal.
  • Remaining — ADVISORY: differential-driver is installed by ordinary zig build because cross/oracle scripts consume its stable installed path, though the Nix product package deliberately omits it.

8. Maintainability

  • Remaining — WARNING: src/randomz_cli.c is a large multi-domain translation unit. Entropy, option parsing, encoding, and stdin operations should become private modules when the post-shipment distributions land.
  • Remaining — WARNING: distribution metadata and the cross-CLI corpus have manually synchronized owners. A descriptor table/shared corpus should precede the planned expansion in modes.
  • Fixed: stale references to the removed migration document and unavailable agent skills were removed from active plans.

9. Public API design

  • Fixed: randomz_fixed's representation and construction rule, callback-status behavior, formatting's unterminated-span contract, thread ownership, cloning, and zeroization are documented in the header.
  • Remaining — ADVISORY: package, header, and Zig manifest versions still have separate literals; release automation should enforce one source.

10. Developer experience and operations

  • Fixed: Zig and Nix installations include the shared self-test and license. Nix wraps the test with its tool closure; manual/Windows Bash requirements are documented. Package checks exercise all six invocation names and both installed --test paths.
  • Fixed: README now distinguishes the three default cross legs from the optional native macOS leg and provides a C embedding quick start.
  • Remaining — ADVISORY: two tracked developer-doc symlinks resolve into the maintainer's adjacent directories and dangle in a clean clone. The active plan is now substantially self-contained, but repository-local snapshots would improve outside onboarding.

11. Dependency management

  • Fixed: the Zig package allowlist includes the header, license, README, self-test, and all build inputs. An isolated zig fetch reconstruction must build/test/install successfully.
  • Fixed: both Zig and Nix product installs carry the MIT license; Nix's unused wrapper dependency was either removed or put to actual use for the installed test closure.
  • Remaining — ADVISORY: LuaJIT's pinned revision and the runtime mitigation roll-number constant are manually coupled and should gain a mechanical release check when the pin next moves.

12. Testing strategy

  • Fixed: CI now has separate correctness, deterministic stats-smoke, installed-package/ABI, ReleaseFast cross-architecture, and Windows x86_64 runtime checks. Required platform manifests cannot silently shrink.
  • Fixed: the full pre-push analysis separately samples true OS entropy at 4 MiB and 50,000 values/distribution for each implementation.
  • Remaining — WARNING: native macOS remains an SSH-controlled optional leg, and Windows ARM64 remains compile-only. CI must not describe those as native runtime evidence.

13. Product completeness

  • Fixed: surplus positional arguments, conflicting stdin operations, incompatible encodings, and irrelevant distribution parameters are rejected consistently by both CLIs.
  • Remaining — planned: the benchmark suite is intentionally still open; gamma, Weibull, Pareto/Zipf, geometric/binomial, Cauchy/Student-t, edge-biased, and log-uniform modes are recorded as post-shipment work.

Rust randomr milestone addendum

Date: 2026-08-11 Scope: the importable Rust core, Rust CLI, shared three-frontend controls, Cargo/Nix packaging, cross targets, and native-target workflow. Method: independent passes over review dimensions 1–4, 5–8, and 9–12, followed by reproduction and revalidation against the changing tree. Result: no critical findings or release-blocking warnings remain. All reproduced warnings were fixed; only explicitly deferred performance and organization advisories remain.

1. Inconsistent, incomplete, or undefined functionality

  • Fixed — WARNING: Rust binary output allocated the entire requested count (plus a second base64 buffer) and aborted on valid large requests. It now streams fixed 64 KiB chunks, carries 0–2 base64 bytes between chunks, and is proven byte-identical at counts 65,535–65,538 under all three encodings. A 128 MiB request must complete beneath a 64 MiB virtual-memory limit.
  • Fixed — WARNING: the first streaming edit duplicated the final raw chunk. Independent review caught it before acceptance; the all-encoding boundary matrix would also turn red for that implementation.
  • Fixed: fractional distributions now default to the deterministic maximum of 18 decimal places. --precision N and --truncate N explicitly truncate to 0–18 places without rounding in all three frontends.
  • Fixed: randomr stdin is byte-oriented, preserves non-UTF-8/NBSP bytes, and accepts non-UTF-8 --random-source paths through OsString/PathBuf.

2. Inadequate test coverage

  • Fixed — WARNING: direct library tests now pin every sampler's exact API output and byte consumption, u32/u64 rejection, typed source failures, invalid domains, DRBG state/cap/endian/zeroization behavior, and exact/EOF path entropy. The public doctest and downstream no-default-features consumer both compile.
  • Fixed — WARNING: the pinned getrandom Linux backend treats EPERM as unavailable and falls back to /dev/urandom, which could turn a sandbox policy denial into silent success. The Linux/Android adapter now owns the blocking syscall policy: it retries EINTR, continues exact partial reads, reports EAGAIN distinctly for nonblocking calls, falls back only on ENOSYS, and fails closed on EPERM, zero-byte returns, and hard errors. Injected syscall controls cover the policy-denial, missing-syscall, interruption, partial-read, and would-block paths without kernel faults.
  • Fixed: Windows/macOS ARM64 workflow payloads cover raw DRBG, every nonlinear distribution, a wide range, stdin shuffle, and OS entropy. The Windows leg also probes the Bash --test launcher; these become runtime evidence only after the remote workflow is green.

3. Futile or falsely reassuring tests

  • Fixed — WARNING: selector/oracle mutations used nonexistent /bin/false and went red at executable preflight. The candidate selector now resolves a real failing executable and requires a downstream diagnostic. The final Zig-vs-Rust oracle mutation uses an executable wrapper whose Zig producer succeeds but corrupts its output; the control requires the named final differential with both producer statuses equal to zero.
  • Fixed — ADVISORY: the purity check only searched a short list of std I/O paths. A dedicated gate now also rejects getrandom, libc, unsafe/FFI, output macros, ambient state, and entropy feature escape hatches everywhere outside entropy.rs; it verifies both OS dependencies remain optional and feature-confined. A feature-gated getrandom mutation in drbg.rs proves this stronger boundary can turn red.
  • Fixed — WARNING: the shared --test probe accepted the formerly vacuous Rust implementation. It now requires child depth zero, and installed-package testing caught/fixed a recursive Nix wrapper before release.
  • Fixed: architecture controls pin BLAKE3's zeroize feature and every seed/key/Hasher/OutputReader zeroizing guard, so deleting a wipe guard makes a source-level control red even though residual memory is not behaviorally observable.

4. Fast-test issues

  • Fixed — WARNING: all three pairwise comparisons reran the complete shared acceptance/chart stack. Each frontend now runs local acceptance once, while the third pair uses an explicit differential-only mode. All three 141-case exact matrices remain mandatory.
  • Fixed — ADVISORY: the nonlinear mutation still compiles an isolated release workspace, but now judges one frozen log-normal vector instead of rerunning the full acceptance/chart/differential stack. Producer independence is retained while routine mutation latency is sharply bounded.

5. Superfluous or duplicated functionality

  • Fixed: the dead public Error::BufferTooSmall variant was removed, and the duplicated fixed exponent-validity predicate plus raw 2^53 literals now have one core owner.
  • Remaining — ADVISORY: five cross-target/stat scripts repeat the same minimal cargo metadata target-directory extraction. A sourced Rust test setup helper would reduce maintenance without affecting behavior.

6. Suboptimal, inconcise, or disorganized code

  • Fixed: generalized differential diagnostics now identify the actual oracle/candidate pair rather than claiming every comparison is Lua-versus-C.
  • Remaining — ADVISORY: Rust CLI token interpretation is split across early actions, generation parsing, distribution help, and renderer selection. Options::parse also mixes consumption and cross-option validation. A typed command/action classifier should precede post-push CLI expansion.
  • Remaining — ADVISORY: numeric CLI parameters remain tuple-encoded as Option<(Fixed, String)>; a ParsedFixed type would make value/spelling ownership clearer before adding more distributions.

7. Algorithmic complexity and performance

  • Fixed — WARNING: encoded binary output is O(1) memory rather than O(requested output), while retaining O(n) time and exact byte order.
  • Fixed — ADVISORY: ./bm formerly timed the Nix Bash wrapper for randomr, whose repeated PATH setup added about 13 ms per process on the measured Linux host. The build now preserves the identical unwrapped ELF for timing while retaining the packaged CLI in the parity preflight. History schema 2 names this timing surface, so wrapper-era results cannot become a false regression baseline.
  • Fixed — ADVISORY: Rust formerly recomputed the log, exponential, sine, and cosine series reciprocal coefficients at runtime through the kernel's 62-step bit-serial division. It now builds exact tables during const evaluation, matching Zig's comptime policy. A red-before/green-after call counter proves ln, exp, and cosine no longer divide for coefficients; another test regenerates every table through the runtime kernel. Quick A/B CPU time improved 32–49% across the five nonlinear distributions while raw and uniform controls remained materially flat, and all benchmark payloads remained byte-identical across both Rust surfaces and both external oracles.
  • Remaining — ADVISORY: beta/log-normal curve rendering calculates every expensive score twice to find and then normalize the maximum. A bounded score vector can halve transcendental work.
  • Remaining — ADVISORY: scalar 4/8-byte sampler draws reconstruct a keyed BLAKE3 XOF reader. Measure this in the planned benchmark suite before adding a zeroized cache that could complicate state/clone semantics.

8. Files without clear purpose

No orphaned Rust file was found. The generated chart module, entropy mutant, downstream fixture, BSD/Windows link gates, and linker adapters each have a named consumer. The Windows ARM64 cross-link gate is now executed in CI rather than merely syntax-checked.

9. Rust language and public API design

  • Fixed: path-bearing argv uses OsString/PathBuf; arbitrary stdin items remain bytes. Rustfmt is repository-configured with hard_tabs = true.
  • Fixed: the crate has a compiling example and complete public rustdoc; documentation builds deny both warnings and missing docs. Seed secrecy, exported derived-key sensitivity, state restoration, and caller wipe ownership are visible at the API site. Planned-to-grow Error and Distribution enums are non-exhaustive.

10. Memory safety, resource ownership, and secrets

  • Fixed — WARNING: BLAKE3's feature alone does not wipe on drop. Incremental KDF and keyed-XOF Hashers, Hash/OutputReader temporaries, derived-key locals, restored-state parameters, option seeds, parsed environment seeds, and auto-seed storage now use zeroizing guards or explicit wipes. Drbg remains ZeroizeOnDrop; caller-owned seed/state copies are documented as caller responsibility.
  • Fixed: help/about/view/generation writes return ordinary I/O errors rather than panicking on /dev/full; the same audit also fixed buffered help/about write failures in the LuaJIT and C frontends.

11. FFI and cross-target boundaries

The Rust deterministic implementation uses no C ABI and shares no code with either oracle. Its sole unsafe block is the scoped Linux/Android getrandom call over a valid remaining slice; other entropy access uses safe Rust APIs. FreeBSD/NetBSD manifest identity is exact, Windows ARM64 is both cross-linked through Zig and proven by first-party native execution, and the pure core is compile-gated for wasm32-wasip1. Equivalent shippable Zig/Rust WASI artifacts remain a measured post-port decision.

12. Error handling and packaging

  • Fixed — WARNING: randomr --test formerly launched the shared suite at recursion depth one, so it returned green without tests. It now selects the Rust frontend at depth zero, propagates status, invokes Bash directly, and works from the standalone Nix package.
  • Fixed — WARNING: the first standalone wrapper forced its suite path and recursively defeated the suite's test probe. --set-default preserves explicit overrides, and package smoke invokes the standalone self-test.
  • Fixed: Unsupported, WouldBlock, EOF, and generic entropy failures have distinct typed errors and CLI diagnostics; path open errors retain path and OS cause. Output errors fail cleanly without panic diagnostics.
  • Remaining — ADVISORY: Nix Rust derivations still hash the full multi-language repository (src = ./.). A fileset limited to Cargo inputs would improve cache reuse, but changing source filtering immediately before shipment adds more packaging risk than value.

13. Database access patterns

Not applicable. The project and all three deterministic cores have no database or persistent RNG state.


Portable continuation-state milestone addendum

Date: 2026-08-13 Scope: uncommitted LuaJIT, Zig/C, and Rust continuation-state implementation, with special attention to the new Rust CLI/core boundary, hostile JSON input, and the shared Bash interoperability oracle. Method: independent fresh-context read-only review after the implementation and full green gate, followed by producer-side fixes and reviewer revalidation. Result: no critical, warning, or advisory findings remain in the reviewed feature. Every reproduced finding below was fixed before shipment.

Fixed findings

  • Fixed — WARNING: recursive C and Rust JSON parsers could overflow their stacks on deeply nested input within the 1 MiB stdin allowance. All three codecs now enforce 64 nesting levels, 32 object members, and 1024 array items; the C limits also prevent quadratic unknown-key parsing from becoming an input-amplification path.
  • Fixed — WARNING: LuaJIT and C accepted raw invalid UTF-8 state strings that Rust rejected, and could produce invalid JSON from a non-UTF-8 delimiter. State input and state-bearing delimiter output now share strict UTF-8 policy; diagnostics remain valid JSON even when hostile argv bytes are escaped.
  • Fixed — WARNING: Lua's JSON decoder accepted leading-zero numbers, non-JSON whitespace, and one missing-object-value shape. The shared negative matrix now pins the same strict grammar in every frontend.
  • Fixed — WARNING: state ranges accepted CLI shorthand despite claiming a canonical wire form. Consumers now require signed-integer M..N; dN, hyphen, and exclusive spellings are rejected in serialized state.
  • Fixed — WARNING: stdin-operation continuation originally covered only same-implementation --choose. It now covers all 3×3 producer/consumer directions for choose, shuffle, and weighted selection, requires successful nonempty output, validates the resumed state shape, and proves that its byte cursor advances rather than restarting from the seed.
  • Resolved contract ambiguity: rv is the informational producer application version requested by the state design, while sv is the enforced state/stream compatibility version. The documentation and oracle now pin that distinction so compatible application releases do not gratuitously invalidate state, and semantic changes must increment sv.
  • Fixed — WARNING: the Nix package installed the new Lua state module, but the top-level ./build copier omitted it from the stable zig-out tree. The in-memory ./bm --check package preflight exposed the missing module; the copier now installs it and all ten benchmark workloads again agree.

Independent oracle assessment

The generation matrix genuinely executes every directed 3×3 pair and compares each prefix-plus-resumed-suffix with its producer's uninterrupted baseline for ten fixed- and variable-consumption output families. The stdin matrix proves all directed pairs, successful cursor advancement, and three-consumer agreement; its semantic authority is differential rather than a separate external oracle. Together with the independent BLAKE3 implementations and existing sampler vectors, this is an appropriate control for a state transport feature rather than a new random algorithm.


State-schema 2, byte-delimiter, and Lean 4 milestone addendum

Date: 2026-08-26 Scope: schema-2 continuation transport, empty-delimiter byte semantics, the Lean deterministic model/proofs/frontend, Nix packaging, and the shared four-command-family gates. Method: one primary-agent review across all thirteen dimensions, aided by the current codescan index, direct source inspection, hostile probes, a controlled mutation, and the complete local test/statistical/benchmark gates. No separate review agent was used for this addendum. Result: no critical finding remains. Three substantive review findings were fixed; the remaining limitations below are explicit proof/product boundaries.

1. Functionality

  • Fixed — WARNING: a manually constructed Lean Drbg with a cursor already above 2^53 could accept a zero-byte fill because natural-number subtraction truncated the bound to zero. Drbg.fill now rejects an invalid incoming cursor, and fill_respects_position_limit proves the successful result cursor itself is at or below the ceiling.
  • Fixed — WARNING: Drbg.init accepted arbitrary seed lengths even though the wire contract is exactly 32 bytes and the modeled BLAKE3 subset is single-block. Initialization now returns none unless the seed is exactly 32 bytes.
  • Remaining — explicit boundary: randoml delegates its complete CLI, entropy, fixed-point distribution, and formatting surface to randomz. It is compatible but not a fourth independent behavioral oracle.

2. Coverage adequacy

  • Fixed — WARNING: one frozen seed/cursor vector did not adequately probe block boundaries or seeking in the independent Lean DRBG. The trust-zero gate now retains that frozen vector and adds five LuaJIT-oracle differentials across seeds, offsets 0/1/63/64/4097, and multi-block reads, plus seed and position boundary controls.
  • The shared state gate covers every 4×4 producer/consumer direction for fixed and variable consumption and every byte-oriented stdin operation direction.

3. Test validity

  • Mutation-verified: flipping one bit in the Lean BLAKE3 IV made the external vector gate fail; restoring the bit returned it to green. The proof-source scan, trust-zero elaboration, and #print axioms audit are separate controls.

4. Fast coverage

No sleeps or timing assertions were introduced. The five extra pure Lean differentials add seconds, not minutes; the multi-minute full gate remains dominated by release/cross builds and intentional mutation builds.

5. Duplication

Schema serialization remains deliberately independent in Lua, C, and Rust so the differential can detect a single-implementation mistake. The shared Bash contract is the single behavioral owner. No actionable duplication finding.

6. Organization

The Lean modules separate BLAKE3, DRBG/range execution, and proofs. Main.lean states its subprocess trust boundary directly. The established large C CLI translation-unit warning remains, but this feature did not materially worsen it.

7. Complexity

State JSON is capped at 1 MiB and already enforces depth/member/item limits. Empty-delimiter shuffle is O(n) storage plus O(n) Fisher–Yates work. The Lean BLAKE3 reference allocates arrays and is not presented as a throughput engine. Removing unnecessary Lean interpreter support reduced the stripped adapter from 10,320,384 to 2,007,232 bytes without changing behavior or proofs.

8. File purpose

Every new Lean and test file has one named role. The evaluation report is the claim matrix and judgment log requested for this experiment; it is not a second specification.

9. Language features

Lean source uses spaces because Lean 4.30 rejects tab indentation. The formal model uses machine words for executable BLAKE3 but does not yet prove a refinement to a separate BitVec/Nat compression specification.

10. Memory and resources

The C byte-item spans retain ownership in one backing allocation and preserve embedded NUL bytes without calling string routines on byte items. Rust owns each byte item. The Lean frontend waits for its child and introduces no persistent state or temporary payload files.

  • Fixed — WARNING: the initial installed Nix closure was 2.4 GiB because the CLI self-test wrapper retained the full CI toolchain and embedded Zig source paths made the WASM retain Zig/LLVM. A minimal, package-smoke-verified self-test PATH plus installation-time reference neutralization reduced the closure to 127.8 MiB without removing the installed self-test or WASM.

11. FFI correctness

The schema/delimiter work does not change the public C ABI. The complete ABI symbol/layout test and C CLI dogfooding remain green. randoml crosses a process boundary, not the C ABI, and is documented accordingly.

12. Error handling and proof gaps

  • Remaining — WARNING: Drbg.range is a partial executable rejection loop. Mapping bounds are proved, but termination and statistical uniformity of the complete loop are not; the report does not claim otherwise.
  • Remaining — ADVISORY: Lean's standard List String argv boundary cannot distinguish invalid UTF-8 replacement from a literal U+FFFD. The frontend fails closed, creating one documented false rejection. Exact parity would require a native raw-argv launcher that adds no value to the currently delegated CLI.
  • Fixed — ADVISORY: package smoke inherited /homeless-shelter as HOME, so recoverable test-shim cleanup printed a failed-directory diagnostic. It now uses private HOME/XDG directories and a mode-0700 runtime directory.

13. Database access

Not applicable. No command family persists RNG state or uses a database.


Full independent Lean implementation — final addendum (2026-08-26)

This addendum supersedes the delegated-adapter conclusions in the preceding Lean checkpoint. Three fresh-context reviews independently covered the Lean core and proofs, the CLI/native boundary, and repository-wide build/test/package behavior. Their actionable findings were reproduced and incorporated before shipment.

1. Summary and scope

randoml now owns its complete production behavior. The native C code is limited to raw argv, OS entropy, platform labels, Lean runtime startup, and Base64 transport acceleration. The independence gate rejects subprocess/dynamic-load surfaces and compares all deterministic distribution families to the external oracle while poisoning the former delegation environment variable.

  • Fixed — BLOCKER: the previous executable delegated nearly the entire CLI to randomz, so benchmarks and shared tests did not evaluate Lean algorithms. Delegation was removed; 141 exact CLI cases and ten benchmark payloads now run the Lean implementation itself.
  • Fixed — BLOCKER: the exact frontend differential was not wired into tests/randoml_test, allowing an edge mismatch (1...1) through the nominal shared suite. It now runs on every randoml_test invocation.
  • Fixed — BLOCKER: a clean suite could reach randoml_test before building randoml. The suite and independence gate now build the owned executable when one is not explicitly supplied.

2. Correctness

  • Fixed — BLOCKER: Lean's singleton range path consumed one draw while the other three implementations consumed none. Production now returns the singleton without advancing state; shared continuation tests freeze it.
  • Fixed — WARNING: raw action-flag pre-scanning interpreted option values such as --delimiter --help as actions. The value-aware parser now owns action selection.
  • Fixed — WARNING: invalid UTF-8 delimiters could fail only after earlier output had already been emitted. Validation now occurs before output.
  • Fixed — WARNING: normalInt accepted a range one unit wider than the common 2^53 contract because its comparison was exclusive. It now rejects width >= clamp.
  • Fixed — WARNING: public BLAKE3 and DRBG shapes admitted invalid key/message sizes and manually manufactured invalid state. Constructors/helpers are now checked, Drbg.mk is private, and large fills are bounded and streamed.
  • Fixed — WARNING: the state parser's recursive implementation and resource limits were not production-total. It is structurally terminating and its exact 1 MiB/depth/member/item boundaries are controlled.

3. Tests and test quality

  • Fixed — BLOCKER: installed randoml --test recursively selected a wrapper and failed. The wrapper uses a default test path and the Lean CLI explicitly identifies itself to the shared harness. The dedicated installed package now self-tests.
  • Fixed — WARNING: the axiom gate was name-shaped and could continue passing after theorem weakening. ProofContract.lean restates release-critical exact theorem types, and the audit requires exactly 25 approved result lines.
  • Fixed — WARNING: BLAKE3 testing lacked standard vectors and parser tests lacked exact limits. Official empty/abc vectors and both sides of all parser boundaries are now gated.
  • Fixed — WARNING: the only chunking theorem concerned an abstract stream. That theorem is now described honestly; executable controls separately compare production fill(a+b) with resumed fill(a); fill(b) across BLAKE3 boundaries.
  • Remaining — WARNING: Blake3.xofAt/Drbg.fill byte content has no formal refinement theorem connecting it to streamSlice. Exact independent vectors and differentials control it today; formal connection is tracked in PLAN.md.

4. Fast coverage

Pure theorem/vector fixtures remain fast. The shared CLI/state tests are pure calculation except deliberate OS-entropy controls. Cold full-suite time is still dominated by release, cross-target, package, and mutation builds, not sampling. No sleeps or timing assertions were introduced.

5. Duplication

  • Remaining — WARNING: CliSource repeats the deterministic distribution control flow for OS-entropy draws. Both copies are Lean-owned and exact tests agree, but the correct abstraction is one pure sampler program interpreted by either a DRBG or native byte source. This is tracked as post-port architecture work rather than hidden as an I/O exception.
  • The four independent implementations intentionally duplicate algorithms; the shared Bash contract, official vectors, and cross-implementation differentials turn that duplication into an oracle rather than an unreviewed fork.

6. Organization

  • Fixed — WARNING: dormant callback/FFI/ABI files described a second unbuilt architecture, lacked correct runtime initialization, and duplicated sampling logic. They were removed to Trash. The surviving native files have one purpose each: runtime/raw-argv launch and native I/O/transport helpers.
  • Fixed — ADVISORY: Lake's default target built a diagnostic dummy instead of the library. lake build now builds Randoml; the owned executable has one explicit build script.

7. Complexity

  • Fixed — WARNING: pure Lean Base64 took about 22 seconds for a 1 MiB payload. The byte transform is now accelerated at the native transport edge and matches frozen digests/framing; end-to-end Base64 is about 104 ms in the quick run.
  • Fixed — ADVISORY: JSON quoting, stdin accumulation, and byte trimming used repeated immutable concatenation. They now use byte builders/chunk collection.
  • Remaining — ADVISORY: the reference-style Lean fixed-point/nonlinear code is 12–53x slower than the fastest implementation in the quick suite. This is acceptable for an oracle, but profiling/algorithmic work is required before presenting it as a high-throughput path.

8. File purpose

Every new production module now has a distinct concern: native declarations, DRBG/BLAKE3, fixed arithmetic, samplers, state, options, source interpretation, shuffle, chart model/encoding, CLI orchestration, proofs, and exact proof contracts. The evaluation report is the requested experiment record and claim matrix rather than a second normative specification.

9. Language features and proof discipline

The implementation uses private constructors and checked wrapper types to carry invariants into theorem statements. Recursive rejection sampling is explicitly fuel-bounded by the public cursor ceiling; there are no proof escapes or nontermination markers in trusted source. Lean files use spaces because Lean 4.30 rejects tab indentation.

  • Remaining — WARNING: BLAKE3 compression has no refinement to a separate BitVec/mathematical standard model, and fixed/transcendental numerical error bounds are not formally established. The report labels these as tested, not proved.

10. Memory and resources

  • Fixed — BLOCKER: xofAt could allocate an arbitrary caller-requested output. Public fill is capped at 1 MiB per call and CLI output streams bounded chunks, preserving the 2^53 logical cursor.
  • Fixed — BLOCKER: Windows BCryptGenRandom narrowed size_t to ULONG, potentially leaving a large-request tail uninitialized. Requests are chunked at the API's 32-bit ceiling.
  • State input remains capped at 1 MiB and parser containers/depth are bounded. The dedicated stripped binary is 2,781,384 bytes; the measured Nix closure is 120.7 MiB rather than the accidental initial 2.4 GiB.

11. FFI/native-boundary correctness

The final executable has no public Lean-specific C ABI: its native calls are an internal implementation boundary. Every platform entropy branch checks short reads/errors and Linux denial is fault-injected. The C source is cross-compiled and symbol/provenance-gated for Linux, macOS, OpenBSD, FreeBSD, NetBSD, illumos, and Windows.

  • Fixed — WARNING: the illumos preprocessor label was shadowed by the generic Solaris branch. Ordering now makes the intended label reachable.
  • Remaining — WARNING: native Lean runtime/digest execution is currently measured only on x86_64 Linux. aarch64 Linux/macOS and a supported Windows Lean toolchain are explicit plan items; source cross-compilation is not reported as runtime proof.

12. Error handling and proof gaps

Errors remain structured JSON and entropy failures fail closed. Checked factories return Option/Except; malformed state and unsupported sizes cannot reach unchecked internal constructors. User-facing parse errors are differentiated where the shared contract requires exact text.

Remaining formal gaps are stated in the evaluation matrix: actual XOF refinement, cryptographic security, statistical uniformity, complete fixed-point/distribution accuracy, and compiler/runtime/hardware correctness are not claimed as proved.

13. Database access

Not applicable. RNG continuation state is explicit process input/output and no implementation persists it in a database or temporary payload file.

2026-09-30: caller-owned LuaJIT library

A fresh reviewer derived the library contract before inspecting the extraction. The review found three validation defects: fractional mantissas could hang inside normalization, an explicit false position defaulted to zero, and normal_int accepted an inclusive span wider than 2^53. Persistent rejection tests were added; the constructor regression failed before the fixes. Canonical-pair validation now avoids normalization, only nil defaults the position, and both range methods share an exact-width guard. Log-normal and beta parameter domains now match Rust.

The reviewer independently rechecked 115 malformed-parameter cases, ownership and clone isolation, 500 interleaved calls, import/draw I/O traps, exact-span boundaries, nonlinear domain corners, and 43 exercised rejection paths. A 131,073-byte native Zig/C differential covered a maximal seed, chunk boundaries and positioned reads. The shared suite compares values and byte cursors with all four CLIs. No remaining actionable LuaJIT defect was found in this scope.

The Nix library gate now executes installed consumers for all four languages: LuaJIT module contracts, Zig module and shared C ABI frozen bytes, Rust frozen bytes/normal/resumption, and Lean compiled-module frozen bytes/resumption. checks.x86_64-linux.library-packages is an exact-commit CI target. These are deterministic execution controls, not a cryptographic security proof.

A five-run release-CLI smoke comparison found no meaningful extraction slowdown: 20,000 d20 draws measured 49.4 ms before and 49.7 ms after; 2,000 normal integers measured 230.7 ms before and 230.2 ms after. Hyperfine discarded output; no random payload files were written. Measurement variance was larger than these changes.

The ai_edu agent acknowledged consuming the pinned random-luajit-lib output at d2dd7e7 and reported 112 passing specs plus its own nix flake check. This is downstream-reported integration evidence, not a test run by this agent.

2026-09-30: bounded Kani core contracts

The independent reviewer froze obligations before implementation inspection and granted acceptance after replaying all 42 actual exports (21 false controls and 21 positive contracts). It independently regenerated the complete 24-file fingerprint set and discovery from all four compiled targets. All 89 mandatory positive assertions and 79 required covers passed. Four constant-disabled covers and four forbidden-call guards retain separately pinned Unreachable statuses.

Review tightened negation against a no-op implementation, replaced collusive canonicality checks with a mathematical predicate, required exact assertion and cover provenance, rejected multiple top-level JSON documents, and exposed why filtered-only discovery can conceal an omitted proof. Six additional mutations of actual exports/discovery were independently rejected. Production-module changes are only cfg(kani) registrations; algorithms and production toolchain are unchanged. The report and replayable acceptance summary state each bounded domain, model, exclusion, resource cost and source identity.

MAX/general multiplication remains unproved after solver timeouts. A rejected SMT diagnostic's four exported witnesses pass native execution under both the production and exact verification-nightly compilers; no faulty component or production defect was established. These are open follow-ups, not exceptions to the acceptance gate or a whole-library/security correctness claim.

2026-10-01: continuous CLI streaming

A fresh reviewer froze twelve streaming obligations before inspecting the four adapter changes. It accepted this increment after 68 machine-asserted controls and 16 additional positive probes across LuaJIT, Zig/C, Rust and Lean. The fresh complete suite then passed: all 29 suites, including 168 shared streaming checks and 1,060 continuation checks. Generator arithmetic, cryptographic algorithms, public library interfaces and Lean proof modules are unchanged.

The review found delayed Lua payload flushes and final-state-only writes that bypassed quiet broken-pipe handling. It also reproduced a /dev/full defect: zero-count stdout state returned empty-stderr failure in Lua and false success in Lean. All four adapters now report real sink failures as JSON and exit quietly when the consumer is already closed. Regressions create a readerless pipe before exec rather than depending on a race with head -c 0.

Producer red tests also exposed finite direct-byte cursor overflow leaking a prefix and incorrect Lua/Lean Base64 padding at unbounded cursor exhaustion. Direct finite reads now preflight the complete count; continuous Base64 retains at most two carry bytes and pads only on finite completion. The consumer's independent seed-0, 8,192-byte SHA-256 fixture anchors the new streaming default; committed finite goldens were not changed. Pipeline checks assert producer and consumer status independently of digest equality.

Memory controls deliver 256 MiB through pipes under a 128 MiB peak-resident threshold for each implementation, with an additional address-space limit for the three non-Lean adapters. Lean's unchanged runtime reserves large stacks and arenas, so its control uses resident memory rather than address space. Numeric controls and source inspection cover bounded buffers and the absence of retained value history or duration-proportional counters. These are execution and lifetime controls, not a formal proof of an infinite run. No payload files are written. Lean's release builder also consumes runtime linker inputs in one compile/link invocation; the production build now has a warning-rejection gate.

The frozen obligation's unconditional interrupted-write retry sub-clause remains unestablished for the inherited C/Lua/Lean stdio boundary. Rust write_all retries interrupted writes; the other writers check full completion and fail closed, but no interrupted/zero-progress syscall fault injection was performed. This acceptance is scoped to the changed streaming behavior, not every frozen sub-clause, a new streaming theorem, cryptographic security or native execution on platforms other than this x86_64 Linux host. Optional output pacing remains deferred and must not be advertised as improving entropy or statistical quality.

The first exact-commit Nix CI run passed all 168 new stream checks but rejected the older LuaJIT huge-prefix control: it still required status 1 or 141 after consumer closure. CI inherited ignored SIGPIPE, exposing the new intentional quiet-success path. The failure was reproduced locally with ignored SIGPIPE. That control now exercises default and ignored handling, accepts only 0 or 141, and asserts every pipeline status plus empty diagnostics. GNU env explicitly sets each producer's signal disposition, regardless of the CI parent's setting. The reviewer independently observed status 141/default and 0/ignored with exact Zig prefix digests, and checked the finite numeric fixture against Bash printf. Its oracle remains the finite Zig digest; neither source bytes nor expectations were regenerated. The numeric memory fixture also uses a finite awk producer instead of yes to avoid unrelated fixture broken-pipe diagnostics under ignored SIGPIPE. The complete local rerun passed all 29 suites; the final explicit-signal control also passed all 54 checks under an ignored parent signal before shipping.