From 7c3b278aab85546b27cbeec899d9414cb18a87db Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 09:50:00 +0100 Subject: [PATCH 1/4] ledger: one spend ledger per window with lane allowances; node spend is a join; ticks record deferrals Call records gain lane and request id (verse_provider_call.v2); a run's ledger holds allowances and spend by lane (verse_run_ledger.v2). reserve refuses a call that could pass its lane's allowance before the provider is called, beside the run cap; the play agent has no lane and is refused at the port. WaveSpend joins records to a frozen wave by the command id a request id begins with, so NodeOutcome.spent and the spent closure of run_frozen_cells are deleted. The verse tick (v3) records what the plan deferred and the report lists deferred nodes, including the ones an allowance stopped. The Dungeon's run-ahead spends in a per-timeline calls.cc, one window- run per post-turn window; ControllerRunner::elaborator takes the window's port. Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight-dungeon/src/begin.rs | 39 ++- .../ghostlight-dungeon/src/playtest_atlas.rs | 6 +- crates/ghostlight-dungeon/src/run_ahead.rs | 24 +- crates/ghostlight-dungeon/src/state_layout.rs | 2 +- crates/ghostlight-dungeon/src/timelines.rs | 38 +- crates/ghostlight-verse/src/main.rs | 8 +- crates/ghostlight/src/controllers.rs | 27 +- crates/ghostlight/src/lib.rs | 5 +- crates/ghostlight/src/verse/calls.rs | 325 +++++++++++++++--- crates/ghostlight/src/verse/calls/tests.rs | 239 ++++++++++++- crates/ghostlight/src/verse/mod.rs | 7 +- crates/ghostlight/src/verse/run.rs | 114 +++++- crates/ghostlight/src/verse/run/tests.rs | 39 ++- crates/ghostlight/src/wave.rs | 29 +- 14 files changed, 797 insertions(+), 105 deletions(-) diff --git a/crates/ghostlight-dungeon/src/begin.rs b/crates/ghostlight-dungeon/src/begin.rs index 6dac994..64ba3fe 100644 --- a/crates/ghostlight-dungeon/src/begin.rs +++ b/crates/ghostlight-dungeon/src/begin.rs @@ -20,7 +20,7 @@ use crate::{ use chrono::Utc; use ghostlight::{ CommandBody, CommandId, ControllerError, CreateJurisdictionIntent, CreateWorldIntent, - EvidenceSource, Lens, LensWeights, MailboxError, PrincipalCommandIntent, SeedPort, SubjectKind, + EvidenceSource, LaneTokens, Lens, LensWeights, MailboxError, PrincipalCommandIntent, SeedPort, SubjectKind, VerifiedPrincipalEvidence, WorldEra, WorldPhase, WorldSnapshot, }; use sha2::{Digest, Sha256}; @@ -48,6 +48,10 @@ pub(crate) struct Scale { pub(crate) sweep_sessions: usize, /// Permits one run-ahead sweep may hold at once. pub(crate) sweep_permits: usize, + /// What each background lane may spend in one post-turn window, in tokens. + /// Unset is unbounded: the ruled credit burn spends without a cap, and the + /// ledger reports. + pub(crate) window: LaneTokens, } const DEFAULT_PERSON_TARGET: u32 = 8; @@ -81,6 +85,10 @@ impl Scale { seed_sessions: number(&read, "GHOSTLIGHT_BEGIN_SEED_SESSIONS", DEFAULT_SEED_SESSIONS), sweep_sessions: number(&read, "GHOSTLIGHT_SWEEP_SESSIONS", DEFAULT_SWEEP_SESSIONS), sweep_permits: number(&read, "GHOSTLIGHT_SWEEP_PERMITS", DEFAULT_SWEEP_PERMITS).max(1), + window: LaneTokens { + wave: number(&read, "GHOSTLIGHT_WINDOW_WAVE_TOKENS", u64::MAX), + elaboration: number(&read, "GHOSTLIGHT_WINDOW_ELABORATION_TOKENS", u64::MAX), + }, } } } @@ -902,6 +910,35 @@ pub(crate) mod tests { .find(|request| prompt_text(request).contains(NOTE)) }) .await; + // The sweep spent in its own post-turn window of the timeline's ledger, + // in the elaboration lane alone: the request on the wire holds its bound. + let window = ghostlight::RunId::new(&format!("window-{}", host.world.snapshot().await.unwrap().revision)).unwrap(); + let spent = host.background.lane_spent(&window).unwrap(); + assert!(spent.elaboration > 0, "the window reserved the elaborator's call"); + assert_eq!(spent.wave, 0); + } + + /// A window whose elaboration allowance is nothing holds no elaborator call: + /// the sweep is refused at the window's port, before a provider is called, + /// and the lane's ledger stays empty. + #[tokio::test] + async fn an_exhausted_elaboration_allowance_refuses_the_sweep_before_the_provider() { + let mut rig = deferred_rig(); + rig.scale = Arc::new(Scale { window: LaneTokens { wave: u64::MAX, elaboration: 0 }, ..(*rig.scale).clone() }); + let begun = begin_vault(&rig, Uuid::new_v4()).await; + let host = rig.timelines.host(&begun.timeline).await.unwrap(); + let draft = host.world.snapshot().await.unwrap(); + rig.port.push(Ok(author("seed-1", &draft, &["a", "b"]))); + rig.port.push(Ok(author("seed-2", &draft, &["c", "d"]))); + eventually(async || { + let world = host.world.snapshot().await.unwrap(); + (world.phase == WorldPhase::Active && rig.status(&begun.timeline).await.is_none()).then_some(()) + }) + .await; + eventually(async || rig.port.seen_requests().into_iter().skip(2).find(|request| prompt_text(request).contains(NOTE))).await; + let revision = host.world.snapshot().await.unwrap().revision; + let window = ghostlight::RunId::new(&format!("window-{revision}")).unwrap(); + assert_eq!(host.background.lane_spent(&window).unwrap(), LaneTokens { wave: 0, elaboration: 0 }); } /// Genesis stands the player at the commons, which no seed populates: a diff --git a/crates/ghostlight-dungeon/src/playtest_atlas.rs b/crates/ghostlight-dungeon/src/playtest_atlas.rs index d1f8272..e5d6876 100644 --- a/crates/ghostlight-dungeon/src/playtest_atlas.rs +++ b/crates/ghostlight-dungeon/src/playtest_atlas.rs @@ -22,7 +22,7 @@ use axum::http::Method; use chrono::Utc; use ghostlight::{ EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource, InferenceFault, InferenceOutput, InferencePort, - InferenceRequest, Lens, PreparedInference, SubjectKind, WorldSnapshot, table_view, + InferenceRequest, LaneTokens, Lens, PreparedInference, SubjectKind, WorldSnapshot, table_view, }; use serde_json::json; use std::{ @@ -106,6 +106,7 @@ impl AtlasOptions { seed_sessions: self.seed_sessions, sweep_sessions: self.sweep_sessions, sweep_permits: self.concurrency.max(1), + window: LaneTokens { wave: u64::MAX, elaboration: u64::MAX }, } } } @@ -825,7 +826,8 @@ pub(super) async fn run(options: AtlasOptions) -> anyhow::Result { let _sweeping = host.sweeping.lock().await; let evidence = evidence_of(&state.catalog, state.vaults.as_ref(), &host, &timeline).await.context("the world's evidence could not be reopened")?; let recorder = Arc::new(Recorder { inner: evidence, sweep: AtomicUsize::new(0), log: StdMutex::new(Vec::new()) }); - let runner = host.controllers.elaborator(recorder.clone()); + let shared = state.timelines.shared().inference.clone(); + let runner = host.controllers.elaborator(shared, recorder.clone()); let mut watch = Watch { host: &host, activity: &activity, seen: BTreeMap::new(), last_poll: Instant::now() }; watch.poll(0).await.context("the seeded world could not be read")?; diff --git a/crates/ghostlight-dungeon/src/run_ahead.rs b/crates/ghostlight-dungeon/src/run_ahead.rs index 8e93476..d0b2e0b 100644 --- a/crates/ghostlight-dungeon/src/run_ahead.rs +++ b/crates/ghostlight-dungeon/src/run_ahead.rs @@ -3,9 +3,11 @@ //! A world's scale deficit is answered after play starts, not before: one sweep //! once Begin activates a seeded world, and one after each closed turn. Each //! sweep starts at most `Scale::sweep_sessions` elaboration sessions and holds -//! at most `Scale::sweep_permits` permits, so a trigger cannot spend without -//! bound. The elaborator reads the evidence of the snapshot its timeline is -//! bound to, the same evidence the seed read; an unseeded world reads none. +//! at most `Scale::sweep_permits` permits, and spends in its own post-turn +//! window: the elaborator calls a provider only through the window's recording +//! port, which refuses a call that could pass the lane's allowance. The elaborator reads the evidence of the snapshot its +//! timeline is bound to, the same evidence the seed read; an unseeded world +//! reads none. use crate::{ begin::{Scale, Vaults}, @@ -23,7 +25,21 @@ pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc world, + Err(error) => { + tracing::warn!(%error, "run-ahead could not read the world"); + return; + } + }; + let window = match host.window(&world, scale.window) { + Ok(window) => Arc::new(window), + Err(error) => { + tracing::warn!(%error, "run-ahead could not open its window"); + return; + } + }; + let runner = host.controllers.elaborator(window, evidence); let permits = Arc::new(Semaphore::new(scale.sweep_permits)); if let Err(error) = runner.sweep(permits, scale.sweep_sessions).await { tracing::warn!(%error, "run-ahead elaboration stopped"); diff --git a/crates/ghostlight-dungeon/src/state_layout.rs b/crates/ghostlight-dungeon/src/state_layout.rs index 68f47c7..f8e06ab 100644 --- a/crates/ghostlight-dungeon/src/state_layout.rs +++ b/crates/ghostlight-dungeon/src/state_layout.rs @@ -8,7 +8,7 @@ use std::{ }; /// The stores one timeline owns, each proved direct before it is opened. -pub(crate) const TIMELINE_STORES: [&str; 3] = ["world.cc", "controller-work.cc", "play-turn-v1.cc"]; +pub(crate) const TIMELINE_STORES: [&str; 4] = ["world.cc", "controller-work.cc", "play-turn-v1.cc", "calls.cc"]; fn default_runtime_root() -> PathBuf { #[cfg(windows)] diff --git a/crates/ghostlight-dungeon/src/timelines.rs b/crates/ghostlight-dungeon/src/timelines.rs index ca42564..627fa28 100644 --- a/crates/ghostlight-dungeon/src/timelines.rs +++ b/crates/ghostlight-dungeon/src/timelines.rs @@ -10,8 +10,9 @@ use crate::{ state_layout::prepare_timeline_directory, }; use ghostlight::{ - ControllerModels, ControllerPort, ControllerRunner, InferencePort, PersonaLane, WorldMailbox, - open_controller_work, + CallRecordError, CallRecordStore, ControllerModels, ControllerPort, ControllerRunner, + InferencePort, LaneTokens, PersonaLane, RecordingInferencePort, RunId, RunStart, WorldMailbox, + WorldSnapshot, open_controller_work, }; use anyhow::Context; use std::{collections::HashMap, path::PathBuf, sync::Arc}; @@ -36,6 +37,33 @@ pub(crate) struct TimelineHost { pub(crate) changes: broadcast::Sender<()>, /// Held while a run-ahead sweep runs: one at a time per timeline. pub(crate) sweeping: Mutex<()>, + /// The spend ledgers of this timeline's background windows, one run each. + /// The play turn's own calls never reach it. + pub(crate) background: Arc, + inference: Arc, +} + +impl TimelineHost { + /// The port of the post-turn window that follows world revision + /// `world.revision`: the one port the background lanes call a provider + /// through, reserving each call in the window's ledger first. The window's + /// cap is its allowances together. A window at the same revision is the same + /// ledger, so a trigger that finds nothing changed spends no new allowance. + pub(crate) fn window( + &self, + world: &WorldSnapshot, + allowances: LaneTokens, + ) -> Result { + let run = RunId::new(&format!("window-{}", world.revision))?; + RecordingInferencePort::open( + self.inference.clone(), + self.background.clone(), + run, + allowances.total(), + allowances, + &RunStart::of(world), + ) + } } pub(crate) struct Timelines { @@ -76,6 +104,10 @@ impl Timelines { let _ = fatal.send(format!("world owner of {label} stopped while serving")); }); let work = open_controller_work(directory.join("controller-work.cc"))?; + let background = Arc::new( + CallRecordStore::open(directory.join("calls.cc")) + .context("the background call ledger could not be opened")?, + ); let controllers = ControllerRunner::open( world.clone(), self.shared.inference.clone(), @@ -103,6 +135,8 @@ impl Timelines { play: Arc::new(play), changes, sweeping: Mutex::new(()), + background, + inference: self.shared.inference.clone(), }); hosts.insert(id.to_owned(), host.clone()); Ok(host) diff --git a/crates/ghostlight-verse/src/main.rs b/crates/ghostlight-verse/src/main.rs index 5d6263d..2c7d020 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, - GestaltKnobs, HostedBinding, Lens, LensWeights, LocalBinding, PrincipalCommandIntent, RecordingInferencePort, + GestaltKnobs, HostedBinding, LaneTokens, 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, @@ -267,6 +267,12 @@ async fn run(flags: Flags) -> Result { calls, call_run_id(sequence), cap, + // The run's token cap is the wave lane's allowance; the verse runs no + // elaborator, so that lane has none. + LaneTokens { + wave: cap, + elaboration: 0, + }, &RunStart::of(&world), ) .context("the run's call records cannot be opened") diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index f9b4f47..335d947 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -3283,14 +3283,19 @@ impl ControllerRunner { }) } - /// The authoring lane, built from the same ports the decision lanes use, - /// reading the evidence the caller's timeline is bound to. A world with no - /// vault passes `NullEvidenceSource`, whose bound is stated where it is - /// defined; there is no mode flag choosing between them. - pub fn elaborator(&self, evidence: Arc) -> ElaborationRunner { + /// The authoring lane, over the mailbox the decision lanes use, reading the + /// evidence the caller's timeline is bound to and calling the provider only + /// through `inference`: the port of the window the sweep spends in. A world + /// with no vault passes `NullEvidenceSource`, whose bound is stated where it + /// is defined; there is no mode flag choosing between them. + pub fn elaborator( + &self, + inference: Arc, + evidence: Arc, + ) -> ElaborationRunner { ElaborationRunner::new( self.elaboration.clone(), - Arc::clone(&self.inference), + inference, evidence, Arc::clone(&self.work), self.models.elaborator.clone(), @@ -7646,6 +7651,12 @@ pub(super) fn decode_catalog_call( /// its completed response, while a repair round that re-prompts under the /// same command and round names a different request instead of colliding /// with the connector's replay record for the first attempt. +/// What every request id of `command_id` begins with: the join from a provider +/// call back to the command it ran under. +pub(crate) fn request_id_prefix(command_id: CommandId) -> Result { + Ok(format!("ghostlight-request-{}-", encoded_id(&command_id)?)) +} + pub(super) fn provider_request_id( command_id: CommandId, purpose: InferencePurpose, @@ -7655,8 +7666,8 @@ pub(super) fn provider_request_id( ) -> Result { let content = request_content_digest(instructions, input)?; Ok(format!( - "ghostlight-request-{}-{}-{round}-{content}", - encoded_id(&command_id)?, + "{}{}-{round}-{content}", + request_id_prefix(command_id)?, purpose_name(purpose) )) } diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index c19dae8..129beb6 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -166,8 +166,9 @@ pub use vault::{ VaultEra, VaultEvidenceSource, VaultProfile, VaultSnapshot, production_eras, production_profile, production_vault_names, }; pub use verse::{ - CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord, - RUN_RECORD_SCHEMA, NodeReport, RecordedKnobs, RecordingInferencePort, RunClaim, + CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, Lane, LaneTokens, + NodeSpend, ProviderCallRecord, WaveSpend, + RUN_RECORD_SCHEMA, DeferredNode, NodeReport, RecordedKnobs, RecordingInferencePort, RunClaim, ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint, TickReport, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore, call_run_id, run_manual, diff --git a/crates/ghostlight/src/verse/calls.rs b/crates/ghostlight/src/verse/calls.rs index 22bfe31..da654f8 100644 --- a/crates/ghostlight/src/verse/calls.rs +++ b/crates/ghostlight/src/verse/calls.rs @@ -21,9 +21,11 @@ //! run's spend never passes the cap unnoticed. One port at a time owns a run. use crate::controllers::{ - InferenceEvent, InferenceFault, InferenceOutput, InferencePort, InferencePurpose, - InferenceRequest, PreparedInference, REQUEST_EXPIRY, TokenUsage, ToolResultOracle, unix_ms, + ControllerError, InferenceEvent, InferenceFault, InferenceOutput, InferencePort, + InferencePurpose, InferenceRequest, PreparedInference, REQUEST_EXPIRY, TokenUsage, + ToolResultOracle, request_id_prefix, unix_ms, }; +use crate::{FrozenCell, NodeId, TickIndex, WorldId}; use async_trait::async_trait; use chrono::Utc; use model_connector::ProviderRequest; @@ -37,14 +39,14 @@ use std::{ }; use thiserror::Error; -const CALL_RECORD_ROW: &str = "verse_provider_call.v1"; -const RUN_LEDGER_ROW: &str = "verse_run_ledger.v1"; +const CALL_RECORD_ROW: &str = "verse_provider_call.v2"; +const RUN_LEDGER_ROW: &str = "verse_run_ledger.v2"; /// The run ledger document's schema. -const RUN_LEDGER_SCHEMA: &str = "ghostlight.verse_run_ledger.v1"; +const RUN_LEDGER_SCHEMA: &str = "ghostlight.verse_run_ledger.v2"; /// The call record document's schema. A store holding any other row type or /// schema is refused at open: this store is not migrated from, or shared with, /// another document. -pub const CALL_RECORD_SCHEMA: &str = "ghostlight.verse_provider_call.v1"; +pub const CALL_RECORD_SCHEMA: &str = "ghostlight.verse_provider_call.v2"; #[derive(Clone, Copy, Debug, Error, PartialEq, Eq)] pub enum CallRecordError { @@ -62,6 +64,8 @@ pub enum CallRecordError { RunInUse, #[error("the call could pass the run's token cap")] OverCap, + #[error("the call could pass its lane's allowance")] + OverAllowance, #[error("the run was recorded with a different {0}")] RunMismatch(RunField), } @@ -71,6 +75,8 @@ pub enum CallRecordError { pub enum RunField { /// The token cap the run was opened with. Cap, + /// The lane allowances the run was opened with. + Allowances, /// The identity of the world the run started from. WorldId, /// The state digest of the world the run started from. @@ -81,12 +87,63 @@ impl std::fmt::Display for RunField { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { Self::Cap => "token cap", + Self::Allowances => "lane allowances", Self::WorldId => "world id", Self::StateDigest => "world state digest", }) } } +/// The background lane a metered call spends in. The room lane, the DM's play +/// turn, is in no window: it is never reserved here. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Lane { + /// A node turn of a Gestalt wave. + Wave, + /// An elaborator session. + Elaboration, +} + +impl Lane { + /// The lane a call of this purpose spends in; the play agent has none. + pub fn of(purpose: InferencePurpose) -> Option { + match purpose { + InferencePurpose::Play => None, + InferencePurpose::Elaboration => Some(Self::Elaboration), + _ => Some(Self::Wave), + } + } +} + +/// Tokens by lane: a window's allowances, or what its lanes have reserved or +/// been charged. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct LaneTokens { + pub wave: u64, + pub elaboration: u64, +} + +impl LaneTokens { + pub fn of(&self, lane: Lane) -> u64 { + match lane { + Lane::Wave => self.wave, + Lane::Elaboration => self.elaboration, + } + } + + fn set(&mut self, lane: Lane, tokens: u64) { + match lane { + Lane::Wave => self.wave = tokens, + Lane::Elaboration => self.elaboration = tokens, + } + } + + /// Every lane together. + pub fn total(&self) -> u64 { + self.wave.saturating_add(self.elaboration) + } +} + /// The world a run began from: its identity and state digest. Replay is of a /// restored copy of this world, so it takes the same two values. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -135,6 +192,8 @@ pub struct ProviderCallRecord { run_id: String, sequence: u64, purpose: InferencePurpose, + lane: Lane, + request_id: String, model: String, content_sha256: String, events: Vec, @@ -156,6 +215,17 @@ impl ProviderCallRecord { self.purpose } + /// The lane this call spent in. + pub fn lane(&self) -> Lane { + self.lane + } + + /// The provider request id, which carries the command id it ran under: the + /// join from a call to the wave cell that made it. + pub fn request_id(&self) -> &str { + &self.request_id + } + pub fn model(&self) -> &str { &self.model } @@ -239,8 +309,10 @@ fn content_digest(request: &ProviderRequest) -> Result { struct RunLedger { run_id: String, cap: u64, + allowances: LaneTokens, start: RunStart, - spent: u64, + /// Tokens reserved or charged, by lane. The run's spend is their sum. + spent: LaneTokens, } enum DecodedRow { @@ -320,13 +392,13 @@ impl CallRecordStore { let rows = store.pull_all().map_err(|_| CallRecordError::Store)?; let mut runs: BTreeMap = BTreeMap::new(); let mut counts: BTreeMap = BTreeMap::new(); - let mut charged: BTreeMap = BTreeMap::new(); + let mut charged: BTreeMap = BTreeMap::new(); for row in &rows { match decode_row(row)? { DecodedRow::Call(record) => { *counts.entry(record.run_id.clone()).or_default() += 1; let total = charged.entry(record.run_id.clone()).or_default(); - *total = total.saturating_add(record.charged); + total.set(record.lane, total.of(record.lane).saturating_add(record.charged)); let tally = runs.entry(record.run_id).or_default(); tally.last_sequence = tally.last_sequence.max(record.sequence); } @@ -342,11 +414,10 @@ impl CallRecordStore { // that covers what they charged. for (run, tally) in &runs { let rows = counts.get(run).copied().unwrap_or(0); - let recorded = charged.get(run).copied().unwrap_or(0); - let covered = tally - .ledger - .as_ref() - .is_some_and(|ledger| ledger.spent >= recorded); + let recorded = charged.get(run).copied().unwrap_or_default(); + let covered = tally.ledger.as_ref().is_some_and(|ledger| { + ledger.spent.wave >= recorded.wave && ledger.spent.elaboration >= recorded.elaboration + }); if rows != tally.last_sequence || !covered { return Err(CallRecordError::Corrupt); } @@ -381,28 +452,48 @@ impl CallRecordStore { .runs .get(run.as_str()) .and_then(|tally| tally.ledger.as_ref()) - .map_or(0, |ledger| ledger.spent)) + .map_or(0, |ledger| ledger.spent.total())) + } + + /// What each lane of this run has reserved or been charged. + pub fn lane_spent(&self, run: &RunId) -> Result { + Ok(self + .lock()? + .runs + .get(run.as_str()) + .and_then(|tally| tally.ledger.as_ref()) + .map_or_else(LaneTokens::default, |ledger| ledger.spent)) } /// Takes the run's ledger for one port, or refuses when another holds it. /// The first claim of a run writes its ledger: the cap it is opened under - /// and the world it starts from. A later claim must name the same cap; the - /// start is not compared, because a resumed world has moved on. - fn claim(&self, run: &RunId, cap: u64, start: &RunStart) -> Result<(), CallRecordError> { + /// the lane allowances, and the world it starts from. A later claim must name + /// the same cap and allowances; the start is not compared, because a resumed world has moved on. + fn claim( + &self, + run: &RunId, + cap: u64, + allowances: LaneTokens, + start: &RunStart, + ) -> Result<(), CallRecordError> { let mut state = self.lock()?; if !state.owned.insert(run.as_str().to_owned()) { return Err(CallRecordError::RunInUse); } let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.as_ref()) { - Some(ledger) if ledger.cap == cap => Ok(()), - Some(_) => Err(CallRecordError::RunMismatch(RunField::Cap)), + Some(ledger) if ledger.cap != cap => Err(CallRecordError::RunMismatch(RunField::Cap)), + Some(ledger) if ledger.allowances != allowances => { + Err(CallRecordError::RunMismatch(RunField::Allowances)) + } + Some(_) => Ok(()), None => Self::write_ledger( &mut state, RunLedger { run_id: run.as_str().to_owned(), cap, + allowances, start: start.clone(), - spent: 0, + spent: LaneTokens::default(), }, ), }; @@ -444,8 +535,13 @@ impl CallRecordStore { Ok(()) } - /// Persists `spent` as the run's spend; the run must have been claimed. - fn write_spent(state: &mut StoreState, run: &str, spent: u64) -> Result<(), CallRecordError> { + /// Persists `spent` as what the run's lanes hold; the run must have been + /// claimed. + fn write_spent( + state: &mut StoreState, + run: &str, + spent: LaneTokens, + ) -> Result<(), CallRecordError> { let mut ledger = state .runs .get(run) @@ -455,24 +551,37 @@ impl CallRecordStore { Self::write_ledger(state, ledger) } - fn held(state: &StoreState, run: &RunId) -> u64 { + fn held(state: &StoreState, run: &RunId) -> LaneTokens { state .runs .get(run.as_str()) .and_then(|tally| tally.ledger.as_ref()) - .map_or(0, |ledger| ledger.spent) + .map_or_else(LaneTokens::default, |ledger| ledger.spent) } - /// Charges `bound` to the run's persisted ledger, or refuses with - /// `OverCap` when the ledger plus the bound would pass `cap`. The check and - /// the write hold one lock, so calls on the wire hold their bounds. - fn reserve(&self, run: &RunId, bound: u64, cap: u64) -> Result<(), CallRecordError> { + /// Charges `bound` to the run's persisted ledger under `lane`, or refuses + /// with `OverCap` when the run would pass `cap`, or `OverAllowance` when + /// the lane would pass its allowance. The check and the write hold one + /// lock, so calls on the wire hold their bounds. + fn reserve( + &self, + run: &RunId, + lane: Lane, + bound: u64, + cap: u64, + allowance: u64, + ) -> Result<(), CallRecordError> { let mut state = self.lock()?; - let after = Self::held(&state, run).saturating_add(bound); - if after > cap { + let mut held = Self::held(&state, run); + let after = held.of(lane).saturating_add(bound); + if held.total().saturating_add(bound) > cap { return Err(CallRecordError::OverCap); } - Self::write_spent(&mut state, run.as_str(), after) + if after > allowance { + return Err(CallRecordError::OverAllowance); + } + held.set(lane, after); + Self::write_spent(&mut state, run.as_str(), held) } /// Replaces a reservation of `bound` with what the call was charged. With @@ -481,6 +590,7 @@ impl CallRecordStore { fn settle( &self, run: &RunId, + lane: Lane, bound: u64, charged: u64, record: Option<&ProviderCallRecord>, @@ -489,10 +599,9 @@ impl CallRecordStore { if let Some(record) = record { Self::push_record(&mut state, record)?; } - let settled = Self::held(&state, run) - .saturating_sub(bound) - .saturating_add(charged); - Self::write_spent(&mut state, run.as_str(), settled) + let mut held = Self::held(&state, run); + held.set(lane, held.of(lane).saturating_sub(bound).saturating_add(charged)); + Self::write_spent(&mut state, run.as_str(), held) } fn append(&self, record: &ProviderCallRecord) -> Result<(), CallRecordError> { @@ -554,26 +663,30 @@ pub struct RecordingInferencePort { store: Arc, run: RunId, cap: u64, + allowances: LaneTokens, } impl RecordingInferencePort { /// Takes ownership of the run's ledger, which resumes from the store. The - /// first open of a run records its cap and the world it starts from; a - /// reopen with another cap is refused with `RunMismatch(Cap)`. A second + /// first open of a run records its cap, its lane allowances and the world it + /// starts from; a reopen with another cap or allowances is refused with + /// `RunMismatch`. A second /// port on a run whose first is alive is refused with `RunInUse`. pub fn open( inner: Arc, store: Arc, run: RunId, cap_tokens: u64, + allowances: LaneTokens, start: &RunStart, ) -> Result { - store.claim(&run, cap_tokens, start)?; + store.claim(&run, cap_tokens, allowances, start)?; Ok(Self { inner, store, run, cap: cap_tokens, + allowances, }) } @@ -592,6 +705,19 @@ impl RecordingInferencePort { self.store.spent(&self.run).unwrap_or(u64::MAX) } + /// Tokens reserved or charged so far, by lane. + pub fn lane_spent(&self) -> LaneTokens { + self.store.lane_spent(&self.run).unwrap_or(LaneTokens { + wave: u64::MAX, + elaboration: u64::MAX, + }) + } + + /// The run's call records in sequence. + pub fn records(&self) -> Result, CallRecordError> { + self.store.records(&self.run) + } + /// The most this request can cost: its serialized bytes plus its output /// allowance. The v4 request type cannot omit the allowance, so every /// request has a bound. @@ -604,8 +730,9 @@ impl RecordingInferencePort { fn settle( &self, + lane: Lane, bound: u64, - identity: (InferencePurpose, String, String), + identity: Identity, result: Result, ) -> Result { // A fault leaves its reservation charged: the request may have run. @@ -616,15 +743,22 @@ impl RecordingInferencePort { }; if charged > bound { self.store - .settle(&self.run, bound, charged, None) + .settle(&self.run, lane, bound, charged, None) .map_err(unrecorded)?; return Err(InferenceFault::budget_exhausted()); } - let (purpose, model, content_sha256) = identity; + let Identity { + purpose, + model, + content_sha256, + request_id, + } = identity; let record = ProviderCallRecord { run_id: self.run.as_str().to_owned(), sequence: self.store.next_sequence(&self.run).map_err(unrecorded)?, purpose, + lane, + request_id, model, content_sha256, events: output.events.clone(), @@ -633,12 +767,20 @@ impl RecordingInferencePort { charged, }; self.store - .settle(&self.run, bound, charged, Some(&record)) + .settle(&self.run, lane, bound, charged, Some(&record)) .map_err(unrecorded)?; Ok(output) } } +/// What a call is recorded as, known before the provider is called. +struct Identity { + purpose: InferencePurpose, + model: String, + content_sha256: String, + request_id: String, +} + impl Drop for RecordingInferencePort { fn drop(&mut self) { self.store.disown(&self.run); @@ -657,19 +799,29 @@ impl InferencePort for RecordingInferencePort { async fn infer(&self, request: PreparedInference) -> Result { let bound = Self::bound(&request)?; - let identity = ( - request.purpose, - request.invocation.request.model.clone(), - content_digest(&request.invocation.request)?, - ); + // The room lane is no window's: a play call that reached this port + // would spend background budget. + let Some(lane) = Lane::of(request.purpose) else { + return Err(InferenceFault::integrity_violation( + "the room lane is not metered by a background window", + )); + }; + let identity = Identity { + purpose: request.purpose, + model: request.invocation.request.model.clone(), + content_sha256: content_digest(&request.invocation.request)?, + request_id: request.invocation.request.request_id.clone(), + }; self.store - .reserve(&self.run, bound, self.cap) + .reserve(&self.run, lane, bound, self.cap, self.allowances.of(lane)) .map_err(|error| match error { - CallRecordError::OverCap => InferenceFault::budget_exhausted(), + CallRecordError::OverCap | CallRecordError::OverAllowance => { + InferenceFault::budget_exhausted() + } _ => unrecorded(error), })?; let result = self.inner.infer(request).await; - self.settle(bound, identity, result) + self.settle(lane, bound, identity, result) } fn lend_tool_results(&self, prepared: &PreparedInference, oracle: Box) { @@ -677,6 +829,77 @@ impl InferencePort for RecordingInferencePort { } } +/// What the calls of one wave cost, by lane and by node. The port never learns +/// which node a call served: a record's request id begins with the command id +/// it ran under, and the frozen wave names the command ids of each node's +/// cells, so attribution is this join and nothing the port keeps. Only settled +/// calls have records; a call that faulted left its reservation in the ledger +/// and no record here. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct WaveSpend { + /// Tokens charged by the wave's joined calls, by lane. + pub lanes: LaneTokens, + /// Per node, in the order the frozen cells first name them. A node whose + /// cells made no recorded call is listed with zero. + pub nodes: Vec, +} + +/// One node's settled calls in a wave. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NodeSpend { + pub node: NodeId, + /// The node's hierarchy distance from the focus when it was planned. + pub distance: u8, + pub calls: u32, + pub charged: u64, +} + +impl WaveSpend { + /// The records of wave `ordinal` of `world`: every record whose request id + /// begins with a command id of one of `frozen`'s cells. Records of other + /// waves or lanes are not this wave's and are left out. + pub fn of( + records: &[ProviderCallRecord], + world: WorldId, + ordinal: TickIndex, + frozen: &[FrozenCell], + ) -> Result { + let mut spend = Self::default(); + let mut prefixes: Vec<(String, usize)> = Vec::new(); + for cell in frozen { + let at = match spend.nodes.iter().position(|node| node.node == cell.node) { + Some(at) => at, + None => { + spend.nodes.push(NodeSpend { + node: cell.node, + distance: cell.distance, + calls: 0, + charged: 0, + }); + spend.nodes.len() - 1 + } + }; + for command in cell.command_ids(world, ordinal) { + prefixes.push((request_id_prefix(command)?, at)); + } + } + for record in records { + let Some(&(_, at)) = prefixes + .iter() + .find(|(prefix, _)| record.request_id.starts_with(prefix)) + else { + continue; + }; + let node = &mut spend.nodes[at]; + node.calls += 1; + node.charged = node.charged.saturating_add(record.charged); + let lane = spend.lanes.of(record.lane).saturating_add(record.charged); + spend.lanes.set(record.lane, lane); + } + Ok(spend) + } +} + /// Serves a run's stored replies, in sequence, to the same requests, matched /// by what they ask of the provider and not by the ids that name them. It holds /// no provider and makes no call: a request that is not the next recorded one diff --git a/crates/ghostlight/src/verse/calls/tests.rs b/crates/ghostlight/src/verse/calls/tests.rs index 201b6f7..dd640eb 100644 --- a/crates/ghostlight/src/verse/calls/tests.rs +++ b/crates/ghostlight/src/verse/calls/tests.rs @@ -1,5 +1,6 @@ use super::*; use crate::CommandId; +use crate::controllers::request_id_prefix; use crate::controllers::{ InferenceFaultClass, InferenceFaultDisposition, RequestShape, tool_request, }; @@ -131,6 +132,14 @@ fn start() -> RunStart { } } +/// Every call these tests make is a wave call, so the wave lane holds the cap. +fn lanes(cap: u64) -> LaneTokens { + LaneTokens { + wave: cap, + elaboration: 0, + } +} + fn recording( inner: &Arc, store: &Arc, @@ -142,6 +151,7 @@ fn recording( store.clone(), RunId::new(run).unwrap(), cap, + lanes(cap), &start(), ) .expect("the port opens") @@ -499,6 +509,7 @@ async fn one_run_has_one_ledger_and_one_owner() { store.clone(), RunId::new("run-own").unwrap(), cap, + lanes(cap), &start(), ); assert_eq!(second.err(), Some(CallRecordError::RunInUse)); @@ -652,6 +663,8 @@ fn sample_record(run: &str, sequence: u64) -> ProviderCallRecord { run_id: run.into(), sequence, purpose: InferencePurpose::Persona, + lane: Lane::Wave, + request_id: "ghostlight-request-x".into(), model: MODEL.into(), content_sha256: "ab".into(), events: vec![InferenceEvent::Text("t".into())], @@ -707,8 +720,9 @@ fn spend_row(run: &str, spent: u64) -> CultCacheEnvelope { rmp_serde::to_vec_named(&RunLedger { run_id: run.into(), cap: u64::MAX, + allowances: lanes(u64::MAX), start: start(), - spent, + spent: LaneTokens { wave: spent, elaboration: 0 }, }) .unwrap(), ) @@ -799,8 +813,9 @@ fn the_store_refuses_any_row_that_is_not_a_canonical_v1_record() { rmp_serde::to_vec_named(&RunLedger { run_id: "run-x".into(), cap: u64::MAX, + allowances: lanes(u64::MAX), start: start(), - spent: 1, + spent: LaneTokens { wave: 1, elaboration: 0 }, }) .unwrap(), ), @@ -815,8 +830,9 @@ fn the_store_refuses_any_row_that_is_not_a_canonical_v1_record() { rmp_serde::to_vec_named(&RunLedger { run_id: "run-x".into(), cap: u64::MAX, + allowances: lanes(u64::MAX), start: start(), - spent: 1, + spent: LaneTokens { wave: 1, elaboration: 0 }, }) .unwrap(), vec![0xc0], @@ -1090,7 +1106,7 @@ async fn a_run_reopens_only_under_the_cap_it_began_with() { drop(recording(&inner, &store, "run-cap", 5_000)); let run = RunId::new("run-cap").unwrap(); let open = |store: &Arc, cap: u64| { - RecordingInferencePort::open(inner.clone(), store.clone(), run.clone(), cap, &start()) + RecordingInferencePort::open(inner.clone(), store.clone(), run.clone(), cap, lanes(cap), &start()) }; for other in [4_999, 5_001, u64::MAX] { assert_eq!( @@ -1152,7 +1168,7 @@ async fn replay_runs_against_a_restored_copy_and_refuses_any_other_world_up_fron let run = RunId::new("run-world").unwrap(); let inner = ScriptedPort::new(ok_all(&[reply("one", "r1")])); let live = - RecordingInferencePort::open(inner.clone(), store.clone(), run.clone(), u64::MAX, &began) + RecordingInferencePort::open(inner.clone(), store.clone(), run.clone(), u64::MAX, lanes(u64::MAX), &began) .unwrap(); live.infer(live.prepare(request_for(command, "go", 1_200)).unwrap()) .await @@ -1195,3 +1211,216 @@ async fn replay_runs_against_a_restored_copy_and_refuses_any_other_world_up_fron ); assert_eq!(inner.calls(), 1, "replay never reached the provider"); } + +fn request_of( + command: CommandId, + purpose: InferencePurpose, + prompt: &str, +) -> InferenceRequest { + tool_request( + command, + 0, + purpose, + MODEL, + "Respond only in prose.", + vec![InputItem::UserText { + text: prompt.into(), + }], + Vec::::new(), + RequestShape { + max_output_tokens: 1_200, + parallel_tool_calls: false, + }, + ) + .expect("the request builds") +} + +#[tokio::test] +async fn a_lane_allowance_refuses_before_the_provider_is_called() { + let directory = tempfile::tempdir().unwrap(); + let (store, _) = store_in(&directory); + let command = CommandId::new(); + let wave = PreparedInference::prepare( + "verse-test", + 4_102_444_800_000, + request_of(command, InferencePurpose::Persona, "act"), + ) + .unwrap(); + let elaboration = PreparedInference::prepare( + "verse-test", + 4_102_444_800_000, + request_of(command, InferencePurpose::Elaboration, "deepen"), + ) + .unwrap(); + let inner = ScriptedPort::new(vec![Ok(reply("acted", "r1")), Ok(reply("deepened", "r2"))]); + let run = RunId::new("run-lanes").unwrap(); + let allowances = LaneTokens { + wave: u64::MAX, + elaboration: bound_of(&elaboration) - 1, + }; + let port = RecordingInferencePort::open( + inner.clone(), + store.clone(), + run.clone(), + u64::MAX, + allowances, + &start(), + ) + .unwrap(); + + let fault = port + .infer(elaboration.clone()) + .await + .expect_err("the elaboration lane cannot hold this call"); + assert_eq!(fault.class(), InferenceFaultClass::BudgetExhausted); + assert_eq!(inner.calls(), 0, "refused before the provider was called"); + assert_eq!(port.lane_spent(), LaneTokens::default(), "nothing was reserved"); + assert!(store.records(&run).unwrap().is_empty()); + + // The wave lane still runs, and the refusal did not touch its ledger. + port.infer(wave.clone()).await.unwrap(); + assert_eq!(inner.calls(), 1); + let records = store.records(&run).unwrap(); + assert_eq!(records.len(), 1); + let record = &records[0]; + assert_eq!(record.lane(), Lane::Wave); + assert_eq!( + record.request_id(), + wave.invocation.request.request_id, + "the record names the request it answered" + ); + assert!( + record + .request_id() + .starts_with(&request_id_prefix(command).unwrap()), + "and the command it ran under" + ); + assert_eq!( + port.lane_spent(), + LaneTokens { + wave: record.charged(), + elaboration: 0 + } + ); + + // An allowance that holds the bound lets the lane through. + drop(port); + let roomy = RecordingInferencePort::open( + inner.clone(), + store.clone(), + RunId::new("run-roomy").unwrap(), + u64::MAX, + LaneTokens { + wave: 0, + elaboration: bound_of(&elaboration), + }, + &start(), + ) + .unwrap(); + roomy.infer(elaboration).await.unwrap(); + let roomy_records = store.records(&RunId::new("run-roomy").unwrap()).unwrap(); + assert_eq!(roomy_records[0].lane(), Lane::Elaboration); + assert_eq!(wave_refused(&roomy, &wave).await, InferenceFaultClass::BudgetExhausted); +} + +async fn wave_refused(port: &RecordingInferencePort, call: &PreparedInference) -> InferenceFaultClass { + port.infer(call.clone()).await.expect_err("refused").class() +} + +#[tokio::test] +async fn the_room_lane_never_reserves_in_a_window() { + let directory = tempfile::tempdir().unwrap(); + let (store, _) = store_in(&directory); + let inner = ScriptedPort::new(vec![Ok(reply("never", "r"))]); + let port = recording(&inner, &store, "run-room", u64::MAX); + let play = PreparedInference::prepare( + "verse-test", + 4_102_444_800_000, + request_of(CommandId::new(), InferencePurpose::Play, "look"), + ) + .unwrap(); + let fault = port.infer(play).await.expect_err("the room lane is not metered here"); + assert_eq!( + fault.disposition(), + InferenceFaultDisposition::IntegrityViolation + ); + assert_eq!(inner.calls(), 0); + assert_eq!(port.spent(), 0, "no reservation was made"); +} + +#[test] +fn a_run_reopens_only_under_the_allowances_it_began_with() { + let directory = tempfile::tempdir().unwrap(); + let (store, _) = store_in(&directory); + let inner = ScriptedPort::new(Vec::new()); + let run = RunId::new("run-allow").unwrap(); + let open = |allowances: LaneTokens| { + RecordingInferencePort::open( + inner.clone(), + store.clone(), + run.clone(), + u64::MAX, + allowances, + &start(), + ) + }; + let began = LaneTokens { + wave: 10, + elaboration: 20, + }; + drop(open(began).unwrap()); + for other in [ + LaneTokens { + wave: 11, + elaboration: 20, + }, + LaneTokens { + wave: 10, + elaboration: 19, + }, + LaneTokens::default(), + ] { + assert_eq!( + open(other).err(), + Some(CallRecordError::RunMismatch(RunField::Allowances)) + ); + } + assert!(open(began).is_ok()); +} + +#[tokio::test] +async fn each_lane_spend_survives_a_restart() { + let directory = tempfile::tempdir().unwrap(); + let (store, path) = store_in(&directory); + let prepared = PreparedInference::prepare( + "verse-test", + 4_102_444_800_000, + request_of(CommandId::new(), InferencePurpose::Elaboration, "deepen"), + ) + .unwrap(); + let inner = ScriptedPort::new(vec![Ok(reply("deepened", "r"))]); + let allowances = LaneTokens { + wave: 5, + elaboration: u64::MAX, + }; + let open = |store: &Arc| { + RecordingInferencePort::open( + inner.clone(), + store.clone(), + RunId::new("run-restart").unwrap(), + u64::MAX, + allowances, + &start(), + ) + .unwrap() + }; + let port = open(&store); + port.infer(prepared.clone()).await.unwrap(); + let spent = port.lane_spent(); + assert_eq!(spent.wave, 0); + assert_eq!(spent.elaboration, bound_of(&prepared)); + drop((port, store)); + + let reopened = Arc::new(CallRecordStore::open(&path).unwrap()); + assert_eq!(open(&reopened).lane_spent(), spent, "no restart returns budget"); +} diff --git a/crates/ghostlight/src/verse/mod.rs b/crates/ghostlight/src/verse/mod.rs index 5662494..9b21250 100644 --- a/crates/ghostlight/src/verse/mod.rs +++ b/crates/ghostlight/src/verse/mod.rs @@ -9,11 +9,12 @@ mod run; pub use genesis::{CreateVerseWorldIntent, VerseGenesisError}; pub use calls::{ - CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, ProviderCallRecord, - RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart, + CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, Lane, LaneTokens, NodeSpend, + ProviderCallRecord, RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart, + WaveSpend, }; pub use run::{ - RUN_RECORD_SCHEMA, NodeReport, RecordedKnobs, RunClaim, RunOutcome, RunStatus, + RUN_RECORD_SCHEMA, DeferredNode, 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 175ff1d..e5a589a 100644 --- a/crates/ghostlight/src/verse/run.rs +++ b/crates/ghostlight/src/verse/run.rs @@ -22,10 +22,10 @@ //! A run starts only when it is invoked: nothing here waits, schedules or //! repeats. -use super::calls::{RecordingInferencePort, canonical}; +use super::calls::{RecordingInferencePort, WaveSpend, canonical}; use crate::cover::TickIndex; use crate::wave::{ - FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, Refusal, RefusalReason, UnattributedCall, + Deferral, FrozenCell, Focus, GestaltKnobs, GestaltKnobsError, Refusal, RefusalReason, UnattributedCall, WaveClock, WaveOutcome, WaveStop, plan_wave, run_frozen_cells, }; use crate::{ @@ -43,12 +43,16 @@ use thiserror::Error; 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.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"]; +pub const TICK_RECORD_SCHEMA: &str = "ghostlight.verse_tick.v3"; +const TICK_ROW: &str = "verse_tick.v3"; +/// The schemas later ones replaced. No store holding one is read: the verse store +/// has never held a live run, so there is no migration, and a retired row is +/// refused by name. +const RETIRED_SCHEMAS: [&str; 3] = [ + "ghostlight.verse_run.v1", + "ghostlight.verse_tick.v1", + "ghostlight.verse_tick.v2", +]; const CLOCK_NAMESPACE: &str = "ghostlight.verse.clock"; /// Why a run could not be recorded or started. Every variant names a kind of @@ -149,7 +153,7 @@ pub enum TickClose { World, } -/// What a tick decided when it opened. Document `ghostlight.verse_tick.v2`, +/// What a tick decided when it opened. Document `ghostlight.verse_tick.v3`, /// keyed (world, ordinal). Written once before the tick's first cell, closed /// once, never reopened or deleted. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -162,6 +166,10 @@ pub struct VerseTick { pub knobs: RecordedKnobs, pub oversubscribed: bool, pub cells: Vec, + /// The nodes the plan left out, with why: not due, or past the node-turn + /// bound. Written with the cells so a resumed tick reports what its wave + /// left out, not what a re-plan would. + pub deferred: Vec<(NodeId, Deferral)>, pub opened_by_run: u64, pub closed: Option, } @@ -214,6 +222,13 @@ pub struct NodeReport { pub spent: u64, } +/// A node that took no turn, or not all of it, as the operator reads it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DeferredNode { + pub label: String, + pub reason: Deferral, +} + /// A tick as the operator reads it, including the one a run ended inside. #[derive(Clone, Debug)] pub struct TickReport { @@ -223,6 +238,11 @@ pub struct TickReport { /// The labels of the subjects the checkpoint's refusals name, from the /// snapshot the tick opened on. pub labels: BTreeMap, + /// What this invocation's calls for the tick's cells cost, by lane and node. + pub spend: WaveSpend, + /// Nodes that took no turn this tick, and why: the plan left them out, or + /// the window's allowance ran out first. + pub deferred: Vec, pub spent: u64, pub remaining: u64, } @@ -304,6 +324,21 @@ impl std::fmt::Display for TickReport { for call in &checkpoint.unattributed { writeln!(f, " note: cell {} call names no handle: tool {:?}", call.cell, call.tool)?; } + for (reason, name) in [ + (Deferral::NotDue, "not due"), + (Deferral::OverBound, "over the node-turn bound"), + (Deferral::Allowance, "past the allowance"), + ] { + let labels: Vec<&str> = self + .deferred + .iter() + .filter(|node| node.reason == reason) + .map(|node| node.label.as_str()) + .collect(); + if !labels.is_empty() { + writeln!(f, " deferred ({name}): {}", labels.join(", "))?; + } + } writeln!( f, " tokens: {} this tick, {} spent, {} remaining", @@ -784,7 +819,7 @@ where return (TickEnd::Open(failed("run_store")), None); }; - let outcome = run_frozen_cells(mailbox, runner, index, &tick.cells, || port.spent()).await; + let outcome = run_frozen_cells(mailbox, runner, index, &tick.cells).await; let mut open = outcome.stop.map(status_of); // The act listing is the tick's report to the operator: a tick whose log @@ -797,6 +832,20 @@ where } }; + // So is a tick whose calls cannot be read back: its nodes' spend is the + // report's, and the ledger and the world must agree before time moves. + let spend = match port + .records() + .ok() + .and_then(|records| WaveSpend::of(&records, world, index, &tick.cells).ok()) + { + Some(spend) => spend, + None => { + open = Some(failed("call_records_unavailable")); + WaveSpend::default() + } + }; + if open.is_none() { if mailbox .submit_clock(clock_command_id(world, ordinal), span) @@ -840,7 +889,9 @@ where }) .collect(); let report = TickReport { - nodes: node_reports(&tick.cells, &outcome, acts, &snapshot, &hierarchy), + nodes: node_reports(&tick.cells, &outcome, acts, &spend, &snapshot, &hierarchy), + deferred: deferred_nodes(&tick, &outcome, &snapshot, &hierarchy), + spend, checkpoint, labels, spent, @@ -857,6 +908,7 @@ fn node_reports( frozen: &[FrozenCell], outcome: &WaveOutcome, acts: Vec, + spend: &WaveSpend, snapshot: &WorldSnapshot, hierarchy: &Hierarchy, ) -> Vec { @@ -881,7 +933,11 @@ fn node_reports( distance: Some(*distance), acts: Vec::new(), refusals: ran.map(|ran| ran.refusals.clone()).unwrap_or_default(), - spent: ran.map_or(0, |ran| ran.spent), + spent: spend + .nodes + .iter() + .find(|spent| spent.node == *node) + .map_or(0, |spent| spent.charged), } }) .collect(); @@ -914,6 +970,39 @@ fn node_reports( kept } +/// The nodes of the tick that took no turn: the plan's deferrals, frozen with +/// the tick, and, when the run stopped on its allowance, the nodes it never +/// reached and the one it stopped inside. A fault stop defers nothing. +fn deferred_nodes( + tick: &VerseTick, + outcome: &WaveOutcome, + snapshot: &WorldSnapshot, + hierarchy: &Hierarchy, +) -> Vec { + let mut deferred: Vec<(NodeId, Deferral)> = tick.deferred.clone(); + if outcome.stop == Some(WaveStop::Budget) { + let entered: Vec = outcome.nodes.iter().map(|node| node.node).collect(); + let stopped_in = entered.last().copied(); + let mut seen: Vec = Vec::new(); + for cell in &tick.cells { + if seen.contains(&cell.node) { + continue; + } + seen.push(cell.node); + if !entered.contains(&cell.node) || Some(cell.node) == stopped_in { + deferred.push((cell.node, Deferral::Allowance)); + } + } + } + deferred + .into_iter() + .map(|(node, reason)| DeferredNode { + label: node_label(node, snapshot, hierarchy), + reason, + }) + .collect() +} + /// 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 { @@ -996,6 +1085,7 @@ fn open_or_find( knobs: RecordedKnobs::of(&config.knobs), oversubscribed: wave.turns.iter().any(|turn| turn.oversubscribed), cells: wave.frozen(), + deferred: wave.deferred, 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 e8a2a5f..96245cc 100644 --- a/crates/ghostlight/src/verse/run/tests.rs +++ b/crates/ghostlight/src/verse/run/tests.rs @@ -7,13 +7,13 @@ use crate::controllers::{ }; use crate::cover::derive_cover; use crate::controllers::{CellRun, ConstituentRefusalReason, ControllerError}; -use crate::cover::CellId; +use crate::cover::{CellId, TickIndex}; use crate::wave::{CellEnd, absorb, classify, pending_code, refreshed}; use crate::{Cell, CoverBudget, CoverBudgetError, EntityId, SubmitReceipt}; use crate::tests::stock_weights; use crate::verse::{ - CallRecordStore, CreateVerseWorldIntent, RecordingInferencePort, ReplayInferencePort, - RunStart, + CallRecordStore, CreateVerseWorldIntent, LaneTokens, RecordingInferencePort, + ReplayInferencePort, RunStart, WaveSpend, }; use crate::{ BoundRole, CommandBody, ControllerMode, FictionalMinutes, KernelError, @@ -267,6 +267,7 @@ impl Harness { self.calls.clone(), call_run_id(sequence), cap, + LaneTokens { wave: cap, elaboration: 0 }, &RunStart::of(&world), ) .unwrap(), @@ -765,6 +766,8 @@ fn the_operator_reads_refusals_and_how_a_run_ended() { }], tokens: 7, }, + deferred: Vec::new(), + spend: WaveSpend::default(), nodes: vec![NodeReport { label: "Ironmarket Guild".into(), distance: Some(1), @@ -1068,6 +1071,7 @@ fn port_and_runner( verse.calls.clone(), call_run_id(sequence), cap, + LaneTokens { wave: cap, elaboration: 0 }, &RunStart::of(world), ) .unwrap(), @@ -1342,6 +1346,7 @@ async fn a_start_refused_after_the_claim_leaves_the_next_run_free_to_choose_its_ verse.calls.clone(), call_run_id(claim.sequence()), 1_000, + LaneTokens { wave: 1_000, elaboration: 0 }, &RunStart::of(&world), ) .unwrap(); @@ -1714,6 +1719,7 @@ fn tick_doc(world: WorldId, ordinal: u64) -> VerseTick { knobs: RecordedKnobs::of(&flat_knobs(two_cells())), oversubscribed: false, cells: Vec::new(), + deferred: Vec::new(), opened_by_run: 1, closed: None, } @@ -1790,7 +1796,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.v3", named.clone()), + envelope(tick_key(world, 0), TICK_ROW, "ghostlight.verse_tick.v4", named.clone()), envelope(tick_key(world, 0), TICK_ROW, TICK_RECORD_SCHEMA, vec![0xc0]), envelope( tick_key(world, 0), @@ -2138,6 +2144,7 @@ async fn open_tick_with(verse: &Harness, cells: Vec) { knobs: RecordedKnobs::of(&flat_knobs(two_cells())), oversubscribed: false, cells, + deferred: Vec::new(), opened_by_run: 1, closed: None, }) @@ -2978,6 +2985,30 @@ async fn a_tick_report_groups_acts_and_refusals_by_node() { report.nodes.iter().map(|node| node.spent).sum::(), report.checkpoint.tokens ); + // The spend report is the join of the run's records to the frozen cells: + // every call lands in the wave lane and in exactly one node, and the + // nodes' sum is what the port charged. + let records = verse.calls.records(&call_run_id(1)).unwrap(); + assert!(!records.is_empty()); + assert_eq!(report.spend.lanes.wave, report.checkpoint.tokens); + assert_eq!(report.spend.lanes.elaboration, 0); + assert_eq!( + report.spend.nodes.iter().map(|node| u64::from(node.calls)).sum::(), + records.len() as u64 + ); + for node in &report.nodes { + let joined = report + .spend + .nodes + .iter() + .find(|spent| spent.distance == node.distance.unwrap() && spent.charged == node.spent) + .expect("a node's spent is its joined records"); + assert!(joined.calls > 0); + } + // Another wave ordinal names other command ids: none of these calls is its. + let world = verse.mailbox.snapshot().await.unwrap().world_id; + let elsewhere = WaveSpend::of(&records, world, TickIndex(tick.ordinal + 1), &tick.cells).unwrap(); + assert_eq!(elsewhere.lanes, LaneTokens::default()); // The refusal is in the second node's report alone. let refused: Vec<(&str, usize)> = report .nodes diff --git a/crates/ghostlight/src/wave.rs b/crates/ghostlight/src/wave.rs index 12bbd06..b83acb2 100644 --- a/crates/ghostlight/src/wave.rs +++ b/crates/ghostlight/src/wave.rs @@ -118,12 +118,16 @@ pub struct NodeTurn { pub oversubscribed: bool, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Deferral { /// Its band's period has not passed since its most neglected voice. NotDue, /// Due, but the wave's node-turn bound ran out first. OverBound, + /// Planned, but a call could pass the window's allowance before the node + /// finished. The planner never returns this; a run that stops on budget + /// does. + Allowance, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -416,6 +420,19 @@ pub struct FrozenCell { } impl FrozenCell { + /// The command ids this cell submits under in wave `tick`: the group's one, + /// or one per constituent of a singleton, as `run_cell` derives them. + pub fn command_ids(&self, world: WorldId, tick: TickIndex) -> Vec { + if self.group { + vec![CommandId::for_cell(world, self.id, tick)] + } else { + self.members + .iter() + .map(|member| CommandId::for_cell_constituent(world, self.id, *member, tick)) + .collect() + } + } + pub(crate) fn of(cell: &Cell, node: NodeId, distance: u8) -> Self { let (id, group) = match cell { Cell::Singleton { id, .. } => (*id, false), @@ -671,8 +688,6 @@ pub struct NodeOutcome { 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 @@ -688,14 +703,13 @@ pub struct WaveOutcome { /// 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. +/// refusals. What a node's calls cost is the ledger's to say, joined through +/// [`FrozenCell::command_ids`]. 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; @@ -710,7 +724,6 @@ pub async fn run_frozen_cells( committed: Vec::new(), refusals: Vec::new(), unattributed: Vec::new(), - spent: 0, }); nodes.len() - 1 } @@ -732,7 +745,6 @@ pub async fn run_frozen_cells( let Some(cell) = cell else { continue; }; - let before = spent(); let result = runner.run_cell(&cell).await; let ended = absorb( result, @@ -742,7 +754,6 @@ pub async fn run_frozen_cells( &mut node.refusals, &mut node.unattributed, ); - node.spent += spent().saturating_sub(before); if ended.is_some() { stop = ended; break; From 0c80f39791dacaf327aaf51a4d318e4f45396645 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 09:50:01 +0100 Subject: [PATCH 2/4] docs: the ledger of the gestalt target has landed Co-Authored-By: Claude Sonnet 5.5 --- docs/targets/multiresolution-gestalt.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/targets/multiresolution-gestalt.md b/docs/targets/multiresolution-gestalt.md index 807025f..36c318b 100644 --- a/docs/targets/multiresolution-gestalt.md +++ b/docs/targets/multiresolution-gestalt.md @@ -270,6 +270,20 @@ Research notes of pass `gestalt-map` (`ghostlight-verse:research:gestalt-map.*`) stay a concurrency bound. The verse's `COVER` constant becomes a knob value. The verse's run token cap is the wave lane's allowance. +Landed (cut `gestalt-ledger`, on Ghostlight `main` `1419b3b`): call records are +`ghostlight.verse_provider_call.v2` (lane and request id) and a run's ledger +`ghostlight.verse_run_ledger.v2` (allowances and spend by lane). A call that +could pass its lane's allowance is refused `budget_exhausted` in `reserve`, +beside the run cap, before the provider is called; the play agent has no lane +and is refused at the port. `WaveSpend::of` joins records to a frozen wave by +the command id a request id begins with, so node spend is a join and +`NodeOutcome.spent` is gone. The verse tick is `ghostlight.verse_tick.v3` and +records what the plan deferred; the tick report lists deferred nodes with why +(not due, over the node-turn bound, past the allowance). The Dungeon's run-ahead +spends in `window-` of the timeline's `calls.cc`, with +`GHOSTLIGHT_WINDOW_WAVE_TOKENS` and `GHOSTLIGHT_WINDOW_ELABORATION_TOKENS` +(unset is unbounded) until `dm-gestalt-knobs` sets them from the knobs. + ### Deletion line Before the hierarchy lands nothing is deleted. In order: `react`'s mandatory From d846363781f07edeeeb9656b19d266121a237073 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 10:34:25 +0100 Subject: [PATCH 3/4] tests: a tick report lists deferred nodes with their reasons Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/verse/run/tests.rs | 54 ++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/ghostlight/src/verse/run/tests.rs b/crates/ghostlight/src/verse/run/tests.rs index 96245cc..6011ee3 100644 --- a/crates/ghostlight/src/verse/run/tests.rs +++ b/crates/ghostlight/src/verse/run/tests.rs @@ -3163,3 +3163,57 @@ async fn a_node_is_labelled_by_what_it_stands_on() { "a node the hierarchy does not hold has no label" ); } + +/// G6: a node that took no turn is in the report with why, whether the plan +/// left it out (frozen in the tick) or the window's allowance stopped the wave +/// inside or before it. A node that ran to its end is not deferred. +#[tokio::test] +async fn a_tick_report_lists_deferred_nodes_with_their_reasons() { + let (_probe_dir, probe) = Harness::fresh().await; + let measuring = ScriptedPort::speaking(); + probe.run_quietly(measuring.clone(), u64::MAX, 1).await; + let first_bound = measuring.bounds()[0]; + + let (_dir, verse) = Harness::fresh().await; + let config = deep_config(1); + let mut tick = opened_tick(&verse, &config).await; + let world = tick.world_id; + tick.deferred.push((NodeId::of(world, &NodeAnchor::World), Deferral::NotDue)); + verse.runs.put_tick(&tick).unwrap(); + + let mut reports = Vec::new(); + let ended = verse + .run_under(ScriptedPort::speaking(), first_bound + 64, config, |report| { + reports.push(report.clone()); + ControlFlow::Continue(()) + }) + .await; + assert_eq!(ended.record.status, RunStatus::BudgetExhausted); + let [report] = reports.as_slice() else { + panic!("one tick reported") + }; + let ran = report.nodes.iter().find(|node| node.acts.len() == 1).unwrap(); + let stopped = report.nodes.iter().find(|node| node.acts.is_empty()).unwrap(); + assert_eq!( + report.deferred, + vec![ + DeferredNode { + label: "world".into(), + reason: Deferral::NotDue + }, + DeferredNode { + label: stopped.label.clone(), + reason: Deferral::Allowance + }, + ], + "the plan's deferral and the node the allowance stopped in; not {}", + ran.label + ); + let text = report.to_string(); + assert!(text.contains(" deferred (not due): world\n"), "{text}"); + assert!( + text.contains(&format!(" deferred (past the allowance): {}\n", stopped.label)), + "{text}" + ); + assert!(!text.contains("over the node-turn bound"), "{text}"); +} From c8919594c65455a2384364a6732f25308475f46c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 10:40:13 +0100 Subject: [PATCH 4/4] tests: a node's spend is its own join Co-Authored-By: Claude Sonnet 5.5 --- crates/ghostlight/src/verse/run/tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ghostlight/src/verse/run/tests.rs b/crates/ghostlight/src/verse/run/tests.rs index 6011ee3..08ed4eb 100644 --- a/crates/ghostlight/src/verse/run/tests.rs +++ b/crates/ghostlight/src/verse/run/tests.rs @@ -3194,6 +3194,10 @@ async fn a_tick_report_lists_deferred_nodes_with_their_reasons() { }; let ran = report.nodes.iter().find(|node| node.acts.len() == 1).unwrap(); let stopped = report.nodes.iter().find(|node| node.acts.is_empty()).unwrap(); + // Each node's spend is its own join: the one that ran paid, the one the + // allowance refused made no recorded call. + assert!(ran.spent > 0); + assert_eq!(stopped.spent, 0); assert_eq!( report.deferred, vec![