aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-omegese-constraint / src / constraint.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! [`OmegeseConstraint`]: the chat framing (forced fence and header) and the per-step legal-token |
| 17 | //! mask from an [`ItemOracle`], as a [`Constraint`] for the generation controller. |
| 18 | |
| 19 | use std::collections::{HashMap, VecDeque}; |
| 20 | use std::sync::Arc; |
| 21 | use std::time::{Duration, Instant}; |
| 22 | |
| 23 | use aien_inference_abi::generation::{Constraint, StepRule}; |
| 24 | |
| 25 | use crate::oracle::{Answer, ItemOracle}; |
| 26 | use crate::signature::Signature; |
| 27 | use crate::table::{Shape, TokenTable}; |
| 28 | use crate::word::{current_word, ItemSet}; |
| 29 | |
| 30 | /// How the reply is framed and which parts are forced or masked. Each switch is independent, so |
| 31 | /// an experiment can run, for example, an unmasked arm with only the forced fence. |
| 32 | #[derive(Debug, Clone)] |
| 33 | pub struct Framing { |
| 34 | /// Forced first (e.g. "```\n"). `None`: no fence, and `eof` maps to the stop token alone. |
| 35 | pub open_fence: Option<String>, |
| 36 | /// Forced after the fence: the entry function's header line. |
| 37 | pub header: Option<Signature>, |
| 38 | /// Mask the program with the oracle. Off: after the forced parts every step is `Any`. |
| 39 | pub mask_body: bool, |
| 40 | /// Written when the oracle says `eof` and a fence was opened (after a newline if the program |
| 41 | /// does not end with one), e.g. "```". |
| 42 | pub close_fence: String, |
| 43 | /// Ends the reply (`<|im_end|>`): forced after the closing fence. |
| 44 | pub stop_token: u32, |
| 45 | } |
| 46 | |
| 47 | /// Counters for the experiment's records. |
| 48 | #[derive(Debug, Clone, Default)] |
| 49 | pub struct Stats { |
| 50 | /// Body steps that asked the oracle. |
| 51 | pub masked_steps: u64, |
| 52 | /// Steps answered `Force` (prelude, closing, or a mask with one legal token). |
| 53 | pub forced_steps: u64, |
| 54 | pub oracle_calls: u64, |
| 55 | /// Wall time inside oracle calls. |
| 56 | pub oracle_time: Duration, |
| 57 | /// Each masked step's wall time: its oracle calls plus the vocabulary scan. |
| 58 | pub step_times: Vec<Duration>, |
| 59 | /// Tokens refused only because they cross two word boundaries, summed over masked steps |
| 60 | /// (counted when the part before their second boundary passed the cheap filter). |
| 61 | pub multi_boundary_refused: u64, |
| 62 | } |
| 63 | |
| 64 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 65 | enum Phase { |
| 66 | /// Forcing `prelude[i]`. |
| 67 | Prelude(usize), |
| 68 | Body, |
| 69 | /// Forcing the rest of the closing fence, then the stop token. |
| 70 | Closing(VecDeque<u32>), |
| 71 | Done, |
| 72 | } |
| 73 | |
| 74 | /// The Omegese guardrail (ADR 0004 section 2.3, Drake's guardrail decision): forced fence, forced |
| 75 | /// header, the body masked to tokens that keep the program a prefix of one `omegese emit` |
| 76 | /// accepts, and `eof` mapped to the closing fence plus the stop token. |
| 77 | /// |
| 78 | /// Mapping rule, per masked step: one oracle call on the program so far gives the items. A token |
| 79 | /// of word bytes only is legal when the current word followed by it is still the start of some |
| 80 | /// item. A token with one run of separators (optional word bytes, separators, optional word |
| 81 | /// bytes) is legal when its word bytes before the separators complete an item (or it starts with |
| 82 | /// a separator run whose canonical first separator is printed), each of its separators is offered by the |
| 83 | /// answer for the text before it, and its word bytes after them start an item of the answer |
| 84 | /// after them. Blank runs are read in [`canonical_seps`] form, so all the whitespace tokens share |
| 85 | /// a few answers: one cached oracle call per distinct (word bytes, canonical separators) prefix |
| 86 | /// per step; a lone separator token needs none. A token with two separator runs is refused (sound, slightly incomplete; see |
| 87 | /// [`Stats::multi_boundary_refused`]). Only bytes Omegese can hold (letters, digits, `_ - =`, |
| 88 | /// space, tab, newline and brackets) are ever legal in the program. |
| 89 | pub struct OmegeseConstraint<O: ItemOracle> { |
| 90 | table: Arc<TokenTable>, |
| 91 | oracle: O, |
| 92 | framing: Framing, |
| 93 | prelude: Vec<u32>, |
| 94 | header_text: Vec<u8>, |
| 95 | /// The generated tokens this constraint has accounted for. |
| 96 | seen: Vec<u32>, |
| 97 | phase: Phase, |
| 98 | program: Vec<u8>, |
| 99 | /// The rule answered for the step whose token arrives next. |
| 100 | last: Option<StepRule>, |
| 101 | stats: Stats, |
| 102 | } |
| 103 | |
| 104 | /// A byte Omegese text may hold (omegese.c refuses every other one). |
| 105 | fn omegese_byte(b: u8) -> bool { |
| 106 | b.is_ascii_alphanumeric() |
| 107 | || matches!(b, b'_' | b'-' | b'=' | b' ' | b'\t' | b'\n' | b'(' | b')') |
| 108 | } |
| 109 | |
| 110 | impl<O: ItemOracle> OmegeseConstraint<O> { |
| 111 | pub fn new(table: Arc<TokenTable>, oracle: O, framing: Framing) -> Result<Self, String> { |
| 112 | if table.text(framing.stop_token).is_some() { |
| 113 | return Err(format!( |
| 114 | "the stop token {} is ordinary text, not a special token", |
| 115 | framing.stop_token |
| 116 | )); |
| 117 | } |
| 118 | if framing.stop_token as usize >= table.len() { |
| 119 | return Err(format!( |
| 120 | "the stop token {} is outside the vocabulary of {}", |
| 121 | framing.stop_token, |
| 122 | table.len() |
| 123 | )); |
| 124 | } |
| 125 | if framing.open_fence.is_some() && !framing.close_fence.contains('`') { |
| 126 | return Err("the closing fence must contain a backtick, the eof marker".into()); |
| 127 | } |
| 128 | let mut prelude = Vec::new(); |
| 129 | if let Some(f) = &framing.open_fence { |
| 130 | prelude.extend(table.encode(f)?); |
| 131 | } |
| 132 | let header_text = framing |
| 133 | .header |
| 134 | .as_ref() |
| 135 | .map(Signature::header) |
| 136 | .unwrap_or_default(); |
| 137 | if !header_text.is_empty() { |
| 138 | prelude.extend(table.encode(&header_text)?); |
| 139 | } |
| 140 | let mut c = Self { |
| 141 | table, |
| 142 | oracle, |
| 143 | framing, |
| 144 | prelude, |
| 145 | header_text: header_text.into_bytes(), |
| 146 | seen: Vec::new(), |
| 147 | phase: Phase::Done, |
| 148 | program: Vec::new(), |
| 149 | last: None, |
| 150 | stats: Stats::default(), |
| 151 | }; |
| 152 | c.restart(); |
| 153 | if c.framing.mask_body && !c.header_text.is_empty() { |
| 154 | // Refuse a header the oracle refuses now, before the fence and header are written. |
| 155 | let h = c.header_text.clone(); |
| 156 | if let Answer::Refused(line) = c.query(&h)? { |
| 157 | return Err(format!( |
| 158 | "the oracle refuses the header ({line}): {:?}", |
| 159 | String::from_utf8_lossy(&h) |
| 160 | )); |
| 161 | } |
| 162 | } |
| 163 | Ok(c) |
| 164 | } |
| 165 | |
| 166 | /// The program text written so far (the header included, the fences not). |
| 167 | pub fn program(&self) -> &[u8] { |
| 168 | &self.program |
| 169 | } |
| 170 | |
| 171 | pub fn stats(&self) -> &Stats { |
| 172 | &self.stats |
| 173 | } |
| 174 | |
| 175 | pub fn oracle(&self) -> &O { |
| 176 | &self.oracle |
| 177 | } |
| 178 | |
| 179 | /// True once the reply is complete: only the stop token is left to force (the controller |
| 180 | /// consumes it without showing it back) or it was emitted. Without a fence the stop token is |
| 181 | /// usually one choice among others at eof, and a consumed stop looks the same to the |
| 182 | /// constraint as a cut by length after another token; there completion is |
| 183 | /// `FinishReason::Stop`, and this is true only when the stop was forced. |
| 184 | pub fn finished(&self) -> bool { |
| 185 | let stop = self.framing.stop_token; |
| 186 | match &self.phase { |
| 187 | Phase::Done => true, |
| 188 | Phase::Closing(q) => q.len() == 1 && q[0] == stop, |
| 189 | Phase::Body if self.framing.mask_body && self.framing.open_fence.is_none() => { |
| 190 | match &self.last { |
| 191 | Some(StepRule::Force(t)) => *t == stop, |
| 192 | _ => false, |
| 193 | } |
| 194 | } |
| 195 | _ => false, |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | fn restart(&mut self) { |
| 200 | self.seen.clear(); |
| 201 | self.last = None; |
| 202 | self.program = self.header_text.clone(); |
| 203 | self.phase = if self.prelude.is_empty() { |
| 204 | Phase::Body |
| 205 | } else { |
| 206 | Phase::Prelude(0) |
| 207 | }; |
| 208 | } |
| 209 | |
| 210 | /// The text `eof` writes before the stop token. |
| 211 | fn closing_text(&self) -> Vec<u8> { |
| 212 | if self.framing.open_fence.is_none() { |
| 213 | return Vec::new(); |
| 214 | } |
| 215 | let mut c = Vec::new(); |
| 216 | if self.program.last().is_some_and(|&b| b != b'\n') { |
| 217 | c.push(b'\n'); |
| 218 | } |
| 219 | c.extend_from_slice(self.framing.close_fence.as_bytes()); |
| 220 | c |
| 221 | } |
| 222 | |
| 223 | /// The closing tokens after `written` bytes of the closing text, then the stop token. |
| 224 | fn closing_queue(&self, written: usize) -> Result<VecDeque<u32>, String> { |
| 225 | let c = self.closing_text(); |
| 226 | let mut q = VecDeque::new(); |
| 227 | if written < c.len() { |
| 228 | let rest = std::str::from_utf8(&c[written..]).map_err(|e| e.to_string())?; |
| 229 | q.extend(self.table.encode(rest)?); |
| 230 | } |
| 231 | q.push_back(self.framing.stop_token); |
| 232 | Ok(q) |
| 233 | } |
| 234 | |
| 235 | /// Accounts for the token the controller emitted after the last rule. |
| 236 | fn advance(&mut self, tok: u32) -> Result<(), String> { |
| 237 | let ok = match &self.last { |
| 238 | Some(StepRule::Force(t)) => *t == tok, |
| 239 | Some(StepRule::Allow(set)) => set.binary_search(&tok).is_ok(), |
| 240 | Some(StepRule::Any) => true, |
| 241 | Some(StepRule::Finish) | None => false, |
| 242 | }; |
| 243 | if !ok { |
| 244 | return Err(format!( |
| 245 | "token {tok} was emitted against the rule {:?}", |
| 246 | self.last |
| 247 | )); |
| 248 | } |
| 249 | self.seen.push(tok); |
| 250 | match &mut self.phase { |
| 251 | Phase::Prelude(i) => { |
| 252 | *i += 1; |
| 253 | if *i == self.prelude.len() { |
| 254 | self.phase = Phase::Body; |
| 255 | } |
| 256 | } |
| 257 | Phase::Body if !self.framing.mask_body => { |
| 258 | if let Some(t) = self.table.text(tok) { |
| 259 | self.program.extend_from_slice(t); |
| 260 | } |
| 261 | } |
| 262 | Phase::Body if tok == self.framing.stop_token => self.phase = Phase::Done, |
| 263 | Phase::Body => { |
| 264 | let t = self |
| 265 | .table |
| 266 | .text(tok) |
| 267 | .ok_or_else(|| format!("special token {tok} inside the program"))?; |
| 268 | if t.contains(&b'`') { |
| 269 | // The eof marker: the model began the closing fence. |
| 270 | let c = self.closing_text(); |
| 271 | let written = if c.starts_with(t) { t.len() } else { c.len() }; |
| 272 | self.phase = Phase::Closing(self.closing_queue(written)?); |
| 273 | } else { |
| 274 | self.program.extend_from_slice(t); |
| 275 | } |
| 276 | } |
| 277 | Phase::Closing(q) => { |
| 278 | q.pop_front(); |
| 279 | if q.is_empty() { |
| 280 | self.phase = Phase::Done; |
| 281 | } |
| 282 | } |
| 283 | Phase::Done => return Err(format!("token {tok} after the reply finished")), |
| 284 | } |
| 285 | Ok(()) |
| 286 | } |
| 287 | |
| 288 | fn query(&mut self, prefix: &[u8]) -> Result<Answer, String> { |
| 289 | let t = Instant::now(); |
| 290 | let r = self.oracle.next(prefix); |
| 291 | self.stats.oracle_calls += 1; |
| 292 | self.stats.oracle_time += t.elapsed(); |
| 293 | r |
| 294 | } |
| 295 | |
| 296 | /// The items after `program` + `key` (a key ending in a separator run is in canonical form), |
| 297 | /// one oracle call per distinct key per step; `None` when the oracle refuses it. |
| 298 | fn state<'c>( |
| 299 | &mut self, |
| 300 | cache: &'c mut HashMap<Vec<u8>, Option<ItemSet>>, |
| 301 | program: &[u8], |
| 302 | key: &[u8], |
| 303 | ) -> Result<Option<&'c ItemSet>, String> { |
| 304 | if !cache.contains_key(key) { |
| 305 | let mut p = program.to_vec(); |
| 306 | p.extend_from_slice(key); |
| 307 | let set = match self.query(&p)? { |
| 308 | Answer::Items(i) => Some(ItemSet::new(&i, current_word(&p))?), |
| 309 | Answer::Refused(_) => None, |
| 310 | }; |
| 311 | cache.insert(key.to_vec(), set); |
| 312 | } |
| 313 | Ok(cache[key].as_ref()) |
| 314 | } |
| 315 | |
| 316 | /// One masked step. |
| 317 | fn mask(&mut self) -> Result<StepRule, String> { |
| 318 | let t0 = Instant::now(); |
| 319 | let program = self.program.clone(); |
| 320 | let items = match self.query(&program)? { |
| 321 | Answer::Items(i) => i, |
| 322 | Answer::Refused(line) => { |
| 323 | return Err(format!( |
| 324 | "the oracle refused the program so far ({line}); program: {:?}", |
| 325 | String::from_utf8_lossy(&program) |
| 326 | )) |
| 327 | } |
| 328 | }; |
| 329 | let here = ItemSet::new(&items, current_word(&program))?; |
| 330 | // Text up to the end of a token's separators -> the items after it (None: refused). |
| 331 | let mut after: HashMap<Vec<u8>, Option<ItemSet>> = HashMap::new(); |
| 332 | let table = Arc::clone(&self.table); |
| 333 | let mut allowed = Vec::new(); |
| 334 | let mut multi = 0u64; |
| 335 | for id in 0..table.len() as u32 { |
| 336 | let (Some(t), shape) = (table.text(id), table.shape(id)) else { |
| 337 | continue; |
| 338 | }; |
| 339 | if !t.iter().all(|&b| omegese_byte(b)) { |
| 340 | continue; |
| 341 | } |
| 342 | match shape { |
| 343 | Shape::Special => {} |
| 344 | Shape::Word => { |
| 345 | if here.extends(t) { |
| 346 | allowed.push(id); |
| 347 | } |
| 348 | } |
| 349 | Shape::Multi => { |
| 350 | let a_end = t.iter().position(|&b| crate::word::is_sep(b)).unwrap_or(0); |
| 351 | let a = &t[..a_end]; |
| 352 | if (a.is_empty() && here.sep_offered(t[0])) |
| 353 | || (!a.is_empty() && here.completes(a)) |
| 354 | { |
| 355 | multi += 1; |
| 356 | } |
| 357 | } |
| 358 | Shape::OneBoundary { a_end, sep_end } => { |
| 359 | let (a, b) = (&t[..a_end], &t[sep_end..]); |
| 360 | // Canonical first: a blank run holding a newline reads as that newline, so a |
| 361 | // token like ` \n` must find the newline offered, not the space. |
| 362 | let seps = canonical_seps(&t[a_end..sep_end]); |
| 363 | let first_ok = if a.is_empty() { |
| 364 | here.sep_offered(seps[0]) |
| 365 | } else { |
| 366 | here.completes(a) |
| 367 | }; |
| 368 | if !first_ok { |
| 369 | continue; |
| 370 | } |
| 371 | if a.is_empty() && seps.len() == 1 && b.is_empty() { |
| 372 | // The separator's own item: exact by section 6.1. |
| 373 | allowed.push(id); |
| 374 | continue; |
| 375 | } |
| 376 | // Walk the separators one at a time: each must be offered by the state |
| 377 | // before it (the state at the program itself is `here`). |
| 378 | let mut key = a.to_vec(); |
| 379 | let mut ok = true; |
| 380 | for (i, &c) in seps.iter().enumerate() { |
| 381 | if !(a.is_empty() && i == 0) { |
| 382 | let st = self.state(&mut after, &program, &key)?; |
| 383 | if !st.is_some_and(|s| s.sep_offered(c)) { |
| 384 | ok = false; |
| 385 | break; |
| 386 | } |
| 387 | } |
| 388 | key.push(c); |
| 389 | } |
| 390 | if !ok { |
| 391 | continue; |
| 392 | } |
| 393 | if b.is_empty() |
| 394 | || self |
| 395 | .state(&mut after, &program, &key)? |
| 396 | .is_some_and(|s| s.extends(b)) |
| 397 | { |
| 398 | allowed.push(id); |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | let mut rule = None; |
| 404 | if here.eof() { |
| 405 | match &self.framing.open_fence { |
| 406 | None => allowed.push(self.framing.stop_token), |
| 407 | Some(_) => { |
| 408 | let c = self.closing_text(); |
| 409 | for id in 0..table.len() as u32 { |
| 410 | let Some(t) = table.text(id) else { continue }; |
| 411 | let fits = c.starts_with(t) |
| 412 | || t.strip_prefix(c.as_slice()) |
| 413 | .is_some_and(|r| r.iter().all(u8::is_ascii_whitespace)); |
| 414 | if fits && t.contains(&b'`') { |
| 415 | allowed.push(id); |
| 416 | } |
| 417 | } |
| 418 | if allowed.is_empty() { |
| 419 | // Eof is the only item and no token both starts the closing text and |
| 420 | // marks it with a backtick: force the closing. (When some body token is |
| 421 | // legal but no marking token fits, eof waits for a later step.) |
| 422 | let q = self.closing_queue(0)?; |
| 423 | let first = q[0]; |
| 424 | self.phase = Phase::Closing(q); |
| 425 | rule = Some(StepRule::Force(first)); |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | allowed.sort_unstable(); |
| 431 | allowed.dedup(); |
| 432 | self.stats.masked_steps += 1; |
| 433 | self.stats.multi_boundary_refused += multi; |
| 434 | self.stats.step_times.push(t0.elapsed()); |
| 435 | if let Some(r) = rule { |
| 436 | return Ok(r); |
| 437 | } |
| 438 | match allowed.as_slice() { |
| 439 | [] => Err(format!( |
| 440 | "no token is legal after {:?} although the oracle printed {} items (a single-byte \ |
| 441 | token should always continue an item)", |
| 442 | String::from_utf8_lossy(&program), |
| 443 | items.len() |
| 444 | )), |
| 445 | [t] => Ok(StepRule::Force(*t)), |
| 446 | _ => Ok(StepRule::Allow(allowed)), |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | impl<O: ItemOracle> Constraint for OmegeseConstraint<O> { |
| 452 | fn rule(&mut self, _prompt: &[u32], generated: &[u32]) -> Result<StepRule, String> { |
| 453 | if generated.is_empty() { |
| 454 | self.restart(); |
| 455 | } else if generated.len() == self.seen.len() + 1 && generated.starts_with(&self.seen) { |
| 456 | self.advance(generated[generated.len() - 1])?; |
| 457 | } else { |
| 458 | return Err(format!( |
| 459 | "the constraint saw {} tokens and is now shown {} that do not extend them", |
| 460 | self.seen.len(), |
| 461 | generated.len() |
| 462 | )); |
| 463 | } |
| 464 | let rule = match &self.phase { |
| 465 | Phase::Prelude(i) => StepRule::Force(self.prelude[*i]), |
| 466 | Phase::Body if !self.framing.mask_body => StepRule::Any, |
| 467 | Phase::Body => self.mask()?, |
| 468 | Phase::Closing(q) => StepRule::Force(q[0]), |
| 469 | Phase::Done => StepRule::Finish, |
| 470 | }; |
| 471 | if matches!(rule, StepRule::Force(_)) { |
| 472 | self.stats.forced_steps += 1; |
| 473 | } |
| 474 | self.last = Some(rule.clone()); |
| 475 | Ok(rule) |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | /// A separator run with every maximal run of blanks (space, tab, newline) written as one |
| 480 | /// newline if it holds one, else one space; brackets kept. Blank space between words is free in |
| 481 | /// Omegese and blank lines are empty lines, so the text after either form has the same items |
| 482 | /// (pinned against the real oracle by `real_oracle_blank_runs_are_interchangeable`). |
| 483 | pub fn canonical_seps(seps: &[u8]) -> Vec<u8> { |
| 484 | let mut out = Vec::with_capacity(seps.len()); |
| 485 | let mut blank: Option<u8> = None; |
| 486 | for &c in seps { |
| 487 | match c { |
| 488 | b' ' | b'\t' => { |
| 489 | blank.get_or_insert(b' '); |
| 490 | } |
| 491 | b'\n' => blank = Some(b'\n'), |
| 492 | _ => { |
| 493 | out.extend(blank.take()); |
| 494 | out.push(c); |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | out.extend(blank); |
| 499 | out |
| 500 | } |
| 501 | |
| 502 | #[cfg(test)] |
| 503 | mod tests { |
| 504 | use super::canonical_seps; |
| 505 | |
| 506 | #[test] |
| 507 | fn blank_runs_shrink_to_one_byte() { |
| 508 | for (run, want) in [ |
| 509 | (" ", " "), |
| 510 | ("\t \t", " "), |
| 511 | (" \n\t\n ", "\n"), |
| 512 | (")\n\n", ")\n"), |
| 513 | (" ( ", " ( "), |
| 514 | ("((", "(("), |
| 515 | ("\t)\t)\n ", " ) )\n"), |
| 516 | ] { |
| 517 | assert_eq!(canonical_seps(run.as_bytes()), want.as_bytes(), "{run:?}"); |
| 518 | } |
| 519 | } |
| 520 | } |