Dungeon: seed status is persisted with the timeline, play refuses a world that is not Active, the seed asks for places

The in-memory Seeding map is cut: the catalog row owns SeedStatus. A seed
still Seeding at startup reads Failed; a panicking seed task ends Failed.
POST /api/play on a Seeding, Failed or Draft world is a 409 naming the
status. The seed brief asks for three to five declared places.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 22:10:31 +01:00
commit c23e5fd046
4 changed files with 360 additions and 95 deletions

View file

@ -7,7 +7,8 @@
use crate::{
auth_guard::{BEGIN_COOKIE, BEGIN_TTL_SECONDS},
heimdall::AuthBeginReceipt,
begin::{BeginRequest, SeedStatus, begin},
begin::{BeginRequest, begin},
catalog::SeedStatus,
run_ahead::{evidence_of, run_ahead},
play::{Admission, OpenQuestion, PlayError, PlayRequest, PlayTurnState, PlayTurnView},
runtime::AppState,
@ -23,7 +24,7 @@ use axum::{
routing::{get, post},
};
use chrono::{DateTime, Utc};
use ghostlight::{CommandId, VerifiedPrincipalEvidence};
use ghostlight::{CommandId, VerifiedPrincipalEvidence, WorldPhase};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{convert::Infallible, time::Duration};
@ -67,6 +68,17 @@ fn unauthorized() -> Response {
refuse(StatusCode::UNAUTHORIZED, "sign in first")
}
/// The refusal of a play on a world that is not Active: 409 with the status
/// the page shows (`seeding`, `failed` with its reason, or `draft`).
fn unplayable(status: &str, reason: Option<&str>) -> Response {
let error = match status {
"seeding" => "this world is still being seeded",
"failed" => "this world's seed did not finish",
_ => "this world is not active yet",
};
reply(StatusCode::CONFLICT, json!({"error": error, "status": status, "reason": reason}))
}
/// The turn as the player sees it: narration, the open question, the refusal
/// of their own act and the fault line. It is derived from the turn record
/// and is display-only; nothing reads it back.
@ -179,10 +191,10 @@ async fn timelines(headers: HeaderMap, State(state): State<AppState>) -> Respons
.timelines_of(account)
.into_iter()
.map(|(timeline, world)| {
let (status, reason) = match state.seeding.status(&timeline.id) {
let (status, reason) = match catalog.seed_status(&timeline.id) {
None => ("ready", None),
Some(SeedStatus::Seeding) => ("seeding", None),
Some(SeedStatus::Failed(reason)) => ("failed", Some(reason)),
Some(SeedStatus::Failed(reason)) => ("failed", Some(reason.as_str())),
};
json!({
"timeline": timeline.id,
@ -231,7 +243,7 @@ async fn begin_world(
&state.catalog,
&state.timelines,
state.vaults.as_ref(),
&state.seeding,
&state.scale,
&principal,
BeginRequest {
key: body.key,
@ -286,6 +298,11 @@ async fn play(
if catalog.owned_timeline(&account, &body.timeline).is_none() {
return refuse(StatusCode::NOT_FOUND, "no such timeline");
}
match catalog.seed_status(&body.timeline) {
Some(SeedStatus::Seeding) => return unplayable("seeding", None),
Some(SeedStatus::Failed(reason)) => return unplayable("failed", Some(reason.as_str())),
None => {}
}
let current = catalog.player(&account).and_then(|player| player.timeline.as_deref());
if current != Some(body.timeline.as_str())
&& let Err(error) = catalog.set_current(&account, &body.timeline)
@ -301,6 +318,16 @@ async fn play(
return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open");
}
};
// The seed's status explains a refusal; the world's phase is what decides
// it, so a Draft with no recorded seed is not playable either.
match host.world.snapshot().await {
Ok(world) if world.phase == WorldPhase::Active => {}
Ok(_) => return unplayable("draft", None),
Err(error) => {
tracing::error!(%error, timeline = %body.timeline, "the world could not be read");
return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the timeline could not open");
}
}
// The server resolves the open question itself; the client proves it saw
// it by its token. A token with no open question, or not that question's,
// is stale and never reaches the table.
@ -371,7 +398,7 @@ async fn play(
if closed
&& let Some(evidence) = evidence_of(&state.catalog, state.vaults.as_ref(), &timeline).await
{
run_ahead(&spawned, evidence, &state.seeding.scale).await;
run_ahead(&spawned, evidence, &state.scale).await;
}
});
reply(StatusCode::ACCEPTED, json!({"outcome": "accepted"}))
@ -857,7 +884,7 @@ mod tests {
catalog: rig.catalog.clone(),
timelines: rig.timelines.clone(),
vaults: one_vault(),
seeding: rig.seeding.clone(),
scale: rig.scale.clone(),
sessions: Arc::new(Mutex::new(sessions)),
heimdall: heimdall.clone(),
auth: Arc::default(),
@ -1034,6 +1061,82 @@ mod tests {
assert!(reason.contains("seed") && !reason.contains("10.0.0.7"), "{reason}");
}
/// A world that is seeding, failed or a Draft is not played: the refusal
/// is a 409 that names the status, and no model is asked.
#[tokio::test]
async fn play_on_a_world_that_is_not_ready_is_refused_with_its_status() {
let app = app_over(deferred_rig(), &["alice"]).await;
let cookie = app.cookies[0].clone();
let timeline = begin_vault_over_http(&app, &cookie).await;
let asked = app.rig.port.seen_requests().len();
let (status, body) = play_text(&app, &cookie, &timeline, "I look around.", None).await;
assert_eq!((status, body["status"].as_str()), (StatusCode::CONFLICT, Some("seeding")), "{body}");
app.rig.port.push(Err("http://10.0.0.7:9/secret endpoint down"));
eventually(async || timeline_status(&app, &cookie, &timeline).await.filter(|(state, _)| state == "failed")).await;
let (status, body) = play_text(&app, &cookie, &timeline, "I look around.", None).await;
assert_eq!((status, body["status"].as_str()), (StatusCode::CONFLICT, Some("failed")), "{body}");
assert!(body["reason"].as_str().unwrap().contains("seed"), "{body}");
// A Draft the catalog calls Ready is still not played.
app.rig.catalog.lock().await.settle_seed(&timeline, None).unwrap();
let (status, body) = play_text(&app, &cookie, &timeline, "I look around.", None).await;
assert_eq!((status, body["status"].as_str()), (StatusCode::CONFLICT, Some("draft")), "{body}");
assert_eq!(app.rig.port.seen_requests().len(), asked + 1, "only the seed's own request reached the model");
let (_, _, view) = call(&app, Method::GET, &format!("/api/turn/{timeline}"), Some(&cookie), None).await;
assert!(view["turn"].is_null(), "no turn was admitted: {view}");
}
/// A turn that closes runs the world ahead; a turn that stops to ask the
/// player does not.
#[tokio::test]
async fn only_a_closed_turn_runs_the_world_ahead() {
let app = app_over(deferred_rig(), &["alice"]).await;
let cookie = app.cookies[0].clone();
let timeline = begin_vault_over_http(&app, &cookie).await;
let host = app.state.timelines.host(&timeline).await.unwrap();
let draft = host.world.snapshot().await.unwrap();
app.rig.port.push(Ok(author("seed-1", &draft, &["a", "b"])));
app.rig.port.push(Ok(author("seed-2", &draft, &["c", "d"])));
eventually(async || (timeline_status(&app, &cookie, &timeline).await.unwrap().0 == "ready").then_some(())).await;
// The sweep that follows activation meets a model that is down.
let mut answered = 0;
eventually(async || {
let seen = app.rig.port.seen_requests().len();
if seen > 2 && seen > answered {
answered = seen;
app.rig.port.push(Err("down"));
}
(seen > 2 && host.sweeping.try_lock().is_ok()).then_some(())
})
.await;
let elaborations = |app: &App| {
app.rig
.port
.seen_requests()
.iter()
.filter(|request| serde_json::to_string(request).unwrap().contains(crate::begin::tests::NOTE))
.count()
};
let before = elaborations(&app);
app.rig.port.push(Ok(output("r0", vec![call_event("c0", ASK_PLAYER_TOOL, json!({"question": "Which way?"}))])));
let (status, body) = play_text(&app, &cookie, &timeline, "A crossroads.", None).await;
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
let view = settled_turn(&app, &cookie, &timeline).await;
assert_eq!(view["turn"]["state"], "awaiting_player");
tokio::time::sleep(Duration::from_millis(300)).await;
assert_eq!(elaborations(&app), before, "an open question runs nothing ahead");
let token = view["turn"]["question"]["token"].as_str().unwrap().to_owned();
app.rig.port.push(Ok(output("r1", vec![call_event("c1", END_TURN_TOOL, json!({}))])));
app.rig.port.push(Ok(output("proj-0", vec![text_event("You choose.")])));
let (status, body) = play_text(&app, &cookie, &timeline, "left", Some(&token)).await;
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
eventually(async || (elaborations(&app) > before).then_some(())).await;
}
#[tokio::test]
async fn logout_revokes_the_cookie_even_when_heimdall_is_unreachable() {
let app = app(vec![], &["alice"]).await;

View file

@ -13,7 +13,7 @@
//! committed.
use crate::{
catalog::{Catalog, Timeline, WorldRecord, timeline_id},
catalog::{Catalog, SeedStatus, Timeline, WorldRecord, timeline_id},
run_ahead::run_ahead,
timelines::{TimelineHost, Timelines},
};
@ -85,55 +85,6 @@ impl Scale {
}
}
/// Where a timeline stands, as the page shows it. Display-only: nothing reads
/// it back to decide anything, and a timeline with no entry reads as Ready.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SeedStatus {
Seeding,
Failed(String),
}
/// The scale a Begin states and the status of the seeds in flight.
pub(crate) struct Seeding {
pub(crate) scale: Scale,
status: std::sync::Mutex<BTreeMap<String, SeedStatus>>,
}
impl Seeding {
pub(crate) fn new(scale: Scale) -> Self {
Self {
scale,
status: std::sync::Mutex::new(BTreeMap::new()),
}
}
pub(crate) fn status(&self, timeline: &str) -> Option<SeedStatus> {
self.status.lock().unwrap().get(timeline).cloned()
}
/// Claims the seed of `timeline`; false when one is already running.
fn claim(&self, timeline: &str) -> bool {
let mut status = self.status.lock().unwrap();
if status.get(timeline) == Some(&SeedStatus::Seeding) {
return false;
}
status.insert(timeline.to_owned(), SeedStatus::Seeding);
true
}
fn settle(&self, timeline: &str, outcome: Result<(), &BeginError>) {
let mut status = self.status.lock().unwrap();
match outcome {
Ok(()) => {
status.remove(timeline);
}
Err(error) => {
status.insert(timeline.to_owned(), SeedStatus::Failed(error.to_string()));
}
}
}
}
/// A vault snapshot ready to seed from: its content id, the evidence source
/// that reads only that snapshot, and the deterministic premise a seed falls
/// back on when the player gave no brief.
@ -232,10 +183,10 @@ async fn current(host: &TimelineHost) -> Result<Option<WorldSnapshot>, MailboxEr
}
pub(crate) async fn begin(
catalog: &Mutex<Catalog>,
catalog: &Arc<Mutex<Catalog>>,
timelines: &Timelines,
vaults: &dyn Vaults,
seeding: &Arc<Seeding>,
scale: &Arc<Scale>,
principal: &VerifiedPrincipalEvidence,
request: BeginRequest,
) -> Result<Begun, BeginError> {
@ -267,7 +218,7 @@ pub(crate) async fn begin(
let brief = request.brief.unwrap_or_default();
let (targets, jurisdictions) = match &vault {
Some(_) => (
seeding.scale.targets.clone(),
scale.targets.clone(),
vec![CreateJurisdictionIntent {
handle: START_HANDLE.into(),
label: request.title.clone(),
@ -336,8 +287,13 @@ pub(crate) async fn begin(
"activated"
}
(true, Some(vault)) => {
if seeding.claim(&timeline) {
let seed_brief = (!brief.is_empty())
let claimed = catalog
.lock()
.await
.claim_seed(&timeline)
.map_err(|error| stopped("record", error))?;
if claimed {
let story = (!brief.is_empty())
.then_some(brief)
.or_else(|| vault.premise.clone());
let seed = Seed {
@ -347,10 +303,11 @@ pub(crate) async fn begin(
key,
world_id,
evidence: vault.evidence,
brief: seed_brief,
seeding: seeding.clone(),
brief: seed_brief(story),
catalog: catalog.clone(),
scale: scale.clone(),
};
tokio::spawn(seed.run());
supervise(seed);
}
"seeding"
}
@ -389,9 +346,24 @@ async fn finish(
Ok(())
}
/// What a seed asks beyond people: the places they stand in. The kernel has no
/// place-scale target, so the ask rides in the seed's brief; a place is a
/// `declare_place` inside the `start` root, and the seed prompt already tells
/// the model where its people must stand.
const SEED_PLACES: &str = "Give the world somewhere to be, not only someone to meet: with declare_place, declare three to five places inside the start place (set each place's container to it): a market, a hall, a gate, a shrine, whatever this world's lore names. Stand each person at one of those places, spread across them, and let the people at a place be the ones who belong there. Do not put every person at the start place itself.";
/// The brief the seed sessions read: the player's story, or the vault's
/// premise, and always the ask for places.
fn seed_brief(story: Option<String>) -> Option<String> {
Some(match story {
Some(story) => format!("{story}\n\n{SEED_PLACES}"),
None => SEED_PLACES.to_owned(),
})
}
/// A vault Begin's background half: the seed sessions, then approval and
/// activation, then the first run-ahead sweep. Its outcome is the timeline's
/// status.
/// persisted status.
struct Seed {
timeline: String,
host: Arc<TimelineHost>,
@ -400,18 +372,41 @@ struct Seed {
world_id: ghostlight::WorldId,
evidence: Arc<dyn EvidenceSource>,
brief: Option<String>,
seeding: Arc<Seeding>,
catalog: Arc<Mutex<Catalog>>,
scale: Arc<Scale>,
}
/// Runs a seed on its own task and watches it: a seed that panics ends
/// Failed, never Seeding forever.
fn supervise(seed: Seed) {
let catalog = seed.catalog.clone();
let timeline = seed.timeline.clone();
tokio::spawn(async move {
if let Err(error) = tokio::spawn(seed.run()).await {
tracing::error!(%error, %timeline, "a seeded begin's task ended abnormally");
let mut catalog = catalog.lock().await;
if catalog.seed_status(&timeline) == Some(&SeedStatus::Seeding)
&& let Err(error) =
catalog.settle_seed(&timeline, Some(SeedStatus::Failed("seeding stopped unexpectedly".into())))
{
tracing::error!(%error, %timeline, "the failed seed could not be recorded");
}
}
});
}
impl Seed {
async fn run(self) {
let outcome = self.seed_and_activate().await;
self.seeding.settle(&self.timeline, outcome.as_ref().map(|_| ()));
let status = outcome.as_ref().err().map(|error| SeedStatus::Failed(error.to_string()));
if let Err(error) = self.catalog.lock().await.settle_seed(&self.timeline, status) {
tracing::error!(%error, timeline = %self.timeline, "a seed's outcome could not be recorded");
}
if let Err(error) = &outcome {
tracing::warn!(%error, timeline = %self.timeline, "a seeded begin stopped");
return;
}
run_ahead(&self.host, self.evidence.clone(), &self.seeding.scale).await;
run_ahead(&self.host, self.evidence.clone(), &self.scale).await;
}
async fn seed_and_activate(&self) -> Result<(), BeginError> {
@ -421,7 +416,7 @@ impl Seed {
self.brief.clone(),
);
runner
.sweep(self.seeding.scale.seed_sessions)
.sweep(self.scale.seed_sessions)
.await
.map_err(|error| {
tracing::warn!(%error, "seeding a world could not complete");
@ -471,10 +466,17 @@ pub(crate) mod tests {
pub(crate) catalog: Arc<Mutex<Catalog>>,
pub(crate) timelines: Arc<Timelines>,
pub(crate) port: Arc<ScriptedPort>,
pub(crate) seeding: Arc<Seeding>,
pub(crate) scale: Arc<Scale>,
_fatal: mpsc::UnboundedReceiver<String>,
}
impl Rig {
/// The timeline's persisted seed status, `None` when Ready.
pub(crate) async fn status(&self, timeline: &str) -> Option<SeedStatus> {
self.catalog.lock().await.seed_status(timeline).cloned()
}
}
/// One catalog and one timeline registry over a scripted inference port.
pub(crate) fn rig(script: Vec<ghostlight::InferenceOutput>) -> Rig {
rig_over(ScriptedPort::new(script))
@ -510,7 +512,7 @@ pub(crate) mod tests {
catalog: Arc::new(Mutex::new(Catalog::open(root.join("catalog.cc")).unwrap())),
timelines: Arc::new(timelines),
port,
seeding: Arc::new(Seeding::new(Scale::from_reader(|_| None))),
scale: Arc::new(Scale::from_reader(|_| None)),
directory,
_fatal: receiver,
}
@ -664,7 +666,7 @@ pub(crate) mod tests {
async fn begin_vault(rig: &Rig, key: Uuid) -> Begun {
let request = BeginRequest { brief: None, ..request(key, Some("delvehold")) };
begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.seeding, &principal("alice"), request)
begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.scale, &principal("alice"), request)
.await
.unwrap()
}
@ -677,7 +679,7 @@ pub(crate) mod tests {
let rig = deferred_rig();
let begun = begin_vault(&rig, Uuid::new_v4()).await;
assert_eq!(begun.reached, "seeding");
assert_eq!(rig.seeding.status(&begun.timeline), Some(SeedStatus::Seeding));
assert_eq!(rig.status(&begun.timeline).await, Some(SeedStatus::Seeding));
let host = rig.timelines.host(&begun.timeline).await.unwrap();
let world = host.world.snapshot().await.unwrap();
assert_eq!(world.phase, WorldPhase::Draft);
@ -711,7 +713,7 @@ pub(crate) mod tests {
let world = eventually(async || {
let world = host.world.snapshot().await.unwrap();
(world.phase == WorldPhase::Active && rig.seeding.status(&begun.timeline).is_none()).then_some(world)
(world.phase == WorldPhase::Active && rig.status(&begun.timeline).await.is_none()).then_some(world)
})
.await;
let person = world.scale_deficit.iter().find(|row| row.kind == SubjectKind::Person).unwrap();
@ -722,7 +724,7 @@ pub(crate) mod tests {
"two seed sessions asked the model"
);
assert!(
prompt_text(&seed[0]).contains("A cold harbor, from the vault."),
prompt_text(&seed[0]).contains("A cold harbor, from the vault.") && prompt_text(&seed[0]).contains("declare_place"),
"the vault's premise stood in for the missing brief"
);
@ -746,7 +748,7 @@ pub(crate) mod tests {
let key = Uuid::new_v4();
let begun = begin_vault(&rig, key).await;
rig.port.push(Err("http://10.0.0.7:9/secret endpoint down"));
let status = eventually(async || match rig.seeding.status(&begun.timeline) {
let status = eventually(async || match rig.status(&begun.timeline).await {
Some(SeedStatus::Failed(reason)) => Some(reason),
_ => None,
})
@ -757,7 +759,82 @@ pub(crate) mod tests {
let again = begin_vault(&rig, key).await;
assert_eq!((again.timeline.as_str(), again.reached), (begun.timeline.as_str(), "seeding"));
assert_eq!(rig.seeding.status(&begun.timeline), Some(SeedStatus::Seeding));
assert_eq!(rig.status(&begun.timeline).await, Some(SeedStatus::Seeding));
}
/// The seed asks for places as well as people, in the brief every seed
/// session reads, whether the story is the player's or the vault's.
#[test]
fn the_seed_brief_always_asks_for_places() {
for story in [Some("A cold harbor town.".to_owned()), None] {
let brief = seed_brief(story.clone()).unwrap();
assert!(brief.contains("declare_place") && brief.contains("three to five"), "{brief}");
if let Some(story) = story {
assert!(brief.starts_with(&story), "the story comes first");
}
}
}
/// A seed that commits no one leaves the world a Draft and reads Failed:
/// the world is never activated empty.
#[tokio::test]
async fn a_seed_that_authored_no_one_fails_and_the_world_stays_a_draft() {
let rig = deferred_rig();
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, &[])));
rig.port.push(Ok(author("seed-2", &draft, &[])));
let reason = eventually(async || match rig.status(&begun.timeline).await {
Some(SeedStatus::Failed(reason)) => Some(reason),
_ => None,
})
.await;
assert!(reason.contains("authored no one"), "{reason}");
assert_eq!(host.world.snapshot().await.unwrap().phase, WorldPhase::Draft);
}
struct PanickingEvidence;
#[async_trait::async_trait]
impl EvidenceSource for PanickingEvidence {
async fn retrieve(
&self,
_: &ghostlight::EvidenceQuery,
) -> Result<Vec<ghostlight::EvidenceReceipt>, ghostlight::EvidenceError> {
panic!("the evidence source panicked");
}
}
/// A seed task that panics ends Failed, never Seeding forever, and the
/// same key may seed again.
#[tokio::test]
async fn a_seed_that_panics_reads_failed_not_seeding() {
let rig = deferred_rig();
let begun = begin_vault(&rig, Uuid::new_v4()).await;
let (timeline, host) = (begun.timeline.clone(), rig.timelines.host(&begun.timeline).await.unwrap());
// The begun seed is waiting on the model; end it, then run a seed
// that panics under the same supervision.
rig.port.push(Err("down"));
eventually(async || matches!(rig.status(&timeline).await, Some(SeedStatus::Failed(_))).then_some(())).await;
assert!(rig.catalog.lock().await.claim_seed(&timeline).unwrap());
supervise(Seed {
timeline: timeline.clone(),
principal: principal("alice"),
key: Uuid::new_v4(),
world_id: host.world.snapshot().await.unwrap().world_id,
evidence: Arc::new(PanickingEvidence),
brief: None,
catalog: rig.catalog.clone(),
scale: rig.scale.clone(),
host,
});
let reason = eventually(async || match rig.status(&timeline).await {
Some(SeedStatus::Failed(reason)) => Some(reason),
_ => None,
})
.await;
assert!(reason.contains("unexpectedly"), "{reason}");
}
/// The owner's brief is the seed's brief; the vault's premise is only what
@ -765,7 +842,7 @@ pub(crate) mod tests {
#[tokio::test]
async fn the_owners_brief_outranks_the_vaults_premise() {
let rig = deferred_rig();
let begun = begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.seeding, &principal("alice"), request(Uuid::new_v4(), Some("delvehold")))
let begun = begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.scale, &principal("alice"), request(Uuid::new_v4(), Some("delvehold")))
.await
.unwrap();
assert_eq!(begun.reached, "seeding");
@ -778,7 +855,7 @@ pub(crate) mod tests {
#[tokio::test]
async fn begin_without_a_profile_activates_unseeded_and_asks_no_model() {
let rig = rig(vec![]);
let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &principal("alice"), request(Uuid::new_v4(), None))
let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &principal("alice"), request(Uuid::new_v4(), None))
.await
.unwrap();
assert_eq!(begun.reached, "activated");
@ -787,7 +864,7 @@ pub(crate) mod tests {
let world = host.world.snapshot().await.unwrap();
assert_eq!(world.phase, WorldPhase::Active);
assert!(world.scale_deficit.is_empty(), "an unseeded Begin states no targets");
assert_eq!(rig.seeding.status(&begun.timeline), None);
assert_eq!(rig.status(&begun.timeline).await, None);
let catalog = rig.catalog.lock().await;
assert_eq!(catalog.owned_timeline("alice", &begun.timeline).unwrap().1.snapshot_id, None);
}
@ -795,7 +872,7 @@ pub(crate) mod tests {
#[tokio::test]
async fn an_unknown_profile_refuses_the_begin_before_anything_is_made() {
let rig = rig(vec![]);
let error = begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.seeding, &principal("alice"), request(Uuid::new_v4(), Some("nowhere")))
let error = begin(&rig.catalog, &rig.timelines, &OneVault::new(), &rig.scale, &principal("alice"), request(Uuid::new_v4(), Some("nowhere")))
.await
.err()
.unwrap();
@ -809,8 +886,8 @@ pub(crate) mod tests {
let rig = rig(vec![]);
let alice = principal("alice");
let key = Uuid::new_v4();
let first = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &alice, request(key, None)).await.unwrap();
let again = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &alice, request(key, None)).await.unwrap();
let first = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &alice, request(key, None)).await.unwrap();
let again = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &alice, request(key, None)).await.unwrap();
assert_eq!(first.timeline, again.timeline);
assert_eq!(rig.catalog.lock().await.timelines_of("alice").len(), 1);
}
@ -819,8 +896,8 @@ pub(crate) mod tests {
async fn another_players_replay_of_a_begin_key_is_refused() {
let rig = rig(vec![]);
let key = Uuid::new_v4();
begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &principal("alice"), request(key, None)).await.unwrap();
let error = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.seeding, &principal("mallory"), request(key, None))
begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &principal("alice"), request(key, None)).await.unwrap();
let error = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &principal("mallory"), request(key, None))
.await
.err()
.unwrap();

View file

@ -37,6 +37,15 @@ pub(crate) struct Timeline {
pub(crate) parent: Option<(String, String)>,
}
/// Where a timeline's seed stands. A timeline with no entry is Ready: it
/// began unseeded, or its seed finished. The entry is persisted with the
/// timeline so a restart cannot turn a Draft into a playable world.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum SeedStatus {
Seeding,
Failed(String),
}
/// A player's one pointer: which timeline they are in, and where they mean to
/// go next. Keyed by principal, so every device of one player reads the same.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -75,6 +84,10 @@ struct CatalogState {
identities: BTreeMap<String, String>,
/// Unconsumed invites: sha256 of the token to its expiry. Only the hash is kept.
invites: BTreeMap<String, DateTime<Utc>>,
/// Seeds that are not Ready, by timeline. Absent in a catalog that has
/// never held one, so older catalogs keep their canonical encoding.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
seeds: BTreeMap<String, SeedStatus>,
}
pub(crate) struct Catalog {
@ -275,6 +288,46 @@ impl Catalog {
self.state.timelines.get(id)
}
/// The seed status of a timeline, `None` when it is Ready.
pub(crate) fn seed_status(&self, timeline: &str) -> Option<&SeedStatus> {
self.state.seeds.get(timeline)
}
/// Claims the seed of `timeline`, durably; false when one is running.
pub(crate) fn claim_seed(&mut self, timeline: &str) -> anyhow::Result<bool> {
if self.state.seeds.get(timeline) == Some(&SeedStatus::Seeding) {
return Ok(false);
}
self.settle_seed(timeline, Some(SeedStatus::Seeding))?;
Ok(true)
}
/// Records where a seed stands; `None` is Ready.
pub(crate) fn settle_seed(&mut self, timeline: &str, status: Option<SeedStatus>) -> anyhow::Result<()> {
let mut next = self.state.clone();
match status {
Some(status) => next.seeds.insert(timeline.to_owned(), status),
None => next.seeds.remove(timeline),
};
self.commit(next)
}
/// Marks every seed still Seeding as Failed. A seed runs only inside the
/// process that claimed it, so one still Seeding at startup was cut off
/// by a restart. Returns how many.
pub(crate) fn fail_interrupted_seeds(&mut self) -> anyhow::Result<usize> {
let mut next = self.state.clone();
let mut count = 0;
for status in next.seeds.values_mut().filter(|status| **status == SeedStatus::Seeding) {
*status = SeedStatus::Failed("seeding was interrupted by a restart".into());
count += 1;
}
if count > 0 {
self.commit(next)?;
}
Ok(count)
}
pub(crate) fn world(&self, world_id: &str) -> Option<&WorldRecord> {
self.state.worlds.get(world_id)
}
@ -399,6 +452,32 @@ mod tests {
assert!(catalog.set_current("mallory", &line.id).is_err());
}
/// A seed's status is part of the catalog row: it survives a reopen, and a
/// seed still Seeding when the process starts again reads Failed, never
/// Ready.
#[test]
fn a_seed_status_persists_and_a_restart_fails_a_running_seed() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("catalog.cc");
{
let mut catalog = Catalog::open(&path).unwrap();
assert!(catalog.claim_seed("timeline:a").unwrap());
assert!(!catalog.claim_seed("timeline:a").unwrap(), "one seed at a time");
catalog.settle_seed("timeline:b", Some(SeedStatus::Failed("no model".into()))).unwrap();
}
let mut catalog = Catalog::open(&path).unwrap();
assert_eq!(catalog.seed_status("timeline:a"), Some(&SeedStatus::Seeding));
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 1);
assert!(matches!(catalog.seed_status("timeline:a"), Some(SeedStatus::Failed(reason)) if reason.contains("restart")));
assert_eq!(catalog.seed_status("timeline:b"), Some(&SeedStatus::Failed("no model".into())));
assert_eq!(catalog.fail_interrupted_seeds().unwrap(), 0);
assert!(catalog.claim_seed("timeline:a").unwrap(), "a failed seed may be claimed again");
catalog.settle_seed("timeline:a", None).unwrap();
catalog.settle_seed("timeline:b", None).unwrap();
drop(catalog);
assert_eq!(Catalog::open(&path).unwrap().seed_status("timeline:a"), None);
}
#[test]
fn a_fork_is_minted_by_the_same_function_and_must_name_a_real_parent() {
let directory = tempfile::tempdir().unwrap();

View file

@ -5,7 +5,7 @@ use crate::{
api,
app_session::AppSessionOwner,
auth_guard::AuthGuard,
begin::{Scale, Seeding, Vaults},
begin::{Scale, Vaults},
catalog::Catalog,
heimdall::{HeimdallClient, HeimdallPort},
idunn_health::{
@ -60,7 +60,7 @@ pub(crate) struct AppState {
pub(crate) catalog: Arc<Mutex<Catalog>>,
pub(crate) timelines: Arc<Timelines>,
pub(crate) vaults: Arc<dyn Vaults>,
pub(crate) seeding: Arc<Seeding>,
pub(crate) scale: Arc<Scale>,
pub(crate) sessions: Arc<Mutex<AppSessionOwner>>,
pub(crate) heimdall: Arc<dyn HeimdallPort>,
pub(crate) auth: Arc<AuthGuard>,
@ -195,7 +195,12 @@ pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<(
}
prepare_admitted_state_layout(&runtime_root)?;
require_current_write_lease(write_lease_guard.as_ref())?;
let catalog = Catalog::open(runtime_root.join("catalog.cc"))?;
let mut catalog = Catalog::open(runtime_root.join("catalog.cc"))?;
// A seed runs only in the process that claimed it; any still Seeding was cut off.
let interrupted = catalog.fail_interrupted_seeds()?;
if interrupted > 0 {
tracing::warn!(interrupted, "seeds interrupted by the last shutdown were marked failed");
}
let shared = open_shared()?;
require_no_runtime_custody_failure(&mut fatal_events)?;
let wrapping_key = std::env::var_os("GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE")
@ -216,7 +221,7 @@ pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<(
catalog: Arc::new(Mutex::new(catalog)),
timelines: Arc::new(Timelines::new(runtime_root.clone(), shared, fatal.clone())),
vaults: Arc::new(crate::vaults::SnapshotVaults::new(&runtime_root)),
seeding: Arc::new(Seeding::new(Scale::from_env())),
scale: Arc::new(Scale::from_env()),
sessions: Arc::new(Mutex::new(sessions)),
heimdall,
auth: Arc::default(),
@ -614,7 +619,7 @@ mod tests {
#[ignore = "live: spends connector credit; run on Yggdrasil under a unit that loads the connector key"]
async fn live_seeded_begin_reaches_ready_with_a_place_and_people() {
use crate::{
begin::{BeginRequest, Scale, SeedStatus, Seeding, begin, tests::principal},
begin::{BeginRequest, Scale, begin, tests::principal}, catalog::SeedStatus,
catalog::Catalog,
state_layout::prepare_admitted_state_layout,
timelines::{Shared, Timelines},
@ -631,16 +636,16 @@ mod tests {
let shared = Shared { inference: counting.clone(), ..shared };
let (fatal, _fatal_events) = mpsc::unbounded_channel();
let timelines = Timelines::new(root.clone(), shared, fatal);
let catalog = Mutex::new(Catalog::open(root.join("catalog.cc")).unwrap());
let catalog = Arc::new(Mutex::new(Catalog::open(root.join("catalog.cc")).unwrap()));
let vaults = crate::vaults::SnapshotVaults::new(&root);
let seeding = Arc::new(Seeding::new(Scale::from_env()));
let scale = Arc::new(Scale::from_env());
let started = Instant::now();
let begun = begin(
&catalog,
&timelines,
&vaults,
&seeding,
&scale,
&principal("live"),
BeginRequest {
key: uuid::Uuid::new_v4().to_string(),
@ -654,7 +659,8 @@ mod tests {
.unwrap();
println!("LIVE begin returned after {:?}: {}", started.elapsed(), begun.reached);
let ready = loop {
match seeding.status(&begun.timeline) {
let status = catalog.lock().await.seed_status(&begun.timeline).cloned();
match status {
None => break started.elapsed(),
Some(SeedStatus::Failed(reason)) => panic!("the seed failed: {reason}"),
Some(SeedStatus::Seeding) if started.elapsed() > Duration::from_secs(1800) => {