Skip to content

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 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. Its scenario matrix 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.

TypeScript
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 A task starts pending. The scheduler runs a phase and the task is running. A phase can move to the next phase, which resets the restart counter, park the task as sleeping until a time or waiting for a signal, or finish. A finished task that still owns live tasks is completing until they end, then terminal. A finished task that owns none is terminal at once. A terminal task ends completed, failed, aborted, orphaned or faulted. A run task owns one task per tool call (zidane.tool), sub-agent call (zidane.child) and compaction (zidane.compact), and each task has its own restart counter. When the process dies, a running task goes back to pending, and the innermost running task gets one more restart, not the owner that waited on it. At the restart limit, 5 by default, the task ends with restart_limit. An owned task that ends becomes an effect record of its owner, which resets the owner to zero restarts. An abort marks the task and every owned task that is not a background task. If the process crashes during an abort, the abort runs again when the session opens. The running phase stops, the owned tasks end, then the abort handler runs. A stop of a run on a local host commits the abort of its task, so its tool calls, sub-agents and compaction stop too. pendingrunningcompletingterminalsleepingwaitingruns a phasedone or fail,owns tasksdone or fail, owns no live taskowned tasksendednext phase: restarts = 0sleepUntil(at)waitSignal(key)Woken at its time, by a signal, or by a timeout.No code runs while a task is parked.process died:restarts + 1restarts reached restartLimit (5): ends with restart_limitcompleted, failed,aborted, orphaned,faultedOwned taskszidane.runthe run, one counterzidane.toolone tool callzidane.childone sub-agent callzidane.compactone compactionownsEach task has its own restart counter. A process death adds one to the innermost running task only.A tool call that was running gets it, not the run that waited on it. An owned task that ends becomesan effect record of the run, and the run goes back to restarts = 0.AbortabortTask marks the task and each owned task that is not a background task. The running phase stops,the owned tasks end, then the abort handler runs. If the process crashes in between, the abort runs again at open.A stop of a run on a local host commits the abort of its task, so its tool calls, sub-agents and compaction stop too.

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 holds entries 1 to 4. A rewind to entry 2 forks it there in one commit, and the fork becomes the root conversation of the session. The fork sees entries 1 and 2 through the fork point, and new entries go to the fork. The rewind restores every registered conversation doc by its fork mode: asOf gets the value as of entry 2, current gets the latest value, and initial is not copied. The kernel deletes no entry, so the old conversation stays readable. Old conversation, still readableentry 1entry 2entry 3entry 4rewind to entry 2,in one commitsession.rewind(conversationId, entryId)New conversation: root of the sessionSees entries 1 and 2 through the fork point.run() and submit() use it from now on.entry 5Conversation docsAll of them, by fork mode:asOf: the value at entry 2current: the latest valueinitial: not copiedThe kernel deletes no entry. history(old conversation id) still reads entries 1 to 4.docAt reads a rewindable doc as of any entry.
  • 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 the value, it gets the new value and the ops that changed it: kind value. A delivery of more than 10,000 ops comes as one root set of the new value. When the commit line stops or closes, the listener gets kind failed with the error and the last value, and the watch ends. Every watcher of the same value gets the same deliveries, and sees a commit only after storage stored it. A read-only session delivers the difference at each refresh. AttachThe value now,with no ops.Each stored committhat changes the value sendsthe new value and its ops.next commit{ kind: 'value', value, ops }More than 10,000 opsOne root set of the newvalue instead.failedThe line stopped or closed.The watch ends.{ kind: 'failed', error, value }Every watcher of the same value gets the same deliveries, and sees a commit only after storage stored it.A read-only session has no commits of its own. It delivers the difference at each refresh.
TypeScript
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 The kernel, zidane/durable, holds the commit line, the scheduler, tasks, docs and signals. It reaches its platform through the host seam and the storage contract. It has five hosts. The local daemon runs on SQLite with timers, and zidane daemon install keeps it running as a launchd or systemd service. 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, segmented invocations, children on their own object keys and awakeables for waits. Kernel (zidane/durable)Commit line, scheduler, tasks, docs and signals.Host seam: now, id, effect, all, race, wakeAt. Storage contract.Local daemonStorage: SQLite(sessions.db)Wake: timerszidane daemon installkeeps it running:launchd on macOS,systemd --useron Linux.ServerStorage: SQLite(sessions.db)Wake: timersResumes interruptedruns when it starts.Durable ObjectStorage: theobject's SQLiteWake: the alarmalarm() callsonAlarm, thenresumeLive().One writer, no lease.Browser tabStorage: IndexedDBWake: timers whilethe tab is openOn load: resumeLive().The lease keeps onetab on a session.RestateStorage: objectstate (zd: keys)Wake: durable timer,then a delayedsend to itselfSegments: a turnbudget for eachinvocation.Children: their ownobject keys.Waits: awakeables.
Daemon, server
SQLite (zidane/durable/sqlite, Bun)
A timer. zidane daemon install keeps the daemon running (the daemon)
Node or Bun
SQLite (zidane/durable/node-sqlite, zidane/durable/sqlite), JSONL files (jsonlStorage with zidane/durable/node-fs) 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.

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

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.

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