aetherlight: cross-partition views (live due, failing dependencies) derived at finish
views.rs owns Views { live_due, failing }, folded only by WorldState::finish
from the open change lists of commitments, subjects, dependencies, edges,
holdings and positions, before the logs close. Derived like a Docs index: not
digested, not encoded, ignored by equality, rebuilt by replay on open, never
touched by rollback. derive_motion reads it with clean logs (asserted) and no
longer walks every dependency row or visits retired subjects' dead pledges.
DueAt leaves commitments (the due question has one owner); dependencies gains
the DependsOn index the fold uses to re-judge a changed route's or placement's
dependents. The old walks live on as cfg(test) derive_motion_by_scan and
Views::rebuild; views_are_derived, view_reads_equal_reference_scans,
a_corrupted_view_is_detected and a debug refusal of an open-log read pin them.
golden.digests is byte-identical.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ae0f6f3463
commit
08cda21b1a
5 changed files with 465 additions and 55 deletions
|
|
@ -7,7 +7,9 @@
|
|||
//! the span.
|
||||
|
||||
use super::patch::{Commitment, CommitmentKey, CommitmentKind, DependencyTarget, MAX_ROUTE_COST};
|
||||
use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, is_retired};
|
||||
use super::{PressureMagnitude, PressureSource, SubjectId, WorldState, action, views};
|
||||
#[cfg(test)]
|
||||
use super::is_retired;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
|
|
@ -110,45 +112,47 @@ mod step {
|
|||
/// and one thousand-minute tick over the same span produce different
|
||||
/// magnitudes. The kernel stays an exact function of the command sequence, and
|
||||
/// the tick cadence is one operational constant in `runtime.rs`.
|
||||
///
|
||||
/// What is due, and which dependencies fail, is read from `Views` (the one owner
|
||||
/// of both questions: a live subject's due commitments and a live subject's
|
||||
/// unavailable dependencies), so a tick reads the work it does and not the
|
||||
/// world. A view is true only with clean logs, so both callers (`reduce`, and
|
||||
/// `apply_effect`'s `TimeAdvanced` arm before its first write) call it clean.
|
||||
pub(super) fn derive_motion(state: &WorldState, to: FictionalMinutes) -> Motion {
|
||||
// Only subjects with something due: the commitments index answers it
|
||||
// without walking every promise in the world.
|
||||
let due: std::collections::BTreeSet<SubjectId> = state
|
||||
.commitments
|
||||
.indexed(..=to)
|
||||
.into_iter()
|
||||
.map(|(_, subject)| subject)
|
||||
.collect();
|
||||
motion_of(state, to, due)
|
||||
debug_assert!(views::readable(state), "the views are read with an open log");
|
||||
motion_of(state, to, &state.views.due_by(to), state.views.failing().copied())
|
||||
}
|
||||
|
||||
/// What `derive_motion` was before the index: every subject holding a promise.
|
||||
/// The index read must derive the same motion.
|
||||
/// What `derive_motion` was before the views: every subject holding a promise
|
||||
/// and every dependency row, with retirement and availability judged on the
|
||||
/// spot. The view reads must derive the same motion.
|
||||
#[cfg(test)]
|
||||
pub(super) fn derive_motion_by_scan(state: &WorldState, to: FictionalMinutes) -> Motion {
|
||||
motion_of(state, to, state.commitments.keys().copied().collect())
|
||||
let live = |subject: &SubjectId| !is_retired(state, *subject);
|
||||
let promisors = state.commitments.keys().copied().filter(live).collect();
|
||||
let failing: Vec<_> = state
|
||||
.dependencies
|
||||
.iter()
|
||||
.filter(|(subject, _)| live(subject))
|
||||
.flat_map(|(subject, targets)| targets.iter().map(move |target| (*subject, *target)))
|
||||
.filter(|(subject, target)| dependency_unavailable(state, *subject, *target))
|
||||
.collect();
|
||||
motion_of(state, to, &promisors, failing.into_iter())
|
||||
}
|
||||
|
||||
/// The motion over `promisors`, which must include every subject with a
|
||||
/// commitment due by `to`. The dependencies walk below is still one row per
|
||||
/// subject holding a dependency: follow-up aetherlight-cross-partition-views.
|
||||
/// The motion over `promisors`, which must hold every live subject with a
|
||||
/// commitment due by `to`, and the `failing` dependencies of live subjects.
|
||||
fn motion_of(
|
||||
state: &WorldState,
|
||||
to: FictionalMinutes,
|
||||
promisors: std::collections::BTreeSet<SubjectId>,
|
||||
promisors: &std::collections::BTreeSet<SubjectId>,
|
||||
failing: impl Iterator<Item = (SubjectId, DependencyTarget)>,
|
||||
) -> Motion {
|
||||
let mut fulfilled = Vec::new();
|
||||
let mut pressed: BTreeMap<(SubjectId, PressureSource), u32> = BTreeMap::new();
|
||||
|
||||
for subject in &promisors {
|
||||
for subject in promisors {
|
||||
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
|
||||
// the clock stops moving them the moment they are its.
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for (key, commitment) in held {
|
||||
if commitment.due > to {
|
||||
continue;
|
||||
|
|
@ -179,16 +183,9 @@ fn motion_of(
|
|||
}
|
||||
}
|
||||
|
||||
for (subject, targets) in &state.dependencies {
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for target in targets {
|
||||
if dependency_unavailable(state, *subject, *target) {
|
||||
let source = PressureSource::Dependency(*target);
|
||||
*pressed.entry((*subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE;
|
||||
}
|
||||
}
|
||||
for (subject, target) in failing {
|
||||
let source = PressureSource::Dependency(target);
|
||||
*pressed.entry((subject, source)).or_default() += step::DEPENDENCY_UNAVAILABLE;
|
||||
}
|
||||
|
||||
Motion {
|
||||
|
|
|
|||
|
|
@ -27,8 +27,9 @@ pub(crate) fn rows_read() -> u64 {
|
|||
ROWS_READ.with(|rows| rows.get())
|
||||
}
|
||||
|
||||
/// Counts rows a view read, where the view is owned (test builds).
|
||||
#[cfg(test)]
|
||||
fn count_rows(rows: u64) {
|
||||
pub(crate) fn count_rows(rows: u64) {
|
||||
ROWS_READ.with(|count| count.set(count.get() + rows));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -593,6 +593,10 @@ fn a_failed_apply_rolls_back() {
|
|||
"{label}: the accumulator no longer matches the documents"
|
||||
);
|
||||
assert_indexes_derived(&kernel.state, &format!("{label}, after the failure"));
|
||||
assert!(
|
||||
kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)),
|
||||
"{label}: the failure left the views behind"
|
||||
);
|
||||
|
||||
let envelope = clockwork_envelope(&kernel, body);
|
||||
kernel
|
||||
|
|
@ -600,6 +604,10 @@ fn a_failed_apply_rolls_back() {
|
|||
.unwrap_or_else(|error| panic!("{label}: the next honest command: {error:?}"));
|
||||
assert_eq!(kernel.state.full_state_digest().unwrap(), kernel.state.state_digest);
|
||||
assert_indexes_derived(&kernel.state, &format!("{label}, after the honest command"));
|
||||
assert!(
|
||||
kernel.state.views.same_as(&crate::views::Views::rebuild(&kernel.state)),
|
||||
"{label}: the views left their documents"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1056,7 +1064,95 @@ fn walked_states() -> Vec<(String, crate::WorldState)> {
|
|||
kernel.submit(envelope, &AuthenticatedCaller::verified_play()).unwrap();
|
||||
states.push((format!("clockwork commit {step}"), kernel.state.clone()));
|
||||
}
|
||||
let reopened = WorldKernel::open(&kernel.export().unwrap()).unwrap();
|
||||
states.push(("clockwork reopened".into(), reopened.state));
|
||||
states.push(("multivalue world".into(), multivalue_world()));
|
||||
states.extend(view_scenario());
|
||||
states
|
||||
}
|
||||
|
||||
/// The commands that move what the views join, one at a time, each state kept:
|
||||
/// dependencies bound on a route, a resource and a subject; the route closed
|
||||
/// and reopened; the resource's holding emptied and refilled; a depended-on
|
||||
/// subject loses its position; a dependent released; and a subject that holds
|
||||
/// past-due routines and a failing dependency retires.
|
||||
fn view_scenario() -> Vec<(String, crate::WorldState)> {
|
||||
use crate::patch::{DependencyRef, EvidenceRef, Quantity};
|
||||
use crate::tests::TITHE_RECEIPT;
|
||||
let (mut kernel, people, _) = clockwork_world(20);
|
||||
let route = *kernel.state.edges.keys().next().expect("a route");
|
||||
let grain = |label: &str| {
|
||||
*kernel
|
||||
.state
|
||||
.entities
|
||||
.iter()
|
||||
.find(|(_, record)| record.label == label)
|
||||
.expect("a declared resource")
|
||||
.0
|
||||
};
|
||||
let (grain_0, grain_1) = (grain("Grain 0"), grain("Grain 1"));
|
||||
let bind = |subject: usize, target: DependencyRef| ComponentOp::Bind {
|
||||
subject: Ref::Existing(people[subject]),
|
||||
target,
|
||||
};
|
||||
let steps: Vec<(&str, CommandBody)> = vec![
|
||||
(
|
||||
"binds",
|
||||
operations(vec![
|
||||
bind(5, DependencyRef::Route(Ref::Existing(route))),
|
||||
bind(6, DependencyRef::Resource(Ref::Existing(grain_1))),
|
||||
bind(7, DependencyRef::Subject(Ref::Existing(people[8]))),
|
||||
bind(7, DependencyRef::Resource(Ref::Existing(grain_0))),
|
||||
bind(3, DependencyRef::Subject(Ref::Existing(people[4]))),
|
||||
]),
|
||||
),
|
||||
("the route closes", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])),
|
||||
("the route reopens", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])),
|
||||
(
|
||||
"a holding empties",
|
||||
operations(vec![ComponentOp::Consume {
|
||||
holder: Ref::Existing(people[7]),
|
||||
resource: Ref::Existing(grain_0),
|
||||
qty: Quantity(1),
|
||||
}]),
|
||||
),
|
||||
(
|
||||
"the holding refills",
|
||||
CommandBody::AdmitPatch {
|
||||
patch: WorldPatch {
|
||||
declarations: Vec::new(),
|
||||
operations: vec![ComponentOp::Admit {
|
||||
holder: Ref::Existing(people[7]),
|
||||
resource: Ref::Existing(grain_0),
|
||||
qty: Quantity(1),
|
||||
evidence: EvidenceRef::new(TITHE_RECEIPT),
|
||||
}],
|
||||
evidence: vec![EvidenceRef::new(TITHE_RECEIPT)],
|
||||
},
|
||||
},
|
||||
),
|
||||
("the route closes again", operations(vec![ComponentOp::CloseRoute { route: Ref::Existing(route) }])),
|
||||
("a long tick", tick_body(30)),
|
||||
("a depended-on subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[8]) }])),
|
||||
(
|
||||
"a dependent is released",
|
||||
operations(vec![ComponentOp::Release {
|
||||
subject: Ref::Existing(people[3]),
|
||||
target: DependencyRef::Subject(Ref::Existing(people[4])),
|
||||
}]),
|
||||
),
|
||||
("a failing, past-due subject retires", operations(vec![ComponentOp::Retire { subject: Ref::Existing(people[6]) }])),
|
||||
("the route reopens after the retirement", operations(vec![ComponentOp::OpenRoute { route: Ref::Existing(route) }])),
|
||||
("a last tick", tick_body(30)),
|
||||
];
|
||||
let mut states = vec![("scenario created".to_owned(), kernel.state.clone())];
|
||||
for (name, body) in steps {
|
||||
let envelope = clockwork_envelope(&kernel, body);
|
||||
kernel
|
||||
.submit(envelope, &AuthenticatedCaller::verified_play())
|
||||
.unwrap_or_else(|error| panic!("{name}: {error:?}"));
|
||||
states.push((format!("scenario: {name}"), kernel.state.clone()));
|
||||
}
|
||||
states
|
||||
}
|
||||
|
||||
|
|
@ -1107,13 +1203,6 @@ fn indexes_are_derived() {
|
|||
/// The first place an index read and the scan it replaced disagree, if any.
|
||||
fn reference_scan_disagreement(state: &crate::WorldState) -> Option<String> {
|
||||
use crate::{Audience, Cost, PressureSource};
|
||||
let now = state.header.now;
|
||||
for minutes in [1, 30] {
|
||||
let to = FictionalMinutes(now.0 + minutes);
|
||||
if crate::clock::derive_motion(state, to) != crate::clock::derive_motion_by_scan(state, to) {
|
||||
return Some(format!("derive_motion over {minutes} minutes"));
|
||||
}
|
||||
}
|
||||
let subjects: Vec<_> = state.subjects.keys().copied().collect();
|
||||
let places: Vec<_> = state
|
||||
.entities
|
||||
|
|
@ -1146,6 +1235,15 @@ fn reference_scan_disagreement(state: &crate::WorldState) -> Option<String> {
|
|||
}
|
||||
}
|
||||
}
|
||||
let targets: std::collections::BTreeSet<_> =
|
||||
state.dependencies.values().flat_map(|held| held.iter().copied()).collect();
|
||||
for target in targets {
|
||||
let mut by_index = crate::views::Views::dependents_of(state, target);
|
||||
by_index.sort();
|
||||
if by_index != crate::views::Views::dependents_by_scan(state, target) {
|
||||
return Some(format!("dependents of {target:?}"));
|
||||
}
|
||||
}
|
||||
for place in &places {
|
||||
if crate::under_place(state, *place) != crate::under_place_by_scan(state, *place) {
|
||||
return Some(format!("under_place {place:?}"));
|
||||
|
|
@ -1271,10 +1369,84 @@ fn a_corrupted_index_is_detected() {
|
|||
"aetherlight.position.v1",
|
||||
"aetherlight.channel.v1",
|
||||
"aetherlight.selection.v1",
|
||||
"aetherlight.commitments.v1",
|
||||
"aetherlight.dependencies.v1",
|
||||
"aetherlight.pressures.v1",
|
||||
]
|
||||
.into();
|
||||
assert_eq!(reported, indexed, "exactly the indexed partitions can be damaged");
|
||||
assert_eq!(misread, indexed, "a damaged index must change what a reader answers");
|
||||
}
|
||||
|
||||
/// A view is derived from the documents and nothing else: after every commit of
|
||||
/// the walked worlds, however each was reached, it is what a scan of the
|
||||
/// committed documents builds.
|
||||
#[test]
|
||||
fn views_are_derived() {
|
||||
for (label, state) in walked_states() {
|
||||
assert!(
|
||||
state.views.same_as(&crate::views::Views::rebuild(&state)),
|
||||
"{label}: the views left their documents"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The motion the views derive is the motion the scans derive: every live
|
||||
/// subject's due commitments and failing dependencies, over short and long
|
||||
/// spans, in every walked state (which holds routes that close and reopen,
|
||||
/// holdings that empty, subjects that lose a position, and subjects that retire
|
||||
/// holding past-due routines and failing dependencies).
|
||||
#[test]
|
||||
fn view_reads_equal_reference_scans() {
|
||||
let mut pressed_dependency = false;
|
||||
for (label, state) in walked_states() {
|
||||
for minutes in [1, 30, 5_000] {
|
||||
let to = FictionalMinutes(state.header.now.0 + minutes);
|
||||
let motion = crate::clock::derive_motion(&state, to);
|
||||
assert_eq!(motion, crate::clock::derive_motion_by_scan(&state, to), "{label}, {minutes} minutes");
|
||||
pressed_dependency |= motion
|
||||
.pressed
|
||||
.iter()
|
||||
.any(|written| matches!(written.source, crate::PressureSource::Dependency(_)));
|
||||
}
|
||||
}
|
||||
assert!(pressed_dependency, "no walked state had a failing dependency to compare");
|
||||
}
|
||||
|
||||
/// A damaged view is seen by the oracle and changes what the clock derives: a
|
||||
/// stray failing row presses a dependency nobody holds, and a missing due
|
||||
/// point leaves its subjects unmoved.
|
||||
#[test]
|
||||
fn a_corrupted_view_is_detected() {
|
||||
let (mut kernel, _, _) = clockwork_world(20);
|
||||
kernel
|
||||
.submit(clockwork_envelope(&kernel, tick_body(1)), &AuthenticatedCaller::verified_play())
|
||||
.unwrap();
|
||||
let state = kernel.state;
|
||||
let to = FictionalMinutes(state.header.now.0 + 30);
|
||||
assert!(state.views.same_as(&crate::views::Views::rebuild(&state)));
|
||||
for stray in [true, false] {
|
||||
let mut damaged = state.clone();
|
||||
assert!(damaged.views.corrupt_for_test(stray), "stray {stray}");
|
||||
assert!(
|
||||
!damaged.views.same_as(&crate::views::Views::rebuild(&damaged)),
|
||||
"stray {stray}: the oracle did not see the damage"
|
||||
);
|
||||
assert_ne!(
|
||||
crate::clock::derive_motion(&damaged, to),
|
||||
crate::clock::derive_motion_by_scan(&damaged, to),
|
||||
"stray {stray}: the damage changed no read"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A view is read only with clean logs: reading one while a partition it joins
|
||||
/// has an open write is refused, not answered from a stale fold.
|
||||
#[cfg(debug_assertions)]
|
||||
#[test]
|
||||
#[should_panic(expected = "open log")]
|
||||
fn a_view_read_with_an_open_log_is_refused() {
|
||||
let (mut kernel, people, _) = clockwork_world(20);
|
||||
kernel.state.begin();
|
||||
kernel.state.positions.remove(&people[3]);
|
||||
crate::clock::derive_motion(&kernel.state, FictionalMinutes(1));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ mod grammar;
|
|||
mod import_key_tests;
|
||||
mod journal;
|
||||
mod patch;
|
||||
mod views;
|
||||
|
||||
pub(crate) use action::ActionMismatch;
|
||||
pub(crate) use clock::Motion;
|
||||
|
|
@ -102,6 +103,7 @@ use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch};
|
|||
|
||||
use digest::{LtHash16, Partition};
|
||||
use docs::{Changed, DocKey, Docs, Tracked};
|
||||
use views::Views;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
|
@ -472,6 +474,10 @@ macro_rules! world_state {
|
|||
header: Tracked<WorldHeader>,
|
||||
revision: u64,
|
||||
$($(#[$meta])* $field: Docs<$key, $value $(, $proj)?>,)*
|
||||
/// Derived from the partitions at every `finish`: outside every
|
||||
/// document, so neither digested nor encoded, and equal whatever
|
||||
/// it holds (see `views`).
|
||||
views: Views,
|
||||
// The chain head: outside every document.
|
||||
accumulator: LtHash16,
|
||||
state_digest: String,
|
||||
|
|
@ -497,6 +503,7 @@ macro_rules! world_state {
|
|||
header,
|
||||
revision: 0,
|
||||
$($field: Docs::default(),)*
|
||||
views: Views::default(),
|
||||
accumulator: LtHash16::default(),
|
||||
state_digest: String::new(),
|
||||
last_commit_digest: None,
|
||||
|
|
@ -533,17 +540,15 @@ impl docs::Projection<Position> for StandsAt {
|
|||
}
|
||||
}
|
||||
|
||||
/// `DueAt`: when a subject's commitments fall due, one entry per distinct due.
|
||||
/// `DependsOn`: who depends on a target. `Views` reads it to re-judge the
|
||||
/// dependents of a route or a placement that changed.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DueAt;
|
||||
struct DependsOn;
|
||||
|
||||
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();
|
||||
impl docs::Projection<BTreeSet<DependencyTarget>> for DependsOn {
|
||||
type Point = DependencyTarget;
|
||||
fn points(value: &BTreeSet<DependencyTarget>, out: &mut Vec<DependencyTarget>) {
|
||||
out.extend(value.iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -611,7 +616,7 @@ world_state! {
|
|||
/// unrepresentable and "nothing" has one shape.
|
||||
holdings: Docs<SubjectId, BTreeMap<EntityId, Quantity>> = "aetherlight.holdings.v1";
|
||||
/// What each subject depends on. Never empty for a present key.
|
||||
dependencies: Docs<SubjectId, BTreeSet<DependencyTarget>> = "aetherlight.dependencies.v1";
|
||||
dependencies: Docs<SubjectId, BTreeSet<DependencyTarget>, DependsOn> = "aetherlight.dependencies.v1";
|
||||
/// One row per `EntityKind::Fact` entity, and no orphan either way. Facts
|
||||
/// are write-once: declaration and `AssertClaim` are the only writers, and
|
||||
/// standing never changes after admission.
|
||||
|
|
@ -637,7 +642,7 @@ world_state! {
|
|||
/// 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>, DueAt> = "aetherlight.commitments.v1";
|
||||
commitments: Docs<SubjectId, BTreeMap<CommitmentKey, Commitment>> = "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.
|
||||
|
|
@ -1308,6 +1313,10 @@ impl WorldState {
|
|||
) -> Vec<Changed<SubjectId, BTreeMap<CommitmentKey, Commitment>>> {
|
||||
self.accumulator = accumulator;
|
||||
self.header.finish();
|
||||
// The views fold from the open logs, so they come before the logs close.
|
||||
let mut views = std::mem::take(&mut self.views);
|
||||
views.fold(self);
|
||||
self.views = views;
|
||||
let commitments = self.commitments.finish();
|
||||
for (_, docs) in self.partitions_mut() {
|
||||
docs.finish_log();
|
||||
|
|
|
|||
231
native/aetherlight/src/views.rs
Normal file
231
native/aetherlight/src/views.rs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
//! Cross-partition views: what a read needs that no one partition's index can
|
||||
//! answer.
|
||||
//!
|
||||
//! A `Docs` projection is a pure function of one document. Two questions the
|
||||
//! clock asks are joins: "is this dependency failing" reads dependencies with
|
||||
//! edges, holdings and positions (two of its arms are anti-joins: a resource
|
||||
//! not held, a subject not placed), and "is this due commitment live" reads
|
||||
//! commitments with `subjects.retired`. [`Views`] answers them as state derived
|
||||
//! from those partitions' change lists, so a tick reads the work due and the
|
||||
//! rows failing instead of every dependency or every dead pledge in the world.
|
||||
//!
|
||||
//! `Views` is derived, never state: not digested, not encoded, never exported,
|
||||
//! and ignored by `WorldState`'s equality (its `PartialEq` is always true, as a
|
||||
//! `Docs` index is ignored). The one writer is [`Views::fold`], called by
|
||||
//! `WorldState::finish` from the open logs before they close, so replay (genesis
|
||||
//! and every replayed commit close through `finish`) rebuilds it on open and a
|
||||
//! rollback has nothing to undo: the view never saw the transaction. It is read
|
||||
//! only with clean logs, which `derive_motion` asserts.
|
||||
|
||||
use super::clock::dependency_unavailable;
|
||||
#[cfg(test)]
|
||||
use super::docs;
|
||||
use super::patch::DependencyTarget;
|
||||
use super::{EntityId, FictionalMinutes, SubjectId, WorldState, is_retired};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Views {
|
||||
/// When live subjects' commitments fall due: a point for each distinct
|
||||
/// due, holding the subjects that have a commitment due then. A retired
|
||||
/// subject has no point.
|
||||
live_due: BTreeMap<FictionalMinutes, BTreeSet<SubjectId>>,
|
||||
/// The (dependent, target) pairs failing a live dependent: a closed route,
|
||||
/// a resource the dependent does not hold, a subject nobody places.
|
||||
failing: BTreeSet<(SubjectId, DependencyTarget)>,
|
||||
}
|
||||
|
||||
/// A view is derived and carries no content of its own, so two worlds with the
|
||||
/// same documents are equal whatever their views hold.
|
||||
impl PartialEq for Views {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Views {}
|
||||
|
||||
/// Whether the six partitions the views read have no open log: the only time a
|
||||
/// view is true.
|
||||
pub(crate) fn readable(state: &WorldState) -> bool {
|
||||
state.commitments.is_clean()
|
||||
&& state.subjects.is_clean()
|
||||
&& state.dependencies.is_clean()
|
||||
&& state.edges.is_clean()
|
||||
&& state.holdings.is_clean()
|
||||
&& state.positions.is_clean()
|
||||
}
|
||||
|
||||
/// The subjects with a dependency on `target`, from the dependencies
|
||||
/// partition's `DependsOn` index (true mid-transaction).
|
||||
fn dependents(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> {
|
||||
state
|
||||
.dependencies
|
||||
.indexed(target..=target)
|
||||
.into_iter()
|
||||
.map(|(_, subject)| subject)
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Views {
|
||||
/// Subjects with a live commitment due at or before `to`.
|
||||
pub(crate) fn due_by(&self, to: FictionalMinutes) -> BTreeSet<SubjectId> {
|
||||
#[cfg(test)]
|
||||
docs::count_rows(self.live_due.range(..=to).map(|(_, held)| held.len() as u64).sum());
|
||||
self.live_due
|
||||
.range(..=to)
|
||||
.flat_map(|(_, held)| held.iter().copied())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every failing (dependent, target), in order.
|
||||
pub(crate) fn failing(&self) -> impl Iterator<Item = &(SubjectId, DependencyTarget)> {
|
||||
#[cfg(test)]
|
||||
docs::count_rows(self.failing.len() as u64);
|
||||
self.failing.iter()
|
||||
}
|
||||
|
||||
/// Brings the views up to the open logs of the six partitions. Called by
|
||||
/// `WorldState::finish` before the logs close; nothing else writes a view.
|
||||
pub(crate) fn fold(&mut self, state: &WorldState) {
|
||||
// Dues. A subject whose commitments or retirement changed loses the
|
||||
// points its commitments held before and regains them if it is live.
|
||||
let mut before: BTreeMap<SubjectId, Option<_>> = BTreeMap::new();
|
||||
for (subject, old, _) in state.commitments.changes() {
|
||||
before.insert(*subject, old);
|
||||
}
|
||||
for (subject, _, _) in state.subjects.changes() {
|
||||
before.entry(*subject).or_insert_with(|| state.commitments.get(subject));
|
||||
}
|
||||
for (subject, old) in &before {
|
||||
for commitment in old.into_iter().flat_map(|held| held.values()) {
|
||||
if let Some(due) = self.live_due.get_mut(&commitment.due) {
|
||||
due.remove(subject);
|
||||
if due.is_empty() {
|
||||
self.live_due.remove(&commitment.due);
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for commitment in state.commitments.get(subject).into_iter().flat_map(|held| held.values()) {
|
||||
self.live_due.entry(commitment.due).or_default().insert(*subject);
|
||||
}
|
||||
}
|
||||
|
||||
// Failing dependencies. A subject whose dependencies, holdings or
|
||||
// retirement changed has every row re-judged; a route or a placement
|
||||
// that changed re-judges its dependents.
|
||||
let rejudged: BTreeSet<SubjectId> = state
|
||||
.dependencies
|
||||
.changes()
|
||||
.map(|(subject, _, _)| *subject)
|
||||
.chain(state.holdings.changes().map(|(subject, _, _)| *subject))
|
||||
.chain(state.subjects.changes().map(|(subject, _, _)| *subject))
|
||||
.collect();
|
||||
for subject in &rejudged {
|
||||
let rows: Vec<_> = self
|
||||
.failing
|
||||
.range(
|
||||
(*subject, DependencyTarget::Resource(EntityId(Uuid::nil())))
|
||||
..=(*subject, DependencyTarget::Subject(SubjectId(Uuid::max()))),
|
||||
)
|
||||
.copied()
|
||||
.collect();
|
||||
for row in rows {
|
||||
self.failing.remove(&row);
|
||||
}
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for target in state.dependencies.get(subject).into_iter().flatten() {
|
||||
if dependency_unavailable(state, *subject, *target) {
|
||||
self.failing.insert((*subject, *target));
|
||||
}
|
||||
}
|
||||
}
|
||||
let moved: BTreeSet<DependencyTarget> = state
|
||||
.edges
|
||||
.changes()
|
||||
.map(|(edge, _, _)| DependencyTarget::Route(*edge))
|
||||
.chain(state.positions.changes().map(|(subject, _, _)| DependencyTarget::Subject(*subject)))
|
||||
.collect();
|
||||
for target in moved {
|
||||
for dependent in dependents(state, target) {
|
||||
if rejudged.contains(&dependent) {
|
||||
continue;
|
||||
}
|
||||
let row = (dependent, target);
|
||||
if !is_retired(state, dependent) && dependency_unavailable(state, dependent, target) {
|
||||
self.failing.insert(row);
|
||||
} else {
|
||||
self.failing.remove(&row);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The views as a scan of the committed documents derives them, and the
|
||||
/// oracle's other tools (test builds).
|
||||
#[cfg(test)]
|
||||
impl Views {
|
||||
pub(crate) fn rebuild(state: &WorldState) -> Self {
|
||||
let mut views = Self::default();
|
||||
for (subject, held) in state.commitments.iter() {
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for commitment in held.values() {
|
||||
views.live_due.entry(commitment.due).or_default().insert(*subject);
|
||||
}
|
||||
}
|
||||
for (subject, targets) in state.dependencies.iter() {
|
||||
if is_retired(state, *subject) {
|
||||
continue;
|
||||
}
|
||||
for target in targets {
|
||||
if dependency_unavailable(state, *subject, *target) {
|
||||
views.failing.insert((*subject, *target));
|
||||
}
|
||||
}
|
||||
}
|
||||
views
|
||||
}
|
||||
|
||||
/// Content equality, which `PartialEq` deliberately is not.
|
||||
pub(crate) fn same_as(&self, other: &Self) -> bool {
|
||||
self.live_due == other.live_due && self.failing == other.failing
|
||||
}
|
||||
|
||||
/// Damages the view in one place: a stray failing row, else a missing
|
||||
/// due point (the latest, which only its own subjects sit at). False when there
|
||||
/// is nothing to damage that way.
|
||||
pub(crate) fn corrupt_for_test(&mut self, stray: bool) -> bool {
|
||||
if stray {
|
||||
let row = (SubjectId(Uuid::from_u128(1)), DependencyTarget::Subject(SubjectId(Uuid::from_u128(2))));
|
||||
return self.failing.insert(row);
|
||||
}
|
||||
let Some(due) = self.live_due.keys().next_back().copied() else {
|
||||
return false;
|
||||
};
|
||||
self.live_due.remove(&due);
|
||||
true
|
||||
}
|
||||
|
||||
/// The subjects with a dependency on `target`, by a scan of every row.
|
||||
pub(crate) fn dependents_by_scan(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> {
|
||||
state
|
||||
.dependencies
|
||||
.iter()
|
||||
.filter(|(_, held)| held.contains(&target))
|
||||
.map(|(subject, _)| *subject)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn dependents_of(state: &WorldState, target: DependencyTarget) -> Vec<SubjectId> {
|
||||
dependents(state, target)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue