diff --git a/crates/ghostlight-dungeon/src/api.rs b/crates/ghostlight-dungeon/src/api.rs index 08ea736..6f1757b 100644 --- a/crates/ghostlight-dungeon/src/api.rs +++ b/crates/ghostlight-dungeon/src/api.rs @@ -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}; @@ -68,6 +69,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. @@ -191,10 +203,10 @@ async fn timelines(headers: HeaderMap, State(state): State) -> 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, @@ -243,7 +255,7 @@ async fn begin_world( &state.catalog, &state.timelines, state.vaults.as_ref(), - &state.seeding, + &state.scale, &principal, BeginRequest { key: body.key, @@ -302,6 +314,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) @@ -317,6 +334,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. @@ -396,7 +423,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"})) @@ -936,7 +963,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(), @@ -1249,6 +1276,84 @@ 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}"); + assert_eq!(body["error"], "this world is still being seeded"); + + 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_eq!(body["error"], "this world's seed did not finish"); + 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; diff --git a/crates/ghostlight-dungeon/src/begin.rs b/crates/ghostlight-dungeon/src/begin.rs index 9333572..3c82548 100644 --- a/crates/ghostlight-dungeon/src/begin.rs +++ b/crates/ghostlight-dungeon/src/begin.rs @@ -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>, -} - -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 { - 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, MailboxEr } pub(crate) async fn begin( - catalog: &Mutex, + catalog: &Arc>, timelines: &Timelines, vaults: &dyn Vaults, - seeding: &Arc, + scale: &Arc, principal: &VerifiedPrincipalEvidence, request: BeginRequest, ) -> Result { @@ -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) -> Option { + 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, @@ -400,18 +372,41 @@ struct Seed { world_id: ghostlight::WorldId, evidence: Arc, brief: Option, - seeding: Arc, + catalog: Arc>, + scale: Arc, +} + +/// 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>, pub(crate) timelines: Arc, pub(crate) port: Arc, - pub(crate) seeding: Arc, + pub(crate) scale: Arc, _fatal: mpsc::UnboundedReceiver, } + impl Rig { + /// The timeline's persisted seed status, `None` when Ready. + pub(crate) async fn status(&self, timeline: &str) -> Option { + 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) -> 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, 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(); diff --git a/crates/ghostlight-dungeon/src/catalog.rs b/crates/ghostlight-dungeon/src/catalog.rs index c397bf0..ef2ad4b 100644 --- a/crates/ghostlight-dungeon/src/catalog.rs +++ b/crates/ghostlight-dungeon/src/catalog.rs @@ -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, /// Unconsumed invites: sha256 of the token to its expiry. Only the hash is kept. invites: BTreeMap>, + /// 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, } pub(crate) struct Catalog { @@ -281,6 +294,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 { + 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) -> 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 { + 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) } @@ -405,6 +458,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(); diff --git a/crates/ghostlight-dungeon/src/run_ahead.rs b/crates/ghostlight-dungeon/src/run_ahead.rs index 979e8a6..53f1bc1 100644 --- a/crates/ghostlight-dungeon/src/run_ahead.rs +++ b/crates/ghostlight-dungeon/src/run_ahead.rs @@ -54,3 +54,48 @@ pub(crate) async fn evidence_of( }, } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + begin::tests::{NoVaults, one_vault}, + catalog::{Timeline, WorldRecord, timeline_id}, + }; + use chrono::Utc; + use uuid::Uuid; + + async fn catalog_with(snapshot_id: Option<&str>) -> (tempfile::TempDir, Mutex, String) { + let directory = tempfile::tempdir().unwrap(); + let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap(); + let timeline = timeline_id(Uuid::new_v4()); + catalog + .mint_timeline( + Some(WorldRecord { + world_id: "w1".into(), + title: "Ashfall".into(), + owner: "alice".into(), + snapshot_id: snapshot_id.map(str::to_owned), + created_at: Utc::now(), + }), + Timeline { id: timeline.clone(), world_id: "w1".into(), parent: None }, + ) + .unwrap(); + (directory, Mutex::new(catalog), timeline) + } + + /// A timeline's elaborator reads what its world was bound to: nothing + /// for an unseeded world, the snapshot for a seeded one, and no evidence + /// (so no sweep) for a snapshot that cannot be reopened or a timeline the + /// catalog does not know. + #[tokio::test] + async fn the_evidence_of_a_timeline_is_its_bound_snapshots() { + let vaults = one_vault(); + let (_a, unseeded, timeline) = catalog_with(None).await; + assert!(evidence_of(&unseeded, &NoVaults, &timeline).await.is_some(), "an unseeded world reads none, and still sweeps"); + let (_b, seeded, timeline) = catalog_with(Some("feedface")).await; + assert!(evidence_of(&seeded, vaults.as_ref(), &timeline).await.is_some()); + assert!(evidence_of(&seeded, &NoVaults, &timeline).await.is_none(), "an unreadable snapshot is never swept blind"); + assert!(evidence_of(&seeded, vaults.as_ref(), "timeline:00000000-0000-4000-8000-000000000000").await.is_none()); + } +} diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index e421f8f..4461929 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -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::{ @@ -70,7 +70,7 @@ pub(crate) struct AppState { pub(crate) catalog: Arc>, pub(crate) timelines: Arc, pub(crate) vaults: Arc, - pub(crate) seeding: Arc, + pub(crate) scale: Arc, pub(crate) sessions: Arc>, pub(crate) heimdall: Arc, pub(crate) auth: Arc, @@ -211,7 +211,12 @@ pub(crate) async fn run(state_root_binding: Option) -> 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") @@ -232,7 +237,7 @@ pub(crate) async fn run(state_root_binding: Option) -> 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(), @@ -634,7 +639,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}, @@ -651,16 +656,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(), @@ -674,7 +679,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) => { @@ -686,10 +692,16 @@ mod tests { let (calls, usage) = (counting.calls.load(std::sync::atomic::Ordering::SeqCst), *counting.usage.lock().unwrap()); println!("LIVE ready after {ready:?}; calls={calls} prompt_tokens={} completion_tokens={}", usage.0, usage.1); let host = timelines.host(&begun.timeline).await.unwrap(); + // A position is not public on the snapshot; the Debug text names it by + // the same entity id a place carries. + let standing = |world: &ghostlight::WorldSnapshot, place: &ghostlight::PlaceSnapshot| -> Vec { + let at = format!("position: Some({:?})", place.id); + world.subjects.iter().filter(|subject| format!("{subject:?}").contains(&at)).map(|subject| subject.label.clone()).collect() + }; let report = |label: &str, world: &ghostlight::WorldSnapshot| { println!("LIVE {label}: phase={:?}", world.phase); for place in &world.places { - println!("LIVE place {}", place.label); + println!("LIVE place {} <- {:?}", place.label, standing(world, place)); } for subject in &world.subjects { println!("LIVE subject {:?} {} qualified={}", subject.kind, subject.label, subject.qualified); @@ -701,7 +713,8 @@ mod tests { let world = host.world.snapshot().await.unwrap(); report("after seed", &world); assert_eq!(world.phase, ghostlight::WorldPhase::Active); - assert!(world.places.len() >= 2, "the root and at least one place under it"); + let authored = world.places.iter().filter(|place| place.label != "The Commons" && place.label != "Ghostlight Live").count(); + assert!(authored >= 2, "the seed authored places beyond the root and The Commons, got {authored}"); let person = world.scale_deficit.iter().find(|row| row.kind == ghostlight::SubjectKind::Person).unwrap(); assert!(person.qualified >= 2, "at least two qualifying people"); diff --git a/crates/ghostlight-dungeon/src/vaults.rs b/crates/ghostlight-dungeon/src/vaults.rs index da7a99d..0b014e1 100644 --- a/crates/ghostlight-dungeon/src/vaults.rs +++ b/crates/ghostlight-dungeon/src/vaults.rs @@ -140,6 +140,18 @@ mod tests { (state, vaults, id) } + /// The id gate keeps a stored id from naming another path: a short hex + /// string and a long non-hex one are both refused before any path is built. + #[test] + fn a_stored_snapshot_id_that_is_not_an_id_is_refused_before_a_path_is_built() { + let (_state, vaults, id) = imported_avatar(); + for bad in ["abc".to_owned(), format!("../{}", &id[3..]), id.to_uppercase()] { + let error = vaults.evidence(&bad).err().expect("refused").to_string(); + assert!(error.contains("not an id"), "{bad}: {error}"); + } + assert!(vaults.evidence(&id).is_ok()); + } + #[test] fn it_lists_the_imported_profiles_and_opens_the_recorded_snapshot() { let (_state, vaults, id) = imported_avatar();