# The Governor

**What you will learn:** how gvn actually runs an actor: who does the work it asks for, how
every step is written down so a crash loses nothing, and how you start, answer and resume a
run.

**Read first:** [the big picture](index.md), [Actors and events](actors-and-events.md) and
[The reference agent](reference-agent.md). **Time:** about 25 minutes for the first half; the
deeper sections are reference you can come back to.

## Where the Governor sits

In the [loop that runs](index.md#picture-1-the-loop-that-runs), the Governor is the box in
the middle: every event goes into it, every request comes out of it, and it alone talks to
the fulfillers, the journal and the outside world. In the
[layers of code](index.md#picture-2-the-layers-of-code) it lives in the **runtime** layer,
above the kernel and the harness, which never do any work themselves.

```mermaid
flowchart LR
    actor["Actor<br/>(harness): decides"]
    governor["Governor<br/>(runtime): drives"]
    fulfillers["Fulfillers<br/>do one kind of work each"]
    journal[("Journal")]
    output["Output<br/>watchers"]
    clock["Clock"]
    governor -- "event" --> actor
    actor -- "requests" --> governor
    governor -- "request" --> fulfillers
    fulfillers -- "result event" --> governor
    governor -- "records" --> journal
    governor -- "reports" --> output
    governor -- "asks the time" --> clock
```

## The shape of it

- **What it does:** takes one event, hands it to the actor, writes it to the journal, starts
  the work the actor now wants, and feeds each result back as the next event, until the
  actor finishes or must wait for someone outside.
- **What you give it:** four parts you choose and inject: fulfillers, a journal, an output
  and a clock.
- **How you use it:** `deliver` an event to start or continue a run, `answer` a request a
  person was asked, and after a crash rebuild the actor with `Recovery` and `resume` it.
- **What it promises:** nothing that was journaled is lost, and work that was in flight
  during a crash runs again, at least once.

The first half of this page builds that up step by step; the deeper sections, after it, are
detail and edge cases.

## The problem: someone has to do the work

An [actor](actors-and-events.md) only decides. It takes an event, changes state, and says
which work it wants next as requests: "call the model", "run these tools", "ask a person".
It never does any of that work itself. That keeps it small and testable, but something still
has to call the model, run the tools, remember what happened, and tell you about it.

That something is the `Governor` (in `gvn.runtime.governor`), the runtime. It drives
actors: it hands them events, does the work they request, writes everything down, and
reports what happens. It is the only part of gvn that does I/O (talking to the network, the
disk, the clock), and it does all of it through objects you inject. Swap those objects and
the same agent runs against a real model, a fake one, a database or memory.

Picture one run of a small `helper` agent asked to "look it up":

1. You deliver `started`. The agent wants the model.
2. The Governor asks the model. The model asks for the `search` tool.
3. The agent wants its tool policy consulted. The policy clears the call.
4. The Governor runs `search`. The agent wants the model again.
5. The model answers "Three hits." The agent is finished.

The Governor did every step in that list except the deciding.

## Four things the Governor needs

You build a Governor from four injected parts. Each is a plain idea:

Each part is reached through a **port**: an interface (an abstract base class, or ABC) that
gvn defines and that any implementation can fill, so the Governor never knows whether it is
talking to a real database or a fake in memory.

- **Fulfillers.** A **fulfiller** is the object that does one kind of work: one fulfiller
  calls the model, another runs tools, another asks the tool policy. You hand the Governor
  a mapping from request kind (`"invoke_model"`, `"invoke_tools"`, ...) to the fulfiller
  for it.
- **A journal.** The **journal** is an append-only log, one per run, of every event the
  actor handled, in order. The actor handles the event in memory first; the Governor
  then writes it *before* starting the resulting work. After a crash, recovery rebuilds
  the actor from the durable history. (The journal also holds snapshots, covered below.)
- **An output.** The **output** receives a stream of **signals**, small records (the class
  `Signal`) describing what happens:
  events, requests, model text as it arrives. Logging, tracing and live streaming are all
  outputs ([Streaming and observability](streaming-and-observability.md) covers them).
- **A clock.** The **clock** gives the time for records and signals, and lets a run wait
  for a deadline (the [Time](time.md) page, later, covers waiting).

In tests you use fakes for all four, from `gvn.testing.fakes`. That is what this page does.

### One request crosses the boundary

The actor owns the decision; a fulfiller owns the work. Neither needs to know the other's
implementation. The Governor connects them through `Event`, `Request`, `Actor` and
`Fulfiller` interfaces. For a model request, that conversation looks like this:

```mermaid
sequenceDiagram
    participant G as Governor
    participant A as Actor
    participant J as Journal port
    participant F as ModelFulfiller
    participant M as Model port
    G->>A: handle(started)
    A-->>G: Reaction
    G->>J: append(started)
    J-->>G: durable
    Note over G,J: Save a snapshot too, if due
    G->>A: pending()
    A-->>G: invoke_model Request
    G->>F: fulfil(request, progress)
    F->>M: generate(exchange, progress)
    M-->>F: Reply
    F-->>G: model_replied Event
    G->>A: handle(model_replied)
    A-->>G: Reaction
    G->>J: append(model_replied)
    J-->>G: durable
```

Read it with the names from [Actors and events](actors-and-events.md): `handle` gives the
actor an event and returns a `Reaction` (what that event changed), and `pending()` lists the
requests the actor wants now. `fulfil(request, progress)` is the one method of a fulfiller;
`progress` is where it reports partial results, such as model text as it arrives. The
`ModelFulfiller` packs the agent's instructions, messages and tools into an `Exchange` and
passes it to the `Model` port's `generate`.

This shows one request; several wanted requests may run concurrently. The initial
**snapshot** (a saved copy of the whole actor, covered [below](#deeper-snapshots-and-journals))
and the output signals are omitted. Each port is an injected object: a real adapter or a fake
can answer the same calls. The actor never calls a model or journal itself.

## Step 1: the fulfillers

Start with the work the `helper` agent will ask for. A scripted model stands in for a real
one: it replays the replies you give it. A stub tool stands in for search. A policy that
clears everything stands in for real rules.

```python
import asyncio
import typing

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.testing.fakes import ScriptedModel, StubTool


class Allow(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("cleared")


search = StubTool(name="search", arguments=Record({"query": Text()}), result={"hits": 3})
toolbox = Toolbox(tools=[search])
model = ScriptedModel(
    script=[
        Reply(message=Message.assistant(
            calls=[ToolCall(call_id="call-1", name="search", arguments={"query": "moore"})]
        )),
        Reply(message=Message.assistant(text="Three hits.")),
    ]
)
fulfillers = {
    "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
    "invoke_tools": ToolFulfiller(toolbox=toolbox),
    "consult_policy": PolicyFulfiller(decision=Allow()),
}
```

The names in that block, briefly. `ScriptedModel` and `StubTool` are fakes from
`gvn.testing.fakes`, as in the [quickstart](../quickstart.md): the first returns the replies
in its `script` in order, the second records each call and returns its fixed `result`.
`Reply`, `Message` and `ToolCall` are the shapes a model's answer arrives in. `Record` and
`Text` (from `gvn.kernel.schema`) declare the tool's argument shape, a
[schema](durable-objects.md#deeper-schemas). `Toolbox` holds the tool objects the runtime
runs, found by each tool's **identity** (its namespace, a dot and its short name:
`gvn.testing.fakes.search` for this stub; [Tools](tools.md) explains the two names), and `Allow`
is a [Decision](decisions.md) over the agent's `VERDICTS`, the tool policy of
[the reference agent](reference-agent.md).

Three fulfillers ship with gvn for the reference agent, and this is all of them:
`ModelFulfiller` calls the model, `ToolFulfiller` runs tools, and `PolicyFulfiller` asks your
policy. Each one is registered under the request kind it answers.

## Step 2: the Governor

Now the other three parts, and the Governor itself:

```python
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput

journal = MemoryJournal()
governor = Governor(
    fulfillers=fulfillers,
    external=["request_approval"],
    journal=journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)
```

The three fakes stand in for the other ports: `MemoryJournal` keeps the journal in memory,
`RecordingOutput` keeps every signal in a list, and `ManualClock` is a clock whose time moves
only when a test tells it to.

`external` lists request kinds that no fulfiller answers, because the answer comes from
outside: here, a person approving a tool call. A kind may not be both fulfilled and external.

If an actor requests a kind that is neither, the call raises `Unfulfillable`, naming the
kind, the actor that asked and the run: unanswerable work is an error, not a silent wait.
The same error comes earlier for an actor the fulfillers cannot serve: before an actor
handles anything, the Governor asks each fulfiller whether it can, and the model and tool
fulfillers answer with the tools (by identity) their toolbox does not hold. So an agent
offered a tool the toolbox lacks is refused before anything is journaled
([checked before the run starts](tools.md#checked-before-the-run-starts)).
`read_clock` and `wake_at`, the request kinds an actor uses to ask for the time and to be
woken at a time, need no entry: the Governor handles them itself (see [Time](time.md), later)
unless you name them.

## Step 3: deliver an event and read the result

`deliver(actor=..., event=...)` hands over one event and drives the actor until it finishes
or must wait. It returns a `Result`.

```python
from gvn.harness.events import Event

helper = Agent(name="helper", instructions="Be brief.", tools=[search])
result = asyncio.run(
    governor.deliver(actor=helper, event=Event(name="started", payload={"prompt": "Look it up."}))
)
print(result.status())
print(result.outcome().payload()["text"])
print(result.pending(), result.rejected())
```

```text
finished
Three hits.
() False
```

`status()` is `FINISHED` or `WAITING` (constants in `gvn.runtime.governor`). The outcome is
the agent's own ([the reference agent](reference-agent.md#outcomes) lists what it holds).
`pending()` lists the external requests a waiting run waits on; it is empty here because the
run finished. `rejected()` is `True` if the delivered event was rejected by the actor.

## What happened inside: the loop

For each call, the Governor runs this loop:

1. Hand the event to the actor. The actor changes state and returns a reaction.
2. Append the event to the journal (write-ahead: the record is durable before starting work
   requested by the new state). Take a snapshot if one is due.
3. Look at `actor.pending()`. Start every wanted request that has a fulfiller, concurrently,
   one task per request. Cancel any work in flight whose request is no longer wanted.
4. Wait for a task to finish. Its result is an event, addressed to the request's origin. Go
   to 1 with that event.
5. Stop when the actor is finished, or when nothing is in flight. A run with no work in
   flight that is not finished is **waiting**: the call returns, and the run holds no
   process until someone delivers the next event.

Step 5 is why a run can wait for a person for a week without a process sitting idle: the
call simply returns `WAITING`, and the journal remembers the rest.

## Step 4: read the journal

Every event the actor handled is in the journal, in order, under the actor's name. That
includes the events fulfillers produced, and events the actor rejected (they were
delivered, so they are recorded; replay rejects them again).

```python
async def show_journal() -> None:
    for record in await journal.read("helper"):
        print(record["sequence"], record["event"]["name"])


asyncio.run(show_journal())
```

```text
0 started
1 model_replied
2 cleared
3 tools_returned
4 model_replied
```

That is the five-step picture from the top of this page, written down. Each record is
`{"form": 3, "sequence": n, "at": <clock time>, "event": <Event.Dto plain>}`. The `form` is
the version of the stored shape, so a later gvn can tell old records from new ones and
upgrade them ([Stability](../reference/stability.md)).

## Step 5: recover after a crash

Because the journal holds every event, an actor can be rebuilt after its process died.
`Recovery` (in `gvn.runtime.recovery`) does the rebuilding. Its call
`Recovery(journal=...).recover(run_id=..., actor_class=...)`, where the run id is the actor's
name, loads the latest snapshot of the run with `actor_class.from_dto` (see
[Durable objects](durable-objects.md)), then replays every later record through `handle`.
Replaying fulfils no work and emits nothing. Then `governor.resume(actor=...)` continues the
run.

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

rebuilt = asyncio.run(Recovery(journal=journal).recover(run_id="helper", actor_class=Agent))
print(rebuilt.state(), rebuilt.to_dto() == helper.to_dto())
```

```text
State('completed') True
```

The rebuilt agent is identical to the one that ran. Recovery raises `UnknownRun` if the
journal has no record of the run: a run exists in the journal only once its opening record
does, so a process that died before writing it left nothing, and the caller starts the run
again under the same name. A complete kill-and-resume program is in
[tutorial 6, Crash and resume](../tutorials/durability.md).

That is the 80% you need: fulfillers do the work, the journal remembers it, `deliver` starts
a run, and `Recovery` plus `resume` bring one back. The rest of this page is detail you can
come back to.

## Deeper: every constructor argument

| Argument | What it is |
|---|---|
| `fulfillers` | a mapping from request kind to the `Fulfiller` that does that work |
| `external` | request kinds answered from outside, by a person or another system |
| `journal` | the `Journal` port: an append-only record per run, plus snapshots |
| `output` | the `Output` port: receives every `Signal` |
| `clock` | the `Clock` port: timestamps for records and signals |
| `snapshot_every` | the fewest journaled events between snapshots (default 20) |
| `snapshot_growth` | how the spacing grows with the run (default 0.5; 0 for a fixed spacing); see [Snapshots](#deeper-snapshots-and-journals) |
| `sleep_within` | how far ahead, in seconds, the Governor sleeps on a wake-up when nothing else is running, instead of letting the run park (default 60); see [Time](time.md) |
| `allowance` | `None` (the default: nothing is tallied) or a `gvn.runtime.spending.Allowance`: what each run driven here may spend on model calls. A run that has reached it is handed `interrupted` instead of starting more work; see [Spending and rate limits](../guides/spending-and-rate-limits.md) |
| `entitlement` | `None` (the default: anyone may answer) or a [Decision](decisions.md) whose outcomes are `gvn.harness.answering.ENTITLEMENTS`: who may answer a waiting request; see [answering a request](#deeper-waiting-answering-and-resuming) and [Trust](trust.md#part-2-who-answered) |

The ports in that table, and the `Model` port the `ModelFulfiller` uses, are the
interfaces described [at the top of the page](#four-things-the-governor-needs): `Journal`,
`Output`, `Clock`, `Model`, all in `gvn.harness.ports`.

## Deeper: what each fulfiller does

A `Fulfiller` is an ABC with one method, `async fulfil(request, progress)`, that does the
work for one kind of request and returns the `Event` describing the result. Expected
failures are reported as events, not raised.

- `ModelFulfiller(model=..., toolbox=...)` fulfils `invoke_model`. It builds an `Exchange`
  (the instructions, the messages and the tool specs), calls the `Model` port, streams text
  fragments to `progress`, and returns `model_replied` with the reply and the tokens it
  used, `"usage": {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"}` (`input_tokens` counts every
  input token, cached or not; the two cache figures are parts of it; see
  [usage](../guides/vendors.md#what-a-call-cost-usage)). A `ModelFailure` becomes
  `model_failed`.
- `ToolFulfiller(toolbox=...)` fulfils `invoke_tools`: it runs the calls of one model reply
  **in the order the model gave them** (below), each with the toolbox's tool of the
  identity the request gives for it, and returns `tools_returned`. A call fails, without
  stopping the later ones, when the toolbox holds no tool of that identity, its arguments do not satisfy
  the tool's schema, the tool raises, or it returns something that is not plain JSON. A
  call the request marks refused does not run, and nor do the later calls that are not
  independent ([below](#after-a-refused-call)).
- `PolicyFulfiller(decision=...)` fulfils `consult_policy` by asking your
  [Decision](decisions.md), whose outcomes must be exactly `VERDICTS`, about each call of the
  reply on its own (see [one verdict per call](reference-agent.md#one-verdict-per-call)).
  When every call gets the same verdict it answers that symbol with no payload; otherwise
  the route, carrying `{"verdicts": [...]}`.

A `Fulfiller` of your own receives the whole `Request`, and can use `request.request_id()` the same
way the tool key is used [below](#at-least-once-and-request-ids).

## Deeper: the order of a reply's tool calls {#the-order-of-a-replys-tool-calls}

A model often puts calls that depend on each other in one reply: edit a file, then run the
tests. So the calls run one at a time, each starting only after the one before it has
finished, in the order the model gave them. The exception is a run of **neighbouring** calls
whose tools all say `independent()` is `True` (pure reads, which neither depend on nor
affect another call): they run together, as one step of that order. `independent()` is
`False` unless a tool overrides it, and a call to a tool the toolbox does not hold is
never independent, so it splits a run. Results always come back in call order.

To see it, here is a tool that records when it starts and ends, and lets other work run in
between:

```python
from gvn.harness.tools import Invocation, Tool


class LoggedStep(Tool):
    """Records when it starts and ends, and lets the event loop run in between."""

    def __init__(self, name: str, log: list[str], independent: bool = False) -> None:
        self._name, self._log, self._independent = name, log, independent

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

    def description(self) -> str:
        return "A step that records itself."

    def arguments(self) -> Record:
        return Record({})

    def independent(self) -> bool:
        return self._independent

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        self._log.append(f"start {self._name}")
        await asyncio.sleep(0)
        self._log.append(f"end {self._name}")
        return {}
```

Two independent reads, then an edit and a test, all in one reply. The fulfiller is called
directly with a hand-made `Request`, whose payload holds the calls and, one per call, the
identity of its tool; `Quiet` (in `gvn.harness.ports`) is a `Progress` that discards what it
is given, for calling a fulfiller or a model directly when nobody is listening.

```python
from gvn.harness.events import Request
from gvn.harness.ports import Quiet

log = []
read_a = LoggedStep(name="read_a", log=log, independent=True)
read_b = LoggedStep(name="read_b", log=log, independent=True)
edit = LoggedStep(name="edit", log=log)
test = LoggedStep(name="test", log=log)
steps = Toolbox(tools=[read_a, read_b, edit, test])


def invoke_payload(call_id: str, *tools: Tool) -> dict[str, typing.Any]:
    """An invoke_tools payload calling each tool once, with no arguments."""
    calls = [
        ToolCall(call_id=f"{call_id}{number}", name=tool.name(), arguments={})
        for number, tool in enumerate(tools)
    ]
    return {
        "calls": [call.to_dto().to_plain() for call in calls],
        "identities": [tool.identity() for tool in tools],
    }


request = Request(
    request_id="helper/7",
    kind="invoke_tools",
    payload=invoke_payload("c", read_a, read_b, edit, test),
)
asyncio.run(ToolFulfiller(toolbox=steps).fulfil(request, Quiet()))
for entry in log:
    print(entry)
```

```text
start read_a
start read_b
end read_a
end read_b
start edit
end edit
start test
end test
```

The two reads ran together; the edit waited for them, and the test waited for the edit.

### After a refused call

Order also decides what happens after a call is refused. An `invoke_tools` request may mark
some calls as refused (the policy forbade them, or a person denied them; see
[one verdict per call](reference-agent.md#one-verdict-per-call)). A refused call never runs.
Every **later** call whose tool is not independent is not run either, because it may depend
on the refused one: its result says it was skipped. Independent calls still run, and calls
before the first refusal run as usual. Every call gets a result, in call order.

Here the edit is denied; the read after it still runs, and the test after it is skipped:

```python
log.clear()
denied_edit = {"status": "denied", "reason": "not now"}
request = Request(
    request_id="helper/9",
    kind="invoke_tools",
    payload={**invoke_payload("c", edit, read_a, test), "refused": [denied_edit, None, None]},
)
returned = asyncio.run(ToolFulfiller(toolbox=steps).fulfil(request, Quiet()))
for result in returned.payload()["results"]:
    print(result["call_id"], result["failed"], result["content"])
print(log)
```

```text
c0 True not run: approval was denied: not now
c1 False {}
c2 True not run: an earlier call in this reply was refused
['start read_a', 'end read_a']
```

The agent turns these results into the statuses `denied`, `ok` and `skipped`. This rule
assumes order means dependence, so it may skip a call that would have been harmless.

## Deeper: waiting, answering and resuming

`resume(actor=...)` drives an actor without a new event, for an actor that was rebuilt or
simply kept in memory. Like `deliver`, it returns a `Result`.

A waiting result lists the external requests the actor is waiting on in `pending()`, and
`due()` is the earliest time of a parked wake-up among them (or `None`): when a scheduler
should call `wake(actor)`, which answers every wake-up that is due and drives on. See
[Time](time.md).

**Answering a request.** `answer(actor=..., request=..., event=...)` delivers an outside
answer to one of those requests. It checks that `request` is among `actor.pending()` and of
an external kind, that `event` is unaddressed or addressed to `request.origin()`, and that
the request's kind admits the event (a `request_approval` admits `approved` and `denied`, a
`request_input` `answered` and `withdrawn`; `gvn.harness.events.ANSWERS` lists them);
otherwise it raises `ValueError` and nothing is journaled. It then addresses the event to the
request's origin and handles it exactly as `deliver` would. Use it whenever an answer
belongs to a request (an approval, a person's reply): in a workflow it reaches the child
that asked. `deliver` stays for unsolicited events, such as the one that starts a run.

**Who answered.** `answer(..., by=principal)` takes a `gvn.harness.events.Principal`: who
gave the answer, as the deployment's entry point (the web handler or chat integration that
received it) authenticated and vouches for. The event is journaled, signalled and handed to
the actor stamped with it (`event.by()`); `by=None` names nobody. Only `answer` says who
answered: an event that already carries a principal is a `ValueError` from `answer` and
from `deliver`. A Governor built with `entitlement=` asks that rule about each answer after
every check above and before anything is driven (answers to its own wake-ups excepted);
when it answers `not_entitled`, `answer` raises `NotEntitled` (from `gvn.harness.answering`),
nothing is journaled or signalled, and the run still waits. [Trust](trust.md#part-2-who-answered)
covers the principal, writing a rule, and where the principal is kept.

A wake-up that is already due is applied first, so an answer that comes after its stage's
deadline is refused as no longer pending. That refusal is `TooLate` (a `ValueError`, imported
from `gvn.harness`), and it
is the one refusal that leaves the journal changed: the deadline had passed before the
answer arrived, so the run is driven on from its `woke` exactly as `wake` would drive it,
those events stand, and `error.result()` carries the `Result` of that drive.

The Governor holds each actor by name while it drives it. Delivering to an actor it is
already driving raises `Busy`.

**One driver per run.** Every record names the place it is written to. The opening record
uses `begin`, and later records use `append(..., position=n)`. Two writers that race for
the same position cannot both write it. The loser gets `PositionTaken` before starting
work requested by that event. Its actor already handled the event that the journal refused,
so discard that actor and
recover the run from the journal.

## Deeper: snapshots and journals

**Snapshots.** A **snapshot** is a saved copy of the whole actor, so recovery does not have
to replay a long run from its first event. A run begins with one atomic write,
`Journal.begin`, that saves the actor as it is, its birth snapshot, together with the run's
opening record. There is never a birth snapshot without an opening record. After a snapshot taken when the run had `n`
journaled events, the next is due once `max(snapshot_every, ceil(n * snapshot_growth))`
more events have been journaled. With the defaults (20 and 0.5) that is at 20, 40, 60, 90,
135, 203, ... events. A snapshot holds the whole actor, so a fixed spacing would make a long
run's snapshot work grow with the square of its length; growing the spacing keeps it
linear. The trade-off is in recovery, which replays the records after the latest snapshot:
at most about a third of the run with the default growth (`snapshot_growth / (1 +
snapshot_growth)` in general). `snapshot_growth=0` gives a snapshot every `snapshot_every`
events. A snapshot is `actor.to_dto().to_plain()` plus its `"form"`, taken right after the event it follows
was journaled, so the latest snapshot plus the records after it always reproduce the actor.

**Journals.** gvn ships three journals: `MemoryJournal` (in `gvn.testing.fakes`),
`SqliteJournal` (in `gvn.adapters.sqlite`, standard library only) and `PostgresJournal` (in
`gvn.adapters.postgres`, the `postgres` extra). All three pass the same contract suite. To
store runs elsewhere, implement the eight methods of `gvn.harness.ports.Journal` (`begin`, `append`,
`read`, `length`, `runs`, `save_snapshot`, `latest_snapshot` and `first_snapshot`) and run
`gvn.testing.contracts.JournalContract`, a ready-made set of tests every journal must pass,
against your class ([Testing your harness](testing.md#contract-suites)). `runs(after=None,
limit=None)` lists the ids of the runs a journal holds, in code point order and in pages, which
is how a tool finds every run without knowing their names
([Inspecting a run](../guides/inspecting-a-run.md#step-1-record-a-run)).

**Leases.** `deliver`, `answer`, `resume` and `wake` also take `lease=`: a
[lease](../reference/glossary.md#lease) (`gvn.harness.ports.Lease`) is the right to drive that
run, held by one process at a time and taken from a lease store that shares the
journal's storage (`MemoryLeases`, `SqliteLeases`, `PostgresLeases`). With a lease, every
write of the call is *fenced*: the journal refuses it, with `LeaseLost`, once another
process has taken the run over. The Governor does not take or renew leases itself;
[Running as a service](../guides/running-as-a-service.md) shows who does, and why the fence
matters.

## Deeper: at-least-once and request ids {#at-least-once-and-request-ids}

What exactly happens to work that was in flight when the process died?

- Recovery applies recorded result events to the actor without running those requests again.
- If a request is still pending after recovery, `resume` can reissue it **with the same
  request ID**. Its effect may already have happened before the process died.

This is **at-least-once** delivery for work that remains pending. Applying an effect once
requires cooperation from the tool or service that performs it.
gvn's part is a key that survives the crash: `ToolFulfiller` runs each tool as
`run(arguments, invocation)`, where `invocation.key()` is `"<request id>#<tool call id>"`. The request id
is deterministic (`"<actor name>/<step count>"`), so a re-issued call gets the same key as
before the crash, and every other call gets a different one.

A tool with a side effect uses the key to make a repeat harmless: it passes the key to the
service it calls as that service's
[idempotency key](../reference/glossary.md#idempotency-key) (a key a service uses to recognise
a repeated request and not repeat its effect), or it remembers the keys it has
completed. Here is the second kind. A plain dict stands in for a store that outlives the
process, and a list for the outside world:

```python
class Notify(Tool):
    def __init__(self, outbox: list[str], done: dict[str, typing.Any]) -> None:
        self._outbox = outbox  # the outside world
        self._done = done  # key -> result, kept where it survives the process

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

    def description(self) -> str:
        return "Send a notification."

    def arguments(self) -> Record:
        return Record({"text": Text()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        key = invocation.key()
        if key in self._done:
            return self._done[key]
        self._outbox.append(arguments["text"])  # the side effect
        self._done[key] = {"sent": True}
        return self._done[key]
```

Fulfilling the same request twice, as `resume` would after a crash, sends once:

```python
outbox, done = [], {}
notify = Notify(outbox=outbox, done=done)
notifier = ToolFulfiller(toolbox=Toolbox(tools=[notify]))
notify_call = ToolCall(call_id="call-9", name="notify", arguments={"text": "hello"})
notify_request = Request(
    request_id="helper/5",
    kind="invoke_tools",
    payload={"calls": [notify_call.to_dto().to_plain()], "identities": [notify.identity()]},
)


async def fulfil_twice() -> bool:
    first = await notifier.fulfil(notify_request, Quiet())
    second = await notifier.fulfil(notify_request, Quiet())
    return first == second


print(asyncio.run(fulfil_twice()), outbox, list(done))
```

```text
True ['hello'] ['helper/5#call-9']
```

What to do with the key. Request ids, and so keys, are unique within a run, and a run is
identified by its actor's name: give two runs different names in one journal, and when a key
store is shared by several journals, add something that tells them apart. A tool that
remembers keys itself repeats the work if the process dies between the side effect and the
write of the key; passing the key on to the system that performs the side effect closes that
gap, which is why it is the stronger choice. The tool's author owns idempotency: gvn supplies
the key, and the tool or the service it calls uses it. ([Run context](run-context.md#idempotency-keys)
covers what the key covers across an interrupt and resume.)

## Deeper: interruption

`governor.interrupt(name)` interrupts an actor the Governor is driving. It cancels and
awaits all work in flight and delivers an `interrupted` event in its place. It returns
`False` if the actor is not being driven; deliver `Event(name="interrupted")` yourself in
that case. See [Humans and interruption](human-in-the-loop.md).

## Deeper: other guarantees

- **No work outlives the call that started it.** On any way out (finished, waiting, an
  error, outside cancellation) the remaining tasks are cancelled and awaited. A cancelled
  call may already have affected an external service.
- **Results of work no longer wanted are discarded.** If a [workflow](workflows.md) stage
  that runs several children at once (a fan-out) ends early because enough of them are done,
  the dropped children's requests disappear and their work is cancelled.
- **Output errors are counted.** The Governor catches exceptions from `Output.emit()`
  that derive from `Exception`, and `governor.output_errors()` reports how many.

## Deeper: the system clock

`ManualClock` (in `gvn.testing.fakes`) is for tests. For real runs, use `SystemClock` from
`gvn.adapters.clock`: `now()` is the system time in seconds since the epoch and never goes
backwards (if the system clock is stepped back, it holds its last reading until the system
clock catches up), and `sleep` awaits `asyncio.sleep`.

```python
from gvn.adapters.clock import SystemClock

clock = SystemClock()
first, second = clock.now(), clock.now()
print(isinstance(first, float), second >= first)

production = Governor(
    fulfillers={"invoke_tools": ToolFulfiller(toolbox=toolbox)},
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=clock,
)
```

```text
True True
```

A clock of your own implements the two methods of `gvn.harness.ports.Clock`; check it with
`gvn.testing.contracts.ClockContract`, as described in [Testing your harness](testing.md).

## Recap

- The Governor is the runtime: it hands events to an actor and does the work the actor asks
  for. It is the only part of gvn that does I/O.
- It is built from fulfillers (one per kind of work), a journal, an output and a clock, all
  injected.
- `deliver` starts or continues a run; `answer` delivers an outside answer to a pending
  request, with `by=` saying who gave it; `resume` drives a rebuilt actor on. Each returns a `Result` that is finished or
  waiting.
- The journal records each handled event before its resulting work starts, so `Recovery` can rebuild an
  actor exactly.
- Work is delivered at least once. Tools with side effects use `invocation.key()` to make a repeat
  harmless.

**Next:** [Run context](run-context.md), the trusted facts about one run that tools and the
policy can check.
