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-allen-profile / src / store.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 revision store `<home>.allen-profile/`: immutable files |
| 17 | //! `r00000000000000000001.json`, `r...2.json`, ... never edited in place. |
| 18 | //! |
| 19 | //! Write order for revision N: create a private temp file, write, fsync, |
| 20 | //! `hard_link(temp, rN)` (fails if rN already exists: that is a lost race, |
| 21 | //! reported as a stale update), fsync the directory, remove the temp file. |
| 22 | //! A crash at any step leaves the old head or the new head, never a mix; a |
| 23 | //! leftover temp file (`.tmp-*`) is ignored. The head is the highest N whose |
| 24 | //! chain 1..N is intact (each `prev_sha256` is the sha256 of the previous |
| 25 | //! file's bytes). Anything else in the directory (a gap, a damaged or |
| 26 | //! oversize file, an unknown schema or field, a foreign file, another |
| 27 | //! identity's revision) is a refusal: the store never silently replaces or |
| 28 | //! skips it. |
| 29 | use crate::refusal::ProfileRefusal as R; |
| 30 | use crate::schema::{ |
| 31 | apply_changes, clean_note, now_utc, Author, Changes, HistoryEntry, Identity, Persona, Profile, |
| 32 | WorkingPref, GENESIS_PREV, MAX_FILE_BYTES, PROFILE_SCHEMA, |
| 33 | }; |
| 34 | use sha2::{Digest, Sha256}; |
| 35 | use std::io::Write; |
| 36 | use std::path::{Path, PathBuf}; |
| 37 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 38 | |
| 39 | /// `<home>.allen-profile`, beside `<home>.allen-binding`. |
| 40 | pub fn profile_dir(home: &Path) -> PathBuf { |
| 41 | let mut n = home.as_os_str().to_owned(); |
| 42 | n.push(".allen-profile"); |
| 43 | PathBuf::from(n) |
| 44 | } |
| 45 | |
| 46 | /// The steps of one revision write, in order. A step is named after it completes. |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 48 | pub enum WriteStep { |
| 49 | TempCreated, |
| 50 | TempWritten, |
| 51 | TempSynced, |
| 52 | Linked, |
| 53 | DirSynced, |
| 54 | TempRemoved, |
| 55 | } |
| 56 | |
| 57 | impl WriteStep { |
| 58 | pub const ALL: [WriteStep; 6] = [ |
| 59 | WriteStep::TempCreated, |
| 60 | WriteStep::TempWritten, |
| 61 | WriteStep::TempSynced, |
| 62 | WriteStep::Linked, |
| 63 | WriteStep::DirSynced, |
| 64 | WriteStep::TempRemoved, |
| 65 | ]; |
| 66 | } |
| 67 | |
| 68 | #[cfg(feature = "fault-injection")] |
| 69 | type Hook = std::sync::Arc<dyn Fn(WriteStep) -> bool + Send + Sync>; |
| 70 | |
| 71 | pub struct Store { |
| 72 | dir: PathBuf, |
| 73 | id: Identity, |
| 74 | #[cfg(feature = "fault-injection")] |
| 75 | hook: Option<Hook>, |
| 76 | } |
| 77 | |
| 78 | struct Rev { |
| 79 | profile: Profile, |
| 80 | sha: String, |
| 81 | } |
| 82 | |
| 83 | fn sha_hex(b: &[u8]) -> String { |
| 84 | aien_allen::hex(&Sha256::digest(b)) |
| 85 | } |
| 86 | |
| 87 | fn file_name(n: u64) -> String { |
| 88 | format!("r{n:020}.json") |
| 89 | } |
| 90 | |
| 91 | fn parse_name(s: &str) -> Option<u64> { |
| 92 | let d = s.strip_prefix('r')?.strip_suffix(".json")?; |
| 93 | if d.len() != 20 || !d.bytes().all(|b| b.is_ascii_digit()) { |
| 94 | return None; |
| 95 | } |
| 96 | d.parse().ok().filter(|n| *n >= 1) |
| 97 | } |
| 98 | |
| 99 | fn io(what: &str, e: std::io::Error) -> R { |
| 100 | R::Io(format!("{what}: {e}")) |
| 101 | } |
| 102 | |
| 103 | impl Store { |
| 104 | /// The store beside `home` for the engaged identity `id`. |
| 105 | pub fn new(home: &Path, id: Identity) -> Store { |
| 106 | Store::at(profile_dir(home), id) |
| 107 | } |
| 108 | |
| 109 | pub fn at(dir: PathBuf, id: Identity) -> Store { |
| 110 | Store { |
| 111 | dir, |
| 112 | id, |
| 113 | #[cfg(feature = "fault-injection")] |
| 114 | hook: None, |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | pub fn dir(&self) -> &Path { |
| 119 | &self.dir |
| 120 | } |
| 121 | |
| 122 | /// Test seam: `hook(step)` runs after each write step; returning true |
| 123 | /// stops the write there, as a crash would (no cleanup). |
| 124 | #[cfg(feature = "fault-injection")] |
| 125 | pub fn with_fault_hook(mut self, hook: Hook) -> Store { |
| 126 | self.hook = Some(hook); |
| 127 | self |
| 128 | } |
| 129 | |
| 130 | fn after(&self, step: WriteStep) -> Result<(), R> { |
| 131 | #[cfg(feature = "fault-injection")] |
| 132 | if let Some(h) = &self.hook { |
| 133 | if h(step) { |
| 134 | return Err(R::Crashed(format!("{step:?}"))); |
| 135 | } |
| 136 | } |
| 137 | let _ = step; |
| 138 | Ok(()) |
| 139 | } |
| 140 | |
| 141 | /// Every revision 1..=head, fully verified. Empty when no store exists. |
| 142 | fn chain(&self) -> Result<Vec<Rev>, R> { |
| 143 | let rd = match std::fs::read_dir(&self.dir) { |
| 144 | Ok(rd) => rd, |
| 145 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), |
| 146 | Err(e) => return Err(io("read profile folder", e)), |
| 147 | }; |
| 148 | let mut nums: Vec<u64> = Vec::new(); |
| 149 | for ent in rd { |
| 150 | let ent = ent.map_err(|e| io("read profile folder", e))?; |
| 151 | let name = ent.file_name().to_string_lossy().into_owned(); |
| 152 | if name.starts_with(".tmp-") { |
| 153 | continue; // a crashed writer's leftover |
| 154 | } |
| 155 | match parse_name(&name) { |
| 156 | Some(n) => nums.push(n), |
| 157 | None => return Err(R::Damaged(format!("unexpected file \"{name}\""))), |
| 158 | } |
| 159 | } |
| 160 | nums.sort_unstable(); |
| 161 | for (i, n) in nums.iter().enumerate() { |
| 162 | if *n != i as u64 + 1 { |
| 163 | return Err(R::Damaged(format!( |
| 164 | "revision files are not contiguous (found {n} where {} was expected)", |
| 165 | i + 1 |
| 166 | ))); |
| 167 | } |
| 168 | } |
| 169 | let mut out: Vec<Rev> = Vec::with_capacity(nums.len()); |
| 170 | let mut prev = GENESIS_PREV.to_string(); |
| 171 | for n in nums { |
| 172 | let path = self.dir.join(file_name(n)); |
| 173 | let meta = std::fs::metadata(&path).map_err(|e| io("stat revision", e))?; |
| 174 | if meta.len() > MAX_FILE_BYTES { |
| 175 | return Err(R::Damaged(format!( |
| 176 | "revision {n} is {} bytes (limit {MAX_FILE_BYTES})", |
| 177 | meta.len() |
| 178 | ))); |
| 179 | } |
| 180 | let bytes = std::fs::read(&path).map_err(|e| io("read revision", e))?; |
| 181 | let p: Profile = serde_json::from_slice(&bytes) |
| 182 | .map_err(|e| R::Damaged(format!("revision {n}: {e}")))?; |
| 183 | p.validate() |
| 184 | .map_err(|e| R::Damaged(format!("revision {n}: {e}")))?; |
| 185 | if !p.is_bound_to(&self.id) { |
| 186 | return Err(R::ForeignProfile(format!( |
| 187 | "revision {n} names agent {}", |
| 188 | &p.agent[..8] |
| 189 | ))); |
| 190 | } |
| 191 | if p.revision != n { |
| 192 | return Err(R::Damaged(format!( |
| 193 | "revision {n} says it is revision {}", |
| 194 | p.revision |
| 195 | ))); |
| 196 | } |
| 197 | if p.prev_sha256 != prev { |
| 198 | return Err(R::Damaged(format!("revision {n} breaks the hash chain"))); |
| 199 | } |
| 200 | prev = sha_hex(&bytes); |
| 201 | out.push(Rev { |
| 202 | profile: p, |
| 203 | sha: prev.clone(), |
| 204 | }); |
| 205 | } |
| 206 | Ok(out) |
| 207 | } |
| 208 | |
| 209 | /// The current head, or `None` when no profile has been saved. |
| 210 | pub fn head(&self) -> Result<Option<Profile>, R> { |
| 211 | Ok(self.chain()?.pop().map(|r| r.profile)) |
| 212 | } |
| 213 | |
| 214 | /// Current revision number (0 = none). |
| 215 | pub fn revision(&self) -> Result<u64, R> { |
| 216 | Ok(self.head()?.map_or(0, |p| p.revision)) |
| 217 | } |
| 218 | |
| 219 | pub fn get(&self, revision: u64) -> Result<Profile, R> { |
| 220 | self.chain()? |
| 221 | .into_iter() |
| 222 | .find(|r| r.profile.revision == revision) |
| 223 | .map(|r| r.profile) |
| 224 | .ok_or(R::UnknownRevision(revision)) |
| 225 | } |
| 226 | |
| 227 | pub fn history(&self) -> Result<Vec<HistoryEntry>, R> { |
| 228 | Ok(self |
| 229 | .chain()? |
| 230 | .into_iter() |
| 231 | .map(|r| HistoryEntry { |
| 232 | revision: r.profile.revision, |
| 233 | written_at: r.profile.written_at, |
| 234 | author: r.profile.author, |
| 235 | note: r.profile.note, |
| 236 | display_name: r.profile.persona.display_name, |
| 237 | }) |
| 238 | .collect()) |
| 239 | } |
| 240 | |
| 241 | /// Apply `changes` on top of revision `expected`. |
| 242 | pub fn set(&self, expected: u64, changes: &Changes) -> Result<Profile, R> { |
| 243 | let chain = self.chain()?; |
| 244 | check_expected(expected, &chain)?; |
| 245 | let (base_p, base_w) = base(&chain); |
| 246 | let note = match &changes.note { |
| 247 | Some(n) => clean_note(n)?, |
| 248 | None => String::new(), |
| 249 | }; |
| 250 | let (p, w) = apply_changes(&base_p, &base_w, changes)?; |
| 251 | self.commit(chain, Author::User, note, p, w) |
| 252 | } |
| 253 | |
| 254 | /// Write a NEW revision whose content is a copy of revision `to`. |
| 255 | pub fn revert(&self, expected: u64, to: u64) -> Result<Profile, R> { |
| 256 | let chain = self.chain()?; |
| 257 | check_expected(expected, &chain)?; |
| 258 | if chain.is_empty() { |
| 259 | return Err(R::NoProfile); |
| 260 | } |
| 261 | let src = chain |
| 262 | .iter() |
| 263 | .find(|r| r.profile.revision == to) |
| 264 | .ok_or(R::UnknownRevision(to))?; |
| 265 | let (p, w) = ( |
| 266 | src.profile.persona.clone(), |
| 267 | src.profile.working_preferences.clone(), |
| 268 | ); |
| 269 | self.commit( |
| 270 | chain, |
| 271 | Author::Revert(to), |
| 272 | format!("reverted to revision {to}"), |
| 273 | p, |
| 274 | w, |
| 275 | ) |
| 276 | } |
| 277 | |
| 278 | /// Write a NEW revision with the defaults. The identity is untouched. |
| 279 | pub fn reset(&self, expected: u64) -> Result<Profile, R> { |
| 280 | let chain = self.chain()?; |
| 281 | check_expected(expected, &chain)?; |
| 282 | if chain.is_empty() { |
| 283 | return Err(R::NoProfile); |
| 284 | } |
| 285 | self.commit( |
| 286 | chain, |
| 287 | Author::Reset, |
| 288 | "reset to defaults".into(), |
| 289 | Persona::default(), |
| 290 | Vec::new(), |
| 291 | ) |
| 292 | } |
| 293 | |
| 294 | fn commit( |
| 295 | &self, |
| 296 | chain: Vec<Rev>, |
| 297 | author: Author, |
| 298 | note: String, |
| 299 | persona: Persona, |
| 300 | prefs: Vec<WorkingPref>, |
| 301 | ) -> Result<Profile, R> { |
| 302 | let (cur_p, cur_w) = base(&chain); |
| 303 | if persona == cur_p && prefs == cur_w { |
| 304 | return Err(R::NothingToChange); |
| 305 | } |
| 306 | let revision = chain.len() as u64 + 1; |
| 307 | let prev_sha256 = chain |
| 308 | .last() |
| 309 | .map_or_else(|| GENESIS_PREV.to_string(), |r| r.sha.clone()); |
| 310 | let profile = Profile { |
| 311 | schema: PROFILE_SCHEMA.into(), |
| 312 | agent: self.id.agent_hex(), |
| 313 | root: self.id.root_hex(), |
| 314 | revision, |
| 315 | prev_sha256, |
| 316 | written_at: now_utc(), |
| 317 | author, |
| 318 | note, |
| 319 | persona, |
| 320 | working_preferences: prefs, |
| 321 | }; |
| 322 | profile.validate().map_err(|e| match e { |
| 323 | R::Damaged(w) => R::Invalid(w), |
| 324 | o => o, |
| 325 | })?; |
| 326 | let bytes = serde_json::to_vec(&profile).map_err(|e| R::Io(format!("serialize: {e}")))?; |
| 327 | if bytes.len() as u64 > MAX_FILE_BYTES { |
| 328 | return Err(R::Invalid(format!( |
| 329 | "the profile would be {} bytes (limit {MAX_FILE_BYTES})", |
| 330 | bytes.len() |
| 331 | ))); |
| 332 | } |
| 333 | self.write_revision(revision, &bytes)?; |
| 334 | Ok(profile) |
| 335 | } |
| 336 | |
| 337 | fn write_revision(&self, n: u64, bytes: &[u8]) -> Result<(), R> { |
| 338 | static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 339 | let fresh = !self.dir.exists(); |
| 340 | std::fs::create_dir_all(&self.dir).map_err(|e| io("create profile folder", e))?; |
| 341 | if fresh { |
| 342 | if let Some(parent) = self.dir.parent() { |
| 343 | sync_dir(parent)?; |
| 344 | } |
| 345 | } |
| 346 | let nanos = std::time::SystemTime::now() |
| 347 | .duration_since(std::time::UNIX_EPOCH) |
| 348 | .map(|d| d.as_nanos()) |
| 349 | .unwrap_or(0); |
| 350 | let tmp = self.dir.join(format!( |
| 351 | ".tmp-{}-{}-{nanos}", |
| 352 | std::process::id(), |
| 353 | COUNTER.fetch_add(1, Ordering::SeqCst) |
| 354 | )); |
| 355 | let r = self.write_steps(&tmp, &self.dir.join(file_name(n)), bytes); |
| 356 | match &r { |
| 357 | // A simulated crash leaves things exactly as they are. |
| 358 | Err(R::Crashed(_)) => {} |
| 359 | // Any other failure: the temp file must not linger. |
| 360 | Err(_) => { |
| 361 | let _ = std::fs::remove_file(&tmp); |
| 362 | } |
| 363 | Ok(()) => {} |
| 364 | } |
| 365 | match r { |
| 366 | Err(R::StaleUpdate { .. }) => { |
| 367 | let current = self.revision().unwrap_or(n); |
| 368 | Err(R::StaleUpdate { |
| 369 | expected: n - 1, |
| 370 | current, |
| 371 | }) |
| 372 | } |
| 373 | o => o, |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | fn write_steps(&self, tmp: &Path, dst: &Path, bytes: &[u8]) -> Result<(), R> { |
| 378 | let mut oo = std::fs::OpenOptions::new(); |
| 379 | oo.write(true).create_new(true); |
| 380 | #[cfg(unix)] |
| 381 | { |
| 382 | use std::os::unix::fs::OpenOptionsExt; |
| 383 | oo.mode(0o600); |
| 384 | } |
| 385 | let mut f = oo.open(tmp).map_err(|e| io("create temp file", e))?; |
| 386 | self.after(WriteStep::TempCreated)?; |
| 387 | f.write_all(bytes).map_err(|e| io("write", e))?; |
| 388 | self.after(WriteStep::TempWritten)?; |
| 389 | f.sync_all().map_err(|e| io("fsync", e))?; |
| 390 | drop(f); |
| 391 | self.after(WriteStep::TempSynced)?; |
| 392 | match std::fs::hard_link(tmp, dst) { |
| 393 | Ok(()) => {} |
| 394 | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { |
| 395 | let _ = std::fs::remove_file(tmp); |
| 396 | return Err(R::StaleUpdate { |
| 397 | expected: 0, |
| 398 | current: 0, |
| 399 | }); |
| 400 | } |
| 401 | Err(e) => return Err(io("link revision", e)), |
| 402 | } |
| 403 | self.after(WriteStep::Linked)?; |
| 404 | sync_dir(&self.dir)?; |
| 405 | self.after(WriteStep::DirSynced)?; |
| 406 | std::fs::remove_file(tmp).map_err(|e| io("remove temp file", e))?; |
| 407 | self.after(WriteStep::TempRemoved)?; |
| 408 | Ok(()) |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | fn sync_dir(p: &Path) -> Result<(), R> { |
| 413 | std::fs::File::open(p) |
| 414 | .and_then(|d| d.sync_all()) |
| 415 | .map_err(|e| io("fsync folder", e)) |
| 416 | } |
| 417 | |
| 418 | fn check_expected(expected: u64, chain: &[Rev]) -> Result<(), R> { |
| 419 | let current = chain.len() as u64; |
| 420 | if expected != current { |
| 421 | return Err(R::StaleUpdate { expected, current }); |
| 422 | } |
| 423 | Ok(()) |
| 424 | } |
| 425 | |
| 426 | fn base(chain: &[Rev]) -> (Persona, Vec<WorkingPref>) { |
| 427 | match chain.last() { |
| 428 | Some(r) => ( |
| 429 | r.profile.persona.clone(), |
| 430 | r.profile.working_preferences.clone(), |
| 431 | ), |
| 432 | None => (Persona::default(), Vec::new()), |
| 433 | } |
| 434 | } |