# 6. The journal: crash and resume

**At the end you can:** keep a run in a SQLite file, continue it from another process after
a restart or a crash, and write a tool whose effect happens once even when its call is
repeated.

**What you will learn:** how a run survives the end of its process. You will store the
journal in a SQLite file, end the process while a refund waits for approval, finish the run
in a new process, then kill a process in the middle of a refund and see what gvn promises,
and what it leaves to you.

**Before this:** [5. A policy, and approval by a person](agent-with-approval.md).

**Time:** about 20 minutes.

## Where this sits in the big picture

This page is about one box of the quickstart's
[big picture](../quickstart.md#the-big-picture): the **journal**, where the Governor
records every event of a run, in order. Until now it lived in memory and died with the
process. Here it moves into a file, and you will see why that is enough to continue a run in
a different process: the actor never did any work itself, so its events are all there is to
restore. The page goes from the whole to the parts: first what survives a crash and what
runs again, then the code that shows each case.

## Where you are

In tutorial 5 the help desk agent asked a person before refunding, and the person answered in
the same Python session. This page builds on one part of that program: the policy. This time
the policy is given the refund tool when it is built, because on this page every process
builds its own tools.

**Start a new file for this page, and begin it with the block below.** The block holds
everything from the earlier pages that this page uses, imports included. That is the same
first step whether you have just finished tutorial 5 or are starting here. Then add each
block of the page below it, in order.

??? example "The policy from tutorial 5"

    ```python
    import asyncio
    import typing

    from gvn.harness.agent import VERDICTS, Agent
    from gvn.harness.events import Event
    from gvn.harness.messages import Message, ToolCall
    from gvn.harness.ports import Exchange, Journal, Reply
    from gvn.harness.tools import Invocation, Tool, Toolbox
    from gvn.kernel.decision import Decision
    from gvn.kernel.schema import Number, Record, Text
    from gvn.kernel.symbols import Alphabet, Symbol
    from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
    from gvn.runtime.governor import Governor, Result
    from gvn.testing.fakes import ManualClock, RecordingOutput

    REFUND_LIMIT = 100.0


    class RefundPolicy(Decision):
        """Look-ups are cleared, refunds need a person, large refunds are forbidden."""

        def __init__(self, refund_tool: Tool) -> None:
            self._refund_tool = refund_tool

        def outcomes(self) -> Alphabet:
            return VERDICTS

        def judge(self, consultation: object) -> Symbol:
            refunds = consultation.calls_to(self._refund_tool)
            if not refunds:
                return VERDICTS.named("cleared")
            (call,) = refunds  # the one call being judged
            amount = call.arguments().get("amount")
            if not isinstance(amount, (int, float)) or amount > REFUND_LIMIT:
                return VERDICTS.named("forbidden")
            return VERDICTS.named("needs_approval")
    ```

The person approving a refund may take hours. A process that waits that long will, sooner
or later, be restarted, redeployed or killed. This tutorial makes the run outlive it.

## What survives, and what runs again

A **snapshot** saves the actor's state at a position in its **journal**, the ordered record
of events. Recovery loads that snapshot and replays later recorded events to rebuild the
actor. It does no outside work. Only after recovery does `resume` fulfil the requests that
are still pending.

The difficult case is a refund that succeeded outside gvn, but whose result was not yet
journaled when the process died:

```mermaid
sequenceDiagram
    participant P as First process
    participant J as Journal and snapshots
    participant T as Refund system
    participant N as New process
    P->>J: Save snapshot
    P->>J: Append events that make refund pending
    P->>T: Refund with stable call key
    T-->>P: Refund succeeded
    Note over P,J: Crash before tools_returned is appended
    N->>J: Load latest snapshot and later events
    J-->>N: Recorded history
    Note over N: Replay events, without calling tools<br/>Refund request is still pending
    N->>T: Resume: refund again with the same key
    T-->>N: Previous result if system deduplicates
    N->>J: Append tools_returned
```

The journal cannot tell whether that first refund happened. gvn therefore reissues pending
work with the same request id, and tools receive the same call key. That gives the tool a
way to recognise a repeat; the tool or payment system must make repeating it harmless.
Below, you will first see a duplicate refund, then add that protection.

## How this page simulates processes

Each "process" below is a function run with its own `asyncio.run`. The processes share
nothing in memory: every object is built inside the function, and the only state that carries
over is in a temporary workspace. A real `kill -9` ends a process somewhere between
two journal writes; `CrashingJournal`, from gvn's test kit, lets you choose exactly which
write, so the program can test a precise moment.

## Step 1: the outside world, in a file

The ledger of tutorial 5 lived in memory and would die with the process. The real payment
system does not, so here it is a file, `refunds.json`:

```python
import json
import pathlib
from tempfile import TemporaryDirectory

workspace = TemporaryDirectory(prefix="gvn-durability-")
state_dir = pathlib.Path(workspace.name)
journal_path = state_dir / "helpdesk.db"
refund_path = state_dir / "refunds.json"
done_path = state_dir / "done.json"


class RefundFile:
    """The shop's payment system: a file of refunds made. Not part of the harness."""

    def __init__(self, path: str | pathlib.Path) -> None:
        self._path = pathlib.Path(path)

    def refunds(self) -> list[dict[str, typing.Any]]:
        if not self._path.exists():
            return []
        return json.loads(self._path.read_text())

    def refund(self, order_id: str, amount: float) -> int:
        made = self.refunds()
        made.append({"order_id": order_id, "amount": amount})
        self._path.write_text(json.dumps(made))
        return len(made)


class IssueRefund(Tool):
    def __init__(self, ledger: RefundFile) -> None:
        self._ledger = ledger

    def name(self) -> str:
        return "issue_refund"

    def description(self) -> str:
        return "Refund an amount on an order. Money leaves the shop."

    def arguments(self) -> Record:
        return Record({"order_id": Text(), "amount": Number()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        number = self._ledger.refund(order_id=arguments["order_id"], amount=arguments["amount"])
        return {"refund": number}
```

## Step 2: a model whose answer depends only on the question

A resumed run asks the model again from where it stopped. A `ScriptedModel` answers by
position in its list, so a new process would need to know how far the script had got.
`FunctionModel` answers with a function of what it is asked (the `Exchange`: the
instructions, messages and tools of one model call), so the same question always gets the
same answer, in any process:

```python
from gvn.harness.messages import TOOL
from gvn.testing.fakes import FunctionModel


def refund_model(exchange: Exchange) -> Reply:
    """Asks to refund A-17; once a tool result is in the conversation, reports."""
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(message=Message.assistant(text="I refunded 40.00 on order A-17."))
    refund = ToolCall(
        call_id="call-1", name="issue_refund", arguments={"order_id": "A-17", "amount": 40.0}
    )
    return Reply(message=Message.assistant(calls=[refund]))
```

## Step 3: a Governor over a SQLite journal

`SqliteJournal(path=...)`, in `gvn.adapters.sqlite`, keeps the journal in a file. It uses only
the standard library, commits every write before returning, and lets several processes share
one file. Each process builds its own Governor around it:

```python
from gvn.adapters.sqlite import SqliteJournal


def new_refund_tool() -> IssueRefund:
    return IssueRefund(ledger=RefundFile(refund_path))


def build_governor(journal: Journal, refund_tool: Tool | None = None) -> Governor:
    tool = refund_tool or new_refund_tool()
    toolbox = Toolbox([tool])
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=FunctionModel(respond=refund_model), toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=RefundPolicy(refund_tool=tool)),
        },
        external=["request_approval"],
        journal=journal,
        output=RecordingOutput(),
        clock=ManualClock(),
        snapshot_every=3,
    )


def new_refund_agent(run_name: str) -> Agent:
    return Agent(
        name=run_name,
        instructions="Help customers with damaged orders.",
        tools=[new_refund_tool()],
    )


BROKEN = Event(name="started", payload={"prompt": "Order A-17 arrived broken. Refund me."})
```

Besides journaling every event, the Governor saves a **snapshot** from time to time: the
agent's whole state as plain JSON (its [Dto](decisions-and-branching.md#step-4-save-the-machine-and-bring-it-back)). `snapshot_every=3` makes it snapshot often, so
that recovery below starts from a snapshot and replays only the few events after it.
`refund_tool` lets step 7 swap in a different tool.

The agent and the Governor each get a tool object built in the same process, never one
carried over from another. That works because the agent stores only the tool's
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity), never the object:
every `IssueRefund` has the same identity, so the tool built by a later process is the same
tool to the recovered agent, and the Governor checks that its toolbox holds it before the
run continues.

