Skip to content

Operations ​

@anvia/durable remains experimental. Pick a topology and keep it: a SQLite deployment is one supervised Node.js process (22.16 or newer) on one host with a dedicated local file; a Postgres, Drizzle, or Prisma deployment is one owning runtime or a set of shared workers plus optional store-only clients and observers. Do not run an owner and workers together, do not share a SQLite file over a network filesystem, and do not run a restored copy alongside the original deployment.

Failure handling and health ​

ts
const runtime = await DurableRuntime.open({
  store,
  tasks,
  agents,
  onFatalError(error) {
    supervisor.report(error)
  },
  limits: {
    maxPendingRuns: 10_000,
    maxPendingTasks: 10_000,
    maxPayloadBytes: 1_048_576,
    maxOperations: 10_000,
  },
})
await runtime.resume()

The runtime fails closed. A storage read, write, admission, or commit error stops both schedulers, aborts active callbacks, and rejects further work with the original error. It is never converted into an ordinary failed business outcome, and a callback cannot catch a journal failure and keep committing. Close the runtime, repair the storage problem, then open and resume it. Do not forcibly clear a live owner row or lease. Recovery policies still apply: models can repeat after an interrupted checkpoint, and uncertain manual tools and effects need reconciliation.

onFatalError fires once per failed owner or worker. Errors thrown or rejected by the observer are ignored, and the observer receives the error or its cause, so apply your own logging and redaction.

runtime.health() performs no database access and returns status (ready, failed, closing, or closed), ready, activeRuns, and activeTasks. Readiness means the runtime accepts work; it does not prove providers are reachable or that definitions match saved work. A worker's readiness does not prove it currently holds a claim.

runtime.metrics() returns a DurableMetrics aggregate: observedAt, per-status runs and tasks counts, oldestPendingAgeMs, operations, events, and databaseBytes where the store can report it. It contains no session IDs, prompts, or outputs. It scans aggregate tables, so scrape periodically rather than per request.

Alert on readiness loss, growing queue age, needs_attention, retry_wait, cancelling, disk pressure, and backup age. Waiting for an approval or signal is not itself an error. Cancellation and shutdown are cooperative: callbacks must honor their AbortSignal, and your supervisor should enforce a shutdown grace period. Workers renew claims on a heartbeat; a stopped worker's runs become claimable again after leaseMs.

Admission and payload limits ​

LimitDefaultBounds
maxPendingRuns10,000Unfinished runs, including graph nodes and owned agents.
maxPendingTasks10,000Unfinished custom tasks, including owned children.
maxPayloadBytes1,048,576A number, or per-field budgets for prompt, operation, event, and outcome.
maxOperations10,000Operations per execution.

maxPayloadBytes accepts either one byte budget or an object with default, prompt, operation, event, and outcome members. Omitted groups fall back to default, which defaults to 1 MiB; runtime.limits() returns the resolved object. The field mapping is:

BudgetPersisted fields
promptrun.prompt, run.input (submitted prompt plus inherited history).
operationoperation.input, operation.result.
eventevent.model_delta.
outcomerun.history, run.outcome, task.outcome.
defaultEvery other persisted field.

Byte counts are UTF-8 JSON of the stored form. Values above 64 KiB move to the blob table behind a content-addressed reference, so the reference—not the value—is measured for tool results, model outcomes, excessively large message parts, and oversized prompts. The logical prompt budget still applies at admission, and media in submitted prompts still counts against it. Blob writes are not limit-checked and blobs are never garbage-collected. Size the HTTP bridge's maxBodyBytes as well.

Capacity checks and insertion share one transaction, so a graph or owned-agent creation that exceeds capacity rolls back atomically, and repeating an identical existing submission still succeeds at capacity. Terminal executions release capacity. Admission failures throw DurableLimitError with code, field, limit, and actual (HTTP 413 for payloads, 429 with Retry-After: 1 for capacity). Status and control changes remain possible after limits are lowered on restart, failure diagnostics use a separate 4,096-character bound, and copying an already-admitted owned agent output survives lower quotas. Status events are not payload-checked, so a limit cannot prevent a run from reaching a terminal status.

