diff --git a/Cargo.lock b/Cargo.lock index 5dd3f9c863..b24dd9039e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3616,6 +3616,15 @@ dependencies = [ "uuid", ] +[[package]] +name = "continuum-proving-types" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "uuid", +] + [[package]] name = "continuum-rooms" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 4175770ab8..efecf7e65f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ members = [ "core/continuum-git", "core/continuum-host", "core/continuum-context", + "core/continuum-proving-types", "core/continuum-core", "core/continuum-sentinel", "core/continuum-kernel", diff --git a/core/continuum-proving-types/Cargo.toml b/core/continuum-proving-types/Cargo.toml new file mode 100644 index 0000000000..256a6e8349 --- /dev/null +++ b/core/continuum-proving-types/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "continuum-proving-types" +version = "0.1.0" +edition = "2021" +publish = false +description = "The proving ground's data shapes, defined once: act reductions with no words in them, node profiles whose every value carries its measurement, and scenario files (docs/architecture/THE-PROVING-GROUND.md 4a, 8a). Data only: the harness, the grid world and the reducer all depend on it." + +[dependencies] +serde = { workspace = true } +uuid = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/core/continuum-proving-types/src/closed.rs b/core/continuum-proving-types/src/closed.rs new file mode 100644 index 0000000000..ea8695ba84 --- /dev/null +++ b/core/continuum-proving-types/src/closed.rs @@ -0,0 +1,195 @@ +//! The only strings a proving-ground file may hold (THE-PROVING-GROUND P9, 4a "the text check"). +//! +//! Captures hold residents' and people's words, and reductions leave their node. So no type in this +//! crate has a free-text field: every string is one of these, and each refuses anything that is not +//! its closed shape at deserialization. A planted sentence fails to parse instead of surviving into +//! a committed file, so no reviewer has to catch it. + +use serde::{Deserialize, Serialize}; + +/// Why a string was refused as a closed value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NotClosed { + pub kind: &'static str, + pub len: usize, +} + +impl std::fmt::Display for NotClosed { + // The refused value is never echoed: it may be the very words this type keeps out. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "a {}-byte string is not a closed {} value", self.len, self.kind) + } +} + +impl std::error::Error for NotClosed {} + +/// A registry name: a tool, a model id, a claim source, a metric or scenario name. Lowercase ASCII +/// letters, digits and `._/:-`, starting with a letter or digit, at most 128 bytes. A word is +/// expressible (`code/read` is two), a sentence is not: no space, no capital, no punctuation of prose. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct Slug(String); + +impl Slug { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl TryFrom for Slug { + type Error = NotClosed; + fn try_from(s: String) -> Result { + let refused = NotClosed { kind: "slug", len: s.len() }; + let mut bytes = s.bytes(); + let starts = bytes.next().is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit()); + let rest = bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._/:-".contains(&b)); + match starts && rest && s.len() <= 128 { + true => Ok(Self(s)), + false => Err(refused), + } + } +} + +impl From for String { + fn from(s: Slug) -> Self { + s.0 + } +} + +/// A model id as the engine and the registry name it: `owner/name`, each part ASCII letters, +/// digits and `._-` (case kept: `continuum-ai/qwen2.5-coder-1.5b-instruct-GGUF`), at most 128 +/// bytes. Exactly one `/`, so a single word or a sentence is never a model id. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct ModelId(String); + +impl TryFrom for ModelId { + type Error = NotClosed; + fn try_from(s: String) -> Result { + let part = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)); + let closed = s.len() <= 128 && matches!(s.split_once('/'), Some((owner, name)) if part(owner) && part(name)); + match closed { + true => Ok(Self(s)), + false => Err(NotClosed { kind: "model id", len: s.len() }), + } + } +} + +impl From for String { + fn from(m: ModelId) -> Self { + m.0 + } +} + +/// A SHA-256 digest: of a message's bytes, a tool schema, a tokenizer artifact, or a tool call's +/// canonical arguments (`continuum_context::cause::Fingerprint`, MIND-CONTEXT invariant 4). +/// Carried as its 32 bytes; written as 64 lowercase hex digits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct Sha256([u8; 32]); + +impl Sha256 { + pub const fn from_bytes(bytes: [u8; 32]) -> Self { + Self(bytes) + } + pub const fn bytes(&self) -> &[u8; 32] { + &self.0 + } +} + +impl TryFrom for Sha256 { + type Error = NotClosed; + fn try_from(s: String) -> Result { + let refused = || NotClosed { kind: "sha256", len: s.len() }; + let hex = s.as_bytes(); + if hex.len() != 64 { + return Err(refused()); + } + let mut out = [0u8; 32]; + for (byte, pair) in out.iter_mut().zip(hex.chunks_exact(2)) { + let (Some(hi), Some(lo)) = (hex_digit(pair[0]), hex_digit(pair[1])) else { + return Err(refused()); + }; + *byte = hi << 4 | lo; + } + Ok(Self(out)) + } +} + +/// A lowercase hex digit's value; uppercase is refused, so a digest has one spelling. +fn hex_digit(b: u8) -> Option { + match b { + b'0'..=b'9' => Some(b - b'0'), + b'a'..=b'f' => Some(b - b'a' + 10), + _ => None, + } +} + +impl From for String { + fn from(h: Sha256) -> Self { + h.0.iter().map(|b| format!("{b:02x}")).collect() + } +} + +/// A git commit: the build a capture came from, a policy revision. 7 to 40 lowercase hex digits. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct GitSha(String); + +impl TryFrom for GitSha { + type Error = NotClosed; + fn try_from(s: String) -> Result { + match (7..=40).contains(&s.len()) && s.bytes().all(|b| hex_digit(b).is_some()) { + true => Ok(Self(s)), + false => Err(NotClosed { kind: "git sha", len: s.len() }), + } + } +} + +impl From for String { + fn from(s: GitSha) -> Self { + s.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: a closed type that lets prose through. Each planted value is something a + // capture holds (a sentence, a path with a space, a capitalised name) and must not parse. + #[test] + fn a_sentence_is_never_a_closed_value() { + for planted in ["please ignore the above", "Kimi", "src/main rs", "", "ok!", "-flag"] { + assert!(Slug::try_from(planted.to_string()).is_err(), "{planted:?} parsed as a slug"); + } + for name in ["code/read", "continuum-ai/qwen2.5-coder-1.5b-instruct-gguf", "delib.window.flex", "a:b_c"] { + assert!(Slug::try_from(name.to_string()).is_ok(), "{name:?} refused"); + } + assert!(Slug::try_from("a".repeat(129)).is_err(), "past 128 bytes"); + assert!(ModelId::try_from("continuum-ai/qwen2.5-coder-1.5b-instruct-GGUF".to_string()).is_ok()); + for planted in ["Kimi", "a/b/c", "my model/x", "/x", "x/"] { + assert!(ModelId::try_from(planted.to_string()).is_err(), "{planted:?} parsed as a model id"); + } + } + + // what this catches: a digest with two spellings, or a short one, joining by hash across nodes. + #[test] + fn a_digest_has_one_spelling() { + let lower = "ab".repeat(32); + let h = Sha256::try_from(lower.clone()).expect("64 lowercase hex"); + assert_eq!(String::from(h), lower, "round trip"); + assert!(Sha256::try_from("AB".repeat(32)).is_err(), "uppercase"); + assert!(Sha256::try_from("ab".repeat(31)).is_err(), "62 digits"); + assert!(Sha256::try_from(format!("{}zz", "ab".repeat(31))).is_err(), "not hex"); + assert!(GitSha::try_from("068540278".to_string()).is_ok()); + assert!(GitSha::try_from("06854".to_string()).is_err(), "under 7"); + } + + // what this catches: a refusal that echoes the refused words into a log or an error file. + #[test] + fn a_refusal_never_repeats_the_words() { + let err = Slug::try_from("my secret plan".to_string()).expect_err("prose"); + assert!(!err.to_string().contains("secret"), "{err}"); + } +} diff --git a/core/continuum-proving-types/src/lib.rs b/core/continuum-proving-types/src/lib.rs new file mode 100644 index 0000000000..56d83b49c0 --- /dev/null +++ b/core/continuum-proving-types/src/lib.rs @@ -0,0 +1,15 @@ +//! The proving ground's data shapes, each defined once (docs/architecture/THE-PROVING-GROUND.md 4a, +//! 8a). The T0/T1 harness, the grid world and the reducer all read these, so no shape is defined +//! twice. Data only: serde, no logic, no clock, no I/O. +//! +//! - [`closed`]: the only strings a file may hold (P9's text check, enforced by type). +//! - [`provenance`]: recorded or unavailable, joined how, measured when and how well. +//! - [`reduction`]: one act without its words. +//! - [`profile`]: what is measured on a node. +//! - [`scenario`]: a world, a workload, events, a policy and what passes. + +pub mod closed; +pub mod profile; +pub mod provenance; +pub mod reduction; +pub mod scenario; diff --git a/core/continuum-proving-types/src/profile.rs b/core/continuum-proving-types/src/profile.rs new file mode 100644 index 0000000000..a877c0c6a3 --- /dev/null +++ b/core/continuum-proving-types/src/profile.rs @@ -0,0 +1,115 @@ +//! What is measured on a node, each value with its source, time and error (THE-PROVING-GROUND 8a, +//! P2). Produced from the node's own `~/.continuum/state/{decode-knee,prefill-rate,serving-rates}.json`, +//! its engine log and a bench run; a machine we do not have is a declared shape, every domain +//! `Unmeasured` until a real one supplies it. + +use serde::{Deserialize, Serialize}; + +use crate::closed::{ModelId, Slug}; +use crate::provenance::Measured; + +/// A memory tier a byte can live on. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Tier { + /// A discrete GPU's memory. + Device, + /// Memory the GPU and CPU share (Apple silicon). + Unified, + Ram, + Disk, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TierCapacity { + pub tier: Tier, + pub bytes: Measured, +} + +/// The engine's slot layout, so a slot layout is data (4a; `/props` `context_geometry`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SlotGeometry { + pub sequences: u32, + /// The KV pool's cells: the one shared pool under `--kv-unified`, the slots' sum without it. + pub allocated_tokens: u32, + pub max_tokens_per_sequence: u32, + pub kv_unified: bool, +} + +/// A rate as a function of how many jobs share the engine. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "shape", rename_all = "snake_case", deny_unknown_fields)] +pub enum RateCurve { + /// Measured at each concurrency (the decode knee's points); the harness interpolates. + Points { points: Vec }, + /// A fitted `scale x n^exponent` tokens per second, as the flow sim's M5 constants are + /// (decode `30.5 x n^0.865`, prefill `304 x n^-0.5`, 2026-10-28). The fit's error is the + /// scale's spread; its points are not kept. + PowerLaw { scale: Measured, exponent: f64 }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RatePoint { + pub concurrency: u32, + pub tokens_per_s: Measured, +} + +/// What a move between tiers costs. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PageCost { + pub from: Tier, + pub to: Tier, + pub bytes_per_s: Measured, +} + +/// One model as served on this node. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ModelProfile { + pub model: ModelId, + pub weight_bytes: Measured, + /// KV plus recurrent state per token (the engine's `memory_breakdown`). + pub state_bytes_per_token: Measured, + pub prefill: RateCurve, + pub decode: RateCurve, + pub page: Vec, + /// One context checkpoint's bytes (`/slots` `checkpoints.max_bytes`, fork #91). + pub checkpoint_bytes: Measured, + pub slots: Measured, +} + +/// A node's measured world (THE-PROVING-GROUND 2, 8a). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NodeProfile { + /// The node's name on the grid (`m5`, `intelmac`, `bigmama-5090`), or a declared class + /// (`class/mac-unified-16g`) for a machine we do not have. + pub node: Slug, + pub memory: Vec, + pub cpu_cores: Measured, + pub models: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: a declared shape for a machine we do not have reading as measured, so a + // sweep over the hardware classes would report another node's numbers as that class's. + #[test] + fn a_declared_class_is_unmeasured_on_the_wire() { + let declared = NodeProfile { + node: Slug::try_from("class/mac-unified-16g".to_string()).expect("slug"), + memory: vec![TierCapacity { tier: Tier::Unified, bytes: Measured::Unmeasured {} }], + cpu_cores: Measured::Unmeasured {}, + models: vec![], + }; + let wire = serde_json::to_value(&declared).expect("ser"); + assert_eq!(wire["memory"][0]["bytes"], serde_json::json!({ "state": "unmeasured" })); + assert_eq!(serde_json::from_value::(wire).expect("de"), declared); + } +} diff --git a/core/continuum-proving-types/src/provenance.rs b/core/continuum-proving-types/src/provenance.rs new file mode 100644 index 0000000000..158c3fffc8 --- /dev/null +++ b/core/continuum-proving-types/src/provenance.rs @@ -0,0 +1,117 @@ +//! What a value is worth: recorded or not, joined how, measured when and how well +//! (THE-PROVING-GROUND 4a, P2). A zero is a measurement, so "not recorded" is its own variant, +//! never a default number. + +use serde::{Deserialize, Serialize}; + +use crate::closed::Slug; + +/// A field the capture either recorded or did not. `Unavailable` is never read as zero. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", content = "value", rename_all = "snake_case", deny_unknown_fields)] +pub enum Known { + Recorded(T), + Unavailable, +} + +/// A field joined from probes by persona and time rather than carried on the request +/// (the sent reasoning budget, the allocation receipt). An ambiguous join holds no value: several +/// concurrent requests could match, and guessing one would attribute another act's budget. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "join", rename_all = "snake_case", deny_unknown_fields)] +pub enum Joined { + /// One request matched, or the capture bound the receipt by request id. + Exact { value: T }, + /// More than one request in flight could match; how many. + Ambiguous { candidates: u32 }, + /// Nothing matched. + Unresolved {}, +} + +impl Joined { + /// The value only when the join is exact; an ambiguous or unresolved join has none to give. + pub fn exact(&self) -> Option<&T> { + match self { + Self::Exact { value } => Some(value), + Self::Ambiguous { .. } | Self::Unresolved {} => None, + } + } +} + +/// Where a measurement came from: a node state file, an engine log, a bench run, a probe class. +/// A slug and a reference, never a description. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Source { + /// The kind of source: `state/prefill-rate`, `engine-log`, `bench`, `probe/delib.window.flex`. + pub kind: Slug, + /// The node it was measured on. + pub node: Slug, +} + +/// A value measured on a node, or a domain never measured there (a declared shape for a machine we +/// do not have, P2). An unmeasured domain is never filled with another node's number. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)] +pub enum Measured { + Measured { + value: T, + /// Unix milliseconds of the measurement (the newest sample it summarizes). + at_ms: u64, + source: Source, + /// How many samples it summarizes. + samples: u64, + error: Spread, + }, + Unmeasured {}, +} + +/// A measurement's published error. A prediction may decide alone only when its before/after +/// difference exceeds this on that metric for that node (THE-PROVING-GROUND 10.2), so an error not +/// yet measured is said, never assumed small. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +#[serde(tag = "state", content = "value", rename_all = "snake_case", deny_unknown_fields)] +pub enum Spread { + /// One standard deviation of the samples, in the value's unit. + StdDev(T), + NotYetMeasured, +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: an unrecorded field written as 0, which a replay would read as "measured + // zero prefill" and score as the fastest act there ever was. + #[test] + fn unavailable_is_not_zero_on_the_wire() { + let none: Known = Known::Unavailable; + let zero: Known = Known::Recorded(0); + let (a, b) = (serde_json::to_string(&none).expect("ser"), serde_json::to_string(&zero).expect("ser")); + assert_ne!(a, b); + assert_eq!(serde_json::from_str::>(&a).expect("de"), Known::Unavailable); + assert!(serde_json::from_str::>("0").is_err(), "a bare number is not a Known"); + } + + // what this catches: an ambiguous join yielding a value, which would attribute a concurrent + // act's reasoning budget to this one (4a: "never resolved by guessing"). + #[test] + fn only_an_exact_join_has_a_value() { + assert_eq!(Joined::Exact { value: 1_024_u32 }.exact(), Some(&1_024)); + assert_eq!(Joined::::Ambiguous { candidates: 2 }.exact(), None); + assert_eq!(Joined::::Unresolved {}.exact(), None); + } + + // what this catches: words beside a variant that carries nothing. serde ignores extra fields + // beside an internally tagged UNIT variant even under deny_unknown_fields, which is why every + // such variant here is an empty struct (`Unresolved {}`) or adjacently tagged. + #[test] + fn nothing_rides_beside_an_empty_variant() { + let w = "\"the words\""; + assert!(serde_json::from_str::>(&format!(r#"{{"join":"unresolved","note":{w}}}"#)).is_err()); + assert!(serde_json::from_str::>(&format!(r#"{{"state":"unmeasured","note":{w}}}"#)).is_err()); + assert!(serde_json::from_str::>(&format!(r#"{{"state":"unavailable","value":{w}}}"#)).is_err()); + assert!(serde_json::from_str::>(&format!(r#"{{"state":"not_yet_measured","note":{w}}}"#)).is_err()); + assert!(serde_json::from_str::>(r#"{"join":"unresolved"}"#).is_ok(), "the clean form parses"); + } +} diff --git a/core/continuum-proving-types/src/reduction.rs b/core/continuum-proving-types/src/reduction.rs new file mode 100644 index 0000000000..b228213cce --- /dev/null +++ b/core/continuum-proving-types/src/reduction.rs @@ -0,0 +1,308 @@ +//! One act, reduced on the node that holds its capture (THE-PROVING-GROUND 4a, P9): sizes, exact +//! token counts, timings, causal ids, content hashes and outcome kinds. No field holds words: every +//! string is a closed value (`closed`), so a reduction can leave its node. + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::closed::{GitSha, ModelId, Sha256, Slug}; +use crate::provenance::{Joined, Known}; + +/// The tokenizer the counts were taken with: the serving model's own, by id AND artifact, so the +/// same capture reduces to the same numbers on any node (Codex on #5618). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TokenizerIdentity { + pub model: ModelId, + /// The artifact's revision (a commit or registry revision). + pub revision: Slug, + /// SHA-256 of the tokenizer artifact's bytes. + pub artifact: Sha256, +} + +/// Why the act ran. The capture's own causes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Cause { + /// Her own time: nothing addressed her. + Ambient, + /// Something arrived for her: a message, a result, a mention. + Stimulus, + /// The substrate made the act (a probe, a warm-up). + Synthetic, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ActIdentity { + pub persona: Uuid, + pub room: Uuid, + pub request: Uuid, + pub session: Uuid, + pub cycle: u64, + pub build: GitSha, + pub captured_at_ms: u64, + pub cause: Cause, + /// The act that started this causal chain; `None` when this act is the root. + pub cause_root: Option, +} + +/// Anything sized and identified without its words: a system prompt, a reasoning run, a reply. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Sized { + pub tokens: u32, + pub hash: Sha256, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Role { + System, + User, + Assistant, + Tool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MessageReduction { + pub role: Role, + pub tokens: u32, + pub hash: Sha256, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ToolReduction { + pub name: Slug, + pub schema_hash: Sha256, + pub tokens: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RequestReduction { + pub model: ModelId, + pub context_window: u32, + pub max_tokens: Known, + /// The request's purpose as the capture names it (`cognition/act`, `cognition/deliberation`): + /// an open registry, so a closed slug rather than an enum this crate would have to grow. + pub purpose: Slug, + pub system_prompt: Sized, + pub messages: Vec, + pub tools: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Finish { + Stop, + ToolUse, + Length, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Usage { + pub input: u32, + pub output: u32, +} + +/// The engine's own timing for the act. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Timing { + /// Prompt tokens the engine reused instead of prefilling. + pub cached: u32, + pub prefill_tokens: u32, + pub prefill_ms: u64, + pub decode_tokens: u32, + pub decode_ms: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ToolCallReduction { + pub name: Slug, + /// The canonical arguments' fingerprint (MIND-CONTEXT invariant 4): repeats are visible + /// without the words. + pub args: Sha256, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ResponseReduction { + pub finish: Known, + pub usage: Known, + pub timing: Known, + pub tool_calls: Vec, + /// Kept apart from the text: a cut inside thinking is not an answer. + pub reasoning: Known, + pub text: Known, +} + +/// One claim in the act's allocation receipt (`delib.window.flex`, `delib.view.sized`). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ClaimReduction { + pub source: Slug, + pub floor: u32, + pub want: u32, + pub granted: u32, +} + +/// The mechanism a known-bad fails on, not only its symptom (4a). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AllocationReduction { + pub claims: Vec, + pub unallocated: u32, + /// The act started a new epoch of her view. + pub turnover: bool, +} + +/// What happened on the wire. `failure` is the producer's typed class (a closed slug), never its +/// message: today's captures carry the message, so the reducer maps it to a class before writing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "outcome", rename_all = "snake_case", deny_unknown_fields)] +pub enum Delivery { + Completed { + elapsed_ms: u64, + attempts: u32, + }, + Cancelled { + elapsed_ms: u64, + failure: Slug, + }, + Failed { + elapsed_ms: u64, + failure: Slug, + }, +} + +/// What the act did, as the producer reports it (HOW-A-MIND section 7), never read from text. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OutcomeKind { + EditApplied, + MessageSent, + PrOpened, + MoveMade, + ToolError, + Unfulfilled, +} + +/// One act, with no words in it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ActReduction { + pub identity: ActIdentity, + pub tokenizer: TokenizerIdentity, + pub request: RequestReduction, + /// `Unavailable` when the act never produced a response record (cancelled before dispatch). + pub response: Known, + /// The reasoning budget actually sent. The engine adds it after capture, so older evidence + /// joins it from `delib.act.reasoning_budgeted` by persona and time. + pub reasoning_budget: Joined, + pub allocation: Joined, + /// Tokens of each view item, in order (count and size, no words). + pub view_items: Vec, + pub delivery: Delivery, + pub outcomes: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hash(b: u8) -> String { + format!("{b:02x}").repeat(32) + } + + fn reduction_json() -> serde_json::Value { + serde_json::json!({ + "identity": { + "persona": "18c04c5b-e059-4129-816f-75e8e58fd74c", "room": "5d33e2a7-67b4-521b-9911-f46724af297f", + "request": "f7b98ca4-2591-4d32-9b8d-54bf30788ac7", "session": "6c359fbd-a7b5-4532-9fca-42a1dd9ffe2a", + "cycle": 1, "build": "f6f331d98", "captured_at_ms": 1_792_969_747_125_u64, "cause": "ambient", "cause_root": null + }, + "tokenizer": { "model": "continuum-ai/qwen2.5-coder-1.5b-instruct-GGUF", "revision": "1af47f78b1", "artifact": hash(1) }, + "request": { + "model": "continuum-ai/qwen2.5-coder-1.5b-instruct-GGUF", "context_window": 32768, + "max_tokens": { "state": "recorded", "value": 4096 }, "purpose": "cognition/act", + "system_prompt": { "tokens": 1200, "hash": hash(2) }, + "messages": [{ "role": "user", "tokens": 300, "hash": hash(3) }], + "tools": [{ "name": "code/read", "schema_hash": hash(4), "tokens": 80 }] + }, + "response": { "state": "recorded", "value": { + "finish": { "state": "recorded", "value": "tool_use" }, + "usage": { "state": "unavailable" }, + "timing": { "state": "recorded", "value": { "cached": 3000, "prefill_tokens": 1500, "prefill_ms": 116000, "decode_tokens": 40, "decode_ms": 9000 } }, + "tool_calls": [{ "name": "code/read", "args": hash(5) }], + "reasoning": { "state": "unavailable" }, + "text": { "state": "recorded", "value": { "tokens": 40, "hash": hash(6) } } + }}, + "reasoning_budget": { "join": "ambiguous", "candidates": 2 }, + "allocation": { "join": "unresolved" }, + "view_items": [1200, 300], + "delivery": { "outcome": "completed", "elapsed_ms": 125000, "attempts": 1 }, + "outcomes": ["tool_error"] + }) + } + + // what this catches: the reduction shape drifting from what the reducer writes and the + // harness reads; one round trip through the one type. + #[test] + fn a_reduction_round_trips() { + let r: ActReduction = serde_json::from_value(reduction_json()).expect("a reduction"); + assert_eq!(r.reasoning_budget.exact(), None, "ambiguous carries no budget"); + let back = serde_json::to_value(&r).expect("ser"); + assert_eq!(serde_json::from_value::(back).expect("de"), r); + } + + // what this catches: words surviving into a reduction (P9). Every string slot gets a planted + // sentence, and one extra field carries one: none may parse. A new free-text field would make + // its slot accept the sentence, and this test fails there. + #[test] + fn planted_words_never_survive() { + let sentence = serde_json::json!("I think the deploy broke because Joel said so"); + let slots: &[&[&str]] = &[ + &["identity", "build"], + &["identity", "persona"], + &["tokenizer", "model"], + &["tokenizer", "revision"], + &["request", "purpose"], + &["request", "system_prompt", "hash"], + &["request", "tools", "0", "name"], + &["response", "value", "tool_calls", "0", "name"], + &["response", "value", "tool_calls", "0", "args"], + ]; + for path in slots { + let mut v = reduction_json(); + let mut at = &mut v; + for key in *path { + at = match key.parse::() { + Ok(i) => &mut at[i], + Err(_) => &mut at[*key], + }; + } + *at = sentence.clone(); + assert!(serde_json::from_value::(v).is_err(), "words parsed at {path:?}"); + } + // An unknown field anywhere is refused, not ignored: the pre-commit check parses the file + // on disk, so a field serde skipped would pass the check with its words still committed. + for nest in [&[][..], &["identity"][..], &["request", "messages", "0"][..], &["response", "value", "timing", "value"][..]] { + let mut v = reduction_json(); + let mut at = &mut v; + for key in nest { + at = match key.parse::() { + Ok(i) => &mut at[i], + Err(_) => &mut at[*key], + }; + } + at["note"] = sentence.clone(); + assert!(serde_json::from_value::(v).is_err(), "an unknown field carried words at {nest:?}"); + } + } +} diff --git a/core/continuum-proving-types/src/scenario.rs b/core/continuum-proving-types/src/scenario.rs new file mode 100644 index 0000000000..6846549977 --- /dev/null +++ b/core/continuum-proving-types/src/scenario.rs @@ -0,0 +1,250 @@ +//! A scenario is data, not code (THE-PROVING-GROUND P5, 4a): the world, the workload, the events, +//! the policy and what passes. A live incident becomes a file the same day, so it cannot return. + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::closed::{GitSha, Sha256, Slug}; +use crate::profile::Tier; + +/// A node profile by its node and the content hash of the profile file, so a scenario names +/// exactly the measurements it ran against. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProfileRef { + pub node: Slug, + pub profile: Sha256, +} + +/// The person at the machine: what their apps take, and how long they will wait. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum PersonEvent { + /// An app (a game, a build) holds memory and cores for a while. + App { + name: Slug, + node: Slug, + tier: Tier, + bytes: u64, + cores: u32, + from_ms: u64, + until_ms: u64, + }, + /// The person writes into a room, and waits this long before it hurts. + Message { + room: Uuid, + at_ms: u64, + patience_ms: u64, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct World { + pub nodes: Vec, + pub person: Vec, +} + +/// Which acts of a reduction set to replay. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkloadRef { + /// Content hash of the reduction set file. + pub reductions: Sha256, + /// The minds it replays; empty is every mind in the set. + pub minds: Vec, +} + +/// Something that happens to the world at a time (THE-PROVING-GROUND 2, 8a's admission events). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum WorldEvent { + CapacityDrop { node: Slug, tier: Tier, bytes: u64 }, + CapacityRecover { node: Slug, tier: Tier, bytes: u64 }, + CoreRestart { node: Slug }, + EngineRelaunch { node: Slug }, + NodeJoin { node: Slug }, + NodeLeave { node: Slug }, + Partition { a: Slug, b: Slug }, + Heal { a: Slug, b: Slug }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TimedEvent { + pub at_ms: u64, + pub event: WorldEvent, +} + +/// The policy under test: a revision, with typed overrides of its knobs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyRef { + pub revision: GitSha, + pub overrides: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Override { + pub knob: Slug, + pub value: OverrideValue, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "value", rename_all = "snake_case", deny_unknown_fields)] +pub enum OverrideValue { + Int(i64), + Bool(bool), +} + +/// A metric the live health line, the 15-minute read and every run report alike +/// (THE-PROVING-GROUND 5), plus the mechanisms the known-bad suite fails on (4a). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "metric", content = "of", rename_all = "snake_case", deny_unknown_fields)] +pub enum Metric { + // per mind + Acts, + Writes, + ActSecondsP50, + ActSecondsP90, + PrefillSecondsPerAct, + DecodeSecondsPerAct, + PrefixReuse, + Faults, + Repeats, + Cuts { stop_class: Slug }, + StarvationSeconds, + // per loop + Reversals, + // per node + Relaunches, + MemoryReturnedBytes, + MemoryReturnSeconds, + // per grid + Placements, + Rehomes, + TransferBytes, + TransferSeconds, + // mechanisms (4a's known-bad suite) + TurnoversPerAct, + UnallocatedZeroWithTurnover, + ReasoningBudgetAboveGrant, + HotWriterCutWhileSlotsIdle, + RepeatsOfUnfulfilled, +} + +/// A measured baseline: the scenario and policy it ran, and the receipt it produced. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Baseline { + pub scenario: Slug, + pub policy: GitSha, + pub receipt: Sha256, +} + +/// What passes. An invariant, or a comparison with a named measured baseline; there is no variant +/// that carries a number, so a threshold someone picked cannot be written (R1). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "criterion", rename_all = "snake_case", deny_unknown_fields)] +pub enum Criterion { + /// The metric is zero over the run. + Never {}, + /// Not worse than the baseline beyond the published error on that metric for that node. + NoWorseThan { baseline: Baseline }, + /// Better than the baseline by more than the published error. + BetterThan { baseline: Baseline }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PassCriterion { + pub metric: Metric, + pub criterion: Criterion, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum ScenarioKind { + Scenario {}, + /// A live incident: the prover must report `fails` as failing under the incident's policy, or + /// it has either broken or shown the incident is no longer bad (10.4: a reviewer decides). + KnownBad { incident: Slug, policy: GitSha, fails: PassCriterion }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Scenario { + pub name: Slug, + pub kind: ScenarioKind, + pub world: World, + pub workload: Vec, + pub events: Vec, + pub policy: PolicyRef, + pub pass: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn known_bad() -> serde_json::Value { + let h = |b: u8| format!("{b:02x}").repeat(32); + serde_json::json!({ + "name": "think-cut-963-grant", + "kind": { "kind": "known_bad", "incident": "2026-10-30-think-cuts", "policy": "b7879d85c", + "fails": { "metric": { "metric": "reasoning_budget_above_grant" }, "criterion": { "criterion": "never" } } }, + "world": { "nodes": [{ "node": "m5", "profile": h(1) }], "person": [] }, + "workload": [{ "reductions": h(2), "minds": [] }], + "events": [{ "at_ms": 0, "event": { "kind": "core_restart", "node": "m5" } }], + "policy": { "revision": "b7879d85c", "overrides": [] }, + "pass": [{ "metric": { "metric": "reasoning_budget_above_grant" }, "criterion": { "criterion": "never" } }] + }) + } + + // what this catches: the known-bad file shape drifting from what the harness reads. + #[test] + fn a_known_bad_file_round_trips() { + let s: Scenario = serde_json::from_value(known_bad()).expect("a known-bad scenario"); + let back = serde_json::to_value(&s).expect("ser"); + assert_eq!(serde_json::from_value::(back).expect("de"), s); + } + + // what this catches: a picked threshold (R1). A criterion carrying a number does not parse, + // whatever its field is called. + #[test] + fn a_picked_threshold_cannot_be_written() { + for picked in [ + serde_json::json!({ "criterion": "at_least", "value": 40 }), + serde_json::json!({ "criterion": "never", "note": "the words" }), + serde_json::json!({ "criterion": "never", "value": 0 }), + serde_json::json!({ "criterion": "no_worse_than", "baseline": { "scenario": "s", "policy": "b7879d85c", "receipt": "ab".repeat(32) }, "by": 0.1 }), + ] { + let mut v = known_bad(); + v["pass"][0]["criterion"] = picked.clone(); + assert!(serde_json::from_value::(v).is_err(), "{picked} parsed"); + } + } + + // what this catches: words beside a metric or a plain scenario kind (see provenance's + // nothing_rides_beside_an_empty_variant for why these shapes are the ones serde enforces). + #[test] + fn nothing_rides_beside_a_metric_or_a_kind() { + for (path, planted) in [ + (&["pass", "0", "metric"][..], serde_json::json!({ "metric": "acts", "note": "the words" })), + (&["pass", "0", "metric"][..], serde_json::json!({ "metric": "acts", "of": "the words" })), + (&["kind"][..], serde_json::json!({ "kind": "scenario", "note": "the words" })), + ] { + let mut v = known_bad(); + let mut at = &mut v; + for key in path { + at = match key.parse::() { + Ok(i) => &mut at[i], + Err(_) => &mut at[*key], + }; + } + *at = planted.clone(); + assert!(serde_json::from_value::(v).is_err(), "{planted} parsed"); + } + } +} diff --git a/docs/architecture/THE-PROVING-GROUND.md b/docs/architecture/THE-PROVING-GROUND.md index 261dc9c6ad..a414d8b6f0 100644 --- a/docs/architecture/THE-PROVING-GROUND.md +++ b/docs/architecture/THE-PROVING-GROUND.md @@ -196,7 +196,7 @@ and asserts that none survive. A stray string fails the build, so no reviewer ha someone picked is refused, as R1 requires. - A `KnownBad` file states the criterion the prover must report as failing. -**Home.** The types live in one small crate, `continuum-proving-types` (serde, ts-rs bindings, no logic). +**Home.** The types live in one small crate, `continuum-proving-types` (serde only, no logic; TypeScript bindings come when a client reads these files, since every reader today is Rust). The T0/T1 harness (Fable), the grid world (Codex) and the reducer (Cormac) all depend on it, so no shape is defined twice. @@ -287,7 +287,7 @@ The proving ground is trusted only as far as it is shown to be right. ## 8a. The harness's shape (Fable's part, for review before code) **Crates.** -- `continuum-proving-types` (Cormac's proposal): the data only, serde and ts-rs, no logic. Reductions, +- `continuum-proving-types` (Cormac's proposal): the data only, serde, no logic. Reductions, scenario files, node profiles, receipts, metrics. - `continuum-proving` (new): the harness, a library plus a `prove` binary. It depends on the types crate and on the production policy crates it drives, and on nothing in serving or the core binary. It is a dev and CI diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index ddd4c5bfb8..15bacfa204 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -15,7 +15,7 @@ const select = (...paths) => { // changing what CI runs. // Tested crates a kernel change does not reach: the floor (base, host, git, service) and the leaf // codec continuum-context, which depends on nothing in the workspace. -const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-context']; +const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-context', 'continuum-proving-types']; test('installer repairs run installer checks without unrelated Rust builds', () => { for (const file of ['install.ps1', 'tools/scripts/lib/install-common.ps1', 'tools/scripts/lib/win-modules.ps1', 'tools/scripts/lib/win-engine.ps1', 'tools/scripts/lib/windows-engine-receipt.ps1', 'tools/scripts/lib/windows-service.ps1', 'tools/scripts/lib/windows-media-reconciliation.ps1', 'tools/scripts/lib/windows-elevation.ps1', 'tools/scripts/tests/windows-process.test.ps1', 'tools/scripts/tests/windows-airc-download.test.ps1', 'tools/scripts/tests/windows-xz.test.ps1', 'tools/scripts/sync-windows-bootstrap.ps1']) @@ -118,7 +118,7 @@ test('a crate-local change runs that crate and every crate that depends on it', const aboveFloor = TESTED_CRATES.filter(n => !BELOW_KERNEL.includes(n)); assert.deepEqual(scope(['core/continuum-kernel/src/lib.rs']), { crates: aboveFloor, cli: false }); // A floor change runs the floor crate and every crate built on it. - assert.deepEqual(scope(['core/continuum-host/src/durable/mod.rs']), { crates: TESTED_CRATES.filter(n => !['continuum-base', 'continuum-service', 'continuum-context'].includes(n)), cli: true }); + assert.deepEqual(scope(['core/continuum-host/src/durable/mod.rs']), { crates: TESTED_CRATES.filter(n => !['continuum-base', 'continuum-service', 'continuum-context', 'continuum-proving-types'].includes(n)), cli: true }); // continuum-git is used by hands (a citizen's git) and core (the deploy tree): both run, and every crate above hands. assert.deepEqual(scope(['core/continuum-git/src/index_lock.rs']), crates('continuum-git', 'continuum-hands', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); // Untested crates reach the tested ones through the graph: llama -> engine -> ...