## Step 4: end the process while it waits

The first process starts the run. The agent stops at `awaiting_approval`, and the process
ends:

```python
async def process_one() -> None:
    journal = SqliteJournal(path=journal_path)
    agent = new_refund_agent("refund-1")
    result = await build_governor(journal).deliver(actor=agent, event=BROKEN)
    print(result.status(), agent.state().name())  # waiting awaiting_approval
    await journal.close()


asyncio.run(process_one())
```

Nothing is running now. Everything about the run is in `helpdesk.db`:

```python
async def look_inside() -> None:
    journal = SqliteJournal(path=journal_path)
    records = await journal.read("refund-1")
    sequence, saved_state = await journal.latest_snapshot("refund-1")
    await journal.close()
    print([record["event"]["name"] for record in records])
    print("snapshot after", sequence, "events, in state", saved_state["machine"]["state"])


asyncio.run(look_inside())
# ['started', 'model_replied', 'needs_approval']
# snapshot after 3 events, in state awaiting_approval
```

The snapshot is the agent's own Dto: `saved_state["machine"]` is its machine's position,
`saved_state["transcript"]` its conversation.

## Step 5: approve from a new process

Hours later, someone approves. A new process opens the file and rebuilds the agent with
`Recovery(journal=...).recover(run_id=..., actor_class=...)`. Recovery loads the latest snapshot
and replays the journaled events after it through the agent's machine. It does no work and
calls nothing while it replays. The rebuilt agent knows what it is waiting for, so the
approval answers its pending request:

