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 / pin.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 | //! Pinned views of pool blocks handed to a store job (ADR 0003 section 3.2). |
| 17 | //! |
| 18 | //! A `PinnedSource` / `PinnedDest` names blocks of one pool allocation and |
| 19 | //! carries a `HolderGuard`: the storage reference (a holder block table, |
| 20 | //! ADR section 5.2) that keeps those blocks alive. The store reads or writes |
| 21 | //! blocks only through the checked accessors below, which refuse once the |
| 22 | //! holder has been released, so a use-after-release becomes a failed job |
| 23 | //! (`PlatformError::InvalidLayout`) instead of a stray memory access. |
| 24 | |
| 25 | use aien_platform::PlatformError; |
| 26 | use alloc::boxed::Box; |
| 27 | use alloc::sync::Arc; |
| 28 | use alloc::vec::Vec; |
| 29 | use core::sync::atomic::{AtomicBool, Ordering}; |
| 30 | |
| 31 | /// Keeps a holder alive. Dropping it runs the release callback exactly once |
| 32 | /// (in the runtime: `free_sequence(holder)`, ADR critical section S4). |
| 33 | pub struct HolderGuard { |
| 34 | held: Arc<AtomicBool>, |
| 35 | /// Set on a lease: the guard it was lent from. A lease reports held only |
| 36 | /// while that guard is held too, so a revoke of the owner reaches the |
| 37 | /// borrower. |
| 38 | parent: Option<Arc<AtomicBool>>, |
| 39 | release: Option<Box<dyn FnOnce() + Send>>, |
| 40 | } |
| 41 | |
| 42 | /// A cloneable view of a guard's liveness, for the owner and for tests. |
| 43 | #[derive(Clone)] |
| 44 | pub struct HolderHandle { |
| 45 | held: Arc<AtomicBool>, |
| 46 | parent: Option<Arc<AtomicBool>>, |
| 47 | } |
| 48 | |
| 49 | impl HolderGuard { |
| 50 | pub fn new(release: impl FnOnce() + Send + 'static) -> Self { |
| 51 | Self { |
| 52 | held: Arc::new(AtomicBool::new(true)), |
| 53 | parent: None, |
| 54 | release: Some(Box::new(release)), |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// A guard with nothing to release (tests, and sources the caller owns outright). |
| 59 | pub fn detached() -> Self { |
| 60 | Self { |
| 61 | held: Arc::new(AtomicBool::new(true)), |
| 62 | parent: None, |
| 63 | release: None, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// A lease on the same blocks for a borrower (the storage worker lends |
| 68 | /// the caller's blocks to the inner store this way). Dropping the lease |
| 69 | /// runs `on_return`, never this guard's release: the owner keeps the |
| 70 | /// holder until it decides. The lease is held only while both it and this |
| 71 | /// guard are held. |
| 72 | pub fn lease(&self, on_return: impl FnOnce() + Send + 'static) -> HolderGuard { |
| 73 | HolderGuard { |
| 74 | held: Arc::new(AtomicBool::new(true)), |
| 75 | parent: Some(Arc::clone(&self.held)), |
| 76 | release: Some(Box::new(on_return)), |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | pub fn handle(&self) -> HolderHandle { |
| 81 | HolderHandle { |
| 82 | held: Arc::clone(&self.held), |
| 83 | parent: self.parent.clone(), |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | // SAFETY: `release` is touched only through `&mut self` (in `drop`); every |
| 89 | // `&self` method reads the atomics behind `Arc`s. Sharing `&HolderGuard` |
| 90 | // across threads therefore exposes nothing that is not already `Sync`. |
| 91 | unsafe impl Sync for HolderGuard {} |
| 92 | |
| 93 | impl Drop for HolderGuard { |
| 94 | fn drop(&mut self) { |
| 95 | self.held.store(false, Ordering::SeqCst); |
| 96 | if let Some(release) = self.release.take() { |
| 97 | release(); |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | impl HolderHandle { |
| 103 | pub fn is_held(&self) -> bool { |
| 104 | self.held.load(Ordering::SeqCst) |
| 105 | && self |
| 106 | .parent |
| 107 | .as_ref() |
| 108 | .is_none_or(|p| p.load(Ordering::SeqCst)) |
| 109 | } |
| 110 | |
| 111 | /// Mark the holder as released out of band, the bug case of ADR 3.2: the |
| 112 | /// owner freed the blocks while a job still referenced them. Every later |
| 113 | /// block access through the pinned view fails. |
| 114 | pub fn revoke(&self) { |
| 115 | self.held.store(false, Ordering::SeqCst); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | fn block_range( |
| 120 | blocks: &[usize], |
| 121 | block_bytes: usize, |
| 122 | i: usize, |
| 123 | ) -> Result<(usize, usize), PlatformError> { |
| 124 | let block = *blocks.get(i).ok_or(PlatformError::InvalidLayout)?; |
| 125 | let start = block |
| 126 | .checked_mul(block_bytes) |
| 127 | .ok_or(PlatformError::InvalidLayout)?; |
| 128 | Ok((start, block_bytes)) |
| 129 | } |
| 130 | |
| 131 | /// Read-only view of pinned pool blocks (store jobs). |
| 132 | pub struct PinnedSource { |
| 133 | base: *const u8, |
| 134 | block_bytes: usize, |
| 135 | blocks: Vec<usize>, |
| 136 | tail_valid_tokens: u32, |
| 137 | guard: HolderGuard, |
| 138 | } |
| 139 | |
| 140 | // SAFETY: the constructor's contract makes the memory behind `base` valid and |
| 141 | // immutable for as long as the guard is held, from any thread. |
| 142 | unsafe impl Send for PinnedSource {} |
| 143 | |
| 144 | impl PinnedSource { |
| 145 | /// `tail_valid_tokens` is the number of token rows of the last block that |
| 146 | /// hold real positions; the writer zeroes the rows at or above it in the |
| 147 | /// stored object (ADR 2.2, 13 T11). Use the block size for a full block. |
| 148 | /// |
| 149 | /// # Safety |
| 150 | /// For every `b` in `blocks`, `base + b * block_bytes .. + block_bytes` |
| 151 | /// must be readable memory that is not written by anyone while `guard` |
| 152 | /// (or the handle derived from it) reports held. |
| 153 | pub unsafe fn new( |
| 154 | base: *const u8, |
| 155 | block_bytes: usize, |
| 156 | blocks: Vec<usize>, |
| 157 | tail_valid_tokens: u32, |
| 158 | guard: HolderGuard, |
| 159 | ) -> Self { |
| 160 | Self { |
| 161 | base, |
| 162 | block_bytes, |
| 163 | blocks, |
| 164 | tail_valid_tokens, |
| 165 | guard, |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /// Token rows of the last block that are real (ADR 13 T11). |
| 170 | pub fn tail_valid_tokens(&self) -> u32 { |
| 171 | self.tail_valid_tokens |
| 172 | } |
| 173 | |
| 174 | pub fn block_bytes(&self) -> usize { |
| 175 | self.block_bytes |
| 176 | } |
| 177 | |
| 178 | pub fn block_count(&self) -> usize { |
| 179 | self.blocks.len() |
| 180 | } |
| 181 | |
| 182 | pub fn blocks(&self) -> &[usize] { |
| 183 | &self.blocks |
| 184 | } |
| 185 | |
| 186 | /// Total bytes, or `None` on overflow. |
| 187 | pub fn total_bytes(&self) -> Option<u64> { |
| 188 | (self.blocks.len() as u64).checked_mul(self.block_bytes as u64) |
| 189 | } |
| 190 | |
| 191 | pub fn handle(&self) -> HolderHandle { |
| 192 | self.guard.handle() |
| 193 | } |
| 194 | |
| 195 | /// The `i`-th block's bytes; refused after the holder was released. |
| 196 | pub fn block(&self, i: usize) -> Result<&[u8], PlatformError> { |
| 197 | if !self.guard.handle().is_held() { |
| 198 | return Err(PlatformError::InvalidLayout); |
| 199 | } |
| 200 | let (start, len) = block_range(&self.blocks, self.block_bytes, i)?; |
| 201 | // SAFETY: `new`'s contract covers this range while the holder is held, |
| 202 | // which was checked just above. |
| 203 | Ok(unsafe { core::slice::from_raw_parts(self.base.add(start), len) }) |
| 204 | } |
| 205 | |
| 206 | /// Give up the view and keep only the guard (the store drops it outside its lock). |
| 207 | pub fn into_guard(self) -> HolderGuard { |
| 208 | self.guard |
| 209 | } |
| 210 | |
| 211 | /// Lend the view: the returned view carries a lease (see |
| 212 | /// [`HolderGuard::lease`]) and the owner keeps the real guard. |
| 213 | pub fn lend(mut self, on_return: impl FnOnce() + Send + 'static) -> (Self, HolderGuard) { |
| 214 | let lease = self.guard.lease(on_return); |
| 215 | let real = core::mem::replace(&mut self.guard, lease); |
| 216 | (self, real) |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /// Writable view of pinned pool blocks (load jobs). |
| 221 | pub struct PinnedDest { |
| 222 | base: *mut u8, |
| 223 | block_bytes: usize, |
| 224 | blocks: Vec<usize>, |
| 225 | guard: HolderGuard, |
| 226 | } |
| 227 | |
| 228 | // SAFETY: as for `PinnedSource`; additionally the holder gives the job |
| 229 | // exclusive write access to these blocks until it is released. |
| 230 | unsafe impl Send for PinnedDest {} |
| 231 | |
| 232 | impl PinnedDest { |
| 233 | /// # Safety |
| 234 | /// For every `b` in `blocks`, `base + b * block_bytes .. + block_bytes` |
| 235 | /// must be writable memory that nobody else reads or writes while `guard` |
| 236 | /// (or the handle derived from it) reports held. |
| 237 | pub unsafe fn new( |
| 238 | base: *mut u8, |
| 239 | block_bytes: usize, |
| 240 | blocks: Vec<usize>, |
| 241 | guard: HolderGuard, |
| 242 | ) -> Self { |
| 243 | Self { |
| 244 | base, |
| 245 | block_bytes, |
| 246 | blocks, |
| 247 | guard, |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | pub fn block_bytes(&self) -> usize { |
| 252 | self.block_bytes |
| 253 | } |
| 254 | |
| 255 | pub fn block_count(&self) -> usize { |
| 256 | self.blocks.len() |
| 257 | } |
| 258 | |
| 259 | pub fn blocks(&self) -> &[usize] { |
| 260 | &self.blocks |
| 261 | } |
| 262 | |
| 263 | pub fn total_bytes(&self) -> Option<u64> { |
| 264 | (self.blocks.len() as u64).checked_mul(self.block_bytes as u64) |
| 265 | } |
| 266 | |
| 267 | pub fn handle(&self) -> HolderHandle { |
| 268 | self.guard.handle() |
| 269 | } |
| 270 | |
| 271 | /// Copy `data` (exactly `block_bytes` long) into the `i`-th block; refused |
| 272 | /// after the holder was released. |
| 273 | pub fn write_block(&mut self, i: usize, data: &[u8]) -> Result<(), PlatformError> { |
| 274 | if !self.guard.handle().is_held() || data.len() != self.block_bytes { |
| 275 | return Err(PlatformError::InvalidLayout); |
| 276 | } |
| 277 | let (start, len) = block_range(&self.blocks, self.block_bytes, i)?; |
| 278 | // SAFETY: `new`'s contract covers this range while the holder is held, |
| 279 | // which was checked just above; `data` is a distinct borrowed slice. |
| 280 | unsafe { core::ptr::copy_nonoverlapping(data.as_ptr(), self.base.add(start), len) }; |
| 281 | Ok(()) |
| 282 | } |
| 283 | |
| 284 | pub fn into_guard(self) -> HolderGuard { |
| 285 | self.guard |
| 286 | } |
| 287 | |
| 288 | /// Lend the view: the returned view carries a lease (see |
| 289 | /// [`HolderGuard::lease`]) and the owner keeps the real guard. |
| 290 | pub fn lend(mut self, on_return: impl FnOnce() + Send + 'static) -> (Self, HolderGuard) { |
| 291 | let lease = self.guard.lease(on_return); |
| 292 | let real = core::mem::replace(&mut self.guard, lease); |
| 293 | (self, real) |
| 294 | } |
| 295 | } |