<!-- https://tinyactors.dev/guides/journal/ -->
# Journal and replay

Kind: how-to. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Record every input your program gives a tinyactors host, and replay the journal to rebuild every actor after a crash, without running any effect again.

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.

<a id="why"></a>

## 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](https://tinyactors.dev/when-to-use/index.md#crash)).

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.

<a id="record"></a>

## 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:

Node.js and Bun:

```javascript title="main.mjs"
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();
```

```scxml title="order.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="cart">
  <datamodel>
    <data id="items" expr="[]"/>
    <data id="attempts" expr="0"/>
  </datamodel>
  <state id="cart">
    <transition event="add">
      <assign location="items" expr="items.concat([_event.data.sku])"/>
    </transition>
    <transition event="checkout" target="paying"/>
  </state>
  <state id="paying">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="payments" event="charge">
        <param name="amount" expr="items.length * 10"/>
        <param name="key" expr="'order-' + _sessionid"/>
      </send>
      <send event="timeout" delay="30s"/>
    </onentry>
    <transition event="paid" target="paid"/>
    <transition event="timeout" cond="attempts &lt; 3" target="paying"/>
    <transition event="timeout" target="failed"/>
  </state>
  <state id="paid"/>
  <state id="failed"/>
</scxml>
```

Browsers:

```javascript title="browser.mjs"
import { compileCharts, Host, SimulatedClock } from '@tinyactors/wasm';

const chart = await fetch(new URL('order.scxml', import.meta.url)).then((response) => response.text());
const compiled = compileCharts([{ name: 'order.scxml', text: chart }]);

// 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();
```

```scxml title="order.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="cart">
  <datamodel>
    <data id="items" expr="[]"/>
    <data id="attempts" expr="0"/>
  </datamodel>
  <state id="cart">
    <transition event="add">
      <assign location="items" expr="items.concat([_event.data.sku])"/>
    </transition>
    <transition event="checkout" target="paying"/>
  </state>
  <state id="paying">
    <onentry>
      <assign location="attempts" expr="attempts + 1"/>
      <send type="payments" event="charge">
        <param name="amount" expr="items.length * 10"/>
        <param name="key" expr="'order-' + _sessionid"/>
      </send>
      <send event="timeout" delay="30s"/>
    </onentry>
    <transition event="paid" target="paid"/>
    <transition event="timeout" cond="attempts &lt; 3" target="paying"/>
    <transition event="timeout" target="failed"/>
  </state>
  <state id="paid"/>
  <state id="failed"/>
</scxml>
```

```text title="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 key**: is `'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 sessions**: the journal reaches the order by its address, `tinyactors://shop/@order-1`, so it reads the same on any host.
- **The webhook**: is an input like any other. An answer from outside the host must be recorded, or the replay never hears it.
- **The replay's processor**: does 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 clock**: moves 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.restore`**: takes 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.

<a id="crash-before-answer"></a>

## 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:

```javascript title="main.mjs"
// 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(', ')}`);
```

```text title="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.

<a id="snapshots"></a>

## 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](https://tinyactors.dev/guides/snapshots/index.md#replaying-inputs)).

The [turn-game example](https://github.com/tinyactors-dev/tinyactors/tree/main/tinyactors-napi/examples/turn-game) does this for a game server it kills and restarts. It checkpoints every second and replays the moves made since.

<a id="deterministic"></a>

## 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 chance**: a 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 services**: an 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 millisecond**: the 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 flight**: a 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](https://tinyactors.dev/guides/journal/index.md#crash-before-answer)).

<a id="one-actor"></a>

## 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.

<a id="choose"></a>

## Choose a journal, snapshots or both

- **A journal**: keeps 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 alone**: cost nothing per input, and restoring two million actors took 0.14 to 0.21 s ([measured on one machine](https://tinyactors.dev/guides/snapshots/index.md#at-scale)). Inputs after the last snapshot are lost.
- **Both**: restore the last snapshot, then replay the short journal written since. This is what turn-game does.
- **[Hibernation](https://tinyactors.dev/guides/hibernation/index.md)**: is not a log: it keeps waiting actors out of memory. Use it with either.
