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 / record.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 256-byte record header, identical on host and native (ADR 0003 section 2.1). |
| 17 | |
| 18 | use crate::error::KvError; |
| 19 | use crate::identity::{ChunkKey, NamespaceId}; |
| 20 | use aien_platform::ObjectId; |
| 21 | use sha2::{Digest, Sha256}; |
| 22 | |
| 23 | pub const MAGIC: [u8; 8] = *b"AIENKVC1"; |
| 24 | pub const HEADER_LEN: usize = 256; |
| 25 | /// A record file is `header region (4096 B) || payload` (ADR 0003 section 2.1, H2). |
| 26 | pub const HEADER_REGION_LEN: usize = 4096; |
| 27 | /// File offset of the first payload byte. |
| 28 | pub const PAYLOAD_OFFSET: usize = 4096; |
| 29 | /// Segment digests that fit between the struct and the seal slot: |
| 30 | /// (4064 - 256) / 32 = 119 (ADR 0003 section 20; 120 before the seal slot). |
| 31 | pub const MAX_SEGMENTS: usize = 119; |
| 32 | /// Region offset of the segment digest table. |
| 33 | pub const SEGMENT_TABLE_OFFSET: usize = HEADER_LEN; |
| 34 | /// Region offset of the 32-byte seal slot of a host object (ADR 0003 section |
| 35 | /// 19): `"AKS"`, sealed format version, 12-byte nonce, 16-byte tag. Zero in |
| 36 | /// a region `encode_region` returns; `seal::SealKey::seal_file` fills it. |
| 37 | pub const SEAL_SLOT_OFFSET: usize = HEADER_REGION_LEN - 32; |
| 38 | pub const FORMAT_VERSION: u16 = 1; |
| 39 | pub const RECORD_KIND_CHUNK: u16 = 1; |
| 40 | /// `flags` bit 0: the chunk holds fewer than `chunk_tokens` positions. |
| 41 | pub const FLAG_PARTIAL_TAIL: u16 = 1; |
| 42 | /// Header bytes covered by `header_sha256`. |
| 43 | pub const HASHED_PREFIX_LEN: usize = 224; |
| 44 | pub(crate) const PAYLOAD_DOMAIN: &[u8] = b"AIEN-PKV-PAYLOAD-V1\0"; |
| 45 | |
| 46 | /// The header fields a caller sets: section 2.1 minus the constants (magic, |
| 47 | /// version, kind, header_len) and minus the two hashes. `payload_sha256` is |
| 48 | /// known only after the payload is read, so it lives in `RecordHeader`. |
| 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 50 | pub struct ChunkHeader { |
| 51 | pub namespace_id: NamespaceId, |
| 52 | pub chunk_key: ChunkKey, |
| 53 | /// All zero for the first chunk. |
| 54 | pub parent_key: [u8; 32], |
| 55 | pub model_sha256: [u8; 32], |
| 56 | pub first_position: u32, |
| 57 | pub token_count: u32, |
| 58 | pub chunk_tokens: u32, |
| 59 | pub block_size: u32, |
| 60 | pub num_layers: u32, |
| 61 | pub num_kv_heads: u32, |
| 62 | pub head_dim: u32, |
| 63 | pub dtype: u8, |
| 64 | pub backend_format: u8, |
| 65 | pub flags: u16, |
| 66 | pub payload_len: u64, |
| 67 | /// Informational, not identity. |
| 68 | pub written_unix_ns: u64, |
| 69 | } |
| 70 | |
| 71 | /// A header plus the payload hash; what sits in the first 256 bytes of a record. |
| 72 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 73 | pub struct RecordHeader { |
| 74 | pub chunk: ChunkHeader, |
| 75 | pub payload_sha256: [u8; 32], |
| 76 | } |
| 77 | |
| 78 | // Byte offsets of ADR 0003 section 2.1. |
| 79 | const O_MAGIC: usize = 0; |
| 80 | const O_VERSION: usize = 8; |
| 81 | const O_KIND: usize = 10; |
| 82 | const O_HEADER_LEN: usize = 12; |
| 83 | const O_NAMESPACE: usize = 16; |
| 84 | const O_KEY: usize = 48; |
| 85 | const O_PARENT: usize = 80; |
| 86 | const O_MODEL: usize = 112; |
| 87 | const O_FIRST_POS: usize = 144; |
| 88 | const O_TOKEN_COUNT: usize = 148; |
| 89 | const O_CHUNK_TOKENS: usize = 152; |
| 90 | const O_BLOCK_SIZE: usize = 156; |
| 91 | const O_LAYERS: usize = 160; |
| 92 | const O_KV_HEADS: usize = 164; |
| 93 | const O_HEAD_DIM: usize = 168; |
| 94 | const O_DTYPE: usize = 172; |
| 95 | const O_BACKEND: usize = 173; |
| 96 | const O_FLAGS: usize = 174; |
| 97 | const O_PAYLOAD_LEN: usize = 176; |
| 98 | const O_PAYLOAD_SHA: usize = 184; |
| 99 | const O_WRITTEN_NS: usize = 216; |
| 100 | const O_HEADER_SHA: usize = 224; |
| 101 | |
| 102 | fn put(buf: &mut [u8; HEADER_LEN], off: usize, bytes: &[u8]) { |
| 103 | buf[off..off + bytes.len()].copy_from_slice(bytes); |
| 104 | } |
| 105 | |
| 106 | fn get32(buf: &[u8], off: usize) -> [u8; 32] { |
| 107 | let mut out = [0u8; 32]; |
| 108 | out.copy_from_slice(&buf[off..off + 32]); |
| 109 | out |
| 110 | } |
| 111 | |
| 112 | fn get_u16(buf: &[u8], off: usize) -> u16 { |
| 113 | u16::from_le_bytes([buf[off], buf[off + 1]]) |
| 114 | } |
| 115 | |
| 116 | fn get_u32(buf: &[u8], off: usize) -> u32 { |
| 117 | u32::from_le_bytes([buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]) |
| 118 | } |
| 119 | |
| 120 | fn get_u64(buf: &[u8], off: usize) -> u64 { |
| 121 | let mut b = [0u8; 8]; |
| 122 | b.copy_from_slice(&buf[off..off + 8]); |
| 123 | u64::from_le_bytes(b) |
| 124 | } |
| 125 | |
| 126 | impl RecordHeader { |
| 127 | /// Serialize to exactly 256 bytes, little-endian, computing `header_sha256`. |
| 128 | pub fn encode(&self) -> [u8; HEADER_LEN] { |
| 129 | let c = &self.chunk; |
| 130 | let mut b = [0u8; HEADER_LEN]; |
| 131 | put(&mut b, O_MAGIC, &MAGIC); |
| 132 | put(&mut b, O_VERSION, &FORMAT_VERSION.to_le_bytes()); |
| 133 | put(&mut b, O_KIND, &RECORD_KIND_CHUNK.to_le_bytes()); |
| 134 | put(&mut b, O_HEADER_LEN, &(HEADER_LEN as u32).to_le_bytes()); |
| 135 | put(&mut b, O_NAMESPACE, &c.namespace_id.0); |
| 136 | put(&mut b, O_KEY, c.chunk_key.as_bytes()); |
| 137 | put(&mut b, O_PARENT, &c.parent_key); |
| 138 | put(&mut b, O_MODEL, &c.model_sha256); |
| 139 | put(&mut b, O_FIRST_POS, &c.first_position.to_le_bytes()); |
| 140 | put(&mut b, O_TOKEN_COUNT, &c.token_count.to_le_bytes()); |
| 141 | put(&mut b, O_CHUNK_TOKENS, &c.chunk_tokens.to_le_bytes()); |
| 142 | put(&mut b, O_BLOCK_SIZE, &c.block_size.to_le_bytes()); |
| 143 | put(&mut b, O_LAYERS, &c.num_layers.to_le_bytes()); |
| 144 | put(&mut b, O_KV_HEADS, &c.num_kv_heads.to_le_bytes()); |
| 145 | put(&mut b, O_HEAD_DIM, &c.head_dim.to_le_bytes()); |
| 146 | b[O_DTYPE] = c.dtype; |
| 147 | b[O_BACKEND] = c.backend_format; |
| 148 | put(&mut b, O_FLAGS, &c.flags.to_le_bytes()); |
| 149 | put(&mut b, O_PAYLOAD_LEN, &c.payload_len.to_le_bytes()); |
| 150 | put(&mut b, O_PAYLOAD_SHA, &self.payload_sha256); |
| 151 | put(&mut b, O_WRITTEN_NS, &c.written_unix_ns.to_le_bytes()); |
| 152 | let digest: [u8; 32] = Sha256::digest(&b[..HASHED_PREFIX_LEN]).into(); |
| 153 | put(&mut b, O_HEADER_SHA, &digest); |
| 154 | b |
| 155 | } |
| 156 | |
| 157 | /// Structural decode of a record's header region: needs the whole 4096 |
| 158 | /// bytes (`Truncated` below that, ADR 0003 section 12 H6), then decodes the |
| 159 | /// 256-byte struct. Padding and the segment root are checked by |
| 160 | /// `validate_record`, which knows the segment count. No allocation. |
| 161 | pub fn decode(buf: &[u8]) -> Result<RecordHeader, KvError> { |
| 162 | if buf.len() < HEADER_REGION_LEN { |
| 163 | return Err(KvError::Truncated); |
| 164 | } |
| 165 | Self::decode_struct(buf) |
| 166 | } |
| 167 | |
| 168 | /// Structural decode of the 256-byte struct only (at least 256 bytes): |
| 169 | /// length, magic, version, kind, header_len, header checksum, reserved flag |
| 170 | /// bits. Identity checks are in `validate_record`. No allocation. |
| 171 | pub fn decode_struct(buf: &[u8]) -> Result<RecordHeader, KvError> { |
| 172 | if buf.len() < HEADER_LEN { |
| 173 | return Err(KvError::Truncated); |
| 174 | } |
| 175 | if buf[O_MAGIC..O_MAGIC + 8] != MAGIC { |
| 176 | return Err(KvError::BadMagic); |
| 177 | } |
| 178 | if get_u16(buf, O_VERSION) != FORMAT_VERSION { |
| 179 | return Err(KvError::UnsupportedVersion); |
| 180 | } |
| 181 | if get_u16(buf, O_KIND) != RECORD_KIND_CHUNK { |
| 182 | return Err(KvError::BadRecordKind); |
| 183 | } |
| 184 | if get_u32(buf, O_HEADER_LEN) as usize != HEADER_LEN { |
| 185 | return Err(KvError::BadHeaderLen); |
| 186 | } |
| 187 | let digest = Sha256::digest(&buf[..HASHED_PREFIX_LEN]); |
| 188 | if digest.as_slice() != &buf[O_HEADER_SHA..O_HEADER_SHA + 32] { |
| 189 | return Err(KvError::HeaderChecksum); |
| 190 | } |
| 191 | let flags = get_u16(buf, O_FLAGS); |
| 192 | if flags & !FLAG_PARTIAL_TAIL != 0 { |
| 193 | return Err(KvError::BadFlags); |
| 194 | } |
| 195 | Ok(RecordHeader { |
| 196 | chunk: ChunkHeader { |
| 197 | namespace_id: NamespaceId(get32(buf, O_NAMESPACE)), |
| 198 | chunk_key: ChunkKey(ObjectId(get32(buf, O_KEY))), |
| 199 | parent_key: get32(buf, O_PARENT), |
| 200 | model_sha256: get32(buf, O_MODEL), |
| 201 | first_position: get_u32(buf, O_FIRST_POS), |
| 202 | token_count: get_u32(buf, O_TOKEN_COUNT), |
| 203 | chunk_tokens: get_u32(buf, O_CHUNK_TOKENS), |
| 204 | block_size: get_u32(buf, O_BLOCK_SIZE), |
| 205 | num_layers: get_u32(buf, O_LAYERS), |
| 206 | num_kv_heads: get_u32(buf, O_KV_HEADS), |
| 207 | head_dim: get_u32(buf, O_HEAD_DIM), |
| 208 | dtype: buf[O_DTYPE], |
| 209 | backend_format: buf[O_BACKEND], |
| 210 | flags, |
| 211 | payload_len: get_u64(buf, O_PAYLOAD_LEN), |
| 212 | written_unix_ns: get_u64(buf, O_WRITTEN_NS), |
| 213 | }, |
| 214 | payload_sha256: get32(buf, O_PAYLOAD_SHA), |
| 215 | }) |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | /// `SHA-256("AIEN-PKV-PAYLOAD-V1\0" || seg_digest_0 || ... || seg_digest_{n-1})`, |
| 220 | /// the value stored at header offset 184 (ADR 0003 section 2.1, H4). |
| 221 | pub fn payload_root(seg_digests: &[[u8; 32]]) -> [u8; 32] { |
| 222 | let mut h = Sha256::new(); |
| 223 | h.update(PAYLOAD_DOMAIN); |
| 224 | for d in seg_digests { |
| 225 | h.update(d); |
| 226 | } |
| 227 | h.finalize().into() |
| 228 | } |
| 229 | |
| 230 | /// Number of segments of a payload: `ceil(payload_len / segment_bytes)`. |
| 231 | /// `InvalidGeometry` for a zero size, `TooManySegments` above `MAX_SEGMENTS`. |
| 232 | pub fn segment_count(payload_len: u64, segment_bytes: u64) -> Result<u32, KvError> { |
| 233 | if payload_len == 0 || segment_bytes == 0 { |
| 234 | return Err(KvError::InvalidGeometry); |
| 235 | } |
| 236 | let n = payload_len.div_ceil(segment_bytes); |
| 237 | if n > MAX_SEGMENTS as u64 { |
| 238 | return Err(KvError::TooManySegments); |
| 239 | } |
| 240 | Ok(n as u32) |
| 241 | } |
| 242 | |
| 243 | impl RecordHeader { |
| 244 | /// Serialize the 4096-byte header region: the 256-byte struct, then the |
| 245 | /// segment digest table, then zeros (ADR 0003 section 2.1, H5). Does not |
| 246 | /// check that `payload_sha256` is the root of `seg_digests`; validation does. |
| 247 | pub fn encode_region( |
| 248 | &self, |
| 249 | seg_digests: &[[u8; 32]], |
| 250 | ) -> Result<[u8; HEADER_REGION_LEN], KvError> { |
| 251 | if seg_digests.len() > MAX_SEGMENTS { |
| 252 | return Err(KvError::TooManySegments); |
| 253 | } |
| 254 | let mut region = [0u8; HEADER_REGION_LEN]; |
| 255 | region[..HEADER_LEN].copy_from_slice(&self.encode()); |
| 256 | for (i, d) in seg_digests.iter().enumerate() { |
| 257 | let at = SEGMENT_TABLE_OFFSET + 32 * i; |
| 258 | region[at..at + 32].copy_from_slice(d); |
| 259 | } |
| 260 | Ok(region) |
| 261 | } |
| 262 | } |