causet the guide

Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.

Guide · 7

Determinism

What application code must do so a run can be repeated.

A test is only as useful as its failures are repeatable. Causet can repeat a run exactly: the same inputs lead to the same steps and the same end. That is what lets a generated test shrink a failing run and hand you a seed that reproduces it, every time. Causet does most of the work, and application code keeps a few rules about iteration order, time, randomness and I/O. This page states what exactly is repeated, and lists those rules.

From the same starting State, given the same inputs and the same clock readings, a Store runs the same executions in the same order, at the same times, and ends with the same State, with one exception: each Store run has its own session (SessionId)sessionsession (SessionId, a number), which every request ID and reply route carries, so that an answer meant for another run is told apart. State that holds request IDs therefore differs between two runs in their session, and nowhere else; compare such State with that in mind.

Event_bus.create gives each bus a fresh session; Event_bus.with_session takes one, so a test can fix it.

eventBus gives each bus a fresh session unless its options name one, { session }, so a test can fix it.

That is what makes a test reliable, a failure reproducible, and a simulated run repeatable from its seed. Causet keeps its side: the order work runs in is fixed (scheduling), every time an execution sees comes from the Store's clock, and request IDs are numbered within executions. The application keeps the other.

causet.rs / crates/causet/guide/determinism.mdcauset.ml / doc/determinism.mdcauset.ts / packages/causet/guide/determinism.md
use causet::guide::shop::*;
use causet::ManualClock;
use causet::observers::TraceLog;

let run = || {
    let mut shop = Shop::open(StoreOptions::with_clock(ManualClock::new(1_000)));
    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();
    let trace: Vec<_> = shop.store.observer::<TraceLog>().unwrap().entries().iter()
        .map(|e| (e.id, e.causal, e.kind, e.path.clone()))
        .collect();
    (trace, shop.store.state().clone())
};
// Two runs, the same executions in the same order, the same end. (Nothing
// compared here holds a request ID, so the sessions do not show.)
assert_eq!(run(), run());
open Causet
open Causet_guide.Shop

let run () =
  let shop = open_ ~clock:(Clock.Manual.clock (Clock.Manual.create 1_000)) () 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);
  let trace =
    List.map
      (fun (e : Observe.Trace_entry.t) -> (e.id, e.causal, e.kind, e.path))
      (Observe.Trace_log.entries log)
  in
  (trace, Store.state shop.store)

(* Two runs: the same executions in the same order, the same end. *)
let () = assert (run () = run ())
import assert from "node:assert/strict";
import { ManualClock } from "causet";
import { open } from "causet/guide";
import { TraceLog } from "causet/observers";

function run() {
  const shop = open({ clock: new ManualClock(1_000) });
  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);
  const trace = log.entries.map((e) => [e.id, e.causal, e.kind, e.path]);
  return { trace, state: shop.store.state };
}

// Two runs: the same executions in the same order, the same end.
const [first, second] = [run(), run()];
assert.deepEqual(first, second);
// `Pending` keeps its requests in a private field, which `deepEqual` does
// not see: it is compared with its own `equals`.
assert.ok(first.state.payments.pending.equals(second.state.payments.pending));

A request still pending at the end shows the exception:

causet.rs / crates/causet/guide/determinism.mdcauset.ml / doc/determinism.mdcauset.ts / packages/causet/guide/determinism.md
use causet::guide::shop::*;
use causet::ManualClock;

let pending = || {
    let mut shop = Shop::open(StoreOptions::with_clock(ManualClock::new(1_000)));
    shop.store.dispatch_to(&shop.payments, PaymentsAction::Charge { amount: 7 }).unwrap();
    shop.store.state().payments.pending.iter().next().unwrap().0 // the answer is not drained
};
let (first, second) = (pending(), pending());
assert_ne!(first.session, second.session); // each run's own
assert_eq!((first.execution, first.index), (second.execution, second.index));
let pending () =
  let shop = open_ ~clock:(Clock.Manual.clock (Clock.Manual.create 1_000)) () in
  ignore (Store.dispatch_exn shop.store shop.payments_mount (Charge { amount = 7 }));
  fst (List.hd (Pending.bindings (Store.state shop.store).payments.pending))
  (* the answer is not drained *)

