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 / tests / common / rig.rs

260 lines · 7952 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//! Shared fixtures for the fake-adapter and (later) worker tests: a tiny
17//! geometry whose objects cost `OBJ` bytes of quota, leaked "pool" memory with
18//! pinned views over it, and a rig that wires them to a `FakeKvStore`.
19#![allow(dead_code)]
20
21use aien_kv_store::fake::{DiskEntry, FakeConfig, FakeKvStore, JobScript};
22use aien_kv_store::{
23 chunk_chain, BackendFormat, ChunkHeader, ChunkKey, Completion, HolderGuard, HolderHandle,
24 Incarnation, JobId, KvDtype, KvStore, LayoutStrides, NamespaceFields, NamespaceId, PinnedDest,
25 PinnedSource,
26};
27use aien_platform::PlatformError;
28use std::sync::atomic::{AtomicU64, Ordering};
29use std::sync::Arc;
30
31/// Bytes of one pool block in the tiny geometry.
32pub const BLOCK: usize = 64;
33/// Payload of a full chunk: 2 blocks.
34pub const PAYLOAD: u64 = 2 * BLOCK as u64;
35/// Quota cost of one full-chunk object: payload plus the 4096-byte header region.
36pub const OBJ: u64 = PAYLOAD + 4096;
37
38/// 4-token blocks of 64 bytes, 8-token chunks (2 blocks per full chunk).
39pub fn tiny() -> NamespaceFields<'static> {
40 let mut f = super::sample();
41 f.block_size = 4;
42 f.chunk_tokens = 8;
43 f.layout = LayoutStrides {
44 head_stride: 2,
45 token_stride: 4,
46 kv_plane_stride: 16,
47 layer_stride: 32,
48 block_stride: BLOCK as u64,
49 element_bytes: 2,
50 };
51 f.dtype = KvDtype::Bf16;
52 f.backend_format = BackendFormat::HostPagedPoolV1;
53 f
54}
55
56/// Leaked memory standing in for the KV pool (it must outlive any raw pointer
57/// handed to a pinned view; tests are short, the leak is fine).
58#[derive(Clone, Copy)]
59pub struct Mem {
60 ptr: *mut u8,
61 pub blocks: usize,
62}
63
64unsafe impl Send for Mem {}
65unsafe impl Sync for Mem {}
66
67impl Mem {
68 pub fn new(blocks: usize, fill: u8) -> Mem {
69 let b: Box<[u8]> = vec![fill; blocks * BLOCK].into_boxed_slice();
70 Mem {
71 ptr: Box::leak(b).as_mut_ptr(),
72 blocks,
73 }
74 }
75
76 pub fn fill_with(&self, f: impl Fn(usize) -> u8) {
77 for i in 0..self.blocks * BLOCK {
78 unsafe { *self.ptr.add(i) = f(i) };
79 }
80 }
81
82 pub fn fill(&self, v: u8) {
83 self.fill_with(|_| v);
84 }
85
86 pub fn bytes(&self) -> Vec<u8> {
87 (0..self.blocks * BLOCK)
88 .map(|i| unsafe { *self.ptr.add(i) })
89 .collect()
90 }
91
92 /// A read-only view of blocks `0..n` with a detached holder. The handle
93 /// stands for the owner: `revoke()` is "the owner freed the blocks".
94 pub fn source(&self, n: usize, tail_valid_tokens: u32) -> (PinnedSource, HolderHandle) {
95 self.source_with(n, tail_valid_tokens, HolderGuard::detached())
96 }
97
98 pub fn source_with(
99 &self,
100 n: usize,
101 tail_valid_tokens: u32,
102 guard: HolderGuard,
103 ) -> (PinnedSource, HolderHandle) {
104 let h = guard.handle();
105 let s = unsafe {
106 PinnedSource::new(
107 self.ptr as *const u8,
108 BLOCK,
109 (0..n).collect(),
110 tail_valid_tokens,
111 guard,
112 )
113 };
114 (s, h)
115 }
116
117 pub fn dest(&self, n: usize) -> (PinnedDest, HolderHandle) {
118 self.dest_with(n, HolderGuard::detached())
119 }
120
121 pub fn dest_with(&self, n: usize, guard: HolderGuard) -> (PinnedDest, HolderHandle) {
122 let h = guard.handle();
123 let d = unsafe { PinnedDest::new(self.ptr, BLOCK, (0..n).collect(), guard) };
124 (d, h)
125 }
126}
127
128/// Deterministic payload bytes for object number `n`.
129pub fn pattern(n: u8, len: usize) -> Vec<u8> {
130 (0..len)
131 .map(|i| n.wrapping_mul(31).wrapping_add(i as u8))
132 .collect()
133}
134
135pub struct Rig {
136 pub fake: FakeKvStore,
137 pub fields: NamespaceFields<'static>,
138 pub ns: NamespaceId,
139}
140
141pub fn rig() -> Rig {
142 rig_with(|_| {})
143}
144
145pub fn rig_with(f: impl FnOnce(&mut FakeConfig)) -> Rig {
146 let fields = tiny();
147 let ns = fields.namespace_id().unwrap();
148 let mut cfg = FakeConfig::new(ns);
149 f(&mut cfg);
150 Rig {
151 fake: FakeKvStore::new(cfg),
152 fields,
153 ns,
154 }
155}
156
157impl Rig {
158 /// Key and header of the first (full, 8-token) chunk of a token stream
159 /// seeded by `n`; distinct `n` give distinct keys.
160 pub fn chunk(&self, n: u32) -> (ChunkKey, ChunkHeader) {
161 self.chunk_of(n, 8)
162 }
163
164 /// Same with `token_count` tokens (a partial chunk when below 8).
165 pub fn chunk_of(&self, n: u32, token_count: u32) -> (ChunkKey, ChunkHeader) {
166 let tokens: Vec<u32> = (0..token_count).map(|i| n * 1000 + i).collect();
167 let key = chunk_chain(&self.ns, 8, &tokens).unwrap()[0];
168 let h = self
169 .fields
170 .chunk_header(&self.ns, key, None, 0, token_count, 1)
171 .unwrap();
172 (key, h)
173 }
174
175 /// Put object `n` in place without a job.
176 pub fn inject(&self, n: u32) -> ChunkKey {
177 let (k, h) = self.chunk(n);
178 self.fake
179 .inject_object(h, pattern(n as u8, PAYLOAD as usize), BLOCK);
180 k
181 }
182
183 /// Submit a store of object `n` from fresh memory; returns the holder handle.
184 pub fn store(&self, n: u32) -> Result<JobId, PlatformError> {
185 self.store_h(n).0
186 }
187
188 pub fn store_h(&self, n: u32) -> (Result<JobId, PlatformError>, HolderHandle, Mem) {
189 let (_, h) = self.chunk(n);
190 let mem = Mem::new(2, 0);
191 mem.fill_with(|i| pattern(n as u8, PAYLOAD as usize)[i]);
192 let (src, handle) = mem.source(2, 4);
193 (
194 self.fake.submit_store(h, src, Incarnation::seq(n as u64)),
195 handle,
196 mem,
197 )
198 }
199
200 /// Submit a load of object `n` into fresh poisoned memory.
201 pub fn load(&self, n: u32) -> (Result<JobId, PlatformError>, Mem, HolderHandle) {
202 let (k, h) = self.chunk(n);
203 let mem = Mem::new(2, 0xEE);
204 let (dst, handle) = mem.dest(2);
205 (
206 self.fake
207 .submit_load(k, &h, dst, Incarnation::seq(1000 + n as u64)),
208 mem,
209 handle,
210 )
211 }
212
213 pub fn script(&self, s: JobScript) {
214 self.fake.script(s);
215 }
216
217 pub fn poll_all(&self) -> Vec<Completion> {
218 let mut out = Vec::new();
219 loop {
220 let v = self.fake.poll(7);
221 if v.is_empty() {
222 return out;
223 }
224 out.extend(v);
225 }
226 }
227
228 /// Run the clock to idle and return every completion.
229 pub fn settle(&self) -> Vec<Completion> {
230 self.fake.run_until_idle();
231 self.poll_all()
232 }
233}
234
235/// A holder guard that counts its release and records whether the store's
236/// lock was free at that moment (it must be, ADR 8).
237pub fn counting_guard(
238 fake: Arc<FakeKvStore>,
239 released: Arc<AtomicU64>,
240 lock_free_at_release: Arc<AtomicU64>,
241) -> HolderGuard {
242 HolderGuard::new(move || {
243 released.fetch_add(1, Ordering::SeqCst);
244 if fake.lock_is_free() {
245 lock_free_at_release.fetch_add(1, Ordering::SeqCst);
246 }
247 })
248}
249
250pub fn disk_object(rig: &Rig, n: u32, ours: bool) -> DiskEntry {
251 let (_, mut h) = rig.chunk(n);
252 if !ours {
253 h.namespace_id = NamespaceId([0x77; 32]);
254 }
255 DiskEntry::Object {
256 header: h,
257 payload: pattern(n as u8, PAYLOAD as usize),
258 segment_bytes: BLOCK,
259 }
260}