Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/36b8f6f8f8eda8e1 # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#301 (code only) closed derived `36b8f6f8f8eda8e1` #301 Imported from GitHub aien-dev/aien-sovereign-core-mv#301 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `5fdd563a87ce1aa4c06f62bbf70716b6125a504d` · Head `f8a1d04cd59cc490659a062cb965164bd0aadf09` ### Fetch it A git bundle of the pull request's head, 18279 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/36b8f6f8f8eda8e1.bundle -o 36b8f6f8f8eda8e1.bundle git fetch 36b8f6f8f8eda8e1.bundle refs/pull/301/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 301 f8a1d04cd59cc490659a062cb965164bd0aadf09 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":301,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/301","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:44Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index be3e6777..83318be9 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-08T00:14:04Z", + "compiled_at": "2026-10-08T00:26:00Z", "compiler": "crumb-compile/1", - "digest": "sha256:083571290ea5f76686f631bd459af7b1f4c77f2e0ab4a0bd1df6a110523df151", + "digest": "sha256:1954daabc1a9e3711344a840a77f8eb73e52a8225964e708a73ffbc737aba410", "evidence_files": 186, "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1317, - "generated_at_commit": "36be9eb9ef2b493c72a44eb5adc3400da10f95d1", - "source_tree": "sha256:31e0f28108c730327049f728ee16acfd8c03cc7c5dd02886546275b43f4b4448" + "files": 1320, + "generated_at_commit": "0732b6dd9530903eb47dcc0c5c2d2670b7875726", + "source_tree": "sha256:a333c601db9df31b7fbf8543839222e6245571fd8f62d37ab6b5cf4d1b11cbcc" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 8611a986..830546a9 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "19bf33a9aa4a78fdb1582f6f5894babd98fe2e0fe3c62d09d73ed2aed5411035", - "last_commit": "38ca311", + "digest": "b0298d44ce42c5d721ddf77d0550bb1d0206b9f1da7dfe755fd9e29dda0e4c81", + "last_commit": "8e0000e", "name": "src", "purpose": "" } ], - "children_root": "sha256:49467d31ab0ba245bfddd5141e95face7fa02a9b55acb0aac0b7c3cdf7f64018", - "compiled_at": "2026-10-07T22:36:23Z", + "children_root": "sha256:5ef216cca4bfdceed4edfb1ef94250623d511bcacc9125f4d1773701cb291926", + "compiled_at": "2026-10-07T23:58:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:d134dc0047d8fe54025f5ee3a2c9936c3e098891a94d7f974d0b6cf9f9938774", + "digest": "sha256:53765e1fd0a9cd03e3846820fc848b63d5d97a620ee3487af7310c7756d192b9", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 30, - "generated_at_commit": "c45a100ddb348a857470e5a38d3cf1d04f9a8524", - "source_tree": "sha256:9021a26e204fd47bbf34910256dced2de35ce7b58c7da5ba848dc149fcf3ba5d" + "generated_at_commit": "8e0000e180d31dcc729cddce83dfc396fc835c8b", + "source_tree": "sha256:3274c2117eb2f2650c49ad353ebcf89f2b3525bd6efab813089193cd9a6ad1ee" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index 308cebab..7d0edef4 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-07T21:44:55Z", + "compiled_at": "2026-10-07T23:58:24Z", "compiler": "crumb-compile/1", - "digest": "sha256:19bf33a9aa4a78fdb1582f6f5894babd98fe2e0fe3c62d09d73ed2aed5411035", + "digest": "sha256:b0298d44ce42c5d721ddf77d0550bb1d0206b9f1da7dfe755fd9e29dda0e4c81", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 25, - "generated_at_commit": "38ca311b97d20ecbdf8ddb082cfb76b540005912", - "source_tree": "sha256:41032bb2d04d39c8fadfb415cac438a4cbc54bf4fa608099d8b0595bfc54f7ef" + "generated_at_commit": "8e0000e180d31dcc729cddce83dfc396fc835c8b", + "source_tree": "sha256:1204d16a4f14a133fbc7d1fe8188134c3abfef5a625acef2e9c9d16c74e38e85" } }, "history": [ diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs index 9deddb19..57fb5f79 100644 --- a/crates/aien-cli/src/commands.rs +++ b/crates/aien-cli/src/commands.rs @@ -1118,7 +1118,6 @@ fn reference_config() -> aien_inference_abi::ModelConfig { /// Result of daemon model loading: the manifest (with SHA-256 digests filled in on /// success), the weights, the tokenizer, and whether reference weights were used. struct DaemonModel { - #[allow(dead_code)] // digests are read by the PREFILL-E2E receipt (Cut 8) manifest: DaemonModelManifest, weights: aien_inference_abi::TransformerWeights, tokenizer: Option, @@ -1127,6 +1126,30 @@ struct DaemonModel { reference_weights: bool, } +/// The digests of the files the daemon actually loaded, for its generation +/// records. Present only when real weights AND a parsed tokenizer loaded (the +/// reference fallback has no file identity). +fn model_identity( + manifest: &DaemonModelManifest, + tokenizer_loaded: bool, +) -> Option { + if !tokenizer_loaded { + return None; + } + let path_text = |p: &std::path::Path| { + std::fs::canonicalize(p) + .unwrap_or_else(|_| p.to_path_buf()) + .display() + .to_string() + }; + Some(aien_runtime::generation::ModelIdentity { + model_sha256: manifest.model_sha256.clone()?, + model_path: path_text(manifest.checkpoint_path.as_deref()?), + tokenizer_sha256: manifest.tokenizer_sha256.clone()?, + tokenizer_path: path_text(manifest.tokenizer_path.as_deref()?), + }) +} + /// Hex SHA-256 of a file, streamed in 1 MiB chunks. fn sha256_file_hex(path: &std::path::Path) -> std::io::Result { use sha2::{Digest, Sha256}; @@ -1327,6 +1350,7 @@ type DaemonBackendParts = ( String, String, Option, + Option, ); fn build_native_daemon_backend() -> Result { @@ -1336,8 +1360,10 @@ fn build_native_daemon_backend() -> Result { weights, tokenizer, label: model_label, + manifest, .. } = load_daemon_model(manifest, policy.require_checkpoint)?; + let identity = model_identity(&manifest, tokenizer.is_some()); // FB-1 cut 6: the native Omega engine is the only GPU backend (no CUDA). The env names // AIEN_REQUIRE_BLACKWELL (the GB10 chip, campaign spec) and AIEN_GPU_BACKEND=omega both // make a missing engine fatal instead of falling back to CPU reference math. @@ -1366,6 +1392,7 @@ fn build_native_daemon_backend() -> Result { format!("NativeTransformerBackend/{name}"), model_label, tokenizer, + identity, )) } else if require_gpu { Err( @@ -1389,6 +1416,7 @@ fn build_native_daemon_backend() -> Result { .to_string(), model_label, tokenizer, + identity, )) } } @@ -1483,7 +1511,7 @@ pub async fn run_daemon_server() { watermark_blocks: 64, }; - let (weights, tensor_backend, backend_label, model_label, tokenizer) = + let (weights, tensor_backend, backend_label, model_label, tokenizer, identity) = match build_native_daemon_backend() { Ok(parts) => parts, Err(fatal) => { @@ -1550,6 +1578,10 @@ pub async fn run_daemon_server() { tokenizer.stop_token_ids() ); server.set_tokenizer(tokenizer); + if let Some(identity) = identity { + // The daemon's generation records name these digests (docs/DAEMON_GENERATION_RECORD.md). + server.set_model_identity(identity); + } // NEXT-PHASE-1 v4: one declared 1-token warm-up before serving. server.enable_warm_up(); } else { @@ -1932,6 +1964,44 @@ pub async fn handle_aegis_command() { mod tests { use super::*; + #[test] + fn model_identity_needs_real_weights_and_a_parsed_tokenizer() { + let loaded = DaemonModelManifest { + model_id: "m".into(), + label: "l".into(), + checkpoint_path: Some("/nonexistent/model.safetensors".into()), + tokenizer_path: Some("/nonexistent/tokenizer.json".into()), + fallback_reason: None, + model_sha256: Some("aa".into()), + tokenizer_sha256: Some("bb".into()), + }; + let id = model_identity(&loaded, true).expect("identity"); + assert_eq!( + (id.model_sha256.as_str(), id.tokenizer_sha256.as_str()), + ("aa", "bb") + ); + assert_eq!(id.model_path, "/nonexistent/model.safetensors"); + // No parsed tokenizer, no weights digest, or no tokenizer digest: no identity. + assert!(model_identity(&loaded, false).is_none()); + for strip in [0, 1] { + let mut m = DaemonModelManifest { + model_sha256: loaded.model_sha256.clone(), + tokenizer_sha256: loaded.tokenizer_sha256.clone(), + checkpoint_path: loaded.checkpoint_path.clone(), + tokenizer_path: loaded.tokenizer_path.clone(), + model_id: "m".into(), + label: "l".into(), + fallback_reason: None, + }; + if strip == 0 { + m.model_sha256 = None; + } else { + m.tokenizer_sha256 = None; + } + assert!(model_identity(&m, true).is_none()); + } + } + #[test] fn checkpoint_loaded_line_format_is_pinned() { // interplane#76 parses this line; the text must not drift. diff --git a/crates/aien-runtime/src/client.rs b/crates/aien-runtime/src/client.rs index 3edf9c96..0b5b8efd 100644 --- a/crates/aien-runtime/src/client.rs +++ b/crates/aien-runtime/src/client.rs @@ -134,6 +134,19 @@ impl AienRuntimeClient { max_tokens: usize, temperature: f32, ) -> Result { + self.stream_turn_recorded(messages, max_tokens, temperature) + .await + .map(|(text, _)| text) + } + + /// [`Self::stream_turn`] plus the compose ledger id of the daemon's + /// generation record for the turn (`None` = the daemon wrote no record). + pub async fn stream_turn_recorded( + &self, + messages: Vec, + max_tokens: usize, + temperature: f32, + ) -> Result<(String, Option), String> { let stream = UnixStream::connect(&self.socket_path).await.map_err(|e| { format!( "Failed to connect to AIEN runtime socket at {}: {}", @@ -185,11 +198,15 @@ impl AienRuntimeClient { .map_err(|e| format!("Failed to parse ControlResponse: {}", e))?; match response { ControlResponse::TurnDelta { text } => finished.push_str(&text), - ControlResponse::TurnFinished { text, .. } => { + ControlResponse::TurnFinished { + text, + generation_record, + .. + } => { if !text.is_empty() { - return Ok(text); + return Ok((text, generation_record)); } - return Ok(finished); + return Ok((finished, generation_record)); } ControlResponse::Error(error) => return Err(error), other => { @@ -203,7 +220,7 @@ impl AienRuntimeClient { if finished.is_empty() { Err("native runtime closed the socket before the turn finished".into()) } else { - Ok(finished) + Ok((finished, None)) } } diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index f1514667..230574b8 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -191,6 +191,11 @@ pub enum ControlResponse { TurnFinished { text: String, total_tokens: usize, + /// Compose ledger id of the daemon's generation record for this turn + /// (docs/DAEMON_GENERATION_RECORD.md). `None` = no record, no claim: + /// no ledger, no model identity, or the append failed. + #[serde(default, skip_serializing_if = "Option::is_none")] + generation_record: Option, }, /// Result record of `RunComposeTask`. ComposeTaskResult(Box), diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index dfed8963..ea4e2ef0 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -699,6 +699,12 @@ pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { // sovereign-core #261: no caller writes an authorization, whatever it // says. Grants come from ComposeAuthorize and ComposeApprovedProposal, // control records from ComposeControl; all are written by the daemon. + if kind == crate::generation::GENERATION { + return Err( + "ComposeNote: generation records are written only by the daemon when a turn finishes" + .into(), + ); + } if kind == "authorization" { return Err( "ComposeNote: authorization records are written only by the daemon (ComposeAuthorize, ComposeApprovedProposal, ComposeControl); a caller-written grant is never honoured (sovereign-core #261)" @@ -709,6 +715,12 @@ pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { return Ok(()); }; match kind { + // The daemon's generation record (evidence only, never an input to any + // decision): effect-class note with the marker field. + "effect" if v.get(crate::generation::GENERATION).is_some() => Err( + "ComposeNote: generation records are written only by the daemon when a turn finishes" + .into(), + ), "effect" if v.get("phase").is_some() => Err( "ComposeNote: effect records with a \"phase\" are written only by the effect commands" .into(), @@ -1083,7 +1095,7 @@ fn ledger(home: &mut ComposeHome) -> Result { Ledger::from_records(&host_views(home)?).map_err(|r| r.to_string()) } -fn append( +pub(crate) fn append( home: &mut ComposeHome, kind: NoteKind, links: &[u64], @@ -1497,6 +1509,67 @@ mod tests { .name } + /// A real daemon-built generation record, as a ledger row. + fn generation_row(id: u64) -> ComposeRecordView { + let identity = crate::generation::ModelIdentity { + model_sha256: "m".repeat(64), + model_path: "/models/m.safetensors".into(), + tokenizer_sha256: "t".repeat(64), + tokenizer_path: "/models/tokenizer.json".into(), + }; + let record = crate::generation::build_record( + &identity, + &crate::generation::TurnEvidence { + prompt_ids: &[1, 2, 3], + output_ids: &[100, 101], + text: "x100 x101", + total_tokens: 2, + finish_reason: "eos", + request_id: 7, + operation_id: 8, + }, + crate::generation::DaemonStart(1), + ); + rec(id, "effect", record) + } + + /// Evidence only: generation records, anywhere in the ledger, change no + /// ledger state and no authorization or intent decision. + #[test] + fn generation_records_change_no_decision() { + let base = vec![ + grant(2, Value::Null), + intent(3, 2), + settle(4, "ack", 3, "DONE"), + grant(5, Value::Null), + ]; + let mut with = base.clone(); + with.push(generation_row(6)); + with.push(generation_row(7)); + let (a, b) = ( + Ledger::from_records(&base).unwrap(), + Ledger::from_records(&with).unwrap(), + ); + assert_eq!(a.view(), b.view()); + assert_eq!(refusal(&a, 2, None), refusal(&b, 2, None)); + assert_eq!(refusal(&a, 2, None), "AlreadySpent"); + assert_eq!( + a.check_intent(&req(5), &None).map(|g| g.id), + b.check_intent(&req(5), &None).map(|g| g.id) + ); + // A generation record alone opens nothing and spends nothing. + let only = Ledger::from_records(&[generation_row(2)]).unwrap(); + assert_eq!(only.view(), Ledger::default().view()); + } + + #[test] + fn generation_records_cannot_be_forged_through_compose_note() { + let g = r#"{"generation":1,"model_sha256":"x"}"#; + assert!(check_reserved_note("effect", g).is_err()); + assert!(check_reserved_note("generation", "anything").is_err()); + assert!(check_reserved_note("generation", g).is_err()); + } + #[test] fn fresh_grant_opens_once() { let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); diff --git a/crates/aien-runtime/src/generation.rs b/crates/aien-runtime/src/generation.rs new file mode 100644 index 00000000..e04831ea --- /dev/null +++ b/crates/aien-runtime/src/generation.rs @@ -0,0 +1,91 @@ +//! The daemon's generation record: evidence that THIS daemon generated THIS +//! text from the model file it loaded (INTERPLANE provenance, interplane#76). +//! +//! Written by the daemon when a `StreamTurn` finishes, into the compose +//! ledger, as an `effect`-class host note carrying the marker field +//! [`GENERATION`]. EVIDENCE ONLY: no grant, intent, replay, commit or effect +//! decision reads it (`effects::Ledger` skips it: it has neither a `phase` nor a +//! `tool` field). `ComposeNote` refuses to write one (`check_reserved_note`), +//! so only the daemon can. It claims nothing about capability or authority. + +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +/// Marker field (and refused `ComposeNote` kind) of the generation record. +pub const GENERATION: &str = "generation"; + +/// The model files the daemon loaded, hashed once at load time. +/// `model_sha256` is the sha256 of the single safetensors file's bytes +/// (streamed, 1 MiB chunks); `tokenizer_sha256` that of the tokenizer file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModelIdentity { + pub model_sha256: String, + pub model_path: String, + pub tokenizer_sha256: String, + pub tokenizer_path: String, +} + +/// What one finished turn contributes to its record. +pub struct TurnEvidence<'a> { + pub prompt_ids: &'a [u32], + pub output_ids: &'a [u32], + /// The exact text returned in `TurnFinished`. + pub text: &'a str, + pub total_tokens: usize, + pub finish_reason: &'a str, + /// Caller-supplied envelope ids (self-asserted by the client, no authority). + pub request_id: u64, + pub operation_id: u128, +} + +/// When this daemon started: unix milliseconds, captured once. +#[derive(Debug, Clone, Copy)] +pub struct DaemonStart(pub u128); + +impl DaemonStart { + pub fn now() -> Self { + Self( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0), + ) + } +} + +fn hex_sha256(bytes: &[u8]) -> String { + aien_omega_compose::hex(&Sha256::digest(bytes)) +} + +/// The record's JSON body (field list is documented in docs/DAEMON_GENERATION_RECORD.md). +pub fn build_record(id: &ModelIdentity, t: &TurnEvidence, start: DaemonStart) -> Value { + let (pid, start_ticks) = crate::effects::self_executor(); + json!({ + GENERATION: 1, + "v": 1, + "model_sha256": id.model_sha256, + "model_path": id.model_path, + "tokenizer_sha256": id.tokenizer_sha256, + "tokenizer_path": id.tokenizer_path, + "prompt_ids_sha256": crate::spine::token_ids_sha256(t.prompt_ids), + "output_token_ids_sha256": crate::spine::token_ids_sha256(t.output_ids), + "output_text_sha256": hex_sha256(t.text.as_bytes()), + "total_tokens": t.total_tokens, + "output_tokens": t.output_ids.len(), + "finish_reason": t.finish_reason, + "daemon": {"pid": pid, "start_ticks": start_ticks, "started_unix_ms": start.0.to_string()}, + // Caller-asserted: the client chooses the envelope ids; recorded, not trusted. + "request_id": t.request_id, + "operation_id": t.operation_id.to_string(), + }) +} + +/// Why an `effect`-class note carrying a `generation` marker, and not a new +/// note kind: omega-compose's `NoteKind` enum (constraint, authorization, +/// effect) is a pinned external dependency with fixed kinds, so this crate +/// cannot add one. The marker field plays the role of a kind: `ComposeNote` +/// refuses it and no ledger reader acts on it. +/// Append `record` to the ledger; the id is returned only once it is written. +pub(crate) fn write(home: &mut crate::spine::ComposeHome, record: &Value) -> Result { + crate::effects::append(home, aien_omega_compose::NoteKind::Effect, &[], record).map(|n| n.id) +} diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index f0973f0f..bce6f4e3 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -9,6 +9,7 @@ pub mod control; pub mod cortex_mark; pub mod destination; pub mod effects; +pub mod generation; pub mod requirements; mod requirements_extract; pub mod rsi; diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 4d6c559f..35a79d32 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -2,6 +2,7 @@ //! Exposes typed control RPC over local IPC to operator CLI tools. use crate::control::{ControlCommand, ControlEnvelope, ControlResponse}; +use crate::generation::{DaemonStart, ModelIdentity, TurnEvidence}; use crate::spine::{compose_dir_from_env, AienRuntimeSpine, ComposeBridge, ComposeProposer}; use aien_inference_abi::{AienInferenceBackend, ChatTokenizer, SamplingParams}; use aien_scheduler::{ChannelCompletionSink, CompletionEvent}; @@ -30,6 +31,10 @@ pub struct AienRuntimeServer { warm_up: AtomicBool, /// Test seam: a ready-made compose bridge (see `with_compose_bridge`). compose_override: std::sync::Mutex>>, + /// The loaded model files' digests (set by the daemon after load; absent + /// = no generation record, see crate::generation). + identity: std::sync::Mutex>>, + started: DaemonStart, } /// NEXT-PHASE-1 v4 declared warm-up prompt (ACCEPTANCE-v4 Section 2(2)): @@ -55,6 +60,8 @@ impl AienRuntimeServer { tokenizer: Arc::new(RwLock::new(None)), warm_up: AtomicBool::new(false), compose_override: std::sync::Mutex::new(None), + identity: std::sync::Mutex::new(None), + started: DaemonStart::now(), } } @@ -68,6 +75,12 @@ impl AienRuntimeServer { self } + /// Installs the digests of the model and tokenizer files the daemon loaded. + /// Without them (stub or reference weights) no generation record is written. + pub fn set_model_identity(&self, identity: ModelIdentity) { + *self.identity.lock().expect("identity lock") = Some(Arc::new(identity)); + } + /// Installs the tokenizer that `StreamTurn` uses to encode prompts and decode tokens. pub fn set_tokenizer(&self, tokenizer: ChatTokenizer) { *self.tokenizer.write().expect("tokenizer lock") = Some(tokenizer); @@ -188,6 +201,7 @@ impl AienRuntimeServer { .lock() .expect("compose override") .clone(); + let identity = self.identity.lock().expect("identity lock").clone(); let compose = match compose_dir_from_env() { _ if preset.is_some() => preset, Ok(dir) => Some(Arc::new( @@ -277,6 +291,8 @@ impl AienRuntimeServer { let tokenizer_conn = self.tokenizer.clone(); let compose_conn = compose.clone(); + let identity_conn = identity.clone(); + let started = self.started; tokio::spawn(async move { handle_connection( stream, @@ -285,6 +301,7 @@ impl AienRuntimeServer { notify_conn, tokenizer_conn, compose_conn, + (identity_conn, started), ) .await; }); @@ -562,6 +579,70 @@ fn proposer_with_cap( }) } +/// What a turn needs to write its generation record. +struct RecordCtx { + compose: Option>, + identity: Option>, + started: DaemonStart, + request_id: u64, + operation_id: u128, +} + +/// Owned inputs of one finished turn's generation record. +struct GenerationOwned { + prompt_ids: Vec, + output_ids: Vec, + text: String, + total_tokens: usize, + finish_reason: &'static str, + request_id: u64, + operation_id: u128, +} + +/// Write the daemon's generation record for a finished turn and return its +/// ledger id. `None` when there is no compose ledger or no model identity (a +/// stub or reference-weights run), or when the append failed; the failure is +/// logged and the turn still succeeds, but an id is returned only for a record +/// that was written. +async fn record_generation( + compose: Option>, + identity: Option>, + started: DaemonStart, + g: GenerationOwned, +) -> Option { + let (bridge, identity) = (compose?, identity?); + let written = tokio::task::spawn_blocking(move || { + let record = crate::generation::build_record( + &identity, + &TurnEvidence { + prompt_ids: &g.prompt_ids, + output_ids: &g.output_ids, + text: &g.text, + total_tokens: g.total_tokens, + finish_reason: g.finish_reason, + request_id: g.request_id, + operation_id: g.operation_id, + }, + started, + ); + bridge.record_generation(&record) + }) + .await; + match written { + Ok(Ok(id)) => Some(id), + Ok(Err(e)) => { + tracing::warn!("generation record not written: {e}"); + eprintln!("generation record not written: {e}"); + None + } + Err(e) => { + tracing::warn!("generation record task failed: {e}"); + eprintln!("generation record task failed: {e}"); + None + } + } +} + async fn stream_turn( writer: &mut tokio::net::unix::OwnedWriteHalf, spine: Arc>, @@ -569,8 +650,16 @@ async fn stream_turn( messages: Vec, max_tokens: usize, temperature: f32, + rec: RecordCtx, ) { - let (tokenizer, mut events, _prompt_ids) = + let RecordCtx { + compose, + identity, + started, + request_id, + operation_id, + } = rec; + let (tokenizer, mut events, prompt_ids) = match submit_turn(spine, tokenizer, messages, max_tokens, temperature, "").await { Ok(x) => x, Err(error) => { @@ -599,10 +688,33 @@ async fn stream_turn( return; } } - Ok(Some(CompletionEvent::Finished { total_tokens, .. })) => { + Ok(Some(CompletionEvent::Finished { + total_tokens, + finish_reason, + .. + })) => { + let generation_record = record_generation( + compose, + identity, + started, + GenerationOwned { + prompt_ids, + output_ids: produced, + text: text.clone(), + total_tokens, + finish_reason: finish_reason_label(&finish_reason), + request_id, + operation_id, + }, + ) + .await; let _ = write_response( writer, - &ControlResponse::TurnFinished { text, total_tokens }, + &ControlResponse::TurnFinished { + text, + total_tokens, + generation_record, + }, ) .await; return; @@ -632,6 +744,7 @@ async fn handle_connection( shutdown_notify: Arc, tokenizer: Arc>>, compose: Option>, + (identity, started): (Option>, DaemonStart), ) { let (reader, mut writer) = stream.into_split(); let mut buf_reader = BufReader::new(reader); @@ -677,6 +790,13 @@ async fn handle_connection( messages, max_tokens, temperature, + RecordCtx { + compose: compose.clone(), + identity: identity.clone(), + started, + request_id: envelope.request_id, + operation_id: envelope.operation_id, + }, ) .await; line.clear(); @@ -822,3 +942,68 @@ async fn handle_connection( line.clear(); } } + +#[cfg(test)] +mod generation_record_tests { + use super::*; + + fn identity() -> Arc { + Arc::new(ModelIdentity { + model_sha256: "a".repeat(64), + model_path: "/m/model.safetensors".into(), + tokenizer_sha256: "b".repeat(64), + tokenizer_path: "/m/tokenizer.json".into(), + }) + } + + fn turn() -> GenerationOwned { + GenerationOwned { + prompt_ids: vec![1, 2], + output_ids: vec![3], + text: "t".into(), + total_tokens: 1, + finish_reason: "eos", + request_id: 1, + operation_id: 1, + } + } + + fn bridge(dir: std::path::PathBuf) -> Arc { + let proposer: ComposeProposer = + Arc::new(|_p: &str, _l: std::time::Duration| Err("not used".to_string())); + Arc::new(ComposeBridge::new(dir, proposer, "test:generation-record")) + } + + #[tokio::test] + async fn no_ledger_means_no_record() { + let got = record_generation(None, Some(identity()), DaemonStart::now(), turn()).await; + assert_eq!(got, None); + } + + #[tokio::test] + async fn no_model_identity_means_no_record() { + let tmp = tempfile::tempdir().unwrap(); + let b = bridge(tmp.path().join("compose")); + let got = record_generation(Some(b), None, DaemonStart::now(), turn()).await; + assert_eq!(got, None); + // Nothing was opened or written. + assert!(!tmp.path().join("compose").exists()); + } + + /// A ledger that cannot be written (here: its directory is a regular + /// file, and in a stub build the engine is absent) yields no id. + #[tokio::test] + async fn a_failed_append_returns_no_id() { + let tmp = tempfile::tempdir().unwrap(); + let blocked = tmp.path().join("compose"); + std::fs::write(&blocked, b"not a directory").unwrap(); + let got = record_generation( + Some(bridge(blocked)), + Some(identity()), + DaemonStart::now(), + turn(), + ) + .await; + assert_eq!(got, None); + } +} diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 37001f64..69663a8d 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -2129,6 +2129,12 @@ impl ComposeBridge { }) } + /// Append the daemon's generation record (evidence only; see + /// `crate::generation`). Returns the record id only once it is written. + pub fn record_generation(&self, record: &serde_json::Value) -> Result { + self.with_home(|home| crate::generation::write(home, record)) + } + pub(crate) fn with_home( &self, f: impl FnOnce(&mut ComposeHome) -> Result, diff --git a/crates/aien-runtime/tests/generation_record_test.rs b/crates/aien-runtime/tests/generation_record_test.rs new file mode 100644 index 00000000..b277bb62 --- /dev/null +++ b/crates/aien-runtime/tests/generation_record_test.rs @@ -0,0 +1,314 @@ +//! The daemon's generation record (docs/DAEMON_GENERATION_RECORD.md): evidence +//! that this daemon generated this text from the model files it loaded. +//! Socket-level, mock backend, toy tokenizer. Every test needs the linked +//! composition archive and is IGNORED in a stub build, never passed (the +//! no-record cases that hold in a stub build are unit tests in server.rs). +use aien_inference_abi::{ChatTokenizer, MockInferenceBackend}; +use aien_kv_cache::create_shared_kv_manager; +use aien_omega_compose::hex; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use aien_runtime::generation::ModelIdentity; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::{token_ids_sha256, AienRuntimeSpine, ComposeBridge, ComposeProposer}; +use aien_runtime::{format_chat, ChatTurn}; +use aien_scheduler::SchedulerConfig; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::sync::Arc; +use std::time::Duration; + +/// The composition engine holds one home at a time per process. +static ONE_HOME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +fn toy_tokenizer() -> ChatTokenizer { + toy_tokenizer_with(r#""x100":100,"x101":101"#) +} + +/// The toy vocabulary with the spelling of the two mock tokens chosen by the test. +fn toy_tokenizer_with(mock_tokens: &str) -> ChatTokenizer { + let json = r#"{"version":"1.0","truncation":null,"padding":null,"added_tokens":[], + "normalizer":null,"pre_tokenizer":{"type":"Whitespace"},"post_processor":null, + "decoder":null,"model":{"type":"WordLevel","unk_token":"","vocab":{ + "":0,"":1,"":2,"hello":6,MOCK}}}"# + .replace("MOCK", mock_tokens); + ChatTokenizer::from_bytes(json.as_bytes()).expect("toy tokenizer") +} + +fn identity() -> ModelIdentity { + ModelIdentity { + model_sha256: "ab".repeat(32), + model_path: "/models/toy/model.safetensors".into(), + tokenizer_sha256: "cd".repeat(32), + tokenizer_path: "/models/toy/tokenizer.json".into(), + } +} + +fn user(content: &str) -> Vec { + vec![ChatTurn { + role: "user".into(), + content: content.into(), + }] +} + +struct Daemon { + client: AienRuntimeClient, + handle: tokio::task::JoinHandle>, + _tmp: tempfile::TempDir, +} + +async fn start(identity: Option) -> Daemon { + start_with(identity, toy_tokenizer()).await +} + +async fn start_with(identity: Option, tokenizer: ChatTokenizer) -> Daemon { + let tmp = tempfile::tempdir().unwrap(); + let socket = tmp.path().join("runtime.sock"); + let cfg = SchedulerConfig { + max_batch_size: 8, + max_batch_tokens: 1024, + prefill_chunk_size: 64, + watermark_blocks: 4, + chunk_prefill: true, + max_prefill_tokens: 1024, + }; + let spine = AienRuntimeSpine::new(64, cfg, create_shared_kv_manager(256, 16)); + let proposer: ComposeProposer = + Arc::new(|_p: &str, _l: Duration| Err("not used in this test".to_string())); + let bridge = Arc::new(ComposeBridge::new( + tmp.path().join("compose"), + proposer, + "test:generation-record", + )); + let server = AienRuntimeServer::new(spine, &socket).with_compose_bridge(bridge); + server.set_tokenizer(tokenizer); + if let Some(id) = identity { + server.set_model_identity(id); + } + let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let client = AienRuntimeClient::new(&socket); + for _ in 0..200 { + if client.is_alive().await { + return Daemon { + client, + handle, + _tmp: tmp, + }; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("daemon did not come up"); +} + +impl Daemon { + async fn turn(&self, content: &str) -> (String, Option) { + self.client + .stream_turn_recorded(user(content), 4, 0.0) + .await + .expect("turn") + } + + async fn records(&self) -> u64 { + match self.recall(vec![]).await { + ControlResponse::ComposeRecalled(r) => r.records_total, + other => panic!("recall: {other:?}"), + } + } + + async fn recall(&self, ids: Vec) -> ControlResponse { + self.client + .send_command(ControlCommand::ComposeRecall { ids, prefix: None }) + .await + .unwrap() + } + + async fn record(&self, id: u64) -> Value { + match self.recall(vec![id]).await { + ControlResponse::ComposeRecalled(r) => { + assert_eq!(r.cited.len(), 1, "record {id} missing"); + assert!(r.cited[0].verified, "record {id} digest does not verify"); + assert_eq!(r.cited[0].note.as_deref(), Some("effect")); + serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap() + } + other => panic!("recall: {other:?}"), + } + } + + async fn note(&self, kind: &str, text: &str) -> ControlResponse { + self.client + .send_command(ControlCommand::ComposeNote { + kind: kind.into(), + text: text.into(), + links: vec![], + }) + .await + .unwrap() + } + + async fn stop(self) { + let _ = self.client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), self.handle).await; + } +} + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +/// The mock backend only emits tokens 100 and 101, which the toy vocabulary +/// spells x100 and x101. +fn ids_of(text: &str) -> Vec { + text.split_whitespace() + .map(|w| match w { + "x100" => 100, + "x101" => 101, + other => panic!("unexpected word {other:?} in {text:?}"), + }) + .collect() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn record_carries_the_digests_of_the_turn() { + let _g = ONE_HOME.lock().await; + let d = start(Some(identity())).await; + let tok = toy_tokenizer(); + let prompt = tok + .encode(&format_chat(tok.template(), &user("hello hello"))) + .unwrap(); + let (text, id) = d.turn("hello hello").await; + assert!(!text.is_empty()); + let id = id.expect("a record id"); + let r = d.record(id).await; + let want = identity(); + assert_eq!(r["generation"], 1); + assert_eq!(r["v"], 1); + assert_eq!(r["model_sha256"], want.model_sha256); + assert_eq!(r["model_path"], want.model_path); + assert_eq!(r["tokenizer_sha256"], want.tokenizer_sha256); + assert_eq!(r["tokenizer_path"], want.tokenizer_path); + assert_eq!(r["prompt_ids_sha256"], token_ids_sha256(&prompt)); + // The digest of the exact text TurnFinished returned. + assert_eq!(r["output_text_sha256"], sha(text.as_bytes())); + let out = ids_of(&text); + assert_eq!(r["output_token_ids_sha256"], token_ids_sha256(&out)); + assert_eq!(r["output_tokens"], out.len()); + assert!(r["total_tokens"].as_u64().unwrap() > 0); + assert!(matches!( + r["finish_reason"].as_str(), + Some("eos" | "max_tokens") + )); + assert_eq!(r["daemon"]["pid"], std::process::id()); + assert!(r["daemon"]["started_unix_ms"].as_str().unwrap().len() > 8); + // The envelope ids are the client's own, recorded as asserted. + assert!(r["request_id"].as_u64().unwrap() > 0); + assert!(r["operation_id"].as_str().unwrap().len() > 3); + d.stop().await; +} + +/// The record hashes the text exactly as returned, whitespace included (a +/// `trim()` before hashing would break the match with what the client holds). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn text_is_hashed_byte_exact_with_surrounding_whitespace() { + let _g = ONE_HOME.lock().await; + // Decoded text of the mock tokens: leading and trailing spaces. + let d = start_with( + Some(identity()), + toy_tokenizer_with(r#"" x100 ":100,"x101 ":101"#), + ) + .await; + let (text, id) = d.turn("hello").await; + assert_ne!( + text, + text.trim(), + "test needs surrounding whitespace: {text:?}" + ); + let r = d.record(id.expect("a record id")).await; + assert_eq!(r["output_text_sha256"], sha(text.as_bytes())); + assert_ne!(r["output_text_sha256"], sha(text.trim().as_bytes())); + d.stop().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn two_identical_turns_make_two_records() { + let _g = ONE_HOME.lock().await; + let d = start(Some(identity())).await; + let (t1, a) = d.turn("hello").await; + let (t2, b) = d.turn("hello").await; + let (a, b) = (a.expect("first record"), b.expect("second record")); + assert_ne!(a, b, "one record per turn"); + assert_eq!(t1, t2); + let (ra, rb) = (d.record(a).await, d.record(b).await); + assert_eq!(ra["output_text_sha256"], rb["output_text_sha256"]); + assert_eq!(ra["prompt_ids_sha256"], rb["prompt_ids_sha256"]); + d.stop().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn no_model_identity_means_no_record_and_the_turn_succeeds() { + let _g = ONE_HOME.lock().await; + let d = start(None).await; + let before = d.records().await; + let (text, id) = d.turn("hello").await; + assert!(!text.is_empty()); + assert_eq!(id, None); + assert_eq!(d.records().await, before, "nothing was written"); + d.stop().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn a_caller_cannot_write_a_generation_record() { + let _g = ONE_HOME.lock().await; + let d = start(Some(identity())).await; + let (_, id) = d.turn("hello").await; + assert!(id.is_some()); + let before = d.records().await; + let forged = r#"{"generation":1,"v":1,"model_sha256":"00","output_text_sha256":"00"}"#; + for (kind, text) in [ + ("generation", forged), + ("generation", "plain text"), + ("effect", forged), + ] { + match d.note(kind, text).await { + ControlResponse::Error(e) => assert!(e.contains("generation"), "{kind}: {e}"), + other => panic!("FORGED generation record accepted ({kind}): {other:?}"), + } + } + assert_eq!(d.records().await, before, "ledger count unchanged"); + d.stop().await; +} + +#[test] +fn turn_finished_without_a_record_serializes_as_before() { + // Older clients and servers: the field is absent when there is no record. + let none = ControlResponse::TurnFinished { + text: "x".into(), + total_tokens: 1, + generation_record: None, + }; + assert_eq!( + serde_json::to_string(&none).unwrap(), + r#"{"TurnFinished":{"text":"x","total_tokens":1}}"# + ); + let old: ControlResponse = + serde_json::from_str(r#"{"TurnFinished":{"text":"x","total_tokens":1}}"#).unwrap(); + assert!(matches!( + old, + ControlResponse::TurnFinished { + generation_record: None, + .. + } + )); + let some = ControlResponse::TurnFinished { + text: "x".into(), + total_tokens: 1, + generation_record: Some(9), + }; + assert!(serde_json::to_string(&some) + .unwrap() + .contains(r#""generation_record":9"#)); +} diff --git a/docs/DAEMON_GENERATION_RECORD.md b/docs/DAEMON_GENERATION_RECORD.md new file mode 100644 index 00000000..d793ca68 --- /dev/null +++ b/docs/DAEMON_GENERATION_RECORD.md @@ -0,0 +1,92 @@ +# Daemon generation record + +Evidence that this daemon generated a piece of text from the model files it +loaded. It exists so a provenance chain (INTERPLANE, interplane#76) does not +have to take the run driver's word for "this text came from this model". + +## What the daemon does + +1. At start, after the model loads, the CLI holds the sha256 of the model file + (the single safetensors file, streamed in 1 MiB chunks, hashed once) and of + the tokenizer file, with the path each came from. The daemon passes both to + the server (`set_model_identity`). The same digests are in the + "checkpoint loaded" log line. +2. When a `StreamTurn` finishes, and the compose ledger is open, the daemon + appends one record to the ledger and returns its id in + `TurnFinished.generation_record` (optional field; absent when there is no + record, so older clients keep working). + +## The record + +An `effect`-class host note whose JSON has the marker field `generation`: + +| field | meaning | +|---|---| +| `generation`, `v` | marker (1) and record version (1) | +| `model_sha256`, `model_path` | the loaded weights file's digest and canonical path | +| `tokenizer_sha256`, `tokenizer_path` | the loaded tokenizer file's digest and path | +| `prompt_ids_sha256` | `token_ids_sha256` of the submitted prompt token ids | +| `output_token_ids_sha256` | same hash over the generated token ids | +| `output_text_sha256` | sha256 of the exact `text` returned in `TurnFinished` | +| `total_tokens`, `output_tokens` | token count the engine reported; generated tokens | +| `finish_reason` | `eos`, `max_tokens`, `aborted` or `preempted` | +| `daemon` | `pid`, `start_ticks` (process start, clock ticks) and `started_unix_ms` | +| `request_id`, `operation_id` | CALLER-ASSERTED: the request envelope's ids, exactly as the client sent them | + +The envelope ids are chosen by the client. They are recorded, not trusted (names kept to match the envelope fields). + +## What it proves + +The daemon process with that pid and start time generated text with that +digest, from prompt ids and output ids with those digests, while it held model +and tokenizer files with those digests. The record sits in the compose ledger, whose records carry digests the engine +re-checks on every read (`verified`), so an edited record is detected rather than +silently accepted. + +## What it does not prove + +- No capability, permission or authority. Nothing reads this record: no grant, + intent, replay, commit or effect decision depends on it + (`effects::generation_records_change_no_decision`). +- Not that the digest is of the very bytes the loader parsed. The CLI hashes the + model and tokenizer files at load, and the loaders then open the same paths + again (the weights loader and tokenizer loader take paths, not bytes). The + digest is of the file read at load time; a swap between the hash and the load + is not detected. +- Not that the file on disk still has that digest later, only what was loaded. +- Not signed. The ledger's per-record digest detects edits to a record, not a + forged append: a process of the same user that can append to the compose + ledger could append a record that passes the digest check. Only the daemon + writes one through the socket (ComposeNote refuses it), but the file is not + protected against that user. +- Not that the text is correct, safe or what an operator approved. +- A caller cannot write one: `ComposeNote` refuses kind `generation` and any + `effect` note carrying the `generation` field. + +## Verifier guidance + +Parse the note text strictly as one JSON object, require the top-level +`generation` marker (value 1) and `v` 1, require the record's links to be empty, +and compare the digests to the files and text you hold. Treat request_id and +operation_id as the client's claims. + +## Timing + +The record is written before `TurnFinished` is sent, and the write waits for +the compose home lock. A running compose task holds that lock, so a turn that +finishes meanwhile can have its `TurnFinished` delayed until the task releases +it. There is no deadlock: the compose task's own model calls (`generate_text`) +write no record and take no home lock. + +## No record means no claim + +The turn still succeeds, with `generation_record` absent, when: + +- there is no compose ledger; +- the daemon has no model identity (a stub run, or the reference-weights + fallback, or a tokenizer that did not load); +- the ledger append failed. The failure is logged + (`generation record not written`); an id is never returned for a record that + was not written. + +A verifier must treat an absent record as an absent claim, not as a pass. ```