```python
from gvn.runtime.recovery import Recovery


async def process_two() -> Result:
    journal = SqliteJournal(path=journal_path)
    agent = await Recovery(journal=journal).recover(run_id="refund-1", actor_class=Agent)
    print("recovered in", agent.state().name())  # recovered in awaiting_approval
    approval = agent.pending()[0]
    result = await build_governor(journal).answer(
        actor=agent, request=approval, event=Event(name="approved")
    )
    await journal.close()
    return result


result = asyncio.run(process_two())
print(result.outcome().payload()["text"])  # I refunded 40.00 on order A-17.
print(RefundFile(refund_path).refunds())  # [{'order_id': 'A-17', 'amount': 40.0}]
```

The run that started in one process finished in another. The approval could have come days
later; a waiting run costs a few rows in a file.

## Step 6: kill it in the middle of a refund

Now the worst moment: after the money left, but before the tool's result reached the journal.
Start a second run (with a fresh payment file), approve it, and kill the process there.

Counting from 0, the run's journal writes are `started`, `model_replied`, `needs_approval`
(the first call returns there), then `approved` and `tools_returned`.
`CrashingJournal(journal=..., at_append=...)` wraps a real journal and raises `Crash` just before write
number `at`, counting only the writes made through it. In the second call, the write to kill
is number 1, `tools_returned`:

```python
from gvn.testing.fakes import Crash, CrashingJournal

refund_path.unlink()


async def process_three() -> None:
    journal = SqliteJournal(path=journal_path)
    agent = new_refund_agent("refund-2")
    waiting = await build_governor(journal).deliver(actor=agent, event=BROKEN)
    (approval,) = waiting.pending()
    dying = CrashingJournal(journal=journal, at_append=1)  # dies writing tools_returned
    try:
        await build_governor(dying).answer(
            actor=agent, request=approval, event=Event(name="approved")
        )
    except Crash as crash:
        print("killed:", crash)  # killed: crashed before append 1
    await journal.close()


asyncio.run(process_three())
print(RefundFile(refund_path).refunds())  # [{'order_id': 'A-17', 'amount': 40.0}]
```

The refund happened. The journal does not know it. Recover and continue with
`governor.resume(actor=...)`, which carries on from wherever the actor stands:

```python
async def process_four() -> Result:
    journal = SqliteJournal(path=journal_path)
    agent = await Recovery(journal=journal).recover(run_id="refund-2", actor_class=Agent)
    wanted = agent.pending()[0]
    print("recovered in", agent.state().name(), "wanting", wanted.request_id(), wanted.kind().name())
    result = await build_governor(journal).resume(actor=agent)
    await journal.close()
    return result


result = asyncio.run(process_four())
print(RefundFile(refund_path).refunds())
```

```text
recovered in acting wanting refund-2/7 invoke_tools
[{'order_id': 'A-17', 'amount': 40.0}, {'order_id': 'A-17', 'amount': 40.0}]
```

The run finished correctly, and the customer was refunded **twice**. The rebuilt agent was in
`acting` and still wanted its tool calls run, because their result never reached the journal,
so `resume` re-issued them, with the same request id (`refund-2/7`) as before.

Recovery replays recorded results without doing the work again. When you resume, the
Governor reissues work that is still pending, even if its effect happened before the crash.

## Step 7: make the refund safe to repeat

Doing it exactly once needs the cooperation of whoever performs the side effect, and in gvn
that is the tool's author. gvn's contribution is a key that survives the crash. Every tool
call receives one as `invocation.key()` in `run(arguments, invocation)`: `"<request id>#<tool call id>"`.
The re-issued call has the same key as the one that was lost (`refund-2/7#call-1` above), and
every other call has a different one.

