Skip to content
Source on GitHub (opens in a new tab)

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.

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.

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.

  • Killed while a model call is in flight: the next start closes the attempt as lost and starts attempt 2.
  • Killed while a command runs: the command is never run again; it is recorded with outcome unknown, and the model is told to verify before retrying.
  • Killed between events: nothing was in flight, so the next start rebuilds the state from the log and goes on.

Each kind of effect has its own rule, and the contract 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). Every attempt of one call gets the same key, through tool.Call.IdempotencyKey(), 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 next Start of the session settles the log in a fixed order:

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

Three things can cut an execution short: a stop, an interrupt and a detach. 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.

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

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:

  • 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, 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 file store (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.

One record: what each append writes

  1. length4 B

    the payload’s length, 1 B to 16 MiB

  2. payload crc4 B

    CRC-32C of the payload

  3. header crc4 B

    CRC-32C of the two fields before it, so a bad length is caught

  4. payloadn B

    one line of JSON: the events appended together

  5. \n1 B

    a newline, so line tools can read the file

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

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

  • 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. A holds fence 7 from 0 s to 50 s.
  • 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. A holds fence 7 from 0 s to 40 s, where it expires unrenewed. B holds fence 8 from 41 s to 71 s.
  • 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. A holds fence 7 from 0 s to 8 s, where it is released. B holds fence 8 from 9 s to 39 s.

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. 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 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 drivers within one process. The default
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 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.

The terminal UI, zelk exec and zelk acp keep their sessions as files under the state directory, 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.

They assume local filesystem semantics: 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.

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.