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 / identity.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 | //! Check identity (ADR 0033 Decision 3). |
| 17 | //! |
| 18 | //! `check_id` is sha256 over the canonical JSON object |
| 19 | //! `{manifest_digest, input_blob_ids, compiler_identity, flags, |
| 20 | //! dependency_check_ids, golden_digests, scope_binding}`. Same inputs give the |
| 21 | //! same id; a different input byte, compiler, flag, declared dependency, |
| 22 | //! golden file, or (for the machine and hardware scopes) machine gives a |
| 23 | //! different id. It is ADR 0028 Decision 7's cache key made explicit about |
| 24 | //! scope. |
| 25 | //! |
| 26 | //! Input identity is the git blob id of every tracked file under each |
| 27 | //! `inputs` entry, read with `git ls-files -s` (no git library). The index is |
| 28 | //! what is read, so an uncommitted edit to a tracked file is not seen: the |
| 29 | //! runner already refuses dirty trees, and `aien-test identity` is meant for |
| 30 | //! clean ones. A declared input that matches no tracked file is recorded with |
| 31 | //! a null blob id rather than dropped, so a typo or a deletion changes the id. |
| 32 | |
| 33 | use crate::evidence::{canonical, sha256_hex}; |
| 34 | use crate::graph::Graph; |
| 35 | use crate::manifest::{CacheScope, Manifest}; |
| 36 | use crate::process; |
| 37 | use serde_json::{json, Value}; |
| 38 | use std::collections::{BTreeMap, BTreeSet}; |
| 39 | use std::fs; |
| 40 | use std::path::Path; |
| 41 | |
| 42 | /// What the `scope_binding` member is built from. Only the part the manifest's |
| 43 | /// `cache_scope` names is used. |
| 44 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 45 | pub struct Binding { |
| 46 | /// The `arch` string (`std::env::consts::ARCH` on the real machine). |
| 47 | pub arch: String, |
| 48 | /// The ADR 0028 `machine_digest`. |
| 49 | pub machine_digest: String, |
| 50 | /// The hardware identity block for `cache_scope: hardware`. The ADR names |
| 51 | /// it but does not define its content (UNVERIFIED); the caller supplies it. |
| 52 | pub hardware_identity: String, |
| 53 | } |
| 54 | |
| 55 | fn git_ls_files(root: &Path, spec: &str) -> Result<Vec<(String, String)>, String> { |
| 56 | let mut cmd = process::git_command(); |
| 57 | cmd.env("GIT_OPTIONAL_LOCKS", "0") |
| 58 | .arg("-C") |
| 59 | .arg(root) |
| 60 | .args(["ls-files", "-s", "-z", "--"]) |
| 61 | .arg(format!(":(literal){spec}")); |
| 62 | let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run git: {e}"))?; |
| 63 | if !out.status.success() { |
| 64 | return Err(format!( |
| 65 | "git ls-files failed: {}", |
| 66 | String::from_utf8_lossy(&out.stderr).trim() |
| 67 | )); |
| 68 | } |
| 69 | let text = String::from_utf8(out.stdout).map_err(|_| "git output is not UTF-8".to_string())?; |
| 70 | let mut rows = Vec::new(); |
| 71 | for rec in text.split('\0').filter(|r| !r.is_empty()) { |
| 72 | let (meta, path) = rec |
| 73 | .split_once('\t') |
| 74 | .ok_or_else(|| format!("unparsable ls-files record {rec:?}"))?; |
| 75 | let f: Vec<&str> = meta.split(' ').collect(); |
| 76 | if f.len() != 3 || f[1].len() != 40 { |
| 77 | return Err(format!("unparsable ls-files record {rec:?}")); |
| 78 | } |
| 79 | if f[2] != "0" { |
| 80 | return Err(format!("{path} has an unmerged index entry")); |
| 81 | } |
| 82 | rows.push((path.to_string(), f[1].to_string())); |
| 83 | } |
| 84 | Ok(rows) |
| 85 | } |
| 86 | |
| 87 | /// `[{path, blob_id}]` sorted by path, one row per tracked file under the |
| 88 | /// manifest's `inputs`; a path that matches nothing gets `blob_id: null`. |
| 89 | pub fn input_blob_ids(m: &Manifest, root: &Path) -> Result<Vec<Value>, String> { |
| 90 | let mut rows: BTreeMap<String, Option<String>> = BTreeMap::new(); |
| 91 | for input in &m.inputs { |
| 92 | let spec = input.trim_end_matches('/'); |
| 93 | let found = git_ls_files(root, spec)?; |
| 94 | if found.is_empty() { |
| 95 | rows.entry(spec.to_string()).or_insert(None); |
| 96 | } |
| 97 | for (path, blob) in found { |
| 98 | rows.insert(path, Some(blob)); |
| 99 | } |
| 100 | } |
| 101 | Ok(rows |
| 102 | .into_iter() |
| 103 | .map(|(path, blob)| json!({ "path": path, "blob_id": blob })) |
| 104 | .collect()) |
| 105 | } |
| 106 | |
| 107 | /// The scope binding string for the manifest's `cache_scope`. |
| 108 | pub fn scope_binding(scope: CacheScope, b: &Binding) -> Result<String, String> { |
| 109 | Ok(match scope { |
| 110 | CacheScope::Portable => String::new(), |
| 111 | CacheScope::Arch => b.arch.clone(), |
| 112 | CacheScope::Machine => b.machine_digest.clone(), |
| 113 | CacheScope::Hardware => { |
| 114 | if b.hardware_identity.is_empty() { |
| 115 | return Err("cache_scope hardware needs a hardware identity".into()); |
| 116 | } |
| 117 | format!("{}:{}", b.machine_digest, b.hardware_identity) |
| 118 | } |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | /// Gates this check declares it rests on: `depends_on` plus an `oracle` |
| 123 | /// `compare` gate, sorted, no repeats. |
| 124 | pub fn declared_dependencies(m: &Manifest) -> Vec<String> { |
| 125 | let mut set: BTreeSet<String> = m.depends_on.iter().cloned().collect(); |
| 126 | if let Some(c) = &m.oracle.compare { |
| 127 | set.insert(c.clone()); |
| 128 | } |
| 129 | set.into_iter().collect() |
| 130 | } |
| 131 | |
| 132 | /// `input_blob_ids` computed from rows already read from a tree |
| 133 | /// (`git ls-tree -r COMMIT`), so a planner can identify a check at a commit |
| 134 | /// that is not checked out. Same shape and order as `input_blob_ids`. |
| 135 | pub fn input_blob_ids_from_rows(m: &Manifest, tree: &BTreeMap<String, String>) -> Vec<Value> { |
| 136 | let mut rows: BTreeMap<String, Option<String>> = BTreeMap::new(); |
| 137 | for input in &m.inputs { |
| 138 | let spec = input.trim_end_matches('/'); |
| 139 | let prefix = format!("{spec}/"); |
| 140 | let mut found = false; |
| 141 | for (path, blob) in tree.range(spec.to_string()..) { |
| 142 | if path == spec || path.starts_with(&prefix) { |
| 143 | rows.insert(path.clone(), Some(blob.clone())); |
| 144 | found = true; |
| 145 | } else if !path.starts_with(spec) { |
| 146 | break; |
| 147 | } |
| 148 | } |
| 149 | if !found { |
| 150 | rows.entry(spec.to_string()).or_insert(None); |
| 151 | } |
| 152 | } |
| 153 | rows.into_iter() |
| 154 | .map(|(path, blob)| json!({ "path": path, "blob_id": blob })) |
| 155 | .collect() |
| 156 | } |
| 157 | |
| 158 | /// The identity object from parts already read: `inputs` as `input_blob_ids` |
| 159 | /// gives them, `golden` the bytes of the oracle golden file if the manifest |
| 160 | /// names one. `identity_object` and the planner both build on this so the |
| 161 | /// hashed shape has one definition. |
| 162 | pub fn identity_object_from_parts( |
| 163 | m: &Manifest, |
| 164 | input_blob_ids: Vec<Value>, |
| 165 | golden: Option<&[u8]>, |
| 166 | compiler_identity: &str, |
| 167 | flags: &[String], |
| 168 | dependency_check_ids: &[String], |
| 169 | binding: &Binding, |
| 170 | ) -> Result<Value, String> { |
| 171 | let mut deps: Vec<String> = dependency_check_ids.to_vec(); |
| 172 | deps.sort(); |
| 173 | let mut goldens: Vec<String> = Vec::new(); |
| 174 | if m.oracle.golden.is_some() { |
| 175 | match golden { |
| 176 | Some(bytes) => goldens.push(sha256_hex(bytes)), |
| 177 | None => { |
| 178 | return Err(format!( |
| 179 | "golden file {} is missing", |
| 180 | m.oracle.golden.as_deref().unwrap_or("") |
| 181 | )) |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | goldens.sort(); |
| 186 | Ok(json!({ |
| 187 | "manifest_digest": m.digest, |
| 188 | "input_blob_ids": input_blob_ids, |
| 189 | "compiler_identity": compiler_identity, |
| 190 | "flags": flags, |
| 191 | "dependency_check_ids": deps, |
| 192 | "golden_digests": goldens, |
| 193 | "scope_binding": scope_binding(m.cache_scope, binding)?, |
| 194 | })) |
| 195 | } |
| 196 | |
| 197 | /// The object that `check_id` hashes. |
| 198 | pub fn identity_object( |
| 199 | m: &Manifest, |
| 200 | root: &Path, |
| 201 | compiler_identity: &str, |
| 202 | flags: &[String], |
| 203 | dependency_check_ids: &[String], |
| 204 | binding: &Binding, |
| 205 | ) -> Result<Value, String> { |
| 206 | let golden = match &m.oracle.golden { |
| 207 | Some(g) => { |
| 208 | Some(fs::read(root.join(g)).map_err(|e| format!("cannot read golden {g}: {e}"))?) |
| 209 | } |
| 210 | None => None, |
| 211 | }; |
| 212 | identity_object_from_parts( |
| 213 | m, |
| 214 | input_blob_ids(m, root)?, |
| 215 | golden.as_deref(), |
| 216 | compiler_identity, |
| 217 | flags, |
| 218 | dependency_check_ids, |
| 219 | binding, |
| 220 | ) |
| 221 | } |
| 222 | |
| 223 | pub fn id_of(object: &Value) -> Result<String, String> { |
| 224 | let bytes = canonical(object).map_err(|e| e.to_string())?; |
| 225 | Ok(sha256_hex(&bytes)) |
| 226 | } |
| 227 | |
| 228 | /// `check_id` (ADR 0033 Decision 3). |
| 229 | pub fn check_id( |
| 230 | m: &Manifest, |
| 231 | root: &Path, |
| 232 | compiler_identity: &str, |
| 233 | flags: &[String], |
| 234 | dependency_check_ids: &[String], |
| 235 | binding: &Binding, |
| 236 | ) -> Result<String, String> { |
| 237 | id_of(&identity_object( |
| 238 | m, |
| 239 | root, |
| 240 | compiler_identity, |
| 241 | flags, |
| 242 | dependency_check_ids, |
| 243 | binding, |
| 244 | )?) |
| 245 | } |
| 246 | |
| 247 | /// Ids and hashed objects for gate `target` and everything it rests on, |
| 248 | /// dependencies first. Dependency ids are computed with the same compiler, |
| 249 | /// flags and binding. |
| 250 | pub fn graph_identities( |
| 251 | graph: &Graph, |
| 252 | target: usize, |
| 253 | root: &Path, |
| 254 | compiler_identity: &str, |
| 255 | flags: &[String], |
| 256 | binding: &Binding, |
| 257 | ) -> Result<BTreeMap<String, (String, Value)>, String> { |
| 258 | let wanted = graph.with_dependencies(&[target]); |
| 259 | let mut done: BTreeMap<String, (String, Value)> = BTreeMap::new(); |
| 260 | for &i in graph.order() { |
| 261 | if !wanted.contains(&i) { |
| 262 | continue; |
| 263 | } |
| 264 | let m = &graph.node(i).manifest; |
| 265 | let mut dep_ids = Vec::new(); |
| 266 | for d in declared_dependencies(m) { |
| 267 | match done.get(&d) { |
| 268 | Some((id, _)) => dep_ids.push(id.clone()), |
| 269 | None => return Err(format!("gate {} declares unknown dependency {d}", m.gate)), |
| 270 | } |
| 271 | } |
| 272 | let obj = identity_object(m, root, compiler_identity, flags, &dep_ids, binding)?; |
| 273 | let id = id_of(&obj)?; |
| 274 | done.insert(m.gate.clone(), (id, obj)); |
| 275 | } |
| 276 | Ok(done) |
| 277 | } |
| 278 | |
| 279 | /// Planner-style path filter: the gates whose `inputs` contain a changed |
| 280 | /// path, plus everything each of them declares it depends on. A declared |
| 281 | /// dependency is never dropped by path filtering (ADR 0033 test 17). |
| 282 | pub fn select_changed(graph: &Graph, changed: &[String]) -> BTreeSet<usize> { |
| 283 | let touched: Vec<usize> = (0..graph.len()) |
| 284 | .filter(|&i| { |
| 285 | graph.node(i).manifest.inputs.iter().any(|input| { |
| 286 | let dir = input.trim_end_matches('/'); |
| 287 | changed |
| 288 | .iter() |
| 289 | .any(|c| c == dir || c.starts_with(&format!("{dir}/"))) |
| 290 | }) |
| 291 | }) |
| 292 | .collect(); |
| 293 | let mut seeds = touched; |
| 294 | for &i in &seeds.clone() { |
| 295 | if let Some(j) = graph |
| 296 | .node(i) |
| 297 | .manifest |
| 298 | .oracle |
| 299 | .compare |
| 300 | .as_deref() |
| 301 | .and_then(|c| graph.index_of(c)) |
| 302 | { |
| 303 | seeds.push(j); |
| 304 | } |
| 305 | } |
| 306 | graph.with_dependencies(&seeds) |
| 307 | } |
| 308 | |
| 309 | /// The binding for the machine this process runs on. |
| 310 | pub fn local_binding(hardware_identity: &str) -> Result<Binding, String> { |
| 311 | let machine = crate::runner::machine(&crate::resources::Hardware::detect()); |
| 312 | let machine_digest = crate::evidence::canonical_digest(&machine).map_err(|e| e.to_string())?; |
| 313 | Ok(Binding { |
| 314 | arch: std::env::consts::ARCH.to_string(), |
| 315 | machine_digest, |
| 316 | hardware_identity: hardware_identity.to_string(), |
| 317 | }) |
| 318 | } |
| 319 | |
| 320 | #[cfg(test)] |
| 321 | mod tests { |
| 322 | use super::*; |
| 323 | use crate::graph; |
| 324 | use crate::manifest; |
| 325 | use crate::testutil::{git, init_repo, write_file, TempDir}; |
| 326 | use std::process::Command; |
| 327 | |
| 328 | fn gate(id: &str, extra: &str) -> String { |
| 329 | format!( |
| 330 | "gate: {id}\nmanifest_version: 2\nowner: t\nrequires:\n - host\ninputs:\n - data_{id}/\nrun:\n exec: tools/run.sh\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 5s\n{extra}" |
| 331 | ) |
| 332 | } |
| 333 | |
| 334 | fn binding(machine: &str) -> Binding { |
| 335 | Binding { |
| 336 | arch: "aarch64".into(), |
| 337 | machine_digest: machine.repeat(64), |
| 338 | hardware_identity: "hw-1".into(), |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | fn repo(extra: &str) -> TempDir { |
| 343 | let g = gate("A", extra); |
| 344 | init_repo( |
| 345 | "ident", |
| 346 | &[ |
| 347 | ("gates/a.gate", g.as_str(), false), |
| 348 | ("tools/run.sh", "#!/bin/sh\nexit 0\n", true), |
| 349 | ("data_A/one.txt", "one\n", false), |
| 350 | ("data_A/sub/two.txt", "two\n", false), |
| 351 | ("elsewhere.txt", "x\n", false), |
| 352 | ], |
| 353 | ) |
| 354 | } |
| 355 | |
| 356 | fn parsed(t: &TempDir) -> Manifest { |
| 357 | manifest::parse(&std::fs::read(t.path().join("gates/a.gate")).unwrap()).unwrap() |
| 358 | } |
| 359 | |
| 360 | fn id(t: &TempDir, compiler: &str, flags: &[&str], deps: &[&str], b: &Binding) -> String { |
| 361 | let flags: Vec<String> = flags.iter().map(|s| s.to_string()).collect(); |
| 362 | let deps: Vec<String> = deps.iter().map(|s| s.to_string()).collect(); |
| 363 | check_id(&parsed(t), t.path(), compiler, &flags, &deps, b).unwrap() |
| 364 | } |
| 365 | |
| 366 | fn commit(t: &TempDir, rel: &str, content: &str) { |
| 367 | write_file(t.path(), rel, content, false); |
| 368 | git(t.path(), &["add", "-A"]); |
| 369 | git(t.path(), &["commit", "-q", "-m", "edit"]); |
| 370 | } |
| 371 | |
| 372 | #[test] |
| 373 | fn t1_same_inputs_twice_give_the_same_id() { |
| 374 | let t = repo(""); |
| 375 | let b = binding("a"); |
| 376 | let first = id(&t, "rustc 1", &["-O"], &[], &b); |
| 377 | assert_eq!(first.len(), 64); |
| 378 | assert_eq!(first, id(&t, "rustc 1", &["-O"], &[], &b)); |
| 379 | // A second repository with byte-identical content has the same id. |
| 380 | let u = repo(""); |
| 381 | assert_eq!(first, id(&u, "rustc 1", &["-O"], &[], &b)); |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn t2_one_input_byte_changes_the_id_and_an_unrelated_file_does_not() { |
| 386 | let t = repo(""); |
| 387 | let b = binding("a"); |
| 388 | let before = id(&t, "c", &[], &[], &b); |
| 389 | commit(&t, "elsewhere.txt", "y\n"); |
| 390 | assert_eq!(before, id(&t, "c", &[], &[], &b)); |
| 391 | commit(&t, "data_A/sub/two.txt", "twp\n"); |
| 392 | let after = id(&t, "c", &[], &[], &b); |
| 393 | assert_ne!(before, after); |
| 394 | commit(&t, "data_A/sub/two.txt", "two\n"); |
| 395 | assert_eq!(before, id(&t, "c", &[], &[], &b)); |
| 396 | } |
| 397 | |
| 398 | #[test] |
| 399 | fn input_blob_ids_are_sorted_git_blob_ids_and_missing_inputs_are_kept() { |
| 400 | let t = repo(""); |
| 401 | let rows = input_blob_ids(&parsed(&t), t.path()).unwrap(); |
| 402 | let paths: Vec<&str> = rows.iter().map(|r| r["path"].as_str().unwrap()).collect(); |
| 403 | assert_eq!(paths, ["data_A/one.txt", "data_A/sub/two.txt"]); |
| 404 | // git's own blob id of "one\n". |
| 405 | let mut cmd = Command::new("git"); |
| 406 | cmd.args(["hash-object", "--stdin"]) |
| 407 | .stdin(std::process::Stdio::piped()) |
| 408 | .stdout(std::process::Stdio::piped()); |
| 409 | // Through the spawn gate like every other spawn in this binary (sc#603): |
| 410 | // a raw spawn here left a child between fork and exec holding a copy of |
| 411 | // another test's GPU lock descriptor, and that test saw LockHeld after |
| 412 | // its own guard was dropped. |
| 413 | let mut child = crate::process::spawn_gated(&mut cmd).unwrap(); |
| 414 | std::io::Write::write_all(child.stdin.as_mut().unwrap(), b"one\n").unwrap(); |
| 415 | let out = child.wait_with_output().unwrap(); |
| 416 | assert_eq!( |
| 417 | rows[0]["blob_id"].as_str().unwrap(), |
| 418 | String::from_utf8_lossy(&out.stdout).trim() |
| 419 | ); |
| 420 | // A declared input that matches no tracked file is a null row. |
| 421 | let g = gate("A", "").replace("data_A/", "nothing_here/"); |
| 422 | let m = manifest::parse(g.as_bytes()).unwrap(); |
| 423 | let rows = input_blob_ids(&m, t.path()).unwrap(); |
| 424 | assert_eq!(rows.len(), 1); |
| 425 | assert!(rows[0]["blob_id"].is_null()); |
| 426 | // An untracked file under an input is not part of the identity. |
| 427 | let before = id(&t, "c", &[], &[], &binding("a")); |
| 428 | write_file(t.path(), "data_A/untracked.txt", "u\n", false); |
| 429 | assert_eq!(before, id(&t, "c", &[], &[], &binding("a"))); |
| 430 | } |
| 431 | |
| 432 | #[test] |
| 433 | fn t3_compiler_identity_and_flags_change_the_id() { |
| 434 | let t = repo(""); |
| 435 | let b = binding("a"); |
| 436 | let base = id(&t, "rustc 1", &["-O"], &[], &b); |
| 437 | assert_ne!(base, id(&t, "rustc 2", &["-O"], &[], &b)); |
| 438 | assert_ne!(base, id(&t, "rustc 1", &["-O3"], &[], &b)); |
| 439 | assert_ne!(base, id(&t, "rustc 1", &[], &[], &b)); |
| 440 | assert_ne!(base, id(&t, "rustc 1", &["-O", "-g"], &[], &b)); |
| 441 | } |
| 442 | |
| 443 | #[test] |
| 444 | fn t4_machine_scope_follows_the_machine_and_portable_does_not() { |
| 445 | let machine = repo("cache_scope: machine\n"); |
| 446 | let portable = repo("cache_scope: portable\n"); |
| 447 | let arch = repo("cache_scope: arch\n"); |
| 448 | let (a, z) = (binding("a"), binding("b")); |
| 449 | assert_ne!( |
| 450 | id(&machine, "c", &[], &[], &a), |
| 451 | id(&machine, "c", &[], &[], &z) |
| 452 | ); |
| 453 | assert_eq!( |
| 454 | id(&portable, "c", &[], &[], &a), |
| 455 | id(&portable, "c", &[], &[], &z) |
| 456 | ); |
| 457 | assert_eq!(id(&arch, "c", &[], &[], &a), id(&arch, "c", &[], &[], &z)); |
| 458 | let mut other_arch = binding("a"); |
| 459 | other_arch.arch = "x86_64".into(); |
| 460 | assert_ne!( |
| 461 | id(&arch, "c", &[], &[], &a), |
| 462 | id(&arch, "c", &[], &[], &other_arch) |
| 463 | ); |
| 464 | // The default scope is machine. |
| 465 | let default = repo(""); |
| 466 | assert_eq!(parsed(&default).cache_scope, CacheScope::Machine); |
| 467 | } |
| 468 | |
| 469 | #[test] |
| 470 | fn hardware_scope_adds_the_hardware_identity_and_refuses_without_it() { |
| 471 | let t = repo("cache_scope: hardware\n"); |
| 472 | let a = binding("a"); |
| 473 | let mut other = a.clone(); |
| 474 | other.hardware_identity = "hw-2".into(); |
| 475 | assert_ne!(id(&t, "c", &[], &[], &a), id(&t, "c", &[], &[], &other)); |
| 476 | let mut none = a.clone(); |
| 477 | none.hardware_identity = String::new(); |
| 478 | assert!(check_id(&parsed(&t), t.path(), "c", &[], &[], &none).is_err()); |
| 479 | // The portable scope binds to nothing at all. |
| 480 | assert_eq!(scope_binding(CacheScope::Portable, &a).unwrap(), ""); |
| 481 | assert_eq!(scope_binding(CacheScope::Arch, &a).unwrap(), "aarch64"); |
| 482 | } |
| 483 | |
| 484 | #[test] |
| 485 | fn golden_file_bytes_enter_the_identity() { |
| 486 | let g = gate("A", "oracle:\n golden: golden.txt\n"); |
| 487 | let t = init_repo( |
| 488 | "ident-golden", |
| 489 | &[ |
| 490 | ("gates/a.gate", g.as_str(), false), |
| 491 | ("tools/run.sh", "#!/bin/sh\n", true), |
| 492 | ("golden.txt", "v1\n", false), |
| 493 | ], |
| 494 | ); |
| 495 | let b = binding("a"); |
| 496 | let first = id(&t, "c", &[], &[], &b); |
| 497 | write_file(t.path(), "golden.txt", "v2\n", false); |
| 498 | assert_ne!(first, id(&t, "c", &[], &[], &b)); |
| 499 | std::fs::remove_file(t.path().join("golden.txt")).unwrap(); |
| 500 | assert!(check_id(&parsed(&t), t.path(), "c", &[], &[], &b).is_err()); |
| 501 | } |
| 502 | |
| 503 | #[test] |
| 504 | fn dependency_ids_are_sorted_and_part_of_the_object() { |
| 505 | let t = repo(""); |
| 506 | let b = binding("a"); |
| 507 | let x = "x".repeat(64); |
| 508 | let y = "y".repeat(64); |
| 509 | let obj = |
| 510 | identity_object(&parsed(&t), t.path(), "c", &[], &[y.clone(), x.clone()], &b).unwrap(); |
| 511 | assert_eq!(obj["dependency_check_ids"], serde_json::json!([x, y])); |
| 512 | assert_eq!( |
| 513 | id(&t, "c", &[], &["x", "y"], &b), |
| 514 | id(&t, "c", &[], &["y", "x"], &b) |
| 515 | ); |
| 516 | assert_ne!(id(&t, "c", &[], &["x"], &b), id(&t, "c", &[], &[], &b)); |
| 517 | for k in [ |
| 518 | "manifest_digest", |
| 519 | "input_blob_ids", |
| 520 | "compiler_identity", |
| 521 | "flags", |
| 522 | "golden_digests", |
| 523 | "scope_binding", |
| 524 | ] { |
| 525 | assert!(obj.get(k).is_some(), "{k}"); |
| 526 | } |
| 527 | assert_eq!(obj.as_object().unwrap().len(), 7); |
| 528 | } |
| 529 | |
| 530 | fn two_gate_repo() -> TempDir { |
| 531 | let a = gate("A", "depends_on:\n - B\n"); |
| 532 | let b = gate("B", ""); |
| 533 | init_repo( |
| 534 | "ident-graph", |
| 535 | &[ |
| 536 | ("gates/a.gate", a.as_str(), false), |
| 537 | ("gates/b.gate", b.as_str(), false), |
| 538 | ("tools/run.sh", "#!/bin/sh\n", true), |
| 539 | ("data_A/a.txt", "a\n", false), |
| 540 | ("data_B/b.txt", "b\n", false), |
| 541 | ], |
| 542 | ) |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | fn t17_a_declared_dependency_is_part_of_the_identity_even_when_no_changed_path_touches_it() { |
| 547 | let t = two_gate_repo(); |
| 548 | let b = binding("a"); |
| 549 | let g = graph::load(t.path()).unwrap(); |
| 550 | let ia = g.index_of("A").unwrap(); |
| 551 | let before = graph_identities(&g, ia, t.path(), "c", &[], &b).unwrap(); |
| 552 | // Only B's input changes. A's own inputs are untouched, but A's id moves. |
| 553 | commit(&t, "data_B/b.txt", "b2\n"); |
| 554 | let g = graph::load(t.path()).unwrap(); |
| 555 | let after = graph_identities(&g, ia, t.path(), "c", &[], &b).unwrap(); |
| 556 | assert_ne!(before["B"].0, after["B"].0); |
| 557 | assert_ne!(before["A"].0, after["A"].0); |
| 558 | assert_eq!( |
| 559 | before["A"].1["input_blob_ids"], |
| 560 | after["A"].1["input_blob_ids"] |
| 561 | ); |
| 562 | // A's recorded dependency id is exactly B's id. |
| 563 | assert_eq!( |
| 564 | after["A"].1["dependency_check_ids"], |
| 565 | serde_json::json!([after["B"].0]) |
| 566 | ); |
| 567 | } |
| 568 | |
| 569 | #[test] |
| 570 | fn t17_path_filtering_keeps_declared_dependencies() { |
| 571 | let t = two_gate_repo(); |
| 572 | let g = graph::load(t.path()).unwrap(); |
| 573 | let (ia, ib) = (g.index_of("A").unwrap(), g.index_of("B").unwrap()); |
| 574 | // Only A's input changed; B is not touched by any changed path, yet |
| 575 | // A cannot be checked without it. |
| 576 | let picked = select_changed(&g, &["data_A/a.txt".to_string()]); |
| 577 | assert!(picked.contains(&ia)); |
| 578 | assert!(picked.contains(&ib)); |
| 579 | // Only B changed: B alone is selected (dependents are not pulled in). |
| 580 | let picked = select_changed(&g, &["data_B/b.txt".to_string()]); |
| 581 | assert!(picked.contains(&ib) && !picked.contains(&ia)); |
| 582 | // Nothing relevant changed: nothing selected. |
| 583 | assert!(select_changed(&g, &["elsewhere.txt".to_string()]).is_empty()); |
| 584 | // A path that merely shares a name prefix with an input does not match. |
| 585 | assert!(select_changed(&g, &["data_A2/a.txt".to_string()]).is_empty()); |
| 586 | } |
| 587 | |
| 588 | #[test] |
| 589 | fn an_oracle_compare_gate_is_a_declared_dependency() { |
| 590 | let m = |
| 591 | manifest::parse(gate("A", "oracle:\n compare: B\ndepends_on:\n - C\n").as_bytes()) |
| 592 | .unwrap(); |
| 593 | assert_eq!(declared_dependencies(&m), ["B", "C"]); |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | #[cfg(test)] |
| 598 | mod rows_tests { |
| 599 | use super::*; |
| 600 | use crate::manifest; |
| 601 | use crate::testutil::init_repo; |
| 602 | use std::process::Command; |
| 603 | |
| 604 | #[test] |
| 605 | fn rows_from_a_tree_listing_give_the_same_identity_as_the_index() { |
| 606 | let g = "gate: A\nmanifest_version: 2\nowner: t\nrequires:\n - host\ninputs:\n - data/\n - missing.txt\nrun:\n exec: run.sh\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 5s\n"; |
| 607 | let t = init_repo( |
| 608 | "ident-rows", |
| 609 | &[ |
| 610 | ("a.gate", g, false), |
| 611 | ("run.sh", "#!/bin/sh\n", true), |
| 612 | ("data/one.txt", "one\n", false), |
| 613 | ("data/sub/two.txt", "two\n", false), |
| 614 | ("data2/three.txt", "three\n", false), |
| 615 | ], |
| 616 | ); |
| 617 | let m = manifest::parse(g.as_bytes()).unwrap(); |
| 618 | let from_index = input_blob_ids(&m, t.path()).unwrap(); |
| 619 | let mut cmd = Command::new("git"); |
| 620 | cmd.arg("-C").arg(t.path()).args(["ls-tree", "-r", "HEAD"]); |
| 621 | let out = process::output_gated(&mut cmd).unwrap(); |
| 622 | let mut tree = BTreeMap::new(); |
| 623 | for line in String::from_utf8_lossy(&out.stdout).lines() { |
| 624 | let (meta, path) = line.split_once('\t').unwrap(); |
| 625 | let blob = meta.split(' ').nth(2).unwrap(); |
| 626 | tree.insert(path.to_string(), blob.to_string()); |
| 627 | } |
| 628 | let from_rows = input_blob_ids_from_rows(&m, &tree); |
| 629 | assert_eq!(from_index, from_rows); |
| 630 | let paths: Vec<&str> = from_rows |
| 631 | .iter() |
| 632 | .map(|r| r["path"].as_str().unwrap()) |
| 633 | .collect(); |
| 634 | assert_eq!(paths, ["data/one.txt", "data/sub/two.txt", "missing.txt"]); |
| 635 | assert!(from_rows[2]["blob_id"].is_null()); |
| 636 | let b = Binding { |
| 637 | arch: "a".into(), |
| 638 | machine_digest: "m".repeat(64), |
| 639 | hardware_identity: String::new(), |
| 640 | }; |
| 641 | let a = identity_object(&m, t.path(), "c", &[], &[], &b).unwrap(); |
| 642 | let r = identity_object_from_parts(&m, from_rows, None, "c", &[], &[], &b).unwrap(); |
| 643 | assert_eq!(a, r); |
| 644 | } |
| 645 | } |