Rebuild a host from its inputs

A chart's state follows from its inputs and their times. Write each input to a journal before the host sees it, and one loop rebuilds every actor without charging a card again.

Your program already has a log

A crash stops every actor in the process. What comes back is what your program wrote down (what a crash keeps).

tinyactors writes no log of its own, because your program already has one: a table, a file, a queue. Recording an input is one write, and replaying is one loop.

A chart that reads no clock and no random numbers has no hidden inputs. Given the same events in the same order at the same times, it takes the same transitions and ends in the same state.

Record every input, then apply it

An order takes two items and checks out. The payment service never answers the first charge, so the chart charges again 30 seconds later, and the provider's webhook then says paid.

Both charges carry one idempotency key. The stand-in provider charges a card once per key, so a retry is safe.

Every input goes through one function, record(), which writes the host's time and the input, then applies it. The replay applies the same lines to a new host:

import { readFileSync } from 'node:fs';
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);

// Every input goes through record(): the host's time, then the input.
const journal = [];
function apply(host, entry) {
  if (entry.spawn) host.spawn(entry.spawn, { name: entry.name });
  else host.send(entry.send);
}
function record(host, entry) {
  const line = JSON.stringify({ at: host.now(), ...entry });
  journal.push(line); // in production: append to a file or a table first
  apply(host, JSON.parse(line));
}

// A stand-in for the payment provider: it charges a card once per key.
const requests = [];
const cards = new Map();
const payments = {
  receive(send) {
    requests.push(send.data.key);
    if (!cards.has(send.data.key)) cards.set(send.data.key, send.data.amount);
  },
};
const nobody = { receive() {} }; // charges nobody

const order = { target: 'tinyactors://shop/@order-1' };
const clock = new SimulatedClock();
const live = new Host(compiled, { system: 'shop', clock, ioProcessors: { payments } });

record(live, { spawn: 'order', name: 'order-1' });
record(live, { send: { ...order, event: 'add', data: { sku: 'pen' } } });
record(live, { send: { ...order, event: 'add', data: { sku: 'notebook' } } });
record(live, { send: { ...order, event: 'checkout' } });
await live.idle();
clock.increment(30_000); // no answer: the chart charges again, with the same key
await live.idle();
clock.increment(5_000);
record(live, { send: { ...order, event: 'paid' } }); // the provider's webhook
await live.idle();

// Replay journal lines into a new host whose processor does nothing.
async function replay(lines) {
  const replayClock = new SimulatedClock();
  const host = new Host(compiled, { system: 'shop', clock: replayClock, ioProcessors: { payments: nobody } });
  for (const line of lines) {
    const entry = JSON.parse(line);
    replayClock.increment(entry.at - host.now());
    await host.idle();
    apply(host, entry);
    await host.idle();
  }
  return host;
}
const replayed = await replay(journal);

// Go on from the replay on the runtime's clock, with the real processor.
const restored = Host.restore(replayed.snapshot(), compiled, { system: 'shop', ioProcessors: { payments } });

for (const [name, host] of [['live', live], ['replay', replayed], ['restored', restored]]) {
  const actor = host.actor('order-1');
  const { value } = await actor.state();
  const { variables } = await actor.context();
  console.log(`${name}: ${JSON.stringify(value)} after ${variables.attempts} attempts, ${variables.items.join(', ')}`);
}
console.log(`${journal.length} inputs journaled; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);

// A crash after the first charge, before its answer: the journal ends at the checkout.
const beforeAnswer = await replay(journal.slice(0, 4));
const crashClock = new SimulatedClock();
const recovered = Host.restore(beforeAnswer.snapshot(), compiled, { system: 'shop', clock: crashClock, ioProcessors: { payments } });
crashClock.increment(30_000); // the chart's timer charges again, with the same key
await recovered.idle();
const crashed = recovered.actor('order-1');
const { value } = await crashed.state();
const { variables } = await crashed.context();
console.log(`after a crash: ${JSON.stringify(value)} after ${variables.attempts} attempts; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);

for (const host of [live, replayed, restored, beforeAnswer, recovered]) host.close();
compiled.close();
output
live: "paid" after 2 attempts, pen, notebook
replay: "paid" after 2 attempts, pen, notebook
restored: "paid" after 2 attempts, pen, notebook
5 inputs journaled; 2 charge requests, cards charged: 20
after a crash: "paying" after 2 attempts; 3 charge requests, cards charged: 20

