@durable-sdk/postgres

The migrator, the doctor, the probe and the plain-SQL store; a host without an ORM.

Open in CursorView as Markdown

Generated from the SDK's own source (packages/durable-postgres/README.md) at build; edit there.

The Postgres half of the Durable SDK (ADR-0043 as decided on 2026-09-25; ADR-0046 §M step 3a, landed by W4.2-b). Private, 0.1.0 (the package that reshaped the bookkeeping to v2, ADR-0062 unit 5), Apache-2.0, consumed by the engine's own tests and by the durable-sdk CLI; nothing is on npm yet. Host-free like @durable-sdk/core: pg is the one runtime dependency (the package-imports guard, which reads the built dist for it: the core is imported as types alone and erased on build).

What is here#

Module What
driver.ts The Driver/Conn/Param contract of ADR-0043 §C, dialect: "postgres" only.
pg-driver.ts pgDriver(pool): the opening in one message (BEGIN; SET LOCAL statement_timeout = <n>[; SET LOCAL lock_timeout = <m>], a parameterless text node-postgres sends as one simple-query message, FW-081), the body, COMMIT/ROLLBACK, release. poolConfig(url, { searchPath?, max?, applicationName? }): the pg.PoolConfig a connection string opens a pool with, for a host that builds the one pool itself (Prisma's ?schema= becomes the connection's search_path, Prisma-only parameters are dropped, a sslmode becomes the explicit ssl setting so pg-connection-string warns on no cold start); openPool(url): a pool the driver owns, configured by it. Since NP-001 (ADR-0043 amendment 2026-10-30) a statement the store opts in (QueryOptions.named: the hot verbs' alone) is sent as a named prepared statement, statementName(text) (d_ and 24 hex of the text's sha1, one text one name, bounded by the verbs' statement shapes since every value is a parameter), so node-postgres parses it once per connection and the server runs its generic plan from the sixth execution; every other statement stays unnamed; a transaction pooler of PgBouncer 1.21 or later with max_prepared_statements set maps the names onto its server connections, each parsing once, so a cold pool's warm-up is the pooler's server pool, while one that tracks none answers the second execution on another server connection with SQLSTATE 26000: pgDriver(pool, owned, { named: false }) and openPool(url, { named: false }) (the store's namedStatements: false) drop the name from every statement, and the driver's namedStatements() probe (one client executes SELECT $1::int AS n named, a second holds a transaction, the first executes it again) answers ok, refused on 26000, off under the switch or unjudged (a pool of one connection, no second server connection within NAMED_PROBE_MS), what the package's probe() refuses refused on; durable-sdk doctor --plans reads every named statement's EXPLAIN (GENERIC_PLAN) beside its custom plan and is red when the generic plan takes none of the indexes the custom plan takes on a table and reaches it by a sequential scan or a whole index instead, a swap onto a partial index the version defines printed and never red (the day it landed it kept the ledger append's read and the bucket's take unnamed).
naming.ts The two presets. snake: the SDK's schema, snake_case, TIMESTAMPTZ(3), TEXT status columns. prisma-legacy: quoted PascalCase and camelCase, shop/shopId, TIMESTAMP(3), the RunStatus/StepStatus enums with casts, in the connection's current schema: the tables exactly as the engine's own Prisma migrations created them.
ddl.ts One canonical definition type, rendered as DDL (renderDdl, a delta as renderDelta, expand-only: NotExpandOnly, since FW-027 (ADR-0062 amendment 2026-10-08) a column added NOT NULL with no default among what it refuses, since a filled table refuses the ADD COLUMN and the older build's inserts fail on an empty one) and as the catalog the doctor expects (expectedObjects), through the same preset, so the migrator and the doctor cannot disagree; since ADR-0062 unit 6 renderReverse, the delta's exact inverse (one drop per object, in reverse order; NotReversible for an enum value appended under a preset with enums), what a version's down renders; since FW-096 (version 23) a version may contract: renderDelta admits the removal of an index the next definition lists under contracts (a plain DROP INDEX, or under when: "c_collation" a DO block that drops where the database's default collation is C-treated alone, the index kept as optional and admitted present or absent by the doctor), BadContraction for an entry naming no index of the previous definition, every other removal or reshape NotExpandOnly as before, renderReverse creating each dropped index again, and contractedObjects what the migrator's in-place check reads beside deltaObjects. Since FW-113 (version 24) a partial index's predicate may name a list, IndexDef.where.in: a status column against two or more labels of its enum, rendered as Postgres deparses an IN list (= ANY (ARRAY['FAILED'::"RunStatus", 'COMPENSATED'::"RunStatus"])), so the doctor reads the written predicate and pg_get_expr's as one, and a list of one label, a label twice or a label the enum does not list is BadPredicate at the render.
migrations/v1.ts Version 1: the eight framework tables as prisma/migrations 20260916182405 … 20260926000000 leave them, every index, both foreign keys, the ledger_append_only function and trigger. Append-only: a change is a new file. The IdempotencyKey(runId) index of ADR-0043 §F renders under snake alone (on the Prisma-modelled tables of a prisma-legacy host it would be drift).
migrations/v2.ts Version 2 (ADR-0046 §H, step 7 PR 2): the N-peer relay's objects as prisma/migrations/20260927120000_relay_peers creates them, a delta over v1 (renderDelta): OutboxEvent.peerId, the four per-peer RelayPeerState columns, RelayDelivery with its index and cascade, Instance. Append-only like v1.
migrations/v3.ts … v32.ts One delta per version over the one before: up to v11 each the Prisma migration it mirrors statement for statement under prisma-legacy (v3 deliver-at, v4 waits, v5 outbox-cancelled, v6 due-items, v7 run-concurrency-key, v8 run-signature, v9 run-cancel, v10 run-version, v11 search-indexes), and since v12 the SDK's alone with no Prisma twin (ADR-0062: applied by durable-sdk migrate on an adopted database and a fresh one alike): v12 step-declared (ADR-0060 decision 12, WorkflowStep.declared), v13 run-deadline-input-hash (ADR-0063 B16 and B20: WorkflowRun.deadlineAt, inputHash and the open-deadline partial index), v14 run-hold (ADR-0063 B37: holdRequestedAt, holdRequestedBy), v15 payload-codec (ADR-0063 B25: codecId on the run, the step and the ledger row), v16 run-tags (ADR-0063 B33: WorkflowRun.tags and its GIN index, the first under a method other than btree), v17 run-build-and-fact-run (ADR-0063 B10 and B30: WorkflowRun.build and builds, OutboxEvent.runId and attempt with OutboxEvent_runId_idx), v18 run-lease-until (ADR-0066 D08: WorkflowRun.leaseUntil, the attempt's lease when its kill is stored, the resumer's recovery at killAt + KILL_GRACE_MS), v19 outbox-dismissed (ADR-0041 amendment 2026-10-05: OutboxEvent.dismissedAt, dismissedBy and dismissReason, an exhausted event a person took off the dispatcher's board), v20 next-batches-columns-and-indexes (FW-001, 2026-10-08: WorkflowRun.compensatingAt and WorkflowWait.firedByRequestId, written by nothing yet, and the five indexes of ADR-0043's amendment of 2026-10-05, LedgerEntry(scope, seq), WorkflowRun(startedAt), WorkflowRun(status, waitUntil), OutboxEvent(occurredAt, id) and the partial unsent one over the relay's rows not yet sent), v21 failed-steps-index (FW-035, 2026-10-08: the partial WorkflowStep(startedAt) WHERE status = 'FAILED' the Errors page's failedSteps walks, the first under the predicate grammar's equality conjunct IndexDef.where.equals), v22 step-window-errored-unsent-partition-ledgered (FW-082, 2026-10-09, the performance audit: WorkflowRun.ledgeredAt, the mark FW-088's finish stamps so retention skips the frozen runs, and five indexes, the whole WorkflowStep(startedAt) for the health refresh's stepWindow, the errored partials on the outbox and the steps for the parked count, eventsWithErrors and failedSteps, the unsent_partition partial for the relay's partition-scoped reads and the unledgered partial for retention; the index builds hold SHARE on the step table for ten to thirty seconds inside the version's transaction, so it lands in the build step), v23 first-contraction-unread-indexes-ledgered-backfill (FW-096, 2026-10-09, the package's first contracting version: seven unread indexes dropped, each listed under the definition's contracts and in CONTRACT.md one release after the code stopped reading it, v21's failed partial among them (its predicate column made every step completion non-HOT), WorkflowRun(actor, startedAt) replaced by the plain (actor), OutboxEvent(key text_pattern_ops) dropped where the database's collation is C-treated alone and kept as optional elsewhere, and the ledgeredAt backfill as the version's data step, two statements between its addition and its drops inside the same transaction and part of its checksum (the drops last, since the ACCESS EXCLUSIVE a drop takes is held to the commit); the down creates the seven again, lossless, and leaves the marks standing), v24 limbo-runs-index (FW-113, 2026-10-09: the partial WorkflowRun(startedAt, id) WHERE status IN ('FAILED', 'COMPENSATED') AND dismissedAt IS NULL the Errors page's and the promotion gate's listLimbo and the bulk dismiss's and redrive's lists walk, the first under the predicate grammar's list conjunct IndexDef.where.in; the whole (startedAt) index walked backward to find none before it, 346 907 buffers and 3 372 ms mean on beta), v25 storage-guard-open-waits-stuck-set-live-partition (ADR-0076 wave 2, 2026-10-12: the open waits' WorkflowWait(eventName, createdAt, id) WHERE firedAt IS NULL, the live partition's OutboxEvent(partition, occurredAt, id) WHERE dispatchedAt IS NULL AND cancelledAt IS NULL (the stuck set's D05 (6) names measured and not taken: its predicate columns are the ones every claim moves, 0 of 2 000 claims HOT under it), and the tables' storage parameters as the definition's record, TableDef.storage, rendered as one ALTER TABLE … SET (…) per table and reset by the down; outside the catalog checksum, a doctor warning and never drift), v26 outbox-attempt-limit-exhausted-by (ADR-0076 FP-028, 2026-10-12, D06: a listener's own retry policy on the row, two nullable columns on the outbox, OutboxEvent.attemptLimit (the count the row exhausts at, written by every transport backoff from the throwing listener's retry.maxReceiveCount or the count the row stands at when its age passed the listener's retry.maxAge; null for the engine's MAX_ATTEMPTS, so every exhaustion predicate reads attempts >= COALESCE(attemptLimit, $max)) and OutboxEvent.exhaustedBy (the listener whose policy exhausted the row, what GET events?exhausted=<listener> lists and events.redrive puts back), both cleared by the reset and the bulk redrive; no index; the down drops both behind an overridable guard over the undelivered rows carrying either), v27 outbox-priority-dedupe-keys-outbox-archive (ADR-0076 wave 2b, 2026-10-12: the queue primitives' schema of FP-025, FP-026 and FP-027 ahead of their engines; on the outbox priority, SMALLINT NOT NULL DEFAULT 0, a seconds offset the door bounds to −600…600, and orderAt, a stored generated column "occurredAt" - make_interval(secs => priority), the row's ordering moment computed by the database on every insert (immutable under both timestamp types through generatedExpression, the grammar's smallint and ColumnDef.generated with it; the one ADD COLUMN that rewrites its table, 2.8 s at beta's shape on the scratch database), the live-partition partial moved onto it ((partition, orderAt, id) WHERE dispatchedAt IS NULL AND cancelledAt IS NULL, v25's over occurredAt the version's one contraction, dropped last; fetchPartition orders by it, the one statement of FP-025's engine the version carries); the table DedupeKey ((kind, key), targetId, createdAt, expiresAt with its index; the store's seventh prune rule expired_dedupe_keys on both doubles, run by no pass yet) and the archive tier OutboxArchive (the outbox's stored columns plus archivedAt, (id) its key, three indexes, no foreign key, no trigger; archiveDays among the retention windows, 30 by default and 365 at most); no writer for either until the engines land; the down reverses it behind three overridable guards), v28 run-state-continuation-join-live-order-at (ADR-0076 wave 3, 2026-10-12: the schema of FP-031, FP-032 and FP-037 ahead of their engines, D07; on the run table state (the declared state the query and update handlers read, written at a step boundary by the fenced touch once FP-031 lands), continuedFrom and continuedTo (the continue-as-new chain under one key) and joinWaitId (the child's pointer to its parent's join wait); on the wait table the join's counters total, remaining, failed and tolerated (remaining decremented by each child's finish in its own statement by the wait's primary key, no index); the RunStatus label CONTINUED, appended IF NOT EXISTS, the first label a down leaves standing (EnumDef.ifNotExists: the doctor admits it below 28 as a warning, the in-place check reads its standing as no evidence, renderReverse leaves it); and the partial OutboxEvent (orderAt, id) WHERE dispatchedAt IS NULL AND cancelledAt IS NULL for the cron tick's window read across every partition, which FP-025's engine (#622) orders by the ordering moment and whose partitionOrder comment named this index as a later version's call (under the burst 1 217 buffers and a 19 ms sort without it, 203 with it, the plan unmoved at rest); every column nullable, written by nothing until the engines land; the down drops the index and the eight columns behind three overridable guards and leaves the label, the version applying again over it), v29 run-step-outputs (ADR-0076 FP-038, 2026-10-12, D07 "Lightweight runs", stacked on #632's v28: one nullable column, WorkflowRun.stepOutputs (JSONB), the list [{ seq, step, ms, output }] the landing of a lightweight: true run writes beside output in the finish's own statement, every step of such a run a read kept in memory with no step row, read by the run detail alone and replayed by nothing since such a run is re-run whole after a crash; no index; the down drops it behind one overridable guard over the rows carrying a list), v30 ledger-truncate-guard (ADR-0076 D09, unit SOC-16, 2026-10-13: the statement-level trigger ledger_append_only_truncate, BEFORE TRUNCATE … FOR EACH STATEMENT on v1's function beside the row-level BEFORE UPDATE OR DELETE one, since Postgres admits TRUNCATE on no row-level trigger and a TRUNCATE "LedgerEntry" landed behind the chain before it; AppendOnlyDef.truncateTrigger, rendered by renderDelta over a definition that lacks it and refused renamed or dropped; the catalog checksum carries its state; no column, no index, no Prisma twin; the down drops it, lossless, no guard), v31 ledger-partitioned-by-month (ADR-0078 D08, unit SR-010 part 1, 2026-10-14: LedgerEntry rebuilt in place inside the version's one transaction as a table partitioned by range over occurredAt, one partition a calendar month in UTC (LedgerEntry_y<YYYY>m<MM>, from the floor, the earliest row's month or twelve months back on an empty table, through three ahead, and the catch-all LedgerEntry_past for every row before the floor, each with the definition's storage parameters and its own TRUNCATE guard; an append whose month has no partition creates it and runs once more), the keys (id, occurredAt) and (seq, occurredAt), the five indexes as partitioned indexes, the triggers on the parent, the owner and the grants carried, the old table dropped last under the one ACCESS EXCLUSIVE lock the rename took (3.0 s at beta's shape on the scratch database); the catalog checksum carries the partition key, the doctor reads the partitions off pg_inherits and warns when fewer than two months stand ahead, the daily core run ledger.partitions.ensure keeps three; no column, no contraction listed, no Prisma twin (the model block mirrors the composite key for the client); the down re-assembles the plain table, lossless, the count held, no guard), v32 wait-open-created-at-id (ADR-0050 decision 3 as amended 2026-10-30, the timers-at-scale unit: the open waits' order index, the partial WorkflowWait (createdAt, id) WHERE firedAt IS NULL the console's open-waits list walks in its own order and stops at its limit where it read every open wait with a sort before; one CREATE INDEX, no column, no contraction, no Prisma twin; no engine verb names it; the down drops it, lossless, no guard); the list is migrations/index.ts, the checksums and the paragraph per version BASELINES.md, and the two v<N>.ts ranges on this page are held to LATEST_VERSION by the schema guard (ADR-0064 P11). Append-only like v1.
migrations/index.ts MIGRATIONS, LATEST_VERSION, MINIMUM_VERSION, checksumOf (sha256 of a version's statements per preset and schema), downChecksumOf (the same over a version's down; null where it is irreversible). Each Migration carries up, definition and, since ADR-0062 unit 6, down(naming, schema).
migrations/down.ts The downs of the shipped versions (ADR-0062 decision 3, unit 6): per version { statements, guards } (the statements renderReverse renders, the exact inverse of the version's delta; the guards one SELECT count(*) each over the rows the statements would lose, the ledger's the one --accept-loss never overrides) or { irreversible } with the sentence saying why none renders under the preset (v4 under prisma-legacy: the WAITING enum labels). Append-only like the versions; the checksums are pinned in BASELINES.md's down column, and the schema guard holds every shipped version file, v1.ts … v32.ts today, byte for byte to the base branch. Since FW-096 a contracting version's down creates the dropped indexes again (the exact inverse still) and says what it leaves standing (leaves: v23's backfilled marks; since v28 an enum label the version appended IF NOT EXISTS, EnumDef.ifNotExists, which renderReverse leaves where v4's WAITING made the down irreversible).
bookkeeping.ts durable_schema (id = 1: version, checksum, package, updated_at, and since v2 (ADR-0062 unit 5) naming, catalog_checksum, applied_by), durable_migrations (version, name, checksum, applied_at, kind in `apply
migrator.ts runMigrations({ driver, schema, naming, mode, appliedBy }): apply (pending versions, one transaction each, the lock first, the version row FOR UPDATE, DDL, the doctor on the version's definition in the same transaction (not_as_defined rolls back), the live catalog's digest, the bookkeeping rows and the log row; idempotent; each version checked in place inside its transaction, ADR-0043 §G as amended 2026-09-27: its objects all present as defined → recorded as a baseline with no DDL, none present → applied, some present or one reshaped → MigrateRefused("objects_missing") naming them; with nothing pending and no checksum recorded, the first stamp while doctor --strict is green, else unverified with the findings), baseline (the doctor confirms the objects of the version asked for, or of the highest version they match, then that version and every one below it is recorded with the live catalog's digest and nothing is created or copied), plan (the statements, nothing written), dry-run (ADR-0062 unit 5: everything an apply does in one transaction, rolled back; the same locks; on framework tables with no version row the baseline migrate --baseline=if-missing would record, adoption on the report). Every apply, baseline, restamp and dry run opens on ensureBookkeeping and refuses a row naming another preset (naming_mismatch). migrateStatus (the row, the pending list, the bookkeeping's shape and agreement, judgeCatalog's verdict `ok
catalog.ts The catalog checksum (ADR-0062 unit 5): sha256 over the structural tuples of the framework objects as the doctor's walk (readCatalog) reads them, sorted; stamped on durable_schema.catalog_checksum and compared by migrate status and verify. catalogTuples is the pure half.
refusals.ts MIGRATE_REFUSALS (ADR-0062 §7, in ADR-0060 decision 16's row shape): every sentence MigrateRefused carries, keyed migrate.<code>[.<variant>], read by every throw site through migrateRefusal(id, parts, details); findMigrateRefusal for durable-sdk explain; assertMigrateRefusals the rule the core's registry passes. A leaf.
render-data-model.ts renderDataModel(definition, naming, { history, schema }) (ADR-0043 decision 5 as landed, FW-074): the framework tables as Markdown from the one definition, every table as the preset spells it with its columns, primary key, indexes (a partial one's predicate, a non-btree method) and foreign keys, the enums, the append-only guard, each object with the version it first stood in read off MIGRATIONS; spliceDataModelBlock puts it between a page's DATA_MODEL_MARKERS (the host's pnpm gen:data-model writes docs/data-model.md); the CLI verb schema emit --docs is deferred with the extraction.
doctor.ts The system catalogs (pg_class, pg_attribute, pg_index, pg_constraint, pg_sequence, pg_proc, pg_trigger; never the privilege-filtered information_schema) against a version's catalog: tables (logged, no row security), columns (type, nullability, the stored default expression, precision), indexes (columns, uniqueness, btree, whole, valid), foreign keys (columns, target, actions, validated), enums, the sequence (bigint, owned by its column), the function (language, body), the trigger (its function, no WHEN, enabled, BEFORE UPDATE OR DELETE FOR EACH ROW). strict adds the recorded version and its checksum (newer when the row is above the package's latest), the durable_migrations audit rows, and no extra column, constraint, index or trigger on a framework table. Since FW-047 warnings: advice off the server's settings (idle_in_transaction_session_timeout at 0, isZeroDuration; since FP-006 the connecting role's statement_timeout and lock_timeout unset, 0 or above SERVER_BOUNDS, 20 s and 5 s, read off the session and pg_roles/pg_db_role_setting by serverBoundsWarnings, durationMs the GUC grammar), one line each with the role's ALTER ROLE, moving neither ok nor strict. Read-only. Since ADR-0076 D09 (SOC-16) the report carries truncateTrigger (the statement-level BEFORE TRUNCATE guard of version 30, judged as the row trigger is) and two more warning readers: ledgerGuardWarnings (UPDATE, DELETE and TRUNCATE on the ledger each need an enabled BEFORE trigger of the right level calling the append-only function, read off pg_trigger's tgtype; one unguarded is said by name with its remedy) and ledgerGrantWarnings (the connecting role owning the ledger, its head or the trigger function, or holding UPDATE, DELETE or TRUNCATE on the ledger or DELETE or TRUNCATE on its head, each a line with the exact ALTER … OWNER TO durable_owner or REVOKE … FROM <role> statement, never run; LEDGER_OWNER_ROLE).
probe.ts The boot-time read: recorded version (0 when absent), naming, append-only guard.
stores/ postgresStores(connection, options) (ADR-0051 §16; ADR-0043 §D as landed): every verb of the engine's Stores as plain SQL over the driver, one module per family (runs, steps, waits, due, ledger, outbox, settings, retention, read-model), the names in names.ts (the preset's tables and columns, TIMESTAMP(3) read and written through UTC under prisma-legacy, the enums cast), every SQLSTATE in failure.ts (a StoreError of the failure's kind, classifyFailure), the probe over probe.ts. Proved by the conformance suite under both namings and by the engine end to end (below). Since FW-095 (the audit of 2026-10-09 B1) runs.createRunWithKey off a cap and runs.finishRun are one statement each and no transaction: the key's insert-if-absent gating the run's insert in one WITH, the fenced update gating the facts' insert in another, each as atomic as the transaction it replaced and bounded by the pool's per-query ceiling alone; the slot's create keeps its transaction.

Not here: the Prisma bridge, memoryStores, a UTC type parser on the pool (the store reads and writes TIMESTAMP(3) through AT TIME ZONE 'UTC' in its own statements; a global pg.types parser would change every consumer of the host's pg).

A host without Prisma#

import { createDurable } from "@durable-sdk/core";
import { openPool, postgresStores, runMigrations } from "@durable-sdk/postgres";

const driver = openPool(process.env.DATABASE_URL!, { max: 10 });
await runMigrations({ driver, schema: "durable", naming: "snake" }); // once, at deploy
export const durable = createDurable({
  stores: postgresStores({ driver }, { naming: "snake", schema: "durable" }),
  // ...the catalog, the partition rule, the platform, the identity
});

postgresStores takes { driver }, { pool } (a pg.Pool you own) or { url } (a pool it owns and close() ends), each with an optional read half of the same form (readDriver, readPool, readUrl: a read replica over the same storage, over which the store carries the read model a second time as readReplica, what the core's consoleReads() answers the console while every door reads readModel; a replica that cannot be reached answers the writer, logs store.replica.fallback once and keeps the family's next REPLICA_PROBE_EVERY reads on the writer before asking the replica again, and a read the standby cancelled with a recovery conflict (40001) is answered from the writer for that read alone under its own bound, logged store.replica.conflict, no window opened (CL-003); beside it the replica family (ADR-0078 D04): lag() reads the replica's replay position and last replayed commit against the writer's position and clock, one statement each side, the replica's failure a value (down with its reason and the driver's code), and fallback() the mark the routed family keeps (the window's count, the recovery conflicts the writer answered and the last one's moment), no statement; a half naming the writer's own pool or URL binds one driver; FW-110); naming is snake (the SDK's own schema) or prisma-legacy (tables Prisma created), schema the bookkeeping schema (durable), lockTimeoutMs and statementTimeoutMs the SET LOCAL bounds of its transactions, headMode what the ledger's append chains from (head by default since ADR-0076 FP-023, 2026-10-12: the scope's LedgerHead where it is usable, the tail otherwise; reconcile the tail on every append, the head repaired from it, the default from the ledger fold to FP-023 and the option for a database a writer that moves no head may still append to; since FP-023's re-landing the same day both run on the pool and no transaction: the read of the head and the tail and the one write statement that locks the head row FOR UPDATE, holds it to what the read answered, fences the attempt under what the head's wait left of lockTimeoutMs (the two waits share the budget), inserts the row (its seq taken behind the lock) and moves the head, committing as it ends, so no lock outlives a round trip and a client killed mid-append leaves nothing held; since the head memo (FP-023 as amended 2026-10-30) a store under head keeps the head it last landed per scope, in a bounded Map, and an append alone on its scope in the process skips the read, the write holding the head to the memo and the row chained from standing (the same cur and origin gates), a miss dropping the memo, said once per scope per store (ledger.head_memo_missed, info, with the memo's headSeq), and reading first under what the wasted write left of the one lockTimeoutMs (a miss never waits two budgets on the head row), the memo written from a landed write's own answer alone and dropped on a moved or a fenced answer, on any error and on a LedgerHeadContradiction, never read under reconcile; a scope's first append and a compare miss under contention take the locking transaction, each lock statement under what the waits before it left, ledger.append.statements the exact pin, 1), and readWorkMemMb (8) the SET LOCAL work_mem of the two health summaries' own transactions, the reads whose Sort over the day's rows spills at a server's default (4 MB on a managed Postgres), the setting the block's alone; a single-statement verb runs on the pool outside any transaction and carries statementTimeoutMs as pg's per-query query_timeout instead, a client-side bound that rejects the call and cancels nothing on the server; the connecting role's statement_timeout (20 s) and lock_timeout (5 s), SERVER_BOUNDS of the doctor (FP-006; ADR-0076 D04, ALTER ROLE <app role> SET …), are the server's own bounds on such a statement, and every transaction of the store, the ledger's append and the migrator (MIGRATE_DEFAULT_TIMEOUT_MS 0, no server-side cut inside a version; MIGRATE_DEFAULT_LOCK_TIMEOUT_MS 10 s) sets its own SET LOCAL inside the block. listen (absent or true by default; ADR-0076 FP-035) is whether a waiter may hold a LISTEN session on the run landings' channel (LANDING_CHANNEL, durable_run_landed; the finish statement says the run's id with pg_notify inside its own RETURNING, the resumer's abandoned mark the same): the store judges it by one probe on the first await, remembered for the process and never read off the URL's text (a session on LISTEN told by a pg_notify sent through the pool within LISTEN_PROBE_MS, 1.5 s; a direct connection hears it in milliseconds, a transaction pooler such as a managed database's pooled endpoint or PgBouncer never, so the waiter polls there), and listen: false answers false with no probe; the session is the driver's listen (one pool.connect() client of pgDriver, counted against the pool as any checkout is, its LISTEN and UNLISTEN outside the tally), absent on a host's own driver, where the store answers false too. The verdict is said once, store.listen.probed. namedStatements on a { pool } or { url } connection (NP-001, ADR-0043 amendment 2026-10-30; true by default) is whether the hot verbs' statements ride named: false is the host's switch for a transaction pooler that keeps no named prepared statement across its server connections (max_prepared_statements = 0, PgBouncer before 1.21), under which every statement is unnamed as before; a value that is not a boolean, or the key beside { driver } (a host's own driver names its statements itself), is refused by name, and the store's probe refuses the connection by name when the driver's namedStatements() found a named statement unknown across its server connections.

Running against a database#

import { doctor, openPool, runMigrations } from "@durable-sdk/postgres";

const driver = openPool(process.env.DATABASE_URL_UNPOOLED!);
await runMigrations({ driver, schema: "durable", naming: "snake" }); // a fresh host
await runMigrations({
  driver,
  schema: "durable",
  naming: "prisma-legacy",
  mode: "baseline",
}); // tables that predate the package
const report = await doctor({
  driver,
  schema: "durable",
  naming: "prisma-legacy",
});
await driver.close?.();

The durable-sdk CLI (packages/durable-cli) is these calls behind migrate, migrate plan, migrate --dry-run, migrate status, migrate restamp, migrate down --to <n> (migrateDown, ADR-0062 unit 6: the versions above n taken down one transaction each, refused down_irreversible, down_refused or deployed_ahead by name; since FW-027 every table a version's guards count is locked ACCESS EXCLUSIVE before the count under the transaction's lock_timeout, so no row lands between the count and the drop, and the in-place check reads a mismatch on an enum's labels as a reshape of the value the version appended, so a database whose labels stand out of order is refused objects_missing and never baselined), doctor and verify (its other verbs, the peer, environment, replay, explain and dev commands, are the CLI's own, packages/durable-cli/README.md). Bookkeeping lives in DURABLE_SCHEMA (durable by default), which a host's ORM never sees: Prisma's drift diff ignores a schema its datasource does not declare, exactly as this repository's warehouse schema shows. BASELINES.md names the version each known host's tables were adopted at and the checksum its baseline records.

Workspace mechanics#

exports["."] points types at src/index.ts and default at dist/index.js while the package is private: the app and the tests resolve the source through the root tsconfig.json paths, and the CLI's built dist (plain Node, no TypeScript loader, because it runs inside the Vercel build and CI) resolves the built dist of this package. pnpm durable-sdk:build at the root builds the four packages the CLI runs on (@durable-sdk/core, this one, @durable-sdk/vercel and the CLI); publishConfig replaces the exports with the dist pair on publish. pnpm --filter @durable-sdk/postgres check runs typecheck, lint, build and pack:check (publint and attw on the packed tarball); pnpm check:sdk runs it for every SDK package.

Proofs#

  • tests/durable/migrator-leaves.test.ts: both presets over a representative table, the enum cast, the timestamp type, names.
  • tests/durable/postgres-migrations.test.ts: v1 under prisma-legacy is the Prisma migrations statement for statement (columns, indexes, foreign keys, enums, function, trigger); the checksum pinned to BASELINES.md.
  • tests/durable/postgres-migrations.test.ts, the downs (ADR-0062 unit 6): renderReverse is renderDelta's exact inverse under each preset (the same objects, reversed, every statement a drop), v12's down the declaration column with its guard, v11's down eight and seven DROP INDEX, v4's irreversible under prisma-legacy with the decision's sentence and rendered under snake with the waits' guards, every guard a SELECT count(*) with the ledger's alone not overridable, each down's prisma-legacy checksum the one BASELINES.md pins.
  • the schema guard: v1.ts … v32.ts byte for byte the base branch's (a shipped version is never edited; its down lives in down.ts), the base named, the down checksums pinned.
  • tests/durable/postgres-migrator.test.ts: over a recording driver, every transaction the migrator opens takes the advisory lock first and v1's DDL runs between the version guard and the bookkeeping rows (the doctor on the version and the catalog digest between them); a down's transaction reads the version row FOR UPDATE, the marker and the guards before its first drop, runs the drops contiguously, the doctor on the previous definition after them, then lowers the instance row, deletes the audit row, moves the version row and appends the log row; down_irreversible is judged over the whole range before any transaction opens.
  • tests/durable/migrator-leaves.test.ts: MIGRATE_REFUSALS both ways (every row thrown at a site, every site a row, the class constructed in the leaf alone), the CLI's words for migrate status, --dry-run and restamp, and the marker key pinned to the core's.
  • tests/durable/postgres-stores.test.ts: every verb's statement text under both namings as a snapshot per verb (a recording driver), the failure mapping, the options and their refusals, the mirrored core words.
  • tests/conformance/postgres.test.ts and postgres-snake.test.ts: the store conformance suite verbatim on postgresStores under prisma-legacy (the app's migrated throwaway database) and under snake (a schema the migrator creates in-process), its SQL tier pinning the next minted id through the ids option; tests/conformance/postgres-stores.test.ts (three files with postgres-stores-primitives.test.ts and postgres-stores-schedule.test.ts, one part of the suite each) and postgres-stores-snake.test.ts: the engine's fifteen promises on the store under each naming; tests/pg/postgres-stores.pg.test.ts: the engine on the store through the host's own workflows.
  • tests/pg/durable-postgres.pg.test.ts (a local DATABASE_URL, throwaway databases): apply twice under both presets, the baseline over a Prisma-migrated database creating nothing in public, the two catalogs identical, the CLI over the same paths (and its connection precedence), a rival migrator under the lock, the driver's transaction contract, the catalog read by a role that cannot see the tables through information_schema, the doctor red on every drift it is asked to see (trigger, function body, defaults, indexes, foreign keys, sequence, persistence, row security, extras, the bookkeeping) with fixing SQL that restores each, and the migration controls (ADR-0062 unit 5): a v1 bookkeeping reshaped in place and judged idempotent, the first stamp, migrate status on ok, a disagreement, a drift, a cleared stamp, a held lock and a pending version, a dry run rolled back whose checksum the real apply then stamps, restamp refused and logged, not_as_defined on a planted version, naming_mismatch, naming_unjudged, lock_timeout at the bookkeeping's reshape, unknown_kind, a dry run over Prisma's tables with no bookkeeping, and the checksum's indifference to a host's objects and to the catalog's row order; and migrate down (ADR-0062 unit 6): the round trip under prisma-legacy (down to 4, down_irreversible at v4 with nothing taken down, up again to the first apply's checksum, Instance.schemaVersion lowered) and under snake (down to 0, every framework relation gone, the bookkeeping and its log kept, up again to the same checksum), a guard's refusal over rows with the versions above untouched, --accept-loss recorded on the log row's applied_by, the ledger's guard never overridden, deployed_ahead from a planted marker (above the target, at it, unrecorded, absent), a rival that moved the row under the lock (version_conflict), and a planted down that leaves the catalog wrong (not_as_defined, rolled back).
  • CI (.depot/workflows/ci.yml): the same on the checks job's database and on two fresh ones (migrate twice, doctor --strict, migrate status ok, migrate --dry-run with nothing to apply, then the up/down/up round trip: migrate down --to 4, under prisma-legacy down --to 3 exits 1 with down_irreversible: v4, under snake down --to 0, migrate again landing on the first apply's catalog checksum, doctor --strict green, under both namings); verify, doctor --strict and migrate status against production after every promotion.