# Durability and recovery

> What zelk promises when a process crashes, stops or hands a session to another process, and how the log on disk keeps that promise.

A process can die at any moment: killed, out of memory, a laptop shut. When
it does, the session's log is all that is left, so every promise zelk makes
is a promise about what the log can show. This page covers what zelk records
before it acts, how the next process settles what a crash left open, how the
log is kept on disk, and how a lease keeps two processes from writing it at
once.

## Intent before action

zelk calls an **effect** anything the loop asks the driver to do: a model
call, a tool call, a question for a person, a hook. The driver runs an
effect in **attempts**, and records each one in two steps:

1. Before it dispatches an attempt, it appends that the attempt started.
2. When the attempt ends, it appends how, in one record with what the attempt
   observed, such as the files it read.

An effect that started ends with exactly one terminal event, however many
crashes and restarts come between. An effect's ID comes from the session and
the event that asked for it, so folding the log again gives the same IDs. That
is what lets a request be delivered again later and still be recognised.

The driver decides what to do next only from the state folded from the log,
its own appends included. After every append it folds what it appended, and
stops if the reducer wouldn't have asked for it. Replaying a log never
dispatches anything, reads the workspace or consults the clock: everything a
fold needs is in the log.

## What a crash leaves

A crash leaves one of two things. Either every effect had ended, and the next
process rebuilds the state from the log and goes on. Or an effect had started
and not ended, and its attempt is still open. That attempt is the only thing
recovery has to settle, and what it does depends on whether doing the effect
twice is safe.

The log is all that survives a killed process, so each cut is settled from it alone:

- **Killed while a command runs**. A command (`run_tool`) was in flight. A command may already have acted, so zelk never runs it twice. It records the outcome as `unknown` and has the model check what the command did before trying again. The next `Start` appends `effect_reconciled` (outcome `unknown`), then `effect_started` (`call_provider`).
- **Killed during a model call**. A model call (`call_provider`) was in flight. A model call is safe to repeat, so zelk closes the lost attempt and starts a second. Each attempt’s cost is counted. The next `Start` appends `attempt_ended`, then `effect_started` (`call_provider`).
- **Killed between events**. Nothing was in flight. Every effect had ended, so the next `Start` rebuilds the state from the log and simply goes on. The next `Start` appends `effect_started` (`call_provider`).

