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-runtime / tests / generation_record_test.rs

480 lines · 17784 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 daemon's generation record (docs/DAEMON_GENERATION_RECORD.md): evidence
17//! that this daemon generated this text from the model files it loaded.
18//! Socket-level, mock backend, toy tokenizer. Every test needs the linked
19//! composition archive and is IGNORED in a stub build, never passed (the
20//! no-record cases that hold in a stub build are unit tests in server.rs).
21#[path = "support/home_guard.rs"]
22mod home_guard;
23
24use aien_inference_abi::{
25 AienInferenceBackend, ChatTokenizer, DecodeObservation, DecodeOutput, MockInferenceBackend,
26 ModelConfig, ScheduledBatch, StepMetrics,
27};
28use aien_kv_cache::create_shared_kv_manager;
29use aien_omega_compose::hex;
30use aien_runtime::client::AienRuntimeClient;
31use aien_runtime::compose::{token_ids_sha256, ComposeBridge, ComposeProposer};
32use aien_runtime::control::{ControlCommand, ControlResponse};
33use aien_runtime::generation::ModelIdentity;
34use aien_runtime::server::AienRuntimeServer;
35use aien_runtime::spine::AienRuntimeSpine;
36use aien_runtime::{format_chat, ChatTurn};
37use aien_scheduler::SchedulerConfig;
38use serde_json::Value;
39use sha2::{Digest, Sha256};
40use std::sync::Arc;
41use std::time::Duration;
42
43/// The composition engine holds one home at a time per process.
44static ONE_HOME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
45
46fn toy_tokenizer() -> ChatTokenizer {
47 toy_tokenizer_with(r#""x100":100,"x101":101"#)
48}
49
50/// The toy vocabulary with the spelling of the two mock tokens chosen by the test.
51fn toy_tokenizer_with(mock_tokens: &str) -> ChatTokenizer {
52 let json = r#"{"version":"1.0","truncation":null,"padding":null,"added_tokens":[],
53 "normalizer":null,"pre_tokenizer":{"type":"Whitespace"},"post_processor":null,
54 "decoder":null,"model":{"type":"WordLevel","unk_token":"<unk>","vocab":{
55 "<unk>":0,"<s>":1,"</s>":2,"hello":6,MOCK}}}"#
56 .replace("MOCK", mock_tokens);
57 ChatTokenizer::from_bytes(json.as_bytes()).expect("toy tokenizer")
58}
59
60fn identity() -> ModelIdentity {
61 ModelIdentity {
62 model_sha256: "ab".repeat(32),
63 model_digest_kind: "index+shards".into(),
64 model_path: "/models/toy/model.safetensors".into(),
65 tokenizer_sha256: "cd".repeat(32),
66 tokenizer_path: "/models/toy/tokenizer.json".into(),
67 }
68}
69
70fn user(content: &str) -> Vec<ChatTurn> {
71 vec![ChatTurn {
72 role: "user".into(),
73 content: content.into(),
74 }]
75}
76
77struct Daemon {
78 client: AienRuntimeClient,
79 handle: tokio::task::JoinHandle<Result<(), String>>,
80 _tmp: tempfile::TempDir,
81}
82
83async fn start(identity: Option<ModelIdentity>) -> Daemon {
84 start_with(identity, toy_tokenizer()).await
85}
86
87async fn start_with(identity: Option<ModelIdentity>, tokenizer: ChatTokenizer) -> Daemon {
88 start_on(identity, tokenizer, MockInferenceBackend::new(1)).await
89}
90
91// Success-path evidence fixtures must actually stop, not merely reach a cap.
92struct EosBackend<B>(B);
93#[async_trait::async_trait]
94impl<B: AienInferenceBackend + Send> AienInferenceBackend for EosBackend<B> {
95 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> {
96 self.0.load_model(config).await
97 }
98 async fn execute_step(
99 &mut self,
100 batch: &ScheduledBatch,
101 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
102 let (mut outputs, metrics) = self.0.execute_step(batch).await?;
103 for output in &mut outputs {
104 if let DecodeOutput::Token { token_id, .. } = output {
105 if *token_id == 101 {
106 *token_id = 2;
107 }
108 }
109 }
110 Ok((outputs, metrics))
111 }
112 fn take_decode_observation(&mut self, request_id: u64) -> Option<DecodeObservation> {
113 self.0.take_decode_observation(request_id)
114 }
115}
116
117async fn start_on<B: AienInferenceBackend + Send + 'static>(
118 identity: Option<ModelIdentity>,
119 tokenizer: ChatTokenizer,
120 backend: B,
121) -> Daemon {
122 let tmp = tempfile::tempdir().unwrap();
123 let socket = tmp.path().join("runtime.sock");
124 let cfg = SchedulerConfig {
125 max_batch_size: 8,
126 max_batch_tokens: 1024,
127 prefill_chunk_size: 64,
128 watermark_blocks: 4,
129 chunk_prefill: true,
130 max_prefill_tokens: 1024,
131 };
132 let spine = AienRuntimeSpine::new(64, cfg, create_shared_kv_manager(256, 16));
133 let proposer: ComposeProposer =
134 Arc::new(|_p: &str, _l: Duration| Err("not used in this test".to_string()));
135 // sc#328: the bridge requires the desk by default; the daemon will not
136 // start without its key.
137 aien_runtime::approved_auth::DeskKey::create(&aien_runtime::approved_auth::desk_key_path(
138 &tmp.path().join("compose"),
139 ))
140 .unwrap();
141 let bridge = Arc::new(ComposeBridge::new(
142 tmp.path().join("compose"),
143 proposer,
144 "test:generation-record",
145 ));
146 let server = AienRuntimeServer::new(spine, &socket).with_compose_bridge(bridge);
147 server.set_tokenizer(tokenizer);
148 if let Some(id) = identity {
149 server.set_model_identity(id);
150 }
151 let handle = tokio::spawn(async move { server.run(EosBackend(backend)).await });
152 let client = AienRuntimeClient::new(&socket);
153 for _ in 0..200 {
154 if client.is_alive().await {
155 return Daemon {
156 client,
157 handle,
158 _tmp: tmp,
159 };
160 }
161 tokio::time::sleep(Duration::from_millis(20)).await;
162 }
163 panic!("daemon did not come up");
164}
165
166impl Daemon {
167 async fn turn(&self, content: &str) -> (String, Option<u64>) {
168 self.client
169 .stream_turn_recorded(user(content), 4, 0.0)
170 .await
171 .expect("turn")
172 }
173
174 async fn records(&self) -> u64 {
175 match self.recall(vec![]).await {
176 ControlResponse::ComposeRecalled(r) => r.records_total,
177 other => panic!("recall: {other:?}"),
178 }
179 }
180
181 async fn recall(&self, ids: Vec<u64>) -> ControlResponse {
182 self.client
183 .send_command(ControlCommand::ComposeRecall { ids, prefix: None })
184 .await
185 .unwrap()
186 }
187
188 async fn record(&self, id: u64) -> Value {
189 match self.recall(vec![id]).await {
190 ControlResponse::ComposeRecalled(r) => {
191 assert_eq!(r.cited.len(), 1, "record {id} missing");
192 assert!(r.cited[0].verified, "record {id} digest does not verify");
193 assert_eq!(r.cited[0].note.as_deref(), Some("effect"));
194 serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap()
195 }
196 other => panic!("recall: {other:?}"),
197 }
198 }
199
200 async fn note(&self, kind: &str, text: &str) -> ControlResponse {
201 self.client
202 .send_command(ControlCommand::ComposeNote {
203 kind: kind.into(),
204 text: text.into(),
205 links: vec![],
206 })
207 .await
208 .unwrap()
209 }
210
211 async fn stop(self) {
212 let _ = self.client.send_command(ControlCommand::Shutdown).await;
213 let _ = tokio::time::timeout(Duration::from_secs(5), self.handle).await;
214 }
215}
216
217fn sha(b: &[u8]) -> String {
218 hex(&Sha256::digest(b))
219}
220
221/// The stopping mock emits ordinary x100 (100), then EOS </s> (2).
222/// This toy tokenizer does not register special added tokens, so both decode.
223fn ids_of(text: &str) -> Vec<u32> {
224 text.split_whitespace()
225 .map(|w| match w {
226 "x100" => 100,
227 "</s>" => 2,
228 other => panic!("unexpected word {other:?} in {text:?}"),
229 })
230 .collect()
231}
232
233#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
234#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
235async fn record_carries_the_digests_of_the_turn() {
236 let _home = home_guard::home_slot();
237 let _g = ONE_HOME.lock().await;
238 let d = start(Some(identity())).await;
239 let tok = toy_tokenizer();
240 let prompt = tok
241 .encode(&format_chat(tok.template(), &user("hello hello")).expect("chat"))
242 .unwrap();
243 let (text, id) = d.turn("hello hello").await;
244 assert!(!text.is_empty());
245 let id = id.expect("a record id");
246 let r = d.record(id).await;
247 let want = identity();
248 assert_eq!(r["generation"], 1);
249 assert_eq!(r["v"], 1);
250 assert_eq!(r["model_sha256"], want.model_sha256);
251 assert_eq!(r["model_digest_kind"], want.model_digest_kind);
252 assert_eq!(r["model_path"], want.model_path);
253 assert_eq!(r["tokenizer_sha256"], want.tokenizer_sha256);
254 assert_eq!(r["tokenizer_path"], want.tokenizer_path);
255 assert_eq!(r["prompt_ids_sha256"], token_ids_sha256(&prompt));
256 // The digest of the exact text TurnFinished returned.
257 assert_eq!(r["output_text_sha256"], sha(text.as_bytes()));
258 let out = ids_of(&text);
259 assert_eq!(r["output_token_ids_sha256"], token_ids_sha256(&out));
260 assert_eq!(r["output_tokens"], out.len());
261 assert!(r["total_tokens"].as_u64().unwrap() > 0);
262 assert_eq!(r["finish_reason"], "eos");
263 assert_eq!(r["daemon"]["pid"], std::process::id());
264 assert!(r["daemon"]["started_unix_ms"].as_str().unwrap().len() > 8);
265 // sc#294: the mock backend observes nothing, so the record makes no
266 // decoding claim (absent, never a default "greedy").
267 assert!(r.get("decoding").is_none(), "{r}");
268 // The envelope ids are the client's own, recorded as asserted.
269 assert!(r["request_id"].as_u64().unwrap() > 0);
270 assert!(r["operation_id"].as_str().unwrap().len() > 3);
271 d.stop().await;
272}
273
274/// The record hashes the text exactly as returned, whitespace included (a
275/// `trim()` before hashing would break the match with what the client holds).
276#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
277#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
278async fn text_is_hashed_byte_exact_with_surrounding_whitespace() {
279 let _home = home_guard::home_slot();
280 let _g = ONE_HOME.lock().await;
281 // Decoded text of the mock tokens: leading and trailing spaces.
282 let d = start_with(
283 Some(identity()),
284 toy_tokenizer_with(r#"" x100 ":100,"x101 ":101"#),
285 )
286 .await;
287 let (text, id) = d.turn("hello").await;
288 assert_ne!(
289 text,
290 text.trim(),
291 "test needs surrounding whitespace: {text:?}"
292 );
293 let r = d.record(id.expect("a record id")).await;
294 assert_eq!(r["output_text_sha256"], sha(text.as_bytes()));
295 assert_ne!(r["output_text_sha256"], sha(text.trim().as_bytes()));
296 d.stop().await;
297}
298
299#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
300#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
301async fn two_identical_turns_make_two_records() {
302 let _home = home_guard::home_slot();
303 let _g = ONE_HOME.lock().await;
304 let d = start(Some(identity())).await;
305 let (t1, a) = d.turn("hello").await;
306 let (t2, b) = d.turn("hello").await;
307 let (a, b) = (a.expect("first record"), b.expect("second record"));
308 assert_ne!(a, b, "one record per turn");
309 assert_eq!(t1, t2);
310 let (ra, rb) = (d.record(a).await, d.record(b).await);
311 assert_eq!(ra["output_text_sha256"], rb["output_text_sha256"]);
312 assert_eq!(ra["prompt_ids_sha256"], rb["prompt_ids_sha256"]);
313 d.stop().await;
314}
315
316#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
317#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
318async fn no_model_identity_means_no_record_and_the_turn_succeeds() {
319 let _home = home_guard::home_slot();
320 let _g = ONE_HOME.lock().await;
321 let d = start(None).await;
322 let before = d.records().await;
323 let (text, id) = d.turn("hello").await;
324 assert!(!text.is_empty());
325 assert_eq!(id, None);
326 assert_eq!(d.records().await, before, "nothing was written");
327 d.stop().await;
328}
329
330#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
331#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
332async fn a_caller_cannot_write_a_generation_record() {
333 let _home = home_guard::home_slot();
334 let _g = ONE_HOME.lock().await;
335 let d = start(Some(identity())).await;
336 let (_, id) = d.turn("hello").await;
337 assert!(id.is_some());
338 let before = d.records().await;
339 let forged = r#"{"generation":1,"v":1,"model_sha256":"00","output_text_sha256":"00"}"#;
340 for (kind, text) in [
341 ("generation", forged),
342 ("generation", "plain text"),
343 ("effect", forged),
344 ] {
345 match d.note(kind, text).await {
346 ControlResponse::Error(e) => assert!(e.contains("generation"), "{kind}: {e}"),
347 other => panic!("FORGED generation record accepted ({kind}): {other:?}"),
348 }
349 }
350 assert_eq!(d.records().await, before, "ledger count unchanged");
351 d.stop().await;
352}
353
354#[test]
355fn turn_finished_without_a_record_serializes_as_before() {
356 // Older clients and servers: the field is absent when there is no record.
357 let none = ControlResponse::TurnFinished {
358 text: "x".into(),
359 total_tokens: 1,
360 generation_record: None,
361 };
362 assert_eq!(
363 serde_json::to_string(&none).unwrap(),
364 r#"{"TurnFinished":{"text":"x","total_tokens":1}}"#
365 );
366 let old: ControlResponse =
367 serde_json::from_str(r#"{"TurnFinished":{"text":"x","total_tokens":1}}"#).unwrap();
368 assert!(matches!(
369 old,
370 ControlResponse::TurnFinished {
371 generation_record: None,
372 ..
373 }
374 ));
375 let some = ControlResponse::TurnFinished {
376 text: "x".into(),
377 total_tokens: 1,
378 generation_record: Some(9),
379 };
380 assert!(serde_json::to_string(&some)
381 .unwrap()
382 .contains(r#""generation_record":9"#));
383}
384
385/// The mock backend, plus a fixed report of how it decoded: stands in for a
386/// backend that observes its sampling branch (sc#294).
387struct ObservingMock {
388 inner: MockInferenceBackend,
389 report: DecodeObservation,
390}
391
392#[async_trait::async_trait]
393impl AienInferenceBackend for ObservingMock {
394 async fn load_model(&mut self, config: &ModelConfig) -> Result<(), String> {
395 self.inner.load_model(config).await
396 }
397 async fn execute_step(
398 &mut self,
399 batch: &ScheduledBatch,
400 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
401 self.inner.execute_step(batch).await
402 }
403 fn take_decode_observation(&mut self, _request_id: u64) -> Option<DecodeObservation> {
404 Some(self.report.clone())
405 }
406}
407
408/// sc#294: the StreamTurn record states the decoding the backend reported at
409/// finish (from `CompletionEvent::Finished`), not the request's temperature:
410/// the client asks for 0.0 here and the backend reports sampling, so a record
411/// built from the settings would say greedy.
412#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
413#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
414async fn record_states_the_decoding_the_backend_reported() {
415 let _home = home_guard::home_slot();
416 let _g = ONE_HOME.lock().await;
417 let report = DecodeObservation {
418 greedy_tokens: 1,
419 sampled_tokens: 3,
420 temperature: Some(0.7),
421 top_p: Some(0.95),
422 seed_request_id: Some(42),
423 };
424 let backend = ObservingMock {
425 inner: MockInferenceBackend::new(1),
426 report,
427 };
428 let d = start_on(Some(identity()), toy_tokenizer(), backend).await;
429 let (_, id) = d.turn("hello hello").await;
430 let r = d.record(id.expect("a record id")).await;
431 assert_eq!(
432 r["decoding"],
433 serde_json::json!({
434 "mode": "mixed",
435 "greedy_tokens": 1,
436 "sampled_tokens": 3,
437 "temperature": 0.7,
438 "top_p": 0.95,
439 "seed_request_id": 42
440 }),
441 "{r}"
442 );
443 d.stop().await;
444}
445
446#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
447#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
448async fn capped_turn_is_refused_but_its_evidence_is_retained() {
449 let _home = home_guard::home_slot();
450 let _g = ONE_HOME.lock().await;
451 let d = start(Some(identity())).await;
452 let before = d.records().await;
453 let error = d
454 .client
455 .stream_turn_recorded(user("hello"), 1, 0.0)
456 .await
457 .expect_err("a token cap is not completion");
458 assert!(error.contains("max_tokens"), "{error}");
459 assert_eq!(d.records().await, before + 1);
460 let ControlResponse::ComposeRecalled(report) = d.recall(vec![]).await else {
461 panic!("recall")
462 };
463 let record = report
464 .host
465 .iter()
466 .rev()
467 .find_map(|record| {
468 let value: Value = serde_json::from_str(record.text.as_deref()?).ok()?;
469 (value["generation"] == 1).then_some((record, value))
470 })
471 .expect("generation evidence");
472 assert!(record.0.verified);
473 assert_eq!(record.1["finish_reason"], "max_tokens");
474 assert_eq!(record.1["output_text_sha256"], sha(b"x100"));
475 assert_eq!(
476 record.1["output_token_ids_sha256"],
477 token_ids_sha256(&[100])
478 );
479 d.stop().await;
480}