causet the guide

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

Guide · 8

Testing

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

Find bugs automatically: define the operations a test may perform and the invariants that must hold. Causet generates seeded runs, finds violations, shrinks a failure and gives you its replay choices. The overview's payment example shows the whole process, including checking the fix.

Asynchronous bugs hide in orderings: an answer that arrives after its timeout, two answers swapped, a node that restarts in the middle of a request. Tests that sleep and hope rarely find them. A causet test runs the real application but holds everything the outside world would do, so it chooses the order itself: deliver this answer, drop that one, move the clock. It can then generate thousands of such choices and shrink a failure to a few steps you can replay.

This page builds up in layers: one transition, one node driven by hand, generated runs with invariants, and several nodes on a simulated network. Most tests need nothing more. The sections after them are for larger ones: invariants that compare with earlier steps, choosing the order of delivery across nodes, and fixtures that start in the middle of a workflow. Projections have checks of their own, on the projections page.

From one node on, tests run the real Store. The causet-test crate (a dev-dependency; its own documentation is cargo doc -p causet-test)Causet_testcauset/test wraps it so that nothing happens until the test says so: every Event a Service sends is held, time is a shared virtual clock, and the application's invariants are checked after every root input. A run is then a list of choices, which can be generated, shrunk when it fails, and repeated, as long as every Service in it is simulated or otherwise controlled by the test: holding Events and a manual clock do not reach a real Service's threads, I/O, clock or randomness. The examples below use the guide's shop (causet::guide::shopCauset_guide.Shopcauset/guide).

causet.ml / doc/testing.md
open Causet
open Causet_guide.Shop
open Causet_test

One transition

The smallest test runs one reducer, with no Store at all: a HarnessCauset.HarnessHarness dispatches an Action to one component, runs its enabling check and its reducer at a time the test sets, and returns what the reducer emitted, in order (authority shows one). It is the place for a transition's own rules. The rest of this page runs the real Store.

One node

A NodeCauset_test.NodeNode is a Store on a held bus, with a chosen session and a ManualClockCauset.Clock.Manual clockManualClock. checkNode.checkcheck registers an invariant: a read-only function of State that says what is wrong, if anything. It is checked at once, which validates the starting State, then after every root input. A violation panicsfails the runfails the run, naming the node, the invariant and the step.

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use causet::guide::shop::*;
use causet::{ManualClock, SessionId};
use causet_test::Node;

let clock = ManualClock::new(1_000);
let services = ShopServices { gateway: Box::new(ApproveUpTo(100)) };
let mut shop = Node::from_protocol("shop", protocol(), ShopState::default(), services, SessionId(1), &clock)
    .check("every order is paid, declined or pending", |s: &ShopState| {
        let p = &s.payments;
        let ended = p.paid.len() + p.declined.len() + p.pending.len();
        if ended as u64 == s.orders { Ok(()) } else { Err(format!("{} orders, {ended} charges", s.orders)) }
    });
let cart = shop.mount(&root::<ShopRoot>().child(CART));

shop.dispatch(&cart, CartAction::Add { item: "tea".into(), price: 4 });
shop.dispatch(&cart, CartAction::Checkout);
// The gateway answered at once, but its answer is held.
assert_eq!(shop.held().len(), 1);
assert_eq!(shop.state().payments.pending.len(), 1);
shop.deliver_next();
assert_eq!(shop.state().payments.paid, [4]);
let every_order_is_accounted_for (s : shop_state) =
  let p = s.payments in
  let ended = List.length p.paid + List.length p.declined + Pending.cardinal p.pending in
  if ended = s.orders then Ok () else Error (Printf.sprintf "%d orders, %d charges" s.orders ended)

let cart_path = Path.child (Path.root shop_root) cart_slot

let () =
  let shop =
    Node.of_protocol ~name:"shop" (protocol ()) ~state:empty
      ~services:{ gateway = approve_up_to 100 } ~session:1 (Clock.Manual.create 1_000)
  in
  let shop = Node.check shop "every order is paid, declined or pending" every_order_is_accounted_for in
  let cart = Node.mount shop cart_path in
  ignore (Node.dispatch shop cart (Add { item = "tea"; price = 4 }));
  ignore (Node.dispatch shop cart Checkout);
  (* The gateway answered at once, but its answer is held. *)
  assert (List.length (Node.held shop) = 1);
  assert (Pending.cardinal (Node.state shop).payments.pending = 1);
  ignore (Node.deliver_next shop);
  assert ((Node.state shop).payments.paid = [ 4 ])
import assert from "node:assert/strict";
import { ManualClock, rootPath } from "causet";
import { approveUpTo, cartSlot, empty, protocol, shopRoot } from "causet/guide";
import { Node } from "causet/test";

const services = { gateway: approveUpTo(100) };
const clock = new ManualClock(1_000);
const shop = Node.ofProtocol("shop", protocol(), {
  state: empty,
  services,
  session: 1,
  clock,
}).check("every order is paid, declined or pending", (s) => {
  const p = s.payments;
  const ended = p.paid.length + p.declined.length + p.pending.size;
  return ended === s.orders ? undefined : `${s.orders} orders, ${ended} charges`;
});
const cart = shop.mount(rootPath(shopRoot).child(cartSlot));

shop.dispatch(cart, { kind: "cart.add", item: "tea", price: 4 });
shop.dispatch(cart, { kind: "cart.checkout" });
// The gateway answered at once, but its answer is held.
assert.equal(shop.held().length, 1);
assert.equal(shop.state.payments.pending.size, 1);
shop.deliverNext();
assert.deepEqual(shop.state.payments.paid, [4]);

deliver_nextNode.deliver_nextdeliverNext takes the held Event the bus would have run next, so delivering one at a time runs Events in production's order. deliver, deliver_where and discardNode.deliver, Node.deliver_where and Node.discarddeliver, deliverWhere and discard choose otherwise: an answer that comes late, out of order, or never. A held Event is delivered once; an answer that comes twice is one the simulated Service sends twice. restartNode.restartrestart rebuilds the Store from a given State, Services and session; with a new session, an answer meant for the run before is told apart.

Generated runs

check(config, f) calls f with an Rng and its runs: Config::default()check f calls f with an Causet_test.Rng.t for each of its runs: defaultcheck(f), or check(config, f), calls f with an Rng for each of its runs: defaultConfig makes 100, from seed 0, and the environment overrides them with CAUSET_RUNS and CAUSET_SEED. Every draw is a bounded integer, and 0 is always the simplest answer: below(n), between, chance, pick, and moreRng.below, Rng.between, Rng.chance, Rng.pick, and Rng.morebelow(n), between, chance, pick, and more, which says whether the run takes another step, 15 times in 16. A run fails when it panicsraisesthrows, which includes an invariant of any NodenodeNode. The failing run's choices are then shrunk to a small list that fails the same way, and printed with a call that repeats it, in this form:

causet_test::check: the run with seed <seed> failed (<what failed>); shrunk from <n> choices to <m> in <runs> runs. Repeat it with CAUSET_SEED=<seed> or
    causet_test::replay(&[<the shrunk choices>], ...)
causet_test.check: the run with seed <seed> failed (<what failed>); shrunk from <n> choices to <m> in <runs> runs. Repeat it with CAUSET_SEED=<seed> or
    Causet_test.replay [<the shrunk choices>] ...
causet/test check: the run with seed <seed> failed (<what failed>); shrunk from <n> choices to <m> in <runs> runs. Repeat it with CAUSET_SEED=<seed> or
    replay([<the shrunk choices>], ...)

