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

577 lines · 21890 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//! Provenance link (arch#162, ALLEN end-to-end demo v1 steps S4 and S8): a
17//! commit the model produced through the compose path names the generation
18//! record of that proposal and the ALLEN the task ran under.
19//!
20//! The real compose library, the real daemon server on its socket and the
21//! ordinary operator flow: propose (RunComposeTask) -> authorize -> intent ->
22//! write -> ack. Only the model is replaced by a fixed proposer that returns
23//! the token ids the real inference path returns; the daemon is told the
24//! "loaded model" digest with `set_model_identity`, exactly as the CLI does
25//! after it loads weights. The live SmolLM2 version of this flow is
26//! `crates/aien-cli/tests/provenance_link_live_test.rs` (ignored: it needs a
27//! prebuilt binary and the model, like recovery_matrix_test).
28//!
29//! Everything here reads the ledger through the socket (`ComposeRecall`) and
30//! the report as JSON, so the test is the same on a build without the link.
31//! Every test needs the linked composition archive and is IGNORED in a stub
32//! build, never passed.
33#[path = "support/home_guard.rs"]
34mod home_guard;
35
36#[path = "../../aien-allen/tests/support/mod.rs"]
37mod support;
38
39use aien_allen::{hex as ahex, ENV_ADOPT, ENV_SUBJECT};
40use aien_inference_abi::MockInferenceBackend;
41use aien_kv_cache::create_shared_kv_manager;
42use aien_omega_compose::{hex, Compose, RootKind};
43use aien_runtime::approved_auth::{desk_key_path, AuthorizeBinding, DeskKey};
44use aien_runtime::client::AienRuntimeClient;
45use aien_runtime::compose::{token_ids_sha256, ComposeBridge, ComposeProposer, Generation};
46use aien_runtime::control::{ControlCommand, ControlResponse, DeskProof};
47use aien_runtime::generation::ModelIdentity;
48use aien_runtime::server::AienRuntimeServer;
49use aien_runtime::spine::AienRuntimeSpine;
50use aien_scheduler::SchedulerConfig;
51use serde_json::{json, Value};
52use sha2::{Digest, Sha256};
53use std::path::{Path, PathBuf};
54use std::sync::Arc;
55use std::time::Duration;
56
57/// The composition engine holds one home at a time per process, and the ALLEN
58/// variables are process-wide.
59static ONE_HOME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
60
61const PROPOSAL: &str = "filename: NOTES.md\nkeep every change inside the workspace\n";
62const CONTENT: &str = "keep every change inside the workspace\n";
63const OUT_IDS: [u32; 3] = [11, 12, 13];
64const PROMPT_IDS: [u32; 5] = [1, 2, 3, 4, 5];
65
66fn sha(b: &[u8]) -> String {
67 hex(&Sha256::digest(b))
68}
69
70fn identity() -> ModelIdentity {
71 ModelIdentity {
72 model_sha256: "ab".repeat(32),
73 model_digest_kind: "index+shards".into(),
74 model_path: "/models/toy/model.safetensors".into(),
75 tokenizer_sha256: "cd".repeat(32),
76 tokenizer_path: "/models/toy/tokenizer.json".into(),
77 }
78}
79
80/// How the backend chose OUT_IDS: all greedy (sc#294).
81fn greedy_observation() -> aien_inference_abi::DecodeObservation {
82 aien_inference_abi::DecodeObservation {
83 greedy_tokens: OUT_IDS.len() as u64,
84 ..Default::default()
85 }
86}
87
88/// The tensor backend and op counters the scheduler reports (sc#337).
89fn cpu_ops() -> aien_inference_abi::OpEvidence {
90 aien_inference_abi::OpEvidence {
91 backend: "reference-cpu".into(),
92 native_fallbacks: 0,
93 reference_runs: 0,
94 report: "OP_REPORT native=[] reference=[] native_fallbacks=[] reference_runs=[]".into(),
95 gpu_executions: None,
96 }
97}
98
99/// The reply the real inference path gives: text, generated ids, prompt ids hash.
100fn proposer() -> ComposeProposer {
101 Arc::new(|_p: &str, _l: Duration| {
102 Ok(Generation {
103 text: PROPOSAL.to_string(),
104 tokens: OUT_IDS.len(),
105 finish_reason: Some("eos".into()),
106 token_ids: Some(OUT_IDS.to_vec()),
107 prompt_tokens: Some(PROMPT_IDS.len()),
108 prompt_ids_sha256: Some(token_ids_sha256(&PROMPT_IDS)),
109 // sc#294: what the scheduler reports for a greedy run of these ids.
110 decoding: Some(greedy_observation()),
111 // sc#337: what the scheduler reports for a production CPU run.
112 ops: Some(cpu_ops()),
113 })
114 })
115}
116
117struct Daemon {
118 client: AienRuntimeClient,
119 bridge: Arc<ComposeBridge>,
120 handle: tokio::task::JoinHandle<Result<(), String>>,
121 _tmp: tempfile::TempDir,
122 ws: PathBuf,
123}
124
125impl Daemon {
126 /// `home`: an existing compose home (ALLEN tests prepare one), else a fresh one.
127 async fn start(
128 model: Option<ModelIdentity>,
129 home: Option<(tempfile::TempDir, PathBuf)>,
130 ) -> Self {
131 let (tmp, home) = home.unwrap_or_else(|| {
132 let t = tempfile::tempdir().unwrap();
133 let h = t.path().join("compose");
134 (t, h)
135 });
136 let ws = std::fs::canonicalize({
137 let w = tmp.path().join("ws");
138 std::fs::create_dir_all(&w).unwrap();
139 w
140 })
141 .unwrap();
142 let socket = tmp.path().join("runtime.sock");
143 let cfg = SchedulerConfig {
144 max_batch_size: 8,
145 max_batch_tokens: 1024,
146 prefill_chunk_size: 64,
147 watermark_blocks: 4,
148 chunk_prefill: true,
149 max_prefill_tokens: 1024,
150 };
151 let spine = AienRuntimeSpine::new(64, cfg, create_shared_kv_manager(256, 16));
152 // sc#328: the desk is required (the default); every authorize here is
153 // signed with this home's desk key, as `aien compose authorize --desk 1`.
154 let key = desk_key_path(&home);
155 if !key.exists() {
156 DeskKey::create(&key).unwrap();
157 }
158 let bridge = Arc::new(ComposeBridge::new(home, proposer(), "test:provenance-link"));
159 let server = AienRuntimeServer::new(spine, &socket).with_compose_bridge(bridge.clone());
160 if let Some(m) = model {
161 server.set_model_identity(m);
162 }
163 let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await });
164 let client = AienRuntimeClient::new(&socket);
165 for _ in 0..200 {
166 if client.is_alive().await {
167 return Self {
168 client,
169 bridge,
170 handle,
171 _tmp: tmp,
172 ws,
173 };
174 }
175 tokio::time::sleep(Duration::from_millis(20)).await;
176 }
177 panic!("daemon did not come up");
178 }
179
180 /// The approval desk's proof for an authorize of commit `cx` (path and
181 /// content as the daemon's commit record names them).
182 fn desk(
183 &self,
184 cx: u64,
185 proposal_sha256: &str,
186 path: &str,
187 content_sha256: &str,
188 ) -> Option<DeskProof> {
189 let key = DeskKey::load(&desk_key_path(self.bridge.dir())).unwrap();
190 let nonce = format!("prov-{cx}");
191 let mac = key.sign_authorize(&AuthorizeBinding {
192 cx_promotion: cx,
193 proposal_sha256: proposal_sha256.into(),
194 path: path.into(),
195 content_sha256: content_sha256.into(),
196 workspace: self.ws.display().to_string(),
197 approver: "drake".into(),
198 constraints: vec![],
199 nonce: nonce.clone(),
200 desk_key_id: key.id().into(),
201 });
202 Some(DeskProof { nonce, mac })
203 }
204
205 async fn send(&self, c: ControlCommand) -> ControlResponse {
206 self.client.send_command(c).await.unwrap()
207 }
208
209 /// Text of record `id` as JSON, digest-verified.
210 async fn record(&self, id: u64) -> Value {
211 match self
212 .send(ControlCommand::ComposeRecall {
213 ids: vec![id],
214 prefix: None,
215 })
216 .await
217 {
218 ControlResponse::ComposeRecalled(r) => {
219 assert_eq!(r.cited.len(), 1, "record {id} missing");
220 assert!(r.cited[0].verified, "record {id} does not verify");
221 serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap()
222 }
223 other => panic!("recall: {other:?}"),
224 }
225 }
226
227 async fn host_records(&self) -> usize {
228 match self
229 .send(ControlCommand::ComposeRecall {
230 ids: vec![],
231 prefix: None,
232 })
233 .await
234 {
235 ControlResponse::ComposeRecalled(r) => r.host.len(),
236 other => panic!("recall: {other:?}"),
237 }
238 }
239
240 async fn stop(self) {
241 let _ = self.client.send_command(ControlCommand::Shutdown).await;
242 let _ = tokio::time::timeout(Duration::from_secs(5), self.handle).await;
243 }
244}
245
246/// Every record id of one ordinary flow, and its report as JSON.
247struct Flow {
248 report: Value,
249 commit: u64,
250 grant: u64,
251 intent: u64,
252 ack: u64,
253}
254
255fn noted(r: ControlResponse, what: &str) -> u64 {
256 match r {
257 ControlResponse::ComposeNoted(n) => n.id,
258 other => panic!("{what}: {other:?}"),
259 }
260}
261
262/// propose -> authorize -> intent -> write -> ack, through the socket.
263async fn ordinary_flow(d: &Daemon) -> Flow {
264 let report = match d
265 .send(ControlCommand::RunComposeTask {
266 context: None,
267 goal: "write the note".into(),
268 workspace: d.ws.to_str().unwrap().into(),
269 })
270 .await
271 {
272 ControlResponse::ComposeTaskResult(r) => serde_json::to_value(&*r).unwrap(),
273 other => panic!("run: {other:?}"),
274 };
275 assert_eq!(report["committed"], true, "{report}");
276 let commit = report["compose_commit"].as_u64().expect("commit record");
277 let grant = noted(
278 d.send(ControlCommand::ComposeAuthorize {
279 cx_promotion: report["cx_promotion"].as_u64().unwrap(),
280 proposal_sha256: sha(PROPOSAL.as_bytes()),
281 workspace: d.ws.display().to_string(),
282 approver: "drake".into(),
283 constraints: vec![],
284 desk_proof: d.desk(
285 report["cx_promotion"].as_u64().unwrap(),
286 &sha(PROPOSAL.as_bytes()),
287 "NOTES.md",
288 &sha(CONTENT.as_bytes()),
289 ),
290 objective_id: None,
291 })
292 .await,
293 "authorize",
294 );
295 let target = d.ws.join("NOTES.md").display().to_string();
296 let (pid, start) = aien_runtime::effects::self_executor();
297 let intent = noted(
298 d.send(ControlCommand::ComposeEffectIntent {
299 authorization: grant,
300 proposal_sha256: sha(PROPOSAL.as_bytes()),
301 path: "NOTES.md".into(),
302 target: target.clone(),
303 content_sha256: sha(CONTENT.as_bytes()),
304 executor_pid: pid,
305 executor_start: start,
306 })
307 .await,
308 "intent",
309 );
310 std::fs::write(&target, CONTENT).unwrap();
311 let ack = noted(
312 d.send(ControlCommand::ComposeEffectAck {
313 intent,
314 reported: json!({"executor": "test"}),
315 })
316 .await,
317 "ack",
318 );
319 assert_eq!(d.record(ack).await["state"], "DONE");
320 Flow {
321 report,
322 commit,
323 grant,
324 intent,
325 ack,
326 }
327}
328
329/// The assertions of the demo's S4 and S8: the commit's records name a
330/// generation record whose model digest is the loaded model's, and the agent.
331async fn assert_linked(d: &Daemon, f: &Flow, want_agent: &str) {
332 let gen_id = f.report["generation_record"]
333 .as_u64()
334 .expect("the report names the generation record");
335 for (name, id) in [
336 ("compose_commit", f.commit),
337 ("grant", f.grant),
338 ("intent", f.intent),
339 ("ack", f.ack),
340 ] {
341 let r = d.record(id).await;
342 assert_eq!(r["provenance"]["generation_record"], gen_id, "{name}: {r}");
343 assert_eq!(r["provenance"]["allen_agent"], want_agent, "{name}: {r}");
344 }
345 let g = d.record(gen_id).await;
346 let want = identity();
347 assert_eq!(g["generation"], 1);
348 assert_eq!(g["origin"], "compose_proposal");
349 assert_eq!(g["model_sha256"], want.model_sha256);
350 assert_eq!(g["model_digest_kind"], want.model_digest_kind);
351 assert_eq!(g["tokenizer_sha256"], want.tokenizer_sha256);
352 assert_eq!(g["task"], f.report["task"]);
353 assert_eq!(g["attempt"], 1);
354 assert_eq!(g["prompt_ids_sha256"], token_ids_sha256(&PROMPT_IDS));
355 assert_eq!(g["output_token_ids_sha256"], token_ids_sha256(&OUT_IDS));
356 assert_eq!(g["output_text_sha256"], sha(PROPOSAL.as_bytes()));
357 assert_eq!(g["output_tokens"], OUT_IDS.len());
358 assert_eq!(g["finish_reason"], "eos");
359 assert_eq!(g["daemon"]["pid"], std::process::id());
360 // sc#294: the decoding the backend reported travels into the record.
361 assert_eq!(
362 g["decoding"],
363 json!({"mode": "greedy", "greedy_tokens": OUT_IDS.len(), "sampled_tokens": 0}),
364 "{g}"
365 );
366 // sc#337: the backend and op counters travel into the record.
367 assert_eq!(
368 g["ops"],
369 json!({
370 "backend": "reference-cpu",
371 "native_fallbacks": 0,
372 "reference_runs": 0,
373 "scope": "process",
374 "report": cpu_ops().report,
375 }),
376 "{g}"
377 );
378 // The grant, intent and commit still say what they said before.
379 assert_eq!(
380 d.record(f.commit).await["proposal_sha256"],
381 sha(PROPOSAL.as_bytes())
382 );
383 assert_eq!(
384 d.record(f.grant).await["content_sha256"],
385 sha(CONTENT.as_bytes())
386 );
387}
388
389#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
390#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
391async fn commit_names_generation_record_and_no_agent_when_none_is_attached() {
392 let _home = home_guard::home_slot();
393 let _g = ONE_HOME.lock().await;
394 std::env::remove_var(ENV_SUBJECT);
395 std::env::remove_var(ENV_ADOPT);
396 let d = Daemon::start(Some(identity()), None).await;
397 let f = ordinary_flow(&d).await;
398 assert_linked(&d, &f, "none").await;
399 d.stop().await;
400}
401
402/// (machine id, digest of Cortex record 1) of a home the daemon already opened.
403fn home_lineage(home: &Path) -> [u8; 32] {
404 let mut name = home.as_os_str().to_owned();
405 name.push(".machine-root");
406 let root = std::fs::read(PathBuf::from(name)).unwrap();
407 let (mut c, _) = Compose::open(home, RootKind::Provisioned, &root, 0xA1E4_0001).unwrap();
408 c.record(1).unwrap().digest
409}
410
411#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
412#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
413async fn commit_names_generation_record_and_the_allen_logical_agent_id() {
414 let _home = home_guard::home_slot();
415 let _g = ONE_HOME.lock().await;
416 std::env::remove_var(ENV_SUBJECT);
417 std::env::remove_var(ENV_ADOPT);
418 // A home that already exists (an ALLEN is bound to a journal's lineage).
419 let tmp = tempfile::tempdir().unwrap();
420 let home = tmp.path().join("compose");
421 {
422 let p = ComposeBridge::new(home.clone(), proposer(), "test:prepare");
423 assert!(matches!(
424 p.note("constraint", "prepare the home", &[]),
425 ControlResponse::ComposeNoted(_)
426 ));
427 p.close();
428 }
429 let mut fx = support::fx("provenance");
430 fx.cortex = home_lineage(&home);
431 let chain = support::chain(&fx, 2);
432 let subject = support::write_head(&tmp.path().join("subject.bin"), chain.last().unwrap());
433 let agent = ahex(&fx.agent);
434 std::env::set_var(ENV_SUBJECT, &subject);
435 std::env::set_var(ENV_ADOPT, &agent);
436 let d = Daemon::start(Some(identity()), Some((tmp, home))).await;
437 let f = ordinary_flow(&d).await;
438 assert_linked(&d, &f, &agent).await;
439 d.stop().await;
440 std::env::remove_var(ENV_SUBJECT);
441 std::env::remove_var(ENV_ADOPT);
442}
443
444/// No model identity (a stub or reference-weights run): no generation record,
445/// an explicit null in the chain, the flow itself unchanged.
446#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
447#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
448async fn no_model_identity_means_no_generation_claim_and_the_flow_still_works() {
449 let _home = home_guard::home_slot();
450 let _g = ONE_HOME.lock().await;
451 std::env::remove_var(ENV_SUBJECT);
452 std::env::remove_var(ENV_ADOPT);
453 let d = Daemon::start(None, None).await;
454 let f = ordinary_flow(&d).await;
455 assert_eq!(f.report["generation_record"], Value::Null);
456 for id in [f.commit, f.grant, f.intent, f.ack] {
457 let r = d.record(id).await;
458 assert_eq!(r["provenance"]["generation_record"], Value::Null, "{r}");
459 assert_eq!(r["provenance"]["allen_agent"], "none");
460 }
461 d.stop().await;
462}
463
464/// A ledger written before this change has no provenance anywhere: it opens,
465/// verifies and runs the same flow; what the daemon writes next says "none".
466#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
467#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
468async fn an_old_ledger_without_provenance_still_opens_and_runs() {
469 let _home = home_guard::home_slot();
470 let _g = ONE_HOME.lock().await;
471 std::env::remove_var(ENV_SUBJECT);
472 std::env::remove_var(ENV_ADOPT);
473 let d = Daemon::start(Some(identity()), None).await;
474 // The old commit record exactly as #261 wrote it (no provenance field),
475 // appended below the note guard, as an old journal would hold it.
476 let target = d.ws.join("OLD.md");
477 let old = json!({"compose_commit": 1, "task": 77, "cx_promotion": 777, "cx_evidence": 778,
478 "proposal_sha256": sha(b"old proposal"), "path": "OLD.md",
479 "content_sha256": sha(b"old\n"), "workspace": d.ws.display().to_string()});
480 let commit = noted(
481 d.bridge.note_unchecked("effect", &old.to_string(), &[]),
482 "old commit",
483 );
484 let before = d.record(commit).await;
485 assert!(before.get("provenance").is_none());
486 let grant = noted(
487 d.send(ControlCommand::ComposeAuthorize {
488 cx_promotion: 777,
489 proposal_sha256: sha(b"old proposal"),
490 workspace: d.ws.display().to_string(),
491 approver: "drake".into(),
492 constraints: vec![],
493 desk_proof: d.desk(777, &sha(b"old proposal"), "OLD.md", &sha(b"old\n")),
494 objective_id: None,
495 })
496 .await,
497 "authorize on an old commit",
498 );
499 let (pid, start) = aien_runtime::effects::self_executor();
500 let intent = noted(
501 d.send(ControlCommand::ComposeEffectIntent {
502 authorization: grant,
503 proposal_sha256: sha(b"old proposal"),
504 path: "OLD.md".into(),
505 target: target.display().to_string(),
506 content_sha256: sha(b"old\n"),
507 executor_pid: pid,
508 executor_start: start,
509 })
510 .await,
511 "intent on an old commit",
512 );
513 std::fs::write(&target, "old\n").unwrap();
514 let ack = noted(
515 d.send(ControlCommand::ComposeEffectAck {
516 intent,
517 reported: json!({}),
518 })
519 .await,
520 "ack",
521 );
522 assert_eq!(d.record(ack).await["state"], "DONE");
523 for id in [grant, intent, ack] {
524 let r = d.record(id).await;
525 assert_eq!(r["provenance"]["generation_record"], Value::Null, "{r}");
526 assert_eq!(r["provenance"]["allen_agent"], "none");
527 }
528 d.stop().await;
529}
530
531/// A caller cannot set the fields: ComposeNote refuses a provenance field on
532/// any record, and a forged "generation" a record that names one; a grant
533/// request carries only ids and digests, so the copy comes from the daemon's
534/// own commit record whatever the request says.
535#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
536#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")]
537async fn a_client_cannot_set_the_provenance_fields() {
538 let _home = home_guard::home_slot();
539 let _g = ONE_HOME.lock().await;
540 std::env::remove_var(ENV_SUBJECT);
541 std::env::remove_var(ENV_ADOPT);
542 let d = Daemon::start(Some(identity()), None).await;
543 let before = d.host_records().await;
544 for (kind, text) in [
545 (
546 "effect",
547 r#"{"provenance":{"generation_record":3,"allen_agent":"none"}}"#,
548 ),
549 ("constraint", r#"{"provenance":{"generation_record":3}}"#),
550 (
551 "effect",
552 r#"{"compose_commit":1,"provenance":{"generation_record":3}}"#,
553 ),
554 ("effect", r#"{"generation":1,"origin":"compose_proposal"}"#),
555 ("authorization", r#"{"provenance":{"generation_record":3}}"#),
556 ] {
557 match d
558 .send(ControlCommand::ComposeNote {
559 kind: kind.into(),
560 text: text.into(),
561 links: vec![],
562 })
563 .await
564 {
565 ControlResponse::Error(e) => assert!(
566 e.contains("provenance") || e.contains("generation") || e.contains("authorization"),
567 "{e}"
568 ),
569 other => panic!("FORGED ({kind} {text}): {other:?}"),
570 }
571 }
572 assert_eq!(d.host_records().await, before, "nothing was written");
573 // The flow's records carry the daemon's values; the request has no field to say otherwise.
574 let f = ordinary_flow(&d).await;
575 assert_linked(&d, &f, "none").await;
576 d.stop().await;
577}