diff --git a/crates/ghostlight-dungeon/src/knobs.rs b/crates/ghostlight-dungeon/src/knobs.rs index adc918c..b288075 100644 --- a/crates/ghostlight-dungeon/src/knobs.rs +++ b/crates/ghostlight-dungeon/src/knobs.rs @@ -46,6 +46,11 @@ pub(crate) enum Target { } impl Target { + /// What the world calls the target, `-` when it no longer holds it. + pub(crate) fn label(&self, world: &WorldSnapshot) -> String { + target_label(self, world) + } + fn text(&self) -> String { match self { Self::Place(id) => id_text(id), @@ -311,7 +316,7 @@ pub(crate) fn tune( return Err(format!("{} focus entries is refused: {MOST_ENTRIES} at most", next.focus.len())); } next.gestalt().map_err(|error| error.to_string())?; - Ok((next, format!("tuned: {}. Allowances apply to the next window; a window already open keeps its own.", changed.join("; ")))) + Ok((next, format!("tuned: {}. Allowances bind the window already open too: a lane held above its new allowance is exhausted.", changed.join("; ")))) } /// `run_world`'s arguments: the targets it names, resolved against the world. @@ -401,7 +406,7 @@ pub(crate) fn gears_view( out } -fn target_label(target: &Target, world: &WorldSnapshot) -> String { +pub(crate) fn target_label(target: &Target, world: &WorldSnapshot) -> String { match target { Target::Place(id) => world.places.iter().find(|place| place.id == *id).map(|place| place.label.clone()), Target::Institution(id) => world.subjects.iter().find(|subject| subject.id == *id).map(|subject| subject.label.clone()), diff --git a/crates/ghostlight-dungeon/src/timelines.rs b/crates/ghostlight-dungeon/src/timelines.rs index e7c2b44..900e761 100644 --- a/crates/ghostlight-dungeon/src/timelines.rs +++ b/crates/ghostlight-dungeon/src/timelines.rs @@ -56,7 +56,9 @@ impl TimelineHost { /// through, reserving each call in the window's ledger first. The window's /// cap is its allowances together. A window at the same revision is the same /// ledger, so a trigger that finds nothing changed spends no new allowance, - /// and a wave resumed after a restart reopens the ledger it opened in. + /// and a wave resumed after a restart reopens the ledger it opened in. The + /// caller passes the knobs' allowances every time and the ledger follows them, + /// keeping its spend: a tune binds the window already open. /// `world` is the world the window is opened over now. pub(crate) fn window( &self, @@ -65,7 +67,7 @@ impl TimelineHost { allowances: LaneTokens, ) -> Result { let run = RunId::new(&format!("window-{revision}"))?; - RecordingInferencePort::open( + RecordingInferencePort::open_following( self.inference.clone(), self.background.clone(), run, diff --git a/crates/ghostlight-dungeon/src/waves.rs b/crates/ghostlight-dungeon/src/waves.rs index a430a76..e0d2eae 100644 --- a/crates/ghostlight-dungeon/src/waves.rs +++ b/crates/ghostlight-dungeon/src/waves.rs @@ -65,6 +65,8 @@ pub(crate) struct WaveReport { pub(crate) waiting: Vec, /// True when the window's wave allowance ran out before the last cell. pub(crate) out_of_allowance: bool, + /// Asked-for targets that had no turn to take. + pub(crate) nothing_stirred: Vec, } /// One wave, document `ghostlight.dungeon_wave.v2`, keyed by the `seq` of the @@ -78,13 +80,16 @@ pub(crate) struct WaveRecord { pub(crate) revision: u64, pub(crate) opened_now: u64, pub(crate) knobs: RecordedKnobs, - /// The window allowances the wave opened under: the ledger it finishes in - /// is reopened with these, whatever the DM has tuned since. + /// The window allowances in force when the wave planned, kept as the + /// record; the window the wave runs in follows the knobs as they stand. pub(crate) allowances: LaneTokens, /// The DM's focus entries holding when the wave planned, and the nodes the /// DM asked to run in it. pub(crate) focus: Vec, pub(crate) forced: Vec, + /// Labels of the asked-for targets no one had a turn to take for, frozen + /// with the plan: the DM's next view says nothing stirred there. + pub(crate) quiet: Vec, pub(crate) cells: Vec, /// What the plan left out, frozen with the cells. pub(crate) deferred: Vec<(NodeId, Deferral)>, @@ -222,6 +227,18 @@ pub(crate) fn offscreen_view(waves: &[WaveRecord]) -> String { } } let mut out = String::new(); + let mut quiet: Vec<&str> = Vec::new(); + for label in reports.iter().flat_map(|report| report.nothing_stirred.iter()) { + if !quiet.contains(&label.as_str()) { + quiet.push(label); + } + } + for label in quiet { + out.push_str(&format!("Nothing stirred at {label}: you asked for its turn and no one there had one to take.\n")); + } + if !out.is_empty() { + out.push('\n'); + } if !lines.is_empty() { out.push_str("Off-screen since your last turn (the world beyond the room moved; the player knows none of it unless it reaches them):\n"); for line in &lines { @@ -331,7 +348,19 @@ async fn plan(host: &TimelineHost, turn_seq: u64) -> anyhow::Result = dm + .forced + .iter() + .filter(|target| { + target.node(&hierarchy).is_none_or(|node| { + !wave.turns.iter().any(|turn| turn.node == node) && !wave.deferred.iter().any(|(id, _)| *id == node) + }) + }) + .map(|target| target.label(&world)) + .collect(); + if cells.is_empty() && quiet.is_empty() { return Ok(None); } Ok(Some(WaveRecord { @@ -342,6 +371,7 @@ async fn plan(host: &TimelineHost, turn_seq: u64) -> anyhow::Result anyhow::Result anyhow::Result { let world = host.world.snapshot().await?; - let window = Arc::new(host.window(record.revision, &world, record.allowances)?); + let window = Arc::new(host.window(record.revision, &world, host.knobs.lock().await.current().allowances)?); let port: Arc = window.clone(); let runner = host.controllers.through(port); let ordinal = TickIndex(record.turn_seq); @@ -388,6 +418,7 @@ async fn finish(host: &TimelineHost, record: WaveRecord) -> anyhow::Result nodes, waiting, out_of_allowance: outcome.stop == Some(WaveStop::Budget), + nothing_stirred: record.quiet.clone(), }; host.waves.lock().await.close_wave(record.turn_seq, report)?; Ok(true) @@ -759,6 +790,7 @@ pub(crate) mod tests { allowances: DmKnobs::default().allowances, focus: Vec::new(), forced: Vec::new(), + quiet: Vec::new(), cells: Vec::new(), deferred: Vec::new(), report, @@ -776,6 +808,7 @@ pub(crate) mod tests { NodeWaiting { label: "Hamlet".into(), reason: Deferral::NotDue }, ], out_of_allowance: false, + nothing_stirred: Vec::new(), }; let view = offscreen_view(&[record(1, Some(report))]); assert!(view.contains("Off-screen since your last turn")); @@ -797,11 +830,11 @@ pub(crate) mod tests { for seq in [1, 2] { store.open_wave(record(seq, None)).unwrap(); } - store.close_wave(1, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false }).unwrap(); + store.close_wave(1, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() }).unwrap(); assert!(store.take_unseen("first").unwrap().iter().map(|wave| wave.turn_seq).eq([1]), "an open wave is not carried"); assert!(store.take_unseen("first").unwrap().iter().map(|wave| wave.turn_seq).eq([1]), "asking again answers the same"); assert!(store.take_unseen("second").unwrap().is_empty(), "a taken wave is not carried twice"); - store.close_wave(2, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false }).unwrap(); + store.close_wave(2, WaveReport { nodes: Vec::new(), waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() }).unwrap(); assert!(store.take_unseen("second").unwrap().iter().map(|wave| wave.turn_seq).eq([2])); } @@ -815,7 +848,7 @@ pub(crate) mod tests { let mut store = WaveStore::open(&path).unwrap(); store.open_wave(record(3, None)).unwrap(); store.open_wave(record(4, None)).unwrap(); - store.close_wave(4, WaveReport { nodes: vec![moved("Guild", &["acts"])], waiting: Vec::new(), out_of_allowance: false }).unwrap(); + store.close_wave(4, WaveReport { nodes: vec![moved("Guild", &["acts"])], waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() }).unwrap(); store.take_unseen("viewer").unwrap(); } let store = WaveStore::open(&path).unwrap(); @@ -831,7 +864,7 @@ pub(crate) mod tests { let long = "x".repeat(VIEW_LINE_CHARS + 50); let many: Vec = (0..VIEW_ACTS + 3).map(|n| format!("act {n} {long}")).collect(); let acts: Vec<&str> = many.iter().map(String::as_str).collect(); - let report = WaveReport { nodes: vec![moved("Guild", &acts)], waiting: Vec::new(), out_of_allowance: false }; + let report = WaveReport { nodes: vec![moved("Guild", &acts)], waiting: Vec::new(), out_of_allowance: false, nothing_stirred: Vec::new() }; let view = offscreen_view(&[record(1, Some(report))]); assert!(view.contains("- and 3 more acts the world holds"), "{view}"); assert!(!view.contains(&long), "each act keeps its first {VIEW_LINE_CHARS} characters"); @@ -864,6 +897,7 @@ pub(crate) mod tests { nodes: Vec::new(), waiting: vec![NodeWaiting { label: "Crown".into(), reason: Deferral::OverBound }], out_of_allowance: false, + nothing_stirred: Vec::new(), }; waves.close_wave(2, report).unwrap(); } @@ -1051,7 +1085,44 @@ pub(crate) mod tests { advance(&host, 400).await; run_waves(&host, 1).await; assert!(port.seen_requests().is_empty(), "the Warden stands in the player's room"); - assert!(wave_of(&host, 1).await.is_none()); + let wave = wave_of(&host, 1).await.expect("an asked-for target nobody could act for is still told"); + let report = wave.report.expect("closed"); + assert!(report.nodes.is_empty() && wave.cells.is_empty()); + assert_eq!(report.nothing_stirred, vec!["The Commons".to_owned()]); + assert!(host.knobs.lock().await.current().forced.is_empty(), "the wave took the request"); + let view = offscreen_view(&[wave_of(&host, 1).await.unwrap()]); + assert!(view.contains("Nothing stirred at The Commons"), "{view}"); + assert!(!view.contains("Off-screen since"), "{view}"); + } + + /// A tune made while the window at the current revision is open binds it: + /// the allowance that refused a wave is raised and the next wave at the + /// same revision runs, spending what the ledger already held on top. + #[tokio::test] + async fn an_allowance_tuned_mid_window_binds_the_open_window() { + let fixture = Fixture::new().await; + let port = ScriptedPort::new(vec![speaks("w0", "The gate holds.")]); + let (timelines, _stopped) = fixture.open(port.clone()); + let host = timelines.host(&fixture.id).await.unwrap(); + allow(&host, |allowances| allowances.wave = 0).await; + advance(&host, 400).await; + run_waves(&host, 1).await; + let refused = wave_of(&host, 1).await.unwrap().report.unwrap(); + assert!(refused.out_of_allowance && refused.nodes.is_empty(), "{refused:?}"); + let revision = wave_of(&host, 1).await.unwrap().revision; + allow(&host, |allowances| allowances.wave = 200_000).await; + run_waves(&host, 2).await; + let wave = wave_of(&host, 2).await.expect("the Warden was still due"); + assert_eq!(wave.revision, revision, "the same world revision, so the same open window"); + let report = wave.report.unwrap(); + assert!(!report.out_of_allowance && report.nodes.len() == 1, "{report:?}"); + let window = ghostlight::RunId::new(&format!("window-{revision}")).unwrap(); + assert!(host.background.lane_spent(&window).unwrap().wave > 0); + // Lowered under what the window holds, the lane is exhausted, not broken. + allow(&host, |allowances| allowances.wave = 1).await; + let world = host.world.snapshot().await.unwrap(); + let window = host.window(revision, &world, host.knobs.lock().await.current().allowances); + assert!(window.is_ok(), "a lowered allowance opens the window"); } /// A port that holds the operational agent's call until the test lets it diff --git a/crates/ghostlight/src/verse/calls.rs b/crates/ghostlight/src/verse/calls.rs index da654f8..1c76d0e 100644 --- a/crates/ghostlight/src/verse/calls.rs +++ b/crates/ghostlight/src/verse/calls.rs @@ -469,18 +469,26 @@ impl CallRecordStore { /// The first claim of a run writes its ledger: the cap it is opened under /// the lane allowances, and the world it starts from. A later claim must name /// the same cap and allowances; the start is not compared, because a resumed world has moved on. + /// With `follow`, a ledger already begun takes the cap and allowances named + /// here in place of its own, its spend kept: a caller whose limits change + /// while a run is open (the Dungeon's tuned allowances) owns them, and a + /// limit below what is already held only exhausts the lane. fn claim( &self, run: &RunId, cap: u64, allowances: LaneTokens, start: &RunStart, + follow: bool, ) -> Result<(), CallRecordError> { let mut state = self.lock()?; if !state.owned.insert(run.as_str().to_owned()) { return Err(CallRecordError::RunInUse); } - let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.as_ref()) { + let begun = match state.runs.get(run.as_str()).and_then(|t| t.ledger.clone()) { + Some(ledger) if follow && (ledger.cap != cap || ledger.allowances != allowances) => { + Self::write_ledger(&mut state, RunLedger { cap, allowances, ..ledger }) + } Some(ledger) if ledger.cap != cap => Err(CallRecordError::RunMismatch(RunField::Cap)), Some(ledger) if ledger.allowances != allowances => { Err(CallRecordError::RunMismatch(RunField::Allowances)) @@ -680,14 +688,24 @@ impl RecordingInferencePort { allowances: LaneTokens, start: &RunStart, ) -> Result { - store.claim(&run, cap_tokens, allowances, start)?; - Ok(Self { - inner, - store, - run, - cap: cap_tokens, - allowances, - }) + store.claim(&run, cap_tokens, allowances, start, false)?; + Ok(Self { inner, store, run, cap: cap_tokens, allowances }) + } + + /// `open`, except that a run already begun follows the cap and allowances + /// given here instead of refusing them: its ledger takes them, the spend + /// already held stays, and a lane whose allowance now sits below its spend + /// refuses further calls as exhausted. + pub fn open_following( + inner: Arc, + store: Arc, + run: RunId, + cap_tokens: u64, + allowances: LaneTokens, + start: &RunStart, + ) -> Result { + store.claim(&run, cap_tokens, allowances, start, true)?; + Ok(Self { inner, store, run, cap: cap_tokens, allowances }) } /// The run this port records. diff --git a/crates/ghostlight/src/verse/calls/tests.rs b/crates/ghostlight/src/verse/calls/tests.rs index dd640eb..3e0f103 100644 --- a/crates/ghostlight/src/verse/calls/tests.rs +++ b/crates/ghostlight/src/verse/calls/tests.rs @@ -527,6 +527,38 @@ async fn one_run_has_one_ledger_and_one_owner() { assert_eq!(inner.calls(), 1); } +#[tokio::test] +async fn a_following_open_takes_new_limits_and_keeps_the_spend() { + let directory = tempfile::tempdir().unwrap(); + let (store, _) = store_in(&directory); + let prepared = prepared_for("follow", 1_200); + let bound = bound_of(&prepared); + let inner = ScriptedPort::new(vec![Ok(reply("a", "r1")), Ok(reply("b", "r2")), Ok(reply("c", "r3"))]); + let run = RunId::new("run-follow").unwrap(); + let open = |cap: u64, follow: bool| { + let open = if follow { RecordingInferencePort::open_following } else { RecordingInferencePort::open }; + open(inner.clone(), store.clone(), run.clone(), cap, lanes(cap), &start()) + }; + let first = open(bound, false).unwrap(); + first.infer(prepared.clone()).await.unwrap(); + first.infer(prepared.clone()).await.expect_err("the one call the limits allowed was made"); + drop(first); + assert_eq!(open(bound * 2, false).err(), Some(CallRecordError::RunMismatch(RunField::Cap)), "a plain reopen still refuses other limits"); + // Raised: the open ledger takes the new limits and the call that was refused runs. + let raised = open(bound * 2, true).unwrap(); + assert_eq!(raised.spent(), bound, "the spend is kept"); + raised.infer(prepared.clone()).await.unwrap(); + drop(raised); + // Lowered below what is already held: the open succeeds and the lane is exhausted. + let lowered = open(bound / 2, true).unwrap(); + assert_eq!(lowered.spent(), bound * 2); + lowered.infer(prepared.clone()).await.expect_err("the lane is exhausted"); + assert_eq!(inner.calls(), 2); + drop(lowered); + // The limits the ledger now holds are the followed ones: a plain open of them is accepted. + drop(open(bound / 2, false).unwrap()); +} + #[tokio::test] async fn usage_over_the_bound_is_charged_in_full_and_faults_the_call() { let directory = tempfile::tempdir().unwrap(); diff --git a/docs/targets/multiresolution-gestalt.md b/docs/targets/multiresolution-gestalt.md index cf07d08..cd94a82 100644 --- a/docs/targets/multiresolution-gestalt.md +++ b/docs/targets/multiresolution-gestalt.md @@ -368,8 +368,8 @@ four-session sweep; no cost is measured yet). `default_knobs`, deleted; `Scale::sweep_permits` stays as the concurrency bound. The wave, the run-ahead sweep and the opening view read the document, and each wave (`ghostlight.dungeon_wave.v2`) records the knobs, allowances, DM focus and -forced nodes it planned under. A resumed wave reopens its ledger with the -allowances it opened with. +forced nodes it planned under; the window it runs in follows the knobs as they +stand. The DM turns them with two tools. `tune` sets bands (1 to 8 periods of 1 to 525600 minutes), depth (1 to 8), `max_node_turns` (1 to 32), the two lane @@ -384,8 +384,11 @@ every other node, within the wave allowance (a node past it is reported waiting); that wave takes the request whether or not it ran. The opening view prints the knobs, the focus path by label, the DM's leases and queued nodes, and the average tokens a node turn has cost in each band from the closed waves. -An allowance change applies from the next window: a window already open at the -current revision keeps the allowances it opened with. +The knobs are the authority over a window's limits: a window already open at +the current revision follows a tuned allowance (`open_following`), keeps its +spend, and a lane held above a lowered allowance is exhausted, not an error. +A `run_world` target with no one to take a turn is frozen into its wave and the +next view says "nothing stirred" at it. A wave gives no turn to a subject standing in the player's place: the room is the DM's `react`. The DM's focus on an institution opens its node for waves;