let () =
  let first = pending () in
  let second = pending () in
  assert (first.session <> second.session) (* each run's own *);
  assert ((first.execution, first.index) = (second.execution, second.index))
import assert from "node:assert/strict";
import { ManualClock, type RequestId } from "causet";
import { open } from "causet/guide";

function pending(): RequestId {
  const shop = open({ clock: new ManualClock(1_000) });
  shop.store.dispatchOrThrow(shop.payments, { kind: "payments.charge", amount: 7 });
  // The answer is not drained.
  const [first] = shop.store.state.payments.pending.entries();
  return first?.[0] ?? assert.fail("a charge is pending");
}

const [first, second] = [pending(), pending()];
assert.notEqual(first.session, second.session); // each run's own
assert.deepEqual([first.execution, first.index], [second.execution, second.index]);

The rules

Code that runs inside the Store (enabling checks, guards, reducers, lowerers, adapters) must follow these:

JavaScript has a few more ways in which code breaks these rules without meaning to:

  • Date.now(), new Date() and performance.now() read the system clock; Math.random(), crypto.getRandomValues() and crypto.randomUUID() the operating system's randomness.
  • localeCompare, Intl and toLocaleString follow the machine's locale, so the same strings may sort or print differently on another machine. < compares strings by UTF-16 code unit, and SortedMap's natural order by code point, as Rust and OCaml order their strings.
  • Whatever a promise, await, setTimeout or queueMicrotask schedules runs after the execution has ended, outside it. A reducer, an Effect handler, an Event adapter, an Output lowerer or an observer that returns a promise faults the Store, and a register that returns one is a problem freeze reports; work that waits belongs to a Service, whose answer comes back as an Event.
  • State is immutable by convention: its types are Readonly, but nothing stops code from changing an array or an object in place. A change made that way is not a new State, and is shared with every snapshot that holds the same object.

Effect handlers and Services are the boundary: whatever is not deterministic about the world (timing, failures, the order answers arrive in) enters only as the Events they send. A test or a simulation controls them, and so controls the run.

The clock

Each Store has one Clock, given in StoreOptionsCauset.Clock.t, given to Store.createClock, given as the clock of Store.create's options: the only source of execution IDs and meta.time. SystemClockClock.systemsystemClock(), the default, gives nanoseconds since the Unix epoch: the system time at start, advanced by the monotonic clock, plus any stretch the monotonic clock missed, such as a device's sleep, which it notices as the system clock gaining on it. A system clock stepped back is ignored. An application that knows the machine's error (from NTP, a server, GPS) corrects it with a ClockOffsetClock.OffsetClockOffset. ManualClockClock.ManualManualClock moves only when told, for tests. Every execution is stamped max(previous, now)max previous nowMath.max(previous, now), so times never go back whatever the clock does; the execution IDs, which count executions, order the run.

causet.rs / crates/causet/guide/determinism.mdcauset.ml / doc/determinism.mdcauset.ts / packages/causet/guide/determinism.md
use causet::*;

#[derive(Debug, Action)]
#[causet(type = "stamp.action", kind = "stamp.now")]
struct Now;

/// Keeps the time of every Action it reduced.
struct Stamps;

impl Component for Stamps {
    type State = Vec<Timestamp>;
    type Action = Now;
    type Output = Never;
    no_effects!();

    fn reduce(mut ctx: ComponentContext<'_, Self>, _: Now, meta: &ActionMeta) {
        ctx.state_mut().push(meta.time); // the execution's time, never the system clock's
    }
}

let clock = ManualClock::new(1_000);
let options = StoreOptions::with_clock(clock.clone());
let (mut store, _sink) = Store::start::<Stamps>(Vec::<Timestamp>::new(), (), options).unwrap();
let stamps = store.mount(&root::<Stamps>()).unwrap();

store.dispatch_to(&stamps, Now).unwrap();
store.dispatch_to(&stamps, Now).unwrap(); // the clock has not moved
clock.set(5_000);
store.dispatch_to(&stamps, Now).unwrap();
clock.set(10); // a clock that steps back
store.dispatch_to(&stamps, Now).unwrap();
assert_eq!(*store.state(), [1_000, 1_000, 5_000, 5_000]);
type stamp = Now [@@deriving message ~name:"stamp.action"]

(* Keeps the time of every Action it reduced. *)
let stamps : (int list, unit, stamp, never, never) Component.t =
  Component.make ~name:"stamps" ~actions:stamp_message ~effects:Message.never
    ~outputs:Message.never
    ~reduce:(fun ctx Now (meta : Meta.t) ->
      (* The execution's time, never the system clock's. *)
      Ctx.update ctx (fun times -> times @ [ meta.time ]))
    ()
import { component, message, type Timestamp } from "causet";

type Stamp = { readonly kind: "stamp.now" };
const stamp = message<Stamp>("stamp.action");

/** Keeps the time of every Action it reduced. */
const stamps = component<readonly Timestamp[]>()({
  name: "stamps",
  actions: stamp,
  reduce(ctx, _now, meta) {
    // The execution's time, never the system clock's.
    ctx.update((times) => [...times, meta.time]);
  },
});
causet.ml / doc/determinism.mdcauset.ts / packages/causet/guide/determinism.md
let () =
  let clock = Clock.Manual.create 1_000 in
  let store, _sink = Store.start_exn ~clock:(Clock.Manual.clock clock) stamps ~state:[] ~services:() in
  let m = Store.mount_exn store (Path.root stamps) in
  ignore (Store.dispatch_exn store m Now);
  ignore (Store.dispatch_exn store m Now) (* the clock has not moved *);
  Clock.Manual.set clock 5_000;
  ignore (Store.dispatch_exn store m Now);
  Clock.Manual.set clock 10 (* a clock that steps back *);
  ignore (Store.dispatch_exn store m Now);
  assert (Store.state store = [ 1_000; 1_000; 5_000; 5_000 ])
import assert from "node:assert/strict";
import { ManualClock, rootPath, Store, type Timestamp } from "causet";

const clock = new ManualClock(1_000);
const { store } = Store.startOrThrow(stamps, { state: [], services: undefined, clock });
const m = store.mountOrThrow(rootPath(stamps));

store.dispatchOrThrow(m, { kind: "stamp.now" });
store.dispatchOrThrow(m, { kind: "stamp.now" }); // the clock has not moved
clock.set(5_000);
store.dispatchOrThrow(m, { kind: "stamp.now" });
clock.set(10); // a clock that steps back
store.dispatchOrThrow(m, { kind: "stamp.now" });
assert.deepEqual(store.state, [1_000, 1_000, 5_000, 5_000]);

Times are nanoseconds since 1970 in a number, as in the other ports, and a number holds every whole number exactly only up to 2^53: about 104 days of nanoseconds. A manual clock in a test stays below that, and is exact. The system clock reads near 1.7 × 10^18 ns, where a number steps by 256 ns: its readings, and the deadlines compared with them, are exact to 256 ns, and Math.max(previous, now) still never goes back. The wall clock it starts from, Date.now(), is in whole milliseconds; the monotonic clock that advances it is performance.now().

Services may keep their own clocks for their I/O, as the TimerCauset.TimerTimer does; reducers only ever see the Event that results.

Request IDs

ComponentContext::new_requestCtx.new_requestctx.newRequest() numbers requests within the current execution and stamps them with the session and the execution's ID, so a repeated run makes the same IDs except for the session, which tells two runs' answers apart. A reducer stores one, puts it in an Effect, and matches the answer.

Serializing State

Messages need no serialization. An application that wants to save State (a fixture, a diagnostic dump) derives serde on its own types, and enables causet's serde feature for the identity types State holds, such as RequestId.

Messages need no serialization: they travel as typed values. An application that wants to save State (a fixture, a diagnostic dump) serializes its own types, request IDs included, which are plain records of integers.

Messages need no serialization: they travel as values. An application that wants to save State (a fixture, a diagnostic dump) serializes its own types. A RequestId is a class of three numbers, which JSON.stringify writes as {"session":1,"execution":2,"index":3} and new RequestId(session, execution, index) makes again. Pending, SortedMap and SortedSet keep their entries in private fields, which JSON.stringify writes as {}: an application saves their entries, and builds the tables again from them.

NextTestingFind bugs with generated simulations, shrink failures and reproduce them; then test individual transitions, several nodes and invariants with memory.