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 / tools / aien-test / src / manifest.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 | //! Gate manifest v1 parser (ADR 0028 Decision 3). Strict: unknown keys, |
| 17 | //! duplicate keys, tabs, CRLF, BOM, deep indentation and trailing garbage are |
| 18 | //! all errors. |
| 19 | //! |
| 20 | //! Slice A deviation (recorded): the ADR's full example nests the `observe` |
| 21 | //! list one level deeper than the normative grammar allows. The grammar wins: |
| 22 | //! `observe` is a one-line JSON list, for example |
| 23 | //! ` observe: ["sqrt_max_ulp <= 1", "chip_verdict == \"PASS\""]`. |
| 24 | //! The `adapter` key is not part of Slice A and is rejected as unknown. |
| 25 | |
| 26 | use crate::evidence::sha256_hex; |
| 27 | use serde_json::Value; |
| 28 | use std::fmt; |
| 29 | |
| 30 | pub const MAX_LINES: usize = 200; |
| 31 | pub const MAX_BYTES: usize = 16 * 1024; |
| 32 | |
| 33 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 34 | pub struct ManifestError(pub String); |
| 35 | |
| 36 | impl fmt::Display for ManifestError { |
| 37 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 38 | f.write_str(&self.0) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | fn err<T>(line: usize, msg: &str) -> Result<T, ManifestError> { |
| 43 | Err(ManifestError(format!("line {line}: {msg}"))) |
| 44 | } |
| 45 | |
| 46 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 47 | pub enum Op { |
| 48 | Eq, |
| 49 | Ne, |
| 50 | Lt, |
| 51 | Le, |
| 52 | Gt, |
| 53 | Ge, |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 57 | pub enum Quant { |
| 58 | Last, |
| 59 | All, |
| 60 | Any, |
| 61 | } |
| 62 | |
| 63 | #[derive(Debug, Clone, PartialEq)] |
| 64 | pub struct Rule { |
| 65 | pub text: String, |
| 66 | pub quant: Quant, |
| 67 | pub name: String, |
| 68 | pub op: Op, |
| 69 | pub value: Value, |
| 70 | } |
| 71 | |
| 72 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 73 | pub struct Build { |
| 74 | pub target: String, |
| 75 | pub tool: String, |
| 76 | } |
| 77 | |
| 78 | /// `prepare` (v2): a step the runner runs after the pool slot and the target |
| 79 | /// dir lock and before the GPU locks, under the host profile, so a gb10 gate |
| 80 | /// builds its program without holding the chip. Its exit must be 0; anything |
| 81 | /// else fails the gate with reason `prepare_failed` and `run` never starts. |
| 82 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 83 | pub struct Prepare { |
| 84 | pub exec: String, |
| 85 | pub args: Vec<String>, |
| 86 | } |
| 87 | |
| 88 | /// Epistemic requirement of a check (ADR 0033 Decision 2). v1 manifests are |
| 89 | /// always `Exact`. |
| 90 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 91 | pub enum Exactness { |
| 92 | Exact, |
| 93 | Bounded, |
| 94 | Approximate, |
| 95 | Advisory, |
| 96 | } |
| 97 | |
| 98 | impl Exactness { |
| 99 | pub fn as_str(self) -> &'static str { |
| 100 | match self { |
| 101 | Exactness::Exact => "EXACT", |
| 102 | Exactness::Bounded => "BOUNDED", |
| 103 | Exactness::Approximate => "APPROXIMATE", |
| 104 | Exactness::Advisory => "ADVISORY", |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// What a check's cache key and identity bind to (ADR 0033 Decision 5). |
| 110 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 111 | pub enum CacheScope { |
| 112 | Portable, |
| 113 | Arch, |
| 114 | Machine, |
| 115 | Hardware, |
| 116 | } |
| 117 | |
| 118 | impl CacheScope { |
| 119 | pub fn as_str(self) -> &'static str { |
| 120 | match self { |
| 121 | CacheScope::Portable => "portable", |
| 122 | CacheScope::Arch => "arch", |
| 123 | CacheScope::Machine => "machine", |
| 124 | CacheScope::Hardware => "hardware", |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// `tolerance`: integers only (receipts carry no floats, ADR 0028 C3). |
| 130 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 131 | pub struct Tolerance { |
| 132 | pub metric: String, |
| 133 | pub abs: u64, |
| 134 | pub rel_ppm: u64, |
| 135 | } |
| 136 | |
| 137 | /// `backends`: where the check may run and which result is authoritative. |
| 138 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 139 | pub struct Backends { |
| 140 | pub eligible: Vec<String>, |
| 141 | pub canonical: String, |
| 142 | } |
| 143 | |
| 144 | /// `oracle`: explicit pass condition beyond the v1 `exit` + `observe`. |
| 145 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 146 | pub struct Oracle { |
| 147 | /// Repo-relative golden file; its sha256 enters the check identity. |
| 148 | pub golden: Option<String>, |
| 149 | /// Another gate whose result this check is compared against. |
| 150 | pub compare: Option<String>, |
| 151 | } |
| 152 | |
| 153 | pub const BACKEND_NAMES: [&str; 6] = [ |
| 154 | "portable", |
| 155 | "spark", |
| 156 | "qemu", |
| 157 | "gb10", |
| 158 | "analog_sim", |
| 159 | "analog_device", |
| 160 | ]; |
| 161 | |
| 162 | fn is_analog(b: &str) -> bool { |
| 163 | b == "analog_sim" || b == "analog_device" |
| 164 | } |
| 165 | |
| 166 | #[derive(Debug, Clone, PartialEq)] |
| 167 | pub struct Manifest { |
| 168 | pub gate: String, |
| 169 | pub owner: String, |
| 170 | pub requires: Vec<String>, |
| 171 | pub depends_on: Vec<String>, |
| 172 | pub inputs: Vec<String>, |
| 173 | pub build: Option<Build>, |
| 174 | pub prepare: Option<Prepare>, |
| 175 | pub exec: String, |
| 176 | pub args: Vec<String>, |
| 177 | pub expect_exit: i64, |
| 178 | pub rules: Vec<Rule>, |
| 179 | pub timeout_ms: u64, |
| 180 | pub mutants: Vec<String>, |
| 181 | pub checks: Vec<String>, |
| 182 | pub cache_allowed: bool, |
| 183 | /// `cache: inputs_complete`: the author promises `inputs` name every file |
| 184 | /// the gate reads, so a result may be reused by another head whose |
| 185 | /// declared inputs are byte-identical (`cache::cross_head`). Without it a |
| 186 | /// result crosses heads only when the whole tree is identical. |
| 187 | pub inputs_complete: bool, |
| 188 | /// `outside_inputs`: files or directories outside the repository the gate |
| 189 | /// reads (a model checkpoint under `~/models`, say). Each entry is `~/` |
| 190 | /// (the judge's home) or an absolute path; the bytes of every file under |
| 191 | /// it join the declared-inputs digest, so a changed checkpoint is a miss. |
| 192 | pub outside_inputs: Vec<String>, |
| 193 | /// `listed`: directories (repo-relative, `*` patterns allowed) whose entry |
| 194 | /// NAMES join the key, not their contents. cargo lists `tests/`, `src/bin/`, |
| 195 | /// `examples/` of every workspace member to find targets, so a file added |
| 196 | /// there changes what it loads even when no byte it compiles changed. |
| 197 | pub listed: Vec<String>, |
| 198 | /// `target_lock: none`: the gate never builds or runs anything from a cargo |
| 199 | /// target dir (a grep, a find, `crumb verify`), so it runs without waiting |
| 200 | /// for the head's target-dir lock. Default true (the lock is taken). |
| 201 | pub target_lock: bool, |
| 202 | /// `manifest_version` (1 or 2). The fields below are v2 and hold their |
| 203 | /// documented defaults for a v1 manifest. |
| 204 | pub version: u8, |
| 205 | pub exactness: Exactness, |
| 206 | pub tolerance: Option<Tolerance>, |
| 207 | pub backends: Backends, |
| 208 | pub fallback: Vec<String>, |
| 209 | pub cache_scope: CacheScope, |
| 210 | pub oracle: Oracle, |
| 211 | /// sha256 of the exact manifest file bytes (P7). |
| 212 | pub digest: String, |
| 213 | } |
| 214 | |
| 215 | impl Manifest { |
| 216 | /// The scarcest listed pool: gb10 > qemu > host. |
| 217 | pub fn pool(&self) -> &'static str { |
| 218 | if self.requires.iter().any(|r| r == "gb10" || r == "nvrm") { |
| 219 | "gb10" |
| 220 | } else if self.requires.iter().any(|r| r == "qemu") { |
| 221 | "qemu" |
| 222 | } else { |
| 223 | "host" |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | #[derive(Debug, Clone)] |
| 229 | enum Val { |
| 230 | Str(String), |
| 231 | List(Vec<String>), |
| 232 | } |
| 233 | |
| 234 | struct Entry { |
| 235 | key: String, |
| 236 | line: usize, |
| 237 | scalar: Option<Val>, |
| 238 | items: Vec<String>, |
| 239 | children: Vec<(String, Val, usize)>, |
| 240 | } |
| 241 | |
| 242 | pub fn valid_key(k: &str) -> bool { |
| 243 | let mut chars = k.chars(); |
| 244 | match chars.next() { |
| 245 | Some(c) if c.is_ascii_lowercase() => {} |
| 246 | _ => return false, |
| 247 | } |
| 248 | chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') |
| 249 | } |
| 250 | |
| 251 | pub fn valid_gate_id(s: &str) -> bool { |
| 252 | !s.is_empty() |
| 253 | && s.len() <= 64 |
| 254 | && s.chars() |
| 255 | .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-') |
| 256 | } |
| 257 | |
| 258 | /// Observation NAME: [a-z][a-z0-9_.-]* |
| 259 | pub fn valid_obs_name(s: &str) -> bool { |
| 260 | let mut chars = s.chars(); |
| 261 | match chars.next() { |
| 262 | Some(c) if c.is_ascii_lowercase() => {} |
| 263 | _ => return false, |
| 264 | } |
| 265 | chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '.' || c == '-') |
| 266 | } |
| 267 | |
| 268 | fn valid_rel_path(s: &str) -> bool { |
| 269 | !s.is_empty() && !s.starts_with('/') && !s.contains('\0') && !s.split('/').any(|c| c == "..") |
| 270 | } |
| 271 | |
| 272 | /// An `outside_inputs` entry: `~/REST` (the judge's home) or `/REST`, with |
| 273 | /// something after the prefix and no `..` component. |
| 274 | fn valid_outside_path(s: &str) -> bool { |
| 275 | let rest = match (s.strip_prefix("~/"), s.strip_prefix('/')) { |
| 276 | (Some(r), _) | (None, Some(r)) => r, |
| 277 | _ => return false, |
| 278 | }; |
| 279 | !rest.trim_matches('/').is_empty() && !s.contains('\0') && !rest.split('/').any(|c| c == "..") |
| 280 | } |
| 281 | |
| 282 | fn parse_val(s: &str, line: usize) -> Result<Val, ManifestError> { |
| 283 | if s.starts_with('"') { |
| 284 | let mut it = serde_json::Deserializer::from_str(s).into_iter::<String>(); |
| 285 | let v = match it.next() { |
| 286 | Some(Ok(v)) => v, |
| 287 | _ => return err(line, "bad quoted string"), |
| 288 | }; |
| 289 | if !s[it.byte_offset()..].is_empty() { |
| 290 | return err(line, "trailing garbage after quoted string"); |
| 291 | } |
| 292 | return Ok(Val::Str(v)); |
| 293 | } |
| 294 | if s.starts_with('[') { |
| 295 | return match serde_json::from_str::<Vec<String>>(s) { |
| 296 | Ok(v) => Ok(Val::List(v)), |
| 297 | Err(_) => err(line, "list must be a one-line JSON array of strings"), |
| 298 | }; |
| 299 | } |
| 300 | let cut = match s.find(" #") { |
| 301 | Some(i) => &s[..i], |
| 302 | None => s, |
| 303 | }; |
| 304 | let t = cut.trim_end(); |
| 305 | if t.is_empty() { |
| 306 | return err(line, "empty value"); |
| 307 | } |
| 308 | Ok(Val::Str(t.to_string())) |
| 309 | } |
| 310 | |
| 311 | /// Split `KEY: VALUE` (value optional). |
| 312 | fn split_key(s: &str, line: usize) -> Result<(String, Option<Val>), ManifestError> { |
| 313 | let i = match s.find(':') { |
| 314 | Some(i) => i, |
| 315 | None => return err(line, "expected KEY: or an item line"), |
| 316 | }; |
| 317 | let key = &s[..i]; |
| 318 | if !valid_key(key) { |
| 319 | return err(line, "invalid key"); |
| 320 | } |
| 321 | let rest = &s[i + 1..]; |
| 322 | if rest.is_empty() { |
| 323 | return Ok((key.to_string(), None)); |
| 324 | } |
| 325 | if !rest.starts_with(' ') { |
| 326 | return err(line, "space required after colon"); |
| 327 | } |
| 328 | let v = &rest[1..]; |
| 329 | if v.starts_with(' ') { |
| 330 | return err(line, "extra space after colon"); |
| 331 | } |
| 332 | Ok((key.to_string(), Some(parse_val(v, line)?))) |
| 333 | } |
| 334 | |
| 335 | fn parse_entries(text: &str) -> Result<Vec<Entry>, ManifestError> { |
| 336 | let mut entries: Vec<Entry> = Vec::new(); |
| 337 | for (i, raw) in text.lines().enumerate() { |
| 338 | let n = i + 1; |
| 339 | let raw = raw.trim_end_matches(' '); |
| 340 | let trimmed = raw.trim_start_matches(' '); |
| 341 | if trimmed.is_empty() || trimmed.starts_with('#') { |
| 342 | continue; |
| 343 | } |
| 344 | if let Some(rest) = raw.strip_prefix(" - ") { |
| 345 | if rest.starts_with(' ') { |
| 346 | return err(n, "extra space after dash"); |
| 347 | } |
| 348 | let v = match parse_val(rest, n)? { |
| 349 | Val::Str(s) => s, |
| 350 | Val::List(_) => return err(n, "list item must be a scalar"), |
| 351 | }; |
| 352 | match entries.last_mut() { |
| 353 | Some(e) => e.items.push(v), |
| 354 | None => return err(n, "item line before any key"), |
| 355 | } |
| 356 | } else if let Some(rest) = raw.strip_prefix(" ") { |
| 357 | if rest.starts_with(' ') { |
| 358 | return err(n, "indentation deeper than two spaces"); |
| 359 | } |
| 360 | let (k, v) = split_key(rest, n)?; |
| 361 | let v = match v { |
| 362 | Some(v) => v, |
| 363 | None => return err(n, "child key needs a value"), |
| 364 | }; |
| 365 | match entries.last_mut() { |
| 366 | Some(e) => { |
| 367 | if e.children.iter().any(|c| c.0 == k) { |
| 368 | return err(n, "duplicate child key"); |
| 369 | } |
| 370 | e.children.push((k, v, n)); |
| 371 | } |
| 372 | None => return err(n, "child line before any key"), |
| 373 | } |
| 374 | } else if raw.starts_with(' ') { |
| 375 | return err(n, "one-space indentation"); |
| 376 | } else { |
| 377 | let (k, v) = split_key(raw, n)?; |
| 378 | if entries.iter().any(|e| e.key == k) { |
| 379 | return err(n, &format!("duplicate key {k}")); |
| 380 | } |
| 381 | entries.push(Entry { |
| 382 | key: k, |
| 383 | line: n, |
| 384 | scalar: v, |
| 385 | items: Vec::new(), |
| 386 | children: Vec::new(), |
| 387 | }); |
| 388 | } |
| 389 | } |
| 390 | for e in &entries { |
| 391 | let shapes = (e.scalar.is_some() as u8) |
| 392 | + (!e.items.is_empty() as u8) |
| 393 | + (!e.children.is_empty() as u8); |
| 394 | if shapes > 1 { |
| 395 | return err(e.line, &format!("key {} mixes value shapes", e.key)); |
| 396 | } |
| 397 | } |
| 398 | Ok(entries) |
| 399 | } |
| 400 | |
| 401 | fn scalar(e: &Entry) -> Result<String, ManifestError> { |
| 402 | match (&e.scalar, e.items.is_empty(), e.children.is_empty()) { |
| 403 | (Some(Val::Str(s)), true, true) => Ok(s.clone()), |
| 404 | _ => err(e.line, &format!("key {} needs a scalar value", e.key)), |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | fn list(e: &Entry) -> Result<Vec<String>, ManifestError> { |
| 409 | match (&e.scalar, e.children.is_empty()) { |
| 410 | (Some(Val::List(l)), true) if e.items.is_empty() => Ok(l.clone()), |
| 411 | (None, true) => Ok(e.items.clone()), |
| 412 | _ => err(e.line, &format!("key {} needs a list", e.key)), |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | fn map<'a>(e: &'a Entry, allowed: &[&str]) -> Result<&'a Vec<(String, Val, usize)>, ManifestError> { |
| 417 | if e.scalar.is_some() || !e.items.is_empty() || e.children.is_empty() { |
| 418 | return err(e.line, &format!("key {} needs child keys", e.key)); |
| 419 | } |
| 420 | for (k, _, n) in &e.children { |
| 421 | if !allowed.contains(&k.as_str()) { |
| 422 | return err(*n, &format!("unknown child key {k} under {}", e.key)); |
| 423 | } |
| 424 | } |
| 425 | Ok(&e.children) |
| 426 | } |
| 427 | |
| 428 | fn child<'a>(c: &'a [(String, Val, usize)], k: &str) -> Option<&'a (String, Val, usize)> { |
| 429 | c.iter().find(|x| x.0 == k) |
| 430 | } |
| 431 | |
| 432 | fn child_str(c: &[(String, Val, usize)], k: &str) -> Result<Option<String>, ManifestError> { |
| 433 | match child(c, k) { |
| 434 | None => Ok(None), |
| 435 | Some((_, Val::Str(s), _)) => Ok(Some(s.clone())), |
| 436 | Some((_, Val::List(_), n)) => err(*n, &format!("{k} must be a scalar")), |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | pub fn parse_duration_ms(s: &str) -> Option<u64> { |
| 441 | let (num, mult) = if let Some(n) = s.strip_suffix("ms") { |
| 442 | (n, 1u64) |
| 443 | } else if let Some(n) = s.strip_suffix('s') { |
| 444 | (n, 1000) |
| 445 | } else if let Some(n) = s.strip_suffix('m') { |
| 446 | (n, 60_000) |
| 447 | } else { |
| 448 | let n = s.strip_suffix('h')?; |
| 449 | (n, 3_600_000) |
| 450 | }; |
| 451 | if num.is_empty() || !num.chars().all(|c| c.is_ascii_digit()) { |
| 452 | return None; |
| 453 | } |
| 454 | let v: u64 = num.parse().ok()?; |
| 455 | if v == 0 { |
| 456 | return None; |
| 457 | } |
| 458 | v.checked_mul(mult) |
| 459 | } |
| 460 | |
| 461 | pub fn parse_rule(text: &str) -> Result<Rule, String> { |
| 462 | let (quant, rest) = if let Some(r) = text.strip_prefix("all ") { |
| 463 | (Quant::All, r) |
| 464 | } else if let Some(r) = text.strip_prefix("any ") { |
| 465 | (Quant::Any, r) |
| 466 | } else { |
| 467 | (Quant::Last, text) |
| 468 | }; |
| 469 | let mut it = rest.splitn(3, ' '); |
| 470 | let name = it.next().unwrap_or(""); |
| 471 | let op = it.next().unwrap_or(""); |
| 472 | let val = it.next().unwrap_or(""); |
| 473 | if !valid_obs_name(name) { |
| 474 | return Err(format!("bad observation name in rule {text:?}")); |
| 475 | } |
| 476 | let op = match op { |
| 477 | "==" => Op::Eq, |
| 478 | "!=" => Op::Ne, |
| 479 | "<" => Op::Lt, |
| 480 | "<=" => Op::Le, |
| 481 | ">" => Op::Gt, |
| 482 | ">=" => Op::Ge, |
| 483 | _ => return Err(format!("bad operator in rule {text:?}")), |
| 484 | }; |
| 485 | let value = |
| 486 | parse_json_scalar(val.trim()).ok_or_else(|| format!("bad value in rule {text:?}"))?; |
| 487 | Ok(Rule { |
| 488 | text: text.to_string(), |
| 489 | quant, |
| 490 | name: name.to_string(), |
| 491 | op, |
| 492 | value, |
| 493 | }) |
| 494 | } |
| 495 | |
| 496 | /// JSON string, integer (no floats), true/false/null. |
| 497 | pub fn parse_json_scalar(s: &str) -> Option<Value> { |
| 498 | let v: Value = serde_json::from_str(s).ok()?; |
| 499 | let ok = match &v { |
| 500 | Value::String(_) | Value::Bool(_) | Value::Null => true, |
| 501 | Value::Number(n) => n.is_i64(), |
| 502 | _ => false, |
| 503 | }; |
| 504 | if ok { |
| 505 | Some(v) |
| 506 | } else { |
| 507 | None |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | pub const REQUIRES_V2: [&str; 9] = [ |
| 512 | "portable", |
| 513 | "aarch64", |
| 514 | "host", |
| 515 | "qemu", |
| 516 | "gb10", |
| 517 | "nvrm", |
| 518 | "bare_metal", |
| 519 | "analog_eligible", |
| 520 | "operator", |
| 521 | ]; |
| 522 | |
| 523 | const V2_KEYS: [&str; 7] = [ |
| 524 | "exactness", |
| 525 | "tolerance", |
| 526 | "backends", |
| 527 | "fallback", |
| 528 | "cache_scope", |
| 529 | "oracle", |
| 530 | "prepare", |
| 531 | ]; |
| 532 | |
| 533 | fn bad<T>(msg: String) -> Result<T, ManifestError> { |
| 534 | Err(ManifestError(msg)) |
| 535 | } |
| 536 | |
| 537 | fn child_u64(c: &[(String, Val, usize)], k: &str) -> Result<u64, ManifestError> { |
| 538 | let s = child_str(c, k)?.ok_or_else(|| ManifestError(format!("tolerance.{k} missing")))?; |
| 539 | if s.is_empty() || !s.chars().all(|ch| ch.is_ascii_digit()) { |
| 540 | return bad(format!( |
| 541 | "tolerance.{k} must be a non-negative integer, got {s:?}" |
| 542 | )); |
| 543 | } |
| 544 | s.parse::<u64>() |
| 545 | .map_err(|_| ManifestError(format!("tolerance.{k} out of range"))) |
| 546 | } |
| 547 | |
| 548 | /// The v2 keys (ADR 0033 Decision 2) with their defaults and refusals. |
| 549 | type V2 = ( |
| 550 | Exactness, |
| 551 | Option<Tolerance>, |
| 552 | Backends, |
| 553 | Vec<String>, |
| 554 | CacheScope, |
| 555 | Oracle, |
| 556 | ); |
| 557 | |
| 558 | fn parse_v2(entries: &[Entry], requires: &[String]) -> Result<V2, ManifestError> { |
| 559 | let get = |k: &str| entries.iter().find(|e| e.key == k); |
| 560 | let exactness = match get("exactness") { |
| 561 | None => Exactness::Exact, |
| 562 | Some(e) => match scalar(e)?.as_str() { |
| 563 | "EXACT" => Exactness::Exact, |
| 564 | "BOUNDED" => Exactness::Bounded, |
| 565 | "APPROXIMATE" => Exactness::Approximate, |
| 566 | "ADVISORY" => Exactness::Advisory, |
| 567 | o => return bad(format!("unknown exactness {o:?}")), |
| 568 | }, |
| 569 | }; |
| 570 | let tolerance = match get("tolerance") { |
| 571 | None => None, |
| 572 | Some(e) => { |
| 573 | let c = map(e, &["metric", "abs", "rel_ppm"])?; |
| 574 | let metric = child_str(c, "metric")? |
| 575 | .ok_or_else(|| ManifestError("tolerance.metric missing".into()))?; |
| 576 | if !valid_obs_name(&metric) { |
| 577 | return bad(format!("bad tolerance.metric {metric:?}")); |
| 578 | } |
| 579 | Some(Tolerance { |
| 580 | metric, |
| 581 | abs: child_u64(c, "abs")?, |
| 582 | rel_ppm: child_u64(c, "rel_ppm")?, |
| 583 | }) |
| 584 | } |
| 585 | }; |
| 586 | if tolerance.is_some() && exactness != Exactness::Bounded { |
| 587 | return bad("tolerance is only allowed with exactness BOUNDED".into()); |
| 588 | } |
| 589 | if tolerance.is_none() && exactness == Exactness::Bounded { |
| 590 | return bad("exactness BOUNDED requires a tolerance".into()); |
| 591 | } |
| 592 | let cache_scope = match get("cache_scope") { |
| 593 | None => CacheScope::Machine, |
| 594 | Some(e) => match scalar(e)?.as_str() { |
| 595 | "portable" => CacheScope::Portable, |
| 596 | "arch" => CacheScope::Arch, |
| 597 | "machine" => CacheScope::Machine, |
| 598 | "hardware" => CacheScope::Hardware, |
| 599 | o => return bad(format!("unknown cache_scope {o:?}")), |
| 600 | }, |
| 601 | }; |
| 602 | let analog_ok = exactness != Exactness::Exact; |
| 603 | if requires.iter().any(|r| r == "analog_eligible") && !analog_ok { |
| 604 | return bad("requires analog_eligible is not allowed for an EXACT check".into()); |
| 605 | } |
| 606 | let check_backend = |b: &str| -> Result<(), ManifestError> { |
| 607 | if BACKEND_NAMES.contains(&b) { |
| 608 | Ok(()) |
| 609 | } else { |
| 610 | bad(format!("unknown backend {b:?}")) |
| 611 | } |
| 612 | }; |
| 613 | // Eligible backends implied by `requires` when none are declared. |
| 614 | let mut implied: Vec<String> = Vec::new(); |
| 615 | for r in requires { |
| 616 | let b = match r.as_str() { |
| 617 | "portable" => "portable", |
| 618 | "host" | "aarch64" => "spark", |
| 619 | "qemu" => "qemu", |
| 620 | "gb10" | "nvrm" => "gb10", |
| 621 | "analog_eligible" => "analog_sim", |
| 622 | _ => continue, |
| 623 | }; |
| 624 | if !implied.iter().any(|x| x == b) { |
| 625 | implied.push(b.to_string()); |
| 626 | } |
| 627 | } |
| 628 | let (eligible, declared_canonical) = match get("backends") { |
| 629 | None => (implied, None), |
| 630 | Some(e) => { |
| 631 | let c = map(e, &["eligible", "canonical"])?; |
| 632 | let eligible = match child(c, "eligible") { |
| 633 | None => implied, |
| 634 | Some((_, Val::List(l), _)) => l.clone(), |
| 635 | Some((_, Val::Str(_), n)) => { |
| 636 | return err(*n, "backends.eligible must be a one-line list") |
| 637 | } |
| 638 | }; |
| 639 | (eligible, child_str(c, "canonical")?) |
| 640 | } |
| 641 | }; |
| 642 | if eligible.is_empty() { |
| 643 | return bad("backends.eligible is empty".into()); |
| 644 | } |
| 645 | for b in &eligible { |
| 646 | check_backend(b)?; |
| 647 | if is_analog(b) && exactness == Exactness::Exact { |
| 648 | return bad(format!( |
| 649 | "backend {b} may not be eligible for an EXACT check" |
| 650 | )); |
| 651 | } |
| 652 | } |
| 653 | let canonical = match declared_canonical { |
| 654 | Some(c) => { |
| 655 | check_backend(&c)?; |
| 656 | c |
| 657 | } |
| 658 | None => { |
| 659 | // ADR default: spark, or portable when `requires` is only |
| 660 | // portable. Deviation: when spark is not eligible (a qemu or gb10 |
| 661 | // only check) the first digital eligible backend is canonical. |
| 662 | let only_portable = requires.iter().all(|r| r == "portable"); |
| 663 | if only_portable && eligible.iter().any(|b| b == "portable") { |
| 664 | "portable".to_string() |
| 665 | } else if eligible.iter().any(|b| b == "spark") { |
| 666 | "spark".to_string() |
| 667 | } else { |
| 668 | match eligible.iter().find(|b| !is_analog(b)) { |
| 669 | Some(b) => b.clone(), |
| 670 | None => return bad("no digital backend is eligible".into()), |
| 671 | } |
| 672 | } |
| 673 | } |
| 674 | }; |
| 675 | if !eligible.contains(&canonical) { |
| 676 | return bad(format!( |
| 677 | "canonical backend {canonical} is not in backends.eligible" |
| 678 | )); |
| 679 | } |
| 680 | if is_analog(&canonical) |
| 681 | && exactness != Exactness::Approximate |
| 682 | && exactness != Exactness::Advisory |
| 683 | { |
| 684 | return bad(format!( |
| 685 | "canonical backend {canonical} is only allowed for APPROXIMATE or ADVISORY" |
| 686 | )); |
| 687 | } |
| 688 | let fallback = match get("fallback") { |
| 689 | None => vec!["spark".to_string()], |
| 690 | Some(e) => { |
| 691 | let l = list(e)?; |
| 692 | if l.is_empty() { |
| 693 | return bad("fallback is empty".into()); |
| 694 | } |
| 695 | for b in &l { |
| 696 | check_backend(b)?; |
| 697 | } |
| 698 | l |
| 699 | } |
| 700 | }; |
| 701 | let oracle = match get("oracle") { |
| 702 | None => Oracle::default(), |
| 703 | Some(e) => { |
| 704 | let c = map(e, &["golden", "compare"])?; |
| 705 | let golden = child_str(c, "golden")?; |
| 706 | let compare = child_str(c, "compare")?; |
| 707 | if golden.is_some() && compare.is_some() { |
| 708 | return bad("oracle takes golden or compare, not both".into()); |
| 709 | } |
| 710 | if golden.is_none() && compare.is_none() { |
| 711 | return bad("oracle needs golden or compare".into()); |
| 712 | } |
| 713 | if let Some(g) = &golden { |
| 714 | if !valid_rel_path(g) { |
| 715 | return bad(format!("oracle.golden must be a repo-relative path: {g:?}")); |
| 716 | } |
| 717 | } |
| 718 | if let Some(g) = &compare { |
| 719 | if !valid_gate_id(g) { |
| 720 | return bad(format!("invalid oracle.compare gate id {g:?}")); |
| 721 | } |
| 722 | } |
| 723 | Oracle { golden, compare } |
| 724 | } |
| 725 | }; |
| 726 | Ok(( |
| 727 | exactness, |
| 728 | tolerance, |
| 729 | Backends { |
| 730 | eligible, |
| 731 | canonical, |
| 732 | }, |
| 733 | fallback, |
| 734 | cache_scope, |
| 735 | oracle, |
| 736 | )) |
| 737 | } |
| 738 | |
| 739 | /// `run:` or `prepare:`: a program and its one-line argument list. |
| 740 | fn parse_exec(e: &Entry) -> Result<(String, Vec<String>), ManifestError> { |
| 741 | let c = map(e, &["exec", "args"])?; |
| 742 | let exec = |
| 743 | child_str(c, "exec")?.ok_or_else(|| ManifestError(format!("{}.exec missing", e.key)))?; |
| 744 | if !valid_rel_path(&exec) { |
| 745 | return Err(ManifestError(format!( |
| 746 | "{}.exec must be a bare program name or a repo-relative path", |
| 747 | e.key |
| 748 | ))); |
| 749 | } |
| 750 | let args = match child(c, "args") { |
| 751 | None => Vec::new(), |
| 752 | Some((_, Val::List(l), _)) => l.clone(), |
| 753 | Some((_, Val::Str(_), n)) => { |
| 754 | return err(*n, &format!("{}.args must be a one-line list", e.key)) |
| 755 | } |
| 756 | }; |
| 757 | Ok((exec, args)) |
| 758 | } |
| 759 | |
| 760 | pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { |
| 761 | if bytes.len() > MAX_BYTES { |
| 762 | return Err(ManifestError("manifest larger than 16 KiB".into())); |
| 763 | } |
| 764 | if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) { |
| 765 | return Err(ManifestError("BOM not allowed".into())); |
| 766 | } |
| 767 | let text = std::str::from_utf8(bytes) |
| 768 | .map_err(|_| ManifestError("manifest is not valid UTF-8".into()))?; |
| 769 | if text.contains('\r') { |
| 770 | return Err(ManifestError( |
| 771 | "CR not allowed (Unix line endings only)".into(), |
| 772 | )); |
| 773 | } |
| 774 | if text.contains('\t') { |
| 775 | return Err(ManifestError("tab not allowed".into())); |
| 776 | } |
| 777 | if text.lines().count() > MAX_LINES { |
| 778 | return Err(ManifestError("manifest longer than 200 lines".into())); |
| 779 | } |
| 780 | let entries = parse_entries(text)?; |
| 781 | |
| 782 | const KNOWN: [&str; 23] = [ |
| 783 | "listed", |
| 784 | "outside_inputs", |
| 785 | "target_lock", |
| 786 | "gate", |
| 787 | "manifest_version", |
| 788 | "owner", |
| 789 | "requires", |
| 790 | "depends_on", |
| 791 | "inputs", |
| 792 | "build", |
| 793 | "run", |
| 794 | "prepare", |
| 795 | "expects", |
| 796 | "timeout", |
| 797 | "mutants", |
| 798 | "checks", |
| 799 | "cache", |
| 800 | "exactness", |
| 801 | "tolerance", |
| 802 | "backends", |
| 803 | "fallback", |
| 804 | "cache_scope", |
| 805 | "oracle", |
| 806 | ]; |
| 807 | for e in &entries { |
| 808 | if !KNOWN.contains(&e.key.as_str()) { |
| 809 | return err(e.line, &format!("unknown key {}", e.key)); |
| 810 | } |
| 811 | } |
| 812 | let get = |k: &str| entries.iter().find(|e| e.key == k); |
| 813 | let need = |k: &str| match get(k) { |
| 814 | Some(e) => Ok(e), |
| 815 | None => Err(ManifestError(format!("missing required key {k}"))), |
| 816 | }; |
| 817 | |
| 818 | let gate = scalar(need("gate")?)?; |
| 819 | if !valid_gate_id(&gate) { |
| 820 | return Err(ManifestError(format!("invalid gate id {gate:?}"))); |
| 821 | } |
| 822 | let version: u8 = match scalar(need("manifest_version")?)?.as_str() { |
| 823 | "1" => 1, |
| 824 | "2" => 2, |
| 825 | _ => { |
| 826 | return Err(ManifestError( |
| 827 | "unsupported manifest_version (only 1 or 2)".into(), |
| 828 | )) |
| 829 | } |
| 830 | }; |
| 831 | if version == 1 { |
| 832 | if let Some(e) = entries.iter().find(|e| V2_KEYS.contains(&e.key.as_str())) { |
| 833 | return err( |
| 834 | e.line, |
| 835 | &format!("key {} requires manifest_version 2", e.key), |
| 836 | ); |
| 837 | } |
| 838 | } |
| 839 | let owner = scalar(need("owner")?)?; |
| 840 | |
| 841 | let requires = match (version, get("requires")) { |
| 842 | (1, _) => list(need("requires")?)?, |
| 843 | (_, Some(e)) => list(e)?, |
| 844 | (_, None) => vec!["host".to_string()], |
| 845 | }; |
| 846 | let allowed: &[&str] = if version == 1 { |
| 847 | &["host", "qemu", "gb10", "operator"] |
| 848 | } else { |
| 849 | &REQUIRES_V2 |
| 850 | }; |
| 851 | for r in &requires { |
| 852 | if !allowed.contains(&r.as_str()) { |
| 853 | return Err(ManifestError(format!("unknown requires entry {r:?}"))); |
| 854 | } |
| 855 | } |
| 856 | let pools: &[&str] = if version == 1 { |
| 857 | &["host", "qemu", "gb10"] |
| 858 | } else { |
| 859 | &["host", "qemu", "gb10", "nvrm", "portable", "aarch64"] |
| 860 | }; |
| 861 | if !requires.iter().any(|r| pools.contains(&r.as_str())) { |
| 862 | return Err(ManifestError(format!( |
| 863 | "requires must list one of {}", |
| 864 | pools.join(", ") |
| 865 | ))); |
| 866 | } |
| 867 | |
| 868 | let depends_on = match get("depends_on") { |
| 869 | Some(e) => list(e)?, |
| 870 | None => Vec::new(), |
| 871 | }; |
| 872 | for d in &depends_on { |
| 873 | if !valid_gate_id(d) { |
| 874 | return Err(ManifestError(format!("invalid depends_on id {d:?}"))); |
| 875 | } |
| 876 | } |
| 877 | let inputs = match get("inputs") { |
| 878 | Some(e) => list(e)?, |
| 879 | None => Vec::new(), |
| 880 | }; |
| 881 | for i in &inputs { |
| 882 | if !valid_rel_path(i) { |
| 883 | return Err(ManifestError(format!( |
| 884 | "inputs path must be repo-relative: {i:?}" |
| 885 | ))); |
| 886 | } |
| 887 | } |
| 888 | |
| 889 | let outside_inputs = match get("outside_inputs") { |
| 890 | Some(e) => list(e)?, |
| 891 | None => Vec::new(), |
| 892 | }; |
| 893 | for o in &outside_inputs { |
| 894 | if !valid_outside_path(o) { |
| 895 | return Err(ManifestError(format!( |
| 896 | "outside_inputs path must start with ~/ or / and have no ..: {o:?}" |
| 897 | ))); |
| 898 | } |
| 899 | } |
| 900 | let listed = match get("listed") { |
| 901 | Some(e) => list(e)?, |
| 902 | None => Vec::new(), |
| 903 | }; |
| 904 | for l in &listed { |
| 905 | if !valid_rel_path(l) { |
| 906 | return Err(ManifestError(format!( |
| 907 | "listed path must be repo-relative: {l:?}" |
| 908 | ))); |
| 909 | } |
| 910 | } |
| 911 | let target_lock = match get("target_lock") { |
| 912 | None => true, |
| 913 | Some(e) => match scalar(e)?.as_str() { |
| 914 | "dir" => true, |
| 915 | "none" => false, |
| 916 | other => { |
| 917 | return Err(ManifestError(format!( |
| 918 | "target_lock must be dir or none, got {other:?}" |
| 919 | ))) |
| 920 | } |
| 921 | }, |
| 922 | }; |
| 923 | |
| 924 | let build = match get("build") { |
| 925 | None => None, |
| 926 | Some(e) => { |
| 927 | let c = map(e, &["target", "tool"])?; |
| 928 | let tool = |
| 929 | child_str(c, "tool")?.ok_or_else(|| ManifestError("build.tool missing".into()))?; |
| 930 | let target = child_str(c, "target")? |
| 931 | .ok_or_else(|| ManifestError("build.target missing".into()))?; |
| 932 | if !["make", "cargo", "none"].contains(&tool.as_str()) { |
| 933 | return Err(ManifestError(format!("unknown build.tool {tool:?}"))); |
| 934 | } |
| 935 | Some(Build { target, tool }) |
| 936 | } |
| 937 | }; |
| 938 | |
| 939 | let (exec, args) = parse_exec(need("run")?)?; |
| 940 | let prepare = match get("prepare") { |
| 941 | None => None, |
| 942 | Some(e) => { |
| 943 | let (exec, args) = parse_exec(e)?; |
| 944 | Some(Prepare { exec, args }) |
| 945 | } |
| 946 | }; |
| 947 | |
| 948 | let (expect_exit, rules) = { |
| 949 | let c = map(need("expects")?, &["exit", "observe", "verdict"])?; |
| 950 | match child_str(c, "verdict")? { |
| 951 | Some(v) if v == "PASS" => {} |
| 952 | _ => return Err(ManifestError("expects.verdict must be PASS in v1".into())), |
| 953 | } |
| 954 | let exit = match child_str(c, "exit")? { |
| 955 | None => 0, |
| 956 | Some(s) => s |
| 957 | .parse::<i64>() |
| 958 | .map_err(|_| ManifestError("expects.exit must be an integer".into()))?, |
| 959 | }; |
| 960 | let texts: Vec<String> = match child(c, "observe") { |
| 961 | None => Vec::new(), |
| 962 | Some((_, Val::List(l), _)) => l.clone(), |
| 963 | Some((_, Val::Str(s), _)) => vec![s.clone()], |
| 964 | }; |
| 965 | let mut rules = Vec::new(); |
| 966 | for t in &texts { |
| 967 | rules.push(parse_rule(t).map_err(ManifestError)?); |
| 968 | } |
| 969 | (exit, rules) |
| 970 | }; |
| 971 | |
| 972 | let timeout_s = scalar(need("timeout")?)?; |
| 973 | let timeout_ms = parse_duration_ms(&timeout_s) |
| 974 | .ok_or_else(|| ManifestError(format!("bad timeout {timeout_s:?}")))?; |
| 975 | |
| 976 | let mutants = match get("mutants") { |
| 977 | Some(e) => list(e)?, |
| 978 | None => Vec::new(), |
| 979 | }; |
| 980 | for m in &mutants { |
| 981 | if m.is_empty() |
| 982 | || !m |
| 983 | .chars() |
| 984 | .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') |
| 985 | { |
| 986 | return Err(ManifestError(format!("bad mutant name {m:?}"))); |
| 987 | } |
| 988 | } |
| 989 | let checks = match get("checks") { |
| 990 | Some(e) => list(e)?, |
| 991 | None => Vec::new(), |
| 992 | }; |
| 993 | for c in &checks { |
| 994 | if !["no_libm_symbols", "no_cuda_symbols", "clean_tree_after"].contains(&c.as_str()) { |
| 995 | return Err(ManifestError(format!("unknown check {c:?}"))); |
| 996 | } |
| 997 | } |
| 998 | let (cache_allowed, inputs_complete) = match get("cache") { |
| 999 | None => (true, false), |
| 1000 | Some(e) => match scalar(e)?.as_str() { |
| 1001 | "allow" => (true, false), |
| 1002 | "inputs_complete" => (true, true), |
| 1003 | "never" => (false, false), |
| 1004 | other => { |
| 1005 | return Err(ManifestError(format!( |
| 1006 | "cache must be allow, inputs_complete or never, got {other:?}" |
| 1007 | ))) |
| 1008 | } |
| 1009 | }, |
| 1010 | }; |
| 1011 | |
| 1012 | // v1 manifests carry none of the v2 keys, so this yields the defaults. |
| 1013 | let (exactness, tolerance, backends, fallback, cache_scope, oracle) = |
| 1014 | parse_v2(&entries, &requires)?; |
| 1015 | |
| 1016 | Ok(Manifest { |
| 1017 | gate, |
| 1018 | owner, |
| 1019 | requires, |
| 1020 | depends_on, |
| 1021 | inputs, |
| 1022 | build, |
| 1023 | prepare, |
| 1024 | exec, |
| 1025 | args, |
| 1026 | expect_exit, |
| 1027 | rules, |
| 1028 | timeout_ms, |
| 1029 | mutants, |
| 1030 | checks, |
| 1031 | cache_allowed, |
| 1032 | inputs_complete, |
| 1033 | outside_inputs, |
| 1034 | listed, |
| 1035 | target_lock, |
| 1036 | version, |
| 1037 | exactness, |
| 1038 | tolerance, |
| 1039 | backends, |
| 1040 | fallback, |
| 1041 | cache_scope, |
| 1042 | oracle, |
| 1043 | digest: sha256_hex(bytes), |
| 1044 | }) |
| 1045 | } |
| 1046 | |
| 1047 | #[cfg(test)] |
| 1048 | mod tests { |
| 1049 | use super::*; |
| 1050 | |
| 1051 | pub const GOOD: &str = concat!( |
| 1052 | "# comment\n", |
| 1053 | "gate: G-1\n", |
| 1054 | "manifest_version: 1\n", |
| 1055 | "owner: omega\n", |
| 1056 | "requires:\n", |
| 1057 | " - host\n", |
| 1058 | "run:\n", |
| 1059 | " exec: tools/run.sh\n", |
| 1060 | " args: [\"--a\", \"b c\"]\n", |
| 1061 | "expects:\n", |
| 1062 | " exit: 0\n", |
| 1063 | " observe: [\"n == 3\", \"all x <= 2\", \"s == \\\"ok\\\"\"]\n", |
| 1064 | " verdict: PASS\n", |
| 1065 | "timeout: 5s\n", |
| 1066 | ); |
| 1067 | |
| 1068 | fn with(extra: &str) -> String { |
| 1069 | format!("{GOOD}{extra}") |
| 1070 | } |
| 1071 | |
| 1072 | #[test] |
| 1073 | fn good_manifest_parses() { |
| 1074 | let m = parse(GOOD.as_bytes()).unwrap(); |
| 1075 | assert_eq!(m.gate, "G-1"); |
| 1076 | assert_eq!(m.owner, "omega"); |
| 1077 | assert_eq!(m.pool(), "host"); |
| 1078 | assert_eq!(m.exec, "tools/run.sh"); |
| 1079 | assert_eq!(m.args, vec!["--a".to_string(), "b c".to_string()]); |
| 1080 | assert_eq!(m.timeout_ms, 5000); |
| 1081 | assert_eq!(m.rules.len(), 3); |
| 1082 | assert_eq!(m.rules[1].quant, Quant::All); |
| 1083 | assert_eq!(m.digest, sha256_hex(GOOD.as_bytes())); |
| 1084 | assert!(m.cache_allowed); |
| 1085 | } |
| 1086 | |
| 1087 | #[test] |
| 1088 | fn digest_covers_comments() { |
| 1089 | let a = parse(GOOD.as_bytes()).unwrap(); |
| 1090 | let b = parse(with("# more\n").as_bytes()).unwrap(); |
| 1091 | assert_ne!(a.digest, b.digest); |
| 1092 | } |
| 1093 | |
| 1094 | #[test] |
| 1095 | fn duplicate_top_level_key_rejected() { |
| 1096 | assert!(parse(with("owner: x\n").as_bytes()).is_err()); |
| 1097 | } |
| 1098 | |
| 1099 | #[test] |
| 1100 | fn duplicate_child_key_rejected() { |
| 1101 | let t = GOOD.replace(" exit: 0\n", " exit: 0\n exit: 1\n"); |
| 1102 | assert!(parse(t.as_bytes()).is_err()); |
| 1103 | } |
| 1104 | |
| 1105 | #[test] |
| 1106 | fn unknown_top_level_key_rejected() { |
| 1107 | assert!(parse(with("surprise: 1\n").as_bytes()).is_err()); |
| 1108 | } |
| 1109 | |
| 1110 | #[test] |
| 1111 | fn unknown_child_key_rejected() { |
| 1112 | let t = GOOD.replace( |
| 1113 | " exec: tools/run.sh\n", |
| 1114 | " exec: tools/run.sh\n shell: sh\n", |
| 1115 | ); |
| 1116 | assert!(parse(t.as_bytes()).is_err()); |
| 1117 | } |
| 1118 | |
| 1119 | #[test] |
| 1120 | fn tab_crlf_bom_rejected() { |
| 1121 | assert!(parse(GOOD.replace("owner: omega", "owner:\tomega").as_bytes()).is_err()); |
| 1122 | assert!(parse(GOOD.replace('\n', "\r\n").as_bytes()).is_err()); |
| 1123 | let mut b = vec![0xEF, 0xBB, 0xBF]; |
| 1124 | b.extend_from_slice(GOOD.as_bytes()); |
| 1125 | assert!(parse(&b).is_err()); |
| 1126 | assert!(parse(&[0xFF, 0xFE, b'\n']).is_err()); |
| 1127 | } |
| 1128 | |
| 1129 | #[test] |
| 1130 | fn deep_indent_rejected() { |
| 1131 | let t = GOOD.replace( |
| 1132 | " exec: tools/run.sh\n", |
| 1133 | " exec: tools/run.sh\n deeper: 1\n", |
| 1134 | ); |
| 1135 | assert!(parse(t.as_bytes()).is_err()); |
| 1136 | } |
| 1137 | |
| 1138 | #[test] |
| 1139 | fn mixed_shapes_rejected() { |
| 1140 | let t = GOOD.replace("requires:\n - host\n", "requires: [\"host\"]\n - host\n"); |
| 1141 | assert!(parse(t.as_bytes()).is_err()); |
| 1142 | } |
| 1143 | |
| 1144 | #[test] |
| 1145 | fn trailing_garbage_rejected() { |
| 1146 | assert!(parse( |
| 1147 | GOOD.replace("owner: omega", "owner: \"omega\" x") |
| 1148 | .as_bytes() |
| 1149 | ) |
| 1150 | .is_err()); |
| 1151 | } |
| 1152 | |
| 1153 | #[test] |
| 1154 | fn size_limits() { |
| 1155 | let mut big = String::from(GOOD); |
| 1156 | for _ in 0..200 { |
| 1157 | big.push_str("# pad\n"); |
| 1158 | } |
| 1159 | assert!(parse(big.as_bytes()).is_err()); |
| 1160 | let huge = format!("{GOOD}# {}\n", "x".repeat(MAX_BYTES)); |
| 1161 | assert!(parse(huge.as_bytes()).is_err()); |
| 1162 | } |
| 1163 | |
| 1164 | #[test] |
| 1165 | fn missing_required_and_bad_version() { |
| 1166 | assert!(parse(GOOD.replace("timeout: 5s\n", "").as_bytes()).is_err()); |
| 1167 | assert!(parse( |
| 1168 | GOOD.replace("manifest_version: 1", "manifest_version: 3") |
| 1169 | .as_bytes() |
| 1170 | ) |
| 1171 | .is_err()); |
| 1172 | assert!(parse( |
| 1173 | GOOD.replace(" verdict: PASS\n", " verdict: FAIL\n") |
| 1174 | .as_bytes() |
| 1175 | ) |
| 1176 | .is_err()); |
| 1177 | } |
| 1178 | |
| 1179 | #[test] |
| 1180 | fn requires_needs_a_pool() { |
| 1181 | assert!(parse(GOOD.replace(" - host\n", " - operator\n").as_bytes()).is_err()); |
| 1182 | assert!(parse(GOOD.replace(" - host\n", " - moon\n").as_bytes()).is_err()); |
| 1183 | } |
| 1184 | |
| 1185 | #[test] |
| 1186 | fn pool_is_scarcest() { |
| 1187 | let t = GOOD.replace(" - host\n", " - host\n - gb10\n"); |
| 1188 | assert_eq!(parse(t.as_bytes()).unwrap().pool(), "gb10"); |
| 1189 | } |
| 1190 | |
| 1191 | #[test] |
| 1192 | fn paths_must_be_relative() { |
| 1193 | assert!(parse(GOOD.replace("tools/run.sh", "/bin/sh").as_bytes()).is_err()); |
| 1194 | assert!(parse(GOOD.replace("tools/run.sh", "../x").as_bytes()).is_err()); |
| 1195 | // An exec that escapes the repository is a reject, never a run. |
| 1196 | for bad in [ |
| 1197 | "../../usr/bin/env", |
| 1198 | "/usr/bin/env", |
| 1199 | "tools/../../x", |
| 1200 | "tools/..", |
| 1201 | "", |
| 1202 | ] { |
| 1203 | let e = parse(GOOD.replace("tools/run.sh", bad).as_bytes()); |
| 1204 | assert!(e.is_err(), "{bad:?} must be rejected"); |
| 1205 | } |
| 1206 | // A bare program name is allowed: it resolves on the PATH. |
| 1207 | let m = parse(GOOD.replace("tools/run.sh", "crumb").as_bytes()).unwrap(); |
| 1208 | assert_eq!(m.exec, "crumb"); |
| 1209 | } |
| 1210 | |
| 1211 | #[test] |
| 1212 | fn durations() { |
| 1213 | assert_eq!(parse_duration_ms("250ms"), Some(250)); |
| 1214 | assert_eq!(parse_duration_ms("2m"), Some(120_000)); |
| 1215 | assert_eq!(parse_duration_ms("1h"), Some(3_600_000)); |
| 1216 | assert_eq!(parse_duration_ms("0s"), None); |
| 1217 | assert_eq!(parse_duration_ms("5"), None); |
| 1218 | assert_eq!(parse_duration_ms("s"), None); |
| 1219 | } |
| 1220 | |
| 1221 | #[test] |
| 1222 | fn rules_parse_and_reject_floats() { |
| 1223 | let r = parse_rule("fence_count == 3").unwrap(); |
| 1224 | assert_eq!(r.op, Op::Eq); |
| 1225 | assert_eq!(r.value, Value::from(3)); |
| 1226 | assert!(parse_rule("x <= 1.5").is_err()); |
| 1227 | assert!(parse_rule("X == 1").is_err()); |
| 1228 | assert!(parse_rule("x ~ 1").is_err()); |
| 1229 | assert!(parse_rule("x ==").is_err()); |
| 1230 | assert_eq!(parse_rule("any v > 2").unwrap().quant, Quant::Any); |
| 1231 | assert_eq!( |
| 1232 | parse_rule("s == \"a b\"").unwrap().value, |
| 1233 | Value::from("a b") |
| 1234 | ); |
| 1235 | } |
| 1236 | |
| 1237 | fn v2(extra: &str) -> String { |
| 1238 | GOOD.replace("manifest_version: 1", "manifest_version: 2") + extra |
| 1239 | } |
| 1240 | |
| 1241 | fn v2_err(extra: &str) -> String { |
| 1242 | parse(v2(extra).as_bytes()).unwrap_err().0 |
| 1243 | } |
| 1244 | |
| 1245 | #[test] |
| 1246 | fn v1_fixture_parses_to_the_same_values_as_before_slice_d() { |
| 1247 | let m = parse(GOOD.as_bytes()).unwrap(); |
| 1248 | let expected = Manifest { |
| 1249 | gate: "G-1".into(), |
| 1250 | owner: "omega".into(), |
| 1251 | requires: vec!["host".into()], |
| 1252 | depends_on: vec![], |
| 1253 | inputs: vec![], |
| 1254 | build: None, |
| 1255 | prepare: None, |
| 1256 | exec: "tools/run.sh".into(), |
| 1257 | args: vec!["--a".into(), "b c".into()], |
| 1258 | expect_exit: 0, |
| 1259 | rules: m.rules.clone(), |
| 1260 | timeout_ms: 5000, |
| 1261 | mutants: vec![], |
| 1262 | checks: vec![], |
| 1263 | cache_allowed: true, |
| 1264 | inputs_complete: false, |
| 1265 | outside_inputs: Vec::new(), |
| 1266 | listed: Vec::new(), |
| 1267 | target_lock: true, |
| 1268 | version: 1, |
| 1269 | exactness: Exactness::Exact, |
| 1270 | tolerance: None, |
| 1271 | backends: Backends { |
| 1272 | eligible: vec!["spark".into()], |
| 1273 | canonical: "spark".into(), |
| 1274 | }, |
| 1275 | fallback: vec!["spark".into()], |
| 1276 | cache_scope: CacheScope::Machine, |
| 1277 | oracle: Oracle::default(), |
| 1278 | digest: sha256_hex(GOOD.as_bytes()), |
| 1279 | }; |
| 1280 | assert_eq!(m, expected); |
| 1281 | assert_eq!(m.rules.len(), 3); |
| 1282 | } |
| 1283 | |
| 1284 | #[test] |
| 1285 | fn v2_prepare_parses_like_run() { |
| 1286 | let m = |
| 1287 | parse(v2("prepare:\n exec: tools/build.sh\n args: [\"chip-prepare\"]\n").as_bytes()) |
| 1288 | .unwrap(); |
| 1289 | let p = m.prepare.unwrap(); |
| 1290 | assert_eq!( |
| 1291 | (p.exec.as_str(), p.args), |
| 1292 | ("tools/build.sh", vec!["chip-prepare".to_string()]) |
| 1293 | ); |
| 1294 | assert!(parse(v2("").as_bytes()).unwrap().prepare.is_none()); |
| 1295 | let e = parse(v2("prepare:\n exec: /bin/sh\n").as_bytes()) |
| 1296 | .unwrap_err() |
| 1297 | .0; |
| 1298 | assert!(e.contains("prepare.exec"), "{e}"); |
| 1299 | assert!(parse(v2("prepare:\n exec: x.sh\n shell: sh\n").as_bytes()).is_err()); |
| 1300 | } |
| 1301 | |
| 1302 | #[test] |
| 1303 | fn v1_rejects_every_v2_key() { |
| 1304 | for extra in [ |
| 1305 | "exactness: EXACT\n", |
| 1306 | "cache_scope: portable\n", |
| 1307 | "fallback: [\"spark\"]\n", |
| 1308 | "backends:\n canonical: spark\n", |
| 1309 | "oracle:\n golden: g.txt\n", |
| 1310 | "tolerance:\n metric: m\n abs: 1\n rel_ppm: 1\n", |
| 1311 | "prepare:\n exec: tools/build.sh\n", |
| 1312 | ] { |
| 1313 | let e = parse(with(extra).as_bytes()).unwrap_err().0; |
| 1314 | assert!(e.contains("requires manifest_version 2"), "{extra}: {e}"); |
| 1315 | } |
| 1316 | assert!(parse(with("requires: [\"portable\"]\n").as_bytes()).is_err()); |
| 1317 | let t = GOOD.replace(" - host\n", " - host\n - nvrm\n"); |
| 1318 | assert!(parse(t.as_bytes()).is_err()); |
| 1319 | } |
| 1320 | |
| 1321 | #[test] |
| 1322 | fn a_v2_manifest_without_v2_keys_equals_its_v1_twin() { |
| 1323 | let a = parse(GOOD.as_bytes()).unwrap(); |
| 1324 | let b = parse(v2("").as_bytes()).unwrap(); |
| 1325 | assert_eq!(b.version, 2); |
| 1326 | let mut b2 = b.clone(); |
| 1327 | b2.version = 1; |
| 1328 | b2.digest = a.digest.clone(); |
| 1329 | assert_eq!(a, b2); |
| 1330 | } |
| 1331 | |
| 1332 | #[test] |
| 1333 | fn v2_defaults() { |
| 1334 | let m = parse(v2("").as_bytes()).unwrap(); |
| 1335 | assert_eq!(m.exactness, Exactness::Exact); |
| 1336 | assert_eq!(m.cache_scope, CacheScope::Machine); |
| 1337 | assert_eq!(m.fallback, vec!["spark".to_string()]); |
| 1338 | assert_eq!(m.backends.canonical, "spark"); |
| 1339 | let t = v2("").replace("requires:\n - host\n", ""); |
| 1340 | let m = parse(t.as_bytes()).unwrap(); |
| 1341 | assert_eq!(m.requires, vec!["host".to_string()]); |
| 1342 | let t = v2("").replace(" - host\n", " - portable\n"); |
| 1343 | let m = parse(t.as_bytes()).unwrap(); |
| 1344 | assert_eq!(m.backends.canonical, "portable"); |
| 1345 | let t = v2("").replace(" - host\n", " - gb10\n"); |
| 1346 | let m = parse(t.as_bytes()).unwrap(); |
| 1347 | assert_eq!(m.backends.canonical, "gb10"); |
| 1348 | assert_eq!(m.pool(), "gb10"); |
| 1349 | } |
| 1350 | |
| 1351 | #[test] |
| 1352 | fn v2_keys_parse() { |
| 1353 | let m = parse( |
| 1354 | v2(concat!( |
| 1355 | "exactness: BOUNDED\n", |
| 1356 | "tolerance:\n metric: max_ulp\n abs: 2\n rel_ppm: 100\n", |
| 1357 | "backends:\n eligible: [\"spark\", \"analog_sim\"]\n canonical: spark\n", |
| 1358 | "fallback: [\"spark\", \"gb10\"]\n", |
| 1359 | "cache_scope: arch\n", |
| 1360 | "oracle:\n golden: tests/g.txt\n", |
| 1361 | )) |
| 1362 | .as_bytes(), |
| 1363 | ) |
| 1364 | .unwrap(); |
| 1365 | assert_eq!(m.exactness, Exactness::Bounded); |
| 1366 | let t = m.tolerance.unwrap(); |
| 1367 | assert_eq!((t.metric.as_str(), t.abs, t.rel_ppm), ("max_ulp", 2, 100)); |
| 1368 | assert_eq!(m.backends.eligible, vec!["spark", "analog_sim"]); |
| 1369 | assert_eq!(m.fallback, vec!["spark", "gb10"]); |
| 1370 | assert_eq!(m.cache_scope, CacheScope::Arch); |
| 1371 | assert_eq!(m.oracle.golden.as_deref(), Some("tests/g.txt")); |
| 1372 | let m = parse(v2("oracle:\n compare: G-0\n").as_bytes()).unwrap(); |
| 1373 | assert_eq!(m.oracle.compare.as_deref(), Some("G-0")); |
| 1374 | } |
| 1375 | |
| 1376 | #[test] |
| 1377 | fn v2_refusals() { |
| 1378 | let tol = "tolerance:\n metric: m\n abs: 1\n rel_ppm: 1\n"; |
| 1379 | assert!(v2_err(tol).contains("only allowed with exactness BOUNDED")); |
| 1380 | assert!(v2_err("exactness: BOUNDED\n").contains("requires a tolerance")); |
| 1381 | assert!(v2_err("backends:\n eligible: [\"spark\", \"analog_sim\"]\n").contains("EXACT")); |
| 1382 | assert!(v2_err("backends:\n eligible: [\"analog_device\"]\n").contains("EXACT")); |
| 1383 | assert!( |
| 1384 | v2_err("backends:\n eligible: [\"spark\"]\n canonical: gb10\n") |
| 1385 | .contains("not in backends.eligible") |
| 1386 | ); |
| 1387 | let t = |
| 1388 | v2("requires: [\"host\", \"analog_eligible\"]\n").replace("requires:\n - host\n", ""); |
| 1389 | assert!(parse(t.as_bytes()).unwrap_err().0.contains("EXACT")); |
| 1390 | for bad in [ |
| 1391 | "exactness: exact\n", |
| 1392 | "cache_scope: galaxy\n", |
| 1393 | "backends:\n canonical: moon\n", |
| 1394 | "backends:\n eligible: [\"moon\"]\n", |
| 1395 | "fallback: [\"moon\"]\n", |
| 1396 | "fallback: []\n", |
| 1397 | "oracle:\n golden: /abs\n", |
| 1398 | "oracle:\n golden: a\n compare: G\n", |
| 1399 | "oracle:\n shell: x\n", |
| 1400 | "surprise: 1\n", |
| 1401 | "exactness: BOUNDED\ntolerance:\n metric: m\n abs: 1.5\n rel_ppm: 1\n", |
| 1402 | "exactness: BOUNDED\ntolerance:\n metric: m\n abs: 1\n", |
| 1403 | ] { |
| 1404 | assert!(parse(v2(bad).as_bytes()).is_err(), "{bad}"); |
| 1405 | } |
| 1406 | let t = v2("").replace(" - host\n", " - moon\n"); |
| 1407 | assert!(parse(t.as_bytes()).is_err()); |
| 1408 | } |
| 1409 | |
| 1410 | #[test] |
| 1411 | fn analog_may_scout_bounded_and_run_approximate() { |
| 1412 | let b = "exactness: BOUNDED\ntolerance:\n metric: m\n abs: 1\n rel_ppm: 0\nbackends:\n eligible: [\"spark\", \"analog_sim\"]\n"; |
| 1413 | assert!(parse(v2(b).as_bytes()).is_ok()); |
| 1414 | let bad = format!("{b} canonical: analog_sim\n"); |
| 1415 | assert!(v2_err(&bad).contains("APPROXIMATE or ADVISORY")); |
| 1416 | let a = "exactness: APPROXIMATE\nbackends:\n eligible: [\"analog_sim\"]\n canonical: analog_sim\n"; |
| 1417 | let m = parse(v2(a).as_bytes()).unwrap(); |
| 1418 | assert_eq!(m.backends.canonical, "analog_sim"); |
| 1419 | let m = parse( |
| 1420 | v2("exactness: ADVISORY\nrequires: [\"host\", \"analog_eligible\"]\n") |
| 1421 | .replace("requires:\n - host\n", "") |
| 1422 | .as_bytes(), |
| 1423 | ) |
| 1424 | .unwrap(); |
| 1425 | assert!(m.backends.eligible.iter().any(|b| b == "analog_sim")); |
| 1426 | } |
| 1427 | |
| 1428 | #[test] |
| 1429 | fn comment_inside_bare_value() { |
| 1430 | let m = parse( |
| 1431 | GOOD.replace("owner: omega", "owner: omega # note") |
| 1432 | .as_bytes(), |
| 1433 | ) |
| 1434 | .unwrap(); |
| 1435 | assert_eq!(m.owner, "omega"); |
| 1436 | let m = parse(GOOD.replace("owner: omega", "owner: a#b").as_bytes()).unwrap(); |
| 1437 | assert_eq!(m.owner, "a#b"); |
| 1438 | } |
| 1439 | } |