diff --git a/crates/ghostlight-verse/src/main.rs b/crates/ghostlight-verse/src/main.rs index 29e93fc..5d6263d 100644 --- a/crates/ghostlight-verse/src/main.rs +++ b/crates/ghostlight-verse/src/main.rs @@ -14,7 +14,7 @@ use chrono::{Duration, Utc}; use ghostlight::{ CommandBody, CommandId, ControllerModels, ControllerOpenError, ControllerRunner, DEFAULT_HOSTED_MODEL_PREFIX, DEFAULT_LOCAL_MODEL_PREFIX, CallRecordStore, CoverBudget, CreateVerseWorldIntent, - HostedBinding, Lens, LensWeights, LocalBinding, PrincipalCommandIntent, RecordingInferencePort, + GestaltKnobs, HostedBinding, Lens, LensWeights, LocalBinding, PrincipalCommandIntent, RecordingInferencePort, RunStart, RunStatus, TickMinutes, VerifiedPrincipalEvidence, VerseRunConfig, VerseRunStore, WorldMailbox, call_run_id, id_text, open_controller_work, open_inference, read_aetheria_catalog, run_manual, @@ -27,13 +27,19 @@ use std::process::ExitCode; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -/// What a manual run spends per tick on cognition cells. The operator's lever -/// on cost is the token cap; the partition always covers every faction. +/// The default knobs' cover: what a manual run spends per tick on cognition +/// cells inside one node. The operator's lever on cost is the token cap; the +/// partition covers every voice of a due node. const COVER: CoverBudget = CoverBudget { cells: 8, constituent_cap: 8, urgency_slots: 2, }; +/// Default depth: only the root is open, so every faction speaks as a voice +/// of one node at the tick's own rate, the shape of the flat cover. +const DEPTH: u8 = 1; +/// Default node-turn bound per tick: far above the world's node count. +const MAX_NODE_TURNS: u16 = 256; const RUNTIME_ID: &str = "ghostlight-verse"; @@ -61,7 +67,7 @@ async fn command(arguments: Vec) -> Result { } const GENESIS_FLAGS: [&str; 4] = ["catalog", "aetheria-commit", "state", "owner-hash"]; -const RUN_FLAGS: [&str; 7] = [ +const RUN_FLAGS: [&str; 9] = [ "state", "ticks", "token-cap", @@ -69,16 +75,21 @@ const RUN_FLAGS: [&str; 7] = [ "model", "base-url", "key-file", + "depth", + "band", ]; /// Flags a command may omit. -const OPTIONAL: [&str; 1] = ["key-file"]; +const OPTIONAL: [&str; 3] = ["key-file", "depth", "band"]; +/// Flags that may be given more than once. +const REPEATABLE: [&str; 1] = ["band"]; -/// `--name value` pairs, each named once and from the command's own list. -struct Flags(BTreeMap<&'static str, String>); +/// `--name value` pairs from the command's own list, each named once unless it +/// is repeatable, in which case its values keep the order given. +struct Flags(BTreeMap<&'static str, Vec>); impl Flags { fn parse(arguments: &[String], allowed: &[&'static str]) -> Result { - let mut seen = BTreeMap::new(); + let mut seen: BTreeMap<&'static str, Vec> = BTreeMap::new(); let mut rest = arguments.iter(); while let Some(flag) = rest.next() { let Some(name) = flag.strip_prefix("--") else { @@ -90,9 +101,11 @@ impl Flags { let Some(value) = rest.next() else { bail!("--{known} needs a value"); }; - if seen.insert(known, value.clone()).is_some() { + let values = seen.entry(known).or_default(); + if !values.is_empty() && !REPEATABLE.contains(&known) { bail!("--{known} was given twice"); } + values.push(value.clone()); } for &required in allowed { if !OPTIONAL.contains(&required) && !seen.contains_key(required) { @@ -103,7 +116,11 @@ impl Flags { } fn text(&self, name: &str) -> &str { - self.0.get(name).map_or("", String::as_str) + self.0.get(name).and_then(|values| values.first()).map_or("", String::as_str) + } + + fn all(&self, name: &str) -> &[String] { + self.0.get(name).map_or(&[], Vec::as_slice) } fn path(&self, name: &str) -> PathBuf { @@ -118,6 +135,44 @@ impl Flags { } } +/// The run's knobs: the flags over the defaults. With no `--band` the one band +/// is the tick span; `--band DIST=MINUTES` gives the period of the nodes +/// DIST hops from the focus (the last band is the rest, and a verse tick has no +/// focus, so only that one governs). Bands must be given for distances 0, 1, 2 +/// and so on, with no gap. +fn knobs(flags: &Flags, tick_span: TickMinutes) -> Result { + let depth = if flags.0.contains_key("depth") { + flags.number::("depth")? + } else { + DEPTH + }; + let mut given: BTreeMap = BTreeMap::new(); + for band in flags.all("band") { + let parsed = band.split_once('=').and_then(|(distance, minutes)| { + Some((distance.parse::().ok()?, TickMinutes::new(minutes.parse().ok()?)?)) + }); + let Some((distance, minutes)) = parsed else { + bail!("--band is not DIST=MINUTES with a minutes value inside the clock's span"); + }; + if given.insert(distance, minutes).is_some() { + bail!("--band names one distance twice"); + } + } + let bands = if given.is_empty() { + vec![tick_span] + } else if given.keys().copied().eq(0..given.len()) { + given.into_values().collect() + } else { + bail!("--band must name distances 0, 1, 2 and so on without a gap"); + }; + Ok(GestaltKnobs { + bands, + depth, + max_node_turns: MAX_NODE_TURNS, + cover: COVER, + }) +} + async fn genesis(flags: Flags) -> Result { let state = flags.path("state"); std::fs::create_dir_all(&state).context("the state directory cannot be created")?; @@ -174,6 +229,7 @@ async fn run(flags: Flags) -> Result { let cap: u64 = flags.number("token-cap")?; let span: u32 = flags.number("tick-span-minutes")?; let tick_span = TickMinutes::new(span).context("--tick-span-minutes is outside the clock's span")?; + let knobs = knobs(&flags, tick_span)?; if !state.join("world.cc").is_file() { bail!("the state directory holds no world; run genesis first"); } @@ -198,7 +254,7 @@ async fn run(flags: Flags) -> Result { let config = VerseRunConfig { ticks, tick_span, - cover: COVER, + knobs, }; let claim = runs .claim(&world, cap, &config) @@ -286,7 +342,7 @@ fn open_lane( ) -> Result> { let (mut hosted, mut local) = (None, None); if model.starts_with(DEFAULT_HOSTED_MODEL_PREFIX) { - let Some(key) = flags.0.get("key-file") else { + let Some(key) = flags.0.get("key-file").and_then(|values| values.first()) else { bail!("a hosted model needs --key-file"); }; hosted = Some(HostedBinding { diff --git a/crates/ghostlight-verse/tests/verse_binary.rs b/crates/ghostlight-verse/tests/verse_binary.rs index 28cf75d..f1ab725 100644 --- a/crates/ghostlight-verse/tests/verse_binary.rs +++ b/crates/ghostlight-verse/tests/verse_binary.rs @@ -143,7 +143,12 @@ fn serve(mut stream: TcpStream, served: &AtomicUsize, status: u16) { } fn run(state: &Path, responder: &Responder, ticks: &str, cap: &str) -> Output { - verse(&[ + run_with(state, responder, ticks, cap, &[]) +} + +fn run_with(state: &Path, responder: &Responder, ticks: &str, cap: &str, extra: &[&str]) -> Output { + let url = responder.url(); + let mut arguments = vec![ "run", "--state", state.to_str().unwrap(), @@ -156,8 +161,32 @@ fn run(state: &Path, responder: &Responder, ticks: &str, cap: &str) -> Output { "--model", "local/scripted", "--base-url", - &responder.url(), - ]) + &url, + ]; + arguments.extend_from_slice(extra); + verse(&arguments) +} + +#[test] +fn binary_run_takes_depth_and_band_flags_and_reports_by_node() { + let state = tempfile::tempdir().unwrap(); + assert!(genesis(state.path()).status.success()); + let responder = Responder::start(); + let output = run_with( + state.path(), + &responder, + "1", + "1000000", + &["--depth", "8", "--band", "0=60", "--band", "1=240"], + ); + assert!(output.status.success(), "{}", stderr(&output)); + let text = stdout(&output); + // Opened to every institution, each faction is its own node; with no focus + // each sits at the last band's index. + for faction in ["Adrasteia", "Brannoch"] { + assert!(text.contains(&format!(" node {faction} (distance 1): ")), "{text}"); + } + assert!(text.contains("tick 0 closed: 2 cells, 2 acts, 0 refused\n"), "{text}"); } #[test] @@ -266,7 +295,7 @@ fn the_command_refuses_what_it_cannot_run_and_never_echoes_a_value() { let secret = "sk-not-a-real-key-0000"; let key = state.path().join(secret); - let cases: [(Vec<&str>, &str); 9] = [ + let cases: [(Vec<&str>, &str); 11] = [ (vec![], "usage"), (vec!["fly"], "unknown command"), ( @@ -322,6 +351,22 @@ fn the_command_refuses_what_it_cannot_run_and_never_echoes_a_value() { ], "a local model takes no --key-file", ), + ( + vec![ + "run", "--state", state.path().to_str().unwrap(), "--ticks", "1", + "--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x", + "--base-url", "http://127.0.0.1:1", "--band", "1=60", + ], + "--band must name distances 0, 1, 2", + ), + ( + vec![ + "run", "--state", state.path().to_str().unwrap(), "--ticks", "1", + "--token-cap", "1", "--tick-span-minutes", "60", "--model", "local/x", + "--base-url", "http://127.0.0.1:1", "--depth", "0", + ], + "--depth is not a positive integer", + ), ]; for (arguments, expected) in cases { let output = verse(&arguments); diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index 5507669..c19dae8 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -114,7 +114,9 @@ pub use aetheria::{ pub use cover::{AgencyGraph, Cell, Cover, CoverBudget, CoverBudgetError, TickIndex, derive_cover}; pub use hierarchy::{Hierarchy, Node, NodeAnchor, NodeId}; pub use wave::{ - Deferral, Focus, GestaltKnobs, GestaltKnobsError, NodeTurn, Wave, WaveClock, plan_wave, + Deferral, Focus, FrozenCell, GestaltKnobs, GestaltKnobsError, NodeOutcome, NodeTurn, Refusal, + RefusalReason, UnattributedCall, Wave, WaveClock, WaveOutcome, WaveStop, plan_wave, + run_frozen_cells, }; pub use elaboration::{ ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, SweepReport, EvidenceError, EvidenceQuery, @@ -165,9 +167,9 @@ pub use vault::{ }; pub use verse::{ CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord, - RUN_RECORD_SCHEMA, RecordedCoverBudget, RecordingInferencePort, Refusal, RefusalReason, RunClaim, + RUN_RECORD_SCHEMA, NodeReport, RecordedKnobs, RecordingInferencePort, RunClaim, ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint, - TickReport, UnattributedCall, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, + TickReport, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, call_run_id, run_manual, }; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; diff --git a/crates/ghostlight/src/verse/mod.rs b/crates/ghostlight/src/verse/mod.rs index abef1b3..5662494 100644 --- a/crates/ghostlight/src/verse/mod.rs +++ b/crates/ghostlight/src/verse/mod.rs @@ -13,7 +13,7 @@ pub use calls::{ RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart, }; pub use run::{ - RUN_RECORD_SCHEMA, RecordedCoverBudget, Refusal, RefusalReason, RunClaim, RunOutcome, RunStatus, - TickCheckpoint, TickReport, UnattributedCall, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, + RUN_RECORD_SCHEMA, NodeReport, RecordedKnobs, RunClaim, RunOutcome, RunStatus, + TickCheckpoint, TickReport, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, call_run_id, run_manual, }; diff --git a/crates/ghostlight/src/verse/run.rs b/crates/ghostlight/src/verse/run.rs index aced104..175ff1d 100644 --- a/crates/ghostlight/src/verse/run.rs +++ b/crates/ghostlight/src/verse/run.rs @@ -1,18 +1,19 @@ //! The manual verse run: the tick driver and its record. //! //! One invocation advances the world tick by tick. A tick reads the world, -//! opens (or finds open) its tick document, runs each frozen cell through the -//! controller organ, advances the clock once by the frozen span, and -//! checkpoints. The driver owns the order of those steps and nothing else: -//! cells decide what factions do, the recording port owns spend, the kernel -//! owns time. +//! opens (or finds open) its tick document, which freezes one planned wave +//! (`plan_wave` over the derived hierarchy, with no focus), runs the frozen +//! cells through the wave runner (`run_frozen_cells`), advances the clock once +//! by the frozen span, and checkpoints. The driver owns the order of those +//! steps and nothing else: the planner chooses nodes and cells, cells decide +//! what factions do, the recording port owns spend, the kernel owns time. //! //! A tick is named by the world's clock-advance count, never by `now`. The //! resume point is the open tick document (world, ordinal), written before the -//! tick's first cell and read by any later run: it froze the span, the cover -//! budget and the cells when the tick opened, so a run under another span or -//! budget finishes the open tick as it was opened and applies its own config -//! from the next tick it opens. A tick whose cells did not all finish never +//! tick's first cell and read by any later run: it froze the span, the knobs +//! and the cells (each with its node and distance) when the tick opened, so a +//! run under another span or knobs finishes the open tick as it was opened and +//! applies its own config from the next tick it opens. A tick whose cells did not all finish never //! advances the clock, so the same ordinal, cells and command ids come back, //! the controller-work rows pick up where they stopped, and the kernel answers //! every re-submission with the original receipt. A run record reports a run @@ -22,17 +23,15 @@ //! repeats. use super::calls::{RecordingInferencePort, canonical}; -use crate::controllers::{ - CellRun, ConstituentRefusalReason, ControllerError, ControllerPendingReason, ControllerRunner, InferenceFaultClass, - NarrativeRun, OperationalRun, SubmissionDisposition, -}; -use crate::cover::{ - Cell, CellId, Constituent, CoverBudget, CoverBudgetError, TickIndex, derive_cover, +use crate::cover::TickIndex; +use crate::wave::{ + FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, Refusal, RefusalReason, UnattributedCall, + WaveClock, WaveOutcome, WaveStop, plan_wave, run_frozen_cells, }; use crate::{ - AgencyGraph, CommandId, DecisionOpportunity, KernelError, MailboxError, OperatorEvent, - RenderPath, - SubjectId, SubmitReceipt, TickMinutes, WorldId, WorldMailbox, WorldSnapshot, + AgencyGraph, CommandId, ControllerRunner, DecisionOpportunity, FictionalMinutes, Hierarchy, MailboxError, + NodeAnchor, NodeId, OperatorEvent, RenderPath, SubjectId, TickMinutes, WorldId, WorldMailbox, + WorldSnapshot, }; use chrono::Utc; use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore}; @@ -41,11 +40,15 @@ use std::{collections::BTreeMap, ops::ControlFlow, path::Path, sync::Mutex}; use thiserror::Error; /// The run record document's schema. -pub const RUN_RECORD_SCHEMA: &str = "ghostlight.verse_run.v1"; -const RUN_ROW: &str = "verse_run.v1"; +pub const RUN_RECORD_SCHEMA: &str = "ghostlight.verse_run.v2"; +const RUN_ROW: &str = "verse_run.v2"; /// The tick document's schema. -pub const TICK_RECORD_SCHEMA: &str = "ghostlight.verse_tick.v1"; -const TICK_ROW: &str = "verse_tick.v1"; +pub const TICK_RECORD_SCHEMA: &str = "ghostlight.verse_tick.v2"; +const TICK_ROW: &str = "verse_tick.v2"; +/// The schemas the knobs replaced the flat cover budget under. No store holding +/// one is read: the verse store has never held a live run, so there is no +/// migration, and a v1 row is refused by name. +const RETIRED_SCHEMAS: [&str; 2] = ["ghostlight.verse_run.v1", "ghostlight.verse_tick.v1"]; const CLOCK_NAMESPACE: &str = "ghostlight.verse.clock"; /// Why a run could not be recorded or started. Every variant names a kind of @@ -64,8 +67,10 @@ pub enum VerseRunError { ConfigNotThisClaim, #[error("the world is not at the revision its claim was made from")] WorldMovedSinceClaim, - #[error("the cover budget is not valid: {0}")] - Budget(#[from] CoverBudgetError), + #[error("the knobs are not valid: {0}")] + Knobs(#[from] GestaltKnobsError), + #[error("the run store holds a row of a retired schema (v1 run or tick); it is not migrated")] + RetiredSchema, #[error(transparent)] Mailbox(#[from] MailboxError), } @@ -88,55 +93,6 @@ pub enum RunStatus { Stopped, } -/// Why a cell committed nothing and the run went on. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum RefusalReason { - /// A narrative turn the world moved under and could not lower again. - Interrupted, - /// The world refused the cell's submission. - WorldRejected, - /// The cell's subject no longer holds an opportunity. - OpportunityGone, - /// The cell's work was bound to a scope that has since moved. Work still - /// reasoning is refused by the operational lane's world check before each - /// inference round. Work whose submission body - /// was persisted but never sent is submitted and refused by the world with - /// `ScopeChanged`. Narrative work is never refused for a moved scope at - /// resume: the kernel refuses it at submit and the same prose is - /// re-lowered once, and only a second move ends it overtaken. A cell whose - /// command already committed does not end this way: the controller answers it with its receipt whatever the scope - /// has done since. - ScopeMoved, - /// A grouped member's own tool call could not be decoded and it proposed - /// nothing else. No turn was submitted for it. - ProposalUndecodable, - /// A resumed cell's persisted row did not hold this member. No turn was - /// submitted for it. - RowDisagreesWithCell, - /// A tool call in the member's cell named no handle and the member - /// finished with no choice of its own, so no turn was submitted for it. - CallUnattributed, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Refusal { - /// The cell's position in the tick's cover. - pub cell: u32, - /// The frozen member that committed nothing. Every member of a closed - /// tick's cells is in `committed` or here, once. - pub subject: SubjectId, - pub reason: RefusalReason, -} - -/// A tool call in a grouped cell that named no handle in it. The name is the -/// call's own, capped; its arguments are never kept. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct UnattributedCall { - /// The cell's position in the tick's cover. - pub cell: u32, - pub tool: String, -} - /// A tick as the run left it. A closed tick has all its cells run and the /// clock advanced by the tick's frozen span. The tick a run ended inside is /// recorded too, unclosed, so what its cells committed is not lost; a later @@ -157,34 +113,27 @@ pub struct TickCheckpoint { pub tokens: u64, } -/// The cover budget as the record carries it. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct RecordedCoverBudget { +/// The knobs as a record carries them. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RecordedKnobs { + /// Band periods in fictional minutes, by distance. + pub bands: Vec, + pub depth: u8, + pub max_node_turns: u16, pub cells: u16, pub constituent_cap: u16, pub urgency_slots: u16, } -/// A cell as the tick document froze it: the partition's identity and its -/// members, decided once when the tick opened. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct FrozenCell { - pub id: CellId, - /// True for a `Cell::Group`, even one a refresh has left a single member. - pub group: bool, - pub members: Vec, -} - -impl FrozenCell { - fn of(cell: &Cell) -> Self { - let (id, group) = match cell { - Cell::Singleton { id, .. } => (*id, false), - Cell::Group { id, .. } => (*id, true), - }; +impl RecordedKnobs { + fn of(knobs: &GestaltKnobs) -> Self { Self { - id, - group, - members: cell.members().iter().map(|member| member.subject).collect(), + bands: knobs.bands.iter().map(|band| band.minutes()).collect(), + depth: knobs.depth, + max_node_turns: knobs.max_node_turns, + cells: knobs.cover.cells, + constituent_cap: knobs.cover.constituent_cap, + urgency_slots: knobs.cover.urgency_slots, } } } @@ -200,7 +149,7 @@ pub enum TickClose { World, } -/// What a tick decided when it opened. Document `ghostlight.verse_tick.v1`, +/// What a tick decided when it opened. Document `ghostlight.verse_tick.v2`, /// keyed (world, ordinal). Written once before the tick's first cell, closed /// once, never reopened or deleted. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -210,7 +159,7 @@ pub struct VerseTick { pub opened_now: u64, pub opened_revision: u64, pub span_minutes: u32, - pub cover_budget: RecordedCoverBudget, + pub knobs: RecordedKnobs, pub oversubscribed: bool, pub cells: Vec, pub opened_by_run: u64, @@ -218,7 +167,7 @@ pub struct VerseTick { } /// One invocation of the verse runner: what it was asked, what it did. -/// Document `ghostlight.verse_run.v1`, keyed (world, run sequence). +/// Document `ghostlight.verse_run.v2`, keyed (world, run sequence). #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct VerseRunRecord { pub world_id: WorldId, @@ -226,7 +175,7 @@ pub struct VerseRunRecord { pub token_cap: u64, pub ticks_requested: u32, pub tick_span_minutes: u32, - pub cover_budget: RecordedCoverBudget, + pub knobs: RecordedKnobs, /// The world's revision when the run began. pub start_revision: u64, pub checkpoints: Vec, @@ -242,19 +191,35 @@ impl VerseRunRecord { /// What a caller asks of one run. The token cap is not here: the recording /// port owns it. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] pub struct VerseRunConfig { pub ticks: u32, pub tick_span: TickMinutes, - pub cover: CoverBudget, + pub knobs: GestaltKnobs, +} + +/// What one node's turn did in a tick, as the operator reads it. +#[derive(Clone, Debug)] +pub struct NodeReport { + /// The node's anchor's label; `-` when the world no longer names the + /// anchor, and for acts no frozen cell claims. + pub label: String, + /// Hierarchy distance from the focus when the wave was planned; none for + /// acts no frozen cell claims. + pub distance: Option, + /// The acts the node's members committed, from the operator log. + pub acts: Vec, + pub refusals: Vec, + /// Tokens charged while the node's cells ran in this invocation. + pub spent: u64, } /// A tick as the operator reads it, including the one a run ended inside. #[derive(Clone, Debug)] pub struct TickReport { pub checkpoint: TickCheckpoint, - /// Every act the tick committed, from the operator log. - pub acts: Vec, + /// The tick's nodes in run order, each with its acts and refusals. + pub nodes: Vec, /// The labels of the subjects the checkpoint's refusals name, from the /// snapshot the tick opened on. pub labels: BTreeMap, @@ -262,6 +227,13 @@ pub struct TickReport { pub remaining: u64, } +impl TickReport { + /// Every act the tick committed, grouped by node in run order. + pub fn acts(&self) -> impl Iterator { + self.nodes.iter().flat_map(|node| node.acts.iter()) + } +} + impl std::fmt::Display for RunStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -274,9 +246,10 @@ impl std::fmt::Display for RunStatus { } } -/// The tick as the operator reads it: a header, one line per committed act -/// (who, which verb, how it renders, what its roles are bound to, what was -/// said or shown), one per refusal, and the spend. +/// The tick as the operator reads it: a header, then per node its label, +/// distance and spend, one line per committed act (who, which verb, how it +/// renders, what its roles are bound to, what was said or shown) and one per +/// refusal, then the spend. impl std::fmt::Display for TickReport { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let checkpoint = &self.checkpoint; @@ -286,39 +259,47 @@ impl std::fmt::Display for TickReport { checkpoint.tick, if checkpoint.closed { "closed" } else { "open" }, checkpoint.cells, - self.acts.len(), + self.acts().count(), checkpoint.refusals.len() )?; - for act in &self.acts { - let path = match act.render_path { - Some(RenderPath::ShipAction) => "ship_action", - Some(RenderPath::Conversation) => "conversation", - None => "-", - }; - write!(f, " {} {} [{path}]", act.speaker_label, act.verb)?; - for role in &act.roles { - write!(f, " {}={}", role.role, role.target)?; + for node in &self.nodes { + match node.distance { + Some(distance) => { + writeln!(f, " node {} (distance {distance}): {} tokens", node.label, node.spent)? + } + None => writeln!(f, " node {}: {} tokens", node.label, node.spent)?, } - if let Some(speech) = &act.speech { - write!(f, " says {:?}", speech.as_str())?; + for act in &node.acts { + let path = match act.render_path { + Some(RenderPath::ShipAction) => "ship_action", + Some(RenderPath::Conversation) => "conversation", + None => "-", + }; + write!(f, " {} {} [{path}]", act.speaker_label, act.verb)?; + for role in &act.roles { + write!(f, " {}={}", role.role, role.target)?; + } + if let Some(speech) = &act.speech { + write!(f, " says {:?}", speech.as_str())?; + } + if let Some(display) = &act.display { + write!(f, " shows {:?}", display.as_str())?; + } + writeln!(f)?; } - if let Some(display) = &act.display { - write!(f, " shows {:?}", display.as_str())?; + for refusal in &node.refusals { + let reason = match refusal.reason { + RefusalReason::Interrupted => "interrupted", + RefusalReason::WorldRejected => "world_rejected", + RefusalReason::OpportunityGone => "opportunity_gone", + RefusalReason::ScopeMoved => "scope_moved", + RefusalReason::ProposalUndecodable => "proposal_undecodable", + RefusalReason::RowDisagreesWithCell => "row_disagrees_with_cell", + RefusalReason::CallUnattributed => "call_unattributed", + }; + let label = self.labels.get(&refusal.subject).map_or("-", String::as_str); + writeln!(f, " refused: cell {} {label} {reason}", refusal.cell)?; } - writeln!(f)?; - } - for refusal in &checkpoint.refusals { - let reason = match refusal.reason { - RefusalReason::Interrupted => "interrupted", - RefusalReason::WorldRejected => "world_rejected", - RefusalReason::OpportunityGone => "opportunity_gone", - RefusalReason::ScopeMoved => "scope_moved", - RefusalReason::ProposalUndecodable => "proposal_undecodable", - RefusalReason::RowDisagreesWithCell => "row_disagrees_with_cell", - RefusalReason::CallUnattributed => "call_unattributed", - }; - let label = self.labels.get(&refusal.subject).map_or("-", String::as_str); - writeln!(f, " refused: cell {} {label} {reason}", refusal.cell)?; } for call in &checkpoint.unattributed { writeln!(f, " note: cell {} call names no handle: tool {:?}", call.cell, call.tool)?; @@ -446,6 +427,9 @@ impl VerseRunStore { } ticks.push(tick); } + (_, Some(schema)) if RETIRED_SCHEMAS.contains(&schema) => { + return Err(VerseRunError::RetiredSchema); + } _ => return Err(VerseRunError::Corrupt), } } @@ -557,18 +541,14 @@ impl VerseRunStore { token_cap: u64, config: &VerseRunConfig, ) -> Result { - let cover_budget = config.cover.validated()?; + config.knobs.validate()?; let record = VerseRunRecord { world_id: snapshot.world_id, sequence: self.next_sequence(snapshot.world_id)?, token_cap, ticks_requested: config.ticks, tick_span_minutes: config.tick_span.minutes(), - cover_budget: RecordedCoverBudget { - cells: cover_budget.cells, - constituent_cap: cover_budget.constituent_cap, - urgency_slots: cover_budget.urgency_slots, - }, + knobs: RecordedKnobs::of(&config.knobs), start_revision: snapshot.revision, checkpoints: Vec::new(), status: RunStatus::Running, @@ -629,212 +609,6 @@ impl VerseRunStore { } } -/// How an error ends a cell. -enum CellEnd { - Budget, - Fatal(&'static str), - Refused(RefusalReason), -} - -fn classify(error: &ControllerError) -> CellEnd { - match error { - ControllerError::Inference { source, .. } - if source.class() == InferenceFaultClass::BudgetExhausted => - { - CellEnd::Budget - } - _ if error.requires_quarantine() => CellEnd::Fatal("controller_quarantined"), - ControllerError::World(KernelError::ScopeChanged { .. }) => { - CellEnd::Refused(RefusalReason::ScopeMoved) - } - ControllerError::World(_) => CellEnd::Refused(RefusalReason::WorldRejected), - ControllerError::NoOpportunity { .. } - | ControllerError::AmbiguousOpportunity - | ControllerError::OpportunityMismatch => CellEnd::Refused(RefusalReason::OpportunityGone), - ControllerError::ScopeMoved => CellEnd::Refused(RefusalReason::ScopeMoved), - _ => CellEnd::Fatal("controller_error"), - } -} - -fn pending_code(reason: ControllerPendingReason) -> &'static str { - match reason { - ControllerPendingReason::InferenceRetryable => "inference_retryable", - ControllerPendingReason::InferenceRecoveryRequired => "inference_recovery_required", - ControllerPendingReason::WorldUnavailable => "world_unavailable", - ControllerPendingReason::WorldOutcomeUnknown => "world_outcome_unknown", - ControllerPendingReason::StoreReopenRequired => "store_reopen_required", - } -} - -fn command_of(submission: &SubmissionDisposition) -> CommandId { - match submission { - SubmissionDisposition::NoProposal(receipt) | SubmissionDisposition::Completed(receipt) => { - match receipt { - SubmitReceipt::Applied(commit) | SubmitReceipt::AlreadyApplied(commit) => { - commit.command_id - } - } - } - SubmissionDisposition::PreviouslyConfirmed(commit) => commit.command_id, - } -} - -/// Folds one cell's outcome into the tick. Returns the status that ends the -/// run, when the cell did not finish. A pending cell's unreached members are -/// not refusals: the tick stays open and they resume. -fn absorb( - result: Result, - cell: &Cell, - position: u32, - committed: &mut Vec, - refusals: &mut Vec, - unattributed: &mut Vec, -) -> Option { - match result { - Ok(run) => { - absorb_run(run, cell, position, committed, refusals, unattributed).map(failed) - } - Err(error) => match classify(&error) { - CellEnd::Budget => Some(RunStatus::BudgetExhausted), - CellEnd::Fatal(code) => Some(failed(code)), - CellEnd::Refused(reason) => { - refusals.extend(refuse_all(cell, position, reason)); - None - } - }, - } -} - -/// A finished cell's commits and refusals; the code of the pending state when -/// it did not finish. -fn absorb_run( - run: CellRun, - cell: &Cell, - position: u32, - committed: &mut Vec, - refusals: &mut Vec, - unattributed: &mut Vec, -) -> Option<&'static str> { - match run { - CellRun::Narrative(NarrativeRun::Completed(decision)) => { - committed.push(command_of(decision.submission())); - None - } - CellRun::Narrative(NarrativeRun::Pending(pending)) => Some(pending_code(pending.reason())), - CellRun::Narrative(NarrativeRun::Interrupted(_)) => { - refusals.extend(refuse_all(cell, position, RefusalReason::Interrupted)); - None - } - CellRun::Operational(OperationalRun::Completed(decision)) => { - committed.push(command_of(decision.submission())); - None - } - CellRun::Operational(OperationalRun::Pending(pending)) => { - Some(pending_code(pending.reason())) - } - CellRun::Grouped(run) => { - // The controller owns who is in the cell and says, for each - // member, committed or refused. The driver copies. A finished - // cell whose lists miss a member, or name one it lacks, is a - // broken invariant and ends the run, not a relabel. - unattributed.extend(run.unattributed.iter().map(|tool| UnattributedCall { - cell: position, - tool: tool.clone(), - })); - for entry in &run.submissions { - committed.push(command_of(&entry.submission)); - } - for refused in &run.refused { - refusals.push(Refusal { - cell: position, - subject: refused.subject, - reason: match refused.reason { - ConstituentRefusalReason::LeftBeforeSelection => { - RefusalReason::OpportunityGone - } - ConstituentRefusalReason::ScopeChanged => RefusalReason::ScopeMoved, - ConstituentRefusalReason::WorldRefused => RefusalReason::WorldRejected, - ConstituentRefusalReason::ProposalUndecodable => { - RefusalReason::ProposalUndecodable - } - ConstituentRefusalReason::RowDisagreesWithCell => { - RefusalReason::RowDisagreesWithCell - } - ConstituentRefusalReason::CallUnattributed => { - RefusalReason::CallUnattributed - } - }, - }); - } - if run.pending.is_none() { - let listed: Vec = run - .submissions - .iter() - .map(|entry| entry.subject) - .chain(run.refused.iter().map(|refused| refused.subject)) - .collect(); - let members = cell.members(); - let exact = listed.len() == members.len() - && members.iter().all(|member| listed.contains(&member.subject)); - if !exact { - return Some("cell_membership"); - } - } - run.pending.map(pending_code) - } - } -} - -/// One refusal per member of the cell. -fn refuse_all(cell: &Cell, position: u32, reason: RefusalReason) -> impl Iterator { - cell.members().iter().map(move |member| Refusal { - cell: position, - subject: member.subject, - reason, - }) -} - -/// The frozen cell with each member bound to the opportunity the world holds -/// for that subject now, and the frozen members that hold none. The partition -/// is fixed when the tick opens; an opportunity is the world's current binding -/// for a subject, and an earlier cell's act can move it (a word spoken in a -/// shared room changes what its listeners know). A subject that no longer holds -/// an opportunity leaves the cell, and an empty cell is gone. -fn refreshed( - frozen: &FrozenCell, - tick: TickIndex, - fresh: &[DecisionOpportunity], -) -> (Option, Vec) { - let mut gone = Vec::new(); - let mut members: Vec = Vec::new(); - for subject in &frozen.members { - match fresh - .iter() - .find(|opportunity| opportunity.scope.subject_id == *subject) - { - Some(opportunity) => members.push(Constituent { - subject: *subject, - opportunity: opportunity.clone(), - }), - None => gone.push(*subject), - } - } - let cell = if frozen.group { - (!members.is_empty()).then(|| Cell::Group { - id: frozen.id, - tick, - members, - }) - } else { - members.into_iter().next().map(|member| Cell::Singleton { - id: frozen.id, - tick, - member, - }) - }; - (cell, gone) -} - enum TickEnd { /// Every cell finished and the clock advanced. Closed, @@ -842,6 +616,14 @@ enum TickEnd { Open(RunStatus), } +/// The run status a wave's stop ends the run with. +fn status_of(stop: WaveStop) -> RunStatus { + match stop { + WaveStop::Budget => RunStatus::BudgetExhausted, + WaveStop::Fault(code) => failed(code), + } +} + fn failed(reason: &str) -> RunStatus { RunStatus::Failed { reason: reason.to_owned(), @@ -881,13 +663,10 @@ pub async fn run_manual( } let sequence = claim.sequence; let mut record = store.claimed(&claim)?; - let cover_budget = match config.cover.validated() { - Ok(cover_budget) if record_matches(&record, config, cover_budget) => cover_budget, - _ => { - store.abandon(claim, "config_not_this_claim")?; - return Err(VerseRunError::ConfigNotThisClaim); - } - }; + if config.knobs.validate().is_err() || !record_matches(&record, config) { + store.abandon(claim, "config_not_this_claim")?; + return Err(VerseRunError::ConfigNotThisClaim); + } // The record names the revision the run started from, so the run starts // from it. if record.start_revision != begun.revision { @@ -904,7 +683,6 @@ pub async fn run_manual( store, sequence, config, - cover_budget, spent_before, || mailbox.operator_log(), ) @@ -940,15 +718,10 @@ pub async fn run_manual( } /// Whether the record a claim wrote was made under this config. -fn record_matches(record: &VerseRunRecord, config: &VerseRunConfig, cover: CoverBudget) -> bool { +fn record_matches(record: &VerseRunRecord, config: &VerseRunConfig) -> bool { record.ticks_requested == config.ticks && record.tick_span_minutes == config.tick_span.minutes() - && record.cover_budget - == RecordedCoverBudget { - cells: cover.cells, - constituent_cap: cover.constituent_cap, - urgency_slots: cover.urgency_slots, - } + && record.knobs == RecordedKnobs::of(&config.knobs) } /// The key a run's provider calls are recorded under: the run's sequence, so a @@ -967,7 +740,6 @@ pub(crate) fn clock_command_id(world: WorldId, ordinal: u64) -> CommandId { /// One tick. The report is absent only when the world or the tick document /// could not be read at all. -#[allow(clippy::too_many_arguments)] async fn run_tick( mailbox: &WorldMailbox, runner: &ControllerRunner, @@ -975,7 +747,6 @@ async fn run_tick( store: &VerseRunStore, sequence: u64, config: &VerseRunConfig, - cover_budget: CoverBudget, spent_before: u64, read_log: ReadLog, ) -> (TickEnd, Option) @@ -988,10 +759,11 @@ where let ordinal = mailbox.clock_advances().await?; let opportunities = mailbox.opportunities().await?; let graph = mailbox.agency_graph().await?; - Ok::<_, MailboxError>((snapshot, ordinal, opportunities, graph)) + let hierarchy = mailbox.hierarchy().await?; + Ok::<_, MailboxError>((snapshot, ordinal, opportunities, graph, hierarchy)) } .await; - let Ok((snapshot, ordinal, opportunities, graph)) = read else { + let Ok((snapshot, ordinal, opportunities, graph, hierarchy)) = read else { return (TickEnd::Open(failed("world_unavailable")), None); }; let world = snapshot.world_id; @@ -1000,10 +772,10 @@ where ordinal, sequence, config, - cover_budget, &snapshot, &opportunities, &graph, + &hierarchy, ) else { return (TickEnd::Open(failed("run_store")), None); }; @@ -1012,41 +784,8 @@ where return (TickEnd::Open(failed("run_store")), None); }; - let mut committed = Vec::new(); - let mut refusals = Vec::new(); - let mut unattributed = Vec::new(); - let mut open: Option = None; - for (position, frozen) in tick.cells.iter().enumerate() { - let position = position as u32; - let fresh = match mailbox.opportunities().await { - Ok(fresh) => fresh, - Err(_) => { - open = Some(failed("world_unavailable")); - break; - } - }; - let (cell, gone) = refreshed(frozen, index, &fresh); - refusals.extend(gone.iter().map(|&subject| Refusal { - cell: position, - subject, - reason: RefusalReason::OpportunityGone, - })); - let Some(cell) = cell else { - continue; - }; - let result = runner.run_cell(&cell).await; - if let Some(status) = absorb( - result, - &cell, - position, - &mut committed, - &mut refusals, - &mut unattributed, - ) { - open = Some(status); - break; - } - } + let outcome = run_frozen_cells(mailbox, runner, index, &tick.cells, || port.spent()).await; + let mut open = outcome.stop.map(status_of); // The act listing is the tick's report to the operator: a tick whose log // cannot be read is not closed, and the run ends there. @@ -1075,7 +814,22 @@ where let spent = port.spent(); let checkpoint_closed = open.is_none(); - let labels = refusals + let mut checkpoint = TickCheckpoint { + tick: ordinal, + closed: checkpoint_closed, + cells: tick.cells.len() as u32, + committed: Vec::new(), + refusals: Vec::new(), + unattributed: Vec::new(), + tokens: spent.saturating_sub(spent_before), + }; + for node in &outcome.nodes { + checkpoint.committed.extend(node.committed.iter().copied()); + checkpoint.refusals.extend(node.refusals.iter().copied()); + checkpoint.unattributed.extend(node.unattributed.iter().cloned()); + } + let labels = checkpoint + .refusals .iter() .filter_map(|refusal| { snapshot @@ -1086,16 +840,8 @@ where }) .collect(); let report = TickReport { - checkpoint: TickCheckpoint { - tick: ordinal, - closed: checkpoint_closed, - cells: tick.cells.len() as u32, - committed, - refusals, - unattributed, - tokens: spent.saturating_sub(spent_before), - }, - acts, + nodes: node_reports(&tick.cells, &outcome, acts, &snapshot, &hierarchy), + checkpoint, labels, spent, remaining: port.cap().saturating_sub(spent), @@ -1103,6 +849,94 @@ where (open.map_or(TickEnd::Closed, TickEnd::Open), Some(report)) } +/// The tick's nodes in the order its frozen cells first name them, each with +/// the acts its members committed and the refusals its cells ended in. A node +/// the run never reached and that committed nothing is not listed. An act no +/// frozen cell claims is kept under a node labelled `-`, never dropped. +fn node_reports( + frozen: &[FrozenCell], + outcome: &WaveOutcome, + acts: Vec, + snapshot: &WorldSnapshot, + hierarchy: &Hierarchy, +) -> Vec { + let mut order: Vec<(NodeId, u8)> = Vec::new(); + let mut home: BTreeMap = BTreeMap::new(); + for cell in frozen { + let at = order + .iter() + .position(|(node, _)| *node == cell.node) + .unwrap_or_else(|| { + order.push((cell.node, cell.distance)); + order.len() - 1 + }); + home.extend(cell.members.iter().map(|member| (*member, at))); + } + let mut reports: Vec = order + .iter() + .map(|(node, distance)| { + let ran = outcome.nodes.iter().find(|ran| ran.node == *node); + NodeReport { + label: node_label(*node, snapshot, hierarchy), + distance: Some(*distance), + acts: Vec::new(), + refusals: ran.map(|ran| ran.refusals.clone()).unwrap_or_default(), + spent: ran.map_or(0, |ran| ran.spent), + } + }) + .collect(); + let ran: Vec = order + .iter() + .map(|(node, _)| outcome.nodes.iter().any(|ran| ran.node == *node)) + .collect(); + let mut unclaimed = Vec::new(); + for act in acts { + match home.get(&act.speaker) { + Some(&at) => reports[at].acts.push(act), + None => unclaimed.push(act), + } + } + let mut kept: Vec = reports + .into_iter() + .zip(ran) + .filter(|(report, ran)| *ran || !report.acts.is_empty()) + .map(|(report, _)| report) + .collect(); + if !unclaimed.is_empty() { + kept.push(NodeReport { + label: "-".into(), + distance: None, + acts: unclaimed, + refusals: Vec::new(), + spent: 0, + }); + } + kept +} + +/// What the operator calls a node: its anchor's label in the snapshot, `world` +/// for the root, `-` for an anchor the world no longer holds. +fn node_label(node: NodeId, snapshot: &WorldSnapshot, hierarchy: &Hierarchy) -> String { + let subject = |id: SubjectId| { + snapshot + .subjects + .iter() + .find(|subject| subject.id == id) + .map(|subject| subject.label.clone()) + }; + match hierarchy.nodes.get(&node).map(|node| node.anchor) { + Some(NodeAnchor::World) => Some("world".to_owned()), + Some(NodeAnchor::Institution(id) | NodeAnchor::Subject(id)) => subject(id), + Some(NodeAnchor::Place(entity)) => snapshot + .places + .iter() + .find(|place| place.id == entity) + .map(|place| place.label.clone()), + None => None, + } + .unwrap_or_else(|| "-".to_owned()) +} + /// The acts a tick committed: the operator log's events past the tick's /// opening revision. A log that cannot be read is `None`, never an empty tick. fn acts_since( @@ -1117,19 +951,20 @@ fn acts_since( } /// The tick document for `ordinal`: the open one a run left, or a new one -/// frozen from a cover derived now. An open tick the world has moved past is -/// closed as the world's first. A document already closed at the world's -/// current ordinal is a store that disagrees with the world. +/// frozen from a wave planned now over the derived hierarchy with no focus. An +/// open tick the world has moved past is closed as the world's first. A +/// document already closed at the world's current ordinal is a store that +/// disagrees with the world. #[allow(clippy::too_many_arguments)] fn open_or_find( store: &VerseRunStore, ordinal: u64, sequence: u64, config: &VerseRunConfig, - cover_budget: CoverBudget, snapshot: &WorldSnapshot, opportunities: &[DecisionOpportunity], graph: &AgencyGraph, + hierarchy: &Hierarchy, ) -> Result { let world = snapshot.world_id; store.close_ticks_before(world, ordinal)?; @@ -1140,20 +975,27 @@ fn open_or_find( Err(VerseRunError::OutOfSequence) }; } - let cover = derive_cover(world, TickIndex(ordinal), opportunities, graph, cover_budget); + let wave = plan_wave( + WaveClock { + world, + ordinal: TickIndex(ordinal), + now: FictionalMinutes(snapshot.now.0), + }, + hierarchy, + opportunities, + graph, + &Focus::default(), + &config.knobs, + )?; let tick = VerseTick { world_id: world, ordinal, opened_now: snapshot.now.0, opened_revision: snapshot.revision, span_minutes: config.tick_span.minutes(), - cover_budget: RecordedCoverBudget { - cells: cover_budget.cells, - constituent_cap: cover_budget.constituent_cap, - urgency_slots: cover_budget.urgency_slots, - }, - oversubscribed: cover.oversubscribed, - cells: cover.cells.iter().map(FrozenCell::of).collect(), + knobs: RecordedKnobs::of(&config.knobs), + oversubscribed: wave.turns.iter().any(|turn| turn.oversubscribed), + cells: wave.frozen(), opened_by_run: sequence, closed: None, }; diff --git a/crates/ghostlight/src/verse/run/tests.rs b/crates/ghostlight/src/verse/run/tests.rs index ff4236a..9b2ff5e 100644 --- a/crates/ghostlight/src/verse/run/tests.rs +++ b/crates/ghostlight/src/verse/run/tests.rs @@ -6,6 +6,10 @@ use crate::controllers::{ open_controller_work, }; use crate::cover::derive_cover; +use crate::controllers::{CellRun, ConstituentRefusalReason, ControllerError}; +use crate::cover::CellId; +use crate::wave::{CellEnd, absorb, classify, pending_code, refreshed}; +use crate::{Cell, CoverBudget, CoverBudgetError, SubmitReceipt}; use crate::tests::stock_weights; use crate::verse::{ CallRecordStore, CreateVerseWorldIntent, RecordingInferencePort, ReplayInferencePort, @@ -176,14 +180,35 @@ fn two_cells() -> CoverBudget { } } +/// The knobs of a flat verse: one band at the tick span and a depth that opens +/// only the root, so every faction speaks as a voice of one node. +fn flat_knobs(cover: CoverBudget) -> GestaltKnobs { + GestaltKnobs { + bands: vec![TickMinutes::new(SPAN).unwrap()], + depth: 1, + max_node_turns: 256, + cover, + } +} + fn config(ticks: u32) -> VerseRunConfig { VerseRunConfig { ticks, tick_span: TickMinutes::new(SPAN).unwrap(), - cover: two_cells(), + knobs: flat_knobs(two_cells()), } } +/// One node every hand-built frozen cell belongs to. +fn test_node() -> NodeId { + static WORLD: std::sync::OnceLock = std::sync::OnceLock::new(); + NodeId::of(*WORLD.get_or_init(WorldId::issue), &NodeAnchor::World) +} + +fn frozen_of(cell: &Cell) -> FrozenCell { + FrozenCell::of(cell, test_node(), 0) +} + /// An opened verse state root: the world, its call records, its run records /// and its controller work, as the binary holds them. struct Harness { @@ -364,12 +389,8 @@ async fn scripted_run_commits_and_checkpoints_every_tick() { assert_eq!(outcome.record.tick_span_minutes, SPAN); assert_eq!(outcome.record.start_revision, world.revision); assert_eq!( - outcome.record.cover_budget, - RecordedCoverBudget { - cells: 2, - constituent_cap: 8, - urgency_slots: 0 - } + outcome.record.knobs, + RecordedKnobs::of(&flat_knobs(two_cells())) ); // A tick's tokens are what the call store charged for its two calls. @@ -389,11 +410,11 @@ async fn scripted_run_commits_and_checkpoints_every_tick() { for (tick, report) in reports.iter().enumerate() { spent += report.checkpoint.tokens; assert!(report.checkpoint.closed); - assert_eq!(report.acts.len(), 2); + assert_eq!(report.acts().count(), 2); assert_eq!(report.spent, spent); assert_eq!(report.remaining, 10_000_000 - spent); assert_eq!(report.checkpoint, outcome.record.checkpoints[tick]); - for act in &report.acts { + for act in report.acts() { assert_eq!(act.verb, "speak"); assert_eq!( act.speech.as_ref().unwrap().as_str(), @@ -404,7 +425,7 @@ async fn scripted_run_commits_and_checkpoints_every_tick() { // A tick reports only its own acts. let revisions: Vec = reports .iter() - .flat_map(|report| report.acts.iter().map(|act| act.revision)) + .flat_map(|report| report.acts().map(|act| act.revision)) .collect(); assert_eq!(revisions.len(), 6); assert!(revisions.windows(2).all(|pair| pair[0] < pair[1])); @@ -444,7 +465,7 @@ async fn budget_exhausted_stops_before_the_clock_and_resumes() { // The open tick is reported, unclosed, with what it committed. assert_eq!(reports.len(), 1); assert!(!reports[0].checkpoint.closed); - assert_eq!(reports[0].acts.len(), 1); + assert_eq!(reports[0].acts().count(), 1); assert_eq!(&reports[0].checkpoint, open); assert!(reports[0].remaining < first_bound); assert_eq!( @@ -485,17 +506,17 @@ async fn budget_exhausted_stops_before_the_clock_and_resumes() { assert!(closing.refusals.is_empty(), "{closing:?}"); assert_eq!(resumed.record.ticks_closed(), 2); // The tick reports the act this run committed and not the one it found. - assert_eq!(resumed_reports[0].acts.len(), 1); - assert!(resumed_reports[0].acts[0].revision > reports[0].acts[0].revision); + assert_eq!(resumed_reports[0].acts().count(), 1); + assert!(resumed_reports[0].acts().next().unwrap().revision > reports[0].acts().next().unwrap().revision); assert_ne!( - resumed_reports[0].acts[0].speaker_label, - reports[0].acts[0].speaker_label + resumed_reports[0].acts().next().unwrap().speaker_label, + reports[0].acts().next().unwrap().speaker_label ); assert_eq!(resumed.record.checkpoints[1].committed.len(), 2); } -/// Both cells of a tick committed through another driver before any run opened -/// it, one after the other, so each one's act has since moved the other's +/// Both cells of an open tick committed through another driver before any run +/// resumed it, one after the other, so each one's act has since moved the other's /// scope. The run that opens the tick reaches both committed rows, in whatever /// order it froze, and answers each with its receipt: no inference, no refusal, /// no second act. `reverse` flips which cell the other driver committed first, @@ -516,6 +537,10 @@ async fn resumed_after_both_cells_committed_elsewhere(reverse: bool) { }, ); assert_eq!(cover.cells.len(), 2); + // The tick is open with both cells frozen before the other driver acts: a + // tick opened after both were attended would plan neither, they are not + // yet due again. + open_tick_with(&verse, cover.cells.iter().map(frozen_of).collect()).await; let elsewhere = ScriptedPort::speaking(); let runner = ControllerRunner::open( verse.mailbox.clone(), @@ -531,7 +556,7 @@ async fn resumed_after_both_cells_committed_elsewhere(reverse: bool) { }; for cell in order { let fresh = verse.mailbox.opportunities().await.unwrap(); - let bound = refreshed(&FrozenCell::of(cell), TickIndex(0), &fresh).0.unwrap(); + let bound = refreshed(&frozen_of(cell), TickIndex(0), &fresh).0.unwrap(); runner.run_cell(&bound).await.unwrap(); } assert_eq!(verse.acts().await, 2); @@ -719,27 +744,34 @@ fn the_operator_reads_refusals_and_how_a_run_ended() { subject, reason, }; + let refusals = vec![ + refusal(1, one, RefusalReason::WorldRejected), + refusal(2, two, RefusalReason::OpportunityGone), + refusal(0, three, RefusalReason::Interrupted), + refusal(5, four, RefusalReason::ScopeMoved), + refusal(3, five, RefusalReason::RowDisagreesWithCell), + refusal(3, six, RefusalReason::CallUnattributed), + ]; let report = TickReport { checkpoint: TickCheckpoint { tick: 4, closed: false, cells: 3, committed: Vec::new(), - refusals: vec![ - refusal(1, one, RefusalReason::WorldRejected), - refusal(2, two, RefusalReason::OpportunityGone), - refusal(0, three, RefusalReason::Interrupted), - refusal(5, four, RefusalReason::ScopeMoved), - refusal(3, five, RefusalReason::RowDisagreesWithCell), - refusal(3, six, RefusalReason::CallUnattributed), - ], + refusals: refusals.clone(), unattributed: vec![UnattributedCall { cell: 3, tool: "c9__speak".into(), }], tokens: 7, }, - acts: Vec::new(), + nodes: vec![NodeReport { + label: "Ironmarket Guild".into(), + distance: Some(1), + acts: Vec::new(), + refusals, + spent: 7, + }], labels: BTreeMap::from([ (one, "Ada".to_owned()), (two, "Brann".to_owned()), @@ -755,12 +787,13 @@ fn the_operator_reads_refusals_and_how_a_run_ended() { report.to_string(), concat!( "tick 4 open: 3 cells, 0 acts, 6 refused\n", - " refused: cell 1 Ada world_rejected\n", - " refused: cell 2 Brann opportunity_gone\n", - " refused: cell 0 Cato interrupted\n", - " refused: cell 5 Dura scope_moved\n", - " refused: cell 3 Eve row_disagrees_with_cell\n", - " refused: cell 3 Fay call_unattributed\n", + " node Ironmarket Guild (distance 1): 7 tokens\n", + " refused: cell 1 Ada world_rejected\n", + " refused: cell 2 Brann opportunity_gone\n", + " refused: cell 0 Cato interrupted\n", + " refused: cell 5 Dura scope_moved\n", + " refused: cell 3 Eve row_disagrees_with_cell\n", + " refused: cell 3 Fay call_unattributed\n", " note: cell 3 call names no handle: tool \"c9__speak\"\n", " tokens: 7 this tick, 40 spent, 60 remaining\n", ) @@ -807,7 +840,7 @@ async fn an_act_names_its_verb_render_path_and_bound_roles() { .await; assert_eq!(outcome.record.status, RunStatus::Completed); let catalog = read_aetheria_catalog(FIXTURE).unwrap(); - let acts = &reports[0].acts; + let acts: Vec<&OperatorEvent> = reports[0].acts().collect(); let attack = acts.iter().find(|act| act.verb == "attack").unwrap(); assert_eq!(attack.speaker_label, "Adrasteia"); assert_eq!( @@ -834,12 +867,12 @@ async fn an_act_names_its_verb_render_path_and_bound_roles() { "{text}" ); let attack_line = format!( - "\n Adrasteia attack [{}] target=Brannoch says \"Adrasteia strikes.\"\n", + "\n Adrasteia attack [{}] target=Brannoch says \"Adrasteia strikes.\"\n", name("attack") ); assert!(text.contains(&attack_line), "{text}"); let speak_line = format!( - "\n Brannoch speak [{}] says \"Brannoch answers.\"\n", + "\n Brannoch speak [{}] says \"Brannoch answers.\"\n", name("speak") ); assert!(text.contains(&speak_line), "{text}"); @@ -906,7 +939,7 @@ async fn a_cell_is_run_on_what_the_world_holds_for_its_members_now() { let Cell::Singleton { member: held, .. } = cell else { panic!("two subjects under two cells are singletons") }; - let frozen = FrozenCell::of(cell); + let frozen = frozen_of(cell); let (Some(Cell::Singleton { member, .. }), gone) = refreshed(&frozen, TickIndex(0), &moved) else { panic!("a subject that still has an opportunity keeps its cell") }; @@ -917,7 +950,7 @@ async fn a_cell_is_run_on_what_the_world_holds_for_its_members_now() { assert_eq!(member.opportunity.scope.subject_id, member.subject); assert!(gone.is_empty()); } - let frozen_group = FrozenCell::of(grouped); + let frozen_group = frozen_of(grouped); let (Some(Cell::Group { members: now, .. }), gone) = refreshed(&frozen_group, TickIndex(0), &moved) else { @@ -943,7 +976,7 @@ async fn a_cell_is_run_on_what_the_world_holds_for_its_members_now() { let gone = singles .cells .iter() - .filter(|cell| refreshed(&FrozenCell::of(cell), TickIndex(0), one).0.is_none()) + .filter(|cell| refreshed(&frozen_of(cell), TickIndex(0), one).0.is_none()) .count(); assert_eq!(gone, 1); let (nothing, all_gone) = refreshed(&frozen_group, TickIndex(0), &[]); @@ -1079,10 +1112,10 @@ async fn a_run_started_on_the_wrong_port_world_or_config_is_refused_and_its_clai // A cover budget with no cells cannot be claimed: no record exists. let mut bad = config(1); - bad.cover.cells = 0; + bad.knobs.cover.cells = 0; assert!(matches!( verse.runs.claim(&world, 1_000, &bad), - Err(VerseRunError::Budget(CoverBudgetError::NoCells)) + Err(VerseRunError::Knobs(GestaltKnobsError::Cover(CoverBudgetError::NoCells))) )); assert!(verse.runs.runs(world.world_id).unwrap().is_empty()); @@ -1113,11 +1146,11 @@ async fn a_run_started_on_the_wrong_port_world_or_config_is_refused_and_its_clai }), ("cells", config_of(1, SPAN, 3)), ("constituent cap", VerseRunConfig { - cover: CoverBudget { constituent_cap: 9, ..two_cells() }, + knobs: flat_knobs(CoverBudget { constituent_cap: 9, ..two_cells() }), ..config(1) }), ("urgency slots", VerseRunConfig { - cover: CoverBudget { urgency_slots: 1, ..two_cells() }, + knobs: flat_knobs(CoverBudget { urgency_slots: 1, ..two_cells() }), ..config(1) }), ]; @@ -1196,11 +1229,7 @@ fn record(world: WorldId, sequence: u64) -> VerseRunRecord { token_cap: 10, ticks_requested: 1, tick_span_minutes: SPAN, - cover_budget: RecordedCoverBudget { - cells: 2, - constituent_cap: 8, - urgency_slots: 0, - }, + knobs: RecordedKnobs::of(&flat_knobs(two_cells())), start_revision: 0, checkpoints: Vec::new(), status: RunStatus::Running, @@ -1370,7 +1399,6 @@ async fn an_unreadable_operator_log_ends_the_run_with_no_clock_advance() { &verse.runs, 1, &config, - config.cover.validated().unwrap(), 0, || async { Err(MailboxError::Unavailable) }, ) @@ -1382,7 +1410,7 @@ async fn an_unreadable_operator_log_ends_the_run_with_no_clock_advance() { let report = report.expect("the tick's checkpoint is kept"); assert!(!report.checkpoint.closed); assert!(!report.checkpoint.committed.is_empty(), "the cells ran"); - assert!(report.acts.is_empty()); + assert!(report.acts().next().is_none()); assert_eq!(verse.mailbox.clock_advances().await.unwrap(), 0); assert_eq!(verse.now().await, world.now.0); let tick = verse.runs.tick(world.world_id, 0).unwrap().unwrap(); @@ -1404,7 +1432,7 @@ fn the_run_store_refuses_rows_that_are_not_canonical_run_records() { let named = rmp_serde::to_vec_named(&good).unwrap(); let cases = [ // Another schema version is not migrated. - envelope(row_key(world, 1), "ghostlight.verse_run.v2", named.clone()), + envelope(row_key(world, 1), "ghostlight.verse_run.v3", named.clone()), // A row under a key that is not its own. envelope(row_key(world, 9), RUN_RECORD_SCHEMA, named.clone()), // A payload that is not the record. @@ -1469,11 +1497,11 @@ fn config_of(ticks: u32, span: u32, cells: u16) -> VerseRunConfig { VerseRunConfig { ticks, tick_span: TickMinutes::new(span).unwrap(), - cover: CoverBudget { + knobs: flat_knobs(CoverBudget { cells, constituent_cap: 8, urgency_slots: 0, - }, + }), } } @@ -1556,7 +1584,7 @@ async fn a_resume_under_another_cover_budget_keeps_the_frozen_cells() { let (_dir, verse, resumed) = resumed_after_a_pending_cell(config_of(1, 60, 1)).await; let world = verse.mailbox.snapshot().await.unwrap().world_id; let tick = verse.runs.tick(world, 1).unwrap().unwrap(); - assert_eq!(tick.cover_budget.cells, 2); + assert_eq!(tick.knobs.cells, 2); assert_eq!(tick.cells.len(), 2); assert!(tick.cells.iter().all(|cell| !cell.group)); assert_eq!(resumed.record.checkpoints[0].cells, 2); @@ -1683,11 +1711,7 @@ fn tick_doc(world: WorldId, ordinal: u64) -> VerseTick { opened_now: 0, opened_revision: 3, span_minutes: SPAN, - cover_budget: RecordedCoverBudget { - cells: 2, - constituent_cap: 8, - urgency_slots: 0, - }, + knobs: RecordedKnobs::of(&flat_knobs(two_cells())), oversubscribed: false, cells: Vec::new(), opened_by_run: 1, @@ -1766,7 +1790,7 @@ fn the_tick_store_opens_once_closes_once_and_refuses_non_canonical_rows() { let named = rmp_serde::to_vec_named(&good).unwrap(); let cases = [ envelope(tick_key(world, 9), TICK_ROW, TICK_RECORD_SCHEMA, named.clone()), - envelope(tick_key(world, 0), TICK_ROW, "ghostlight.verse_tick.v2", named.clone()), + envelope(tick_key(world, 0), TICK_ROW, "ghostlight.verse_tick.v3", named.clone()), envelope(tick_key(world, 0), TICK_ROW, TICK_RECORD_SCHEMA, vec![0xc0]), envelope( tick_key(world, 0), @@ -1943,11 +1967,11 @@ fn one_cell(ticks: u32) -> VerseRunConfig { VerseRunConfig { ticks, tick_span: TickMinutes::new(SPAN).unwrap(), - cover: CoverBudget { + knobs: flat_knobs(CoverBudget { cells: 1, constituent_cap: 8, urgency_slots: 0, - }, + }), } } @@ -2111,11 +2135,7 @@ async fn open_tick_with(verse: &Harness, cells: Vec) { opened_now: snapshot.now.0, opened_revision: snapshot.revision, span_minutes: SPAN, - cover_budget: RecordedCoverBudget { - cells: 2, - constituent_cap: 8, - urgency_slots: 0, - }, + knobs: RecordedKnobs::of(&flat_knobs(two_cells())), oversubscribed: false, cells, opened_by_run: 1, @@ -2155,11 +2175,15 @@ async fn a_tick_refuses_the_frozen_members_that_hold_no_opportunity_by_cell_and_ id: group, group: true, members, + node: test_node(), + distance: 0, }, FrozenCell { id: single, group: false, members: vec![g3], + node: test_node(), + distance: 0, }, ], ) @@ -2224,6 +2248,8 @@ async fn a_row_lacking_a_frozen_member(lacking_first: bool, behind_a_gone_cell: id: single, group: false, members: vec![gone], + node: test_node(), + distance: 0, }]; all.extend(cells); all @@ -2238,6 +2264,8 @@ async fn a_row_lacking_a_frozen_member(lacking_first: bool, behind_a_gone_cell: id: group, group: true, members: vec![a, SubjectId::issue()], + node: test_node(), + distance: 0, }]), ) .await; @@ -2254,6 +2282,8 @@ async fn a_row_lacking_a_frozen_member(lacking_first: bool, behind_a_gone_cell: id: group, group: true, members: if lacking_first { vec![b, a] } else { vec![a, b] }, + node: test_node(), + distance: 0, }]); verse.runs.put_tick(&tick).unwrap(); let cell = u32::from(behind_a_gone_cell); @@ -2292,6 +2322,8 @@ async fn a_row_member_outside_the_frozen_cell_is_never_listed() { id: group, group: true, members: vec![a, b], + node: test_node(), + distance: 0, }], ) .await; @@ -2308,6 +2340,8 @@ async fn a_row_member_outside_the_frozen_cell_is_never_listed() { id: group, group: true, members: vec![a], + node: test_node(), + distance: 0, }]; verse.runs.put_tick(&tick).unwrap(); let second = verse @@ -2337,7 +2371,7 @@ fn fold( &mut refusals, &mut Vec::new(), ); - (status, committed, refusals) + (status.map(status_of), committed, refusals) } fn grouped_refusing( @@ -2527,11 +2561,15 @@ async fn a_grouped_cell_behind_another_is_accounted_at_its_own_position() { id: single, group: false, members: vec![gone], + node: test_node(), + distance: 0, }, FrozenCell { id: group, group: true, members: real.clone(), + node: test_node(), + distance: 0, }, ], ) @@ -2781,3 +2819,209 @@ async fn a_call_naming_no_handle_is_printed_and_its_quiet_member_is_refused_not_ assert!(!printed.contains("SENTINEL-ARGUMENT")); assert_every_member_accounted_for(&verse, &outcome).await; } + +// ---- The tick freezes a planned wave ---- + +/// Knobs that open every institution of the fixture world: each faction is its +/// own node, one band at the tick span. +fn deep_config(ticks: u32) -> VerseRunConfig { + VerseRunConfig { + knobs: GestaltKnobs { + depth: u8::MAX, + ..flat_knobs(two_cells()) + }, + ..config(ticks) + } +} + +/// Opens tick 0 of a fresh world under `config` and returns what the planner +/// was given alongside the open tick document. +async fn opened_tick(verse: &Harness, config: &VerseRunConfig) -> VerseTick { + let snapshot = verse.mailbox.snapshot().await.unwrap(); + open_or_find( + &verse.runs, + 0, + 1, + config, + &snapshot, + &verse.mailbox.opportunities().await.unwrap(), + &verse.mailbox.agency_graph().await.unwrap(), + &verse.mailbox.hierarchy().await.unwrap(), + ) + .unwrap() +} + +#[tokio::test] +async fn a_flat_world_plans_what_the_old_cover_did() { + let (_dir, verse) = Harness::fresh().await; + let snapshot = verse.mailbox.snapshot().await.unwrap(); + let old = derive_cover( + snapshot.world_id, + TickIndex(0), + &verse.mailbox.opportunities().await.unwrap(), + &verse.mailbox.agency_graph().await.unwrap(), + two_cells(), + ); + let tick = opened_tick(&verse, &config(1)).await; + + let frozen: Vec<(CellId, bool, Vec)> = tick + .cells + .iter() + .map(|cell| (cell.id, cell.group, cell.members.clone())) + .collect(); + let derived: Vec<(CellId, bool, Vec)> = old + .cells + .iter() + .map(frozen_of) + .map(|cell| (cell.id, cell.group, cell.members)) + .collect(); + assert_eq!(frozen, derived); + assert_eq!(tick.oversubscribed, old.oversubscribed); + // One node speaks for every faction, at the rest band's distance. + assert!(tick.cells.iter().all(|cell| cell.node == tick.cells[0].node)); + assert!(tick.cells.iter().all(|cell| cell.distance == 0)); + assert_eq!(tick.knobs, RecordedKnobs::of(&flat_knobs(two_cells()))); +} + +#[tokio::test] +async fn opening_every_institution_gives_each_faction_its_own_node() { + let (_dir, verse) = Harness::fresh().await; + let tick = opened_tick(&verse, &deep_config(1)).await; + let nodes: std::collections::BTreeSet = tick.cells.iter().map(|cell| cell.node).collect(); + assert_eq!(nodes.len(), 2, "{:?}", tick.cells); + assert_eq!(tick.cells.len(), 2); + assert_eq!(tick.knobs.depth, u8::MAX); +} + +#[tokio::test] +async fn a_resumed_wave_reruns_the_same_cells_and_ids() { + let (_dir, verse) = Harness::fresh().await; + let ordinal = verse.mailbox.clock_advances().await.unwrap(); + let world = verse.mailbox.snapshot().await.unwrap().world_id; + + let ended = verse + .run_quietly_under(fault_at(1), deep_config(1)) + .await; + assert_eq!( + ended.record.status, + RunStatus::Failed { + reason: "inference_retryable".into() + } + ); + let frozen = verse.runs.tick(world, ordinal).unwrap().unwrap(); + assert!(frozen.closed.is_none()); + let [first] = ended.record.checkpoints.as_slice() else { + panic!("the killed run left its open tick's checkpoint") + }; + assert!(!first.closed); + assert_eq!(first.committed.len(), 1, "one cell finished before the fault"); + assert_eq!(verse.acts().await, 1); + + // The resuming run asks for other knobs; the open tick keeps its own. + let resumed = verse + .run_quietly_under(ScriptedPort::speaking(), config(1)) + .await; + assert_eq!(resumed.record.status, RunStatus::Completed); + let after = verse.runs.tick(world, ordinal).unwrap().unwrap(); + assert_eq!(after.cells, frozen.cells); + assert_eq!(after.knobs, frozen.knobs); + let [closing] = resumed.record.checkpoints.as_slice() else { + panic!("the resuming run closed one tick") + }; + assert!(closing.closed); + assert_eq!(closing.committed.len(), 2); + assert_eq!( + closing.committed[0], first.committed[0], + "the kernel answered the re-submission with the original receipt" + ); + assert_eq!(verse.acts().await, 2, "no act was committed twice"); +} + +#[tokio::test] +async fn a_tick_report_groups_acts_and_refusals_by_node() { + let (_dir, verse) = Harness::fresh().await; + let config = deep_config(1); + let mut tick = opened_tick(&verse, &config).await; + // A frozen member of the second node that holds no opportunity. + let second = tick.cells[1].clone(); + let gone = SubjectId::issue(); + tick.cells.push(FrozenCell { + id: second.id, + group: false, + members: vec![gone], + node: second.node, + distance: second.distance, + }); + verse.runs.put_tick(&tick).unwrap(); + + let mut reports = Vec::new(); + let outcome = verse + .run_under(ScriptedPort::speaking(), u64::MAX, config, |report| { + reports.push(report.clone()); + ControlFlow::Continue(()) + }) + .await; + assert_eq!(outcome.record.status, RunStatus::Completed); + let [report] = reports.as_slice() else { + panic!("one tick reported") + }; + let labels: Vec<&str> = report.nodes.iter().map(|node| node.label.as_str()).collect(); + assert_eq!(labels.len(), 2); + assert!(labels.contains(&"Adrasteia") && labels.contains(&"Brannoch"), "{labels:?}"); + for node in &report.nodes { + assert_eq!(node.distance, Some(0)); + assert!(node.spent > 0); + assert_eq!(node.acts.len(), 1); + assert_eq!(node.acts[0].speaker_label, node.label, "an act sits under its own node"); + } + assert_eq!( + report.nodes.iter().map(|node| node.spent).sum::(), + report.checkpoint.tokens + ); + // The refusal is in the second node's report alone. + let refused: Vec<(&str, usize)> = report + .nodes + .iter() + .map(|node| (node.label.as_str(), node.refusals.len())) + .collect(); + assert_eq!(refused.iter().filter(|(_, count)| *count == 1).count(), 1, "{refused:?}"); + assert_eq!(refused.iter().filter(|(_, count)| *count == 0).count(), 1, "{refused:?}"); + assert_eq!( + report.nodes.iter().flat_map(|node| node.refusals.iter()).copied().collect::>(), + report.checkpoint.refusals + ); + assert_eq!(report.checkpoint.refusals[0].subject, gone); + let text = report.to_string(); + assert!(text.contains(" node Adrasteia (distance 0): "), "{text}"); + assert!(text.contains(" Brannoch speak "), "{text}"); +} + +#[tokio::test] +async fn a_v1_tick_or_run_row_is_refused_by_name() { + let dir = tempfile::tempdir().unwrap(); + let world = WorldId::nil_for_test(); + for (index, (row, schema)) in [ + ("verse_tick.v1", "ghostlight.verse_tick.v1"), + ("verse_run.v1", "ghostlight.verse_run.v1"), + ] + .into_iter() + .enumerate() + { + let file = dir.path().join(format!("retired-{index}.cc")); + { + let mut raw = OwnedRedbMessagePackBackingStore::new(&file).unwrap(); + raw.push(&CultCacheEnvelope { + key: tick_key(world, 0), + r#type: row.into(), + payload: vec![0xc0], + stored_at: Utc::now().to_rfc3339(), + schema_id: Some(schema.into()), + }) + .unwrap(); + } + assert!( + matches!(VerseRunStore::open(&file), Err(VerseRunError::RetiredSchema)), + "{schema} was not refused by name" + ); + } +} diff --git a/crates/ghostlight/src/wave.rs b/crates/ghostlight/src/wave.rs index 4e5a6d3..2e8edf0 100644 --- a/crates/ghostlight/src/wave.rs +++ b/crates/ghostlight/src/wave.rs @@ -1,7 +1,9 @@ -//! The wave planner: one pure function that says which nodes of the hierarchy -//! take a turn now, and how each node's voices partition into cells. +//! The wave: one pure planner that says which nodes of the hierarchy take a +//! turn now and how each node's voices partition into cells, and the one runner +//! that carries a frozen plan through the controller organ. //! -//! This organ owns the plan and nothing else. [`plan_wave`] is pure over its +//! This organ owns the plan and the order its cells run in, and nothing else. +//! [`plan_wave`] is pure over its //! arguments: no clock read, no entropy, no mailbox, no filesystem, no store. //! Due-ness is derived from the kernel's `last_opportunity_at` (carried in the //! hierarchy as `last_attended`), so there is no schedule to keep in step with @@ -23,12 +25,25 @@ //! rest are reported, never dropped. Inside a node [`derive_cover`] partitions //! the voices with the wave ordinal as its tick, so its rotation guarantee and //! its oversubscription signal hold per node. +//! +//! A driver freezes [`Wave::frozen`] in its own document before the first +//! inference and hands the frozen cells to [`run_frozen_cells`], which binds +//! each to what the world holds now, runs it, and folds the outcome into its +//! node. The runner never advances the clock and never chooses a cell: time +//! and the document are the driver's. use super::{ - AgencyGraph, Cell, CoverBudget, CoverBudgetError, DecisionOpportunity, EntityId, - FictionalMinutes, SubjectId, TickIndex, TickMinutes, WorldId, derive_cover, + AgencyGraph, Cell, CellId, CommandId, Constituent, CoverBudget, CoverBudgetError, + DecisionOpportunity, EntityId, FictionalMinutes, KernelError, SubjectId, SubmitReceipt, + TickIndex, TickMinutes, WorldId, WorldMailbox, derive_cover, + controllers::{ + CellRun, ConstituentRefusalReason, ControllerError, ControllerPendingReason, + ControllerRunner, InferenceFaultClass, NarrativeRun, OperationalRun, + SubmissionDisposition, + }, hierarchy::{Hierarchy, Node, NodeAnchor, NodeId}, }; +use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; /// The standing knobs: how often each distance band runs, how far the focus @@ -335,6 +350,411 @@ pub fn plan_wave( }) } +/// Why a cell committed nothing and the run went on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum RefusalReason { + /// A narrative turn the world moved under and could not lower again. + Interrupted, + /// The world refused the cell's submission. + WorldRejected, + /// The cell's subject no longer holds an opportunity. + OpportunityGone, + /// The cell's work was bound to a scope that has since moved. Work still + /// reasoning is refused by the operational lane's world check before each + /// inference round. Work whose submission body + /// was persisted but never sent is submitted and refused by the world with + /// `ScopeChanged`. Narrative work is never refused for a moved scope at + /// resume: the kernel refuses it at submit and the same prose is + /// re-lowered once, and only a second move ends it overtaken. A cell whose + /// command already committed does not end this way: the controller answers it with its receipt whatever the scope + /// has done since. + ScopeMoved, + /// A grouped member's own tool call could not be decoded and it proposed + /// nothing else. No turn was submitted for it. + ProposalUndecodable, + /// A resumed cell's persisted row did not hold this member. No turn was + /// submitted for it. + RowDisagreesWithCell, + /// A tool call in the member's cell named no handle and the member + /// finished with no choice of its own, so no turn was submitted for it. + CallUnattributed, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Refusal { + /// The cell's position in the wave's frozen cells. + pub cell: u32, + /// The frozen member that committed nothing. Every member of a closed + /// tick's cells is in `committed` or here, once. + pub subject: SubjectId, + pub reason: RefusalReason, +} + +/// A tool call in a grouped cell that named no handle in it. The name is the +/// call's own, capped; its arguments are never kept. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct UnattributedCall { + /// The cell's position in the wave's frozen cells. + pub cell: u32, + pub tool: String, +} + + +/// A cell as the driver's document froze it: the partition's identity, its +/// members and the node turn it belongs to, decided once when the wave was +/// planned. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct FrozenCell { + pub id: CellId, + /// True for a `Cell::Group`, even one a refresh has left a single member. + pub group: bool, + pub members: Vec, + /// The node whose turn this cell is part of. + pub node: NodeId, + /// That node's hierarchy distance from the focus when it was planned. + pub distance: u8, +} + +impl FrozenCell { + pub(crate) fn of(cell: &Cell, node: NodeId, distance: u8) -> Self { + let (id, group) = match cell { + Cell::Singleton { id, .. } => (*id, false), + Cell::Group { id, .. } => (*id, true), + }; + Self { + id, + group, + members: cell.members().iter().map(|member| member.subject).collect(), + node, + distance, + } + } +} + +impl Wave { + /// The wave's cells in run order, nearest node first, each carrying its + /// node: what a driver writes down before the first inference. + pub fn frozen(&self) -> Vec { + self.turns + .iter() + .flat_map(|turn| { + turn.cells + .iter() + .map(move |cell| FrozenCell::of(cell, turn.node, turn.distance)) + }) + .collect() + } +} + +/// How an error ends a cell. +pub(crate) enum CellEnd { + Budget, + Fatal(&'static str), + Refused(RefusalReason), +} + +pub(crate) fn classify(error: &ControllerError) -> CellEnd { + match error { + ControllerError::Inference { source, .. } + if source.class() == InferenceFaultClass::BudgetExhausted => + { + CellEnd::Budget + } + _ if error.requires_quarantine() => CellEnd::Fatal("controller_quarantined"), + ControllerError::World(KernelError::ScopeChanged { .. }) => { + CellEnd::Refused(RefusalReason::ScopeMoved) + } + ControllerError::World(_) => CellEnd::Refused(RefusalReason::WorldRejected), + ControllerError::NoOpportunity { .. } + | ControllerError::AmbiguousOpportunity + | ControllerError::OpportunityMismatch => CellEnd::Refused(RefusalReason::OpportunityGone), + ControllerError::ScopeMoved => CellEnd::Refused(RefusalReason::ScopeMoved), + _ => CellEnd::Fatal("controller_error"), + } +} + +pub(crate) fn pending_code(reason: ControllerPendingReason) -> &'static str { + match reason { + ControllerPendingReason::InferenceRetryable => "inference_retryable", + ControllerPendingReason::InferenceRecoveryRequired => "inference_recovery_required", + ControllerPendingReason::WorldUnavailable => "world_unavailable", + ControllerPendingReason::WorldOutcomeUnknown => "world_outcome_unknown", + ControllerPendingReason::StoreReopenRequired => "store_reopen_required", + } +} + +fn command_of(submission: &SubmissionDisposition) -> CommandId { + match submission { + SubmissionDisposition::NoProposal(receipt) | SubmissionDisposition::Completed(receipt) => { + match receipt { + SubmitReceipt::Applied(commit) | SubmitReceipt::AlreadyApplied(commit) => { + commit.command_id + } + } + } + SubmissionDisposition::PreviouslyConfirmed(commit) => commit.command_id, + } +} + +/// Folds one cell's outcome into its node. Returns what ends the wave, when the cell did not finish. A pending cell's unreached members are +/// not refusals: the tick stays open and they resume. +pub(crate) fn absorb( + result: Result, + cell: &Cell, + position: u32, + committed: &mut Vec, + refusals: &mut Vec, + unattributed: &mut Vec, +) -> Option { + match result { + Ok(run) => { + absorb_run(run, cell, position, committed, refusals, unattributed).map(WaveStop::Fault) + } + Err(error) => match classify(&error) { + CellEnd::Budget => Some(WaveStop::Budget), + CellEnd::Fatal(code) => Some(WaveStop::Fault(code)), + CellEnd::Refused(reason) => { + refusals.extend(refuse_all(cell, position, reason)); + None + } + }, + } +} + +/// A finished cell's commits and refusals; the code of the pending state when +/// it did not finish. +fn absorb_run( + run: CellRun, + cell: &Cell, + position: u32, + committed: &mut Vec, + refusals: &mut Vec, + unattributed: &mut Vec, +) -> Option<&'static str> { + match run { + CellRun::Narrative(NarrativeRun::Completed(decision)) => { + committed.push(command_of(decision.submission())); + None + } + CellRun::Narrative(NarrativeRun::Pending(pending)) => Some(pending_code(pending.reason())), + CellRun::Narrative(NarrativeRun::Interrupted(_)) => { + refusals.extend(refuse_all(cell, position, RefusalReason::Interrupted)); + None + } + CellRun::Operational(OperationalRun::Completed(decision)) => { + committed.push(command_of(decision.submission())); + None + } + CellRun::Operational(OperationalRun::Pending(pending)) => { + Some(pending_code(pending.reason())) + } + CellRun::Grouped(run) => { + // The controller owns who is in the cell and says, for each + // member, committed or refused. The driver copies. A finished + // cell whose lists miss a member, or name one it lacks, is a + // broken invariant and ends the run, not a relabel. + unattributed.extend(run.unattributed.iter().map(|tool| UnattributedCall { + cell: position, + tool: tool.clone(), + })); + for entry in &run.submissions { + committed.push(command_of(&entry.submission)); + } + for refused in &run.refused { + refusals.push(Refusal { + cell: position, + subject: refused.subject, + reason: match refused.reason { + ConstituentRefusalReason::LeftBeforeSelection => { + RefusalReason::OpportunityGone + } + ConstituentRefusalReason::ScopeChanged => RefusalReason::ScopeMoved, + ConstituentRefusalReason::WorldRefused => RefusalReason::WorldRejected, + ConstituentRefusalReason::ProposalUndecodable => { + RefusalReason::ProposalUndecodable + } + ConstituentRefusalReason::RowDisagreesWithCell => { + RefusalReason::RowDisagreesWithCell + } + ConstituentRefusalReason::CallUnattributed => { + RefusalReason::CallUnattributed + } + }, + }); + } + if run.pending.is_none() { + let listed: Vec = run + .submissions + .iter() + .map(|entry| entry.subject) + .chain(run.refused.iter().map(|refused| refused.subject)) + .collect(); + let members = cell.members(); + let exact = listed.len() == members.len() + && members.iter().all(|member| listed.contains(&member.subject)); + if !exact { + return Some("cell_membership"); + } + } + run.pending.map(pending_code) + } + } +} + +/// One refusal per member of the cell. +fn refuse_all(cell: &Cell, position: u32, reason: RefusalReason) -> impl Iterator { + cell.members().iter().map(move |member| Refusal { + cell: position, + subject: member.subject, + reason, + }) +} + +/// The frozen cell with each member bound to the opportunity the world holds +/// for that subject now, and the frozen members that hold none. The partition +/// is fixed when the tick opens; an opportunity is the world's current binding +/// for a subject, and an earlier cell's act can move it (a word spoken in a +/// shared room changes what its listeners know). A subject that no longer holds +/// an opportunity leaves the cell, and an empty cell is gone. +pub(crate) fn refreshed( + frozen: &FrozenCell, + tick: TickIndex, + fresh: &[DecisionOpportunity], +) -> (Option, Vec) { + let mut gone = Vec::new(); + let mut members: Vec = Vec::new(); + for subject in &frozen.members { + match fresh + .iter() + .find(|opportunity| opportunity.scope.subject_id == *subject) + { + Some(opportunity) => members.push(Constituent { + subject: *subject, + opportunity: opportunity.clone(), + }), + None => gone.push(*subject), + } + } + let cell = if frozen.group { + (!members.is_empty()).then(|| Cell::Group { + id: frozen.id, + tick, + members, + }) + } else { + members.into_iter().next().map(|member| Cell::Singleton { + id: frozen.id, + tick, + member, + }) + }; + (cell, gone) +} + + +/// Why a wave ended before its last cell. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WaveStop { + /// A provider call could pass the allowance the port holds. + Budget, + /// A fixed code naming the kind of fault, never a value. + Fault(&'static str), +} + +/// What one node's cells did. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NodeOutcome { + pub node: NodeId, + pub distance: u8, + /// Frozen cells of the node the wave reached. + pub cells: u32, + /// Every command the node's cells hold a receipt for, in cell order. A + /// decline is a commit, so it is listed. + pub committed: Vec, + pub refusals: Vec, + pub unattributed: Vec, + /// What `spent` charged while the node's cells ran. + pub spent: u64, +} + +/// A wave as it ran: per node, in the order the nodes first appear in the +/// frozen cells. `stop` says why it did not reach the end. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WaveOutcome { + pub nodes: Vec, + pub stop: Option, +} + +/// Runs frozen cells in order, each bound to what the world holds for its +/// members now, through the controller organ. This owns order and the fold of +/// each cell's outcome into its node, and nothing else: the cells decide, the +/// kernel admits, and the driver owns time. A cell that did not finish ends +/// the wave with the stop that names why; its unreached members are not +/// refusals. `spent` reads the driver's running token total, so each node can +/// report what its cells cost. +pub async fn run_frozen_cells( + mailbox: &WorldMailbox, + runner: &ControllerRunner, + ordinal: TickIndex, + frozen: &[FrozenCell], + spent: impl Fn() -> u64, +) -> WaveOutcome { + let mut nodes: Vec = Vec::new(); + let mut stop = None; + for (position, frozen) in frozen.iter().enumerate() { + let position = position as u32; + let slot = match nodes.iter().position(|node| node.node == frozen.node) { + Some(slot) => slot, + None => { + nodes.push(NodeOutcome { + node: frozen.node, + distance: frozen.distance, + cells: 0, + committed: Vec::new(), + refusals: Vec::new(), + unattributed: Vec::new(), + spent: 0, + }); + nodes.len() - 1 + } + }; + let node = &mut nodes[slot]; + node.cells += 1; + let fresh = match mailbox.opportunities().await { + Ok(fresh) => fresh, + Err(_) => { + stop = Some(WaveStop::Fault("world_unavailable")); + break; + } + }; + let (cell, gone) = refreshed(frozen, ordinal, &fresh); + node.refusals.extend(gone.iter().map(|&subject| Refusal { + cell: position, + subject, + reason: RefusalReason::OpportunityGone, + })); + let Some(cell) = cell else { + continue; + }; + let before = spent(); + let result = runner.run_cell(&cell).await; + let ended = absorb( + result, + &cell, + position, + &mut node.committed, + &mut node.refusals, + &mut node.unattributed, + ); + node.spent += spent().saturating_sub(before); + if ended.is_some() { + stop = ended; + break; + } + } + WaveOutcome { nodes, stop } +} + #[cfg(test)] mod tests { use super::*;