From 8aebfb68111379c204c1acf4a124d557c1a69054 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Sep 2026 02:48:38 +0200 Subject: [PATCH] Falsify pass 9's cover, resume, and replay claims Tests only. Ten additions across the two organs pass 9 landed. world/cover.rs, pure over `derive_cover` with no kernel: - the rotation guarantee at the design profile, not at a toy size: 2,400 subjects, B=240, C=24, U=36 gives R=110 and the window closes in exactly ceil(2400/110)=22 ticks, and not in 21; - urgency reads the attention order while the window reads ascending id order, proved on a fixture whose two rankings are reversed against each other, so no third ranking can explain the result; - the cover is pure for identical inputs, and the attention order is a real input rather than an incidental one; - every cell in one cover carries that cover's tick index; - derived cell and constituent keys are collision-free across a full sweep of ticks; - the cap yields when component shapes cannot pack inside the budget even though token capacity would allow it, and the flag tracks the partition rather than the subject count. world/controllers.rs: - an uncoupled grouped cell commits every constituent, which is what makes the coupled cell's refusal a fact about coupling instead of a per-cell quota or a moved world revision; - the refused constituent's scope digest really did change; - the other grouped checkpoint resumes: a retryable fault parks the row at AgentInFlight, and the resumed run re-derives the same constituent ids, infers once, and commits once; - a grouped tick replays from genesis to an identical state digest and an identical event sequence. Co-Authored-By: Claude Opus 5 --- .../src/world/controllers.rs | 333 ++++++++++++++++++ crates/ghostlight-dungeon/src/world/cover.rs | 231 ++++++++++++ 2 files changed, 564 insertions(+) diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index ff91af6..d6992b1 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -7728,6 +7728,339 @@ mod tests { task.await.unwrap(); } + /// The same fixture, with every subject standing in its own room. The + /// agency graph relates none of them, so the cell that packs them together + /// holds constituents that cannot change each other's scope. + async fn apart_cell_mailbox( + controllers: Vec, + ) -> (tempfile::TempDir, WorldMailbox, tokio::task::JoinHandle<()>) { + let directory = tempfile::tempdir().unwrap(); + let (mailbox, task) = WorldMailbox::open(directory.path().join("world.cc")).unwrap(); + let owner = PrincipalId::new("owner"); + let authenticated = AuthenticatedCaller::fixture(CallerId::Principal(owner.clone())); + let mut declarations = Vec::new(); + for (index, controller) in controllers.into_iter().enumerate() { + declarations.push(Declaration::Entity(crate::world::EntityDeclaration { + handle: DraftHandle::new(&format!("room{index}")), + label: format!("Room {index}"), + kind: EntityKind::Place, + container: None, + })); + declarations.push(Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(&format!("subject{index}")), + label: format!("Subject {index}"), + kind: SubjectKind::Person, + controller, + affordances: kernel_speak_grant(), + position: Some(crate::world::Ref::Draft(DraftHandle::new(&format!( + "room{index}" + )))), + })); + } + let creation = mailbox + .create_fixture( + CreateWorld { + id: CommandId::new(), + owner: owner.clone(), + title: "Apart Fixture".into(), + patch: WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + }, + scale_intent: WorldScaleIntentRef::default(), + }, + &authenticated, + ) + .await + .unwrap(); + let mut snapshot = mailbox.snapshot().await.unwrap(); + for body in [CommandBody::ApproveDraft, CommandBody::ActivateWorld] { + mailbox + .submit_fixture( + CommandEnvelope { + id: CommandId::new(), + world_id: creation.world_id, + expected_revision: snapshot.revision, + caller: CallerId::Principal(owner.clone()), + body, + }, + &authenticated, + ) + .await + .unwrap(); + snapshot = mailbox.snapshot().await.unwrap(); + } + assert_eq!(snapshot.phase, WorldPhase::Active); + (directory, mailbox, task) + } + + /// The contention finding is a fact about coupling, not about grouping. Two + /// constituents in separate rooms both propose from one inference and both + /// commit: the refusal a coupled cell earns is not a per-cell quota, and it + /// is not the world revision moving underneath the second submission. + #[tokio::test] + async fn soul_b_an_uncoupled_grouped_cell_commits_every_constituent() { + let (_directory, mailbox, task) = apart_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + ]) + .await; + let graph = mailbox.agency_graph().await.unwrap(); + assert!( + graph.edges.is_empty(), + "subjects in separate rooms were related: {:?}", + graph.edges + ); + let cell = one_group(&mailbox).await; + assert_eq!(cell.members().len(), 2); + + let (runner, _store) = grouped_runner( + &mailbox, + vec![output( + vec![ + speak_call("c0", "c0__speak", "The east hinge is dry."), + speak_call("c1", "c1__speak", "The west hinge is dry."), + ], + "two-uncoupled-acts", + )], + ); + let CellRun::Grouped(run) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert!(run.pending.is_none()); + assert_eq!( + run.submissions.len(), + 2, + "an uncoupled constituent was refused: {:?}", + run.needs + ); + for entry in &run.submissions { + assert!(matches!( + entry.submission, + SubmissionDisposition::Completed(_) + )); + } + assert!(run.needs.is_empty(), "{:?}", run.needs); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 2); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// The refusal a coupled cell earns is honest: the second constituent's + /// scope digest really is different after its neighbour acted. A refusal + /// that fired on a moved world revision rather than on a moved scope would + /// leave this digest untouched. + #[tokio::test] + async fn soul_b_the_refused_constituent_bound_a_scope_that_really_changed() { + let (_directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + ]) + .await; + let cell = one_group(&mailbox).await; + let second = cell.members()[1].subject; + let digest_of = |snapshot: &WorldSnapshot, subject: SubjectId| { + snapshot + .opportunities + .iter() + .find(|entry| entry.scope.subject_id == subject) + .map(|entry| entry.scope_digest.clone()) + }; + let before = digest_of(&mailbox.snapshot().await.unwrap(), second) + .expect("the second constituent has an opportunity before the cell runs"); + + let (runner, _store) = grouped_runner( + &mailbox, + vec![output( + vec![ + speak_call("c0", "c0__speak", "The hinge is flooding."), + speak_call("c1", "c1__speak", "Then we close the span."), + ], + "coupled-acts", + )], + ); + let CellRun::Grouped(run) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert_eq!(run.submissions.len(), 1); + assert!( + run.needs + .iter() + .any(|need| need.detail.contains("scope changed")), + "{:?}", + run.needs + ); + + let after = digest_of(&mailbox.snapshot().await.unwrap(), second) + .expect("the refused constituent still has an opportunity"); + assert_ne!( + before, after, + "the refusal named a scope change that did not happen" + ); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// The other checkpoint's resume. A retryable fault leaves the row at + /// `AgentInFlight` with nothing committed; the resumed run re-derives the + /// same constituent ids from the persisted row, infers once, and commits + /// once. Both grouped checkpoints therefore resume without a second commit. + #[tokio::test] + async fn soul_b_a_cell_resumed_from_agent_in_flight_commits_nothing_twice() { + let (_directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + ]) + .await; + let cell = one_group(&mailbox).await; + let (runner, store) = grouped_runner( + &mailbox, + vec![ + Err(InferenceFault::retryable("the provider is busy")), + output( + vec![ + speak_call("c0", "c0__speak", "Hold the bridge."), + InferenceEvent::ToolCall { + call_id: "c1".into(), + name: "c1__finish_without_proposal".into(), + arguments: "{}".into(), + }, + ], + "grouped-after-retry", + ), + ], + ); + + let CellRun::Grouped(first) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert!( + first.pending.is_some(), + "a retryable fault did not park the cell" + ); + assert!(first.submissions.is_empty()); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 0); + + let parked = store.work.lock().unwrap().values().next().unwrap().clone(); + let ControllerWork::Grouped(GroupedCheckpoint::AgentInFlight { constituents, .. }) = + &parked + else { + panic!("the parked row is not an in-flight grouped checkpoint: {parked:?}") + }; + let parked_ids: Vec = constituents + .iter() + .map(|constituent| constituent.command_id) + .collect(); + + let CellRun::Grouped(second) = runner.run_cell(&cell).await.unwrap() else { + panic!("a resumed coarse cell did not run the grouped lane") + }; + assert!(second.pending.is_none()); + assert_eq!(second.submissions.len(), 2); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 1); + + let resumed = store.work.lock().unwrap().values().next().unwrap().clone(); + let ControllerWork::Grouped(GroupedCheckpoint::Submitting { constituents, .. }) = &resumed + else { + panic!("the resumed row did not reach submission: {resumed:?}") + }; + assert_eq!( + parked_ids, + constituents + .iter() + .map(|constituent| constituent.command_id) + .collect::>(), + "a resumed cell derived different constituent ids" + ); + + // A third pass has no inference left: it must answer from the ledger. + let CellRun::Grouped(third) = runner.run_cell(&cell).await.unwrap() else { + panic!("a twice-resumed coarse cell did not run the grouped lane") + }; + assert!(matches!( + third.submissions[0].submission, + SubmissionDisposition::PreviouslyConfirmed(_) + )); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 1); + + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// The replay half of the grouped-tick verification. A coarse cell reaches + /// the kernel as ordinary one-opportunity submissions, so the store it + /// leaves must replay from genesis to the same digest and the same events. + /// If a cell were a command shape, this is where it would show. + #[tokio::test] + async fn soul_b_a_grouped_tick_replays_to_an_identical_state_digest() { + let (directory, mailbox, task) = active_cell_mailbox(vec![ + NewController::OperationalAgent, + NewController::OperationalAgent, + NewController::NarrativePersona, + ]) + .await; + let path = directory.path().join("world.cc"); + let cell = one_group(&mailbox).await; + assert_eq!(cell.members().len(), 3); + let (runner, _store) = grouped_runner( + &mailbox, + vec![ + output( + vec![ + speak_call("c0", "c0__speak", "The hinge is flooding."), + speak_call("outside", "c9__speak", "I speak for someone else."), + ], + "replay-one", + ), + output( + vec![InferenceEvent::Text("Nothing further.".into())], + "replay-two", + ), + ], + ); + let CellRun::Grouped(run) = runner.run_cell(&cell).await.unwrap() else { + panic!("a coarse cell did not run the grouped lane") + }; + assert!(run.pending.is_none()); + assert_eq!(run.submissions.len(), 3); + + let live = mailbox.snapshot().await.unwrap(); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 1); + drop(runner); + drop(mailbox); + task.await.unwrap(); + + let replayed = + crate::world::WorldKernel::open(&path, live.world_id).expect("the world store replays"); + assert_eq!( + replayed.state.state_digest, live.state_digest, + "a grouped tick did not replay to the same digest" + ); + assert_eq!(replayed.state.revision, live.revision); + // The event sequence, not just its digest: a replay that agreed on a + // digest while disagreeing on what happened would be a worse bug. + let events = serde_json::to_string(&replayed.state.events).unwrap(); + assert!(events.contains("The hinge is flooding.")); + for forbidden in ["cell-act", "cell-work", "c0__", "constituent", "resolution"] { + assert!( + !events.contains(forbidden), + "the replayed event sequence names `{forbidden}`" + ); + } + // A second open is the same open: replay is a function of the store. + let expected = replayed.state.clone(); + drop(replayed); + let again = crate::world::WorldKernel::open(&path, live.world_id) + .expect("the world store replays twice"); + assert_eq!(again.state, expected); + } + /// The cover is derived and disposable. Nothing the kernel persists or /// hands out names a cell, a handle, or a resolution: the only durable /// trace is the controller-work row, whose custody is separate from world diff --git a/crates/ghostlight-dungeon/src/world/cover.rs b/crates/ghostlight-dungeon/src/world/cover.rs index 8b3d2bb..5121486 100644 --- a/crates/ghostlight-dungeon/src/world/cover.rs +++ b/crates/ghostlight-dungeon/src/world/cover.rs @@ -897,4 +897,235 @@ mod tests { ); assert!(budget(4, 2, 0).validated().is_ok()); } + + /// The rotation guarantee at the design profile rather than at a toy size. + /// `K = 146`, `U = 36`, so the reserve is `R = 110` and the window closes in + /// `ceil(2400 / 110) = 22` ticks. Membership is stable across the sweep, + /// which is the precondition the tight bound is stated under. + #[test] + fn soul_b_the_profile_rotation_closes_over_every_subject_in_ceil_n_over_reserve_ticks() { + let opportunities = active(2_400); + let budget = budget(240, 24, 36); + let reserve = 146 - 36; + let cycle = 2_400usize.div_ceil(reserve); + assert_eq!(cycle, 22, "the profile's window is not 22 ticks wide"); + + let mut seen: BTreeSet = BTreeSet::new(); + for tick in 0..cycle as u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + assert_eq!(cover.singletons(), 146); + for cell in &cover.cells { + if let Cell::Singleton { member, .. } = cell { + seen.insert(member.subject); + } + } + } + assert_eq!( + seen.len(), + 2_400, + "{} subjects never reached detail inside the window", + 2_400 - seen.len() + ); + + // One tick short of the cycle must not already close it, or the bound + // is being read off a coincidence rather than the arithmetic. + let mut short: BTreeSet = BTreeSet::new(); + for tick in 0..(cycle - 1) as u64 { + for cell in &derive(&opportunities, &AgencyGraph::default(), budget, tick).cells { + if let Cell::Singleton { member, .. } = cell { + short.insert(member.subject); + } + } + } + assert!(short.len() < 2_400, "the window closed a tick early"); + } + + /// The urgency slots go to the head of the attention order the kernel + /// already owns, and the rotation window goes to ascending id order. The + /// fixture arrives in descending id order so the two rankings cannot be + /// confused with each other, and no third ranking exists to explain the + /// result. + #[test] + fn soul_b_urgency_slots_follow_the_attention_order_not_the_id_order() { + let mut opportunities = active(40); + opportunities.reverse(); + // N = 40, B = 10, C = 8 → K = floor((80 - 40) / 7) = 5, U = 3, R = 2. + let cover = derive(&opportunities, &AgencyGraph::default(), budget(10, 8, 3), 0); + let singletons: BTreeSet = cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect(); + assert_eq!(singletons.len(), 5); + + let head: BTreeSet = opportunities[..3] + .iter() + .map(|entry| entry.scope.subject_id) + .collect(); + assert!( + head.is_subset(&singletons), + "the urgency slots did not follow the attention order" + ); + // The window is the ascending-id reserve, which here is the tail of the + // attention order: two rankings, both honoured, neither invented. + assert!( + singletons.contains(&subject(1)) && singletons.contains(&subject(2)), + "the rotation window did not follow ascending id order" + ); + } + + /// The partition is a pure function of its arguments, and the attention + /// order is one of those arguments rather than an incidental input. Equal + /// inputs derive an equal cover; a permuted order derives a different one, + /// because urgency and backfill read that order and `order_opportunities` + /// is its one owner. + #[test] + fn soul_b_the_cover_is_pure_and_the_attention_order_is_a_real_input() { + let opportunities = active(40); + let mut graph = AgencyGraph::default(); + graph.link(subject(11), subject(12)); + let budget = budget(10, 8, 3); + let ids = |cover: &Cover| -> Vec { + cover + .cells + .iter() + .map(|cell| match cell { + Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, + }) + .collect() + }; + + let one = derive(&opportunities, &graph, budget, 5); + let other = derive(&opportunities, &graph, budget, 5); + assert_eq!(one, other, "identical inputs derived different covers"); + assert_eq!( + serde_json::to_string(&ids(&one)).unwrap(), + serde_json::to_string(&ids(&other)).unwrap(), + "identical inputs derived different cell ids" + ); + + let mut reversed = opportunities.clone(); + reversed.reverse(); + let permuted = derive(&reversed, &graph, budget, 5); + assert_eq!( + covered(&one), + covered(&permuted), + "a permutation lost or duplicated a subject" + ); + let singletons = |cover: &Cover| -> BTreeSet { + cover + .cells + .iter() + .filter_map(|cell| match cell { + Cell::Singleton { member, .. } => Some(member.subject), + Cell::Group { .. } => None, + }) + .collect() + }; + assert_ne!( + singletons(&one), + singletons(&permuted), + "the attention order is not an input to the partition" + ); + } + + /// Every cell in one cover carries that cover's tick index. This is what the + /// driver's "advance the clock after the cells" ordering buys: one `now`, + /// one phase, one set of derived command ids per tick. + #[test] + fn soul_b_every_cell_shares_the_covers_tick_index() { + let opportunities = active(60); + for tick in [0u64, 1, 7, 4_000] { + let cover = derive( + &opportunities, + &AgencyGraph::default(), + budget(10, 8, 2), + tick, + ); + assert_eq!(cover.tick, TickIndex(tick)); + for cell in &cover.cells { + let carried = match cell { + Cell::Singleton { tick, .. } | Cell::Group { tick, .. } => *tick, + }; + assert_eq!(carried, cover.tick, "a cell carried another tick's index"); + } + } + } + + /// Derived ids are collision-free across every cell of every tick in a full + /// sweep, and a cell key never collides with a constituent key. + #[test] + fn soul_b_derived_ids_do_not_collide_across_a_sweep_of_ticks() { + let world = WorldId::nil_for_test(); + let opportunities = active(600); + let budget = budget(60, 24, 6); + let mut cells: BTreeSet = BTreeSet::new(); + let mut keys: BTreeSet = BTreeSet::new(); + let mut cell_count = 0usize; + let mut key_count = 0usize; + for tick in 0..12u64 { + let cover = derive(&opportunities, &AgencyGraph::default(), budget, tick); + for cell in &cover.cells { + let id = match cell { + Cell::Singleton { id, .. } | Cell::Group { id, .. } => *id, + }; + cells.insert(id); + cell_count += 1; + keys.insert(cell_work_uuid(world, id, cover.tick)); + key_count += 1; + for member in cell.members() { + keys.insert(cell_constituent_uuid(world, id, member.subject, cover.tick)); + key_count += 1; + } + } + } + assert!( + cell_count >= 700, + "the sweep was too small to mean anything" + ); + assert_eq!(cells.len(), cell_count, "two cells share one id"); + assert_eq!(keys.len(), key_count, "two derived command keys collide"); + } + + /// The cap yields for exactly one reason: no partition inside the budget + /// respects it. Token capacity alone does not decide that — component shapes + /// do. Here `C * B = 12 >= N = 9`, and the cap still yields, because two + /// three-member components and two isolates cannot pack into two cells of + /// four. Coverage holds and the operator is told. + #[test] + fn soul_b_the_cap_yields_when_component_shapes_cannot_pack_inside_the_budget() { + let opportunities = active(9); + let mut graph = AgencyGraph::default(); + graph.link(subject(2), subject(3)); + graph.link(subject(3), subject(4)); + graph.link(subject(5), subject(6)); + graph.link(subject(6), subject(7)); + let cover = derive(&opportunities, &graph, budget(3, 4, 0), 0); + + assert_eq!(covered(&cover).len(), 9); + assert_eq!(covered(&cover).iter().collect::>().len(), 9); + assert!(cover.cells.len() <= 3); + assert!( + cover.cells.iter().any(|cell| cell.members().len() > 4), + "the cap did not yield: {:?}", + cover + .cells + .iter() + .map(|cell| cell.members().len()) + .collect::>() + ); + assert!( + cover.oversubscribed, + "the cap yielded without telling the operator" + ); + + // The same subjects with no edges pack cleanly and the flag stays down, + // so the flag tracks the partition rather than the subject count. + let loose = derive(&opportunities, &AgencyGraph::default(), budget(3, 4, 0), 0); + assert!(!loose.oversubscribed); + assert!(loose.cells.iter().all(|cell| cell.members().len() <= 4)); + } }