interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-kv-store / src / store.rs

306 lines · 12537 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//! The `KvStore` contract (ADR 0003 section 3.2, revised by section 13).
17//!
18//! Binding rules, in one place:
19//!
20//! * `submit_*` is bounded and non-blocking. `submit_store` only **reserves**
21//! (`payload + 4096` bytes of quota); it never evicts and never touches the
22//! filesystem. Reclamation and unlinks run on the worker (section 7.4).
23//! * Every accepted job yields **exactly one terminal completion** (done,
24//! failed or cancelled), including cancelled and failed jobs. A caller that
25//! cancels or abandons a job still polls that terminal completion before it
26//! frees the job's memory (section 5.5).
27//! * Completion capacity is reserved at submit (three slots per job), so
28//! `poll` never overflows and the worker never blocks on a full queue.
29//! * While the store is `Recovering`, `lookup` misses and `submit_*` refuses
30//! with `QueueFull` (section 4.1).
31//! * Rename done but directory sync failed: the object is served, the job ends
32//! with `PublishOutcome::Indeterminate`, the store goes `Degraded`.
33//! * `shutdown` returns at its deadline with a `DrainReport` naming every job
34//! still running; nothing is freed to meet the deadline (section 7.5).
35
36use crate::identity::{ChunkKey, NamespaceId};
37use crate::pin::{HolderGuard, HolderHandle, PinnedDest, PinnedSource};
38use crate::record::ChunkHeader;
39use aien_platform::PlatformError;
40use alloc::sync::Arc;
41use alloc::vec::Vec;
42
43/// Never reused within a store lifetime.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
45pub struct JobId(pub u64);
46
47/// The caller's token, echoed in every completion so stale completions can be
48/// dropped (ADR 5.3). The full tuple `(seq_id, epoch)`: the scheduler's
49/// sequence id already uses all 64 bits (`slot << 32 | generation`,
50/// aien-scheduler/src/sequence.rs `to_u64`), so the residency epoch cannot be
51/// packed beside it. Two tokens name the same request only if both fields
52/// match; a reused sequence id in a later epoch is a different incarnation.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct Incarnation {
55 pub seq_id: u64,
56 pub epoch: u32,
57}
58
59impl Incarnation {
60 pub const fn new(seq_id: u64, epoch: u32) -> Self {
61 Self { seq_id, epoch }
62 }
63
64 /// Epoch 0: for callers that have no residency epoch (flush barriers,
65 /// fixtures).
66 pub const fn seq(seq_id: u64) -> Self {
67 Self { seq_id, epoch: 0 }
68 }
69}
70
71/// Returned by `pin`; hand it back to `unpin`.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
73pub struct PinToken(pub u64);
74
75/// How far a job has got. Ordered: later stages compare greater.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
77pub enum JobStage {
78 /// Accepted; source pinned; counted in the in-flight bounds.
79 Submitted,
80 /// Store: bytes written to the temporary object and synced. Load: every
81 /// segment landed in the destination and verified.
82 Completed,
83 /// Store: visible to `lookup` and to recovery. Not a load stage (a load is
84 /// published by the caller when it commits the table, ADR 3.3).
85 Published,
86 /// Store: persistence is claimed. Flush: the barrier finished.
87 Durable,
88}
89
90/// How a store job ended with respect to durability (ADR 2.4, P4).
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum PublishOutcome {
93 /// Loads, flushes, failed and cancelled jobs, and stores whose durability
94 /// is claimed later by a flush (`OnFlush` adapters).
95 NotApplicable,
96 /// Published and durable at the same instant (host adapter).
97 Durable,
98 /// Published (complete, indexed, served) but its survival across power loss
99 /// is unknown: the directory sync failed after a successful rename.
100 Indeterminate,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum StoreState {
105 /// A full pass over the store has not finished; admission is closed.
106 Recovering,
107 Open,
108 /// An indeterminate publication or a failed file sync: loads are served,
109 /// no new stores until reopen.
110 Degraded,
111 /// Fail-stop: nothing is served until reopen.
112 Failed,
113}
114
115/// Exactly one terminal per accepted job.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub enum Terminal {
118 Done(JobStage),
119 Failed(PlatformError),
120 Cancelled,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Completion {
125 pub job: JobId,
126 pub incarnation: Incarnation,
127 /// The chunk key; all zero for a flush.
128 pub key: ChunkKey,
129 /// The stage this completion reports (for a failed job, the last stage reached).
130 pub stage: JobStage,
131 /// `None`: progress report (a store reached `Completed`). `Some`: the
132 /// job's one terminal completion; nothing follows it.
133 pub terminal: Option<Terminal>,
134 pub publish: PublishOutcome,
135 pub bytes: u64,
136 pub elapsed_us: u64,
137 /// Load terminals from the [`crate::worker::StorageWorker`]: the landing
138 /// holder, handed back so it outlives the terminal the caller sees (Grok
139 /// C5 P1-2). Every waiter of a coalesced load gets a copy; the holder is
140 /// released when the last copy is dropped (after S3 adopted its blocks,
141 /// or on any failure). Raw stores release at the terminal: `None`.
142 pub holder: Option<LandingHolder>,
143}
144
145/// A shared landing holder (see [`Completion::holder`]).
146#[derive(Clone)]
147pub struct LandingHolder(Arc<HolderGuard>);
148
149impl LandingHolder {
150 pub fn new(guard: HolderGuard) -> Self {
151 Self(Arc::new(guard))
152 }
153
154 pub fn handle(&self) -> HolderHandle {
155 self.0.handle()
156 }
157}
158
159impl core::fmt::Debug for LandingHolder {
160 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
161 f.write_str("LandingHolder")
162 }
163}
164
165impl PartialEq for LandingHolder {
166 fn eq(&self, other: &Self) -> bool {
167 Arc::ptr_eq(&self.0, &other.0)
168 }
169}
170
171impl Eq for LandingHolder {}
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct Capacity {
175 pub state: StoreState,
176 pub quota_bytes: u64,
177 /// Physical bytes of every object found or published, any namespace, plus
178 /// `unindexed_bytes` (ADR 4.1).
179 pub used_bytes: u64,
180 /// Submit-time reservations of stores that have not published yet.
181 pub reserved_bytes: u64,
182 /// Bytes of objects marked for removal whose unlink has not returned.
183 pub evicting_bytes: u64,
184 pub unindexed_bytes: u64,
185 pub unindexed_objects: u64,
186 pub objects: u64,
187 pub max_objects: u64,
188 pub restore_ops: u32,
189 pub max_restore_ops: u32,
190 pub park_ops: u32,
191 pub max_park_ops: u32,
192 pub inflight_bytes: u64,
193 pub max_inflight_bytes: u64,
194 pub max_waiters_per_job: u32,
195}
196
197/// Where a resumable recovery pass stands (ADR 4.1).
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
199pub struct RecoveryProgress {
200 /// The walk finished and admission opened (or the store is `Degraded`).
201 pub done: bool,
202 /// The store is `Failed`: recovery stopped and is never `done` (Grok C4 P2-6).
203 pub failed: bool,
204 pub indexed: u64,
205 pub bytes: u64,
206 pub unindexed_objects: u64,
207 pub unindexed_bytes: u64,
208 pub foreign_namespace: u64,
209 pub corrupt_deleted: u64,
210 pub tmp_deleted: u64,
211 pub elapsed_us: u64,
212}
213
214/// `Cancelled`: the job never touched the destination and published nothing.
215/// `TooLate`: it will complete (or already did); ignore by incarnation. Either
216/// way the job yields its one terminal completion.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum CancelOutcome {
219 Cancelled,
220 TooLate,
221}
222
223/// A job `shutdown` could not finish by its deadline (ADR 7.5).
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct UnfinishedJob {
226 pub job: JobId,
227 pub key: ChunkKey,
228 pub bytes: u64,
229 pub stage: JobStage,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Default)]
233pub struct DrainReport {
234 /// Stores that were already past the file sync and finished their publication.
235 pub published: u64,
236 /// Jobs cancelled during the drain.
237 pub cancelled: u64,
238 /// Jobs still running at the deadline. Their buffers stay owned by the
239 /// store until each reaches its terminal completion.
240 pub unfinished: Vec<UnfinishedJob>,
241}
242
243pub trait KvStore: Send + Sync {
244 fn namespace(&self) -> NamespaceId;
245 fn capacity(&self) -> Capacity;
246 /// Index only, no I/O, O(keys). `Some(len)` means a published object of
247 /// `len` payload bytes exists. While `state` is `Recovering` (or `Failed`),
248 /// and for keys marked for removal, every key is a miss.
249 fn lookup(&self, keys: &[ChunkKey]) -> Vec<Option<u64>>;
250 /// Bounded and non-blocking; never evicts and never touches the
251 /// filesystem. Reserves `payload + 4096` bytes of quota. Refuses with
252 /// `QueueFull` when the class's ops, its bytes or the completion slots
253 /// would exceed their limits (and always while `Recovering`),
254 /// `OutOfMemory` when `used + reserved + request` exceeds quota plus the
255 /// bytes that are evictable (unpinned, not in flight, not already
256 /// evicting), `DeviceUnavailable` when `Degraded`, `Failed` or shut down,
257 /// `InvalidLayout` when the header and source disagree. A store of a key
258 /// that is already in flight returns the existing job's id.
259 fn submit_store(
260 &self,
261 header: ChunkHeader,
262 src: PinnedSource,
263 inc: Incarnation,
264 ) -> Result<JobId, PlatformError>;
265 /// Same refusals as `submit_store` (a `Degraded` store still serves loads),
266 /// plus `ObjectNotFound` for a key that is not published and
267 /// `InvalidLayout` when `expect` or `dst` disagrees with the stored object.
268 /// Nothing is written to `dst` before validation passes.
269 fn submit_load(
270 &self,
271 key: ChunkKey,
272 expect: &ChunkHeader,
273 dst: PinnedDest,
274 inc: Incarnation,
275 ) -> Result<JobId, PlatformError>;
276 /// Durability barrier for everything `Published` before the call.
277 fn submit_flush(&self, inc: Incarnation) -> Result<JobId, PlatformError>;
278 /// Coalescing: register one more waiter, named by its own `inc`, on an
279 /// in-flight load; `QueueFull` past `max_waiters_per_job` waiters on the job
280 /// or the total bound. A raw store (fake, host adapter) runs one job and
281 /// yields one terminal carrying the opener's token; the storage worker
282 /// fans that out to one terminal per waiter, each with its own token
283 /// (ADR 5.3), so no completion ever stands for several incarnations.
284 fn attach_waiter(&self, job: JobId, inc: Incarnation) -> Result<(), PlatformError>;
285 /// Non-blocking: drains at most `max` completions, oldest first.
286 fn poll(&self, max: usize) -> Vec<Completion>;
287 /// Returns immediately. The destination or source of the job is safe to
288 /// release only after the job's terminal completion has been polled
289 /// (ADR 5.5).
290 fn cancel(&self, job: JobId) -> CancelOutcome;
291 /// Pins against eviction and deletion while a restore chain is being
292 /// assembled. All-or-nothing; `QueueFull` past `max_restore_ops` live tokens.
293 fn pin(&self, keys: &[ChunkKey]) -> Result<PinToken, PlatformError>;
294 fn unpin(&self, token: PinToken);
295 /// Marks keys for removal (lookups miss at once); skips pinned keys and
296 /// keys with a job in flight; the unlink runs on the worker and the bytes
297 /// are subtracted when it returns. Returns the number of keys marked.
298 fn delete(&self, keys: &[ChunkKey]) -> u64;
299 /// Resumable recovery: call until `done`, each call bounded by `slice_ms`.
300 /// Admission stays closed until `done`.
301 fn recover_step(&self, slice_ms: u64) -> RecoveryProgress;
302 /// Stops intake, cancels what can be cancelled, lets jobs past the file
303 /// sync finish, and returns at `intake_deadline_ms` with the jobs still
304 /// running listed in `unfinished`.
305 fn shutdown(&self, intake_deadline_ms: u64) -> DrainReport;
306}