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 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-20 05:58:09 +01:00
commit edeea42f5e
6 changed files with 555 additions and 84 deletions

View file

@ -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 {

View file

@ -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<SubjectId> = 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

View file

@ -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<K, V> Partition for Docs<K, V>
impl<K, V, P> Partition for Docs<K, V, P>
where
K: Ord + Clone + DocKey + Serialize,
V: Clone + PartialEq + Serialize,
P: crate::docs::Projection<V>,
{
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.

View file

@ -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<I: DoubleEndedIterator> DoubleEndedIterator for Counted<I> {
/// (`None` when the key was absent). The new value is whatever the map holds.
pub(crate) type Changed<K, V> = (K, Option<V>);
#[derive(Clone, Debug)]
pub(crate) struct Docs<K: Ord + Clone, V: Clone + PartialEq> {
map: BTreeMap<K, V>,
touched: BTreeMap<K, Option<V>>,
/// 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<V> {
type Point: Ord + Clone + std::fmt::Debug;
/// Appends every point `value` sits at (duplicates allowed).
fn points(value: &V, out: &mut Vec<Self::Point>);
}
impl<K: Ord + Clone, V: Clone + PartialEq> Default for Docs<K, V> {
/// The projection of a partition nothing reads by value.
#[derive(Clone, Debug, Default)]
pub(crate) struct NoIndex;
impl<V> Projection<V> 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<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V> = NoIndex> {
map: BTreeMap<K, V>,
touched: BTreeMap<K, Option<V>>,
index: BTreeMap<P::Point, BTreeSet<K>>,
}
impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> Default for Docs<K, V, P> {
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<K: Ord + Clone, V: Clone + PartialEq> PartialEq for Docs<K, V> {
impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> PartialEq for Docs<K, V, P> {
fn eq(&self, other: &Self) -> bool {
self.map == other.map
}
}
impl<K: Ord + Clone, V: Clone + PartialEq + Eq> Eq for Docs<K, V> {}
impl<K: Ord + Clone, V: Clone + PartialEq + Eq, P: Projection<V>> Eq for Docs<K, V, P> {}
impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs<K, V> {
impl<'a, K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> IntoIterator for &'a Docs<K, V, P> {
type Item = (&'a K, &'a V);
type IntoIter = Counted<std::collections::btree_map::Iter<'a, K, V>>;
fn into_iter(self) -> Self::IntoIter {
@ -101,20 +124,20 @@ impl<'a, K: Ord + Clone, V: Clone + PartialEq> IntoIterator for &'a Docs<K, V> {
/// A partition encodes as its map, so the encoded world is what it was before
/// the partitions were tracked.
impl<K: Ord + Clone + Serialize, V: Clone + PartialEq + Serialize> Serialize for Docs<K, V> {
impl<K: Ord + Clone + Serialize, V: Clone + PartialEq + Serialize, P: Projection<V>> Serialize for Docs<K, V, P> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.map.serialize(serializer)
}
}
impl<K: Ord + Clone, V: Clone + PartialEq> std::ops::Index<&K> for Docs<K, V> {
impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> std::ops::Index<&K> for Docs<K, V, P> {
type Output = V;
fn index(&self, key: &K) -> &V {
&self.map[key]
}
}
impl<K: Ord + Clone, V: Clone + PartialEq> Docs<K, V> {
impl<K: Ord + Clone, V: Clone + PartialEq, P: Projection<V>> Docs<K, V, P> {
pub(crate) fn get(&self, key: &K) -> Option<&V> {
self.map.get(key)
}
@ -197,10 +220,112 @@ impl<K: Ord + Clone, V: Clone + PartialEq> Docs<K, V> {
/// 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<Changed<K, V>> {
std::mem::take(&mut self.touched)
let changed: Vec<Changed<K, V>> = 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<R: std::ops::RangeBounds<P::Point>>(
&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<P::Point, BTreeSet<K>> = 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<u8> for Digits {
type Point = u8;
fn points(value: &u8, out: &mut Vec<u8>) {
out.push(value / 10);
out.push(value % 10);
}
}
type Spread = Docs<u8, u8, Digits>;
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::<Vec<_>>()
);
}
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()
}

View file

@ -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<WorldHeader>,
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<EntityRecord> for ChildOf {
type Point = EntityId;
fn points(value: &EntityRecord, out: &mut Vec<EntityId>) {
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<Position> for StandsAt {
type Point = EntityId;
fn points(value: &Position, out: &mut Vec<EntityId>) {
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<BTreeMap<CommitmentKey, Commitment>> for DueAt {
type Point = FictionalMinutes;
fn points(value: &BTreeMap<CommitmentKey, Commitment>, out: &mut Vec<FictionalMinutes>) {
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<BTreeMap<PressureSource, PressureMagnitude>> for BySource {
type Point = PressureSource;
fn points(
value: &BTreeMap<PressureSource, PressureMagnitude>,
out: &mut Vec<PressureSource>,
) {
out.extend(value.keys().copied());
}
}
/// `ByEndpoint`: the routes touching a place, at either end.
#[derive(Clone, Debug)]
struct ByEndpoint;
impl docs::Projection<EdgeRecord> for ByEndpoint {
type Point = EntityId;
fn points(value: &EdgeRecord, out: &mut Vec<EntityId>) {
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<ChannelRecord> for ByController {
type Point = SubjectId;
fn points(value: &ChannelRecord, out: &mut Vec<SubjectId>) {
out.extend(value.controller);
}
}
/// `ByIncumbent`: the institutions in which a subject holds an office.
#[derive(Clone, Debug)]
struct ByIncumbent;
impl docs::Projection<BTreeMap<OfficeName, Office>> for ByIncumbent {
type Point = SubjectId;
fn points(value: &BTreeMap<OfficeName, Office>, out: &mut Vec<SubjectId>) {
let first = out.len();
out.extend(value.values().filter_map(|office| office.incumbent));
out[first..].sort();
out.dedup();
}
}
world_state! {
subjects: Docs<SubjectId, SubjectState> = "aetherlight.subject.v1";
entities: Docs<EntityId, EntityRecord> = "aetherlight.entity.v1";
edges: Docs<EdgeId, EdgeRecord> = "aetherlight.edge.v1";
positions: Docs<SubjectId, Position> = "aetherlight.position.v1";
entities: Docs<EntityId, EntityRecord, ChildOf> = "aetherlight.entity.v1";
edges: Docs<EdgeId, EdgeRecord, ByEndpoint> = "aetherlight.edge.v1";
positions: Docs<SubjectId, Position, StandsAt> = "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<EntityId, FactRecord> = "aetherlight.fact.v1";
/// One row per `EntityKind::Channel` entity, and no orphan either way.
channels: Docs<EntityId, ChannelRecord> = "aetherlight.channel.v1";
channels: Docs<EntityId, ChannelRecord, ByController> = "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<SubjectId, BTreeMap<OfficeName, Office>> = "aetherlight.selection.v1";
selection: Docs<SubjectId, BTreeMap<OfficeName, Office>, 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<GrievanceKindName, Forum> = "aetherlight.redress.v1";
/// What each subject has promised. Never empty for a present key.
commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>> = "aetherlight.commitments.v1";
commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>, 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<SubjectId, BTreeMap<PressureSource, PressureMagnitude>> = "aetherlight.pressures.v1";
pressures: Docs<SubjectId, BTreeMap<PressureSource, PressureMagnitude>, BySource> = "aetherlight.pressures.v1";
/// What an affordance *is*. World-authored and written by `admit_resolved`
/// alone.
affordance_catalog: Docs<AffordanceId, Affordance> = "aetherlight.affordance.v1";
@ -2347,13 +2444,7 @@ fn apply_operation(
subject: *subject,
key: *key,
};
let holding: Vec<SubjectId> = 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<SubjectId> {
// 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<SubjectId> {
state
.positions
.iter()
@ -2604,9 +2727,9 @@ fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet<Sub
};
state
.positions
.iter()
.filter(|(_, position)| **position == here)
.map(|(subject_id, _)| *subject_id)
.indexed(here.place..=here.place)
.into_iter()
.map(|(_, subject_id)| subject_id)
.collect()
}
Audience::Channel(channel) => {
@ -2848,30 +2971,54 @@ fn delegated_authority(
) -> BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> {
let mut held: BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> =
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<OfficeName, Office>,
held: &mut BTreeMap<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>>,
) {
// 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<AuthorityGrant> = 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<AuthorityGrant> = 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<SubjectId, BTreeMap<OfficeName, BTreeSet<AuthorityGrant>>> {
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<Auth
)
}
/// The routes with an end at `place`, keyed by edge.
fn routes_at(state: &WorldState, place: EntityId) -> BTreeMap<EdgeId, EdgeRecord> {
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<EdgeId, EdgeRecord> {
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<EntityId, ChannelRecord> {
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<EntityId, ChannelRecord> {
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<SubjectId> {
state
.pressures
.indexed(source..=source)
.into_iter()
.map(|(_, target)| target)
.collect()
}
#[cfg(test)]
fn pressure_holders_by_scan(state: &WorldState, source: PressureSource) -> Vec<SubjectId> {
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)

View file

@ -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<EntityId>,
index: &BTreeMap<DraftHandle, RefKind>,
entities: &Docs<EntityId, EntityRecord>,
entities: &Docs<EntityId, EntityRecord, ChildOf>,
mismatches: &mut Vec<Mismatch>,
) -> Option<Key<EntityId>> {
let expected = RefKind::Entity(expected_kind);
@ -2767,7 +2768,7 @@ fn resolve_route(
site: Site,
reference: &Ref<EdgeId>,
index: &BTreeMap<DraftHandle, RefKind>,
edges: &Docs<EdgeId, EdgeRecord>,
edges: &Docs<EdgeId, EdgeRecord, ByEndpoint>,
mismatches: &mut Vec<Mismatch>,
) -> Option<Key<EdgeId>> {
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<EntityId, EntityRecord>,
entities: &Docs<EntityId, EntityRecord, ChildOf>,
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<EntityId, EntityRecord>,
entities: &Docs<EntityId, EntityRecord, ChildOf>,
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<EntityId, EntityRecord>,
entities: &Docs<EntityId, EntityRecord, ChildOf>,
) -> bool {
let mut current = entities.get(&start).and_then(|record| record.container);
for _ in 0..=entities.len() {