@durable-sdk/testing
The memory stores, testDurable, the fakes, the replay, the conformance suite, the guard pack.
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,occurredAtchosen 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.stateexposes the tables,reset()empties them,failNext(error)makes the next transactional verb throwerrorbefore it writes (the pool timed out, the connection dropped), andappendOnly.enabledstands in for the ledger trigger's switch. It binds noclassifyFailure: a planted error is thrown as it is and, not being aStoreError, is never retried by the engine, so a test that wants the one retry plants aStoreErrorof a retriable kind (timeout,lock_timeout,conflict); naming a driver's SQLSTATEs is the database store's job (@durable-sdk/postgres'sstores/failure.ts, every code to its kind,classifyFailure). -
testDurable(options)(ADR-0051 §3): the engine overmemoryStores()behind one call, bound throughbindDurable(never the process's registration: two harnesses in one file are two worlds), with a fake platform (every wake recorded inwakes(), every promise handed tokeepAlivesettled before a verb answers,selfTicksoff,nowthe harness clock) and a session factory answering{}, and the options a host binds (catalog,partition,scope,principal,redaction,reverters,tickTasks(default the core'sschedulestask),retention,workflows,listeners,sessions,platform,environment,scrub,steps(strictStepsits deprecated alias),schemaPolicy(the host's"refuse"unless given; ADR-0076 FP-016: a test of what awarnrule lets through names it,{ drifted: "warn" }),clock: { start },logs).run(definition, input, options?)executes assystem:test;emitqueues 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 mostmaxTicks), 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,ledgerare the console's views (ledgerEntriesfor the last);listeners: "none"runs no lane;logs: "silent"(default) keeps the engine's lines off stdout (configureLog({ print }), put back bydispose()),logs: "collect"keeps them forlogged()instead (the uncaptured bookkeeping no step row holds included:step.replay_missed,run.fenced,step.replayed; the sinks swapped and restored bydispose());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,runanswersin_progress, fenced: truewith the run RUNNING, andadvancepastdurable.leaseMslets the resumer claim it as the next attempt;crashBeforeFinish()arms the other crash, at the attempt'sfinishRunonce 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 itspendingentry, the world written, no ledger row: the next attempt reconciles it from the world) or else at theupdateStepthat 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:advancemoves the boundnow, 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 bytests/durable/harness.test.ts. -
seed(rows)onmemoryStores()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 aDateor 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), soverifyLedgerholds over what was seeded. A database store refuses the verb by name (seedRefusal(name):postgresStores'seedthrows naming the store). -
redriveTicketForTests()(ADR-0041 item 5): the engine's redrive ticket for a test that drives a FAILED run to another attempt throughexecute(redrive: redriveTicketForTests()) instead of therun.redriveworkflow; 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'srunBundle) seeded into the caller's harness, or one opened overmemoryStores()at the bundle's moment, and redriven through the engine exactly as the console'srun.redrivewould (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 sentencedescribeResult's andfailedStepthe 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.stepsor.ledgerabove 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 answersredrive: { 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 })), thenharness.advance("1m")for the resumer) and read the run again. The provider calls run against whatever the test bound; no network, no database. Whatdurable-sdk replay <runId>writes a test around. The host's own rows (ADR-0051 §8 follow-up): a bundle carries underhostwhat the host'sbundleHostcomposer answered ({ version: 1, tables: { <name>: { key, rows } }, truncated?, error? }, the tables by the host's names), andseedHost?: (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 optionalcheck(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 thehostfield 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 atestDurable()overmemoryStores()underlogs: "collect"with the host's fakes installed. The clean run first (the input read fresh throughoptions.run,ctx.step,ctx.pollandctx.batchobserved 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 areadstep declaredcompletion: "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 aProof(ran,clean,steps,hostSteps,providerSteps,calls, theboundarieswith theirproblems, the clean run'sservices,shapeandboundsfindings,ok), every finding a sentence with its remedy (problemsOf). What a host hands in (ProveOptions): itsharness(or a thunk answering it), itsrunof the observed definition (the input, the client a route would hand),fakes(its connectors' recorders:callsByStep()andwritesByStep(), every call filed under the step it was made under orOUTSIDE_ANY_STEP, the key this package spells),seedWorld(what puts a definition'sworldinto its doubles after every reset, required for a definition that carries one) andhostWrites(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,listedVerdictunder 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 intests/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 afetchover 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 keykeepnames, as{ "$literal": "pending" }; the path's ids replaced throughpaths's templates, the query's values shapes, no header ever read), withcassette()andsave(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'sfetchfor the call. Proved bytests/durable/cassette.test.ts; used by the host'stests/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).makeStoresanswers{ stores, harness, reset }(StoreDouble;writerbeside it for a store split over a read half),traitswhat the double is (StoreTraits:MEMORY_TRAITSfor a store over maps,POSTGRES_TRAITSfor a store over a live database; the suite's first case holds the declaration to its probe throughjudgeConcurrencyDeclaration), andapithe 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) ismemoryHarness(stores)overmemoryStores()andpostgresHarness({ driver, stores, naming?, pins? })overpostgresStores()and the driver it was built on (the spies this module's own,restoreSpies(driver)between cases; the trigger switched bywithAppendOnlyDisabledVia, the one place this package turns it off;frameworkTablesOfandwipeFrameworkTablesViathe cleanup between cases;pinnedIds(cuid)what the store'sidsoption 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'sdurable.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-006index.doors(the route ladders withfile,pattern,prefix,binding,handlersandbodies;actions,webhooks,starters,judges,hands) andindex.refusals(thecataloguewithmodule,export,prefix,judgedBy, and thecallees), read as text by the host's graph-index walk into the index'sdoors[]andrefusals[]; since ADR-0105 D09 theframeworkis one ofreact-router,vercel-functionsandnext, the routes directory is walked whole under the last two (its top-level files alone underreact-router) withframeworkRoutematched against a file's path inside it, the pin is the framework's literal,export const config = { maxDuration: <n> }for the first two andexport const maxDuration = <n>for Next, and a cron at/jobs/<name>is served byjobs.<name>.tsx,jobs/<name>.ts(through avercel.jsonrewrite or at its own path) orjobs/<name>/route.tsby framework,FRAMEWORKSof 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 itstypescriptin, so the package's runtime stays the core; the names and the holdouts off the descriptor'sauthoringwhere 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 whereroots.packagescarries the sources) andplatformGuards(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 areCORE_RULES(the same grammar as a host's the guard rules' registry, under its own literal;CORE_GUARDSthe stems), read bydurable-sdk doctoras text through the host's install (./guards/rules),coreRule(stem)(slug)minting eachit'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 markedcore: truein its manifest), or letsdurable-sdk doctorwrite the spec under<tests>/.durable-sdk/guards/<stem>.test.ts;doctor --coreruns the pack alone. The tree readers (sourceFiles,read,code,calls,findLines,importsOf,where), the parser helpers over a handed-intypescript(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,workflowIndexOfandindexFilesOfover a tree under a root,readWalkHost(the descriptor'sroots,modulesandindexblocks read as text),coverageOfandcoverageLine, the render as two-space JSON a caller formats; whatdurable-sdk indexruns from any app directory and a host'sgen:graph-indexwraps.
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 withfact(name, payload)), and a world handed to theseedWorldthe 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 ast.rundoes (the scenario'sactor,system:testunless 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)andtick()move the harness;crashAfterStep(seq, { workflow? })andcrashBeforeFinish()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 (COMPLETEDunless 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 (nullfor an image that must be absent); a fact by name, key or key prefix, fields of its payload and whether it was delivered;noFactsthe names the outbox may not carry;providerper fake,total,callsper method andbyStep(step → method → count), read off theproviderCallsandproviderCallsByStepseams 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 exactlycount. A named field is compared by value as stored JSON; an unnamed one is not read.- A failed expectation throws
ScenarioFailed, a plainError: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 asresult. An action that throws fails the scenario naming the action. judge(expectations, result),fieldsMatch(row, fields)andbrief(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.