@durable-sdk/testing

The memory stores, testDurable, the fakes, the replay, the conformance suite, the guard pack.

Open in CursorView as Markdown

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

The Durable SDK's test kit (ADR-0046 §B, §M step 3b; ADR-0072 for the packaged store conformance). Private, 0.0.0, Apache-2.0; depends on @durable-sdk/core alone (the store package's driver and store shapes are imported as types, a devDependency). Proved in the host repository by tests/durable/harness.test.ts, tests/durable/memory-stores.test.ts, tests/durable/bundle.test.ts and the conformance runners under tests/conformance/.

  • memoryStores(): the engine's store interface, every family (RunStore, StepStore, LedgerStore, OutboxStore, SettingsStore, RetentionStore, ReadModel, WaitStore, DueStore), over plain maps, with the semantics the Postgres store has where the engine could tell the difference: one append at a time per scope, the attempt fence on the RUNNING run inside the append, occurredAt chosen after the fence and handed to the engine's hash with the body inserted, the scope's head moved in the same step, the run and its key created together (a taken key rolls the run back and answers the winner), facts inserted if absent by key in the transaction that finishes the run, every fenced verb answering { ok: false } instead of throwing. What comes back is a copy, never the stored row. state exposes the tables, reset() empties them, failNext(error) makes the next transactional verb throw error before it writes (the pool timed out, the connection dropped), and appendOnly.enabled stands in for the ledger trigger's switch. It binds no classifyFailure: a planted error is thrown as it is and, not being a StoreError, is never retried by the engine, so a test that wants the one retry plants a StoreError of a retriable kind (timeout, lock_timeout, conflict); naming a driver's SQLSTATEs is the database store's job (@durable-sdk/postgres's stores/failure.ts, every code to its kind, classifyFailure).

  • testDurable(options) (ADR-0051 §3): the engine over memoryStores() behind one call, bound through bindDurable (never the process's registration: two harnesses in one file are two worlds), with a fake platform (every wake recorded in wakes(), every promise handed to keepAlive settled before a verb answers, selfTicks off, now the harness clock) and a session factory answering {}, and the options a host binds (catalog, partition, scope, principal, redaction, reverters, tickTasks (default the core's schedules task), retention, workflows, listeners, sessions, platform, environment, scrub, steps (strictSteps its deprecated alias), schemaPolicy (the host's "refuse" unless given; ADR-0076 FP-016: a test of what a warn rule lets through names it, { drifted: "warn" }), clock: { start }, logs). run(definition, input, options?) executes as system:test; emit queues a fact; under(fn) runs any engine call under the instance; tick() is one whole tick (runDispatchTick: the tasks, the lanes, the resumer's passes) at the clock's moment; advance("3h") moves the clock and runs a tick at every minute crossed (at most maxTicks), so a delayed fact, a schedule's slot, a timer and a deadline fire when due, and answers the ticks run (the grain is the minute: a fact due mid-minute lands at the following minute's tick, never earlier, and a sub-minute move runs no tick); runs, detail, steps, outbox, waits, ledger are the console's views (ledgerEntries for the last); listeners: "none" runs no lane; logs: "silent" (default) keeps the engine's lines off stdout (configureLog({ print }), put back by dispose()), logs: "collect" keeps them for logged() instead (the uncaptured bookkeeping no step row holds included: step.replay_missed, run.fenced, step.replayed; the sinks swapped and restored by dispose()); crashAfterStep(seq) arms one crash on the memory store (ADR-0060 decision 1: once the step row at that seq lands COMPLETED the attempt loses its lease, run answers in_progress, fenced: true with the run RUNNING, and advance past durable.leaseMs lets the resumer claim it as the next attempt; crashBeforeFinish() arms the other crash, at the attempt's finishRun once the body returned whole, so the resumed attempt replays every row and runs the trailing code again; crashInsideStep(seq, { after: "write" }) arms the third (ADR-0063 B07), inside the step: the attempt loses its lease after the step's write and before its row, at the ledger append that records a write the step row holds the intent of (the row STARTED with its pending entry, the world written, no ledger row: the next attempt reconciles it from the world) or else at the updateStep that would land the row COMPLETED (refused, the row left STARTED: a plain step's body runs again); all three held to a named workflow's run with { workflow }; crashed() says which attempt it took and where (at: "step" | "finish" | "inside"); one harness collects the engine's lines at a time, a second refused while one stands); reset() empties the world and puts the clock back; dispose() refuses every later verb, the readers included. The clock rule: advance moves the bound now, which the engine reads for every moment it decides on; Date.now() is left alone (the engine's stopwatch: budgets, leases, timeouts). Proved in the host repository by tests/durable/harness.test.ts.

  • seed(rows) on memoryStores() and on the harness (ADR-0051 §8): rows the world left behind put into the tables as they are (runs, keys, steps, entries, events, waits), each with the defaults a store would fill and an id minted when none is given, a moment a Date or an ISO string, the ids answered per table; a ledger row is chained as the append chains it (the scope's previous verified row, else genesis; the head moved), so verifyLedger holds over what was seeded. A database store refuses the verb by name (seedRefusal(name): postgresStores' seed throws naming the store).

  • redriveTicketForTests() (ADR-0041 item 5): the engine's redrive ticket for a test that drives a FAILED run to another attempt through execute (redrive: redriveTicketForTests()) instead of the run.redrive workflow; the one mint beside that workflow, held so by the host's invariants guard.

  • replayRun(bundle, definition | name, options?) (ADR-0051 §8): a run bundle (GET runs/:id/bundle, the console's runBundle) seeded into the caller's harness, or one opened over memoryStores() at the bundle's moment, and redriven through the engine exactly as the console's run.redrive would (durable.operator.redrive.run: the claim by id as attempt + 1, the recorder serving every COMPLETED row stored whole and re-invoking the step that failed); answers { outcome, sentence, failedStep?, error?, redrive, detail, steps, ledger, harness }, the outcome the engine's own value (landedResultOf), the sentence describeResult's and failedStep the newest attempt's failed row ({ attempt, seq, name, error, errorCode }, the code what a generated replay test's "reproduces" compares with the bundle's, ADR-0063 B12). A bundle whose workflow is not the definition's, one no module registered, or one the API's bounds cut (truncated.steps or .ledger above zero: a seed of the rest would be a run the engine never had) is refused with the reason (ReplayRefused) before anything is seeded. A bundle whose siblings name another owner of the key seeds the key row to that owner and answers the engine's refusal (redrive: { status: "refused", reason: "superseded by <id>; not redrivable" }), nothing invoked. A WAITING run's bundle seeds its wait rows and answers redrive: { status: "refused", reason: "the run is WAITING" }, nothing fired: fire the wait on the returned harness (harness.under(() => harness.durable.operator.signal.run(runId, { token, payload, actor, requestId })), then harness.advance("1m") for the resumer) and read the run again. The provider calls run against whatever the test bound; no network, no database. What durable-sdk replay <runId> writes a test around. The host's own rows (ADR-0051 §8 follow-up): a bundle carries under host what the host's bundleHost composer answered ({ version: 1, tables: { <name>: { key, rows } }, truncated?, error? }, the tables by the host's names), and seedHost?: (host, harness) => Promise<void> is the host's hook that puts them into its doubles, called after the engine's seed and before the redrive, never when the bundle carries none; its optional check(host) property is asked before the engine's seed, so what the host would refuse is refused with nothing seeded on either side; with the hook given, a host part not shaped as one, one the composer could not answer (error) or one the bound cut (truncated) is refused before any seed. This package names no host table; without the hook the host field is not read at all, whatever it holds.

  • prove(definition, options) (ADR-0072; the proof itself ADR-0060 decision 1): the double-run proof of one registered definition, run on a testDurable() over memoryStores() under logs: "collect" with the host's fakes installed. The clean run first (the input read fresh through options.run, ctx.step, ctx.poll and ctx.batch observed so what the body got back is judged against the row attempt 2 would replay, ADR-0060 decision 8, and every output held under the stored cap, decision 9), then the same run crashed and resumed at every boundary the memory store's seams offer: at each step's fenced insert (crashBeforeStep, FW-090), after each step's COMPLETED row (crashAfterStep; for a read step declared completion: "behind", whose completion rides the next boundary's statement, FP-011 as landed, at that statement before it lands, the row left STARTED and re-invoked by contract, which the proof admits for that step alone and names in its finding text), at the finish (crashBeforeFinish) and inside each step the clean run wrote the host's store or called a provider under (crashInsideStep, one boundary per recorded write's record and one at the row; ADR-0063 B07, FW-015), each claimed by the resumer past the lease and judged: COMPLETED at attempt 2, every row attempt 1 completed served and nothing invoked twice, no memo lost, the fakes' provider counts per step equal to the clean run's (a count that grew names the fake, the method and the step, or says the call sits outside any step before the boundary it first grew at), the host's writes under the crashed step not made again, and after a lost record no provider write made again (the read phase adopts what the write landed). It answers a Proof (ran, clean, steps, hostSteps, providerSteps, calls, the boundaries with their problems, the clean run's services, shape and bounds findings, ok), every finding a sentence with its remedy (problemsOf). What a host hands in (ProveOptions): its harness (or a thunk answering it), its run of the observed definition (the input, the client a route would hand), fakes (its connectors' recorders: callsByStep() and writesByStep(), every call filed under the step it was made under or OUTSIDE_ANY_STEP, the key this package spells), seedWorld (what puts a definition's world into its doubles after every reset, required for a definition that carries one) and hostWrites (the name a finding calls its store and the write journal, each row a step and a statement). The judges are exported beside it for a guard's own reading (judgeShape, judgeBounds, listedVerdict under the guard's list name, countDiff, hostWriteDiff, the boundary counters), so a host holds a listed definition to the sentence its run says and its coverage to a floor that only rises. A host's one binding names the seams once (the first host: tests/helpers/replay-proof.ts) and its guard proves every registered definition through it; the pure judges are proved in tests/durable/prove.test.ts.

  • recordingFetch, replayFetch, checkFake (ADR-0072 D08, TQ-007): provider cassettes, so a fake's claim about a provider is held to a recording that carries a date. recordingFetch(fetch, { provider, name, keep, paths }) is a fetch over the real one that keeps each exchange as shapes, never values (an object's keys each mapped to its shape, an array as its first element's, a scalar as its type; the one value that survives is an enum word under a key keep names, as { "$literal": "pending" }; the path's ids replaced through paths's templates, the query's values shapes, no header ever read), with cassette() and save(dir); loadCassette(file) reads one back validated, cassetteClean(cassette, { keep }) refuses what a hand could have put in (a literal outside the allowlist, an e-mail-shaped literal, a literal under an address-looking key, a literal longer than an enum word, an id-looking path segment) as sentences; replayFetch(cassette) answers a request from the matching exchange with the shape filled per type (fillShape: a number 1, a boolean true, a string its own key's name, a date-named key an ISO moment, an enum word itself), so a client runs without the network; checkFake(cassette, handlers) runs every recorded exchange through the host's handler for its <METHOD> <path> (fake, the fake's answer; read, optionally, how the host's own client reads the recording, run over a replay of that exchange, so a fake that answers a reduced shape is held to the wire through the module that knows it) and answers sentences with the date (compareShapes: a key the fake answers not, a key the provider did not, a type that differs, null against a value among them, a status that differs, an exchange no handler checks), never a throw on a finding; withFetch(fetch, fn) swaps the process's fetch for the call. Proved by tests/durable/cassette.test.ts; used by the host's tests/cassettes/.

  • @durable-sdk/testing/conformance (ADR-0072): the store conformance suite as a product of the SDK. storeConformance(name, makeStores, traits, api) is the verb tier (ADR-0043 §I): every verb of every family (RunStore, StepStore, LedgerStore, OutboxStore, SettingsStore, RetentionStore, ReadModel, WaitStore, DueStore) driven and checked through the verbs, the operator workflows' verbs, the retention rules, the console's reads, the relay's verbs, the due items and, where the double declares it, the SQL tier (the duplicate-id and bounds cases) and the concurrency tier (two writers racing for one slot). makeStores answers { stores, harness, reset } (StoreDouble; writer beside it for a store split over a read half), traits what the double is (StoreTraits: MEMORY_TRAITS for a store over maps, POSTGRES_TRAITS for a store over a live database; the suite's first case holds the declaration to its probe through judgeConcurrencyDeclaration), and api the runner's own doors (TestApi: { describe, it, expect, beforeAll, beforeEach } as vitest spells them; the package imports no runner, and a hook left out is refused by name before any case is collected). The harness over a double (StoreHarness: the states no verb produces, the reads no verb offers, the planted failure, the append-only switch, the pinned ids and the transaction spy of the SQL tier) is memoryHarness(stores) over memoryStores() and postgresHarness({ driver, stores, naming?, pins? }) over postgresStores() and the driver it was built on (the spies this module's own, restoreSpies(driver) between cases; the trigger switched by withAppendOnlyDisabledVia, the one place this package turns it off; frameworkTablesOf and wipeFrameworkTablesVia the cleanup between cases; pinnedIds(cuid) what the store's ids option reads). durable-sdk test store --url <postgres url> runs it against a database through the host's vitest, with the ledger's append-only trigger, the catalog's drift verdict and the engine's round trip over the store beside it; a host's own runners call it the same way (the first host: tests/conformance/).

Both conformance suites in the first host's repository run on this store: the verb tier (this package's storeConformance) and the fifteen engine-level promises (tests/conformance/suite.ts, the host's: it drives the host's modules and reads its manifest on disk), beside postgresStores() under both namings, three doubles, so none drifts (a host's transitional Prisma store and its two runners left with it, ADR-0062 unit 4). The suite's concurrency tier (ADR-0043 §I; FW-024) is skipped on this store by its declaration and reported as skipped: MEMORY_CAPABILITIES says rowLocks: false and concurrentTransactions: false, since a double over maps has no row a FOR UPDATE could block on and never holds two transactions open at once (its appends queue per scope in-process, every compare-and-set verb decides with no await between its read and its write), and the suite's first case holds that declaration to its probe. A pass here proves verb semantics, never isolation. The fake adapters the suites and testDurable() share are this package's (fakePlatform with killAfter(ms) and a recorded wake, fakeSessions(client) with opened and missing, fakeManifest() with modules and loads, and plantAppendFailure(stores), one plantable failure on the ledger's two append verbs, and plantBoundaryFailure(stores), one per step-boundary verb (insertStepFenced, updateStep, finishRun, claimEvent, deliverEvent), before the write or after it with the answer lost, for as many consecutive calls as said; FP-005); testDurable({ stores }) binds the harness over any store (memoryStores() by default; a database store keeps its rows across reset(), and seed is refused by the store's name) and exposes the controls (sessions, killAfter, failNextAppend, failNextBoundary, loseNextCreateAnswer (FP-008: the next run insert lands and its answer is lost), crashAfterStep, crashBeforeFinish and crashInsideStep with crashed, logged, peers.override, manifest). The engine-level suite is the host repository's (tests/conformance/suite.ts, run on this package's memoryStores() and on postgresStores() under both namings, three doubles), not packaged (it drives the host's own modules; the extraction is paused, ADR-0046 §M steps 8–10); the store suite is this package's since ADR-0072 (@durable-sdk/testing/conformance, above). The fake connectors name a host's interfaces and live in the host (the first host: tests/helpers/fakes).

  • @durable-sdk/testing/guards (ADR-0072 D06; the doctor's third layer, ADR-0060 decision 18): the core guard pack, the rules whose law names no fact of one host, each a suite over a host's descriptor (DurableGuards, the host's durable.guards.ts: the routes convention and the pin, the heartbeat, the lease and the call window, the roots, the modules, the setup, and since GR-004 (ADR-0060 decision 14 as amended 2026-10-30) index.prismaSchemas, the Prisma schema per database client the host's graph-index walk reads as text, and since GR-006 index.doors (the route ladders with file, pattern, prefix, binding, handlers and bodies; actions, webhooks, starters, judges, hands) and index.refusals (the catalogue with module, export, prefix, judgedBy, and the callees), read as text by the host's graph-index walk into the index's doors[] and refusals[]; since ADR-0105 D09 the framework is one of react-router, vercel-functions and next, the routes directory is walked whole under the last two (its top-level files alone under react-router) with frameworkRoute matched against a file's path inside it, the pin is the framework's literal, export const config = { maxDuration: <n> } for the first two and export const maxDuration = <n> for Next, and a cron at /jobs/<name> is served by jobs.<name>.tsx, jobs/<name>.ts (through a vercel.json rewrite or at its own path) or jobs/<name>/route.ts by framework, FRAMEWORKS of the platform suite) and the runner's own test API (GuardApi: { describe, it, expect, afterAll } handed in; nothing here imports a runner). authoringGuards(host, api, { ts, primitiveNames?, holdouts? }) (the emit inside a step and beside a write, the fan-out, the caught step, the listener's value, the primitives barrel; the host hands its typescript in, so the package's runtime stays the core; the names and the holdouts off the descriptor's authoring where the deps hand none, authoringBindingsOf, so the doctor's spec judges what the host's own guard file judges), definitionsGuards(host, api, { durable, hostTables?, worldsExpected?, beforeReport? }) (the strict load and the engine's verdict per rule; answers the report), workflowIdentityGuards(host, api, { durable, listenerInput?, secretInputs? }) (every example keyed live, stored and re-keyed, the slots, the caps, the clock held still; answers what it read), refusalsGuards(host, api) (the registry, and the core's door modules where roots.packages carries the sources) and platformGuards(host, api) (the route literals, the lease arithmetic, vercel.json, the window) and, since GR-018 of ADR-0060 decision 14, graphGuards(host, api, { root? }) (the reaction graph's two index files held to the kit's walk, the index's shapes, the coverage floors every host holds, the walk proved on the pack's fixture). The rows are CORE_RULES (the same grammar as a host's the guard rules' registry, under its own literal; CORE_GUARDS the stems), read by durable-sdk doctor as text through the host's install (./guards/rules), coreRule(stem)(slug) minting each it's title and each assertion's remedy line as the doctor reads them back. A host runs a suite from a thin guard file of the suite's stem (the first host: one guard file per pack, each marked core: true in its manifest), or lets durable-sdk doctor write the spec under <tests>/.durable-sdk/guards/<stem>.test.ts; doctor --core runs the pack alone. The tree readers (sourceFiles, read, code, calls, findLines, importsOf, where), the parser helpers over a handed-in typescript (parserOf) and the fixed clock (withClockAt) ride the same subpath. The reaction graph's index walk and the workflow index's name walk ride @durable-sdk/testing/graph-walk (GR-018): walkTexts (pure, over texts in hand), walkGraphIndex, workflowIndexOf and indexFilesOf over a tree under a root, readWalkHost (the descriptor's roots, modules and index blocks read as text), coverageOf and coverageLine, the render as two-space JSON a caller formats; what durable-sdk index runs from any app directory and a host's gen:graph-index wraps.

Scenarios#

scenario(t, name, options?) (ADR-0072 TQ-003) is the readable shape of a workflow test over the harness, one per workflow, framework-agnostic: given a world, when something happens, expect what the console would show. The builder's three verbs accumulate and nothing runs until expect (or run, with nothing to judge); the answer is the collected rows (ScenarioResult: every run with its page, the ledger, the outbox, the open waits, the ticks, the host's provider counts, the attempt an armed crash took, and describeResult's sentence per executed run) for the assertions the DSL does not spell, in the test framework's own words.

import {
  advance,
  crashAfterStep,
  execute,
  scenario,
  tick,
} from "@durable-sdk/testing";

const t = testDurable({ catalog, clock: { start: "2026-09-28T12:00:00Z" } });

const result = await scenario(t, "a crash after the first step")
  .given({ settings: { "orders.flag": { on: true } } })
  .when(
    crashAfterStep(1, { workflow: "orders.place" }),
    execute(placeOrder, { orderId: "o1", requestId: "r1" }),
    advance(t.durable.leaseMs + 60_000),
    tick(),
  )
  .expect({
    runs: [
      {
        workflow: "orders.place",
        status: "COMPLETED",
        steps: [{ name: "orders.reserve", count: 1 }, "orders.charge"],
        output: { ok: true },
      },
    ],
    ledger: [
      {
        type: "order",
        resourceId: "o1",
        before: null,
        after: { status: "placed" },
      },
    ],
    facts: [
      {
        name: "order.placed",
        key: "order.placed:o1:r1",
        count: 1,
        delivered: true,
      },
    ],
    noFacts: ["order.failed"],
    waits: [],
  });

expect(result.crashed).toMatchObject({ attempt: 1, at: "step", seq: 1 });
  • given({ settings, facts, world }): settings rows written as they are, facts emitted as the world's past (queued until a tick; build one with fact(name, payload)), and a world handed to the seedWorld the scenario was made with (a host's seeder over its doubles and fakes; a world without one is refused by name).
  • when(...): execute(definition, input, options?) runs a definition as t.run does (the scenario's actor, system:test unless named); emit(name, payload, options?) queues a fact as a route would, a payload the door refuses failing the scenario with the first issue; signal(token, payload?, { runId? }) fires a signal on the last executed run or the one named; advance(duration) and tick() move the harness; crashAfterStep(seq, { workflow? }) and crashBeforeFinish() arm the memory store's crash for the action that follows; act(fn) runs any code over the harness.
  • expect({ runs, ledger, facts, noFacts, provider, waits }), judged in that order: a run by workflow, status (COMPLETED unless named), key prefix, the steps it walked (a name, or { name, status, attempt, count }) and fields of its output; a ledger row by resource type, id, step, operation and fields of its before and after images (null for an image that must be absent); a fact by name, key or key prefix, fields of its payload and whether it was delivered; noFacts the names the outbox may not carry; provider per fake, total, calls per method and byStep (step → method → count), read off the providerCalls and providerCallsByStep seams the scenario was made with (a host's fakes); an open wait by kind, workflow and step. Every list entry matches at least one row, or exactly count. A named field is compared by value as stored JSON; an unnamed one is not read.
  • A failed expectation throws ScenarioFailed, a plain Error: scenario "<name>": expected a run of orders.place COMPLETED; found 1 run: ["FAILED (orders.charge: card declined; steps orders.reserve:COMPLETED, orders.charge:FAILED)"], one or two sentences with the outcome's sentence (describeResult) and the fields that differed, never a dump (a value is cut at 300 characters); the rows read ride on the error as result. An action that throws fails the scenario naming the action.
  • judge(expectations, result), fieldsMatch(row, fields) and brief(value) are the pure half, for a host that judges its own rows.

A host binds the seams once beside its harness (the first host: tests/helpers/scenario.ts, scenario(t, name) over testDurable: seedWorld the definition worlds' seeder and, under fakes: true, the fakes' counts) and its scenarios live in tests/scenarios/, one file per workflow.