From 02757c8c59f24e74b0536eca13a78ea6e94df9fb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 10:49:04 +0100 Subject: [PATCH] elaboration: a sweep claims demand at the focus places first; Dungeon run-ahead focuses on the player's place ElaborationRunner::sweep takes a Focus; demand_entries stably partitions in-focus answers (a focus place, inside one, or one open route from one) ahead of the rest. Run-ahead builds the focus from the owner's human subject. Co-Authored-By: Claude Opus 5.5 --- crates/ghostlight-dungeon/src/begin.rs | 2 +- .../ghostlight-dungeon/src/playtest_atlas.rs | 2 +- crates/ghostlight-dungeon/src/run_ahead.rs | 51 +++- crates/ghostlight/src/controllers.rs | 253 ++++++++++++++---- crates/ghostlight/src/elaboration.rs | 73 ++++- crates/ghostlight/src/lib.rs | 8 +- 6 files changed, 333 insertions(+), 56 deletions(-) diff --git a/crates/ghostlight-dungeon/src/begin.rs b/crates/ghostlight-dungeon/src/begin.rs index 64ba3fe..6778817 100644 --- a/crates/ghostlight-dungeon/src/begin.rs +++ b/crates/ghostlight-dungeon/src/begin.rs @@ -485,7 +485,7 @@ impl Seed { // completed request by its id, so asking again cannot spend twice. let mut retries = 0; loop { - match runner.sweep(self.permits.clone(), self.scale.seed_sessions).await { + match runner.sweep(self.permits.clone(), self.scale.seed_sessions, &ghostlight::Focus::default()).await { Ok(_) => break, Err(error) if retries < SEED_RETRIES && is_retryable(&error) => { retries += 1; diff --git a/crates/ghostlight-dungeon/src/playtest_atlas.rs b/crates/ghostlight-dungeon/src/playtest_atlas.rs index e5d6876..c27cb79 100644 --- a/crates/ghostlight-dungeon/src/playtest_atlas.rs +++ b/crates/ghostlight-dungeon/src/playtest_atlas.rs @@ -856,7 +856,7 @@ pub(super) async fn run(options: AtlasOptions) -> anyhow::Result { recorder.sweep.store(sweep, Ordering::SeqCst); let began = Instant::now(); let permits = Arc::new(Semaphore::new(options.concurrency)); - let mut sweeping = Box::pin(runner.sweep(permits, options.sweep_sessions)); + let mut sweeping = Box::pin(runner.sweep(permits, options.sweep_sessions, &ghostlight::Focus::default())); let outcome = loop { tokio::select! { outcome = &mut sweeping => break outcome, diff --git a/crates/ghostlight-dungeon/src/run_ahead.rs b/crates/ghostlight-dungeon/src/run_ahead.rs index d0b2e0b..fdfa328 100644 --- a/crates/ghostlight-dungeon/src/run_ahead.rs +++ b/crates/ghostlight-dungeon/src/run_ahead.rs @@ -2,7 +2,7 @@ //! //! A world's scale deficit is answered after play starts, not before: one sweep //! once Begin activates a seeded world, and one after each closed turn. Each -//! sweep starts at most `Scale::sweep_sessions` elaboration sessions and holds +//! sweep claims what the player is looking at first (`focus_of`), and starts at most `Scale::sweep_sessions` elaboration sessions and holds //! at most `Scale::sweep_permits` permits, and spends in its own post-turn //! window: the elaborator calls a provider only through the window's recording //! port, which refuses a call that could pass the lane's allowance. The elaborator reads the evidence of the snapshot its @@ -14,7 +14,7 @@ use crate::{ catalog::Catalog, timelines::TimelineHost, }; -use ghostlight::{EvidenceSource, NullEvidenceSource}; +use ghostlight::{ControllerMode, EvidenceSource, Focus, NullEvidenceSource, WorldSnapshot}; use std::sync::Arc; use tokio::sync::{Mutex, Semaphore}; @@ -41,11 +41,28 @@ pub(crate) async fn run_ahead(host: &TimelineHost, evidence: Arc Focus { + let places = world + .subjects + .iter() + .filter(|subject| { + subject.controller_mode == Some(ControllerMode::Human) + && subject.human_controller.as_ref() == Some(&world.owner) + }) + .filter_map(|subject| world.place_of(subject.id)) + .collect(); + Focus { places, nodes: Vec::new() } +} + /// The evidence a timeline's elaborator reads: its bound snapshot's, for the /// era its world was pinned to, or none for a world that began unseeded. A /// bound snapshot that cannot be reopened, or a world that cannot be read, @@ -85,6 +102,34 @@ mod tests { }; use uuid::Uuid; + /// The sweep looks where the player stands: the place of the owner's own + /// human subject, and nowhere for a world whose owner controls no subject. + #[tokio::test] + async fn the_focus_of_a_world_is_its_owners_human_subjects_place() { + let rig = deferred_rig(); + let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &rig.scale, &principal("alice"), request(Uuid::new_v4(), None)) + .await + .unwrap(); + let host = rig.timelines.host(&begun.timeline).await.unwrap(); + let world = host.world.snapshot().await.unwrap(); + let player = world + .subjects + .iter() + .find(|subject| subject.human_controller.as_ref() == Some(&world.owner)) + .expect("the owner's player"); + let stands = world.place_of(player.id).expect("the player stands somewhere"); + assert_eq!(focus_of(&world).places, vec![stands]); + + let mut stranger = world.clone(); + stranger.owner = ghostlight::PrincipalId::new("someone else"); + assert!(focus_of(&stranger).places.is_empty(), "another principal's subject is not the owner's player"); + let mut automaton = world; + for subject in &mut automaton.subjects { + subject.controller_mode = Some(ControllerMode::NarrativePersona); + } + assert!(focus_of(&automaton).places.is_empty(), "a persona is not looking"); + } + /// 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 diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 335d947..601d0cd 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -8327,7 +8327,7 @@ mod tests { use super::*; use crate::elaboration::{ElaboratorSession, EvidenceError, EvidenceQuery, EvidenceReceipt}; use crate::tests::{operations, opportunity_for}; - use crate::{CausalBoundary, Lens, LensWeights}; + use crate::{CausalBoundary, Focus, Lens, LensWeights}; use crate::patch::{RECORD_GAP_PATCH_TOOL, kernel_speak_entry, kernel_speak_grant}; use crate::{ CommitmentKind, CoverBudget, CreateJurisdictionIntent, CreateWorldIntent, @@ -14780,7 +14780,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let runner = sweep_runner(&mailbox, port.clone(), store.clone()); let sweep = tokio::spawn({ let permits = permits.clone(); - async move { runner.sweep(permits, usize::MAX).await } + async move { runner.sweep(permits, usize::MAX, &Focus::default()).await } }); port.entered.acquire_many(2).await.unwrap().forget(); @@ -14833,15 +14833,174 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur ("The Far Road", roads[1]), ]))); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - runner.sweep(pool(2), 1).await.unwrap(); + runner.sweep(pool(2), 1, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 1, "a bound of one started more than one session"); - runner.sweep(pool(2), 1).await.unwrap(); + runner.sweep(pool(2), 1, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 2, "the second sweep answers the entry the first left"); drop(runner); drop(mailbox); task.await.unwrap(); } + /// The boundary a dead end at `road` raises, and the commons' deficit, as + /// the claim order names them. + fn boundary_at(road: EntityId) -> impl Fn(&PatchAnswer) -> bool { + move |answer| { + matches!(answer, PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) if *place == road) + } + } + + fn is_deficit(answer: &PatchAnswer) -> bool { + matches!(answer, PatchAnswer::Deficit(_)) + } + + /// The claim order with the places of `focus` in focus: in-focus answers + /// first, each class in the kernel's order. Boundaries sit at their dead + /// ends, the deficit at the commons its root names. + #[tokio::test] + async fn the_claim_order_puts_what_the_focus_holds_first_and_keeps_order_within_a_class() { + let (_directory, mailbox, task, commons, roads) = dead_end_world( + crate::tests::stock_weights(), + &["The Unwalked Road", "The Far Road"], + Roots::Commons, + 3, + ) + .await; + let snapshot = mailbox.snapshot().await.unwrap(); + let unfocused = crate::elaboration::claim_order(&snapshot, &Focus::default()); + assert_eq!(unfocused.len(), 3, "two boundaries and the commons' deficit"); + let (first, second) = (roads[0], roads[1]); + let at = |road| unfocused.iter().find(|answer| boundary_at(road)(answer)).unwrap().clone(); + let deficit = unfocused.iter().find(|answer| is_deficit(answer)).unwrap().clone(); + assert_eq!( + unfocused, + vec![at(first), at(second), deficit.clone()], + "an empty focus keeps the kernel's order: boundaries in derivation order, then the deficit" + ); + + // The dead end the player's exit leads to is claimed first. + let focus = Focus { places: vec![second], nodes: Vec::new() }; + assert_eq!( + crate::elaboration::claim_order(&snapshot, &focus), + vec![at(second), at(first), deficit.clone()] + ); + // The commons is one open route from the first road: its deficit + // joins that road's boundary in focus, and the other road waits. + let focus = Focus { places: vec![first], nodes: Vec::new() }; + assert_eq!( + crate::elaboration::claim_order(&snapshot, &focus), + vec![at(first), deficit.clone(), at(second)] + ); + // A place with a focus place around it is in focus with all it holds. + let focus = Focus { places: vec![commons], nodes: Vec::new() }; + assert_eq!(crate::elaboration::claim_order(&snapshot, &focus), unfocused); + drop(mailbox); + task.await.unwrap(); + } + + /// What "in focus" reads: a place inside a focus place, or one open route + /// from it in either direction, and nothing else. The world is edited so + /// that each reading stands alone. + #[tokio::test] + async fn a_place_is_in_focus_by_containment_or_by_one_open_route_and_no_other_way() { + let (_directory, mailbox, task, commons, roads) = dead_end_world( + crate::tests::stock_weights(), + &["The Unwalked Road", "The Far Road"], + Roots::Commons, + 3, + ) + .await; + let world = mailbox.snapshot().await.unwrap(); + let (first, second) = (roads[0], roads[1]); + let held = |snapshot: &WorldSnapshot, focus: EntityId, place: EntityId| { + crate::elaboration::in_focus(snapshot, &Focus { places: vec![focus], nodes: Vec::new() }, place) + }; + + // Containment alone: no routes, and the second road stands outside. + let mut contained = world.clone(); + contained.routes.clear(); + contained.places.iter_mut().find(|place| place.id == second).unwrap().container = None; + assert!(held(&contained, commons, first), "a place inside a focus place is in focus"); + assert!(held(&contained, commons, commons), "a focus place is in focus"); + assert!(!held(&contained, commons, second)); + assert!(!held(&contained, first, commons), "what contains a focus place is not in focus"); + + // An open route alone, read forward: nothing is inside anything, and + // the commons' route to the second road is closed. + let mut routed = world.clone(); + for place in &mut routed.places { + place.container = None; + } + for route in &mut routed.routes { + route.open = route.to != second; + } + assert!(held(&routed, commons, first), "the road one open route away"); + assert!(!held(&routed, commons, second), "a closed route leads nowhere"); + // The same route read backward: from the road, the commons is one open + // route away. + assert!(held(&routed, first, commons)); + assert!(!held(&routed, second, commons)); + assert!(!held(&routed, first, second), "two routes away is out"); + + // Closed routes carry no focus either way. + for route in &mut routed.routes { + route.open = false; + } + assert!(!held(&routed, commons, first)); + assert!(!held(&routed, first, commons)); + drop(mailbox); + task.await.unwrap(); + } + + /// With one session allowed, the sweep spends it on the dead end the focus + /// names, not the first the kernel lists. + #[tokio::test] + async fn a_bounded_sweep_spends_its_one_session_where_the_focus_is() { + let (_directory, mailbox, task, _commons, roads) = dead_end_world( + crate::tests::stock_weights(), + &["The Unwalked Road", "The Far Road"], + Roots::Commons, + 0, + ) + .await; + let port = Arc::new(SweepPort::new(shed_on_the_named_road(vec![ + ("The Unwalked Road", roads[0]), + ("The Far Road", roads[1]), + ]))); + let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); + let focus = Focus { places: vec![roads[1]], nodes: Vec::new() }; + runner.sweep(pool(2), 1, &focus).await.unwrap(); + assert_eq!(port.calls(), 1); + let snapshot = mailbox.snapshot().await.unwrap(); + assert!(place_labelled(&snapshot, "The Shed on The Far Road").is_some(), "the focused dead end was answered"); + assert!(place_labelled(&snapshot, "The Shed on The Unwalked Road").is_none(), "the other waits for the next sweep"); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + + /// Once the window's allowance refuses a call, the sweep starts no further + /// session: the refusal is the fault the owning flow stops on, not one + /// more session's failure. + #[tokio::test] + async fn a_sweep_stops_starting_sessions_once_the_allowance_refuses() { + let (_directory, mailbox, task, _commons, _roads) = dead_end_world( + crate::tests::stock_weights(), + &["The Unwalked Road", "The Far Road"], + Roots::Commons, + 0, + ) + .await; + let port = Arc::new(SweepPort::new(|_, _| Err(InferenceFault::budget_exhausted()))); + let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); + let outcome = runner.sweep(pool(1), usize::MAX, &Focus::default()).await; + assert!(outcome.is_err(), "the refusal ends the sweep"); + assert_eq!(port.calls(), 1, "a second session started after the allowance refused"); + drop(runner); + drop(mailbox); + task.await.unwrap(); + } + /// Fair claims: whichever entry a bound of one starts first is refused, and /// so is its repair. The second sweep starts the entry nobody has tried, not /// the refused one again, and commits it. @@ -14866,9 +15025,9 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur } })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let first = runner.sweep(pool(2), 1).await.unwrap(); + let first = runner.sweep(pool(2), 1, &Focus::default()).await.unwrap(); assert_eq!((first.started, first.rejected), (1, 1)); - let second = runner.sweep(pool(2), 1).await.unwrap(); + let second = runner.sweep(pool(2), 1, &Focus::default()).await.unwrap(); assert_eq!((second.started, second.committed), (1, 1), "{second:?}"); let snapshot = mailbox.snapshot().await.unwrap(); assert_eq!(snapshot.boundaries.len(), 1, "one entry answered, one still refused"); @@ -14903,9 +15062,9 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur } })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let first = runner.sweep(pool(1), 1).await.unwrap(); + let first = runner.sweep(pool(1), 1, &Focus::default()).await.unwrap(); assert_eq!((first.rejected, first.failed.len()), (1, 0), "{first:?}"); - let second = runner.sweep(pool(1), 1).await.unwrap(); + let second = runner.sweep(pool(1), 1, &Focus::default()).await.unwrap(); assert_eq!(second.committed, 1, "{second:?}"); let repair = wire_of(&port.seen.lock().unwrap()[1]); assert!(repair.contains(REFUSAL_TURN) && repair.contains("dead end"), "{repair}"); @@ -14935,7 +15094,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let (holder, held) = debtor.expect("the fixture's debtor holds a promise"); let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); let prompt = prompt_of(&port.seen.lock().unwrap()[0]); let promise = prompt.lines().find(|line| line.starts_with("Promise:")).expect("a Promise line"); assert!(promise.contains(&holder.label), "{promise}"); @@ -15019,10 +15178,10 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); for _ in 0..crate::elaboration::MAX_REFUSALS { - let report = runner.sweep(pool(1), 1).await.unwrap(); + let report = runner.sweep(pool(1), 1, &Focus::default()).await.unwrap(); assert_eq!(report.rejected, 1, "{report:?}"); } - let last = runner.sweep(pool(1), 1).await.unwrap(); + let last = runner.sweep(pool(1), 1, &Focus::default()).await.unwrap(); assert_eq!(last.abandoned, 1, "{last:?}"); // The stored end is a valid row; the same row with its ending refusal // moved or removed is not. @@ -15047,7 +15206,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur refusals.remove(0); })); let calls = port.calls(); - let after = runner.sweep(pool(1), 1).await.unwrap(); + let after = runner.sweep(pool(1), 1, &Focus::default()).await.unwrap(); assert_eq!((after.claimed, after.started), (0, 0), "{after:?}"); assert_eq!(port.calls(), calls, "an abandoned session ran inference again"); drop(runner); @@ -15078,7 +15237,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); let sweep = tokio::spawn({ let permits = permits.clone(); - async move { runner.sweep(permits, usize::MAX).await } + async move { runner.sweep(permits, usize::MAX, &Focus::default()).await } }); for _ in 0..2 { @@ -15118,7 +15277,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let runner = sweep_runner(&mailbox, port.clone(), store.clone()); let sweep = tokio::spawn({ let permits = permits.clone(); - async move { runner.sweep(permits, usize::MAX).await } + async move { runner.sweep(permits, usize::MAX, &Focus::default()).await } }); store.listed.acquire().await.unwrap().forget(); @@ -15158,7 +15317,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let port = Arc::new(port); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(permits, usize::MAX).await.unwrap(); + runner.sweep(permits, usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 1); assert_eq!(*port.free_while_inferring.lock().unwrap(), vec![1]); assert_eq!(elaboration_commands(store.custody_probe().await.unwrap()), 1); @@ -15194,7 +15353,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(2), usize::MAX).await.unwrap(); + runner.sweep(pool(2), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 1, "the nested boundary was claimed more than once"); assert_eq!(store.work.lock().unwrap().len(), 1); drop(runner); @@ -15220,7 +15379,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur })); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(2), usize::MAX).await.unwrap(); + runner.sweep(pool(2), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 1, "one deficit, one session"); let first: Vec = store.work.lock().unwrap().keys().copied().collect(); assert_eq!(first.len(), 1); @@ -15228,7 +15387,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur assert!(snapshot.subjects.iter().any(|subject| subject.label == "Sere p1")); assert!(snapshot.boundaries.is_empty()); - runner.sweep(pool(2), usize::MAX).await.unwrap(); + runner.sweep(pool(2), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 2, "the second ancestry ran no new session"); let stored = store.work.lock().unwrap(); assert_eq!(stored.len(), 2, "the committed row was adopted"); @@ -15270,7 +15429,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let recording = fresh_store(); let store = ListingProbe::over(recording.clone()); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(permits.clone(), usize::MAX).await.unwrap(); + runner.sweep(permits.clone(), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(store.listings.load(Ordering::SeqCst), 0, "a Draft world's listing was read"); assert_eq!(port.calls(), 0, "a Draft world reached the provider"); assert!(recording.work.lock().unwrap().is_empty(), "a Draft world gained a row"); @@ -15392,7 +15551,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 1, "the uncovered boundary ran no session"); let stored = store.work.lock().unwrap(); assert_eq!(stored.len(), 1); @@ -15425,7 +15584,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur } })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - runner.sweep(pool(2), usize::MAX).await.expect("a retryable fault ended the sweep"); + runner.sweep(pool(2), usize::MAX, &Focus::default()).await.expect("a retryable fault ended the sweep"); assert_eq!(port.calls(), 2); let snapshot = mailbox.snapshot().await.unwrap(); assert!(place_labelled(&snapshot, "The Shed on The Far Road").is_some()); @@ -15459,7 +15618,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let store = fresh_store(); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 2, "the deficit and the uncovered boundary are two sessions"); let stored = store.work.lock().unwrap(); let sessions: Vec = stored.values().map(recorded_session).collect(); @@ -15505,7 +15664,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur } })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - runner.sweep(pool(1), usize::MAX).await.expect("a retryable fault ended the sweep"); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.expect("a retryable fault ended the sweep"); assert_eq!(port.calls(), 2, "no session started after a retryable fault"); let snapshot = mailbox.snapshot().await.unwrap(); assert_eq!(snapshot.boundaries.len(), 1, "the second session did not commit"); @@ -15568,7 +15727,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur calls: std::sync::atomic::AtomicUsize::new(0), }); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let sweep = tokio::spawn(async move { runner.sweep(pool(2), usize::MAX).await }); + let sweep = tokio::spawn(async move { runner.sweep(pool(2), usize::MAX, &Focus::default()).await }); port.faulted.acquire().await.unwrap().forget(); port.release.add_permits(1); let result = sweep.await.unwrap(); @@ -15604,7 +15763,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur )) })); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let Err(error) = runner.sweep(pool(1), usize::MAX).await else { + let Err(error) = runner.sweep(pool(1), usize::MAX, &Focus::default()).await else { panic!("a quarantine-class fault did not end the sweep with an error"); }; assert!(error.requires_quarantine(), "{error:?}"); @@ -15686,7 +15845,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let sweep = tokio::spawn({ let runner = runner.clone(); let permits = permits.clone(); - async move { runner.sweep(permits, usize::MAX).await } + async move { runner.sweep(permits, usize::MAX, &Focus::default()).await } }); port.panicking.acquire().await.unwrap().forget(); port.release.add_permits(1); @@ -15704,7 +15863,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur assert_eq!(port.calls.load(Ordering::SeqCst), 2); assert_eq!(permits.available_permits(), 2, "a permit outlived its session"); - runner.sweep(permits.clone(), usize::MAX).await.expect("the sweep after a panic did not run"); + runner.sweep(permits.clone(), usize::MAX, &Focus::default()).await.expect("the sweep after a panic did not run"); assert_eq!(port.calls.load(Ordering::SeqCst), 3); let snapshot = mailbox.snapshot().await.unwrap(); assert!(snapshot.boundaries.is_empty()); @@ -15733,7 +15892,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur })); let permits = pool(1); let runner = sweep_runner(&mailbox, port.clone(), fresh_store()); - let Err(error) = runner.sweep(permits.clone(), usize::MAX).await else { + let Err(error) = runner.sweep(permits.clone(), usize::MAX, &Focus::default()).await else { panic!("a panicking session did not end the sweep with an error"); }; assert!(error.requires_quarantine(), "{error:?}"); @@ -15766,7 +15925,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur CultCacheControllerWorkStore::open(directory.path().join("controller-work.cc")).unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); let (first_id, refused) = { let journal = store.journal.lock().unwrap(); assert_eq!(journal.work.len(), 1); @@ -15787,7 +15946,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur "the tick did not move the ancestry" ); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 2, "the refused round was repeated or skipped"); { let journal = store.journal.lock().unwrap(); @@ -15843,7 +16002,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur CultCacheControllerWorkStore::open(directory.path().join("controller-work.cc")).unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); let command_id = { let journal = store.journal.lock().unwrap(); assert_eq!(journal.work.len(), 1); @@ -15871,7 +16030,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur assert_eq!(after.revision, before.revision + 2); assert_eq!(after.boundaries, before.boundaries, "the commits moved the boundary"); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 2); { let journal = store.journal.lock().unwrap(); @@ -15908,7 +16067,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur ); let refusing = Arc::new(SweepPort::new(|call, _| refused_round(call))); let runner = sweep_runner(&mailbox, refusing.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); drop(runner); let ControllerWork::Elaboration(ElaborationCheckpoint::ElaboratorInFlight { command_id, @@ -15951,7 +16110,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let idle = Arc::new(SweepPort::new(|call, _| idle_round(call))); let runner = sweep_runner(&mailbox, idle.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(idle.calls(), 0, "the ready row ran a new inference"); let snapshot = mailbox.snapshot().await.unwrap(); assert!(snapshot.boundaries.is_empty(), "the ready row was not submitted"); @@ -16046,13 +16205,13 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur CultCacheControllerWorkStore::open(directory.path().join("controller-work.cc")).unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - let mut results = vec![runner.sweep(pool(1), usize::MAX).await]; + let mut results = vec![runner.sweep(pool(1), usize::MAX, &Focus::default()).await]; for tick in 1..=5 { mailbox .submit_clock(CommandId::new(), TickMinutes::new(60).unwrap()) .await .unwrap(); - results.push(runner.sweep(pool(1), usize::MAX).await); + results.push(runner.sweep(pool(1), usize::MAX, &Focus::default()).await); assert_eq!(port.calls(), tick + 1, "tick {tick}: one inference per sweep"); // Past `MAX_REFUSALS` the session ends and its deficit id, which // moves with the ancestry, starts a new one; rows may grow then, @@ -16123,7 +16282,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let other_id = *store.journal.lock().unwrap().work.keys().next().unwrap(); let other_bytes = row_payload(&store, other_id).unwrap(); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 2, "the entry built no fresh session"); let journal = store.journal.lock().unwrap(); assert_eq!(journal.work.len(), 2, "the other jurisdiction's row was adopted"); @@ -16156,7 +16315,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur Arc::new(SweepPort::new(|call, _| refused_round(call))), scratch.clone(), ); - foreign_runner.sweep(pool(1), usize::MAX).await.unwrap(); + foreign_runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); drop(foreign_runner); drop(foreign_mailbox); foreign_task.await.unwrap(); @@ -16214,7 +16373,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur let foreign_bytes = row_payload(&store, command_id).unwrap(); let port = Arc::new(SweepPort::new(|call, _| idle_round(call))); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 1, "the entry built no fresh session"); assert_eq!(store.journal.lock().unwrap().work.len(), 2, "the foreign row was adopted"); assert_eq!( @@ -16237,7 +16396,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur .unwrap(), ); let runner = sweep_runner(&mailbox, port.clone(), store.clone()); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); let finished = { let journal = store.journal.lock().unwrap(); let (id, work) = journal.work.iter().next().unwrap(); @@ -16252,7 +16411,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur .submit_clock(CommandId::new(), TickMinutes::new(60).unwrap()) .await .unwrap(); - runner.sweep(pool(1), usize::MAX).await.unwrap(); + runner.sweep(pool(1), usize::MAX, &Focus::default()).await.unwrap(); assert_eq!(port.calls(), 2, "the finished row was adopted in place of a fresh session"); assert_eq!(store.journal.lock().unwrap().work.len(), 2); assert_eq!(row_payload(&store, finished).unwrap(), finished_bytes); @@ -18062,7 +18221,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur fresh_store(), Arc::new(NullEvidenceSource), ); - assert_eq!(runner.sweep(pool(1), 8).await.unwrap(), SeedOutcome::Clean); + assert_eq!(runner.sweep(pool(1), 8, &Focus::default()).await.unwrap(), SeedOutcome::Clean); assert_eq!( root_deficit(&fixture.mailbox.snapshot().await.unwrap(), fixture.sere), 0 @@ -18099,7 +18258,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur fresh_store(), Arc::new(NullEvidenceSource), ); - assert_eq!(runner.sweep(pool(1), 4).await.unwrap(), SeedOutcome::NoProgress); + assert_eq!(runner.sweep(pool(1), 4, &Focus::default()).await.unwrap(), SeedOutcome::NoProgress); assert_eq!( scripted.seen.lock().unwrap().len(), 1, @@ -18566,7 +18725,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur models().elaborator, None, ); - assert_eq!(runner.sweep(pool(1), 3).await.unwrap(), SeedOutcome::Clean); + assert_eq!(runner.sweep(pool(1), 3, &Focus::default()).await.unwrap(), SeedOutcome::Clean); let seeded = mailbox.snapshot().await.unwrap(); assert!( seeded.scale_deficit.iter().all(|row| row.deficit == 0), @@ -19177,7 +19336,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur store.clone(), Arc::new(NullEvidenceSource), ); - assert_eq!(resumed.sweep(pool(1), 4).await.unwrap(), SeedOutcome::NoPatch); + assert_eq!(resumed.sweep(pool(1), 4, &Focus::default()).await.unwrap(), SeedOutcome::NoPatch); assert_eq!( scripted.seen.lock().unwrap().len(), SEED_ROUND_BUDGET, @@ -19257,7 +19416,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur store.clone(), Arc::new(NullEvidenceSource), ); - assert_eq!(runner.sweep(pool(1), 4).await.unwrap(), SeedOutcome::Clean); + assert_eq!(runner.sweep(pool(1), 4, &Focus::default()).await.unwrap(), SeedOutcome::Clean); let ids: BTreeSet = store.work.lock().unwrap().keys().copied().collect(); assert_eq!(ids.len(), 2, "two landed sessions shared one derived id"); @@ -19420,7 +19579,7 @@ assert!(projector_text.contains("I ask about the hinge."), "the player's own tur fresh_store(), Arc::new(NullEvidenceSource), ); - assert_eq!(runner.sweep(pool(1), 4).await.unwrap(), SeedOutcome::Clean); + assert_eq!(runner.sweep(pool(1), 4, &Focus::default()).await.unwrap(), SeedOutcome::Clean); drop(runner); let authenticated = diff --git a/crates/ghostlight/src/elaboration.rs b/crates/ghostlight/src/elaboration.rs index 12498f4..222f84c 100644 --- a/crates/ghostlight/src/elaboration.rs +++ b/crates/ghostlight/src/elaboration.rs @@ -32,6 +32,7 @@ use super::{ JurisdictionKey, KernelError, MailboxError, Mismatch, PatchAnswer, ScaleDeficitRow, SeedPort, SubjectId, SubjectKind, WorldId, WorldPatch, WorldPhase, WorldSnapshot, }; +use super::wave::Focus; use async_trait::async_trait; use model_connector::InputItem; use serde::{Deserialize, Serialize}; @@ -761,6 +762,10 @@ impl ElaborationRunner { /// sessions start, in claim order: the rest of the demand waits for the /// next sweep. The library holds no concurrency or spend number of its own. /// + /// `focus` orders the claim set: demand at a focus place is claimed first, + /// so a bounded sweep spends on what the player is looking at before the + /// rest. The focus's nodes name no place and are not read here. + /// /// The claim set is the only set of sessions alive only while one sweep /// runs at a time. The caller's loop awaits each sweep; nothing here guards /// against overlap. @@ -774,6 +779,7 @@ impl ElaborationRunner { &self, permits: Arc, max_sessions: usize, + focus: &Focus, ) -> Result { let mut report = SweepReport::default(); let snapshot = self.mailbox.snapshot().await.map_err(snapshot_error)?; @@ -781,7 +787,12 @@ impl ElaborationRunner { return Ok(report); } let in_flight = self.work.elaboration_in_flight().await?; - let entries = demand_entries(&snapshot, &sweep_jurisdictions(&snapshot), &in_flight)?; + let entries = demand_entries( + &snapshot, + &sweep_jurisdictions(&snapshot), + &in_flight, + focus, + )?; let entries = self.fair_claims(entries, &in_flight).await?; report.claimed = entries.len(); let snapshot = Arc::new(snapshot); @@ -896,7 +907,7 @@ impl ElaborationRunner { return Ok(None); } let in_flight = self.work.elaboration_in_flight().await?; - let Some((command_id, session)) = demand_entries(&snapshot, &[jurisdiction], &in_flight)? + let Some((command_id, session)) = demand_entries(&snapshot, &[jurisdiction], &in_flight, &Focus::default())? .into_iter() .next() else { @@ -955,6 +966,10 @@ fn sweep_jurisdictions(snapshot: &WorldSnapshot) -> Vec { /// and its command id are adopted and nothing is drawn. Only an unmatched /// entry derives an id and draws a lens. /// +/// The jurisdiction order, then a stable partition: an entry whose place is in +/// focus (see `in_focus`) first, the rest after, each class in the order above. +/// An empty focus leaves the order untouched. +/// /// A boundary under nested roots is covered by each of them, so an answer /// already claimed is not claimed again, and no command id is claimed twice. /// The stop condition is "no open boundary and no deficit", plus the one other @@ -964,6 +979,7 @@ fn demand_entries( snapshot: &WorldSnapshot, jurisdictions: &[JurisdictionKey], in_flight: &[(CommandId, ElaboratorSession)], + focus: &Focus, ) -> Result, ControllerError> { let ancestry = snapshot.last_commit_digest.clone().unwrap_or_default(); let mut claimed_ids = BTreeSet::new(); @@ -982,7 +998,58 @@ fn demand_entries( } } } - Ok(entries) + let (focused, rest): (Vec<_>, Vec<_>) = entries.into_iter().partition(|(_, session)| { + answer_place(snapshot, &session.answer).is_some_and(|place| in_focus(snapshot, focus, place)) + }); + Ok(focused.into_iter().chain(rest).collect()) +} + +/// What a sweep over `snapshot` would claim, in claim order, before fair +/// claims reorders by what sessions already tried. Tests read the order here. +#[cfg(test)] +pub(super) fn claim_order(snapshot: &WorldSnapshot, focus: &Focus) -> Vec { + demand_entries(snapshot, &sweep_jurisdictions(snapshot), &[], focus) + .expect("the claim set derives") + .into_iter() + .map(|(_, session)| session.answer) + .collect() +} + +/// The place an answer's demand sits at: a boundary's own place (a +/// destination's, or the position of the subject it names), a deficit's +/// jurisdiction root. Demand with no place, the uncovered residual, sits +/// nowhere and is never in focus. +fn answer_place(snapshot: &WorldSnapshot, answer: &PatchAnswer) -> Option { + let subject_place = |subject: SubjectId| { + snapshot + .subjects + .iter() + .find(|row| row.id == subject) + .and_then(|row| row.position) + }; + match answer { + PatchAnswer::Deficit(JurisdictionKey::PlaceSubtree(root)) => Some(*root), + PatchAnswer::Deficit(JurisdictionKey::Uncovered) => None, + PatchAnswer::Boundary(CausalBoundary::UnelaboratedDestination { place, .. }) => Some(*place), + PatchAnswer::Boundary( + CausalBoundary::MissingStructure { subject, .. } + | CausalBoundary::PolityInCausalRange { subject, .. } + | CausalBoundary::IndividuationRequired { population: subject, .. }, + ) => subject_place(*subject), + } +} + +/// A place is in focus when it is a focus place, inside one, or one open route +/// from one, the route read either way: the player's exits and the way back. +pub(super) fn in_focus(snapshot: &WorldSnapshot, focus: &Focus, place: EntityId) -> bool { + focus.places.iter().any(|&root| { + snapshot_covers_place(snapshot, root, place) + || snapshot.routes.iter().any(|route| { + route.open + && ((route.from == root && route.to == place) + || (route.to == root && route.from == place)) + }) + }) } /// The in-flight row that answers this entry, if any. The listing is least diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index 129beb6..fa878cd 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -1344,10 +1344,16 @@ pub struct WorldSnapshot { } impl WorldSnapshot { + /// The place a subject stands in, for the owner's own surfaces; no + /// subject-facing lane reads this. + pub fn place_of(&self, subject: SubjectId) -> Option { + self.subjects.iter().find(|candidate| candidate.id == subject)?.position + } + /// The label of the place a subject stands in, for the owner's own /// surfaces and tests; no subject-facing lane reads this. pub fn standing_place(&self, subject: SubjectId) -> Option<&str> { - let position = self.subjects.iter().find(|candidate| candidate.id == subject)?.position?; + let position = self.place_of(subject)?; self.places.iter().find(|place| place.id == position).map(|place| place.label.as_str()) }