`IssueRefundOnce` wraps the refund tool and remembers, in a file that outlives the process,
the keys it has completed and what each returned. It takes its short name and its namespace
from the tool it wraps, so it has the same identity: to the model, the agent and the policy
it is the same refund tool. Asked again under a completed key, it
returns the remembered result and refunds nothing:

```python
class IssueRefundOnce(Tool):
    """The same tool to the model, but each call key is refunded at most once."""

    def __init__(self, inner: Tool, done_path: str | pathlib.Path) -> None:
        self._inner = inner
        self._done = pathlib.Path(done_path)

    def name(self) -> str:
        return self._inner.name()

    def namespace(self) -> str:
        return self._inner.namespace()

    def description(self) -> str:
        return self._inner.description()

    def arguments(self) -> Record:
        return self._inner.arguments()

    def _completed(self) -> dict[str, typing.Any]:
        if not self._done.exists():
            return {}
        return json.loads(self._done.read_text())

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        completed = self._completed()
        if invocation.key() in completed:
            return completed[invocation.key()]
        result = await self._inner.run(arguments, invocation)
        completed[invocation.key()] = result
        self._done.write_text(json.dumps(completed))
        return result
```

Run the same crash again, on a fresh run, with the careful tool:

```python
refund_path.unlink()


def careful_governor(journal: Journal) -> Governor:
    plain = IssueRefund(ledger=RefundFile(refund_path))
    return build_governor(journal, refund_tool=IssueRefundOnce(inner=plain, done_path=done_path))


async def process_five() -> None:
    journal = SqliteJournal(path=journal_path)
    agent = new_refund_agent("refund-3")
    waiting = await careful_governor(journal).deliver(actor=agent, event=BROKEN)
    (approval,) = waiting.pending()
    try:
        await careful_governor(CrashingJournal(journal=journal, at_append=1)).answer(
            actor=agent, request=approval, event=Event(name="approved")
        )
    except Crash:
        pass
    await journal.close()


async def process_six() -> Result:
    journal = SqliteJournal(path=journal_path)
    agent = await Recovery(journal=journal).recover(run_id="refund-3", actor_class=Agent)
    result = await careful_governor(journal).resume(actor=agent)
    await journal.close()
    return result


asyncio.run(process_five())
result = asyncio.run(process_six())
print(result.outcome().payload()["text"])  # I refunded 40.00 on order A-17.
print(RefundFile(refund_path).refunds())  # [{'order_id': 'A-17', 'amount': 40.0}]
print(list(json.loads(done_path.read_text())))  # ['refund-3/7#call-1']
```

The resumed run called the tool again with the same key, and the tool refunded nothing the
second time. The model was told the refund was made, which is the truth.

!!! warning "Pass the key to the service that acts"
    `done.json` recognises a repeat once the key is written. A process that dies between the
    refund and that write repeats the refund, so the strongest place for the key is the
    system that performs the side effect: when a payment service accepts an idempotency key
    (a key you send with a request so that the service carries out a repeat of it only once),
    pass `invocation.key()` on to it instead of (or as well as) remembering it. gvn supplies a
    stable key; the tool's author uses it to make the effect happen once.

## Step 8: name the run after the job

Every run so far had a name you typed: `refund-1`, `refund-2`. A real script is started many
times, by a queue, a web request or a restart, and must find the same run each time. Three
rules do that:

1. **Derive the run's name from the job.** A ticket has an id; the run that handles it is
   named after that id. Any process that is given the ticket then knows the run's name.
2. **Recover first.** `Recovery.recover` raises `UnknownRun` when the journal holds nothing
   for that name, and returns the rebuilt agent otherwise.
3. **Start only when the run is unknown.** Build a fresh agent and deliver `started` in the
   `except UnknownRun` branch, and nowhere else.

```python
from gvn.runtime.recovery import UnknownRun


async def handle_ticket(ticket_id: str) -> str:
    run_name = f"refund-ticket-{ticket_id}"
    journal = SqliteJournal(path=journal_path)
    governor = careful_governor(journal)
    try:
        agent = await Recovery(journal=journal).recover(run_id=run_name, actor_class=Agent)
        result = await governor.resume(actor=agent)
        how = "recovered"
    except UnknownRun:
        agent = new_refund_agent(run_name)
        result = await governor.deliver(actor=agent, event=BROKEN)
        how = "started"
    await journal.close()
    return f"{how} {run_name}: {result.status()} in {agent.state().name()}"


print(asyncio.run(handle_ticket("4711")))
print(asyncio.run(handle_ticket("4711")))
```

```text
started refund-ticket-4711: waiting in awaiting_approval
recovered refund-ticket-4711: waiting in awaiting_approval
```

