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-kv-store / src / index.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 in-memory object index of the host filesystem adapter (ADR 0003 |
| 17 | //! section 4.1, finding 8). |
| 18 | //! |
| 19 | //! One entry per published or recovered object file: 64 bytes of state |
| 20 | //! (`IndexEntry`), capped by `max_objects` (65536 by default, 4 194 304 bytes |
| 21 | //! of entries). The index also keeps the aggregates admission needs in O(1): |
| 22 | //! total physical bytes, bytes marked for removal, and bytes that are busy |
| 23 | //! (pinned or being loaded), so `evictable()` never scans. |
| 24 | //! |
| 25 | //! Pure data structure: no I/O, `no_std` + `alloc`. All locking is the |
| 26 | //! adapter's (the index lives behind its mutex). |
| 27 | |
| 28 | use alloc::collections::BTreeMap; |
| 29 | use alloc::format; |
| 30 | use alloc::string::String; |
| 31 | |
| 32 | /// The object belongs to another namespace: counted toward quota, never |
| 33 | /// served, evicted first. |
| 34 | pub const FLAG_FOREIGN: u32 = 1; |
| 35 | /// Marked for removal: lookups miss, the unlink has not returned yet. |
| 36 | pub const FLAG_EVICTING: u32 = 2; |
| 37 | /// Renamed into place but the directory sync failed (ADR 2.4 P4). |
| 38 | pub const FLAG_INDETERMINATE: u32 = 4; |
| 39 | |
| 40 | /// Bytes of one index entry (ADR 4.1 as amended: 64 bytes per entry, payload length 64-bit). |
| 41 | pub const INDEX_ENTRY_BYTES: usize = 64; |
| 42 | |
| 43 | /// What the index knows about one object file. |
| 44 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 45 | #[repr(C)] |
| 46 | pub struct IndexEntry { |
| 47 | pub key: [u8; 32], |
| 48 | /// `max(st_size, st_blocks * 512)`: includes the 4096-byte header region. |
| 49 | pub phys_bytes: u64, |
| 50 | /// Nanoseconds since the Unix epoch: file mtime at recovery or publish |
| 51 | /// time, raised to the load time by a successful load (in memory only). |
| 52 | pub mtime_ns: u64, |
| 53 | /// Payload bytes (`lookup`'s answer), the record header's u64 `payload_len`. |
| 54 | pub payload_len: u64, |
| 55 | pub flags: u32, |
| 56 | } |
| 57 | |
| 58 | impl IndexEntry { |
| 59 | pub fn is_foreign(&self) -> bool { |
| 60 | self.flags & FLAG_FOREIGN != 0 |
| 61 | } |
| 62 | |
| 63 | pub fn is_evicting(&self) -> bool { |
| 64 | self.flags & FLAG_EVICTING != 0 |
| 65 | } |
| 66 | |
| 67 | pub fn is_indeterminate(&self) -> bool { |
| 68 | self.flags & FLAG_INDETERMINATE != 0 |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// An entry without its key (the map holds the key). |
| 73 | #[derive(Debug, Clone, Copy)] |
| 74 | struct Body { |
| 75 | phys_bytes: u64, |
| 76 | mtime_ns: u64, |
| 77 | payload_len: u64, |
| 78 | flags: u32, |
| 79 | } |
| 80 | |
| 81 | impl Body { |
| 82 | fn entry(&self, key: [u8; 32]) -> IndexEntry { |
| 83 | IndexEntry { |
| 84 | key, |
| 85 | phys_bytes: self.phys_bytes, |
| 86 | mtime_ns: self.mtime_ns, |
| 87 | payload_len: self.payload_len, |
| 88 | flags: self.flags, |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /// Keyed object index with O(1) admission aggregates. |
| 94 | #[derive(Debug, Default)] |
| 95 | pub struct Index { |
| 96 | map: BTreeMap<[u8; 32], Body>, |
| 97 | total_bytes: u64, |
| 98 | evicting_bytes: u64, |
| 99 | evicting_count: u64, |
| 100 | /// Pin and in-flight-load reference counts, by key. |
| 101 | busy: BTreeMap<[u8; 32], u32>, |
| 102 | /// Bytes and count of non-evicting entries with a busy count above zero. |
| 103 | busy_bytes: u64, |
| 104 | busy_count: u64, |
| 105 | } |
| 106 | |
| 107 | impl Index { |
| 108 | pub fn new() -> Self { |
| 109 | Self::default() |
| 110 | } |
| 111 | |
| 112 | pub fn len(&self) -> usize { |
| 113 | self.map.len() |
| 114 | } |
| 115 | |
| 116 | pub fn is_empty(&self) -> bool { |
| 117 | self.map.is_empty() |
| 118 | } |
| 119 | |
| 120 | pub fn get(&self, key: &[u8; 32]) -> Option<IndexEntry> { |
| 121 | self.map.get(key).map(|b| b.entry(*key)) |
| 122 | } |
| 123 | |
| 124 | pub fn contains(&self, key: &[u8; 32]) -> bool { |
| 125 | self.map.contains_key(key) |
| 126 | } |
| 127 | |
| 128 | /// Sum of `phys_bytes` over every entry, including those being removed. |
| 129 | pub fn total_bytes(&self) -> u64 { |
| 130 | self.total_bytes |
| 131 | } |
| 132 | |
| 133 | /// (bytes, count) of entries marked for removal whose unlink has not returned. |
| 134 | pub fn evicting(&self) -> (u64, u64) { |
| 135 | (self.evicting_bytes, self.evicting_count) |
| 136 | } |
| 137 | |
| 138 | /// (bytes, count) of entries eviction could reclaim now: not marked, not |
| 139 | /// pinned, not being loaded. |
| 140 | pub fn evictable(&self) -> (u64, u64) { |
| 141 | ( |
| 142 | self.total_bytes - self.evicting_bytes - self.busy_bytes, |
| 143 | self.map.len() as u64 - self.evicting_count - self.busy_count, |
| 144 | ) |
| 145 | } |
| 146 | |
| 147 | pub fn is_busy(&self, key: &[u8; 32]) -> bool { |
| 148 | self.busy.get(key).copied().unwrap_or(0) > 0 |
| 149 | } |
| 150 | |
| 151 | /// Insert or replace. Returns the entry it replaced. |
| 152 | pub fn insert(&mut self, e: IndexEntry) -> Option<IndexEntry> { |
| 153 | let old = self.remove(&e.key); |
| 154 | self.total_bytes += e.phys_bytes; |
| 155 | if e.is_evicting() { |
| 156 | self.evicting_bytes += e.phys_bytes; |
| 157 | self.evicting_count += 1; |
| 158 | } else if self.is_busy(&e.key) { |
| 159 | self.busy_bytes += e.phys_bytes; |
| 160 | self.busy_count += 1; |
| 161 | } |
| 162 | self.map.insert( |
| 163 | e.key, |
| 164 | Body { |
| 165 | phys_bytes: e.phys_bytes, |
| 166 | mtime_ns: e.mtime_ns, |
| 167 | payload_len: e.payload_len, |
| 168 | flags: e.flags, |
| 169 | }, |
| 170 | ); |
| 171 | old |
| 172 | } |
| 173 | |
| 174 | /// Remove an entry. Busy reference counts for the key are kept: the |
| 175 | /// pins and loads that hold them release them later. |
| 176 | pub fn remove(&mut self, key: &[u8; 32]) -> Option<IndexEntry> { |
| 177 | let b = self.map.remove(key)?; |
| 178 | self.total_bytes -= b.phys_bytes; |
| 179 | if b.flags & FLAG_EVICTING != 0 { |
| 180 | self.evicting_bytes -= b.phys_bytes; |
| 181 | self.evicting_count -= 1; |
| 182 | } else if self.is_busy(key) { |
| 183 | self.busy_bytes -= b.phys_bytes; |
| 184 | self.busy_count -= 1; |
| 185 | } |
| 186 | Some(b.entry(*key)) |
| 187 | } |
| 188 | |
| 189 | /// Mark for removal. Refused (false) for an absent, already marked or busy entry. |
| 190 | pub fn mark_evicting(&mut self, key: &[u8; 32]) -> bool { |
| 191 | if self.is_busy(key) { |
| 192 | return false; |
| 193 | } |
| 194 | match self.map.get_mut(key) { |
| 195 | Some(b) if b.flags & FLAG_EVICTING == 0 => { |
| 196 | b.flags |= FLAG_EVICTING; |
| 197 | self.evicting_bytes += b.phys_bytes; |
| 198 | self.evicting_count += 1; |
| 199 | true |
| 200 | } |
| 201 | _ => false, |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /// Return a marked entry to service (the unlink failed). |
| 206 | pub fn clear_evicting(&mut self, key: &[u8; 32]) { |
| 207 | let busy = self.is_busy(key); |
| 208 | if let Some(b) = self.map.get_mut(key) { |
| 209 | if b.flags & FLAG_EVICTING != 0 { |
| 210 | b.flags &= !FLAG_EVICTING; |
| 211 | self.evicting_bytes -= b.phys_bytes; |
| 212 | self.evicting_count -= 1; |
| 213 | if busy { |
| 214 | self.busy_bytes += b.phys_bytes; |
| 215 | self.busy_count += 1; |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /// Take one busy reference. False (nothing taken) for an absent or marked entry. |
| 222 | pub fn busy_inc(&mut self, key: &[u8; 32]) -> bool { |
| 223 | let Some(b) = self.map.get(key) else { |
| 224 | return false; |
| 225 | }; |
| 226 | if b.flags & FLAG_EVICTING != 0 { |
| 227 | return false; |
| 228 | } |
| 229 | let c = self.busy.entry(*key).or_insert(0); |
| 230 | *c += 1; |
| 231 | if *c == 1 { |
| 232 | self.busy_bytes += b.phys_bytes; |
| 233 | self.busy_count += 1; |
| 234 | } |
| 235 | true |
| 236 | } |
| 237 | |
| 238 | /// Release one busy reference (no-op when there is none). |
| 239 | pub fn busy_dec(&mut self, key: &[u8; 32]) { |
| 240 | let Some(c) = self.busy.get_mut(key) else { |
| 241 | return; |
| 242 | }; |
| 243 | *c -= 1; |
| 244 | if *c > 0 { |
| 245 | return; |
| 246 | } |
| 247 | self.busy.remove(key); |
| 248 | if let Some(b) = self.map.get(key) { |
| 249 | if b.flags & FLAG_EVICTING == 0 { |
| 250 | self.busy_bytes -= b.phys_bytes; |
| 251 | self.busy_count -= 1; |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | /// Raise the entry's recency to `mtime_ns` (a successful load). |
| 257 | pub fn touch(&mut self, key: &[u8; 32], mtime_ns: u64) { |
| 258 | if let Some(b) = self.map.get_mut(key) { |
| 259 | b.mtime_ns = b.mtime_ns.max(mtime_ns); |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | /// Set the indeterminate flag (P4 failed) or clear it. |
| 264 | pub fn set_indeterminate(&mut self, key: &[u8; 32], on: bool) { |
| 265 | if let Some(b) = self.map.get_mut(key) { |
| 266 | if on { |
| 267 | b.flags |= FLAG_INDETERMINATE; |
| 268 | } else { |
| 269 | b.flags &= !FLAG_INDETERMINATE; |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /// ADR 4.1 step 6: foreign namespaces first, then least recently used |
| 275 | /// (smallest `mtime_ns`, then key); never a busy or marked entry. O(n), |
| 276 | /// called only on the worker. |
| 277 | pub fn pick_victim(&self) -> Option<[u8; 32]> { |
| 278 | self.map |
| 279 | .iter() |
| 280 | .filter(|(k, b)| b.flags & FLAG_EVICTING == 0 && !self.is_busy(k)) |
| 281 | .min_by_key(|(k, b)| (b.flags & FLAG_FOREIGN == 0, b.mtime_ns, **k)) |
| 282 | .map(|(k, _)| *k) |
| 283 | } |
| 284 | |
| 285 | /// Recompute every aggregate from scratch and compare. For tests and |
| 286 | /// debug assertions. |
| 287 | pub fn audit(&self) -> Result<(), String> { |
| 288 | let mut total = 0u64; |
| 289 | let (mut eb, mut ec, mut bb, mut bc) = (0u64, 0u64, 0u64, 0u64); |
| 290 | for (k, b) in &self.map { |
| 291 | total += b.phys_bytes; |
| 292 | if b.flags & FLAG_EVICTING != 0 { |
| 293 | eb += b.phys_bytes; |
| 294 | ec += 1; |
| 295 | } else if self.is_busy(k) { |
| 296 | bb += b.phys_bytes; |
| 297 | bc += 1; |
| 298 | } |
| 299 | } |
| 300 | let got = ( |
| 301 | self.total_bytes, |
| 302 | self.evicting_bytes, |
| 303 | self.evicting_count, |
| 304 | self.busy_bytes, |
| 305 | self.busy_count, |
| 306 | ); |
| 307 | if got != (total, eb, ec, bb, bc) { |
| 308 | return Err(format!( |
| 309 | "index aggregates {got:?} differ from recomputed {:?}", |
| 310 | (total, eb, ec, bb, bc) |
| 311 | )); |
| 312 | } |
| 313 | Ok(()) |
| 314 | } |
| 315 | } |