Five inputs rebuilt the order. The live host sent two charge requests under one key, so the card was charged once, and the replay sent none. What each part does:

  • record()writes host.now() and the input as one JSON line, and only then applies it, so the journal never misses an input the host saw. In production, make the write durable before applying (an fsync, a committed transaction). A crash between the write and the apply replays an input the host never saw. A sender that never heard back may send it again, so give such inputs a sendid the chart checks.
  • The charge's keyis 'order-' + _sessionid, the same on every attempt and in a host restored from a snapshot, so a retry never charges a card twice.
  • Names, not sessionsthe journal reaches the order by its address, tinyactors://shop/@order-1, so it reads the same on any host.
  • The webhookis an input like any other. An answer from outside the host must be recorded, or the replay never hears it.
  • The replay's processordoes nothing, so no card is charged again. Effects leave the chart as events, which is what lets the replay switch them off.
  • The replay's clockmoves to each entry's time and runs everything due by then before applying the entry, so the 30-second timeout fires before the webhook arrives, as it did live.
  • Host.restoretakes a snapshot of the replayed host and runs it on the runtime's clock with the real processor, so the program goes on where it stopped.

Charge again after a crash, under one key

A process can die after a charge left it and before its answer came back. The journal then ends at the checkout, and nobody knows whether the card was charged.

The program's last lines play that crash. They replay the journal up to the checkout, restore the result with the real processor and move its clock 30 seconds:

main.mjsjavascript
// A crash after the first charge, before its answer: the journal ends at the checkout.
const beforeAnswer = await replay(journal.slice(0, 4));
const crashClock = new SimulatedClock();
const recovered = Host.restore(beforeAnswer.snapshot(), compiled, { system: 'shop', clock: crashClock, ioProcessors: { payments } });
crashClock.increment(30_000); // the chart's timer charges again, with the same key
await recovered.idle();
const crashed = recovered.actor('order-1');
const { value } = await crashed.state();
const { variables } = await crashed.context();
console.log(`after a crash: ${JSON.stringify(value)} after ${variables.attempts} attempts; ${requests.length} charge requests, cards charged: ${[...cards.values()].join(', ')}`);
output
live: "paid" after 2 attempts, pen, notebook
replay: "paid" after 2 attempts, pen, notebook
restored: "paid" after 2 attempts, pen, notebook
5 inputs journaled; 2 charge requests, cards charged: 20
after a crash: "paying" after 2 attempts; 3 charge requests, cards charged: 20

The restored order's timer charged again, so the provider got a third request. It carried the first charge's key, so the card was still charged once, and the order waits in paying for the provider's answer.

Keep the journal short with snapshots

A journal that is never cut grows with every input, and so does the replay. Snapshot the host now and then, and store the journal's position with the snapshot.

After a crash, restore the last snapshot on a SimulatedClock and replay only the entries after it. Then snapshot again and empty the journal (replay the inputs that came after).

The turn-game example does this for a game server it kills and restarts. It checkpoints every second and replays the moves made since.

Keep the chart's inputs in the journal

A replay matches only when every input the chart reads is in the journal. Check three things.

  • Time and chancea chart that reads Date or Math.random gets a new answer on replay. Read them in your program and pass them in as event data, which the journal then holds.
  • Answers and servicesan I/O processor's answer, a service's sendBack and done and a host.fail are inputs. Give them through record(), with the sender's address and the send's sendid, and on replay give the processors and services stand-ins that do nothing.
  • The same millisecondthe replay runs every timer due at an entry's time before the entry, while live the input may have come first. A chart should not depend on which wins within one millisecond, as a move against its turn's timeout in the turn-game example does.
  • Effects in flighta charge the live host sent, whose answer never reached the journal, is lost with the crash. After the restore, the chart's timer charges again, so send the same idempotency key on every attempt (above).

Journal a host, or one actor

When actors send each other events, one actor's input changes another's state. Journal the whole host, the unit a replay rebuilds.

An actor that hears only from outside can have a journal of its own, keyed by its name. Replay that journal into a fresh host to rebuild it alone.

Choose a journal, snapshots or both

  • A journalkeeps every input, so nothing after the last write is lost, and it doubles as an audit log. It costs one write before each input and a replay as long as the journal.
  • Snapshots alonecost nothing per input, and restoring two million actors took 0.14 to 0.21 s (measured on one machine). Inputs after the last snapshot are lost.
  • Bothrestore the last snapshot, then replay the short journal written since. This is what turn-game does.
  • Hibernationis not a log: it keeps waiting actors out of memory. Use it with either.