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 / identity_tests.rs

728 lines · 27458 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// Test cases adapted (re-expressed in Rust, none copied) from LMCache
17// tests/v1/distributed/test_nixl_store_dynamic_l2_adapter.py at 4d69cdc4,
18// Apache-2.0, Copyright LMCache contributors:
19// test_salted_objects_recover_independently_after_restart (line 745)
20// See THIRD_PARTY.md and ADR 0003 context item 24.
21
22mod common;
23
24use aien_kv_store::{
25 chunk_chain, chunk_key, validate_record, BackendFormat, ComputeConfig, EngineConfig,
26 EngineIdentity, KvDtype, KvError, NamespaceFields, NamespaceId, RecordHeader, RopeScaling,
27 WeightFormat,
28};
29use common::*;
30use sha2::{Digest, Sha256};
31
32type Mutator = (&'static str, fn(&mut NamespaceFields<'static>));
33
34fn mutators() -> Vec<Mutator> {
35 vec![
36 ("model_sha256", |f| f.model_sha256[31] ^= 1),
37 ("model_digest_kind", |f| f.model_digest_kind = "blake3-file"),
38 ("model_id", |f| f.model_id = "llama-3.2-3b-instruct"),
39 ("num_layers", |f| f.num_layers += 1),
40 ("num_kv_heads", |f| f.num_kv_heads += 1),
41 ("head_dim", |f| f.head_dim += 1),
42 ("block_size", |f| f.block_size = 8),
43 ("rope_theta", |f| f.rope_theta = 10000.0),
44 ("rope_scaling_none", |f| f.rope_scaling = None),
45 ("rope_factor", |f| {
46 f.rope_scaling.as_mut().unwrap().factor = 8.0
47 }),
48 ("rope_low", |f| {
49 f.rope_scaling.as_mut().unwrap().low_freq_factor = 2.0
50 }),
51 ("rope_high", |f| {
52 f.rope_scaling.as_mut().unwrap().high_freq_factor = 8.0
53 }),
54 ("rope_original_max", |f| {
55 f.rope_scaling
56 .as_mut()
57 .unwrap()
58 .original_max_position_embeddings = 4096
59 }),
60 ("qk_norm", |f| f.qk_norm = true),
61 ("dtype", |f| f.dtype = KvDtype::Fp16),
62 ("layout_head_stride", |f| f.layout.head_stride += 2),
63 ("layout_token_stride", |f| f.layout.token_stride += 2),
64 ("layout_kv_plane_stride", |f| f.layout.kv_plane_stride += 2),
65 ("layout_layer_stride", |f| f.layout.layer_stride += 2),
66 ("layout_block_stride", |f| f.layout.block_stride += 2),
67 ("layout_element_bytes", |f| f.layout.element_bytes = 4),
68 ("backend_format", |f| {
69 f.backend_format = BackendFormat::NativeF32DecodeStateV1
70 }),
71 ("chunk_tokens", |f| f.chunk_tokens = 512),
72 ("sharing_namespace", |f| f.sharing_namespace = "tenant-b"),
73 ("compute_config_digest", |f| f.compute_config_digest[0] ^= 1),
74 ]
75}
76
77#[test]
78fn namespace_changes_when_any_field_changes() {
79 let base = sample().namespace_id().unwrap();
80 let mut seen: Vec<(&str, NamespaceId)> = vec![("base", base)];
81 for (name, mutate) in mutators() {
82 let mut f = sample();
83 mutate(&mut f);
84 let id = f.namespace_id().unwrap();
85 for (other, other_id) in &seen {
86 assert_ne!(id, *other_id, "{name} collides with {other}");
87 }
88 seen.push((name, id));
89 }
90 // Same inputs, same id (deterministic).
91 assert_eq!(base, sample().namespace_id().unwrap());
92 // Every ADR 1.2 field is covered: 14 field rows expand to 25 mutators (the
93 // 24 of C1 plus field 14), and the base is the 26th id.
94 assert_eq!(seen.len(), 26);
95}
96
97#[test]
98fn rope_scaling_presence_is_distinct_from_zeroed_scaling() {
99 let mut a = sample();
100 a.rope_scaling = None;
101 let mut b = sample();
102 b.rope_scaling = Some(RopeScaling {
103 factor: 0.0,
104 low_freq_factor: 0.0,
105 high_freq_factor: 0.0,
106 original_max_position_embeddings: 0,
107 });
108 assert_ne!(a.namespace_id().unwrap(), b.namespace_id().unwrap());
109}
110
111#[test]
112fn namespace_refuses_oversized_or_inconsistent_fields() {
113 let mut f = sample();
114 let long = "x".repeat(65);
115 // Leak is fine in a test: NamespaceFields borrows with a 'static lifetime here.
116 f.sharing_namespace = Box::leak(long.into_boxed_str());
117 assert_eq!(
118 f.namespace_id(),
119 Err(KvError::FieldTooLong("sharing_namespace"))
120 );
121
122 let mut f = sample();
123 f.model_digest_kind = Box::leak("k".repeat(256).into_boxed_str());
124 assert_eq!(
125 f.namespace_id(),
126 Err(KvError::FieldTooLong("model_digest_kind"))
127 );
128
129 let mut f = sample();
130 f.chunk_tokens = 250; // not a multiple of block_size 16
131 assert_eq!(f.namespace_id(), Err(KvError::InvalidGeometry));
132 let mut f = sample();
133 f.block_size = 0;
134 assert_eq!(f.namespace_id(), Err(KvError::InvalidGeometry));
135 let mut f = sample();
136 f.chunk_tokens = 0;
137 assert_eq!(f.namespace_id(), Err(KvError::InvalidGeometry));
138}
139
140#[test]
141fn chunk_key_chain_depends_on_parent_and_position() {
142 let ns = small().namespace_id().unwrap();
143 let toks: Vec<u32> = (100..108).collect();
144 let k0 = chunk_key(&ns, None, 0, &toks).unwrap();
145
146 // Parent matters.
147 let k_parent_a = chunk_key(&ns, Some(&key(1)), 8, &toks).unwrap();
148 let k_parent_b = chunk_key(&ns, Some(&key(2)), 8, &toks).unwrap();
149 assert_ne!(k_parent_a, k_parent_b);
150 // Position matters even with identical tokens and parent.
151 let k_pos_8 = chunk_key(&ns, Some(&key(1)), 8, &toks).unwrap();
152 let k_pos_16 = chunk_key(&ns, Some(&key(1)), 16, &toks).unwrap();
153 assert_ne!(k_pos_8, k_pos_16);
154 // Namespace matters.
155 let other_ns = {
156 let mut f = small();
157 f.sharing_namespace = "tenant-b";
158 f.namespace_id().unwrap()
159 };
160 assert_ne!(k0, chunk_key(&other_ns, None, 0, &toks).unwrap());
161 // Tokens matter, and so does token count (partial vs full prefix).
162 let mut toks2 = toks.clone();
163 toks2[7] += 1;
164 assert_ne!(k0, chunk_key(&ns, None, 0, &toks2).unwrap());
165 assert_ne!(k0, chunk_key(&ns, None, 0, &toks[..7]).unwrap());
166 // First chunk uses an all-zero parent.
167 assert_eq!(
168 k0,
169 chunk_key(
170 &ns,
171 Some(&aien_kv_store::ChunkKey(aien_platform::ObjectId([0; 32]))),
172 0,
173 &toks
174 )
175 .unwrap()
176 );
177}
178
179#[test]
180fn chunk_chain_links_each_chunk_to_all_earlier_tokens() {
181 let ns = small().namespace_id().unwrap();
182 let toks: Vec<u32> = (0..20).collect(); // chunks of 8: 8, 8, 4 (partial tail)
183 let chain = chunk_chain(&ns, 8, &toks).unwrap();
184 assert_eq!(chain.len(), 3);
185 assert_eq!(chain[0], chunk_key(&ns, None, 0, &toks[0..8]).unwrap());
186 assert_eq!(
187 chain[1],
188 chunk_key(&ns, Some(&chain[0]), 8, &toks[8..16]).unwrap()
189 );
190 assert_eq!(
191 chain[2],
192 chunk_key(&ns, Some(&chain[1]), 16, &toks[16..20]).unwrap()
193 );
194
195 // Changing one token in chunk 0 changes every later key.
196 let mut changed = toks.clone();
197 changed[0] = 999;
198 let chain2 = chunk_chain(&ns, 8, &changed).unwrap();
199 assert!(chain.iter().zip(&chain2).all(|(a, b)| a != b));
200
201 // Changing a token in the tail only changes the tail.
202 let mut tail = toks.clone();
203 tail[19] = 999;
204 let chain3 = chunk_chain(&ns, 8, &tail).unwrap();
205 assert_eq!(chain[..2], chain3[..2]);
206 assert_ne!(chain[2], chain3[2]);
207
208 // A longer prompt shares the full-chunk prefix keys with a shorter one.
209 let longer: Vec<u32> = (0..28).collect();
210 let chain4 = chunk_chain(&ns, 8, &longer).unwrap();
211 assert_eq!(chain[..2], chain4[..2]);
212 // The 4-token tail of the short prompt does not match a full 8-token chunk.
213 assert_ne!(chain[2], chain4[2]);
214
215 assert!(chunk_chain(&ns, 8, &[]).unwrap().is_empty());
216 assert_eq!(chunk_chain(&ns, 0, &toks), Err(KvError::InvalidGeometry));
217}
218
219/// Adapted idea: LMCache `test_salted_objects_recover_independently_after_restart`.
220/// Two salts over the same tokens never share keys, and recomputing after a
221/// "restart" (fresh derivation from scratch) reproduces each salt's own keys.
222#[test]
223fn salted_namespaces_stay_independent_after_recomputation() {
224 let toks: Vec<u32> = (0..16).collect();
225 let derive = |salt: &'static str| {
226 let mut f = small();
227 f.sharing_namespace = salt;
228 let ns = f.namespace_id().unwrap();
229 chunk_chain(&ns, 8, &toks).unwrap()
230 };
231 let a1 = derive("salt-a");
232 let b1 = derive("salt-b");
233 let a2 = derive("salt-a");
234 let b2 = derive("salt-b");
235 assert_eq!(a1, a2);
236 assert_eq!(b1, b2);
237 for (x, y) in a1.iter().zip(&b1) {
238 assert_ne!(x, y);
239 }
240}
241
242type CfgMutator = (&'static str, fn(&mut ComputeConfig<'static>));
243
244/// The eight `ComputeConfig` fields that have more than one legal value today.
245/// The ninth, `hidden_act`, has the single value `Silu` (the loader refuses
246/// every other activation, ADR 1.2.1), so it is mutated at the byte level in
247/// `compute_config_digest_changes_with_each_field`.
248fn compute_mutators() -> Vec<CfgMutator> {
249 vec![
250 ("num_heads", |c| c.num_heads = 24),
251 ("hidden_dim", |c| c.hidden_dim = 3072),
252 ("intermediate_dim", |c| c.intermediate_dim = 8193),
253 ("vocab_size", |c| c.vocab_size = 128_257),
254 ("rms_norm_eps", |c| c.rms_norm_eps = 1e-6),
255 ("tie_word_embeddings", |c| c.tie_word_embeddings = false),
256 ("arith_id", |c| {
257 c.arith_id = "NativeCpuBackend (Rayon Multi-Core)"
258 }),
259 ("arith_epoch", |c| c.arith_epoch = 2),
260 ]
261}
262
263/// The digest bytes assembled by hand from ADR 1.2.1 / section 12 I3, with the
264/// activation byte given explicitly so the test can flip it.
265fn manual_digest(c: &ComputeConfig, act_byte: u8) -> [u8; 32] {
266 let mut h = Sha256::new();
267 h.update(b"AIEN-PKV-CFG-V1\0");
268 h.update(c.num_heads.to_le_bytes());
269 h.update(c.hidden_dim.to_le_bytes());
270 h.update(c.intermediate_dim.to_le_bytes());
271 h.update(c.vocab_size.to_le_bytes());
272 h.update(c.rms_norm_eps.to_bits().to_le_bytes());
273 h.update([u8::from(c.tie_word_embeddings)]);
274 h.update([act_byte]);
275 h.update([c.arith_id.len() as u8]);
276 h.update(c.arith_id.as_bytes());
277 h.update(c.arith_epoch.to_le_bytes());
278 h.finalize().into()
279}
280
281#[test]
282fn compute_config_digest_changes_with_each_field() {
283 let base = sample_compute();
284 let base_digest = base.digest().unwrap();
285 // The implementation equals the byte-by-byte formula of the ADR.
286 assert_eq!(base_digest, manual_digest(&base, 1));
287 assert_eq!(base_digest, sample_compute().digest().unwrap());
288
289 let mut seen = vec![("base", base_digest)];
290 for (name, mutate) in compute_mutators() {
291 let mut c = sample_compute();
292 mutate(&mut c);
293 let d = c.digest().unwrap();
294 assert_eq!(d, manual_digest(&c, 1), "{name}: matches the formula");
295 for (other, other_d) in &seen {
296 assert_ne!(d, *other_d, "{name} collides with {other}");
297 }
298 seen.push((name, d));
299 }
300 // Ninth field: the activation byte is part of the digest (1 = silu).
301 let act2 = manual_digest(&base, 2);
302 assert!(seen.iter().all(|(_, d)| *d != act2));
303 assert_eq!(
304 seen.len(),
305 9,
306 "8 struct mutators + base; hidden_act is the 9th"
307 );
308
309 // A length-prefixed string cannot alias its neighbour: "ab"+epoch vs "a"+...
310 let mut a = sample_compute();
311 a.arith_id = "";
312 let mut b = sample_compute();
313 b.arith_id = "x";
314 assert_ne!(a.digest().unwrap(), b.digest().unwrap());
315}
316
317#[test]
318fn compute_config_refuses_oversized_arith_id() {
319 let mut c = sample_compute();
320 c.arith_id = Box::leak("a".repeat(256).into_boxed_str());
321 assert_eq!(c.digest(), Err(KvError::FieldTooLong("arith_id")));
322 c.arith_id = Box::leak("a".repeat(255).into_boxed_str());
323 assert!(c.digest().is_ok());
324}
325
326/// Review finding 1: two model directories with the same weights and the same
327/// fields 1 to 13 but a different `rms_norm_eps` must not share objects.
328#[test]
329fn rms_norm_eps_alone_changes_the_namespace() {
330 let ns_for = |eps: f32| {
331 let mut c = sample_compute();
332 c.rms_norm_eps = eps;
333 let mut f = sample();
334 f.compute_config_digest = c.digest_with_engine(&sample_engine()).unwrap();
335 f.namespace_id().unwrap()
336 };
337 let a = ns_for(1e-5);
338 let b = ns_for(1e-6);
339 assert_ne!(a, b);
340 assert_eq!(a, ns_for(1e-5));
341 // Everything else about the two fields structs is equal.
342 let mut f1 = sample();
343 f1.compute_config_digest = {
344 let mut c = sample_compute();
345 c.rms_norm_eps = 1e-5;
346 c.digest_with_engine(&sample_engine()).unwrap()
347 };
348 assert_eq!(f1, sample());
349 // And the chunk keys derived from them differ, so no object can be found.
350 let toks: Vec<u32> = (0..8).collect();
351 assert_ne!(
352 chunk_key(&a, None, 0, &toks).unwrap(),
353 chunk_key(&b, None, 0, &toks).unwrap()
354 );
355}
356
357/// ADR 1.2: field 14 is appended after field 13 and every earlier field keeps
358/// its position, so the namespace id equals a hand-assembled hash.
359fn manual_namespace(f: &NamespaceFields, domain: &[u8]) -> [u8; 32] {
360 let mut h = Sha256::new();
361 h.update(domain);
362 h.update(1u16.to_le_bytes());
363 h.update(f.model_sha256);
364 h.update([f.model_digest_kind.len() as u8]);
365 h.update(f.model_digest_kind.as_bytes());
366 h.update((f.model_id.len() as u16).to_le_bytes());
367 h.update(f.model_id.as_bytes());
368 for v in [f.num_layers, f.num_kv_heads, f.head_dim, f.block_size] {
369 h.update(v.to_le_bytes());
370 }
371 h.update(f.rope_theta.to_bits().to_le_bytes());
372 let r = f.rope_scaling.unwrap();
373 h.update([1u8]);
374 h.update(r.factor.to_bits().to_le_bytes());
375 h.update(r.low_freq_factor.to_bits().to_le_bytes());
376 h.update(r.high_freq_factor.to_bits().to_le_bytes());
377 h.update(r.original_max_position_embeddings.to_le_bytes());
378 h.update([u8::from(f.qk_norm)]);
379 h.update([f.dtype as u8]);
380 let l = f.layout;
381 for v in [
382 l.head_stride,
383 l.token_stride,
384 l.kv_plane_stride,
385 l.layer_stride,
386 l.block_stride,
387 l.element_bytes,
388 ] {
389 h.update(v.to_le_bytes());
390 }
391 h.update([f.backend_format as u8]);
392 h.update(f.chunk_tokens.to_le_bytes());
393 h.update((f.sharing_namespace.len() as u16).to_le_bytes());
394 h.update(f.sharing_namespace.as_bytes());
395 h.update(f.compute_config_digest); // field 14, raw 32 bytes
396 h.finalize().into()
397}
398
399#[test]
400fn namespace_id_appends_compute_digest_after_sharing_namespace() {
401 let f = sample();
402 let want = manual_namespace(&f, b"AIEN-PKV-NS-V2\0");
403 assert_eq!(f.namespace_id().unwrap().0, want);
404}
405
406#[test]
407fn segments_follow_the_backend_format() {
408 // Host: one segment per pool block.
409 let f = sample();
410 assert_eq!(f.segment_bytes(256).unwrap(), 524_288);
411 assert_eq!(f.segment_count(256).unwrap(), 16);
412 assert_eq!(f.segment_count(17).unwrap(), 2); // 17 tokens = 2 blocks
413 assert_eq!(f.segment_count(1).unwrap(), 1);
414 assert_eq!(f.segment_count(0), Err(KvError::TokenCountOutOfRange));
415 // Native: the whole payload is one segment (ADR 2.1 item 3).
416 let mut n = sample();
417 n.backend_format = BackendFormat::NativeF32DecodeStateV1;
418 n.dtype = KvDtype::Fp32;
419 n.layout.element_bytes = 4;
420 n.chunk_tokens = 64;
421 assert_eq!(
422 n.segment_bytes(64).unwrap(),
423 n.expected_payload_len(64).unwrap()
424 );
425 assert_eq!(n.segment_count(64).unwrap(), 1);
426 assert_eq!(n.segment_count(3).unwrap(), 1);
427}
428
429#[test]
430fn host_chunk_blocks_are_capped_at_119() {
431 // (4064 - 256) / 32: the digest table ends where the seal slot starts.
432 let mut f = sample();
433 f.chunk_tokens = 119 * f.block_size;
434 assert!(f.namespace_id().is_ok());
435 assert_eq!(f.segment_count(f.chunk_tokens).unwrap(), 119);
436 f.chunk_tokens = 120 * f.block_size;
437 assert_eq!(f.namespace_id(), Err(KvError::TooManySegments));
438 // Native has one segment, so no block cap applies.
439 f.backend_format = BackendFormat::NativeF32DecodeStateV1;
440 assert!(f.namespace_id().is_ok());
441}
442
443#[test]
444fn zero_byte_factors_in_the_layout_are_refused() {
445 let mut f = sample();
446 f.backend_format = BackendFormat::HostPagedPoolV1;
447 f.layout.block_stride = 0;
448 assert_eq!(f.namespace_id(), Err(KvError::InvalidGeometry));
449 assert_eq!(f.expected_payload_len(16), Err(KvError::InvalidGeometry));
450
451 let mut f = sample();
452 f.backend_format = BackendFormat::NativeF32DecodeStateV1;
453 f.layout.element_bytes = 0;
454 assert_eq!(f.namespace_id(), Err(KvError::InvalidGeometry));
455 assert_eq!(f.expected_payload_len(16), Err(KvError::InvalidGeometry));
456}
457
458// ---------------------------------------------------------------------------
459// sc#504: the engine that computed the bytes is part of their identity
460// (ADR 1.2.2). Each engine field changed alone gives a different namespace,
461// and a record written under the old namespace is refused by validation.
462// ---------------------------------------------------------------------------
463
464type EngineMutator = (&'static str, fn(&mut EngineIdentity<'static>));
465
466/// One mutator per `EngineIdentity` field.
467fn engine_mutators() -> Vec<EngineMutator> {
468 vec![
469 ("weight_format", |e| {
470 e.weight_format = WeightFormat::Fp8Experts
471 }),
472 ("engine_build_id", |e| {
473 e.engine_build_id = "omega@0123abcd+kernels:feedf00d"
474 }),
475 ("rounding_class", |e| {
476 e.rounding_class = "omega-gb10@whole-prompt-v1"
477 }),
478 ("engine_config_digest", |e| e.engine_config_digest[0] ^= 1),
479 ]
480}
481
482fn fields_with_engine(e: &EngineIdentity) -> NamespaceFields<'static> {
483 let mut f = sample();
484 f.compute_config_digest = sample_compute().digest_with_engine(e).unwrap();
485 f
486}
487
488/// A record written under `old` and read back by a runtime whose identity is
489/// `new` must be refused: same tokens, same position, other namespace.
490fn assert_old_record_refused(old: &NamespaceFields, new: &NamespaceFields, name: &str) {
491 let toks: Vec<u32> = (0..old.chunk_tokens).collect();
492 let old_ns = old.namespace_id().unwrap();
493 let new_ns = new.namespace_id().unwrap();
494 let old_key = chunk_key(&old_ns, None, 0, &toks).unwrap();
495 let new_key = chunk_key(&new_ns, None, 0, &toks).unwrap();
496 assert_ne!(old_key, new_key, "{name}: chunk key must differ");
497 let stored = old
498 .chunk_header(&old_ns, old_key, None, 0, old.chunk_tokens, 1)
499 .unwrap();
500 let n_seg = old.segment_count(old.chunk_tokens).unwrap() as usize;
501 let digests = vec![[0x5Au8; 32]; n_seg];
502 let rec = RecordHeader {
503 chunk: stored,
504 payload_sha256: aien_kv_store::payload_root(&digests),
505 };
506 let region = rec.encode_region(&digests).unwrap();
507 let file_size = 4096 + stored.payload_len;
508 let seg = old.segment_bytes(old.chunk_tokens).unwrap();
509 // Positive control: the writer's own identity accepts the record.
510 validate_record(&region, file_size, &stored, seg).unwrap();
511 // The new identity expects its own namespace and key: refused.
512 let expected = new
513 .chunk_header(&new_ns, old_key, None, 0, new.chunk_tokens, 1)
514 .unwrap();
515 assert_eq!(
516 validate_record(&region, file_size, &expected, seg),
517 Err(KvError::NamespaceMismatch),
518 "{name}: a record of the old namespace was accepted"
519 );
520}
521
522#[test]
523fn each_engine_field_alone_changes_the_namespace_and_refuses_old_records() {
524 let base = fields_with_engine(&sample_engine());
525 assert_eq!(base, sample(), "sample() carries sample_engine()");
526 let mut seen = vec![("base", base.namespace_id().unwrap())];
527 for (name, mutate) in engine_mutators() {
528 let mut e = sample_engine();
529 mutate(&mut e);
530 let f = fields_with_engine(&e);
531 let id = f.namespace_id().unwrap();
532 for (other, other_id) in &seen {
533 assert_ne!(id, *other_id, "{name} collides with {other}");
534 }
535 seen.push((name, id));
536 assert_old_record_refused(&base, &f, name);
537 assert_old_record_refused(&f, &base, name);
538 }
539 assert_eq!(seen.len(), 5, "4 engine fields + base");
540}
541
542#[test]
543fn weight_format_alone_changes_the_namespace() {
544 let mut ids = Vec::new();
545 for wf in [
546 WeightFormat::AsFile,
547 WeightFormat::Bf16,
548 WeightFormat::Fp8Experts,
549 WeightFormat::Fp8All,
550 ] {
551 let mut e = sample_engine();
552 e.weight_format = wf;
553 let id = fields_with_engine(&e).namespace_id().unwrap();
554 assert!(!ids.contains(&id), "{wf:?} aliases another weight format");
555 ids.push(id);
556 assert_eq!(WeightFormat::from_u8(wf as u8), Some(wf));
557 }
558 assert_eq!(WeightFormat::Fp8Experts.as_str(), "fp8-experts");
559 assert_eq!(WeightFormat::from_u8(0), None);
560}
561
562#[test]
563fn engine_build_id_alone_changes_the_namespace() {
564 let mut e = sample_engine();
565 e.engine_build_id = "aien-runtime/0.1.0+git:other";
566 let f = fields_with_engine(&e);
567 assert_ne!(f.namespace_id().unwrap(), sample().namespace_id().unwrap());
568 assert_old_record_refused(&sample(), &f, "engine_build_id");
569}
570
571#[test]
572fn rounding_class_alone_changes_the_namespace() {
573 let mut e = sample_engine();
574 e.rounding_class = "ReferenceCpuBackend@kv-arith-epoch-2";
575 let f = fields_with_engine(&e);
576 assert_ne!(f.namespace_id().unwrap(), sample().namespace_id().unwrap());
577 assert_old_record_refused(&sample(), &f, "rounding_class");
578}
579
580#[test]
581fn engine_config_digest_alone_changes_the_namespace() {
582 let mut e = sample_engine();
583 e.engine_config_digest[31] ^= 0x80;
584 let f = fields_with_engine(&e);
585 assert_ne!(f.namespace_id().unwrap(), sample().namespace_id().unwrap());
586 assert_old_record_refused(&sample(), &f, "engine_config_digest");
587}
588
589type EngCfgMutator = (&'static str, fn(&mut EngineConfig<'static>));
590
591/// MoE shape and run-time numeric switches (ADR 1.2.2): whole-prompt prefill
592/// changes activation rounding, so it changes the K/V bytes.
593fn engine_config_mutators() -> Vec<EngCfgMutator> {
594 vec![
595 ("num_experts", |c| c.num_experts = 128),
596 ("experts_per_token", |c| c.experts_per_token = 8),
597 ("expert_intermediate_dim", |c| {
598 c.expert_intermediate_dim = 768
599 }),
600 ("whole_prompt_prefill", |c| c.whole_prompt_prefill = true),
601 ("device_router", |c| c.device_router = true),
602 ("matmul_path", |c| c.matmul_path = "gemv"),
603 ]
604}
605
606fn manual_engine_config_digest(c: &EngineConfig) -> [u8; 32] {
607 let mut h = Sha256::new();
608 h.update(b"AIEN-PKV-ENG-V1\0");
609 h.update(c.num_experts.to_le_bytes());
610 h.update(c.experts_per_token.to_le_bytes());
611 h.update(c.expert_intermediate_dim.to_le_bytes());
612 h.update([u8::from(c.whole_prompt_prefill)]);
613 h.update([u8::from(c.device_router)]);
614 h.update([c.matmul_path.len() as u8]);
615 h.update(c.matmul_path.as_bytes());
616 h.finalize().into()
617}
618
619#[test]
620fn engine_config_digest_changes_with_each_moe_field_and_switch() {
621 let base = sample_engine_config();
622 let base_d = base.digest().unwrap();
623 assert_eq!(base_d, manual_engine_config_digest(&base));
624 let mut seen = vec![("base", base_d)];
625 for (name, mutate) in engine_config_mutators() {
626 let mut c = sample_engine_config();
627 mutate(&mut c);
628 let d = c.digest().unwrap();
629 assert_eq!(d, manual_engine_config_digest(&c), "{name}: formula");
630 for (other, od) in &seen {
631 assert_ne!(d, *od, "{name} collides with {other}");
632 }
633 seen.push((name, d));
634 // And through field 14 the namespace differs too.
635 let mut e = sample_engine();
636 e.engine_config_digest = d;
637 assert_ne!(
638 fields_with_engine(&e).namespace_id().unwrap(),
639 sample().namespace_id().unwrap(),
640 "{name}: namespace ignores the switch"
641 );
642 }
643 assert_eq!(seen.len(), 7);
644}
645
646/// Field 14 equals the byte-by-byte formula of ADR 1.2.2.
647#[test]
648fn field_14_binds_compute_config_then_engine_identity() {
649 let c = sample_compute();
650 let e = sample_engine();
651 let mut h = Sha256::new();
652 h.update(b"AIEN-PKV-CFG-V2\0");
653 h.update(c.num_heads.to_le_bytes());
654 h.update(c.hidden_dim.to_le_bytes());
655 h.update(c.intermediate_dim.to_le_bytes());
656 h.update(c.vocab_size.to_le_bytes());
657 h.update(c.rms_norm_eps.to_bits().to_le_bytes());
658 h.update([u8::from(c.tie_word_embeddings)]);
659 h.update([1u8]);
660 h.update([c.arith_id.len() as u8]);
661 h.update(c.arith_id.as_bytes());
662 h.update(c.arith_epoch.to_le_bytes());
663 h.update([e.weight_format as u8]);
664 h.update([e.engine_build_id.len() as u8]);
665 h.update(e.engine_build_id.as_bytes());
666 h.update([e.rounding_class.len() as u8]);
667 h.update(e.rounding_class.as_bytes());
668 h.update(e.engine_config_digest);
669 let want: [u8; 32] = h.finalize().into();
670 assert_eq!(c.digest_with_engine(&e).unwrap(), want);
671 assert_eq!(sample().compute_config_digest, want);
672 // The compute-only digest is not field 14 any more.
673 assert_ne!(c.digest().unwrap(), want);
674}
675
676/// The engine build id and the rounding class are required: an empty string
677/// would let every engine alias, so it is refused, as is an oversized one.
678#[test]
679fn empty_or_oversized_engine_strings_are_refused() {
680 let c = sample_compute();
681 let mut e = sample_engine();
682 e.engine_build_id = "";
683 assert_eq!(
684 c.digest_with_engine(&e),
685 Err(KvError::FieldEmpty("engine_build_id"))
686 );
687 let mut e = sample_engine();
688 e.rounding_class = "";
689 assert_eq!(
690 c.digest_with_engine(&e),
691 Err(KvError::FieldEmpty("rounding_class"))
692 );
693 let mut e = sample_engine();
694 e.engine_build_id = Box::leak("b".repeat(256).into_boxed_str());
695 assert_eq!(
696 c.digest_with_engine(&e),
697 Err(KvError::FieldTooLong("engine_build_id"))
698 );
699 let mut e = sample_engine();
700 e.rounding_class = Box::leak("r".repeat(256).into_boxed_str());
701 assert_eq!(
702 c.digest_with_engine(&e),
703 Err(KvError::FieldTooLong("rounding_class"))
704 );
705 let mut ec = sample_engine_config();
706 ec.matmul_path = "";
707 assert_eq!(ec.digest(), Err(KvError::FieldEmpty("matmul_path")));
708}
709
710/// The namespace domain moved to V2 with the engine identity: the V1
711/// derivation over the very same 14 field values no longer matches, so no
712/// object written before sc#504 can be found.
713#[test]
714fn v1_namespace_domain_no_longer_matches() {
715 let f = sample();
716 let v1 = manual_namespace(&f, b"AIEN-PKV-NS-V1\0");
717 let v2 = manual_namespace(&f, b"AIEN-PKV-NS-V2\0");
718 let got = f.namespace_id().unwrap().0;
719 assert_ne!(got, v1, "the V1 domain still matches");
720 assert_eq!(got, v2);
721 // Also with the old (compute-only) field 14 the V1 id is not reproduced.
722 let mut old = sample();
723 old.compute_config_digest = sample_compute().digest().unwrap();
724 assert_ne!(
725 old.namespace_id().unwrap().0,
726 manual_namespace(&old, b"AIEN-PKV-NS-V1\0")
727 );
728}