diff --git a/.crumb b/.crumb index 7cbfcfdb..1f9e67ce 100644 --- a/.crumb +++ b/.crumb @@ -65,68 +65,68 @@ "children": [ { "digest": "4e7f370019e67f6c71565d1544530851eb1b3b1bed61c2712f4ac7d9614a89bf", - "last_commit": "6bbe2ec", + "last_commit": "6bbe2ec2", "name": "crates/aien-allen", "purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). " }, { "digest": "40a231c50dba92af7de2527ab33879c5d1eaaa6e7ea5d6a5ebaa9d60c7542075", - "last_commit": "b9b52f9", + "last_commit": "b9b52f9c", "name": "crates/aien-allen-memory", "purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying for" }, { "digest": "44dc482b8c9db8919a68ec69b019cd77967232a6ec8b1910c0dfe3cd4d71f141", - "last_commit": "b9b52f9", + "last_commit": "b9b52f9c", "name": "crates/aien-allen-profile", "purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; " }, { "digest": "f5571bcc0bb95b44dd8bf8f0b47ded3bcb1e1ee76c81b4ff5edb87ac237d66d8", - "last_commit": "f8eea42", + "last_commit": "f8eea420", "name": "crates/aien-cli", "purpose": "" }, { "digest": "25fd9f8afbea19702750f8ddba2ef4aeafc5bc4515aa695340a5af6931989c03", - "last_commit": "8cca802", + "last_commit": "8cca8020", "name": "crates/aien-scheduler/src/bin", "purpose": "" }, { "digest": "a0a981f6168d15e43a6b036c3aa82d44547aadfc3b6c62139a5a3afab0644514", - "last_commit": "8cca802", + "last_commit": "8cca8020", "name": "crates/spark-cockpit-rs", "purpose": "" }, { "digest": "459e0218a85fe55235bcbdf94455e069c52b77c0811063105da5bf438995b7a4", - "last_commit": "1615afb", + "last_commit": "1615afbb", "name": "scripts", "purpose": "" }, { "digest": "75e439cb2ae120e1807af894b70b6454971028f5527f56451f9d6558f503c88b", - "last_commit": "fa73e77", + "last_commit": "fa73e778", "name": "skills", "purpose": "" }, { "digest": "b95ea9baa15ce7ddc69a3ef4dc25cdcccba52ec1f5fd99e19f0f24af9181a306", - "last_commit": "247e092", + "last_commit": "247e0927", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], "children_root": "sha256:9c8f34b4f863ab4604666e780128e486c6b32d512c2f8c9342f8b26a582874d3", - "compiled_at": "2026-10-16T08:14:38Z", + "compiled_at": "2026-10-16T09:13:10Z", "compiler": "crumb-compile/1", - "digest": "sha256:2d3c31afb4fb05cbf064123c0040c48e5d684bb3e13c5c4ece4eba98ee5b82bf", - "evidence_files": 1571, - "evidence_root": "sha256:3daf70b2d921e14a5ec37662f2210a6e3b677f5e7b4ca8c723a30bf922411fad", - "files": 5869, - "generated_at_commit": "ff829a69ade15ee44f06e1905c605ec7fd29993d", - "source_tree": "sha256:2ea56307ce1636fc2314e52f6d186ebb60d11ba835e96ad4e04ee2e7b6946e19" + "digest": "sha256:b03efd466778c2c308b3c9b79ca88e6207a05b2f6cccd35beb12f7b13718d852", + "evidence_files": 1578, + "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160", + "files": 5888, + "generated_at_commit": "0deac986ea154a409ce3178ecc217653e4032562", + "source_tree": "sha256:ee32ef00cb8e8e543c80b0424275f4ff4afb37d6ebb3de8f4c38ce54377d1da1" } }, "history": [], diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1013e408..5327d73f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -203,3 +203,39 @@ jobs: - name: Headstart M6 A/B driver self-check (STUB build, overhead and correctness only) run: cargo test -p aien-runtime --features provisional-prep --test headstart_ab -- --ignored headstart_ab_smoke --test-threads=1 + + omegese-constraint: + # The Omegese guardrail (crates/aien-omegese-constraint) against the real oracle. Its real-oracle + # tests are #[ignore] in the verify job (no omegese binary there). This job builds `omegese` + # (one C file, CPU only) from omega at crates/aien-omegese-constraint/omegese.lock and runs them. + # A pin of its own, separate from the root omega.lock (the release candidate's omega commit, + # checked by scripts/check-release-candidate.sh): this one follows the Omegese grammar only. + name: Omegese guardrail against the real oracle + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v4 + + - name: Install pinned Rust toolchain (rust-toolchain.toml) + run: | + rustup toolchain install "$(sed -n 's/^channel *= *"\(.*\)"/\1/p' rust-toolchain.toml)" --profile minimal + rustc --version + + - name: Read pin (crates/aien-omegese-constraint/omegese.lock) + id: pin + run: echo "omega=$(tr -d '[:space:]' < crates/aien-omegese-constraint/omegese.lock)" >> "$GITHUB_OUTPUT" + + - name: Checkout omega at the pin + uses: actions/checkout@v4 + with: + repository: aien-spark/omega + ref: ${{ steps.pin.outputs.omega }} + path: omega + + - name: Build omegese (the flags of omega's mk/omegese.mk) + run: cc -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -o "$RUNNER_TEMP/omegese" omega/tools/omegese/omegese.c + + - name: Real-oracle walks on the host fake + env: + OMEGESE_BIN: ${{ runner.temp }}/omegese + run: cargo test -p aien-omegese-constraint --test echo_walks -- --ignored --test-threads=1 --nocapture diff --git a/Cargo.lock b/Cargo.lock index cef9d9f5..b89eff65 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -354,6 +354,14 @@ dependencies = [ "aien-omega-gpu", ] +[[package]] +name = "aien-omegese-constraint" +version = "0.1.0" +dependencies = [ + "aien-inference-abi", + "tokenizers", +] + [[package]] name = "aien-platform" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index a0b8e306..52ca9775 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,6 +56,7 @@ members = [ "crates/aien-drive", "crates/aien-serve-http", "crates/aien-kv-bench", + "crates/aien-omegese-constraint", "crates/aien-localhttp", ] diff --git a/crates/aien-omegese-constraint/Cargo.toml b/crates/aien-omegese-constraint/Cargo.toml new file mode 100644 index 00000000..c1cbb960 --- /dev/null +++ b/crates/aien-omegese-constraint/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "aien-omegese-constraint" +version = "0.1.0" +edition = "2021" +authors = ["Drake Stapleton "] +description = "The Omegese guardrail: a Constraint for the generation controller (ADR 0004 section 2.3) fed by the omegese next oracle" +license.workspace = true + +# Nothing depends on this crate by default. A consumer (the door, an experiment harness) opts in +# with an optional dependency behind its own feature; the generation controller and the 30B never +# need it (Drake's guardrail decision (a), ADR 0004). + +[dependencies] +aien-inference-abi = { path = "../aien-inference-abi" } +tokenizers = { version = "0.21", default-features = false, features = ["onig"] } + +[dev-dependencies] +aien-inference-abi = { path = "../aien-inference-abi", features = ["host-test-engine"] } diff --git a/crates/aien-omegese-constraint/omegese.lock b/crates/aien-omegese-constraint/omegese.lock new file mode 100644 index 00000000..95f0de16 --- /dev/null +++ b/crates/aien-omegese-constraint/omegese.lock @@ -0,0 +1 @@ +6c1827baa9ce0270c5ebc467bb341df8e0aed606 diff --git a/crates/aien-omegese-constraint/src/constraint.rs b/crates/aien-omegese-constraint/src/constraint.rs new file mode 100644 index 00000000..e136e0b8 --- /dev/null +++ b/crates/aien-omegese-constraint/src/constraint.rs @@ -0,0 +1,505 @@ +//! [`OmegeseConstraint`]: the chat framing (forced fence and header) and the per-step legal-token +//! mask from an [`ItemOracle`], as a [`Constraint`] for the generation controller. + +use std::collections::{HashMap, VecDeque}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use aien_inference_abi::generation::{Constraint, StepRule}; + +use crate::oracle::{Answer, ItemOracle}; +use crate::signature::Signature; +use crate::table::{Shape, TokenTable}; +use crate::word::{current_word, ItemSet}; + +/// How the reply is framed and which parts are forced or masked. Each switch is independent, so +/// an experiment can run, for example, an unmasked arm with only the forced fence. +#[derive(Debug, Clone)] +pub struct Framing { + /// Forced first (e.g. "```\n"). `None`: no fence, and `eof` maps to the stop token alone. + pub open_fence: Option, + /// Forced after the fence: the entry function's header line. + pub header: Option, + /// Mask the program with the oracle. Off: after the forced parts every step is `Any`. + pub mask_body: bool, + /// Written when the oracle says `eof` and a fence was opened (after a newline if the program + /// does not end with one), e.g. "```". + pub close_fence: String, + /// Ends the reply (`<|im_end|>`): forced after the closing fence. + pub stop_token: u32, +} + +/// Counters for the experiment's records. +#[derive(Debug, Clone, Default)] +pub struct Stats { + /// Body steps that asked the oracle. + pub masked_steps: u64, + /// Steps answered `Force` (prelude, closing, or a mask with one legal token). + pub forced_steps: u64, + pub oracle_calls: u64, + /// Wall time inside oracle calls. + pub oracle_time: Duration, + /// Each masked step's wall time: its oracle calls plus the vocabulary scan. + pub step_times: Vec, + /// Tokens refused only because they cross two word boundaries, summed over masked steps + /// (counted when the part before their second boundary passed the cheap filter). + pub multi_boundary_refused: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Phase { + /// Forcing `prelude[i]`. + Prelude(usize), + Body, + /// Forcing the rest of the closing fence, then the stop token. + Closing(VecDeque), + Done, +} + +/// The Omegese guardrail (ADR 0004 section 2.3, Drake's guardrail decision): forced fence, forced +/// header, the body masked to tokens that keep the program a prefix of one `omegese emit` +/// accepts, and `eof` mapped to the closing fence plus the stop token. +/// +/// Mapping rule, per masked step: one oracle call on the program so far gives the items. A token +/// of word bytes only is legal when the current word followed by it is still the start of some +/// item. A token with one run of separators (optional word bytes, separators, optional word +/// bytes) is legal when its word bytes before the separators complete an item (or it starts with +/// a separator run whose canonical first separator is printed), each of its separators is offered by the +/// answer for the text before it, and its word bytes after them start an item of the answer +/// after them. Blank runs are read in [`canonical_seps`] form, so all the whitespace tokens share +/// a few answers: one cached oracle call per distinct (word bytes, canonical separators) prefix +/// per step; a lone separator token needs none. A token with two separator runs is refused (sound, slightly incomplete; see +/// [`Stats::multi_boundary_refused`]). Only bytes Omegese can hold (letters, digits, `_ - =`, +/// space, tab, newline and brackets) are ever legal in the program. +pub struct OmegeseConstraint { + table: Arc, + oracle: O, + framing: Framing, + prelude: Vec, + header_text: Vec, + /// The generated tokens this constraint has accounted for. + seen: Vec, + phase: Phase, + program: Vec, + /// The rule answered for the step whose token arrives next. + last: Option, + stats: Stats, +} + +/// A byte Omegese text may hold (omegese.c refuses every other one). +fn omegese_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() + || matches!(b, b'_' | b'-' | b'=' | b' ' | b'\t' | b'\n' | b'(' | b')') +} + +impl OmegeseConstraint { + pub fn new(table: Arc, oracle: O, framing: Framing) -> Result { + if table.text(framing.stop_token).is_some() { + return Err(format!( + "the stop token {} is ordinary text, not a special token", + framing.stop_token + )); + } + if framing.stop_token as usize >= table.len() { + return Err(format!( + "the stop token {} is outside the vocabulary of {}", + framing.stop_token, + table.len() + )); + } + if framing.open_fence.is_some() && !framing.close_fence.contains('`') { + return Err("the closing fence must contain a backtick, the eof marker".into()); + } + let mut prelude = Vec::new(); + if let Some(f) = &framing.open_fence { + prelude.extend(table.encode(f)?); + } + let header_text = framing + .header + .as_ref() + .map(Signature::header) + .unwrap_or_default(); + if !header_text.is_empty() { + prelude.extend(table.encode(&header_text)?); + } + let mut c = Self { + table, + oracle, + framing, + prelude, + header_text: header_text.into_bytes(), + seen: Vec::new(), + phase: Phase::Done, + program: Vec::new(), + last: None, + stats: Stats::default(), + }; + c.restart(); + if c.framing.mask_body && !c.header_text.is_empty() { + // Refuse a header the oracle refuses now, before the fence and header are written. + let h = c.header_text.clone(); + if let Answer::Refused(line) = c.query(&h)? { + return Err(format!( + "the oracle refuses the header ({line}): {:?}", + String::from_utf8_lossy(&h) + )); + } + } + Ok(c) + } + + /// The program text written so far (the header included, the fences not). + pub fn program(&self) -> &[u8] { + &self.program + } + + pub fn stats(&self) -> &Stats { + &self.stats + } + + pub fn oracle(&self) -> &O { + &self.oracle + } + + /// True once the reply is complete: only the stop token is left to force (the controller + /// consumes it without showing it back) or it was emitted. Without a fence the stop token is + /// usually one choice among others at eof, and a consumed stop looks the same to the + /// constraint as a cut by length after another token; there completion is + /// `FinishReason::Stop`, and this is true only when the stop was forced. + pub fn finished(&self) -> bool { + let stop = self.framing.stop_token; + match &self.phase { + Phase::Done => true, + Phase::Closing(q) => q.len() == 1 && q[0] == stop, + Phase::Body if self.framing.mask_body && self.framing.open_fence.is_none() => { + match &self.last { + Some(StepRule::Force(t)) => *t == stop, + _ => false, + } + } + _ => false, + } + } + + fn restart(&mut self) { + self.seen.clear(); + self.last = None; + self.program = self.header_text.clone(); + self.phase = if self.prelude.is_empty() { + Phase::Body + } else { + Phase::Prelude(0) + }; + } + + /// The text `eof` writes before the stop token. + fn closing_text(&self) -> Vec { + if self.framing.open_fence.is_none() { + return Vec::new(); + } + let mut c = Vec::new(); + if self.program.last().is_some_and(|&b| b != b'\n') { + c.push(b'\n'); + } + c.extend_from_slice(self.framing.close_fence.as_bytes()); + c + } + + /// The closing tokens after `written` bytes of the closing text, then the stop token. + fn closing_queue(&self, written: usize) -> Result, String> { + let c = self.closing_text(); + let mut q = VecDeque::new(); + if written < c.len() { + let rest = std::str::from_utf8(&c[written..]).map_err(|e| e.to_string())?; + q.extend(self.table.encode(rest)?); + } + q.push_back(self.framing.stop_token); + Ok(q) + } + + /// Accounts for the token the controller emitted after the last rule. + fn advance(&mut self, tok: u32) -> Result<(), String> { + let ok = match &self.last { + Some(StepRule::Force(t)) => *t == tok, + Some(StepRule::Allow(set)) => set.binary_search(&tok).is_ok(), + Some(StepRule::Any) => true, + Some(StepRule::Finish) | None => false, + }; + if !ok { + return Err(format!( + "token {tok} was emitted against the rule {:?}", + self.last + )); + } + self.seen.push(tok); + match &mut self.phase { + Phase::Prelude(i) => { + *i += 1; + if *i == self.prelude.len() { + self.phase = Phase::Body; + } + } + Phase::Body if !self.framing.mask_body => { + if let Some(t) = self.table.text(tok) { + self.program.extend_from_slice(t); + } + } + Phase::Body if tok == self.framing.stop_token => self.phase = Phase::Done, + Phase::Body => { + let t = self + .table + .text(tok) + .ok_or_else(|| format!("special token {tok} inside the program"))?; + if t.contains(&b'`') { + // The eof marker: the model began the closing fence. + let c = self.closing_text(); + let written = if c.starts_with(t) { t.len() } else { c.len() }; + self.phase = Phase::Closing(self.closing_queue(written)?); + } else { + self.program.extend_from_slice(t); + } + } + Phase::Closing(q) => { + q.pop_front(); + if q.is_empty() { + self.phase = Phase::Done; + } + } + Phase::Done => return Err(format!("token {tok} after the reply finished")), + } + Ok(()) + } + + fn query(&mut self, prefix: &[u8]) -> Result { + let t = Instant::now(); + let r = self.oracle.next(prefix); + self.stats.oracle_calls += 1; + self.stats.oracle_time += t.elapsed(); + r + } + + /// The items after `program` + `key` (a key ending in a separator run is in canonical form), + /// one oracle call per distinct key per step; `None` when the oracle refuses it. + fn state<'c>( + &mut self, + cache: &'c mut HashMap, Option>, + program: &[u8], + key: &[u8], + ) -> Result, String> { + if !cache.contains_key(key) { + let mut p = program.to_vec(); + p.extend_from_slice(key); + let set = match self.query(&p)? { + Answer::Items(i) => Some(ItemSet::new(&i, current_word(&p))?), + Answer::Refused(_) => None, + }; + cache.insert(key.to_vec(), set); + } + Ok(cache[key].as_ref()) + } + + /// One masked step. + fn mask(&mut self) -> Result { + let t0 = Instant::now(); + let program = self.program.clone(); + let items = match self.query(&program)? { + Answer::Items(i) => i, + Answer::Refused(line) => { + return Err(format!( + "the oracle refused the program so far ({line}); program: {:?}", + String::from_utf8_lossy(&program) + )) + } + }; + let here = ItemSet::new(&items, current_word(&program))?; + // Text up to the end of a token's separators -> the items after it (None: refused). + let mut after: HashMap, Option> = HashMap::new(); + let table = Arc::clone(&self.table); + let mut allowed = Vec::new(); + let mut multi = 0u64; + for id in 0..table.len() as u32 { + let (Some(t), shape) = (table.text(id), table.shape(id)) else { + continue; + }; + if !t.iter().all(|&b| omegese_byte(b)) { + continue; + } + match shape { + Shape::Special => {} + Shape::Word => { + if here.extends(t) { + allowed.push(id); + } + } + Shape::Multi => { + let a_end = t.iter().position(|&b| crate::word::is_sep(b)).unwrap_or(0); + let a = &t[..a_end]; + if (a.is_empty() && here.sep_offered(t[0])) + || (!a.is_empty() && here.completes(a)) + { + multi += 1; + } + } + Shape::OneBoundary { a_end, sep_end } => { + let (a, b) = (&t[..a_end], &t[sep_end..]); + // Canonical first: a blank run holding a newline reads as that newline, so a + // token like ` \n` must find the newline offered, not the space. + let seps = canonical_seps(&t[a_end..sep_end]); + let first_ok = if a.is_empty() { + here.sep_offered(seps[0]) + } else { + here.completes(a) + }; + if !first_ok { + continue; + } + if a.is_empty() && seps.len() == 1 && b.is_empty() { + // The separator's own item: exact by section 6.1. + allowed.push(id); + continue; + } + // Walk the separators one at a time: each must be offered by the state + // before it (the state at the program itself is `here`). + let mut key = a.to_vec(); + let mut ok = true; + for (i, &c) in seps.iter().enumerate() { + if !(a.is_empty() && i == 0) { + let st = self.state(&mut after, &program, &key)?; + if !st.is_some_and(|s| s.sep_offered(c)) { + ok = false; + break; + } + } + key.push(c); + } + if !ok { + continue; + } + if b.is_empty() + || self + .state(&mut after, &program, &key)? + .is_some_and(|s| s.extends(b)) + { + allowed.push(id); + } + } + } + } + let mut rule = None; + if here.eof() { + match &self.framing.open_fence { + None => allowed.push(self.framing.stop_token), + Some(_) => { + let c = self.closing_text(); + for id in 0..table.len() as u32 { + let Some(t) = table.text(id) else { continue }; + let fits = c.starts_with(t) + || t.strip_prefix(c.as_slice()) + .is_some_and(|r| r.iter().all(u8::is_ascii_whitespace)); + if fits && t.contains(&b'`') { + allowed.push(id); + } + } + if allowed.is_empty() { + // Eof is the only item and no token both starts the closing text and + // marks it with a backtick: force the closing. (When some body token is + // legal but no marking token fits, eof waits for a later step.) + let q = self.closing_queue(0)?; + let first = q[0]; + self.phase = Phase::Closing(q); + rule = Some(StepRule::Force(first)); + } + } + } + } + allowed.sort_unstable(); + allowed.dedup(); + self.stats.masked_steps += 1; + self.stats.multi_boundary_refused += multi; + self.stats.step_times.push(t0.elapsed()); + if let Some(r) = rule { + return Ok(r); + } + match allowed.as_slice() { + [] => Err(format!( + "no token is legal after {:?} although the oracle printed {} items (a single-byte \ + token should always continue an item)", + String::from_utf8_lossy(&program), + items.len() + )), + [t] => Ok(StepRule::Force(*t)), + _ => Ok(StepRule::Allow(allowed)), + } + } +} + +impl Constraint for OmegeseConstraint { + fn rule(&mut self, _prompt: &[u32], generated: &[u32]) -> Result { + if generated.is_empty() { + self.restart(); + } else if generated.len() == self.seen.len() + 1 && generated.starts_with(&self.seen) { + self.advance(generated[generated.len() - 1])?; + } else { + return Err(format!( + "the constraint saw {} tokens and is now shown {} that do not extend them", + self.seen.len(), + generated.len() + )); + } + let rule = match &self.phase { + Phase::Prelude(i) => StepRule::Force(self.prelude[*i]), + Phase::Body if !self.framing.mask_body => StepRule::Any, + Phase::Body => self.mask()?, + Phase::Closing(q) => StepRule::Force(q[0]), + Phase::Done => StepRule::Finish, + }; + if matches!(rule, StepRule::Force(_)) { + self.stats.forced_steps += 1; + } + self.last = Some(rule.clone()); + Ok(rule) + } +} + +/// A separator run with every maximal run of blanks (space, tab, newline) written as one +/// newline if it holds one, else one space; brackets kept. Blank space between words is free in +/// Omegese and blank lines are empty lines, so the text after either form has the same items +/// (pinned against the real oracle by `real_oracle_blank_runs_are_interchangeable`). +pub fn canonical_seps(seps: &[u8]) -> Vec { + let mut out = Vec::with_capacity(seps.len()); + let mut blank: Option = None; + for &c in seps { + match c { + b' ' | b'\t' => { + blank.get_or_insert(b' '); + } + b'\n' => blank = Some(b'\n'), + _ => { + out.extend(blank.take()); + out.push(c); + } + } + } + out.extend(blank); + out +} + +#[cfg(test)] +mod tests { + use super::canonical_seps; + + #[test] + fn blank_runs_shrink_to_one_byte() { + for (run, want) in [ + (" ", " "), + ("\t \t", " "), + (" \n\t\n ", "\n"), + (")\n\n", ")\n"), + (" ( ", " ( "), + ("((", "(("), + ("\t)\t)\n ", " ) )\n"), + ] { + assert_eq!(canonical_seps(run.as_bytes()), want.as_bytes(), "{run:?}"); + } + } +} diff --git a/crates/aien-omegese-constraint/src/lib.rs b/crates/aien-omegese-constraint/src/lib.rs new file mode 100644 index 00000000..3a07825f --- /dev/null +++ b/crates/aien-omegese-constraint/src/lib.rs @@ -0,0 +1,23 @@ +//! The Omegese guardrail: a [`Constraint`](aien_inference_abi::generation::Constraint) for the +//! generation controller (ADR 0004 section 2.3) that keeps a model's reply a prefix of a program +//! `omegese emit` accepts. +//! +//! A separately tested feature (Drake's guardrail decision, ADR 0004): nothing depends on this +//! crate by default, the controller with no constraint is unchanged, and the sparse output head +//! stays the default gather. The legal-token source is any [`ItemOracle`] (the contract is omega +//! `docs/one_layer/OMEGESE.md` section 6.2); [`SubprocessOracle`] runs `omegese next --machine`. +//! [`TokenTable`] holds the model vocabulary as bytes (Qwen's `tokenizer.json`, or a synthetic +//! table in tests). [`OmegeseConstraint`] forces the opening fence and the entry header, masks the +//! body, and maps `eof` to the closing fence plus the stop token; each part is switchable +//! ([`Framing`]). + +pub mod constraint; +pub mod oracle; +pub mod signature; +pub mod table; +pub mod word; + +pub use constraint::{Framing, OmegeseConstraint, Stats}; +pub use oracle::{parse_machine, Answer, Item, ItemOracle, SubprocessOracle, DEFAULT_TIMEOUT}; +pub use signature::Signature; +pub use table::{Shape, TokenTable}; diff --git a/crates/aien-omegese-constraint/src/oracle.rs b/crates/aien-omegese-constraint/src/oracle.rs new file mode 100644 index 00000000..c50e6870 --- /dev/null +++ b/crates/aien-omegese-constraint/src/oracle.rs @@ -0,0 +1,346 @@ +//! The item oracle: what may come next after a prefix of an Omegese program. +//! +//! The contract is the fixed grammar of `omegese next --machine` (omega +//! `docs/one_layer/OMEGESE.md` section 6.2): one item per line, exit 0 with at least one item, or +//! exit 1 with exactly one line starting `REFUSED omegese: `. [`ItemOracle`] is that contract as +//! a trait; [`SubprocessOracle`] runs the real binary once per query. + +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +/// One line of `omegese next --machine`. Let U be the word still being written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Item { + /// `word X`: finish the current word as X (X starts with U). + Word(Vec), + /// `newname E1 E2 ...`: finish the current word as any new name that starts with U, is not a + /// reserved word and is not one of `exclude`. + NewName { exclude: Vec> }, + /// `number LO HI`: finish the current word as a number in `lo..=hi` whose text starts with U. + Number { lo: i128, hi: i128 }, + /// `(`: an opening bracket (it also ends the current word). + Open, + /// `)`: a closing bracket (it also ends the current word). + Close, + /// `space`: a space or tab. + Space, + /// `newline`: ends the current word and the line. + Newline, + /// `eof`: the prefix is already an accepted program. + Eof, +} + +/// The oracle's answer for one prefix. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Answer { + /// Exit 0: at least one item. + Items(Vec), + /// Exit 1: no text after this prefix makes a program `omegese emit` accepts. The whole line. + Refused(String), +} + +/// What may come next after a prefix (section 6.2 is the contract). +pub trait ItemOracle { + /// The answer for `prefix`. `Err` only for a broken oracle (I/O, a line outside the grammar); + /// a prefix with no legal continuation is `Ok(Answer::Refused)`. + fn next(&mut self, prefix: &[u8]) -> Result; +} + +impl ItemOracle for Box { + fn next(&mut self, prefix: &[u8]) -> Result { + (**self).next(prefix) + } +} + +/// Parses one `omegese next --machine` run: its stdout and whether it exited 0 (`true`) or 1. +pub fn parse_machine(stdout: &str, exit_zero: bool) -> Result { + let lines: Vec<&str> = stdout.lines().collect(); + if !exit_zero { + return match lines.as_slice() { + [l] if l.starts_with("REFUSED omegese: ") => Ok(Answer::Refused(l.to_string())), + _ => Err(format!( + "oracle exit 1 must print exactly one REFUSED line, got {} lines", + lines.len() + )), + }; + } + if lines.is_empty() { + return Err("oracle exit 0 with no item".into()); + } + lines + .iter() + .map(|l| parse_item(l)) + .collect::, _>>() + .map(Answer::Items) +} + +fn parse_item(line: &str) -> Result { + let bad = || format!("oracle line outside the 6.2 grammar: {line:?}"); + let mut parts = line.split(' '); + let head = parts.next().ok_or_else(bad)?; + let rest: Vec<&str> = parts.collect(); + let item = match (head, rest.as_slice()) { + ("word", [x]) if !x.is_empty() => Item::Word(x.as_bytes().to_vec()), + ("newname", names) => Item::NewName { + exclude: names + .iter() + .map(|n| { + if n.is_empty() { + Err(bad()) + } else { + Ok(n.as_bytes().to_vec()) + } + }) + .collect::>()?, + }, + ("number", [lo, hi]) => { + let lo: i128 = lo.parse().map_err(|_| bad())?; + let hi: i128 = hi.parse().map_err(|_| bad())?; + if lo > hi { + return Err(bad()); + } + Item::Number { lo, hi } + } + ("(", []) => Item::Open, + (")", []) => Item::Close, + ("space", []) => Item::Space, + ("newline", []) => Item::Newline, + ("eof", []) => Item::Eof, + _ => return Err(bad()), + }; + Ok(item) +} + +/// How long one query may take before the process is killed and the query fails. +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); + +/// The real oracle: ` next --machine /dev/stdin`, the prefix on stdin, one process per query. +/// The binary's path is configuration (built from omega `tools/omegese/omegese.c`). A query +/// that has not answered within the timeout is killed and fails, which the generation loop +/// handles through its rollback. +pub struct SubprocessOracle { + bin: PathBuf, + timeout: Duration, + calls: u64, + elapsed: Duration, +} + +impl SubprocessOracle { + /// Checks that `bin` is a file; the first query proves it runs. The timeout is + /// [`DEFAULT_TIMEOUT`]. + pub fn new(bin: impl Into) -> Result { + let bin = bin.into(); + if !bin.is_file() { + return Err(format!("omegese binary not found at {}", bin.display())); + } + Ok(Self { + bin, + timeout: DEFAULT_TIMEOUT, + calls: 0, + elapsed: Duration::ZERO, + }) + } + + /// The same oracle with another per-query timeout. + pub fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + /// Queries made so far. + pub fn calls(&self) -> u64 { + self.calls + } + + /// Wall time spent in queries so far (spawn, write, wait, parse). + pub fn elapsed(&self) -> Duration { + self.elapsed + } +} + +fn read_all(mut r: impl Read) -> std::io::Result> { + let mut v = Vec::new(); + r.read_to_end(&mut v).map(|_| v) +} + +impl ItemOracle for SubprocessOracle { + fn next(&mut self, prefix: &[u8]) -> Result { + let t = Instant::now(); + let mut child = Command::new(&self.bin) + .args(["next", "--machine", "/dev/stdin"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("spawn {}: {e}", self.bin.display()))?; + let mut stdin = child.stdin.take().ok_or("oracle stdin missing")?; + let stdout = child.stdout.take().ok_or("oracle stdout missing")?; + let stderr = child.stderr.take().ok_or("oracle stderr missing")?; + let timeout = self.timeout; + // One thread per pipe, so a prefix larger than the pipe buffer cannot deadlock against + // stdout; stdout closing (the process ending) is what the deadline waits for. + let (stdout, stderr, wrote, status) = std::thread::scope(|s| { + let w = s.spawn(move || stdin.write_all(prefix)); + let e = s.spawn(move || read_all(stderr)); + let (tx, rx) = mpsc::channel(); + s.spawn(move || tx.send(read_all(stdout))); + let out = match rx.recv_timeout(timeout) { + Ok(out) => out, + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!( + "the oracle gave no answer within {timeout:?}; killed it" + )); + } + }; + // Stdout closed; the process should be gone or going. Wait out the rest of the deadline. + let status = loop { + match child.try_wait() { + Ok(Some(st)) => break st, + Ok(None) if t.elapsed() < timeout => { + std::thread::sleep(Duration::from_micros(100)) + } + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!( + "the oracle closed its answer but did not exit within {timeout:?}; killed it" + )); + } + Err(e) => return Err(format!("wait for the oracle: {e}")), + } + }; + let wrote = w + .join() + .map_err(|_| "oracle writer thread panicked".to_string())?; + let err = e + .join() + .map_err(|_| "oracle stderr thread panicked".to_string())? + .unwrap_or_default(); + let out = out.map_err(|e| format!("read the oracle's answer: {e}"))?; + Ok((out, err, wrote, status)) + })?; + self.calls += 1; + self.elapsed += t.elapsed(); + // The exit status first: a process that quit early also breaks the pipe it was fed by, + // and its own message says why. + let code = status.code(); + if !matches!(code, Some(0 | 1)) { + return Err(format!( + "oracle exit {code:?}: {}", + String::from_utf8_lossy(&stderr).trim() + )); + } + wrote.map_err(|e| format!("write the prefix to the oracle: {e}"))?; + let stdout = String::from_utf8(stdout).map_err(|_| "oracle stdout is not UTF-8")?; + parse_machine(&stdout, code == Some(0)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_section_6_2_example_parses() { + let out = "word if\nword while\nword for\nword ret\nword trap\nword a\nnewname a f\nspace\nnewline\n"; + let Answer::Items(items) = parse_machine(out, true).unwrap() else { + panic!("items") + }; + assert_eq!(items.len(), 9); + assert_eq!(items[0], Item::Word(b"if".to_vec())); + assert_eq!( + items[6], + Item::NewName { + exclude: vec![b"a".to_vec(), b"f".to_vec()] + } + ); + assert_eq!(items[8], Item::Newline); + } + + #[test] + fn numbers_span_u64_and_i64() { + let out = + "number 0 18446744073709551615\nnumber -9223372036854775808 -1\n(\n)\neof\nnewname\n"; + let Answer::Items(items) = parse_machine(out, true).unwrap() else { + panic!("items") + }; + assert_eq!( + items[0], + Item::Number { + lo: 0, + hi: u64::MAX as i128 + } + ); + assert_eq!( + items[1], + Item::Number { + lo: i64::MIN as i128, + hi: -1 + } + ); + assert_eq!(&items[2..5], &[Item::Open, Item::Close, Item::Eof]); + assert_eq!(items[5], Item::NewName { exclude: vec![] }); + } + + #[test] + fn refusals_and_contract_breaks() { + let r = "REFUSED omegese: line 2: no text after this prefix makes a program emit accepts\n"; + assert!(matches!(parse_machine(r, false), Ok(Answer::Refused(_)))); + assert!(parse_machine("", true).is_err(), "exit 0 needs an item"); + assert!(parse_machine("", false).is_err(), "exit 1 needs its line"); + assert!(parse_machine("word if\n", false).is_err()); + assert!(parse_machine("word\n", true).is_err()); + assert!(parse_machine("word a b\n", true).is_err()); + assert!(parse_machine("number 5 1\n", true).is_err()); + assert!(parse_machine("number x 1\n", true).is_err()); + assert!(parse_machine("space \n", true).is_err()); + assert!(parse_machine("tab\n", true).is_err()); + } + + /// A stand-in binary: a shell script with `body`, in a fresh scratch folder. + fn script(name: &str, body: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("omegese-oracle-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join(name); + std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + p + } + + #[test] + fn a_hung_oracle_is_killed_at_the_deadline() { + let bin = script("hang", "exec sleep 30"); + let mut o = SubprocessOracle::new(bin) + .unwrap() + .with_timeout(Duration::from_millis(200)); + let t = Instant::now(); + let e = o.next(b"fn f").unwrap_err(); + assert!(e.contains("no answer within"), "{e}"); + assert!(t.elapsed() < Duration::from_secs(5), "{:?}", t.elapsed()); + } + + #[test] + fn an_early_exit_reports_its_own_message() { + // The process quits without reading a prefix larger than the pipe buffer: its message + // is the error, not the broken pipe. + let bin = script("quit", "echo prefix too long >&2; exit 2"); + let mut o = SubprocessOracle::new(bin).unwrap(); + let e = o.next(&vec![b'a'; 1 << 20]).unwrap_err(); + assert!( + e.contains("exit Some(2)") && e.contains("prefix too long"), + "{e}" + ); + let bin = script("ok", "cat >/dev/null; echo eof"); + let mut o = SubprocessOracle::new(bin).unwrap(); + assert_eq!( + o.next(&vec![b'a'; 1 << 20]).unwrap(), + Answer::Items(vec![Item::Eof]) + ); + } +} diff --git a/crates/aien-omegese-constraint/src/signature.rs b/crates/aien-omegese-constraint/src/signature.rs new file mode 100644 index 00000000..7f5562b9 --- /dev/null +++ b/crates/aien-omegese-constraint/src/signature.rs @@ -0,0 +1,173 @@ +//! The entry function's public signature, as the task gives it (the `entry`, `params` and `ret` +//! lines the user message already contains), and the Omegese header line built from it. + +/// Parameter names given to a signature that names none, in order (Omegese allows 6 parameters). +const PARAM_NAMES: [&str; 6] = ["a", "b", "c", "d", "e", "f"]; + +/// The entry function: its name, its parameters (name, Omegese type word) and its return type +/// word (`None`: void). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Signature { + pub entry: String, + pub params: Vec<(String, String)>, + pub ret: Option, +} + +/// The IR type name the task writes, as the one-token Omegese word (OMEGESE.md section 3). +fn omegese_type(ir: &str) -> Option<&'static str> { + Some(match ir { + "bool" => "bool", + "u8" => "uchar", + "u16" => "ushort", + "u32" => "uint", + "u64" => "ulong", + "i8" => "byte", + "i16" => "short", + "i32" => "int", + "i64" => "long", + _ => return None, + }) +} + +impl Signature { + /// From the task's signature lines: `entry `, `params *`, `ret ` + /// (`ret` alone or `ret void`: void). Other lines are ignored. Parameters are named + /// `a`, `b`, ... in order. + pub fn from_requirement(text: &str) -> Result { + let (mut entry, mut params, mut ret) = (None, None, None); + for line in text.lines() { + let mut w = line.split_whitespace(); + match w.next() { + Some("entry") => entry = Some(w.collect::>()), + Some("params") => params = Some(w.collect::>()), + Some("ret") => ret = Some(w.collect::>()), + _ => {} + } + } + let entry = match entry.as_deref() { + Some([name]) => name.to_string(), + _ => return Err("the signature needs one `entry ` line".into()), + }; + let params = params.ok_or("the signature has no `params` line")?; + if params.len() > PARAM_NAMES.len() { + return Err(format!("{} parameters; Omegese allows 6", params.len())); + } + let params = params + .iter() + .zip(PARAM_NAMES) + .map(|(t, n)| { + omegese_type(t) + .map(|t| (n.to_string(), t.to_string())) + .ok_or_else(|| format!("unknown parameter type {t:?}")) + }) + .collect::, _>>()?; + let ret = match ret.as_deref() { + Some([]) | Some(["void"]) => None, + Some([t]) => Some( + omegese_type(t) + .ok_or_else(|| format!("unknown return type {t:?}"))? + .to_string(), + ), + _ => return Err("the signature needs one `ret ` line".into()), + }; + if params.iter().any(|(n, _)| *n == entry) { + return Err(format!( + "the entry {entry:?} has the name of a parameter; name the parameters explicitly" + )); + } + Ok(Self { entry, params, ret }) + } + + /// From a written header line, `fn ( )* to |void` (an array type is + /// `own|edit|view `), names and type words kept as written. + pub fn from_header(line: &str) -> Result { + let w: Vec<&str> = line.split_whitespace().collect(); + let bad = || format!("not a header line: {line:?}"); + let (Some(&"fn"), Some(entry)) = (w.first(), w.get(1)) else { + return Err(bad()); + }; + let to = w.iter().position(|&x| x == "to").ok_or_else(bad)?; + let (mut mid, tail) = (&w[2..to], &w[to + 1..]); + if tail.len() != 1 { + return Err(bad()); + } + let mut params = Vec::new(); + while let Some((name, rest)) = mid.split_first() { + // A type is one word, or `own|edit|view ` for an array. + let n = match rest.first() { + Some(&"own" | &"edit" | &"view") => 3, + Some(_) => 1, + None => return Err(bad()), + }; + if rest.len() < n { + return Err(bad()); + } + params.push((name.to_string(), rest[..n].join(" "))); + mid = &rest[n..]; + } + Ok(Self { + entry: entry.to_string(), + params, + ret: (tail[0] != "void").then(|| tail[0].to_string()), + }) + } + + /// `fn ... to ` and a newline. + pub fn header(&self) -> String { + let mut s = format!("fn {}", self.entry); + for (n, t) in &self.params { + s.push(' '); + s.push_str(n); + s.push(' '); + s.push_str(t); + } + s.push_str(" to "); + s.push_str(self.ret.as_deref().unwrap_or("void")); + s.push('\n'); + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn requirement_lines_make_the_header() { + let s = Signature::from_requirement("entry clamp_sub\nparams u32 u32\nret u32\n").unwrap(); + assert_eq!(s.header(), "fn clamp_sub a uint b uint to uint\n"); + let s = Signature::from_requirement("entry go\nparams\nret\n").unwrap(); + assert_eq!(s.header(), "fn go to void\n"); + let s = Signature::from_requirement("x\nentry t\nparams i16 u8 bool\nret i64\n").unwrap(); + assert_eq!(s.header(), "fn t a short b uchar c bool to long\n"); + for bad in [ + "params u32\nret u32", + "entry x\nret u32", + "entry x\nparams u33\nret u32", + "entry x\nparams u32\nret f32", + "entry b\nparams u32 u32\nret u32", + "entry x\nparams u8 u8 u8 u8 u8 u8 u8\nret u8", + ] { + assert!(Signature::from_requirement(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn header_lines_round_trip() { + for h in [ + "fn gcd a uint b uint to uint\n", + "fn dot u view long 3 w view long 3 to long\n", + "fn go to void\n", + ] { + assert_eq!(Signature::from_header(h).unwrap().header(), h); + } + for bad in [ + "ret a", + "fn f a to uint", + "fn f a view uint to uint", + "fn f a uint to", + ] { + assert!(Signature::from_header(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/aien-omegese-constraint/src/table.rs b/crates/aien-omegese-constraint/src/table.rs new file mode 100644 index 00000000..c0d5953b --- /dev/null +++ b/crates/aien-omegese-constraint/src/table.rs @@ -0,0 +1,272 @@ +//! The model vocabulary as byte strings, with each token's shape against Omegese's word +//! separators precomputed, and an encoder for the text the constraint forces. + +use std::collections::HashMap; +use std::path::Path; + +use crate::word::is_sep; + +/// A token's text against the word separators (space, tab, newline, brackets). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shape { + /// No program text: a special or added token, or an empty one. + Special, + /// Word bytes only: the token grows the current word. + Word, + /// Word bytes `..a_end` (maybe none), one run of separators `a_end..sep_end`, then word + /// bytes to the end (maybe none): one word boundary. + OneBoundary { a_end: usize, sep_end: usize }, + /// A second separator run after word bytes: the token crosses two word boundaries. + Multi, +} + +fn shape_of(t: &[u8]) -> Shape { + if t.is_empty() { + return Shape::Special; + } + let Some(a_end) = t.iter().position(|&b| is_sep(b)) else { + return Shape::Word; + }; + let sep_end = a_end + + t[a_end..] + .iter() + .position(|&b| !is_sep(b)) + .unwrap_or(t.len() - a_end); + if t[sep_end..].iter().any(|&b| is_sep(b)) { + Shape::Multi + } else { + Shape::OneBoundary { a_end, sep_end } + } +} + +enum Encoder { + /// The model's own tokenizer: forced text is tokenized as the model would read it. + Hf(Box), + /// Longest match over the table (synthetic tables in tests). + Greedy { + by_text: HashMap, u32>, + longest: usize, + }, +} + +/// Every token id's bytes (`None` for special tokens) and the encoder for forced text. +pub struct TokenTable { + texts: Vec>>, + shapes: Vec, + encoder: Encoder, +} + +impl TokenTable { + /// A synthetic table: `texts[id]`, `None` for a special token; forced text is encoded by + /// longest match (the lowest id wins a duplicate). + pub fn from_texts(texts: Vec>>) -> Self { + let mut by_text = HashMap::new(); + let mut longest = 0; + for (id, t) in texts.iter().enumerate() { + if let Some(t) = t.as_ref().filter(|t| !t.is_empty()) { + by_text.entry(t.clone()).or_insert(id as u32); + longest = longest.max(t.len()); + } + } + Self::build(texts, Encoder::Greedy { by_text, longest }) + } + + /// The vocabulary of a byte-level BPE `tokenizer.json` (Qwen's). Added tokens (the chat + /// specials) have no program text. `Err` if any other token is not byte-level text. + pub fn from_tokenizer_json(path: &Path) -> Result { + let tk = tokenizers::Tokenizer::from_file(path) + .map_err(|e| format!("load {}: {e}", path.display()))?; + let added = tk.get_added_tokens_decoder(); + let inv = byte_decoder(); + let n = tk.get_vocab_size(true); + let mut texts = Vec::with_capacity(n); + for id in 0..n as u32 { + if added.contains_key(&id) { + texts.push(None); + continue; + } + let Some(s) = tk.id_to_token(id) else { + texts.push(None); + continue; + }; + let bytes = s + .chars() + .map(|c| inv.get(&c).copied()) + .collect::>>() + .ok_or_else(|| format!("token {id} ({s:?}) is not byte-level text"))?; + texts.push(Some(bytes)); + } + Ok(Self::build(texts, Encoder::Hf(Box::new(tk)))) + } + + fn build(texts: Vec>>, encoder: Encoder) -> Self { + let shapes = texts + .iter() + .map(|t| t.as_deref().map_or(Shape::Special, shape_of)) + .collect(); + Self { + texts, + shapes, + encoder, + } + } + + pub fn len(&self) -> usize { + self.texts.len() + } + + pub fn is_empty(&self) -> bool { + self.texts.is_empty() + } + + /// The bytes of `id`, `None` for a special token or an id outside the table. + pub fn text(&self, id: u32) -> Option<&[u8]> { + self.texts.get(id as usize)?.as_deref() + } + + pub fn shape(&self, id: u32) -> Shape { + self.shapes + .get(id as usize) + .copied() + .unwrap_or(Shape::Special) + } + + /// A special token's id by its content (`<|im_end|>`); only for a `tokenizer.json` table. + pub fn special_id(&self, content: &str) -> Option { + match &self.encoder { + Encoder::Hf(tk) => tk + .token_to_id(content) + .filter(|&id| self.text(id).is_none()), + Encoder::Greedy { .. } => None, + } + } + + /// The bytes of a token sequence; `Err` on a special token. + pub fn decode(&self, ids: &[u32]) -> Result, String> { + let mut out = Vec::new(); + for &id in ids { + out.extend_from_slice( + self.text(id) + .ok_or_else(|| format!("token {id} has no program text"))?, + ); + } + Ok(out) + } + + /// Tokens for `text`, checked to decode back to exactly `text`. + pub fn encode(&self, text: &str) -> Result, String> { + let ids = match &self.encoder { + Encoder::Hf(tk) => tk + .encode(text, false) + .map_err(|e| format!("encode {text:?}: {e}"))? + .get_ids() + .to_vec(), + Encoder::Greedy { by_text, longest } => { + let b = text.as_bytes(); + let mut ids = Vec::new(); + let mut i = 0; + while i < b.len() { + let id = (1..=(*longest).min(b.len() - i)) + .rev() + .find_map(|n| by_text.get(&b[i..i + n]).map(|&id| (id, n))); + let (id, n) = id.ok_or_else(|| { + format!("no token in the table starts byte {i} of {text:?}") + })?; + ids.push(id); + i += n; + } + ids + } + }; + if self.decode(&ids)? != text.as_bytes() { + return Err(format!( + "{text:?} does not round-trip through the tokenizer" + )); + } + Ok(ids) + } +} + +/// GPT-2's byte-level alphabet, inverted: each printable stand-in character to its byte. +fn byte_decoder() -> HashMap { + let mut map = HashMap::new(); + let mut n = 0u32; + for b in 0..=255u8 { + let direct = (b'!'..=b'~').contains(&b) || (0xA1..=0xAC).contains(&b) || b >= 0xAE; + let c = if direct { + char::from(b) + } else { + n += 1; + char::from_u32(255 + n).expect("a valid code point") + }; + map.insert(c, b); + } + map +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shapes() { + assert_eq!(shape_of(b"add"), Shape::Word); + assert_eq!(shape_of(b"=-"), Shape::Word); + assert_eq!( + shape_of(b" add"), + Shape::OneBoundary { + a_end: 0, + sep_end: 1 + } + ); + assert_eq!( + shape_of(b"end\n"), + Shape::OneBoundary { + a_end: 3, + sep_end: 4 + } + ); + assert_eq!( + shape_of(b")\n"), + Shape::OneBoundary { + a_end: 0, + sep_end: 2 + } + ); + assert_eq!( + shape_of(b"a b"), + Shape::OneBoundary { + a_end: 1, + sep_end: 2 + } + ); + assert_eq!(shape_of(b" a "), Shape::Multi); + assert_eq!(shape_of(b"(x)"), Shape::Multi); + assert_eq!(shape_of(b""), Shape::Special); + } + + #[test] + fn the_byte_alphabet_is_a_bijection() { + let d = byte_decoder(); + assert_eq!(d.len(), 256); + assert_eq!(d[&'Ġ'], b' '); + assert_eq!(d[&'Ċ'], b'\n'); + assert_eq!(d[&'a'], b'a'); + } + + #[test] + fn greedy_encoding_round_trips() { + let t = TokenTable::from_texts(vec![ + Some(b"a".to_vec()), + Some(b"ab".to_vec()), + Some(b"b".to_vec()), + None, + ]); + assert_eq!(t.encode("abab").unwrap(), vec![1, 1]); + assert_eq!(t.encode("ba").unwrap(), vec![2, 0]); + assert!(t.encode("c").is_err()); + assert!(t.decode(&[3]).is_err()); + assert_eq!(t.shape(3), Shape::Special); + assert_eq!(t.shape(99), Shape::Special); + } +} diff --git a/crates/aien-omegese-constraint/src/word.rs b/crates/aien-omegese-constraint/src/word.rs new file mode 100644 index 00000000..a712b0ef --- /dev/null +++ b/crates/aien-omegese-constraint/src/word.rs @@ -0,0 +1,339 @@ +//! Word-level reading of one oracle answer: may the current word grow by some bytes, and is it a +//! whole item. Section 6.2's writer rule: text may be appended to the current word exactly when +//! U followed by it is still the start of some `word`, `newname` or `number` item. + +use std::collections::HashSet; + +use crate::oracle::Item; + +/// The longest new name (OMEGESE.md section 6.2). +pub const NAME_MAX: usize = 63; + +/// Space, tab, newline and the brackets end a word (section 6.2). +pub fn is_sep(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\n' | b'(' | b')') +} + +/// The word still being written: the bytes after the last separator. +pub fn current_word(text: &[u8]) -> &[u8] { + match text.iter().rposition(|&b| is_sep(b)) { + Some(i) => &text[i + 1..], + None => text, + } +} + +/// One oracle answer, read against the current word U. +#[derive(Debug, Clone)] +pub struct ItemSet { + u: Vec, + /// Every non-empty prefix of `X[U.len()..]` over the `word X` items. + word_prefixes: HashSet>, + /// `X[U.len()..]` over the `word X` items. + word_rests: HashSet>, + /// `Some(exclusions)` when a `newname` item was printed. + newname: Option>>, + numbers: Vec<(i128, i128)>, + open: bool, + close: bool, + space: bool, + newline: bool, + eof: bool, +} + +impl ItemSet { + /// `Err` when a `word` item does not start with U (the grammar promises it does). + pub fn new(items: &[Item], u: &[u8]) -> Result { + let mut s = Self { + u: u.to_vec(), + word_prefixes: HashSet::new(), + word_rests: HashSet::new(), + newname: None, + numbers: Vec::new(), + open: false, + close: false, + space: false, + newline: false, + eof: false, + }; + for it in items { + match it { + Item::Word(x) => { + let rest = x.strip_prefix(u).ok_or_else(|| { + format!( + "oracle item `word {}` does not start with the current word {:?}", + String::from_utf8_lossy(x), + String::from_utf8_lossy(u) + ) + })?; + for k in 1..=rest.len() { + s.word_prefixes.insert(rest[..k].to_vec()); + } + s.word_rests.insert(rest.to_vec()); + } + Item::NewName { exclude } => { + s.newname + .get_or_insert_with(Vec::new) + .extend(exclude.iter().cloned()); + } + Item::Number { lo, hi } => s.numbers.push((*lo, *hi)), + Item::Open => s.open = true, + Item::Close => s.close = true, + Item::Space => s.space = true, + Item::Newline => s.newline = true, + Item::Eof => s.eof = true, + } + } + Ok(s) + } + + pub fn eof(&self) -> bool { + self.eof + } + + /// The item that lets separator byte `b` come next. + pub fn sep_offered(&self, b: u8) -> bool { + match b { + b' ' | b'\t' => self.space, + b'\n' => self.newline, + b'(' => self.open, + b')' => self.close, + _ => false, + } + } + + /// U followed by `a` (non-empty, no separator) is still the start of some word, new name or + /// number item. + pub fn extends(&self, a: &[u8]) -> bool { + if self.word_prefixes.contains(a) { + return true; + } + let mut buf = [0u8; 80]; + let Some(w) = joined(&mut buf, &self.u, a) else { + return false; + }; + if let Some(ex) = &self.newname { + if name_prefix_ok(w, ex) { + return true; + } + } + self.numbers + .iter() + .any(|&(lo, hi)| number_prefix_ok(w, lo, hi)) + } + + /// U followed by `a` is a whole item, so a separator may end it (a cheap filter; the oracle + /// decides what may follow). New names are not checked against the reserved words here. + pub fn completes(&self, a: &[u8]) -> bool { + if self.word_rests.contains(a) { + return true; + } + let mut buf = [0u8; 80]; + let Some(w) = joined(&mut buf, &self.u, a) else { + return false; + }; + if let Some(ex) = &self.newname { + if is_name(w) && w.len() <= NAME_MAX && !ex.iter().any(|e| e == w) { + return true; + } + } + number_value(w).is_some_and(|v| self.numbers.iter().any(|&(lo, hi)| lo <= v && v <= hi)) + } +} + +fn joined<'a>(buf: &'a mut [u8; 80], u: &[u8], a: &[u8]) -> Option<&'a [u8]> { + let n = u.len() + a.len(); + if n > buf.len() { + return None; + } + buf[..u.len()].copy_from_slice(u); + buf[u.len()..n].copy_from_slice(a); + Some(&buf[..n]) +} + +/// A letter or `_`, then letters, digits or `_`. +fn is_name(w: &[u8]) -> bool { + match w.split_first() { + Some((&c, rest)) => { + (c.is_ascii_alphabetic() || c == b'_') + && rest.iter().all(|&c| c.is_ascii_alphanumeric() || c == b'_') + } + None => false, + } +} + +/// Some legal new name starts with `w`. +fn name_prefix_ok(w: &[u8], exclude: &[Vec]) -> bool { + is_name(w) && (w.len() < NAME_MAX || (w.len() == NAME_MAX && !exclude.iter().any(|e| e == w))) +} + +/// The value of a whole number word: decimal digits, an optional minus sign, no leading zeros, +/// not `-0`. +pub fn number_value(w: &[u8]) -> Option { + let (neg, d) = match w.split_first() { + Some((b'-', d)) => (true, d), + _ => (false, w), + }; + if d.is_empty() || d.len() > 20 || !d.iter().all(u8::is_ascii_digit) { + return None; + } + if d[0] == b'0' && (d.len() > 1 || neg) { + return None; + } + let m: i128 = std::str::from_utf8(d).ok()?.parse().ok()?; + Some(if neg { -m } else { m }) +} + +/// Some number `v` with `lo <= v <= hi` has a decimal text (as [`number_value`] reads it) that +/// starts with `p`. +pub fn number_prefix_ok(p: &[u8], lo: i128, hi: i128) -> bool { + if p.is_empty() { + return lo <= hi; + } + let (neg, d) = match p.split_first() { + Some((b'-', d)) => (true, d), + _ => (false, p), + }; + if !d.iter().all(u8::is_ascii_digit) { + return false; + } + // The magnitudes of the values of the sign `p` has. + let (mlo, mhi) = if neg { + if lo > -1 { + return false; + } + ((-hi).max(1), -lo) + } else { + if hi < 0 { + return false; + } + (lo.max(0), hi) + }; + if mlo > mhi { + return false; + } + if d.is_empty() { + return true; + } + if d[0] == b'0' { + // Only "0" itself, and never "-0". + return d.len() == 1 && !neg && mlo == 0; + } + if d.len() > 20 { + return false; + } + let Some(dv) = std::str::from_utf8(d) + .ok() + .and_then(|s| s.parse::().ok()) + else { + return false; + }; + // Values whose text has `len` digits and starts with `d`: [dv * 10^k, (dv + 1) * 10^k - 1]. + let mut scale: i128 = 1; + for _ in d.len()..=20 { + let a = dv * scale; + let b = (dv + 1) * scale - 1; + if a > mhi { + return false; + } + if b >= mlo { + return true; + } + scale *= 10; + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Brute force over every value in a small range. + fn brute(p: &str, lo: i128, hi: i128) -> bool { + (lo..=hi).any(|v| v.to_string().starts_with(p)) + } + + #[test] + fn number_prefixes_match_brute_force() { + let ranges = [ + (0, 0), + (0, 255), + (-128, 127), + (-5, -1), + (1, 14), + (7, 1000), + (-1000, 3), + ]; + let mut prefixes = vec!["-".to_string(), "".to_string()]; + for n in 0..1200 { + prefixes.push(n.to_string()); + prefixes.push(format!("-{n}")); + } + prefixes.extend(["00", "01", "-0", "-00", "0-", "1a"].map(String::from)); + for &(lo, hi) in &ranges { + for p in &prefixes { + assert_eq!( + number_prefix_ok(p.as_bytes(), lo, hi), + brute(p, lo, hi), + "{p:?} in {lo}..={hi}" + ); + } + } + } + + #[test] + fn number_prefixes_at_the_64_bit_edges() { + let u = u64::MAX as i128; + assert!(number_prefix_ok(b"18446744073709551615", 0, u)); + assert!(!number_prefix_ok(b"18446744073709551616", 0, u)); + assert!(number_prefix_ok(b"1844674407370955161", 0, u)); + assert!(!number_prefix_ok(b"28446744073709551615", 0, u)); + assert!(number_prefix_ok(b"9", 0, u)); + let (lo, hi) = (i64::MIN as i128, i64::MAX as i128); + assert!(number_prefix_ok(b"-9223372036854775808", lo, hi)); + assert!(!number_prefix_ok(b"-9223372036854775809", lo, hi)); + assert!(!number_prefix_ok(b"123456789012345678901", 0, u)); + } + + #[test] + fn number_values_are_canonical() { + assert_eq!(number_value(b"0"), Some(0)); + assert_eq!(number_value(b"-7"), Some(-7)); + for bad in ["", "-", "-0", "007", "1x", "--1"] { + assert_eq!(number_value(bad.as_bytes()), None, "{bad}"); + } + } + + #[test] + fn words_names_and_separators() { + let items = vec![ + Item::Word(b"add".to_vec()), + Item::Word(b"a".to_vec()), + Item::NewName { + exclude: vec![b"a".to_vec()], + }, + Item::Space, + ]; + let s = ItemSet::new(&items, b"a").unwrap(); + assert!(s.extends(b"d") && s.extends(b"dd") && s.extends(b"x9")); + assert!(!s.extends(b"-") && !s.extends(b"=")); + assert!(s.completes(b"") && s.completes(b"dd") && s.completes(b"b")); + assert!(s.sep_offered(b' ') && s.sep_offered(b'\t') && !s.sep_offered(b'\n')); + assert!( + ItemSet::new(&items, b"x").is_err(), + "word a does not start with x" + ); + let only = ItemSet::new(&[Item::Word(b"end".to_vec())], b"").unwrap(); + assert!(only.extends(b"en") && !only.extends(b"enx") && !only.completes(b"en")); + assert_eq!(current_word(b"fn f a(uint"), b"uint"); + assert_eq!(current_word(b"ret a\n"), b""); + } + + #[test] + fn a_new_name_stops_at_63_characters() { + let ex = vec![b"x".repeat(63)]; + assert!(name_prefix_ok(&b"y".repeat(63), &ex)); + assert!(!name_prefix_ok(&b"x".repeat(63), &ex)); + assert!(!name_prefix_ok(&b"y".repeat(64), &ex)); + assert!(!name_prefix_ok(b"9a", &ex)); + } +} diff --git a/crates/aien-omegese-constraint/tests/common/mod.rs b/crates/aien-omegese-constraint/tests/common/mod.rs new file mode 100644 index 00000000..ea44f43a --- /dev/null +++ b/crates/aien-omegese-constraint/tests/common/mod.rs @@ -0,0 +1,171 @@ +//! Shared by the host tests: the 64-token synthetic table, an exact one-program oracle, and the +//! real binary's path from the environment. +#![allow(dead_code)] + +use std::path::PathBuf; +use std::process::Command; + +use aien_omegese_constraint::constraint::canonical_seps; +use aien_omegese_constraint::word::{current_word, is_sep}; +use aien_omegese_constraint::{Answer, Item, ItemOracle, Signature, TokenTable}; + +/// The synthetic table's stop token (a special token, no text). +pub const STOP: u32 = 63; + +/// 64 tokens for the 64-token `EchoChainModel`: every single byte Omegese uses (so a mask is +/// never empty), the fence, and multi-item tokens with one boundary (` add`, `end\n`, `a b`, +/// `)\n`, and ` \n`, a blank run that reads as its newline) and with two (` a `, `(b)`). +pub fn synthetic_texts() -> Vec>> { + let mut t: Vec>> = Vec::new(); + for c in b'a'..=b'z' { + t.push(Some(vec![c])); + } + for c in b'0'..=b'9' { + t.push(Some(vec![c])); + } + for s in [ + "_", "-", "=", " ", "\n", "(", ")", "`", "```", "end", "ret", "uint", " uint", " add", + " a", " b", "\n\n", ")\n", " (", "end\n", "a b", " a ", "(b)", "if", " \n", "\n```", "fn", + ] { + t.push(Some(s.as_bytes().to_vec())); + } + t.push(None); + assert_eq!(t.len(), 64); + assert_eq!(t[STOP as usize], None); + t +} + +pub fn synthetic_table() -> TokenTable { + TokenTable::from_texts(synthetic_texts()) +} + +pub fn sig_f() -> Signature { + Signature::from_requirement("entry f\nparams u32 u32\nret u32\n").unwrap() +} + +/// An exact oracle for the one-program language {`target`} (prefix-closed; `target` has single +/// blanks), blank runs read as Omegese reads them: what a writer may add is exactly the next +/// piece of `target`, or more blank space after blank space. +pub struct ExactText { + pub target: Vec, + pub calls: usize, +} + +impl ExactText { + pub fn new(target: &str) -> Self { + Self { + target: target.as_bytes().to_vec(), + calls: 0, + } + } +} + +impl ItemOracle for ExactText { + fn next(&mut self, raw: &[u8]) -> Result { + self.calls += 1; + // Blank runs read in canonical form, as Omegese reads them (the mask relies on it). + let p = &normalize(raw); + let t = &self.target; + if !t.starts_with(p) { + return Ok(Answer::Refused( + "REFUSED omegese: line 1: not the target".into(), + )); + } + let u = current_word(p); + let mut items = Vec::new(); + let word_end = t[p.len()..] + .iter() + .position(|&b| is_sep(b)) + .map_or(t.len(), |k| p.len() + k); + let start = p.len() - u.len(); + if word_end > start { + items.push(Item::Word(t[start..word_end].to_vec())); + } + if p.len() == t.len() { + items.push(Item::Eof); + } else if word_end == p.len() { + items.push(match t[p.len()] { + b' ' | b'\t' => Item::Space, + b'\n' => Item::Newline, + b'(' => Item::Open, + _ => Item::Close, + }); + } + // More blank space after blank space reads the same (the target has no two blanks in + // a row, so these are new items). + match p.last() { + Some(b' ') => items.push(Item::Space), + Some(b'\n') => items.extend([Item::Space, Item::Newline]), + _ => {} + } + Ok(Answer::Items(items)) + } +} + +/// Every separator run in `canonical_seps` form. +pub fn normalize(p: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < p.len() { + if is_sep(p[i]) { + let j = p[i..] + .iter() + .position(|&b| !is_sep(b)) + .map_or(p.len(), |k| i + k); + out.extend(canonical_seps(&p[i..j])); + i = j; + } else { + out.push(p[i]); + i += 1; + } + } + out +} + +/// `OMEGESE_BIN`: the `omegese` binary built from omega main (`make omegese`). The tests that need +/// it are `#[ignore]` and fail, never skip, when it is missing. +pub fn omegese_bin() -> PathBuf { + let p = std::env::var_os("OMEGESE_BIN") + .map(PathBuf::from) + .expect("set OMEGESE_BIN to the omegese binary built from omega main"); + assert!(p.is_file(), "OMEGESE_BIN {} is not a file", p.display()); + p +} + +fn scratch(name: &str, body: &[u8]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("omegese-constraint-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join(name); + std::fs::write(&p, body).unwrap(); + p +} + +/// `omegese emit` on `program`: `Ok(())` accepted, `Err(its line)` refused. +pub fn emit(bin: &PathBuf, program: &[u8]) -> Result<(), String> { + let src = scratch("emit.omegese", program); + let out = src.with_extension("json"); + let o = Command::new(bin) + .arg("emit") + .arg(&src) + .arg(&out) + .output() + .unwrap(); + match o.status.code() { + Some(0) => Ok(()), + _ => Err(String::from_utf8_lossy(&o.stdout).trim().to_string()), + } +} + +/// `omegese complete` on `prefix`: the text that finishes it. +pub fn complete(bin: &PathBuf, prefix: &[u8]) -> Result, String> { + let src = scratch("complete.omegese", prefix); + let o = Command::new(bin) + .arg("complete") + .arg(&src) + .output() + .unwrap(); + match o.status.code() { + Some(0) => Ok(o.stdout), + _ => Err(String::from_utf8_lossy(&o.stdout).trim().to_string()), + } +} diff --git a/crates/aien-omegese-constraint/tests/echo_walks.rs b/crates/aien-omegese-constraint/tests/echo_walks.rs new file mode 100644 index 00000000..5bcf27fe --- /dev/null +++ b/crates/aien-omegese-constraint/tests/echo_walks.rs @@ -0,0 +1,548 @@ +//! The guardrail end to end on the host fake `EchoChainModel` (ADR 0004 section 4) with the +//! 64-token synthetic table: exact walks, refusal through the rollback, the no-constraint path +//! byte for byte, and (with `OMEGESE_BIN`) random walks against the real oracle. + +mod common; + +use std::cell::RefCell; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; + +use aien_inference_abi::generation::echo_chain::EchoChainModel; +use aien_inference_abi::generation::{ + Constraint, ForwardPass, GenerationController, SampleNext, Sampler, Want, +}; +use aien_inference_abi::qwen3_moe_omega::{ + FinishReason, GenerateOutcome, GenerateParams, StepTiming, +}; +use aien_omegese_constraint::{ + Answer, Framing, ItemOracle, OmegeseConstraint, Shape, SubprocessOracle, TokenTable, +}; +use common::*; + +type Ctl = GenerationController; + +fn ctl(ctx: usize, graph: bool) -> Ctl { + let mut m = EchoChainModel::new(ctx); + m.graph_mode = graph; + GenerationController::new(m) +} + +fn prompt(n: usize, seed: usize) -> Vec { + (0..n) + .map(|i| ((i * 7 + seed * 13 + 1) % 63) as u32) + .collect() +} + +fn greedy(n: usize) -> GenerateParams { + GenerateParams::greedy(n, vec![STOP]) +} + +fn sampled(n: usize, seed: u64) -> GenerateParams { + GenerateParams { + max_new_tokens: n, + temperature: 1.0, + top_p: 1.0, + top_k: 0, + seed, + stop_token_ids: vec![STOP], + } +} + +fn run( + c: &mut Ctl, + p: &[u32], + params: &GenerateParams, + sampler: &mut dyn Sampler, + constraint: Option<&mut dyn Constraint>, +) -> Result<(Vec, GenerateOutcome), String> { + let mut out = Vec::new(); + let o = c.generate(p, params, sampler, constraint, &mut |t| { + out.push(t); + true + })?; + Ok((out, o)) +} + +fn run_sn( + c: &mut Ctl, + p: &[u32], + params: &GenerateParams, + constraint: Option<&mut dyn Constraint>, +) -> Result<(Vec, GenerateOutcome), String> { + run(c, p, params, &mut SampleNext(params.clone()), constraint) +} + +fn counted(o: &GenerateOutcome) -> GenerateOutcome { + GenerateOutcome { + prefill_ms: 0, + decode_ms: 0, + ..o.clone() + } +} + +fn full() -> Framing { + Framing { + open_fence: Some("```\n".into()), + header: Some(sig_f()), + mask_body: true, + close_fence: "```".into(), + stop_token: STOP, + } +} + +const TARGET: &str = "fn f a uint b uint to uint\nret add a b\nend\n"; + +/// Every walk under the exact one-program oracle writes the fence, the program (up to blank space) +/// and the closing fence, whatever tokens the model prefers, and stops on the stop token. +#[test] +fn exact_walks_write_the_one_program() { + let table = Arc::new(synthetic_table()); + let mut multi_item_picked = 0; + let mut multi_refused = 0; + for seed in 0..12 { + for params in [greedy(64), sampled(64, seed as u64 + 1)] { + let mut c = ctl(256, seed % 2 == 0); + let mut k = + OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), full()).unwrap(); + let (toks, o) = run_sn(&mut c, &prompt(9, seed), ¶ms, Some(&mut k)).unwrap(); + assert_eq!(o.finish, FinishReason::Stop, "seed {seed}"); + let text = table.decode(&toks).unwrap(); + let program = k.program().to_vec(); + assert_eq!(normalize(&program), TARGET.as_bytes(), "seed {seed}"); + let mut want = b"```\n".to_vec(); + want.extend(&program); + if !program.ends_with(b"\n") { + want.push(b'\n'); + } + want.extend(b"```"); + assert_eq!(text, want, "seed {seed}"); + assert!(k.finished()); + multi_item_picked += toks + .iter() + .filter(|&&t| { + matches!(table.shape(t), Shape::OneBoundary { .. }) + && table.text(t).unwrap().len() > 1 + }) + .count(); + multi_refused += k.stats().multi_boundary_refused; + } + } + assert!(multi_item_picked > 0, "some walk used a multi-item token"); + assert!(multi_refused > 0, "` a ` is refused where ` a` is legal"); +} + +/// The masked arm with no fence: the header is forced, the body masked, and eof is the stop token +/// itself, so the reply is the program and the run ends on stop. +#[test] +fn the_unfenced_arm_ends_on_the_stop_token() { + let table = Arc::new(synthetic_table()); + for seed in 0..6 { + for params in [greedy(64), sampled(64, seed as u64 + 31)] { + let arm = Framing { + open_fence: None, + ..full() + }; + let mut k = OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), arm).unwrap(); + let (toks, o) = run_sn( + &mut ctl(256, seed % 2 == 1), + &prompt(9, seed), + ¶ms, + Some(&mut k), + ) + .unwrap(); + assert_eq!(o.finish, FinishReason::Stop, "seed {seed}"); + let program = k.program().to_vec(); + assert_eq!(normalize(&program), TARGET.as_bytes(), "seed {seed}"); + assert_eq!( + table.decode(&toks).unwrap(), + program, + "the reply is the program" + ); + // Completion here is `FinishReason::Stop` (asserted above): the stop was allowed among + // blank tokens, not forced, so `finished()` cannot know it was taken. + assert!(!k.finished()); + } + } +} + +/// The fake oracle answers REFUSED (or breaks its contract) from its `n`th call on. +struct FailAt { + inner: O, + n: usize, + calls: usize, + broken: bool, +} + +impl ItemOracle for FailAt { + fn next(&mut self, p: &[u8]) -> Result { + self.calls += 1; + if self.calls >= self.n { + return if self.broken { + Err("oracle exit 0 with no item".into()) + } else { + Ok(Answer::Refused("REFUSED omegese: line 2: injected".into())) + }; + } + self.inner.next(p) + } +} + +/// A REFUSED answer ends the generation with `Err` after the controller's rollback: the ledger +/// keeps the tokens emitted before, every layer holds exactly the ledger, no head is pending, and +/// a warm run then equals a cold one. +#[test] +fn an_oracle_refusal_goes_through_the_rollback() { + let table = Arc::new(synthetic_table()); + let p = prompt(10, 3); + for broken in [false, true] { + // Call 1 is the header check when the constraint is built; call 2 is the first step. + for n in [2, 5] { + let mut c = ctl(256, true); + let oracle = FailAt { + inner: ExactText::new(TARGET), + n, + calls: 0, + broken, + }; + let mut k = OmegeseConstraint::new(table.clone(), oracle, full()).unwrap(); + let mut emitted = Vec::new(); + let r = c.generate( + &p, + &greedy(64), + &mut SampleNext(greedy(64)), + Some(&mut k), + &mut |t| { + emitted.push(t); + true + }, + ); + let e = r.expect_err("the refusal is an error"); + assert!( + e.contains(if broken { "no item" } else { "injected" }), + "{e}" + ); + assert!( + emitted.len() >= 2, + "the fence was forced before the oracle ran" + ); + assert_eq!(&c.history()[p.len()..], &emitted[..], "{n} {broken}"); + let pos = c.position(); + assert_eq!( + c.model().layer_lens(), + vec![pos; 2], + "every layer at the ledger" + ); + assert!( + c.model_mut() + .next(0, Want::Logits, &mut StepTiming::default()) + .is_err(), + "the rollback forgets the pending head" + ); + let mut q = c.history().to_vec(); + q.push(1); + let (warm, _) = run_sn(&mut c, &q, &greedy(12), None).unwrap(); + let (cold, _) = run_sn(&mut ctl(256, true), &q, &greedy(12), None).unwrap(); + assert_eq!(warm, cold); + } + } +} + +/// With every switch off the constraint answers `Any` on every step and the run is byte for byte +/// the run with no constraint (tokens, outcome, call log, head reads), with no oracle call. +#[test] +fn every_switch_off_is_byte_identical_to_no_constraint() { + let table = Arc::new(synthetic_table()); + let p = prompt(12, 19); + for graph in [false, true] { + for params in [ + GenerateParams::greedy(10, vec![]), + GenerateParams { + stop_token_ids: vec![], + ..sampled(10, 21) + }, + ] { + let mut a = ctl(128, graph); + let (ta, oa) = run_sn(&mut a, &p, ¶ms, None).unwrap(); + let mut b = ctl(128, graph); + let off = Framing { + open_fence: None, + header: None, + mask_body: false, + close_fence: "```".into(), + stop_token: STOP, + }; + let mut k = OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), off).unwrap(); + let (tb, ob) = run_sn(&mut b, &p, ¶ms, Some(&mut k)).unwrap(); + assert_eq!(ta, tb, "same tokens"); + assert_eq!(counted(&oa), counted(&ob), "same outcome and counters"); + assert_eq!(a.model().calls(), b.model().calls(), "same call log"); + let (ma, mb) = (a.model(), b.model()); + assert_eq!( + (ma.chip_reads, ma.lm_heads, ma.rows_reads), + (mb.chip_reads, mb.lm_heads, mb.rows_reads) + ); + assert_eq!(mb.rows_reads, 0, "next_rows is never called"); + assert_eq!(k.oracle().calls, 0, "no oracle call"); + assert_eq!(k.stats().forced_steps, 0); + } + } +} + +/// The unmasked arm: only the fence is forced; after it the model runs free, exactly as a run +/// whose prompt ended with the fence, and the oracle is never asked. +#[test] +fn the_fence_only_arm_forces_the_fence_and_nothing_else() { + let table = Arc::new(synthetic_table()); + let fence = table.encode("```\n").unwrap(); + let p = prompt(12, 5); + for params in [ + GenerateParams::greedy(12, vec![]), + GenerateParams { + stop_token_ids: vec![], + ..sampled(12, 9) + }, + ] { + let arm = Framing { + open_fence: Some("```\n".into()), + header: None, + mask_body: false, + close_fence: "```".into(), + stop_token: STOP, + }; + let mut k = OmegeseConstraint::new(table.clone(), ExactText::new(TARGET), arm).unwrap(); + let (t, _) = run_sn(&mut ctl(128, true), &p, ¶ms, Some(&mut k)).unwrap(); + assert_eq!(&t[..fence.len()], &fence[..]); + assert_eq!(k.oracle().calls, 0); + let mut q = p.clone(); + q.extend(&fence); + if params.temperature == 0.0 { + let (free, _) = run_sn( + &mut ctl(128, true), + &q, + &GenerateParams::greedy(12 - fence.len(), vec![]), + None, + ) + .unwrap(); + assert_eq!(&t[fence.len()..], &free[..], "the rest is the free run"); + } + } +} + +/// A seeded random walk among the allowed tokens, weighted by the fake's logits. From step +/// `steer_after` on it steers home: it takes the longest allowed token that starts what +/// `omegese complete` would write after the reply so far (shared through `reply`), or the closing +/// fence when the program is already whole. The constraint alone decides what is allowed. +struct Walk { + seed: u64, + table: Arc, + reply: Rc>>, + bin: PathBuf, + steer_after: Option, + plan: Vec, +} + +fn mix(mut x: u64) -> u64 { + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^ (x >> 31) +} + +impl Walk { + fn steer(&mut self, allowed: &[u32]) -> Option { + let text = self.table.decode(&self.reply.borrow()).ok()?; + let program = text.strip_prefix(b"```\n".as_slice())?; + // Keep one plan (the prefix plus `omegese complete`'s text) while the walk follows it: + // asking again after every token can loop (a name's first letters are a keyword). + if !self.plan.starts_with(program) { + self.plan = program.to_vec(); + self.plan.extend(complete(&self.bin, program).ok()?); + } + let rest = &self.plan[program.len()..]; + allowed + .iter() + .copied() + .filter(|&id| { + let t = self.table.text(id).unwrap_or_default(); + if rest.is_empty() { + t.contains(&b'`') + } else { + !t.is_empty() && rest.starts_with(t) + } + }) + .max_by_key(|&id| self.table.text(id).map_or(0, <[u8]>::len)) + } +} + +impl Sampler for Walk { + fn wants_logits(&self) -> bool { + true + } + fn pick(&mut self, logits: &[f32], step: usize) -> u32 { + let allowed: Vec = (0..logits.len() as u32) + .filter(|&i| logits[i as usize].is_finite()) + .collect(); + if self.steer_after.is_some_and(|s| step >= s) { + if let Some(t) = self.steer(&allowed) { + return t; + } + } + let w: Vec = allowed + .iter() + .map(|&i| (3.0 * logits[i as usize]).exp()) + .collect(); + let total: f32 = w.iter().sum(); + let r = (mix(self.seed ^ mix(step as u64)) >> 11) as f32 / (1u64 << 53) as f32 * total; + let mut acc = 0.0; + for (&i, &x) in allowed.iter().zip(&w) { + acc += x; + if acc >= r { + return i; + } + } + *allowed.last().unwrap_or(&0) + } +} + +/// With the real oracle (`OMEGESE_BIN`): every guardrail-on walk is sound. A walk that ended on +/// `eof` wrote a program `omegese emit` accepts, inside the fences; a walk cut by length wrote a +/// prefix `omegese complete` finishes into one `emit` accepts. +#[test] +#[ignore = "needs OMEGESE_BIN (the omegese binary built from omega main)"] +fn real_oracle_walks_write_programs_emit_accepts() { + let bin = omegese_bin(); + let table = Arc::new(synthetic_table()); + let (mut ended, mut cut, mut steps, mut calls, mut multi) = (0, 0, 0u64, 0u64, 0u64); + let mut times = Vec::new(); + for seed in 0..40u64 { + let mut c = ctl(512, seed % 2 == 0); + let oracle = SubprocessOracle::new(&bin).unwrap(); + let mut k = OmegeseConstraint::new(table.clone(), oracle, full()).unwrap(); + let reply = Rc::new(RefCell::new(Vec::new())); + // Every eighth walk never steers, so some walks are cut by length. + let steer_after = (seed % 8 != 7).then_some(20 + (seed as usize % 5) * 30); + let mut s = Walk { + seed, + table: table.clone(), + reply: reply.clone(), + bin: bin.clone(), + steer_after, + plan: Vec::new(), + }; + let params = sampled(300, seed + 1); + let p = prompt(8, seed as usize); + let o = c + .generate(&p, ¶ms, &mut s, Some(&mut k), &mut |t| { + reply.borrow_mut().push(t); + true + }) + .unwrap_or_else(|e| panic!("walk {seed}: {e}")); + let toks = reply.borrow().clone(); + let text = table.decode(&toks).unwrap(); + let program = k.program().to_vec(); + match o.finish { + FinishReason::Stop => { + ended += 1; + emit(&bin, &program).unwrap_or_else(|e| { + panic!( + "walk {seed}: emit refused {:?}: {e}", + String::from_utf8_lossy(&program) + ) + }); + let mut want = b"```\n".to_vec(); + want.extend(&program); + if !program.ends_with(b"\n") { + want.push(b'\n'); + } + want.extend(b"```"); + assert_eq!(text, want, "walk {seed}: the fences frame the program"); + } + FinishReason::Length => { + cut += 1; + let rest = complete(&bin, &program).unwrap_or_else(|e| { + panic!( + "walk {seed}: no completion for {:?}: {e}", + String::from_utf8_lossy(&program) + ) + }); + let mut whole = program.clone(); + whole.extend(&rest); + emit(&bin, &whole) + .unwrap_or_else(|e| panic!("walk {seed}: completed, refused: {e}")); + } + f => panic!("walk {seed}: finish {f:?}"), + } + let st = k.stats(); + steps += st.masked_steps; + calls += st.oracle_calls; + multi += st.multi_boundary_refused; + times.extend(st.step_times.iter().copied()); + } + times.sort(); + let us = |d: std::time::Duration| d.as_micros(); + println!( + "walks: {ended} ended on eof (emit accepted), {cut} cut by length (completed and accepted); \ + {steps} masked steps, {calls} oracle calls ({:.2} per step), {multi} two-boundary refusals; \ + step time median {} us, p95 {} us, max {} us", + calls as f64 / steps as f64, + us(times[times.len() / 2]), + us(times[times.len() * 95 / 100]), + us(times[times.len() - 1]), + ); + assert!( + ended >= 20 && cut >= 3, + "walks of both kinds ({ended} ended, {cut} cut)" + ); +} + +/// The mask reads every blank run in its canonical form (`canonical_seps`): one space, or one +/// newline when the run holds one. With the real oracle: at every cut of three programs, the +/// text after a blank run and after its canonical form gets the same items (or both are +/// refused), with brackets around and between the blanks too. +#[test] +#[ignore = "needs OMEGESE_BIN (the omegese binary built from omega main)"] +fn real_oracle_blank_runs_are_interchangeable() { + let mut oracle = SubprocessOracle::new(omegese_bin()).unwrap(); + let programs = [ + TARGET, + "fn gcd a uint b uint to uint\nwhile ne b 0 bound 100\nt = rem a b\na = b\nb = t\nend\nret a\nend\n", + "fn g v view uint 4 to uint\ns = uint 0\nfor i uint 4\ns = add s (get v i)\nend\nret s\nend\n", + ]; + let runs = [ + " ", "\t", " \t ", "\n\n", " \n", "\n ", "\n\t\n ", " (\t ", "( ", ")\n\n", ") \n ", + "\t)\t", " ((", "(\n\n", "() ", + ]; + let (mut compared, mut items_both) = (0, 0); + for prog in programs { + for cut in 0..=prog.len() { + let p = &prog.as_bytes()[..cut]; + for run in runs { + let canon = aien_omegese_constraint::constraint::canonical_seps(run.as_bytes()); + assert_ne!(canon, run.as_bytes(), "{run:?} is not already canonical"); + let ask = |o: &mut SubprocessOracle, s: &[u8]| { + let mut q = p.to_vec(); + q.extend_from_slice(s); + o.next(&q).unwrap() + }; + let (x, y) = (ask(&mut oracle, run.as_bytes()), ask(&mut oracle, &canon)); + match (&x, &y) { + (Answer::Items(a), Answer::Items(b)) => { + assert_eq!(a, b, "after {:?} + {run:?}", String::from_utf8_lossy(p)); + items_both += 1; + } + (Answer::Refused(_), Answer::Refused(_)) => {} + _ => panic!( + "after {:?}: {run:?} gives {x:?}, {:?} gives {y:?}", + String::from_utf8_lossy(p), + String::from_utf8_lossy(&canon) + ), + } + compared += 1; + } + } + } + println!("blank runs: {compared} pairs compared, {items_both} with items on both sides"); + assert!(items_both > 100); +} diff --git a/crates/aien-omegese-constraint/tests/mask_steps.rs b/crates/aien-omegese-constraint/tests/mask_steps.rs new file mode 100644 index 00000000..8a5db980 --- /dev/null +++ b/crates/aien-omegese-constraint/tests/mask_steps.rs @@ -0,0 +1,179 @@ +//! The mask step by step, without a model: a driver writes a known program through the +//! constraint, and at every masked step every allowed token is checked against an exact oracle +//! (soundness), not only the token the driver takes. + +mod common; + +use std::sync::Arc; + +use aien_inference_abi::generation::{Constraint, StepRule}; +use aien_omegese_constraint::{Answer, Framing, Item, ItemOracle, OmegeseConstraint, TokenTable}; +use common::*; + +const TARGET: &str = "fn f a uint b uint to uint\nret add a b\nend\n"; + +fn framing(fence: bool, header: bool) -> Framing { + Framing { + open_fence: fence.then(|| "```\n".into()), + header: header.then(sig_f), + mask_body: true, + close_fence: "```".into(), + stop_token: STOP, + } +} + +fn offers_eof(check: &mut ExactText, p: &[u8]) -> bool { + matches!(check.next(p).unwrap(), Answer::Items(i) if i.contains(&Item::Eof)) +} + +/// Writes `text` through `k`, the longest allowed token that continues it at each step (the +/// closing fence or the stop token at its end). At every `Allow` step every allowed token is +/// checked: a body token must leave a prefix `check` does not refuse, and a token that ends the +/// program (a fence marker, or the stop token) needs eof offered. Returns the tokens (stop +/// included) and how many allowed tokens were checked. +fn drive( + table: &TokenTable, + k: &mut OmegeseConstraint, + text: &str, + check: &mut ExactText, +) -> (Vec, usize) { + let mut gen: Vec = Vec::new(); + let mut checked = 0; + loop { + let rule = k.rule(&[], &gen).unwrap_or_else(|e| panic!("{e}")); + let prog = k.program().to_vec(); + assert!( + text.as_bytes().starts_with(&prog), + "the program left the text" + ); + let rest = &text.as_bytes()[prog.len()..]; + match rule { + StepRule::Force(id) => { + gen.push(id); + if id == STOP { + break; + } + } + StepRule::Allow(set) => { + for &id in &set { + checked += 1; + match table.text(id) { + None => assert!(offers_eof(check, &prog), "stop without eof"), + Some(t) if t.contains(&b'`') => { + assert!(offers_eof(check, &prog), "fence {t:?} without eof") + } + Some(t) => { + let mut p = prog.clone(); + p.extend_from_slice(t); + assert!( + matches!(check.next(&p).unwrap(), Answer::Items(_)), + "token {:?} allowed after {:?} leads nowhere", + String::from_utf8_lossy(t), + String::from_utf8_lossy(&prog) + ); + } + } + } + let pick = if rest.is_empty() { + set.iter() + .copied() + .find(|&id| table.text(id).is_none_or(|t| t.contains(&b'`'))) + .expect("eof offers the closing") + } else { + set.iter() + .copied() + .filter(|&id| table.text(id).is_some_and(|t| rest.starts_with(t))) + .max_by_key(|&id| table.text(id).unwrap().len()) + .unwrap_or_else(|| panic!("no allowed token writes {rest:?}")) + }; + gen.push(pick); + if pick == STOP { + break; + } + } + StepRule::Finish => break, + StepRule::Any => panic!("Any inside a masked body"), + } + } + (gen, checked) +} + +/// Every token the mask allows keeps the program a prefix of the target, in every framing, for a +/// target that ends on a newline and one that does not (eof right after `end`). +#[test] +fn every_allowed_token_keeps_the_target_reachable() { + let table = Arc::new(synthetic_table()); + let mut total = 0; + for target in [TARGET, TARGET.trim_end()] { + for (fence, header) in [(true, true), (false, true), (true, false), (false, false)] { + let mut k = OmegeseConstraint::new( + table.clone(), + ExactText::new(target), + framing(fence, header), + ) + .unwrap(); + let mut check = ExactText::new(target); + let (gen, checked) = drive(&table, &mut k, target, &mut check); + total += checked; + assert_eq!(k.program(), target.as_bytes()); + assert_eq!(*gen.last().unwrap(), STOP); + let reply = table.decode(&gen[..gen.len() - 1]).unwrap(); + let want = if fence { + let nl = if target.ends_with('\n') { "" } else { "\n" }; + format!("```\n{target}{nl}```") + } else { + target.to_string() + }; + assert_eq!(String::from_utf8(reply).unwrap(), want, "{fence} {header}"); + // Without a fence, after `end\n` the stop token is one choice among others (more blank + // space may follow): the constraint cannot tell a consumed stop from a cut by length + // after another token, so it claims the reply finished only when the stop was forced + // (after a bare `end` nothing else may follow). + let forced_stop = !target.ends_with('\n'); + assert_eq!(k.finished(), fence || forced_stop, "{fence} {header}"); + } + } + assert!(total > 100, "{total} tokens checked"); +} + +/// With no token that both starts the closing text and marks it, eof forces the closing: a +/// newline (the program ends on `end`), the fence one backtick at a time, then the stop token. +#[test] +fn the_closing_is_forced_when_no_token_marks_it() { + let mut texts = synthetic_texts(); + for t in texts.iter_mut() { + if t.as_deref() == Some(b"```") || t.as_deref() == Some(b"\n```") { + *t = Some(b"zz".to_vec()); + } + } + let table = Arc::new(TokenTable::from_texts(texts)); + let target = TARGET.trim_end(); + let mut k = + OmegeseConstraint::new(table.clone(), ExactText::new(target), framing(true, true)).unwrap(); + let mut check = ExactText::new(target); + let (gen, _) = drive(&table, &mut k, target, &mut check); + let tail: Vec = ["\n", "`", "`", "`"] + .iter() + .map(|s| table.encode(s).unwrap()[0]) + .chain([STOP]) + .collect(); + assert_eq!(&gen[gen.len() - 5..], &tail[..]); + let reply = table.decode(&gen[..gen.len() - 1]).unwrap(); + assert_eq!(reply, format!("```\n{target}\n```").into_bytes()); +} + +/// A header the oracle refuses is an error when the constraint is built, before anything is +/// written; with the mask off the header is not asked about. +#[test] +fn a_header_the_oracle_refuses_fails_at_construction() { + let table = Arc::new(synthetic_table()); + let other = "fn g a uint to uint\nret a\nend\n"; + let e = OmegeseConstraint::new(table.clone(), ExactText::new(other), framing(true, true)) + .err() + .expect("the header is refused"); + assert!(e.contains("refuses the header"), "{e}"); + let mut unmasked = framing(true, true); + unmasked.mask_body = false; + let k = OmegeseConstraint::new(table, ExactText::new(other), unmasked).unwrap(); + assert_eq!(k.oracle().calls, 0); +} diff --git a/crates/aien-omegese-constraint/tests/qwen_vocab.rs b/crates/aien-omegese-constraint/tests/qwen_vocab.rs new file mode 100644 index 00000000..a7fd92ed --- /dev/null +++ b/crates/aien-omegese-constraint/tests/qwen_vocab.rs @@ -0,0 +1,275 @@ +//! Host integration: the real Qwen vocabulary against the real oracle on the public dev programs. +//! Each program is walked through the constraint one step at a time; at every masked step the +//! token Qwen's own tokenizer would write next must be allowed, unless it crosses two word +//! boundaries (the one refusal the mapping makes on purpose), in which case the longest allowed +//! token that still writes the program is taken. Needs `OMEGESE_BIN`, `QWEN_TOKENIZER` (the +//! model's tokenizer.json) and `OMEGESE_DEV_DIRS` (colon-separated folders searched for +//! `*.omegese`). + +mod common; + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use aien_inference_abi::generation::{Constraint, StepRule}; +use aien_omegese_constraint::word::is_sep; +use aien_omegese_constraint::{ + Answer, Framing, ItemOracle, OmegeseConstraint, Shape, Signature, SubprocessOracle, TokenTable, +}; +use common::*; + +fn programs() -> Vec { + fn walk(d: &Path, out: &mut Vec) { + let mut es: Vec<_> = std::fs::read_dir(d) + .unwrap_or_else(|e| panic!("{}: {e}", d.display())) + .map(|e| e.unwrap().path()) + .collect(); + es.sort(); + for p in es { + if p.is_dir() { + walk(&p, out); + } else if p.extension().is_some_and(|x| x == "omegese") { + out.push(p); + } + } + } + let dirs = std::env::var("OMEGESE_DEV_DIRS").expect("set OMEGESE_DEV_DIRS"); + let mut out = Vec::new(); + for d in dirs.split(':').filter(|d| !d.is_empty()) { + walk(Path::new(d), &mut out); + } + assert!(!out.is_empty(), "no *.omegese under OMEGESE_DEV_DIRS"); + out +} + +#[derive(Default)] +struct Tally { + masked: u64, + canonical_ok: u64, + refused_multi: u64, + refused_other: Vec, + checked: u64, + unsound: Vec, + forced: u64, + calls: u64, + masked_out_multi: u64, + times: Vec, +} + +/// Walks `text` (a whole program) through a fresh constraint; returns what it saw. +fn walk(table: &Arc, bin: &Path, stop: u32, text: &str, header: bool, t: &mut Tally) { + let framing = Framing { + open_fence: Some("```\n".into()), + header: header.then(|| Signature::from_header(text.lines().next().unwrap()).unwrap()), + mask_body: true, + close_fence: "```".into(), + stop_token: stop, + }; + let oracle = SubprocessOracle::new(bin).unwrap(); + let mut check = SubprocessOracle::new(bin).unwrap(); + let mut k = OmegeseConstraint::new(table.clone(), oracle, framing).unwrap(); + let mut gen: Vec = Vec::new(); + loop { + let rule = k + .rule(&[], &gen) + .unwrap_or_else(|e| panic!("{e}\nafter {:?}", String::from_utf8_lossy(k.program()))); + let prog = k.program(); + assert!( + text.as_bytes().starts_with(prog), + "the program left the text" + ); + let rest = &text[prog.len()..]; + match rule { + StepRule::Force(id) => { + t.forced += 1; + gen.push(id); + if id == stop { + break; + } + } + StepRule::Allow(set) => { + t.masked += 1; + // Soundness: every allowed token that ends in a separator (the blank and bracket + // tokens among them) and about 8 others spread over the set must leave a prefix + // the oracle does not refuse. + let mut keys = HashSet::new(); + let spread = (set.len() / 8).max(1); + for (i, &id) in set.iter().enumerate() { + let Some(x) = table.text(id) else { continue }; + if x.contains(&b'`') + || !(x.last().is_some_and(|&b| is_sep(b)) || i % spread == 0) + { + continue; + } + let mut p = prog.to_vec(); + p.extend_from_slice(x); + if !keys.insert(normalize(&p)) { + continue; + } + t.checked += 1; + if let Answer::Refused(r) = check.next(&p).unwrap() { + t.unsound.push(format!( + "{:?} after {:?}: {r}", + String::from_utf8_lossy(x), + String::from_utf8_lossy(prog) + )); + } + } + if rest.is_empty() { + let close = set + .iter() + .copied() + .find(|&id| table.text(id).is_some_and(|x| x.contains(&b'`'))) + .expect("eof offers the closing fence"); + gen.push(close); + continue; + } + let canon = table.encode(rest).unwrap()[0]; + if set.binary_search(&canon).is_ok() { + t.canonical_ok += 1; + gen.push(canon); + continue; + } + let ct = String::from_utf8_lossy(table.text(canon).unwrap()).to_string(); + if table.shape(canon) == Shape::Multi { + t.refused_multi += 1; + } else { + t.refused_other + .push(format!("{ct:?} after {:?}", String::from_utf8_lossy(prog))); + } + let fallback = set + .iter() + .copied() + .filter(|&id| { + table + .text(id) + .is_some_and(|x| rest.as_bytes().starts_with(x)) + }) + .max_by_key(|&id| table.text(id).unwrap().len()) + .unwrap_or_else(|| panic!("no allowed token writes {rest:?}")); + gen.push(fallback); + } + StepRule::Finish => break, + StepRule::Any => panic!("Any inside a masked body"), + } + } + assert_eq!(k.program(), text.as_bytes()); + let reply = table.decode(&gen[..gen.len() - 1]).unwrap(); + assert_eq!(reply, format!("```\n{text}```").into_bytes()); + let st = k.stats(); + t.calls += st.oracle_calls; + t.masked_out_multi += st.multi_boundary_refused; + t.times.extend(st.step_times.iter().copied()); +} + +#[test] +#[ignore = "needs OMEGESE_BIN, QWEN_TOKENIZER and OMEGESE_DEV_DIRS"] +fn qwen_vocab_writes_every_dev_program_through_the_real_oracle() { + let bin = omegese_bin(); + let tok = std::env::var("QWEN_TOKENIZER").expect("set QWEN_TOKENIZER to tokenizer.json"); + let table = Arc::new(TokenTable::from_tokenizer_json(Path::new(&tok)).unwrap()); + let stop = table.special_id("<|im_end|>").expect("<|im_end|>"); + println!("vocabulary: {} tokens, stop {stop}", table.len()); + // The vocabulary by shape, over tokens made only of bytes Omegese text can hold. + let mut census = [0u64; 3]; + for id in 0..table.len() as u32 { + let Some(x) = table.text(id) else { continue }; + if !x + .iter() + .all(|&b| b.is_ascii_alphanumeric() || b"_-= \t\n()".contains(&b)) + { + continue; + } + census[match table.shape(id) { + Shape::Word => 0, + Shape::OneBoundary { .. } => 1, + _ => 2, + }] += 1; + } + println!( + "omegese-byte tokens: no boundary {}, one boundary {}, two or more boundaries {}", + census[0], census[1], census[2] + ); + assert!( + census[2] > 0, + "the vocabulary has tokens the mapping refuses" + ); + let mut all = Tally::default(); + for p in programs() { + let mut text = std::fs::read_to_string(&p).unwrap(); + if !text.ends_with('\n') { + text.push('\n'); + } + emit(&bin, text.as_bytes()).unwrap_or_else(|e| panic!("{}: {e}", p.display())); + let header_ok = Signature::from_header(text.lines().next().unwrap()).is_ok() + && text.starts_with("fn ") + && text.matches("\nfn ").count() == 0; + for header in [false, true] { + if header && !header_ok { + continue; + } + let mut t = Tally::default(); + walk(&table, &bin, stop, &text, header, &mut t); + println!( + "{} header={header}: masked {} canonical-ok {} two-boundary-refused {} other-refused {} forced {} oracle-calls {}", + p.display(), + t.masked, + t.canonical_ok, + t.refused_multi, + t.refused_other.len(), + t.forced, + t.calls + ); + all.masked += t.masked; + all.canonical_ok += t.canonical_ok; + all.refused_multi += t.refused_multi; + all.refused_other.extend(t.refused_other); + all.checked += t.checked; + all.unsound.extend(t.unsound); + all.forced += t.forced; + all.calls += t.calls; + all.masked_out_multi += t.masked_out_multi; + all.times.extend(t.times); + } + } + all.times.sort(); + let n = all.times.len(); + let us = |d: Duration| d.as_micros(); + let mean = all.times.iter().sum::() / n as u32; + println!( + "TOTAL masked {} canonical-ok {} two-boundary-refused {} other-refused {} forced {} oracle-calls {} ({:.2} per masked step); two-boundary tokens masked out (token x step) {}", + all.masked, + all.canonical_ok, + all.refused_multi, + all.refused_other.len(), + all.forced, + all.calls, + all.calls as f64 / all.masked as f64 +, + all.masked_out_multi + ); + println!( + "STEP LATENCY (oracle calls + vocabulary scan) over {n} masked steps: mean {} us, median {} us, p95 {} us, max {} us", + us(mean), + us(all.times[n / 2]), + us(all.times[n * 95 / 100]), + us(all.times[n - 1]) + ); + println!( + "SOUNDNESS {} allowed continuations checked against the oracle, {} refused", + all.checked, + all.unsound.len() + ); + assert!( + all.unsound.is_empty(), + "allowed tokens the oracle refuses: {:#?}", + all.unsound + ); + assert!( + all.refused_other.is_empty(), + "tokens refused although they cross at most one boundary: {:#?}", + all.refused_other + ); +} diff --git a/docs/inference/evidence/omegese-constraint-20261015/README.md b/docs/inference/evidence/omegese-constraint-20261015/README.md new file mode 100644 index 00000000..84ab4aab --- /dev/null +++ b/docs/inference/evidence/omegese-constraint-20261015/README.md @@ -0,0 +1,47 @@ +# Omegese constraint receipts (2026-10-15) + +Branch `feat/omegese-constraint` (PR #555), new crate `crates/aien-omegese-constraint`, built on main 9196c786 (ADR 0004 step 2, PR #550) and since merged up with main. Host only: no chip run, no GPU, and the 30B engine and the door untouched. Nothing in the workspace depends on the crate; with no constraint, generation is the step 2 loop unchanged. + +Oracle: `omegese next --machine`, built from aien-spark/omega 6c1827ba (`crates/aien-omegese-constraint/omegese.lock`; CI builds the same commit). The programs walked are the public dev programs (`tests/one_layer/omegese/dev`) and the arm examples (`tools/exp445/arms/examples`). No held-out task text was read. + +All receipts are at code commit 63bd631, after both review passes. + +| Gate | Receipt | Result | +|---|---|---| +| Host tests (`cargo test -p aien-omegese-constraint --no-fail-fast`, debug) | `host-tests.txt` | 24 passed, 0 failed, 3 ignored (the ignored ones need the real binary or the tokenizer and run below) | +| Exact-oracle walks on `EchoChainModel` (64-token synthetic table with one- and two-boundary tokens, ` \n` among them), 12 seeds, greedy and sampled | `host-tests.txt`, `exact_walks_write_the_one_program` | every walk writes the one target program inside the fences and ends on the stop token; multi-item tokens were picked; two-boundary tokens were refused and counted | +| Soundness step by step: every allowed token at every masked step checked against the exact oracle, for 2 targets (ending on a newline and not) × 4 framings | `host-tests.txt`, `every_allowed_token_keeps_the_target_reachable` | no allowed token leads nowhere; replies framed as asked | +| Forced closing when no token marks the fence; a header the oracle refuses fails when the constraint is built | `host-tests.txt`, `the_closing_is_forced_when_no_token_marks_it`, `a_header_the_oracle_refuses_fails_at_construction` | pass | +| A refusal goes through the rollback | `host-tests.txt`, `an_oracle_refusal_goes_through_the_rollback` | the history equals what was emitted, every layer at the ledger, the pending head forgotten, warm run equals cold run | +| Every switch off is byte-identical to no constraint (graph on and off, greedy and sampled) | `host-tests.txt`, `every_switch_off_is_byte_identical_to_no_constraint` | same tokens, outcome, call log and head reads; zero oracle calls | +| Fence-only arm; unfenced masked arm | `host-tests.txt`, `the_fence_only_arm_forces_the_fence_and_nothing_else`, `the_unfenced_arm_ends_on_the_stop_token` | the fence alone is forced, the rest is the free run; without a fence the reply is the program and ends on stop, and `finished()` claims completion only where the stop was forced (completion there is `FinishReason::Stop`) | +| Oracle process: a hung process is killed at the deadline; an early exit reports its own message | `host-tests.txt`, `a_hung_oracle_is_killed_at_the_deadline`, `an_early_exit_reports_its_own_message` | pass | +| Real oracle, 40 seeded walks on the synthetic table (`OMEGESE_BIN`, `--ignored`) | `real-oracle-walks.txt` | 35 walks ended on eof and `omegese emit` accepted all 35; 5 were cut by length, completed by `omegese complete`, and accepted; 5685 masked steps, 3.08 oracle calls per step | +| Blank-run equivalence the mask relies on (a run of blanks reads as one space, or as one newline if it holds one) | `real-oracle-walks.txt`, `real_oracle_blank_runs_are_interchangeable` | 3315 prefix pairs, identical item lists (881 with items on both sides) | +| Qwen vocabulary (151669 tokens, `~/models/qwen3-30b-a3b-instruct-2507-fp8/tokenizer.json`) on 25 dev programs, 47 walks (header forced and not), release build | `qwen-vocab-release.txt` | every program written exactly, reply = fence + program + fence; 2279 masked steps, 2232 took Qwen's own next token, the other 47 are the eof steps (the closing fence); 0 two-boundary refusals of Qwen's own token, 0 other refusals; soundness: 22134 allowed continuations checked against the oracle, 0 refused | +| Review MUST, red before green: a blank run holding a newline (` \n`) was checked against its space | `must1-red-run.txt` (the fix reverted on top of the new tests) | red: synthetic walks and the step-by-step check fail on ` \n` after `ret`; on Qwen 1364 of 22879 checked continuations refused. Green at 63bd631 (`host-tests.txt`, `qwen-vocab-release.txt`) | +| Red before green: ten mutants of `constraint.rs`, each alone, at 63bd631 | `mutants-red.txt` | each turns at least one test red: M1 two-boundary tokens allowed; M2 separators unchecked; M3 the part after the separators unchecked; M4 switch off masks instead of `Any`; M5 a refusal read as `Any`; M6 the first separator read raw; M7 eof tokens without a backtick; M8 the closing rewritten from the start; M9 no forced closing; M10 header not checked | +| `cargo clippy -p aien-omegese-constraint --all-targets -- -D warnings`, `cargo fmt --all` | run locally, and CI | clean | + +## The mapping rule, measured on Qwen + +Of the tokens made only of bytes Omegese text can hold: + +- 34823 cross no word boundary; +- 45553 cross one; +- 35 cross two or more. + +The 35 are always refused: 72655 token-step refusals were counted over the 2279 masked steps. Qwen's own tokenizer never chose one of them on the dev programs, so the refusal cost nothing there. + +## Per-step latency + +Wall time of one masked step: its oracle calls (one subprocess each) plus the scan of the vocabulary. The machine was shared with other sessions. + +| Build, table | Steps | Calls per step | Median | p95 | Max | +|---|---|---|---|---|---| +| release, Qwen 151669 | 2279 | 6.62 | 13.4 ms | 20.6 ms | 26.5 ms | +| debug, synthetic 64 | 5685 | 3.08 | 2.8 ms | 5.1 ms | 8.3 ms | + +`SHA256SUMS` lists the receipts. + +CALC-EXEMPT: every figure above is copied from a receipt line, not derived. diff --git a/docs/inference/evidence/omegese-constraint-20261015/SHA256SUMS b/docs/inference/evidence/omegese-constraint-20261015/SHA256SUMS new file mode 100644 index 00000000..e22b96a9 --- /dev/null +++ b/docs/inference/evidence/omegese-constraint-20261015/SHA256SUMS @@ -0,0 +1,5 @@ +59845d1af4a01979238448764d91ef9327987a954e48968dbbd6037a750cabde ./host-tests.txt +f2549e66ec9831918d51297dc5bea79e3be9105d5e09ae83f08da5b8838fd173 ./must1-red-run.txt +27a2e87e786515c44de710f3db2300944082936d80665811935990394d509ee7 ./mutants-red.txt +d49e4cdbf375db23d314c617ca5f85bd7ee0a2948ba9d9eb7b31308de48ca13f ./qwen-vocab-release.txt +39640528f19ca8b4b33ce16686deb1ad3016965c13b2f4aa667afbe6374c03a6 ./real-oracle-walks.txt diff --git a/docs/inference/evidence/omegese-constraint-20261015/host-tests.txt b/docs/inference/evidence/omegese-constraint-20261015/host-tests.txt new file mode 100644 index 00000000..e493cf43 --- /dev/null +++ b/docs/inference/evidence/omegese-constraint-20261015/host-tests.txt @@ -0,0 +1,60 @@ +warning: aien-omega-gpu@0.1.0: aien-omega-gpu: no AIEN_OMEGA_DIR or AIEN_OMEGA_GPU_LIB, building the CPU stub + Compiling aien-omegese-constraint v0.1.0 (/home/drakestapleton/workspace/g2-omegese-constraint/crates/aien-omegese-constraint) + Finished `test` profile [unoptimized + debuginfo] target(s) in 1.11s + Running unittests src/lib.rs (target/debug/deps/aien_omegese_constraint-8160e7c2b7bf0f23) + +running 16 tests +test oracle::tests::numbers_span_u64_and_i64 ... ok +test constraint::tests::blank_runs_shrink_to_one_byte ... ok +test signature::tests::header_lines_round_trip ... ok +test signature::tests::requirement_lines_make_the_header ... ok +test oracle::tests::the_section_6_2_example_parses ... ok +test table::tests::greedy_encoding_round_trips ... ok +test oracle::tests::refusals_and_contract_breaks ... ok +test table::tests::shapes ... ok +test word::tests::a_new_name_stops_at_63_characters ... ok +test word::tests::number_prefixes_at_the_64_bit_edges ... ok +test word::tests::words_names_and_separators ... ok +test table::tests::the_byte_alphabet_is_a_bijection ... ok +test word::tests::number_values_are_canonical ... ok +test oracle::tests::an_early_exit_reports_its_own_message ... ok +test oracle::tests::a_hung_oracle_is_killed_at_the_deadline ... ok +test word::tests::number_prefixes_match_brute_force ... ok + +test result: ok. 16 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.43s + + Running tests/echo_walks.rs (target/debug/deps/echo_walks-fc75283c9bfd6772) + +running 7 tests +test real_oracle_blank_runs_are_interchangeable ... ignored, needs OMEGESE_BIN (the omegese binary built from omega main) +test real_oracle_walks_write_programs_emit_accepts ... ignored, needs OMEGESE_BIN (the omegese binary built from omega main) +test the_fence_only_arm_forces_the_fence_and_nothing_else ... ok +test every_switch_off_is_byte_identical_to_no_constraint ... ok +test an_oracle_refusal_goes_through_the_rollback ... ok +test the_unfenced_arm_ends_on_the_stop_token ... ok +test exact_walks_write_the_one_program ... ok + +test result: ok. 5 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.52s + + Running tests/mask_steps.rs (target/debug/deps/mask_steps-80da51caac9849fa) + +running 3 tests +test a_header_the_oracle_refuses_fails_at_construction ... ok +test the_closing_is_forced_when_no_token_marks_it ... ok +test every_allowed_token_keeps_the_target_reachable ... ok + +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s + + Running tests/qwen_vocab.rs (target/debug/deps/qwen_vocab-20f5027443064287) + +running 1 test +test qwen_vocab_writes_every_dev_program_through_the_real_oracle ... ignored, needs OMEGESE_BIN, QWEN_TOKENIZER and OMEGESE_DEV_DIRS + +test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s + + Doc-tests aien_omegese_constraint + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s + diff --git a/docs/inference/evidence/omegese-constraint-20261015/must1-red-run.txt b/docs/inference/evidence/omegese-constraint-20261015/must1-red-run.txt new file mode 100644 index 00000000..4ba3fc17 --- /dev/null +++ b/docs/inference/evidence/omegese-constraint-20261015/must1-red-run.txt @@ -0,0 +1,19 @@ +=== MUST 1 red run: first separator read raw, here.sep_offered(t[0]), on top of 5daf9dc with the new tests +thread 'exact_walks_write_the_one_program' (2442690) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:109:85: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\nret add a \\n\"" +thread 'real_oracle_walks_write_programs_emit_accepts' (2470361) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:439:33: +walk 1: the oracle refused the program so far (REFUSED omegese: line 5: 'adky6qp' does not start a line (a name =, if, while, for, ret, put, free, trap, break, else, end, or a call)); program: "fn f a uint b uint to uint\nro add b a\n\nzecv4 ( a) \n adky6qp \n" +thread 'the_unfenced_arm_ends_on_the_stop_token' (2471287) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:154:14: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\n\\n\\n\\nret add a \\n\"" +test result: FAILED. 4 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.04s +--- mask_steps alone (cargo stops at the first red binary above) +thread 'every_allowed_token_keeps_the_target_reachable' (2475034) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +token " \n" allowed after "fn f a uint b uint to uint\nret" leads nowhere +thread 'the_closing_is_forced_when_no_token_marks_it' (2475040) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +token " \n" allowed after "fn f a uint b uint to uint\nret" leads nowhere +test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s +--- qwen_vocab (release) with the same revert +TOTAL masked 2279 canonical-ok 2232 two-boundary-refused 0 other-refused 0 forced 404 oracle-calls 15086 (6.62 per masked step); two-boundary tokens masked out (token x step) 72655 +SOUNDNESS 22879 allowed continuations checked against the oracle, 1364 refused +thread 'qwen_vocab_writes_every_dev_program_through_the_real_oracle' (2488138) panicked at crates/aien-omegese-constraint/tests/qwen_vocab.rs:265:5: +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 64.85s diff --git a/docs/inference/evidence/omegese-constraint-20261015/mutants-red.txt b/docs/inference/evidence/omegese-constraint-20261015/mutants-red.txt new file mode 100644 index 00000000..d981b195 --- /dev/null +++ b/docs/inference/evidence/omegese-constraint-20261015/mutants-red.txt @@ -0,0 +1,146 @@ +=== mutant M1-multi-allowed at 63bd631: perl -0pi -e 's/(\s+)multi \+= 1;/$1multi += 1;$1allowed.push(id);/' ++ allowed.push(id); +thread 'exact_walks_write_the_one_program' (222428) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:109:85: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\n a \"" +thread 'real_oracle_walks_write_programs_emit_accepts' (250021) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:441:33: +walk 1: the oracle refused the program so far (REFUSED omegese: line 7: extra words at the end of the line: 'a'); program: "fn f a uint b uint to uint\ntn add uint a add b b\n\ny add a 8 \n\n\ncjv9sq(b) a " +thread 'the_unfenced_arm_ends_on_the_stop_token' (250910) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:154:14: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\n\\n\\n\\n a \"" +test result: FAILED. 4 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.33s +error: test failed, to rerun pass `-p aien-omegese-constraint --test echo_walks` +thread 'every_allowed_token_keeps_the_target_reachable' (250913) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +thread 'the_closing_is_forced_when_no_token_marks_it' (250914) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 2 targets failed: +=== mutant M2-separators-unchecked at 63bd631: perl -0pi -e 's/if !\(a\.is_empty\(\) && i == 0\) \{/if false {/' +- if !(a.is_empty() && i == 0) { ++ if false { +thread 'an_oracle_refusal_goes_through_the_rollback' (251753) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:222:13: +the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: "fn f a uint b uint to uint\n (" +thread 'exact_walks_write_the_one_program' (251762) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:109:85: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\nret add a (\"" +thread 'real_oracle_walks_write_programs_emit_accepts' (279065) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:441:33: +walk 1: the oracle refused the program so far (REFUSED omegese: line 5: ( ... ) must hold exactly one value; '(' is extra); program: "fn f a uint b uint to uint\ntn uint add a a\n\nbdw0 b \nzfn uint(long add b b (" +thread 'the_unfenced_arm_ends_on_the_stop_token' (279742) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:154:14: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\n\\n\\n (\"" +test result: FAILED. 3 passed; 4 failed; 0 ignored; 0 measured; 0 filtered out; finished in 4.99s +error: test failed, to rerun pass `-p aien-omegese-constraint --test echo_walks` +thread 'every_allowed_token_keeps_the_target_reachable' (279781) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +thread 'the_closing_is_forced_when_no_token_marks_it' (279783) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 2 targets failed: +=== mutant M3-after-part-unchecked at 63bd631: perl -0pi -e 's/if b\.is_empty\(\)\n(\s+)\|\| self/if true\n$1|| self/' +- if b.is_empty() ++ if true +thread 'an_oracle_refusal_goes_through_the_rollback' (280883) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:222:13: +the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: "fn f a uint b uint to uint\n add" +thread 'exact_walks_write_the_one_program' (280889) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:109:85: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\n a\"" +thread 'real_oracle_walks_write_programs_emit_accepts' (308328) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:441:33: +walk 1: the oracle refused the program so far (REFUSED omegese: line 2: no text after this prefix makes a program emit accepts (extra words at the end of the line: 'add')); program: "fn f a uint b uint to uint\nro add add a a uint b add" +thread 'the_unfenced_arm_ends_on_the_stop_token' (308836) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:154:14: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\n\\n\\n add\"" +test result: FAILED. 3 passed; 4 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.06s +error: test failed, to rerun pass `-p aien-omegese-constraint --test echo_walks` +thread 'every_allowed_token_keeps_the_target_reachable' (308839) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +thread 'the_closing_is_forced_when_no_token_marks_it' (308840) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 2 targets failed: +=== mutant M4-switch-off-masks-everything at 63bd631: perl -0pi -e 's/Phase::Body if !self\.framing\.mask_body => StepRule::Any,/Phase::Body if !self.framing.mask_body => StepRule::Allow((0..self.table.len() as u32).filter(|\&i| i != self.framing.stop_token).collect()),/' +- Phase::Body if !self.framing.mask_body => StepRule::Any, ++ Phase::Body if !self.framing.mask_body => StepRule::Allow((0..self.table.len() as u32).filter(|&i| i != self.framing.stop_token).collect()), +thread 'every_switch_off_is_byte_identical_to_no_constraint' (309296) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:282:13: +assertion `left == right` failed + left: (0, 10, 0) + right: (0, 10, 10) +thread 'the_fence_only_arm_forces_the_fence_and_nothing_else' (414815) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:328:13: +assertion `left == right` failed: the rest is the free run + left: [18, 26, 26, 40, 4, 32, 34, 37, 61, 24] + right: [63, 12, 1, 36, 45, 63, 62, 3, 25, 49] +test result: FAILED. 5 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 37.97s +error: test failed, to rerun pass `-p aien-omegese-constraint --test echo_walks` +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s +error: 1 target failed: +=== mutant M5-refusal-means-anything at 63bd631: perl -0pi -e 's/Answer::Refused\(line\) => \{\n\s+return Err\(format!\(\n\s+"the oracle refused the program so far \(\{line\}\); program: \{:\?\}",\n\s+String::from_utf8_lossy\(&program\)\n\s+\)\)\n\s+\}/Answer::Refused(_line) => return Ok(StepRule::Any)/' +- Answer::Refused(line) => { +- return Err(format!( +- "the oracle refused the program so far ({line}); program: {:?}", +- String::from_utf8_lossy(&program) +- )) +- } ++ Answer::Refused(_line) => return Ok(StepRule::Any) +thread 'an_oracle_refusal_goes_through_the_rollback' (415317) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:221:23: +the refusal is an error: GenerateOutcome { emitted_tokens: 18, finish: Stop, prefill_ms: 1, decode_ms: 8, prompt_tokens: 10, reused_prompt_tokens: 0, decode_timing: StepTiming { total_ns: 0, attention_ns: 0, experts_ns: 0, lm_head_ns: 0, host_ns: 0, chip_ns: 0, launches: 18, route_ns: 0, moe_host_ns +test result: FAILED. 6 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 39.04s +error: test failed, to rerun pass `-p aien-omegese-constraint --test echo_walks` +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s +error: 1 target failed: +=== mutant M6-first-separator-read-raw at 63bd631: perl -0pi -e 's/here\.sep_offered\(seps\[0\]\)/here.sep_offered(t[0])/' +- here.sep_offered(seps[0]) ++ here.sep_offered(t[0]) +thread 'exact_walks_write_the_one_program' (524726) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:109:85: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\nret add a \\n\"" +thread 'real_oracle_walks_write_programs_emit_accepts' (552329) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:441:33: +walk 1: the oracle refused the program so far (REFUSED omegese: line 5: 'adky6qp' does not start a line (a name =, if, while, for, ret, put, free, trap, break, else, end, or a call)); program: "fn f a uint b uint to uint\nro add b a\n\nzecv4 ( a) \n adky6qp \n" +thread 'the_unfenced_arm_ends_on_the_stop_token' (553218) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:154:14: +called `Result::unwrap()` on an `Err` value: "the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: \"fn f a uint b uint to uint\\n\\n\\n\\nret add a \\n\"" +test result: FAILED. 4 passed; 3 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.26s +error: test failed, to rerun pass `-p aien-omegese-constraint --test echo_walks` +thread 'every_allowed_token_keeps_the_target_reachable' (553221) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +thread 'the_closing_is_forced_when_no_token_marks_it' (553222) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 2 targets failed: +=== mutant M7-eof-token-without-backtick at 63bd631: perl -0pi -e 's/if fits && t\.contains\(&b.`.\) \{/if fits {/' +- if fits && t.contains(&b'`') { ++ if fits { +test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 39.03s +thread 'every_allowed_token_keeps_the_target_reachable' (660736) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:68:29: +thread 'the_closing_is_forced_when_no_token_marks_it' (660737) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:43:57: +the oracle refused the program so far (REFUSED omegese: line 1: not the target); program: "fn f a uint b uint to uint\nret add a b\nend\n" +test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 1 target failed: +=== mutant M8-closing-rewritten-from-the-start at 63bd631: perl -0pi -e 's/let written = if c\.starts_with\(t\) \{ t\.len\(\) \} else \{ c\.len\(\) \};/let written = 0;/' +- let written = if c.starts_with(t) { t.len() } else { c.len() }; ++ let written = 0; +thread 'exact_walks_write_the_one_program' (661484) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:120:13: +assertion `left == right` failed: seed 0 + left: [96, 96, 96, 10, 102, 110, 32, 102, 32, 97, 32, 117, 105, 110, 116, 32, 98, 32, 117, 105, 110, 116, 32, 116, 111, 32, 117, 105, 110, 116, 10, 114, 101, 116, 32, 97, 100, 100, 32, 97, 32, 98, 32, 10, 101, 110, 100, 10, 96, 96, 96, 96] + right: [96, 96, 96, 10, 102, 110, 32, 102, 32, 97, 32, 117, 105, 110, 116, 32, 98, 32, 117, 105, 110, 116, 32, 116, 111, 32, 117, 105, 110, 116, 10, 114, 101, 116, 32, 97, 100, 100, 32, 97, 32, 98, 32, 10, 101, 110, 100, 10, 96, 96, 96] +thread 'real_oracle_walks_write_programs_emit_accepts' (691925) panicked at crates/aien-omegese-constraint/tests/echo_walks.rs:460:17: +assertion `left == right` failed: walk 0: the fences frame the program + left: [96, 96, 96, 10, 102, 110, 32, 102, 32, 97, 32, 117, 105, 110, 116, 32, 98, 32, 117, 105, 110, 116, 32, 116, 111, 32, 117, 105, 110, 116, 10, 105, 102, 110, 107, 115, 52, 99, 32, 117, 105, 110, 116, 32, 48, 10, 105, 102, 110, 107, 115, 52, 99, 32, 61, 32, 105, 102, 110, 107, 115, 52, 99, 10, + right: [96, 96, 96, 10, 102, 110, 32, 102, 32, 97, 32, 117, 105, 110, 116, 32, 98, 32, 117, 105, 110, 116, 32, 116, 111, 32, 117, 105, 110, 116, 10, 105, 102, 110, 107, 115, 52, 99, 32, 117, 105, 110, 116, 32, 48, 10, 105, 102, 110, 107, 115, 52, 99, 32, 61, 32, 105, 102, 110, 107, 115, 52, 99, 10, +test result: FAILED. 5 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.49s +error: test failed, to rerun pass `-p aien-omegese-constraint --test echo_walks` +thread 'every_allowed_token_keeps_the_target_reachable' (693145) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:127:13: +assertion `left == right` failed: true true + left: "```\nfn f a uint b uint to uint\nret add a b\nend\n````" + right: "```\nfn f a uint b uint to uint\nret add a b\nend\n```" +test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 2 targets failed: +=== mutant M9-no-forced-closing at 63bd631: perl -0pi -e 's/if allowed\.is_empty\(\) \{\n(\s+)\/\/ Eof is the only item/if false {\n$1\/\/ Eof is the only item/' +- if allowed.is_empty() { ++ if false { +test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 38.35s +thread 'the_closing_is_forced_when_no_token_marks_it' (813104) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:43:57: +test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 1 target failed: +=== mutant M10-header-not-checked at 63bd631: perl -0pi -e 's/if c\.framing\.mask_body && !c\.header_text\.is_empty\(\) \{/if false {/' +- if c.framing.mask_body && !c.header_text.is_empty() { ++ if false { +test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 38.86s +thread 'a_header_the_oracle_refuses_fails_at_construction' (919232) panicked at crates/aien-omegese-constraint/tests/mask_steps.rs:173:10: +the header is refused +test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s +error: test failed, to rerun pass `-p aien-omegese-constraint --test mask_steps` +error: 1 target failed: + M docs/inference/evidence/omegese-constraint-20261015/host-tests.txt + M docs/inference/evidence/omegese-constraint-20261015/qwen-vocab-release.txt + M docs/inference/evidence/omegese-constraint-20261015/real-oracle-walks.txt diff --git a/docs/inference/evidence/omegese-constraint-20261015/qwen-vocab-release.txt b/docs/inference/evidence/omegese-constraint-20261015/qwen-vocab-release.txt new file mode 100644 index 00000000..e33b9226 --- /dev/null +++ b/docs/inference/evidence/omegese-constraint-20261015/qwen-vocab-release.txt @@ -0,0 +1,62 @@ +warning: aien-omega-gpu@0.1.0: aien-omega-gpu: no AIEN_OMEGA_DIR or AIEN_OMEGA_GPU_LIB, building the CPU stub + Compiling aien-omegese-constraint v0.1.0 (/home/drakestapleton/workspace/g2-omegese-constraint/crates/aien-omegese-constraint) + Finished `release` profile [optimized] target(s) in 17.91s + Running tests/qwen_vocab.rs (target/release/deps/qwen_vocab-2fefa41431f6730e) + +running 1 test +test qwen_vocab_writes_every_dev_program_through_the_real_oracle ... vocabulary: 151669 tokens, stop 151645 +omegese-byte tokens: no boundary 34823, one boundary 45553, two or more boundaries 35 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev01.omegese header=false: masked 49 canonical-ok 48 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 298 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev01.omegese header=true: masked 39 canonical-ok 38 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 259 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev02.omegese header=false: masked 44 canonical-ok 43 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 282 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev02.omegese header=true: masked 34 canonical-ok 33 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 243 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev03.omegese header=false: masked 58 canonical-ok 57 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 400 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev03.omegese header=true: masked 50 canonical-ok 49 two-boundary-refused 0 other-refused 0 forced 12 oracle-calls 369 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev04.omegese header=false: masked 42 canonical-ok 41 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 250 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev04.omegese header=true: masked 33 canonical-ok 32 two-boundary-refused 0 other-refused 0 forced 13 oracle-calls 217 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev05.omegese header=false: masked 18 canonical-ok 17 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 86 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev05.omegese header=true: masked 8 canonical-ok 7 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 47 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev06.omegese header=false: masked 18 canonical-ok 17 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 86 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev06.omegese header=true: masked 8 canonical-ok 7 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 47 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev07.omegese header=false: masked 73 canonical-ok 72 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 520 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev07.omegese header=true: masked 65 canonical-ok 64 two-boundary-refused 0 other-refused 0 forced 12 oracle-calls 489 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev08.omegese header=false: masked 85 canonical-ok 84 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 592 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev08.omegese header=true: masked 76 canonical-ok 75 two-boundary-refused 0 other-refused 0 forced 13 oracle-calls 555 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev09.omegese header=false: masked 56 canonical-ok 55 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 388 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev09.omegese header=true: masked 47 canonical-ok 46 two-boundary-refused 0 other-refused 0 forced 13 oracle-calls 351 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev10.omegese header=false: masked 16 canonical-ok 15 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 75 +/home/drakestapleton/workspace/g2-omega-main/tests/one_layer/omegese/dev/dev10.omegese header=true: masked 7 canonical-ok 6 two-boundary-refused 0 other-refused 0 forced 13 oracle-calls 39 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/clamp_sub/program.omegese header=false: masked 29 canonical-ok 28 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 162 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/clamp_sub/program.omegese header=true: masked 19 canonical-ok 18 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 123 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/count_above/program.omegese header=false: masked 112 canonical-ok 111 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 678 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/count_digits/program.omegese header=false: masked 48 canonical-ok 47 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 298 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/count_digits/program.omegese header=true: masked 40 canonical-ok 39 two-boundary-refused 0 other-refused 0 forced 12 oracle-calls 267 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/cube_xor_pair/program.omegese header=false: masked 69 canonical-ok 68 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 444 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/cube_xor_pair/program.omegese header=true: masked 60 canonical-ok 59 two-boundary-refused 0 other-refused 0 forced 13 oracle-calls 407 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/dot3/program.omegese header=false: masked 144 canonical-ok 143 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 855 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/halve_or_dec_steps/program.omegese header=false: masked 69 canonical-ok 68 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 472 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/halve_or_dec_steps/program.omegese header=true: masked 58 canonical-ok 57 two-boundary-refused 0 other-refused 0 forced 15 oracle-calls 423 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/has_digit/program.omegese header=false: masked 67 canonical-ok 66 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 442 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/has_digit/program.omegese header=true: masked 57 canonical-ok 56 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 403 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/hash_step/program.omegese header=false: masked 23 canonical-ok 22 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 126 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/hash_step/program.omegese header=true: masked 13 canonical-ok 12 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 87 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/narrow_sum/program.omegese header=false: masked 19 canonical-ok 18 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 94 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/narrow_sum/program.omegese header=true: masked 9 canonical-ok 8 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 55 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/nibble_mirror/program.omegese header=false: masked 59 canonical-ok 58 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 396 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/nibble_mirror/program.omegese header=true: masked 50 canonical-ok 49 two-boundary-refused 0 other-refused 0 forced 13 oracle-calls 359 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/power_mod/program.omegese header=false: masked 103 canonical-ok 102 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 676 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/rotl8/program.omegese header=false: masked 44 canonical-ok 43 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 280 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/rotl8/program.omegese header=true: masked 33 canonical-ok 32 two-boundary-refused 0 other-refused 0 forced 15 oracle-calls 235 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/sum_range/program.omegese header=false: masked 55 canonical-ok 54 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 334 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/sum_range/program.omegese header=true: masked 45 canonical-ok 44 two-boundary-refused 0 other-refused 0 forced 14 oracle-calls 295 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/sum_squares3/program.omegese header=false: masked 30 canonical-ok 29 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 170 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/sum_squares3/program.omegese header=true: masked 16 canonical-ok 15 two-boundary-refused 0 other-refused 0 forced 18 oracle-calls 111 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/tri_kind/program.omegese header=false: masked 97 canonical-ok 96 two-boundary-refused 0 other-refused 0 forced 4 oracle-calls 674 +/home/drakestapleton/workspace/g2-omega-main/tools/exp445/arms/examples/tri_kind/program.omegese header=true: masked 85 canonical-ok 84 two-boundary-refused 0 other-refused 0 forced 16 oracle-calls 627 +TOTAL masked 2279 canonical-ok 2232 two-boundary-refused 0 other-refused 0 forced 404 oracle-calls 15086 (6.62 per masked step); two-boundary tokens masked out (token x step) 72655 +STEP LATENCY (oracle calls + vocabulary scan) over 2279 masked steps: mean 13692 us, median 13359 us, p95 20606 us, max 26537 us +SOUNDNESS 22134 allowed continuations checked against the oracle, 0 refused +ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 51.14s + diff --git a/docs/inference/evidence/omegese-constraint-20261015/real-oracle-walks.txt b/docs/inference/evidence/omegese-constraint-20261015/real-oracle-walks.txt new file mode 100644 index 00000000..fe9e1226 --- /dev/null +++ b/docs/inference/evidence/omegese-constraint-20261015/real-oracle-walks.txt @@ -0,0 +1,12 @@ +warning: aien-omega-gpu@0.1.0: aien-omega-gpu: no AIEN_OMEGA_DIR or AIEN_OMEGA_GPU_LIB, building the CPU stub + Finished `test` profile [unoptimized + debuginfo] target(s) in 0.10s + Running tests/echo_walks.rs (target/debug/deps/echo_walks-fc75283c9bfd6772) + +running 2 tests +test real_oracle_blank_runs_are_interchangeable ... blank runs: 3315 pairs compared, 881 with items on both sides +ok +test real_oracle_walks_write_programs_emit_accepts ... walks: 35 ended on eof (emit accepted), 5 cut by length (completed and accepted); 5685 masked steps, 17501 oracle calls (3.08 per step), 7575 two-boundary refusals; step time median 2756 us, p95 5110 us, max 8306 us +ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 5 filtered out; finished in 37.67s +