Unreleased. Packages are not on crates.io, npm or opam yet. Use commit-pinned source.
Guide · 0
Overview
Causet is a framework for building event-driven systems from composable state machines. It separates state transitions from external work, so the same components can run in production or in a deterministic simulation.
Tests define the operations to explore and the rules that must hold. Causet automatically generates sequences of inputs and modeled failures, checks those rules, and shrinks failures into small, reproducible cases.
Implementations
The three implementations follow the same model and scheduling rules.
| Implementation | GitHub repository |
|---|---|
| Rust | tizoc/causet.rs |
| OCaml | tizoc/causet.ml |
| TypeScript | tizoc/causet.ts |
The guide source is maintained separately. Packages are not yet published; each implementation's README explains how to install from a pinned source revision.
The problem
Event-driven behavior often becomes scattered across callbacks, tasks, timers and shared mutable state. Timeouts, retries and delayed responses can affect the same operation. Understanding a failure requires reconstructing which paths ran first, and reproducing a rare ordering is difficult.
Causet puts transition logic in reducers and makes scheduling explicit. Tests control external inputs and time, so they can explore difficult orderings using the application's real components.
The model
- A component owns a piece of State. Only its reducer changes it, and only in answer to an Action: a request such as "charge 30".
- When the reducer needs the outside world, it emits an Effect: a description of the work, not the work itself. The component's Effect handler gives it to a Service, which does the I/O however it likes, on worker threads, over sockets, with real timers.
- The Service answers with an Event. The component's adapter turns the Event into an Action, and the reducer handles the answer like any other input.
- Components form a tree. A child reports facts to its parent with an Output (such as "checked out, total 4"), and the parent decides what they mean for the rest of the application.
A Store holds the whole State and runs all of it on one thread, one input at a time, in an order fixed by a few rules (scheduling). Nothing changes State between inputs, and a reducer never waits: it records what it is waiting for and returns.
Find bugs automatically
A simulated payment gateway has a total budget of 100. Its bug is forgetting to deduct earlier approvals. This test generates charges and decides when to deliver replies, checking that total payments stay within the budget. It checks the fixed gateway, then finds and shrinks a failure in the faulty one and verifies that replay fails the same way.
The application uses the guide's Payments component, running in a real Store with a simulated gateway. The test supplies the possible operations and an invariant; Causet generates the runs, checks the invariant and shrinks the failure. This is generated simulation testing, with seeded randomness and controlled Services so a failing run can be repeated.
use causet::{ManualClock, Reply, RequestId, SessionId, root};
use causet::guide::shop::{Charged, Gateway, Payments, PaymentsAction, PaymentsState};
use causet_test::{Config, Node, Rng, check, replay, search};
struct Budget { remaining: u64, forgets: bool }
impl Gateway for Budget {
fn charge(&mut self, request: RequestId, amount: u64, reply: Reply<Charged>) {
let approved = amount <= self.remaining;
// The planted bug: earlier approvals are forgotten.
if approved && !self.forgets { self.remaining -= amount; }
reply.try_send(Charged { request, approved }).unwrap();
}
}
fn spending(rng: &mut Rng, forgets: bool) {
let gateway: Box<dyn Gateway> = Box::new(Budget { remaining: 100, forgets });
let mut node = Node::new::<Payments>("shop", PaymentsState::default(), gateway, SessionId(1), &ManualClock::new(0))
.check("paid within budget", |s: &PaymentsState| {
if s.paid.iter().sum::<u64>() <= 100 { Ok(()) } else { Err("overspent".into()) }
});
let mount = node.mount(&root::<Payments>());
while rng.more() {
if rng.chance(1, 2) {
node.dispatch(&mount, PaymentsAction::Charge { amount: rng.between(1, 100) });
} else {
node.deliver_next();
}
}
while node.deliver_next().is_some() {}
}
check(Config::default(), |rng| spending(rng, false)); // The fixed gateway passes.
let found = search(Config::default(), |rng| spending(rng, true)).unwrap();
assert_eq!(found.key, r#"node shop: invariant "paid within budget""#);
assert!(found.choices.len() < found.original);
println!("seed {}: {}\nshrunk {} choices to {}\nchoices {:?}",
found.seed, found.key, found.original, found.choices.len(), found.choices);
// Replay must reproduce the planted failure.
assert!(std::panic::catch_unwind(|| replay(&found.choices, |rng| spending(rng, true))).is_err());open Causet
open Causet_guide.Shop
open Causet_test
let spending rng ~forgets =
let remaining = ref 100 in
let gateway =
{
charge =
(fun request amount reply ->
let approved = amount <= !remaining in
(* The planted bug: earlier approvals are forgotten. *)
if approved && not forgets then remaining := !remaining - amount;
assert (Reply.try_send reply { request; approved } = Ok ()));
}
in
let node =
Node.create ~name:"shop" payments ~state:{ pending = Pending.empty; paid = []; declined = [] }
~services:gateway ~session:1 (Clock.Manual.create 0)
in
let node =
Node.check node "paid within budget" (fun s ->
if List.fold_left ( + ) 0 s.paid <= 100 then Ok () else Error "overspent")
in
let mount = Node.mount node (Path.root payments) in
while Rng.more rng do
if Rng.chance rng 1 2 then
ignore (Node.dispatch node mount (Charge { amount = Rng.between rng 1 100 }))
else ignore (Node.deliver_next node)
done;
while Option.is_some (Node.deliver_next node) do
()
done
let () =
check (fun rng -> spending rng ~forgets:false); (* The fixed gateway passes. *)
let found = Option.get (search default (fun rng -> spending rng ~forgets:true)) in
assert (found.key = {|node shop: invariant "paid within budget"|});
assert (List.length found.choices < found.original);
Printf.printf "seed %d: %s\nshrunk %d choices to %d\nchoices [%s]\n" found.seed found.key
found.original (List.length found.choices)
(String.concat ", " (List.map string_of_int found.choices));
(* Replay must reproduce the planted failure. *)
try
replay found.choices (fun rng -> spending rng ~forgets:true);
assert false
with Failed failure -> assert (failure.key = found.key)import assert from "node:assert/strict";
import { ManualClock, rootPath } from "causet";
import { type Gateway, empty, payments } from "causet/guide";
import { check, Node, replay, type Rng, search } from "causet/test";
function spending(rng: Rng, forgets: boolean): void {
let remaining = 100;
const gateway: Gateway = {
charge(request, amount, reply) {
const approved = amount <= remaining;
// The planted bug: earlier approvals are forgotten.
if (approved && !forgets) remaining -= amount;
assert.ok(reply.trySend({ kind: "payments.charged", request, approved }).ok);
},
};
const node = Node.create("shop", payments, {
state: empty.payments,
services: gateway,
session: 1,
clock: new ManualClock(0),
}).check("paid within budget", (s) =>
s.paid.reduce((sum, amount) => sum + amount, 0) <= 100 ? undefined : "overspent",
);
const mount = node.mount(rootPath(payments));
while (rng.more()) {
if (rng.chance(1, 2)) {
node.dispatch(mount, { kind: "payments.charge", amount: rng.between(1, 100) });
} else {
node.deliverNext();
}
}
while (node.deliverNext()) {}
}
check((rng) => spending(rng, false)); // The fixed gateway passes.
const found = search({}, (rng) => spending(rng, true));
assert.ok(found);
assert.equal(found.key, 'node shop: invariant "paid within budget"');
assert.ok(found.choices.length < found.original);
console.log(
`seed ${found.seed}: ${found.key}\nshrunk ${found.original} choices to ${found.choices.length}\nchoices [${found.choices.join(", ")}]`,
);
// Replay must reproduce the planted failure.
assert.throws(() => replay(found.choices, (rng) => spending(rng, true)), /paid within budget/);All three ports produce:
seed 1: node shop: invariant "paid within budget"
shrunk 13 choices to 7
choices [1, 1, 51, 1, 1, 48, 0]
The shrunk run charges 52 and 49, then delivers both replies: 101 paid from
a budget of 100. search lets this example assert that a known bug is found;
use check in ordinary tests to fail on a discovered violation. Keeping the
shrunk choices gives you a reproducible regression test.
The last assertion catches the expected replay failure so this example can pass as a documentation test. With the fault fixed, keep the choices as a regression test and let replay run normally. The testing page develops this into timeouts, restarts and several nodes on one simulated network.
One checkout, step by step
Run the small shop from a checkout of your port:
cargo run -p causet --example shopopam install . --deps-only --with-test once for its dependencies, then dune exec examples/shop/main.exepnpm install once for its dependencies, then pnpm --filter shop start.
It prints the payment before and after Event delivery, then runs the same
Payments component in simulation with two replies delivered out of order.
The port's examples/README.md gives the reading order and commands for
the larger reference applications.
The guide's example application is a small shop: a cart and a payments component under one root, and a gateway Service that payments charges through.
| Mount | Component | What it does |
|---|---|---|
/ |
ShopRootshop_rootshopRoot |
The root; its State is the whole application's. |
/cart |
Cartcartcart |
Collects items; reports a checkout to its parent. |
/payments |
Paymentspaymentspayments |
Charges through the gateway Service. |
A checkout passes through every kind of message:
- The cart reducer empties the cart and emits the Output
CheckedOut { total }Checked_out { total }{ kind: "cart.checked_out", total }. - The root's lowerer turns that Output into the root's own Action,
Pay { total }. - The root reducer counts the order and sends
Charge { amount }to its payments child. - The payments reducer makes a request ID, records the charge as
pending under it, and emits the Effect
Charge { request, amount }Charge_effect { request; amount }{ kind: "payments.charge", request, amount }. - The Effect handler gives the gateway the charge and a reply to answer through. The gateway answers now or later, from any thread, from any thread, from a promise or a callback, and its Event waits on the bus until the application drains it.
- The payments adapter turns the Event into the Action
Settled { request, approved }Settled { request; approved }{ kind: "payments.settled", request, approved }. - The payments reducer takes the pending charge and records it as paid.
In code, the application drives it from outside:
use causet::guide::shop::*;
let mut shop = Shop::open(StoreOptions::default());
shop.store.dispatch_to(&shop.cart, CartAction::Add { item: "tea".into(), price: 4 }).unwrap();
shop.store.dispatch_to(&shop.cart, CartAction::Checkout).unwrap();
assert_eq!(shop.store.state().payments.pending.len(), 1); // sent, not answered yet
shop.store.drain_events(16).unwrap(); // the gateway's answer runs
assert_eq!(shop.store.state().payments.paid, [4]);open Causet
open Causet_guide.Shop
let () =
let shop = open_ () in
ignore (Store.dispatch_exn shop.store shop.cart_mount (Add { item = "tea"; price = 4 }));
ignore (Store.dispatch_exn shop.store shop.cart_mount Checkout);
(* Sent, not answered yet. *)
assert (Pending.cardinal (Store.state shop.store).payments.pending = 1);
(* The gateway's answer runs. *)
ignore (Store.drain_events shop.store 16);
assert ((Store.state shop.store).payments.paid = [ 4 ])import assert from "node:assert/strict";
import { open } from "causet/guide";
const shop = open();
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.add", item: "tea", price: 4 });
shop.store.dispatchOrThrow(shop.cart, { kind: "cart.checkout" });
assert.equal(shop.store.state.payments.pending.size, 1); // sent, not answered yet
shop.store.drainEvents(16); // the gateway's answer runs
assert.deepEqual(shop.store.state.payments.paid, [4]);The Store records each step as an execution, numbered in the order it ran, with the execution that caused it. This is the trace of the run above:
| ID | Caused by | Category | Mount | Kind |
|---|---|---|---|---|
| 1 | input | Action | /cart |
cart.add |
| 2 | input | Action | /cart |
cart.checkout |
| 3 | 2 | Action | / |
shop.pay |
| 4 | 3 | Action | /payments |
payments.charge |
| 5 | 4 | Effect | /payments |
payments.charge |
| 6 | input, answering 5 | Event | /payments |
payments.charged |
| 7 | 6 | Action | /payments |
payments.settled |
The payments reducer is all of the payment logic. The request ID ties each
answer to its charge: the reducer makes it, keeps the charge in a Pending
table under it, and sends it with the Effect; the answer carries it back.
fn reduce(mut ctx: ComponentContext<'_, Self>, action: PaymentsAction, _: &ActionMeta) {
match action {
PaymentsAction::Charge { amount } => {
let request = ctx.new_request();
ctx.state_mut().pending.insert(request, amount);
ctx.into_emitter().emit_effect(PaymentsEffect::Charge { request, amount });
}
PaymentsAction::Settled { request, approved } => {
let state = ctx.state_mut();
// A duplicate, or an answer after a timeout, finds nothing: it is stale.
if let Some(amount) = state.pending.take(request) {
if approved { state.paid.push(amount) } else { state.declined.push(amount) }
}
}
}
}~reduce:(fun ctx action _ ->
match action with
| Charge { amount } ->
let request = Ctx.new_request ctx in
Ctx.update ctx (fun s -> { s with pending = Pending.add request amount s.pending });
Ctx.emit_effect ctx (Charge_effect { request; amount })
| Settled { request; approved } -> (
let s = Ctx.state ctx in
(* A duplicate, or an answer after a timeout, finds nothing: it is stale. *)
match Pending.take request s.pending with
| None -> ()
| Some (amount, pending) ->
Ctx.set_state ctx
(if approved then { s with pending; paid = s.paid @ [ amount ] }
else { s with pending; declined = s.declined @ [ amount ] })))import { component } from "causet";
import { type Gateway, type PaymentsState, paymentsAction, paymentsEffect } from "causet/guide";
export const payments = component<PaymentsState, Gateway>()({
name: "payments",
actions: paymentsAction,
effects: paymentsEffect,
reduce(ctx, action) {
switch (action.kind) {
case "payments.charge": {
const request = ctx.newRequest();
ctx.update((s) => ({ ...s, pending: s.pending.add(request, action.amount) }));
ctx.emitEffect({ kind: "payments.charge", request, amount: action.amount });
break;
}
case "payments.settled": {
const s = ctx.state;
// A duplicate, or an answer after a timeout, finds nothing: it is stale.
const taken = s.pending.take(action.request);
if (taken === undefined) return;
const [amount, pending] = taken;
ctx.set(
action.approved
? { ...s, pending, paid: [...s.paid, amount] }
: { ...s, pending, declined: [...s.declined, amount] },
);
break;
}
}
},
});A timeout would be one more Effect, asking the timer Service for an Event later, and one more Action that takes the same request ID out of the table. Whichever arrives first, the answer or the timeout, wins, and the other finds nothing.
Controlling one run
Components reach the world only through Services, so a test can give them simulated ones. And since the Store runs one input at a time, the test decides what happens next: which answer arrives, in which order, and when.
A test Node runs the real Store but holds every Event a Service sends
until the test delivers it. Here two charges are answered in the opposite
order:
use causet::{ManualClock, SessionId, root};
use causet::guide::shop::{ApproveUpTo, Charged, Gateway, Payments, PaymentsAction, PaymentsState};
use causet_test::Node;
let gateway: Box<dyn Gateway> = Box::new(ApproveUpTo(100));
let clock = ManualClock::new(0);
let mut node = Node::new::<Payments>("shop", PaymentsState::default(), gateway, SessionId(1), &clock);
let payments = node.mount(&root::<Payments>());
node.dispatch(&payments, PaymentsAction::Charge { amount: 30 });
node.dispatch(&payments, PaymentsAction::Charge { amount: 200 });
// The second answer arrives first; each still settles its own charge.
assert!(node.deliver_where(|charged: &Charged| !charged.approved));
assert_eq!(node.state().declined, [200]);
node.deliver_next();
assert_eq!(node.state().paid, [30]);module Node = Causet_test.Node
let () =
let node =
Node.create ~name:"shop" payments
~state:{ pending = Pending.empty; paid = []; declined = [] }
~services:(approve_up_to 100) ~session:1 (Clock.Manual.create 0)
in
let m = Node.mount node (Path.root payments) in
ignore (Node.dispatch node m (Charge { amount = 30 }));
ignore (Node.dispatch node m (Charge { amount = 200 }));
(* The second answer arrives first; each still settles its own charge. *)
assert (Node.deliver_where node charged_message (fun c -> not c.approved));
assert ((Node.state node).declined = [ 200 ]);
ignore (Node.deliver_next node);
assert ((Node.state node).paid = [ 30 ])import assert from "node:assert/strict";
import { ManualClock, rootPath } from "causet";
import { approveUpTo, charged, empty, payments } from "causet/guide";
import { Node } from "causet/test";
const node = Node.create("shop", payments, {
state: empty.payments,
services: approveUpTo(100),
session: 1,
clock: new ManualClock(0),
});
const m = node.mount(rootPath(payments));
node.dispatch(m, { kind: "payments.charge", amount: 30 });
node.dispatch(m, { kind: "payments.charge", amount: 200 });
// The second answer arrives first; each still settles its own charge.
assert.ok(node.deliverWhere(charged, (c) => !c.approved));
assert.deepEqual(node.state.declined, [200]);
node.deliverNext();
assert.deepEqual(node.state.paid, [30]);A hand-driven test is useful for a particular ordering. The generated test above explores many such choices automatically. Several nodes can also share a simulated network and one virtual clock; the testing page shows how to control both individual cases and generated runs.
Seeing what happened
Every step the Store takes 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 one as it happens: a logger, statistics, a trace, or your own. So a log can say not only what happened but why, back to the input that started it.Watching is cheap: with the stock observers installed, an execution still allocates nothing. The observability page shows how.
What you write, and what causet does
| You write | Causet does |
|---|---|
| Message types, with derivesa deriverdescriptors that name them | Runs every input to completion, in a fixed order |
| Each component's State and reducer | Checks whether each Action is allowed before it runs |
| Effect handlers and Services, for the I/O | Routes each answer to the component that asked |
| Adapters and lowerers, which translate | Numbers requests and stamps time from one clock |
| Possible test operations and invariants | Generates simulations, finds violations, shrinks failures and reproduces them from saved choices |
When it fits
The cost is more explicit code: every asynchronous step is a named message, and every lifecycle is State. That pays off when the hard parts are ordering, timeouts, retries, cancellation and stale results, as in network protocols, wallets and synchronization engines. An application whose hard parts live in its database queries gains little from it.
Reading on
- Messages: declaring Actions, Effects, Events and Outputs, their kinds, nesting and what they log.
- Authority: what each kind of code may read, change and start, and why the compilertype checkertype checker can enforce it.
- Scheduling: the exact order in which work runs, how an Action is admitted or refused, and what a panican exceptionan exception does.
- Addressing: how components nest, how a parent calls a child, and where an Effect belongs.
- Running an application: starting a Store, driving it, Services on other threads, and assembling it by hand.
- Timeouts and retries: deadlines, timers, and requests sent again.
- Determinism: the few rules application code must follow so a run can be repeated.
- Testing: one transition, one node, generated runs, and several nodes on a simulated network.
- Observability: what observers see, following a result to its cause, logging, statistics, reporting, and what they cost.
- Projections: facts derived from an ordered log, kept right across restarts, and the checks for them.