aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#130 (code only)
Apply it
git checkout -b patch-44d2f44dc4c79b2f e1c50184bdf73d9f130d23b5a1033edbb09ef72d curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/44d2f44dc4c79b2f.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
130
4026e6cef61704fa7aa0872076fbda63bc37d546
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":130,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/130","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:03Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Cargo.lock b/Cargo.lock index ff25bb98..48e3c5c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1040,6 +1040,16 @@ dependencies = [ "uuid", ] +[[package]] +name = "crumbs" +version = "0.1.0" +dependencies = [ + "blake3", + "serde", + "serde_json", + "uuid", +] + [[package]] name = "crypto-bigint" version = "0.7.5" diff --git a/Cargo.toml b/Cargo.toml index 01e39175..cff610c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,7 @@ members = [ "crates/cortex-path-m1", "crates/aien-campaign-verifier", "crates/aien-proof", + "crates/crumbs", ] [workspace.package] diff --git a/crates/crumbs/Cargo.toml b/crates/crumbs/Cargo.toml new file mode 100644 index 00000000..d5be7e89 --- /dev/null +++ b/crates/crumbs/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "crumbs" +description = "Crumbline: the Crumb v1 curriculum substrate for AIEN (visible/sealed contract, generators, mixer, verifier contract, trace corpus, promotion ladder, ledger)" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true + +# Standalone by rule: no dependency on crumb-spec, spark-crumbs or any other +# workspace crate. Only ledger machinery: BLAKE3, UUID v7, serde. +[dependencies] +blake3 = "1.8" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +uuid = { version = "1", features = ["v7", "std", "serde"] } + +[[bin]] +name = "crumbs" +path = "src/bin/crumbs.rs" + +[[bin]] +name = "crumbs-probe-learner" +path = "src/bin/crumbs-probe-learner.rs" diff --git a/crates/crumbs/SPEC.md b/crates/crumbs/SPEC.md new file mode 100644 index 00000000..31e87fcd --- /dev/null +++ b/crates/crumbs/SPEC.md @@ -0,0 +1,171 @@ +# Crumb v1 Specification + +**Status:** ACCEPTED: Crumb v1 Architecture; implementation qualification pending. +**Date:** 27 September 2026 (drafted); accepted with four amendments the same day. +**Purpose:** Define the permanent curriculum substrate for AIEN: the problem instances AIEN learns from, the sealed machinery behind them, and the evidence pipeline that turns searches into training data. + +Nothing in this spec may be quoted as a result. A mechanism is a proposal until it is built, measured and ratified. Section 18 lists what v1 implements today and where; section 19 lists what is deliberately deferred. + +## The Crumbline + +The curriculum's public name is the **Crumbline**: the unbroken lineage of AIEN's training records. Every crumb AIEN solves and every trace it learns from is a record of something the machine actually did, verified against sealed held-outs. + +The guarantee: **LLMs built the structure. They never touched the training data or the training process.** Language models built the laboratory: the generators, the harness, the curriculum machinery. No traditional LLM touches AIEN's training data or its training process. + +That claim is encoded as a mechanically checkable chain, not doctrine. Every Crumbline record binds the generator instance digest, the sealed record digest, the verifier digest, the learner-visible digest, the learner build digest, the evaluation receipts, the trace stream digest and the previous Crumbline root (section 4.4). + +--- + +## 1. What a crumb is + +A crumb is one learning problem presented to AIEN as **observations only**: input/output examples with no title, explanation, difficulty or purpose. One crumb may be a toy invented a minute ago, another a bounded shadow of a deep open problem, another deliberately meaningless. To AIEN they are all observations. + +A crumb is not a benchmark item, a test question or a fact to memorize. It is the substrate AIEN grows up inside. + +## 2. The non-negotiable rule + +**AIEN is never told why a crumb matters.** + +No titles, no topic words, no equations, no explanations, no difficulty labels, no signal that one problem matters more than another. The task boundary comes from the runtime (produce the outputs), never from descriptive text. + +This is an information-segregation rule enforced by process boundaries, types and tests (section 10), not a UI choice. It is what makes later rediscovery checkable. + +## 3. The old crumb standard + +`crumb-spec` and `spark-crumbs` mean something else: filesystem agent scent trails for coordinating LLM coding agents. The curriculum takes zero dependency on them. The two systems share no code, schemas or identity spaces. + +## 4. The Crumb v1 contract + +### 4.1 Visible side (AIEN sees this) + +An ordered list of examples, each `INPUT_BYTES -> OUTPUT_BYTES`, plus the minimum structure needed to parse them. Canonical bytes (`crumbs::visible`): + +```text +"CRB1" | schema_version u16 (=1) | encoding u8 | flags u8 +in_arity u8 | out_arity u8 | in_lane_bytes u8 | out_lane_bytes u8 +n u32 | n x (u32 len, input bytes, u32 len, output bytes) +[optional budget: max_candidates, max_depth, max_oracle_queries, max_program_ops, 4 x u32] +``` + +Encoding 1 is canonical decimal UTF-8 lanes separated by one space (v1 default). Encoding 2 is raw little-endian lanes (reserved move to raw bytes). Decoding is strict: bytes decode only if re-encoding reproduces them exactly. + +### 4.2 Sealed side (AIEN never sees this) + +`crumbs::sealed::SealedCrumb`: crumb digest, family id and key, mechanism, generator version, generator code digest, seed, held-out seed, canonical generation parameters, generator instance digest, verification method, difficulty, capability rung, required and provided capabilities (opaque BLAKE3 ids), provenance and contamination class, source family, truth status (verified, conjectural, none), decoy status (clean, rabbit hole with class A to G, no structure), known-solution status, rival explanations, noisy visible indices, expected domain, internal topic, and three held-out tiers (interpolation, extrapolation, adversarial). Its `Debug` output is redacted. + +Occurrence-level facts (population tag, draw reason, time) live in the ledger, not in the sealed record, so the sealed record is a pure function of its generator inputs. + +### 4.3 Identity (amendment 4) + +```text +CrumbOccurrenceId UUID v7: this presentation in this run +CrumbDigest BLAKE3(canonical learner-visible Crumb v1 bytes) the observable problem +GeneratorInstanceDigest BLAKE3(family_id || generator_version || seed || canonical parameters) +SealedRecordDigest BLAKE3(canonical sealed record); never enters learner space +``` + +Every digest uses its own BLAKE3 `derive_key` context. Two independently generated crumbs that expose the same phenomenon get the same CrumbDigest, and the system can see that without revealing why. + +### 4.4 The Crumbline ledger + +`crumbs::ledger`: each record binds seq, lane, occurrence, condition, population, CrumbDigest, GeneratorInstanceDigest, SealedRecordDigest, verifier digest, learner digest, evaluation digests, trace stream digest, promotion digests and the previous root. `Ledger::verify` recomputes the chain from genesis. Lanes (main, clean room) are separate chains. + +## 5. Generator families (amendment 1) + +The v1 target is **100 registered family ids** over **at least 24 genuinely distinct mechanisms** covering every rung. Families are parameterizations of reusable mechanisms and combinators, not copies. Acceptance is measured acquisition and reuse, not a file count. + +Rungs (builder vocabulary, never sent to AIEN): single transformation, two transformations, repeated transformation, conditional transformation, multi-input relation, recurrence, state, composition, symmetry, modularity, invariance, multi-step algorithms, latent variables, noisy observation, partial observation, counterexample search, theory formation. + +Interface: `gen::generate(family, seed) -> (VisibleCrumb, SealedCrumb)`, deterministic in (family id, generator version, seed, parameters). Held-out inputs are disjoint from visible inputs and from each other. A golden digest over every family at fixed seeds pins behaviour; changing a generator without bumping `GENERATOR_VERSION` fails the test suite. + +## 6. Composition: the breadcrumb trail + +Every operation AIEN discovers and verifies can become a building block for later crumbs. Capability families teach hidden capabilities; composition families quietly require two or three of them. The Omega Library is AIEN's accumulated collection of verified transformations, each with a provenance chain back to the crumbs that demanded it. + +## 7. Adversarial generators + +Rabbit holes deceive; they never lie. No wrong answer is ever labeled correct. Classes: A simple wrong rule, B several programs fit, C spurious dimension, D prefix imitates then diverges, E arbitrary table with an elegant prefix, F insufficient evidence, G noisy observations; plus no-structure crumbs. **Pattern observed is not law established.** The learner may, and should, retain uncertainty. + +## 8. Secret populations and the mixer + +Initial schedule, loaded from `config/mixer.v1.json`, not hard-coded: 55 fundamental, 20 composition, 10 ambiguous, 10 rabbit hole, 5 frontier. The population tag is sealed. Consecutive crumbs never share a family or a capability. The mix adapts to evidence: as capabilities are demonstrated, weight moves from acquisition to composition. A population with nothing eligible (v1 has no frontier sources) is redistributed and the redistribution is recorded. + +## 9. Frontier feeders + +For unresolved mathematics: open structure, finite instance, exact computation or proof, byte examples. The conjecture is never shown, and a relationship AIEN extrapolates beyond the verified region enters a conjecture pipeline, never learned truth. **Deferred past v1** (section 19). + +## 10. Verification protocol and the information boundary + +The learner is a separate operating-system process with an empty environment. The only channel is the learner protocol (`crumbs::protocol`), whose frames carry exactly: HELLO (search limits), CRUMB (visible bytes), VERDICT (one byte), ADMIT (an operation, its reference and scope), SHUTDOWN; and from the learner READY, BANK, SUBMIT, EVENTS, DONE. No frame can carry a sealed field. Any unknown frame aborts the session with no reply. The oracle answers at most `max_oracle_queries` submissions per crumb; after that it answers "budget exhausted" without evaluating. + +The verifier contract (amendment 3) is generic: candidates arrive as learner-neutral **CPG1** programs (`crumbs::program`), and the sealed verifier executes them with its own interpreter against visible examples and all three held-out tiers. A candidate that interpolates the visible samples but fails a held-out is `FalsifiedHidden`: recorded as a useful failure, never discarded. + +## 11. Clean-room lane (amendment 2) + +Built in v1: contamination classes (SyntheticNovel, AdversarialSynthetic, HumanTheoryDerived, FrontierDerived, RealWorldMeasured), human-constant and human-ontology flags on every family, the forbidden-source policy `provenance::clean_room_check`, a clean-room ledger partition that refuses forbidden records, and a clean-room mixer mode. Actual Physics Zero worlds are **not** built in v1. + +## 12. Trace capture + +The learner reports bare search events (operation applied, node ids, prune reason, verification outcome). The sealed side reconstructs every candidate program from those events and the declared operation bank and derives state digests, remaining-mismatch vectors, improvement flags, result classes (pruned, failed, partial, improved, verified, rejected by held-outs, rejected robust guess) and contribution to the verified solution. Held-out results enter a record only on SUBMIT events, as the verdict the learner received. Records (`CTR1`, 247 bytes) and training samples (`CTS1`, 268 bytes, one per decision state on a verified path, equivalence-aware positives) are fixed-size, numbers only and BLAKE3 hash-chained. No record can hold reasoning text. + +## 13. Evidence-based promotion + +```text +candidate operation sub-chain of an accepted solution +held-out verified part of a solution the sealed verifier accepted +corroborated supports >= 2 distinct crumbs +survived adversarial every support passed a non-empty adversarial tier; exposures bounded +generalized every support passed a non-empty extrapolation tier +admitted sent to the learner's library with an explicit scope +``` + +Scope is recorded, not assumed: `scope_bits` is the widest input magnitude over which a supporting solution was verified, and the learner refuses to offer an operation on crumbs outside it. + +## 14. Endgame (out of v1 scope) + +Self-generated curricula: AIEN constructs tests of what it believes, Omega realizes them, the verifier evaluates, Cortex records evidence. v1 must not preclude this and does not attempt it. + +## 15. Milestone 1 scope + +In scope: the contract (4), 100 registered families over >= 24 mechanisms (5), adversarial families (7), the mixer (8), the Omega adapter with architectural sealed-side blindness and the held-out verifier (10), trace capture (12), the promotion ladder (13), the clean-room boundary (11). + +Out of scope: frontier feeders (9), actual clean-room physics worlds (11), self-generated curriculum (14). + +**Acceptance:** measurable acquisition and reuse of progressively deeper operations, with the reuse recorded in provenance chains. If composition crumbs are solved without reusing earlier discoveries, the trail is not a trail. + +## 16. Ownership (amendment 3) + +- `crumbs` (this crate, aien-sovereign-core `crates/crumbs`): contracts, identities, generators, mixer, verifier contract, protocol, trace schema, promotion evidence, ledger. It knows nothing of Omega internals and depends only on BLAKE3, UUID and serde. +- `omega` (aien-dev/omega): the consumer adapter. `build/crumbline-learner` reads Crumb v1 bytes, runs Omega synthesis, submits CPG1 candidates, stores admitted operations in the OmegaLibrary. +- `crumb-spec`, `spark-crumbs`: untouched. + +## 17. Open questions resolved at acceptance + +1. 100 registered family ids is the target; >= 24 distinct mechanisms is the floor; acceptance is acquisition and reuse. +2. The clean-room boundary is built now; physics worlds wait. +3. The Omega adapter lives in Omega; the protocol and generic verifier contract live in `crumbs`. + +## 18. Implementation map (v1) + +| Mechanism | Code | Test or gate | +|---|---|---| +| Visible contract, strict decode, CrumbDigest | `src/visible.rs`, `src/digest.rs` | `tests/boundary.rs` crumb_v1_format_pass | +| Sealed record, redacted Debug, digests | `src/sealed.rs` | boundary: sealed_boundary_pass_* | +| 122 registered families, 38 mechanisms, capability pool | `src/gen/` | `tests/generators.rs` | +| Determinism and golden pin | `src/gen/mod.rs` | generators crumb_determinism_pass, boundary crumb_determinism_golden_pass | +| Verifier contract, CPG1 | `src/verify.rs`, `src/program.rs` | generators, gates CRUMB_HIDDEN_VERIFY_PASS | +| Process boundary, protocol, oracle budget | `src/protocol.rs`, `src/bin/crumbs-probe-learner.rs` | boundary no_hidden_access_* , gates CRUMB_NO_HIDDEN_ACCESS_PASS | +| Trace corpus and samples | `src/trace.rs` | curriculum crumb_trace_and_sample_pass, gates CRUMB_TRACE_PASS / CRUMB_TRAINING_SAMPLE_PASS / NO_COT_STORAGE_PASS | +| Promotion ladder and scope | `src/promotion.rs` | curriculum crumb_operation_promotion_pass, gates CRUMB_OPERATION_PROMOTION_PASS / CRUMB_LIBRARY_REUSE_PASS / CRUMB_SCOPE_ENFORCEMENT_PASS | +| Mixer | `src/mixer.rs`, `config/mixer.v1.json` | curriculum crumb_curriculum_pass / crumb_no_category_leak_pass | +| Clean room | `src/provenance.rs`, `src/ledger.rs` | curriculum clean_room_provenance_pass | +| Ledger | `src/ledger.rs`, `src/session.rs` | curriculum ledger_chain_detects_tampering | +| Acquisition and reuse experiment | `src/experiment.rs` | `crumbs experiment --learner PATH [--replicates K]` | + +## 19. Deferred (not implemented in v1) + +- Frontier feeders and the conjecture pipeline (section 9). +- Clean-room physics worlds and the hidden-law world interface. +- Cortex ingress of candidate relations and evidence. Cortex (`crates/cortex-rs`) already has the candidate, evidence and promotion model this should use; v1 writes promotion records and evaluation receipts to files only. +- AIEN_0 next-action guidance: the trace corpus is its training input; no trained policy exists yet. +- Multi-lane CPG1 programs. v1 candidates map lane 0 to lane 0, so multi-input families are valid crumbs that the Omega adapter reports as unsupported. diff --git a/crates/crumbs/config/mixer.v1.json b/crates/crumbs/config/mixer.v1.json new file mode 100644 index 00000000..f5f1cd62 --- /dev/null +++ b/crates/crumbs/config/mixer.v1.json @@ -0,0 +1,17 @@ +{ + "populations": { + "Fundamental": 55, + "Composition": 20, + "Ambiguous": 10, + "RabbitHole": 10, + "Frontier": 5 + }, + "select_new": 40, + "select_retention": 20, + "select_uncertain": 20, + "select_random": 20, + "adapt_pct": 50, + "clean_room": false, + "capability_subset": null, + "composition_keys": null +} diff --git a/crates/crumbs/src/audit.rs b/crates/crumbs/src/audit.rs new file mode 100644 index 00000000..cca12c4b --- /dev/null +++ b/crates/crumbs/src/audit.rs @@ -0,0 +1,195 @@ +//! Leak audits: the vocabulary that must never reach a learner, and scanners +//! for byte streams and for a live learner process's memory. + +use crate::digest::Digest; +use crate::gen::{registry, Mechanism}; +use crate::sealed::{AdversarialClass, Population, Rung, SealedCrumb, SourceFamily}; + +/// Every human-readable label the sealed side knows (>= 5 chars, so short +/// coincidences in binary data are not mistaken for leaks). +pub fn label_vocabulary() -> Vec<String> { + let mut v: Vec<String> = Vec::new(); + for f in ®istry().families { + v.push(f.key.clone()); + v.push(f.topic.to_string()); + } + for m in Mechanism::ALL { + v.push(m.key().to_string()); + } + for r in Rung::ALL { + v.push(format!("{r:?}")); + } + for p in Population::ALL { + v.push(format!("{p:?}")); + } + for s in [ + SourceFamily::Capability, + SourceFamily::Composition, + SourceFamily::Ambiguous, + SourceFamily::RabbitHole, + SourceFamily::Frontier, + SourceFamily::CleanRoomPhysics, + ] { + v.push(format!("{s:?}")); + } + for c in [ + AdversarialClass::SimpleWrongRule, + AdversarialClass::MultiFit, + AdversarialClass::SpuriousDimension, + AdversarialClass::PrefixDiverges, + AdversarialClass::ElegantArbitrary, + AdversarialClass::InsufficientEvidence, + AdversarialClass::Noisy, + ] { + v.push(format!("{c:?}")); + } + for w in [ + "SyntheticNovel", + "AdversarialSynthetic", + "HumanTheoryDerived", + "FrontierDerived", + "RealWorldMeasured", + "decoy", + "rabbit", + "heldout", + "held-out", + "difficulty", + "prime", + "gravity", + "conjecture", + "algebra", + "velocity", + "energy", + "force", + "charge", + "crumbs-registry", + ] { + v.push(w.to_string()); + } + v.retain(|s| s.len() >= 5); + v.sort(); + v.dedup(); + v +} + +/// Labels that exist only in the sealed registry (family keys, mechanism keys, +/// topic phrases). Generic English words are excluded, so this list can be +/// used to scan a learner binary's own code and read-only data. +pub fn sealed_specific_labels() -> Vec<String> { + let mut v: Vec<String> = Vec::new(); + for f in ®istry().families { + v.push(f.key.clone()); + v.push(f.topic.to_string()); + } + for m in Mechanism::ALL { + v.push(m.key().to_string()); + } + v.push("crumbs-registry".into()); + v.retain(|s| s.len() >= 6); + v.sort(); + v.dedup(); + v +} + +pub fn contains(hay: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) +} + +/// Labels found in `bytes` (case-sensitive and lowercase variants). +pub fn find_labels(bytes: &[u8]) -> Vec<String> { + let mut hits = Vec::new(); + for l in label_vocabulary() { + if contains(bytes, l.as_bytes()) || contains(bytes, l.to_lowercase().as_bytes()) { + hits.push(l); + } + } + hits +} + +/// Sealed secrets of one crumb that could identify a leak: its digests and +/// every held-out output (and input) value that does not also occur visibly. +pub fn sealed_needles( + sealed: &SealedCrumb, + visible_values: &[(Vec<u64>, Vec<u64>)], + min_value: u64, +) -> Vec<Vec<u8>> { + let mut vis: Vec<u64> = Vec::new(); + for (i, o) in visible_values { + vis.extend(i); + vis.extend(o); + } + let mut out: Vec<Vec<u8>> = Vec::new(); + for d in [ + sealed.digest(), + sealed.generator_instance_digest, + sealed.heldouts.digest(), + sealed.generator_code_digest, + ] { + out.push(d.0.to_vec()); + out.push(d.hex().into_bytes()); + } + for t in crate::sealed::HeldoutTier::ALL { + for ex in sealed.heldouts.tier(t) { + for v in ex.output.iter().chain(ex.input.iter()) { + if *v >= min_value && !vis.contains(v) { + // Only distinctive encodings count as evidence of a leak: a + // mostly-zero u64 matches ordinary length fields by chance. + let le = v.to_le_bytes(); + if le.iter().filter(|b| **b != 0).count() >= 5 { + out.push(le.to_vec()); + } + let dec = v.to_string(); + if dec.len() >= 6 { + out.push(dec.into_bytes()); + } + } + } + } + } + out +} + +pub fn find_needles(bytes: &[u8], needles: &[Vec<u8>]) -> usize { + needles.iter().filter(|n| contains(bytes, n)).count() +} + +/// Read every writable mapping of a live process (heap, stack, anonymous and +/// data segments). Requires permission to trace the process (a child of ours). +pub fn read_process_writable_memory(pid: u32) -> std::io::Result<Vec<u8>> { + use std::io::{Read, Seek, SeekFrom}; + let maps = std::fs::read_to_string(format!("/proc/{pid}/maps"))?; + let mut mem = std::fs::File::open(format!("/proc/{pid}/mem"))?; + let mut out = Vec::new(); + for line in maps.lines() { + let mut parts = line.split_whitespace(); + let (Some(range), Some(perms)) = (parts.next(), parts.next()) else { + continue; + }; + if !perms.starts_with("rw") { + continue; + } + let name = line.split_whitespace().nth(5).unwrap_or(""); + if name.starts_with("[vvar") || name.starts_with("[vsyscall") { + continue; + } + let Some((a, b)) = range.split_once('-') else { + continue; + }; + let (a, b) = ( + u64::from_str_radix(a, 16).unwrap_or(0), + u64::from_str_radix(b, 16).unwrap_or(0), + ); + if b <= a || b - a > (512 << 20) { + continue; + } + let mut buf = vec![0u8; (b - a) as usize]; + if mem.seek(SeekFrom::Start(a)).is_ok() && mem.read_exact(&mut buf).is_ok() { + out.extend_from_slice(&buf); + } + } + Ok(out) +} + +pub fn digest_needle(d: &Digest) -> Vec<Vec<u8>> { + vec![d.0.to_vec(), d.hex().into_bytes()] +} diff --git a/crates/crumbs/src/bin/crumbs-probe-learner.rs b/crates/crumbs/src/bin/crumbs-probe-learner.rs new file mode 100644 index 00000000..79b387e6 --- /dev/null +++ b/crates/crumbs/src/bin/crumbs-probe-learner.rs @@ -0,0 +1,93 @@ +//! A minimal learner used to test the protocol boundary without Omega. +//! +//! `crumbs-probe-learner honest LOOT` enumerates short chains and submits the first visible fit +//! `crumbs-probe-learner hostile LOOT` after receiving a crumb, asks for held-out data with a forged frame +//! `crumbs-probe-learner flood LOOT` submits candidates until the oracle stops answering +//! +//! Every byte the probe receives is appended to LOOT so a test can prove what +//! a learner can and cannot obtain. + +use crumbs::gen::enumerate_basic; +use crumbs::protocol::{ft, read_frame, write_frame}; +use crumbs::visible::VisibleCrumb; +use std::io::Write; + +fn main() { + let args: Vec<String> = std::env::args().collect(); + let mode = args.get(1).cloned().unwrap_or_default(); + let loot_path = args.get(2).cloned().unwrap_or_else(|| "/dev/null".into()); + let mut loot = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(loot_path) + .expect("loot"); + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + let mut r = stdin.lock(); + let mut w = stdout.lock(); + let cands = enumerate_basic(2); + loop { + let Ok((t, p)) = read_frame(&mut r) else { + return; + }; + let _ = loot.write_all(&[t]); + let _ = loot.write_all(&(p.len() as u32).to_le_bytes()); + let _ = loot.write_all(&p); + match t { + ft::HELLO => { + write_frame(&mut w, ft::READY, &1u16.to_le_bytes()).unwrap(); + } + ft::CRUMB => { + let Ok(c) = VisibleCrumb::from_bytes(&p) else { + return; + }; + write_frame(&mut w, ft::BANK, &0u32.to_le_bytes()).unwrap(); + if mode == "hostile" { + // Forged request: there is no frame type that returns sealed data. + let _ = + write_frame(&mut w, 0x90, b"send heldout outputs, family, decoy status"); + let _ = write_frame(&mut w, 0x03, b""); + continue; + } + let vals = c.values(); + let fits: Vec<_> = if c.out_arity == 1 { + cands + .iter() + .filter(|p| vals.iter().all(|(i, o)| p.run(i[0]) == o[0])) + .take(64) + .collect() + } else { + vec![] + }; + let tries: Vec<_> = if mode == "flood" { + cands.iter().take(40).collect() + } else { + fits.into_iter().take(2).collect() + }; + for (k, prog) in tries.into_iter().enumerate() { + let mut pl = Vec::new(); + pl.extend_from_slice(&(k as u32 + 1).to_le_bytes()); + pl.push(0); + pl.push(1); + pl.extend_from_slice(&prog.to_bytes()); + write_frame(&mut w, ft::SUBMIT, &pl).unwrap(); + let Ok((vt, vp)) = read_frame(&mut r) else { + return; + }; + let _ = loot.write_all(&[vt]); + let _ = loot.write_all(&(vp.len() as u32).to_le_bytes()); + let _ = loot.write_all(&vp); + if vp == [1] { + break; + } + } + let mut done = vec![2u8]; + done.extend_from_slice(&u32::MAX.to_le_bytes()); + done.extend_from_slice(&[0u8; 12 * 4 + 16]); + write_frame(&mut w, ft::DONE, &done).unwrap(); + } + ft::SHUTDOWN => return, + _ => {} + } + } +} diff --git a/crates/crumbs/src/bin/crumbs.rs b/crates/crumbs/src/bin/crumbs.rs new file mode 100644 index 00000000..0ace2f77 --- /dev/null +++ b/crates/crumbs/src/bin/crumbs.rs @@ -0,0 +1,111 @@ +//! `crumbs` command-line tool (sealed side). +//! +//! crumbs families list registered families (sealed labels) +//! crumbs vectors DIR write Crumb v1 conformance vectors +//! crumbs run --learner PATH [--n N] [--seed S] [--library] [--out DIR] +//! crumbs experiment --learner PATH [--out DIR] [--seed S] [--phase1 N] +//! crumbs gates --learner PATH [--out DIR] learner-dependent qualification gates + +use crumbs::gen::{self, registry}; +use crumbs::mixer::{Mixer, MixerConfig}; +use crumbs::promotion::PromotionConfig; +use crumbs::protocol::SearchConfig; +use crumbs::session::{Session, SessionConfig}; +use std::path::PathBuf; + +fn arg(args: &[String], name: &str) -> Option<String> { + args.iter() + .position(|a| a == name) + .and_then(|i| args.get(i + 1).cloned()) +} + +fn flag(args: &[String], name: &str) -> bool { + args.iter().any(|a| a == name) +} + +fn main() { + let args: Vec<String> = std::env::args().collect(); + let cmd = args.get(1).map(String::as_str).unwrap_or("help"); + let code = match cmd { + "families" => { + for f in ®istry().families { + println!( + "{:4} {:32} {:26} {:?} {:?}", + f.id, + f.key, + f.mechanism.key(), + f.rung, + f.source_family + ); + } + 0 + } + "vectors" => crumbs::conformance::write_vectors(&PathBuf::from(args.get(2).expect("DIR"))), + "run" => run(&args), + "experiment" => crumbs::experiment::main(&args), + "gates" => crumbs::gates::main(&args), + _ => { + eprintln!("usage: crumbs families | vectors DIR | run --learner PATH | experiment --learner PATH | gates --learner PATH"); + 2 + } + }; + std::process::exit(code); +} + +fn run(args: &[String]) -> i32 { + let learner = arg(args, "--learner").expect("--learner PATH"); + let n: u64 = arg(args, "--n").map_or(40, |v| v.parse().unwrap()); + let seed: u64 = arg(args, "--seed").map_or(1, |v| v.parse().unwrap()); + let cfg = SessionConfig { + condition: if flag(args, "--library") { + "learning".into() + } else { + "control".into() + }, + learner, + run_id: format!("run-{seed}"), + search: SearchConfig::default(), + library_enabled: flag(args, "--library"), + promotion: PromotionConfig::default(), + record_transcript: false, + out_dir: arg(args, "--out").map(PathBuf::from), + }; + let mut s = Session::start(cfg).expect("learner starts"); + let mut mixer = Mixer::new(MixerConfig::default(), seed); + for _ in 0..n { + let d = mixer.draw(); + let fam = registry().get(d.family_id).unwrap(); + let o = s + .present(fam, d.seed, d.population, "run") + .expect("session"); + mixer.record(fam, o.verified); + println!( + "{:4} {:30} pop={:?} supported={} accepted={} verified={} subs={} fh={} gen={} lib_avail={} reuse={} admitted={}", + o.seq, + o.family_key, + o.population, + o.supported, + o.accepted, + o.verified, + o.evaluations.len(), + o.falsified_hidden(), + o.stats.generated, + o.library_ops_available, + o.reused_library(), + o.admissions_after.len() + ); + } + let _ = gen::GENERATOR_VERSION; + let (ledger, _, ladder) = s.finish().expect("clean shutdown"); + println!( + "ledger head {} records {}", + ledger.head, + ledger.records.len() + ); + println!( + "ops tracked {} admitted {}", + ladder.ops.len(), + ladder.count(crumbs::promotion::Stage::Admitted) + ); + 0 +} diff --git a/crates/crumbs/src/canon.rs b/crates/crumbs/src/canon.rs new file mode 100644 index 00000000..91696d00 --- /dev/null +++ b/crates/crumbs/src/canon.rs @@ -0,0 +1,115 @@ +//! Canonical little-endian encoding primitives. All identities are computed +//! over bytes produced here, never over serde/JSON output. + +use crate::digest::Digest; + +#[derive(Default, Clone)] +pub struct Enc { + pub buf: Vec<u8>, +} + +impl Enc { + pub fn new() -> Self { + Enc { buf: Vec::new() } + } + pub fn bytes(&mut self, b: &[u8]) -> &mut Self { + self.buf.extend_from_slice(b); + self + } + pub fn u8(&mut self, v: u8) -> &mut Self { + self.buf.push(v); + self + } + pub fn u16(&mut self, v: u16) -> &mut Self { + self.bytes(&v.to_le_bytes()) + } + pub fn u32(&mut self, v: u32) -> &mut Self { + self.bytes(&v.to_le_bytes()) + } + pub fn u64(&mut self, v: u64) -> &mut Self { + self.bytes(&v.to_le_bytes()) + } + pub fn digest(&mut self, d: &Digest) -> &mut Self { + self.bytes(&d.0) + } + /// u32 length prefix + bytes. + pub fn blob(&mut self, b: &[u8]) -> &mut Self { + self.u32(b.len() as u32).bytes(b) + } + pub fn str(&mut self, s: &str) -> &mut Self { + self.blob(s.as_bytes()) + } + pub fn u64s(&mut self, v: &[u64]) -> &mut Self { + self.u32(v.len() as u32); + for x in v { + self.u64(*x); + } + self + } + pub fn finish(self) -> Vec<u8> { + self.buf + } +} + +/// Decoding error: a bare code, never content. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DecodeError; + +impl std::fmt::Display for DecodeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("malformed canonical bytes") + } +} + +impl std::error::Error for DecodeError {} + +pub struct Dec<'a> { + buf: &'a [u8], + pos: usize, +} + +impl<'a> Dec<'a> { + pub fn new(buf: &'a [u8]) -> Self { + Dec { buf, pos: 0 } + } + pub fn take(&mut self, n: usize) -> Result<&'a [u8], DecodeError> { + if n > self.buf.len() - self.pos { + return Err(DecodeError); + } + let s = &self.buf[self.pos..self.pos + n]; + self.pos += n; + Ok(s) + } + pub fn u8(&mut self) -> Result<u8, DecodeError> { + Ok(self.take(1)?[0]) + } + pub fn u16(&mut self) -> Result<u16, DecodeError> { + Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap())) + } + pub fn u32(&mut self) -> Result<u32, DecodeError> { + Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap())) + } + pub fn u64(&mut self) -> Result<u64, DecodeError> { + Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap())) + } + pub fn digest(&mut self) -> Result<Digest, DecodeError> { + Ok(Digest(self.take(32)?.try_into().unwrap())) + } + pub fn blob(&mut self, max: usize) -> Result<&'a [u8], DecodeError> { + let n = self.u32()? as usize; + if n > max { + return Err(DecodeError); + } + self.take(n) + } + pub fn done(&self) -> bool { + self.pos == self.buf.len() + } + pub fn finish(&self) -> Result<(), DecodeError> { + if self.done() { + Ok(()) + } else { + Err(DecodeError) + } + } +} diff --git a/crates/crumbs/src/conformance.rs b/crates/crumbs/src/conformance.rs new file mode 100644 index 00000000..e774710c --- /dev/null +++ b/crates/crumbs/src/conformance.rs @@ -0,0 +1,44 @@ +//! Crumb v1 conformance vectors for other implementations (e.g. Omega's reader). + +use crate::gen::{self, registry}; +use std::path::Path; + +/// Write one visible crumb per family (seed 7) plus an expected-values file. +pub fn write_vectors(dir: &Path) -> i32 { + if std::fs::create_dir_all(dir).is_err() { + return 1; + } + let mut index = String::new(); + for f in ®istry().families { + let g = gen::generate(f, 7); + let name = format!("v{:03}.crb", f.id); + if std::fs::write(dir.join(&name), g.visible.to_bytes()).is_err() { + return 1; + } + let mut line = format!( + "{name} ok enc={} in={}x{} out={}x{} n={}", + g.visible.encoding as u8, + g.visible.in_arity, + g.visible.in_lane_bytes, + g.visible.out_arity, + g.visible.out_lane_bytes, + g.visible.examples.len() + ); + for (i, o) in g.visible.values() { + line.push_str(" |"); + for v in i { + line.push_str(&format!(" {v}")); + } + line.push_str(" ->"); + for v in o { + line.push_str(&format!(" {v}")); + } + } + index.push_str(&line); + index.push('\n'); + } + if std::fs::write(dir.join("expected.txt"), index).is_err() { + return 1; + } + 0 +} diff --git a/crates/crumbs/src/digest.rs b/crates/crumbs/src/digest.rs new file mode 100644 index 00000000..7c8e7ed5 --- /dev/null +++ b/crates/crumbs/src/digest.rs @@ -0,0 +1,166 @@ +//! Domain-separated BLAKE3 digests and the Crumb v1 identity model. +//! +//! | identity | derivation | learner sees it | +//! |---------------------------|---------------------------------------------------------|-----------------| +//! | `CrumbOccurrenceId` | UUID v7, one per presentation/run | no | +//! | `CrumbDigest` | BLAKE3(canonical learner-visible Crumb v1 bytes) | no (derivable) | +//! | `GeneratorInstanceDigest` | BLAKE3(family_id, generator_version, seed, parameters) | no | +//! | `SealedRecordDigest` | BLAKE3(canonical sealed record) | no | +//! +//! Every digest uses a distinct BLAKE3 `derive_key` context, so a byte string +//! hashed for one purpose can never collide with the same bytes hashed for +//! another. + +use std::fmt; + +/// A 32-byte BLAKE3 digest. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] +pub struct Digest(pub [u8; 32]); + +impl Digest { + pub const ZERO: Digest = Digest([0u8; 32]); + + pub fn hex(&self) -> String { + self.0.iter().map(|b| format!("{b:02x}")).collect() + } + + pub fn short(&self) -> String { + self.hex()[..16].to_string() + } + + pub fn from_hex(s: &str) -> Option<Digest> { + if s.len() != 64 { + return None; + } + let mut out = [0u8; 32]; + for (i, chunk) in s.as_bytes().chunks(2).enumerate() { + let hi = (chunk[0] as char).to_digit(16)?; + let lo = (chunk[1] as char).to_digit(16)?; + out[i] = (hi * 16 + lo) as u8; + } + Some(Digest(out)) + } +} + +impl fmt::Debug for Digest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.short()) + } +} + +impl fmt::Display for Digest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.hex()) + } +} + +impl serde::Serialize for Digest { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + s.serialize_str(&self.hex()) + } +} + +impl<'de> serde::Deserialize<'de> for Digest { + fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + let s = String::deserialize(d)?; + Digest::from_hex(&s).ok_or_else(|| serde::de::Error::custom("bad digest")) + } +} + +/// Every digest purpose in the system. Adding one is a schema change. +#[derive(Clone, Copy, Debug)] +pub enum Domain { + CrumbDigest, + GeneratorInstance, + GeneratorCode, + SealedRecord, + HeldoutSet, + VisibleSet, + Program, + Behavior, + Verifier, + Evaluation, + TraceRecord, + TrainingSample, + TraceStream, + Capability, + Promotion, + LedgerRecord, + LedgerGenesis, + Rng, + Config, + LearnerBank, + SearchState, +} + +impl Domain { + fn context(self) -> &'static str { + match self { + Domain::CrumbDigest => "crumbs v1 2026-09-27 CrumbDigest", + Domain::GeneratorInstance => "crumbs v1 2026-09-27 GeneratorInstanceDigest", + Domain::GeneratorCode => "crumbs v1 2026-09-27 GeneratorCodeDigest", + Domain::SealedRecord => "crumbs v1 2026-09-27 SealedRecordDigest", + Domain::HeldoutSet => "crumbs v1 2026-09-27 HeldoutSetDigest", + Domain::VisibleSet => "crumbs v1 2026-09-27 VisibleSetDigest", + Domain::Program => "crumbs v1 2026-09-27 CandidateProgramDigest", + Domain::Behavior => "crumbs v1 2026-09-27 BehaviorSignature", + Domain::Verifier => "crumbs v1 2026-09-27 VerifierDigest", + Domain::Evaluation => "crumbs v1 2026-09-27 EvaluationDigest", + Domain::TraceRecord => "crumbs v1 2026-09-27 TraceRecordChain", + Domain::TrainingSample => "crumbs v1 2026-09-27 TrainingSampleChain", + Domain::TraceStream => "crumbs v1 2026-09-27 TraceStreamDigest", + Domain::Capability => "crumbs v1 2026-09-27 CapabilityId", + Domain::Promotion => "crumbs v1 2026-09-27 PromotionRecord", + Domain::LedgerRecord => "crumbs v1 2026-09-27 CrumblineRecord", + Domain::LedgerGenesis => "crumbs v1 2026-09-27 CrumblineGenesis", + Domain::Rng => "crumbs v1 2026-09-27 DeterministicStream", + Domain::Config => "crumbs v1 2026-09-27 ConfigDigest", + Domain::LearnerBank => "crumbs v1 2026-09-27 LearnerBankDigest", + Domain::SearchState => "crumbs v1 2026-09-27 SearchStateDigest", + } + } +} + +pub fn digest(domain: Domain, bytes: &[u8]) -> Digest { + Digest(blake3::derive_key(domain.context(), bytes)) +} + +/// Incremental hashing under a domain. +pub struct Hasher(blake3::Hasher); + +impl Hasher { + pub fn new(domain: Domain) -> Self { + Hasher(blake3::Hasher::new_derive_key(domain.context())) + } + pub fn update(&mut self, bytes: &[u8]) -> &mut Self { + self.0.update(bytes); + self + } + pub fn finish(&self) -> Digest { + Digest(*self.0.finalize().as_bytes()) + } +} + +/// UUID v7 occurrence id: identifies one presentation of a crumb in one run. +/// Time-ordered and deliberately NOT content-derived; it never identifies the problem. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, serde::Serialize, serde::Deserialize)] +pub struct CrumbOccurrenceId(pub uuid::Uuid); + +impl CrumbOccurrenceId { + pub fn new() -> Self { + CrumbOccurrenceId(uuid::Uuid::now_v7()) + } +} + +impl Default for CrumbOccurrenceId { + fn default() -> Self { + Self::new() + } +} + +/// BLAKE3 of the canonical learner-visible bytes (which include the schema version). +pub type CrumbDigest = Digest; +/// BLAKE3(family_id || generator_version || seed || canonical generation parameters). +pub type GeneratorInstanceDigest = Digest; +/// BLAKE3 of the canonical sealed record (metadata + held-outs + provenance). +pub type SealedRecordDigest = Digest; diff --git a/crates/crumbs/src/experiment.rs b/crates/crumbs/src/experiment.rs new file mode 100644 index 00000000..afb287fb --- /dev/null +++ b/crates/crumbs/src/experiment.rs @@ -0,0 +1,711 @@ +//! BREADCRUMB-8: the acquisition and reuse experiment. +//! +//! Pre-registered design (fixed in code before any run): +//! +//! * Capabilities 0..=7 are TAUGHT (phase 1 may draw them); 8..=11 are never +//! presented in phase 1. +//! * Phase 1: `phase1` mixer draws over the whole curriculum, restricted to +//! taught capabilities and to the TRAIN composition pairs below. +//! * Phase 2: a fixed list of unseen test crumbs, identical in both +//! conditions, presented with the library frozen: +//! - `heldout-pair` compositions of two taught capabilities never shown as a pair +//! - `triple` compositions of three taught capabilities (never shown) +//! - `untaught` compositions involving an untaught capability +//! - `novel-primitive` the untaught capabilities themselves +//! - `general` ordinary chains (harm check: does a library slow search?) +//! * Conditions: CONTROL (admissions never sent; the learner cannot reuse +//! discovered operations) and LEARNING (verified admissions are sent). +//! Same learner binary, same search budget, same test seeds. +//! +//! The report states whatever happened. Nothing here is tuned to a result. + +use crate::gen::{registry, rng::Rng, FamilySpec}; +use crate::mixer::{Mixer, MixerConfig}; +use crate::promotion::{PromotionConfig, Stage}; +use crate::protocol::SearchConfig; +use crate::sealed::{AdversarialClass, DecoyStatus, Population}; +use crate::session::{CrumbOutcome, Session, SessionConfig}; +use crate::verify::{verifier_digest, EvalClass}; +use serde::Serialize; +use std::collections::BTreeMap; +use std::path::PathBuf; + +pub const TAUGHT: [u16; 8] = [0, 1, 2, 3, 4, 5, 6, 7]; +pub const TRAIN_PAIRS: [&str; 7] = [ + "compose-00-01", + "compose-02-03", + "compose-04-05", + "compose-06-07", + "compose-01-03", + "compose-03-05", + "compose-05-07", +]; +pub const HELDOUT_PAIRS: [&str; 6] = [ + "compose-01-02", + "compose-03-04", + "compose-05-06", + "compose-00-02", + "compose-02-04", + "compose-04-06", +]; +pub const TRIPLES: [&str; 4] = [ + "compose-00-01-02", + "compose-03-04-05", + "compose-00-03-06", + "compose-01-04-07", +]; +pub const UNTAUGHT_PAIRS: [&str; 11] = [ + "compose-07-08", + "compose-08-09", + "compose-09-10", + "compose-10-11", + "compose-11-00", + "compose-06-08", + "compose-07-09", + "compose-08-10", + "compose-09-11", + "compose-10-00", + "compose-11-01", +]; +pub const NOVEL_PRIMITIVES: [&str; 4] = [ + "capability-08", + "capability-09", + "capability-10", + "capability-11", +]; +pub const GENERAL: [&str; 4] = [ + "chain-basic-l2-w16", + "chain-basic-l3-w16", + "latent-offset-w16", + "mod-affine-w12", +]; +pub const GROUPS: [&str; 5] = [ + "heldout-pair", + "triple", + "untaught", + "novel-primitive", + "general", +]; + +#[derive(Clone, Debug, Serialize)] +pub struct TestItem { + pub group: &'static str, + pub family: String, + pub seed: u64, +} + +pub fn test_plan(run_seed: u64) -> Vec<TestItem> { + let mut out = Vec::new(); + let groups: [(&'static str, &[&str], u64); 5] = [ + ("heldout-pair", &HELDOUT_PAIRS, 3), + ("triple", &TRIPLES, 3), + ("untaught", &UNTAUGHT_PAIRS, 2), + ("novel-primitive", &NOVEL_PRIMITIVES, 2), + ("general", &GENERAL, 2), + ]; + for (gi, (g, fams, reps)) in groups.into_iter().enumerate() { + for (i, f) in fams.iter().enumerate() { + for r in 0..reps { + let seed = Rng::named("experiment-test-seed", &[run_seed, gi as u64, i as u64, r]) + .next_u64(); + out.push(TestItem { + group: g, + family: f.to_string(), + seed, + }); + } + } + } + out +} + +#[derive(Clone, Debug, Default, Serialize)] +pub struct GroupMetrics { + pub crumbs: u32, + pub supported: u32, + pub solved: u32, + pub verified: u32, + pub solve_rate: f64, + pub interpolation_pass_rate: f64, + pub extrapolation_pass_rate: f64, + pub adversarial_pass_rate: f64, + pub submissions: u32, + pub falsified_hidden: u32, + pub false_generalization_rate: f64, + pub mean_candidates_generated: f64, + pub mean_candidates_evaluated: f64, + pub candidates_per_solution: f64, + pub mean_exec_count: f64, + pub mean_wall_ms: f64, + pub reuse_rate: f64, +} + +fn metrics(outs: &[&CrumbOutcome]) -> GroupMetrics { + let mut m = GroupMetrics { + crumbs: outs.len() as u32, + ..Default::default() + }; + if outs.is_empty() { + return m; + } + let (mut ip, mut it, mut ep, mut et, mut ap, mut at) = (0u64, 0u64, 0u64, 0u64, 0u64, 0u64); + let (mut gen_sum, mut eval_sum, mut exec_sum, mut wall, mut gen_to_solution) = + (0u64, 0u64, 0u64, 0u64, 0u64); + let mut reuse = 0u32; + for o in outs { + m.supported += o.supported as u32; + m.solved += o.accepted as u32; + m.verified += o.verified as u32; + m.submissions += o.evaluations.len() as u32; + m.falsified_hidden += o.falsified_hidden() as u32; + gen_sum += o.stats.generated as u64; + eval_sum += o.stats.evaluated as u64; + exec_sum += o.stats.exec_count; + wall += o.stats.wall_ns; + reuse += o.reused_library() as u32; + if o.accepted { + gen_to_solution += o.stats.candidates_to_solution as u64; + } + // Held-out pass rates of the learner's final committed answer. + if let Some(e) = o.evaluations.last() { + ip += e.interpolation.passed as u64; + it += e.interpolation.total as u64; + ep += e.extrapolation.passed as u64; + et += e.extrapolation.total as u64; + ap += e.adversarial.passed as u64; + at += e.adversarial.total as u64; + } + } + let n = outs.len() as f64; + let r = |a: u64, b: u64| if b == 0 { 0.0 } else { a as f64 / b as f64 }; + m.solve_rate = m.solved as f64 / n; + m.interpolation_pass_rate = r(ip, it); + m.extrapolation_pass_rate = r(ep, et); + m.adversarial_pass_rate = r(ap, at); + m.false_generalization_rate = r(m.falsified_hidden as u64, m.submissions as u64); + m.mean_candidates_generated = gen_sum as f64 / n; + m.mean_candidates_evaluated = eval_sum as f64 / n; + m.candidates_per_solution = if m.solved == 0 { + f64::NAN + } else { + gen_to_solution as f64 / m.solved as f64 + }; + m.mean_exec_count = exec_sum as f64 / n; + m.mean_wall_ms = wall as f64 / n / 1e6; + m.reuse_rate = if m.solved == 0 { + 0.0 + } else { + reuse as f64 / m.solved as f64 + }; + m +} + +/// Curriculum-wide epistemic metrics (phase 1). +#[derive(Clone, Debug, Default, Serialize)] +pub struct CurriculumMetrics { + pub crumbs: u32, + pub by_population: BTreeMap<String, u32>, + pub redistributed_draws: BTreeMap<String, u32>, + pub visible_fit_rate: f64, + pub heldout_verified_rate: f64, + pub rabbit_hole_crumbs: u32, + /// Rabbit holes (classes A-E, G) whose first submitted answer was not held-out-falsified. + pub adversarial_survival_rate: f64, + pub false_generalization_rate: f64, + pub insufficient_evidence_crumbs: u32, + pub ambiguity_recognition_rate: f64, + pub false_ambiguity_rate_on_clean: f64, + pub noisy_crumbs: u32, + pub noisy_verified: u32, + pub operations_tracked: u32, + pub operations_admitted: u32, +} + +#[derive(Serialize)] +pub struct ConditionReport { + pub condition: String, + pub curriculum: CurriculumMetrics, + pub test: BTreeMap<String, GroupMetrics>, + pub test_all: GroupMetrics, + pub ledger_head: String, + pub ledger_records: usize, + pub ledger_verified: bool, +} + +#[derive(Serialize)] +pub struct PairedComparison { + pub group: String, + pub crumbs: u32, + pub solved_control: u32, + pub solved_learning: u32, + pub solved_only_learning: u32, + pub solved_only_control: u32, + pub both_solved: u32, + pub fewer_candidates_learning: u32, + pub fewer_candidates_control: u32, + pub equal_candidates: u32, + /// Geometric mean of learning/control candidates-to-solution over crumbs both solved. + pub geomean_candidate_ratio_both_solved: f64, + pub mean_generated_control: f64, + pub mean_generated_learning: f64, + pub mean_exec_control: f64, + pub mean_exec_learning: f64, + pub mean_wall_ms_control: f64, + pub mean_wall_ms_learning: f64, + pub heldout_correct_control: u32, + pub heldout_correct_learning: u32, +} + +#[derive(Serialize)] +pub struct ExperimentReport { + pub design: &'static str, + pub run_seed: u64, + pub phase1_draws: u64, + pub search: SearchConfig, + pub promotion: PromotionConfig, + pub mixer: MixerConfig, + pub test_plan: Vec<TestItem>, + pub verifier_digest: String, + pub learner_digest: String, + pub registry_version: &'static str, + pub generator_version: &'static str, + pub control: ConditionReport, + pub learning: ConditionReport, + pub paired: Vec<PairedComparison>, + pub aien_next_action_guidance: &'static str, + pub wall_seconds: f64, +} + +fn curriculum_metrics( + outs: &[CrumbOutcome], + ladder: &crate::promotion::Ladder, + mixer: &Mixer, +) -> CurriculumMetrics { + let ph: Vec<&CrumbOutcome> = outs.iter().filter(|o| o.phase == "phase1").collect(); + let mut c = CurriculumMetrics { + crumbs: ph.len() as u32, + ..Default::default() + }; + for o in &ph { + *c.by_population + .entry(format!("{:?}", o.population)) + .or_insert(0) += 1; + } + for (p, n) in &mixer.redistributed_draws { + c.redistributed_draws.insert(format!("{p:?}"), *n); + } + let n = ph.len().max(1) as f64; + c.visible_fit_rate = ph.iter().filter(|o| o.stats.visible_fits > 0).count() as f64 / n; + c.heldout_verified_rate = ph.iter().filter(|o| o.verified).count() as f64 / n; + let rh: Vec<_> = ph + .iter() + .filter(|o| matches!(o.decoy, DecoyStatus::RabbitHole(k) if k != AdversarialClass::InsufficientEvidence)) + .collect(); + c.rabbit_hole_crumbs = rh.len() as u32; + let survived = rh + .iter() + .filter(|o| o.first_class() != Some(EvalClass::FalsifiedHidden)) + .count(); + c.adversarial_survival_rate = if rh.is_empty() { + f64::NAN + } else { + survived as f64 / rh.len() as f64 + }; + let subs: usize = ph.iter().map(|o| o.evaluations.len()).sum(); + let fh: usize = ph.iter().map(|o| o.falsified_hidden()).sum(); + c.false_generalization_rate = if subs == 0 { + 0.0 + } else { + fh as f64 / subs as f64 + }; + let ie: Vec<_> = ph + .iter() + .filter(|o| { + o.decoy == DecoyStatus::RabbitHole(AdversarialClass::InsufficientEvidence) + && !o.evaluations.is_empty() + }) + .collect(); + c.insufficient_evidence_crumbs = ie.len() as u32; + let recog = ie + .iter() + .filter(|o| o.stats.hypotheses_at_first_submit >= 2) + .count(); + c.ambiguity_recognition_rate = if ie.is_empty() { + f64::NAN + } else { + recog as f64 / ie.len() as f64 + }; + let clean: Vec<_> = ph + .iter() + .filter(|o| o.decoy == DecoyStatus::Clean && !o.evaluations.is_empty()) + .collect(); + let false_amb = clean + .iter() + .filter(|o| o.stats.hypotheses_at_first_submit >= 2) + .count(); + c.false_ambiguity_rate_on_clean = if clean.is_empty() { + f64::NAN + } else { + false_amb as f64 / clean.len() as f64 + }; + let noisy: Vec<_> = ph + .iter() + .filter(|o| o.decoy == DecoyStatus::RabbitHole(AdversarialClass::Noisy)) + .collect(); + c.noisy_crumbs = noisy.len() as u32; + c.noisy_verified = noisy.iter().filter(|o| o.verified).count() as u32; + c.operations_tracked = ladder.ops.len() as u32; + c.operations_admitted = ladder.count(Stage::Admitted) as u32; + c +} + +pub struct ConditionRun { + pub outcomes: Vec<CrumbOutcome>, + pub report: ConditionReport, + pub learner_digest: String, +} + +#[allow(clippy::too_many_arguments)] +pub fn run_condition( + learner: &str, + condition: &str, + library: bool, + run_seed: u64, + phase1: u64, + search: SearchConfig, + mixer_cfg: &MixerConfig, + out_dir: Option<PathBuf>, +) -> Result<ConditionRun, crate::protocol::ProtocolError> { + let cfg = SessionConfig { + condition: condition.to_string(), + learner: learner.to_string(), + run_id: format!("crumbline-experiment-{run_seed}-{condition}"), + search, + library_enabled: library, + promotion: PromotionConfig::default(), + record_transcript: false, + out_dir, + }; + let mut s = Session::start(cfg)?; + let learner_digest = s.learner_digest.hex(); + let mut mixer = Mixer::new(mixer_cfg.clone(), run_seed); + for _ in 0..phase1 { + let d = mixer.draw(); + let fam = registry().get(d.family_id).expect("registered"); + let o = s.present(fam, d.seed, d.population, "phase1")?; + mixer.record(fam, o.verified); + } + s.freeze_admissions(); + for item in test_plan(run_seed) { + let fam: &FamilySpec = registry() + .by_key(&item.family) + .expect("test family registered"); + s.present(fam, item.seed, Population::Composition, item.group)?; + } + let genesis = s.ledger.genesis; + let (ledger, outcomes, ladder) = s.finish()?; + let verified = crate::ledger::Ledger::verify(genesis, &ledger.records).is_ok(); + let curriculum = curriculum_metrics(&outcomes, &ladder, &mixer); + let mut test = BTreeMap::new(); + for g in GROUPS { + let v: Vec<&CrumbOutcome> = outcomes.iter().filter(|o| o.phase == g).collect(); + test.insert(g.to_string(), metrics(&v)); + } + let all: Vec<&CrumbOutcome> = outcomes.iter().filter(|o| o.phase != "phase1").collect(); + let report = ConditionReport { + condition: condition.to_string(), + curriculum, + test, + test_all: metrics(&all), + ledger_head: ledger.head.hex(), + ledger_records: ledger.records.len(), + ledger_verified: verified, + }; + Ok(ConditionRun { + outcomes, + report, + learner_digest, + }) +} + +pub fn paired( + control: &[CrumbOutcome], + learning: &[CrumbOutcome], + group: &str, +) -> PairedComparison { + let pick = |o: &&CrumbOutcome| { + if group == "all" { + o.phase != "phase1" + } else { + o.phase == group + } + }; + let c: Vec<&CrumbOutcome> = control.iter().filter(pick).collect(); + let l: Vec<&CrumbOutcome> = learning.iter().filter(pick).collect(); + let mut p = PairedComparison { + group: group.to_string(), + crumbs: c.len() as u32, + solved_control: 0, + solved_learning: 0, + solved_only_learning: 0, + solved_only_control: 0, + both_solved: 0, + fewer_candidates_learning: 0, + fewer_candidates_control: 0, + equal_candidates: 0, + geomean_candidate_ratio_both_solved: f64::NAN, + mean_generated_control: 0.0, + mean_generated_learning: 0.0, + mean_exec_control: 0.0, + mean_exec_learning: 0.0, + mean_wall_ms_control: 0.0, + mean_wall_ms_learning: 0.0, + heldout_correct_control: 0, + heldout_correct_learning: 0, + }; + let mut log_sum = 0.0; + for (a, b) in c.iter().zip(l.iter()) { + assert_eq!( + a.crumb_digest, b.crumb_digest, + "paired crumbs must be identical" + ); + p.solved_control += a.accepted as u32; + p.solved_learning += b.accepted as u32; + p.heldout_correct_control += a.verified as u32; + p.heldout_correct_learning += b.verified as u32; + match (a.accepted, b.accepted) { + (true, true) => { + p.both_solved += 1; + let x = a.stats.candidates_to_solution.max(1) as f64; + let y = b.stats.candidates_to_solution.max(1) as f64; + log_sum += (y / x).ln(); + } + (false, true) => p.solved_only_learning += 1, + (true, false) => p.solved_only_control += 1, + _ => {} + } + let (ga, gb) = (a.stats.generated, b.stats.generated); + if gb < ga { + p.fewer_candidates_learning += 1; + } else if ga < gb { + p.fewer_candidates_control += 1; + } else { + p.equal_candidates += 1; + } + p.mean_generated_control += ga as f64; + p.mean_generated_learning += gb as f64; + p.mean_exec_control += a.stats.exec_count as f64; + p.mean_exec_learning += b.stats.exec_count as f64; + p.mean_wall_ms_control += a.stats.wall_ns as f64 / 1e6; + p.mean_wall_ms_learning += b.stats.wall_ns as f64 / 1e6; + } + let n = c.len().max(1) as f64; + p.mean_generated_control /= n; + p.mean_generated_learning /= n; + p.mean_exec_control /= n; + p.mean_exec_learning /= n; + p.mean_wall_ms_control /= n; + p.mean_wall_ms_learning /= n; + if p.both_solved > 0 { + p.geomean_candidate_ratio_both_solved = (log_sum / p.both_solved as f64).exp(); + } + p +} + +pub fn run( + learner: &str, + run_seed: u64, + phase1: u64, + out: Option<PathBuf>, +) -> Result<ExperimentReport, crate::protocol::ProtocolError> { + let t0 = std::time::Instant::now(); + let search = SearchConfig::default(); + let mixer_cfg = MixerConfig { + capability_subset: Some(TAUGHT.to_vec()), + composition_keys: Some(TRAIN_PAIRS.iter().map(|s| s.to_string()).collect()), + ..MixerConfig::default() + }; + let sub = |name: &str| out.as_ref().map(|d| d.join(name)); + let control = run_condition( + learner, + "control", + false, + run_seed, + phase1, + search, + &mixer_cfg, + sub("control"), + )?; + let learning = run_condition( + learner, + "learning", + true, + run_seed, + phase1, + search, + &mixer_cfg, + sub("learning"), + )?; + let mut paired_v = Vec::new(); + for g in GROUPS.iter().copied().chain(["all"]) { + paired_v.push(paired(&control.outcomes, &learning.outcomes, g)); + } + let report = ExperimentReport { + design: "pre-registered: taught caps 0-7, train pairs fixed, 68 unseen test crumbs, library frozen before test, identical budgets", + run_seed, + phase1_draws: phase1, + search, + promotion: PromotionConfig::default(), + mixer: mixer_cfg, + test_plan: test_plan(run_seed), + verifier_digest: verifier_digest().hex(), + learner_digest: control.learner_digest.clone(), + registry_version: crate::gen::registry::REGISTRY_VERSION, + generator_version: crate::gen::GENERATOR_VERSION, + control: control.report, + learning: learning.report, + paired: paired_v, + aien_next_action_guidance: "not available: no trained AIEN_0 policy exists yet; the trace corpus produced here is its training input", + wall_seconds: t0.elapsed().as_secs_f64(), + }; + if let Some(d) = &out { + let _ = std::fs::create_dir_all(d); + let _ = std::fs::write( + d.join("report.json"), + serde_json::to_string_pretty(&report).unwrap(), + ); + for (name, outs) in [ + ("control", &control.outcomes), + ("learning", &learning.outcomes), + ] { + let _ = std::fs::write( + d.join(format!("{name}-outcomes.json")), + serde_json::to_string(outs).unwrap(), + ); + } + } + Ok(report) +} + +/// Pooled comparison over independent replicates (different curriculum draws +/// and different test seeds per replicate; same design). +#[derive(Serialize)] +pub struct ReplicateReport { + pub run_seeds: Vec<u64>, + pub phase1_draws: u64, + pub pooled: Vec<PairedComparison>, + pub per_seed_all: Vec<PairedComparison>, + pub control_curriculum: Vec<CurriculumMetrics>, + pub learning_curriculum: Vec<CurriculumMetrics>, + pub wall_seconds: f64, +} + +pub fn replicate( + learner: &str, + first_seed: u64, + k: u64, + phase1: u64, + out: Option<PathBuf>, +) -> Result<ReplicateReport, crate::protocol::ProtocolError> { + let t0 = std::time::Instant::now(); + let search = SearchConfig::default(); + let mixer_cfg = MixerConfig { + capability_subset: Some(TAUGHT.to_vec()), + composition_keys: Some(TRAIN_PAIRS.iter().map(|s| s.to_string()).collect()), + ..MixerConfig::default() + }; + let (mut all_c, mut all_l) = (Vec::new(), Vec::new()); + let mut per_seed = Vec::new(); + let (mut cc, mut lc) = (Vec::new(), Vec::new()); + let seeds: Vec<u64> = (first_seed..first_seed + k).collect(); + for &seed in &seeds { + let sub = |name: &str| { + out.as_ref() + .map(|d| d.join(format!("seed-{seed}")).join(name)) + }; + let c = run_condition( + learner, + "control", + false, + seed, + phase1, + search, + &mixer_cfg, + sub("control"), + )?; + let l = run_condition( + learner, + "learning", + true, + seed, + phase1, + search, + &mixer_cfg, + sub("learning"), + )?; + per_seed.push(paired(&c.outcomes, &l.outcomes, "all")); + cc.push(c.report.curriculum.clone()); + lc.push(l.report.curriculum.clone()); + all_c.extend(c.outcomes); + all_l.extend(l.outcomes); + } + let pooled = GROUPS + .iter() + .copied() + .chain(["all"]) + .map(|g| paired(&all_c, &all_l, g)) + .collect(); + let rep = ReplicateReport { + run_seeds: seeds, + phase1_draws: phase1, + pooled, + per_seed_all: per_seed, + control_curriculum: cc, + learning_curriculum: lc, + wall_seconds: t0.elapsed().as_secs_f64(), + }; + if let Some(d) = &out { + let _ = std::fs::create_dir_all(d); + let _ = std::fs::write( + d.join("replicates.json"), + serde_json::to_string_pretty(&rep).unwrap(), + ); + } + Ok(rep) +} + +pub fn main(args: &[String]) -> i32 { + let get = |n: &str| { + args.iter() + .position(|a| a == n) + .and_then(|i| args.get(i + 1).cloned()) + }; + let learner = get("--learner").expect("--learner PATH"); + let seed = get("--seed").map_or(20260927, |v| v.parse().unwrap()); + let phase1 = get("--phase1").map_or(120, |v| v.parse().unwrap()); + let out = get("--out").map(PathBuf::from); + if let Some(k) = get("--replicates") { + return match replicate(&learner, seed, k.parse().unwrap(), phase1, out) { + Ok(r) => { + println!("{}", serde_json::to_string_pretty(&r.pooled).unwrap()); + println!("wall {:.1}s", r.wall_seconds); + 0 + } + Err(e) => { + eprintln!("{e}"); + 1 + } + }; + } + match run(&learner, seed, phase1, out) { + Ok(r) => { + println!("{}", serde_json::to_string_pretty(&r.paired).unwrap()); + println!("wall {:.1}s", r.wall_seconds); + 0 + } + Err(e) => { + eprintln!("{e}"); + 1 + } + } +} diff --git a/crates/crumbs/src/gates.rs b/crates/crumbs/src/gates.rs new file mode 100644 index 00000000..839dfce7 --- /dev/null +++ b/crates/crumbs/src/gates.rs @@ -0,0 +1,420 @@ +//! Learner-dependent qualification gates, run against a real learner binary +//! (for v1: Omega's `crumbline-learner`). +//! +//! crumbs gates --learner PATH [--out DIR] +//! +//! Prints one `GATE_NAME PASS|FAIL detail` line per gate and writes gates.json +//! plus an aien-proof assertion file (`aien-proof receipt import --assert ...`). + +use crate::audit::{find_labels, read_process_writable_memory, sealed_specific_labels}; +use crate::digest::Domain; +use crate::gen::{self, registry, rng::Rng}; +use crate::program::{Op, Program}; +use crate::promotion::{PromotionConfig, Stage}; +use crate::protocol::{LearnerProcess, SearchConfig, Submission}; +use crate::sealed::{HeldoutTier, KnownSolution, LaneExample, Population}; +use crate::session::{CrumbOutcome, Session, SessionConfig}; +use crate::trace::{verify_chain, ResultClass, SAMPLE_RECORD_BYTES, TRACE_RECORD_BYTES}; +use crate::verify::{EvalClass, Verdict}; +use crate::visible::{Encoding, VisibleCrumb}; +use serde::Serialize; +use std::path::{Path, PathBuf}; + +#[derive(Serialize, Clone)] +pub struct GateResult { + pub id: String, + pub pass: bool, + pub observed: String, +} + +fn gate(id: &str, pass: bool, observed: String) -> GateResult { + println!("{id} {} {observed}", if pass { "PASS" } else { "FAIL" }); + GateResult { + id: id.to_string(), + pass, + observed, + } +} + +fn session(learner: &str, cond: &str, library: bool, dir: &Path) -> Session { + Session::start(SessionConfig { + condition: cond.into(), + learner: learner.into(), + run_id: format!("gates-{cond}"), + search: SearchConfig::default(), + library_enabled: library, + promotion: PromotionConfig::default(), + record_transcript: true, + out_dir: Some(dir.join(cond)), + }) + .expect("learner starts") +} + +fn present(s: &mut Session, key: &str, seed: u64) -> CrumbOutcome { + let f = registry() + .by_key(key) + .unwrap_or_else(|| panic!("family {key}")); + s.present(f, seed, Population::Fundamental, "gates") + .expect("session") +} + +pub fn run_gates(learner: &str, out: &Path) -> Vec<GateResult> { + let _ = std::fs::remove_dir_all(out); + std::fs::create_dir_all(out).unwrap(); + let mut gates = Vec::new(); + + // CRUMB_OMEGA_VISIBLE_PASS: the learner synthesizes programs that explain + // the visible examples, and never submits one that does not. + let mut s = session(learner, "visible", false, out); + let (mut fits, mut bad_visible, mut n) = (0u32, 0usize, 0u32); + let (mut expressible, mut expressible_found) = (0u32, 0u32); + for key in [ + "chain-basic-l1-w16", + "chain-basic-l2-w16", + "chain-basic-l3-w16", + "latent-offset-w16", + "mod-affine-w12", + ] { + for seed in 1..=8 { + let f = registry().by_key(key).unwrap(); + let g = gen::generate(f, seed); + let o = s + .present(f, seed, Population::Fundamental, "gates") + .expect("session"); + n += 1; + let found = o.stats.visible_fits > 0; + fits += found as u32; + bad_visible += o + .evaluations + .iter() + .filter(|e| e.class == EvalClass::FalsifiedVisible && !e.robust_submission) + .count(); + // Truth expressible as <= 3 single-step operations the learner itself + // declared: an exhaustive depth-3 search must find a visible fit. + if let KnownSolution::Known(t) = &g.sealed.known_solution { + let in_bank = t.steps.iter().all(|st| { + o.declared_bank + .iter() + .any(|b| b.steps.len() == 1 && b.steps[0] == *st) + }); + if in_bank && t.len() <= 3 { + expressible += 1; + expressible_found += found as u32; + } + } + } + } + gates.push(gate( + "CRUMB_OMEGA_VISIBLE_PASS", + expressible > 0 && expressible_found == expressible && bad_visible == 0, + format!("visible fit found on {expressible_found}/{expressible} crumbs whose truth is <= 3 of the learner's declared operations ({fits}/{n} overall); {bad_visible} exact submissions that failed the visible examples"), + )); + let (_, visible_outs, _) = s.finish().unwrap(); + + // CRUMB_HIDDEN_VERIFY_PASS: visible fits that fail held-outs are recorded + // as useful failures and search continues; acceptance needs held-outs. + let mut s = session(learner, "hidden", false, out); + let (mut useful_failures, mut continued, mut accepted_not_verified) = (0usize, 0u32, 0usize); + for key in [ + "decoy-simple-rule-w12", + "decoy-simple-rule-w16", + "multi-fit-w12", + "multi-fit-w16", + "insufficient-evidence-n3", + "prefix-diverges-k8", + ] { + for seed in 1..=4 { + let o = present(&mut s, key, seed); + let fh = o.falsified_hidden(); + useful_failures += fh; + if fh > 0 + && (o.evaluations.len() > 1 || o.stats.generated > o.stats.candidates_to_solution) + { + continued += 1; + } + accepted_not_verified += o + .evaluations + .iter() + .filter(|e| { + e.verdict == Verdict::Accept + && !matches!( + e.class, + EvalClass::Verified | EvalClass::AmbiguousUnderdetermined + ) + }) + .count(); + } + } + let (_, hidden_outs, _) = s.finish().unwrap(); + let rejected_records = count_records( + &out.join("hidden").join("trace.ctr"), + ResultClass::RejectedHidden, + ); + gates.push(gate( + "CRUMB_HIDDEN_VERIFY_PASS", + useful_failures > 0 && continued > 0 && accepted_not_verified == 0 && rejected_records == useful_failures, + format!("{useful_failures} visible-fit candidates falsified by held-outs, all recorded ({rejected_records} REJECTED_HIDDEN trace records); search continued after a rejection in {continued} crumbs; {accepted_not_verified} acceptances without held-out verification"), + )); + + gates.push(no_hidden_access(learner, out)); + + // Trace corpus gates over the real Omega sessions above. + let (mut chains_ok, mut total_records, mut total_samples, mut label_hits) = + (true, 0usize, 0usize, 0usize); + for d in ["visible", "hidden"] { + let tr = std::fs::read(out.join(d).join("trace.ctr")).unwrap_or_default(); + let smp = std::fs::read(out.join(d).join("samples.cts")).unwrap_or_default(); + chains_ok &= verify_chain(&tr, TRACE_RECORD_BYTES, Domain::TraceRecord).is_some(); + chains_ok &= verify_chain(&smp, SAMPLE_RECORD_BYTES, Domain::TrainingSample).is_some(); + total_records += tr.len() / TRACE_RECORD_BYTES; + total_samples += smp.len() / SAMPLE_RECORD_BYTES; + label_hits += find_labels(&tr).len() + find_labels(&smp).len(); + } + let all: Vec<&CrumbOutcome> = visible_outs.iter().chain(hidden_outs.iter()).collect(); + let integrity: u32 = all.iter().map(|o| o.trace.integrity_violations).sum(); + let samples_for_solved = all + .iter() + .filter(|o| o.accepted && o.stats.generated > 0) + .all(|o| o.trace.samples > 0); + gates.push(gate( + "CRUMB_TRACE_PASS", + chains_ok && total_records > 0 && integrity == 0, + format!("{total_records} hash-chained CTR1 records re-verified from disk; {integrity} submitted-vs-reconstructed program mismatches"), + )); + let consistent = check_samples(&out.join("visible").join("samples.cts")) + && check_samples(&out.join("hidden").join("samples.cts")); + gates.push(gate( + "CRUMB_TRAINING_SAMPLE_PASS", + total_samples > 0 && samples_for_solved && consistent, + format!("{total_samples} CTS1 samples; every solved crumb produced samples; every sample's positives are a non-empty subset of the operations tried"), + )); + gates.push(gate( + "NO_COT_STORAGE_PASS", + label_hits == 0 && chains_ok, + format!("fixed-size numeric records ({TRACE_RECORD_BYTES} B / {SAMPLE_RECORD_BYTES} B) with no text fields; {label_hits} label strings in the corpus"), + )); + + gates.extend(promotion_and_reuse(learner, out)); + gates.push(scope_enforcement(learner)); + + let _ = std::fs::write( + out.join("gates.json"), + serde_json::to_string_pretty(&gates).unwrap(), + ); + let assertions: Vec<serde_json::Value> = gates + .iter() + .map(|g| { + serde_json::json!({"id": g.id, "expected": "PASS", "observed": g.observed, + "result": if g.pass {"pass"} else {"fail"}, "source": "crumbs gates", "note": ""}) + }) + .collect(); + let _ = std::fs::write( + out.join("aien-proof-assertions.json"), + serde_json::to_string_pretty(&serde_json::json!({ "assertions": assertions })).unwrap(), + ); + gates +} + +fn count_records(path: &Path, class: ResultClass) -> usize { + let tr = std::fs::read(path).unwrap_or_default(); + // byte 7 of a CTR1 record is its result class + tr.chunks(TRACE_RECORD_BYTES) + .filter(|r| r.len() == TRACE_RECORD_BYTES && r[7] == class as u8) + .count() +} + +/// Positive bits must be a non-empty subset of tried bits in every sample. +fn check_samples(path: &Path) -> bool { + let b = std::fs::read(path).unwrap_or_default(); + b.chunks(SAMPLE_RECORD_BYTES).all(|r| { + // body: magic 4, version 2, n_ops 2, digests 64, 4 bytes, values 64, targets 64 => 204 + let pos = &r[204..220]; + let tried = &r[220..236]; + pos.iter().zip(tried).all(|(p, t)| p & !t == 0) && pos.iter().any(|p| *p != 0) + }) +} + +fn no_hidden_access(learner: &str, out: &Path) -> GateResult { + // Canary crumbs: the visible examples come from a known chain, and the + // held-outs are random 64-bit inputs the learner never sees. Neither those + // inputs nor their outputs can appear in the learner's memory unless the + // boundary leaks. + let mut s = session(learner, "canary", false, out); + let mut needles: Vec<Vec<u8>> = Vec::new(); + let mut rng = Rng::named("canary", &[1]); + let mut accepted = 0u32; + for seed in 1..=4u64 { + let f = registry().by_key("chain-basic-l2-w16").unwrap(); + let mut g = gen::generate(f, seed); + let KnownSolution::Known(p) = g.sealed.known_solution.clone() else { + unreachable!() + }; + let mut mk = || -> Vec<LaneExample> { + (0..16) + .map(|_| { + let x = rng.next_u64() | (1 << 63); + LaneExample { + input: vec![x], + output: vec![p.run(x)], + } + }) + .collect() + }; + g.sealed.heldouts.interpolation = mk(); + g.sealed.heldouts.extrapolation = mk(); + g.sealed.heldouts.adversarial = mk(); + for t in HeldoutTier::ALL { + for ex in g.sealed.heldouts.tier(t) { + for v in [ex.input[0], ex.output[0]] { + if v.to_le_bytes().iter().filter(|b| **b != 0).count() >= 6 { + needles.push(v.to_le_bytes().to_vec()); + needles.push(v.to_string().into_bytes()); + } + } + } + } + needles.push(g.sealed.digest().0.to_vec()); + needles.push(g.sealed.generator_instance_digest.0.to_vec()); + if let Ok(o) = s.present_with(&g.visible, &g.sealed) { + accepted += o.accepted as u32; + } + } + let pid = s.learner_pid().unwrap(); + let mem = read_process_writable_memory(pid).unwrap_or_default(); + let mem_hits = needles + .iter() + .filter(|n| crate::audit::contains(&mem, n)) + .count(); + let label_hits_mem = find_labels(&mem); + let transcript = s.transcript().map(|t| t.to_vec()).unwrap_or_default(); + let tr_hits = needles + .iter() + .filter(|n| crate::audit::contains(&transcript, n)) + .count(); + s.finish().unwrap(); + let bin = std::fs::read(learner).unwrap_or_default(); + let bin_hits: Vec<String> = sealed_specific_labels() + .into_iter() + .filter(|l| crate::audit::contains(&bin, l.as_bytes())) + .collect(); + gate( + "CRUMB_NO_HIDDEN_ACCESS_PASS", + !mem.is_empty() && mem_hits == 0 && label_hits_mem.is_empty() && tr_hits == 0 && bin_hits.is_empty() && accepted > 0, + format!( + "read {} KiB of the live learner's writable memory: {mem_hits} of {} canary held-out values/digests found; labels in memory {:?}; canary bytes in transcript {tr_hits}; sealed labels in learner binary {:?}; canary crumbs verified {accepted}/4", + mem.len() >> 10, + needles.len(), + label_hits_mem, + bin_hits + ), + ) +} + +fn promotion_and_reuse(learner: &str, out: &Path) -> Vec<GateResult> { + // A short trail: two capabilities, each shown twice, then their composition. + let script: [(&str, u64); 5] = [ + ("capability-03", 1), + ("capability-05", 1), + ("capability-03", 2), + ("capability-05", 2), + ("compose-03-05", 9), + ]; + let mut runs = Vec::new(); + for (cond, lib) in [("control-trail", false), ("learning-trail", true)] { + let mut s = session(learner, cond, lib, out); + let outs: Vec<CrumbOutcome> = script + .iter() + .map(|(k, seed)| present(&mut s, k, *seed)) + .collect(); + let (_, _, ladder) = s.finish().unwrap(); + runs.push((outs, ladder)); + } + let (learn_outs, ladder) = &runs[1]; + let admitted: Vec<_> = ladder + .ops + .values() + .filter(|r| r.stage == Stage::Admitted) + .collect(); + let evidence_ok = admitted.iter().all(|r| { + r.distinct_crumbs() >= 2 + && r.supports + .iter() + .all(|s| s.adversarial_total > 0 && s.extrapolation_total > 0) + && r.history + .windows(2) + .all(|w| w[0].0 < w[1].0 && w[0].1 <= w[1].1) + && r.scope_bits > 0 + }); + let mut res = vec![gate( + "CRUMB_OPERATION_PROMOTION_PASS", + !admitted.is_empty() && evidence_ok, + format!( + "{} operations admitted, each with >= 2 distinct held-out-verified crumbs, adversarial and extrapolation evidence, ordered ladder history and a recorded scope; {} tracked candidates not admitted", + admitted.len(), + ladder.ops.len() - admitted.len() + ), + )]; + let (cl, cc) = (&learn_outs[4], &runs[0].0[4]); + res.push(gate( + "CRUMB_LIBRARY_REUSE_PASS", + cl.accepted && cl.verified && cl.reused_library(), + format!( + "composition crumb: learning verified using admitted ops {:?} after {} candidates; control verified={} after {} candidates", + cl.trace.library_refs_in_solution, cl.stats.candidates_to_solution, cc.verified, cc.stats.candidates_to_solution + ), + )); + res +} + +fn scope_enforcement(learner: &str) -> GateResult { + let mut lp = LearnerProcess::spawn(learner, &[], false).expect("learner"); + lp.hello( + &SearchConfig { + max_candidates: 2000, + ..SearchConfig::default() + }, + true, + ) + .unwrap(); + let op = Program::of(&[(Op::Mul, 3), (Op::Add, 2)]); + lp.admit(1, 4, &op).unwrap(); // verified only for inputs below 2^4 + let small: Vec<(Vec<u64>, Vec<u64>)> = + (1..9u64).map(|x| (vec![x], vec![op.run(x) * 2])).collect(); + let wide: Vec<(Vec<u64>, Vec<u64>)> = [3u64, 700, 40_000, 9, 12_345, 60_001] + .iter() + .map(|&x| (vec![x], vec![op.run(x) * 2])) + .collect(); + let mut reject = |_: &Submission| Verdict::Reject; + let vs = VisibleCrumb::from_values(Encoding::DecimalUtf8, 0, 0, &small, None).unwrap(); + let vw = VisibleCrumb::from_values(Encoding::DecimalUtf8, 0, 0, &wide, None).unwrap(); + let in_scope = lp.run_crumb(&vs, &mut reject).unwrap(); + let out_scope = lp.run_crumb(&vw, &mut reject).unwrap(); + let _ = lp.shutdown(); + let lib_in = in_scope.bank.iter().filter(|b| b.origin == 1).count(); + let lib_out = out_scope.bank.iter().filter(|b| b.origin == 1).count(); + gate( + "CRUMB_SCOPE_ENFORCEMENT_PASS", + lib_in == 1 && lib_out == 0, + format!("operation admitted with a 4-bit scope: offered on a crumb with inputs below 2^4 ({lib_in}), withheld on a crumb with 16-bit inputs ({lib_out})"), + ) +} + +pub fn main(args: &[String]) -> i32 { + let get = |n: &str| { + args.iter() + .position(|a| a == n) + .and_then(|i| args.get(i + 1).cloned()) + }; + let learner = get("--learner").expect("--learner PATH"); + let out = get("--out") + .map(PathBuf::from) + .unwrap_or_else(|| std::env::temp_dir().join("crumbs-gates")); + let g = run_gates(&learner, &out); + let passed = g.iter().filter(|x| x.pass).count(); + println!( + "GATES {passed}/{} PASS (evidence: {})", + g.len(), + out.display() + ); + i32::from(passed != g.len()) +} diff --git a/crates/crumbs/src/gen/mechanisms.rs b/crates/crumbs/src/gen/mechanisms.rs new file mode 100644 index 00000000..15392a07 --- /dev/null +++ b/crates/crumbs/src/gen/mechanisms.rs @@ -0,0 +1,1285 @@ +//! Generator mechanisms. Each is a genuinely distinct way of producing +//! observations; registered families are parameterizations of these. +//! +//! Every mechanism returns honest observations: outputs are always the exact +//! value of the hidden rule (noise families corrupt only visible outputs, and +//! say so in the sealed record). Rabbit holes deceive through *which* inputs +//! are shown, never by labeling a wrong output correct. + +use super::{ + build_sets, default_sample, enumerate_basic, lane_bytes_for, out_mask_for, random_chain, + width_max, Ctx, Draft, FamilySpec, Stage, Vocab, +}; +use crate::gen::registry::capability_pool; +use crate::gen::rng::Rng; +use crate::program::{Op, Program, Step}; +use crate::sealed::{Heldouts, KnownSolution, LaneExample, VerificationMethod}; +use std::collections::HashSet; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Mechanism { + OpChain, + Repeat, + Threshold, + ParityBranch, + MultiLinear, + AbsDifference, + Recurrence1, + Recurrence2, + BitAutomaton, + LaneFold, + ByteReverse, + BitMirror, + SymmetricLanes, + ModResidue, + ModAffine, + PopCount, + NibblePermute, + GraphComponents, + HiddenGraphReach, + PolySequence, + Euclid, + DigitSum, + LatentOffset, + LatentXorMask, + NoisyChain, + PartialObservation, + CounterexampleSensitive, + TheoryFamily, + DecoySimpleRule, + MultiFit, + SpuriousField, + PrefixDiverges, + ElegantArbitrary, + InsufficientEvidence, + NoStructure, + CapabilityPrimitive, + CapabilityComposition, + WrapBoundary, +} + +impl Mechanism { + pub const ALL: [Mechanism; 38] = [ + Mechanism::OpChain, + Mechanism::Repeat, + Mechanism::Threshold, + Mechanism::ParityBranch, + Mechanism::MultiLinear, + Mechanism::AbsDifference, + Mechanism::Recurrence1, + Mechanism::Recurrence2, + Mechanism::BitAutomaton, + Mechanism::LaneFold, + Mechanism::ByteReverse, + Mechanism::BitMirror, + Mechanism::SymmetricLanes, + Mechanism::ModResidue, + Mechanism::ModAffine, + Mechanism::PopCount, + Mechanism::NibblePermute, + Mechanism::GraphComponents, + Mechanism::HiddenGraphReach, + Mechanism::PolySequence, + Mechanism::Euclid, + Mechanism::DigitSum, + Mechanism::LatentOffset, + Mechanism::LatentXorMask, + Mechanism::NoisyChain, + Mechanism::PartialObservation, + Mechanism::CounterexampleSensitive, + Mechanism::TheoryFamily, + Mechanism::DecoySimpleRule, + Mechanism::MultiFit, + Mechanism::SpuriousField, + Mechanism::PrefixDiverges, + Mechanism::ElegantArbitrary, + Mechanism::InsufficientEvidence, + Mechanism::NoStructure, + Mechanism::CapabilityPrimitive, + Mechanism::CapabilityComposition, + Mechanism::WrapBoundary, + ]; + + pub fn key(self) -> &'static str { + match self { + Mechanism::OpChain => "op-chain", + Mechanism::Repeat => "repeat", + Mechanism::Threshold => "threshold", + Mechanism::ParityBranch => "parity-branch", + Mechanism::MultiLinear => "multi-linear", + Mechanism::AbsDifference => "abs-difference", + Mechanism::Recurrence1 => "recurrence-1", + Mechanism::Recurrence2 => "recurrence-2", + Mechanism::BitAutomaton => "bit-automaton", + Mechanism::LaneFold => "lane-fold", + Mechanism::ByteReverse => "byte-reverse", + Mechanism::BitMirror => "bit-mirror", + Mechanism::SymmetricLanes => "symmetric-lanes", + Mechanism::ModResidue => "mod-residue", + Mechanism::ModAffine => "mod-affine", + Mechanism::PopCount => "pop-count", + Mechanism::NibblePermute => "nibble-permute", + Mechanism::GraphComponents => "graph-components", + Mechanism::HiddenGraphReach => "hidden-graph-reach", + Mechanism::PolySequence => "poly-sequence", + Mechanism::Euclid => "euclid", + Mechanism::DigitSum => "digit-sum", + Mechanism::LatentOffset => "latent-offset", + Mechanism::LatentXorMask => "latent-xor-mask", + Mechanism::NoisyChain => "noisy-chain", + Mechanism::PartialObservation => "partial-observation", + Mechanism::CounterexampleSensitive => "counterexample-sensitive", + Mechanism::TheoryFamily => "theory-family", + Mechanism::DecoySimpleRule => "decoy-simple-rule", + Mechanism::MultiFit => "multi-fit", + Mechanism::SpuriousField => "spurious-field", + Mechanism::PrefixDiverges => "prefix-diverges", + Mechanism::ElegantArbitrary => "elegant-arbitrary", + Mechanism::InsufficientEvidence => "insufficient-evidence", + Mechanism::NoStructure => "no-structure", + Mechanism::CapabilityPrimitive => "capability-primitive", + Mechanism::CapabilityComposition => "capability-composition", + Mechanism::WrapBoundary => "wrap-boundary", + } + } + + /// Per-mechanism code version (part of generator_code_digest). + pub fn version(self) -> u32 { + 1 + } +} + +pub fn run(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + match spec.mechanism { + Mechanism::OpChain => op_chain(spec, ctx), + Mechanism::Repeat => repeat(spec, ctx), + Mechanism::Threshold => threshold(spec, ctx), + Mechanism::ParityBranch => parity_branch(spec, ctx), + Mechanism::MultiLinear => multi_linear(spec, ctx), + Mechanism::AbsDifference => abs_difference(spec, ctx), + Mechanism::Recurrence1 => recurrence1(spec, ctx), + Mechanism::Recurrence2 => recurrence2(spec, ctx), + Mechanism::BitAutomaton => bit_automaton(spec, ctx), + Mechanism::LaneFold => lane_fold(spec, ctx), + Mechanism::ByteReverse => byte_reverse(spec, ctx), + Mechanism::BitMirror => bit_mirror(spec, ctx), + Mechanism::SymmetricLanes => symmetric_lanes(spec, ctx), + Mechanism::ModResidue => mod_residue(spec, ctx), + Mechanism::ModAffine => mod_affine(spec, ctx), + Mechanism::PopCount => pop_count(spec, ctx), + Mechanism::NibblePermute => nibble_permute(spec, ctx), + Mechanism::GraphComponents => graph_components(spec, ctx), + Mechanism::HiddenGraphReach => hidden_graph_reach(spec, ctx), + Mechanism::PolySequence => poly_sequence(spec, ctx), + Mechanism::Euclid => euclid(spec, ctx), + Mechanism::DigitSum => digit_sum(spec, ctx), + Mechanism::LatentOffset => latent_offset(spec, ctx), + Mechanism::LatentXorMask => latent_xor_mask(spec, ctx), + Mechanism::NoisyChain => noisy_chain(spec, ctx), + Mechanism::PartialObservation => partial_observation(spec, ctx), + Mechanism::CounterexampleSensitive => counterexample_sensitive(spec, ctx), + Mechanism::TheoryFamily => theory_family(spec, ctx), + Mechanism::DecoySimpleRule => decoy_simple_rule(spec, ctx), + Mechanism::MultiFit => multi_fit(spec, ctx), + Mechanism::SpuriousField => spurious_field(spec, ctx), + Mechanism::PrefixDiverges => prefix_diverges(spec, ctx), + Mechanism::ElegantArbitrary => elegant_arbitrary(spec, ctx), + Mechanism::InsufficientEvidence => insufficient_evidence(spec, ctx), + Mechanism::NoStructure => no_structure(spec, ctx), + Mechanism::CapabilityPrimitive => capability_primitive(spec, ctx), + Mechanism::CapabilityComposition => capability_composition(spec, ctx), + Mechanism::WrapBoundary => wrap_boundary(spec, ctx), + } +} + +// --------------------------------------------------------------------------- +// helpers +// --------------------------------------------------------------------------- + +fn unary_draft( + spec: &FamilySpec, + ctx: &mut Ctx, + out_width: u8, + known: KnownSolution, + sample: &mut dyn FnMut(&mut Rng, Stage) -> u64, + truth: &dyn Fn(u64) -> u64, +) -> Draft { + let p = &spec.params; + let in_lb = lane_bytes_for(p.encoding, p.width); + let out_lb = lane_bytes_for(p.encoding, out_width); + let mask = out_mask_for(p.encoding, out_lb); + let (visible, heldouts) = build_sets( + ctx, + p.visible as usize, + mask, + &mut |r, s| vec![sample(r, s)], + &|x: &[u64]| vec![truth(x[0])], + ); + Draft { + in_lane_bytes: in_lb, + out_lane_bytes: out_lb, + visible, + heldouts, + known, + alternatives: vec![], + noisy_visible: vec![], + domain: (0, width_max(p.width)), + requires: vec![], + provides: None, + verification: VerificationMethod::ExactGeneratorEvaluation, + } +} + +fn multi_draft( + spec: &FamilySpec, + ctx: &mut Ctx, + arity: usize, + out_width: u8, + sample: &mut dyn FnMut(&mut Rng, Stage) -> Vec<u64>, + truth: &dyn Fn(&[u64]) -> Vec<u64>, +) -> Draft { + let p = &spec.params; + let in_lb = lane_bytes_for(p.encoding, p.width); + let out_lb = lane_bytes_for(p.encoding, out_width); + let mask = out_mask_for(p.encoding, out_lb); + let (visible, heldouts) = build_sets(ctx, p.visible as usize, mask, sample, truth); + debug_assert!(visible.iter().all(|(i, _)| i.len() == arity)); + Draft { + in_lane_bytes: in_lb, + out_lane_bytes: out_lb, + visible, + heldouts, + known: KnownSolution::KnownOutsideProgramFormat, + alternatives: vec![], + noisy_visible: vec![], + domain: (0, width_max(p.width)), + requires: vec![], + provides: None, + verification: VerificationMethod::ExactGeneratorEvaluation, + } +} + +fn dflt(width: u8) -> impl FnMut(&mut Rng, Stage) -> u64 { + move |r, s| default_sample(r, s, width) +} + +fn lanes_sample(arity: usize, width: u8) -> impl FnMut(&mut Rng, Stage) -> Vec<u64> { + move |r, s| (0..arity).map(|_| default_sample(r, s, width)).collect() +} + +/// Re-draw every tier from a fixed input predicate (used by rabbit holes). +fn sets_from_pools( + ctx: &mut Ctx, + n_visible: usize, + visible_pool: &[u64], + interp_pool: &[u64], + extrap_pool: &[u64], + adversarial_pool: &[u64], + truth: &dyn Fn(u64) -> u64, +) -> (super::Pairs, Heldouts) { + let mut used = HashSet::new(); + let take = |rng: &mut Rng, pool: &[u64], n: usize, used: &mut HashSet<u64>| -> Vec<u64> { + let mut idx: Vec<usize> = (0..pool.len()).collect(); + rng.shuffle(&mut idx); + let mut out = Vec::new(); + for i in idx { + if out.len() == n { + break; + } + if used.insert(pool[i]) { + out.push(pool[i]); + } + } + out + }; + let vis = take(&mut ctx.vis, visible_pool, n_visible, &mut used); + let mk = |xs: Vec<u64>| { + xs.into_iter() + .map(|x| LaneExample { + input: vec![x], + output: vec![truth(x)], + }) + .collect() + }; + let visible = vis.iter().map(|&x| (vec![x], vec![truth(x)])).collect(); + let h = Heldouts { + interpolation: mk(take( + &mut ctx.hold, + interp_pool, + super::HELDOUT_PER_TIER, + &mut used, + )), + extrapolation: mk(take( + &mut ctx.hold, + extrap_pool, + super::HELDOUT_PER_TIER, + &mut used, + )), + adversarial: mk(take( + &mut ctx.hold, + adversarial_pool, + super::HELDOUT_PER_TIER, + &mut used, + )), + }; + (visible, h) +} + +fn pool(rng: &mut Rng, n: usize, stage: Stage, width: u8, keep: &dyn Fn(u64) -> bool) -> Vec<u64> { + let mut out = Vec::new(); + let mut tries = 0; + while out.len() < n && tries < n * 400 { + tries += 1; + let x = default_sample(rng, stage, width); + if keep(x) { + out.push(x); + } + } + out +} + +// --------------------------------------------------------------------------- +// single / composed transformations +// --------------------------------------------------------------------------- + +fn op_chain(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let prog = random_chain(&mut ctx.rule, spec.params.vocab, spec.params.len as usize); + let t = prog.clone(); + unary_draft( + spec, + ctx, + 64, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ) +} + +fn repeat(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let glen = 1 + ctx.rule.below(2) as usize; + let g = random_chain(&mut ctx.rule, spec.params.vocab, glen); + let mut prog = Program::default(); + for _ in 0..spec.params.len { + prog = prog.then(&g); + } + let t = prog.clone(); + unary_draft( + spec, + ctx, + 64, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ) +} + +fn wrap_boundary(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // A chain whose behaviour is dominated by wrap-around at the lane width. + let w = spec.params.width; + let mut prog = random_chain(&mut ctx.rule, Vocab::Basic, spec.params.len as usize); + prog.steps.push(Step { + op: Op::And, + imm: width_max(w), + }); + let t = prog.clone(); + unary_draft( + spec, + ctx, + w, + KnownSolution::Known(prog), + &mut dflt(w), + &move |x| t.run(x), + ) +} + +// --------------------------------------------------------------------------- +// conditional +// --------------------------------------------------------------------------- + +fn threshold(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let w = spec.params.width; + let t = ctx.rule.range(8, width_max(w).min(4095)); + let a = random_chain(&mut ctx.rule, Vocab::Basic, 1); + let b = random_chain(&mut ctx.rule, Vocab::Basic, 1); + unary_draft( + spec, + ctx, + 64, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(w), + &move |x| { + if x < t { + a.run(x) + } else { + b.run(x) + } + }, + ) +} + +fn parity_branch(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let m = 2 + ctx.rule.below(spec.params.k.max(1)); + let a = random_chain(&mut ctx.rule, Vocab::Basic, 1); + let b = random_chain(&mut ctx.rule, Vocab::Basic, 1); + unary_draft( + spec, + ctx, + 64, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(spec.params.width), + &move |x| { + if x % m == 0 { + a.run(x) + } else { + b.run(x) + } + }, + ) +} + +fn counterexample_sensitive(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // Almost always rule R, but a sparse residue class is shifted. Exactly one + // visible example sits in the exceptional class: ignoring it is an error. + let w = spec.params.width; + let base = random_chain(&mut ctx.rule, Vocab::Basic, 2); + let m = ctx.rule.range(11, 29); + let r = ctx.rule.below(m); + let delta = ctx.rule.range(1, 7); + let truth = { + let base = base.clone(); + move |x: u64| { + if x % m == r { + base.run(x).wrapping_add(delta) + } else { + base.run(x) + } + } + }; + let n = spec.params.visible as usize; + let normal = pool(&mut ctx.vis, 400, Stage::Visible, w, &|x| x % m != r); + let special = pool(&mut ctx.vis, 50, Stage::Visible, w, &|x| x % m == r); + let mut vis_pool: Vec<u64> = normal.iter().take(n - 1).cloned().collect(); + if let Some(s) = special.first() { + vis_pool.push(*s); + } + let interp = pool(&mut ctx.hold, 200, Stage::Interpolation, w, &|_| true); + let extrap = pool(&mut ctx.hold, 200, Stage::Extrapolation, w, &|_| true); + let adv = pool(&mut ctx.hold, 200, Stage::Interpolation, w, &|x| x % m == r); + let (visible, heldouts) = sets_from_pools(ctx, n, &vis_pool, &interp, &extrap, &adv, &truth); + Draft { + in_lane_bytes: 0, + out_lane_bytes: 0, + visible, + heldouts, + known: KnownSolution::KnownOutsideProgramFormat, + alternatives: vec![base], + noisy_visible: vec![], + domain: (0, width_max(w)), + requires: vec![], + provides: None, + verification: VerificationMethod::ExactGeneratorEvaluation, + } +} + +// --------------------------------------------------------------------------- +// multi-input relations +// --------------------------------------------------------------------------- + +fn multi_linear(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let arity = spec.params.len.clamp(2, 4) as usize; + let coef: Vec<u64> = (0..arity).map(|_| ctx.rule.range(1, 9)).collect(); + let d = ctx.rule.range(0, 20); + multi_draft( + spec, + ctx, + arity, + 64, + &mut lanes_sample(arity, spec.params.width), + &move |x| { + vec![x + .iter() + .zip(&coef) + .fold(d, |acc, (v, c)| acc.wrapping_add(v.wrapping_mul(*c)))] + }, + ) +} + +fn abs_difference(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let s = ctx.rule.range(0, 5); + multi_draft( + spec, + ctx, + 2, + 64, + &mut lanes_sample(2, spec.params.width), + &move |x| vec![x[0].abs_diff(x[1]) << s], + ) +} + +fn symmetric_lanes(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // Invariant under any permutation of the input lanes. + let arity = spec.params.len.clamp(2, 4) as usize; + let c = ctx.rule.range(1, 9); + multi_draft( + spec, + ctx, + arity, + 64, + &mut lanes_sample(arity, spec.params.width), + &move |x| { + let s: u64 = x.iter().fold(0u64, |a, v| a.wrapping_add(*v)); + let q: u64 = x + .iter() + .fold(0u64, |a, v| a.wrapping_add(v.wrapping_mul(*v))); + vec![q.wrapping_add(s.wrapping_mul(c))] + }, + ) +} + +fn theory_family(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // One law, many parameterizations: lane 0 is a parameter p, lane 1 is x. + let a = ctx.rule.range(1, 5); + let b = ctx.rule.range(0, 9); + let w = spec.params.width; + multi_draft( + spec, + ctx, + 2, + 64, + &mut move |r, s| vec![r.range(1, 12), default_sample(r, s, w)], + &move |x| { + vec![x[0] + .wrapping_mul(x[1]) + .wrapping_add(a.wrapping_mul(x[0])) + .wrapping_add(b)] + }, + ) +} + +fn euclid(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let _ = ctx.rule.next_u64(); + multi_draft( + spec, + ctx, + 2, + 64, + &mut lanes_sample(2, spec.params.width), + &|x| { + let (mut a, mut b) = (x[0], x[1]); + while b != 0 { + let t = a % b; + a = b; + b = t; + } + vec![a] + }, + ) +} + +// --------------------------------------------------------------------------- +// recurrence / sequences +// --------------------------------------------------------------------------- + +fn seq_sample(max_n: u64) -> impl FnMut(&mut Rng, Stage) -> u64 { + move |r, s| match s { + Stage::Visible | Stage::Interpolation => r.range(0, max_n), + Stage::Extrapolation | Stage::Adversarial => r.range(max_n + 1, max_n * 4), + } +} + +fn recurrence1(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let (a0, p, q) = ( + ctx.rule.range(0, 9), + ctx.rule.range(2, 5), + ctx.rule.range(0, 9), + ); + unary_draft( + spec, + ctx, + 64, + KnownSolution::KnownOutsideProgramFormat, + &mut seq_sample(24), + &move |n| (0..n).fold(a0, |a, _| a.wrapping_mul(p).wrapping_add(q)), + ) +} + +fn recurrence2(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let (s0, s1, p, q) = ( + ctx.rule.range(0, 5), + ctx.rule.range(1, 5), + ctx.rule.range(1, 3), + ctx.rule.range(1, 3), + ); + unary_draft( + spec, + ctx, + 64, + KnownSolution::KnownOutsideProgramFormat, + &mut seq_sample(24), + &move |n| { + let (mut a, mut b) = (s0, s1); + for _ in 0..n { + let c = b.wrapping_mul(p).wrapping_add(a.wrapping_mul(q)); + a = b; + b = c; + } + a + }, + ) +} + +fn poly_sequence(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let (a, b, c) = ( + ctx.rule.range(1, 5), + ctx.rule.range(0, 9), + ctx.rule.range(0, 9), + ); + unary_draft( + spec, + ctx, + 64, + KnownSolution::KnownOutsideProgramFormat, + &mut seq_sample(40), + &move |n| { + a.wrapping_mul(n) + .wrapping_mul(n) + .wrapping_add(b.wrapping_mul(n)) + .wrapping_add(c) + }, + ) +} + +fn prefix_diverges(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // f(n) = s(n) + c * prod_{i<K}(n - i): identical to the simple rule s on + // the visible prefix n < K, different from n = K on. + let s = random_chain(&mut ctx.rule, Vocab::Basic, 2); + let k = spec.params.visible as u64; + let c = ctx.rule.range(1, 3); + let truth = { + let s = s.clone(); + move |n: u64| { + let prod = (0..k).fold(1u64, |acc, i| acc.wrapping_mul(n.wrapping_sub(i))); + s.run(n).wrapping_add(c.wrapping_mul(prod)) + } + }; + let vis_pool: Vec<u64> = (0..k).collect(); + let interp: Vec<u64> = (k..k + 8).collect(); + let extrap: Vec<u64> = (k + 8..k + 64).collect(); + let adv: Vec<u64> = (k..k + 3).chain([k * 4, k * 16]).collect(); + let (visible, heldouts) = + sets_from_pools(ctx, k as usize, &vis_pool, &interp, &extrap, &adv, &truth); + Draft { + in_lane_bytes: 0, + out_lane_bytes: 0, + visible, + heldouts, + known: KnownSolution::KnownOutsideProgramFormat, + alternatives: vec![s], + noisy_visible: vec![], + domain: (0, k + 64), + requires: vec![], + provides: None, + verification: VerificationMethod::ExactGeneratorEvaluation, + } +} + +// --------------------------------------------------------------------------- +// state +// --------------------------------------------------------------------------- + +fn bit_automaton(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let states = spec.params.len.clamp(2, 8) as usize; + let table: Vec<[u8; 2]> = (0..states) + .map(|_| { + [ + ctx.rule.below(states as u64) as u8, + ctx.rule.below(states as u64) as u8, + ] + }) + .collect(); + let w = spec.params.width; + unary_draft( + spec, + ctx, + 8, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(w), + &move |x| { + let mut s = 0usize; + for i in 0..w { + s = table[s][((x >> i) & 1) as usize] as usize; + } + s as u64 + }, + ) +} + +fn lane_fold(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let arity = spec.params.len.clamp(2, 8) as usize; + let m = ctx.rule.range(2, 5); + let a = ctx.rule.range(0, 9); + multi_draft( + spec, + ctx, + arity, + 64, + &mut lanes_sample(arity, spec.params.width), + &move |x| { + vec![x + .iter() + .fold(a, |acc, v| acc.wrapping_mul(m).wrapping_add(*v))] + }, + ) +} + +// --------------------------------------------------------------------------- +// symmetry / permutation / bits +// --------------------------------------------------------------------------- + +fn byte_reverse(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let _ = ctx.rule.next_u64(); + let w = spec.params.width; + let bytes = (w as u32).div_ceil(8); + unary_draft( + spec, + ctx, + w, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(w), + &move |x| x.swap_bytes() >> (64 - 8 * bytes), + ) +} + +fn bit_mirror(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let _ = ctx.rule.next_u64(); + let w = spec.params.width as u32; + unary_draft( + spec, + ctx, + w as u8, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(w as u8), + &move |x| x.reverse_bits() >> (64 - w), + ) +} + +fn nibble_permute(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let mut perm: Vec<u32> = (0..4).collect(); + loop { + ctx.rule.shuffle(&mut perm); + if perm != [0, 1, 2, 3] { + break; + } + } + unary_draft( + spec, + ctx, + 16, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(16), + &move |x| { + (0..4).fold(0u64, |acc, i| { + acc | (((x >> (4 * i)) & 0xF) << (4 * perm[i as usize])) + }) + }, + ) +} + +fn pop_count(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let c = ctx.rule.range(0, 5); + let w = spec.params.width; + unary_draft( + spec, + ctx, + 8, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(w), + &move |x| x.count_ones() as u64 + c, + ) +} + +// --------------------------------------------------------------------------- +// modularity +// --------------------------------------------------------------------------- + +fn mod_residue(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let m = ctx.rule.range(3, 97) | 1; + unary_draft( + spec, + ctx, + 8, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(spec.params.width), + &move |x| x % m, + ) +} + +fn mod_affine(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let bits = ctx.rule.range(4, 12); + let prog = Program::of(&[ + (Op::Mul, ctx.rule.range(2, 7)), + (Op::Add, ctx.rule.range(1, 9)), + (Op::And, (1u64 << bits) - 1), + ]); + let t = prog.clone(); + unary_draft( + spec, + ctx, + bits as u8, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ) +} + +// --------------------------------------------------------------------------- +// graphs and algorithms +// --------------------------------------------------------------------------- + +fn graph_components(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let _ = ctx.rule.next_u64(); + let v = spec.params.len.clamp(3, 6) as usize; + let edges: Vec<(usize, usize)> = (0..v) + .flat_map(|a| (a + 1..v).map(move |b| (a, b))) + .collect(); + let e = edges.len() as u8; + let mut sample = move |r: &mut Rng, _s: Stage| r.below(1u64 << e); + unary_draft( + spec, + ctx, + 8, + KnownSolution::KnownOutsideProgramFormat, + &mut sample, + &move |mask| { + let mut parent: Vec<usize> = (0..v).collect(); + fn find(p: &mut [usize], x: usize) -> usize { + let mut x = x; + while p[x] != x { + p[x] = p[p[x]]; + x = p[x]; + } + x + } + for (i, &(a, b)) in edges.iter().enumerate() { + if mask >> i & 1 == 1 { + let (ra, rb) = (find(&mut parent, a), find(&mut parent, b)); + parent[ra] = rb; + } + } + (0..v).filter(|&x| find(&mut parent, x) == x).count() as u64 + }, + ) +} + +fn hidden_graph_reach(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // A hidden directed graph on N nodes; input = start node, output = reachable-set bitmask. + let n = spec.params.len.clamp(4, 16) as u64; + let adj: Vec<u64> = (0..n) + .map(|_| ctx.rule.below(1 << n) & ctx.rule.below(1 << n)) + .collect(); + let mut sample = move |r: &mut Rng, _s: Stage| r.below(n); + let mut d = unary_draft( + spec, + ctx, + 16, + KnownSolution::KnownOutsideProgramFormat, + &mut sample, + &move |s| { + let mut seen = 1u64 << s; + let mut frontier = seen; + while frontier != 0 { + let mut next = 0; + for i in 0..n { + if frontier >> i & 1 == 1 { + next |= adj[i as usize]; + } + } + frontier = next & !seen; + seen |= next; + } + seen + }, + ); + d.domain = (0, n - 1); + d +} + +fn digit_sum(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let _ = ctx.rule.next_u64(); + unary_draft( + spec, + ctx, + 8, + KnownSolution::KnownOutsideProgramFormat, + &mut dflt(spec.params.width), + &|mut x| { + let mut s = 0; + while x > 0 { + s += x % 10; + x /= 10; + } + s + }, + ) +} + +// --------------------------------------------------------------------------- +// latent variables, noise, partial observation +// --------------------------------------------------------------------------- + +fn latent_offset(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let prog = Program::of(&[ + (Op::Mul, ctx.rule.range(2, 5)), + (Op::Add, ctx.rule.range(6, 40)), + ]); + let t = prog.clone(); + unary_draft( + spec, + ctx, + 64, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ) +} + +fn latent_xor_mask(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let w = spec.params.width; + let prog = Program::of(&[ + (Op::Xor, ctx.rule.below(width_max(w))), + (Op::And, width_max(w)), + ]); + let t = prog.clone(); + unary_draft( + spec, + ctx, + w, + KnownSolution::Known(prog), + &mut dflt(w), + &move |x| t.run(x), + ) +} + +fn noisy_chain(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // Held-outs are exact; a minority of visible outputs carry a one-bit flip. + let prog = random_chain(&mut ctx.rule, Vocab::Basic, spec.params.len as usize); + let t = prog.clone(); + let mut d = unary_draft( + spec, + ctx, + 64, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ); + let n = d.visible.len(); + let flips = (n / 8).max(1); + let mut idx: Vec<usize> = (0..n).collect(); + ctx.rule.shuffle(&mut idx); + let mut noisy: Vec<u32> = idx[..flips].iter().map(|&i| i as u32).collect(); + noisy.sort_unstable(); + for &i in &noisy { + let bit = ctx.rule.below(6); + d.visible[i as usize].1[0] ^= 1u64 << bit; + } + d.noisy_visible = noisy; + d +} + +fn partial_observation(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // Only the low part of a hidden computation is observed. + let inner = random_chain(&mut ctx.rule, Vocab::Basic, 2); + let keep = *ctx.rule.pick(&[0x0Fu64, 0xFF]); + let prog = inner.then(&Program::of(&[(Op::And, keep)])); + let t = prog.clone(); + unary_draft( + spec, + ctx, + 8, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ) +} + +// --------------------------------------------------------------------------- +// rabbit holes +// --------------------------------------------------------------------------- + +fn decoy_simple_rule(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // A: truth = (a*x + b) & M. Visible inputs keep a*x+b <= M, so the + // simpler rule a*x + b fits every visible example. + let (a, b) = (ctx.rule.range(2, 7), ctx.rule.range(1, 9)); + let m = *ctx.rule.pick(&[0xFFu64, 0xFFF]); + let truth_p = Program::of(&[(Op::Mul, a), (Op::Add, b), (Op::And, m)]); + let decoy = Program::of(&[(Op::Mul, a), (Op::Add, b)]); + let w = spec.params.width; + let fits = |x: u64| a.wrapping_mul(x).wrapping_add(b) <= m; + let vis_pool = pool(&mut ctx.vis, 400, Stage::Visible, w, &|x| fits(x)); + let interp = pool(&mut ctx.hold, 400, Stage::Visible, w, &|x| fits(x)); + let extrap = pool(&mut ctx.hold, 400, Stage::Extrapolation, w, &|x| !fits(x)); + let adv = pool(&mut ctx.hold, 400, Stage::Visible, w, &|x| !fits(x)); + let t = truth_p.clone(); + let (visible, heldouts) = sets_from_pools( + ctx, + spec.params.visible as usize, + &vis_pool, + &interp, + &extrap, + &adv, + &move |x| t.run(x), + ); + rabbit( + visible, + heldouts, + KnownSolution::Known(truth_p), + vec![decoy], + w, + ) +} + +fn multi_fit(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // B: truth T and rival R agree on the visible inputs, disagree on held-outs. + let w = spec.params.width; + let n = spec.params.visible as usize; + let cands = enumerate_basic(2); + for _ in 0..200 { + let t = random_chain(&mut ctx.rule, Vocab::Basic, 2); + let tb = t.behavior(); + let probe = pool(&mut ctx.rule, 256, Stage::Visible, w, &|_| true); + let mut best: Option<(usize, &Program)> = None; + for r in &cands { + if r.behavior() == tb { + continue; + } + let agree = probe.iter().filter(|&&x| r.run(x) == t.run(x)).count(); + if agree >= n * 3 && agree < probe.len() && best.is_none_or(|(b, _)| agree > b) { + best = Some((agree, r)); + } + } + if let Some((_, r)) = best { + let r = r.clone(); + let (tc, rc) = (t.clone(), r.clone()); + let agree = move |x: u64| tc.run(x) == rc.run(x); + let vis_pool = pool(&mut ctx.vis, 600, Stage::Visible, w, &agree); + let interp = pool(&mut ctx.hold, 600, Stage::Interpolation, w, &|_| true); + let extrap = pool(&mut ctx.hold, 600, Stage::Extrapolation, w, &|_| true); + let adv = pool(&mut ctx.hold, 600, Stage::Interpolation, w, &|x| !agree(x)); + if vis_pool.len() < n || adv.is_empty() { + continue; + } + let tt = t.clone(); + let (visible, heldouts) = + sets_from_pools(ctx, n, &vis_pool, &interp, &extrap, &adv, &move |x| { + tt.run(x) + }); + return rabbit(visible, heldouts, KnownSolution::Known(t), vec![r], w); + } + } + op_chain(spec, ctx) +} + +fn spurious_field(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // C: x = a | (z << 16). The answer depends only on a, but in the visible + // sample the high field z equals the answer, so reading z also fits. + let f = random_chain(&mut ctx.rule, Vocab::Basic, 2); + let truth_p = Program::of(&[(Op::And, 0xFFFF)]).then(&f); + let decoy = Program::of(&[(Op::Shr, 16)]); + let mk_vis = |rng: &mut Rng, n: usize| -> Vec<u64> { + let mut out = Vec::new(); + let mut tries = 0; + while out.len() < n && tries < 10_000 { + tries += 1; + let a = rng.range(0, 0xFFFF); + let y = f.run(a); + if y <= 0xFFFF { + out.push(a | (y << 16)); + } + } + out + }; + let vis_pool = mk_vis(&mut ctx.vis, 200); + let interp = mk_vis(&mut ctx.hold, 200); + let extrap: Vec<u64> = (0..200) + .map(|_| ctx.hold.range(0, 0xFFFF) | (ctx.hold.range(0, 0xFFFF) << 16)) + .collect(); + let adv: Vec<u64> = (0..200) + .map(|_| ctx.hold.range(0, 0xFFFF) | (ctx.hold.range(0, 0xFFFF) << 32)) + .collect(); + let t = truth_p.clone(); + let (visible, heldouts) = sets_from_pools( + ctx, + spec.params.visible as usize, + &vis_pool, + &interp, + &extrap, + &adv, + &move |x| t.run(x), + ); + rabbit( + visible, + heldouts, + KnownSolution::Known(truth_p), + vec![decoy], + 48, + ) +} + +fn elegant_arbitrary(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // E: an arbitrary 256-entry table whose first entries follow a neat chain. + let s = random_chain(&mut ctx.rule, Vocab::Basic, 2); + let k = spec.params.visible as u64; + let table: Vec<u64> = (0..256u64) + .map(|i| { + if i < k { + s.run(i) + } else { + ctx.rule.below(1 << 20) + } + }) + .collect(); + let vis_pool: Vec<u64> = (0..k).collect(); + let rest: Vec<u64> = (k..256).collect(); + let t2 = table.clone(); + let (visible, heldouts) = + sets_from_pools(ctx, k as usize, &vis_pool, &rest, &rest, &rest, &move |x| { + t2[x as usize] + }); + let mut d = rabbit( + visible, + heldouts, + KnownSolution::NoCompactStructure, + vec![s], + 8, + ); + d.domain = (0, 255); + d +} + +fn insufficient_evidence(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + // F: too few examples to separate several short explanations. + let w = spec.params.width; + let n = spec.params.visible.clamp(2, 4) as usize; + let cands = enumerate_basic(2); + for _ in 0..200 { + let t = random_chain(&mut ctx.rule, Vocab::Basic, 2); + let xs = pool(&mut ctx.vis, n, Stage::Visible, w, &|x| x < 64); + if xs.len() < n { + continue; + } + let mut rivals: Vec<Program> = Vec::new(); + let mut seen = HashSet::new(); + seen.insert(t.behavior()); + for c in &cands { + if xs.iter().all(|&x| c.run(x) == t.run(x)) && seen.insert(c.behavior()) { + rivals.push(c.clone()); + } + } + if rivals.len() >= 2 { + rivals.truncate(8); + let tt = t.clone(); + let interp = pool(&mut ctx.hold, 200, Stage::Interpolation, w, &|_| true); + let extrap = pool(&mut ctx.hold, 200, Stage::Extrapolation, w, &|_| true); + // Every rival gets at least one held-out that separates it from the truth. + let mut adv: Vec<u64> = Vec::new(); + for r in &rivals { + let sep = pool(&mut ctx.hold, 1, Stage::Interpolation, w, &|x| { + r.run(x) != tt.run(x) && !xs.contains(&x) + }); + adv.extend(sep); + } + if adv.len() < rivals.len() { + continue; + } + let t3 = t.clone(); + let (visible, heldouts) = + sets_from_pools(ctx, n, &xs, &interp, &extrap, &adv, &move |x| t3.run(x)); + return rabbit(visible, heldouts, KnownSolution::Known(t), rivals, w); + } + } + op_chain(spec, ctx) +} + +fn no_structure(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let table: Vec<u64> = (0..256).map(|_| ctx.rule.below(1 << 24)).collect(); + let mut sample = |r: &mut Rng, _s: Stage| r.below(256); + let mut d = unary_draft( + spec, + ctx, + 24, + KnownSolution::NoCompactStructure, + &mut sample, + &move |x| table[x as usize], + ); + d.domain = (0, 255); + d +} + +fn rabbit( + visible: Vec<(Vec<u64>, Vec<u64>)>, + heldouts: Heldouts, + known: KnownSolution, + alternatives: Vec<Program>, + width: u8, +) -> Draft { + Draft { + in_lane_bytes: 0, + out_lane_bytes: 0, + visible, + heldouts, + known, + alternatives, + noisy_visible: vec![], + domain: (0, width_max(width)), + requires: vec![], + provides: None, + verification: VerificationMethod::ExactGeneratorEvaluation, + } +} + +// --------------------------------------------------------------------------- +// capabilities and their compositions (the breadcrumb trail) +// --------------------------------------------------------------------------- + +fn capability_primitive(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let pool = capability_pool(); + let cap = &pool[spec.params.caps[0] as usize]; + let prog = cap.program.clone(); + let t = prog.clone(); + let mut d = unary_draft( + spec, + ctx, + 64, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ); + d.provides = Some(cap.id); + d +} + +fn capability_composition(spec: &FamilySpec, ctx: &mut Ctx) -> Draft { + let pool = capability_pool(); + let mut prog = Program::default(); + let mut requires = Vec::new(); + for &c in &spec.params.caps { + prog = prog.then(&pool[c as usize].program); + requires.push(pool[c as usize].id); + } + let t = prog.clone(); + let mut d = unary_draft( + spec, + ctx, + 64, + KnownSolution::Known(prog), + &mut dflt(spec.params.width), + &move |x| t.run(x), + ); + d.requires = requires; + d +} + +/// Count how many visible examples a program explains (used by tests). +pub fn visible_agreement(p: &Program, visible: &[(Vec<u64>, Vec<u64>)]) -> usize { + visible.iter().filter(|(i, o)| p.run(i[0]) == o[0]).count() +} diff --git a/crates/crumbs/src/gen/mod.rs b/crates/crumbs/src/gen/mod.rs new file mode 100644 index 00000000..c1434766 --- /dev/null +++ b/crates/crumbs/src/gen/mod.rs @@ -0,0 +1,426 @@ +//! Generator framework: deterministic families built from reusable mechanisms. +//! +//! `generate(family, seed)` is a pure function of (family_id, +//! generator_version, seed, canonical parameters). It returns the +//! learner-visible crumb and its sealed record together; the two are separated +//! by type from that point on. +//! +//! Streams: the hidden rule is drawn from `rule`, visible inputs from +//! `visible`, and held-outs from `heldout` keyed by a separate heldout seed, +//! so the visible set can be regenerated without touching the held-outs. + +pub mod mechanisms; +pub mod registry; +pub mod rng; + +use crate::canon::Enc; +use crate::digest::{digest, Digest, Domain}; +use crate::program::{Op, Program, Step}; +use crate::provenance::Provenance; +use crate::sealed::{ + generator_instance_digest, CapabilityId, DecoyStatus, Heldouts, KnownSolution, LaneExample, + Rung, SealedCrumb, SourceFamily, TruthStatus, VerificationMethod, SEALED_SCHEMA_VERSION, +}; +use crate::visible::{lane_mask, Encoding, VisibleCrumb}; +use rng::Rng; +use serde::Serialize; +use std::collections::HashSet; + +pub use mechanisms::Mechanism; +pub use registry::{capability_pool, registry, Registry}; + +/// Version of every v1 generator. A behaviour change requires a bump; the +/// golden vectors in the test suite fail otherwise. +pub const GENERATOR_VERSION: &str = "1.0.0"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] +pub enum Vocab { + /// add/sub/mul/and/or with small constants. + Basic = 1, + /// Basic plus xor/shift/rotate. + Extended = 2, +} + +/// Static, canonical family parameters (part of GeneratorInstanceDigest). +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Params { + pub encoding: Encoding, + /// Input lane width in bits (lane 0 range for unary families). + pub width: u8, + /// Chain length, arity, repetition count or state count, per mechanism. + pub len: u8, + /// Extra integer parameter, per mechanism. + pub k: u64, + pub vocab: Vocab, + /// Capability pool indices (capability and composition families). + pub caps: Vec<u16>, + /// Visible example count. + pub visible: u8, +} + +impl Params { + pub fn new(width: u8, len: u8) -> Params { + Params { + encoding: Encoding::DecimalUtf8, + width, + len, + k: 0, + vocab: Vocab::Basic, + caps: vec![], + visible: 8, + } + } + + pub fn to_bytes(&self) -> Vec<u8> { + let mut e = Enc::new(); + e.u8(self.encoding as u8) + .u8(self.width) + .u8(self.len) + .u64(self.k) + .u8(self.vocab as u8); + e.u32(self.caps.len() as u32); + for c in &self.caps { + e.u16(*c); + } + e.u8(self.visible); + e.finish() + } +} + +/// One registered family: a mechanism plus parameters plus sealed labels. +#[derive(Clone, Debug)] +pub struct FamilySpec { + pub id: u32, + pub key: String, + pub mechanism: Mechanism, + pub params: Params, + pub rung: Rung, + pub source_family: SourceFamily, + pub provenance: Provenance, + pub decoy: DecoyStatus, + pub difficulty: u16, + pub topic: &'static str, +} + +/// A generated crumb: the visible half and the sealed half. +pub struct Generated { + pub visible: VisibleCrumb, + pub sealed: SealedCrumb, +} + +/// What a mechanism produces before the framework seals it. +pub struct Draft { + pub in_lane_bytes: u8, + pub out_lane_bytes: u8, + pub visible: Vec<(Vec<u64>, Vec<u64>)>, + pub heldouts: Heldouts, + pub known: KnownSolution, + pub alternatives: Vec<Program>, + pub noisy_visible: Vec<u32>, + pub domain: (u64, u64), + pub requires: Vec<CapabilityId>, + pub provides: Option<CapabilityId>, + pub verification: VerificationMethod, +} + +/// Random streams handed to a mechanism. +pub struct Ctx { + pub rule: Rng, + pub vis: Rng, + pub hold: Rng, +} + +/// Which sample a sampler is being asked for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + Visible, + Interpolation, + Extrapolation, + Adversarial, +} + +pub fn heldout_seed(family_id: u32, seed: u64) -> u64 { + let mut e = Enc::new(); + e.bytes(b"heldout-seed").u32(family_id).u64(seed); + let d = digest(Domain::Rng, &e.finish()); + u64::from_le_bytes(d.0[..8].try_into().unwrap()) +} + +/// Code identity of a mechanism at this generator version. +pub fn generator_code_digest(m: Mechanism) -> Digest { + let mut e = Enc::new(); + e.str(m.key()).u32(m.version()).str(GENERATOR_VERSION); + digest(Domain::GeneratorCode, &e.finish()) +} + +pub fn generate(spec: &FamilySpec, seed: u64) -> Generated { + let hseed = heldout_seed(spec.id, seed); + let mut ctx = Ctx { + rule: Rng::named("rule", &[spec.id as u64, seed]), + vis: Rng::named("visible", &[spec.id as u64, seed]), + hold: Rng::named("heldout", &[spec.id as u64, hseed]), + }; + let draft = mechanisms::run(spec, &mut ctx); + let visible = VisibleCrumb::from_values( + spec.params.encoding, + draft.in_lane_bytes, + draft.out_lane_bytes, + &draft.visible, + None, + ) + .expect("mechanism produced a well-formed visible set"); + let params = spec.params.to_bytes(); + let sealed = SealedCrumb { + schema_version: SEALED_SCHEMA_VERSION, + crumb_digest: visible.digest(), + family_id: spec.id, + family_key: spec.key.clone(), + mechanism: spec.mechanism.key().to_string(), + generator_version: GENERATOR_VERSION.to_string(), + generator_code_digest: generator_code_digest(spec.mechanism), + seed, + heldout_seed: hseed, + generator_instance_digest: generator_instance_digest( + spec.id, + GENERATOR_VERSION, + seed, + ¶ms, + ), + generation_parameters: params, + verification_method: draft.verification, + difficulty: spec.difficulty, + rung: spec.rung, + required_capabilities: draft.requires, + provides_capability: draft.provides, + provenance: spec.provenance, + source_family: spec.source_family, + truth_status: TruthStatus::Verified, + decoy_status: spec.decoy, + known_solution: draft.known, + alternatives: draft.alternatives, + noisy_visible: draft.noisy_visible, + expected_domain: draft.domain, + topic_internal: spec.topic.to_string(), + heldouts: draft.heldouts, + }; + Generated { visible, sealed } +} + +// --------------------------------------------------------------------------- +// Combinators shared by mechanisms. +// --------------------------------------------------------------------------- + +pub fn width_max(width: u8) -> u64 { + if width >= 64 { + u64::MAX + } else { + (1u64 << width) - 1 + } +} + +/// The default unary input sampler for a lane of `width` bits. +pub fn default_sample(rng: &mut Rng, stage: Stage, width: u8) -> u64 { + let max = width_max(width); + let common = max.min(4095); + match stage { + Stage::Visible | Stage::Interpolation => match rng.below(10) { + 0..=5 => rng.range(0, common), + 6..=7 => rng.range(0, max.min(31)), + _ => rng.range(0, max), + }, + Stage::Extrapolation => { + if common < max { + rng.range(common + 1, max) + } else { + rng.range(0, max) + } + } + Stage::Adversarial => { + let k = rng.below(width as u64) as u32; + let p = 1u64.checked_shl(k).unwrap_or(0) & max; + match rng.below(8) { + 0 => 0, + 1 => 1, + 2 => max, + 3 => max.wrapping_sub(1) & max, + 4 => p, + 5 => p.wrapping_sub(1) & max, + 6 => p.wrapping_add(1) & max, + _ => rng.range(0, max), + } + } + } +} + +/// Sizes of the sealed held-out tiers. +pub const HELDOUT_PER_TIER: usize = 16; + +/// Build visible + three held-out tiers from a truth function and a sampler. +/// Held-out inputs never repeat a visible input, and tiers never repeat each other. +pub type Pairs = Vec<(Vec<u64>, Vec<u64>)>; + +pub fn build_sets( + ctx: &mut Ctx, + n_visible: usize, + out_mask: u64, + sample: &mut dyn FnMut(&mut Rng, Stage) -> Vec<u64>, + truth: &dyn Fn(&[u64]) -> Vec<u64>, +) -> (Pairs, Heldouts) { + let mut seen: HashSet<Vec<u64>> = HashSet::new(); + let mut visible = Vec::new(); + draw_unique( + &mut ctx.vis, + Stage::Visible, + n_visible, + &mut seen, + sample, + &mut |x| visible.push((x.clone(), mask_all(truth(&x), out_mask))), + ); + let mut h = Heldouts::default(); + for (stage, dst) in [ + (Stage::Interpolation, &mut h.interpolation), + (Stage::Extrapolation, &mut h.extrapolation), + (Stage::Adversarial, &mut h.adversarial), + ] { + draw_unique( + &mut ctx.hold, + stage, + HELDOUT_PER_TIER, + &mut seen, + sample, + &mut |x| { + dst.push(LaneExample { + output: mask_all(truth(&x), out_mask), + input: x, + }) + }, + ); + } + (visible, h) +} + +fn mask_all(mut v: Vec<u64>, m: u64) -> Vec<u64> { + for x in v.iter_mut() { + *x &= m; + } + v +} + +fn draw_unique( + rng: &mut Rng, + stage: Stage, + n: usize, + seen: &mut HashSet<Vec<u64>>, + sample: &mut dyn FnMut(&mut Rng, Stage) -> Vec<u64>, + sink: &mut dyn FnMut(Vec<u64>), +) { + let mut got = 0; + let mut tries = 0; + while got < n && tries < n * 200 { + tries += 1; + let x = sample(rng, stage); + if seen.insert(x.clone()) { + sink(x); + got += 1; + } + } +} + +pub fn out_mask_for(encoding: Encoding, out_lane_bytes: u8) -> u64 { + match encoding { + Encoding::DecimalUtf8 => u64::MAX, + Encoding::RawLe => lane_mask(out_lane_bytes), + } +} + +pub fn lane_bytes_for(encoding: Encoding, width_bits: u8) -> u8 { + match encoding { + Encoding::DecimalUtf8 => 0, + Encoding::RawLe => match width_bits { + 0..=8 => 1, + 9..=16 => 2, + 17..=32 => 4, + _ => 8, + }, + } +} + +/// Random step from a vocabulary. +pub fn random_step(rng: &mut Rng, vocab: Vocab) -> Step { + let n_ops = match vocab { + Vocab::Basic => 5, + Vocab::Extended => 9, + }; + let op = Op::from_u8(1 + rng.below(n_ops) as u8).unwrap(); + let imm = match op { + Op::Add | Op::Sub => rng.range(1, 9), + Op::Mul => rng.range(2, 7), + Op::And => *rng.pick(&[0xFF, 0x0F, 0x3F, 0xFFF, 0xFFFF]), + Op::Or => *rng.pick(&[1, 2, 4, 8, 16]), + Op::Xor => rng.range(1, 255), + Op::Shl | Op::Shr => rng.range(1, 4), + Op::Rotl => rng.range(1, 15), + }; + Step { op, imm } +} + +/// Probe-behaviour is constant (the chain ignores its input). +pub fn is_constant(p: &Program) -> bool { + let first = p.run(crate::program::PROBES[0]); + crate::program::PROBES.iter().all(|&x| p.run(x) == first) +} + +/// A chain of `len` steps with no dead step: removing any one step changes +/// its behaviour, and it is not constant. +pub fn random_chain(rng: &mut Rng, vocab: Vocab, len: usize) -> Program { + for _ in 0..10_000 { + let p = Program::new((0..len).map(|_| random_step(rng, vocab)).collect()); + if is_constant(&p) { + continue; + } + let b = p.behavior(); + let dead = (0..len).any(|i| { + let mut q = p.clone(); + q.steps.remove(i); + q.behavior() == b + }); + if !dead { + return p; + } + } + Program::of(&[(Op::Add, 1)]) +} + +/// Every Basic chain of length 1..=max_len (the generator's own enumeration, +/// used to find rival explanations for ambiguity and multi-fit families). +pub fn enumerate_basic(max_len: usize) -> Vec<Program> { + let mut steps = Vec::new(); + for imm in 1..=9 { + steps.push(Step { op: Op::Add, imm }); + steps.push(Step { op: Op::Sub, imm }); + } + for imm in 2..=7 { + steps.push(Step { op: Op::Mul, imm }); + } + for imm in [0xFF, 0x0F, 0x3F, 0xFFF, 0xFFFF] { + steps.push(Step { op: Op::And, imm }); + } + for imm in [1, 2, 4, 8, 16] { + steps.push(Step { op: Op::Or, imm }); + } + let mut out: Vec<Program> = steps.iter().map(|s| Program::new(vec![*s])).collect(); + let mut frontier = out.clone(); + for _ in 1..max_len { + let mut next = Vec::new(); + for p in &frontier { + for s in &steps { + let mut q = p.clone(); + q.steps.push(*s); + next.push(q); + } + } + out.extend(next.iter().cloned()); + frontier = next; + } + out +} diff --git a/crates/crumbs/src/gen/registry.rs b/crates/crumbs/src/gen/registry.rs new file mode 100644 index 00000000..2501a61f --- /dev/null +++ b/crates/crumbs/src/gen/registry.rs @@ -0,0 +1,708 @@ +//! The v1 family registry: 38 mechanisms parameterized into 100+ registered +//! family ids, plus the capability pool the breadcrumb trail is built from. +//! +//! Family ids are assigned in registration order and are part of every +//! GeneratorInstanceDigest; the order below is frozen for registry v1. + +use super::mechanisms::Mechanism; +use super::rng::Rng; +use super::{random_chain, FamilySpec, Params, Vocab}; +use crate::canon::Enc; +use crate::digest::{digest, Domain}; +use crate::program::Program; +use crate::provenance::Provenance; +use crate::sealed::{AdversarialClass, CapabilityId, DecoyStatus, Rung, SourceFamily}; +use crate::visible::Encoding; +use std::collections::HashSet; +use std::sync::OnceLock; + +pub const REGISTRY_VERSION: &str = "crumbs-registry/1.0.0"; +pub const CAPABILITY_POOL_SIZE: usize = 12; + +/// A hidden capability: a short transformation that later crumbs quietly require. +#[derive(Clone, Debug)] +pub struct Capability { + pub index: u16, + pub id: CapabilityId, + pub program: Program, +} + +/// Twelve distinct two-step capabilities drawn deterministically from the +/// Basic vocabulary. Deliberately not tuned to any learner. +pub fn capability_pool() -> &'static [Capability] { + static POOL: OnceLock<Vec<Capability>> = OnceLock::new(); + POOL.get_or_init(|| { + let mut rng = Rng::named("capability-pool", &[1]); + let mut out = Vec::new(); + let mut seen = HashSet::new(); + while out.len() < CAPABILITY_POOL_SIZE { + let p = random_chain(&mut rng, Vocab::Basic, 2); + if !seen.insert(p.behavior()) { + continue; + } + let mut e = Enc::new(); + e.str(REGISTRY_VERSION).blob(&p.to_bytes()); + out.push(Capability { + index: out.len() as u16, + id: digest(Domain::Capability, &e.finish()), + program: p, + }); + } + out + }) +} + +pub struct Registry { + pub families: Vec<FamilySpec>, +} + +impl Registry { + pub fn get(&self, id: u32) -> Option<&FamilySpec> { + self.families.iter().find(|f| f.id == id) + } + pub fn by_key(&self, key: &str) -> Option<&FamilySpec> { + self.families.iter().find(|f| f.key == key) + } +} + +/// Capability pairs used by composition families (ordered: first applied first). +pub const COMPOSITION_PAIRS: [(u16, u16); 24] = [ + (0, 1), + (1, 2), + (2, 3), + (3, 4), + (4, 5), + (5, 6), + (6, 7), + (7, 8), + (8, 9), + (9, 10), + (10, 11), + (11, 0), + (0, 2), + (1, 3), + (2, 4), + (3, 5), + (4, 6), + (5, 7), + (6, 8), + (7, 9), + (8, 10), + (9, 11), + (10, 0), + (11, 1), +]; +pub const COMPOSITION_TRIPLES: [(u16, u16, u16); 8] = [ + (0, 1, 2), + (3, 4, 5), + (6, 7, 8), + (9, 10, 11), + (0, 3, 6), + (1, 4, 7), + (2, 5, 8), + (9, 0, 4), +]; + +pub fn registry() -> &'static Registry { + static REG: OnceLock<Registry> = OnceLock::new(); + REG.get_or_init(build) +} + +struct B { + fams: Vec<FamilySpec>, +} + +impl B { + #[allow(clippy::too_many_arguments)] + fn add( + &mut self, + key: String, + mechanism: Mechanism, + params: Params, + rung: Rung, + source: SourceFamily, + provenance: Provenance, + decoy: DecoyStatus, + difficulty: u16, + topic: &'static str, + ) { + let id = self.fams.len() as u32 + 1; + self.fams.push(FamilySpec { + id, + key, + mechanism, + params, + rung, + source_family: source, + provenance, + decoy, + difficulty, + topic, + }); + } +} + +fn p(width: u8, len: u8) -> Params { + Params::new(width, len) +} + +fn build() -> Registry { + use Mechanism as M; + use SourceFamily as S; + let syn = Provenance::synthetic(); + let adv = Provenance::adversarial(); + let hum = Provenance::human_theory(); + let clean = DecoyStatus::Clean; + let mut b = B { fams: Vec::new() }; + + // Single and chained transformations across widths and vocabularies. + for (len, rung) in [ + (1u8, Rung::SingleTransformation), + (2, Rung::TwoTransformations), + (3, Rung::MultiStepAlgorithm), + (4, Rung::Composition), + ] { + for width in [8u8, 16, 32] { + b.add( + format!("chain-basic-l{len}-w{width}"), + M::OpChain, + p(width, len), + rung, + S::Capability, + syn, + clean, + len as u16 * 10, + "wrapping arithmetic chain", + ); + } + } + for (len, rung) in [ + (1u8, Rung::SingleTransformation), + (2, Rung::TwoTransformations), + (3, Rung::MultiStepAlgorithm), + ] { + let mut prm = p(32, len); + prm.vocab = Vocab::Extended; + b.add( + format!("chain-ext-l{len}-w32"), + M::OpChain, + prm.clone(), + rung, + S::Capability, + syn, + clean, + 15 + len as u16 * 10, + "bitwise chain", + ); + prm.encoding = Encoding::RawLe; + b.add( + format!("chain-ext-l{len}-w32-raw"), + M::OpChain, + prm, + rung, + S::Capability, + syn, + clean, + 15 + len as u16 * 10, + "bitwise chain, raw bytes", + ); + } + for k in [2u8, 3, 4] { + b.add( + format!("repeat-k{k}"), + M::Repeat, + p(16, k), + Rung::RepeatedTransformation, + S::Capability, + syn, + clean, + 20 + k as u16 * 5, + "repeated transformation", + ); + } + for w in [8u8, 16] { + b.add( + format!("wrap-w{w}"), + M::WrapBoundary, + p(w, 2), + Rung::Modularity, + S::Capability, + syn, + clean, + 30, + "wrap at lane width", + ); + } + b.add( + "threshold-w12".into(), + M::Threshold, + p(12, 1), + Rung::ConditionalTransformation, + S::Capability, + syn, + clean, + 35, + "piecewise rule", + ); + b.add( + "threshold-w16".into(), + M::Threshold, + p(16, 1), + Rung::ConditionalTransformation, + S::Capability, + syn, + clean, + 40, + "piecewise rule", + ); + for k in [1u64, 4] { + let mut prm = p(16, 1); + prm.k = k; + b.add( + format!("parity-branch-k{k}"), + M::ParityBranch, + prm, + Rung::ConditionalTransformation, + S::Capability, + syn, + clean, + 35, + "residue-class branch", + ); + } + for a in [2u8, 3, 4] { + b.add( + format!("multi-linear-a{a}"), + M::MultiLinear, + p(12, a), + Rung::MultiInputRelation, + S::Capability, + syn, + clean, + 30 + a as u16 * 5, + "weighted lane sum", + ); + } + b.add( + "abs-difference".into(), + M::AbsDifference, + p(16, 2), + Rung::MultiInputRelation, + S::Capability, + syn, + clean, + 30, + "lane distance", + ); + for a in [2u8, 3] { + b.add( + format!("symmetric-lanes-a{a}"), + M::SymmetricLanes, + p(10, a), + Rung::Invariance, + S::Capability, + syn, + clean, + 45, + "permutation-invariant lanes", + ); + } + b.add( + "theory-family".into(), + M::TheoryFamily, + p(12, 2), + Rung::TheoryFormation, + S::Capability, + syn, + clean, + 55, + "one law, many parameters", + ); + b.add( + "euclid".into(), + M::Euclid, + p(16, 2), + Rung::MultiStepAlgorithm, + S::Capability, + hum, + clean, + 60, + "greatest common divisor", + ); + b.add( + "recurrence-1".into(), + M::Recurrence1, + p(8, 1), + Rung::Recurrence, + S::Capability, + syn, + clean, + 45, + "first-order recurrence", + ); + b.add( + "recurrence-2".into(), + M::Recurrence2, + p(8, 2), + Rung::Recurrence, + S::Capability, + syn, + clean, + 55, + "second-order recurrence", + ); + b.add( + "poly-sequence".into(), + M::PolySequence, + p(8, 2), + Rung::Recurrence, + S::Capability, + syn, + clean, + 45, + "quadratic sequence", + ); + for (s, w) in [(2u8, 8u8), (3, 12), (4, 16)] { + b.add( + format!("bit-automaton-s{s}-w{w}"), + M::BitAutomaton, + p(w, s), + Rung::State, + S::Capability, + syn, + clean, + 50 + s as u16 * 5, + "finite automaton over bits", + ); + } + for a in [3u8, 5] { + b.add( + format!("lane-fold-a{a}"), + M::LaneFold, + p(8, a), + Rung::State, + S::Capability, + syn, + clean, + 50, + "running fold over lanes", + ); + } + for w in [16u8, 32] { + b.add( + format!("byte-reverse-w{w}"), + M::ByteReverse, + p(w, 1), + Rung::Symmetry, + S::Capability, + syn, + clean, + 45, + "byte order reversal", + ); + } + for w in [8u8, 16] { + b.add( + format!("bit-mirror-w{w}"), + M::BitMirror, + p(w, 1), + Rung::Symmetry, + S::Capability, + syn, + clean, + 45, + "bit order reversal", + ); + } + b.add( + "nibble-permute".into(), + M::NibblePermute, + p(16, 1), + Rung::Symmetry, + S::Capability, + syn, + clean, + 50, + "fixed nibble permutation", + ); + for w in [16u8, 32] { + b.add( + format!("pop-count-w{w}"), + M::PopCount, + p(w, 1), + Rung::MultiStepAlgorithm, + S::Capability, + syn, + clean, + 45, + "set-bit count", + ); + } + for w in [12u8, 24] { + b.add( + format!("mod-residue-w{w}"), + M::ModResidue, + p(w, 1), + Rung::Modularity, + S::Capability, + syn, + clean, + 45, + "residue", + ); + b.add( + format!("mod-affine-w{w}"), + M::ModAffine, + p(w, 3), + Rung::Modularity, + S::Capability, + syn, + clean, + 40, + "affine map with wrap", + ); + } + for v in [4u8, 5] { + b.add( + format!("graph-components-v{v}"), + M::GraphComponents, + p(8, v), + Rung::MultiStepAlgorithm, + S::Capability, + hum, + clean, + 65, + "connected components of an edge mask", + ); + } + for n in [12u8, 16] { + let mut prm = p(8, n); + prm.visible = 6; + b.add( + format!("hidden-graph-reach-n{n}"), + M::HiddenGraphReach, + prm, + Rung::LatentVariables, + S::Capability, + syn, + clean, + 60, + "reachability in a hidden graph", + ); + } + b.add( + "digit-sum".into(), + M::DigitSum, + p(20, 1), + Rung::MultiStepAlgorithm, + S::Capability, + hum, + clean, + 50, + "base-ten digit sum", + ); + for w in [16u8, 32] { + b.add( + format!("latent-offset-w{w}"), + M::LatentOffset, + p(w, 2), + Rung::LatentVariables, + S::Capability, + syn, + clean, + 40, + "hidden constant offset", + ); + } + b.add( + "latent-xor-w16".into(), + M::LatentXorMask, + p(16, 2), + Rung::LatentVariables, + S::Capability, + syn, + clean, + 45, + "hidden xor key", + ); + for w in [16u8, 32] { + b.add( + format!("partial-observation-w{w}"), + M::PartialObservation, + p(w, 2), + Rung::PartialObservation, + S::Capability, + syn, + clean, + 45, + "only low bits observed", + ); + } + b.add( + "counterexample-sensitive".into(), + M::CounterexampleSensitive, + p(12, 2), + Rung::CounterexampleSearch, + S::Capability, + syn, + clean, + 60, + "rule with a sparse exception class", + ); + + // Rabbit holes (population: rabbit hole), classes A to E and G. + let rh = |c| DecoyStatus::RabbitHole(c); + for w in [12u8, 16] { + b.add( + format!("decoy-simple-rule-w{w}"), + M::DecoySimpleRule, + p(w, 3), + Rung::CounterexampleSearch, + S::RabbitHole, + adv, + rh(AdversarialClass::SimpleWrongRule), + 55, + "masked affine shown only below the mask", + ); + b.add( + format!("multi-fit-w{w}"), + M::MultiFit, + p(w, 2), + Rung::CounterexampleSearch, + S::RabbitHole, + adv, + rh(AdversarialClass::MultiFit), + 55, + "two chains agree on the shown inputs", + ); + } + b.add( + "spurious-field".into(), + M::SpuriousField, + p(48, 2), + Rung::PartialObservation, + S::RabbitHole, + adv, + rh(AdversarialClass::SpuriousDimension), + 60, + "high field copies the answer when shown", + ); + for k in [6u8, 8] { + let mut prm = p(8, 2); + prm.visible = k; + b.add( + format!("prefix-diverges-k{k}"), + M::PrefixDiverges, + prm, + Rung::Recurrence, + S::RabbitHole, + adv, + rh(AdversarialClass::PrefixDiverges), + 60, + "prefix imitates a simple rule", + ); + } + b.add( + "elegant-arbitrary".into(), + M::ElegantArbitrary, + p(8, 2), + Rung::TheoryFormation, + S::RabbitHole, + adv, + rh(AdversarialClass::ElegantArbitrary), + 60, + "arbitrary table with a neat prefix", + ); + for len in [2u8, 3] { + let mut prm = p(16, len); + prm.visible = 12; + b.add( + format!("noisy-chain-l{len}"), + M::NoisyChain, + prm, + Rung::NoisyObservation, + S::RabbitHole, + adv, + rh(AdversarialClass::Noisy), + 55, + "noisy visible outputs", + ); + } + + // Ambiguous / insufficient evidence (class F) and no structure. + for n in [2u8, 3] { + let mut prm = p(16, 2); + prm.visible = n; + b.add( + format!("insufficient-evidence-n{n}"), + M::InsufficientEvidence, + prm, + Rung::CounterexampleSearch, + S::Ambiguous, + adv, + rh(AdversarialClass::InsufficientEvidence), + 50, + "too few observations", + ); + } + b.add( + "no-structure".into(), + M::NoStructure, + p(8, 1), + Rung::TheoryFormation, + S::Ambiguous, + syn, + DecoyStatus::NoStructure, + 50, + "random table", + ); + + // The breadcrumb trail: capability primitives and their compositions. + for c in 0..CAPABILITY_POOL_SIZE as u16 { + let mut prm = p(16, 2); + prm.caps = vec![c]; + b.add( + format!("capability-{c:02}"), + M::CapabilityPrimitive, + prm, + Rung::TwoTransformations, + S::Capability, + syn, + clean, + 20, + "hidden capability", + ); + } + for (a, c) in COMPOSITION_PAIRS { + let mut prm = p(16, 4); + prm.caps = vec![a, c]; + b.add( + format!("compose-{a:02}-{c:02}"), + M::CapabilityComposition, + prm, + Rung::Composition, + S::Composition, + syn, + clean, + 60, + "composition of two capabilities", + ); + } + for (a, c, d) in COMPOSITION_TRIPLES { + let mut prm = p(16, 6); + prm.caps = vec![a, c, d]; + b.add( + format!("compose-{a:02}-{c:02}-{d:02}"), + M::CapabilityComposition, + prm, + Rung::Composition, + S::Composition, + syn, + clean, + 80, + "composition of three capabilities", + ); + } + + Registry { families: b.fams } +} diff --git a/crates/crumbs/src/gen/rng.rs b/crates/crumbs/src/gen/rng.rs new file mode 100644 index 00000000..1fae0dff --- /dev/null +++ b/crates/crumbs/src/gen/rng.rs @@ -0,0 +1,84 @@ +//! Deterministic, named random streams (xoshiro256** seeded from BLAKE3). +//! A stream is fully determined by its name and integer parts, so every +//! generator draw can be replayed exactly years later. + +use crate::digest::{digest, Domain}; + +#[derive(Clone, Debug)] +pub struct Rng { + s: [u64; 4], +} + +impl Rng { + pub fn named(name: &str, parts: &[u64]) -> Rng { + let mut bytes = Vec::with_capacity(name.len() + 1 + parts.len() * 8); + bytes.extend_from_slice(name.as_bytes()); + bytes.push(0); + for p in parts { + bytes.extend_from_slice(&p.to_le_bytes()); + } + let d = digest(Domain::Rng, &bytes).0; + let mut s = [0u64; 4]; + for (i, w) in s.iter_mut().enumerate() { + *w = u64::from_le_bytes(d[i * 8..i * 8 + 8].try_into().unwrap()); + } + if s == [0; 4] { + s[0] = 1; + } + Rng { s } + } + + pub fn next_u64(&mut self) -> u64 { + let s = &mut self.s; + let result = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9); + let t = s[1] << 17; + s[2] ^= s[0]; + s[3] ^= s[1]; + s[1] ^= s[2]; + s[0] ^= s[3]; + s[2] ^= t; + s[3] = s[3].rotate_left(45); + result + } + + /// Uniform in [0, n); n == 0 means the full u64 range. + pub fn below(&mut self, n: u64) -> u64 { + if n == 0 { + return self.next_u64(); + } + let limit = u64::MAX - (u64::MAX % n); + loop { + let v = self.next_u64(); + if v < limit { + return v % n; + } + } + } + + /// Uniform in [lo, hi] inclusive. + pub fn range(&mut self, lo: u64, hi: u64) -> u64 { + if hi <= lo { + return lo; + } + let span = hi - lo; + if span == u64::MAX { + return self.next_u64(); + } + lo + self.below(span + 1) + } + + pub fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T { + &items[self.below(items.len() as u64) as usize] + } + + pub fn chance(&mut self, num: u64, den: u64) -> bool { + self.below(den) < num + } + + pub fn shuffle<T>(&mut self, v: &mut [T]) { + for i in (1..v.len()).rev() { + let j = self.below(i as u64 + 1) as usize; + v.swap(i, j); + } + } +} diff --git a/crates/crumbs/src/ledger.rs b/crates/crumbs/src/ledger.rs new file mode 100644 index 00000000..45efdf6a --- /dev/null +++ b/crates/crumbs/src/ledger.rs @@ -0,0 +1,139 @@ +//! The Crumbline ledger: a mechanically checkable provenance chain. +//! +//! Every record binds the generator instance digest, the sealed record digest, +//! the verifier digest, the learner-visible digest, the learner build digest, +//! the evaluation receipts, the trace stream digest and the previous root. The +//! claim "every training record is firsthand" is then a property anyone can +//! re-verify from the ledger file, not a statement of doctrine. +//! +//! Lanes are separate chains. The clean-room lane refuses any record whose +//! provenance violates the clean-room policy. + +use crate::canon::Enc; +use crate::digest::{digest, CrumbOccurrenceId, Digest, Domain}; +use crate::provenance::{clean_room_check, CleanRoomViolation, Lane, Provenance}; +use crate::sealed::Population; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CrumblineRecord { + pub seq: u64, + pub lane: Lane, + pub occurrence: CrumbOccurrenceId, + pub condition: String, + pub population: Population, + pub crumb_digest: Digest, + pub generator_instance_digest: Digest, + pub sealed_digest: Digest, + pub verifier_digest: Digest, + pub learner_digest: Digest, + pub evaluations: Vec<Digest>, + pub trace_stream_digest: Digest, + pub promotions: Vec<Digest>, + pub prev_root: Digest, + pub root: Digest, +} + +impl CrumblineRecord { + fn body(&self) -> Vec<u8> { + let mut e = Enc::new(); + e.bytes(b"CLR1") + .u64(self.seq) + .u8(self.lane as u8) + .bytes(self.occurrence.0.as_bytes()); + e.str(&self.condition).u8(self.population as u8); + for d in [ + &self.crumb_digest, + &self.generator_instance_digest, + &self.sealed_digest, + &self.verifier_digest, + &self.learner_digest, + ] { + e.digest(d); + } + e.u32(self.evaluations.len() as u32); + for d in &self.evaluations { + e.digest(d); + } + e.digest(&self.trace_stream_digest); + e.u32(self.promotions.len() as u32); + for d in &self.promotions { + e.digest(d); + } + e.digest(&self.prev_root); + e.finish() + } + + pub fn compute_root(&self) -> Digest { + digest(Domain::LedgerRecord, &self.body()) + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum LedgerError { + CleanRoom(CleanRoomViolation), + Chain, +} + +pub struct Ledger { + pub lane: Lane, + pub genesis: Digest, + pub head: Digest, + pub records: Vec<CrumblineRecord>, +} + +pub fn genesis(lane: Lane, run_id: &str) -> Digest { + let mut e = Enc::new(); + e.u8(lane as u8).str(run_id); + digest(Domain::LedgerGenesis, &e.finish()) +} + +impl Ledger { + pub fn new(lane: Lane, run_id: &str) -> Self { + let g = genesis(lane, run_id); + Ledger { + lane, + genesis: g, + head: g, + records: vec![], + } + } + + /// Append a record. The clean-room lane checks provenance first. + pub fn append( + &mut self, + mut rec: CrumblineRecord, + provenance: &Provenance, + ) -> Result<Digest, LedgerError> { + if self.lane == Lane::CleanRoom { + clean_room_check(provenance).map_err(LedgerError::CleanRoom)?; + } + rec.lane = self.lane; + rec.prev_root = self.head; + rec.root = rec.compute_root(); + self.head = rec.root; + self.records.push(rec); + Ok(self.head) + } + + /// Re-verify the whole chain from genesis. + pub fn verify(genesis: Digest, records: &[CrumblineRecord]) -> Result<Digest, LedgerError> { + let mut head = genesis; + for r in records { + if r.prev_root != head || r.compute_root() != r.root { + return Err(LedgerError::Chain); + } + head = r.root; + } + Ok(head) + } + + pub fn to_jsonl(&self) -> String { + let mut s = String::new(); + for r in &self.records { + s.push_str(&serde_json::to_string(r).expect("serializable")); + s.push('\n'); + } + s + } +} diff --git a/crates/crumbs/src/lib.rs b/crates/crumbs/src/lib.rs new file mode 100644 index 00000000..a132e6fb --- /dev/null +++ b/crates/crumbs/src/lib.rs @@ -0,0 +1,28 @@ +//! Crumbline: the Crumb v1 curriculum substrate for AIEN. +//! +//! AIEN receives observations only. Everything that explains a crumb (its +//! family, provenance, difficulty, population, decoy status, truth status and +//! held-out answers) stays on the sealed side of a process boundary. +//! +//! This crate knows nothing about any particular learner. A learner speaks the +//! protocol in `protocol`, submits candidates in the CPG1 format of `program`, +//! and receives one verdict byte per submission. + +pub mod audit; +pub mod canon; +pub mod conformance; +pub mod digest; +pub mod experiment; +pub mod gates; +pub mod gen; +pub mod ledger; +pub mod mixer; +pub mod program; +pub mod promotion; +pub mod protocol; +pub mod provenance; +pub mod sealed; +pub mod session; +pub mod trace; +pub mod verify; +pub mod visible; diff --git a/crates/crumbs/src/mixer.rs b/crates/crumbs/src/mixer.rs new file mode 100644 index 00000000..f6910ef8 --- /dev/null +++ b/crates/crumbs/src/mixer.rs @@ -0,0 +1,335 @@ +//! The population mixer (sealed side). +//! +//! Crumbs are drawn from five secret populations with configurable weights +//! (initial v1 schedule 55/20/10/10/5, loaded from data, not hard-coded +//! behaviour). The mix adapts to evidence: as capabilities are demonstrated, +//! weight moves from acquisition to composition. Within a population the +//! mixer balances new capabilities, retention retests, previously failed +//! capabilities and random draws. Consecutive draws never repeat a family or +//! a capability, so curriculum order carries no ontology. +//! +//! The learner never sees a population, a family, or the draw reason. + +use crate::gen::rng::Rng; +use crate::gen::{registry, FamilySpec}; +use crate::provenance::clean_room_check; +use crate::sealed::{CapabilityId, Population, SourceFamily}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MixerConfig { + /// Percent weights per population. Need not sum to 100. + pub populations: BTreeMap<Population, u32>, + /// Within the fundamental population: weights for new / retention / uncertain / random. + pub select_new: u32, + pub select_retention: u32, + pub select_uncertain: u32, + pub select_random: u32, + /// Fraction (percent) of acquisition weight moved to composition when every capability is demonstrated. + pub adapt_pct: u32, + /// Only families that pass the clean-room policy. + pub clean_room: bool, + /// Restrict capability-bearing families to these capability pool indices (None = all). + pub capability_subset: Option<Vec<u16>>, + /// Restrict composition families to these family keys (None = all ready ones). + pub composition_keys: Option<Vec<String>>, +} + +impl Default for MixerConfig { + fn default() -> Self { + let mut populations = BTreeMap::new(); + populations.insert(Population::Fundamental, 55); + populations.insert(Population::Composition, 20); + populations.insert(Population::Ambiguous, 10); + populations.insert(Population::RabbitHole, 10); + populations.insert(Population::Frontier, 5); + MixerConfig { + populations, + select_new: 40, + select_retention: 20, + select_uncertain: 20, + select_random: 20, + adapt_pct: 50, + clean_room: false, + capability_subset: None, + composition_keys: None, + } + } +} + +impl MixerConfig { + pub fn from_json(s: &str) -> Result<Self, serde_json::Error> { + serde_json::from_str(s) + } +} + +/// Evidence about one capability, updated from sealed evaluations. +#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)] +pub struct CapabilityState { + pub attempts: u32, + pub verified: u32, + pub last_verified: bool, +} + +impl CapabilityState { + pub fn demonstrated(&self) -> bool { + self.verified > 0 && self.last_verified + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum DrawReason { + NewCapability, + Retention, + Uncertain, + Random, + Composition, + Fallback, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Draw { + pub seq: u64, + pub family_id: u32, + pub seed: u64, + pub population: Population, + pub reason: DrawReason, +} + +pub struct Mixer { + pub cfg: MixerConfig, + rng: Rng, + run_seed: u64, + seq: u64, + pub caps: HashMap<CapabilityId, CapabilityState>, + last_family: Option<u32>, + last_caps: Vec<CapabilityId>, + /// Draws whose population had nothing eligible (empty, or only back-to-back repeats) and were redistributed. + pub redistributed_draws: BTreeMap<Population, u32>, +} + +fn population_of(f: &FamilySpec) -> Option<Population> { + Some(match f.source_family { + SourceFamily::Capability => Population::Fundamental, + SourceFamily::Composition => Population::Composition, + SourceFamily::Ambiguous => Population::Ambiguous, + SourceFamily::RabbitHole => Population::RabbitHole, + SourceFamily::Frontier => Population::Frontier, + SourceFamily::CleanRoomPhysics => return None, + }) +} + +impl Mixer { + pub fn new(cfg: MixerConfig, run_seed: u64) -> Self { + Mixer { + cfg, + rng: Rng::named("mixer", &[run_seed]), + run_seed, + seq: 0, + caps: HashMap::new(), + last_family: None, + last_caps: vec![], + redistributed_draws: BTreeMap::new(), + } + } + + fn family_caps(f: &FamilySpec) -> Vec<CapabilityId> { + let pool = crate::gen::capability_pool(); + f.params.caps.iter().map(|&c| pool[c as usize].id).collect() + } + + fn eligible(&self, f: &FamilySpec) -> bool { + if self.cfg.clean_room && clean_room_check(&f.provenance).is_err() { + return false; + } + if let Some(sub) = &self.cfg.capability_subset { + if !f.params.caps.is_empty() && !f.params.caps.iter().all(|c| sub.contains(c)) { + return false; + } + } + if f.source_family == SourceFamily::Composition { + if let Some(keys) = &self.cfg.composition_keys { + if !keys.contains(&f.key) { + return false; + } + } + } + true + } + + fn adjacent(&self, f: &FamilySpec) -> bool { + if self.last_family == Some(f.id) { + return true; + } + let caps = Self::family_caps(f); + caps.iter().any(|c| self.last_caps.contains(c)) + } + + /// Current population weights after evidence-driven adaptation. + pub fn weights(&self) -> BTreeMap<Population, u32> { + let mut w = self.cfg.populations.clone(); + let pool = crate::gen::capability_pool(); + let tracked: Vec<_> = pool + .iter() + .filter(|c| { + self.cfg + .capability_subset + .as_ref() + .is_none_or(|s| s.contains(&c.index)) + }) + .collect(); + if !tracked.is_empty() { + let demo = tracked + .iter() + .filter(|c| self.caps.get(&c.id).is_some_and(|s| s.demonstrated())) + .count(); + let fund = *w.get(&Population::Fundamental).unwrap_or(&0); + let moved = fund as u64 * self.cfg.adapt_pct as u64 * demo as u64 + / (100 * tracked.len() as u64); + *w.entry(Population::Fundamental).or_insert(0) -= moved as u32; + *w.entry(Population::Composition).or_insert(0) += moved as u32; + } + w + } + + fn pick_weighted<T: Copy>(&mut self, items: &[(T, u32)]) -> Option<T> { + let total: u64 = items.iter().map(|x| x.1 as u64).sum(); + if total == 0 { + return None; + } + let mut r = self.rng.below(total); + for &(t, w) in items { + if r < w as u64 { + return Some(t); + } + r -= w as u64; + } + None + } + + fn candidates(&self, pop: Population) -> Vec<&'static FamilySpec> { + registry() + .families + .iter() + .filter(|f| population_of(f) == Some(pop) && self.eligible(f)) + .collect() + } + + fn cap_state(&self, id: &CapabilityId) -> CapabilityState { + self.caps.get(id).copied().unwrap_or_default() + } + + /// Choose a family within a population, or None if the population is empty. + fn choose_in(&mut self, pop: Population) -> Option<(&'static FamilySpec, DrawReason)> { + let all = self.candidates(pop); + if all.is_empty() { + return None; + } + let pools: Vec<(DrawReason, Vec<&'static FamilySpec>)> = match pop { + Population::Fundamental => { + let with_cap = + |pred: &dyn Fn(CapabilityState) -> bool| -> Vec<&'static FamilySpec> { + all.iter() + .copied() + .filter(|f| { + f.params.caps.len() == 1 + && pred(self.cap_state(&Self::family_caps(f)[0])) + }) + .collect() + }; + vec![ + (DrawReason::NewCapability, with_cap(&|s| s.attempts == 0)), + (DrawReason::Retention, with_cap(&|s| s.demonstrated())), + ( + DrawReason::Uncertain, + with_cap(&|s| s.attempts > 0 && !s.demonstrated()), + ), + (DrawReason::Random, all.clone()), + ] + } + Population::Composition => { + let ready: Vec<_> = all + .iter() + .copied() + .filter(|f| { + Self::family_caps(f) + .iter() + .all(|c| self.cap_state(c).demonstrated()) + }) + .collect(); + vec![(DrawReason::Composition, ready)] + } + _ => vec![(DrawReason::Random, all.clone())], + }; + // Never repeat a family or a capability back to back. + let pools: Vec<(DrawReason, Vec<&'static FamilySpec>)> = pools + .into_iter() + .map(|(r, v)| (r, v.into_iter().filter(|f| !self.adjacent(f)).collect())) + .collect(); + let weights = [ + self.cfg.select_new, + self.cfg.select_retention, + self.cfg.select_uncertain, + self.cfg.select_random, + ]; + let options: Vec<(usize, u32)> = pools + .iter() + .enumerate() + .filter(|(_, (_, v))| !v.is_empty()) + .map(|(i, _)| (i, if pools.len() == 4 { weights[i] } else { 1 })) + .collect(); + let i = self.pick_weighted(&options)?; + let (reason, fams) = &pools[i]; + let f = fams[self.rng.below(fams.len() as u64) as usize]; + Some((f, *reason)) + } + + pub fn draw(&mut self) -> Draw { + let seq = self.seq; + self.seq += 1; + let weights: Vec<(Population, u32)> = self.weights().into_iter().collect(); + let mut pop = self + .pick_weighted(&weights) + .unwrap_or(Population::Fundamental); + let mut chosen = self.choose_in(pop); + if chosen.is_none() { + // Empty population (e.g. no v1 frontier sources, or nothing ready to + // compose): record it and redistribute over the populations that can draw. + *self.redistributed_draws.entry(pop).or_insert(0) += 1; + let rest: Vec<(Population, u32)> = + weights.iter().copied().filter(|(p, _)| *p != pop).collect(); + for _ in 0..8 { + pop = self.pick_weighted(&rest).unwrap_or(Population::Fundamental); + chosen = self.choose_in(pop); + if chosen.is_some() { + break; + } + } + } + let (f, reason) = chosen.unwrap_or_else(|| (®istry().families[0], DrawReason::Fallback)); + self.last_family = Some(f.id); + self.last_caps = Self::family_caps(f); + let seed = Rng::named("draw-seed", &[self.run_seed, seq]).next_u64(); + Draw { + seq, + family_id: f.id, + seed, + population: pop, + reason, + } + } + + /// Feed back a sealed verdict for a drawn family. + pub fn record(&mut self, family: &FamilySpec, verified: bool) { + if family.params.caps.len() == 1 { + let id = Self::family_caps(family)[0]; + let s = self.caps.entry(id).or_default(); + s.attempts += 1; + if verified { + s.verified += 1; + } + s.last_verified = verified; + } + } +} diff --git a/crates/crumbs/src/program.rs b/crates/crumbs/src/program.rs new file mode 100644 index 00000000..99b15244 --- /dev/null +++ b/crates/crumbs/src/program.rs @@ -0,0 +1,225 @@ +//! Candidate Program v1 ("CPG1"): the learner-neutral program format of the +//! generic verifier contract. +//! +//! A learner submits candidates in this format; the sealed verifier executes +//! them with its own interpreter (it never trusts the learner's execution and +//! never needs to know the learner's internals). v1 programs are unary: they +//! map lane 0 of the input to lane 0 of the output as a chain of wrapping u64 +//! operations. +//! +//! ```text +//! "CPG1" | version u16 (=1) | n u8 (<= 64) | n x (op u8, imm u64) +//! ``` + +use crate::canon::{Dec, DecodeError, Enc}; +use crate::digest::{digest, Digest, Domain}; + +pub const MAGIC: &[u8; 4] = b"CPG1"; +pub const VERSION: u16 = 1; +pub const MAX_STEPS: usize = 64; + +#[derive( + Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize, +)] +#[repr(u8)] +pub enum Op { + Add = 1, + Sub = 2, + Mul = 3, + And = 4, + Or = 5, + Xor = 6, + Shl = 7, + Shr = 8, + Rotl = 9, +} + +impl Op { + pub fn from_u8(v: u8) -> Option<Op> { + Some(match v { + 1 => Op::Add, + 2 => Op::Sub, + 3 => Op::Mul, + 4 => Op::And, + 5 => Op::Or, + 6 => Op::Xor, + 7 => Op::Shl, + 8 => Op::Shr, + 9 => Op::Rotl, + _ => return None, + }) + } + + #[inline] + pub fn apply(self, x: u64, imm: u64) -> u64 { + match self { + Op::Add => x.wrapping_add(imm), + Op::Sub => x.wrapping_sub(imm), + Op::Mul => x.wrapping_mul(imm), + Op::And => x & imm, + Op::Or => x | imm, + Op::Xor => x ^ imm, + Op::Shl => x.wrapping_shl((imm & 63) as u32), + Op::Shr => x.wrapping_shr((imm & 63) as u32), + Op::Rotl => x.rotate_left((imm & 63) as u32), + } + } +} + +#[derive( + Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize, +)] +pub struct Step { + pub op: Op, + pub imm: u64, +} + +#[derive( + Clone, + Debug, + PartialEq, + Eq, + Hash, + Default, + PartialOrd, + Ord, + serde::Serialize, + serde::Deserialize, +)] +pub struct Program { + pub steps: Vec<Step>, +} + +impl Program { + pub fn new(steps: Vec<Step>) -> Self { + Program { steps } + } + + pub fn of(steps: &[(Op, u64)]) -> Self { + Program { + steps: steps.iter().map(|&(op, imm)| Step { op, imm }).collect(), + } + } + + #[inline] + pub fn run(&self, mut x: u64) -> u64 { + for s in &self.steps { + x = s.op.apply(x, s.imm); + } + x + } + + pub fn then(&self, next: &Program) -> Program { + let mut steps = self.steps.clone(); + steps.extend_from_slice(&next.steps); + Program { steps } + } + + pub fn len(&self) -> usize { + self.steps.len() + } + + pub fn is_empty(&self) -> bool { + self.steps.is_empty() + } + + pub fn to_bytes(&self) -> Vec<u8> { + let mut e = Enc::new(); + e.bytes(MAGIC).u16(VERSION).u8(self.steps.len() as u8); + for s in &self.steps { + e.u8(s.op as u8).u64(s.imm); + } + e.finish() + } + + pub fn decode(d: &mut Dec<'_>) -> Result<Program, DecodeError> { + if d.take(4)? != MAGIC || d.u16()? != VERSION { + return Err(DecodeError); + } + let n = d.u8()? as usize; + if n > MAX_STEPS { + return Err(DecodeError); + } + let mut steps = Vec::with_capacity(n); + for _ in 0..n { + let op = Op::from_u8(d.u8()?).ok_or(DecodeError)?; + steps.push(Step { op, imm: d.u64()? }); + } + Ok(Program { steps }) + } + + pub fn from_bytes(bytes: &[u8]) -> Result<Program, DecodeError> { + let mut d = Dec::new(bytes); + let p = Program::decode(&mut d)?; + d.finish()?; + Ok(p) + } + + /// Candidate program digest (operation semantic id). + pub fn digest(&self) -> Digest { + digest(Domain::Program, &self.to_bytes()) + } + + /// Behaviour signature over the public probe inputs. + pub fn behavior(&self) -> Digest { + let mut e = Enc::new(); + for &x in PROBES.iter() { + e.u64(self.run(x)); + } + digest(Domain::Behavior, &e.finish()) + } + + /// Every contiguous sub-chain of length in [min_len, max_len]. + pub fn sub_chains(&self, min_len: usize, max_len: usize) -> Vec<Program> { + let mut out = Vec::new(); + for len in min_len..=max_len.min(self.steps.len()) { + for start in 0..=self.steps.len() - len { + out.push(Program { + steps: self.steps[start..start + len].to_vec(), + }); + } + } + out + } +} + +/// Identity of this interpreter's semantics (part of the verifier digest). +pub fn std_interpreter_id() -> &'static str { + "cpg1-interp/1: u64 wrapping add sub mul; and or xor; shl shr rotl by imm&63" +} + +/// Public probe inputs used for behaviour signatures (not secret). +pub const PROBES: [u64; 32] = [ + 0, + 1, + 2, + 3, + 5, + 7, + 13, + 42, + 100, + 127, + 128, + 255, + 256, + 1000, + 4095, + 65535, + 65536, + 1_000_003, + 0x7FFF_FFFF, + 0x8000_0000, + 0xFFFF_FFFF, + 0x1_0000_0000, + 0x0123_4567_89AB_CDEF, + 0x0F0F_0F0F_0F0F_0F0F, + 0x5555_5555_5555_5555, + 0xAAAA_AAAA_AAAA_AAAA, + 0x7FFF_FFFF_FFFF_FFFF, + 0x8000_0000_0000_0000, + 0xFFFF_FFFF_FFFF_FFFE, + u64::MAX, + 0x9E37_79B9_7F4A_7C15, + 0xD1B5_4A32_D192_ED03, +]; diff --git a/crates/crumbs/src/promotion.rs b/crates/crumbs/src/promotion.rs new file mode 100644 index 00000000..80072d68 --- /dev/null +++ b/crates/crumbs/src/promotion.rs @@ -0,0 +1,281 @@ +//! The promotion ladder (sealed side). +//! +//! One solved crumb never makes an operation universal. An operation climbs: +//! +//! ```text +//! candidate operation sub-chain of an accepted solution +//! -> held-out verified part of a solution the sealed verifier accepted +//! -> corroborated supports >= min_support distinct crumbs +//! -> survived adversarial every support passed a non-empty adversarial tier, +//! and rejected-submission exposures stay bounded +//! -> generalized every support passed a non-empty extrapolation tier +//! -> admitted sent to the learner's library with an explicit scope +//! ``` +//! +//! Scope is recorded, not assumed: `scope_bits` is the widest input magnitude +//! (in bits) over which a supporting solution was verified. A learner may only +//! apply an admitted operation to crumbs inside that scope. + +use crate::canon::Enc; +use crate::digest::{digest, Digest, Domain}; +use crate::program::Program; +use crate::sealed::{HeldoutTier, SealedCrumb}; +use crate::verify::{EvalClass, SealedEvaluation}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Stage { + Candidate = 1, + HeldoutVerified = 3, + Corroborated = 4, + SurvivedAdversarial = 5, + Generalized = 6, + Admitted = 7, + Suspended = 9, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PromotionConfig { + pub min_len: usize, + pub max_len: usize, + pub min_support: usize, + /// Suspend when exposures in rejected submissions exceed this percent of supports. + pub max_exposure_pct: u32, +} + +impl Default for PromotionConfig { + fn default() -> Self { + PromotionConfig { + min_len: 2, + max_len: 6, + min_support: 2, + max_exposure_pct: 200, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Support { + pub seq: u64, + pub crumb: Digest, + pub family_id: u32, + pub evaluation: Digest, + pub adversarial_total: u32, + pub extrapolation_total: u32, + pub max_input_bits: u8, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct OpRecord { + pub behavior: Digest, + pub program: Program, + pub stage: Stage, + pub supports: Vec<Support>, + pub exposures: Vec<Digest>, + pub scope_bits: u8, + pub first_seen_seq: u64, + pub op_ref: Option<u32>, + pub history: Vec<(Stage, u64)>, +} + +impl OpRecord { + pub fn distinct_crumbs(&self) -> usize { + let mut v: Vec<_> = self.supports.iter().map(|s| s.crumb).collect(); + v.sort(); + v.dedup(); + v.len() + } + + /// Commitment to the operation, its evidence and its scope. + pub fn promotion_digest(&self) -> Digest { + let mut e = Enc::new(); + e.blob(&self.program.to_bytes()) + .u8(self.stage as u8) + .u8(self.scope_bits); + e.u32(self.supports.len() as u32); + for s in &self.supports { + e.digest(&s.crumb).digest(&s.evaluation); + } + e.u32(self.exposures.len() as u32); + for x in &self.exposures { + e.digest(x); + } + digest(Domain::Promotion, &e.finish()) + } +} + +/// A newly admitted operation, to be sent to a learner that may reuse it. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Admission { + pub op_ref: u32, + pub program: Program, + pub scope_bits: u8, + pub promotion_digest: Digest, +} + +#[derive(Default, Serialize, Deserialize)] +pub struct Ladder { + pub cfg: PromotionConfig, + pub ops: BTreeMap<Digest, OpRecord>, + next_ref: u32, +} + +fn bits(x: u64) -> u8 { + (64 - x.leading_zeros()) as u8 +} + +impl Ladder { + pub fn new(cfg: PromotionConfig) -> Self { + Ladder { + cfg, + ops: BTreeMap::new(), + next_ref: 1, + } + } + + fn candidates_of(&self, program: &Program) -> Vec<Program> { + let mut out = program.sub_chains(self.cfg.min_len, self.cfg.max_len); + out.sort(); + out.dedup(); + out + } + + /// An accepted solution: every sub-chain is (evidence for) a candidate operation. + pub fn observe_accept( + &mut self, + seq: u64, + sealed: &SealedCrumb, + eval: &SealedEvaluation, + program: &Program, + ) { + if !matches!(eval.class, EvalClass::Verified) { + return; // ambiguous acceptances are not evidence for reuse + } + let max_in = HeldoutTier::ALL + .iter() + .flat_map(|t| sealed.heldouts.tier(*t)) + .map(|ex| ex.input[0]) + .max() + .unwrap_or(0); + for cand in self.candidates_of(program) { + let b = cand.behavior(); + let rec = self.ops.entry(b).or_insert_with(|| OpRecord { + behavior: b, + program: cand.clone(), + stage: Stage::Candidate, + supports: vec![], + exposures: vec![], + scope_bits: 0, + first_seen_seq: seq, + op_ref: None, + history: vec![(Stage::Candidate, seq)], + }); + if cand.len() < rec.program.len() { + rec.program = cand.clone(); + } + if rec.supports.iter().any(|s| s.crumb == eval.crumb_digest) { + continue; + } + rec.supports.push(Support { + seq, + crumb: eval.crumb_digest, + family_id: sealed.family_id, + evaluation: eval.digest(), + adversarial_total: eval.adversarial.total, + extrapolation_total: eval.extrapolation.total, + max_input_bits: bits(max_in), + }); + } + } + + /// A submission that fit the visible examples but failed held-outs. + pub fn observe_reject(&mut self, eval: &SealedEvaluation, program: &Program) { + if !matches!(eval.class, EvalClass::FalsifiedHidden) { + return; + } + for cand in self.candidates_of(program) { + if let Some(rec) = self.ops.get_mut(&cand.behavior()) { + rec.exposures.push(eval.digest()); + } + } + } + + /// Climb every operation as far as its evidence allows. Returns operations + /// that reached `Admitted` in this call. + pub fn advance(&mut self, seq: u64) -> Vec<Admission> { + let mut admitted = Vec::new(); + let cfg = self.cfg.clone(); + for rec in self.ops.values_mut() { + if rec.stage == Stage::Admitted || rec.stage == Stage::Suspended { + continue; + } + let supports = rec.distinct_crumbs(); + if supports > 0 && rec.exposures.len() * 100 > supports * cfg.max_exposure_pct as usize + { + rec.stage = Stage::Suspended; + rec.history.push((Stage::Suspended, seq)); + continue; + } + let mut next = Stage::Candidate; + if supports >= 1 { + next = Stage::HeldoutVerified; + } + if next == Stage::HeldoutVerified && supports >= cfg.min_support { + next = Stage::Corroborated; + } + if next == Stage::Corroborated && rec.supports.iter().all(|s| s.adversarial_total > 0) { + next = Stage::SurvivedAdversarial; + } + if next == Stage::SurvivedAdversarial + && rec.supports.iter().all(|s| s.extrapolation_total > 0) + { + next = Stage::Generalized; + } + if next == Stage::Generalized { + next = Stage::Admitted; + } + // Record every rung crossed, in order. + for st in [ + Stage::HeldoutVerified, + Stage::Corroborated, + Stage::SurvivedAdversarial, + Stage::Generalized, + Stage::Admitted, + ] { + if st > rec.stage && st <= next { + rec.history.push((st, seq)); + } + } + if next > rec.stage { + rec.stage = next; + } + rec.scope_bits = rec + .supports + .iter() + .map(|s| s.max_input_bits) + .max() + .unwrap_or(0); + if rec.stage == Stage::Admitted && rec.op_ref.is_none() { + let r = self.next_ref; + self.next_ref += 1; + rec.op_ref = Some(r); + admitted.push(Admission { + op_ref: r, + program: rec.program.clone(), + scope_bits: rec.scope_bits, + promotion_digest: rec.promotion_digest(), + }); + } + } + admitted + } + + pub fn by_ref(&self, op_ref: u32) -> Option<&OpRecord> { + self.ops.values().find(|r| r.op_ref == Some(op_ref)) + } + + pub fn count(&self, stage: Stage) -> usize { + self.ops.values().filter(|r| r.stage == stage).count() + } +} diff --git a/crates/crumbs/src/protocol.rs b/crates/crumbs/src/protocol.rs new file mode 100644 index 00000000..b91e7563 --- /dev/null +++ b/crates/crumbs/src/protocol.rs @@ -0,0 +1,396 @@ +//! The learner protocol (v1): the only channel between the sealed side and a learner. +//! +//! The learner runs as a separate operating-system process. It never shares an +//! address space with sealed data; everything it can know arrives through the +//! frames below, and every frame type is listed here. There is no frame that +//! can carry a sealed field, a held-out example, a label or an explanation. +//! +//! Frame: `type u8 | len u32 | payload`. +//! +//! Sealed side -> learner: +//! - `0x01 HELLO `: protocol u16, library_enabled u8, SearchConfig (6 x u32) +//! - `0x02 CRUMB `: canonical Crumb v1 visible bytes +//! - `0x03 VERDICT `: one byte (1 accept, 2 reject, 3 budget exhausted) +//! - `0x04 ADMIT `: op_ref u32, scope_bits u8, CPG1 program +//! - `0x05 SHUTDOWN`: empty +//! +//! Learner -> sealed side: +//! - `0x81 READY `: protocol u16 +//! - `0x82 BANK `: n u32, n x (origin u8, op_ref u32, CPG1 program) (per crumb) +//! - `0x83 SUBMIT `: node u32, flags u8, hypotheses u8, CPG1 program +//! - `0x84 EVENTS `: n u32, n x 20-byte search event +//! - `0x85 DONE `: outcome u8, solution_node u32, 12 x u32 counters, 2 x u64 counters +//! +//! Any other frame from the learner aborts the session; nothing is sent in reply. + +use crate::canon::{Dec, DecodeError, Enc}; +use crate::program::Program; +use crate::verify::Verdict; +use crate::visible::VisibleCrumb; +use serde::{Deserialize, Serialize}; +use std::io::{Read, Write}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; + +pub const PROTOCOL_VERSION: u16 = 1; +pub const MAX_FRAME: usize = 1 << 24; + +pub mod ft { + pub const HELLO: u8 = 0x01; + pub const CRUMB: u8 = 0x02; + pub const VERDICT: u8 = 0x03; + pub const ADMIT: u8 = 0x04; + pub const SHUTDOWN: u8 = 0x05; + pub const READY: u8 = 0x81; + pub const BANK: u8 = 0x82; + pub const SUBMIT: u8 = 0x83; + pub const EVENTS: u8 = 0x84; + pub const DONE: u8 = 0x85; +} + +/// Search limits handed to the learner. Identical in every experimental condition. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SearchConfig { + pub max_candidates: u32, + pub max_depth: u32, + pub frontier_cap: u32, + pub max_oracle_queries: u32, + pub ambiguity_scan: u32, + pub robust_min_pct: u32, +} + +impl Default for SearchConfig { + fn default() -> Self { + SearchConfig { + max_candidates: 20_000, + max_depth: 6, + frontier_cap: 4_000, + max_oracle_queries: 4, + ambiguity_scan: 400, + robust_min_pct: 75, + } + } +} + +/// Learner search-event kinds. +pub mod ek { + pub const EXPAND: u8 = 1; + pub const SUBMIT: u8 = 2; +} + +/// One observable search step, as reported by the learner. Numbers only. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LearnerEvent { + pub kind: u8, + pub prune: u8, + pub verify: u8, + pub fit: u8, + pub op_index: u16, + pub parent: u32, + pub child: u32, + pub exec_cost: u32, + pub oracle_index: u16, +} + +pub const EVENT_BYTES: usize = 20; + +impl LearnerEvent { + fn decode(d: &mut Dec<'_>) -> Result<Self, DecodeError> { + Ok(LearnerEvent { + kind: d.u8()?, + prune: d.u8()?, + verify: d.u8()?, + fit: d.u8()?, + op_index: d.u16()?, + parent: d.u32()?, + child: d.u32()?, + exec_cost: d.u32()?, + oracle_index: d.u16()?, + }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BankEntry { + /// 0 = learner base vocabulary, 1 = admitted library operation. + pub origin: u8, + /// The ADMIT op_ref this entry came from (0 for base operations). + pub op_ref: u32, + pub program: Program, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Submission { + pub node: u32, + pub flags: u8, + pub hypotheses: u8, + pub program: Program, + pub verdict: Verdict, +} + +pub const SUBMIT_ROBUST: u8 = 1; + +/// The learner's own end-of-crumb counters. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct LearnerStats { + pub outcome: u8, + pub solution_node: u32, + pub generated: u32, + pub evaluated: u32, + pub expansions: u32, + pub pruned_equiv: u32, + pub pruned_cost: u32, + pub pruned_cap: u32, + pub visible_fits: u32, + pub verify_failures: u32, + pub oracle_queries: u32, + pub oracle_rejections: u32, + pub candidates_to_solution: u32, + pub hypotheses_at_first_submit: u32, + pub exec_count: u64, + pub wall_ns: u64, +} + +pub const OUTCOME_SOLVED: u8 = 1; +pub const OUTCOME_UNSOLVED: u8 = 2; +pub const OUTCOME_UNSUPPORTED: u8 = 3; + +/// Everything the learner produced for one crumb. +#[derive(Clone, Debug, Default)] +pub struct CrumbSession { + pub bank: Vec<BankEntry>, + pub events: Vec<LearnerEvent>, + pub submissions: Vec<Submission>, + pub stats: LearnerStats, +} + +#[derive(Debug)] +pub enum ProtocolError { + Io, + Malformed, + Violation, + Version, +} + +impl std::fmt::Display for ProtocolError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "learner protocol error: {self:?}") + } +} + +impl std::error::Error for ProtocolError {} + +impl From<std::io::Error> for ProtocolError { + fn from(_: std::io::Error) -> Self { + ProtocolError::Io + } +} + +impl From<DecodeError> for ProtocolError { + fn from(_: DecodeError) -> Self { + ProtocolError::Malformed + } +} + +pub fn write_frame(w: &mut dyn Write, t: u8, payload: &[u8]) -> std::io::Result<()> { + let mut hdr = [0u8; 5]; + hdr[0] = t; + hdr[1..].copy_from_slice(&(payload.len() as u32).to_le_bytes()); + w.write_all(&hdr)?; + w.write_all(payload)?; + w.flush() +} + +pub fn read_frame(r: &mut dyn Read) -> Result<(u8, Vec<u8>), ProtocolError> { + let mut hdr = [0u8; 5]; + r.read_exact(&mut hdr)?; + let len = u32::from_le_bytes(hdr[1..].try_into().unwrap()) as usize; + if len > MAX_FRAME { + return Err(ProtocolError::Malformed); + } + let mut buf = vec![0u8; len]; + r.read_exact(&mut buf)?; + Ok((hdr[0], buf)) +} + +/// A learner running as a child process. +pub struct LearnerProcess { + child: Child, + stdin: ChildStdin, + stdout: ChildStdout, + /// Every byte sent to the learner, kept for leak audits when enabled. + pub transcript: Option<Vec<u8>>, +} + +impl LearnerProcess { + pub fn spawn( + path: &str, + args: &[&str], + record_transcript: bool, + ) -> Result<Self, ProtocolError> { + let mut child = Command::new(path) + .args(args) + .env_clear() + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn()?; + let stdin = child.stdin.take().ok_or(ProtocolError::Io)?; + let stdout = child.stdout.take().ok_or(ProtocolError::Io)?; + Ok(LearnerProcess { + child, + stdin, + stdout, + transcript: record_transcript.then(Vec::new), + }) + } + + pub fn pid(&self) -> u32 { + self.child.id() + } + + fn send(&mut self, t: u8, payload: &[u8]) -> Result<(), ProtocolError> { + if let Some(tr) = self.transcript.as_mut() { + tr.push(t); + tr.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + tr.extend_from_slice(payload); + } + write_frame(&mut self.stdin, t, payload)?; + Ok(()) + } + + pub fn hello( + &mut self, + cfg: &SearchConfig, + library_enabled: bool, + ) -> Result<(), ProtocolError> { + let mut e = Enc::new(); + e.u16(PROTOCOL_VERSION).u8(library_enabled as u8); + for v in [ + cfg.max_candidates, + cfg.max_depth, + cfg.frontier_cap, + cfg.max_oracle_queries, + cfg.ambiguity_scan, + cfg.robust_min_pct, + ] { + e.u32(v); + } + self.send(ft::HELLO, &e.finish())?; + let (t, p) = read_frame(&mut self.stdout)?; + if t != ft::READY { + return Err(ProtocolError::Violation); + } + let mut d = Dec::new(&p); + if d.u16()? != PROTOCOL_VERSION { + return Err(ProtocolError::Version); + } + Ok(()) + } + + /// Admit a verified library operation (sent only in conditions that allow reuse). + pub fn admit( + &mut self, + op_ref: u32, + scope_bits: u8, + program: &Program, + ) -> Result<(), ProtocolError> { + let mut e = Enc::new(); + e.u32(op_ref).u8(scope_bits).bytes(&program.to_bytes()); + self.send(ft::ADMIT, &e.finish()) + } + + /// Present one crumb. `oracle` is the sealed evaluator; it sees each + /// submission and returns the verdict byte the learner will receive. + pub fn run_crumb( + &mut self, + visible: &VisibleCrumb, + oracle: &mut dyn FnMut(&Submission) -> Verdict, + ) -> Result<CrumbSession, ProtocolError> { + self.send(ft::CRUMB, &visible.to_bytes())?; + let mut s = CrumbSession::default(); + loop { + let (t, p) = read_frame(&mut self.stdout)?; + let mut d = Dec::new(&p); + match t { + ft::BANK => { + let n = d.u32()? as usize; + for _ in 0..n.min(4096) { + let origin = d.u8()?; + let op_ref = d.u32()?; + let program = Program::decode(&mut d)?; + s.bank.push(BankEntry { + origin, + op_ref, + program, + }); + } + d.finish()?; + } + ft::EVENTS => { + let n = d.u32()? as usize; + if n * EVENT_BYTES + 4 != p.len() { + return Err(ProtocolError::Malformed); + } + for _ in 0..n { + s.events.push(LearnerEvent::decode(&mut d)?); + } + } + ft::SUBMIT => { + let node = d.u32()?; + let flags = d.u8()?; + let hypotheses = d.u8()?; + let program = Program::decode(&mut d)?; + d.finish()?; + let mut sub = Submission { + node, + flags, + hypotheses, + program, + verdict: Verdict::Reject, + }; + sub.verdict = oracle(&sub); + self.send(ft::VERDICT, &[sub.verdict as u8])?; + s.submissions.push(sub); + } + ft::DONE => { + let st = &mut s.stats; + st.outcome = d.u8()?; + st.solution_node = d.u32()?; + for f in [ + &mut st.generated, + &mut st.evaluated, + &mut st.expansions, + &mut st.pruned_equiv, + &mut st.pruned_cost, + &mut st.pruned_cap, + &mut st.visible_fits, + &mut st.verify_failures, + &mut st.oracle_queries, + &mut st.oracle_rejections, + &mut st.candidates_to_solution, + &mut st.hypotheses_at_first_submit, + ] { + *f = d.u32()?; + } + st.exec_count = d.u64()?; + st.wall_ns = d.u64()?; + d.finish()?; + return Ok(s); + } + _ => return Err(ProtocolError::Violation), + } + } + } + + pub fn shutdown(mut self) -> Result<std::process::ExitStatus, ProtocolError> { + let _ = self.send(ft::SHUTDOWN, &[]); + drop(self.stdin); + Ok(self.child.wait()?) + } + + /// Kill without ceremony (used after a protocol violation). + pub fn kill(mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} diff --git a/crates/crumbs/src/provenance.rs b/crates/crumbs/src/provenance.rs new file mode 100644 index 00000000..5b6cf8e6 --- /dev/null +++ b/crates/crumbs/src/provenance.rs @@ -0,0 +1,92 @@ +//! Provenance, contamination classes and the clean-room boundary (sealed side). +//! +//! The clean-room lane exists so that a later rediscovery can be checked: a +//! crumb enters it only if nothing about its construction came from human +//! theory, human constants or human physical ontology. The lane has its own +//! ledger partition, and the partition refuses forbidden records outright. + +use serde::{Deserialize, Serialize}; + +/// Where the structure behind a crumb came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ContaminationClass { + /// Invented by a generator with no reference to human theory. + SyntheticNovel = 1, + /// Invented to mislead (rabbit holes); still no human theory. + AdversarialSynthetic = 2, + /// Encodes a relationship known from human mathematics or science. + HumanTheoryDerived = 3, + /// Finite instances of structures around open problems. + FrontierDerived = 4, + /// Measurements of the real world. + RealWorldMeasured = 5, +} + +/// Everything the clean-room policy needs to judge a crumb. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Provenance { + pub class: ContaminationClass, + pub uses_human_constants: bool, + pub uses_human_ontology: bool, +} + +impl Provenance { + pub const fn synthetic() -> Self { + Provenance { + class: ContaminationClass::SyntheticNovel, + uses_human_constants: false, + uses_human_ontology: false, + } + } + pub const fn adversarial() -> Self { + Provenance { + class: ContaminationClass::AdversarialSynthetic, + uses_human_constants: false, + uses_human_ontology: false, + } + } + pub const fn human_theory() -> Self { + Provenance { + class: ContaminationClass::HumanTheoryDerived, + uses_human_constants: true, + uses_human_ontology: false, + } + } +} + +/// Ledger lanes. Each lane is a separate hash chain. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Lane { + Main = 1, + CleanRoom = 2, +} + +/// Why the clean-room lane refused a crumb. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum CleanRoomViolation { + HumanTheoryDerived, + FrontierDerived, + RealWorldMeasured, + HumanConstants, + HumanOntology, +} + +/// The clean-room forbidden list. Permitted: synthetic and adversarial +/// synthetic structure with no human constants and no human ontology. +pub fn clean_room_check(p: &Provenance) -> Result<(), CleanRoomViolation> { + match p.class { + ContaminationClass::HumanTheoryDerived => { + return Err(CleanRoomViolation::HumanTheoryDerived) + } + ContaminationClass::FrontierDerived => return Err(CleanRoomViolation::FrontierDerived), + ContaminationClass::RealWorldMeasured => return Err(CleanRoomViolation::RealWorldMeasured), + ContaminationClass::SyntheticNovel | ContaminationClass::AdversarialSynthetic => {} + } + if p.uses_human_constants { + return Err(CleanRoomViolation::HumanConstants); + } + if p.uses_human_ontology { + return Err(CleanRoomViolation::HumanOntology); + } + Ok(()) +} diff --git a/crates/crumbs/src/sealed.rs b/crates/crumbs/src/sealed.rs new file mode 100644 index 00000000..95c963ff --- /dev/null +++ b/crates/crumbs/src/sealed.rs @@ -0,0 +1,350 @@ +//! Crumb v1 sealed contract: everything the learner never sees. +//! +//! A `SealedCrumb` is a pure function of (family, generator version, seed, +//! generation parameters): regenerating it reproduces the identical bytes and +//! digests. Occurrence-level facts (which population the mixer drew it into, +//! when it was shown) live in the ledger record, not here. +//! +//! `Debug` is redacted: logging a sealed record by accident prints only its +//! digest, never labels or held-out data. + +use crate::canon::Enc; +use crate::digest::{ + digest, CrumbDigest, Digest, Domain, GeneratorInstanceDigest, SealedRecordDigest, +}; +use crate::program::Program; +use crate::provenance::Provenance; +use serde::{Deserialize, Serialize}; + +pub const SEALED_SCHEMA_VERSION: u16 = 1; + +/// Capability rungs of the progression. Builder vocabulary; never sent to a learner. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Rung { + SingleTransformation = 1, + TwoTransformations = 2, + RepeatedTransformation = 3, + ConditionalTransformation = 4, + MultiInputRelation = 5, + Recurrence = 6, + State = 7, + Composition = 8, + Symmetry = 9, + Modularity = 10, + Invariance = 11, + MultiStepAlgorithm = 12, + LatentVariables = 13, + NoisyObservation = 14, + PartialObservation = 15, + CounterexampleSearch = 16, + TheoryFormation = 17, +} + +impl Rung { + pub const ALL: [Rung; 17] = [ + Rung::SingleTransformation, + Rung::TwoTransformations, + Rung::RepeatedTransformation, + Rung::ConditionalTransformation, + Rung::MultiInputRelation, + Rung::Recurrence, + Rung::State, + Rung::Composition, + Rung::Symmetry, + Rung::Modularity, + Rung::Invariance, + Rung::MultiStepAlgorithm, + Rung::LatentVariables, + Rung::NoisyObservation, + Rung::PartialObservation, + Rung::CounterexampleSearch, + Rung::TheoryFormation, + ]; +} + +/// What kind of generator family produced the crumb. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum SourceFamily { + Capability = 1, + Composition = 2, + Ambiguous = 3, + RabbitHole = 4, + Frontier = 5, + CleanRoomPhysics = 6, +} + +/// The five secret populations the mixer draws from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Population { + Fundamental = 1, + Composition = 2, + Ambiguous = 3, + RabbitHole = 4, + Frontier = 5, +} + +impl Population { + pub const ALL: [Population; 5] = [ + Population::Fundamental, + Population::Composition, + Population::Ambiguous, + Population::RabbitHole, + Population::Frontier, + ]; +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum TruthStatus { + /// Every labeled output is established by exact computation. + Verified = 1, + /// Outputs rest on an unproven claim. Never used for labeled examples. + Conjectural = 2, + /// No truth claim. + None = 3, +} + +/// Rabbit-hole mechanisms. Rabbit holes deceive; they never lie. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum AdversarialClass { + /// A: visible examples favour a simple wrong rule; held-outs break it. + SimpleWrongRule = 1, + /// B: several programs fit the visible examples exactly; held-outs distinguish. + MultiFit = 2, + /// C: an irrelevant input dimension correlates with the answer only in the visible sample. + SpuriousDimension = 3, + /// D: a finite prefix imitates a simpler process, then diverges. + PrefixDiverges = 4, + /// E: an arbitrary complex generator produces an elegant-looking prefix. + ElegantArbitrary = 5, + /// F: the visible evidence cannot separate several hypotheses. + InsufficientEvidence = 6, + /// G: noisy observations; exact interpolation is the wrong objective. + Noisy = 7, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum DecoyStatus { + Clean, + RabbitHole(AdversarialClass), + NoStructure, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum KnownSolution { + /// A generating program in the CPG1 format is known. + Known(Program), + /// The generator is known, but not as a CPG1 chain. + KnownOutsideProgramFormat, + /// Nobody knows (frontier material). + UnknownToHumanity, + /// The outputs have no compact structure by construction. + NoCompactStructure, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum VerificationMethod { + /// Outputs are the generator's own exact evaluation. + ExactGeneratorEvaluation = 1, + /// Outputs recomputed by an independent routine and cross-checked. + IndependentRecomputation = 2, + /// Bounded exact computation of a finite instance. + FiniteExactComputation = 3, +} + +/// Held-out tiers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum HeldoutTier { + Interpolation = 0, + Extrapolation = 1, + Adversarial = 2, +} + +impl HeldoutTier { + pub const ALL: [HeldoutTier; 3] = [ + HeldoutTier::Interpolation, + HeldoutTier::Extrapolation, + HeldoutTier::Adversarial, + ]; +} + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct LaneExample { + pub input: Vec<u64>, + pub output: Vec<u64>, +} + +#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Heldouts { + pub interpolation: Vec<LaneExample>, + pub extrapolation: Vec<LaneExample>, + pub adversarial: Vec<LaneExample>, +} + +impl Heldouts { + pub fn tier(&self, t: HeldoutTier) -> &[LaneExample] { + match t { + HeldoutTier::Interpolation => &self.interpolation, + HeldoutTier::Extrapolation => &self.extrapolation, + HeldoutTier::Adversarial => &self.adversarial, + } + } + + pub fn encode(&self, e: &mut Enc) { + for t in HeldoutTier::ALL { + let set = self.tier(t); + e.u32(set.len() as u32); + for ex in set { + e.u64s(&ex.input).u64s(&ex.output); + } + } + } + + pub fn digest(&self) -> Digest { + let mut e = Enc::new(); + self.encode(&mut e); + digest(Domain::HeldoutSet, &e.finish()) + } + + pub fn len(&self) -> usize { + self.interpolation.len() + self.extrapolation.len() + self.adversarial.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +/// Opaque capability identifier (BLAKE3 of the capability's defining bytes). +pub type CapabilityId = Digest; + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SealedCrumb { + pub schema_version: u16, + pub crumb_digest: CrumbDigest, + + pub family_id: u32, + pub family_key: String, + pub mechanism: String, + pub generator_version: String, + pub generator_code_digest: Digest, + pub seed: u64, + pub heldout_seed: u64, + pub generation_parameters: Vec<u8>, + pub generator_instance_digest: GeneratorInstanceDigest, + + pub verification_method: VerificationMethod, + pub difficulty: u16, + pub rung: Rung, + pub required_capabilities: Vec<CapabilityId>, + pub provides_capability: Option<CapabilityId>, + + pub provenance: Provenance, + pub source_family: SourceFamily, + pub truth_status: TruthStatus, + pub decoy_status: DecoyStatus, + pub known_solution: KnownSolution, + /// Programs that fit the visible examples as well as the truth does. + pub alternatives: Vec<Program>, + /// Indices of visible examples carrying observation noise. + pub noisy_visible: Vec<u32>, + /// Inclusive input range the family draws from (lane 0). + pub expected_domain: (u64, u64), + pub topic_internal: String, + + pub heldouts: Heldouts, +} + +impl std::fmt::Debug for SealedCrumb { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "SealedCrumb(<redacted {}>)", self.digest().short()) + } +} + +impl std::fmt::Debug for Heldouts { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Heldouts(<redacted {} examples>)", self.len()) + } +} + +impl std::fmt::Debug for LaneExample { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LaneExample(<redacted>)") + } +} + +impl SealedCrumb { + pub fn to_bytes(&self) -> Vec<u8> { + let mut e = Enc::new(); + e.bytes(b"CRS1") + .u16(self.schema_version) + .digest(&self.crumb_digest); + e.u32(self.family_id) + .str(&self.family_key) + .str(&self.mechanism) + .str(&self.generator_version); + e.digest(&self.generator_code_digest) + .u64(self.seed) + .u64(self.heldout_seed); + e.blob(&self.generation_parameters) + .digest(&self.generator_instance_digest); + e.u8(self.verification_method as u8) + .u16(self.difficulty) + .u8(self.rung as u8); + e.u32(self.required_capabilities.len() as u32); + for c in &self.required_capabilities { + e.digest(c); + } + match &self.provides_capability { + Some(c) => e.u8(1).digest(c), + None => e.u8(0), + }; + e.u8(self.provenance.class as u8) + .u8(self.provenance.uses_human_constants as u8) + .u8(self.provenance.uses_human_ontology as u8); + e.u8(self.source_family as u8).u8(self.truth_status as u8); + match self.decoy_status { + DecoyStatus::Clean => e.u8(0), + DecoyStatus::RabbitHole(c) => e.u8(1).u8(c as u8), + DecoyStatus::NoStructure => e.u8(2), + }; + match &self.known_solution { + KnownSolution::Known(p) => e.u8(1).blob(&p.to_bytes()), + KnownSolution::KnownOutsideProgramFormat => e.u8(2), + KnownSolution::UnknownToHumanity => e.u8(3), + KnownSolution::NoCompactStructure => e.u8(4), + }; + e.u32(self.alternatives.len() as u32); + for p in &self.alternatives { + e.blob(&p.to_bytes()); + } + e.u32(self.noisy_visible.len() as u32); + for i in &self.noisy_visible { + e.u32(*i); + } + e.u64(self.expected_domain.0) + .u64(self.expected_domain.1) + .str(&self.topic_internal); + self.heldouts.encode(&mut e); + e.finish() + } + + /// Commits to metadata, held-outs and provenance. Never enters learner space. + pub fn digest(&self) -> SealedRecordDigest { + digest(Domain::SealedRecord, &self.to_bytes()) + } +} + +/// GeneratorInstanceDigest = BLAKE3(family_id || generator_version || seed || canonical parameters). +pub fn generator_instance_digest( + family_id: u32, + generator_version: &str, + seed: u64, + params: &[u8], +) -> GeneratorInstanceDigest { + let mut e = Enc::new(); + e.u32(family_id) + .str(generator_version) + .u64(seed) + .blob(params); + digest(Domain::GeneratorInstance, &e.finish()) +} diff --git a/crates/crumbs/src/session.rs b/crates/crumbs/src/session.rs new file mode 100644 index 00000000..e6ca095a --- /dev/null +++ b/crates/crumbs/src/session.rs @@ -0,0 +1,293 @@ +//! A curriculum session: the sealed side driving one learner process. +//! +//! For every crumb: generate (visible + sealed), present the visible bytes, +//! evaluate each submission against the sealed held-outs, derive the trace, +//! climb the promotion ladder, admit operations to the learner (only when the +//! condition allows reuse), and append a Crumbline ledger record. + +use crate::digest::{digest, CrumbOccurrenceId, Digest, Domain}; +use crate::gen::{self, FamilySpec}; +use crate::ledger::{CrumblineRecord, Ledger}; +use crate::promotion::{Admission, Ladder, PromotionConfig}; +use crate::protocol::{LearnerProcess, LearnerStats, ProtocolError, SearchConfig, SUBMIT_ROBUST}; +use crate::provenance::Lane; +use crate::sealed::{DecoyStatus, Population, SealedCrumb}; +use crate::trace::{self, TraceSummary}; +use crate::verify::{evaluate, verifier_digest, EvalClass, SealedEvaluation, Verdict}; +use serde::{Deserialize, Serialize}; +use std::io::Write; +use std::path::PathBuf; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct SessionConfig { + pub condition: String, + pub learner: String, + pub run_id: String, + pub search: SearchConfig, + /// Admitted operations are sent to the learner only when true. + pub library_enabled: bool, + pub promotion: PromotionConfig, + pub record_transcript: bool, + /// Directory for the trace corpus, ledger and evidence (None = in memory only). + pub out_dir: Option<PathBuf>, +} + +/// Per-crumb outcome (sealed-side bookkeeping; never sent to a learner). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct CrumbOutcome { + pub seq: u64, + pub phase: String, + pub family_id: u32, + pub family_key: String, + pub mechanism: String, + pub population: Population, + pub decoy: DecoyStatus, + pub crumb_digest: Digest, + pub supported: bool, + pub accepted: bool, + pub verified: bool, + pub ambiguous_accept: bool, + pub evaluations: Vec<SealedEvaluation>, + pub stats: LearnerStats, + pub trace: TraceSummary, + pub library_ops_available: u32, + /// The operation bank the learner declared for this crumb (learner-neutral CPG1). + pub declared_bank: Vec<crate::program::Program>, + pub admissions_after: Vec<Admission>, + pub ledger_root: Digest, +} + +impl CrumbOutcome { + pub fn falsified_hidden(&self) -> usize { + self.evaluations + .iter() + .filter(|e| e.class == EvalClass::FalsifiedHidden) + .count() + } + pub fn first_class(&self) -> Option<EvalClass> { + self.evaluations.first().map(|e| e.class) + } + pub fn reused_library(&self) -> bool { + self.accepted && !self.trace.library_refs_in_solution.is_empty() + } +} + +pub struct Session { + pub cfg: SessionConfig, + learner: Option<LearnerProcess>, + pub ladder: Ladder, + pub ledger: Ledger, + pub outcomes: Vec<CrumbOutcome>, + pub learner_digest: Digest, + seq: u64, + admissions_frozen: bool, + trace_chain: Digest, + sample_chain: Digest, +} + +fn file_digest(path: &str) -> Digest { + std::fs::read(path) + .map(|b| digest(Domain::Config, &b)) + .unwrap_or(Digest::ZERO) +} + +impl Session { + pub fn start(cfg: SessionConfig) -> Result<Self, ProtocolError> { + let mut learner = LearnerProcess::spawn(&cfg.learner, &[], cfg.record_transcript)?; + learner.hello(&cfg.search, cfg.library_enabled)?; + if let Some(d) = &cfg.out_dir { + std::fs::create_dir_all(d).map_err(|_| ProtocolError::Io)?; + } + Ok(Session { + learner_digest: file_digest(&cfg.learner), + ladder: Ladder::new(cfg.promotion.clone()), + ledger: Ledger::new(Lane::Main, &cfg.run_id), + learner: Some(learner), + cfg, + outcomes: vec![], + seq: 0, + admissions_frozen: false, + trace_chain: Digest::ZERO, + sample_chain: Digest::ZERO, + }) + } + + pub fn learner_pid(&self) -> Option<u32> { + self.learner.as_ref().map(|l| l.pid()) + } + + pub fn transcript(&self) -> Option<&[u8]> { + self.learner.as_ref().and_then(|l| l.transcript.as_deref()) + } + + /// Stop admitting operations (used to freeze the library for evaluation). + pub fn freeze_admissions(&mut self) { + self.admissions_frozen = true; + } + + fn append_file(&self, name: &str, bytes: &[u8]) { + if let Some(d) = &self.cfg.out_dir { + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(d.join(name)) + { + let _ = f.write_all(bytes); + } + } + } + + pub fn present( + &mut self, + fam: &FamilySpec, + seed: u64, + population: Population, + phase: &str, + ) -> Result<CrumbOutcome, ProtocolError> { + let g = gen::generate(fam, seed); + self.present_sealed(&g.visible, &g.sealed, population, phase) + } + + /// Present a crumb from an explicit visible/sealed pair (used by gates that + /// construct canary sealed records). + pub fn present_with( + &mut self, + visible: &crate::visible::VisibleCrumb, + sealed: &SealedCrumb, + ) -> Result<CrumbOutcome, ProtocolError> { + self.present_sealed(visible, sealed, Population::Fundamental, "gates") + } + + fn present_sealed( + &mut self, + visible: &crate::visible::VisibleCrumb, + sealed: &SealedCrumb, + population: Population, + phase: &str, + ) -> Result<CrumbOutcome, ProtocolError> { + let seq = self.seq; + self.seq += 1; + let max_q = self.cfg.search.max_oracle_queries as usize; + let mut evaluations: Vec<SealedEvaluation> = Vec::new(); + let learner = self.learner.as_mut().ok_or(ProtocolError::Io)?; + let ladder = &mut self.ladder; + let session = learner.run_crumb(visible, &mut |sub| { + if evaluations.len() >= max_q { + return Verdict::BudgetExhausted; + } + let ev = evaluate( + visible, + sealed, + &sub.program, + sub.hypotheses, + sub.flags & SUBMIT_ROBUST != 0, + ); + match ev.class { + EvalClass::Verified => ladder.observe_accept(seq, sealed, &ev, &sub.program), + EvalClass::FalsifiedHidden => ladder.observe_reject(&ev, &sub.program), + _ => {} + } + let v = ev.verdict; + evaluations.push(ev); + v + })?; + + let tr = trace::derive(visible, &session); + let mut rec_chain = self.trace_chain; + let tbytes = trace::encode_records(&tr.records, &mut rec_chain); + let mut s_chain = self.sample_chain; + let sbytes = trace::encode_samples(&tr.samples, &mut s_chain); + self.trace_chain = rec_chain; + self.sample_chain = s_chain; + self.append_file("trace.ctr", &tbytes); + self.append_file("samples.cts", &sbytes); + + let admissions = if self.admissions_frozen { + vec![] + } else { + self.ladder.advance(seq) + }; + if self.cfg.library_enabled { + let learner = self.learner.as_mut().ok_or(ProtocolError::Io)?; + for a in &admissions { + learner.admit(a.op_ref, a.scope_bits, &a.program)?; + } + } + + let summary = tr.summary.clone().expect("derive always summarizes"); + let rec = CrumblineRecord { + seq, + lane: Lane::Main, + occurrence: CrumbOccurrenceId::new(), + condition: self.cfg.condition.clone(), + population, + crumb_digest: visible.digest(), + generator_instance_digest: sealed.generator_instance_digest, + sealed_digest: sealed.digest(), + verifier_digest: verifier_digest(), + learner_digest: self.learner_digest, + evaluations: evaluations.iter().map(|e| e.digest()).collect(), + trace_stream_digest: summary.stream_digest, + promotions: admissions.iter().map(|a| a.promotion_digest).collect(), + prev_root: Digest::ZERO, + root: Digest::ZERO, + }; + let root = self + .ledger + .append(rec, &sealed.provenance) + .expect("main lane accepts every provenance"); + if let Some(r) = self.ledger.records.last() { + self.append_file( + "ledger.jsonl", + format!("{}\n", serde_json::to_string(r).unwrap()).as_bytes(), + ); + } + for e in &evaluations { + self.append_file( + "evaluations.jsonl", + format!("{}\n", serde_json::to_string(e).unwrap()).as_bytes(), + ); + } + + let accepted = evaluations.iter().any(|e| e.verdict == Verdict::Accept); + let out = CrumbOutcome { + seq, + phase: phase.to_string(), + family_id: sealed.family_id, + family_key: sealed.family_key.clone(), + mechanism: sealed.mechanism.clone(), + population, + decoy: sealed.decoy_status, + crumb_digest: visible.digest(), + supported: session.stats.outcome != crate::protocol::OUTCOME_UNSUPPORTED, + accepted, + verified: evaluations.iter().any(|e| e.class == EvalClass::Verified), + ambiguous_accept: evaluations + .iter() + .any(|e| e.class == EvalClass::AmbiguousUnderdetermined), + library_ops_available: session.bank.iter().filter(|b| b.origin == 1).count() as u32, + declared_bank: session.bank.iter().map(|b| b.program.clone()).collect(), + evaluations, + stats: session.stats, + trace: summary, + admissions_after: admissions, + ledger_root: root, + }; + self.outcomes.push(out.clone()); + Ok(out) + } + + pub fn finish(mut self) -> Result<(Ledger, Vec<CrumbOutcome>, Ladder), ProtocolError> { + if let Some(l) = self.learner.take() { + l.shutdown()?; + } + if let Some(d) = &self.cfg.out_dir { + let _ = std::fs::write( + d.join("promotion.json"), + serde_json::to_string_pretty(&self.ladder.ops.values().collect::<Vec<_>>()) + .unwrap(), + ); + } + Ok((self.ledger, self.outcomes, self.ladder)) + } +} diff --git a/crates/crumbs/src/trace.rs b/crates/crumbs/src/trace.rs new file mode 100644 index 00000000..0738f2ae --- /dev/null +++ b/crates/crumbs/src/trace.rs @@ -0,0 +1,522 @@ +//! Search-trace corpus (the M23-style training data for AIEN_0). +//! +//! The learner reports bare search events (which operation it applied to which +//! node, how it pruned, what it submitted). The sealed side reconstructs every +//! candidate program from those events and the declared operation bank, and +//! derives everything else itself from the *visible* examples: state digests, +//! remaining-mismatch vectors, improvement flags. Held-out results enter a +//! record only on SUBMIT events, and only as the verdict the learner received. +//! +//! No record has a free-text field. Nothing resembling reasoning prose can be +//! stored; records hold operations, states, measurements and outcomes. +//! +//! `CTR1` trace record (fixed 247 bytes incl. chain digest) and `CTS1` +//! training sample (fixed 268 bytes incl. chain digest) are hash-chained with +//! BLAKE3 so a corpus file cannot be edited without detection. + +use crate::canon::Enc; +use crate::digest::{digest, Digest, Domain, Hasher}; +use crate::program::Program; +use crate::protocol::{ek, CrumbSession}; +use crate::verify::Verdict; +use crate::visible::{lane_mask, Encoding, VisibleCrumb}; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; + +pub const TRACE_RECORD_BYTES: usize = 247; +pub const SAMPLE_RECORD_BYTES: usize = 268; +pub const SAMPLE_MAX_OPS: usize = 128; +pub const RESIDUALS: usize = 4; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[repr(u8)] +pub enum ResultClass { + /// Generated but pruned (equivalent, over cost, frontier cap). + Pruned = 1, + /// Evaluated; mismatch did not shrink. + Failed = 2, + /// Evaluated; some examples matched but no improvement on the parent. + Partial = 3, + /// Evaluated; mismatch shrank relative to the parent. + Improved = 4, + /// Submitted and accepted by the sealed verifier. + Verified = 5, + /// Submitted, explained the visible examples, rejected by held-outs. + RejectedHidden = 6, + /// A robust (best partial fit) submission that was rejected. + RejectedRobust = 7, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TraceRecord { + pub event_index: u32, + pub kind: u8, + pub result_class: ResultClass, + pub parent: u32, + pub child: u32, + pub op_index: u16, + pub op_id: Digest, + pub op_origin: u8, + pub depth: u16, + pub prune: u8, + pub verify: u8, + pub fit: u8, + /// 0 unless this is a SUBMIT record; then the verdict byte the learner got. + pub hidden: u8, + pub improved: bool, + pub contributed: bool, + pub state_digest: Digest, + pub child_state_digest: Digest, + pub program_digest: Digest, + pub mismatch_before: u16, + pub mismatch_after: u16, + pub hamming_before: u32, + pub hamming_after: u32, + pub exec_cost: u32, + pub search_cost: u32, + pub program_steps: u16, + pub oracle_index: u16, + pub residual: [u64; RESIDUALS], +} + +/// One decision state on a verified solution path, with the operations that +/// were tried there and which of them led onward (equivalence-aware). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TrainingSample { + pub bank_digest: Digest, + pub state_digest: Digest, + pub depth: u8, + pub solution_depth: u8, + pub n_examples: u8, + pub n_ops: u16, + pub values: [u64; 8], + pub targets: [u64; 8], + pub positive_bits: [u8; SAMPLE_MAX_OPS / 8], + pub tried_bits: [u8; SAMPLE_MAX_OPS / 8], +} + +/// Per-crumb summary (the `final:` block of the trace). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TraceSummary { + pub bank_digest: Digest, + pub bank_op_ids: Vec<Digest>, + pub solved: bool, + pub solution_digest: Option<Digest>, + pub verified_on_heldout: bool, + pub records: u32, + pub samples: u32, + pub stream_digest: Digest, + /// Library operations (by op_ref) used in the accepted solution. + pub library_refs_in_solution: Vec<u32>, + /// A submitted program disagreed with the program reconstructed from events. + pub integrity_violations: u32, +} + +#[derive(Clone, Debug, Default)] +pub struct CrumbTrace { + pub records: Vec<TraceRecord>, + pub samples: Vec<TrainingSample>, + pub summary: Option<TraceSummary>, +} + +struct Node { + parent: u32, + op: u16, + depth: u16, + vals: Vec<u64>, + program: Program, +} + +fn state_digest(vals: &[u64]) -> Digest { + let mut e = Enc::new(); + for v in vals { + e.u64(*v); + } + digest(Domain::SearchState, &e.finish()) +} + +pub fn bank_digest(bank: &[crate::protocol::BankEntry]) -> Digest { + let mut h = Hasher::new(Domain::LearnerBank); + for b in bank { + h.update(&[b.origin]).update(&b.program.digest().0); + } + h.finish() +} + +/// Derive the canonical trace for one crumb session. +pub fn derive(visible: &VisibleCrumb, session: &CrumbSession) -> CrumbTrace { + let mut out = CrumbTrace::default(); + let vals_in: Vec<(u64, u64)> = visible + .values() + .into_iter() + .map(|(i, o)| (i[0], o[0])) + .collect(); + let mask = match visible.encoding { + Encoding::DecimalUtf8 => u64::MAX, + Encoding::RawLe => lane_mask(visible.out_lane_bytes), + }; + let targets: Vec<u64> = vals_in.iter().map(|p| p.1).collect(); + let bank_ids: Vec<Digest> = session.bank.iter().map(|b| b.program.digest()).collect(); + let bdig = bank_digest(&session.bank); + + let measure = |vals: &[u64]| -> (u16, u32, [u64; RESIDUALS]) { + let mut mism = 0u16; + let mut ham = 0u32; + let mut res = [0u64; RESIDUALS]; + for (i, (v, t)) in vals.iter().zip(&targets).enumerate() { + let v = v & mask; + if v != *t { + mism += 1; + } + ham += (v ^ t).count_ones(); + if i < RESIDUALS { + res[i] = t.wrapping_sub(v); + } + } + (mism, ham, res) + }; + + let mut nodes: HashMap<u32, Node> = HashMap::new(); + nodes.insert( + 0, + Node { + parent: u32::MAX, + op: u16::MAX, + depth: 0, + vals: vals_in.iter().map(|p| p.0).collect(), + program: Program::default(), + }, + ); + + // Oracle verdicts by node, from the actual submissions. + let mut verdict_of: HashMap<u32, Verdict> = HashMap::new(); + let mut integrity_violations = 0; + for s in &session.submissions { + verdict_of.insert(s.node, s.verdict); + } + + for (idx, ev) in session.events.iter().enumerate() { + let mut r = TraceRecord { + event_index: idx as u32, + kind: ev.kind, + result_class: ResultClass::Failed, + parent: ev.parent, + child: ev.child, + op_index: ev.op_index, + op_id: Digest::ZERO, + op_origin: 0, + depth: 0, + prune: ev.prune, + verify: ev.verify, + fit: ev.fit, + hidden: 0, + improved: false, + contributed: false, + state_digest: Digest::ZERO, + child_state_digest: Digest::ZERO, + program_digest: Digest::ZERO, + mismatch_before: 0, + mismatch_after: 0, + hamming_before: 0, + hamming_after: 0, + exec_cost: ev.exec_cost, + search_cost: idx as u32, + program_steps: 0, + oracle_index: ev.oracle_index, + residual: [0; RESIDUALS], + }; + match ev.kind { + ek::EXPAND => { + let Some(parent) = nodes.get(&ev.parent) else { + continue; + }; + let Some(op) = session.bank.get(ev.op_index as usize) else { + continue; + }; + let vals: Vec<u64> = parent.vals.iter().map(|&x| op.program.run(x)).collect(); + let program = parent.program.then(&op.program); + let (mb, hb, _) = measure(&parent.vals); + let (ma, ha, res) = measure(&vals); + r.op_id = bank_ids[ev.op_index as usize]; + r.op_origin = op.origin; + r.depth = parent.depth + 1; + r.state_digest = state_digest(&parent.vals); + r.child_state_digest = state_digest(&vals); + r.program_digest = program.digest(); + r.mismatch_before = mb; + r.mismatch_after = ma; + r.hamming_before = hb; + r.hamming_after = ha; + r.program_steps = program.len() as u16; + r.residual = res; + r.improved = ev.prune == 0 && (ma < mb || (ma == mb && ha < hb)); + r.result_class = if ev.prune != 0 { + ResultClass::Pruned + } else if r.improved { + ResultClass::Improved + } else if (ma as usize) < targets.len() { + ResultClass::Partial + } else { + ResultClass::Failed + }; + let depth = r.depth; + nodes.insert( + ev.child, + Node { + parent: ev.parent, + op: ev.op_index, + depth, + vals, + program, + }, + ); + } + ek::SUBMIT => { + let Some(node) = nodes.get(&ev.parent) else { + continue; + }; + let (m, h, res) = measure(&node.vals); + r.depth = node.depth; + r.state_digest = state_digest(&node.vals); + r.child_state_digest = r.state_digest; + r.program_digest = node.program.digest(); + r.mismatch_before = m; + r.mismatch_after = m; + r.hamming_before = h; + r.hamming_after = h; + r.program_steps = node.program.len() as u16; + r.residual = res; + let v = verdict_of.get(&ev.parent).copied(); + r.hidden = v.map_or(0, |v| v as u8); + r.result_class = match v { + Some(Verdict::Accept) => ResultClass::Verified, + _ if ev.fit == 2 => ResultClass::RejectedRobust, + _ => ResultClass::RejectedHidden, + }; + if let Some(sub) = session.submissions.iter().find(|s| s.node == ev.parent) { + if sub.program.run_all_eq(&node.program) == Some(false) { + integrity_violations += 1; + } + } + } + _ => continue, + } + out.records.push(r); + } + + // Backfill: which transitions contributed to the accepted solution? + let accepted = session + .submissions + .iter() + .find(|s| s.verdict == Verdict::Accept); + let mut library_refs = Vec::new(); + let mut path_states: HashSet<(u16, Digest)> = HashSet::new(); + let mut path_nodes: Vec<u32> = Vec::new(); + if let Some(acc) = accepted { + let mut n = acc.node; + while let Some(node) = nodes.get(&n) { + path_nodes.push(n); + path_states.insert((node.depth, state_digest(&node.vals))); + if node.op != u16::MAX { + let b = &session.bank[node.op as usize]; + if b.origin == 1 { + library_refs.push(b.op_ref); + } + } + if node.parent == u32::MAX { + break; + } + n = node.parent; + } + library_refs.sort_unstable(); + for r in out.records.iter_mut() { + if r.kind == ek::EXPAND && path_states.contains(&(r.depth, r.child_state_digest)) { + r.contributed = true; + } + if r.kind == ek::SUBMIT && r.parent == acc.node { + r.contributed = true; + } + } + // Training samples: one per decision state on the path. A submission + // whose node was never reported in the event stream yields none. + path_nodes.reverse(); // root first + let solution_depth = path_nodes.len().saturating_sub(1) as u8; + for &pn in path_nodes.iter().take(path_nodes.len().saturating_sub(1)) { + let node = &nodes[&pn]; + let sd = state_digest(&node.vals); + let mut s = TrainingSample { + bank_digest: bdig, + state_digest: sd, + depth: node.depth as u8, + solution_depth, + n_examples: targets.len().min(255) as u8, + n_ops: session.bank.len() as u16, + values: [0; 8], + targets: [0; 8], + positive_bits: [0; SAMPLE_MAX_OPS / 8], + tried_bits: [0; SAMPLE_MAX_OPS / 8], + }; + let k = 8.min(targets.len()); + s.values[..k].copy_from_slice(&node.vals[..k]); + s.targets[..k].copy_from_slice(&targets[..k]); + for r in out + .records + .iter() + .filter(|r| r.kind == ek::EXPAND && r.parent == pn) + { + let i = r.op_index as usize; + if i < SAMPLE_MAX_OPS { + s.tried_bits[i / 8] |= 1 << (i % 8); + if r.contributed { + s.positive_bits[i / 8] |= 1 << (i % 8); + } + } + } + out.samples.push(s); + } + } + + let stream = stream_digest(&out.records, &out.samples); + out.summary = Some(TraceSummary { + bank_digest: bdig, + bank_op_ids: bank_ids, + solved: accepted.is_some(), + solution_digest: accepted.map(|a| a.program.digest()), + verified_on_heldout: accepted.is_some(), + records: out.records.len() as u32, + samples: out.samples.len() as u32, + stream_digest: stream, + library_refs_in_solution: library_refs, + integrity_violations, + }); + out +} + +impl Program { + /// Compare behaviour on the public probes (None if either is empty). + pub fn run_all_eq(&self, other: &Program) -> Option<bool> { + if self.is_empty() || other.is_empty() { + return None; + } + Some(self.behavior() == other.behavior()) + } +} + +impl TraceRecord { + pub fn encode_body(&self, e: &mut Enc) { + e.bytes(b"CTR1") + .u16(1) + .u8(self.kind) + .u8(self.result_class as u8); + e.u32(self.event_index) + .u32(self.parent) + .u32(self.child) + .u16(self.op_index) + .u8(self.op_origin); + e.u8(self.prune) + .u8(self.verify) + .u8(self.fit) + .u8(self.hidden); + e.u8(self.improved as u8) + .u8(self.contributed as u8) + .u16(self.depth); + e.digest(&self.op_id) + .digest(&self.state_digest) + .digest(&self.child_state_digest) + .digest(&self.program_digest); + e.u16(self.mismatch_before) + .u16(self.mismatch_after) + .u32(self.hamming_before) + .u32(self.hamming_after); + e.u32(self.exec_cost) + .u32(self.search_cost) + .u16(self.program_steps) + .u16(self.oracle_index); + for r in self.residual { + e.u64(r); + } + } +} + +impl TrainingSample { + pub fn encode_body(&self, e: &mut Enc) { + e.bytes(b"CTS1").u16(1).u16(self.n_ops); + e.digest(&self.bank_digest).digest(&self.state_digest); + e.u8(self.depth) + .u8(self.solution_depth) + .u8(self.n_examples) + .u8(0); + for v in self.values { + e.u64(v); + } + for v in self.targets { + e.u64(v); + } + e.bytes(&self.positive_bits).bytes(&self.tried_bits); + } +} + +/// Encode records with a BLAKE3 chain; `chain` carries the previous digest. +pub fn encode_records(records: &[TraceRecord], chain: &mut Digest) -> Vec<u8> { + let mut out = Vec::with_capacity(records.len() * TRACE_RECORD_BYTES); + for r in records { + let mut e = Enc::new(); + r.encode_body(&mut e); + let body = e.finish(); + debug_assert_eq!(body.len(), TRACE_RECORD_BYTES - 32); + let d = Hasher::new(Domain::TraceRecord) + .update(&chain.0) + .update(&body) + .finish(); + out.extend_from_slice(&body); + out.extend_from_slice(&d.0); + *chain = d; + } + out +} + +pub fn encode_samples(samples: &[TrainingSample], chain: &mut Digest) -> Vec<u8> { + let mut out = Vec::with_capacity(samples.len() * SAMPLE_RECORD_BYTES); + for s in samples { + let mut e = Enc::new(); + s.encode_body(&mut e); + let body = e.finish(); + debug_assert_eq!(body.len(), SAMPLE_RECORD_BYTES - 32); + let d = Hasher::new(Domain::TrainingSample) + .update(&chain.0) + .update(&body) + .finish(); + out.extend_from_slice(&body); + out.extend_from_slice(&d.0); + *chain = d; + } + out +} + +fn stream_digest(records: &[TraceRecord], samples: &[TrainingSample]) -> Digest { + let mut c1 = Digest::ZERO; + let a = encode_records(records, &mut c1); + let mut c2 = Digest::ZERO; + let b = encode_samples(samples, &mut c2); + let _ = (a, b); + let mut e = Enc::new(); + e.digest(&c1).digest(&c2); + digest(Domain::TraceStream, &e.finish()) +} + +/// Re-verify a chained record file. Returns the number of records or None. +pub fn verify_chain(bytes: &[u8], record_len: usize, domain: Domain) -> Option<usize> { + if !bytes.len().is_multiple_of(record_len) { + return None; + } + let mut chain = Digest::ZERO; + for rec in bytes.chunks(record_len) { + let (body, d) = rec.split_at(record_len - 32); + let want = Hasher::new(domain).update(&chain.0).update(body).finish(); + if want.0 != d { + return None; + } + chain = want; + } + Some(bytes.len() / record_len) +} diff --git a/crates/crumbs/src/verify.rs b/crates/crumbs/src/verify.rs new file mode 100644 index 00000000..8e3223ec --- /dev/null +++ b/crates/crumbs/src/verify.rs @@ -0,0 +1,251 @@ +//! The generic verifier contract (sealed side). +//! +//! A learner's candidate arrives as a CPG1 `Program`. The verifier executes it +//! with this crate's own interpreter against the visible examples and the +//! three sealed held-out tiers, and produces a `SealedEvaluation`. The learner +//! receives exactly one byte derived from it (`learner_verdict`). +//! +//! Visible interpolation is never verification: a candidate is accepted only +//! if it also predicts every sealed held-out. + +use crate::canon::Enc; +use crate::digest::{digest, Digest, Domain}; +use crate::program::Program; +use crate::sealed::{AdversarialClass, DecoyStatus, HeldoutTier, SealedCrumb}; +use crate::visible::{lane_mask, Encoding, VisibleCrumb}; +use serde::{Deserialize, Serialize}; + +pub const VERIFIER_VERSION: &str = "crumbs-verifier/1.0.0"; + +/// Identity of the verification rules and interpreter. +pub fn verifier_digest() -> Digest { + let mut e = Enc::new(); + e.str(VERIFIER_VERSION).str(crate::program::std_interpreter_id()).str("accept=visible_ok&&all_heldout_tiers_pass;noise=mismatch_subset_of_sealed_noisy_indices"); + digest(Domain::Verifier, &e.finish()) +} + +/// The single byte a learner is told. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[repr(u8)] +pub enum Verdict { + Accept = 1, + Reject = 2, + BudgetExhausted = 3, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum EvalClass { + /// Fits the visible examples and predicts every held-out. + Verified, + /// Does not even explain the visible examples. + FalsifiedVisible, + /// Explains the visible examples, fails held-outs: a recorded useful failure. + FalsifiedHidden, + /// Predicts the held-outs, but the visible evidence could not have + /// established it (insufficient-evidence crumb). + AmbiguousUnderdetermined, + /// The crumb's shape is outside CPG1 v1 (output arity != 1). + Unsupported, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TierResult { + pub passed: u32, + pub total: u32, +} + +impl TierResult { + pub fn ok(&self) -> bool { + self.passed == self.total + } +} + +/// Machine-readable evidence for one evaluation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SealedEvaluation { + pub class: EvalClass, + pub verdict: Verdict, + pub visible_matches: u32, + pub visible_total: u32, + pub interpolation: TierResult, + pub extrapolation: TierResult, + pub adversarial: TierResult, + /// The visible evidence admitted rival explanations (sealed alternatives exist). + pub underdetermined: bool, + /// Insufficient-evidence crumbs only: did the learner report >= 2 rival fits? + pub ambiguity_recognized: Option<bool>, + /// Index of the sealed alternative this candidate behaves like on the held-outs. + pub matches_alternative: Option<u32>, + pub learner_hypotheses: u8, + pub robust_submission: bool, + pub crumb_digest: Digest, + pub sealed_digest: Digest, + pub generator_instance_digest: Digest, + pub program_digest: Digest, + pub visible_set_digest: Digest, + pub heldout_set_digest: Digest, + pub verifier_digest: Digest, + pub program_steps: u32, + pub evaluation_ops: u64, +} + +impl SealedEvaluation { + pub fn tier(&self, t: HeldoutTier) -> TierResult { + match t { + HeldoutTier::Interpolation => self.interpolation, + HeldoutTier::Extrapolation => self.extrapolation, + HeldoutTier::Adversarial => self.adversarial, + } + } + + pub fn to_bytes(&self) -> Vec<u8> { + let mut e = Enc::new(); + e.bytes(b"CEV1").u8(self.class as u8).u8(self.verdict as u8); + e.u32(self.visible_matches).u32(self.visible_total); + for t in [self.interpolation, self.extrapolation, self.adversarial] { + e.u32(t.passed).u32(t.total); + } + e.u8(self.underdetermined as u8); + e.u8(match self.ambiguity_recognized { + None => 0, + Some(false) => 1, + Some(true) => 2, + }); + e.u32(self.matches_alternative.unwrap_or(u32::MAX)); + e.u8(self.learner_hypotheses) + .u8(self.robust_submission as u8); + for d in [ + &self.crumb_digest, + &self.sealed_digest, + &self.generator_instance_digest, + &self.program_digest, + &self.visible_set_digest, + &self.heldout_set_digest, + &self.verifier_digest, + ] { + e.digest(d); + } + e.u32(self.program_steps).u64(self.evaluation_ops); + e.finish() + } + + /// Evidence receipt id of this evaluation. + pub fn digest(&self) -> Digest { + digest(Domain::Evaluation, &self.to_bytes()) + } +} + +fn out_mask(v: &VisibleCrumb) -> u64 { + match v.encoding { + Encoding::DecimalUtf8 => u64::MAX, + Encoding::RawLe => lane_mask(v.out_lane_bytes), + } +} + +pub fn evaluate( + visible: &VisibleCrumb, + sealed: &SealedCrumb, + cand: &Program, + learner_hypotheses: u8, + robust_submission: bool, +) -> SealedEvaluation { + let mask = out_mask(visible); + let mut ops: u64 = 0; + let steps = cand.len() as u64; + let mut run = |x: u64| { + ops += steps; + cand.run(x) & mask + }; + + let supported = visible.out_arity == 1; + let values = visible.values(); + let mut visible_matches = 0u32; + let mut mismatched = Vec::new(); + if supported { + for (i, (inp, out)) in values.iter().enumerate() { + if run(inp[0]) == out[0] { + visible_matches += 1; + } else { + mismatched.push(i as u32); + } + } + } + let visible_ok = supported && mismatched.iter().all(|i| sealed.noisy_visible.contains(i)); + + let mut tiers = [TierResult { + passed: 0, + total: 0, + }; 3]; + for (k, t) in HeldoutTier::ALL.iter().enumerate() { + for ex in sealed.heldouts.tier(*t) { + tiers[k].total += 1; + if supported && run(ex.input[0]) == ex.output[0] { + tiers[k].passed += 1; + } + } + } + let hidden_ok = tiers.iter().all(|t| t.ok()); + + let insufficient = matches!( + sealed.decoy_status, + DecoyStatus::RabbitHole(AdversarialClass::InsufficientEvidence) + ); + let class = if !supported { + EvalClass::Unsupported + } else if !visible_ok { + EvalClass::FalsifiedVisible + } else if !hidden_ok { + EvalClass::FalsifiedHidden + } else if insufficient { + EvalClass::AmbiguousUnderdetermined + } else { + EvalClass::Verified + }; + let verdict = if matches!( + class, + EvalClass::Verified | EvalClass::AmbiguousUnderdetermined + ) { + Verdict::Accept + } else { + Verdict::Reject + }; + + let matches_alternative = if supported { + sealed.alternatives.iter().position(|alt| { + HeldoutTier::ALL + .iter() + .flat_map(|t| sealed.heldouts.tier(*t)) + .all(|ex| alt.run(ex.input[0]) & mask == cand.run(ex.input[0]) & mask) + }) + } else { + None + }; + + SealedEvaluation { + class, + verdict, + visible_matches, + visible_total: values.len() as u32, + interpolation: tiers[0], + extrapolation: tiers[1], + adversarial: tiers[2], + underdetermined: !sealed.alternatives.is_empty(), + ambiguity_recognized: if insufficient { + Some(learner_hypotheses >= 2) + } else { + None + }, + matches_alternative: matches_alternative.map(|i| i as u32), + learner_hypotheses, + robust_submission, + crumb_digest: visible.digest(), + sealed_digest: sealed.digest(), + generator_instance_digest: sealed.generator_instance_digest, + program_digest: cand.digest(), + visible_set_digest: visible.visible_set_digest(), + heldout_set_digest: sealed.heldouts.digest(), + verifier_digest: verifier_digest(), + program_steps: cand.len() as u32, + evaluation_ops: ops, + } +} diff --git a/crates/crumbs/src/visible.rs b/crates/crumbs/src/visible.rs new file mode 100644 index 00000000..e6951078 --- /dev/null +++ b/crates/crumbs/src/visible.rs @@ -0,0 +1,340 @@ +//! Crumb v1 learner-visible contract. +//! +//! The visible side is an ordered list of opaque `INPUT_BYTES -> OUTPUT_BYTES` +//! examples plus the minimum structure needed to parse them. It has no field +//! that could carry a name, topic, family, difficulty, population, decoy flag, +//! provenance, explanation, solution or held-out example. +//! +//! Canonical bytes (little-endian): +//! +//! ```text +//! "CRB1" magic +//! schema_version u16 = 1 +//! encoding u8 1 = decimal UTF-8 lanes, 2 = raw little-endian lanes +//! flags u8 bit0 = budget present; other bits must be 0 +//! in_arity u8 lanes per input (1..=8) +//! out_arity u8 lanes per output (1..=8) +//! in_lane_bytes u8 raw: 1,2,4,8; decimal: 0 +//! out_lane_bytes u8 raw: 1,2,4,8; decimal: 0 +//! n u32 examples (1..=64) +//! n x (u32 len, input bytes, u32 len, output bytes) +//! [max_candidates u32, max_depth u32, max_oracle_queries u32, max_program_ops u32] +//! ``` +//! +//! Decimal lanes are canonical base-10 u64 values (no sign, no leading zeros) +//! separated by one ASCII space. `CrumbDigest` = BLAKE3 over exactly these +//! bytes, so it covers the schema version and nothing else. + +use crate::canon::{Dec, DecodeError, Enc}; +use crate::digest::{digest, CrumbDigest, Digest, Domain}; + +pub const MAGIC: &[u8; 4] = b"CRB1"; +pub const SCHEMA_VERSION: u16 = 1; +pub const MAX_ARITY: u8 = 8; +pub const MAX_EXAMPLES: usize = 64; +const FLAG_BUDGET: u8 = 1; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum Encoding { + DecimalUtf8 = 1, + RawLe = 2, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +pub struct Budget { + pub max_candidates: u32, + pub max_depth: u32, + pub max_oracle_queries: u32, + pub max_program_ops: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Example { + pub input: Vec<u8>, + pub output: Vec<u8>, +} + +/// The only problem representation a learner may receive. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VisibleCrumb { + pub encoding: Encoding, + pub in_arity: u8, + pub out_arity: u8, + pub in_lane_bytes: u8, + pub out_lane_bytes: u8, + pub examples: Vec<Example>, + pub budget: Option<Budget>, +} + +/// Visible-side errors are bare codes: they cannot carry crumb content. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VisibleError { + Magic, + Version, + Shape, + Lane, + Length, + NonCanonical, +} + +impl std::fmt::Display for VisibleError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "visible crumb rejected: {self:?}") + } +} + +impl std::error::Error for VisibleError {} + +impl From<DecodeError> for VisibleError { + fn from(_: DecodeError) -> Self { + VisibleError::Length + } +} + +fn lane_bytes_ok(encoding: Encoding, b: u8) -> bool { + match encoding { + Encoding::DecimalUtf8 => b == 0, + Encoding::RawLe => matches!(b, 1 | 2 | 4 | 8), + } +} + +pub fn lane_mask(lane_bytes: u8) -> u64 { + if lane_bytes == 0 || lane_bytes >= 8 { + u64::MAX + } else { + (1u64 << (8 * lane_bytes as u32)) - 1 + } +} + +/// Encode lane values into example bytes. +pub fn encode_lanes(encoding: Encoding, lane_bytes: u8, lanes: &[u64]) -> Vec<u8> { + match encoding { + Encoding::DecimalUtf8 => lanes + .iter() + .map(|v| v.to_string()) + .collect::<Vec<_>>() + .join(" ") + .into_bytes(), + Encoding::RawLe => { + let mut out = Vec::with_capacity(lanes.len() * lane_bytes as usize); + for v in lanes { + out.extend_from_slice(&v.to_le_bytes()[..lane_bytes as usize]); + } + out + } + } +} + +/// Strictly parse example bytes into lane values. +pub fn decode_lanes( + encoding: Encoding, + lane_bytes: u8, + arity: u8, + bytes: &[u8], +) -> Result<Vec<u64>, VisibleError> { + match encoding { + Encoding::DecimalUtf8 => { + let text = std::str::from_utf8(bytes).map_err(|_| VisibleError::Lane)?; + let parts: Vec<&str> = text.split(' ').collect(); + if parts.len() != arity as usize { + return Err(VisibleError::Lane); + } + let mut out = Vec::with_capacity(parts.len()); + for p in parts { + if p.is_empty() + || !p.bytes().all(|c| c.is_ascii_digit()) + || (p.len() > 1 && p.starts_with('0')) + { + return Err(VisibleError::NonCanonical); + } + out.push(p.parse::<u64>().map_err(|_| VisibleError::Lane)?); + } + Ok(out) + } + Encoding::RawLe => { + let lb = lane_bytes as usize; + if bytes.len() != lb * arity as usize { + return Err(VisibleError::Lane); + } + Ok(bytes + .chunks(lb) + .map(|c| { + let mut b = [0u8; 8]; + b[..lb].copy_from_slice(c); + u64::from_le_bytes(b) + }) + .collect()) + } + } +} + +impl VisibleCrumb { + /// Build a crumb from lane values; values are masked to the lane width. + pub fn from_values( + encoding: Encoding, + in_lane_bytes: u8, + out_lane_bytes: u8, + pairs: &[(Vec<u64>, Vec<u64>)], + budget: Option<Budget>, + ) -> Result<Self, VisibleError> { + if pairs.is_empty() || pairs.len() > MAX_EXAMPLES { + return Err(VisibleError::Length); + } + let in_arity = pairs[0].0.len(); + let out_arity = pairs[0].1.len(); + if in_arity == 0 + || out_arity == 0 + || in_arity > MAX_ARITY as usize + || out_arity > MAX_ARITY as usize + { + return Err(VisibleError::Shape); + } + if !lane_bytes_ok(encoding, in_lane_bytes) || !lane_bytes_ok(encoding, out_lane_bytes) { + return Err(VisibleError::Shape); + } + let (im, om) = (lane_mask(in_lane_bytes), lane_mask(out_lane_bytes)); + let mut examples = Vec::with_capacity(pairs.len()); + for (i, o) in pairs { + if i.len() != in_arity || o.len() != out_arity { + return Err(VisibleError::Shape); + } + let i: Vec<u64> = i.iter().map(|v| v & im).collect(); + let o: Vec<u64> = o.iter().map(|v| v & om).collect(); + examples.push(Example { + input: encode_lanes(encoding, in_lane_bytes, &i), + output: encode_lanes(encoding, out_lane_bytes, &o), + }); + } + Ok(VisibleCrumb { + encoding, + in_arity: in_arity as u8, + out_arity: out_arity as u8, + in_lane_bytes, + out_lane_bytes, + examples, + budget, + }) + } + + pub fn to_bytes(&self) -> Vec<u8> { + let mut e = Enc::new(); + e.bytes(MAGIC).u16(SCHEMA_VERSION).u8(self.encoding as u8); + e.u8(if self.budget.is_some() { + FLAG_BUDGET + } else { + 0 + }); + e.u8(self.in_arity) + .u8(self.out_arity) + .u8(self.in_lane_bytes) + .u8(self.out_lane_bytes); + e.u32(self.examples.len() as u32); + for ex in &self.examples { + e.blob(&ex.input).blob(&ex.output); + } + if let Some(b) = &self.budget { + e.u32(b.max_candidates) + .u32(b.max_depth) + .u32(b.max_oracle_queries) + .u32(b.max_program_ops); + } + e.finish() + } + + /// Strict decode: the bytes must be exactly what `to_bytes` would produce. + pub fn from_bytes(bytes: &[u8]) -> Result<Self, VisibleError> { + let mut d = Dec::new(bytes); + if d.take(4)? != MAGIC { + return Err(VisibleError::Magic); + } + if d.u16()? != SCHEMA_VERSION { + return Err(VisibleError::Version); + } + let encoding = match d.u8()? { + 1 => Encoding::DecimalUtf8, + 2 => Encoding::RawLe, + _ => return Err(VisibleError::Shape), + }; + let flags = d.u8()?; + if flags & !FLAG_BUDGET != 0 { + return Err(VisibleError::NonCanonical); + } + let (in_arity, out_arity, in_lb, out_lb) = (d.u8()?, d.u8()?, d.u8()?, d.u8()?); + if !(1..=MAX_ARITY).contains(&in_arity) || !(1..=MAX_ARITY).contains(&out_arity) { + return Err(VisibleError::Shape); + } + if !lane_bytes_ok(encoding, in_lb) || !lane_bytes_ok(encoding, out_lb) { + return Err(VisibleError::Shape); + } + let n = d.u32()? as usize; + if n == 0 || n > MAX_EXAMPLES { + return Err(VisibleError::Length); + } + let mut examples = Vec::with_capacity(n); + for _ in 0..n { + let input = d.blob(8 * 21)?.to_vec(); + let output = d.blob(8 * 21)?.to_vec(); + decode_lanes(encoding, in_lb, in_arity, &input)?; + decode_lanes(encoding, out_lb, out_arity, &output)?; + examples.push(Example { input, output }); + } + let budget = if flags & FLAG_BUDGET != 0 { + Some(Budget { + max_candidates: d.u32()?, + max_depth: d.u32()?, + max_oracle_queries: d.u32()?, + max_program_ops: d.u32()?, + }) + } else { + None + }; + d.finish()?; + let c = VisibleCrumb { + encoding, + in_arity, + out_arity, + in_lane_bytes: in_lb, + out_lane_bytes: out_lb, + examples, + budget, + }; + if c.to_bytes() != bytes { + return Err(VisibleError::NonCanonical); + } + Ok(c) + } + + pub fn digest(&self) -> CrumbDigest { + digest(Domain::CrumbDigest, &self.to_bytes()) + } + + /// Digest of the example list alone (the "visible-set digest" in evidence). + pub fn visible_set_digest(&self) -> Digest { + let mut e = Enc::new(); + e.u32(self.examples.len() as u32); + for ex in &self.examples { + e.blob(&ex.input).blob(&ex.output); + } + digest(Domain::VisibleSet, &e.finish()) + } + + /// Parsed lane values of every example. + pub fn values(&self) -> Vec<(Vec<u64>, Vec<u64>)> { + self.examples + .iter() + .map(|ex| { + ( + decode_lanes(self.encoding, self.in_lane_bytes, self.in_arity, &ex.input) + .expect("validated"), + decode_lanes( + self.encoding, + self.out_lane_bytes, + self.out_arity, + &ex.output, + ) + .expect("validated"), + ) + }) + .collect() + } +} diff --git a/crates/crumbs/tests/boundary.rs b/crates/crumbs/tests/boundary.rs new file mode 100644 index 00000000..10f1e6f7 --- /dev/null +++ b/crates/crumbs/tests/boundary.rs @@ -0,0 +1,332 @@ +//! BREADCRUMB-1 and security gates: CRUMB_V1_FORMAT_PASS, SEALED_BOUNDARY_PASS, +//! CRUMB_DETERMINISM_PASS (golden), and the leak tests over serialization, +//! Debug/Display, errors, protocol transcripts, traces and training samples. + +use crumbs::audit::{find_labels, find_needles, sealed_needles}; +use crumbs::digest::Digest; +use crumbs::gen::{self, registry}; +use crumbs::protocol::{LearnerProcess, SearchConfig}; +use crumbs::verify::{evaluate, Verdict}; +use crumbs::visible::{Encoding, VisibleCrumb, VisibleError}; + +const PROBE: &str = env!("CARGO_BIN_EXE_crumbs-probe-learner"); + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("crumbs-test-{}-{name}", std::process::id())); + let _ = std::fs::remove_file(&d); + d.to_string_lossy().into_owned() +} + +#[test] +fn crumb_v1_format_pass() { + let pairs = vec![ + (vec![1u64], vec![3u64]), + (vec![2], vec![5]), + (vec![10], vec![21]), + ]; + let c = VisibleCrumb::from_values(Encoding::DecimalUtf8, 0, 0, &pairs, None).unwrap(); + let b = c.to_bytes(); + assert_eq!(&b[..4], b"CRB1"); + assert_eq!(VisibleCrumb::from_bytes(&b).unwrap(), c); + // The digest is BLAKE3 over exactly these bytes and nothing else. + assert_eq!( + c.digest(), + crumbs::digest::digest(crumbs::digest::Domain::CrumbDigest, &b) + ); + // Any byte change changes identity; a sealed label cannot influence it. + let c2 = VisibleCrumb::from_values( + Encoding::DecimalUtf8, + 0, + 0, + &[(vec![1], vec![3]), (vec![2], vec![5]), (vec![10], vec![22])], + None, + ) + .unwrap(); + assert_ne!(c.digest(), c2.digest()); + + // Strict decoding. + let mut bad = b.clone(); + bad[0] = b'X'; + assert_eq!(VisibleCrumb::from_bytes(&bad), Err(VisibleError::Magic)); + let mut bad = b.clone(); + bad[4] = 2; + assert_eq!(VisibleCrumb::from_bytes(&bad), Err(VisibleError::Version)); + let mut bad = b.clone(); + bad.push(0); + assert!( + VisibleCrumb::from_bytes(&bad).is_err(), + "trailing byte accepted" + ); + let mut bad = b.clone(); + bad[7] = 0x80; + assert!( + VisibleCrumb::from_bytes(&bad).is_err(), + "unknown flag accepted" + ); + // Non-canonical decimal ("03" instead of "3") is rejected. + let text = String::from_utf8_lossy(&b).to_string(); + assert!(text.contains('3')); + let mut e = crumbs::canon::Enc::new(); + e.bytes(b"CRB1") + .u16(1) + .u8(1) + .u8(0) + .u8(1) + .u8(1) + .u8(0) + .u8(0) + .u32(1) + .blob(b"1") + .blob(b"03"); + assert_eq!( + VisibleCrumb::from_bytes(&e.finish()), + Err(VisibleError::NonCanonical) + ); + + // Raw little-endian encoding round-trips and masks to the lane width. + let r = VisibleCrumb::from_values( + Encoding::RawLe, + 2, + 1, + &[(vec![0x1_0005], vec![0x1FF])], + None, + ) + .unwrap(); + assert_eq!(r.values(), vec![(vec![5], vec![0xFF])]); + assert_eq!(VisibleCrumb::from_bytes(&r.to_bytes()).unwrap(), r); +} + +/// Golden identities: any behavioural change to a generator or to the +/// canonical encodings without a version bump fails here. +#[test] +fn crumb_determinism_golden_pass() { + let reg = registry(); + let mut acc = blake3::Hasher::new(); + for f in ®.families { + for seed in [0u64, 1, 99] { + let g = gen::generate(f, seed); + acc.update(&g.visible.digest().0); + acc.update(&g.sealed.digest().0); + acc.update(&g.sealed.generator_instance_digest.0); + } + } + let got = Digest(*acc.finalize().as_bytes()).hex(); + let golden = include_str!("golden_registry_digest.txt").trim(); + assert_eq!( + got, golden, + "generator output drifted; bump GENERATOR_VERSION and re-pin" + ); +} + +#[test] +fn sealed_boundary_pass_visible_bytes() { + for f in ®istry().families { + for seed in [0u64, 5, 11] { + let g = gen::generate(f, seed); + let bytes = g.visible.to_bytes(); + let hits = find_labels(&bytes); + assert!( + hits.is_empty(), + "{}: labels in visible bytes: {hits:?}", + f.key + ); + let needles = sealed_needles(&g.sealed, &g.visible.values(), 1 << 32); + let hits: Vec<String> = needles + .iter() + .filter(|n| crumbs::audit::contains(&bytes, n)) + .map(|n| String::from_utf8(n.clone()).unwrap_or_else(|_| format!("{n:?}"))) + .collect(); + assert!( + hits.is_empty(), + "{} seed {seed}: sealed value in visible bytes: {hits:?} in {:?}", + f.key, + String::from_utf8_lossy(&bytes) + ); + // Sealed digests appear nowhere in the visible crumb. + for d in [ + g.sealed.digest(), + g.sealed.generator_instance_digest, + g.sealed.heldouts.digest(), + ] { + assert!(!crumbs::audit::contains(&bytes, &d.0)); + } + } + } +} + +#[test] +fn sealed_boundary_pass_debug_display_errors() { + let f = registry().by_key("decoy-simple-rule-w12").unwrap(); + let g = gen::generate(f, 3); + for s in [ + format!("{:?}", g.sealed), + format!("{:?}", g.sealed.heldouts), + format!("{:?}", g.sealed.heldouts.adversarial.first().unwrap()), + ] { + assert!( + find_labels(s.as_bytes()).is_empty(), + "Debug leaked labels: {s}" + ); + for ex in g.sealed.heldouts.adversarial.iter() { + assert!( + !s.contains(&ex.output[0].to_string()) || ex.output[0] < 1000, + "Debug leaked a held-out value: {s}" + ); + } + assert!(s.contains("redacted")); + } + // Error types carry no content. + for e in [ + VisibleError::Magic, + VisibleError::Version, + VisibleError::Shape, + VisibleError::Lane, + VisibleError::Length, + VisibleError::NonCanonical, + ] { + let s = e.to_string(); + assert!(find_labels(s.as_bytes()).is_empty()); + assert!(s.len() < 64); + } + let pe = crumbs::protocol::ProtocolError::Violation.to_string(); + assert!(find_labels(pe.as_bytes()).is_empty()); + let de = crumbs::canon::DecodeError.to_string(); + assert!(find_labels(de.as_bytes()).is_empty()); +} + +type ProbeRun = ( + Result<Vec<(u8, Verdict)>, String>, + Vec<u8>, + Vec<u8>, + Vec<Vec<u8>>, +); + +fn run_probe(mode: &str, fam: &str, seed: u64, max_q: u32) -> ProbeRun { + let loot = tmp(&format!("{mode}-{fam}-{seed}")); + let mut lp = LearnerProcess::spawn(PROBE, &[mode, &loot], true).unwrap(); + let cfg = SearchConfig { + max_oracle_queries: max_q, + ..SearchConfig::default() + }; + lp.hello(&cfg, false).unwrap(); + let f = registry().by_key(fam).unwrap(); + let g = gen::generate(f, seed); + let mut verdicts = Vec::new(); + let mut n = 0u32; + let res = lp.run_crumb(&g.visible, &mut |sub| { + n += 1; + if n > max_q { + return Verdict::BudgetExhausted; + } + let ev = evaluate(&g.visible, &g.sealed, &sub.program, sub.hypotheses, false); + verdicts.push((sub.hypotheses, ev.verdict)); + ev.verdict + }); + let transcript = lp.transcript.clone().unwrap(); + let out = match res { + Ok(_) => { + let _ = lp.shutdown(); + Ok(verdicts) + } + Err(e) => { + lp.kill(); + Err(e.to_string()) + } + }; + let needles = sealed_needles(&g.sealed, &g.visible.values(), 0); + let loot_bytes = std::fs::read(&loot).unwrap_or_default(); + (out, transcript, loot_bytes, needles) +} + +/// Everything sent to a learner is sterile: no labels, no digests, no held-out values. +#[test] +fn sealed_boundary_pass_protocol_transcript() { + for (fam, seed) in [ + ("chain-basic-l2-w16", 1u64), + ("decoy-simple-rule-w12", 2), + ("insufficient-evidence-n2", 3), + ("capability-03", 4), + ] { + let (res, transcript, loot, needles) = run_probe("honest", fam, seed, 4); + res.unwrap(); + // The learner received exactly the transcript, then the shutdown frame. + assert_eq!(loot, [transcript.clone(), vec![0x05, 0, 0, 0, 0]].concat()); + assert!( + find_labels(&transcript).is_empty(), + "{fam}: labels in transcript" + ); + // Held-out values that are not also visible never cross the boundary. + let vis = gen::generate(registry().by_key(fam).unwrap(), seed) + .visible + .to_bytes(); + let leaked: Vec<_> = needles + .iter() + .filter(|n| { + n.len() >= 8 + && crumbs::audit::contains(&transcript, n) + && !crumbs::audit::contains(&vis, n) + }) + .collect(); + assert!(leaked.is_empty(), "{fam}: sealed bytes in transcript"); + } +} + +/// Negative test: a learner that asks for held-out data through the protocol +/// gets nothing. The session aborts on the forged frame and no reply is sent. +#[test] +fn no_hidden_access_hostile_learner() { + let (res, transcript, loot, needles) = run_probe("hostile", "decoy-simple-rule-w12", 9, 4); + assert!(res.is_err(), "a forged frame must abort the session"); + // The learner received HELLO and CRUMB only. + let mut kinds = Vec::new(); + let mut i = 0; + while i + 5 <= loot.len() { + kinds.push(loot[i]); + let n = u32::from_le_bytes(loot[i + 1..i + 5].try_into().unwrap()) as usize; + i += 5 + n; + } + assert_eq!( + kinds, + vec![0x01, 0x02], + "learner received more than HELLO and CRUMB" + ); + assert_eq!(transcript, loot); + assert_eq!( + find_needles( + &loot, + &needles + .into_iter() + .filter(|n| n.len() >= 32) + .collect::<Vec<_>>() + ), + 0 + ); +} + +/// Negative test: the oracle cannot be mined. After the query budget every +/// answer is "budget exhausted", and every answer is a single byte. +#[test] +fn no_hidden_access_oracle_budget() { + let (res, _transcript, loot, _) = run_probe("flood", "chain-basic-l3-w16", 12, 3); + let verdicts = res.unwrap(); + assert!( + verdicts.len() <= 3, + "the sealed evaluator ran more than the budget" + ); + let mut i = 0; + let mut vbytes = Vec::new(); + while i + 5 <= loot.len() { + let t = loot[i]; + let n = u32::from_le_bytes(loot[i + 1..i + 5].try_into().unwrap()) as usize; + if t == 0x03 { + assert_eq!(n, 1, "a verdict frame carried more than one byte"); + vbytes.push(loot[i + 5]); + } + i += 5 + n; + } + assert!(vbytes.iter().all(|b| (1..=3).contains(b))); + assert!( + vbytes.iter().skip(3).all(|b| *b == 3), + "answers after the budget must be 'exhausted'" + ); +} diff --git a/crates/crumbs/tests/curriculum.rs b/crates/crumbs/tests/curriculum.rs new file mode 100644 index 00000000..1a28e42e --- /dev/null +++ b/crates/crumbs/tests/curriculum.rs @@ -0,0 +1,328 @@ +//! CRUMB_CURRICULUM_PASS, CRUMB_NO_CATEGORY_LEAK_PASS, CLEAN_ROOM_PROVENANCE_PASS, +//! CRUMB_OPERATION_PROMOTION_PASS (ladder unit), ledger chain, and the trace +//! corpus gates that do not need a real learner (CRUMB_TRACE_PASS, +//! CRUMB_TRAINING_SAMPLE_PASS, NO_COT_STORAGE_PASS with the probe learner). + +use crumbs::audit::find_labels; +use crumbs::digest::{CrumbOccurrenceId, Digest}; +use crumbs::gen::{self, registry}; +use crumbs::ledger::{CrumblineRecord, Ledger, LedgerError}; +use crumbs::mixer::{Mixer, MixerConfig}; +use crumbs::program::{Op, Program}; +use crumbs::promotion::{Ladder, PromotionConfig, Stage}; +use crumbs::provenance::{ + clean_room_check, CleanRoomViolation, ContaminationClass, Lane, Provenance, +}; +use crumbs::sealed::Population; +use crumbs::session::{Session, SessionConfig}; +use crumbs::trace::{self, verify_chain, SAMPLE_RECORD_BYTES, TRACE_RECORD_BYTES}; +use crumbs::verify::evaluate; +use std::collections::BTreeMap; + +const PROBE: &str = env!("CARGO_BIN_EXE_crumbs-probe-learner"); + +#[test] +fn crumb_curriculum_pass() { + // The v1 schedule is data: it loads from the shipped config file. + let cfg = + MixerConfig::from_json(include_str!("../config/mixer.v1.json")).expect("config parses"); + assert_eq!(cfg, MixerConfig::default()); + let w: Vec<u32> = Population::ALL.iter().map(|p| cfg.populations[p]).collect(); + assert_eq!(w, vec![55, 20, 10, 10, 5]); + + let mut m = Mixer::new(cfg.clone(), 7); + let mut counts: BTreeMap<Population, u32> = BTreeMap::new(); + let mut last: Option<u32> = None; + for _ in 0..3000 { + let d = m.draw(); + *counts.entry(d.population).or_insert(0) += 1; + assert_ne!( + Some(d.family_id), + last, + "the same family was drawn twice in a row" + ); + last = Some(d.family_id); + } + // No frontier sources exist in v1: its share is redistributed and recorded. + assert!( + m.redistributed_draws + .get(&Population::Frontier) + .copied() + .unwrap_or(0) + > 0 + ); + let fund = counts[&Population::Fundamental] as f64 / 3000.0; + assert!((0.45..0.75).contains(&fund), "fundamental share {fund}"); + + // Adaptation: demonstrating capabilities moves weight to composition. + let before = m.weights(); + for f in registry() + .families + .iter() + .filter(|f| f.params.caps.len() == 1) + { + m.record(f, true); + } + let after = m.weights(); + assert!(after[&Population::Fundamental] < before[&Population::Fundamental]); + assert!(after[&Population::Composition] > before[&Population::Composition]); + + // Determinism: same seed, same draws. + let (mut a, mut b) = (Mixer::new(cfg.clone(), 42), Mixer::new(cfg, 42)); + for _ in 0..200 { + let (x, y) = (a.draw(), b.draw()); + assert_eq!((x.family_id, x.seed), (y.family_id, y.seed)); + } +} + +/// Curriculum order carries no ontology: the learner-visible stream of a long +/// run contains no population, family or label bytes, and consecutive draws +/// never share a family or a capability. +#[test] +fn crumb_no_category_leak_pass() { + let mut m = Mixer::new(MixerConfig::default(), 3); + let mut stream = Vec::new(); + let mut prev_caps: Vec<u16> = vec![]; + for _ in 0..500 { + let d = m.draw(); + let f = registry().get(d.family_id).unwrap(); + assert!( + prev_caps.iter().all(|c| !f.params.caps.contains(c)), + "consecutive crumbs share a capability" + ); + prev_caps = f.params.caps.clone(); + stream.extend(gen::generate(f, d.seed).visible.to_bytes()); + } + assert!(find_labels(&stream).is_empty()); +} + +#[test] +fn clean_room_provenance_pass() { + // Every registered family declares a contamination class. + for f in ®istry().families { + let _ = f.provenance.class; + } + // The forbidden list. + assert_eq!( + clean_room_check(&Provenance::human_theory()), + Err(CleanRoomViolation::HumanTheoryDerived) + ); + for (class, want) in [ + ( + ContaminationClass::FrontierDerived, + CleanRoomViolation::FrontierDerived, + ), + ( + ContaminationClass::RealWorldMeasured, + CleanRoomViolation::RealWorldMeasured, + ), + ] { + let p = Provenance { + class, + uses_human_constants: false, + uses_human_ontology: false, + }; + assert_eq!(clean_room_check(&p), Err(want)); + } + let consts = Provenance { + uses_human_constants: true, + ..Provenance::synthetic() + }; + assert_eq!( + clean_room_check(&consts), + Err(CleanRoomViolation::HumanConstants) + ); + let onto = Provenance { + uses_human_ontology: true, + ..Provenance::synthetic() + }; + assert_eq!( + clean_room_check(&onto), + Err(CleanRoomViolation::HumanOntology) + ); + assert!(clean_room_check(&Provenance::synthetic()).is_ok()); + assert!(clean_room_check(&Provenance::adversarial()).is_ok()); + + // The clean-room ledger partition refuses forbidden records outright. + let mut clean = Ledger::new(Lane::CleanRoom, "t"); + let rec = |seq| CrumblineRecord { + seq, + lane: Lane::Main, + occurrence: CrumbOccurrenceId::new(), + condition: "t".into(), + population: Population::Fundamental, + crumb_digest: Digest::ZERO, + generator_instance_digest: Digest::ZERO, + sealed_digest: Digest::ZERO, + verifier_digest: Digest::ZERO, + learner_digest: Digest::ZERO, + evaluations: vec![], + trace_stream_digest: Digest::ZERO, + promotions: vec![], + prev_root: Digest::ZERO, + root: Digest::ZERO, + }; + assert_eq!( + clean.append(rec(0), &Provenance::human_theory()), + Err(LedgerError::CleanRoom( + CleanRoomViolation::HumanTheoryDerived + )) + ); + assert!(clean.append(rec(0), &Provenance::synthetic()).is_ok()); + assert_eq!(clean.records[0].lane, Lane::CleanRoom); + + // A clean-room mixer never draws a forbidden family. + let mut m = Mixer::new( + MixerConfig { + clean_room: true, + ..MixerConfig::default() + }, + 11, + ); + for _ in 0..1000 { + let f = registry().get(m.draw().family_id).unwrap(); + assert!( + clean_room_check(&f.provenance).is_ok(), + "{} entered the clean room", + f.key + ); + } + // Contamination classes never appear in learner bytes (checked for every family in boundary.rs). +} + +#[test] +fn ledger_chain_detects_tampering() { + let mut l = Ledger::new(Lane::Main, "run"); + for s in 0..5 { + let r = CrumblineRecord { + seq: s, + lane: Lane::Main, + occurrence: CrumbOccurrenceId::new(), + condition: "c".into(), + population: Population::Composition, + crumb_digest: Digest([s as u8; 32]), + generator_instance_digest: Digest::ZERO, + sealed_digest: Digest::ZERO, + verifier_digest: Digest::ZERO, + learner_digest: Digest::ZERO, + evaluations: vec![], + trace_stream_digest: Digest::ZERO, + promotions: vec![], + prev_root: Digest::ZERO, + root: Digest::ZERO, + }; + l.append(r, &Provenance::synthetic()).unwrap(); + } + assert_eq!(Ledger::verify(l.genesis, &l.records), Ok(l.head)); + let mut forged = l.records.clone(); + forged[2].crumb_digest = Digest([9; 32]); + assert_eq!(Ledger::verify(l.genesis, &forged), Err(LedgerError::Chain)); +} + +/// One solved crumb never admits an operation; two distinct supporting crumbs +/// with adversarial and extrapolation evidence do, with an explicit scope. +#[test] +fn crumb_operation_promotion_pass() { + let fam = registry().by_key("capability-03").unwrap(); + let mut ladder = Ladder::new(PromotionConfig::default()); + let g1 = gen::generate(fam, 1); + let crumbs::sealed::KnownSolution::Known(truth) = g1.sealed.known_solution.clone() else { + panic!() + }; + let e1 = evaluate(&g1.visible, &g1.sealed, &truth, 1, false); + ladder.observe_accept(0, &g1.sealed, &e1, &truth); + assert!( + ladder.advance(0).is_empty(), + "one crumb must not admit anything" + ); + let rec = ladder.ops.values().next().unwrap(); + assert_eq!(rec.stage, Stage::HeldoutVerified); + // The same crumb again is not new evidence. + ladder.observe_accept(1, &g1.sealed, &e1, &truth); + assert!(ladder.advance(1).is_empty()); + let g2 = gen::generate(fam, 2); + let e2 = evaluate(&g2.visible, &g2.sealed, &truth, 1, false); + ladder.observe_accept(2, &g2.sealed, &e2, &truth); + let adm = ladder.advance(2); + assert_eq!(adm.len(), 1); + assert_eq!(adm[0].program, truth); + assert!(adm[0].scope_bits > 0 && adm[0].scope_bits <= 64); + let rec = ladder.by_ref(adm[0].op_ref).unwrap(); + let stages: Vec<Stage> = rec.history.iter().map(|h| h.0).collect(); + assert_eq!( + stages, + vec![ + Stage::Candidate, + Stage::HeldoutVerified, + Stage::Corroborated, + Stage::SurvivedAdversarial, + Stage::Generalized, + Stage::Admitted + ] + ); + // Too many held-out-falsified exposures suspend a candidate instead of promoting it. + let mut l2 = Ladder::new(PromotionConfig { + max_exposure_pct: 50, + ..PromotionConfig::default() + }); + let decoy = gen::generate(registry().by_key("decoy-simple-rule-w12").unwrap(), 4); + let alt = decoy.sealed.alternatives[0].clone(); + let ea = evaluate(&decoy.visible, &decoy.sealed, &alt, 1, false); + let gcap = gen::generate(registry().by_key("chain-basic-l2-w16").unwrap(), 5); + let crumbs::sealed::KnownSolution::Known(cap) = gcap.sealed.known_solution.clone() else { + panic!() + }; + let _ = Program::of(&[(Op::Mul, 2)]); + let ec = evaluate(&gcap.visible, &gcap.sealed, &cap, 1, false); + l2.observe_accept(0, &gcap.sealed, &ec, &cap); + l2.observe_reject(&ea, &cap); + l2.observe_reject(&ea, &cap); + assert!(l2.advance(1).is_empty()); + assert_eq!( + l2.ops[&cap.behavior()].stage, + Stage::Suspended, + "exposed operation must be suspended, not promoted" + ); + let _ = alt; +} + +/// Trace corpus through a real (probe) learner session: chained records, +/// numbers only, hidden results only on SUBMIT records, samples on solved crumbs. +#[test] +fn crumb_trace_and_sample_pass() { + let dir = std::env::temp_dir().join(format!("crumbs-trace-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let cfg = SessionConfig { + condition: "test".into(), + learner: PROBE.into(), + run_id: "trace-test".into(), + search: Default::default(), + library_enabled: false, + promotion: PromotionConfig::default(), + record_transcript: false, + out_dir: Some(dir.clone()), + }; + // The probe reports no search events; the trace still records its submissions. + let mut s = Session::start(cfg).unwrap(); + let fam = registry().by_key("chain-basic-l1-w16").unwrap(); + let o = s.present(fam, 3, Population::Fundamental, "t").unwrap(); + assert!(o.accepted); + s.finish().unwrap(); + let tr = std::fs::read(dir.join("trace.ctr")).unwrap(); + let smp = std::fs::read(dir.join("samples.cts")).unwrap_or_default(); + assert_eq!(tr.len() % TRACE_RECORD_BYTES, 0); + assert_eq!(smp.len() % SAMPLE_RECORD_BYTES, 0); + assert!(verify_chain(&tr, TRACE_RECORD_BYTES, crumbs::digest::Domain::TraceRecord).is_some()); + let mut tampered = tr.clone(); + if !tampered.is_empty() { + tampered[40] ^= 1; + assert!(verify_chain( + &tampered, + TRACE_RECORD_BYTES, + crumbs::digest::Domain::TraceRecord + ) + .is_none()); + } + assert!(find_labels(&tr).is_empty() && find_labels(&smp).is_empty()); + let _ = trace::bank_digest(&[]); +} diff --git a/crates/crumbs/tests/generators.rs b/crates/crumbs/tests/generators.rs new file mode 100644 index 00000000..4728f32c --- /dev/null +++ b/crates/crumbs/tests/generators.rs @@ -0,0 +1,195 @@ +//! BREADCRUMB-2 gates: CRUMB_GENERATORS_PASS, CRUMB_ADVERSARIAL_PASS, CRUMB_AMBIGUITY_PASS. + +use crumbs::gen::{self, registry, Mechanism}; +use crumbs::sealed::{AdversarialClass, DecoyStatus, HeldoutTier, KnownSolution, Rung}; +use crumbs::verify::{evaluate, EvalClass}; +use std::collections::HashSet; + +const SEEDS: [u64; 6] = [0, 1, 2, 3, 17, 1_000_003]; + +#[test] +fn crumb_generators_pass() { + let reg = registry(); + assert!( + reg.families.len() >= 100, + "registered families: {}", + reg.families.len() + ); + let mechs: HashSet<_> = reg.families.iter().map(|f| f.mechanism).collect(); + assert!(mechs.len() >= 24, "distinct mechanisms: {}", mechs.len()); + assert_eq!( + mechs.len(), + Mechanism::ALL.len(), + "every mechanism is registered" + ); + let rungs: HashSet<_> = reg.families.iter().map(|f| f.rung).collect(); + for r in Rung::ALL { + assert!(rungs.contains(&r), "rung {r:?} has no family"); + } + let keys: HashSet<_> = reg.families.iter().map(|f| f.key.clone()).collect(); + assert_eq!(keys.len(), reg.families.len(), "family keys unique"); + + for fam in ®.families { + for seed in SEEDS { + let g = gen::generate(fam, seed); + let bytes = g.visible.to_bytes(); + let back = + crumbs::visible::VisibleCrumb::from_bytes(&bytes).expect("visible round-trips"); + assert_eq!(back, g.visible); + assert_eq!(g.sealed.crumb_digest, g.visible.digest()); + assert!( + g.visible.examples.len() >= 2, + "{} has too few visible examples", + fam.key + ); + assert!( + !g.sealed.heldouts.is_empty(), + "{} has no held-outs", + fam.key + ); + + // Held-out inputs are disjoint from visible inputs and from each other. + let vis: HashSet<Vec<u64>> = g.visible.values().into_iter().map(|(i, _)| i).collect(); + let mut seen = HashSet::new(); + for t in HeldoutTier::ALL { + for ex in g.sealed.heldouts.tier(t) { + assert!( + !vis.contains(&ex.input), + "{} held-out repeats a visible input", + fam.key + ); + assert!( + seen.insert(ex.input.clone()), + "{} held-out tiers overlap", + fam.key + ); + } + } + + // A known CPG1 truth must pass the verifier. + if let KnownSolution::Known(p) = &g.sealed.known_solution { + if g.visible.out_arity == 1 { + let ev = evaluate(&g.visible, &g.sealed, p, 1, false); + assert!( + matches!( + ev.class, + EvalClass::Verified | EvalClass::AmbiguousUnderdetermined + ), + "{} seed {seed}: truth evaluated as {:?}", + fam.key, + ev.class + ); + } + } + } + } +} + +#[test] +fn crumb_determinism_pass() { + for fam in ®istry().families { + let a = gen::generate(fam, 42); + let b = gen::generate(fam, 42); + assert_eq!(a.visible.to_bytes(), b.visible.to_bytes(), "{}", fam.key); + assert_eq!(a.sealed.to_bytes(), b.sealed.to_bytes(), "{}", fam.key); + assert_eq!(a.sealed.digest(), b.sealed.digest()); + let c = gen::generate(fam, 43); + assert_ne!( + a.sealed.generator_instance_digest, + c.sealed.generator_instance_digest + ); + } +} + +/// Every rabbit hole: the alternative fits all visible examples and fails a held-out. +#[test] +fn crumb_adversarial_pass() { + let mut classes = HashSet::new(); + for fam in ®istry().families { + let DecoyStatus::RabbitHole(class) = fam.decoy else { + continue; + }; + for seed in SEEDS { + let g = gen::generate(fam, seed); + classes.insert(class); + if class == AdversarialClass::Noisy { + assert!(!g.sealed.noisy_visible.is_empty()); + let KnownSolution::Known(truth) = &g.sealed.known_solution else { + panic!() + }; + let vals = g.visible.values(); + let wrong = vals.iter().filter(|(i, o)| truth.run(i[0]) != o[0]).count(); + assert_eq!( + wrong, + g.sealed.noisy_visible.len(), + "{}: noise count", + fam.key + ); + assert!(wrong < vals.len() / 2, "truth still explains the majority"); + continue; + } + assert!( + !g.sealed.alternatives.is_empty(), + "{} seed {seed}: no alternative recorded", + fam.key + ); + for alt in &g.sealed.alternatives { + let ev = evaluate(&g.visible, &g.sealed, alt, 1, false); + assert_ne!( + ev.class, + EvalClass::FalsifiedVisible, + "{} seed {seed}: alternative must fit visible", + fam.key + ); + assert!( + matches!(ev.class, EvalClass::FalsifiedHidden), + "{} seed {seed}: held-outs must break the alternative, got {:?}", + fam.key, + ev.class + ); + } + } + } + for c in [ + AdversarialClass::SimpleWrongRule, + AdversarialClass::MultiFit, + AdversarialClass::SpuriousDimension, + AdversarialClass::PrefixDiverges, + AdversarialClass::ElegantArbitrary, + AdversarialClass::InsufficientEvidence, + AdversarialClass::Noisy, + ] { + assert!(classes.contains(&c), "class {c:?} not generated"); + } +} + +/// Insufficient-evidence crumbs carry >= 2 rival explanations, and the +/// evaluation records whether the learner recognized the ambiguity. +#[test] +fn crumb_ambiguity_pass() { + let reg = registry(); + let fams: Vec<_> = reg + .families + .iter() + .filter(|f| f.decoy == DecoyStatus::RabbitHole(AdversarialClass::InsufficientEvidence)) + .collect(); + assert!(!fams.is_empty()); + for fam in fams { + for seed in SEEDS { + let g = gen::generate(fam, seed); + assert!(g.sealed.alternatives.len() >= 2, "{} seed {seed}", fam.key); + let KnownSolution::Known(truth) = &g.sealed.known_solution else { + panic!() + }; + let lone = evaluate(&g.visible, &g.sealed, truth, 1, false); + assert_eq!(lone.class, EvalClass::AmbiguousUnderdetermined); + assert_eq!(lone.ambiguity_recognized, Some(false)); + let aware = evaluate(&g.visible, &g.sealed, truth, 3, false); + assert_eq!(aware.ambiguity_recognized, Some(true)); + } + } + let ns = reg.by_key("no-structure").unwrap(); + let g = gen::generate(ns, 5); + assert_eq!(g.sealed.decoy_status, DecoyStatus::NoStructure); + assert_eq!(g.sealed.known_solution, KnownSolution::NoCompactStructure); +} diff --git a/crates/crumbs/tests/golden_registry_digest.txt b/crates/crumbs/tests/golden_registry_digest.txt new file mode 100644 index 00000000..343e7861 --- /dev/null +++ b/crates/crumbs/tests/golden_registry_digest.txt @@ -0,0 +1 @@ +c4ee1ce4901c79ab79c10ae61fed40765a8cdbfc69c0249b7860cd468f2b0420 diff --git a/docs/archive/plans/2026-09-22/AIEN_COMPLETE_SYSTEM_ARCHITECTURE_v2.md b/docs/archive/plans/2026-09-22/AIEN_COMPLETE_SYSTEM_ARCHITECTURE_v2.md index aaafc8b7..a65da1a1 100644 --- a/docs/archive/plans/2026-09-22/AIEN_COMPLETE_SYSTEM_ARCHITECTURE_v2.md +++ b/docs/archive/plans/2026-09-22/AIEN_COMPLETE_SYSTEM_ARCHITECTURE_v2.md @@ -1,4 +1,4 @@ -> **SUPERSEDED / HISTORICAL — NOT AN ACTIVE PROJECT PLAN** +> **SUPERSEDED / HISTORICAL: NOT AN ACTIVE PROJECT PLAN** > > Archived on 2026-09-27. Whole-system architecture and sequencing now live in `aien-dev/aien-architecture`. >