An oversized external effect result leaves its started intent and blocks for reconciliation instead of running the effect again. Limits do not expire data, and automatic retention and execution deadlines are not available. Do not delete journal rows or blob rows manually; deduplication, history, cursors, and recovery depend on them.

Backup and restore ​

ts
import { backupSqlite, restoreSqlite } from '@anvia/durable/maintenance'

await runtime.close()
const info = await backupSqlite('./durable.sqlite', './backup-2026-11-23.sqlite')
// Later, while the original deployment remains stopped:
await restoreSqlite('./backup-2026-11-23.sqlite', './restored.sqlite')

Both functions return a DurableBackupInfo of { createdAt, schemaVersion } and are offline maintenance operations that accept schema 3 through 12 databases. backupSqlite acquires the database's exclusive ownership, uses SQLite's backup API (including committed WAL state), integrity-checks the copy, seals it with metadata, and publishes a new file with mode 0600. Existing destination files, symlinks, and SQLite sidecars are rejected and nothing is replaced. A sealed archive cannot be opened as a runtime. restoreSqlite validates the archive and creates a new unsealed database without modifying the archive or a live file. If directory sync fails after publication the call reports an error but the destination may exist, so inspect it.

For Postgres, Drizzle, and Prisma, backup and restore with your database's own tooling and stop every runtime and worker first. Preserve the owner or claim rows alongside the data.

Archives contain prompts, checkpoints, signals, tool results, and blobs: protect and encrypt them. Stop the original deployment before restoring, restore compatible code and task definitions, and inspect unfinished snapshots before resume(). External effects performed after the backup are not in the snapshot, so reconcile them using stable idempotency keys before replay. Restoring cannot undo payments, emails, or other external work. Practice restoration in an isolated environment with side effects disabled, and measure recovery point and time.

Upgrade, rollback, and rollout ​

  1. Drain traffic, stop admission, close every runtime and worker, and take a verified backup.
  2. Keep the previous application artifact and matching task and agent definitions.
  3. Test the new application on a restored copy with external services isolated.
  4. Restart one owner or one worker, inspect readiness and blocked work, call resume() or let workers claim, then admit a small workload.
  5. Expand only after fault recovery, restoration, and sustained-load checks meet your targets.

Opening a SQLite database upgrades schemas 1–12 on ownership acquisition, retaining existing runs, graphs, and tasks. The maintenance helpers accept schemas 3–12; backup acquisition upgrades its source before producing a schema-12 archive. Read-only observers do not migrate and require a schema this release can read. Keep an infrastructure-level offline copy before an upgrade when rollback to an older engine is required. Older engines reject newer schemas, and there is no automatic downgrade; roll back by restoring the prior backup to a new file and auditing post-backup external effects.

Tests cover injected journal failures, process kills at real model and tool boundaries, claim loss, bounded task load, cancellation, remote authorization, and backup and restore. They do not replace a disk-full or read-only drill, a long soak on your filesystem, or an operational recovery exercise.

Bounded inspection and shared histories ​

For frequent polling, use await run.status() or await runtime.status(runId): these read a bounded DurableRunSummary without decoding transcripts. await runtime.run(runId) reads the record without operations. run.snapshot({ operations: false }) still decodes the record and outcome but skips operation payloads. Task snapshots omit operations by default; request { operations: true } when inspecting effects.

SQLite snapshots expose compact operation envelopes. Model operations with historyEncoding: 'linked-v1' store an opaque { head, length } at input.request.chatHistory; context operations also use linked histories. Use await runtime.operationRequest(runId, operation.key) to reconstruct a model's full CompletionRequest, including pre-compaction requests. Do not treat stored history references as message arrays. Backups include the shared log and blob area; there is no automatic pruning or vacuum.

Custom stores must implement bounded DurableTransaction.getRunSummary(id) reads, return expanded histories from getOperation(), and preserve stored envelopes in operations(). Upgrade Core and Durable together for execution protocol 5. New runs capture steering and live-compaction support; legacy runs preserve their original replay boundaries. Test recovery on a database copy before rollout.

Built for Anvia.