Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/store.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / store.rs` 451 lines ยท 15447 bytes Raw Blame History 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 //! Legacy ADR 0003 storage plus the canonical System Store v1 engine. 17 //! 18 //! Note: This module provides a host-tested implementation of ADR 0003 storage semantics, 19 //! not yet native AIENOS storage on bare-metal block devices. 20 //! 21 //! Content-addressed extents (`model/`, `cortex/wal`, `agent/`) 22 //! rather than a general-purpose POSIX filesystem. 23 24 #[allow(non_upper_case_globals)] // checkpoint exposes PascalCase interoperability aliases 25 pub mod checkpoint; 26 pub mod device; 27 pub mod engine; 28 pub mod genesis; 29 /// Canonical System Store v1 format and bounded Store-unit mount/transaction engine. 30 pub mod v1; 31 pub use checkpoint::{Checkpoint, CheckpointHook, NullCheckpointHook}; 32 pub use device::{StoreDeviceAdapter, StoreDeviceError}; 33 pub use engine::{MountError, MountState, ObjectInput, Store, StoreDevice, StoreError}; 34 35 use crate::block::{BlockDevice, BlockError}; 36 use crate::crypto::sha256; 37 38 const STORE_MAGIC: &[u8; 8] = b"AIENST01"; 39 const WAL_MAGIC: &[u8; 8] = b"AIENWL01"; 40 41 /// Latest committed extent on a block device. Payloads must fit in one block. 42 /// Blocks 0 and 1 are alternating superblocks; later blocks form the WAL ring. 43 pub struct BlockStore { 44 device: D, 45 generation: u64, 46 wal_lba: u64, 47 length: usize, 48 hash: [u8; 32], 49 } 50 51 impl BlockStore { 52 pub fn format(mut device: D) -> Result { 53 if (device.block_size() as usize) < 92 || device.block_count() < 5 { 54 return Err(BlockError::InvalidInput); 55 } 56 let zero = alloc::vec![0; device.block_size() as usize]; 57 device.write_blocks(0, &zero)?; 58 device.flush()?; 59 device.write_blocks(1, &zero)?; 60 device.flush()?; 61 Ok(Self { 62 device, 63 generation: 0, 64 wal_lba: 0, 65 length: 0, 66 hash: [0; 32], 67 }) 68 } 69 70 pub fn open(mut device: D) -> Result { 71 if (device.block_size() as usize) < 92 || device.block_count() < 5 { 72 return Err(BlockError::InvalidInput); 73 } 74 let size = device.block_size() as usize; 75 let mut best: Option<(u64, u64, usize, [u8; 32])> = None; 76 let mut saw_data = false; 77 for lba in 0..2 { 78 let mut b = alloc::vec![0; size]; 79 device.read_blocks(lba, &mut b)?; 80 if b.iter().all(|x| *x == 0) { 81 continue; 82 } 83 saw_data = true; 84 if &b[..8] != STORE_MAGIC || checksum(&b[..size - 32]) != b[size - 32..] { 85 continue; 86 } 87 let generation = get_u64(&b, 8); 88 let wal = get_u64(&b, 16); 89 let len = get_u32(&b, 24) as usize; 90 let mut hash = [0; 32]; 91 hash.copy_from_slice(&b[28..60]); 92 if len > size.saturating_sub(84) || wal < 2 || wal >= device.block_count() { 93 continue; 94 } 95 let mut record = alloc::vec![0; size]; 96 device.read_blocks(wal, &mut record)?; 97 if &record[..8] != WAL_MAGIC 98 || get_u64(&record, 8) != generation 99 || get_u32(&record, 16) as usize != len 100 || record[20..52] != hash 101 || checksum(&record[..size - 32]) != record[size - 32..] 102 || sha256::hash(&record[52..52 + len]) != hash 103 { 104 continue; 105 } 106 if best.is_none_or(|v| generation > v.0) { 107 best = Some((generation, wal, len, hash)); 108 } 109 } 110 if let Some((generation, wal_lba, length, hash)) = best { 111 Ok(Self { 112 device, 113 generation, 114 wal_lba, 115 length, 116 hash, 117 }) 118 } else if saw_data { 119 Err(BlockError::DeviceError) 120 } else { 121 Self::format(device) 122 } 123 } 124 125 /// Append and commit one extent. The returned descriptor addresses its WAL payload. 126 pub fn write_extent(&mut self, payload: &[u8]) -> Result { 127 let size = self.device.block_size() as usize; 128 if payload.len() > size.saturating_sub(84) { 129 return Err(BlockError::InvalidInput); 130 } 131 let generation = self 132 .generation 133 .checked_add(1) 134 .ok_or(BlockError::DeviceError)?; 135 let wal = 2 + (generation - 1) % (self.device.block_count() - 2); 136 let hash = sha256::hash(payload); 137 let mut record = alloc::vec![0; size]; 138 record[..8].copy_from_slice(WAL_MAGIC); 139 record[8..16].copy_from_slice(&generation.to_le_bytes()); 140 record[16..20].copy_from_slice(&(payload.len() as u32).to_le_bytes()); 141 record[20..52].copy_from_slice(&hash); 142 record[52..52 + payload.len()].copy_from_slice(payload); 143 let sum = sha256::hash(&record[..size - 32]); 144 record[size - 32..].copy_from_slice(&sum); 145 self.device.write_blocks(wal, &record)?; 146 self.device.flush()?; 147 let mut sb = alloc::vec![0; size]; 148 sb[..8].copy_from_slice(STORE_MAGIC); 149 sb[8..16].copy_from_slice(&generation.to_le_bytes()); 150 sb[16..24].copy_from_slice(&wal.to_le_bytes()); 151 sb[24..28].copy_from_slice(&(payload.len() as u32).to_le_bytes()); 152 sb[28..60].copy_from_slice(&hash); 153 let sum = sha256::hash(&sb[..size - 32]); 154 sb[size - 32..].copy_from_slice(&sum); 155 self.device.write_blocks(generation % 2, &sb)?; 156 self.device.flush()?; 157 self.generation = generation; 158 self.wal_lba = wal; 159 self.length = payload.len(); 160 self.hash = hash; 161 Ok(ExtentDescriptor { 162 hash, 163 offset: wal as usize * size + 52, 164 length: payload.len(), 165 }) 166 } 167 168 pub fn read_extent(&mut self) -> Result>, BlockError> { 169 if self.generation == 0 { 170 return Ok(None); 171 } 172 let size = self.device.block_size() as usize; 173 if self.length > size.saturating_sub(84) 174 || self.wal_lba < 2 175 || self.wal_lba >= self.device.block_count() 176 { 177 return Err(BlockError::InvalidInput); 178 } 179 let mut b = alloc::vec![0; size]; 180 self.device.read_blocks(self.wal_lba, &mut b)?; 181 if &b[..8] != WAL_MAGIC || get_u32(&b, 16) as usize != self.length { 182 return Err(BlockError::InvalidInput); 183 } 184 let data = &b[52..52 + self.length]; 185 if sha256::hash(data) != self.hash { 186 return Err(BlockError::DeviceError); 187 } 188 Ok(Some(data.to_vec())) 189 } 190 pub fn generation(&self) -> u64 { 191 self.generation 192 } 193 pub fn into_device(self) -> D { 194 self.device 195 } 196 } 197 198 fn checksum(bytes: &[u8]) -> [u8; 32] { 199 sha256::hash(bytes) 200 } 201 fn get_u32(b: &[u8], at: usize) -> u32 { 202 u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) 203 } 204 fn get_u64(b: &[u8], at: usize) -> u64 { 205 u64::from_le_bytes([ 206 b[at], 207 b[at + 1], 208 b[at + 2], 209 b[at + 3], 210 b[at + 4], 211 b[at + 5], 212 b[at + 6], 213 b[at + 7], 214 ]) 215 } 216 217 /// An immutable content-addressed storage extent. 218 #[derive(Clone, Debug, PartialEq, Eq)] 219 pub struct ExtentDescriptor { 220 pub hash: [u8; 32], 221 pub offset: usize, 222 pub length: usize, 223 } 224 225 /// Fixed-buffer Sovereign System Store for bare-metal `#![no_std]` substrate. 226 pub struct SystemStore { 227 storage: [u8; CAPACITY], 228 allocated: usize, 229 } 230 231 impl Default for SystemStore { 232 fn default() -> Self { 233 Self::new() 234 } 235 } 236 237 impl SystemStore { 238 /// Create a new sovereign system store over a fixed buffer. 239 pub const fn new() -> Self { 240 Self { 241 storage: [0u8; CAPACITY], 242 allocated: 0, 243 } 244 } 245 246 /// Write an immutable content-addressed extent into store. 247 pub fn write_extent(&mut self, payload: &[u8]) -> Option { 248 let new_allocated = self.allocated.checked_add(payload.len())?; 249 if new_allocated > CAPACITY { 250 return None; 251 } 252 253 let hash = sha256::hash(payload); 254 let offset = self.allocated; 255 let length = payload.len(); 256 257 self.storage[offset..new_allocated].copy_from_slice(payload); 258 self.allocated = new_allocated; 259 260 Some(ExtentDescriptor { 261 hash, 262 offset, 263 length, 264 }) 265 } 266 267 /// Read an extent and verify its cryptographic integrity. 268 pub fn read_extent<'a>(&'a self, desc: &ExtentDescriptor) -> Option<&'a [u8]> { 269 let extent_end = desc.offset.checked_add(desc.length)?; 270 if extent_end > self.allocated { 271 return None; 272 } 273 274 let slice = &self.storage[desc.offset..extent_end]; 275 let actual_hash = sha256::hash(slice); 276 if actual_hash != desc.hash { 277 return None; // Integrity violation 278 } 279 280 Some(slice) 281 } 282 283 /// Total bytes currently stored. 284 pub const fn allocated_bytes(&self) -> usize { 285 self.allocated 286 } 287 288 /// Total capacity. 289 pub const fn capacity(&self) -> usize { 290 CAPACITY 291 } 292 } 293 294 /// Slice-backed Sovereign System Store operating over caller-allocated memory 295 /// (e.g. static memory frame, DMA region, or heap buffer) without stack allocation risk. 296 pub struct SliceStore<'a> { 297 storage: &'a mut [u8], 298 allocated: usize, 299 } 300 301 impl<'a> SliceStore<'a> { 302 /// Create a new store backed by an existing memory slice. 303 pub fn new(storage: &'a mut [u8]) -> Self { 304 Self { 305 storage, 306 allocated: 0, 307 } 308 } 309 310 /// Write an immutable content-addressed extent into the memory slice. 311 pub fn write_extent(&mut self, payload: &[u8]) -> Option { 312 let new_allocated = self.allocated.checked_add(payload.len())?; 313 if new_allocated > self.storage.len() { 314 return None; 315 } 316 317 let hash = sha256::hash(payload); 318 let offset = self.allocated; 319 let length = payload.len(); 320 321 self.storage[offset..new_allocated].copy_from_slice(payload); 322 self.allocated = new_allocated; 323 324 Some(ExtentDescriptor { 325 hash, 326 offset, 327 length, 328 }) 329 } 330 331 /// Read an extent and verify its cryptographic integrity. 332 pub fn read_extent(&self, desc: &ExtentDescriptor) -> Option<&[u8]> { 333 let extent_end = desc.offset.checked_add(desc.length)?; 334 if extent_end > self.allocated { 335 return None; 336 } 337 338 let slice = &self.storage[desc.offset..extent_end]; 339 let actual_hash = sha256::hash(slice); 340 if actual_hash != desc.hash { 341 return None; // Integrity violation 342 } 343 344 Some(slice) 345 } 346 347 /// Total bytes allocated so far. 348 pub fn allocated_bytes(&self) -> usize { 349 self.allocated 350 } 351 352 /// Total available capacity. 353 pub fn capacity(&self) -> usize { 354 self.storage.len() 355 } 356 } 357 358 #[cfg(test)] 359 mod tests { 360 use super::*; 361 use crate::block::RamDisk; 362 363 #[test] 364 fn block_store_persists_reopens_and_falls_back_from_bad_copy() { 365 let disk = RamDisk::new(256, 12).unwrap(); 366 let mut store = BlockStore::format(disk).unwrap(); 367 store.write_extent(b"first committed payload").unwrap(); 368 store.write_extent(b"second committed payload").unwrap(); 369 let mut disk = store.into_device(); 370 // Generation two is in copy A (LBA 0); damage its checksum and use generation one. 371 disk.corrupt_byte(256 - 1, 0x80).unwrap(); 372 let mut reopened = BlockStore::open(disk).unwrap(); 373 assert_eq!(reopened.generation(), 1); 374 assert_eq!( 375 reopened.read_extent().unwrap().unwrap(), 376 b"first committed payload" 377 ); 378 } 379 380 #[test] 381 fn block_store_rejects_wrong_magic() { 382 let mut disk = RamDisk::new(256, 8).unwrap(); 383 disk.corrupt_byte(0, 0x7f).unwrap(); 384 assert!(matches!( 385 BlockStore::open(disk), 386 Err(BlockError::DeviceError) 387 )); 388 } 389 390 #[test] 391 fn block_store_crash_boundaries_keep_old_or_new_commit() { 392 let mut formatted = BlockStore::format(RamDisk::new(256, 12).unwrap()).unwrap(); 393 formatted.write_extent(b"old state").unwrap(); 394 let base = formatted.into_device(); 395 let block_size = base.block_size() as usize; 396 // write_extent issues exactly two single-block writes (WAL record, then the 397 // superblock commit). Tear each one at every byte offset, 0..=block_size. 398 for write_number in 1..=2 { 399 for offset in 0..=block_size { 400 let mut store = BlockStore::open(base.clone()).unwrap(); 401 store.device.tear_write(write_number, offset); 402 assert!(store.write_extent(b"new state").is_err()); 403 let mut reopened = BlockStore::open(store.into_device()).unwrap(); 404 let value = reopened.read_extent().unwrap().unwrap(); 405 assert!(value == b"old state" || value == b"new state"); 406 } 407 } 408 } 409 410 #[test] 411 fn block_store_rejects_corrupt_in_memory_length_without_panicking() { 412 let mut store = BlockStore::format(RamDisk::new(256, 8).unwrap()).unwrap(); 413 store.write_extent(b"committed").unwrap(); 414 store.length = usize::MAX; 415 assert_eq!(store.read_extent(), Err(BlockError::InvalidInput)); 416 } 417 418 #[test] 419 fn test_content_addressed_extent_storage() { 420 let mut store = SystemStore::<4096>::new(); 421 422 let model_header = b"AIENOS_MODEL_METADATA_v1:llama-3.2-1b"; 423 let desc = store.write_extent(model_header).expect("Write extent"); 424 425 let read_back = store.read_extent(&desc).expect("Read extent"); 426 assert_eq!(read_back, model_header); 427 428 // Verify tamper detection 429 let mut corrupted_desc = desc; 430 corrupted_desc.hash[0] ^= 0xFF; 431 assert!(store.read_extent(&corrupted_desc).is_none()); 432 } 433 434 #[test] 435 fn test_slice_store_operations_and_boundaries() { 436 let mut mem = [0u8; 1024]; 437 let mut store = SliceStore::new(&mut mem); 438 439 let data1 = b"cortex_snapshot_data_001"; 440 let desc1 = store.write_extent(data1).expect("Write data1"); 441 assert_eq!(store.read_extent(&desc1), Some(&data1[..])); 442 443 // Capacity overflow check 444 let huge_data = [0x55u8; 2048]; 445 assert!(store.write_extent(&huge_data).is_none()); 446 447 // Zero-length extent 448 let empty_desc = store.write_extent(b"").expect("Write empty extent"); 449 assert_eq!(store.read_extent(&empty_desc), Some(&b""[..])); 450 } 451 }