Verse run: the run store claims a run's sequence before its call ledger opens

next_sequence was a public read followed by a caller-chosen sequence on save,
so a second run could take number 1 and overwrite run 1's record, and a start
refused after its ledger opened bound that cap to the number the next run was
handed. VerseRunStore::claim now allocates and writes the Running record in one
insert-if-absent and returns a non-Clone RunClaim; next_sequence and save are
private and save is update-only. run_manual takes the claim, refuses a port
whose run id or cap is not the claim's, a claim for another world, or a config
other than the claim's, and abandons the claim as Failed in each case. The
binary claims before opening the ledger and abandons a start it cannot make.
Fixes old-sequence-overwrites-record and refused-start-binds-cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-11 14:47:52 +02:00
commit d1883e9973
5 changed files with 384 additions and 133 deletions

View file

@ -195,13 +195,40 @@ async fn run(flags: Flags) -> Result<ExitCode> {
let runs = VerseRunStore::open(state.join("runs.cc")).context("the run records cannot be opened")?;
let work = open_controller_work(state.join("controller-work.cc"))
.context("the controller work store cannot be opened")?;
let sequence = runs.next_sequence(world.world_id).context("the run records cannot be read")?;
let port = Arc::new(
RecordingInferencePort::open(inner, calls, call_run_id(sequence), cap, &RunStart::of(&world))
.context("the run's call records cannot be opened")?,
);
let runner = ControllerRunner::open(mailbox.clone(), port.clone(), work, models)
.context("the controller organ cannot open")?;
let config = VerseRunConfig {
ticks,
tick_span,
cover: COVER,
};
let claim = runs
.claim(&world, cap, &config)
.context("the run cannot be claimed")?;
let sequence = claim.sequence();
// A start that fails after the claim ends the claimed run, so it binds
// nothing: the next claim takes the next number.
let started = RecordingInferencePort::open(
inner,
calls,
call_run_id(sequence),
cap,
&RunStart::of(&world),
)
.context("the run's call records cannot be opened")
.and_then(|port| {
let port = Arc::new(port);
ControllerRunner::open(mailbox.clone(), port.clone(), work, models)
.map(|runner| (port, runner))
.context("the controller organ cannot open")
});
let (port, runner) = match started {
Ok(started) => started,
Err(error) => {
return Err(match runs.abandon(claim, "start_refused") {
Ok(()) => error,
Err(_) => error.context("the refused run's record could not be ended"),
});
}
};
println!(
"run {sequence}: {ticks} ticks of {span} minutes, cap {cap} tokens, model {model}"
@ -220,12 +247,8 @@ async fn run(flags: Flags) -> Result<ExitCode> {
&runner,
&port,
&runs,
&VerseRunConfig {
ticks,
tick_span,
cover: COVER,
},
sequence,
claim,
&config,
|report| {
print!("{report}");
if interrupted.load(Ordering::SeqCst) {
@ -315,4 +338,3 @@ fn lane_fault(error: &ControllerOpenError) -> &'static str {
ControllerOpenError::EmptyModelPrefix { .. } => "an inference lane's model prefix is empty",
}
}

View file

@ -146,7 +146,7 @@ pub use table::{
pub use vault::{VaultError, VaultEvidenceSource};
pub use verse::{
CALL_RECORD_SCHEMA, CallRecordError, CallRecordStore, CreateVerseWorldIntent, ProviderCallRecord,
RUN_RECORD_SCHEMA, RecordedCoverBudget, RecordingInferencePort, Refusal, RefusalReason,
RUN_RECORD_SCHEMA, RecordedCoverBudget, RecordingInferencePort, Refusal, RefusalReason, RunClaim,
ReplayInferencePort, RunField, RunId, RunOutcome, RunStart, RunStatus, TickCheckpoint,
TickReport, VerseGenesisError, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
call_run_id, run_manual,

View file

@ -13,7 +13,7 @@ pub use calls::{
RecordingInferencePort, ReplayInferencePort, RunField, RunId, RunStart,
};
pub use run::{
RUN_RECORD_SCHEMA, RecordedCoverBudget, Refusal, RefusalReason, RunOutcome, RunStatus,
RUN_RECORD_SCHEMA, RecordedCoverBudget, Refusal, RefusalReason, RunClaim, RunOutcome, RunStatus,
TickCheckpoint, TickReport, VerseRunConfig, VerseRunError, VerseRunRecord, VerseRunStore,
call_run_id, run_manual,
};

View file

@ -59,6 +59,8 @@ pub enum VerseRunError {
OutOfSequence,
#[error("the recording port belongs to another run")]
PortNotThisRun,
#[error("the run's configuration is not the one its claim recorded")]
ConfigNotThisClaim,
#[error("the cover budget is not valid: {0}")]
Budget(#[from] CoverBudgetError),
#[error(transparent)]
@ -311,15 +313,43 @@ fn tick_row(tick: &VerseTick) -> Result<CultCacheEnvelope, VerseRunError> {
})
}
fn run_row(record: &VerseRunRecord) -> Result<CultCacheEnvelope, VerseRunError> {
Ok(CultCacheEnvelope {
key: row_key(record.world_id, record.sequence),
r#type: RUN_ROW.into(),
payload: rmp_serde::to_vec_named(record).map_err(|_| VerseRunError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(RUN_RECORD_SCHEMA.into()),
})
}
/// A run's number and cap, claimed from the run store before anything of the
/// run exists. The call ledger's run id derives from it ([`call_run_id`]), and
/// [`run_manual`] runs only the record it names. Not `Clone`: a claim runs once
/// or is abandoned.
#[derive(Debug)]
pub struct RunClaim {
world_id: WorldId,
sequence: u64,
token_cap: u64,
}
impl RunClaim {
/// The run's number, the one [`call_run_id`] names.
pub fn sequence(&self) -> u64 {
self.sequence
}
}
/// 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, and only by the tick
/// Run records and tick documents in one CultCache file. A run is claimed
/// when it begins and saved again each time it moves, so a row is replaced by
/// its own later state. A tick is opened once and closed once, and only by the tick
/// driver: the writers are private to this module.
///
/// ```compile_fail
@ -383,9 +413,9 @@ impl VerseRunStore {
Ok(Rows { runs, ticks })
}
/// The sequence the next run of this world must carry. Sequences count from
/// one.
pub fn next_sequence(&self, world: WorldId) -> Result<u64, VerseRunError> {
/// The sequence the next claim of this world takes. Sequences count from
/// one. Private: a caller never chooses a run's number, `claim` does.
fn next_sequence(&self, world: WorldId) -> Result<u64, VerseRunError> {
Ok(self
.records()?
.runs
@ -474,22 +504,78 @@ impl VerseRunStore {
.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)? {
/// Claims the next run of the snapshot's world: writes its `Running`
/// record, with the cap and config it was claimed under, in one insert that
/// cannot overwrite a record. The returned claim is the only way to run it;
/// a claim that never runs stays `Running` (a process that died) or is
/// ended by [`abandon`](Self::abandon), and its number is never issued
/// again.
pub fn claim(
&self,
snapshot: &WorldSnapshot,
token_cap: u64,
config: &VerseRunConfig,
) -> Result<RunClaim, VerseRunError> {
let cover_budget = config.cover.validated()?;
let record = VerseRunRecord {
world_id: snapshot.world_id,
sequence: self.next_sequence(snapshot.world_id)?,
token_cap,
ticks_requested: config.ticks,
tick_span_minutes: config.tick_span.minutes(),
cover_budget: RecordedCoverBudget {
cells: cover_budget.cells,
constituent_cap: cover_budget.constituent_cap,
urgency_slots: cover_budget.urgency_slots,
},
start_revision: snapshot.revision,
checkpoints: Vec::new(),
status: RunStatus::Running,
};
let inserted = self
.store
.lock()
.map_err(|_| VerseRunError::Store)?
.insert_entry_if_absent(run_row(&record)?)
.map_err(|_| VerseRunError::Store)?;
if !inserted {
return Err(VerseRunError::OutOfSequence);
}
let row = CultCacheEnvelope {
key: row_key(record.world_id, record.sequence),
r#type: RUN_ROW.into(),
payload: rmp_serde::to_vec_named(record).map_err(|_| VerseRunError::Store)?,
stored_at: Utc::now().to_rfc3339(),
schema_id: Some(RUN_RECORD_SCHEMA.into()),
};
Ok(RunClaim {
world_id: record.world_id,
sequence: record.sequence,
token_cap,
})
}
/// Ends a claim that never ran: its record becomes `Failed { reason }`.
pub fn abandon(&self, claim: RunClaim, reason: &'static str) -> Result<(), VerseRunError> {
let mut record = self.claimed(&claim)?;
record.status = failed(reason);
self.save(&record)
}
/// The record a claim names.
fn claimed(&self, claim: &RunClaim) -> Result<VerseRunRecord, VerseRunError> {
self.records()?
.runs
.into_iter()
.find(|record| record.world_id == claim.world_id && record.sequence == claim.sequence)
.ok_or(VerseRunError::OutOfSequence)
}
/// Replaces a claimed record with its later state. A sequence with no
/// record is refused: only `claim` creates one.
fn save(&self, record: &VerseRunRecord) -> Result<(), VerseRunError> {
self.claimed(&RunClaim {
world_id: record.world_id,
sequence: record.sequence,
token_cap: record.token_cap,
})?;
self.store
.lock()
.map_err(|_| VerseRunError::Store)?
.push(&row)
.push(&run_row(record)?)
.map_err(|_| VerseRunError::Store)
}
}
@ -627,39 +713,43 @@ fn failed(reason: &str) -> RunStatus {
/// Runs `config.ticks` ticks from the world's present clock under the cap the
/// recording port was opened with. `observe` sees each tick as it ends,
/// including the one a run ends inside, and may stop the run after a finished
/// tick by breaking. `sequence` is the run's number from
/// [`VerseRunStore::next_sequence`]; the port must have been opened for it
/// ([`call_run_id`]).
/// tick by breaking. `claim` is the run's number from
/// [`VerseRunStore::claim`]; the port must have been opened for it
/// ([`call_run_id`]) under the cap the claim recorded, and `config` is the one
/// the claim was made with. A claim this refuses is abandoned, so a refused
/// start binds nothing.
pub async fn run_manual(
mailbox: &WorldMailbox,
runner: &ControllerRunner,
port: &RecordingInferencePort,
store: &VerseRunStore,
claim: RunClaim,
config: &VerseRunConfig,
sequence: u64,
mut observe: impl FnMut(&TickReport) -> ControlFlow<()>,
) -> Result<RunOutcome, VerseRunError> {
if port.run_id() != &call_run_id(sequence) {
let begun = match mailbox.snapshot().await {
Ok(begun) => begun,
Err(error) => {
store.abandon(claim, "world_unavailable")?;
return Err(error.into());
}
};
if port.run_id() != &call_run_id(claim.sequence)
|| port.cap() != claim.token_cap
|| begun.world_id != claim.world_id
{
store.abandon(claim, "port_not_this_run")?;
return Err(VerseRunError::PortNotThisRun);
}
let cover_budget = config.cover.validated()?;
let begun = mailbox.snapshot().await?;
let mut record = VerseRunRecord {
world_id: begun.world_id,
sequence,
token_cap: port.cap(),
ticks_requested: config.ticks,
tick_span_minutes: config.tick_span.minutes(),
cover_budget: RecordedCoverBudget {
cells: cover_budget.cells,
constituent_cap: cover_budget.constituent_cap,
urgency_slots: cover_budget.urgency_slots,
},
start_revision: begun.revision,
checkpoints: Vec::new(),
status: RunStatus::Running,
let sequence = claim.sequence;
let mut record = store.claimed(&claim)?;
let cover_budget = match config.cover.validated() {
Ok(cover_budget) if record_matches(&record, config, cover_budget) => cover_budget,
_ => {
store.abandon(claim, "config_not_this_claim")?;
return Err(VerseRunError::ConfigNotThisClaim);
}
};
store.save(&record)?;
let mut spent_before = port.spent();
for completed in 0..config.ticks {
@ -704,6 +794,18 @@ pub async fn run_manual(
Ok(RunOutcome { record })
}
/// Whether the record a claim wrote was made under this config.
fn record_matches(record: &VerseRunRecord, config: &VerseRunConfig, cover: CoverBudget) -> bool {
record.ticks_requested == config.ticks
&& record.tick_span_minutes == config.tick_span.minutes()
&& record.cover_budget
== RecordedCoverBudget {
cells: cover.cells,
constituent_cap: cover.constituent_cap,
urgency_slots: cover.urgency_slots,
}
}
/// The key a run's provider calls are recorded under: the run's sequence, so a
/// run record and its call records name each other.
pub fn call_run_id(sequence: u64) -> super::RunId {

View file

@ -213,7 +213,7 @@ impl Harness {
(dir, harness)
}
/// One run over `inner`, recorded under the next sequence.
/// One run over `inner`, claimed and recorded under the next sequence.
async fn run(
&self,
inner: Arc<dyn InferencePort>,
@ -224,7 +224,8 @@ impl Harness {
self.run_under(inner, cap, config(ticks), observe).await
}
/// One run under the given config, recorded under the next sequence.
/// One run under the given config, claimed and recorded under the next
/// sequence.
async fn run_under(
&self,
inner: Arc<dyn InferencePort>,
@ -233,7 +234,8 @@ impl Harness {
observe: impl FnMut(&TickReport) -> ControlFlow<()>,
) -> RunOutcome {
let world = self.mailbox.snapshot().await.unwrap();
let sequence = self.runs.next_sequence(world.world_id).unwrap();
let claim = self.runs.claim(&world, cap, &config).unwrap();
let sequence = claim.sequence();
let port = Arc::new(
RecordingInferencePort::open(
inner,
@ -252,8 +254,8 @@ impl Harness {
&runner,
&port,
&self.runs,
claim,
&config,
sequence,
observe,
)
.await
@ -977,17 +979,21 @@ fn an_error_ends_a_cell_as_the_run_must_treat_it() {
));
}
#[tokio::test]
async fn a_port_opened_for_another_run_is_refused_before_anything_is_written() {
let (_dir, verse) = Harness::fresh().await;
let world = verse.mailbox.snapshot().await.unwrap();
/// A recording port over the harness's call store for `sequence` under `cap`,
/// and a runner on it.
fn port_and_runner(
verse: &Harness,
world: &WorldSnapshot,
sequence: u64,
cap: u64,
) -> (Arc<RecordingInferencePort>, ControllerRunner) {
let port = Arc::new(
RecordingInferencePort::open(
ScriptedPort::speaking(),
verse.calls.clone(),
call_run_id(7),
1_000,
&RunStart::of(&world),
call_run_id(sequence),
cap,
&RunStart::of(world),
)
.unwrap(),
);
@ -998,43 +1004,215 @@ async fn a_port_opened_for_another_run_is_refused_before_anything_is_written() {
models(),
)
.unwrap();
let error = run_manual(
(port, runner)
}
/// Runs `claim` on the given port and runner, which must refuse it.
async fn refused(
verse: &Harness,
port: &RecordingInferencePort,
runner: &ControllerRunner,
claim: RunClaim,
config: &VerseRunConfig,
) -> VerseRunError {
run_manual(
&verse.mailbox,
&runner,
&port,
runner,
port,
&verse.runs,
&config(1),
1,
claim,
config,
|_| ControlFlow::Continue(()),
)
.await
.unwrap_err();
assert!(matches!(error, VerseRunError::PortNotThisRun));
assert!(verse.runs.runs(world.world_id).unwrap().is_empty());
.unwrap_err()
}
// A cover budget with no cells is refused before the record exists.
#[tokio::test]
async fn a_run_started_on_the_wrong_port_world_or_config_is_refused_and_its_claim_ends_failed() {
let (_dir, verse) = Harness::fresh().await;
let world = verse.mailbox.snapshot().await.unwrap();
let (_other_dir, elsewhere) = Harness::fresh().await;
let strange = elsewhere.mailbox.snapshot().await.unwrap();
// A cover budget with no cells cannot be claimed: no record exists.
let mut bad = config(1);
bad.cover.cells = 0;
let own = Arc::new(
RecordingInferencePort::open(
ScriptedPort::speaking(),
verse.calls.clone(),
call_run_id(1),
1_000,
&RunStart::of(&world),
)
.unwrap(),
);
let error = run_manual(&verse.mailbox, &runner, &own, &verse.runs, &bad, 1, |_| {
ControlFlow::Continue(())
})
.await
.unwrap_err();
assert!(matches!(
error,
VerseRunError::Budget(CoverBudgetError::NoCells)
verse.runs.claim(&world, 1_000, &bad),
Err(VerseRunError::Budget(CoverBudgetError::NoCells))
));
assert!(verse.runs.runs(world.world_id).unwrap().is_empty());
// Run 1: a port opened for another run's number.
let claim = verse.runs.claim(&world, 1_000, &config(1)).unwrap();
let (port, runner) = port_and_runner(&verse, &world, 7, 1_000);
let error = refused(&verse, &port, &runner, claim, &config(1)).await;
assert!(matches!(error, VerseRunError::PortNotThisRun));
// Run 2: a port under another cap than the claim recorded.
let claim = verse.runs.claim(&world, 1_000, &config(1)).unwrap();
let (port, runner) = port_and_runner(&verse, &world, claim.sequence(), 5_000);
let error = refused(&verse, &port, &runner, claim, &config(1)).await;
assert!(matches!(error, VerseRunError::PortNotThisRun));
// Run 3: a config other than the one the claim was made with.
let claim = verse.runs.claim(&world, 1_000, &config(1)).unwrap();
let (port, runner) = port_and_runner(&verse, &world, claim.sequence(), 1_000);
let error = refused(&verse, &port, &runner, claim, &config(2)).await;
assert!(matches!(error, VerseRunError::ConfigNotThisClaim));
// Another world's claim 1, on this world's mailbox and a port that fits it.
let claim = verse.runs.claim(&strange, 1_000, &config(1)).unwrap();
let (port, runner) = port_and_runner(&verse, &world, claim.sequence(), 1_000);
let error = refused(&verse, &port, &runner, claim, &config(1)).await;
assert!(matches!(error, VerseRunError::PortNotThisRun));
let statuses = |world: &WorldSnapshot| -> Vec<(u64, RunStatus)> {
verse
.runs
.runs(world.world_id)
.unwrap()
.into_iter()
.map(|record| (record.sequence, record.status))
.collect()
};
assert_eq!(
statuses(&world),
vec![
(1, failed("port_not_this_run")),
(2, failed("port_not_this_run")),
(3, failed("config_not_this_claim")),
]
);
assert_eq!(statuses(&strange), vec![(1, failed("port_not_this_run"))]);
assert!(verse.runs.tick(world.world_id, 0).unwrap().is_none());
assert!(verse.runs.tick(strange.world_id, 0).unwrap().is_none());
assert_eq!(verse.mailbox.operator_log().await.unwrap().len(), 0);
}
fn record(world: WorldId, sequence: u64) -> VerseRunRecord {
VerseRunRecord {
world_id: world,
sequence,
token_cap: 10,
ticks_requested: 1,
tick_span_minutes: SPAN,
cover_budget: RecordedCoverBudget {
cells: 2,
constituent_cap: 8,
urgency_slots: 0,
},
start_revision: 0,
checkpoints: Vec::new(),
status: RunStatus::Running,
}
}
#[tokio::test]
async fn the_run_store_claims_runs_per_world_and_replaces_a_claimed_run_with_its_later_state() {
let (_one_dir, one) = Harness::fresh().await;
let (_other_dir, other) = Harness::fresh().await;
let one = one.mailbox.snapshot().await.unwrap();
let other = other.mailbox.snapshot().await.unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("runs.cc");
let store = VerseRunStore::open(&path).unwrap();
// Claims number runs from one, per world, and write the Running record.
let first = store.claim(&one, 10, &config(3)).unwrap();
let second = store.claim(&one, 20, &config(1)).unwrap();
let elsewhere = store.claim(&other, 10, &config(1)).unwrap();
assert_eq!(
(first.sequence(), second.sequence(), elsewhere.sequence()),
(1, 2, 1)
);
let claimed = store.runs(one.world_id).unwrap();
assert_eq!(claimed.len(), 2);
assert_eq!(claimed[0].token_cap, 10);
assert_eq!(claimed[0].ticks_requested, 3);
assert_eq!(claimed[1].token_cap, 20);
assert_eq!(claimed[0].start_revision, one.revision);
assert_eq!(claimed[0].status, RunStatus::Running);
// A record is only ever a claimed one: a sequence with no record is refused.
assert!(matches!(
store.save(&record(one.world_id, 3)),
Err(VerseRunError::OutOfSequence)
));
assert!(matches!(
store.save(&record(one.world_id, 0)),
Err(VerseRunError::OutOfSequence)
));
assert_eq!(store.runs(one.world_id).unwrap().len(), 2);
// Saving a claimed run again replaces it, and the file reopens to the
// same rows.
let mut finished = claimed[0].clone();
finished.status = RunStatus::Completed;
store.save(&finished).unwrap();
drop(store);
let store = VerseRunStore::open(&path).unwrap();
assert_eq!(
store.runs(one.world_id).unwrap(),
vec![finished, claimed[1].clone()]
);
assert_eq!(store.runs(other.world_id).unwrap().len(), 1);
}
#[tokio::test]
async fn a_claim_is_never_reissued_even_when_its_run_never_started() {
let (_dir, verse) = Harness::fresh().await;
let world = verse.mailbox.snapshot().await.unwrap();
// Run 1 is claimed, then nothing happens: the process died.
let lost = verse.runs.claim(&world, 1_000_000_000, &config(1)).unwrap();
assert_eq!(lost.sequence(), 1);
let before = verse.runs.runs(world.world_id).unwrap();
drop(lost);
// The next run is run 2 and leaves run 1's record exactly as it was.
let outcome = verse
.run_quietly(ScriptedPort::speaking(), 1_000_000_000, 1)
.await;
assert_eq!(outcome.record.sequence, 2);
assert_eq!(outcome.record.status, RunStatus::Completed);
let after = verse.runs.runs(world.world_id).unwrap();
assert_eq!(after.len(), 2);
assert_eq!(after[0], before[0], "run 1's record was overwritten");
assert_eq!(after[0].status, RunStatus::Running);
assert_eq!(after[1], outcome.record);
}
#[tokio::test]
async fn a_start_refused_after_the_claim_leaves_the_next_run_free_to_choose_its_cap() {
let (_dir, verse) = Harness::fresh().await;
let world = verse.mailbox.snapshot().await.unwrap();
// Run 1 is claimed and its call ledger opens under a cap, then the start
// is refused before the run begins.
let claim = verse.runs.claim(&world, 1_000, &config(1)).unwrap();
let ledger = RecordingInferencePort::open(
ScriptedPort::speaking(),
verse.calls.clone(),
call_run_id(claim.sequence()),
1_000,
&RunStart::of(&world),
)
.unwrap();
drop(ledger);
verse.runs.abandon(claim, "start_refused").unwrap();
// The operator tries again under another cap: it is a new run, and runs.
let outcome = verse
.run_quietly(ScriptedPort::speaking(), 50_000, 1)
.await;
assert_eq!(outcome.record.sequence, 2);
assert_eq!(outcome.record.token_cap, 50_000);
assert_eq!(outcome.record.status, RunStatus::Completed);
let runs = verse.runs.runs(world.world_id).unwrap();
assert_eq!(runs[0].status, failed("start_refused"));
assert_eq!(runs[0].token_cap, 1_000);
}
#[tokio::test]
@ -1061,62 +1239,6 @@ async fn an_unreadable_operator_log_is_no_tick_report() {
);
}
fn record(world: WorldId, sequence: u64) -> VerseRunRecord {
VerseRunRecord {
world_id: world,
sequence,
token_cap: 10,
ticks_requested: 1,
tick_span_minutes: SPAN,
cover_budget: RecordedCoverBudget {
cells: 2,
constituent_cap: 8,
urgency_slots: 0,
},
start_revision: 0,
checkpoints: Vec::new(),
status: RunStatus::Running,
}
}
#[test]
fn the_run_store_numbers_runs_per_world_and_replaces_a_run_with_its_later_state() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("runs.cc");
let store = VerseRunStore::open(&path).unwrap();
let one = WorldId::nil_for_test();
let other = WorldId::issue();
assert_eq!(store.next_sequence(one).unwrap(), 1);
// A run can only begin as the next in its world.
assert!(matches!(
store.save(&record(one, 2)),
Err(VerseRunError::OutOfSequence)
));
assert!(matches!(
store.save(&record(one, 0)),
Err(VerseRunError::OutOfSequence)
));
store.save(&record(one, 1)).unwrap();
assert_eq!(store.next_sequence(one).unwrap(), 2);
assert_eq!(
store.next_sequence(other).unwrap(),
1,
"sequences are per world"
);
// Saving a run again replaces it, and the file reopens to the same rows.
let mut finished = record(one, 1);
finished.status = RunStatus::Completed;
store.save(&finished).unwrap();
store.save(&record(one, 2)).unwrap();
store.save(&record(other, 1)).unwrap();
drop(store);
let store = VerseRunStore::open(&path).unwrap();
assert_eq!(store.runs(one).unwrap(), vec![finished, record(one, 2)]);
assert_eq!(store.runs(other).unwrap(), vec![record(other, 1)]);
}
#[test]
fn the_run_store_refuses_rows_that_are_not_canonical_run_records() {
let dir = tempfile::tempdir().unwrap();
@ -1472,7 +1594,12 @@ fn the_tick_store_opens_once_closes_once_and_refuses_non_canonical_rows() {
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();
store
.store
.lock()
.unwrap()
.push(&run_row(&record(world, 1)).unwrap())
.unwrap();
drop(store);
let store = VerseRunStore::open(&path).unwrap();
assert_eq!(store.runs(world).unwrap(), vec![record(world, 1)]);