# Durable tasks and hosts

> Open the durable kernel on a storage and a host to run tasks, docs and signals that survive restarts, on a server, a Durable Object or a browser tab.

The durable kernel (`zidane/durable`) is what [crash recovery](https://zidane.si/docs/durability.md) runs on. A run is one of its tasks. Your own code can define more: a task with phases (named steps, each committed), a versioned JSON doc, a signal a task waits for. Each survives the death of its process, and the next process goes on where it stopped.

The contract is [DURABILITY.md](https://github.com/Tahul/zidane/blob/main/docs/DURABILITY.md). Its [scenario matrix](https://github.com/Tahul/zidane/blob/main/docs/durability/scenario-matrix.md) names the test of each rule, and marks the gaps.

## Open it

`openDurable` takes a storage, a host and the definitions it runs. It is also the runtime an agent takes.

```ts
import { createAgent } from 'zidane'
import { defineTask, memoryStorage, openDurable } from 'zidane/durable'
import { anthropic } from 'zidane/providers'

const digest = defineTask<{ topic: string }, null, string>({
  kind: 'app.digest',
  version: 1,
  initial: () => ({ phase: 'write', checkpoint: null }),
  phases: {
    write: async (rt) => {
      const out = await rt.effect('fetch', async () => `notes on ${rt.input.topic}`, { replay: 'safe' })
      return out.status === 'completed' ? { done: out.value } : { fail: new Error('fetch was interrupted') }
    },
  },
})

const durable = await openDurable({ storage: memoryStorage(), definitions: [digest] })
// Tasks a dead process left go on.
await durable.resumeLive()

const session = await durable.session('job-42')
const id = await session.startTask(digest, { topic: 'release' })
console.log((await session.waitTask(id)).state.result)

const agent = createAgent({ provider: anthropic(), durable: { runtime: durable, onInterrupted: 'resume' }, sessionId: 'job-42' })
```

- A phase commits its next phase and checkpoint with the effects it made. An effect that finished is not run again after a crash.
- `rt.effect` resolves to an outcome. Read `value` when `status` is `completed`. An unsafe effect that a crash cut off has `status: 'interrupted'`.
- `rt.sleepUntil` and `rt.waitSignal` park a task. No code runs while it waits, and a signal sent while no process ran is kept.
- `rt.race` cancels each wait that lost, so its signal or its deadline leaves the stored task. Pass each wait as `rt.waitSignal` or `rt.sleepUntil` returned it: `race` cannot cancel a promise chained from a wait. A cancelled wait rejects with `WaitCancelledError`.
- The timer of the local host does not keep the process alive (the host calls `unref` on it). If a standalone script waits on a sleeping task, keep the process alive until the task wakes, for example with a timer of your own.
- One process opens one runtime per storage. A second `openDurable` on the same storage is refused until the first is disposed.
- A storage failure stops the session, a failed read as well as a failed write. Its next use opens it again from storage, so what was stored before the failure is there.
- A mistake in a commit (an append to a missing conversation, a value that is not JSON) fails only that commit. The session goes on.

## Task lifecycle

A task starts as pending. The scheduler runs one phase at a time. A phase moves to the next phase, parks the task, or ends it. When the process dies, a running task goes back to pending. Only the innermost running task counts a restart. An owner that waited on a running owned task gets none. At the restart limit (5 by default) the task ends with `restart_limit`.

![Task lifecycle: pending, running, sleeping or waiting, completing, terminal. A run task owns its tool call, sub-agent and compaction tasks, and each task has its own restart counter. A process death sends a running task back to pending, and the innermost running task gets one more restart. At the restart limit the task ends with restart_limit. An abort marks the task and its owned tasks that are not background tasks, stops the running phase, waits for the owned tasks, then runs the abort handler.](https://zidane.si/diagrams/durability-task-lifecycle.svg)

An abort marks the task, and each task it owns that is not a background task. The running phase stops, the owned tasks end, then the task's `abort` handler runs. A crash in the middle does not lose the abort. A task that cannot run (its definition is missing or older) ends `orphaned` when you abort it, and no handler runs.

## Owned tasks

A run owns a task for each tool call (`zidane.tool`), sub-agent call (`zidane.child`) and compaction (`zidane.compact`). Your phases can own tasks too:

- `rt.run(def, input, { key }, body)` runs a hosted task inline, with `body` as its phase. The same `key` after a restart reaches the same task, or answers how it ended without running `body` again. When it ends, storage drops its record, and the owner keeps its end as an effect record.
- `rt.all(values, { failFast: true })` aborts the other owned tasks of `values` when the first one fails.
- `abandonOnRestart: true` aborts an owned task that a restart finds running, instead of running it again.
- `rt.spawn(def, input, { key })` starts an owned task that the scheduler runs on its own.

## Rewind and read a doc as of an entry

`session.rewind(conversationId, entryId)` takes a conversation back to an entry in one commit. It forks the conversation there and makes the fork the root conversation. The old conversation stays readable. The registered conversation docs get their value back by their fork mode (`asOf`, `current` or `initial`, set on the doc).

![Rewind: the old conversation keeps entries 1 to 4 and stays readable. A rewind to entry 2 forks it there in one commit, and the fork becomes the root conversation of the session. New entries go to the fork. Conversation docs are restored by fork mode: asOf gets the value at entry 2, current gets the latest value, and initial is not copied.](https://zidane.si/diagrams/durability-rewind.svg)

- An `entryId` of `null` rewinds to before the first entry. The new root is empty.
- `session.docAt(def, target, { entryId })` reads a doc as of the commit that stored the entry (or `{ seq }`). Only a doc with `history: 'rewindable'` keeps the history for it. A `latest` doc throws `DocNotRewindableError`.
- Inside your own transaction, `tx.fork` and `tx.rewind` do the same.

## Watch a session

A watch follows a doc (`watchDoc`), the last entries of a conversation (`watchConversation(id, { window })`) or the live task graph (`watchTasks`).

![Watch: at attach the listener gets the value with no ops. After each stored commit that changes it, the listener gets the new value and the ops. More than 10,000 ops come as one root set of the new value. When the commit line stops or closes, the listener gets failed with the error and the last value, and the watch ends.](https://zidane.si/diagrams/durability-watch.svg)

```ts
const stop = await session.watchConversation(undefined, { window: 50 }, (delivery) => {
  if (delivery.kind === 'failed')
    return console.error(delivery.error)
  render(delivery.value)
})
```

Every watcher of the same value gets the same deliveries, in commit order, after the commit is stored. A doc that an older version stored comes migrated. A commit that stores a version newer than your definition ends that watch with `failed`, and the other watches go on.

## Read-only viewer

`openDurable({ storage, readOnly: true })` opens a viewer. Its sessions take no lease and never write. So a viewer runs beside the process that owns the storage, in the same process or another one. A viewer reads storage again every `pollMs` (1000 by default) while a watch is open, or when you call `refresh()`.

## Hosts

![Hosts of the kernel. The local daemon runs on SQLite with timers, and a launchd or systemd service keeps it running. The server runs on SQLite with timers. A Durable Object runs on its own SQLite, and its alarm wakes it. A browser tab runs on IndexedDB with timers while the tab is open. Restate runs on object state, with a durable timer, segments, child objects and awakeables.](https://zidane.si/diagrams/durability-hosts.svg)

| Host | Storage | Wakes a parked task with |
| - | - | - |
| Daemon, server | SQLite (`zidane/durable/sqlite`, Bun) | A timer. `zidane daemon install` keeps the daemon running ([the daemon](https://zidane.si/docs/daemon.md#start-it-at-login)) |
| Node or Bun | SQLite (`zidane/durable/node-sqlite`, `zidane/durable/sqlite`), JSONL files (`jsonlStorage` with [`zidane/durable/node-fs`](https://zidane.si/docs/reference/durable-node-fs.md)) or memory | A timer |
| Cloudflare Durable Object | The object's SQLite (`durableObjectSqlDriver`) | The object's alarm |
| Browser tab | IndexedDB (`indexedDbStorage`) | A timer, while the tab is open |
| Restate | The virtual object's state (`zidane/restate`) | A durable timer, then a delayed call to the object |

`zidane/durable` imports no `node:` or `bun:` module, so it bundles for a browser and a Durable Object.

### Durable Object

Use one object per session. The object is the only writer of its session, so it takes no lease. A task parked until a deadline sets the object's alarm, and `alarm()` resumes the session, also in a new instance.

```ts
import type { DurableObjectStateLike, DurableObjectStorageLike } from 'zidane/durable'
import { durableObjectHost, durableObjectSqlDriver, openDurable, sqliteStorage } from 'zidane/durable'

export class ZidaneAgent {
  readonly host
  readonly durable

  constructor(state: DurableObjectStateLike & { storage: DurableObjectStorageLike }) {
    this.host = durableObjectHost(state)
    this.durable = openDurable({ storage: sqliteStorage(durableObjectSqlDriver(state.storage), { singleWriter: true }), host: this.host, lease: false })
  }

  // The platform's wake: a task's deadline came, maybe in a new instance.
  async alarm() {
    const durable = await this.durable
    await this.host.onAlarm(() => durable.resumeLive())
  }
}
```

The full class is in [examples/durable-object](https://github.com/Tahul/zidane/tree/main/examples/durable-object).

### Browser

`localHost()` is the browser host. Its timers fire while the tab is open. When the page loads again, call `resumeLive()`. Two tabs on one database are two writers. The lease keeps one of them on a session at a time.

```ts
import { indexedDbStorage, openDurable } from 'zidane/durable'

const durable = await openDurable({ storage: indexedDbStorage({ name: 'zidane', indexedDB, IDBKeyRange }) })
await durable.resumeLive()
```

A tab runs the kernel and your own tasks. It does not run the agent, because the `zidane` entry imports Node built-in modules and does not bundle for a browser. Import from `zidane/durable` only.

The example in [examples/browser](https://github.com/Tahul/zidane/tree/main/examples/browser) keeps reminders in IndexedDB:

- Each reminder is a task. It adds its row to a session doc, then waits for a dismiss signal until its time (`rt.waitSignal(key, { until })`).
- A watch on the doc draws the list again after each commit that changed it.
- After a reload, `resumeLive()` runs each reminder that still waits. A reminder whose time passed while the tab was closed fires at once.

## Your own storage

Any `DurableStorage` works as `storage`. Prove it with the conformance kit, [`zidane/durable/testing`](https://zidane.si/docs/reference/durable-testing.md). `registerStorageConformance` runs the storage contract against it. `assertReplayDeterministic` makes sure that a scenario makes the same commits when it runs again from the same stored state.

## Extensions

An extension defines its own tasks and docs with `ctx.durable`. See [durable extension work](https://zidane.si/docs/extensions-durable.md).
