Verse run: a tick is (world, clock-advance ordinal), its span and cells frozen in a tick document

The tick index is the world's TimeAdvanced count, read through a driver-only
mailbox door, and derive_cover takes it instead of now and the span. A tick
document ghostlight.verse_tick.v1 is written before the first cell and read by
any later run, so a resume under another span or cover budget finishes the open
tick as it was opened. The clock id is clock_command_id(world, ordinal) and is
pinned by a test. TickIndex::of and run_tick's per-call derive_cover are gone.

Fixes findings resume-rederives-tick-identity, tick-identity-collides-across-spans,
clock-id-unpinned. Not yet built or run at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-11 12:11:07 +02:00
commit 5277973afb
7 changed files with 768 additions and 135 deletions

View file

@ -469,7 +469,7 @@ mod tests {
AuthorityTargetRef, CallerId, CausalBoundary, CommandBody, CommandEnvelope, CommitmentKind,
ComponentOp, CoverBudget, DecisionOpportunity, DecisionScope, Declaration, DraftHandle,
EntityDeclaration, EntityId, EntityKind, EvidenceRef, FactDeclaration, FactStandingRef,
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref,
FictionalMinutes, JurisdictionKey, NewController, PatchGround, Quantity, Ref, TickIndex,
RouteDeclaration, Statement, SubjectDeclaration, SubjectId, SubjectKind, SystemCapability,
WorldEffect, WorldId, WorldKernel, WorldMailbox, WorldScaleIntentRef, agency_graph,
commit_digest, derive_boundaries, derive_cover, derive_opportunities,
@ -736,8 +736,7 @@ mod tests {
assert!(!graph.subjects.contains(&mirror.first));
let cover = derive_cover(
snapshot.world_id,
snapshot.now,
30,
TickIndex(0),
&opportunities,
&graph,
CoverBudget {

View file

@ -14699,8 +14699,7 @@ mod tests {
let graph = mailbox.agency_graph().await.unwrap();
let cover = derive_cover(
snapshot.world_id,
snapshot.now,
60,
TickIndex(snapshot.now.0 / 60),
&snapshot.opportunities,
&graph,
CoverBudget {

View file

@ -11,7 +11,6 @@
//! The cover is a partition, never a filter: every active subject is in exactly
//! one cell every tick. The budget decides at what resolution, not whether.
use super::clock::FictionalMinutes;
use super::{ControllerMode, DecisionOpportunity, SubjectId, WorldId};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@ -29,25 +28,18 @@ pub(crate) const AGENCY_STAR_THRESHOLD: usize = 16;
/// the name, not by a second namespace.
const COVER_NAMESPACE: &str = "ghostlight.cover.v1";
/// Monotone tick index. Derived from the world clock, never stored. It is
/// threaded into every derived command id, so a resumed tick over the same
/// snapshot re-derives the same ids and the kernel's idempotency ledger answers
/// with the original receipts instead of double-committing.
/// A tick's ordinal: the number of clock advances the world had committed when
/// the tick opened. The driver reads it from the world and freezes it in the
/// tick document; it is never derived from `now`, so it does not depend on the
/// span. It is threaded into every derived command id, so a resumed tick
/// re-submits the same ids and the kernel's idempotency ledger answers with the
/// original receipts instead of double-committing.
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default,
)]
#[serde(transparent)]
pub struct TickIndex(pub u64);
impl TickIndex {
/// Floor division by the span one `AdvanceTime` carries. The driver submits
/// the clock *after* the cells run, so every cell in one tick sees the same
/// `now` and therefore the same index.
pub(crate) fn of(now: FictionalMinutes, tick_minutes: u32) -> Self {
Self(now.0 / u64::from(tick_minutes.max(1)))
}
}
/// How a subject was represented this tick. Derived from the cell, carried
/// nowhere in world state: representation is a compute budget, not world truth.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -254,7 +246,7 @@ impl AgencyGraph {
}
}
/// The partition. Pure over `(world, now, opportunities, graph, budget)`.
/// The partition. Pure over `(world, tick, opportunities, graph, budget)`.
///
/// `opportunities` arrives in the kernel's one attention order (pressure, then
/// attention debt, then id) and is never re-sorted and never filtered here: a
@ -262,13 +254,11 @@ impl AgencyGraph {
/// is a fact about cognition rather than a scheduling preference.
pub fn derive_cover(
world: WorldId,
now: FictionalMinutes,
tick_minutes: u32,
tick: TickIndex,
opportunities: &[DecisionOpportunity],
graph: &AgencyGraph,
budget: CoverBudget,
) -> Cover {
let tick = TickIndex::of(now, tick_minutes);
let active: Vec<&DecisionOpportunity> = opportunities
.iter()
.filter(|opportunity| opportunity.controller_mode != ControllerMode::Human)
@ -601,8 +591,7 @@ mod tests {
) -> Cover {
derive_cover(
WorldId::nil_for_test(),
FictionalMinutes(tick * 60),
60,
TickIndex(tick),
opportunities,
graph,
budget,

View file

@ -1609,6 +1609,19 @@ impl WorldKernel {
))
}
/// How many clock advances the world has committed: the next tick's
/// ordinal, held by the world and read from its journal. Separate from
/// `snapshot` for the reason `opportunities` is: only the tick driver
/// reads it.
fn clock_advances(&self) -> Result<u64, KernelError> {
self.journal.ensure_healthy()?;
Ok(self
.journal
.commits()
.filter(|commit| matches!(commit.effect, WorldEffect::TimeAdvanced { .. }))
.count() as u64)
}
/// The scheduler's adjacency projection. Separate from `snapshot` for the
/// same reason `operator_log` is: it is wider than any subject view, so a
/// `WorldSnapshot` field carrying it would be reachable from every prompt

View file

@ -87,6 +87,11 @@ enum Request {
Opportunities {
reply: oneshot::Sender<Result<Vec<DecisionOpportunity>, KernelError>>,
},
/// The tick ordinal's one door: how many clock advances the world has
/// committed. Held by the tick driver, as `Opportunities` is.
ClockAdvances {
reply: oneshot::Sender<Result<u64, KernelError>>,
},
ControllerReceipt {
command_id: CommandId,
opportunity: super::DecisionOpportunity,
@ -506,6 +511,22 @@ impl WorldMailbox {
.map_err(MailboxError::Kernel)
}
/// The tick driver's ordinal: how many clock advances the world has
/// committed. It is on `WorldMailbox` and on no controller port, as
/// `opportunities` is.
pub async fn clock_advances(&self) -> Result<u64, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
.send(Request::ClockAdvances { reply })
.await
.map_err(|_| MailboxError::Unavailable)?;
response
.await
.map_err(|_| MailboxError::Unavailable)?
.map_err(MailboxError::Kernel)
}
pub async fn operator_log(&self) -> Result<Vec<OperatorEvent>, MailboxError> {
let (reply, response) = oneshot::channel();
self.sender
@ -988,6 +1009,19 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver<Request>)
return;
}
}
Request::ClockAdvances { reply } => {
let result = match &owned {
OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated),
OwnedWorld::Live(kernel) => kernel.clock_advances(),
};
let owner_must_stop = result
.as_ref()
.is_err_and(KernelError::requires_owner_restart);
let _ = reply.send(result);
if owner_must_stop {
return;
}
}
Request::ControllerReceipt {
command_id,
opportunity,

View file

@ -1,17 +1,22 @@
//! The manual verse run: the tick driver and its record.
//!
//! One invocation advances the world tick by tick. A tick reads the world,
//! derives the budgeted cover, runs each cell through the controller organ,
//! advances the clock once by the tick 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 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.
//!
//! The world's own clock is the resume point. A tick whose cells did not all
//! finish never advances the clock, so a later run derives the same tick index,
//! the same cells and the same command ids, the controller-work rows pick up
//! where they stopped, and the kernel answers every re-submission with the
//! original receipt. A run record therefore reports a run and is never read to
//! resume one.
//! 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
//! 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
//! and is never read to resume one.
//!
//! A run starts only when it is invoked: nothing here waits, schedules or
//! repeats.
@ -21,10 +26,12 @@ use crate::controllers::{
CellRun, ControllerError, ControllerPendingReason, ControllerRunner, InferenceFaultClass,
NarrativeRun, OperationalRun, SubmissionDisposition,
};
use crate::cover::{Cell, Constituent, CoverBudget, CoverBudgetError, derive_cover};
use crate::cover::{
Cell, CellId, Constituent, CoverBudget, CoverBudgetError, TickIndex, derive_cover,
};
use crate::{
CommandId, DecisionOpportunity, MailboxError, OperatorEvent, RenderPath, SubmitReceipt,
TickMinutes, WorldId, WorldMailbox,
AgencyGraph, CommandId, DecisionOpportunity, MailboxError, OperatorEvent, RenderPath,
SubjectId, SubmitReceipt, TickMinutes, WorldId, WorldMailbox, WorldSnapshot,
};
use chrono::Utc;
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
@ -35,6 +42,9 @@ 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";
/// The tick document's schema.
pub const TICK_RECORD_SCHEMA: &str = "ghostlight.verse_tick.v1";
const TICK_ROW: &str = "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
@ -98,11 +108,12 @@ pub struct Refusal {
}
/// A tick as the run left it. A closed tick has all its cells run and the
/// clock advanced by the run's span. The tick a run ended inside is recorded
/// too, unclosed, so what its cells committed is not lost; a later run derives
/// that tick again from the world's clock.
/// 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
/// run finds that tick's document open and works in it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TickCheckpoint {
/// The tick's ordinal, as its tick document names it.
pub tick: u64,
pub closed: bool,
pub cells: u32,
@ -122,6 +133,58 @@ pub struct RecordedCoverBudget {
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<SubjectId>,
}
impl FrozenCell {
fn of(cell: &Cell) -> 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(),
}
}
}
/// What closed a tick.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TickClose {
/// The run with this sequence submitted the tick's clock advance.
Clock { run: u64 },
/// A later run found the world's ordinal past the tick with the document
/// still open: its clock landed and the close was lost, or another clock
/// writer moved time.
World,
}
/// What a tick decided when it opened. Document `ghostlight.verse_tick.v1`,
/// keyed (world, ordinal). Written once before the tick's first cell, closed
/// once, never reopened or deleted.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerseTick {
pub world_id: WorldId,
pub ordinal: u64,
pub opened_now: u64,
pub opened_revision: u64,
pub span_minutes: u32,
pub cover_budget: RecordedCoverBudget,
pub oversubscribed: bool,
pub cells: Vec<FrozenCell>,
pub opened_by_run: u64,
pub closed: Option<TickClose>,
}
/// One invocation of the verse runner: what it was asked, what it did.
/// Document `ghostlight.verse_run.v1`, keyed (world, run sequence).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -235,8 +298,19 @@ fn row_key(world: WorldId, sequence: u64) -> String {
format!("{}/{sequence:020}", world.key())
}
/// Run records in one CultCache file. A run is saved when it begins and again
/// each time it moves, so a row is replaced by its own later state.
fn tick_key(world: WorldId, ordinal: u64) -> String {
format!("{}/{ordinal:020}", world.key())
}
/// Every row of the file, split by type.
struct Rows {
runs: Vec<VerseRunRecord>,
ticks: Vec<VerseTick>,
}
/// Run records and tick documents in one CultCache file. A run is saved when
/// it begins and again each time it moves, so a row is replaced by its own
/// later state. A tick is opened once and closed once.
pub struct VerseRunStore {
store: Mutex<OwnedRedbMessagePackBackingStore>,
}
@ -257,27 +331,40 @@ impl VerseRunStore {
Ok(opened)
}
fn records(&self) -> Result<Vec<VerseRunRecord>, VerseRunError> {
fn records(&self) -> Result<Rows, VerseRunError> {
let rows = self
.store
.lock()
.map_err(|_| VerseRunError::Store)?
.pull_all()
.map_err(|_| VerseRunError::Store)?;
let mut records = Vec::new();
let mut runs = Vec::new();
let mut ticks = Vec::new();
for row in &rows {
if row.r#type != RUN_ROW || row.schema_id.as_deref() != Some(RUN_RECORD_SCHEMA) {
return Err(VerseRunError::Corrupt);
match (row.r#type.as_str(), row.schema_id.as_deref()) {
(RUN_ROW, Some(RUN_RECORD_SCHEMA)) => {
let record: VerseRunRecord =
canonical(row).map_err(|_| VerseRunError::Corrupt)?;
if row.key != row_key(record.world_id, record.sequence)
|| record.sequence == 0
{
return Err(VerseRunError::Corrupt);
}
runs.push(record);
}
(TICK_ROW, Some(TICK_RECORD_SCHEMA)) => {
let tick: VerseTick = canonical(row).map_err(|_| VerseRunError::Corrupt)?;
if row.key != tick_key(tick.world_id, tick.ordinal) {
return Err(VerseRunError::Corrupt);
}
ticks.push(tick);
}
_ => return Err(VerseRunError::Corrupt),
}
let record: VerseRunRecord =
canonical(row).map_err(|_| VerseRunError::Corrupt)?;
if row.key != row_key(record.world_id, record.sequence) || record.sequence == 0 {
return Err(VerseRunError::Corrupt);
}
records.push(record);
}
records.sort_by_key(|record| (record.world_id.key(), record.sequence));
Ok(records)
runs.sort_by_key(|record| (record.world_id.key(), record.sequence));
ticks.sort_by_key(|tick| (tick.world_id.key(), tick.ordinal));
Ok(Rows { runs, ticks })
}
/// The sequence the next run of this world must carry. Sequences count from
@ -285,6 +372,7 @@ impl VerseRunStore {
pub fn next_sequence(&self, world: WorldId) -> Result<u64, VerseRunError> {
Ok(self
.records()?
.runs
.iter()
.filter(|record| record.world_id == world)
.map(|record| record.sequence)
@ -297,11 +385,72 @@ impl VerseRunStore {
pub fn runs(&self, world: WorldId) -> Result<Vec<VerseRunRecord>, VerseRunError> {
Ok(self
.records()?
.runs
.into_iter()
.filter(|record| record.world_id == world)
.collect())
}
/// The tick document of (world, ordinal), when one was opened.
pub fn tick(&self, world: WorldId, ordinal: u64) -> Result<Option<VerseTick>, VerseRunError> {
Ok(self
.records()?
.ticks
.into_iter()
.find(|tick| tick.world_id == world && tick.ordinal == ordinal))
}
/// Writes a tick document that does not exist yet, open.
pub fn open_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
if tick.closed.is_some() || self.tick(tick.world_id, tick.ordinal)?.is_some() {
return Err(VerseRunError::OutOfSequence);
}
self.put_tick(tick)
}
/// Closes an open tick document.
pub fn close_tick(
&self,
world: WorldId,
ordinal: u64,
close: TickClose,
) -> Result<(), VerseRunError> {
let Some(mut tick) = self.tick(world, ordinal)? else {
return Err(VerseRunError::OutOfSequence);
};
if tick.closed.is_some() {
return Err(VerseRunError::OutOfSequence);
}
tick.closed = Some(close);
self.put_tick(&tick)
}
/// Closes, as the world's, every open tick of the world below `ordinal`.
pub fn close_ticks_before(&self, world: WorldId, ordinal: u64) -> Result<(), VerseRunError> {
for mut tick in self.records()?.ticks {
if tick.world_id == world && tick.ordinal < ordinal && tick.closed.is_none() {
tick.closed = Some(TickClose::World);
self.put_tick(&tick)?;
}
}
Ok(())
}
fn put_tick(&self, tick: &VerseTick) -> Result<(), VerseRunError> {
let row = CultCacheEnvelope {
key: tick_key(tick.world_id, tick.ordinal),
r#type: TICK_ROW.into(),
payload: rmp_serde::to_vec_named(tick).map_err(|_| VerseRunError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(TICK_RECORD_SCHEMA.into()),
};
self.store
.lock()
.map_err(|_| VerseRunError::Store)?
.push(&row)
.map_err(|_| VerseRunError::Store)
}
/// Writes the record: the next run of its world, or a run already saved.
pub fn save(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
if record.sequence == 0 || record.sequence > self.next_sequence(record.world_id)? {
@ -404,36 +553,38 @@ fn absorb(
}
}
/// The cell with each member's opportunity read fresh. The cover is a
/// partition of subjects, fixed for the tick; 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(cell: &Cell, fresh: &[DecisionOpportunity]) -> Option<Cell> {
let current = |member: &Constituent| {
fresh
.iter()
.find(|opportunity| opportunity.scope == member.opportunity.scope)
.map(|opportunity| Constituent {
subject: member.subject,
opportunity: opportunity.clone(),
})
};
match cell {
Cell::Singleton { id, tick, member } => current(member).map(|member| Cell::Singleton {
id: *id,
tick: *tick,
/// The frozen cell with each member bound to the opportunity the world holds
/// for that subject now. 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<Cell> {
let members: Vec<Constituent> = frozen
.members
.iter()
.filter_map(|subject| {
fresh
.iter()
.find(|opportunity| opportunity.scope.subject_id == *subject)
.map(|opportunity| Constituent {
subject: *subject,
opportunity: opportunity.clone(),
})
})
.collect();
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::Group { id, tick, members } => {
let members: Vec<Constituent> = members.iter().filter_map(current).collect();
(!members.is_empty()).then(|| Cell::Group {
id: *id,
tick: *tick,
members,
})
}
})
}
}
@ -493,6 +644,8 @@ pub async fn run_manual(
mailbox,
runner,
port,
store,
sequence,
config,
cover_budget,
spent_before,
@ -535,40 +688,60 @@ pub fn call_run_id(sequence: u64) -> super::RunId {
.expect("a decimal sequence is a canonical run id")
}
/// One tick. The report is absent only when the world could not be read at all.
/// The id of a tick's clock advance: the world and the ordinal, nothing the
/// run holds. A retry in the same tick has the same body and is answered
/// `AlreadyApplied`.
pub(crate) fn clock_command_id(world: WorldId, ordinal: u64) -> CommandId {
CommandId::derived(CLOCK_NAMESPACE, &[&world.text(), &ordinal.to_string()])
}
/// 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,
port: &RecordingInferencePort,
store: &VerseRunStore,
sequence: u64,
config: &VerseRunConfig,
cover_budget: CoverBudget,
spent_before: u64,
) -> (TickEnd, Option<TickReport>) {
let read = async {
let snapshot = mailbox.snapshot().await?;
let ordinal = mailbox.clock_advances().await?;
let opportunities = mailbox.opportunities().await?;
let graph = mailbox.agency_graph().await?;
Ok::<_, MailboxError>((snapshot, opportunities, graph))
Ok::<_, MailboxError>((snapshot, ordinal, opportunities, graph))
}
.await;
let Ok((snapshot, opportunities, graph)) = read else {
let Ok((snapshot, ordinal, opportunities, graph)) = read else {
return (TickEnd::Open(failed("world_unavailable")), None);
};
let span = config.tick_span;
let cover = derive_cover(
snapshot.world_id,
snapshot.now,
span.minutes(),
let world = snapshot.world_id;
let Ok(tick) = open_or_find(
store,
ordinal,
sequence,
config,
cover_budget,
&snapshot,
&opportunities,
&graph,
cover_budget,
);
) else {
return (TickEnd::Open(failed("run_store")), None);
};
let index = TickIndex(ordinal);
let Some(span) = TickMinutes::new(tick.span_minutes) else {
return (TickEnd::Open(failed("run_store")), None);
};
let mut committed = Vec::new();
let mut refusals = Vec::new();
let mut open: Option<RunStatus> = None;
for (index, cell) in cover.cells.iter().enumerate() {
let index = index as u32;
for (position, frozen) in tick.cells.iter().enumerate() {
let position = position as u32;
let fresh = match mailbox.opportunities().await {
Ok(fresh) => fresh,
Err(_) => {
@ -576,16 +749,16 @@ async fn run_tick(
break;
}
};
let Some(cell) = refreshed(cell, &fresh) else {
let Some(cell) = refreshed(frozen, index, &fresh) else {
refusals.push(Refusal {
cell: index,
cell: position,
reason: RefusalReason::OpportunityGone,
});
continue;
};
match runner.run_cell(&cell).await {
Ok(run) => {
if let Some(code) = absorb(run, index, &mut committed, &mut refusals) {
if let Some(code) = absorb(run, position, &mut committed, &mut refusals) {
open = Some(failed(code));
break;
}
@ -600,7 +773,7 @@ async fn run_tick(
break;
}
CellEnd::Refused(reason) => refusals.push(Refusal {
cell: index,
cell: position,
reason,
}),
},
@ -609,21 +782,26 @@ async fn run_tick(
let closed = open.is_none();
if closed {
let clock = CommandId::derived(
CLOCK_NAMESPACE,
&[&snapshot.world_id.text(), &cover.tick.0.to_string()],
);
if mailbox.submit_clock(clock, span).await.is_err() {
if mailbox
.submit_clock(clock_command_id(world, ordinal), span)
.await
.is_err()
{
open = Some(failed("clock_refused"));
} else if store
.close_tick(world, ordinal, TickClose::Clock { run: sequence })
.is_err()
{
open = Some(failed("run_store"));
}
}
let spent = port.spent();
let report = TickReport {
checkpoint: TickCheckpoint {
tick: cover.tick.0,
tick: ordinal,
closed: open.is_none(),
cells: cover.cells.len() as u32,
cells: tick.cells.len() as u32,
committed,
refusals,
tokens: spent.saturating_sub(spent_before),
@ -643,5 +821,50 @@ async fn run_tick(
(open.map_or(TickEnd::Closed, TickEnd::Open), Some(report))
}
/// 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.
#[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,
) -> Result<VerseTick, VerseRunError> {
let world = snapshot.world_id;
store.close_ticks_before(world, ordinal)?;
if let Some(tick) = store.tick(world, ordinal)? {
return if tick.closed.is_none() {
Ok(tick)
} else {
Err(VerseRunError::OutOfSequence)
};
}
let cover = derive_cover(world, TickIndex(ordinal), opportunities, graph, cover_budget);
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(),
opened_by_run: sequence,
closed: None,
};
store.open_tick(&tick)?;
Ok(tick)
}
#[cfg(test)]
mod tests;

View file

@ -220,6 +220,17 @@ impl Harness {
cap: u64,
ticks: u32,
observe: impl FnMut(&TickReport) -> ControlFlow<()>,
) -> RunOutcome {
self.run_under(inner, cap, config(ticks), observe).await
}
/// One run under the given config, recorded under the next sequence.
async fn run_under(
&self,
inner: Arc<dyn InferencePort>,
cap: u64,
config: VerseRunConfig,
observe: impl FnMut(&TickReport) -> ControlFlow<()>,
) -> RunOutcome {
let world = self.mailbox.snapshot().await.unwrap();
let sequence = self.runs.next_sequence(world.world_id).unwrap();
@ -241,7 +252,7 @@ impl Harness {
&runner,
&port,
&self.runs,
&config(ticks),
&config,
sequence,
observe,
)
@ -254,6 +265,15 @@ impl Harness {
.await
}
async fn run_quietly_under(
&self,
inner: Arc<dyn InferencePort>,
config: VerseRunConfig,
) -> RunOutcome {
self.run_under(inner, u64::MAX, config, |_| ControlFlow::Continue(()))
.await
}
async fn now(&self) -> u64 {
self.mailbox.snapshot().await.unwrap().now.0
}
@ -279,8 +299,6 @@ impl Harness {
async fn scripted_run_commits_and_checkpoints_every_tick() {
let (_dir, verse) = Harness::fresh().await;
let world = verse.mailbox.snapshot().await.unwrap();
let opportunities = verse.mailbox.opportunities().await.unwrap();
let graph = verse.mailbox.agency_graph().await.unwrap();
let port = ScriptedPort::speaking();
let mut reports = Vec::new();
let outcome = verse
@ -300,25 +318,28 @@ async fn scripted_run_commits_and_checkpoints_every_tick() {
assert_eq!(verse.acts().await, 6);
assert_eq!(port.calls(), 6);
// Every committed command id is the one the cover derives for that cell,
// in cell order.
// Every committed command id is the one the tick document's frozen cells
// derive, in cell order, and the document is closed by this run's clock.
for checkpoint in &outcome.record.checkpoints {
let cover = derive_cover(
world.world_id,
FictionalMinutes(checkpoint.tick * u64::from(SPAN)),
SPAN,
&opportunities,
&graph,
two_cells(),
);
let expected: Vec<CommandId> = cover
let tick = verse
.runs
.tick(world.world_id, checkpoint.tick)
.unwrap()
.unwrap();
assert_eq!(tick.closed, Some(TickClose::Clock { run: 1 }));
assert_eq!(tick.opened_by_run, 1);
assert_eq!(tick.span_minutes, SPAN);
let expected: Vec<CommandId> = tick
.cells
.iter()
.map(|cell| match cell {
Cell::Singleton { id, tick, member } => {
CommandId::for_cell_constituent(world.world_id, *id, member.subject, *tick)
}
Cell::Group { .. } => panic!("two factions under two cells are singletons"),
.map(|cell| {
assert!(!cell.group, "two factions under two cells are singletons");
CommandId::for_cell_constituent(
world.world_id,
cell.id,
cell.members[0],
TickIndex(checkpoint.tick),
)
})
.collect();
assert_eq!(expected.len(), 2);
@ -441,6 +462,10 @@ async fn budget_exhausted_stops_before_the_clock_and_resumes() {
.await;
assert_eq!(resumed.record.status, RunStatus::Completed);
assert_eq!(resumed.record.sequence, 2);
// The resumed tick is the document run 1 opened, closed by run 2.
let opened = verse.runs.tick(world.world_id, 0).unwrap().unwrap();
assert_eq!(opened.opened_by_run, 1);
assert_eq!(opened.closed, Some(TickClose::Clock { run: 2 }));
let ticks: Vec<u64> = resumed.record.checkpoints.iter().map(|c| c.tick).collect();
assert_eq!(ticks, vec![0, 1], "the open tick is the first this run closes");
assert_eq!(verse.now().await, 2 * u64::from(SPAN));
@ -771,16 +796,14 @@ async fn a_cell_is_run_on_what_the_world_holds_for_its_members_now() {
let world = verse.mailbox.snapshot().await.unwrap().world_id;
let singles = derive_cover(
world,
FictionalMinutes(0),
SPAN,
TickIndex(0),
&opportunities,
&graph,
two_cells(),
);
let group = derive_cover(
world,
FictionalMinutes(0),
SPAN,
TickIndex(0),
&opportunities,
&graph,
CoverBudget {
@ -803,13 +826,16 @@ 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 Some(Cell::Singleton { member, .. }) = refreshed(cell, &moved) else {
let frozen = FrozenCell::of(cell);
let Some(Cell::Singleton { member, .. }) = refreshed(&frozen, TickIndex(0), &moved) else {
panic!("a subject that still has an opportunity keeps its cell")
};
assert_ne!(member.opportunity, held.opportunity);
assert!(moved.contains(&member.opportunity));
}
let Some(Cell::Group { members: now, .. }) = refreshed(grouped, &moved) else {
let frozen_group = FrozenCell::of(grouped);
let Some(Cell::Group { members: now, .. }) = refreshed(&frozen_group, TickIndex(0), &moved)
else {
panic!("a group keeps its members")
};
assert_eq!(now.len(), 2);
@ -817,7 +843,8 @@ async fn a_cell_is_run_on_what_the_world_holds_for_its_members_now() {
// A subject with no opportunity leaves its cell, and an empty cell is gone.
let one = &opportunities[..1];
let Some(Cell::Group { members: left, .. }) = refreshed(grouped, one) else {
let Some(Cell::Group { members: left, .. }) = refreshed(&frozen_group, TickIndex(0), one)
else {
panic!("one member remains")
};
assert_eq!(left.len(), 1);
@ -825,10 +852,10 @@ async fn a_cell_is_run_on_what_the_world_holds_for_its_members_now() {
let gone = singles
.cells
.iter()
.filter(|cell| refreshed(cell, one).is_none())
.filter(|cell| refreshed(&FrozenCell::of(cell), TickIndex(0), one).is_none())
.count();
assert_eq!(gone, 1);
assert!(refreshed(grouped, &[]).is_none());
assert!(refreshed(&frozen_group, TickIndex(0), &[]).is_none());
}
#[test]
@ -1038,3 +1065,352 @@ fn the_run_store_refuses_rows_that_are_not_canonical_run_records() {
);
}
}
/// A port that answers like `ScriptedPort::speaking` and fails the `at`th
/// provider call it sees, retryably.
struct FaultAt {
inner: Arc<ScriptedPort>,
at: usize,
seen: AtomicUsize,
}
#[async_trait]
impl InferencePort for FaultAt {
fn prepare(&self, request: InferenceRequest) -> Result<PreparedInference, InferenceFault> {
self.inner.prepare(request)
}
async fn infer(&self, request: PreparedInference) -> Result<InferenceOutput, InferenceFault> {
if self.seen.fetch_add(1, Ordering::SeqCst) == self.at {
return Err(InferenceFault::retryable("the provider is busy"));
}
self.inner.infer(request).await
}
}
fn fault_at(at: usize) -> Arc<FaultAt> {
Arc::new(FaultAt {
inner: ScriptedPort::speaking(),
at,
seen: AtomicUsize::new(0),
})
}
fn config_of(ticks: u32, span: u32, cells: u16) -> VerseRunConfig {
VerseRunConfig {
ticks,
tick_span: TickMinutes::new(span).unwrap(),
cover: CoverBudget {
cells,
constituent_cap: 8,
urgency_slots: 0,
},
}
}
/// Run 1 closes tick 0 (two cells, 60 minutes). Run 2 commits one faction's act
/// in tick 1 and ends pending. Run 3 resumes under `resume`. Asserts that each
/// faction acted exactly once between the end of run 1 and the end of run 3.
async fn resumed_after_a_pending_cell(
resume: VerseRunConfig,
) -> (tempfile::TempDir, Harness, RunOutcome) {
let (dir, verse) = Harness::fresh().await;
let first = verse
.run_quietly_under(ScriptedPort::speaking(), config_of(1, 60, 2))
.await;
assert_eq!(first.record.status, RunStatus::Completed);
let mark = verse.mailbox.snapshot().await.unwrap().revision;
let ended = verse
.run_quietly_under(fault_at(1), config_of(1, 60, 2))
.await;
assert_eq!(
ended.record.status,
RunStatus::Failed {
reason: "inference_retryable".into()
}
);
let opened: Vec<_> = verse
.mailbox
.operator_log()
.await
.unwrap()
.into_iter()
.filter(|event| event.revision > mark)
.map(|event| event.speaker)
.collect();
assert_eq!(opened.len(), 1, "one faction acted in the open tick");
let resumed = verse
.run_quietly_under(ScriptedPort::speaking(), resume)
.await;
assert_eq!(resumed.record.status, RunStatus::Completed);
let since: Vec<_> = verse
.mailbox
.operator_log()
.await
.unwrap()
.into_iter()
.filter(|event| event.revision > mark)
.map(|event| event.speaker)
.collect();
assert_eq!(since.len(), 2, "each faction acted once in the open tick");
assert_eq!(
since.iter().filter(|speaker| **speaker == opened[0]).count(),
1,
"the faction that acted before the pause did not act again"
);
(dir, verse, resumed)
}
#[tokio::test]
async fn a_resume_under_another_span_finishes_the_open_tick_under_its_own() {
let (_dir, verse, resumed) = resumed_after_a_pending_cell(config_of(1, 30, 2)).await;
// Tick 1's clock advance is the frozen 60 minutes, not the resuming 30.
assert_eq!(verse.now().await, 120);
let world = verse.mailbox.snapshot().await.unwrap().world_id;
let tick = verse.runs.tick(world, 1).unwrap().unwrap();
assert_eq!(tick.span_minutes, 60);
assert_eq!(tick.opened_by_run, 2);
assert_eq!(tick.closed, Some(TickClose::Clock { run: 3 }));
let [closing] = resumed.record.checkpoints.as_slice() else {
panic!("the resuming run closed one tick")
};
assert_eq!(closing.tick, 1);
assert!(closing.closed);
}
#[tokio::test]
async fn a_resume_under_another_cover_budget_keeps_the_frozen_cells() {
// One cell would be a group of both factions; the open tick keeps its two
// singletons.
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.cells.len(), 2);
assert!(tick.cells.iter().all(|cell| !cell.group));
assert_eq!(resumed.record.checkpoints[0].cells, 2);
assert_eq!(verse.now().await, 120);
}
#[tokio::test]
async fn a_new_span_opens_a_new_tick_and_never_reuses_a_closed_one() {
let (_dir, verse) = Harness::fresh().await;
let first = verse
.run_quietly_under(ScriptedPort::speaking(), config_of(2, 60, 2))
.await;
assert_eq!(first.record.status, RunStatus::Completed);
assert_eq!(verse.now().await, 120);
let acts = verse.acts().await;
let port = ScriptedPort::speaking();
let second = verse
.run_quietly_under(port.clone(), config_of(2, 120, 2))
.await;
assert_eq!(second.record.status, RunStatus::Completed);
let ordinals: Vec<u64> = second.record.checkpoints.iter().map(|c| c.tick).collect();
assert_eq!(ordinals, vec![2, 3]);
assert_eq!(verse.now().await, 120 + 240);
assert_eq!(verse.acts().await, acts + 4);
assert_eq!(port.calls(), 4);
let before: Vec<CommandId> = first
.record
.checkpoints
.iter()
.flat_map(|c| c.committed.clone())
.collect();
for checkpoint in &second.record.checkpoints {
assert!(checkpoint.committed.iter().all(|id| !before.contains(id)));
}
}
#[tokio::test]
async fn a_closed_ticks_clock_is_answered_from_the_kernels_ledger() {
let (_dir, verse) = Harness::fresh().await;
verse.run_quietly(ScriptedPort::speaking(), u64::MAX, 2).await;
let world = verse.mailbox.snapshot().await.unwrap().world_id;
assert_eq!(verse.now().await, 120);
for ordinal in 0..2 {
let receipt = verse
.mailbox
.submit_clock(
clock_command_id(world, ordinal),
TickMinutes::new(SPAN).unwrap(),
)
.await
.unwrap();
assert!(
matches!(receipt, SubmitReceipt::AlreadyApplied(_)),
"the clock of tick {ordinal} was not the id the run submitted"
);
}
assert_eq!(verse.now().await, 120);
}
#[tokio::test]
async fn an_open_tick_the_world_moved_past_is_closed_by_the_world() {
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 world = verse.mailbox.snapshot().await.unwrap().world_id;
let ended = verse
.run_under(
ScriptedPort::speaking(),
first_bound + 64,
config(1),
|_| ControlFlow::Continue(()),
)
.await;
assert_eq!(ended.record.status, RunStatus::BudgetExhausted);
assert_eq!(verse.acts().await, 1);
// Another writer moves time without closing the tick.
verse
.mailbox
.submit_clock(CommandId::new(), TickMinutes::new(SPAN).unwrap())
.await
.unwrap();
assert_eq!(verse.now().await, 60);
let resumed = verse
.run_quietly(ScriptedPort::speaking(), u64::MAX, 1)
.await;
assert_eq!(resumed.record.status, RunStatus::Completed);
let abandoned = verse.runs.tick(world, 0).unwrap().unwrap();
assert_eq!(abandoned.closed, Some(TickClose::World));
let next = verse.runs.tick(world, 1).unwrap().unwrap();
assert_eq!(next.opened_by_run, 2);
assert_eq!(next.closed, Some(TickClose::Clock { run: 2 }));
let [checkpoint] = resumed.record.checkpoints.as_slice() else {
panic!("one tick, one checkpoint")
};
assert_eq!(checkpoint.tick, 1);
assert_eq!(checkpoint.committed.len(), 2, "a fresh cover ran both factions");
assert_eq!(verse.acts().await, 3);
assert_eq!(verse.now().await, 120);
// No faction has two acts in one ordinal: ordinal 1 opened after run 1's
// act, so its acts are the ones past the tick's opening revision.
let log = verse.mailbox.operator_log().await.unwrap();
for speaker in log.iter().map(|event| event.speaker) {
let in_first = log
.iter()
.filter(|event| event.speaker == speaker && event.revision <= next.opened_revision)
.count();
let in_second = log
.iter()
.filter(|event| event.speaker == speaker && event.revision > next.opened_revision)
.count();
assert!(in_first <= 1 && in_second <= 1);
}
}
fn tick_doc(world: WorldId, ordinal: u64) -> VerseTick {
VerseTick {
world_id: world,
ordinal,
opened_now: 0,
opened_revision: 3,
span_minutes: SPAN,
cover_budget: RecordedCoverBudget {
cells: 2,
constituent_cap: 8,
urgency_slots: 0,
},
oversubscribed: false,
cells: Vec::new(),
opened_by_run: 1,
closed: None,
}
}
#[test]
fn the_tick_store_opens_once_closes_once_and_refuses_non_canonical_rows() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("runs.cc");
let store = VerseRunStore::open(&path).unwrap();
let world = WorldId::nil_for_test();
let other = WorldId::issue();
store.open_tick(&tick_doc(world, 0)).unwrap();
assert!(matches!(
store.open_tick(&tick_doc(world, 0)),
Err(VerseRunError::OutOfSequence)
));
// A tick opened already closed is not an open.
let mut born_closed = tick_doc(world, 5);
born_closed.closed = Some(TickClose::World);
assert!(matches!(
store.open_tick(&born_closed),
Err(VerseRunError::OutOfSequence)
));
assert!(matches!(
store.close_tick(world, 9, TickClose::World),
Err(VerseRunError::OutOfSequence)
));
store
.close_tick(world, 0, TickClose::Clock { run: 4 })
.unwrap();
assert!(matches!(
store.close_tick(world, 0, TickClose::World),
Err(VerseRunError::OutOfSequence)
));
// The world closes the open ticks below an ordinal and no others.
for ordinal in 1..4 {
store.open_tick(&tick_doc(world, ordinal)).unwrap();
}
store.open_tick(&tick_doc(other, 1)).unwrap();
store.close_ticks_before(world, 3).unwrap();
let closed_by = |store: &VerseRunStore, world, ordinal| {
store.tick(world, ordinal).unwrap().unwrap().closed
};
assert_eq!(closed_by(&store, world, 0), Some(TickClose::Clock { run: 4 }));
assert_eq!(closed_by(&store, world, 1), Some(TickClose::World));
assert_eq!(closed_by(&store, world, 2), Some(TickClose::World));
assert_eq!(closed_by(&store, world, 3), None);
assert_eq!(closed_by(&store, other, 1), None);
assert!(store.tick(world, 7).unwrap().is_none());
// Tick documents and run records share the file and reopen intact.
store.save(&record(world, 1)).unwrap();
drop(store);
let store = VerseRunStore::open(&path).unwrap();
assert_eq!(store.runs(world).unwrap(), vec![record(world, 1)]);
assert_eq!(closed_by(&store, world, 2), Some(TickClose::World));
let good = tick_doc(world, 0);
let envelope = |key: String, row_type: &str, schema: &str, payload: Vec<u8>| CultCacheEnvelope {
key,
r#type: row_type.into(),
payload,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(schema.into()),
};
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, TICK_RECORD_SCHEMA, vec![0xc0]),
envelope(
tick_key(world, 0),
TICK_ROW,
TICK_RECORD_SCHEMA,
rmp_serde::to_vec(&good).unwrap(),
),
envelope(tick_key(world, 0), "something_else.v1", TICK_RECORD_SCHEMA, named),
];
for (index, row) in cases.into_iter().enumerate() {
let file = dir.path().join(format!("tick-case-{index}.cc"));
{
let mut raw = OwnedRedbMessagePackBackingStore::new(&file).unwrap();
raw.push(&row).unwrap();
}
assert!(
matches!(VerseRunStore::open(&file), Err(VerseRunError::Corrupt)),
"tick case {index} was accepted"
);
}
}