From edeea42f5e5a0bf0c798ebafcee5955287e9f325 Mon Sep 17 00:00:00 2001 From: soul Date: Fri, 20 Nov 2026 05:58:09 +0100 Subject: [PATCH] aetherlight: partition read indexes owned by Docs; eight whole-partition scans become index reads A Docs may carry a Projection: a pure function of one document's value. Docs::finish folds each changed key (old points out, new points in) from the list the digest folds; Docs::indexed returns (point, key) in order, corrected by the open log so it is true mid-transaction; rollback never touches the index. Seven projections: DueAt, StandsAt, ChildOf, BySource, ByEndpoint, ByController, ByIncumbent. under_place, audience Colocated, DischargeCommitment holders, scope_components routes and controls, delegated_authority, derive_motion's commitments and reachable's outbound edges now read the index; each old scan is kept as a cfg(test) *_by_scan reference. golden.digests byte-identical. Co-Authored-By: Claude Sonnet 5.5 --- native/aetherlight/src/action.rs | 6 +- native/aetherlight/src/clock.rs | 13 +- native/aetherlight/src/digest.rs | 20 +- native/aetherlight/src/docs.rs | 265 +++++++++++++++++++++++-- native/aetherlight/src/lib.rs | 319 +++++++++++++++++++++++++------ native/aetherlight/src/patch.rs | 22 ++- 6 files changed, 558 insertions(+), 87 deletions(-) diff --git a/native/aetherlight/src/action.rs b/native/aetherlight/src/action.rs index fb6fb9347..2ad319e79 100644 --- a/native/aetherlight/src/action.rs +++ b/native/aetherlight/src/action.rs @@ -663,7 +663,9 @@ fn reachable( settled.insert(place); let outbound: Vec<(EdgeId, EntityId, u64)> = state .edges - .iter() + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| (edge_id, &state.edges[&edge_id])) .filter(|(_, record)| record.is_open()) .filter_map(|(edge_id, record)| { let (from, to) = record.endpoints(); @@ -675,7 +677,7 @@ fn reachable( return None; }; patch::route_admits(state, authority, record.access(), next) - .then(|| (*edge_id, next, u64::from(record.cost().0))) + .then(|| (edge_id, next, u64::from(record.cost().0))) }) .collect(); for (_, next, step) in outbound { diff --git a/native/aetherlight/src/clock.rs b/native/aetherlight/src/clock.rs index bde23bb79..3fe6c8a5d 100644 --- a/native/aetherlight/src/clock.rs +++ b/native/aetherlight/src/clock.rs @@ -114,7 +114,18 @@ pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion let mut fulfilled = Vec::new(); let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new(); - for (subject, held) in &state.commitments { + // Only subjects with something due: the commitments index answers it + // without walking every promise in the world. The dependencies walk below + // is still one row per subject holding a dependency: follow-up + // aetherlight-cross-partition-views. + let due: std::collections::BTreeSet = state + .commitments + .indexed(..=to) + .into_iter() + .map(|(_, subject)| subject) + .collect(); + for subject in &due { + let held = &state.commitments[subject]; // A retired subject cannot act, and neither fulfilling a routine nor // pressing an obligation or goal is anything but that subject acting: // its commitments stay in history, un-discharged and un-deleted, but diff --git a/native/aetherlight/src/digest.rs b/native/aetherlight/src/digest.rs index d9be5bff6..1cf891244 100644 --- a/native/aetherlight/src/digest.rs +++ b/native/aetherlight/src/digest.rs @@ -129,12 +129,20 @@ pub(crate) trait Partition { /// Removes the first document, logged like any write; false when empty. #[cfg(test)] fn remove_first(&mut self) -> bool; + /// Whether the read index is exactly the projection of the documents. + #[cfg(test)] + fn index_is_derived(&self) -> bool; + /// Damages the read index in one place (a stray entry, else a missing one); + /// false when there is nothing to damage. + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool; } -impl Partition for Docs +impl Partition for Docs where K: Ord + Clone + DocKey + Serialize, V: Clone + PartialEq + Serialize, + P: crate::docs::Projection, { fn is_clean(&self) -> bool { Docs::is_clean(self) @@ -186,6 +194,16 @@ where }; self.remove(&key).is_some() } + + #[cfg(test)] + fn index_is_derived(&self) -> bool { + Docs::index_is_derived(self) + } + + #[cfg(test)] + fn corrupt_index_first(&mut self, stray: bool) -> bool { + self.corrupt_index_for_test(stray) + } } /// The header's one change, keyed by its own world id. diff --git a/native/aetherlight/src/docs.rs b/native/aetherlight/src/docs.rs index 7ef189406..bb05fd192 100644 --- a/native/aetherlight/src/docs.rs +++ b/native/aetherlight/src/docs.rs @@ -9,7 +9,7 @@ //! The fields are private to this module for the same reason. use serde::{Serialize, Serializer}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::collections::btree_map::Entry; use std::ops::Deref; @@ -66,32 +66,55 @@ impl DoubleEndedIterator for Counted { /// (`None` when the key was absent). The new value is whatever the map holds. pub(crate) type Changed = (K, Option); -#[derive(Clone, Debug)] -pub(crate) struct Docs { - map: BTreeMap, - touched: BTreeMap>, +/// Where a document sits in a partition's read index: a pure function of one +/// document's value, so the index can always be rebuilt from the map and never +/// disagrees with it. +pub(crate) trait Projection { + type Point: Ord + Clone + std::fmt::Debug; + /// Appends every point `value` sits at (duplicates allowed). + fn points(value: &V, out: &mut Vec); } -impl Default for Docs { +/// The projection of a partition nothing reads by value. +#[derive(Clone, Debug, Default)] +pub(crate) struct NoIndex; + +impl Projection for NoIndex { + type Point = (); + fn points(_: &V, _: &mut Vec<()>) {} +} + +/// A partition: its documents, the log of the open transaction, and the read +/// index (the projection of the documents as of the last `finish`). The index +/// is derived state: it is not digested, not encoded, and ignored by equality. +#[derive(Clone, Debug)] +pub(crate) struct Docs = NoIndex> { + map: BTreeMap, + touched: BTreeMap>, + index: BTreeMap>, +} + +impl> Default for Docs { fn default() -> Self { Self { map: BTreeMap::new(), touched: BTreeMap::new(), + index: BTreeMap::new(), } } } /// Equality is the documents, never the log: two worlds with the same content /// are equal whatever transaction state they are in. -impl PartialEq for Docs { +impl> PartialEq for Docs { fn eq(&self, other: &Self) -> bool { self.map == other.map } } -impl Eq for Docs {} +impl> Eq for Docs {} -impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs { +impl<'a, K: Ord + Clone, V: Clone + PartialEq, P: Projection> IntoIterator for &'a Docs { type Item = (&'a K, &'a V); type IntoIter = Counted>; fn into_iter(self) -> Self::IntoIter { @@ -101,20 +124,20 @@ impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs { /// A partition encodes as its map, so the encoded world is what it was before /// the partitions were tracked. -impl Serialize for Docs { +impl> Serialize for Docs { fn serialize(&self, serializer: S) -> Result { self.map.serialize(serializer) } } -impl std::ops::Index<&K> for Docs { +impl> std::ops::Index<&K> for Docs { type Output = V; fn index(&self, key: &K) -> &V { &self.map[key] } } -impl Docs { +impl> Docs { pub(crate) fn get(&self, key: &K) -> Option<&V> { self.map.get(key) } @@ -197,10 +220,112 @@ impl Docs { /// value they had then. A key written back to what it was is not reported. /// The log is empty afterwards. pub(crate) fn finish(&mut self) -> Vec> { - std::mem::take(&mut self.touched) + let changed: Vec> = std::mem::take(&mut self.touched) .into_iter() .filter(|(key, old)| self.map.get(key) != old.as_ref()) - .collect() + .collect(); + for (key, old) in &changed { + self.fold_index(key, old.as_ref()); + } + changed + } + + /// Moves one changed key's entries: its old points out, its current points in. + fn fold_index(&mut self, key: &K, old: Option<&V>) { + let mut points = Vec::new(); + if let Some(old) = old { + P::points(old, &mut points); + for point in points.drain(..) { + if let Some(keys) = self.index.get_mut(&point) { + keys.remove(key); + if keys.is_empty() { + self.index.remove(&point); + } + } + } + } + if let Some(new) = self.map.get(key) { + P::points(new, &mut points); + for point in points { + self.index.entry(point).or_default().insert(key.clone()); + } + } + } + + /// Every (point, key) inside `range`, in order, true at this moment: the + /// committed index, corrected by the open log. A logged key's committed + /// entries are dropped and its current value's points are read from the + /// map, so a read inside a transaction sees what the transaction wrote and + /// the index itself never saw it (which is why `rollback` leaves it alone). + pub(crate) fn indexed>( + &self, + range: R, + ) -> Vec<(P::Point, K)> { + let mut found: Vec<(P::Point, K)> = self + .index + .range((range.start_bound(), range.end_bound())) + .flat_map(|(point, keys)| keys.iter().map(move |key| (point, key))) + .filter(|(_, key)| !self.touched.contains_key(*key)) + .map(|(point, key)| (point.clone(), key.clone())) + .collect(); + if !self.touched.is_empty() { + let mut points = Vec::new(); + for key in self.touched.keys() { + if let Some(value) = self.map.get(key) { + P::points(value, &mut points); + for point in points.drain(..) { + if range.contains(&point) { + found.push((point, key.clone())); + } + } + } + } + found.sort(); + found.dedup(); + } + #[cfg(test)] + count_rows(found.len() as u64); + found + } + + /// Whether the index is exactly the projection of the map (test builds). + #[cfg(test)] + pub(crate) fn index_is_derived(&self) -> bool { + let mut rebuilt: BTreeMap> = BTreeMap::new(); + let mut points = Vec::new(); + for (key, value) in &self.map { + P::points(value, &mut points); + for point in points.drain(..) { + rebuilt.entry(point).or_default().insert(key.clone()); + } + } + rebuilt == self.index + } + + /// Makes the index disagree with the map in one place: a stray entry (a + /// document listed at a point it does not sit at) or a missing one. False + /// when this partition has no such place to damage (test builds). + #[cfg(test)] + pub(crate) fn corrupt_index_for_test(&mut self, stray: bool) -> bool { + if !stray { + let Some(point) = self.index.keys().next().cloned() else { + return false; + }; + let keys = self.index.get_mut(&point).expect("the point is present"); + let key = keys.iter().next().cloned().expect("a point holds a key"); + keys.remove(&key); + if keys.is_empty() { + self.index.remove(&point); + } + return true; + } + for keys in self.index.values_mut() { + if let Some(key) = self.map.keys().find(|key| !keys.contains(*key)) { + keys.insert(key.clone()); + return true; + } + } + false } /// Puts every touched key back as it was and empties the log. @@ -317,6 +442,118 @@ mod tests { docs } + /// A value sits at its tens digit and its units digit (one point when they + /// agree), so a document has several points and two documents can share one. + #[derive(Clone, Debug)] + struct Digits; + + impl Projection for Digits { + type Point = u8; + fn points(value: &u8, out: &mut Vec) { + out.push(value / 10); + out.push(value % 10); + } + } + + type Spread = Docs; + + fn spread(held: &[(u8, u8)]) -> Spread { + let mut docs = Spread::default(); + for (key, value) in held { + docs.insert(*key, *value); + } + docs.finish(); + docs + } + + /// The projection of the map, computed from scratch: what `indexed(..)` must + /// return at every moment. + fn truth(docs: &Spread) -> Vec<(u8, u8)> { + let mut out = Vec::new(); + for (key, value) in docs.iter() { + out.push((value / 10, *key)); + out.push((value % 10, *key)); + } + out.sort(); + out.dedup(); + out + } + + #[test] + fn a_committed_index_is_the_projection_and_follows_every_finish() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), truth(&docs)); + assert_eq!(docs.indexed(1..=1), vec![(1, 1), (1, 2)]); + + docs.insert(1, 32); + docs.remove(&2); + docs.insert(4, 44); + docs.finish(); + assert!(docs.index_is_derived(), "old points leave, new points arrive"); + assert_eq!(docs.indexed(..), truth(&docs)); + assert!(docs.indexed(0..=0).is_empty() && docs.indexed(1..=1).is_empty()); + } + + #[test] + fn a_read_inside_a_transaction_sees_the_log_and_the_index_does_not() { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + docs.insert(1, 55); + docs.remove(&2); + docs.insert(7, 12); + assert_eq!(docs.indexed(..), truth(&docs), "the read is true mid-transaction"); + assert!(!docs.indexed(0..=0).iter().any(|(_, key)| *key == 1), "an overwritten value leaves its old points"); + assert!(docs.indexed(5..=5).contains(&(5, 1)), "a new value is seen at once"); + assert!(docs.indexed(..).iter().all(|(_, key)| *key != 2), "a removed document is gone"); + for point in 0..=9 { + assert_eq!( + docs.indexed(point..=point), + truth(&docs).into_iter().filter(|(p, _)| *p == point).collect::>() + ); + } + assert!(!docs.index_is_derived(), "the open log has not reached the index"); + + docs.insert(1, 10); + docs.insert(7, 12); + docs.remove(&7); + assert_eq!(docs.indexed(..), truth(&docs), "a key written back or added and removed adds nothing"); + } + + #[test] + fn rollback_leaves_the_index_as_it_was_because_it_never_saw_the_transaction() { + let mut docs = spread(&[(1, 10), (2, 21)]); + let before = docs.indexed(..); + docs.insert(1, 99); + docs.insert(5, 35); + docs.remove(&2); + docs.rollback(); + assert!(docs.index_is_derived()); + assert_eq!(docs.indexed(..), before); + assert_eq!(docs.indexed(..), truth(&docs)); + } + + #[test] + fn an_index_read_counts_the_entries_it_returns() { + let docs = spread(&[(1, 10), (2, 21), (3, 33)]); + let before = rows_read(); + let found = docs.indexed(..); + assert_eq!(rows_read() - before, found.len() as u64); + let before = rows_read(); + assert_eq!(docs.indexed(1..=1).len(), 2); + assert_eq!(rows_read() - before, 2); + } + + #[test] + fn a_damaged_index_is_seen_as_not_derived() { + for stray in [true, false] { + let mut docs = spread(&[(1, 10), (2, 21), (3, 33)]); + assert!(docs.corrupt_index_for_test(stray)); + assert!(!docs.index_is_derived(), "stray={stray}"); + } + let mut empty = Spread::default(); + assert!(!empty.corrupt_index_for_test(true) && !empty.corrupt_index_for_test(false)); + } + fn contents(docs: &Rows) -> Vec<(u8, u8)> { docs.iter().map(|(key, value)| (*key, *value)).collect() } diff --git a/native/aetherlight/src/lib.rs b/native/aetherlight/src/lib.rs index cbc5b94f9..91766348e 100644 --- a/native/aetherlight/src/lib.rs +++ b/native/aetherlight/src/lib.rs @@ -462,14 +462,16 @@ struct WorldHeader { /// there is no second list to forget it from. /// /// Every partition is a `Docs`: reads see the map, every write is logged, and -/// `submit` applies in place and either finishes or rolls the log back. +/// `submit` applies in place and either finishes or rolls the log back. A row +/// may name a [`docs::Projection`] as a third type: that partition then keeps a +/// read index, and the projections sit just above this macro. macro_rules! world_state { - ($($(#[$meta:meta])* $field:ident: Docs<$key:ty, $value:ty> = $schema:literal;)*) => { + ($($(#[$meta:meta])* $field:ident: Docs<$key:ty, $value:ty $(, $proj:ty)?> = $schema:literal;)*) => { #[derive(Clone, Debug, PartialEq, Eq)] struct WorldState { header: Tracked, revision: u64, - $($(#[$meta])* $field: Docs<$key, $value>,)* + $($(#[$meta])* $field: Docs<$key, $value $(, $proj)?>,)* // The chain head: outside every document. accumulator: LtHash16, state_digest: String, @@ -504,11 +506,106 @@ macro_rules! world_state { }; } +/// The read indexes. Each is a pure function of one document's value, held by +/// its partition's `Docs` and read only through `Docs::indexed`; none is state +/// of its own, so none is digested or encoded. +/// +/// `ChildOf`: the places directly inside a place. +#[derive(Clone, Debug)] +struct ChildOf; + +impl docs::Projection for ChildOf { + type Point = EntityId; + fn points(value: &EntityRecord, out: &mut Vec) { + out.extend(value.container); + } +} + +/// `StandsAt`: who stands in a place. A position holds only its place, so two +/// positions are equal exactly when their places are. +#[derive(Clone, Debug)] +struct StandsAt; + +impl docs::Projection for StandsAt { + type Point = EntityId; + fn points(value: &Position, out: &mut Vec) { + out.push(value.place); + } +} + +/// `DueAt`: when a subject's commitments fall due, one entry per distinct due. +#[derive(Clone, Debug)] +struct DueAt; + +impl docs::Projection> for DueAt { + type Point = FictionalMinutes; + fn points(value: &BTreeMap, out: &mut Vec) { + let first = out.len(); + out.extend(value.values().map(|commitment| commitment.due)); + out[first..].sort(); + out.dedup(); + } +} + +/// `BySource`: which pressure sources press on a subject. +#[derive(Clone, Debug)] +struct BySource; + +impl docs::Projection> for BySource { + type Point = PressureSource; + fn points( + value: &BTreeMap, + out: &mut Vec, + ) { + out.extend(value.keys().copied()); + } +} + +/// `ByEndpoint`: the routes touching a place, at either end. +#[derive(Clone, Debug)] +struct ByEndpoint; + +impl docs::Projection for ByEndpoint { + type Point = EntityId; + fn points(value: &EdgeRecord, out: &mut Vec) { + let (from, to) = value.endpoints(); + out.push(from); + if to != from { + out.push(to); + } + } +} + +/// `ByController`: the channels a subject controls. +#[derive(Clone, Debug)] +struct ByController; + +impl docs::Projection for ByController { + type Point = SubjectId; + fn points(value: &ChannelRecord, out: &mut Vec) { + out.extend(value.controller); + } +} + +/// `ByIncumbent`: the institutions in which a subject holds an office. +#[derive(Clone, Debug)] +struct ByIncumbent; + +impl docs::Projection> for ByIncumbent { + type Point = SubjectId; + fn points(value: &BTreeMap, out: &mut Vec) { + let first = out.len(); + out.extend(value.values().filter_map(|office| office.incumbent)); + out[first..].sort(); + out.dedup(); + } +} + world_state! { subjects: Docs = "aetherlight.subject.v1"; - entities: Docs = "aetherlight.entity.v1"; - edges: Docs = "aetherlight.edge.v1"; - positions: Docs = "aetherlight.position.v1"; + entities: Docs = "aetherlight.entity.v1"; + edges: Docs = "aetherlight.edge.v1"; + positions: Docs = "aetherlight.position.v1"; /// What each subject holds. Absence is zero at both levels: no stored /// `Quantity(0)` and no empty inner map, so a duplicate holding is /// unrepresentable and "nothing" has one shape. @@ -520,7 +617,7 @@ world_state! { /// standing never changes after admission. facts: Docs = "aetherlight.fact.v1"; /// One row per `EntityKind::Channel` entity, and no orphan either way. - channels: Docs = "aetherlight.channel.v1"; + channels: Docs = "aetherlight.channel.v1"; /// What each subject knows. The sole owner of who-heard-what: `events` /// records what was done, and this decides what a subject may act on and /// what its projection may contain. One document per (subject, fact), and @@ -534,17 +631,17 @@ world_state! { /// The offices each institution constitutes, and who sits in them. An /// incumbent never acts as its institution: an office answers what its /// incumbent has jurisdiction over, not who the actor is. - selection: Docs> = "aetherlight.selection.v1"; + selection: Docs, ByIncumbent> = "aetherlight.selection.v1"; /// Where each kind of grievance goes, and who may bring it. Keyed by /// neither a subject nor a referent, so it enters no scope components and /// is admission-only state. redress: Docs = "aetherlight.redress.v1"; /// What each subject has promised. Never empty for a present key. - commitments: Docs> = "aetherlight.commitments.v1"; + commitments: Docs, DueAt> = "aetherlight.commitments.v1"; /// Pressure *on* each subject, keyed target-major then source. Never empty /// for a present key; no stored zero magnitude. Lived meaning: read by /// projection and by nothing that decides. - pressures: Docs> = "aetherlight.pressures.v1"; + pressures: Docs, BySource> = "aetherlight.pressures.v1"; /// What an affordance *is*. World-authored and written by `admit_resolved` /// alone. affordance_catalog: Docs = "aetherlight.affordance.v1"; @@ -2347,13 +2444,7 @@ fn apply_operation( subject: *subject, key: *key, }; - let holding: Vec = state - .pressures - .iter() - .filter(|(_, held)| held.contains_key(&sourced)) - .map(|(target, _)| *target) - .collect(); - for target in holding { + for target in pressure_holders(state, sourced) { let emptied = state.pressures.get_mut(&target).is_some_and(|held| { held.remove(&sourced); held.is_empty() @@ -2581,6 +2672,38 @@ pub(crate) fn is_retired(state: &WorldState, subject_id: SubjectId) -> bool { /// declared broadcast area and a witnessed event. A subject with no position is /// under nothing. fn under_place(state: &WorldState, root: EntityId) -> BTreeSet { + // The subtree by `ChildOf`, collecting who stands in each place. Containment + // is acyclic (`admit_resolved` refuses a chain that does not terminate); the + // visited set keeps the walk total regardless. + let mut under = BTreeSet::new(); + let mut seen = BTreeSet::new(); + let mut frontier = vec![root]; + while let Some(place) = frontier.pop() { + if !seen.insert(place) { + continue; + } + under.extend( + state + .positions + .indexed(place..=place) + .into_iter() + .map(|(_, subject_id)| subject_id), + ); + frontier.extend( + state + .entities + .indexed(place..=place) + .into_iter() + .map(|(_, child)| child), + ); + } + under +} + +/// What `under_place` was before the index: every position, asked whether its +/// place is covered. The index read must equal it. +#[cfg(test)] +fn under_place_by_scan(state: &WorldState, root: EntityId) -> BTreeSet { state .positions .iter() @@ -2604,9 +2727,9 @@ fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet { @@ -2848,30 +2971,54 @@ fn delegated_authority( ) -> BTreeMap>> { let mut held: BTreeMap>> = BTreeMap::new(); - for (institution, offices) in &state.selection { - // A retired institution lends nothing: `Retire` does not vacate - // offices, so the incumbency stays on record, but a dissolved - // institution's grants stop reaching its office-holders here, the one - // site that turns an office into effective authority. - if is_retired(state, *institution) { + for (_, institution) in state.selection.indexed(subject_id..=subject_id) { + lend_offices(state, subject_id, institution, &state.selection[&institution], &mut held); + } + held +} + +/// What one institution's offices lend `subject_id`, added to `held`. +fn lend_offices( + state: &WorldState, + subject_id: SubjectId, + institution: SubjectId, + offices: &BTreeMap, + held: &mut BTreeMap>>, +) { + // A retired institution lends nothing: `Retire` does not vacate + // offices, so the incumbency stays on record, but a dissolved + // institution's grants stop reaching its office-holders here, the one + // site that turns an office into effective authority. + if is_retired(state, institution) { + return; + } + for (name, office) in offices { + if office.incumbent != Some(subject_id) { continue; } - for (name, office) in offices { - if office.incumbent != Some(subject_id) { - continue; - } - let lent: BTreeSet = state - .authority - .get(institution) - .into_iter() - .flatten() - .filter(|grant| office.delegated.contains(&grant.kind)) - .cloned() - .collect(); - held.entry(*institution) - .or_default() - .insert(name.clone(), lent); - } + let lent: BTreeSet = state + .authority + .get(&institution) + .into_iter() + .flatten() + .filter(|grant| office.delegated.contains(&grant.kind)) + .cloned() + .collect(); + held.entry(institution) + .or_default() + .insert(name.clone(), lent); + } +} + +/// What `delegated_authority` was before the index: every institution. +#[cfg(test)] +fn delegated_authority_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap>> { + let mut held = BTreeMap::new(); + for (institution, offices) in &state.selection { + lend_offices(state, subject_id, *institution, offices, &mut held); } held } @@ -2886,20 +3033,79 @@ fn subject_authority(state: &WorldState, subject_id: SubjectId) -> BTreeSet BTreeMap { + state + .edges + .indexed(place..=place) + .into_iter() + .map(|(_, edge_id)| (edge_id, state.edges[&edge_id].clone())) + .collect() +} + +#[cfg(test)] +fn routes_at_by_scan(state: &WorldState, place: EntityId) -> BTreeMap { + state + .edges + .iter() + .filter(|(_, record)| { + let (from, to) = record.endpoints(); + from == place || to == place + }) + .map(|(edge_id, record)| (*edge_id, record.clone())) + .collect() +} + +/// The channels `subject_id` controls, with their records. +fn channels_controlled_by( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap { + state + .channels + .indexed(subject_id..=subject_id) + .into_iter() + .map(|(_, entity_id)| (entity_id, state.channels[&entity_id].clone())) + .collect() +} + +#[cfg(test)] +fn channels_controlled_by_by_scan( + state: &WorldState, + subject_id: SubjectId, +) -> BTreeMap { + state + .channels + .iter() + .filter(|(_, record)| record.controller == Some(subject_id)) + .map(|(entity_id, record)| (*entity_id, record.clone())) + .collect() +} + +/// The subjects with a pressure row from `source`. +fn pressure_holders(state: &WorldState, source: PressureSource) -> Vec { + state + .pressures + .indexed(source..=source) + .into_iter() + .map(|(_, target)| target) + .collect() +} + +#[cfg(test)] +fn pressure_holders_by_scan(state: &WorldState, source: PressureSource) -> Vec { + state + .pressures + .iter() + .filter(|(_, held)| held.contains_key(&source)) + .map(|(target, _)| *target) + .collect() +} + fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponents { let position = state.positions.get(&subject_id).copied(); let routes = position - .map(|position| { - state - .edges - .iter() - .filter(|(_, record)| { - let (from, to) = record.endpoints(); - from == position.place || to == position.place - }) - .map(|(edge_id, record)| (*edge_id, record.clone())) - .collect() - }) + .map(|position| routes_at(state, position.place)) .unwrap_or_default(); ScopeComponents { position, @@ -2920,12 +3126,7 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent .knowledge_of(subject_id) .map(|(fact, _)| *fact) .collect(), - controls: state - .channels - .iter() - .filter(|(_, record)| record.controller == Some(subject_id)) - .map(|(entity_id, record)| (*entity_id, record.clone())) - .collect(), + controls: channels_controlled_by(state, subject_id), commitments: state .commitments .get(&subject_id) diff --git a/native/aetherlight/src/patch.rs b/native/aetherlight/src/patch.rs index 21dcd0374..7bf53d956 100644 --- a/native/aetherlight/src/patch.rs +++ b/native/aetherlight/src/patch.rs @@ -12,10 +12,11 @@ //! after that set is empty, so a rejected patch never mints an ID. use super::clock::{FictionalMinutes, TickMinutes}; -use super::grammar::GrammarRefusal; use super::docs::Docs; +use super::grammar::GrammarRefusal; use super::{ - AffordanceId, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, SubjectState, WorldId, + AffordanceId, ByEndpoint, ChildOf, CommandId, EdgeId, EntityId, SubjectId, SubjectKind, + SubjectState, WorldId, }; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -2677,7 +2678,7 @@ fn resolve_entity( expected_kind: EntityKind, reference: &Ref, index: &BTreeMap, - entities: &Docs, + entities: &Docs, mismatches: &mut Vec, ) -> Option> { let expected = RefKind::Entity(expected_kind); @@ -2767,7 +2768,7 @@ fn resolve_route( site: Site, reference: &Ref, index: &BTreeMap, - edges: &Docs, + edges: &Docs, mismatches: &mut Vec, ) -> Option> { match reference { @@ -5603,11 +5604,12 @@ fn contains_itself( /// Whether `place` is `root` or is contained in it, over canonical state: one /// upward walk in the shape of [`containment_terminates`], bounded by the graph /// size. It is total because `admit_resolved` refuses a non-terminating chain, -/// so the bound is belt-and-braces rather than a repair loop. There is no -/// downward enumeration and no child index: every jurisdictional question this -/// kernel asks is "is this target inside my ground". +/// so the bound is belt-and-braces rather than a repair loop. The question it +/// answers is "is this target inside my ground". Enumerating who stands under a +/// place is the other direction and has its own owner: `under_place` walks the +/// subtree by the entities partition's `ChildOf` index. pub(super) fn covers_place( - entities: &Docs, + entities: &Docs, root: EntityId, place: EntityId, ) -> bool { @@ -5625,7 +5627,7 @@ pub(super) fn covers_place( /// The canonical twin of the candidate graph's `candidate_targets_overlap`: whether two /// jurisdictions of one kind cover common ground. pub(super) fn targets_overlap( - entities: &Docs, + entities: &Docs, left: AuthorityTarget, right: AuthorityTarget, ) -> bool { @@ -5664,7 +5666,7 @@ pub(super) fn route_admits( /// chain that never terminates dies before the partition keeps it. pub(super) fn containment_terminates( start: EntityId, - entities: &Docs, + entities: &Docs, ) -> bool { let mut current = entities.get(&start).and_then(|record| record.container); for _ in 0..=entities.len() {