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 / oracle.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 | //! The item oracle: what may come next after a prefix of an Omegese program. |
| 17 | //! |
| 18 | //! The contract is the fixed grammar of `omegese next --machine` (omega |
| 19 | //! `docs/one_layer/OMEGESE.md` section 6.2): one item per line, exit 0 with at least one item, or |
| 20 | //! exit 1 with exactly one line starting `REFUSED omegese: `. [`ItemOracle`] is that contract as |
| 21 | //! a trait; [`SubprocessOracle`] runs the real binary once per query. |
| 22 | |
| 23 | use std::io::{Read, Write}; |
| 24 | use std::path::PathBuf; |
| 25 | use std::process::{Command, Stdio}; |
| 26 | use std::sync::mpsc; |
| 27 | use std::time::{Duration, Instant}; |
| 28 | |
| 29 | /// One line of `omegese next --machine`. Let U be the word still being written. |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub enum Item { |
| 32 | /// `word X`: finish the current word as X (X starts with U). |
| 33 | Word(Vec<u8>), |
| 34 | /// `newname E1 E2 ...`: finish the current word as any new name that starts with U, is not a |
| 35 | /// reserved word and is not one of `exclude`. |
| 36 | NewName { exclude: Vec<Vec<u8>> }, |
| 37 | /// `number LO HI`: finish the current word as a number in `lo..=hi` whose text starts with U. |
| 38 | Number { lo: i128, hi: i128 }, |
| 39 | /// `(`: an opening bracket (it also ends the current word). |
| 40 | Open, |
| 41 | /// `)`: a closing bracket (it also ends the current word). |
| 42 | Close, |
| 43 | /// `space`: a space or tab. |
| 44 | Space, |
| 45 | /// `newline`: ends the current word and the line. |
| 46 | Newline, |
| 47 | /// `eof`: the prefix is already an accepted program. |
| 48 | Eof, |
| 49 | } |
| 50 | |
| 51 | /// The oracle's answer for one prefix. |
| 52 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 53 | pub enum Answer { |
| 54 | /// Exit 0: at least one item. |
| 55 | Items(Vec<Item>), |
| 56 | /// Exit 1: no text after this prefix makes a program `omegese emit` accepts. The whole line. |
| 57 | Refused(String), |
| 58 | } |
| 59 | |
| 60 | /// What may come next after a prefix (section 6.2 is the contract). |
| 61 | pub trait ItemOracle { |
| 62 | /// The answer for `prefix`. `Err` only for a broken oracle (I/O, a line outside the grammar); |
| 63 | /// a prefix with no legal continuation is `Ok(Answer::Refused)`. |
| 64 | fn next(&mut self, prefix: &[u8]) -> Result<Answer, String>; |
| 65 | } |
| 66 | |
| 67 | impl<O: ItemOracle + ?Sized> ItemOracle for Box<O> { |
| 68 | fn next(&mut self, prefix: &[u8]) -> Result<Answer, String> { |
| 69 | (**self).next(prefix) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// Parses one `omegese next --machine` run: its stdout and whether it exited 0 (`true`) or 1. |
| 74 | pub fn parse_machine(stdout: &str, exit_zero: bool) -> Result<Answer, String> { |
| 75 | let lines: Vec<&str> = stdout.lines().collect(); |
| 76 | if !exit_zero { |
| 77 | return match lines.as_slice() { |
| 78 | [l] if l.starts_with("REFUSED omegese: ") => Ok(Answer::Refused(l.to_string())), |
| 79 | _ => Err(format!( |
| 80 | "oracle exit 1 must print exactly one REFUSED line, got {} lines", |
| 81 | lines.len() |
| 82 | )), |
| 83 | }; |
| 84 | } |
| 85 | if lines.is_empty() { |
| 86 | return Err("oracle exit 0 with no item".into()); |
| 87 | } |
| 88 | lines |
| 89 | .iter() |
| 90 | .map(|l| parse_item(l)) |
| 91 | .collect::<Result<Vec<_>, _>>() |
| 92 | .map(Answer::Items) |
| 93 | } |
| 94 | |
| 95 | fn parse_item(line: &str) -> Result<Item, String> { |
| 96 | let bad = || format!("oracle line outside the 6.2 grammar: {line:?}"); |
| 97 | let mut parts = line.split(' '); |
| 98 | let head = parts.next().ok_or_else(bad)?; |
| 99 | let rest: Vec<&str> = parts.collect(); |
| 100 | let item = match (head, rest.as_slice()) { |
| 101 | ("word", [x]) if !x.is_empty() => Item::Word(x.as_bytes().to_vec()), |
| 102 | ("newname", names) => Item::NewName { |
| 103 | exclude: names |
| 104 | .iter() |
| 105 | .map(|n| { |
| 106 | if n.is_empty() { |
| 107 | Err(bad()) |
| 108 | } else { |
| 109 | Ok(n.as_bytes().to_vec()) |
| 110 | } |
| 111 | }) |
| 112 | .collect::<Result<_, _>>()?, |
| 113 | }, |
| 114 | ("number", [lo, hi]) => { |
| 115 | let lo: i128 = lo.parse().map_err(|_| bad())?; |
| 116 | let hi: i128 = hi.parse().map_err(|_| bad())?; |
| 117 | if lo > hi { |
| 118 | return Err(bad()); |
| 119 | } |
| 120 | Item::Number { lo, hi } |
| 121 | } |
| 122 | ("(", []) => Item::Open, |
| 123 | (")", []) => Item::Close, |
| 124 | ("space", []) => Item::Space, |
| 125 | ("newline", []) => Item::Newline, |
| 126 | ("eof", []) => Item::Eof, |
| 127 | _ => return Err(bad()), |
| 128 | }; |
| 129 | Ok(item) |
| 130 | } |
| 131 | |
| 132 | /// How long one query may take before the process is killed and the query fails. |
| 133 | pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); |
| 134 | |
| 135 | /// The real oracle: `<bin> next --machine /dev/stdin`, the prefix on stdin, one process per query. |
| 136 | /// The binary's path is configuration (built from omega `tools/omegese/omegese.c`). A query |
| 137 | /// that has not answered within the timeout is killed and fails, which the generation loop |
| 138 | /// handles through its rollback. |
| 139 | pub struct SubprocessOracle { |
| 140 | bin: PathBuf, |
| 141 | timeout: Duration, |
| 142 | calls: u64, |
| 143 | elapsed: Duration, |
| 144 | } |
| 145 | |
| 146 | impl SubprocessOracle { |
| 147 | /// Checks that `bin` is a file; the first query proves it runs. The timeout is |
| 148 | /// [`DEFAULT_TIMEOUT`]. |
| 149 | pub fn new(bin: impl Into<PathBuf>) -> Result<Self, String> { |
| 150 | let bin = bin.into(); |
| 151 | if !bin.is_file() { |
| 152 | return Err(format!("omegese binary not found at {}", bin.display())); |
| 153 | } |
| 154 | Ok(Self { |
| 155 | bin, |
| 156 | timeout: DEFAULT_TIMEOUT, |
| 157 | calls: 0, |
| 158 | elapsed: Duration::ZERO, |
| 159 | }) |
| 160 | } |
| 161 | |
| 162 | /// The same oracle with another per-query timeout. |
| 163 | pub fn with_timeout(mut self, timeout: Duration) -> Self { |
| 164 | self.timeout = timeout; |
| 165 | self |
| 166 | } |
| 167 | |
| 168 | /// Queries made so far. |
| 169 | pub fn calls(&self) -> u64 { |
| 170 | self.calls |
| 171 | } |
| 172 | |
| 173 | /// Wall time spent in queries so far (spawn, write, wait, parse). |
| 174 | pub fn elapsed(&self) -> Duration { |
| 175 | self.elapsed |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | fn read_all(mut r: impl Read) -> std::io::Result<Vec<u8>> { |
| 180 | let mut v = Vec::new(); |
| 181 | r.read_to_end(&mut v).map(|_| v) |
| 182 | } |
| 183 | |
| 184 | impl ItemOracle for SubprocessOracle { |
| 185 | fn next(&mut self, prefix: &[u8]) -> Result<Answer, String> { |
| 186 | let t = Instant::now(); |
| 187 | let mut child = Command::new(&self.bin) |
| 188 | .args(["next", "--machine", "/dev/stdin"]) |
| 189 | .stdin(Stdio::piped()) |
| 190 | .stdout(Stdio::piped()) |
| 191 | .stderr(Stdio::piped()) |
| 192 | .spawn() |
| 193 | .map_err(|e| format!("spawn {}: {e}", self.bin.display()))?; |
| 194 | let mut stdin = child.stdin.take().ok_or("oracle stdin missing")?; |
| 195 | let stdout = child.stdout.take().ok_or("oracle stdout missing")?; |
| 196 | let stderr = child.stderr.take().ok_or("oracle stderr missing")?; |
| 197 | let timeout = self.timeout; |
| 198 | // One thread per pipe, so a prefix larger than the pipe buffer cannot deadlock against |
| 199 | // stdout; stdout closing (the process ending) is what the deadline waits for. |
| 200 | let (stdout, stderr, wrote, status) = std::thread::scope(|s| { |
| 201 | let w = s.spawn(move || stdin.write_all(prefix)); |
| 202 | let e = s.spawn(move || read_all(stderr)); |
| 203 | let (tx, rx) = mpsc::channel(); |
| 204 | s.spawn(move || tx.send(read_all(stdout))); |
| 205 | let out = match rx.recv_timeout(timeout) { |
| 206 | Ok(out) => out, |
| 207 | Err(_) => { |
| 208 | let _ = child.kill(); |
| 209 | let _ = child.wait(); |
| 210 | return Err(format!( |
| 211 | "the oracle gave no answer within {timeout:?}; killed it" |
| 212 | )); |
| 213 | } |
| 214 | }; |
| 215 | // Stdout closed; the process should be gone or going. Wait out the rest of the deadline. |
| 216 | let status = loop { |
| 217 | match child.try_wait() { |
| 218 | Ok(Some(st)) => break st, |
| 219 | Ok(None) if t.elapsed() < timeout => { |
| 220 | std::thread::sleep(Duration::from_micros(100)) |
| 221 | } |
| 222 | Ok(None) => { |
| 223 | let _ = child.kill(); |
| 224 | let _ = child.wait(); |
| 225 | return Err(format!( |
| 226 | "the oracle closed its answer but did not exit within {timeout:?}; killed it" |
| 227 | )); |
| 228 | } |
| 229 | Err(e) => return Err(format!("wait for the oracle: {e}")), |
| 230 | } |
| 231 | }; |
| 232 | let wrote = w |
| 233 | .join() |
| 234 | .map_err(|_| "oracle writer thread panicked".to_string())?; |
| 235 | let err = e |
| 236 | .join() |
| 237 | .map_err(|_| "oracle stderr thread panicked".to_string())? |
| 238 | .unwrap_or_default(); |
| 239 | let out = out.map_err(|e| format!("read the oracle's answer: {e}"))?; |
| 240 | Ok((out, err, wrote, status)) |
| 241 | })?; |
| 242 | self.calls += 1; |
| 243 | self.elapsed += t.elapsed(); |
| 244 | // The exit status first: a process that quit early also breaks the pipe it was fed by, |
| 245 | // and its own message says why. |
| 246 | let code = status.code(); |
| 247 | if !matches!(code, Some(0 | 1)) { |
| 248 | return Err(format!( |
| 249 | "oracle exit {code:?}: {}", |
| 250 | String::from_utf8_lossy(&stderr).trim() |
| 251 | )); |
| 252 | } |
| 253 | wrote.map_err(|e| format!("write the prefix to the oracle: {e}"))?; |
| 254 | let stdout = String::from_utf8(stdout).map_err(|_| "oracle stdout is not UTF-8")?; |
| 255 | parse_machine(&stdout, code == Some(0)) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | #[cfg(test)] |
| 260 | mod tests { |
| 261 | use super::*; |
| 262 | |
| 263 | #[test] |
| 264 | fn the_section_6_2_example_parses() { |
| 265 | let out = "word if\nword while\nword for\nword ret\nword trap\nword a\nnewname a f\nspace\nnewline\n"; |
| 266 | let Answer::Items(items) = parse_machine(out, true).unwrap() else { |
| 267 | panic!("items") |
| 268 | }; |
| 269 | assert_eq!(items.len(), 9); |
| 270 | assert_eq!(items[0], Item::Word(b"if".to_vec())); |
| 271 | assert_eq!( |
| 272 | items[6], |
| 273 | Item::NewName { |
| 274 | exclude: vec![b"a".to_vec(), b"f".to_vec()] |
| 275 | } |
| 276 | ); |
| 277 | assert_eq!(items[8], Item::Newline); |
| 278 | } |
| 279 | |
| 280 | #[test] |
| 281 | fn numbers_span_u64_and_i64() { |
| 282 | let out = |
| 283 | "number 0 18446744073709551615\nnumber -9223372036854775808 -1\n(\n)\neof\nnewname\n"; |
| 284 | let Answer::Items(items) = parse_machine(out, true).unwrap() else { |
| 285 | panic!("items") |
| 286 | }; |
| 287 | assert_eq!( |
| 288 | items[0], |
| 289 | Item::Number { |
| 290 | lo: 0, |
| 291 | hi: u64::MAX as i128 |
| 292 | } |
| 293 | ); |
| 294 | assert_eq!( |
| 295 | items[1], |
| 296 | Item::Number { |
| 297 | lo: i64::MIN as i128, |
| 298 | hi: -1 |
| 299 | } |
| 300 | ); |
| 301 | assert_eq!(&items[2..5], &[Item::Open, Item::Close, Item::Eof]); |
| 302 | assert_eq!(items[5], Item::NewName { exclude: vec![] }); |
| 303 | } |
| 304 | |
| 305 | #[test] |
| 306 | fn refusals_and_contract_breaks() { |
| 307 | let r = "REFUSED omegese: line 2: no text after this prefix makes a program emit accepts\n"; |
| 308 | assert!(matches!(parse_machine(r, false), Ok(Answer::Refused(_)))); |
| 309 | assert!(parse_machine("", true).is_err(), "exit 0 needs an item"); |
| 310 | assert!(parse_machine("", false).is_err(), "exit 1 needs its line"); |
| 311 | assert!(parse_machine("word if\n", false).is_err()); |
| 312 | assert!(parse_machine("word\n", true).is_err()); |
| 313 | assert!(parse_machine("word a b\n", true).is_err()); |
| 314 | assert!(parse_machine("number 5 1\n", true).is_err()); |
| 315 | assert!(parse_machine("number x 1\n", true).is_err()); |
| 316 | assert!(parse_machine("space \n", true).is_err()); |
| 317 | assert!(parse_machine("tab\n", true).is_err()); |
| 318 | } |
| 319 | |
| 320 | /// A stand-in binary: a shell script with `body`, in a fresh scratch folder. |
| 321 | fn script(name: &str, body: &str) -> PathBuf { |
| 322 | use std::os::unix::fs::PermissionsExt; |
| 323 | let dir = std::env::temp_dir().join(format!("omegese-oracle-{}", std::process::id())); |
| 324 | std::fs::create_dir_all(&dir).unwrap(); |
| 325 | let p = dir.join(name); |
| 326 | std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap(); |
| 327 | std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 328 | p |
| 329 | } |
| 330 | |
| 331 | #[test] |
| 332 | fn a_hung_oracle_is_killed_at_the_deadline() { |
| 333 | let bin = script("hang", "exec sleep 30"); |
| 334 | let mut o = SubprocessOracle::new(bin) |
| 335 | .unwrap() |
| 336 | .with_timeout(Duration::from_millis(200)); |
| 337 | let t = Instant::now(); |
| 338 | let e = o.next(b"fn f").unwrap_err(); |
| 339 | assert!(e.contains("no answer within"), "{e}"); |
| 340 | assert!(t.elapsed() < Duration::from_secs(5), "{:?}", t.elapsed()); |
| 341 | } |
| 342 | |
| 343 | #[test] |
| 344 | fn an_early_exit_reports_its_own_message() { |
| 345 | // The process quits without reading a prefix larger than the pipe buffer: its message |
| 346 | // is the error, not the broken pipe. |
| 347 | let bin = script("quit", "echo prefix too long >&2; exit 2"); |
| 348 | let mut o = SubprocessOracle::new(bin).unwrap(); |
| 349 | let e = o.next(&vec![b'a'; 1 << 20]).unwrap_err(); |
| 350 | assert!( |
| 351 | e.contains("exit Some(2)") && e.contains("prefix too long"), |
| 352 | "{e}" |
| 353 | ); |
| 354 | let bin = script("ok", "cat >/dev/null; echo eof"); |
| 355 | let mut o = SubprocessOracle::new(bin).unwrap(); |
| 356 | assert_eq!( |
| 357 | o.next(&vec![b'a'; 1 << 20]).unwrap(), |
| 358 | Answer::Items(vec![Item::Eof]) |
| 359 | ); |
| 360 | } |
| 361 | } |