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-expert-store / src / store.rs
| 1 | //! The on-disk expert store. |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! <root>/objects/<sha256 hex> one artifact per file, named by its content address |
| 5 | //! <root>/index-v1 the committed index (see `format`) |
| 6 | //! <root>/tmp/ private temporaries, removed on open |
| 7 | //! ``` |
| 8 | //! |
| 9 | //! Crash safety: every file is written to a fresh temporary (`O_EXCL`, mode |
| 10 | //! 0600), synced, renamed into place and its directory synced. An object is |
| 11 | //! durable before `put` returns; the index is replaced atomically by |
| 12 | //! `commit`, so after a crash the store holds either the old or the new index |
| 13 | //! and every object either index names. Orphan objects are harmless. |
| 14 | //! |
| 15 | //! Bounded memory: the store holds only the index (`max_entries` entries); |
| 16 | //! `put` holds one artifact (`max_object_bytes`). |
| 17 | |
| 18 | use crate::error::StoreError; |
| 19 | use crate::format::{ |
| 20 | build_artifact, decode_index, digest_eq, encode_index, hex, max_index_bytes, sha256, ExpertKey, |
| 21 | IndexEntry, ScaleDtype, |
| 22 | }; |
| 23 | use crate::source::{FileSource, IoMode}; |
| 24 | use std::collections::BTreeMap; |
| 25 | use std::fs::{File, OpenOptions}; |
| 26 | use std::io::{Read, Write}; |
| 27 | use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; |
| 28 | use std::path::{Path, PathBuf}; |
| 29 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 30 | |
| 31 | pub const INDEX_FILE: &str = "index-v1"; |
| 32 | static TMP_COUNTER: AtomicU64 = AtomicU64::new(0); |
| 33 | |
| 34 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 35 | pub struct StoreLimits { |
| 36 | pub max_entries: usize, |
| 37 | pub max_object_bytes: u64, |
| 38 | } |
| 39 | |
| 40 | impl Default for StoreLimits { |
| 41 | fn default() -> Self { |
| 42 | // One Qwen3-30B-A3B checkpoint: 48 layers x 128 experts x 3 projections. |
| 43 | Self { |
| 44 | max_entries: 48 * 128 * 3, |
| 45 | max_object_bytes: 64 << 20, |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | pub struct ExpertStore { |
| 51 | root: PathBuf, |
| 52 | limits: StoreLimits, |
| 53 | entries: BTreeMap<ExpertKey, IndexEntry>, |
| 54 | } |
| 55 | |
| 56 | const OPEN_FLAGS: i32 = libc::O_NOFOLLOW | libc::O_CLOEXEC; |
| 57 | |
| 58 | fn sync_dir(dir: &Path) -> Result<(), StoreError> { |
| 59 | File::open(dir)?.sync_all()?; |
| 60 | Ok(()) |
| 61 | } |
| 62 | |
| 63 | fn ensure_dir(dir: &Path) -> Result<(), StoreError> { |
| 64 | match std::fs::DirBuilder::new().mode(0o700).create(dir) { |
| 65 | Ok(()) => Ok(()), |
| 66 | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { |
| 67 | if std::fs::symlink_metadata(dir)?.is_dir() { |
| 68 | Ok(()) |
| 69 | } else { |
| 70 | Err(StoreError::Io(std::io::ErrorKind::NotADirectory)) |
| 71 | } |
| 72 | } |
| 73 | Err(e) => Err(e.into()), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /// Reads a whole file of at most `max` bytes without following a symlink. |
| 78 | fn read_bounded(path: &Path, max: u64) -> Result<Vec<u8>, StoreError> { |
| 79 | let f = OpenOptions::new() |
| 80 | .read(true) |
| 81 | .custom_flags(OPEN_FLAGS) |
| 82 | .open(path)?; |
| 83 | let len = f.metadata()?.len(); |
| 84 | if len > max { |
| 85 | return Err(StoreError::ObjectTooLarge { len, max }); |
| 86 | } |
| 87 | let mut out = Vec::with_capacity(len as usize); |
| 88 | f.take(max + 1).read_to_end(&mut out)?; |
| 89 | if out.len() as u64 > max { |
| 90 | return Err(StoreError::ObjectTooLarge { |
| 91 | len: out.len() as u64, |
| 92 | max, |
| 93 | }); |
| 94 | } |
| 95 | Ok(out) |
| 96 | } |
| 97 | |
| 98 | impl ExpertStore { |
| 99 | /// Opens (creating if needed) the store at `root`, removes temporaries |
| 100 | /// left by a crash, and loads and validates the committed index. |
| 101 | pub fn open(root: &Path, limits: StoreLimits) -> Result<Self, StoreError> { |
| 102 | ensure_dir(root)?; |
| 103 | ensure_dir(&root.join("objects"))?; |
| 104 | let tmp = root.join("tmp"); |
| 105 | ensure_dir(&tmp)?; |
| 106 | for e in std::fs::read_dir(&tmp)? { |
| 107 | let e = e?; |
| 108 | if e.file_type()?.is_file() { |
| 109 | std::fs::remove_file(e.path())?; |
| 110 | } |
| 111 | } |
| 112 | let mut entries = BTreeMap::new(); |
| 113 | match read_bounded(&root.join(INDEX_FILE), max_index_bytes(limits.max_entries)) { |
| 114 | Ok(bytes) => { |
| 115 | for e in decode_index(&bytes, limits.max_entries)? { |
| 116 | if e.object_len > limits.max_object_bytes { |
| 117 | return Err(StoreError::ObjectTooLarge { |
| 118 | len: e.object_len, |
| 119 | max: limits.max_object_bytes, |
| 120 | }); |
| 121 | } |
| 122 | entries.insert(e.key, e); |
| 123 | } |
| 124 | } |
| 125 | Err(StoreError::Io(std::io::ErrorKind::NotFound)) => {} |
| 126 | Err(StoreError::ObjectTooLarge { .. }) => return Err(StoreError::TooManyEntries), |
| 127 | Err(e) => return Err(e), |
| 128 | } |
| 129 | Ok(Self { |
| 130 | root: root.to_path_buf(), |
| 131 | limits, |
| 132 | entries, |
| 133 | }) |
| 134 | } |
| 135 | |
| 136 | pub fn root(&self) -> &Path { |
| 137 | &self.root |
| 138 | } |
| 139 | |
| 140 | pub fn limits(&self) -> StoreLimits { |
| 141 | self.limits |
| 142 | } |
| 143 | |
| 144 | pub fn objects_dir(&self) -> PathBuf { |
| 145 | self.root.join("objects") |
| 146 | } |
| 147 | |
| 148 | /// A read source over this store's objects. |
| 149 | pub fn file_source(&self, mode: IoMode) -> FileSource { |
| 150 | FileSource::new(self.objects_dir(), mode) |
| 151 | } |
| 152 | |
| 153 | /// Entries in key order (committed plus staged by `put`). |
| 154 | pub fn entries(&self) -> impl Iterator<Item = &IndexEntry> { |
| 155 | self.entries.values() |
| 156 | } |
| 157 | |
| 158 | pub fn len(&self) -> usize { |
| 159 | self.entries.len() |
| 160 | } |
| 161 | |
| 162 | pub fn is_empty(&self) -> bool { |
| 163 | self.entries.is_empty() |
| 164 | } |
| 165 | |
| 166 | /// Index lookup only, no I/O. |
| 167 | pub fn get(&self, key: &ExpertKey) -> Option<IndexEntry> { |
| 168 | self.entries.get(key).copied() |
| 169 | } |
| 170 | |
| 171 | /// Writes one artifact durably and stages its index entry (persisted by |
| 172 | /// [`ExpertStore::commit`]). Putting the same key with the same content is |
| 173 | /// idempotent; the same key with other content is |
| 174 | /// [`StoreError::DuplicateKey`]. |
| 175 | pub fn put( |
| 176 | &mut self, |
| 177 | key: ExpertKey, |
| 178 | rows: u64, |
| 179 | cols: u64, |
| 180 | scale_dtype: ScaleDtype, |
| 181 | weights: &[u8], |
| 182 | scales: &[u8], |
| 183 | ) -> Result<IndexEntry, StoreError> { |
| 184 | let (hdr, bytes) = build_artifact( |
| 185 | key, |
| 186 | rows, |
| 187 | cols, |
| 188 | scale_dtype, |
| 189 | weights, |
| 190 | scales, |
| 191 | self.limits.max_object_bytes, |
| 192 | )?; |
| 193 | let entry = IndexEntry { |
| 194 | key, |
| 195 | data_digest: sha256(&bytes), |
| 196 | object_len: hdr.object_len, |
| 197 | }; |
| 198 | match self.entries.get(&key) { |
| 199 | Some(old) if old == &entry => {} |
| 200 | Some(_) => return Err(StoreError::DuplicateKey(key)), |
| 201 | None if self.entries.len() >= self.limits.max_entries => { |
| 202 | return Err(StoreError::TooManyEntries) |
| 203 | } |
| 204 | None => {} |
| 205 | } |
| 206 | let name = hex(&entry.data_digest); |
| 207 | let objects = self.objects_dir(); |
| 208 | // An existing object is reused only if it still hashes to its name; |
| 209 | // a damaged one is replaced. |
| 210 | let present = match read_bounded(&objects.join(&name), self.limits.max_object_bytes) { |
| 211 | Ok(existing) => digest_eq(&sha256(&existing), &entry.data_digest), |
| 212 | Err(StoreError::Io(std::io::ErrorKind::NotFound)) |
| 213 | | Err(StoreError::ObjectTooLarge { .. }) => false, |
| 214 | Err(e) => return Err(e), |
| 215 | }; |
| 216 | if !present { |
| 217 | self.write_atomic(&objects, &name, &bytes)?; |
| 218 | } |
| 219 | self.entries.insert(key, entry); |
| 220 | Ok(entry) |
| 221 | } |
| 222 | |
| 223 | /// Atomically replaces the on-disk index with the current entries. |
| 224 | pub fn commit(&self) -> Result<(), StoreError> { |
| 225 | let entries: Vec<IndexEntry> = self.entries.values().copied().collect(); |
| 226 | let bytes = encode_index(&entries)?; |
| 227 | self.write_atomic(&self.root, INDEX_FILE, &bytes) |
| 228 | } |
| 229 | |
| 230 | fn write_atomic(&self, dir: &Path, name: &str, bytes: &[u8]) -> Result<(), StoreError> { |
| 231 | let tmp = self.root.join("tmp").join(format!( |
| 232 | "{name}.{}.{}", |
| 233 | std::process::id(), |
| 234 | TMP_COUNTER.fetch_add(1, Ordering::Relaxed) |
| 235 | )); |
| 236 | let result = (|| { |
| 237 | let mut f = OpenOptions::new() |
| 238 | .write(true) |
| 239 | .create_new(true) |
| 240 | .mode(0o600) |
| 241 | .custom_flags(OPEN_FLAGS) |
| 242 | .open(&tmp)?; |
| 243 | f.write_all(bytes)?; |
| 244 | f.sync_all()?; |
| 245 | drop(f); |
| 246 | std::fs::rename(&tmp, dir.join(name))?; |
| 247 | sync_dir(dir) |
| 248 | })(); |
| 249 | if result.is_err() { |
| 250 | let _ = std::fs::remove_file(&tmp); |
| 251 | } |
| 252 | result |
| 253 | } |
| 254 | } |