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-proof / src / lease.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 | //! Exclusive resource lease binding for evidence receipts. |
| 17 | //! |
| 18 | //! Hardware runs go through the merged coordination machinery: |
| 19 | //! `Board::hold` runs the command while holding its exclusive keys, seals an |
| 20 | //! `audit` event into the Crumb ledger, and stores a hold record under |
| 21 | //! `holds/`. Receipts reference the hold by its audit event hash; this |
| 22 | //! module checks the record, the ledger event, and the output digest. |
| 23 | //! Nothing here invents a second lock: all exclusion lives in `board`. |
| 24 | |
| 25 | use std::fs; |
| 26 | use std::path::Path; |
| 27 | |
| 28 | use crate::board::{valid_resource, Record}; |
| 29 | use crate::evidence::{Receipt, Report, Verdict}; |
| 30 | use crate::ledger; |
| 31 | |
| 32 | /// Subdirectory of the proof board root holding hold records. |
| 33 | pub const HOLD_DIR: &str = "holds"; |
| 34 | /// Ledger action used for hold audit events. |
| 35 | pub const HOLD_ACTION: &str = "audit"; |
| 36 | |
| 37 | /// Resource names follow the board rule: path components of lowercase |
| 38 | /// letters, digits, and dashes, at most 64 bytes. |
| 39 | pub fn check_resource_name(name: &str) -> Result<(), String> { |
| 40 | if valid_resource(name) { |
| 41 | Ok(()) |
| 42 | } else { |
| 43 | Err(format!( |
| 44 | "invalid resource name {name:?}: use lowercase letters, digits, dashes" |
| 45 | )) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// Find the hold record whose audit event hash is `hold_id`. |
| 50 | pub fn load_hold(store: &Path, hold_id: &str) -> Result<Record, String> { |
| 51 | let normalized = hold_id.to_ascii_lowercase(); |
| 52 | if normalized.len() != 64 || !normalized.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 53 | return Err(format!("hold id {hold_id:?} is not a 64 digit hash")); |
| 54 | } |
| 55 | let dir = store.join(HOLD_DIR); |
| 56 | let entries = fs::read_dir(&dir) |
| 57 | .map_err(|_| format!("hold record {normalized} not found: no holds in store"))?; |
| 58 | for entry in entries.flatten() { |
| 59 | let text = match fs::read(entry.path()) { |
| 60 | Ok(t) => t, |
| 61 | Err(_) => continue, |
| 62 | }; |
| 63 | if let Ok(record) = serde_json::from_slice::<Record>(&text) { |
| 64 | if record.ledger_hash.to_ascii_lowercase() == normalized { |
| 65 | return Ok(record); |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | Err(format!("missing hold record {normalized}")) |
| 70 | } |
| 71 | |
| 72 | /// Resources named in a hold audit intent (`... resources=a,b`). |
| 73 | fn intent_resources(intent: &str) -> Vec<String> { |
| 74 | intent |
| 75 | .rsplit_once("resources=") |
| 76 | .map(|(_, list)| { |
| 77 | list.split(',') |
| 78 | .map(|s| s.trim().to_string()) |
| 79 | .filter(|s| !s.is_empty()) |
| 80 | .collect() |
| 81 | }) |
| 82 | .unwrap_or_default() |
| 83 | } |
| 84 | |
| 85 | /// Check a receipt's lease reference against the hold store and ledger. |
| 86 | /// Returns `None` when the receipt claims no lease. `Ok(Some(report))` is |
| 87 | /// the binding verdict; `Err` means the store itself is unreadable. |
| 88 | pub fn check_lease_ref(receipt: &Receipt, store: &Path) -> Result<Option<Report>, String> { |
| 89 | let lease = match &receipt.lease { |
| 90 | Some(l) => l, |
| 91 | None => return Ok(None), |
| 92 | }; |
| 93 | let record = |
| 94 | load_hold(store, &lease.hold_id).map_err(|e| format!("lease binding broken: {e}"))?; |
| 95 | let mut problems = Vec::new(); |
| 96 | // The hold audit event must exist in the ledger with a matching hash. |
| 97 | let event = ledger::read_event(&store.join(ledger::LEDGER_FILE), record.ledger_index)? |
| 98 | .ok_or_else(|| { |
| 99 | format!( |
| 100 | "lease binding broken: ledger event {} is missing", |
| 101 | record.ledger_index |
| 102 | ) |
| 103 | })?; |
| 104 | if ledger::hex(&event.hash) != record.ledger_hash.to_ascii_lowercase() |
| 105 | || ledger::hex(&event.hash) != lease.hold_id.to_ascii_lowercase() |
| 106 | { |
| 107 | problems.push("hold record does not match its ledger audit event".to_string()); |
| 108 | } |
| 109 | if event.action != HOLD_ACTION { |
| 110 | problems.push(format!( |
| 111 | "ledger event {} is not a hold audit event", |
| 112 | record.ledger_index |
| 113 | )); |
| 114 | } |
| 115 | if !intent_resources(&event.intent) |
| 116 | .iter() |
| 117 | .any(|r| r == &lease.resource) |
| 118 | { |
| 119 | problems.push(format!( |
| 120 | "hold {} never covered resource {:?}", |
| 121 | lease.hold_id, lease.resource |
| 122 | )); |
| 123 | } |
| 124 | if receipt.machine != lease.resource { |
| 125 | problems.push(format!( |
| 126 | "receipt machine {:?} does not match leased resource {:?}", |
| 127 | receipt.machine, lease.resource |
| 128 | )); |
| 129 | } |
| 130 | if receipt.procedure != record.cmd.join(" ") { |
| 131 | problems.push(format!( |
| 132 | "receipt procedure {:?} does not match held command {:?}", |
| 133 | receipt.procedure, |
| 134 | record.cmd.join(" ") |
| 135 | )); |
| 136 | } |
| 137 | if !receipt |
| 138 | .output_digest |
| 139 | .eq_ignore_ascii_case(&ledger::hex(&event.payload_hash)) |
| 140 | { |
| 141 | problems.push("receipt output digest does not match the held run output".to_string()); |
| 142 | } |
| 143 | if receipt.result == Verdict::Pass && record.exit_code != 0 { |
| 144 | problems.push(format!( |
| 145 | "receipt claims PASS but the held run exited with {}", |
| 146 | record.exit_code |
| 147 | )); |
| 148 | } |
| 149 | if problems.is_empty() { |
| 150 | Ok(Some(Report::pass("lease binding checks out"))) |
| 151 | } else { |
| 152 | Ok(Some(Report::fail(problems))) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// Require a lease for hardware tiers. Called by chain and gate evaluation |
| 157 | /// so a Machine 1 qualification without a lease never reads as PASS. |
| 158 | pub fn lease_status(receipt: &Receipt, store: &Path) -> Option<Report> { |
| 159 | if !receipt.tier.is_hardware() { |
| 160 | return None; |
| 161 | } |
| 162 | match &receipt.lease { |
| 163 | None => Some(Report::closed( |
| 164 | Verdict::Incomplete, |
| 165 | vec!["Machine 1 qualification has no exclusive hardware lease".to_string()], |
| 166 | )), |
| 167 | Some(_) => match check_lease_ref(receipt, store) { |
| 168 | Ok(Some(r)) => Some(r), |
| 169 | Ok(None) => None, |
| 170 | Err(e) => Some(Report::fail(vec![e])), |
| 171 | }, |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /// Run a held command through the board and return its record plus the |
| 176 | /// output digest. Test helper that exercises the real exclusion path. |
| 177 | #[cfg(test)] |
| 178 | pub fn test_hold( |
| 179 | store: &Path, |
| 180 | base: &Path, |
| 181 | resource: &str, |
| 182 | holder: &str, |
| 183 | cmd: &[String], |
| 184 | ) -> (Record, String) { |
| 185 | use crate::board::{Board, Job}; |
| 186 | let board = Board { |
| 187 | root: store.to_path_buf(), |
| 188 | cpu_slots: 4, |
| 189 | min_free_bytes: 0, |
| 190 | mem_wait: std::time::Duration::from_secs(1), |
| 191 | quiet: true, |
| 192 | }; |
| 193 | let job = Job { |
| 194 | name: format!("test-hold-{resource}"), |
| 195 | agent: holder.to_string(), |
| 196 | base: base.to_path_buf(), |
| 197 | inputs: vec![], |
| 198 | cmd: cmd.to_vec(), |
| 199 | gpu: false, |
| 200 | resources: vec![resource.to_string()], |
| 201 | toolchain: String::new(), |
| 202 | }; |
| 203 | let record = board.hold(&job).unwrap(); |
| 204 | let event = ledger::read_event(&store.join(ledger::LEDGER_FILE), record.ledger_index) |
| 205 | .unwrap() |
| 206 | .unwrap(); |
| 207 | let digest = ledger::hex(&event.payload_hash); |
| 208 | (record, digest) |
| 209 | } |
| 210 | |
| 211 | #[cfg(test)] |
| 212 | mod tests { |
| 213 | use super::*; |
| 214 | use crate::evidence::fixtures::{sample, sealed}; |
| 215 | use crate::evidence::{store_receipt, LeaseRef, Mutation, Tier, Verdict}; |
| 216 | |
| 217 | fn machine_receipt( |
| 218 | resource: &str, |
| 219 | procedure: &str, |
| 220 | lease: Option<LeaseRef>, |
| 221 | output: &str, |
| 222 | ) -> Receipt { |
| 223 | let mut r = sample(); |
| 224 | r.tier = Tier::Machine1Attended; |
| 225 | r.env_class = "MACHINE1_ATTENDED".to_string(); |
| 226 | r.machine = resource.to_string(); |
| 227 | r.procedure = procedure.to_string(); |
| 228 | r.declared_mutation = Mutation::RemovableMediaOnly; |
| 229 | r.observed_mutation = Mutation::RemovableMediaOnly; |
| 230 | r.output_digest = output.to_string(); |
| 231 | r.lease = lease; |
| 232 | sealed(r) |
| 233 | } |
| 234 | |
| 235 | fn held_run(tag: &str) -> (std::path::PathBuf, (Record, String)) { |
| 236 | let store = crate::testutil::temp_dir(tag); |
| 237 | let base = crate::testutil::temp_dir(&format!("{tag}-base")); |
| 238 | let cmd = vec![ |
| 239 | "sh".to_string(), |
| 240 | "-c".to_string(), |
| 241 | "printf held-output".to_string(), |
| 242 | ]; |
| 243 | let held = test_hold(&store, &base, "machine-1", "tester", &cmd); |
| 244 | (store, held) |
| 245 | } |
| 246 | |
| 247 | #[test] |
| 248 | fn resource_names_follow_the_board_rule() { |
| 249 | assert!(check_resource_name("machine-1").is_ok()); |
| 250 | assert!(check_resource_name("machine_1").is_err()); |
| 251 | assert!(check_resource_name("Machine-1").is_err()); |
| 252 | assert!(check_resource_name("").is_err()); |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn lease_binding_verifies_end_to_end() { |
| 257 | let (store, (record, digest)) = held_run("lease-ok"); |
| 258 | let r = machine_receipt( |
| 259 | "machine-1", |
| 260 | &record.cmd.join(" "), |
| 261 | Some(LeaseRef { |
| 262 | hold_id: record.ledger_hash.clone(), |
| 263 | resource: "machine-1".to_string(), |
| 264 | }), |
| 265 | &digest, |
| 266 | ); |
| 267 | store_receipt(&store, &r).unwrap(); |
| 268 | let report = check_lease_ref(&r, &store).unwrap().unwrap(); |
| 269 | assert_eq!(report.status, Verdict::Pass); |
| 270 | } |
| 271 | |
| 272 | #[test] |
| 273 | fn hardware_receipt_without_hold_is_incomplete() { |
| 274 | let store = crate::testutil::temp_dir("lease-missing"); |
| 275 | let r = machine_receipt("machine-1", "scripts/x.sh", None, &"c".repeat(64)); |
| 276 | let report = lease_status(&r, &store).unwrap(); |
| 277 | assert_eq!(report.status, Verdict::Incomplete); |
| 278 | } |
| 279 | |
| 280 | #[test] |
| 281 | fn output_digest_mismatch_fails_binding() { |
| 282 | let (store, (record, _)) = held_run("lease-digest"); |
| 283 | let r = machine_receipt( |
| 284 | "machine-1", |
| 285 | &record.cmd.join(" "), |
| 286 | Some(LeaseRef { |
| 287 | hold_id: record.ledger_hash.clone(), |
| 288 | resource: "machine-1".to_string(), |
| 289 | }), |
| 290 | &"d".repeat(64), |
| 291 | ); |
| 292 | let report = check_lease_ref(&r, &store).unwrap().unwrap(); |
| 293 | assert_eq!(report.status, Verdict::Fail); |
| 294 | } |
| 295 | |
| 296 | #[test] |
| 297 | fn wrong_resource_fails_binding() { |
| 298 | let (store, (record, digest)) = held_run("lease-resource"); |
| 299 | let r = machine_receipt( |
| 300 | "machine-2", |
| 301 | &record.cmd.join(" "), |
| 302 | Some(LeaseRef { |
| 303 | hold_id: record.ledger_hash.clone(), |
| 304 | resource: "machine-2".to_string(), |
| 305 | }), |
| 306 | &digest, |
| 307 | ); |
| 308 | let report = check_lease_ref(&r, &store).unwrap().unwrap(); |
| 309 | assert_eq!(report.status, Verdict::Fail); |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn missing_hold_record_fails_closed() { |
| 314 | let store = crate::testutil::temp_dir("lease-gone"); |
| 315 | let r = machine_receipt( |
| 316 | "machine-1", |
| 317 | "scripts/x.sh", |
| 318 | Some(LeaseRef { |
| 319 | hold_id: "e".repeat(64), |
| 320 | resource: "machine-1".to_string(), |
| 321 | }), |
| 322 | &"c".repeat(64), |
| 323 | ); |
| 324 | assert!(check_lease_ref(&r, &store).is_err()); |
| 325 | } |
| 326 | } |