Each kind of effect has its own rule, and
[the contract](/internals/durability/#r4) gives the exact one:

| Effect | What recovery does |
|---|---|
| A model call | Retries it. A lost call's only side effect is the tokens it spent, which are charged against the budget |
| A tool call that is trusted, read-only and idempotent | Runs it again; what it observes is recorded afresh |
| A tool call with an enforced idempotency key | Runs it again with the same key |
| Any other tool call | Records the outcome as `unknown` and tells the model: "the session stopped while this call ran; verify the state it would have changed before retrying" |
| An approval or a question | Delivers it to the host again with the same ID. It was waiting, not lost, and an answer already in the log settles it |
| A hook | Calls it again with the same invocation ID, so a host can deduplicate its side effects. Hooks that run in the background are best effort and never re-run |
| A subagent's call | Reopens the child's session, which is named by the call, or creates it if it doesn't exist yet |

zelk re-runs a tool call only when running it again can't do anything the
first run didn't. Only built-in read-only tools are trusted to say so. Any
other tool can earn a re-run by declaring that it deduplicates by the call's
**idempotency key**
([`tool.WithEnforcedIdempotency`](/reference/go/tool/#withenforcedidempotency)).
Every attempt of one call gets the same key, through
[`tool.Call.IdempotencyKey()`](/reference/go/tool/#call), and the tool must make any
number of runs with one key act at most once, for example by passing the key to
a payment API that deduplicates by it.

A command may have started something that outlives the process. A Bash call
of a dead holder is reconciled as `unknown`, and the model is told to check
what it did. A background process is picked up again only through an
environment that keeps its identity and its output; the local one can't, so a
command it can no longer find is reported as lost, never restarted.

### The order at start

The next `Start` of the session settles the log in [a fixed
order](/internals/durability/#r1):

1. Acquire the lease.
2. Adopt the log, then fold it.
3. Check that this process can continue the log: it refuses one written by a
   newer reducer, by another provider family, or for tools that are missing or
   have changed.
4. Append the commands `Start` was given.
5. Fire the timers that came due.
6. Reconcile what is open.
7. Go on with the run. Nothing is dispatched before reconciliation is done.

Commands come before timers and timers before reconciliation, so an answer
delivered at `Start` wins over a deadline that passed while nobody was
running, and both are in the log before recovery decides anything. Deadlines are
absolute times derived from events in the log, so time spent crashed counts.
zelk doesn't schedule processes: [`zelk.NextWake`](/reference/go/zelk/#nextwake) tells a
host the session's earliest deadline, and the host calls `Start` by then.

If the log already shows the run ending, because an interrupt was accepted or
a deadline fired, recovery finishes the ending and re-dispatches nothing. The
user's decision or the deadline is not undone by a retry.

Reconciliation is itself recorded in small batches of whole resolutions, and
computed from the log alone, so a crash during recovery leaves a log from which
the next recovery works out the rest of the same plan. Recovering a log that
needs nothing appends nothing.

A run waiting for an approval or a question can also suspend: it records what
it waits for, then the Agent cleans up execution-owned background work
before releasing the lease and returning. The requests stay waiting, and
resuming delivers them again with the same IDs.

## Stop, interrupt and detach

Three things can cut an execution short: a
[stop](/internals/durability/#s1), an [interrupt](/internals/durability/#s2)
and a [detach](/internals/durability/#s3). They are kept apart because they
mean different things.

| | Stop | Interrupt | Detach |
|---|---|---|---|
| Means | this process is going away | the user wants the run to end | a watcher goes away |
| How | cancel the context given to `Start`, `Execution.Cancel`, `Agent.Close` | `Execution.Interrupt`; esc in the terminal UI | a subscriber or a client disconnects |
| Attempts in flight | told to stop; those that end are recorded, the rest are left open | cancelled, and each ends as cancelled with the reason | untouched |
| The run | still in progress: it is not finished | finished as `interrupted` | untouched |
| Afterwards | the next `Start` reconciles and continues | nothing to recover | nothing |

A stop is a crash that loses no finished work. An interrupt is an answer: it
is a command, accepted and deduplicated like any other, and every tool call
without a result gets one that says it was cancelled by the user.

### Retries

Only model calls are retried automatically, and only when the error says the
call did nothing or is likely to pass: transient or rate limited. The attempt
closes with a time before which the next one mustn't start, and a warning says
why. That time is in the log, so a crash during the wait neither skips it nor
starts it over. A tool error is never retried by zelk: the model sees the result
and decides.

Every error is [classed](/internals/durability/#e5) by what may have happened,
and the class decides what may follow:

| Class | Means | What may follow |
|---|---|---|
| not dispatched | it provably did nothing | a retry, or a failed result for the model |
| failed | it ran and definitely failed | the error goes to the model |
| outcome unknown | it may have acted | never retried by zelk; the model is told to verify first |

A plain Go `error` from a tool counts as unknown: zelk doesn't guess that a
failure was harmless.

## Commands delivered twice

A host that may deliver a command twice, say after its own crash, gives it a
stable `ID`. The log keeps the ID of every accepted command with a digest of
what it said, and before appending, the driver [checks each command against
it](/internals/durability/#k3):

- the same ID with the same content isn't appended again. It is acknowledged
  with the original's sequence number, marked as a duplicate;
- the same ID with different content is refused with
  [`ErrCommandConflict`](/reference/go/zelk/), and nothing of that batch is
  appended.

A command given without an ID gets a random one, so it is never a duplicate.
`Execution.Send` never blocks: it admits the command to a bounded queue and
returns an acknowledgement, or refuses it at once because the queue is full or
the execution is ending. After a failed append the command may or may not be in
the log, and sending it again with the same ID is always safe.

## The log on disk

The file store ([`store/file`](/reference/go/store-file/)) keeps one file per
session, and each append is one framed, checksummed record. A record holds a
batch of events, so a batch is all or nothing.

A log file starts with the 8-byte header `ZELKLOG` and a format version, then holds one record per append:

| Part | Size | What it holds |
|---|---|---|
| `length` | 4 B | the payload’s length, 1 B to 16 MiB |
| `payload crc` | 4 B | CRC-32C of the payload |
| `header crc` | 4 B | CRC-32C of the two fields before it, so a bad length is caught |
| `payload` | n B | one line of JSON: the events appended together |
| `\n` | 1 B | a newline, so line tools can read the file |

- **An append**. An append counts once it is on disk. zelk frames the batch as one record, writes it, waits for `fsync`, and only then acknowledges it. A batch is all or nothing: its record is valid, or none of its events exist. A reader reads all 4 records.
- **Killed mid-append**. A torn tail was never acknowledged, so nothing anyone was told about is lost. Readers stop before it without an error and never change the file; the writer, holding the lock, cuts it off and logs the repair. A reader reads 3 records and stops before record 4 without an error. The writer truncates the file to the end of record 3.
- **Damaged in the middle**. Valid records after the damage were acknowledged, so the storage misbehaved, and cutting the file would hide it. zelk reports corruption as an error and truncates nothing. A reader reads 1 record, finds record 2 damaged with valid records after it, and returns an error. Nothing is truncated.
- **fsync fails**. After a failed `fsync`, nobody can know what is on disk: the page cache may show the record while the disk never got it. zelk doesn’t retry or read it back. The session breaks: the store keeps its lock until the process exits, and a `.broken` marker warns everyone else. The append fails and the session is refused from then on.

An append is acknowledged only after `fsync` (on macOS, `F_FULLFSYNC`, which
also flushes the drive's cache; on Windows, `FlushFileBuffers`). On NTFS this
is checked for process crashes; power loss is not. So a crash can damage only the last record, the
one nobody was told about, in any way: the file may end inside it, or hold its
new size but not all its data. That is how a reader tells a **torn tail** from
**corruption**. It reads valid records from the start, and at the first damaged
one looks for a valid record after it. With none, the damage is the
unacknowledged final append: readers stop before it and never change the file,
and the writer cuts it off. With one, acknowledged data follows the damage, which
only misbehaving storage explains, so zelk reports an error and truncates
nothing.

A failed write or `fsync` [breaks the
session](/internals/durability/#file-store-record-format). After the error the
record's durability can't be learned by reading the file back: the page cache
may still show it to every process on the machine while the disk never got it,
and a later `fsync` may report success without writing it. So the store doesn't
retry. The driver stops without dispatching the effect whose intent was being
recorded, and the session is refused for appends and reads, by the store that
failed, by other writers through the log's lock, which the process keeps until
it exits, and by other processes through a marker file next to the log.

Blobs, such as long tool output, are written to a temporary file, synced, linked
into place and their directory synced, all before any event refers to them. A
name that exists isn't necessarily durable, so whoever finds or makes one syncs
its directory before relying on it.

## One writer at a time

A **lease** gives one process at a time the right to write a session. It lasts
a TTL, 30 seconds by default (`lease.DefaultTTL`), unless the holder renews it,
which it does every third of the TTL. Every holder after the first gets a higher
**fence**, and the store [refuses an append](/internals/durability/#l8) whose
fence is older than the newest it has accepted. The store keeps that newest fence
durably, so a restart doesn't make it forget.

Two processes, A and B, and one session whose lease lasts 30 s unless renewed:

- **Renewed in time**. A live holder keeps the session. It renews every third of the TTL, so its grant never runs out, and anyone else who asks is told the lease is held. In the terminal UI, that session opens read-only.
   - 0 s, A: acquire → granted, fence 7, until 30 s
   - 4 s, A: append, fence 7 → event 41
   - 10 s, A: renew → until 40 s
   - 15 s, B: acquire → held by A until 40 s
   - 18 s, A: append, fence 7 → event 42
   - 20 s, A: renew → until 50 s
   - 26 s, A: append, fence 7 → event 43
- **Frozen, then taken over**. A frozen holder can’t write over its successor. A froze with an append on its way, a laptop gone to sleep perhaps. Its grant expired, B took the lease with a higher fence, and the store refuses A’s fence 7. A’s own clock tells it that its authority has ended too, and it stops.
   - 0 s, A: acquire → granted, fence 7, until 30 s
   - 4 s, A: append, fence 7 → event 41
   - 10 s, A: renew → until 40 s
   - 12 s, A: freezes with an append on its way
   - 30 s, B: acquire → held by A until 40 s
   - 41 s, B: acquire → granted, fence 8, until 71 s
   - 43 s, B: append, fence 8 → event 42
   - 55 s, A: wakes
   - 55 s, A: append, fence 7 → refused: fence 8 is newer
- **Released on exit**. An execution that ends gives its lease back, so the next process needn’t wait out the TTL. It takes the lease at once with the next fence and goes on from the log.
   - 0 s, A: acquire → granted, fence 7, until 30 s
   - 4 s, A: append, fence 7 → event 41
   - 8 s, A: release → free
   - 9 s, B: acquire → granted, fence 8, until 39 s
   - 11 s, B: append, fence 8 → event 42

A lease is never taken from a holder whose grant hasn't run out. Whoever asks
meanwhile is told it is held. Once a grant has run out, the next to ask gets a
higher fence, and the old holder's renewals and release are told the lease is
lost. An execution that ends releases its lease, so the next process needn't
wait out the TTL.

The holder doesn't [trust the lease's clock](/internals/durability/#l3). It reads
its own clocks just before it asks to acquire or renew, and counts its authority
from then on, less a safety margin, on two clocks: the monotonic clock, and the
wall clock, which keeps running while a laptop or a virtual machine sleeps and
the monotonic clock stops. Authority ends when either passes its deadline. From
then on nothing new is appended or dispatched, the attempts in flight are
cancelled, their records are not appended, so the next holder settles them, and
the execution ends with a lease-lost error.

Before a new holder folds anything, it [**adopts**](/internals/durability/#l11)
the log: it makes everything the log holds durable, records its fence, and folds
only up to the end it gets back. Another process's reader can see a batch whose
`fsync` is still pending or has failed, and a holder mustn't decide from data
that may not last.

Fencing protects the log. It protects an external side effect only through a
port that checks the token itself, which a tool reads from `tool.Call.Token()`.
A payment or a message sent by an old holder can't be taken back by the log.

Two leases ship, and a host brings any other:

| Lease | Coordinates |
|---|---|
| [`lease.Local`](/reference/go/lease/#local) | drivers within one process. The default |
| [`lease/file`](/reference/go/lease-file/) | processes on one machine, through locked files that are synced before an answer is given |
| one backed by a shared database, written by the host | processes on several machines |

A store whose logs outlive the process needs a lease whose fences do too, and
`zelk.New` refuses the pair otherwise. Every lease implementation passes the
conformance kit in `lease/leasetest`, as every store passes `store/storetest`.

`lease/file` [compares wall-clock times](/internals/durability/#l7) across
processes. After a sleep, a new holder can take over as soon as the wall clock
passes the recorded expiry. The old holder's own wall-clock deadline has passed
too, so its next check ends its authority, and the store's fence refuses its
appends. But its attempts already in flight are cancelled only within a second of
waking, so an effect one of them is in the middle of may overlap the new
holder's for that long. A host that can't accept the overlap uses a lease backed
by a single clock, such as a database's.

## In the zelk command

The terminal UI, `zelk exec` and `zelk acp` keep their sessions as files under
the [state directory](/cli/sessions/#where-sessions-live), with a file lease
beside them. Print mode keeps its session in memory, so it has nothing to
recover.

- A session another zelk holds opens read-only. The UI says "another zelk has
  this session open", with the time its lease ends, and a message sent to it is
  refused until you start a new session with `/new`.
- Esc interrupts the run in the terminal UI. In print mode and `zelk exec`, the
  first Ctrl+C does the same and exits 130.
- Ctrl+C twice quits. With a run under way, zelk first interrupts it, so the run
  ends `interrupted`, and waits up to ten seconds for it to end. Quitting again
  while it waits quits at once, leaving whatever was open for the next start to
  settle.
- In `zelk exec`, a second Ctrl+C or SIGTERM stops the execution, which leaves
  the run open. `zelk exec resume --last` settles it before it does anything
  else.
- After a crash or a kill, `zelk -c` reopens the session, and the next message
  you send starts an execution that settles what the crash left, as above. If
  the crashed zelk held the lease, it lasts out its 30 seconds first. A command
  it ran that zelk can no longer find is recorded as lost, never restarted.

## What the guarantees don't cover

They [assume local filesystem
semantics](/internals/durability/#scope-of-the-guarantees): `fsync` makes data durable, `rename` is
atomic and file locks are released when their process exits. Network
filesystems may not honour all of these. A host that needs durability on one
implements its own store and runs `store/storetest` against it.

On Windows NTFS, the file stores cover process crashes. OS crashes and
power-loss ordering on NTFS remain unverified.
[Windows durability evidence](/internals/durability/#windows-ntfs).

One case is outside what the file store covers: a write the kernel couldn't
write back, whose writer died before it could leave its marker, read by another
holder while the machine stays up. The failed pages can still show in the page
cache, and an adopting `fsync` can report success without writing them. A host
that can't accept the window uses a store whose reads stay authoritative after a
failure, such as a database.

The log covers zelk's own state. A tool that acts on the outside world is
covered only as far as the table above says: re-run when it is safe, otherwise
reported as unknown. The overlap after a sleep is the other window, described
under the leases.

## Where to go deeper

- [Stores, leases and recovery](/go/stores/): keep sessions on disk and reopen
  them in another process, in Go
- [Sessions, rewind and checkpoints](/cli/sessions/): resume and inspect sessions
  in the `zelk` command
- [Sessions and executions](/go/executions/): stopping, interrupting and sending
  commands from Go
- [How zelk works](/concepts/overview/): sessions as logs
- The [durability contract](/internals/durability/) specifies every rule here,
  from [recovery](/internals/durability/#r4) to the
  [file store's record format](/internals/durability/#file-store-record-format),
  and its [verification index](/internals/durability-tests/) links each rule to the
  tests that cover it.
- [Loop states](/internals/loop-states/) says which of these rules the reducer
  enforces and which rest on the driver.
