Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 10
Projections
Facts derived from an ordered log of records, with bounded context, a warm-up after a restart, and checks that a restart or an incremental shortcut changes nothing.
An application that stores records, such as the reports its nodes send, wants facts from them: an alert when a source fails three times in a minute, or where each block a node produced ended up. The records arrive late and out of order, and the process that derives the facts restarts. Deriving everything again from the first record after every restart is slow, and the log may not be kept that long. Remembering everything in memory is lost on the restart itself.
A projection derives facts from the log one record at a time, in log order,
and keeps only a window of recent context. After a restart it is warmed up
from that window of the stored log, and it then outputs exactly what it
would have without the restart. That property, and the shortcut a
projection takes to stay fast, each have a check a test can run. The
projections are in causet::projection (the causet-projection crate)Causet_projection (the library causet.projection)causet/projection.
Storing the records, the outputs and the cursor stays the application's
work, with a few rules this page states.
A projection
A projection has a name, for diagnostics, a retention, and a function that processes one record and gives what it derives from it.
It is a type implementing Projection<R>, for records of type R, with
name, retention_ms (None unless overridden) and
process(&mut self, record, out), which pushes its outputs into out. A
record implements LogEntry: its time_ms is its event time, when it
happened rather than when it arrived. Every output implements Keyed.
It is a record { name; retention_ms; process }, made with
projection ?retention_ms ~name process, where process takes one record
and returns its outputs in order. Its State lives in the closure. A
record's event time, when it happened rather than when it arrived, is read
by a function the Projector is given.
It is an object implementing Projection<R, O>, for records of type R
and outputs of type O: a name, a retentionMs (absent unless given)
and process(record), which returns its outputs in order. Its State is its
own: a class's fields or a closure's variables. A record's event time, when
it happened rather than when it arrived, is read by a function the
Projector is given.
Each output has a key, which is an idempotency key: the same derivation
always gives the same key and value, so writing an output twice is
harmless. The output type is free; check_incremental is told how to read its key.The output type is free; checkIncremental is told how to read its key.
The retention is how far back in event time the projection's context reaches. A warm-up feeds it the stored records of that window again. A projection with no retention keeps no context, and is not warmed up.
A projection follows the determinism rules: ordered collections, no I/O, no wall clock. Its only time is the records' own, so it measures its window from the newest event time it has seen, never from the record at hand, which may be late.
Here a projection reports a burst whenever a source has failed three times within a minute. It keeps each source's failures of the last minute, and drops what is older, so it keeps nothing that a warm-up would not feed back:
use std::collections::BTreeMap;
use causet::projection::{Keyed, LogEntry, Projection, Projector};
const MINUTE: u64 = 60_000;
/// A stored report: a source failed, at an event time.
struct Failed { at: u64, source: &'static str }
impl LogEntry for Failed {
fn time_ms(&self) -> u64 { self.at }
}
/// A source failed three times or more within a minute.
#[derive(Debug, PartialEq)]
struct Burst { key: String, failures: usize }
impl Keyed for Burst {
fn key(&self) -> &str { &self.key }
}
#[derive(Default)]
struct Bursts {
/// The newest event time seen: records can arrive late, so the window
/// is measured from here, never from the record at hand.
newest: u64,
/// Each source's failures within the window.
recent: BTreeMap<&'static str, Vec<u64>>,
}
impl Projection<Failed> for Bursts {
type Output = Burst;
fn name(&self) -> &str { "bursts" }
fn retention_ms(&self) -> Option<u64> { Some(MINUTE) }
fn process(&mut self, failed: &Failed, out: &mut Vec<Burst>) {
self.newest = self.newest.max(failed.at);
let times = self.recent.entry(failed.source).or_default();
times.push(failed.at);
let failures = times.iter().filter(|t| **t <= failed.at && *t + MINUTE >= failed.at).count();
if failures >= 3 {
out.push(Burst { key: format!("{}@{}", failed.source, failed.at), failures });
}
// Keep only the window: what a warm-up would feed back.
let horizon = self.newest.saturating_sub(MINUTE);
for times in self.recent.values_mut() {
times.retain(|t| *t >= horizon);
}
self.recent.retain(|_, times| !times.is_empty());
}
}
let log: Vec<Failed> = [(0, "db"), (40_000, "db"), (70_000, "db"), (80_000, "cache"), (100_000, "db")]
.into_iter()
.map(|(at, source)| Failed { at, source })
.collect();
let mut projector = Projector::new();
projector.add_projection(Bursts::default());
let out: Vec<Vec<Burst>> = log.iter().map(|failed| projector.process(failed)).collect();
// At 70 s, the failure at 0 is more than a minute old: only at 100 s are
// there three within a minute.
assert_eq!(out, [vec![], vec![], vec![], vec![], vec![Burst { key: "db@100000".into(), failures: 3 }]]);open Causet_projection
module By_source = Map.Make (String)
let minute = 60_000
(* A stored report: a source failed, at an event time. *)
type failed = { at : int; source : string }
(* A source failed three times or more within a minute. *)
type burst = { key : string; failures : int }
let bursts () =
(* The newest event time seen: records can arrive late, so the window is
measured from here, never from the record at hand. *)
let newest = ref 0 in
(* Each source's failures within the window. *)
let recent = ref By_source.empty in
projection ~name:"bursts" ~retention_ms:minute (fun failed ->
newest := max !newest failed.at;
let times = failed.at :: Option.value (By_source.find_opt failed.source !recent) ~default:[] in
recent := By_source.add failed.source times !recent;
let failures = List.length (List.filter (fun t -> t <= failed.at && t + minute >= failed.at) times) in
let out =
if failures >= 3 then [ { key = Printf.sprintf "%s@%d" failed.source failed.at; failures } ]
else []
in
(* Keep only the window: what a warm-up would feed back. *)
let horizon = max 0 (!newest - minute) in
let keep _ times = match List.filter (fun t -> t >= horizon) times with [] -> None | kept -> Some kept in
recent := By_source.filter_map keep !recent;
out)
let fresh make () =
let projector = Projector.create ~time:(fun failed -> failed.at) in
Projector.add projector (make ());
projector
let log =
List.map (fun (at, source) -> { at; source })
[ (0, "db"); (40_000, "db"); (70_000, "db"); (80_000, "cache"); (100_000, "db") ]
let () =
let projector = fresh bursts () in
let out = List.map (Projector.process projector) log in
(* At 70 s, the failure at 0 is more than a minute old: only at 100 s are
there three within a minute. *)
assert (out = [ []; []; []; []; [ { key = "db@100000"; failures = 3 } ] ])import assert from "node:assert/strict";
import { type Projection, Projector } from "causet/projection";
export const MINUTE = 60_000;
/** A stored report: a source failed, at an event time. */
export interface Failed {
readonly at: number;
readonly source: string;
}
/** A source failed three times or more within a minute. */
export interface Burst {
readonly key: string;
readonly failures: number;
}
export class Bursts implements Projection<Failed, Burst> {
readonly name: string = "bursts";
readonly retentionMs: number = MINUTE;
/**
* The newest event time seen: records can arrive late, so the window is
* measured from here, never from the record at hand.
*/
#newest = 0;
/** Each source's failures within the window. */
#recent = new Map<string, number[]>();
process(failed: Failed): Burst[] {
this.#newest = Math.max(this.#newest, failed.at);
const times = [...(this.#recent.get(failed.source) ?? []), failed.at];
this.#recent.set(failed.source, times);
const failures = times.filter((t) => t <= failed.at && t + MINUTE >= failed.at).length;
const out = failures >= 3 ? [{ key: `${failed.source}@${failed.at}`, failures }] : [];
// Keep only the window: what a warm-up would feed back.
const horizon = Math.max(0, this.#newest - MINUTE);
const kept = new Map<string, number[]>();
for (const [source, times] of this.#recent) {
const recent = times.filter((t) => t >= horizon);
if (recent.length > 0) kept.set(source, recent);
}
this.#recent = kept;
return out;
}
}
/** A projector of one projection, made by `make`. */
export const fresh = (make: () => Projection<Failed, Burst>) => (): Projector<Failed, Burst> => {
const projector = new Projector<Failed, Burst>((failed) => failed.at);
projector.add(make());
return projector;
};
export const log: Failed[] = (
[
[0, "db"],
[40_000, "db"],
[70_000, "db"],
[80_000, "cache"],
[100_000, "db"],
] as const
).map(([at, source]) => ({ at, source }));
const projector = fresh(() => new Bursts())();
const out = log.map((failed) => projector.process(failed));
// At 70 s, the failure at 0 is more than a minute old: only at 100 s are
// there three within a minute.
assert.deepEqual(out, [[], [], [], [], [{ key: "db@100000", failures: 3 }]]);The Projector
A ProjectorProjector.tProjector feeds each record to its
projections in the order they were added, and returns what they derive in
that order. All its projections derive outputs of one type.
new, add_projection, process (or process_into, which pushes into a vector of your own), names and max_retention_msProjector.create ~time, add, process, names and max_retention_msnew Projector(time), add, process, names and maxRetentionMs
are its everyday calls. The others warm it up.
After a restart
A restart rebuilds context, never history. The application starts a new
ProjectorprojectorProjector and asks
warm_up_from(last_time_ms)Projector.warm_up_from projector last_time_mswarmUpFrom(lastTimeMs),
where last_time_mslast_time_mslastTimeMs is the latest event time among the records up to its
cursor. Each projection's window then starts that far before it, by its
retention, and the call returns the earliest of them: the event time from
which to read the stored log. It returns NoneNoneundefined when no projection keeps
context.
The application then feeds the stored records to warmProjector.warmwarm,
in log order, the order live processing saw them. Each record reaches only
the projections whose window it falls in, and what they derive from it is
dropped: a replayed record may lack context older than the window, so its
outputs can differ from those stored, and must not overwrite them. For a log
held in memory, warm_upProjector.warm_upwarmUp does the
whole warm-up over the records up to the cursor.
// The process restarts with its cursor past the first four records, the
// latest of them at 80 s.
let (stored, next) = (&log[..4], &log[4]);
let mut projector = Projector::new();
projector.add_projection(Bursts::default());
// A minute of context: read the stored log from 20 s on, and feed it back
// in log order. What the projection derives meanwhile is dropped.
let from = projector.warm_up_from(80_000).unwrap();
assert_eq!(from, 20_000);
for failed in stored.iter().filter(|failed| failed.at >= from) {
projector.warm(failed);
}
// The failures at 40 s and 70 s are back in context.
assert_eq!(projector.process(next), [Burst { key: "db@100000".into(), failures: 3 }]);
// The same, for a log held in memory.
let mut projector = Projector::new();
projector.add_projection(Bursts::default());
projector.warm_up(stored);
assert_eq!(projector.process(next).len(), 1);let () =
(* The process restarts with its cursor past the first four records, the
latest of them at 80 s. *)
let stored = List.filteri (fun i _ -> i < 4) log and next = List.nth log 4 in
let projector = fresh bursts () in
(* A minute of context: read the stored log from 20 s on, and feed it back
in log order. What the projection derives meanwhile is dropped. *)
let from = Option.get (Projector.warm_up_from projector 80_000) in
assert (from = 20_000);
List.iter (Projector.warm projector) (List.filter (fun failed -> failed.at >= from) stored);
(* The failures at 40 s and 70 s are back in context. *)
assert (Projector.process projector next = [ { key = "db@100000"; failures = 3 } ]);
(* The same, for a log held in memory. *)
let projector = fresh bursts () in
Projector.warm_up projector stored;
assert (List.length (Projector.process projector next) = 1)import assert from "node:assert/strict";
// The process restarts with its cursor past the first four records, the
// latest of them at 80 s.
const stored = log.slice(0, 4);
const next = log[4]!;
let projector = fresh(() => new Bursts())();
// A minute of context: read the stored log from 20 s on, and feed it back
// in log order. What the projection derives meanwhile is dropped.
const from = projector.warmUpFrom(80_000)!;
assert.equal(from, 20_000);
for (const failed of stored.filter((failed) => failed.at >= from)) projector.warm(failed);
// The failures at 40 s and 70 s are back in context.
assert.deepEqual(projector.process(next), [{ key: "db@100000", failures: 3 }]);
// The same, for a log held in memory.
projector = fresh(() => new Bursts())();
projector.warmUp(stored);
assert.equal(projector.process(next).length, 1);The projection crate does not store anything. Storage, the cursor, checkpoints and delivery are the application's, and these rules keep them sound:
- A record's outputs are stored before, or atomically with, the cursor's advance past it, and processing resumes strictly after the cursor.
- An application that stores outputs first and advances the cursor separately writes some outputs again after a crash. That is safe only if its writes are duplicate-safe, by the outputs' keys, and the projection passes the restart check below.
- What a warm-up derives is dropped, never stored.
- Rebuilding outputs, for a new or corrected projection, is possible only where their records are still stored: from the log's beginning, or from a checkpoint.
With its reporting feature, the causet-projection crate implements
LogEntry for the reporting pipeline's Record, so a projection can read
the stored reports as they are, by their
timestamp_ms.
Checking restarts
A projection is sound across restarts when a restart changes nothing it
outputs. check_restarts(fresh, records, restarts)check_restarts fresh records restartscheckRestarts(fresh, records, restarts)
checks it: it runs records through a fresh projector once without a
restart, then once more, restarting before each index in restarts, one
after another, each time with a fresh projector warmed up from the records
before it. It returns the first record whose outputs differ, as a
DifferencedifferenceDifference, the error of a result whose ok is false: record, its index, expected
and actual, its outputs in the two passes, and restart, the cursor of
the latest restart before it. A restart of NoneNoneundefined means the passes
differed with no restart at all: the projections are not deterministic.
pp_difference prints one, and ?equal compares outputs when (=) cannot.differenceMessage prints one. Outputs are compared structurally (structuralEqual, as the other ports compare them), unless the equal option says how.
A retention shorter than what the projection reads is the usual mistake. Here a copy of the burst projection says it keeps 30 seconds; restarted after the record at 80 s, it is warmed up from 50 s on, and misses a failure it needed:
use causet::projection::{Difference, check_restarts};
/// The planted bug: it reads a minute back, but says it keeps 30 seconds.
#[derive(Default)]
struct Short(Bursts);
impl Projection<Failed> for Short {
type Output = Burst;
fn name(&self) -> &str { "short bursts" }
fn retention_ms(&self) -> Option<u64> { Some(30_000) }
fn process(&mut self, failed: &Failed, out: &mut Vec<Burst>) { self.0.process(failed, out) }
}
fn fresh<P: Projection<Failed, Output = Burst> + Default + Send + 'static>() -> Projector<Failed, Burst> {
let mut projector = Projector::new();
projector.add_projection(P::default());
projector
}
// Restart before every record but the first, one after another.
let restarts: Vec<usize> = (1..log.len()).collect();
assert_eq!(check_restarts(fresh::<Bursts>, &log, &restarts), Ok(()));
// Restarted at 80 s, the short one warms up from 50 s on, and misses the
// failure at 40 s.
assert_eq!(
check_restarts(fresh::<Short>, &log, &restarts),
Err(Difference {
restart: Some(4),
record: 4,
expected: vec![Burst { key: "db@100000".into(), failures: 3 }],
actual: vec![],
})
);(* The planted bug: it reads a minute back, but says it keeps 30 seconds. *)
let short () = { (bursts ()) with name = "short bursts"; retention_ms = Some 30_000 }
let () =
(* Restart before every record but the first, one after another. *)
let restarts = List.init (List.length log - 1) succ in
assert (check_restarts (fresh bursts) log restarts = Ok ());
(* Restarted at 80 s, the short one warms up from 50 s on, and misses the
failure at 40 s. *)
assert (
check_restarts (fresh short) log restarts
= Error { restart = Some 4; record = 4; expected = [ { key = "db@100000"; failures = 3 } ]; actual = [] })import assert from "node:assert/strict";
import { checkRestarts } from "causet/projection";
/** The planted bug: it reads a minute back, but says it keeps 30 seconds. */
class Short extends Bursts {
override readonly name = "short bursts";
override readonly retentionMs = 30_000;
}
// Restart before every record but the first, one after another.
const restarts = log.map((_, i) => i).slice(1);
assert.deepEqual(checkRestarts(fresh(() => new Bursts()), log, restarts), { ok: true });
// Restarted at 80 s, the short one warms up from 50 s on, and misses the
// failure at 40 s.
assert.deepEqual(checkRestarts(fresh(() => new Short()), log, restarts), {
ok: false,
error: {
restart: 4,
record: 4,
expected: [{ key: "db@100000", failures: 3 }],
actual: [],
},
});An application whose restart does more, such as seeding a projection from a
checkpoint before the warm-up, checks its own with
check_restarts_with(fresh, restarted, records, restarts)check_restarts_with fresh restarted records restartscheckRestartsWith(fresh, restarted, records, restarts),
where restarted is given the records up to the cursor and returns the
projector ready to go on. A warm-up that sorted the stored records by event
time, for instance, while live processing kept log order, is one this check
finds. The restart points are best generated, with the
generated runs of the testing page, as
chain placement's tests do.
Checking incremental recomputation
A projection that keeps many keys does not recompute all of them on every record: it recomputes only the keys it judges the record to change. A missed key leaves a stale output, and context evicted while a key that reads it is still maintained makes a later recomputation lose facts. Restart equivalence finds neither when the uninterrupted pass is wrong the same way.
check_incremental(projection, reference, records, recompute)check_incremental ~key ~projection ~reference ~recompute recordscheckIncremental({ projection, reference, records, key, recompute })
checks the shortcut. It feeds every record to the projection and to a
reference, usually the same projection keeping everything it sees, keeps
each key's last output as the application would store it, and after each
record asks recompute for each stored key's output now. The first stored
output that differs is returned as a MismatchmismatchMismatch:
the index of the record after which they differ (recordm_recordrecord),
the key, the output stored and the one recomputed.
Here, each id's sightings within a minute of the newest one are counted. A projection that recomputes only the id of the record at hand leaves another id's count stale when the minute moves past its sightings:
use std::collections::BTreeMap;
use causet::projection::{Keyed, LogEntry, Projection, check_incremental};
const MINUTE: u64 = 60_000;
struct Seen { at: u64, id: u64 }
impl LogEntry for Seen {
fn time_ms(&self) -> u64 { self.at }
}
/// How many times an id was seen within a minute of the newest sighting.
#[derive(Clone, Debug, PartialEq)]
struct Recent { key: String, count: usize }
impl Keyed for Recent {
fn key(&self) -> &str { &self.key }
}
#[derive(Default)]
struct Counts {
newest: u64,
seen: BTreeMap<u64, Vec<u64>>,
/// The planted bug: recomputes only the record's own id.
careless: bool,
}
impl Counts {
fn count(&self, id: u64) -> usize {
self.seen[&id].iter().filter(|at| *at + MINUTE >= self.newest).count()
}
fn counts(&self) -> BTreeMap<u64, usize> {
self.seen.keys().map(|id| (*id, self.count(*id))).collect()
}
}
impl Projection<Seen> for Counts {
type Output = Recent;
fn name(&self) -> &str { "recent" }
fn process(&mut self, seen: &Seen, out: &mut Vec<Recent>) {
let before = self.counts();
self.newest = self.newest.max(seen.at);
self.seen.entry(seen.id).or_default().push(seen.at);
// Every id whose count this record changed.
for (id, count) in self.counts() {
let judged = !self.careless || id == seen.id;
if judged && before.get(&id) != Some(&count) {
out.push(Recent { key: id.to_string(), count });
}
}
}
}
// From scratch: the reference's count for the key.
let recompute = |_: &Counts, reference: &Counts, key: &str| {
let id = key.parse().unwrap();
reference.seen.contains_key(&id).then(|| Recent { key: key.to_owned(), count: reference.count(id) })
};
let log: Vec<Seen> = [(0, 1), (10_000, 2), (70_000, 2)].into_iter().map(|(at, id)| Seen { at, id }).collect();
assert_eq!(check_incremental(Counts::default(), Counts::default(), &log, recompute), Ok(()));
let careless = Counts { careless: true, ..Counts::default() };
let mismatch = check_incremental(careless, Counts::default(), &log, recompute).unwrap_err();
// At 70 s, id 1's sighting at 0 is past the minute: it is stored as 1.
assert_eq!((mismatch.record, mismatch.key.as_str(), mismatch.stored.count, mismatch.recomputed.count), (2, "1", 1, 0));module Int_map = Map.Make (Int)
let minute = 60_000
type seen = { at : int; id : int }
(* How many times an id was seen within a minute of the newest sighting. *)
type recent = { key : string; count : int }
type counts = {
mutable newest : int;
mutable sightings : int list Int_map.t;
careless : bool; (** The planted bug: recomputes only the record's own id. *)
}
let count c id = List.length (List.filter (fun at -> at + minute >= c.newest) (Int_map.find id c.sightings))
let counts c = Int_map.mapi (fun id _ -> count c id) c.sightings
let process c s =
let before = counts c in
c.newest <- max c.newest s.at;
c.sightings <- Int_map.update s.id (fun l -> Some (Option.value l ~default:[] @ [ s.at ])) c.sightings;
(* Every id whose count this record changed. *)
Int_map.fold
(fun id n out ->
let judged = (not c.careless) || id = s.id in
if judged && Int_map.find_opt id before <> Some n then { key = string_of_int id; count = n } :: out
else out)
(counts c) []
|> List.rev
(* From scratch: the reference's count for the key. *)
let recompute reference key =
let id = int_of_string key in
if Int_map.mem id reference.sightings then Some { key; count = count reference id } else None
let log = List.map (fun (at, id) -> { at; id }) [ (0, 1); (10_000, 2); (70_000, 2) ]
let check_counts ~careless =
let fresh careless = { newest = 0; sightings = Int_map.empty; careless } in
let projection = fresh careless and reference = fresh false in
Causet_projection.check_incremental
~key:(fun (r : recent) -> r.key)
~projection:(process projection)
~reference:(fun s -> ignore (process reference s))
~recompute:(recompute reference) log
let () =
assert (check_counts ~careless:false = Ok ());
match check_counts ~careless:true with
| Error (m : recent Causet_projection.mismatch) ->
(* At 70 s, id 1's sighting at 0 is past the minute: it is stored as 1. *)
assert ((m.m_record, m.key, m.stored.count, m.recomputed.count) = (2, "1", 1, 0))
| Ok () -> assert falseimport assert from "node:assert/strict";
import { SortedMap } from "causet";
import { checkIncremental, type Projection } from "causet/projection";
const MINUTE = 60_000;
interface Seen {
readonly at: number;
readonly id: number;
}
/** How many times an id was seen within a minute of the newest sighting. */
interface Recent {
readonly key: string;
readonly count: number;
}
class Counts implements Projection<Seen, Recent> {
readonly name = "recent";
newest = 0;
seen = SortedMap.empty<number, readonly number[]>();
/** The planted bug: recomputes only the record's own id. */
readonly careless: boolean;
constructor(careless = false) {
this.careless = careless;
}
count(id: number): number {
return (this.seen.get(id) ?? []).filter((at) => at + MINUTE >= this.newest).length;
}
counts(): Map<number, number> {
return new Map(this.seen.keys().map((id) => [id, this.count(id)]));
}
process(seen: Seen): Recent[] {
const before = this.counts();
this.newest = Math.max(this.newest, seen.at);
this.seen = this.seen.set(seen.id, [...(this.seen.get(seen.id) ?? []), seen.at]);
// Every id whose count this record changed.
const out: Recent[] = [];
for (const [id, count] of this.counts()) {
const judged = !this.careless || id === seen.id;
if (judged && before.get(id) !== count) out.push({ key: String(id), count });
}
return out;
}
}
// From scratch: the reference's count for the key.
const recompute = (_: Counts, reference: Counts, key: string): Recent | undefined => {
const id = Number(key);
return reference.seen.has(id) ? { key, count: reference.count(id) } : undefined;
};
const log: Seen[] = [
[0, 1],
[10_000, 2],
[70_000, 2],
].map(([at, id]) => ({ at: at!, id: id! }));
const records = log;
const key = (r: Recent) => r.key;
assert.deepEqual(
checkIncremental({ projection: new Counts(), reference: new Counts(), records, key, recompute }),
{ ok: true },
);
const careless = new Counts(true);
const result = checkIncremental({
projection: careless,
reference: new Counts(),
records,
key,
recompute,
});
assert(!result.ok);
const mismatch = result.error;
// At 70 s, id 1's sighting at 0 is past the minute: it is stored as 1.
assert.deepEqual(
[mismatch.record, mismatch.key, mismatch.stored.count, mismatch.recomputed.count],
[2, "1", 1, 0],
);recompute returns NoneNoneundefined for a key the projection no longer maintains
(one it evicted, or an output made once and never revised): such a key is
not compared. Nor is a key the projection never output: one that outputs
nothing passes. A test checks that the keys expected are output as well,
for example by running the projection over the log itself and reading what
it outputs.
A real one: chain placement
examples/chain-placementexamples/chain_placementexamples/chain-placement is a
projection of a chain's stored reports into each block's placement. Nodes
report the blocks they produce and the tips they adopt, late and out of
order. For each produced block, the projection finds its facts in the
reports around it by event time (the chain's height then, whether its
parent was seen, who else adopted it, which blocks competed for its slot)
and classifies it as canonical, orphaned, likely_main_chain,
likely_side_chain, stale_parent or unknown. It outputs a block's
status, keyed by its block, whenever the status changes, and its placement
once, when the chain's progress makes it final.
It keeps blocks a fixed retention behind the newest event time, and the
chain reports a kept block may still read, so its declared retention is
that retention plus how far back a block reads. After each record it
recomputes only the blocks the record may have changed.
ChainPlacement::unbounded()Projection.unbounded ()ChainPlacement.unbounded(),
the same projection keeping everything, is the reference for
check_incremental, and status_nowProjection.status_nowstatusNow
recomputes a key. Its tests generate chains, nodes and late reports, and
check restarts, incremental recomputation and the output's contract; what
generation found is pinned in its findings tests.