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 / coalesce.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 | //! Landing-buffer coalescing table (ADR 0003 section 7.3, review finding 6). |
| 17 | //! |
| 18 | //! Same-key loads coalesce at the **job and landing-buffer level**: one |
| 19 | //! in-flight load per chunk key lands in that chunk's holder, later requests |
| 20 | //! register as waiters on the job. The table is pure bookkeeping (no I/O, no |
| 21 | //! locks); the worker keeps it inside its own critical section. |
| 22 | //! |
| 23 | //! Counting rules (consistent with the deterministic fake, C2): |
| 24 | //! |
| 25 | //! * The request that opened the job is waiter 1, so `max_waiters_per_job` |
| 26 | //! counts it; attaching is refused once `waiters >= max_waiters_per_job`. |
| 27 | //! * `max_waiters_total` bounds the **attached** waiters (waiters beyond the |
| 28 | //! first) over all jobs. |
| 29 | //! * Stores share the table to deduplicate a store of a key that is already |
| 30 | //! in flight: the duplicate is an additional owner of the same job, so one |
| 31 | //! owner cancelling cannot cancel the others' store. |
| 32 | |
| 33 | use crate::identity::ChunkKey; |
| 34 | use crate::store::JobId; |
| 35 | use alloc::collections::BTreeMap; |
| 36 | |
| 37 | /// What kind of work a key is shared for. Loads and stores of one key never |
| 38 | /// share a job. |
| 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 40 | pub enum Share { |
| 41 | Load, |
| 42 | Store, |
| 43 | } |
| 44 | |
| 45 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 46 | pub struct CoalesceLimits { |
| 47 | /// ADR 7.1: default 16 (the settings table lists 8, see the C5 report). |
| 48 | pub max_waiters_per_job: u32, |
| 49 | /// ADR 7.1: default 1024. |
| 50 | pub max_waiters_total: u32, |
| 51 | } |
| 52 | |
| 53 | impl Default for CoalesceLimits { |
| 54 | fn default() -> Self { |
| 55 | Self { |
| 56 | max_waiters_per_job: 16, |
| 57 | max_waiters_total: 1024, |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// Why `attach` refused. |
| 63 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 64 | pub enum AttachRefused { |
| 65 | /// No such job, or every waiter already left (the job is being torn down). |
| 66 | NoSuchJob, |
| 67 | /// The job already has `max_waiters_per_job` waiters. |
| 68 | JobFull, |
| 69 | /// `max_waiters_total` attached waiters exist over all jobs. |
| 70 | TotalFull, |
| 71 | } |
| 72 | |
| 73 | /// What `detach` left behind. |
| 74 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 75 | pub enum Detach { |
| 76 | /// The job is not in the table (a flush, or already closed). |
| 77 | Unknown, |
| 78 | /// Other waiters remain: the shared work must go on. |
| 79 | Remaining(u32), |
| 80 | /// That was the last waiter: nobody wants the job any more. |
| 81 | Last, |
| 82 | } |
| 83 | |
| 84 | #[derive(Debug, Clone, Copy)] |
| 85 | struct Entry { |
| 86 | share: Share, |
| 87 | key: [u8; 32], |
| 88 | waiters: u32, |
| 89 | } |
| 90 | |
| 91 | /// Key to job bookkeeping with per-job and total waiter bounds. |
| 92 | #[derive(Debug, Clone)] |
| 93 | pub struct CoalesceTable { |
| 94 | limits: CoalesceLimits, |
| 95 | by_key: BTreeMap<(Share, [u8; 32]), JobId>, |
| 96 | jobs: BTreeMap<JobId, Entry>, |
| 97 | attached_total: u32, |
| 98 | } |
| 99 | |
| 100 | impl CoalesceTable { |
| 101 | pub fn new(limits: CoalesceLimits) -> Self { |
| 102 | Self { |
| 103 | limits, |
| 104 | by_key: BTreeMap::new(), |
| 105 | jobs: BTreeMap::new(), |
| 106 | attached_total: 0, |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | pub fn limits(&self) -> CoalesceLimits { |
| 111 | self.limits |
| 112 | } |
| 113 | |
| 114 | /// Register `job` as the owner of `(share, key)` with its opener as waiter 1. |
| 115 | /// If another job with waiters already owns the key, that job stays the |
| 116 | /// coalescing target; `job` is still tracked for `attach`/`detach`/`close`. |
| 117 | pub fn open(&mut self, share: Share, key: &ChunkKey, job: JobId) { |
| 118 | let k = (share, key.0 .0); |
| 119 | let taken = self |
| 120 | .by_key |
| 121 | .get(&k) |
| 122 | .and_then(|j| self.jobs.get(j)) |
| 123 | .is_some_and(|e| e.waiters > 0); |
| 124 | if !taken { |
| 125 | self.by_key.insert(k, job); |
| 126 | } |
| 127 | self.jobs.insert( |
| 128 | job, |
| 129 | Entry { |
| 130 | share, |
| 131 | key: k.1, |
| 132 | waiters: 1, |
| 133 | }, |
| 134 | ); |
| 135 | } |
| 136 | |
| 137 | /// The job a new request for `(share, key)` may join: it exists and still |
| 138 | /// has at least one waiter. |
| 139 | pub fn find(&self, share: Share, key: &ChunkKey) -> Option<JobId> { |
| 140 | let job = *self.by_key.get(&(share, key.0 .0))?; |
| 141 | (self.jobs.get(&job)?.waiters > 0).then_some(job) |
| 142 | } |
| 143 | |
| 144 | /// True while any job (even one whose waiters all left) is registered for the key. |
| 145 | pub fn has(&self, share: Share, key: &ChunkKey) -> bool { |
| 146 | self.by_key.contains_key(&(share, key.0 .0)) |
| 147 | } |
| 148 | |
| 149 | /// Add one waiter; returns the waiter count now. Bounded. |
| 150 | pub fn attach(&mut self, job: JobId) -> Result<u32, AttachRefused> { |
| 151 | let max_job = self.limits.max_waiters_per_job; |
| 152 | let max_total = self.limits.max_waiters_total; |
| 153 | let attached = self.attached_total; |
| 154 | let e = match self.jobs.get_mut(&job) { |
| 155 | Some(e) if e.waiters > 0 => e, |
| 156 | _ => return Err(AttachRefused::NoSuchJob), |
| 157 | }; |
| 158 | if e.waiters >= max_job { |
| 159 | return Err(AttachRefused::JobFull); |
| 160 | } |
| 161 | if attached >= max_total { |
| 162 | return Err(AttachRefused::TotalFull); |
| 163 | } |
| 164 | e.waiters += 1; |
| 165 | self.attached_total += 1; |
| 166 | Ok(e.waiters) |
| 167 | } |
| 168 | |
| 169 | /// Remove one waiter (the caller cancelled its own interest). |
| 170 | pub fn detach(&mut self, job: JobId) -> Detach { |
| 171 | let Some(e) = self.jobs.get_mut(&job) else { |
| 172 | return Detach::Unknown; |
| 173 | }; |
| 174 | match e.waiters { |
| 175 | 0 | 1 => { |
| 176 | e.waiters = 0; |
| 177 | Detach::Last |
| 178 | } |
| 179 | n => { |
| 180 | e.waiters = n - 1; |
| 181 | self.attached_total -= 1; |
| 182 | Detach::Remaining(n - 1) |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// The job reached its terminal completion: forget it and release its |
| 188 | /// attached waiters from the total. |
| 189 | pub fn close(&mut self, job: JobId) { |
| 190 | let Some(e) = self.jobs.remove(&job) else { |
| 191 | return; |
| 192 | }; |
| 193 | self.attached_total -= e.waiters.saturating_sub(1); |
| 194 | let k = (e.share, e.key); |
| 195 | if self.by_key.get(&k) == Some(&job) { |
| 196 | self.by_key.remove(&k); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | pub fn waiters(&self, job: JobId) -> u32 { |
| 201 | self.jobs.get(&job).map_or(0, |e| e.waiters) |
| 202 | } |
| 203 | |
| 204 | /// Attached waiters (beyond each job's first) over all jobs. |
| 205 | pub fn attached_total(&self) -> u32 { |
| 206 | self.attached_total |
| 207 | } |
| 208 | |
| 209 | /// Jobs currently tracked. |
| 210 | pub fn jobs(&self) -> usize { |
| 211 | self.jobs.len() |
| 212 | } |
| 213 | } |