The first call found no such run and started it. The second call, which stands for the same
script run again later, found the run and continued it: `resume` carried on from where the
agent stood, which here is still waiting for a person. Whatever happened to the process in
between, the script is the same.

A journal can also tell you which runs it holds. `journal.runs()` returns their names, in
order:

```python
async def list_runs() -> tuple[str, ...]:
    journal = SqliteJournal(path=journal_path)
    names = await journal.runs()
    await journal.close()
    return names


print(asyncio.run(list_runs()))
# ('refund-1', 'refund-2', 'refund-3', 'refund-ticket-4711')
```

For a journal with many runs, `runs(after=..., limit=...)` returns them a page at a time:
pass the last name of one page as `after` to get the next.

## Change it and run again

Predict the answer first, then run the code and open the block.

**1. Crash one write earlier.** Steps 6 and 7 killed the process at write 1, `tools_returned`. Kill
it at write 0 instead, the write of `approved` itself. After recovery, which state is the
agent in, what does it want, and how many refunds were made?

```python
refund_path.unlink()


async def process_seven() -> None:
    journal = SqliteJournal(path=journal_path)
    agent = new_refund_agent("refund-4")
    waiting = await careful_governor(journal).deliver(actor=agent, event=BROKEN)
    (approval,) = waiting.pending()
    try:
        await careful_governor(CrashingJournal(journal=journal, at_append=0)).answer(
            actor=agent, request=approval, event=Event(name="approved")
        )
    except Crash as crash:
        print("killed:", crash)
    await journal.close()


async def process_eight() -> None:
    journal = SqliteJournal(path=journal_path)
    agent = await Recovery(journal=journal).recover(run_id="refund-4", actor_class=Agent)
    wanted = agent.pending()[0]
    print("recovered in", agent.state().name(), "wanting", wanted.request_id(), wanted.kind().name())
    result = await careful_governor(journal).resume(actor=agent)
    print(result.status(), [request.kind().name() for request in result.pending()])
    await journal.close()


asyncio.run(process_seven())
asyncio.run(process_eight())
print(RefundFile(refund_path).refunds())
```

??? note "What happens"

    ```text
    killed: crashed before append 0
    recovered in awaiting_approval wanting refund-4/6 request_approval
    waiting ['request_approval']
    []
    ```

    The approval never reached the journal, so for the run it never happened. The
    recovered agent is still waiting for a person, `resume` has nothing to do but wait, and
    no money moved: an event is written before any work it calls for starts. The person
    answers again, with `governor.answer`, as in step 5.

**2. Use the plain tool in the script of step 8.** In step 6, `build_governor` (the tool
that does not remember keys) refunded twice. If `handle_ticket` used `build_governor`
instead of `careful_governor`, and the process died at `tools_returned`, what would the
next `handle_ticket` for that ticket do?

??? note "What happens"

    The same as `process_four` in step 6: it recovers the agent in `acting`, `resume`
    re-issues the tool call under the same key, and the plain tool refunds a second time.
    The recover-first script finds the right run; it is the tool that makes the repeat
    harmless.

## Recap

- The journal is the run. A process can end at any time, while waiting or while working, and
  another process continues from the file.
- `Recovery(journal=...).recover(run_id=..., actor_class=...)` rebuilds an actor from its latest
  snapshot plus the events after it, without doing any work. `governor.answer(...)` delivers
  an answer it was waiting for; `governor.resume(actor=...)` re-issues whatever it still
  wanted.
- Resuming a pending tool request may repeat the effect. Every tool call receives a key
  that is stable across that repeat. A tool with side effects uses it to deduplicate the effect.
- A run begins with one write that saves the agent as it was born together with its first
  event, so a process that died before it left no trace: `Recovery` raises `UnknownRun`.
- In a script, derive the run's name from the job, recover first, and start the run only
  when it is unknown. `journal.runs()` lists the runs a journal holds.
- The [Governor](../concepts/governor.md) page explains journaling and snapshots in full.
  You will meet two more uses of this page later: [tutorial 8](workflow.md) recovers a run
  of several agents the same way, and [tutorial 11](testing.md) tests a crash at every
  journal write, not just the one you picked.

**Practice:** two recipes do this page's work in a single file each. The
[standalone SQLite recipe](../recipes.md#park-and-recover-with-sqlite) parks and recovers an
actor in a fresh workspace, and
[agent approval across a restart](../recipes.md#agent-approval-across-a-restart) does it for
an agent that waits for a person.

**Next:** [7. Streaming and seeing what happened](streaming.md) shows the run while it
happens, and reads it back afterwards.
