Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 9
Observability
Every step a Store takes, with its cause, for logs, traces, statistics and your own tools; reports for errors and metrics; and what it all costs.
When an asynchronous system misbehaves, the hard question is why: which input led to this state, which request an answer belonged to, what ran in between. In most code that history is gone by the time you look, or spread over log lines from different threads with nothing to join them on.
In causet it is part of how the Store runs. Every step is an execution with its own ID, the execution that caused it, where it ran and when, and an Event names the Effect it answers. Observers see each execution as it happens, so a log line, a trace or a dashboard can say not only what happened but what caused it. Watching changes nothing: an observer reads, and cannot dispatch, emit or change State.
Beside observers, a reporting pipeline turns what the application decides is worth reporting (errors, metrics, events, healthchecks) into records ready to send, with deduplication, rate limits, sampling and metric aggregation.
This page covers what an observer sees, how to follow a result back to its cause, logging and statistics, checking invariants as the Store runs, reporting, and what all of it costs.
What an observer sees
An observer is a set of callbacks the Store calls at each boundary of a run
(the lifecycle). In Rust it is a type
implementing the Observer trait, whose methods all default to nothing;
in OCaml it is an Observe.t record of functions, and Observe.none does
nothing.
In TypeScript it is any object of the Observer interface,
whose callbacks are all optional and named in camelCase: actionStart,
actionRefused, inlineAction and so on.
The Store calls only the callbacks an observer does not leave as
Observe.none's.The Store calls only the callbacks an observer has
when it is added.
| Callback | When |
|---|---|
action_start, effect_start, event_start |
An execution starts. Its payload is still readable. |
action_finish, effect_finish, event_finish |
Its handler returned; what it queued has not run yet. |
action_settled, event_settled |
Everything it caused has finished or been refused. |
action_refused |
An Action was refused at admission: what refused it, and where it was sent from. |
inline_action |
A child's Action runs inline, within its parent's execution. |
bug, fault |
A bug was reported; the Store faulted. |
bus |
The Event bus's depths, at the start of a drain. |
Each execution comes with its metadata: its ID (a Store numbers executions 1, 2, 3 in the order they start), its time, its depth, its origin (the execution that emitted it, and how), the path and instance of the mount it ran on, and its message's type and kind. Only start callbacks see the payload: after that, its handler owns it.
A panicAn exceptionA throw in an observer faults the Store, like
one anywhere else in a run, except in bug and fault, which report
something already decided.
Here an observer writes one line per execution: its ID, the execution that caused it, its kind and where it ran. The checkout from the overview produces seven:
use causet::guide::shop::*;
use causet::observers::{Execution, MessageView, Observer};
/// One line per execution: its ID, the execution that caused it, its kind
/// and where it ran.
#[derive(Default)]
struct Causes(Vec<String>);
impl Causes {
fn line(&mut self, exec: &Execution<'_>) {
let (id, cause) = (exec.meta.id.0, exec.meta.causal_execution_id().0);
self.0.push(format!("{id} <- {cause} {} {}", exec.kind, exec.path));
}
}
impl Observer for Causes {
fn action_start(&mut self, exec: &Execution<'_>, _: &dyn MessageView) { self.line(exec) }
fn effect_start(&mut self, exec: &Execution<'_>, _: &dyn MessageView) { self.line(exec) }
fn event_start(&mut self, exec: &Execution<'_>, _: &dyn MessageView) { self.line(exec) }
}
let mut shop = Shop::open(StoreOptions::default());
shop.store.add_observer(Causes::default());
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
shop.store.drain_events(16).unwrap();
assert_eq!(shop.store.observer::<Causes>().unwrap().0, [
"1 <- 1 cart.add /cart",
"2 <- 2 cart.checkout /cart",
"3 <- 2 shop.pay /",
"4 <- 3 payments.charge /payments",
"5 <- 4 payments.charge /payments",
"6 <- 6 payments.charged /payments",
"7 <- 6 payments.settled /payments",
]);open Causet
open Causet_guide.Shop
(* One line per execution: its ID, the execution that caused it, its kind
and where it ran. *)
let causes () =
let lines = ref [] in
let line (e : Observe.Execution.t) =
let cause = Meta.causal_execution_id e.meta in
lines := Printf.sprintf "%d <- %d %s %s" e.meta.id cause e.kind e.path :: !lines
in
( {
Observe.none with
action_start = (fun e _ -> line e);
effect_start = (fun e _ -> line e);
event_start = (fun e _ -> line e);
},
fun () -> List.rev !lines )
let () =
let shop = open_ () in
let observer, lines = causes () in
Store.add_observer shop.store observer;
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
ignore (Store.drain_events shop.store 16);
assert (
lines ()
= [
"1 <- 1 cart.add /cart";
"2 <- 2 cart.checkout /cart";
"3 <- 2 shop.pay /";
"4 <- 3 payments.charge /payments";
"5 <- 4 payments.charge /payments";
"6 <- 6 payments.charged /payments";
"7 <- 6 payments.settled /payments";
])import assert from "node:assert/strict";
import { causalExecutionId } from "causet";
import { open } from "causet/guide";
import type { Execution, Observer } from "causet/observers";
/** One line per execution: its ID, the execution that caused it, its kind and where it ran. */
class Causes implements Observer {
readonly lines: string[] = [];
#line(e: Execution): void {
this.lines.push(`${e.meta.id} <- ${causalExecutionId(e.meta)} ${e.kind} ${e.path}`);
}
actionStart(e: Execution): void {
this.#line(e);
}
effectStart(e: Execution): void {
this.#line(e);
}
eventStart(e: Execution): void {
this.#line(e);
}
}
const shop = open();
const causes = new Causes();
shop.store.addObserver(causes);
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price: 4 });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
shop.store.drainEvents(16);
assert.deepEqual(causes.lines, [
"1 <- 1 cart.add /cart",
"2 <- 2 cart.checkout /cart",
"3 <- 2 shop.pay /",
"4 <- 3 payments.charge /payments",
"5 <- 4 payments.charge /payments",
"6 <- 6 payments.charged /payments",
"7 <- 6 payments.settled /payments",
]);Following a result to its cause
TraceLogObserve.Trace_logTraceLog keeps every execution, every
refusal and every inline call, in order. Because each step names its
cause, a question such as "why was this charge settled?" has an exact
answer: walk back from the result to the input that started it. The chain
crosses the gap where the gateway worked on a thread of its own, because
the Event names the Effect it answers.
use causet::guide::shop::*;
use causet::observers::TraceLog;
let mut shop = Shop::open(StoreOptions::default());
shop.store.add_observer(TraceLog::new());
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
shop.store.drain_events(16).unwrap();
// Why was the charge settled? Walk back from the last execution: an Event
// to the Effect it answers, anything else to its cause, up to a root input.
let entries = shop.store.observer::<TraceLog>().unwrap().entries();
let find = |id| entries.iter().find(|e| e.id == id).unwrap();
let mut why = Vec::new();
let mut step = entries.last().unwrap();
loop {
why.push(step.kind);
let back = step.answers.unwrap_or(step.causal);
if back == step.id { break } // a root input
step = find(back);
}
assert_eq!(why, [
"payments.settled", "payments.charged", "payments.charge", "payments.charge",
"shop.pay", "cart.checkout",
]);let () =
let shop = open_ () in
let log = Observe.Trace_log.create () in
Store.add_observer shop.store (Observe.Trace_log.observer log);
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
ignore (Store.drain_events shop.store 16);
(* Why was the charge settled? Walk back from the last execution: an Event
to the Effect it answers, anything else to its cause, up to a root input. *)
let entries = Observe.Trace_log.entries log in
let find id = List.find (fun (e : Observe.Trace_entry.t) -> e.id = id) entries in
let rec why (step : Observe.Trace_entry.t) =
let back = Option.value step.answers ~default:step.causal in
step.kind :: (if back = step.id then [] (* a root input *) else why (find back))
in
assert (
why (List.nth entries (List.length entries - 1))
= [
"payments.settled"; "payments.charged"; "payments.charge"; "payments.charge";
"shop.pay"; "cart.checkout";
])import assert from "node:assert/strict";
import { open } from "causet/guide";
import { TraceLog } from "causet/observers";
const shop = open();
const log = new TraceLog();
shop.store.addObserver(log);
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price: 4 });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
shop.store.drainEvents(16);
// Why was the charge settled? Walk back from the last execution: an Event
// to the Effect it answers, anything else to its cause, up to a root input.
const byId = new Map(log.entries.map((e) => [e.id, e]));
const why: string[] = [];
let step = log.entries.at(-1);
while (step !== undefined) {
why.push(step.kind);
const back = step.answers ?? step.causal;
step = back === step.id ? undefined : byId.get(back); // a root input ends it
}
assert.deepEqual(why, [
"payments.settled",
"payments.charged",
"payments.charge",
"payments.charge",
"shop.pay",
"cart.checkout",
]);The same walk is how a test explains a failure, and how a log line can carry the whole story of a request: the root input, and every step between it and the line.
Logging
causet::observers::LoggerCauset_observers.loggerLogger, from causet/observers, logs
every execution as it starts, through tracing, on the target
causet::execLogs, on the source causet.execa LogSink, on the target causet.exec: the scheduler
time, an optional label (a node's name, say), the category, type, kind,
destination path, metadata and the message's chosen fields. A refused Action
is logged with what refused it and where it came from, a child's Action run
inline with its parent's execution and time.
JavaScript has no standard logging library like Rust's tracing or
OCaml's Logs, so the logger writes to a LogSink, an interface of two
methods: enabled(level, target), asked before a record is built, and
log(record), which takes one record (its level, target, message, and
fields in order). An application adapts it to the logging it uses in a few
lines. setLogSink sets the sink that every logger without its own writes
to, and until it is set nothing is logged. consoleSink() writes each
record to the console as one line, MemorySink keeps them for a test, and
new Logger({ sink, label }) gives one logger a sink of its own and a
label.
Each message type chooses the level it is logged at and which of its fields appear, per type or per variant, so a log shows what matters and leaves out what must not be logged:
use causet::{Action, Message};
#[derive(Debug, Action)]
#[causet(type = "withdrawal.action", log(level = "debug"))]
enum WithdrawalAction {
/// Logged at info, with its amount only: the account stays out of the logs.
#[causet(log(level = "info", fields(amount)))]
Withdraw { account: String, amount: u64 },
Cancel,
}
assert_eq!(WithdrawalAction::Cancel.kind(), "withdrawal.cancel");type withdrawal_action =
| Withdraw of { account : string; amount : int } [@level Info] [@fields amount]
(** Logged at info, with its amount only: the account stays out of the logs. *)
| Cancel
[@@deriving message ~name:"withdrawal.action" ~level:Debug]import assert from "node:assert/strict";
import { message } from "causet";
type WithdrawalAction =
| { readonly kind: "withdrawal.withdraw"; readonly account: string; readonly amount: number }
| { readonly kind: "withdrawal.cancel" };
const withdrawalAction = message<WithdrawalAction>("withdrawal.action", {
level: "debug",
// A withdrawal is logged at info, with its amount only: the account stays
// out of the logs.
levels: { "withdrawal.withdraw": "info" },
fields: { "withdrawal.withdraw": ["amount"] },
});
const withdraw = { kind: "withdrawal.withdraw", account: "savings", amount: 30 } as const;
assert.equal(withdrawalAction.level(withdraw), "info");
assert.deepEqual(withdrawalAction.fields(withdraw), [["amount", "30"]]);
assert.equal(withdrawalAction.level({ kind: "withdrawal.cancel" }), "debug");Reducers and handlers never read the system clock, so their own log lines
are stamped with the execution's time:
causet::observers::info!(meta.time; job = id, "stale job")Causet_observers.log_at Logs.Info ~time:meta.time "stale job %d" idlogAt("info", meta.time, "stale job", { job: id }).
A log from a simulated run then reads in simulated time, and lines up with
the trace.
Statistics
causet::observers::StatsCauset_observers.StatsStats, from causet/observers, counts
executions and their durations by category, type and kind, in nine ranges
from under 1 µs to over 50 ms. A snapshot is plain data; serving it, as
metrics or a status page, is the application's business.
use causet::guide::shop::*;
use causet::observers::{Logger, Stats};
let mut shop = Shop::open(StoreOptions::default());
shop.store.add_observer(Logger::new()); // one `tracing` event per execution
shop.store.add_observer(Stats::new()); // counts and durations, by kind
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
shop.store.drain_events(16).unwrap();
let stats = shop.store.observer::<Stats>().unwrap().snapshot();
assert_eq!(stats.actions["payments.action"]["payments.charge"].calls(), 1);
assert_eq!(stats.events["payments.charged"]["payments.charged"].calls(), 1);let () =
let open Causet_observers in
let shop = open_ () in
(* One Logs message per execution. *)
Store.add_observer shop.store (logger ());
(* Counts and durations, by kind. *)
let stats = Stats.create () in
Store.add_observer shop.store (Stats.observer stats);
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
ignore (Store.drain_events shop.store 16);
let s = Stats.snapshot stats in
let calls category ty kind = Duration_ranges.calls (List.assoc kind (List.assoc ty category)) in
assert (calls s.actions "payments.action" "payments.charge" = 1);
assert (calls s.events "payments.charged" "payments.charged" = 1)import assert from "node:assert/strict";
import { open } from "causet/guide";
import { Logger, MemorySink, Stats } from "causet/observers";
const shop = open();
// One record per execution, into a sink; here one that keeps them.
const logs = new MemorySink("debug");
shop.store.addObserver(new Logger({ sink: logs }));
// Counts and durations, by kind.
const stats = new Stats();
shop.store.addObserver(stats);
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price: 4 });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
shop.store.drainEvents(16);
assert.equal(logs.records.length, 7);
const s = stats.snapshot();
assert.equal(s.actions.get("payments.action")?.get("payments.charge")?.calls(), 1);
assert.equal(s.events.get("payments.charged")?.get("payments.charged")?.calls(), 1);Invariants in production
An observer sees steps; an invariant judges the State they leave. A Store
can check the application's own invariants as it runs, in production as
in a test: Store::add_invariantStore.add_invariantstore.addInvariant
takes a name and a checker, which reads the whole State and says what is
wrong with it, if anything.
A checker runs once as it is added, then after every root input that settles: an admitted Action dispatched to the Store, or one drained Event, each with everything it caused. It does not run after a refused Action or an empty drain, nor once the Store has faulted, and it never sees the steps inside a root input, only the State between two of them.
A violation is a bug report, not a fault.
It reaches observers at phase Phase::Invariant(name)Invariant name{ kind: "invariant", name },
placed at the root input it settled after (at none as it is added), with
the invariant's name as a
field and its registration as the source
(the caller of add_invariantthe position passed as its ?posthe caller of addInvariant, read from the stack).
The Store goes on, and checks again after the next root input: a State
that stays wrong is reported each time. A checker that
panicsraisesthrows does not fault the Store either: it is
reported at Phase::InvariantPanic(name)Invariant_panic name{ kind: "invariantPanic", name }
and disabled, since what it remembers may be half updated.
Here the shop's orders must all be accounted for: each one paid, declined
or still pending. A charge sent straight to payments, with no order behind
it, breaks that, and a BugLogObserve.Bug_logBugLog catches
the report:
use causet::guide::shop::*;
use causet::ExecutionId;
use causet::observers::{BugLog, Phase};
let mut shop = Shop::open(StoreOptions::default());
shop.store.add_observer(BugLog::new());
// Every order the shop took is paid, declined or still pending.
shop.store.add_invariant("every order is accounted for", |state: &ShopState, _| {
let p = &state.payments;
let charges = (p.paid.len() + p.declined.len() + p.pending.len()) as u64;
if charges == state.orders { return Ok(()) }
Err(format!("orders {}, charges {charges}", state.orders))
});
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
shop.store.drain_events(16).unwrap();
shop.store.observer::<BugLog>().unwrap().assert_none();
// A charge sent straight to payments, with no order behind it.
shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 9 }).unwrap();
let report = &shop.store.observer::<BugLog>().unwrap().reports()[0];
assert_eq!(report.message, "orders 1, charges 2");
let place = report.place.as_ref().unwrap();
assert_eq!(place.phase, Phase::Invariant("every order is accounted for"));
assert_eq!(place.at, Some(ExecutionId(8))); // the root input that broke it
// The Store goes on, and the invariant is checked again after each root input.
shop.store.drain_events(16).unwrap();
assert_eq!(shop.store.observer::<BugLog>().unwrap().reports().len(), 2);let () =
let shop = open_ () in
let bugs = Observe.Bug_log.create () in
Store.add_observer shop.store (Observe.Bug_log.observer bugs);
(* Every order the shop took is paid, declined or still pending. *)
Store.add_invariant ~pos:__POS__ shop.store "every order is accounted for"
(fun state _ ->
let p = state.payments in
let charges =
List.length p.paid + List.length p.declined + Pending.cardinal p.pending
in
if charges = state.orders then Ok ()
else Error (Printf.sprintf "orders %d, charges %d" state.orders charges));
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
ignore (Store.drain_events shop.store 16);
assert (Observe.Bug_log.reports bugs = []);
(* A charge sent straight to payments, with no order behind it. *)
ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 9 }));
(match Observe.Bug_log.reports bugs with
| [ { Observe.Bug_report.message; place = Some { phase; at; _ }; _ } ] ->
assert (message = "orders 1, charges 2");
assert (phase = Observe.Invariant "every order is accounted for");
assert (at = Some 8) (* the root input that broke it *)
| _ -> assert false);
(* The Store goes on, and the invariant is checked again after each root input. *)
ignore (Store.drain_events shop.store 16);
assert (List.length (Observe.Bug_log.reports bugs) = 2)import assert from "node:assert/strict";
import { open } from "causet/guide";
import { BugLog } from "causet/observers";
const shop = open();
const bugs = new BugLog();
shop.store.addObserver(bugs);
// Every order the shop took is paid, declined or still pending.
shop.store.addInvariant("every order is accounted for", (state) => {
const p = state.payments;
const charges = p.paid.length + p.declined.length + p.pending.size;
return charges === state.orders ? undefined : `orders ${state.orders}, charges ${charges}`;
});
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price: 4 });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
shop.store.drainEvents(16);
bugs.assertNone();
// A charge sent straight to payments, with no order behind it.
shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 9 });
const [report] = bugs.reports;
assert.equal(report?.message, "orders 1, charges 2");
assert.deepEqual(report.place?.phase, { kind: "invariant", name: "every order is accounted for" });
assert.equal(report.place?.at, 8); // the root input that broke it
// The Store goes on, and the invariant is checked again after each root input.
shop.store.drainEvents(16);
assert.equal(bugs.reports.length, 2);A checker can remember earlier steps: what its closure captureswhat its closure holds, such as a refwhat its closure holds, such as a let
is its memory, and it is told why it runs, as
an InvariantStep: Added, Restored (moved into a new Store) or
Settledan invariant_step: Added, Restored (put back by
Causet_test as a node restarts) or Settled_stepan InvariantStep: { step: "added" },
{ step: "restored" } (moved into a new Store, as Node.restart does) or
{ step: "settled" }, the last with the root input's execution,
category, path, kind and time. This one checks that no paid charge is ever
forgotten, which no single State can show, and reports each loss once:
use causet::guide::shop::*;
use causet::invariants::InvariantStep;
use causet::observers::BugLog;
/// No paid charge is ever forgotten. The checker remembers how many it has
/// seen, and reports each loss once, saying when it saw it.
fn never_forgets() -> impl FnMut(&ShopState, &InvariantStep<'_>) -> Result<(), String> + Send {
let mut seen = 0;
move |state, step| {
let paid = state.payments.paid.len();
let before = std::mem::replace(&mut seen, paid);
if paid >= before { return Ok(()) }
let when = match step {
InvariantStep::Added => "when added".to_string(),
InvariantStep::Restored => "on restore".to_string(),
InvariantStep::Settled { kind, .. } => format!("after {kind}"),
};
Err(format!("{before} paid, then {paid} {when}"))
}
}
let mut shop = Shop::open(StoreOptions::default());
shop.store.add_observer(BugLog::new());
shop.store.add_invariant("paid charges are kept", never_forgets());
for price in [4, 6] {
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
shop.store.drain_events(16).unwrap();
}
shop.store.observer::<BugLog>().unwrap().assert_none();(* No paid charge is ever forgotten. The checker remembers how many it has
seen, and reports each loss once, saying when it saw it. *)
let never_forgets () =
let seen = ref 0 in
fun (state : shop_state) (step : invariant_step) ->
let paid = List.length state.payments.paid in
let before = !seen in
seen := paid;
if paid >= before then Ok ()
else
let when_ =
match step with
| Added -> "when added"
| Restored -> "on restore"
| Settled_step { kind; _ } -> "after " ^ kind
in
Error (Printf.sprintf "%d paid, then %d %s" before paid when_)
let buy shop price =
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
ignore (Store.drain_events shop.store 16)
let () =
let shop = open_ () in
let bugs = Observe.Bug_log.create () in
Store.add_observer shop.store (Observe.Bug_log.observer bugs);
Store.add_invariant ~pos:__POS__ shop.store "paid charges are kept" (never_forgets ());
buy shop 4;
buy shop 6;
assert (Observe.Bug_log.reports bugs = [])import { open, type Shop, type ShopState } from "causet/guide";
import type { InvariantCheck } from "causet/invariants";
import { BugLog } from "causet/observers";
/**
* No paid charge is ever forgotten. The checker remembers how many it has
* seen, and reports each loss once, saying when it saw it.
*/
function neverForgets(): InvariantCheck<ShopState> {
let seen = 0;
return (state, step) => {
const paid = state.payments.paid.length;
const before = seen;
seen = paid;
if (paid >= before) return undefined;
const when =
step.step === "added"
? "when added"
: step.step === "restored"
? "on restore"
: `after ${step.kind}`;
return `${before} paid, then ${paid} ${when}`;
};
}
function buy(shop: Shop, price: number): void {
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
shop.store.drainEvents(16);
}
const shop = open();
const bugs = new BugLog();
shop.store.addObserver(bugs);
shop.store.addInvariant("paid charges are kept", neverForgets());
buy(shop, 4);
buy(shop, 6);
bugs.assertNone();That memory lives in the checker, so it can outlast the Store.
Store::take_invariantsStore.take_invariantsstore.takeInvariants() takes the
invariants out, with what they remember, for the Store that replaces this
one, say one rebuilt from a snapshot after a fault;
Store::restore_invariantsStore.restore_invariantsstore.restoreInvariants moves
them into the new Store and runs each on its State as RestoredRestoredrestored, before
any root input. One disabled in the old Store stays disabled. Here the new
Store starts from a stale snapshot, and the invariant notices what it lost:
use causet::observers::BugLog;
let mut shop = Shop::open(StoreOptions::default());
shop.store.add_invariant("paid charges are kept", never_forgets());
let mut snapshots = Vec::new();
for price in [4, 6] {
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
shop.store.drain_events(16).unwrap();
snapshots.push(shop.store.state().clone());
}
// The Store is replaced, and its successor starts from a snapshot: here a
// stale one, taken before the second charge was paid. The invariants move
// across with what they remember.
let invariants = shop.store.take_invariants();
let services = ShopServices { gateway: Box::new(ApproveUpTo(100)) };
let state = snapshots.remove(0);
let (mut store, _sink) = Store::open(shop.store.protocol(), state, services, StoreOptions::default());
store.add_observer(BugLog::new());
store.restore_invariants(invariants);
store.observer::<BugLog>().unwrap().assert_messages(&["2 paid, then 1 on restore"]);let () =
let shop = open_ () in
Store.add_invariant ~pos:__POS__ shop.store "paid charges are kept" (never_forgets ());
buy shop 4;
let stale = Store.state shop.store in
buy shop 6;
(* The Store is replaced, and its successor starts from a snapshot: here a
stale one, taken before the second charge was paid. The invariants move
across with what they remember. *)
let invariants = Store.take_invariants shop.store in
Store.close shop.store;
let services = { gateway = approve_up_to 100 } in
let store, _sink = Store.open_protocol (Store.protocol shop.store) ~state:stale ~services in
let bugs = Observe.Bug_log.create () in
Store.add_observer store (Observe.Bug_log.observer bugs);
Store.restore_invariants store invariants;
match Observe.Bug_log.reports bugs with
| [ { Observe.Bug_report.message; _ } ] -> assert (message = "2 paid, then 1 on restore")
| _ -> assert falseimport { Store } from "causet";
import { approveUpTo, open } from "causet/guide";
import { BugLog } from "causet/observers";
const shop = open();
shop.store.addInvariant("paid charges are kept", neverForgets());
buy(shop, 4);
// State is immutable: the State as it is now is a snapshot.
const stale = shop.store.state;
buy(shop, 6);
// The Store is replaced, and its successor starts from a snapshot: here a
// stale one, taken before the second charge was paid. The invariants move
// across with what they remember.
const invariants = shop.store.takeInvariants();
shop.store.close();
const services = { gateway: approveUpTo(100) };
const { store } = Store.open(shop.store.protocol, { state: stale, services });
const bugs = new BugLog();
store.addObserver(bugs);
store.restoreInvariants(invariants);
bugs.assertMessages(["2 paid, then 1 on restore"]);The memory moves between Stores in one process; it does not survive the process.
A set of invariants taken from one Store goes to one other Store only: the
types cannot stop it being given twice. Adding the same checker again
works too, since its memory is in what its closure holds; it then runs as
Added, not Restored, and one disabled in the old Store runs again:
A set of invariants taken from one Store goes to one other Store only: the
types cannot stop it being given twice. Adding the same checker again
works too, since its memory is in what its closure holds; it then runs as
added, not restored, and one disabled in the old Store runs again:
let () =
let shop = open_ () in
let kept = never_forgets () in
Store.add_invariant ~pos:__POS__ shop.store "paid charges are kept" kept;
buy shop 4;
let stale = Store.state shop.store in
buy shop 6;
Store.close shop.store;
(* The Store is replaced, and its successor starts from a stale snapshot,
taken before the second charge was paid. The same checker, added
again, still remembers. *)
let services = { gateway = approve_up_to 100 } in
let store, _sink = Store.open_protocol (Store.protocol shop.store) ~state:stale ~services in
let bugs = Observe.Bug_log.create () in
Store.add_observer store (Observe.Bug_log.observer bugs);
Store.add_invariant ~pos:__POS__ store "paid charges are kept" kept;
match Observe.Bug_log.reports bugs with
| [ { Observe.Bug_report.message; _ } ] -> assert (message = "2 paid, then 1 when added")
| _ -> assert falseimport { Store } from "causet";
import { approveUpTo, open } from "causet/guide";
import { BugLog } from "causet/observers";
const shop = open();
const kept = neverForgets();
shop.store.addInvariant("paid charges are kept", kept);
buy(shop, 4);
const stale = shop.store.state;
buy(shop, 6);
shop.store.close();
// The Store is replaced, and its successor, on the same Protocol, starts
// from a stale snapshot, taken before the second charge was paid. The same
// checker, added again, still remembers.
const services = { gateway: approveUpTo(100) };
const { store } = Store.open(shop.store.protocol, { state: stale, services });
const bugs = new BugLog();
store.addObserver(bugs);
store.addInvariant("paid charges are kept", kept);
bugs.assertMessages(["2 paid, then 1 when added"]);With no invariant, the Store checks nothing; with some, it runs every checker on the whole State after each root input, so their cost is their own. Tests check invariants the same way and stop at a violation; the testing page covers them.
Reporting
Observers see every step; most of them are not worth sending anywhere. A
report is what the application decides is: an error, a measurement, a
notable event, a healthcheck. The reporting pipeline,
the causet-reporting cratethe causet-reporting packagethe causet-reporting package,
takes each report and decides whether it goes out:
- Deduplication drops a report seen again within a window (five seconds by default, for errors), by its dedupe key or its content.
- Rate limits keep at most so many reports per source in any window.
- Sampling keeps a share of each kind, decided by the report's hash, so the same report is always kept or always dropped, in every run.
- Metric aggregation folds a metric's numeric fields over a window into one report: count, minimum, maximum, average, p50 and p95 (by nearest rank: the p95 of four values is the largest, and a NaN ranks above every number) and a sample of values, with counts for the fields it groups by.
- Records come out numbered, stamped and ready to write as one JSON line each; a dump writes them to files rotated by size, and a context trail keeps the last steps of a workflow to attach to an error.
The pipeline knows nothing of the Store. An application wires it in as a Service: the reducer emits an Effect that says, as plain data, what happened; the Effect handler builds the report and hands it to the pipeline, stamped with the execution's time; and the application delivers the records however it likes. Reports are built in one place, the handler, so the reducer stays a pure transition.
use causet::*;
use causet_reporting::{Config, Pipeline, Record, Report, ReportKind, Source, payload_builder};
/// The reporting Service: the pipeline, and where its records go.
struct Reporting {
pipeline: Pipeline,
delivered: Vec<Record>,
}
#[derive(Debug, Action)]
#[causet(type = "orders.action", kind = "orders.fail")]
struct Fail {
order: u64,
}
/// What went wrong, as data: the reducer describes it, the Service builds
/// the report.
#[derive(Debug, Effect)]
#[causet(type = "orders.report", kind = "orders.failed")]
struct Failed {
order: u64,
}
struct Orders;
impl Component for Orders {
type State = u32;
type Service = Reporting;
type Action = Fail;
type Effect = Failed;
type Output = Never;
fn reduce(mut ctx: ComponentContext<'_, Self>, Fail { order }: Fail, _: &ActionMeta) {
*ctx.state_mut() += 1;
ctx.into_emitter().emit_effect(Failed { order });
}
fn handle(mut ctx: EffectContext<'_, Self>, Failed { order }: Failed, meta: &EffectMeta) {
let payload = payload_builder!({ event: "order_failed", order }).finish();
let report = Report::new(ReportKind::Error, Source::new("orders"), payload);
// Stamped with the execution's time, in milliseconds, never the system clock.
let reporting = ctx.service();
let outcome = reporting.pipeline.accept_report(meta.time / 1_000_000, report);
reporting.delivered.extend(outcome.record);
}
}
let reporting = Reporting { pipeline: Pipeline::new(Config::default()), delivered: Vec::new() };
let options = StoreOptions::with_clock(ManualClock::new(5_000_000_000));
let (mut store, _sink) = Store::start::<Orders>(0u32, reporting, options).unwrap();
let orders = store.mount(&root::<Orders>()).unwrap();
store.dispatch_to(&orders, Fail { order: 7 }).unwrap();
let delivered = &store.services().delivered;
assert_eq!(delivered.len(), 1);
assert_eq!(delivered[0].timestamp_ms, 5_000);(* The reporting Service: the pipeline, and where its records go. *)
type reporting = {
pipeline : Causet_reporting.Pipeline.t;
mutable delivered : Causet_reporting.Report.Record.t list;
}
type orders_action = Fail of { order : int } [@@deriving message ~name:"orders.action"]
(* What went wrong, as data: the reducer describes it, the Service builds the
report. *)
type orders_report = Failed of { order : int }
[@@deriving message ~name:"orders.report"]
let orders : (int, reporting, orders_action, orders_report, never) Component.t =
Component.make ~name:"orders" ~actions:orders_action_message
~effects:orders_report_message ~outputs:Message.never
~reduce:(fun ctx (Fail { order }) _ ->
Ctx.update ctx (( + ) 1);
Ctx.emit_effect ctx (Failed { order }))
~handle:(fun ctx (Failed { order }) (meta : Meta.t) ->
let open Causet_reporting in
let payload =
Payload.create "order_failed"
|> Payload.field "order" (Payload.uint order)
|> Payload.finish
in
let report = Report.make Report.Error ~source:"orders" payload in
(* Stamped with the execution's time, in milliseconds, never the system clock. *)
let reporting = Effect_ctx.service ctx in
let outcome =
Pipeline.accept_report reporting.pipeline (meta.time / 1_000_000) report
in
reporting.delivered <- reporting.delivered @ Option.to_list outcome.record)
()import { component, message } from "causet";
import { makeReport, PayloadBuilder, type Pipeline, type ReportRecord } from "causet-reporting";
/** The reporting Service: the pipeline, and where its records go. */
interface Reporting {
readonly pipeline: Pipeline;
readonly delivered: ReportRecord[];
}
type OrdersAction = { readonly kind: "orders.fail"; readonly order: number };
const ordersAction = message<OrdersAction>("orders.action");
/** What went wrong, as data: the reducer describes it, the Service builds the report. */
type OrdersReport = { readonly kind: "orders.failed"; readonly order: number };
const ordersReport = message<OrdersReport>("orders.report");
const orders = component<number, Reporting>()({
name: "orders",
actions: ordersAction,
effects: ordersReport,
reduce(ctx, { order }) {
ctx.update((failed) => failed + 1);
ctx.emitEffect({ kind: "orders.failed", order });
},
handle(ctx, { order }, meta) {
const payload = PayloadBuilder.create("order_failed").uint("order", order).finish();
const report = makeReport("error", "orders", payload);
// Stamped with the execution's time, in milliseconds, never the system clock.
const { pipeline, delivered } = ctx.service;
const outcome = pipeline.acceptReport(Math.floor(meta.time / 1_000_000), report);
if (outcome.record !== undefined) delivered.push(outcome.record);
},
});let () =
let reporting = { pipeline = Pipeline.create (); delivered = [] } in
let clock = Clock.Manual.clock (Clock.Manual.create 5_000_000_000) in
let store, _sink = Store.start_exn ~clock orders ~state:0 ~services:reporting in
let m = Store.mount_exn store (Path.root orders) in
ignore (Store.dispatch_exn store m (Fail { order = 7 }));
match (Store.services store).delivered with
| [ record ] -> assert (record.timestamp_ms = 5_000)
| _ -> assert falseimport assert from "node:assert/strict";
import { ManualClock, rootPath, Store } from "causet";
import { Pipeline } from "causet-reporting";
const reporting: Reporting = { pipeline: new Pipeline(), delivered: [] };
const clock = new ManualClock(5_000_000_000);
const { store } = Store.startOrThrow(orders, { state: 0, services: reporting, clock });
const m = store.mountOrThrow(rootPath(orders));
store.dispatchOrThrow(m, { kind: "orders.fail", order: 7 });
const [record, ...more] = store.services.delivered;
assert.equal(more.length, 0);
assert.equal(record?.timestampMs, 5_000);Two failures for the same reason within the dedupe window make one record:
use causet_reporting::{Config, Pipeline, Report, ReportKind, Source, payload_builder};
const PAYMENTS: Source = Source::new("payments");
/// A declined charge, as an error report deduplicated by its reason.
fn declined(amount: u64, reason: &str) -> Report {
let (payload, dedupe) = payload_builder!({ event: "charge_declined", amount, reason })
.finish_with_dedupe_key_fmt(format_args!("charge_declined:{reason}"));
Report::new(ReportKind::Error, PAYMENTS, payload).with_dedupe_key(Some(dedupe))
}
let mut pipeline = Pipeline::new(Config::default());
// Times are milliseconds of the Store's clock, so a test chooses them.
let first = pipeline.accept_report(1_000, declined(30, "insufficient_funds"));
let again = pipeline.accept_report(1_200, declined(45, "insufficient_funds"));
let other = pipeline.accept_report(1_300, declined(10, "card_expired"));
assert!(first.record.is_some() && other.record.is_some());
assert!(again.record.is_none()); // the same error, within the dedupe window
assert_eq!((pipeline.stats.accepted, pipeline.stats.dropped_deduped), (2, 1));
// One JSON line, ready to dump or send.
let mut line = Vec::new();
first.record.unwrap().write_json(&mut line).unwrap();
let line = String::from_utf8(line).unwrap();
assert!(line.contains(r#""kind":"error","source":"payments""#));
assert!(line.contains(r#""event":"charge_declined","amount":30,"reason":"insufficient_funds""#));open Causet_reporting
let contains line part =
let n = String.length part in
let rec at i = i + n <= String.length line && (String.sub line i n = part || at (i + 1)) in
at 0
(* A declined charge, as an error report deduplicated by its reason. *)
let declined amount reason =
let payload, dedupe_key =
Payload.create "charge_declined"
|> Payload.field "amount" (Payload.uint amount)
|> Payload.field "reason" (Payload.string reason)
|> Payload.finish_with_dedupe_key ("charge_declined:" ^ reason)
in
Report.make ~dedupe_key Report.Error ~source:"payments" payload
let () =
let pipeline = Pipeline.create () in
(* Times are milliseconds of the Store's clock, so a test chooses them. *)
let first = Pipeline.accept_report pipeline 1_000 (declined 30 "insufficient_funds") in
let again = Pipeline.accept_report pipeline 1_200 (declined 45 "insufficient_funds") in
let other = Pipeline.accept_report pipeline 1_300 (declined 10 "card_expired") in
assert (Option.is_some first.record && Option.is_some other.record);
assert (Option.is_none again.record) (* the same error, within the dedupe window *);
let stats = Pipeline.stats pipeline in
assert ((stats.accepted, stats.dropped_deduped) = (2, 1));
(* One JSON line, ready to dump or send. *)
let line = Report.Record.to_json (Option.get first.record) in
assert (contains line {|"kind":"error","source":"payments"|});
assert (contains line {|"event":"charge_declined","amount":30,"reason":"insufficient_funds"|})import assert from "node:assert/strict";
import { makeReport, PayloadBuilder, Pipeline, type Report, recordToJson } from "causet-reporting";
/** A declined charge, as an error report deduplicated by its reason. */
function declined(amount: number, reason: string): Report {
const { payload, dedupeKey } = PayloadBuilder.create("charge_declined")
.uint("amount", amount)
.string("reason", reason)
.finishWithDedupeKey(`charge_declined:${reason}`);
return makeReport("error", "payments", payload, dedupeKey);
}
const pipeline = new Pipeline();
// Times are milliseconds of the Store's clock, so a test chooses them.
const first = pipeline.acceptReport(1_000, declined(30, "insufficient_funds"));
const again = pipeline.acceptReport(1_200, declined(45, "insufficient_funds"));
const other = pipeline.acceptReport(1_300, declined(10, "card_expired"));
assert.ok(first.record !== undefined && other.record !== undefined);
assert.equal(again.record, undefined); // the same error, within the dedupe window
assert.deepEqual([pipeline.stats.accepted, pipeline.stats.droppedDeduped], [2, 1]);
// One JSON line, ready to dump or send. Its run ID varies from run to run.
const line = recordToJson(first.record).replace(/"run_id":"\w+"/, '"run_id":"…"');
assert.equal(
line,
'{"id":1,"timestamp_ms":1000,"kind":"error","source":"payments","payload":{"run_id":"…","event":"charge_declined","amount":30,"reason":"insufficient_funds"}}',
);A record is one JSON object, with the pipeline's run ID on its first record (here it varies from run to run):
{"id":1,"timestamp_ms":1000,"kind":"error","source":"payments","payload":{"run_id":"28Sqb3m9uz2","event":"charge_declined","amount":30,"reason":"insufficient_funds"}}
A metric policy can aggregate a measurement instead of sending each one. Here four checkouts become one report when the minute is up:
use causet_reporting::{
Config, MetricAggregateConfig, MetricConfig, MetricPolicy, Pipeline, Report, ReportKind,
Source, payload_builder,
};
const SHOP: Source = Source::new("shop");
let mut pipeline = Pipeline::new(Config {
metrics: MetricConfig {
policies: vec![MetricPolicy {
source: SHOP,
event: "checkout".into(),
// Aggregated only: no checkout report goes out on its own.
sample_rate: Some(0.0),
aggregate: Some(MetricAggregateConfig {
window_ms: 60_000,
fields: vec!["took_ms".into()],
group_by: vec!["ok".into()],
max_groups: 4,
samples: 16,
}),
}],
},
..Config::default()
});
for (at, (took_ms, ok)) in [(120u64, true), (80, true), (95, true), (300, false)].into_iter().enumerate() {
let report = payload_builder!({ event: "checkout", took_ms, ok }).finish();
let outcome = pipeline.accept_report(1_000 + at as u64, Report::new(ReportKind::Metric, SHOP, report));
assert!(outcome.record.is_none());
}
// When the minute is up, one report sums it up.
let mut aggregates = Vec::new();
pipeline.flush_aggregates_into(61_000, &mut aggregates);
assert_eq!(aggregates.len(), 1);
let record = pipeline.accept_aggregate_report(61_000, aggregates.remove(0)).unwrap();
let mut line = Vec::new();
record.write_json(&mut line).unwrap();
let line = String::from_utf8(line).unwrap();
assert!(line.contains(r#""event":"metric_aggregate""#));
assert!(line.contains(r#""count":4,"min":80,"max":300,"avg":148.75"#));
assert!(line.contains(r#""groups":{"ok":{"false":1,"true":3}}"#));let () =
let policy =
{
Config.Policy.source = "shop";
event = "checkout";
(* Aggregated only: no checkout report goes out on its own. *)
sample_rate = Some 0.0;
aggregate =
Some
{
Config.Aggregate.window_ms = 60_000;
fields = [ "took_ms" ];
group_by = [ "ok" ];
max_groups = 4;
samples = 16;
};
}
in
let pipeline = Pipeline.create ~config:{ Config.default with metrics = [ policy ] } () in
List.iteri
(fun at (took_ms, ok) ->
let payload =
Payload.create "checkout"
|> Payload.field "took_ms" (Payload.uint took_ms)
|> Payload.field "ok" (Payload.bool ok)
|> Payload.finish
in
let outcome =
Pipeline.accept_report pipeline (1_000 + at) (Report.make Report.Metric ~source:"shop" payload)
in
assert (Option.is_none outcome.record))
[ (120, true); (80, true); (95, true); (300, false) ];
(* When the minute is up, one report sums it up. *)
match Pipeline.flush_aggregates pipeline 61_000 with
| [ aggregate ] ->
let record = Option.get (Pipeline.accept_aggregate_report pipeline 61_000 aggregate) in
let line = Report.Record.to_json record in
assert (contains line {|"event":"metric_aggregate"|});
assert (contains line {|"count":4,"min":80,"max":300,"avg":148.75|});
assert (contains line {|"groups":{"ok":{"false":1,"true":3}}|})
| _ -> assert falseimport assert from "node:assert/strict";
import {
defaultConfig,
makeReport,
PayloadBuilder,
Pipeline,
recordToJson,
} from "causet-reporting";
const pipeline = new Pipeline({
...defaultConfig,
metrics: [
{
source: "shop",
event: "checkout",
// Aggregated only: no checkout report goes out on its own.
sampleRate: 0,
aggregate: {
windowMs: 60_000,
fields: ["took_ms"],
groupBy: ["ok"],
maxGroups: 4,
samples: 16,
},
},
],
});
const checkouts = [
[120, true],
[80, true],
[95, true],
[300, false],
] as const;
for (const [at, [tookMs, ok]] of checkouts.entries()) {
const payload = PayloadBuilder.create("checkout").uint("took_ms", tookMs).bool("ok", ok).finish();
const outcome = pipeline.acceptReport(1_000 + at, makeReport("metric", "shop", payload));
assert.equal(outcome.record, undefined);
}
// When the minute is up, one report sums it up.
const [aggregate, ...more] = pipeline.flushAggregates(61_000);
assert.ok(aggregate !== undefined && more.length === 0);
const record = pipeline.acceptAggregateReport(61_000, aggregate);
assert.ok(record !== undefined);
const line = recordToJson(record).replace(/"run_id":"\w+"/, '"run_id":"…"');
assert.equal(
line,
'{"id":1,"timestamp_ms":61000,"kind":"metric","source":"pipeline","payload":{"run_id":"…","event":"metric_aggregate","window_ms":60000,"window_start_ms":1000,"metric":{"source":"shop","event":"checkout"},"fields":{"took_ms":{"count":4,"min":80,"max":300,"avg":148.75,"p50":95,"p95":300,"samples":[120,80,95,300]}},"groups":{"ok":{"false":1,"true":3}}}}',
);{"id":1,"timestamp_ms":61000,"kind":"metric","source":"pipeline","payload":{"run_id":"28Sqb3mBYBE","event":"metric_aggregate","window_ms":60000,"window_start_ms":1000,"metric":{"source":"shop","event":"checkout"},"fields":{"took_ms":{"count":4,"min":80,"max":300,"avg":148.75,"p50":95,"p95":300,"samples":[120,80,95,300]}},"groups":{"ok":{"false":1,"true":3}}}}
The whole configuration reads from JSON (through serdeConfig.of_jsonconfigFromJson, or parseConfig from text),
and every section has defaults, so {} is a valid configuration. Every
port makes the same records from the same reports: the OCaml and
TypeScript pipelines reproduce the Rust one's test transcript record for
record.
What it costs
With no observer installed, the Store skips every callback, and reads no message kind for refusals and inline calls. The same goes for each boundary no observer has a callback for: it costs nothing.The same goes for each boundary no observer has a callback for: it costs nothing.
With observers installed, the Rust port still allocates nothing per
execution. An observer gets borrowed views of the execution and its
payload, and Logger and Stats keep no buffer per execution. Measured
with cargo bench -p causet --bench baseline on an Apple M3 Max, rustc
1.90, per execution:
| Scenario | ns | Allocations |
|---|---|---|
| queued Action, no observer | 61.8 | 0 |
queued Action, Stats |
65.3 | 0 |
queued Action, Logger, logging off |
58.6 | 0 |
| refused Action, no observer | 12.4 | 0 |
refused Action, Stats |
20.2 | 0 |
refused Action, Logger, logging off |
20.6 | 0 |
| inline child call, no observer | 9.4 | 0 |
inline child call, Logger, logging off |
11.8 | 0 |
"Logging off" means no subscriber wants the causet::exec target: the cost
of leaving the logger installed in production, which is within noise of
having none. With logging on, the cost is the subscriber's.
The Store itself makes no allocation per execution in these benchmarks:
queued messages travel inline up to 48 bytes, and only a larger payload is
boxed when queued.
TraceLog keeps every execution, so it grows with the run: it is meant for
tests and debugging.
Reports are built in a pooled buffer (causet-pooled-payload): a field is
written into a reused byte pool and kept as an offset, so building a
report allocates nothing once the pool has grown. Accepting one allocates
nothing either, aggregated metrics included: an aggregate's windows are
set up when the pipeline is made, and allocate only when a window closes
into its report. A report is hashed with BLAKE3 only when a step needs it
(deduplication, or sampling at a rate between 0 and 1), and that hash is
most of what a deduplicated report costs. Measured with
cargo bench -p causet-reporting --bench accept, per report:
| Report | ns | Allocations |
|---|---|---|
| build an error report | 41 | 0 |
| build and accept, kept | 76 | 0 |
| build and accept, deduplicated | 233 | 0 |
| build and accept, aggregated | 437 | 0 |
Observers cost more in the OCaml port, where every execution allocates on
the minor heap and a callback is a closure call. Measured with
dune exec --profile release bench/baseline.exe on an Apple M3 Max, per
execution:
| Scenario | ns | Minor words |
|---|---|---|
| queued Action, no observer | 82.1 | 114 |
queued Action, Stats |
142.7 | 140 |
queued Action, logger, logging off |
97.4 | 130 |
| refused Action, no observer | 30.4 | 36 |
refused Action, Stats |
31.2 | 36 |
refused Action, logger, logging off |
46.2 | 57 |
| inline child call, no observer | 37.3 | 57 |
inline child call, logger, logging off |
51.1 | 83 |
Stats has start callbacks only, so a refusal costs it nothing.
"Logging off" means the causet.exec source is set to log none of the
messages: the logger then costs a level check per execution, beside the
callbacks themselves. Observe.Trace_log keeps every execution, so it
grows with the run: it is meant for tests and debugging.
A report's payload is built as a small tree, with no pool. A report is
hashed with BLAKE3, written in OCaml, only when a step needs it
(deduplication, or sampling at a rate between 0 and 1); that hash is most
of what a deduplicated report costs. Measured with
dune exec --profile release bench/reporting.exe, per report:
| Report | ns | Minor words |
|---|---|---|
| build an error report | 20 | 91 |
| build and accept, kept | 51 | 113 |
| build and accept, deduplicated | 487 | 119 |
| build and accept, aggregated | 913 | 171 |
Observers cost more in the TypeScript port, where every execution
allocates on V8's young heap. Measured with pnpm --filter causet bench
(bench/baseline.ts) on an Apple M3 Max, Node 24.22, per execution. V8
cannot count allocations, so the bench reads the bytes allocated off the
heap's growth over a round in which no collection runs:
| Scenario | ns | Bytes |
|---|---|---|
| queued Action, no observer | 169.6 | 363 |
queued Action, Stats |
215.9 | 486 |
queued Action, Logger, logging off |
193.0 | 485 |
| refused Action, no observer | 52.2 | 4 |
refused Action, Stats |
56.4 | 5 |
refused Action, Logger, logging off |
78.9 | 235 |
| inline child call, no observer | 82.4 | 196 |
inline child call, Logger, logging off |
97.1 | 211 |
Stats has start callbacks only, so a refusal costs it nothing.
"Logging off" means the log sink, here the default one, keeps nothing at
the message's level: the logger then costs a level check per execution,
beside the callbacks themselves. TraceLog keeps every execution, so it
grows with the run: it is meant for tests and debugging.
A report's payload is built as a small tree of objects, with no pool. A
report is hashed with BLAKE3, written in TypeScript on 32-bit words, only
when a step needs it (deduplication, or sampling at a rate between 0 and
1); that hash is most of what a deduplicated report costs. Measured with
node bench/accept.ts in causet-reporting, per report:
| Report | ns | Bytes |
|---|---|---|
| build an error report | 33 | 785 |
| build and accept, kept | 53 | 880 |
| build and accept, deduplicated | 496 | 879 |
| build and accept, aggregated | 936 | 805 |