# Running gvn as a service

This guide takes a harness (the program around a model: its agents, tools and policy) from
one Python process to a service of several: an API process that starts and answers runs,
and worker processes that wake them. At the end you have runs
that any process can pick up, that exactly one process drives at a time, and that another
process finishes when the one driving them dies.

In the [big picture](../quickstart.md#the-big-picture) of gvn, one **governor** drives a
run and writes every event of it to the **journal**. In the tutorials both live in one
Python process. In a long-lived service they run in several processes at once: the journal
becomes shared storage, and the processes need a way to agree on which of them drives each
run.

- **You will be able to:** choose a journal that every process can reach, give each run a single
  owner with a *lease* (a time-limited right to drive one run), say why the journal also
  checks a *fence* (a number that tells a current owner from a stale one) on every write,
  and run a `Worker` (a loop that wakes parked runs) that finds the runs whose time has
  come. Then you kill a process in the middle of a run and watch another one finish it,
  answer a waiting run from the entry point, saying who answered, and write the two entry
  files of a PostgreSQL deployment.
- **Read first:** [6. Crash and resume](../tutorials/durability.md) (journals, snapshots and
  recovery), [9. A deadline](../tutorials/deadline.md) and [Time](../concepts/time.md) (how a
  run parks on a wake-up), and [The Governor](../concepts/governor.md).
- **Time:** about 30 minutes.

## Where this fits

Each process runs the same harness. It has its own governor, but they all share one
database, which holds two things: the journal, and a **lease store** that records who
drives each run and when each parked run is due again.

```mermaid
flowchart LR
    subgraph api ["API process"]
        apiLauncher["Launcher<br/>(a governor inside)"]
    end
    subgraph worker ["Worker process"]
        workerLoop["Worker loop"] --> workerLauncher["Launcher<br/>(a governor inside)"]
    end
    subgraph database ["One shared database"]
        journal[("Journal<br/>every event of every run")]
        leases[("Lease store<br/>owner, fence, next due time")]
    end
    apiLauncher -- "take or release a lease" --> leases
    workerLauncher -- "take or release a lease" --> leases
    workerLoop -- "which runs are due?" --> leases
    apiLauncher -- "fenced writes" --> journal
    workerLauncher -- "fenced writes" --> journal
```

The pieces, in the order this guide builds them:

- **A shared journal** (step 1): SQLite for processes on one machine, PostgreSQL for several.
- **Leases** (step 2): before a process drives a run, it takes the run's lease; while it
  holds it, no other process may drive that run.
- **Fences** (step 3): every journal write carries the lease's fence, so a process that lost
  its lease without noticing cannot write any more.
- **A Launcher** (steps 4 and 5): the object that does the lease work for you. A
  [**harness**](../concepts/harnesses.md) packages one kind of job (its actor, tools, policy,
  the shape of its input, and what a good run looks like), and a `Launcher` builds a
  governor for a harness and starts, answers and wakes its runs. With a lease store it
  takes, renews and releases each run's lease around every call.
- **A Worker** (step 6): a loop that asks the lease store which **parked** runs are due and
  wakes them. A run parks when it waits for a time in the future: it is written to the
  journal and no process holds it in memory until something wakes it.

Which package each piece is in:

| Piece | Module | Package |
|---|---|---|
| Journals and lease stores | `gvn.adapters.sqlite`, `gvn.adapters.postgres` | `gvn` |
| `Harness` | `gvn.runtime.harnesses` | `gvn` |
| `Launcher` | `gvn.runtime.launching` | `gvn` |
| `Worker` | `gvn_domains.worker` | `gvn-domains` |

So leases, fences, the harness interface and the Launcher are part of gvn itself. The
`Worker` loop is in `gvn-domains`, the sibling package that also holds the example
harnesses ([Domains](../domains/index.md#the-launcher)); `gvn_domains.launcher` and
`gvn_domains.catalog` export the same `Launcher` and `Harness` objects under a second name.

## The guarantees, in short

- **gvn guarantees one writer per run.** Once a process has taken a run over, the journal
  refuses every write of the previous owner; a crash loses nothing that was journaled; a
  dead owner's run is taken over when its lease expires.
- **You supply idempotent effects.** Work in flight at a crash or a takeover runs again, at
  least once, with the same key, and your tools use that key to make a repeat harmless.
- **You run leases in every process** that drives runs from the shared journal, and a
  `Worker` to wake parked runs.

[What the service layer guarantees and what you supply](#what-the-service-layer-guarantees-and-what-you-supply)
has the full list.

## The problem

The tutorials run everything in one Python process. A service is different:

- **Several processes**, often on several machines, start runs, answer approvals and wake
  timers. They all need the same journal.
- **Two of them can touch the same run at once.** A web request answers an approval while a
  scheduler wakes the same run. Both would append events, and the journal would no longer be
  the history of any one actor.
- **Parked runs must be woken.** A run waiting for a deadline costs nothing, but something
  has to notice when the deadline arrives, without reading every run there is.

gvn answers each with one piece: a shared journal (SQLite or PostgreSQL), leases with fenced
writes, and the `Worker`. This guide builds them up in that order.

## Step 1: a journal every process can reach

A **journal** is where a run lives: one record per event, plus snapshots
([Crash and resume](../tutorials/durability.md)). gvn has three:

| Journal | Where | Shared by | Use it for |
|---|---|---|---|
| `MemoryJournal` (`gvn.testing.fakes`) | the process's memory | nothing else | tests |
| `SqliteJournal` (`gvn.adapters.sqlite`) | one file | processes on one machine | one machine, standard library only |
| `PostgresJournal` (`gvn.adapters.postgres`) | a PostgreSQL database | processes on any machine | a real service |

Each journal has a matching **lease store** over the same storage (`MemoryLeases`,
`SqliteLeases`, `PostgresLeases`), which the next steps use. All of them pass the same
**contract tests**, shared test suites that any journal or lease store must pass
(`gvn.testing.contracts.JournalContract` and `LeasesContract`).

The walkthrough runs on SQLite. These PostgreSQL setup scripts need a database and the
`postgres` [extra](../install.md#optional-extras) of `gvn`, which supplies psycopg 3.
Prepare gvn's tables before the first run:

```python { .live-script }
# not runnable: needs a PostgreSQL server.
import asyncio
import os

from gvn.adapters.postgres import PostgresJournal


async def main() -> None:
    journal = PostgresJournal(conninfo=os.environ["GVN_DATABASE_URL"])
    try:
        await journal.prepare()
    finally:
        await journal.close()


if __name__ == "__main__":
    asyncio.run(main())
```

Set `GVN_DATABASE_URL` before running the script. Point `PostgresLeases` at the same
database when wiring the workers.

`prepare()` takes a lock inside the database, so every process may call it at start-up. A
journal used before its tables exist raises `SchemaNotPrepared`; tables made by a newer gvn
raise `NewerSchema` and are left alone. gvn's integration tests run both classes against a
real PostgreSQL server started in Docker.

A harness whose agents keep a [memory](../concepts/memory.md) needs it shared as well, or
what one process remembered would be missing in the next. `PostgresMemory` keeps it in the
same database (or another one), in a table of its own that its own `prepare()` creates,
beside the journal's:

```python { .live-script }
# not runnable: needs a PostgreSQL server.
import asyncio
import os

from gvn.adapters.postgres import PostgresMemory


async def main() -> None:
    memory = PostgresMemory(conninfo=os.environ["GVN_DATABASE_URL"])
    try:
        await memory.prepare()
    finally:
        await memory.close()


if __name__ == "__main__":
    asyncio.run(main())
```

Every process builds its `MemoryFulfiller` and memory tools over such an object;
[Memory](../concepts/memory.md#shared-memory-postgresmemory) explains how it matches and
ranks what it recalls.

## Step 2: a lease, so that one process drives a run

A **lease** is the right to drive one run until a given time. A process takes it before
driving the run, renews it while driving, and gives it back when the run parks or ends. A
second process that asks while the lease is held is told no.

Here are two processes, `api` and `worker`, asking for the same run on one SQLite file.
Each call names the run (`run_id`), the asking process (`holder`), the time now (`now`) and
the time the lease should last until (`until`). Times are seconds; the store never reads a
clock, the caller passes `now`. `pool` names the group of workers that may pick the run up
later; a Launcher uses its harness's name.

```python
import asyncio

from gvn.adapters.sqlite import SqliteJournal, SqliteLeases
from gvn.harness.ports import Lease


async def two_processes_ask() -> tuple[Lease | None, Lease | None, Lease | None]:
    leases = SqliteLeases(path="service.db")
    first = await leases.acquire(
        run_id="reminder-1", pool="reminders", holder="api", now=0.0, until=30.0
    )
    second = await leases.acquire(
        run_id="reminder-1", pool="reminders", holder="worker", now=10.0, until=40.0
    )
    later = await leases.acquire(
        run_id="reminder-1", pool="reminders", holder="worker", now=30.0, until=60.0
    )
    await leases.close()
    return first, second, later


first, second, later = asyncio.run(two_processes_ask())
print(first.holder(), first.fence())  # api 1
print(second)  # None
print(later.holder(), later.fence())  # worker 2
```

`api` got the run. `worker`, asking at time 10, got `None`: the lease was still good. At
time 30 the lease had **expired** (a lease is expired once `until <= now`), so `worker` took
it over.

Notice the **fence**: a number that grows by one every time anyone acquires the run. It is
what makes the next step safe.

## Step 3: why the journal checks a fence

Leases alone are not enough. Picture `api` driving a run when its process stalls for a
minute (a long garbage collection, a paused virtual machine). Its lease expires, `worker`
takes the run and carries on. Then `api` wakes up. It still believes it owns the run, and
it is in the middle of writing an event.

So every write made under a lease carries its fence, and the journal refuses a write whose
fence is no longer the run's current one, in the same transaction as the write.

```mermaid
sequenceDiagram
    participant A as API process
    participant L as Lease store
    participant W as Worker process
    participant J as Journal
    A->>L: acquire(now=0, until=30)
    L-->>A: Lease with fence 1
    Note over A: Process stalls
    W->>L: acquire(now=10, until=40)
    L-->>W: None: lease still held
    W->>L: acquire(now=30, until=60)
    L-->>W: Lease with fence 2
    W->>J: Recover after acquiring lease
    J-->>W: Latest durable history
    W->>J: Append with fence 2
    J-->>W: Accepted
    Note over A: Process wakes with stale lease
    A->>J: Append with fence 1
    J-->>A: LeaseLost: no write
```

The lease store and journal share storage: acquisition changes the fence that journal
writes check. The fence protects records and snapshots; it cannot cancel an outside effect
already in flight. Tools still need the stable-key protection from
[Crash and resume](../tutorials/durability.md#what-survives-and-what-runs-again).

Continue from step 2, where `api` holds fence 1 and `worker` fence 2:

```python
from gvn.harness.ports import LeaseLost


async def a_stale_write() -> tuple[dict[str, object], ...]:
    journal = SqliteJournal(path="service.db")
    await journal.append(run_id="reminder-1", record={"by": "worker"}, fence=later.fence())
    try:
        await journal.append(run_id="reminder-1", record={"by": "api"}, fence=first.fence())
    except LeaseLost as refused:
        print("refused:", refused)
    records = await journal.read(run_id="reminder-1")
    await journal.close()
    return records


print(asyncio.run(a_stale_write()))
```

```text
refused: run 'reminder-1' is no longer held under fence 1
({'by': 'worker'},)
```

The stale write was refused and nothing was written. This is the whole correctness
argument, in three sentences:

1. Taking a run over raises its fence before the new owner reads anything.
2. The new owner rebuilds the run from the journal only after that, so it sees every record
   the old owner managed to write.
3. From then on the journal refuses every write of the old owner, whatever its clock says.

Clocks decide only *when* a takeover may happen. They never let two owners write. You will
rarely call `acquire` or pass `fence` yourself: the Launcher does both, as the next step
shows.

## Step 4: a harness that parks

To see leases at work you need a run that parks. This harness starts a
[Timer](../concepts/time.md), gvn's actor that waits until a given time and then ends in its
final state `elapsed`. The time comes from the **brief**: the input a run is started with.

The harness has no tools, so its policy forbids every call. The policy is a
[Decision](../tutorials/decisions-and-branching.md) whose outcomes are `VERDICTS`, the three answers of a tool policy (`cleared`, `needs_approval`, `forbidden`; see
[A policy and approval](../tutorials/agent-with-approval.md)), and it always answers
`forbidden`:

```python
import typing

from gvn.harness.agent import VERDICTS
from gvn.harness.events import Event
from gvn.harness.timer import Timer
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Number, Record
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.evaluation import Evaluation, Finishes
from gvn.runtime.governor import Result
from gvn.runtime.harnesses import Harness


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

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

A harness is a subclass of `Harness` from `gvn.runtime.harnesses`. Each method answers one
question a Launcher asks: its `name` and one-line `summary`; the `brief` it accepts, as a
schema; the `actor_class` of its runs (what recovery rebuilds); how to `start` one run (a
fresh actor and its first event); its `toolbox`, every tool its runs may use (the runtime
refuses a run whose actor needs a tool the toolbox does not hold before the run starts, see
[Tools](../concepts/tools.md#checked-before-the-run-starts)), and its `policy`; and its
`evaluation`, the checks that say what a good run looks like. `Evaluation` and `Finishes` come from
[Replay and evaluation](replay-and-evaluation.md#checks); here the one check is "the run
finished in `elapsed`".

```python
class Reminders(Harness):
    """Waits until the brief's ``at``, then ends."""

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

    def summary(self) -> str:
        return "Waits until a given time."

    def brief(self) -> Record:
        return Record({"at": Number()})

    def actor_class(self) -> type[Timer]:
        return Timer

    def start(self, run_id: str, brief: dict[str, typing.Any]) -> tuple[Timer, Event]:
        return Timer(name=run_id, at=brief["at"]), Event(name="started")

    def toolbox(self) -> Toolbox:
        return Toolbox(tools=[])

    def policy(self) -> Decision:
        return NoTools()

    def evaluation(self) -> Evaluation:
        return Evaluation(name="reminders", checks=[Finishes("elapsed")])
```

## Step 5: a Launcher with leases

A Launcher is built from the harness and the parts the harness does not choose for itself:
the `model` its agents call (none here, so an empty `ScriptedModel`), the `journal`, the
`output` that receives what runs report (`RecordingOutput` keeps it in memory) and the
`clock`. It drives runs under leases when you also give it the lease store and a `holder`, a
name for this process that shows up in errors. Each process builds its own Launcher over the
same file. `sleep_within=0` makes every wake-up not yet due park the run instead of sleeping
in the process (see [Time](../concepts/time.md)):

```python
from gvn.runtime.launching import Launcher
from gvn.testing.fakes import ManualClock, RecordingOutput, ScriptedModel

clock = ManualClock(start=1000.0)  # a clock that moves only when told: time in examples


def process(holder: str) -> tuple[SqliteJournal, SqliteLeases, Launcher]:
    """What one process builds: its own connections, the same file."""
    journal = SqliteJournal(path="reminders.db")
    leases = SqliteLeases(path="reminders.db")
    launcher = Launcher(
        harness=Reminders(),
        model=ScriptedModel(script=[]),  # no agent here, so no model calls
        journal=journal,
        output=RecordingOutput(),
        clock=clock,
        sleep_within=0,
        leases=leases,
        holder=holder,
    )
    return journal, leases, launcher
```

The `api` process starts two reminders, one due in a minute and one in two:

```python
async def start_two() -> tuple[Result, Result, Lease | None, float | None]:
    journal, leases, api = process(holder="api")
    first = await api.start(run_id="call-ada", brief={"at": 1060.0})
    second = await api.start(run_id="call-bob", brief={"at": 1120.0})
    held = await leases.holder(run_id="call-ada")
    due = await leases.earliest(pool="reminders")
    await journal.close()
    await leases.close()
    return first, second, held, due


first, second, held, due = asyncio.run(start_two())
print(first.status(), first.due(), second.due())  # waiting 1060.0 1120.0
print(held, due)  # None 1060.0
```

Each `start` took the run's lease, drove it until it parked on its wake-up, and released
the lease (`holder` is `None` again). On release the Launcher recorded *when the run next
needs driving*: its `Result.due()`. That is the **schedule**, kept in the lease store with
an index, so `leases.earliest(pool=...)` and `leases.due(pool=..., now=..., limit=...)`
answer without reading every run.

With leases, the journal is the run: any process's Launcher can answer, wake or resume any
run the journal holds, not only the runs it started. Before driving, it checks whether
another process moved the run on since it last looked, and if so rebuilds it from the
journal first. A call for a run that another process is driving right now raises `RunHeld`
at once, or, with `wait_for_lease=` seconds, waits for it up to that long.

## Step 6: a Worker wakes what is due

Something must call `wake` when a run's time comes. That is the `Worker`, in
`gvn_domains.worker` (the `gvn-domains` package). It loops: ask the schedule for runs that are due and not held, drive
each with the Launcher's `wake` (which takes the lease, recovers, answers the due wake-ups,
drives until the run parks or ends, and releases), then sleep on the clock until the next
due time. `concurrency` caps how many runs it drives at once:

```python
from collections.abc import Callable

from gvn_domains.worker import Worker


async def until(condition: Callable[[], bool]) -> None:
    """Wait for the worker's database calls (they run in threads) to finish."""
    while not condition():
        await asyncio.sleep(0.01)


async def serve() -> tuple[list[str], tuple[tuple[str, str], ...]]:
    journal, leases, launcher = process(holder="worker-1")
    worker = Worker(launcher=launcher, leases=leases, clock=clock, concurrency=4)
    serving = asyncio.create_task(worker.run())
    await clock.sleeping()
    print("asleep until", clock.earliest())  # asleep until 1060.0
    clock.advance(120)
    await until(lambda: worker.driven() == 2)
    worker.stop()
    await serving
    events = [record["event"]["name"] for record in await journal.read(run_id="call-bob")]
    await journal.close()
    await leases.close()
    return events, worker.failures()


print(asyncio.run(serve()))  # (['started', 'woke'], ())
```

The worker slept until the earliest due time, 1060. When the clock moved two minutes on,
the worker woke both reminders. `stop()` lets current drives finish and stops claiming new
runs. Cancelling `run()` instead cancels the drives and leaves their runs due for the next
worker.

Three settings control the waiting. `poll_every` (default 60 seconds) bounds each sleep, so
that a worker notices runs another process scheduled earlier than anything it knew about;
`notify()` makes it look at once (call it from the same process when you park a run). A run
another worker took first is skipped. Use `failures()` to investigate failed attempts. An
unexpected drive error after recovery takes the run off the schedule. Fix the cause, then `wake` or
`resume` it. An error before driving, such as a failed recovery, can leave the run due.

## Step 7: a process dies in the middle of a run

Now the hard case. A process takes a run and dies while driving it, so it never releases
the lease. To fake a dead process, give it a clock of its own that never moves: its lease
is never renewed, exactly as if it had stopped. Start a reminder due at 1135 and let the
doomed process take it at 1120:

```python
async def a_process_takes_the_run_and_dies() -> Lease | None:
    journal, leases, api = process(holder="api")
    await api.start(run_id="call-cy", brief={"at": 1135.0})  # the clock is at 1120
    lease = await leases.acquire(
        run_id="call-cy", pool="reminders", holder="doomed", now=1120.0, until=1150.0
    )
    await journal.close()
    await leases.close()
    return lease


doomed = asyncio.run(a_process_takes_the_run_and_dies())
print(doomed.holder(), doomed.until())  # doomed 1150.0
```

The doomed process holds the run until 1150 and will never give it back. A worker comes
along at 1130. It may not touch the run yet; once the lease has expired, it takes it over,
rebuilds the run from the journal, and finishes it:

```python
async def a_worker_takes_over() -> tuple[list[str], str | None]:
    journal, leases, launcher = process(holder="worker-2")
    worker = Worker(launcher=launcher, leases=leases, clock=clock)
    clock.advance(10)  # 1130: the lease is still good
    serving = asyncio.create_task(worker.run())
    await clock.sleeping()
    print("asleep until", clock.earliest())  # asleep until 1150.0
    clock.advance(20)  # 1150: the lease has expired
    await until(lambda: worker.driven() == 1)
    worker.stop()
    await serving
    events = [record["event"]["name"] for record in await journal.read(run_id="call-cy")]
    stale = None
    try:
        await journal.append(run_id="call-cy", record={"late": True}, fence=doomed.fence())
    except LeaseLost:
        stale = "refused"
    await journal.close()
    await leases.close()
    return events, stale


print(asyncio.run(a_worker_takes_over()))  # (['started', 'woke'], 'refused')
```

The worker slept exactly until the dead lease expired, then took the run and finished it.
If the dead process comes back to life and tries to write, the journal refuses it.

What about work that was in flight when the process died? The same rule as after any crash
applies: the new owner re-issues it with the same request id, so it runs **at least once**
([at-least-once and request ids](../concepts/governor.md#at-least-once-and-request-ids)). A
tool with side effects uses its stable key to make a repeat harmless.

## Step 8: the entry point answers a waiting run

A run that waits for a person is answered through the service's **entry point**: the web
handler or chat integration that receives the person's click. The entry point authenticates
the caller, as it does for any request, and passes who they are to the Launcher as `by=`, a
`gvn.harness.events.Principal`. A Launcher built with `entitlement=` hands its Governor a
rule that decides whether that principal may answer; [Trust](../concepts/trust.md#part-2-who-answered)
explains both.

This harness parks on an [`Approval`](../concepts/human-in-the-loop.md#an-approval-on-its-own),
a yes-or-no step with no tool call, and only a member of the `release` group may answer it:

```python
from gvn.harness.answering import ENTITLEMENTS, NotEntitled
from gvn.harness.approval import Approval
from gvn.harness.events import Principal
from gvn.kernel.schema import Record, Text


class Releases(Harness):
    """Asks a person to approve a release."""

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

    def summary(self) -> str:
        return "Waits for a release to be approved."

    def brief(self) -> Record:
        return Record({"version": Text()})

    def actor_class(self) -> type[Approval]:
        return Approval

    def start(self, run_id: str, brief: dict[str, typing.Any]) -> tuple[Approval, Event]:
        text = f"Release {brief['version']}?"
        return Approval(name=run_id, label="release", text=text), Event(name="started")

    def toolbox(self) -> Toolbox:
        return Toolbox(tools=[])

    def policy(self) -> Decision:
        return NoTools()

    def evaluation(self) -> Evaluation:
        return Evaluation(name="releases", checks=[Finishes("approved", "declined")])


class ReleaseTeam(Decision):
    def outcomes(self) -> Alphabet:
        return ENTITLEMENTS

    def judge(self, answering: object) -> Symbol:
        by = answering.by()
        if by is not None and "release" in by.claims().get("groups", []):
            return ENTITLEMENTS.named("entitled")
        return ENTITLEMENTS.named("not_entitled")


def release_process(holder: str) -> tuple[SqliteJournal, SqliteLeases, Launcher]:
    journal = SqliteJournal(path="releases.db")
    leases = SqliteLeases(path="releases.db")
    launcher = Launcher(
        harness=Releases(),
        model=ScriptedModel(script=[]),
        journal=journal,
        output=RecordingOutput(),
        clock=clock,
        leases=leases,
        holder=holder,
        entitlement=ReleaseTeam(),
    )
    return journal, leases, launcher
```

The `api` process starts the run, which parks on the approval. Later, the `web` process
receives two clicks on it. Its handler has authenticated each caller (here the principals are
built by hand, standing for what the session says) and passes them as `by=`:

```python
async def start_then_answer() -> str:
    journal, leases, api = release_process(holder="api")
    waiting = await api.start(run_id="release-2.4", brief={"version": "2.4"})
    (request,) = waiting.pending()
    await journal.close()
    await leases.close()

    journal, leases, web = release_process(holder="web")
    intern = Principal("kim@example.com", issuer="corp-sso", claims={"groups": ["support"]})
    lead = Principal("lee@example.com", issuer="corp-sso", claims={"groups": ["release"]})
    try:
        await web.approve(run_id="release-2.4", request=request, by=intern)
    except NotEntitled as error:
        print(error)
    done = await web.approve(run_id="release-2.4", request=request, by=lead)
    await journal.close()
    await leases.close()
    return done.outcome().payload()["answered_by"]["subject"]


print(asyncio.run(start_then_answer()))
```

```text
request 'release-2.4/request_approval' of kind 'request_approval' may not be answered by 'kim@example.com' (issuer 'corp-sso')
lee@example.com
```

The refused click journaled nothing and the run kept waiting; the handler reports the
refusal to its caller. The accepted one is journaled with the principal, so every process
that reads the run later sees who approved it.

`launcher.approve(..., by=)` is one mechanism at its service level: under the lease it calls
`Governor.answer` with an `approved` event. The same call is made directly in the recipe
[Stop a tool call until a person approves](../recipes.md#approve-a-tool-call) and in the loop
of [A coding agent](coding-agent.md#step-9-approve), and by `run_agent` when you give it an
`approve=` function ([The short path](shortcuts.md#step-4-asking-a-person)).

A service can set a journal-based interruption threshold for a run's model calls with
`Launcher(..., allowance=...)`. See [Spending and rate limits](spending-and-rate-limits.md)
for how different actors respond and which usage the journal can count.

## The two entry files of a deployment

The steps above ran on SQLite with a clock moved by hand, so that every result could be
shown. A deployment has the same objects with PostgreSQL storage and the real clock
(`SystemClock`, from `gvn.adapters.clock`), in two files. Both import `Releases` and
`ReleaseTeam` from step 8, saved in a module of your own (here `my_service.releases`), read
the database from `GVN_DATABASE_URL` and the model id from `MODEL_ID`, and send what runs
report to your logs ([Logs, traces and streams](observability.md)).

`api.py` is the module your web application imports: it builds one Launcher for the process,
and its three functions are what the handlers call to start a run, to answer one as the
authenticated caller, and to close the connections.

```python { .live-script }
# not runnable: needs a PostgreSQL server, an API key and your harness module.
import logging
import os
import socket

import anthropic

from gvn.adapters.anthropic import AnthropicModel
from gvn.adapters.clock import SystemClock
from gvn.adapters.logs import LoggingOutput
from gvn.adapters.postgres import PostgresJournal, PostgresLeases
from gvn.harness.events import Principal
from gvn.runtime.governor import Result
from gvn.runtime.launching import Launcher
from my_service.releases import Releases, ReleaseTeam

DATABASE = os.environ["GVN_DATABASE_URL"]
journal = PostgresJournal(conninfo=DATABASE)
leases = PostgresLeases(conninfo=DATABASE)
launcher = Launcher(
    harness=Releases(),
    model=AnthropicModel(client=anthropic.AsyncAnthropic(), model=os.environ["MODEL_ID"]),
    journal=journal,
    output=LoggingOutput(logging.getLogger("gvn")),
    clock=SystemClock(),
    sleep_within=0,  # a wake-up not yet due parks the run, so the request returns
    leases=leases,
    holder=f"api-{socket.gethostname()}-{os.getpid()}",
    entitlement=ReleaseTeam(),
)


async def start_release(run_id: str, version: str) -> Result:
    await journal.prepare()  # safe to call from every process, every time
    result = await launcher.start(run_id=run_id, brief={"version": version})
    launcher.forget(run_id)  # the run is in the journal; any process can pick it up
    return result


async def approve_release(run_id: str, by: Principal) -> Result:
    waiting = await launcher.recover(run_id)  # read the run back: what is it waiting on?
    try:
        (request,) = waiting.pending()
        return await launcher.approve(run_id=run_id, request=request, by=by)
    finally:
        launcher.forget(run_id)


async def shutdown() -> None:
    await journal.close()
    await leases.close()
```

`worker.py` is a process of its own, started as `python worker.py` once or several times: it
wakes the runs that are due and finishes the runs of processes that died, until it receives
`SIGTERM`, when it lets the runs it is driving finish and exits.

```python { .live-script }
# not runnable: needs a PostgreSQL server, an API key and your harness module.
import asyncio
import logging
import os
import signal
import socket

import anthropic

from gvn.adapters.anthropic import AnthropicModel
from gvn.adapters.clock import SystemClock
from gvn.adapters.logs import LoggingOutput
from gvn.adapters.postgres import PostgresJournal, PostgresLeases
from gvn.runtime.launching import Launcher
from gvn_domains.worker import Worker
from my_service.releases import Releases


async def main() -> None:
    database = os.environ["GVN_DATABASE_URL"]
    journal = PostgresJournal(conninfo=database)
    leases = PostgresLeases(conninfo=database)
    clock = SystemClock()
    launcher = Launcher(
        harness=Releases(),
        model=AnthropicModel(client=anthropic.AsyncAnthropic(), model=os.environ["MODEL_ID"]),
        journal=journal,
        output=LoggingOutput(logging.getLogger("gvn")),
        clock=clock,
        leases=leases,
        holder=f"worker-{socket.gethostname()}-{os.getpid()}",
    )
    worker = Worker(launcher=launcher, leases=leases, clock=clock, concurrency=4)
    asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, worker.stop)
    try:
        await journal.prepare()
        await worker.run()
    finally:
        await journal.close()
        await leases.close()


if __name__ == "__main__":
    asyncio.run(main())
```

Each process names itself in `holder=` by host and process id, so an error about a held run
says which process holds it. `launcher.recover` rebuilds a run from the journal and returns
what it is waiting on, and `launcher.forget` drops the process's in-memory copy afterwards:
the journal is the run, so neither process keeps runs between calls.

## What the service layer guarantees and what you supply

Guaranteed, and tested:

- **One writer per run.** Once a process has taken a run over, the previous owner cannot add
  a single record or snapshot to it. The tests pause a process before each of its writes in
  turn, let another take the run over and finish it, then let the first go on; every time,
  the journal holds one consistent history, and without fences the same test corrupts it.
  (On the memory store and on PostgreSQL; the fence checks themselves on all three stores.)
- **A crash at any append** loses nothing that was journaled (memory store and PostgreSQL).
- **Durable wakes under contention.** In the PostgreSQL worker race test, workers could
  visit a reminder more than once, and each reminder recorded one `woke` event and one effect.
  Handle repeated attempts with the same idempotency contract as other work in flight.
- **Dead owners are replaced** once their lease expires, and the run continues from the
  journal (on the fakes, and in step 7 on SQLite).

What you supply, and how the layer behaves around it:

- **Idempotent effects.** Work in flight at a takeover or a crash runs again (at least
  once). A tool with side effects uses the key gvn gives it to make a repeat harmless.
- **Takeover timing.** A dead owner's run is taken over when its lease expires (`lease_for`,
  default 30 seconds, renewed every 10 while driving). Processes whose clocks disagree can
  make a takeover come earlier or later than intended; they can never make two owners write.
- **A cancelled write.** A write whose caller was cancelled may or may not have happened. If
  it happened it is whole: a record is never half written and positions never skip. This is
  true of SQLite and PostgreSQL alike.
- **Wake-ups across processes.** A Worker learns of runs that other processes schedule earlier
  than it expected at its next `poll_every`, or at once when `notify()` is called in its own
  process.
- **Failed drives.** A failed worker attempt can appear in `failures()`. An unexpected
  drive error takes the run off the schedule. A recovery error can leave it
  due, so check the error before deciding whether to `wake` or `resume` it.
- **Leases everywhere.** Use leases in every process driving runs from a shared journal.
  See [Runtime guarantees](../reference/runtime-guarantees.md) for application responsibilities.

## Recap

- Choose a journal every process can reach: SQLite for one machine, PostgreSQL for several.
  Create PostgreSQL's tables explicitly with `prepare()`.
- A lease gives a run one owner at a time; its fence makes the journal refuse a stale
  owner's writes, so a stalled process cannot corrupt a run.
- `Launcher(..., leases=..., holder=...)` takes, renews and releases leases for you, and
  schedules each parked run at its due time.
- A `Worker` sleeps until the next due time, wakes what is due, and takes over runs whose
  owner died.
- A deployment is two entry files over `PostgresJournal`, `PostgresLeases` and `SystemClock`:
  the module your web application calls, and a worker process.
- The entry point answers a waiting run with `by=` the caller it authenticated; a Launcher
  built with `entitlement=` refuses an answer from someone who may not give it, journaling
  nothing.

**Next:** to cap what each run of the service may spend on model calls, read
[Spending and rate limits](spending-and-rate-limits.md); to send what every process does
to your logs and tracing system, read [Logs, traces and streams](observability.md).