What failed names the check when an invariant failed, such as node shop: invariant "..." or group shops: invariant "..."; otherwise it is where the run failed, such as panic at <file>:<line> for a test's own assertion, or step budget. With a ConfigconfigConfig whose max_stepsmax_stepsmaxSteps is not the default, the call printed is causet_test::replay_with, with that Configpasses that configpasses that maxSteps. The shrunk run is then made once more, so its own panicexceptionerror fails the test; if it passes instead, the run was not repeatable, and check says so.

Every run that passes is made a second time from its own choices. The second must pass too, and run the same executions, refusals and inline calls on every node, each with the same message, compared by its printed form; the first that differs fails the test as not deterministic, naming where the two first differ, and so does a second making that rejects. A run that reads what its choices do not decide (the system clock, a HashMap's order, a thread's timingthe system clock, a Hashtbl's order, a thread's timingthe system clock, Math.random, a timer's or a promise's timing) is caught the first time it shows, rather than when a shrunk failure will not replay. Config::determinismconfig.determinismthe Config's determinism turns it off; a run that makes no NodenodeNode is made once.

The check sees only what the nodes do and send. A difference that stays in State, never changing a message, a refusal or what runs, passes it; an invariant on that State is what catches it. A message compares only as far as it prints: one whose Debug form varies from run to run, such as one holding a HashMap, is reported even when nothing else differs, so hold a BTreeMap in messagesone with no printer, written by hand without ~pp or derived with ~no_pp, prints as _ and compares by kind alonea value prints field by field, but a function in it prints as _ and a class instance shows its public fields only, never its #private ones, so give such a message's descriptor a debug printer, or the value a [debugCustom] method.

A replay(&choices, f)replay choices freplay(choices, f) with that list is the failure kept as a regression test. rng.reject()Rng.rejectrng.reject() ends a run that drew an invalid fixture, without counting it. search finds and shrinks the first failure as check does, and returns it instead of failing, without the final replay and without reading CAUSET_RUNS or CAUSET_SEED: it is how a test shows that a planted bug is found.

Two tools make rare interleavings likelier:

Several nodes on a simulated world

examples/wallet-send and examples/p2p-nodeexamples/wallet_send and examples/p2p_nodeexamples/wallet-send and examples/p2p-node test several Stores this way:

  1. One shared world. The network or the remote service lives in one value behind Arc<Mutex<_>>. The nodes' Services hold clones of it, and so does the test, as a World.is one value, which the nodes' Services and the test's Causet_test.world share.is one object, which the nodes' Services hold and the test drives as its World. A Service does not answer: it puts the answer in flight. An InFlightCauset_test.In_flightInFlight holds the world's messages, due in order of time and, when due together, of sending; on a channel (one direction of a link), send_in_orderIn_flight.send_in_ordersendInOrder keeps a message after the one before it, whatever delay it drew. World::next_timeThe world's next_timeThe world's nextTime reports when the next one is due, and advance delivers what due(now)In_flight.duedue(now) returns, through a node's sink or the Replysink or the replysink or the Reply it was sent with. What stands in for a worker thread sends with try_send_to_as_worker or Reply::try_send_as_workerSink.try_send_to_as_worker or Reply.try_send_as_workertrySendToAsWorker or Reply's trySendAsWorker, so its Events take the worker lane, as they would in production.
  2. One clock and one scenario. A ScenarioCauset_test.ScenarioScenario drives every node on one virtual clock. stepScenario.stepstep delivers a held Event if any node holds one, and otherwise advances the clock to the next timer deadline or world time, lets the world act, then fires the timers. run_untilScenario.run_untilrunUntil steps until a predicate holds, nothing is left (Stop::QuietQuiet"quiet"), a step budget runs out or a time limit is reached. A scenario dropped by a failing test prints its last steps, and its seed when it draws from one; under check, that is the shrunk run's replay, which draws from its choices. Timers are Timer::simulatedTimer.simulatedTimer.simulated on the scenario's clock, handed to the node with with_timerNode.with_timerwithTimer.
  3. Invariants per node and over the group. Each node checks its own State. A GroupCauset_test.GroupGroup holds what spans the nodes: each node publishes a view of its State (publishNode.publishpublish), and the group's checks read every view after any member's root input.
  4. Generated steps, then the end. The world draws from rng.split()Rng.split rngrng.split(), the steps from a Swarm while rng.more()Rng.more rngrng.more(). Then the scenario runs until it is quiet, and the test checks what must hold once nothing is left: every request ended, nothing left pending.

A shop's gateway, shared here by up to three shops, approves charges while a budget lasts and answers 1 to 50 ms later. The shops cannot see one another; the group checks that together they were never paid more than the budget. A bank that forgets what it approved is found, and shrunk:

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use std::sync::{Arc, Mutex};

use causet::guide::shop::*;
use causet::{ManualClock, SessionId};
use causet_test::{Config, Driven, Group, InFlight, Node, Rng, Scenario, Stop, Swarm, World, check, search};

const MS: u64 = 1_000_000;
const BUDGET: u64 = 200;

/// The bank every shop's gateway reaches.
struct Bank {
    /// The world's own stream: the answers' delays.
    world: Rng,
    clock: ManualClock,
    flight: InFlight<(Reply<Charged>, Charged)>,
    approved: u64,
    /// The planted bug: approvals are not counted.
    forgets: bool,
}

/// The gateway of every shop, and the test's world.
#[derive(Clone)]
struct Shared(Arc<Mutex<Bank>>);

impl Gateway for Shared {
    fn charge(&mut self, request: RequestId, amount: u64, reply: Reply<Charged>) {
        let mut bank = self.0.lock().unwrap();
        let approved = bank.approved + amount <= BUDGET;
        if approved && !bank.forgets {
            bank.approved += amount;
        }
        let at = bank.clock.get() + bank.world.between(1, 50) * MS;
        bank.flight.send_at(at, (reply, Charged { request, approved }));
    }
}

impl World for Shared {
    fn next_time(&self) -> Option<Timestamp> {
        self.0.lock().unwrap().flight.next_time()
    }
    fn advance(&mut self, now: Timestamp) {
        let due = self.0.lock().unwrap().flight.due(now);
        for (reply, answer) in due {
            reply.try_send_as_worker(answer).expect("the held bus takes it");
        }
    }
}

#[derive(Clone, Copy)]
enum Step { Deliver, Add, Checkout }

/// The nodes, as a scenario drives them.
fn driven(nodes: &mut [Node<ShopState, ShopServices>]) -> Vec<&mut dyn Driven> {
    nodes.iter_mut().map(|n| n as &mut dyn Driven).collect()
}

fn shops(rng: &mut Rng, forgets: bool) {
    let mut scenario = Scenario::with_rng(rng.clone(), 1_000 * MS);
    let bank = Bank { world: rng.split(), clock: scenario.clock.clone(), flight: InFlight::new(), approved: 0, forgets };
    let mut world = Shared(Arc::new(Mutex::new(bank)));
    let group = Group::new("shops");
    group.check("paid within the budget", |views, _| {
        let paid: u64 = views.nodes().map(|node| *views.get::<u64>(node).unwrap()).sum();
        if paid <= BUDGET { Ok(()) } else { Err(format!("{paid} paid")) }
    });
    let protocol = protocol();
    let mut nodes: Vec<_> = (0..rng.between(2, 3))
        .map(|i| {
            let services = ShopServices { gateway: Box::new(world.clone()) };
            Node::from_protocol(&format!("shop {i}"), protocol.clone(), ShopState::default(), services, SessionId(1), &scenario.clock)
                .publish(&group, |s: &ShopState| s.payments.paid.iter().sum::<u64>())
        })
        .collect();
    let cart = nodes[0].mount(&root::<ShopRoot>().child(CART));

    let swarm = Swarm::new(rng, &[(Step::Deliver, 3), (Step::Add, 2), (Step::Checkout, 1)]);
    while rng.more() {
        let shop = rng.below(nodes.len() as u64) as usize;
        match swarm.pick(rng) {
            Step::Deliver => drop(scenario.step(&mut driven(&mut nodes), &mut world)),
            Step::Add => drop(nodes[shop].dispatch(&cart, CartAction::Add { item: "tea".into(), price: rng.between(1, 90) })),
            Step::Checkout => drop(nodes[shop].dispatch(&cart, CartAction::Checkout)),
        }
    }
    let stop = scenario.run_until(&mut driven(&mut nodes), &mut world, 1_000, None, |_| false);
    assert_eq!(stop, Stop::Quiet);
    for node in &nodes {
        assert!(node.state().payments.pending.is_empty(), "{}: a charge never answered", node.name());
    }
}

