Close pass 7's four Soul follow-ups

- verify_state_shape now enforces the 1..=MAX_ROUTE_COST span bound on a
  routine's period, the same bound TickMinutes::new enforces, closing the
  serde-transparent forgery gap. Inverted and renamed the falsification test
  to soul_a_zero_period_is_refused_by_the_shape_check.
- Extracted advance_world_clock's per-tick body into submit_clock_tick, a
  narrow port over submit_clock, and added a test that captures the
  submitted span without driving tokio's timer.
- Removed the dead top-level PreconditionRef/PressureSourceRef imports in
  world/mod.rs; clock_tests keeps its own.
- Renamed JurisdictionKey::Unplaced to Uncovered and fixed the scale deficit
  to count a positioned subject under no jurisdiction root in that row
  instead of dropping it, with a test asserting the row counts sum to the
  subject count.

cargo test -p ghostlight-dungeon --bin ghostlight-dungeon world:: -> 217 passed
cargo test -p ghostlight-dungeon --bin ghostlight-dungeon -> 251 passed
cargo fmt -p ghostlight-dungeon -- --check -> clean
This commit is contained in:
Meta Vens 2026-09-05 00:37:55 +02:00
commit 5874fc232a
4 changed files with 170 additions and 27 deletions

View file

@ -1446,8 +1446,23 @@ async fn maintain_mesh_projection(state: AppState) {
const CLOCK_TICK_INTERVAL: Duration = Duration::from_secs(60);
const CLOCK_TICK_MINUTES: u32 = 60;
/// The world clock's only driver. A refused tick — no world yet, a Draft world,
/// a stale revision — is logged and skipped: the next tick re-reads live state.
/// One tick's work, apart from the wall clock that decides when to run it: ask
/// `submit` for the outcome of one `minutes`-wide `AdvanceTime`, and log
/// (never propagate) a refusal — no world yet, a Draft world, a stale
/// revision. `submit` is a narrow port over [`WorldMailbox::submit_clock`], so
/// a test can capture what one tick submits without driving tokio's timer.
async fn submit_clock_tick<F, Fut>(minutes: TickMinutes, submit: F)
where
F: FnOnce(CommandId, TickMinutes) -> Fut,
Fut: std::future::Future<Output = Result<SubmitReceipt, MailboxError>>,
{
match submit(CommandId::new(), minutes).await {
Ok(_) => {}
Err(error) => tracing::debug!(%error, "world clock tick was not admitted"),
}
}
/// The world clock's only driver.
async fn advance_world_clock(state: AppState) {
let Some(minutes) = TickMinutes::new(CLOCK_TICK_MINUTES) else {
tracing::error!("the configured clock tick is outside one year of minutes");
@ -1458,10 +1473,7 @@ async fn advance_world_clock(state: AppState) {
interval.tick().await;
loop {
interval.tick().await;
match state.world.submit_clock(CommandId::new(), minutes).await {
Ok(_) => {}
Err(error) => tracing::debug!(%error, "world clock tick was not admitted"),
}
submit_clock_tick(minutes, |id, minutes| state.world.submit_clock(id, minutes)).await;
}
}
@ -2336,4 +2348,25 @@ mod tests {
.contains("payload may not supply caller authority")
);
}
/// One tick submits exactly the configured span, and nothing else: the
/// captured argument is the `TickMinutes` `submit_clock_tick` was given,
/// with no measured elapsed duration — no `Duration`, no `Instant` — ever
/// constructed along the way. Driven through the narrow port rather than
/// `advance_world_clock` itself, so the assertion holds without waiting on
/// tokio's timer.
#[tokio::test]
async fn advance_world_clock_tick_submits_the_configured_span_and_nothing_measured() {
let minutes = TickMinutes::new(CLOCK_TICK_MINUTES).expect("a valid configured tick");
let captured: std::sync::Arc<std::sync::Mutex<Option<TickMinutes>>> =
std::sync::Arc::new(std::sync::Mutex::new(None));
let sink = captured.clone();
submit_clock_tick(minutes, move |_id, submitted| {
*sink.lock().unwrap() = Some(submitted);
std::future::ready(Ok(SubmitReceipt::AlreadyApplied(controller_commit())))
})
.await;
let submitted = captured.lock().unwrap().expect("the tick submitted a span");
assert_eq!(submitted.minutes(), CLOCK_TICK_MINUTES);
}
}

View file

@ -642,6 +642,9 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> {
for (subject_id, held) in &state.commitments {
let commitment_is_canonical = |commitment: &super::Commitment| {
(commitment.kind == super::CommitmentKind::Routine) == commitment.period.is_some()
&& commitment.period.is_none_or(|period| {
(1..=super::patch::MAX_ROUTE_COST).contains(&period.minutes())
})
&& (commitment.kind == super::CommitmentKind::Routine
|| commitment.checks.is_empty())
&& match commitment.counterparty {
@ -2416,15 +2419,13 @@ mod custody_tests {
let _ = subject;
}
/// Soul falsification, reported as a bounded gap: `TickMinutes` is
/// `#[serde(transparent)]`, so a hand-written store row can carry a period
/// of zero — a routine that re-arms on the same minute forever — and
/// `verify_state_shape` admits it, because the shape check reads
/// `period.is_some()` and never the span bound the constructor enforces.
/// The commit chain still refuses the row, so the gap is bounded to a store
/// whose commits were forged to match.
/// `TickMinutes` is `#[serde(transparent)]`, so a hand-written store row
/// can carry a period of zero — a routine that re-arms on the same minute
/// forever — without ever passing through `TickMinutes::new`. The shape
/// check now enforces the same `1..=MAX_ROUTE_COST` span bound the
/// constructor enforces, so the forged row is refused directly.
#[test]
fn soul_a_zero_period_passes_the_shape_check_and_is_caught_only_by_the_chain() {
fn soul_a_zero_period_is_refused_by_the_shape_check() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("world.cc");
let (kernel, subject, _) = ticking_world(&path);
@ -2449,13 +2450,13 @@ mod custody_tests {
.unwrap()
.period = Some(zero);
// The gap: the shape check admits it.
// The shape check refuses the forged span bound directly.
assert!(
verify_state_shape(&forged).is_ok(),
"verify_state_shape gained a span bound"
matches!(verify_state_shape(&forged), Err(JournalError::Corrupt(_))),
"verify_state_shape admitted a period outside 1..=MAX_ROUTE_COST"
);
// The bound: the commit chain does not.
// The commit chain refuses it too.
let commits: Vec<CultCacheEnvelope> = kernel
.journal
.commits

View file

@ -34,8 +34,7 @@ pub(crate) use patch::{
#[cfg(test)]
use patch::{
AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp,
DependencyRef, FactDeclaration, FactStandingRef, PreconditionRef, PressureSourceRef, ReachRef,
RouteDeclaration,
DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration,
};
#[cfg(test)]
pub(crate) use patch::{AuthorityGrantRef, AuthorityTargetRef};
@ -3306,20 +3305,29 @@ fn derive_scale_deficit(state: &WorldState) -> Result<Vec<ScaleDeficitRow>, Kern
}
match state.positions.get(subject_id) {
// A subject under nested roots counts toward both: layered
// jurisdiction applied to counting.
// jurisdiction applied to counting. A subject standing somewhere
// no declared root covers still counts, in `Uncovered`, so the
// deficit stays total over every qualifying subject.
Some(position) => {
let mut covered = false;
for root in state.scale_intent.jurisdictions.keys() {
if patch::covers_place(&state.entities, *root, position.place) {
covered = true;
*counted
.entry((JurisdictionKey::PlaceSubtree(*root), subject.kind))
.or_default() += 1;
}
}
if !covered {
*counted
.entry((JurisdictionKey::Uncovered, subject.kind))
.or_default() += 1;
}
}
// Counted, visible, and reducing no target.
None => {
*counted
.entry((JurisdictionKey::Unplaced, subject.kind))
.entry((JurisdictionKey::Uncovered, subject.kind))
.or_default() += 1;
}
}
@ -10761,7 +10769,7 @@ mod clock_tests {
refuse(
&mut kernel,
declaring(
Some(PatchAnswer::Deficit(JurisdictionKey::Unplaced)),
Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)),
"no-deficit"
)
),
@ -10796,7 +10804,7 @@ mod clock_tests {
refuse(
&mut draft_kernel,
declaring(
Some(PatchAnswer::Deficit(JurisdictionKey::Unplaced)),
Some(PatchAnswer::Deficit(JurisdictionKey::Uncovered)),
"in-draft"
)
),
@ -10898,6 +10906,105 @@ mod clock_tests {
assert_eq!((row.target, row.qualified, row.deficit), (3, 0, 3));
}
/// A qualifying subject standing somewhere no declared root covers still
/// counts, in the `Uncovered` row, rather than vanishing from the deficit
/// entirely: the count is total over every qualifying subject.
#[test]
fn a_subject_placed_outside_every_root_counts_as_uncovered() {
let directory = tempfile::tempdir().unwrap();
let mut creation = creation_with_intent(
CommandId::new(),
"Uncovered",
intent(super::tests::COMMONS, 3, 1000),
);
creation
.patch
.declarations
.push(Declaration::Entity(EntityDeclaration {
handle: DraftHandle::new("elsewhere"),
label: "The Elsewhere".into(),
kind: EntityKind::Place,
container: None,
}));
creation
.patch
.declarations
.push(Declaration::Route(RouteDeclaration {
handle: DraftHandle::new("bridge"),
label: "The Elsewhere Bridge".into(),
from: Ref::Draft(DraftHandle::new(super::tests::COMMONS)),
to: Ref::Draft(DraftHandle::new("elsewhere")),
access: AccessKind::Public,
cost: Cost(1),
}));
let mut kernel = WorldKernel::create(
directory.path().join("world.cc"),
creation,
&auth_principal(owner()),
)
.expect("a created world")
.0;
let active = activate(&mut kernel);
let subject_count = kernel.state.subjects.len() as u32;
assert_eq!(subject_count, 3, "the base fixture declares three subjects");
// Every subject qualifies, so the deficit's row counts must sum to
// the whole subject count.
let goal = |subject: SubjectId| ComponentOp::CreateCommitment {
subject: Ref::Existing(subject),
counterparty: None,
kind: CommitmentKind::Goal,
due: FictionalMinutes(500),
period: None,
checks: Vec::new(),
};
let subject_ids: Vec<SubjectId> =
active.subjects.iter().map(|subject| subject.id).collect();
let snapshot = kernel.snapshot().unwrap();
submit_owner(
&mut kernel,
&snapshot,
operations(subject_ids.iter().copied().map(goal).collect()),
);
let moved = active
.subjects
.iter()
.find(|subject| subject.kind == SubjectKind::Person)
.expect("the fixture world has a person")
.id;
let bridge = active
.routes
.iter()
.find(|route| route.label == "The Elsewhere Bridge")
.expect("the declared route")
.id;
let snapshot = kernel.snapshot().unwrap();
submit_owner(
&mut kernel,
&snapshot,
operations(vec![ComponentOp::Relocate {
subject: Ref::Existing(moved),
via: Ref::Existing(bridge),
}]),
);
let rows = derive_scale_deficit(&kernel.state).unwrap();
let uncovered = rows
.iter()
.find(|row| {
row.jurisdiction == JurisdictionKey::Uncovered && row.kind == SubjectKind::Person
})
.expect("the relocated subject counts as uncovered");
assert_eq!(uncovered.qualified, 1);
let counted_total: u32 = rows.iter().map(|row| row.qualified).sum();
assert_eq!(
counted_total, subject_count,
"the deficit is total over every qualifying subject"
);
}
/// Weights distribute the target and never raise it, and a root must be a
/// declared place.
#[test]

View file

@ -609,13 +609,15 @@ pub(crate) struct WorldScaleIntentRef {
pub(crate) jurisdictions: BTreeMap<DraftHandle, u32>,
}
/// One counted region of the scale deficit. `Unplaced` is the residual: a
/// subject standing nowhere is counted and visible while reducing no target.
/// One counted region of the scale deficit. `Uncovered` is the residual: a
/// subject with no jurisdiction root covering it — standing nowhere, or
/// standing somewhere outside every declared root's subtree — is counted and
/// visible while reducing no target.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(tag = "jurisdiction", content = "root", rename_all = "snake_case")]
pub(crate) enum JurisdictionKey {
PlaceSubtree(EntityId),
Unplaced,
Uncovered,
}
/// What must already be true of committed state before an invocation is