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 / src / generation.rs

407 lines · 16997 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: evidence that THIS daemon generated THIS
17//! text from the model file it loaded (INTERPLANE provenance, interplane#76).
18//!
19//! Written by the daemon when a `StreamTurn` finishes, into the compose
20//! ledger, as an `effect`-class host note carrying the marker field
21//! [`GENERATION`]. EVIDENCE ONLY: no grant, intent, replay, commit or effect
22//! decision reads it (`effects::Ledger` skips it: it has neither a `phase` nor a
23//! `tool` field). `ComposeNote` refuses to write one (`check_reserved_note`),
24//! so only the daemon can. It claims nothing about capability or authority.
25
26use serde_json::{json, Value};
27use sha2::{Digest, Sha256};
28
29/// Marker field (and refused `ComposeNote` kind) of the generation record.
30pub const GENERATION: &str = "generation";
31
32/// The model files the daemon loaded, hashed once at load time (streamed,
33/// 1 MiB chunks). `model_sha256` is the digest of what was loaded, in the form
34/// `model_digest_kind` names: `file` (the single safetensors file's sha256) or
35/// `index+shards` (sc#338: the manifest digest over the shard index and every
36/// shard it names; docs/DAEMON_GENERATION_RECORD.md). `tokenizer_sha256` is the
37/// tokenizer file's sha256.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct ModelIdentity {
40 pub model_sha256: String,
41 pub model_digest_kind: String,
42 pub model_path: String,
43 pub tokenizer_sha256: String,
44 pub tokenizer_path: String,
45}
46
47/// What one finished turn contributes to its record.
48pub struct TurnEvidence<'a> {
49 pub prompt_ids: &'a [u32],
50 pub output_ids: &'a [u32],
51 /// The exact text returned in `TurnFinished`.
52 pub text: &'a str,
53 pub total_tokens: usize,
54 pub finish_reason: &'a str,
55 /// Caller-supplied envelope ids (self-asserted by the client, no authority).
56 pub request_id: u64,
57 pub operation_id: u128,
58 /// How the backend chose the output tokens (sc#294); None: no claim.
59 pub decoding: Option<&'a aien_abi_core::DecodeObservation>,
60 /// The tensor backend and its op counters when the call finished (sc#337); None: no claim.
61 pub ops: Option<&'a aien_abi_core::OpEvidence>,
62}
63
64/// When this daemon started: unix milliseconds, captured once.
65#[derive(Debug, Clone, Copy)]
66pub struct DaemonStart(pub u128);
67
68impl DaemonStart {
69 pub fn now() -> Self {
70 Self(
71 std::time::SystemTime::now()
72 .duration_since(std::time::UNIX_EPOCH)
73 .map(|d| d.as_millis())
74 .unwrap_or(0),
75 )
76 }
77}
78
79fn hex_sha256(bytes: &[u8]) -> String {
80 aien_omega_compose::hex(&Sha256::digest(bytes))
81}
82
83/// An f32 setting as the JSON number it was written as (0.7, not 0.699999988).
84fn f32_number(v: f32) -> Value {
85 v.to_string()
86 .parse::<f64>()
87 .ok()
88 .and_then(serde_json::Number::from_f64)
89 .map_or(Value::Null, Value::Number)
90}
91
92/// Adds `decoding` (sc#294): how the backend chose the output tokens, counted
93/// in the sampling branch it took, not read from the request's settings. The
94/// field is left out when nothing observed it (a stub or a backend without the
95/// observation): no field means no claim, never "greedy".
96fn with_decoding(record: &mut Value, d: Option<&aien_abi_core::DecodeObservation>) {
97 let Some(d) = d else { return };
98 let mut o = json!({
99 "mode": d.mode(),
100 "greedy_tokens": d.greedy_tokens,
101 "sampled_tokens": d.sampled_tokens,
102 });
103 if let Some(t) = d.temperature {
104 o["temperature"] = f32_number(t);
105 }
106 if let Some(p) = d.top_p {
107 o["top_p"] = f32_number(p);
108 }
109 if let Some(s) = d.seed_request_id {
110 o["seed_request_id"] = json!(s);
111 }
112 record["decoding"] = o;
113}
114
115/// Adds `ops` (sc#337): the tensor backend that ran the call and its op
116/// counters when the call finished, as process totals since the daemon built
117/// the backend (`native_fallbacks`: claimed-native ops that ran on the
118/// reference CPU path, always 0 in a production build, which panics on the
119/// first; `reference_runs`: ops on the reference path by design). Left out
120/// when the backend does not account its ops: no field means no claim.
121fn with_ops(record: &mut Value, o: Option<&aien_abi_core::OpEvidence>) {
122 let Some(o) = o else { return };
123 record["ops"] = json!({
124 "backend": o.backend,
125 "native_fallbacks": o.native_fallbacks,
126 "reference_runs": o.reference_runs,
127 "scope": "process",
128 "report": o.report,
129 });
130 if let Some(n) = o.gpu_executions {
131 record["ops"]["gpu_executions"] = json!(n); // sc#402, process total like the rest
132 }
133}
134
135/// The line the daemon logs at the end of every model call (sc#337): the
136/// backend's `OP_REPORT ...` line with ` backend=<name>` appended and, after it,
137/// ` gpu_executions=<n>` when the backend counts chip calls (sc#402). None when
138/// the backend does not account its ops.
139///
140/// Layout contract (sc#384, 2026-10-11): the frozen OPEN-MODEL-QWEN3 v5 row
141/// `-OPR` parses `OP_REPORT native=[..] reference=[..] native_fallbacks=[..]
142/// reference_runs=[..] backend=<rest>` to the end of the line; any new field
143/// goes AFTER `backend=`, never between the bracketed fields and `backend=`.
144/// Putting `gpu_executions` before `backend=` (sc#405) made every v7 dry
145/// launch fail that row.
146pub fn op_report_line(o: Option<&aien_abi_core::OpEvidence>) -> Option<String> {
147 o.map(|o| match o.gpu_executions {
148 Some(n) => format!("{} backend={} gpu_executions={n}", o.report, o.backend),
149 None => format!("{} backend={}", o.report, o.backend),
150 })
151}
152
153/// The record's JSON body (field list is documented in docs/DAEMON_GENERATION_RECORD.md).
154pub fn build_record(id: &ModelIdentity, t: &TurnEvidence, start: DaemonStart) -> Value {
155 let (pid, start_ticks) = crate::effects::self_executor();
156 let mut record = json!({
157 GENERATION: 1,
158 "v": 1,
159 "model_sha256": id.model_sha256,
160 "model_digest_kind": id.model_digest_kind,
161 "model_path": id.model_path,
162 "tokenizer_sha256": id.tokenizer_sha256,
163 "tokenizer_path": id.tokenizer_path,
164 "prompt_ids_sha256": crate::compose::token_ids_sha256(t.prompt_ids),
165 "output_token_ids_sha256": crate::compose::token_ids_sha256(t.output_ids),
166 "output_text_sha256": hex_sha256(t.text.as_bytes()),
167 "total_tokens": t.total_tokens,
168 "output_tokens": t.output_ids.len(),
169 "finish_reason": t.finish_reason,
170 "daemon": {"pid": pid, "start_ticks": start_ticks, "started_unix_ms": start.0.to_string()},
171 // Caller-asserted: the client chooses the envelope ids; recorded, not trusted.
172 "request_id": t.request_id,
173 "operation_id": t.operation_id.to_string(),
174 });
175 with_decoding(&mut record, t.decoding);
176 with_ops(&mut record, t.ops);
177 record
178}
179
180/// Why an `effect`-class note carrying a `generation` marker, and not a new
181/// note kind: omega-compose's `NoteKind` enum (constraint, authorization,
182/// effect) is a pinned external dependency with fixed kinds, so this crate
183/// cannot add one. The marker field plays the role of a kind: `ComposeNote`
184/// refuses it and no ledger reader acts on it.
185/// Append `record` to the ledger; the id is returned only once it is written.
186pub(crate) fn write(home: &mut crate::compose::ComposeHome, record: &Value) -> Result<u64, String> {
187 crate::effects::append(home, aien_omega_compose::NoteKind::Effect, &[], record).map(|n| n.id)
188}
189
190// ---------------------------------------------------------------------------
191// Provenance link: which generation produced a committed proposal, and which
192// ALLEN asked for it. EVIDENCE ONLY, like the generation record itself.
193// ---------------------------------------------------------------------------
194
195use crate::control::ComposeRecordView;
196
197/// Top-level field of the evidence the daemon copies along the chain
198/// compose-commit -> minted grant -> intent -> ack (and onto an approved
199/// grant). Reserved: `ComposeNote` refuses any note that carries it, and no
200/// ledger reader (`effects::Ledger`) parses it. Only [`Provenance::from_text`]
201/// does, and only `effects::stamp` calls that.
202pub const PROVENANCE: &str = "provenance";
203
204/// The `allen_agent` value when no ALLEN identity is attached to the daemon.
205pub const NO_AGENT: &str = "none";
206
207/// The evidence fields of the link.
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct Provenance {
210 /// Ledger id of the generation record of the attempt the committed
211 /// proposal came from. `None` when no record was written (no ledger, no
212 /// model identity, a proposer that does not expose token ids, an approved
213 /// proposal): an absent claim, not a pass.
214 pub generation_record: Option<u64>,
215 /// The ALLEN LogicalAgentId (64 hex, `aien_allen::Resolved::agent`) the
216 /// task ran under, or [`NO_AGENT`].
217 pub allen_agent: String,
218 /// Set when a copy found the source's generation id not naming a verified
219 /// generation record: the old id, kept visible. `generation_record` is then
220 /// null, and this marker tells that apart from "no model ran".
221 pub stale_generation: Option<u64>,
222 /// Why the evidence is degraded (`generation_record_stale`,
223 /// `allen_agent_malformed`, `provenance_malformed`), `;`-joined.
224 /// Absent on ordinary records.
225 pub note: Option<String>,
226}
227
228impl Default for Provenance {
229 fn default() -> Self {
230 Self {
231 generation_record: None,
232 allen_agent: NO_AGENT.to_string(),
233 stale_generation: None,
234 note: None,
235 }
236 }
237}
238
239impl Provenance {
240 pub fn new(generation_record: Option<u64>, allen: Option<&aien_allen::Resolved>) -> Self {
241 Self {
242 generation_record,
243 allen_agent: allen.map_or_else(|| NO_AGENT.to_string(), |r| aien_allen::hex(&r.agent)),
244 ..Self::default()
245 }
246 }
247
248 fn add_note(&mut self, n: &str) {
249 match &mut self.note {
250 Some(x) if x.split("; ").any(|y| y == n) => {}
251 Some(x) => {
252 x.push_str("; ");
253 x.push_str(n);
254 }
255 None => self.note = Some(n.to_string()),
256 }
257 }
258
259 pub fn to_json(&self) -> Value {
260 let mut v =
261 json!({"generation_record": self.generation_record, "allen_agent": self.allen_agent});
262 if let Some(s) = self.stale_generation {
263 v["generation_record_stale"] = json!(s);
264 }
265 if let Some(n) = &self.note {
266 v["provenance_note"] = json!(n);
267 }
268 v
269 }
270
271 /// Lenient read of a record's text, never an error. A record with no
272 /// provenance field at all (an old record) reads as the plain default.
273 /// A field that is present but damaged reads as the default values PLUS a
274 /// visible note, so it is never mistaken for "no model ran" / "no ALLEN".
275 pub fn from_text(text: &str) -> Self {
276 let Ok(v) = serde_json::from_str::<Value>(text) else {
277 return Self::default();
278 };
279 let Some(p) = v.get(PROVENANCE) else {
280 return Self::default();
281 };
282 let mut out = Self::default();
283 if !p.is_object() {
284 tracing::warn!("provenance field is not an object; copied as default with a note");
285 out.add_note("provenance_malformed");
286 return out;
287 }
288 match p.get("allen_agent").and_then(Value::as_str) {
289 Some(a)
290 if a == NO_AGENT
291 || (a.len() == 64
292 && a.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))) =>
293 {
294 out.allen_agent = a.to_string()
295 }
296 _ => {
297 tracing::warn!(
298 "provenance allen_agent is missing or malformed; copied as none with a note"
299 );
300 out.add_note("allen_agent_malformed");
301 }
302 }
303 out.generation_record = p.get("generation_record").and_then(Value::as_u64);
304 out.stale_generation = p.get("generation_record_stale").and_then(Value::as_u64);
305 // Carry an earlier note along the chain (bounded, printable ASCII only).
306 if let Some(n) = p.get("provenance_note").and_then(Value::as_str) {
307 let n: String = n
308 .chars()
309 .filter(|c| c.is_ascii_graphic() || *c == ' ')
310 .take(200)
311 .collect();
312 for part in n.split("; ").filter(|s| !s.is_empty()) {
313 out.add_note(part);
314 }
315 }
316 out
317 }
318}
319
320/// True when `id` names a verified `effect` note in `views` that is a
321/// generation record (marker 1, no links).
322pub fn generation_exists(views: &[ComposeRecordView], id: u64) -> bool {
323 views.iter().any(|r| {
324 r.id == id
325 && r.verified
326 && r.note.as_deref() == Some("effect")
327 && r.links.iter().all(|&l| l == 0)
328 && r.text
329 .as_deref()
330 .and_then(|t| serde_json::from_str::<Value>(t).ok())
331 .is_some_and(|v| v.get(GENERATION).and_then(Value::as_u64) == Some(1))
332 })
333}
334
335/// The provenance to copy from record `source` onto the next record of the
336/// chain. A generation id that does not name a real generation record is
337/// dropped (not refused): copying must not change any decision.
338pub fn inherit(views: &[ComposeRecordView], source: u64) -> Provenance {
339 let mut p = views
340 .iter()
341 .find(|r| r.id == source)
342 .and_then(|r| r.text.as_deref())
343 .map(Provenance::from_text)
344 .unwrap_or_default();
345 if let Some(g) = p.generation_record {
346 if !generation_exists(views, g) {
347 tracing::warn!(
348 "provenance names generation record #{g}, which is not a verified generation record; copied as null with a stale marker"
349 );
350 p.generation_record = None;
351 p.stale_generation = Some(g);
352 p.add_note("generation_record_stale");
353 }
354 }
355 p
356}
357
358/// What one compose proposal attempt contributes to its generation record.
359pub struct ComposeEvidence<'a> {
360 /// `token_ids_sha256` of the submitted prompt ids.
361 pub prompt_ids_sha256: &'a str,
362 pub prompt_tokens: usize,
363 pub output_ids: &'a [u32],
364 /// The reply text handed to the template parser (assistant prefix plus the
365 /// decoded generated tokens).
366 pub text: &'a str,
367 pub finish_reason: &'a str,
368 /// The compose task and attempt (1-based) that made the generation. Daemon-assigned.
369 pub task: u64,
370 pub attempt: u32,
371 /// How the backend chose the output tokens (sc#294); None: no claim.
372 pub decoding: Option<&'a aien_abi_core::DecodeObservation>,
373 /// The tensor backend and its op counters when the call finished (sc#337); None: no claim.
374 pub ops: Option<&'a aien_abi_core::OpEvidence>,
375}
376
377/// The generation record of one compose proposal attempt: the same fields as
378/// [`build_record`] plus `origin`, `task` and `attempt`. `request_id` and
379/// `operation_id` are 0: there is no client envelope for a model call the
380/// compose task makes itself.
381pub fn build_compose_record(id: &ModelIdentity, e: &ComposeEvidence, start: DaemonStart) -> Value {
382 let (pid, start_ticks) = crate::effects::self_executor();
383 let mut record = json!({
384 GENERATION: 1,
385 "v": 1,
386 "origin": "compose_proposal",
387 "task": e.task,
388 "attempt": e.attempt,
389 "model_sha256": id.model_sha256,
390 "model_digest_kind": id.model_digest_kind,
391 "model_path": id.model_path,
392 "tokenizer_sha256": id.tokenizer_sha256,
393 "tokenizer_path": id.tokenizer_path,
394 "prompt_ids_sha256": e.prompt_ids_sha256,
395 "output_token_ids_sha256": crate::compose::token_ids_sha256(e.output_ids),
396 "output_text_sha256": hex_sha256(e.text.as_bytes()),
397 "total_tokens": e.prompt_tokens + e.output_ids.len(),
398 "output_tokens": e.output_ids.len(),
399 "finish_reason": e.finish_reason,
400 "daemon": {"pid": pid, "start_ticks": start_ticks, "started_unix_ms": start.0.to_string()},
401 "request_id": 0,
402 "operation_id": "0",
403 });
404 with_decoding(&mut record, e.decoding);
405 with_ops(&mut record, e.ops);
406 record
407}