check(Config::default(), |rng| shops(rng, false));
let found = search(Config::default(), |rng| shops(rng, true)).expect("the planted bug is found");
assert_eq!(found.key, r#"group shops: invariant "paid within the budget""#);
assert!(found.choices.len() < found.original);
let ms = 1_000_000
let budget = 200

(* The bank every shop's gateway reaches. *)
type bank = {
  world : Rng.t;  (** The world's own stream: the answers' delays. *)
  clock : Clock.Manual.m;
  flight : (charged reply * charged, unit) In_flight.t;
  mutable approved : int;
  forgets : bool;  (** The planted bug: approvals are not counted. *)
}

(* The gateway of every shop. *)
let gateway_of bank =
  {
    charge =
      (fun request amount reply ->
        let approved = bank.approved + amount <= budget in
        if approved && not bank.forgets then bank.approved <- bank.approved + amount;
        let at = Clock.Manual.get bank.clock + (Rng.between bank.world 1 50 * ms) in
        In_flight.send_at bank.flight at (reply, { request; approved }));
  }

(* The test's view of the same bank. *)
let world_of bank =
  {
    next_time = (fun () -> In_flight.next_time bank.flight);
    advance =
      (fun now ->
        List.iter
          (fun (reply, answer) ->
            match Reply.try_send_as_worker reply answer with
            | Ok () -> ()
            | Error _ -> failwith "the held bus takes it")
          (In_flight.due bank.flight now));
  }

type step = Deliver | Add_tea | Check_out

let shops rng ~forgets =
  let scenario = Scenario.with_rng rng (1_000 * ms) in
  let bank =
    { world = Rng.split rng; clock = (Scenario.clock scenario); flight = In_flight.create (); approved = 0; forgets }
  in
  let world = world_of bank in
  let group = Group.create "shops" in
  Group.check group "paid within the budget" (fun views _ ->
      let paid = List.fold_left (fun sum (_, paid) -> sum + paid) 0 views in
      if paid <= budget then Ok () else Error (Printf.sprintf "%d paid" paid));
  let protocol = protocol () in
  let nodes =
    Array.init (Rng.between rng 2 3) (fun i ->
        let node =
          Node.of_protocol ~name:(Printf.sprintf "shop %d" i) protocol ~state:empty
            ~services:{ gateway = gateway_of bank } ~session:1 (Scenario.clock scenario)
        in
        Node.publish node group (fun s -> List.fold_left ( + ) 0 s.payments.paid))
  in
  let driven_nodes = Array.to_list (Array.map driven nodes) in
  let cart = Node.mount nodes.(0) cart_path in
  let swarm = Swarm.create rng [ (Deliver, 3); (Add_tea, 2); (Check_out, 1) ] in
  while Rng.more rng do
    let shop = nodes.(Rng.below rng (Array.length nodes)) in
    match Swarm.pick swarm rng with
    | Deliver -> ignore (Scenario.step scenario driven_nodes world)
    | Add_tea -> ignore (Node.dispatch shop cart (Add { item = "tea"; price = Rng.between rng 1 90 }))
    | Check_out -> ignore (Node.dispatch shop cart Checkout)
  done;
  let stop = Scenario.run_until scenario driven_nodes world ~steps:1_000 ~until:(fun () -> false) in
  assert (stop = Quiet);
  Array.iter
    (fun node ->
      if not (Pending.is_empty (Node.state node).payments.pending) then
        failwith (Node.name node ^ ": a charge never answered"))
    nodes

let () =
  check (fun rng -> shops rng ~forgets:false);
  match search default (fun rng -> shops rng ~forgets:true) with
  | Some found ->
      assert (found.key = {|group shops: invariant "paid within the budget"|});
      assert (List.length found.choices < found.original)
  | None -> assert false
import assert from "node:assert/strict";
import { type ManualClock, type Reply, type RequestId, rootPath, type Timestamp } from "causet";
import { type Charged, cartSlot, empty, type Gateway, protocol, shopRoot } from "causet/guide";
import {
  check,
  Group,
  InFlight,
  Node,
  type Rng,
  Scenario,
  search,
  Swarm,
  type World,
} from "causet/test";

const MS = 1_000_000;
const BUDGET = 200;

/** The bank every shop's gateway reaches: their gateway, and the test's world. */
class Bank implements Gateway, World {
  /** The world's own stream: the answers' delays. */
  readonly #world: Rng;
  readonly #clock: ManualClock;
  readonly #flight = new InFlight<readonly [Reply<Charged>, Charged]>();
  #approved = 0;
  /** The planted bug: approvals are not counted. */
  readonly #forgets: boolean;

  constructor(world: Rng, clock: ManualClock, forgets: boolean) {
    this.#world = world;
    this.#clock = clock;
    this.#forgets = forgets;
  }

  charge(request: RequestId, amount: number, reply: Reply<Charged>): void {
    const approved = this.#approved + amount <= BUDGET;
    if (approved && !this.#forgets) this.#approved += amount;
    const at = this.#clock.now() + this.#world.between(1, 50) * MS;
    this.#flight.sendAt(at, [reply, { kind: "payments.charged", request, approved }]);
  }

  nextTime(): Timestamp | undefined {
    return this.#flight.nextTime();
  }

  advance(now: Timestamp): void {
    for (const [reply, answer] of this.#flight.due(now)) {
      if (!reply.trySendAsWorker(answer).ok) throw new Error("the held bus takes it");
    }
  }
}

function shops(rng: Rng, forgets: boolean): void {
  const scenario = Scenario.withRng(rng, 1_000 * MS);
  const bank = new Bank(rng.split(), scenario.clock, forgets);
  const group = new Group<number>("shops");
  group.check("paid within the budget", (views) => {
    const paid = [...views.values()].reduce((sum, paid) => sum + paid, 0);
    return paid <= BUDGET ? undefined : `${paid} paid`;
  });
  const shared = protocol();
  const nodes = Array.from({ length: rng.between(2, 3) }, (_, i) =>
    Node.ofProtocol(`shop ${i}`, shared, {
      state: empty,
      services: { gateway: bank },
      session: 1,
      clock: scenario.clock,
    }).publish(group, (s) => s.payments.paid.reduce((sum, paid) => sum + paid, 0)),
  );
  const cart = nodes[0]!.mount(rootPath(shopRoot).child(cartSlot));

  const swarm = new Swarm(rng, [
    ["deliver", 3],
    ["add", 2],
    ["checkout", 1],
  ] as const);
  while (rng.more()) {
    const shop = nodes[rng.below(nodes.length)]!;
    switch (swarm.pick(rng)) {
      case "deliver":
        scenario.step(nodes, bank);
        break;
      case "add":
        shop.dispatch(cart, { kind: "cart.add", item: "tea", price: rng.between(1, 90) });
        break;
      case "checkout":
        shop.dispatch(cart, { kind: "cart.checkout" });
        break;
    }
  }
  const stop = scenario.runUntil(nodes, bank, { steps: 1_000, until: () => false });
  assert.equal(stop, "quiet");
  for (const node of nodes) {
    assert(node.state.payments.pending.isEmpty(), `${node.name}: a charge never answered`);
  }
}

check((rng) => shops(rng, false));
const found = search({}, (rng) => shops(rng, true));
assert(found !== undefined, "the planted bug is found");
assert.equal(found.key, 'group shops: invariant "paid within the budget"');
assert(found.choices.length < found.original);

The two larger examples go further. Both worlds delay what is in flight, and break links, losing what was on them. wallet-send'swallet_send'swallet-send's peers also restart and lie. p2p-node'sp2p_node'sp2p-node's world also delivers stale callbacks again and opens extra links; and it adds an observer on each Store that checks why things happen (an answer only to the request that was sent, a disconnection reported once). examples/chain-placementexamples/chain_placementexamples/chain-placement has no Store: its generated runs make logs for a projection, and check them as the projections page does.

examples/p2p has only doctests that some code does not compile; p2p-node runs it.

Invariants that remember

Some properties are about change rather than about one State: a payment is never forgotten, a count only grows, a value changes only when a certain Event arrives. check_withNode.check_withcheckWith registers such an invariant. Its checker is called with the State and with the step it runs at, and what it captures is its memory, so it can compare the State with the one it saw last. The step is one of three:

checkNode.checkcheck is check_withcheck_withcheckWith with a checker that ignores the step. A checker that panicsraisesthrows fails the node under the key node <name>: invariant "<name>" panicked, and the Store disables it, since its memory may be half updated.

Here the invariant remembers what was paid. The amount may grow only when a payments.charged Event settles, and may not change on any other root input or on a restart. A restart that keeps the State passes; one that starts again from an empty State is found:

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use causet::guide::shop::*;
use causet::{ManualClock, SessionId};
use causet::invariants::InvariantStep;
use causet_test::{Config, Node, search};

/// A shop takes one payment, then restarts from what it keeps.
fn pay_then_restart(keeps: bool) {
    let services = || ShopServices { gateway: Box::new(ApproveUpTo(100)) };
    // The invariant's memory: what was paid at its last step.
    let mut before = 0;
    let mut shop = Node::from_protocol("shop", protocol(), ShopState::default(), services(), SessionId(1), &ManualClock::new(1_000))
        .check_with("paid only by answers, never forgotten", move |s: &ShopState, step: &InvariantStep<'_>| {
            let paid: u64 = s.payments.paid.iter().sum();
            let was = std::mem::replace(&mut before, paid);
            let ok = match step {
                // A fixture may start with payments made.
                InvariantStep::Added => true,
                InvariantStep::Settled { kind: "payments.charged", .. } => paid >= was,
                InvariantStep::Settled { .. } | InvariantStep::Restored => paid == was,
            };
            if ok { Ok(()) } else { Err(format!("paid {was}, then {paid}")) }
        });
    let cart = shop.mount(&root::<ShopRoot>().child(CART));
    shop.dispatch(&cart, CartAction::Add { item: "tea".into(), price: 4 });
    shop.dispatch(&cart, CartAction::Checkout);
    shop.deliver_next();
    let kept = if keeps { shop.state().clone() } else { ShopState::default() };
    shop.restart(kept, services(), SessionId(2));
}

pay_then_restart(true);
let found = search(Config::default(), |_| pay_then_restart(false)).expect("the forgotten payment is found");
assert_eq!(found.key, r#"node shop: invariant "paid only by answers, never forgotten""#);
(* A shop takes one payment, then restarts from what it keeps. *)
let pay_then_restart ~keeps =
  let services () = { gateway = approve_up_to 100 } in
  (* The invariant's memory: what was paid at its last step. *)
  let before = ref 0 in
  let shop =
    Node.of_protocol ~name:"shop" (protocol ()) ~state:empty ~services:(services ()) ~session:1
      (Clock.Manual.create 1_000)
  in
  let shop =
    Node.check_with shop "paid only by answers, never forgotten" (fun s step ->
        let paid = List.fold_left ( + ) 0 s.payments.paid in
        let was = !before in
        before := paid;
        let ok =
          match (step : invariant_step) with
          (* A fixture may start with payments made. *)
          | Added -> true
          | Settled_step { kind = "payments.charged"; _ } -> paid >= was
          | Settled_step _ | Restored -> paid = was
        in
        if ok then Ok () else Error (Printf.sprintf "paid %d, then %d" was paid))
  in
  let cart = Node.mount shop cart_path in
  ignore (Node.dispatch shop cart (Add { item = "tea"; price = 4 }));
  ignore (Node.dispatch shop cart Checkout);
  ignore (Node.deliver_next shop);
  let kept = if keeps then Node.state shop else empty in
  Node.restart shop ~state:kept ~services:(services ()) ~session:2

let () =
  pay_then_restart ~keeps:true;
  match search default (fun _ -> pay_then_restart ~keeps:false) with
  | Some found -> assert (found.key = {|node shop: invariant "paid only by answers, never forgotten"|})
  | None -> assert false
import assert from "node:assert/strict";
import { ManualClock, rootPath } from "causet";
import { approveUpTo, cartSlot, empty, protocol, shopRoot } from "causet/guide";
import { Node, search } from "causet/test";

/** A shop takes one payment, then restarts from what it keeps. */
function payThenRestart(keeps: boolean): void {
  const services = () => ({ gateway: approveUpTo(100) });
  // The invariant's memory: what was paid at its last step.
  let before = 0;
  const shop = Node.ofProtocol("shop", protocol(), {
    state: empty,
    services: services(),
    session: 1,
    clock: new ManualClock(1_000),
  }).checkWith("paid only by answers, never forgotten", (s, step) => {
    const paid = s.payments.paid.reduce((sum, p) => sum + p, 0);
    const was = before;
    before = paid;
    let ok: boolean;
    switch (step.step) {
      // A fixture may start with payments made.
      case "added":
        ok = true;
        break;
      case "settled":
        ok = step.kind === "payments.charged" ? paid >= was : paid === was;
        break;
      case "restored":
        ok = paid === was;
        break;
    }
    return ok ? undefined : `paid ${was}, then ${paid}`;
  });
  const cart = shop.mount(rootPath(shopRoot).child(cartSlot));
  shop.dispatch(cart, { kind: "cart.add", item: "tea", price: 4 });
  shop.dispatch(cart, { kind: "cart.checkout" });
  shop.deliverNext();
  const kept = keeps ? shop.state : empty;
  shop.restart({ state: kept, services: services(), session: 2 });
}

payThenRestart(true);
const found = search({}, () => payThenRestart(false));
assert(found !== undefined, "the forgotten payment is found");
assert.equal(found.key, 'node shop: invariant "paid only by answers, never forgotten"');

A group's checks have the same two inputs. A Group::checkGroup.checka group's check is called with the members' views and the step it runs at, and its captures are its memory:

A node leaves its groups when it is droppedwith Node.close, which also closes its Store, or by name with Group.leavewith close, which also closes its Store, or by name with the group's leave, and no check runs then: its view is simply gone from the next step's views. A check that must still count what a departed node did keeps it in its memory. Here each shop's paid total is remembered after the shop has gone, so the budget still counts shop a's 4 once a has gone. With shop b paid 5 the two make 9, within the budget of 10; with 7 they make 11, which the check finds although shop b's view alone is within it:

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;

use causet::guide::shop::*;
use causet::{ManualClock, SessionId};
use causet_test::{Config, Group, GroupStep, Node, search};

/// Shop a is paid 4 and closes; shop b restarts, then is paid `price`.
/// Returns the steps the group's check ran at.
fn two_shops(price: u64) -> Vec<String> {
    let group = Group::new("shops");
    let steps = Rc::new(RefCell::new(Vec::new()));
    let log = Rc::clone(&steps);
    // The check's memory: each shop's paid total, kept after the shop has gone.
    let mut last = BTreeMap::new();
    group.check("paid within 10, gone shops included", move |views, step| {
        log.borrow_mut().push(match step {
            GroupStep::Added => "added".to_owned(),
            GroupStep::Published { node } => format!("{node} published"),
            GroupStep::Settled { node } => format!("{node} settled"),
            GroupStep::Restarted { node } => format!("{node} restarted"),
        });
        for node in views.nodes() {
            last.insert(node.to_owned(), *views.get::<u64>(node).unwrap());
        }
        let paid: u64 = last.values().sum();
        if paid <= 10 { Ok(()) } else { Err(format!("{paid} paid")) }
    });
    let (protocol, clock) = (protocol(), ManualClock::new(1_000));
    let services = || ShopServices { gateway: Box::new(ApproveUpTo(100)) };
    let open = |name: &str| {
        Node::from_protocol(name, protocol.clone(), ShopState::default(), services(), SessionId(1), &clock)
            .publish(&group, |s: &ShopState| s.payments.paid.iter().sum::<u64>())
    };
    let cart = protocol.resolve(&root::<ShopRoot>().child(CART)).unwrap();
    let pay = |shop: &mut Node<ShopState, ShopServices>, price| {
        shop.dispatch(&cart, CartAction::Add { item: "tea".into(), price });
        shop.dispatch(&cart, CartAction::Checkout);
        shop.deliver_next();
    };
    let (mut a, b) = (open("a"), open("b"));
    pay(&mut a, 4);
    // A dropped node's view leaves its groups, and no check runs.
    drop(a);
    let state = b.state().clone();
    let mut b = b.restart(state, services(), SessionId(2));
    pay(&mut b, price);
    steps.take()
}

let steps = two_shops(5);
assert_eq!(steps[..4], ["added", "a published", "b published", "a settled"]);
assert_eq!(steps[6..], ["b restarted", "b settled", "b settled", "b settled"]);
let found = search(Config::default(), |_| drop(two_shops(7))).expect("a's 4 is remembered");
assert_eq!(found.key, r#"group shops: invariant "paid within 10, gone shops included""#);
(* Shop a is paid 4 and closes; shop b restarts, then is paid [price].
   Returns the steps the group's check ran at. *)
let two_shops price =
  let group = Group.create "shops" in
  let steps = ref [] in
  (* The check's memory: each shop's paid total, kept after the shop has gone. *)
  let last = Hashtbl.create 2 in
  Group.check group "paid within 10, gone shops included" (fun views step ->
      let seen =
        match step with
        | Added -> "added"
        | Published node -> node ^ " published"
        | Settled node -> node ^ " settled"
        | Restarted node -> node ^ " restarted"
      in
      steps := seen :: !steps;
      List.iter (fun (node, paid) -> Hashtbl.replace last node paid) views;
      let paid = Hashtbl.fold (fun _ paid sum -> sum + paid) last 0 in
      if paid <= 10 then Ok () else Error (Printf.sprintf "%d paid" paid));
  let protocol = protocol () and clock = Clock.Manual.create 1_000 in
  let services () = { gateway = approve_up_to 100 } in
  let open_ name =
    let shop =
      Node.of_protocol ~name protocol ~state:empty ~services:(services ()) ~session:1 clock
    in
    Node.publish shop group (fun s -> List.fold_left ( + ) 0 s.payments.paid)
  in
  let cart = Protocol.resolve_exn protocol cart_path in
  let pay shop price =
    ignore (Node.dispatch shop cart (Add { item = "tea"; price }));
    ignore (Node.dispatch shop cart Checkout);
    ignore (Node.deliver_next shop)
  in
  let a = open_ "a" and b = open_ "b" in
  pay a 4;
  (* A closed node's view leaves its groups, and no check runs. *)
  Node.close a;
  Node.restart b ~state:(Node.state b) ~services:(services ()) ~session:2;
  pay b price;
  List.rev !steps

let () =
  let steps = two_shops 5 in
  assert (List.filteri (fun i _ -> i < 4) steps = [ "added"; "a published"; "b published"; "a settled" ]);
  assert (List.filteri (fun i _ -> i >= 6) steps = [ "b restarted"; "b settled"; "b settled"; "b settled" ]);
  match search default (fun _ -> ignore (two_shops 7)) with
  | Some found -> assert (found.key = {|group shops: invariant "paid within 10, gone shops included"|})
  | None -> assert false
import assert from "node:assert/strict";
import { ManualClock, rootPath } from "causet";
import {
  approveUpTo,
  cartSlot,
  empty,
  protocol,
  type ShopServices,
  type ShopState,
  shopRoot,
} from "causet/guide";
import { Group, Node, search } from "causet/test";

/**
 * Shop a is paid 4 and closes; shop b restarts, then is paid `price`.
 * Returns the steps the group's check ran at.
 */
function twoShops(price: number): string[] {
  const group = new Group<number>("shops");
  const steps: string[] = [];
  // The check's memory: each shop's paid total, kept after the shop has gone.
  const last = new Map<string, number>();
  group.check("paid within 10, gone shops included", (views, step) => {
    steps.push(step.step === "added" ? "added" : `${step.node} ${step.step}`);
    for (const [node, paid] of views) last.set(node, paid);
    const paid = [...last.values()].reduce((sum, p) => sum + p, 0);
    return paid <= 10 ? undefined : `${paid} paid`;
  });
  const shared = protocol();
  const clock = new ManualClock(1_000);
  const services = () => ({ gateway: approveUpTo(100) });
  const open = (name: string) =>
    Node.ofProtocol(name, shared, {
      state: empty,
      services: services(),
      session: 1,
      clock,
    }).publish(group, (s) => s.payments.paid.reduce((sum, p) => sum + p, 0));
  const cart = shared.resolveOrThrow(rootPath(shopRoot).child(cartSlot));
  const pay = (shop: Node<ShopState, ShopServices>, price: number) => {
    shop.dispatch(cart, { kind: "cart.add", item: "tea", price });
    shop.dispatch(cart, { kind: "cart.checkout" });
    shop.deliverNext();
  };
  const a = open("a");
  const b = open("b");
  pay(a, 4);
  // A closed node's view leaves its groups, and no check runs.
  a.close();
  b.restart({ state: b.state, services: services(), session: 2 });
  pay(b, price);
  return steps;
}

const steps = twoShops(5);
assert.deepEqual(steps.slice(0, 4), ["added", "a published", "b published", "a settled"]);
assert.deepEqual(steps.slice(6), ["b restarted", "b settled", "b settled", "b settled"]);
const found = search({}, () => void twoShops(7));
assert(found !== undefined, "a's 4 is remembered");
assert.equal(found.key, 'group shops: invariant "paid within 10, gone shops included"');

Choosing the order across nodes

Scenario::stepScenario.stepA scenario's step delivers, of the first node that holds something, the Event its bus would run next. Across nodes that is a fixed order: the first node's Events always go first. step_withScenario.step_withstepWith takes a Chooser~choose functionChooser instead, which picks the Event to deliver. It is given every node's held Events, as (node, HeldEvent)(node, held_event){ node, event } pairs listed node by node, each node's in send order, with the scenario's generator, and returns an index into them. A scenario made with Scenario::with_rngwith Scenario.with_rngwith Scenario.withRng from a generated run's generator draws from the run's choices, so an order found this way is shrunk and replayed with the rest of the run. A step that finds nothing held advances the clock as step does.

Here three answers are held on two shops. The chooser picks any of them, and with seed 1 the second shop's answer goes first, then the first shop's answers in the opposite order to the one they were sent in:

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use causet::guide::shop::*;
use causet::SessionId;
use causet::hosting::HeldEvent;
use causet_test::{Driven, Node, NoWorld, Rng, Scenario};

fn driven(nodes: &mut [Node<ShopState, ShopServices>]) -> Vec<&mut dyn Driven> {
    nodes.iter_mut().map(|n| n as &mut dyn Driven).collect()
}

let mut scenario = Scenario::new(1, 1_000);
let protocol = protocol();
let mut nodes: Vec<_> = (0..2)
    .map(|i| {
        let services = ShopServices { gateway: Box::new(ApproveUpTo(100)) };
        Node::from_protocol(&format!("shop {i}"), protocol.clone(), ShopState::default(), services, SessionId(1), &scenario.clock)
    })
    .collect();
let cart = nodes[0].mount(&root::<ShopRoot>().child(CART));
for (shop, price) in [(0, 4), (0, 5), (1, 6)] {
    nodes[shop].dispatch(&cart, CartAction::Add { item: "tea".into(), price });
    nodes[shop].dispatch(&cart, CartAction::Checkout);
}
scenario.log.push("test: three checkouts, every answer held".into());
let pending = scenario.pending(&driven(&mut nodes), &NoWorld);
assert!(pending.starts_with("at 1000:\n  shop 0: 2 held, next timer None\n"));

// Any held Event of any node, chosen by the scenario's generator.
let mut any = |held: &[(usize, HeldEvent)], rng: &mut Rng| rng.below(held.len() as u64) as usize;
while scenario.step_with(&mut driven(&mut nodes), &mut NoWorld, &mut any).is_some() {}
// Shop 1 first, then shop 0's second answer before its first.
assert_eq!(nodes[0].state().payments.paid, [5, 4]);
assert_eq!(
    scenario.report(2),
    "scenario seed 1 failed after 4 steps; the last 2:\n     3. shop 0: deliver payments.charged to /payments\n     4. shop 0: deliver payments.charged to /payments"
);
let log = scenario.into_log();
assert_eq!(log[..2], ["test: three checkouts, every answer held", "shop 1: deliver payments.charged to /payments"]);
let () =
  let scenario = Scenario.create 1 1_000 in
  let protocol = protocol () in
  let nodes =
    Array.init 2 (fun i ->
        Node.of_protocol ~name:(Printf.sprintf "shop %d" i) protocol ~state:empty
          ~services:{ gateway = approve_up_to 100 } ~session:1 (Scenario.clock scenario))
  in
  let driven_nodes = Array.to_list (Array.map driven nodes) in
  let cart = Node.mount nodes.(0) cart_path in
  List.iter
    (fun (shop, price) ->
      ignore (Node.dispatch nodes.(shop) cart (Add { item = "tea"; price }));
      ignore (Node.dispatch nodes.(shop) cart Checkout))
    [ (0, 4); (0, 5); (1, 6) ];
  Scenario.note scenario "test: three checkouts, every answer held";
  let pending = Scenario.pending scenario driven_nodes no_world in
  assert (String.starts_with ~prefix:"at 1000:\n  shop 0: 2 held, next timer none\n" pending);
  (* Any held Event of any node, chosen by the scenario's generator. *)
  let any held rng = Rng.below rng (List.length held) in
  while Scenario.step_with scenario driven_nodes no_world ~choose:any <> None do () done;
  (* Shop 1 first, then shop 0's second answer before its first. *)
  assert ((Node.state nodes.(0)).payments.paid = [ 5; 4 ]);
  assert (
    Scenario.report scenario 2
    = "scenario seed 1 failed after 4 steps; the last 2:\n\
      \     3. shop 0: deliver payments.charged to /payments\n\
      \     4. shop 0: deliver payments.charged to /payments");
  match Scenario.log scenario with
  | note :: first :: _ ->
      assert (note = "test: three checkouts, every answer held");
      assert (first = "shop 1: deliver payments.charged to /payments")
  | _ -> assert false
import assert from "node:assert/strict";
import { rootPath } from "causet";
import { approveUpTo, cartSlot, empty, protocol, shopRoot } from "causet/guide";
import { type Chooser, Node, noWorld, Scenario } from "causet/test";

const scenario = new Scenario(1, 1_000);
const shared = protocol();
const nodes = [0, 1].map((i) =>
  Node.ofProtocol(`shop ${i}`, shared, {
    state: empty,
    services: { gateway: approveUpTo(100) },
    session: 1,
    clock: scenario.clock,
  }),
);
const cart = nodes[0]!.mount(rootPath(shopRoot).child(cartSlot));
for (const [shop, price] of [
  [0, 4],
  [0, 5],
  [1, 6],
] as const) {
  nodes[shop]!.dispatch(cart, { kind: "cart.add", item: "tea", price });
  nodes[shop]!.dispatch(cart, { kind: "cart.checkout" });
}
scenario.note("test: three checkouts, every answer held");
const pending = scenario.pending(nodes, noWorld);
assert(pending.startsWith("at 1000:\n  shop 0: 2 held, next timer none\n"));

// Any held Event of any node, chosen by the scenario's generator.
const any: Chooser = (held, rng) => rng.below(held.length);
while (scenario.stepWith(nodes, noWorld, any) !== undefined) {}
// Shop 1 first, then shop 0's second answer before its first.
assert.deepEqual(nodes[0]!.state.payments.paid, [5, 4]);
assert.equal(
  scenario.report(2),
  "scenario seed 1 failed after 4 steps; the last 2:\n     3. shop 0: deliver payments.charged to /payments\n     4. shop 0: deliver payments.charged to /payments",
);
assert.deepEqual(scenario.log.slice(0, 2), [
  "test: three checkouts, every answer held",
  "shop 1: deliver payments.charged to /payments",
]);

A chooser that varies the order across nodes but keeps production's order within each one uses next_in_queue_ordernext_in_queue_ordernextInQueueOrder. Given one node's held Events in send order, it returns the one its lanes would run had none been held: the Store lane before the worker lane, and on each lane the Events sent to its head newest first, then the others oldest first. step and Node::deliver_nextScenario.step and Node.deliver_nextstep and deliverNext use it.

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use causet::guide::shop::*;
use causet::SessionId;
use causet::hosting::HeldEvent;
use causet_test::{Driven, Node, NoWorld, Rng, Scenario, next_in_queue_order};

/// Any node that holds something, chosen by the generator; within it, the
/// Event its bus would run next.
fn any_node(held: &[(usize, HeldEvent)], rng: &mut Rng) -> usize {
    let node = held[rng.below(held.len() as u64) as usize].0;
    let first = held.iter().position(|(n, _)| *n == node).unwrap();
    let own: Vec<HeldEvent> = held[first..].iter().take_while(|(n, _)| *n == node).map(|(_, e)| e.clone()).collect();
    first + next_in_queue_order(&own).unwrap()
}

for seed in 0..20 {
    let mut scenario = Scenario::new(seed, 1_000);
    let protocol = protocol();
    let mut nodes: Vec<_> = (0..2)
        .map(|i| {
            let services = ShopServices { gateway: Box::new(ApproveUpTo(100)) };
            Node::from_protocol(&format!("shop {i}"), protocol.clone(), ShopState::default(), services, SessionId(1), &scenario.clock)
        })
        .collect();
    let cart = nodes[0].mount(&root::<ShopRoot>().child(CART));
    for (shop, price) in [(0, 4), (0, 5), (1, 6)] {
        nodes[shop].dispatch(&cart, CartAction::Add { item: "tea".into(), price });
        nodes[shop].dispatch(&cart, CartAction::Checkout);
    }
    let mut driven: Vec<&mut dyn Driven> = nodes.iter_mut().map(|n| n as &mut dyn Driven).collect();
    while scenario.step_with(&mut driven, &mut NoWorld, &mut any_node).is_some() {}
    // Whichever shop goes first, each settles its own answers in order.
    assert_eq!(nodes[0].state().payments.paid, [4, 5]);
}
(* Any node that holds something, chosen by the generator; within it, the
   Event its bus would run next. *)
let any_node held rng =
  let node = fst (List.nth held (Rng.below rng (List.length held))) in
  let first = Option.get (List.find_index (fun (n, _) -> n = node) held) in
  let own = List.filter_map (fun (n, e) -> if n = node then Some e else None) held in
  first + Option.get (next_in_queue_order own)

let () =
  for seed = 0 to 19 do
    let scenario = Scenario.create seed 1_000 in
    let protocol = protocol () in
    let nodes =
      Array.init 2 (fun i ->
          Node.of_protocol ~name:(Printf.sprintf "shop %d" i) protocol ~state:empty
            ~services:{ gateway = approve_up_to 100 } ~session:1 (Scenario.clock scenario))
    in
    let cart = Node.mount nodes.(0) cart_path in
    List.iter
      (fun (shop, price) ->
        ignore (Node.dispatch nodes.(shop) cart (Add { item = "tea"; price }));
        ignore (Node.dispatch nodes.(shop) cart Checkout))
      [ (0, 4); (0, 5); (1, 6) ];
    let driven_nodes = Array.to_list (Array.map driven nodes) in
    while Scenario.step_with scenario driven_nodes no_world ~choose:any_node <> None do () done;
    (* Whichever shop goes first, each settles its own answers in order. *)
    assert ((Node.state nodes.(0)).payments.paid = [ 4; 5 ])
  done
import assert from "node:assert/strict";
import { rootPath } from "causet";
import { approveUpTo, cartSlot, empty, protocol, shopRoot } from "causet/guide";
import { type Chooser, Node, nextInQueueOrder, noWorld, Scenario } from "causet/test";

/**
 * Any node that holds something, chosen by the generator; within it, the
 * Event its bus would run next.
 */
const anyNode: Chooser = (held, rng) => {
  const node = held[rng.below(held.length)]!.node;
  const first = held.findIndex((c) => c.node === node);
  const own = held.filter((c) => c.node === node).map((c) => c.event);
  return first + nextInQueueOrder(own)!;
};

for (let seed = 0; seed < 20; seed++) {
  const scenario = new Scenario(seed, 1_000);
  const shared = protocol();
  const nodes = [0, 1].map((i) =>
    Node.ofProtocol(`shop ${i}`, shared, {
      state: empty,
      services: { gateway: approveUpTo(100) },
      session: 1,
      clock: scenario.clock,
    }),
  );
  const cart = nodes[0]!.mount(rootPath(shopRoot).child(cartSlot));
  for (const [shop, price] of [
    [0, 4],
    [0, 5],
    [1, 6],
  ] as const) {
    nodes[shop]!.dispatch(cart, { kind: "cart.add", item: "tea", price });
    nodes[shop]!.dispatch(cart, { kind: "cart.checkout" });
  }
  while (scenario.stepWith(nodes, noWorld, anyNode) !== undefined) {}
  // Whichever shop goes first, each settles its own answers in order.
  assert.deepEqual(nodes[0]!.state.payments.paid, [4, 5]);
}

A scenario also says what it did. Its log has a line for every step taken, such as shop 1: deliver payments.charged to /payments or advance to <time>: <n> timers fired, oldest first; a test adds its own by pushing onto the public logwith Scenario.notewith note. report(last)Scenario.reportreport(last) is the failure report: the seed (or that the choices were replayed), the number of steps and the last last of them. It is what a scenario prints, with the last 20 steps, when it is dropped by a failing test. pendingScenario.pendingpending says what is left, for a run that stopped without reaching its condition: the clock, each node's held Events (with the lane each waits for and the Effect it answers) and its next timer, and the world's next time. into_log takes the log out of a finished scenario, since a field cannot be moved out of a value that reports on drop.Scenario.log returns the log.log is the log.

Fixtures that start mid-workflow

A test of what happens late in a workflow does not have to run the workflow first. A node starts from any State, and its invariants are checked on that State at once, so a fixture that breaks them fails before the first step. What the State refers to outside the Store (a charge the gateway has taken, an answer on its way) is made by the test in the same way:

Here a shop starts as if a checkout of 30 had run: its Effect, execution 7, made the request, which is pending, and the charge is with a gateway that does not answer by itself. The test answers twice, as the gateway's worker would, loses the second answer and delivers the first:

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use causet::guide::shop::*;
use causet::{Child, ExecutionId, ManualClock, SessionId};
use causet::hosting::Lane;
use causet_test::Node;

/// A gateway that takes a charge and answers only when the test says.
struct Silent;
impl Gateway for Silent {
    fn charge(&mut self, _: RequestId, _: u64, _: Reply<Charged>) {}
}

// As if a checkout of 30 had run: its Effect, execution 7, made the request,
// and the charge is with the gateway.
let request = RequestId { session: SessionId(1), execution: ExecutionId(7), index: 0 };
let mut state = ShopState { orders: 1, ..ShopState::default() };
state.payments.pending.insert(request, 30);
let services = ShopServices { gateway: Box::new(Silent) };
let mut shop = Node::from_protocol("shop", protocol(), state, services, SessionId(1), &ManualClock::new(1_000));
let payments = shop.try_mount(&root::<ShopRoot>().child(PAYMENTS)).expect("mounted");
assert!(shop.try_mount(&root::<ShopRoot>().child(Child::<ShopRoot, Payments>::new("refunds"))).is_err());

// The Reply that Effect would have handed the gateway. The gateway answers
// twice, from what stands in for its worker thread.
let reply = shop.sink().reply_for::<Payments, Charged>(&payments, ExecutionId(7)).expect("payments adapts Charged");
for _ in 0..2 {
    reply.try_send_as_worker(Charged { request, approved: true }).unwrap();
}
let held = shop.held();
assert_eq!((held[0].answers, held[0].lane, &*held[0].path), (Some(ExecutionId(7)), Lane::Worker, "/payments"));
assert_eq!(shop.inspect(held[1].id, |c: &Charged| c.approved), Some(true));
// The second answer is lost on the way; the first settles the charge.
assert!(shop.discard(held[1].id));
shop.deliver(held[0].id);
assert_eq!(shop.state().payments.paid, [30]);
assert!(shop.held().is_empty() && shop.state().payments.pending.is_empty());
(* A gateway that takes a charge and answers only when the test says. *)
let silent = { charge = (fun _ _ _ -> ()) }

let () =
  (* As if a checkout of 30 had run: its Effect, execution 7, made the
     request, and the charge is with the gateway. *)
  let request = { Request_id.session = 1; execution = 7; index = 0 } in
  let pending = Pending.add request 30 Pending.empty in
  let state = { empty with orders = 1; payments = { empty.payments with pending } } in
  let shop =
    Node.of_protocol ~name:"shop" (protocol ()) ~state ~services:{ gateway = silent } ~session:1
      (Clock.Manual.create 1_000)
  in
  let at_payments = Node.mount shop (Path.child (Path.root shop_root) payments_slot) in
  let refunds = Path.child (Path.root shop_root) (Child.make "refunds" payments) in
  assert (Result.is_error (Protocol.resolve (Node.protocol shop) refunds));
  (* The reply that Effect would have handed the gateway. The gateway answers
     twice, from what stands in for its worker thread. *)
  let reply = Option.get (Sink.reply_for (Node.sink shop) at_payments charged_message ~answers:7) in
  for _ = 1 to 2 do
    assert (Reply.try_send_as_worker reply ({ request; approved = true } : charged) = Ok ())
  done;
  match Node.held shop with
  | [ first; second ] ->
      assert ((first.held_answers, first.held_lane, first.held_path) = (Some 7, Worker_lane, "/payments"));
      let approved = Option.map (fun (c : charged) -> c.approved) (Node.inspect shop second.held_id charged_message) in
      assert (approved = Some true);
      (* The second answer is lost on the way; the first settles the charge. *)
      assert (Node.discard shop second.held_id);
      Node.deliver shop first.held_id;
      assert ((Node.state shop).payments.paid = [ 30 ]);
      assert (Node.held shop = [] && Pending.is_empty (Node.state shop).payments.pending)
  | _ -> assert false
import assert from "node:assert/strict";
import { child, ManualClock, RequestId, rootPath } from "causet";
import {
  charged,
  empty,
  type Gateway,
  payments,
  paymentsSlot,
  protocol,
  type ShopState,
  shopRoot,
} from "causet/guide";
import { Node } from "causet/test";

/** A gateway that takes a charge and answers only when the test says. */
const silent: Gateway = { charge() {} };

// As if a checkout of 30 had run: its Effect, execution 7, made the request,
// and the charge is with the gateway.
const request = new RequestId(1, 7, 0);
const state: ShopState = {
  ...empty,
  orders: 1,
  payments: { ...empty.payments, pending: empty.payments.pending.add(request, 30) },
};
const shop = Node.ofProtocol("shop", protocol(), {
  state,
  services: { gateway: silent },
  session: 1,
  clock: new ManualClock(1_000),
});
const found = shop.tryMount(rootPath(shopRoot).child(paymentsSlot));
assert(found.ok, "mounted");
const refunds = child<ShopState>()("refunds", payments);
assert(!shop.tryMount(rootPath(shopRoot).child(refunds)).ok);

// The Reply that Effect would have handed the gateway. The gateway answers
// twice, from what stands in for its worker thread.
const reply = shop.sink.replyFor(found.mount, charged, 7);
assert(reply !== undefined, "payments adapts Charged");
for (let i = 0; i < 2; i++) {
  assert(reply.trySendAsWorker({ kind: "payments.charged", request, approved: true }).ok);
}
const [first, second] = shop.held();
assert.deepEqual([first!.answers, first!.lane, first!.path], [7, "worker", "/payments"]);
assert.equal(shop.inspect(second!.id, charged)?.approved, true);
// The second answer is lost on the way; the first settles the charge.
assert(shop.discard(second!.id));
shop.deliver(first!.id);
assert.deepEqual(shop.state.payments.paid, [30]);
assert(shop.held().length === 0 && shop.state.payments.pending.isEmpty());

Under every node is a held bus, EventBus::held(protocol, worker_capacity, session)Event_bus.held proto ~worker_capacity sessionheldBus(protocol, { workerCapacity, session }), which a test can use with a Store directly. Every accepted send waits in a held set, never waiting or failing for room, until the test's handle (HeldEventsHeld.tHeld) releases it into its lane or discards it. The handle lists, inspects, releases and discards; it never delivers anything itself: the Store's drain_eventsdrain_eventsdrainEvents does, by the ordinary rules. A release into a full worker lane is refused, and the Event stays held.

causet.rs / crates/causet/guide/testing.mdcauset.ml / doc/testing.mdcauset.ts / packages/causet/guide/testing.md
use std::sync::Arc;

use causet::guide::shop::*;
use causet::hosting::EventBus;
use causet::SessionId;

let protocol = protocol();
let (_sink, inbox, held) = EventBus::held(&protocol, 64, SessionId(1));
let services = ShopServices { gateway: Box::new(ApproveUpTo(100)) };
let mut store = Store::new(Arc::clone(&protocol), ShopState::default(), services, inbox, StoreOptions::default()).unwrap();
let cart = protocol.resolve(&root::<ShopRoot>().child(CART)).unwrap();
for price in [4, 200] {
    store.dispatch_to(&cart, CartAction::Add { item: "tea".into(), price }).unwrap();
    store.dispatch_to(&cart, CartAction::Checkout).unwrap();
}
// Both answers are held: a drain finds nothing to run.
assert_eq!(store.drain_events(16).unwrap(), 0);
let [approved, declined]: [_; 2] = held.list().try_into().unwrap();
assert_eq!(held.inspect(declined.id, |c: &Charged| c.approved), Some(false));
assert!(held.discard(declined.id));
held.release(approved.id).unwrap();
assert_eq!(store.drain_events(16).unwrap(), 1);
assert_eq!(store.state().payments.paid, [4]);
// The declined charge's answer was lost: it is still pending.
assert_eq!(store.state().payments.pending.len(), 1);
let () =
  let proto = protocol () in
  let _sink, inbox, held = Event_bus.held proto ~worker_capacity:64 1 in
  let store = Store.create_exn proto ~state:empty ~services:{ gateway = approve_up_to 100 } inbox in
  let cart = Protocol.resolve_exn proto cart_path in
  List.iter
    (fun price ->
      ignore (Store.dispatch_exn store cart (Add { item = "tea"; price }));
      ignore (Store.dispatch_exn store cart Checkout))
    [ 4; 200 ];
  (* Both answers are held: a drain finds nothing to run. *)
  assert (Store.drain_events store 16 = Ok 0);
  match Held.list held with
  | [ approved; declined ] ->
      let answer = Held.inspect held declined.held_id charged_message in
      assert (Option.map (fun (c : charged) -> c.approved) answer = Some false);
      assert (Held.discard held declined.held_id);
      assert (Held.release held approved.held_id = Ok ());
      assert (Store.drain_events store 16 = Ok 1);
      assert ((Store.state store).payments.paid = [ 4 ]);
      (* The declined charge's answer was lost: it is still pending. *)
      assert (Pending.cardinal (Store.state store).payments.pending = 1)
  | _ -> assert false
import assert from "node:assert/strict";
import { rootPath, Store } from "causet";
import { approveUpTo, cartSlot, charged, empty, protocol, shopRoot } from "causet/guide";
import { heldBus } from "causet/hosting";

const shared = protocol();
const { inbox, held } = heldBus(shared, { workerCapacity: 64, session: 1 });
const services = { gateway: approveUpTo(100) };
const store = Store.createOrThrow(shared, { state: empty, services, inbox });
const cart = shared.resolveOrThrow(rootPath(shopRoot).child(cartSlot));
for (const price of [4, 200]) {
  store.dispatchOrThrow(cart, { kind: "cart.add", item: "tea", price });
  store.dispatchOrThrow(cart, { kind: "cart.checkout" });
}
// Both answers are held: a drain finds nothing to run.
assert.deepEqual(store.drainEvents(16), { ok: true, delivered: 0 });
const [approved, declined] = held.list();
assert.equal(held.inspect(declined!.id, charged)?.approved, false);
assert(held.discard(declined!.id));
assert(held.release(approved!.id).ok);
assert.deepEqual(store.drainEvents(16), { ok: true, delivered: 1 });
assert.deepEqual(store.state.payments.paid, [4]);
// The declined charge's answer was lost: it is still pending.
assert.equal(store.state.payments.pending.size, 1);
NextObservabilityEvery 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.