workflow 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,6 +65,12 @@ Choose your framework in the
65
65
 
66
66
  ## Run anywhere
67
67
 
68
+ For application-level completion and failure reporting, `registerLifecycleHooks`
69
+ from `workflow/api` registers handlers in the workflow executor's host startup.
70
+ Calling it inside a workflow or step throws. Check the
71
+ [lifecycle hooks guide](https://workflow-sdk.dev/v5/docs/observability/lifecycle-hooks)
72
+ for supported framework/deployment combinations and stream cleanup requirements.
73
+
68
74
  Local development uses the bundled backend with no configuration. Deploy to
69
75
  Vercel for managed storage, queuing, scaling, and observability. To self-host,
70
76
  use the Postgres backend or implement a custom
@@ -1 +1 @@
1
- {"version":3,"file":"api-workflow.d.ts","sourceRoot":"","sources":["../src/api-workflow.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,6BAA6B,EAC7B,WAAW,EACX,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAQrD,eAAO,MAAM,MAAM,aAA+B,CAAC;AACnD,eAAO,MAAM,cAAc,aAAuC,CAAC;AACnE,eAAO,MAAM,UAAU,aAAmC,CAAC;AAC3D,eAAO,MAAM,aAAa,aAAsC,CAAC;AACjE,eAAO,MAAM,OAAO,aAAgC,CAAC;AACrD,eAAO,MAAM,sBAAsB,aACK,CAAC;AACzC,YAAY,EACV,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,wCAAwC,CAAC"}
1
+ {"version":3,"file":"api-workflow.d.ts","sourceRoot":"","sources":["../src/api-workflow.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,gBAAgB,EAChB,KAAK,EACL,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,6BAA6B,EAC7B,WAAW,EACX,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAQrD,eAAO,MAAM,MAAM,aAA+B,CAAC;AACnD,eAAO,MAAM,cAAc,aAAuC,CAAC;AACnE,eAAO,MAAM,UAAU,aAAmC,CAAC;AAC3D,eAAO,MAAM,aAAa,aAAsC,CAAC;AACjE,eAAO,MAAM,OAAO,aAAgC,CAAC;AACrD,eAAO,MAAM,sBAAsB,aAIlC,CAAC;AACF,YAAY,EACV,sBAAsB,EACtB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,wCAAwC,CAAC"}
@@ -8,5 +8,7 @@ export const getHookByToken = () => workflowStub('getHookByToken');
8
8
  export const resumeHook = () => workflowStub('resumeHook');
9
9
  export const resumeWebhook = () => workflowStub('resumeWebhook');
10
10
  export const runStep = () => workflowStub('runStep');
11
- export const registerLifecycleHooks = () => workflowStub('registerLifecycleHooks');
12
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBpLXdvcmtmbG93LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2FwaS13b3JrZmxvdy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFXQSxPQUFPLEVBQUUsR0FBRyxFQUFFLE1BQU0sNEJBQTRCLENBQUM7QUFDakQsT0FBTyxFQUFFLEtBQUssRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBRXJELE1BQU0sWUFBWSxHQUFHLENBQUMsSUFBWSxFQUFFLEVBQUU7SUFDcEMsTUFBTSxJQUFJLEtBQUssQ0FDYixnRUFBZ0UsSUFBSSwyRkFBMkYsQ0FDaEssQ0FBQztBQUNKLENBQUMsQ0FBQztBQUVGLE1BQU0sQ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ifecycleHooks must be called at host startup, not inside a workflow or step function. Register before handling workflow requests (for example, in instrumentation.ts on Next.js).');
13
+ };
14
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBpLXdvcmtmbG93LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2FwaS13b3JrZmxvdy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFXQSxPQUFPLEVBQUUsR0FBRyxFQUFFLE1BQU0sNEJBQTRCLENBQUM7QUFDakQsT0FBTyxFQUFFLEtBQUssRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBRXJELE1BQU0sWUFBWSxHQUFHLENBQUMsSUFBWSxFQUFFLEVBQUU7SUFDcEMsTUFBTSxJQUFJLEtBQUssQ0FDYixnRUFBZ0UsSUFBSSwyRkFBMkYsQ0FDaEssQ0FBQztBQUNKLENBQUMsQ0FBQztBQUVGLE1BQU0sQ0FBQyxNQUFNLE1BQU0sR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsUUFBUSxDQUFDLENBQUM7QUFDbkQsTUFBTSxDQUFDLE1BQU0sY0FBYyxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxnQkFBZ0IsQ0FBQyxDQUFDO0FBQ25FLE1BQU0sQ0FBQyxNQUFNLFVBQVUsR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsWUFBWSxDQUFDLENBQUM7QUFDM0QsTUFBTSxDQUFDLE1BQU0sYUFBYSxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxlQUFlLENBQUMsQ0FBQztBQUNqRSxNQUFNLENBQUMsTUFBTSxPQUFPLEdBQUcsR0FBRyxFQUFFLENBQUMsWUFBWSxDQUFDLFNBQVMsQ0FBQyxDQUFDO0FBQ3JELE1BQU0sQ0FBQyxNQUFNLHNCQUFzQixHQUFHLEdBQUcsRUFBRTtJQUN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tmbG93U3R1YigncmVzdW1lSG9vaycpO1xuZXhwb3J0IGNvbnN0IHJlc3VtZVdlYmhvb2sgPSAoKSA9PiB3b3JrZmxvd1N0dWIoJ3Jlc3VtZVdlYmhvb2snKTtcbmV4cG9ydCBjb25zdCBydW5TdGVwID0gKCkgPT4gd29ya2Zsb3dTdHViKCdydW5TdGVwJyk7XG5leHBvcnQgY29uc3QgcmVnaXN0ZXJMaWZlY3ljbGVIb29rcyA9ICgpID0+IHtcbiAgdGhyb3cgbmV3IEVycm9yKFxuICAgICdyZWdpc3RlckxpZmVjeWNsZUhvb2tzIG11c3QgYmUgY2FsbGVkIGF0IGhvc3Qgc3RhcnR1cCwgbm90IGluc2lkZSBhIHdvcmtmbG93IG9yIHN0ZXAgZnVuY3Rpb24uIFJlZ2lzdGVyIGJlZm9yZSBoYW5kbGluZyB3b3JrZmxvdyByZXF1ZXN0cyAoZm9yIGV4YW1wbGUsIGluIGluc3RydW1lbnRhdGlvbi50cyBvbiBOZXh0LmpzKS4nXG4gICk7XG59O1xuZXhwb3J0IHR5cGUge1xuICBSdW5Db21wbGV0ZWRIb29rUGFyYW1zLFxuICBSdW5GYWlsZWRIb29rUGFyYW1zLFxuICBXb3JrZmxvd0xpZmVjeWNsZUhvb2tzLFxufSBmcm9tICdAd29ya2Zsb3cvY29yZS9ydW50aW1lL2xpZmVjeWNsZS1ob29rcyc7XG4iXX0=
@@ -12,7 +12,9 @@ related:
12
12
 
13
13
  Registers global workflow lifecycle handlers, invoked by the runtime on the compute that records a run's terminal transition. Use it for best-effort centralized reporting, such as forwarding failed runs to Sentry, without wrapping each workflow body.
14
14
 
15
- Register early in the process lifecycle (in Next.js, `instrumentation.ts`) so handlers exist before the first run finishes. See the [lifecycle hooks guide](/docs/observability/lifecycle-hooks) for semantics and a full Sentry example.
15
+ Register in the host process that executes workflows, before it handles requests. In **Next.js 16.3.0 and later**, use `instrumentation.ts` as below. Earlier Next.js versions can process a cold Vercel invocation before async registration finishes. See the [framework support table](/docs/observability/lifecycle-hooks#framework-support) for registration locations and a full Sentry example in the guide.
16
+
17
+ App startup registration does not reach the standalone workflow functions emitted on Vercel by Nuxt 4 / Nitro v2, Astro, Nest, or the CLI `vercel-build-output-api` target. Those targets do not yet support this registration pattern. In Nitro v3, use a static import and synchronous server-plugin registration; Nitro does not await async plugins. Do not register from a workflow file or a step function.
16
18
 
17
19
  ```typescript title="instrumentation.ts" lineNumbers
18
20
  export async function register() {
@@ -36,6 +38,8 @@ export async function register() {
36
38
 
37
39
  Keep the dynamic import inside the `NEXT_RUNTIME === "nodejs"` guard. Next.js also compiles `instrumentation.ts` for the Edge runtime. A top-level static import of `workflow/api` pulls Node.js-only dependencies into that compilation and breaks webpack Edge builds, even if the registration call is guarded.
38
40
 
41
+ Restart `next dev` after editing instrumentation handlers: Next.js memoizes registration per process, so edits may not take effect until restart. Other hot-reloading hosts can re-register in the same process; keep the unregister function in process-wide state across reloads, or restart the server.
42
+
39
43
  ## API Signature
40
44
 
41
45
  ### Parameters
@@ -55,6 +59,8 @@ Returns a function that unregisters these hooks. Registrations are not deduplica
55
59
 
56
60
  Both handlers receive a `workflowName` string and a lazily hydrated [`Run`](/docs/api-reference/workflow-api/get-run) instance. Use the `workflowName` parameter to filter without a backend read; `run.runId` also requires no read. Accessors such as `run.workflowName`, `run.status`, and `run.returnValue` still fetch from the backend when used. In particular, `workflowName` is a string, while `run.workflowName` is a `Promise<string>`. Lazy access defers those reads rather than eliminating them.
57
61
 
62
+ Parameters come from the runtime's module copy, which may differ from the handler's copy in a bundled app. Avoid `instanceof` checks against `Run`, SDK errors, or your own bundled error classes. Use `WorkflowRunFailedError.is(error)` (`workflow/errors`), `FatalError.is(error.cause)` (`workflow`), `error.errorCode`, and the cause's `name` or your own serialized discriminator. See [identifying errors across module copies](/docs/observability/lifecycle-hooks#identifying-errors-across-module-copies) for an example.
63
+
58
64
  ### `onRunCompleted`
59
65
 
60
66
  Invoked when a workflow run completes successfully.
@@ -74,14 +80,18 @@ Invoked when a workflow run fails terminally (after any retries).
74
80
  | `params.workflowName` | `string` | The machine-readable workflow identifier, such as `workflow//./src/workflows/order//processOrder`. Available without a backend read. |
75
81
  | `params.error` | `WorkflowRunFailedError` | The persisted failure hydrated for reporting: `error.errorCode` carries the classification (e.g. `USER_ERROR`) and `error.cause` is the hydrated thrown value. |
76
82
 
77
- Unlike `run.returnValue`, `error.cause` defers readable stream I/O until consumption and revives abort signals as persisted snapshots without live subscriptions. Writable streams retain their normal forwarding pipe and lock-polling setup during hydration. If hydration fails, the cause is a generic `Error`, matching `run.returnValue`'s fallback. In `onRunFailed`, `run.returnValue` rejects because the run failed. Use `error.cause` to inspect or report the thrown value instead.
83
+ Unlike `run.returnValue`, `error.cause` defers readable stream I/O until consumption and revives abort signals as persisted snapshots without live subscriptions. Writable streams retain their normal forwarding setup, and writes still reach the failed run's stream or the parent run's stream for a forwarded writable. Custom serialization revives registered classes using the runtime's module copy; plain user-defined Error subclasses without custom serialization revive as generic errors with their name preserved. If hydration fails, the SDK logs the reason and the cause is a generic `Error`, matching `run.returnValue`'s fallback. In `onRunFailed`, `run.returnValue` rejects because the run failed. Use `error.cause` to inspect or report the thrown value instead.
84
+
85
+ On Vercel, the invocation's `waitUntil` scope drains background stream operations from **`error.cause`**, even after a handler returns or throws. It does not automatically cover pipes from `await run.returnValue` in `onRunCompleted`, or consumption scheduled after the handler returns. Await consumption and other reporting work in your handler. Other hosts may stop detached work when the process freezes or terminates.
78
86
 
79
- The invocation's `waitUntil` scope includes background stream operations from the hydrated cause, even after a handler returns or throws. Close or release stream reader and writer locks when finished so that work can settle. Await other asynchronous reporting work in your handler to keep it in the same lifetime scope.
87
+ <Callout type="warn">
88
+ A stream lock left open can keep the drain and lifecycle span pending until the function's maximum duration. Close or release reader and writer locks when finished; cancel a partially consumed reader in `finally`. See the [stream cleanup example](/docs/observability/lifecycle-hooks#stream-lifetime).
89
+ </Callout>
80
90
 
81
91
  ## Behavior
82
92
 
83
- - Handlers run on the host (full Node.js), never inside the workflow VM. Calling `registerLifecycleHooks` from workflow code throws.
93
+ - Register at host startup. Handlers run on the host (full Node.js), never inside the workflow VM. Calling `registerLifecycleHooks` from workflow or step code throws.
84
94
  - Handlers are fire-and-forget. They cannot delay or change the run's outcome, and the runtime logs and swallows a throwing handler. On Vercel, `waitUntil` keeps the invocation alive while handlers finish, subject to the invocation's duration limit. On other hosts, handlers run as detached work and may not complete if the host freezes or terminates the process after the response.
85
95
  - Delivery is best effort. Each registered handler is invoked at most once by the invocation that writes the terminal event. Callbacks are not retried if they throw or the process dies, so they may never run or may stop before completing. The [event log](/docs/how-it-works/event-sourcing) is the system of record.
86
96
  - Handlers fire only on the invocation that wrote the terminal event. Transitions recorded outside your app's compute (e.g. a run cancelled from the CLI or dashboard) do not fire handlers.
87
- - You can register multiple hook sets, and handlers run in registration order.
97
+ - You can register multiple hook sets, and handlers run in registration order. Registrations are not deduplicated; unregister a previous hook set before registering it again in the same process.
@@ -33,7 +33,7 @@ const parsed = parseStepName("step//./src/workflows/order//processPayment"); //
33
33
 
34
34
  | Property | Description |
35
35
  |----------|-------------|
36
- | `shortName` | The display name: the last segment of the function name. For nested steps like `processOrder/chargeCard`, this is `"chargeCard"`. |
36
+ | `shortName` | The display name: the last segment of the function name. For nested steps like `processOrder/chargeCard`, this is `"chargeCard"`. When same-named nested steps require disambiguation, the generated `~N` suffix is preserved (for example, `"chargeCard~1"`). |
37
37
  | `moduleSpecifier` | The module the step is defined in: a relative path (`./src/workflows/order`) or a package specifier (`@myorg/tasks@2.0.0`). |
38
38
  | `functionName` | The full function name including nesting (e.g. `processOrder/chargeCard`). |
39
39
 
@@ -62,11 +62,11 @@ The contract:
62
62
 
63
63
  ## The runtime integration (suspension fan-out fold)
64
64
 
65
- **On by default.** The suspension handler folds a **clean fan-out** (the suspension's eager `step_created` and `wait_created` writes) into `createBatch` calls of at most 32 events (mirroring the server's transaction budgets). Chunks of a larger fan-out commit **concurrently**: slot assignment is the World's, so parallel chunks race for slot ranges exactly like the pre-fold path's parallel single writes did, and per-entity conditions, not commit order, carry correctness. The fold only engages when the World implements `createBatch`, the run is on slot identity, and the suspension carries no attribute writes and no resilient step dispatch; everything else keeps the single-event path byte-for-byte. A suspension that also creates or disposes hooks still folds: hook writes are not batchable, so they go through the single-event path **concurrently** with the fold rather than ahead of it.
65
+ **On by default.** The suspension handler folds a **clean fan-out** (the suspension's eager `step_created` and `wait_created` writes) into `createBatch` calls of at most 16 events. The server's transaction budgets allow more; 16 is a latency choice (see **Per-chunk continuation**). Chunks of a larger fan-out commit **concurrently**: slot assignment is the World's, so parallel chunks race for slot ranges exactly like the pre-fold path's parallel single writes did, and per-entity conditions, not commit order, carry correctness. The fold only engages when the World implements `createBatch`, the run is on slot identity, and the suspension carries no attribute writes and no resilient step dispatch; everything else keeps the single-event path byte-for-byte. A suspension that also creates or disposes hooks still folds: hook writes are not batchable, so they go through the single-event path **concurrently** with the fold rather than ahead of it.
66
66
 
67
- **Per-chunk continuation.** Each chunk's follow-on work starts the moment **that chunk** commits, not when the whole fold does: a chunk's step-execution queue messages publish right off its own commit (publish-after-create holds per step), and only the chunk carrying the inline pairs gates the replay's continuation: trailing chunks' commits and publishes are joined before the invocation can acknowledge its message, so the durability contract ("every create durable before ack") is unchanged.
67
+ **Per-chunk continuation.** Each chunk's follow-on work starts the moment **that chunk** commits, not when the whole fold does: a chunk's step-execution queue messages publish right off its own commit (publish-after-create holds per step), and only the chunk carrying the inline pairs gates the replay's continuation: trailing chunks' commits and publishes are joined before the invocation can acknowledge its message, so the durability contract ("every create durable before ack") is unchanged. A queued step's message therefore waits on two hops in series, its chunk's commit and then its chunk's batched publish, and both grow with the chunk's size, so smaller chunks start a wide fan-out's queued branches sooner. More chunks also means more concurrent batch writes per run, and from about 16 of them the pair chunk, and with it the first inline branch, slows down. The 16-event cap is where production measurements balanced the two: on 64- and 128-branch fan-outs the last branch started about 90 to 200 ms sooner than at 32 events, with no first-branch cost at those widths.
68
68
 
69
- **Pre-claimed inline pairs.** When the fold engages with at least two inline steps, the steps the runtime is about to execute inline join the batch as adjacent `[step_created, step_started]` pairs: the created row carrying the input, the started row a bare ownership-stamped claim the World folds into a born-running create. The pairs commit in a chunk of their own, ahead of the plain `step_created` and `wait_created` chunks, so the write the inline bodies wait for carries only two rows per inline step (a small transaction that commits faster than a full 32-event chunk) while the plain creates commit concurrently beside it. The inline bodies start straight off the pair chunk's commit (in parallel with the queue publishes and the sibling chunks) with no per-step claim POST at all, and a pair that loses its atomic create-claim to a concurrent delivery skips its body exactly as a lost lazy claim does. A lone inline step keeps the optimistic lazy-start path (one row, whose claim overlaps the body) even when eager creates batch beside it: the pairs share no round trip with those creates, so only two or more inline steps make a pair chunk worth the trade. The exception is a lone inline step in a suspension that creates a hook: the runtime never starts a body before its claim settles while a hook is being created, and a lazy claim could only be sent after the hook write committed, so the step's pair is folded instead and its claim commits concurrently with the hook write. A plain partition of exactly one `step_created` or `wait_created` beside the pairs is written through the ordinary single path rather than a one-row batch, and its queue message still waits for that write.
69
+ **Pre-claimed inline pairs.** When the fold engages with at least two inline steps, the steps the runtime is about to execute inline join the batch as adjacent `[step_created, step_started]` pairs: the created row carrying the input, the started row a bare ownership-stamped claim the World folds into a born-running create. The pairs commit in a chunk of their own, ahead of the plain `step_created` and `wait_created` chunks, so the write the inline bodies wait for carries only two rows per inline step (a small transaction that commits faster than a full 16-event chunk) while the plain creates commit concurrently beside it. The inline bodies start straight off the pair chunk's commit (in parallel with the queue publishes and the sibling chunks) with no per-step claim POST at all, and a pair that loses its atomic create-claim to a concurrent delivery skips its body exactly as a lost lazy claim does. A lone inline step keeps the optimistic lazy-start path (one row, whose claim overlaps the body) even when eager creates batch beside it: the pairs share no round trip with those creates, so only two or more inline steps make a pair chunk worth the trade. The exception is a lone inline step in a suspension that creates a hook: the runtime never starts a body before its claim settles while a hook is being created, and a lazy claim could only be sent after the hook write committed, so the step's pair is folded instead and its claim commits concurrently with the hook write. A plain partition of exactly one `step_created` or `wait_created` beside the pairs is written through the ordinary single path rather than a one-row batch, and its queue message still waits for that write.
70
70
 
71
71
  Per-event `409`s are tolerated the same way the single path tolerates `EntityConflictError` (a concurrent delivery already created the entity); any other per-event failure fails the suspension write the way a single-path rejection would. A batch carrying a `step_started` (that is, any batch with inline pairs) is **not** retried in-process on a transport blip: a pair's `409` cannot be told apart from the caller's own earlier attempt having committed it, so recovery goes through queue redelivery instead, where the step's ownership stamp routes it back to the same invocation.
72
72
 
@@ -239,14 +239,15 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
239
239
 
240
240
  ### `WORKFLOW_SNAPSHOT_THRESHOLD`
241
241
 
242
- - Default: `0` (disabled)
243
- - Values: non-negative integer
242
+ - Default: `1000` when the QuickJS engine is selected
243
+ - Values: non-negative integer. `0` disables snapshotting.
244
244
  - Experimental. Only used by the QuickJS engine (`WORKFLOW_VM=quickjs`), and only with a World that provides snapshot storage (world-local, world-postgres, and world-vercel do).
245
- - When set above `0`, the runtime persists a **VM-memory snapshot** at a suspension once at least this many events have been processed since the last snapshot. Subsequent invocations restore the VM from the snapshot and replay only the events recorded since, instead of re-executing the workflow from the top against the full event log.
245
+ - When above `0`, the runtime persists a **VM-memory snapshot** at a suspension once at least this many events have been processed since the last snapshot. Subsequent invocations restore the VM from the snapshot and replay only the events recorded since, instead of re-executing the workflow from the top against the full event log.
246
246
  - Short-lived runs below the threshold never pay the snapshot cost; long-running or unbounded runs stop scaling their resume cost with total event-log length. `1` snapshots at every qualifying suspension.
247
247
  - Choosing a value: a restore costs roughly the same regardless of log length (tens of milliseconds to decompress and restore the heap, plus fetching the snapshot), while a full replay grows with the log (tens of milliseconds at a few hundred events, seconds at several thousand). Restoring starts to pay off at a few hundred events, so values in the hundreds suit most long-running workflows. Very low values mostly add snapshot saves to runs that replay quickly anyway.
248
248
  - Snapshots are an optimization, not a source of truth: the event log remains authoritative, and a missing, corrupt, oversized, or incompatible snapshot automatically falls back to a full replay. Snapshots over 32 MB uncompressed are not saved.
249
- - Like `WORKFLOW_VM`, the policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
249
+ - Set `0` to opt out and always replay the full event log.
250
+ - Like `WORKFLOW_VM`, an explicitly set policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. Runs without a stamped policy use the handler's value, or the default. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
250
251
  - A snapshot can only be restored by the exact QuickJS engine build that captured it. On Vercel, runs keep executing on the deployment they started on, so deploys don't affect in-flight snapshots. If your deployment serves in-flight runs from new code (for example, a self-hosted rolling update), an upgrade that changes the embedded engine makes every in-flight run fall back to a full replay at its next resume, all at once, before re-snapshotting at its next qualifying suspension. Plan for that one-time replay load when upgrading.
251
252
 
252
253
  What a snapshot contains, and how it is protected:
@@ -293,9 +293,12 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
293
293
 
294
294
  - Factory option: none
295
295
  - CLI flag: none
296
- - Default: `http`
297
- - Experimental stream-write transport capability. Set to exactly `ws` to attempt `workflow-stream-ws/v1`. The server authoritatively accepts or declines each upgrade; a decline uses HTTP directly for that writer lifetime. Stream reads remain HTTP and demand-driven.
298
- - This is not tenant rollout policy or a package-version check. HTTP remains the compatibility path. `/websockets/v1` is independent of REST v2/v4 and persisted workflow `specVersion` values.
296
+ - Default: `ws`
297
+ - Stream writes upgrade to a WebSocket (`workflow-stream-ws/v1`). Set to `http` (case-insensitive, surrounding whitespace ignored) to opt out; any other value, including unset, empty, or `ws`, uses the WebSocket. Stream reads always use HTTP.
298
+ - A writer's first two write groups go over HTTP, and the socket opens in the background after that, so no write waits for the upgrade. The server accepts or declines each upgrade; a declined or failed upgrade leaves that writer on HTTP for its lifetime.
299
+ - Ignored when the World is configured with `projectConfig` and routes through the `api-workflow` proxy, which does not forward a WebSocket upgrade, so stream writes stay on HTTP.
300
+ - The server pings idle sockets to keep them open, and the client must answer. The `ws` library the Vercel World uses does so automatically.
301
+ - Each WebSocket message is at most `WORKFLOW_WS_MAX_MESSAGE_BYTES`. Larger write groups are sent as several ordered requests, and a single chunk too large for one message is written over HTTP.
299
302
  - A throttled (429) socket write or close is retried after the server's `Retry-After`, as over HTTP. It moves to HTTP if the connection ends during the wait or the cumulative wait passes 30 seconds.
300
303
 
301
304
  ### `WORKFLOW_DISABLE_ANALYTICS_READS`
@@ -311,7 +314,7 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
311
314
  - Default: on
312
315
  - Set to `0` (or `false`) to **disable** batched event writes, the escape hatch that restores the exact prior one-write-per-event path.
313
316
 
314
- When enabled (the default), a suspension's eager `step_created` and `wait_created` writes fold into batched `events.createBatch` calls (one durable write with per-event outcomes) on Worlds that implement the optional batch API. The fold only engages when the World implements `events.createBatch` (the Vercel World does; Local and Postgres do not), the run's spec version supports slot identity (≥ 6), and the suspension carries no attribute writes or resilient step dispatch. Hook writes in the same suspension go through the single-event path concurrently with the batch. Everything else keeps the single-event path unchanged, so disabling is only needed as an operational escape hatch. Batches are capped at 32 events; larger fan-outs commit in successive batches. See the [batched event writes changelog](/docs/changelog/batched-event-writes) for the World API contract.
317
+ When enabled (the default), a suspension's eager `step_created` and `wait_created` writes fold into batched `events.createBatch` calls (one durable write with per-event outcomes) on Worlds that implement the optional batch API. The fold only engages when the World implements `events.createBatch` (the Vercel World does; Local and Postgres do not), the run's spec version supports slot identity (≥ 6), and the suspension carries no attribute writes or resilient step dispatch. Hook writes in the same suspension go through the single-event path concurrently with the batch. Everything else keeps the single-event path unchanged, so disabling is only needed as an operational escape hatch. Batches are capped at 16 events; larger fan-outs commit in several batches at once. See the [batched event writes changelog](/docs/changelog/batched-event-writes) for the World API contract.
315
318
 
316
319
  ### `WORKFLOW_EVENTS_TRANSPORT`
317
320
 
@@ -198,6 +198,41 @@ export async function dataCollectionWorkflow() {
198
198
 
199
199
  Each time you call `resumeHook()` with the same token, the loop receives another value.
200
200
 
201
+ ### Waiting with a timeout
202
+
203
+ Race a hook against `sleep()` to stop waiting after a deadline. To wait again after a timeout, create the hook's promise once and race that same promise on every attempt:
204
+
205
+ ```typescript lineNumbers
206
+ import { createHook, sleep } from "workflow";
207
+
208
+ declare function sendReminder(): Promise<void>; // @setup
209
+
210
+ export async function reminderWorkflow() {
211
+ "use workflow";
212
+
213
+ using hook = createHook<{ approved: boolean }>();
214
+ const approval = hook.then((payload) => payload); // [!code highlight]
215
+
216
+ for (let reminder = 0; reminder < 3; reminder++) {
217
+ const result = await Promise.race([
218
+ approval, // [!code highlight]
219
+ sleep("1d").then(() => "timeout" as const),
220
+ ]);
221
+
222
+ if (result !== "timeout") {
223
+ return result.approved;
224
+ }
225
+ await sendReminder();
226
+ }
227
+
228
+ return false;
229
+ }
230
+ ```
231
+
232
+ Racing a fresh `hook.then()` on each attempt also receives an event that arrives while that race is running. An event that arrives between races, for example while `sendReminder()` runs, is delivered to the awaiter left behind by the earlier race, so the workflow never sees it. Don't race `iterator.next()` from `hook[Symbol.asyncIterator]()` either. The `next()` call that lost a race keeps waiting and takes the next event, even one that arrives while a later race is running. Race the promise you created once instead.
233
+
234
+ Don't await one hook from several places at the same time, for example `Promise.all([hook, hook])`. Which event each await receives depends on how far the workflow had replayed when it awaited, so it can differ between code that looks equivalent. To receive successive events, await them one after another or iterate with `for await...of`.
235
+
201
236
  ### Disposing hooks early
202
237
 
203
238
  When a workflow ends, hooks are automatically disposed. However, you may want to release a hook token early so another workflow can use it while your workflow continues running. Use a block scope with `using` to control when disposal happens:
@@ -59,6 +59,21 @@ These types have special handling and are explained in detail in the sections be
59
59
  - `AbortController`
60
60
  - `AbortSignal`
61
61
 
62
+ ### Typing serializable values
63
+
64
+ Import the `Serializable` type from `workflow` to type values that cross a workflow or step boundary:
65
+
66
+ ```typescript title="workflows/record-event.ts" lineNumbers
67
+ import type { Serializable } from "workflow";
68
+
69
+ async function recordEvent(payload: Serializable) {
70
+ "use step";
71
+ // ...
72
+ }
73
+ ```
74
+
75
+ `Serializable` is a union of the JSON and built-in types listed above. It doesn't include `Request`, `Float16Array`, or classes with [custom serialization](#custom-class-serialization), so type those values directly.
76
+
62
77
  ## Pass-by-value semantics
63
78
 
64
79
  **Parameters are passed by value, not by reference.** Steps receive deserialized copies of data. Mutations inside a step won't affect the original in the workflow.
@@ -15,7 +15,24 @@ Lifecycle hooks let you register global handlers that observe workflow runs comp
15
15
 
16
16
  ## Registering hooks
17
17
 
18
- Call `registerLifecycleHooks` from `workflow/api` early in your application's lifecycle, so the handlers exist before the first run finishes. In Next.js, [`instrumentation.ts`](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation) is the natural place; in any other app, any module that loads at startup works.
18
+ Call `registerLifecycleHooks` from `workflow/api` in the **host process that executes workflows**, before it handles requests. Registering in a different server or Vercel Function does not populate the executor's registry.
19
+
20
+ ### Framework support
21
+
22
+ | Integration / deployment | Where to register | Limitations |
23
+ | --- | --- | --- |
24
+ | Next.js 16.3.0 and later | [`instrumentation.ts`](https://nextjs.org/docs/app/building-your-application/optimizing/instrumentation), using the guarded dynamic import below | Earlier Next.js versions can handle a cold Vercel invocation before async instrumentation finishes, skipping hooks. Upgrade to 16.3.0 or later for this pattern. |
25
+ | SvelteKit | `init` in `src/hooks.server.ts`, before serving requests | Re-running initialization during hot reload can append duplicate registrations. |
26
+ | Nitro v3, including the Nitro-based Vite, TanStack Start, Express, Hono, and Fastify integrations | A server plugin with a static import and synchronous registration | Nitro does not await async plugin registration. Do not copy the Next.js dynamic-import pattern into a Nitro plugin. Vite server reloads can re-run plugins in the same process. |
27
+ | Nuxt 4 / Nitro v2 with the Vercel preset | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load Nitro app plugins. |
28
+ | Astro on Vercel | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load Astro middleware. |
29
+ | Nest on Vercel | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load Nest bootstrap code. |
30
+ | CLI `vercel-build-output-api` target | App startup registration is not supported for lifecycle hooks on this target | The generated standalone workflow function does not load the application's startup module. |
31
+ | A shared Node.js server on other hosts | Bootstrap before accepting requests | The bootstrap must run in every process serving workflow queue handlers. |
32
+
33
+ The unsupported Vercel targets above emit a separate `.well-known/workflow/v1/flow.func`. App-startup hooks never reach it, so callbacks do not fire there. Do not work around this by registering at the top level of a workflow file: its VM bundle resolves `workflow/api` to a throwing stub. Registration inside a step also throws; it would otherwise accumulate a handler on every execution.
34
+
35
+ ### Next.js registration
19
36
 
20
37
  ```typescript title="instrumentation.ts" lineNumbers
21
38
  export async function register() {
@@ -41,6 +58,8 @@ Keep the dynamic `workflow/api` import inside the `NEXT_RUNTIME === "nodejs"` gu
41
58
 
42
59
  `registerLifecycleHooks` returns an unregister function. You can register multiple hook sets, and handlers run in registration order. Registrations are not deduplicated: register each hook set once per process, and call its unregister function before registering it again during hot reload or module re-evaluation. Otherwise, repeated registrations invoke the same handler multiple times for each transition.
43
60
 
61
+ **Restart `next dev` after changing handlers registered by `instrumentation.ts`.** Next.js memoizes instrumentation registration per process, so edits may not take effect until restart. For other hot-reloading hosts, preserve the unregister function in process-wide state across module re-evaluation, or restart the server. A module-local variable may be reset by the reload.
62
+
44
63
  ## Handler parameters
45
64
 
46
65
  Both handlers receive a `workflowName` string and the [`Run`](/docs/api-reference/workflow-api/get-run) instance for the transitioned run. `workflowName` is the machine-readable workflow identifier, such as `workflow//./src/workflows/order//processOrder`. Use this parameter to filter runs without a backend read. `run.runId` is also available without a read.
@@ -50,11 +69,56 @@ The `Run` instance hydrates lazily. Accessors such as `run.workflowName`, `run.s
50
69
  `onRunFailed` additionally receives a `WorkflowRunFailedError` hydrated for reporting. Unlike `run.returnValue`, it defers readable stream I/O and uses persisted abort snapshots:
51
70
 
52
71
  - `error.errorCode`: the failure classification (`USER_ERROR`, `RUNTIME_ERROR`, `MAX_DELIVERIES_EXCEEDED`, and more). See [error codes](/docs/errors) for the full list.
53
- - `error.cause`: the thrown value hydrated from the persisted error data, with registered Error subclass identity, message, stack, and cause chain preserved. Readable streams load lazily when consumed, and abort signals reflect their persisted state without live subscriptions. Writable streams retain their normal forwarding pipe and lock-polling setup during hydration. If hydration fails, the cause is a generic `Error`, matching `run.returnValue`'s fallback. Any JavaScript value can be thrown, so this is typed `unknown`.
72
+ - `error.cause`: the thrown value hydrated from the persisted error data, including its message, stack, and cause chain. Custom serialization revives registered classes using the runtime's module copy; constructor identity may differ from the handler's copy. Plain user-defined Error subclasses without custom serialization revive as generic errors with their name preserved. Readable streams load lazily when consumed, and abort signals reflect their persisted state without live subscriptions. Writable streams retain their normal forwarding setup: **writes still reach the failed run's stream, or the parent run's stream for a forwarded writable**. If hydration fails, the SDK logs the reason and supplies a generic `Error`, matching `run.returnValue`'s fallback. Any JavaScript value can be thrown, so this is typed `unknown`.
54
73
 
55
74
  In `onRunFailed`, `run.returnValue` rejects because the run failed. Use `error.cause` to inspect or report the thrown value instead of awaiting `run.returnValue`.
56
75
 
57
- The invocation's `waitUntil` scope includes background stream operations from the hydrated cause, even after a handler returns or throws. Close or release stream reader and writer locks when finished so that work can settle. Await other asynchronous reporting work in your handler, such as `Sentry.flush()` below, to keep it in the same lifetime scope.
76
+ ### Identifying errors across module copies
77
+
78
+ Handler parameters come from the runtime's module copy. For example, Next.js bundles instrumentation separately from app routes. The shared registry connects those copies, but `run instanceof Run`, `error instanceof WorkflowRunFailedError`, and checks against custom error constructors can be false. Use `WorkflowRunFailedError.is(error)` and `FatalError.is(error.cause)` for SDK errors, and inspect `errorCode`, the cause's `name`, or your own serialized discriminator for application errors:
79
+
80
+ ```typescript title="report-failure.ts" lineNumbers
81
+ import { FatalError } from "workflow";
82
+ import { WorkflowRunFailedError } from "workflow/errors";
83
+
84
+ export function reportFailure(error: unknown) {
85
+ if (!WorkflowRunFailedError.is(error)) return;
86
+ const cause = error.cause;
87
+ const name = typeof cause === "object" && cause !== null && "name" in cause
88
+ ? cause.name
89
+ : undefined;
90
+ console.error({ errorCode: error.errorCode, name, fatal: FatalError.is(cause) });
91
+ }
92
+ ```
93
+
94
+ Load this reporting module from the host registration module, using the guarded dynamic import on Next.js.
95
+
96
+ ### Stream lifetime
97
+
98
+ On Vercel, the invocation's `waitUntil` scope drains background stream operations from **`error.cause`**, even after a handler returns or throws. This does not automatically cover pipes from `await run.returnValue` in `onRunCompleted`, or consumption scheduled after the handler returns with timers or other detached work. Await consumption and other asynchronous reporting work in the handler, such as `Sentry.flush()` below. Other hosts run handlers as detached work and may stop them when the process freezes or terminates.
99
+
100
+ <Callout type="warn">
101
+ A readable or writable lock left open can keep the drain and lifecycle span pending until the Vercel Function's maximum duration. Close or release locks when finished. If you only need part of a readable, cancel its reader in a `finally` block:
102
+ </Callout>
103
+
104
+ ```typescript lineNumbers
105
+ import type { RunFailedHookParams } from "workflow/api";
106
+
107
+ async function onRunFailed({ error }: RunFailedHookParams) {
108
+ if (!(error.cause instanceof ReadableStream)) return;
109
+ const reader = error.cause.getReader();
110
+ try {
111
+ const first = await reader.read();
112
+ console.error(first.value);
113
+ } finally {
114
+ try {
115
+ await reader.cancel();
116
+ } finally {
117
+ reader.releaseLock();
118
+ }
119
+ }
120
+ }
121
+ ```
58
122
 
59
123
  ## Reporting failed runs to Sentry
60
124
 
@@ -88,8 +152,8 @@ export async function register() {
88
152
 
89
153
  ## How handlers behave
90
154
 
91
- - **Host-only.** Handlers run with full Node.js access, never inside the workflow's sandboxed VM. Calling `registerLifecycleHooks` from workflow code throws.
155
+ - **Host startup only.** Handlers run with full Node.js access, never inside the workflow's sandboxed VM. Calling `registerLifecycleHooks` from workflow or step code throws.
92
156
  - **Fire-and-forget.** Handlers cannot delay or change the run's outcome. The runtime logs and swallows a throwing handler, and the remaining handlers still run. On Vercel, `waitUntil` keeps the invocation alive while handlers finish, subject to the invocation's duration limit. On other hosts, handlers run as detached work. If the host freezes or terminates the process after the response, handlers may not complete.
93
157
  - **Best-effort delivery.** Each registered handler is invoked at most once by the invocation that writes the terminal event. For a failure, this happens after any workflow or step retries are exhausted. Callbacks are not retried if they throw or the process dies, so a callback may never run or may stop before completing. The [event log](/docs/how-it-works/event-sourcing) is the system of record, not lifecycle callbacks.
94
158
  - **Fires where the transition is recorded.** Terminal transitions recorded outside your app's compute do **not** fire handlers. For example, when you cancel a run from the CLI or the Vercel dashboard, the backend writes that transition, so no handler runs.
95
- - **Register everywhere your workflows run.** The terminal write can happen in any function invocation that processes the run's queue messages, so registration must run at startup in every instance of the app (which `instrumentation.ts` guarantees).
159
+ - **Register in each executor.** The terminal write can happen in any process that handles the run's queue messages. Use the [framework support table](#framework-support) to check whether app startup reaches that process.
@@ -40,6 +40,7 @@ No workflow-specific configuration is required. As soon as a tracer provider and
40
40
  | `workflow.start <name>` | internal | `start()` is called in your application code |
41
41
  | `workflow.execute <name>` | consumer (root) | a queue delivery invokes the workflow; replay, orchestration, and inline steps run under it |
42
42
  | `step.execute <name>` | internal (inline) / consumer + root (queue-delivered) | a step function executes |
43
+ | `workflow.lifecycle.onRunCompleted` / `workflow.lifecycle.onRunFailed` | internal | registered lifecycle handlers observe a persisted terminal transition; includes parameter hydration, handler execution, and the failure-cause stream drain |
43
44
  | `http <method>` | client | the SDK calls the workflow backend (event reads/writes) |
44
45
  | `workflow.stream.write` | client | a stream chunk (or the stream close) is flushed to the backend |
45
46
  | `workflow.stream.flush` | client | a buffered batch of stream writes settles; back-dated to the batch's first `write()`, so its duration is the app-perceived batch latency (buffer dwell + RPC) |
@@ -52,6 +53,8 @@ No workflow-specific configuration is required. As soon as a tracer provider and
52
53
 
53
54
  Stream spans are emitted by the SDK's world backend on the client that writes or reads the stream, and (like all SDK spans) are no-ops when no OpenTelemetry SDK is registered. The `workflow.stream.read` span only appears once the first non-empty chunk arrives.
54
55
 
56
+ [Lifecycle hook](/docs/observability/lifecycle-hooks) spans carry `workflow.run.id` and `workflow.name`. Caught handler, hydration, and stream-operation failures emit `workflow.lifecycle.failure` events with a `phase` and exception details. The span may still have OK status because reporting failures are isolated from workflow execution; inspect its failure events. A retained stream lock extends the span's duration through the drain, so follow the [stream cleanup guidance](/docs/observability/lifecycle-hooks#stream-lifetime).
57
+
55
58
  ## Key attributes
56
59
 
57
60
  | Attribute | Description |
@@ -105,21 +105,21 @@ See [Attributes](/docs/observability/attributes).
105
105
 
106
106
  ### Richer serialization
107
107
 
108
- Everything that crosses a workflow/step boundary is serialized, and v5 widens what survives the trip with its identity intact. Errors, including your own classes and built-ins like `TypeError`, keep their class and `cause` chain through `WorkflowRunFailedError.cause`:
108
+ Everything that crosses a workflow/step boundary is serialized. In v5, built-in errors such as `TypeError` preserve their type, message, stack, and `cause` chain through `WorkflowRunFailedError.cause`. Plain user-defined Error subclasses preserve their name but revive as generic errors unless they implement [custom serialization](/docs/foundations/serialization). Bundled module copies can still have distinct constructors, so use SDK error `.is()` helpers instead of `instanceof`:
109
109
 
110
110
  ```typescript lineNumbers
111
+ import { FatalError } from "workflow";
111
112
  import { WorkflowRunFailedError } from "workflow/errors";
112
113
  import { getRun } from "workflow/api";
113
- declare class PaymentDeclinedError extends Error {} // @setup
114
114
 
115
115
  try {
116
116
  await getRun(runId).returnValue;
117
117
  } catch (error) {
118
118
  if (
119
- error instanceof WorkflowRunFailedError &&
120
- error.cause instanceof PaymentDeclinedError // [!code highlight]
119
+ WorkflowRunFailedError.is(error) &&
120
+ FatalError.is(error.cause) // [!code highlight]
121
121
  ) {
122
- // your class, not a flattened generic Error
122
+ console.error(error.errorCode, error.cause.message);
123
123
  }
124
124
  }
125
125
  ```
@@ -152,7 +152,7 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
152
152
  - **Support for more frameworks.** [React Router](/docs/getting-started/react-router) (v7 and v8, via Nitro) and [NestJS](/docs/getting-started/nestjs) are now supported.
153
153
  - **A misrouted delivery no longer fails a run.** Runs are pinned to the deployment that created them. A delivery that arrives at a different deployment is now re-routed to the pinned one with backoff instead of failing, and only gives up with the new [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) error once the recovery budget is spent. Nothing executes on the wrong deployment while this happens. In 4.x the same situation surfaced as an unexplained decryption failure.
154
154
  - **A run cannot be forked across environments.** `start()` stamps the environment it was called from onto the queue message, and a deployment refuses a delivery whose run was created in a different environment. Previously a preview client and a production deployment could each hold half of one run ID.
155
- - **An experimental QuickJS VM engine.** Set [`WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run workflow functions in a QuickJS VM compiled to WebAssembly instead of `node:vm`, for platforms that do not provide `node:vm`. Replay semantics are identical, but the available globals are not: check the differences before switching an existing deployment.
155
+ - **An experimental QuickJS VM engine.** Set [`WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run workflow functions in a QuickJS VM compiled to WebAssembly instead of `node:vm`, for platforms that do not provide `node:vm`. Replay semantics are identical, but the available globals are not: check the differences before switching an existing deployment. By default, an encrypted QuickJS run that passes 1,000 events resumes from a VM-memory snapshot instead of replaying its full event log (see [`WORKFLOW_SNAPSHOT_THRESHOLD`](/docs/configuration/runtime-tuning#workflow_snapshot_threshold)).
156
156
  - **Experimental dynamic workflows.** Pass workflow source as a string to `start()` to run orchestration assembled after deployment over steps already deployed with your app. The code is stored with the run (encrypted on Vercel), so replays always execute the code the run started with. Off unless the deployment sets `WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1`. See [Dynamic Workflows](/docs/advanced/dynamic-workflows).
157
157
  - **A WebSocket transport for event writes** on the Vercel World, which ships a run's events over one socket instead of one HTTP request each. It is the default; set [`WORKFLOW_EVENTS_TRANSPORT=http`](/worlds/vercel#workflow_events_transport) to opt out. Tracing is unaffected: each write still emits an `http POST` client span, synthesized around the frame, with the transport on `workflow.events.transport`.
158
158
  - **`await run.returnValue` waits instead of polling.** Reading a run's result long-polls the World until the run reaches a terminal status, rather than asking again on a fixed interval. A result is observed as soon as it exists, and an idle wait costs one open request instead of a request per tick. Worlds that do not implement the long poll keep the interval.
@@ -117,6 +117,10 @@ WORKFLOW_TARGET_WORLD="./my-world.ts"
117
117
 
118
118
  `createWorld()` also accepts `tag`, which scopes local storage files to a suffix. It is mainly used by test harnesses that share one `.workflow-data` directory.
119
119
 
120
+ ## Data directory layout
121
+
122
+ Each run's event and step files are stored in their own directory (`events/<runId>/`, `steps/<runId>/`). A directory that mixes both layouts, or holds `.json` files in `events/` or `steps/` that the World did not write, is never deleted: starting fails with a `DataDirLayoutError` that lists the files.
123
+
120
124
  ## Limitations
121
125
 
122
126
  The Local World is designed for development, not production:
@@ -344,7 +344,7 @@ The Postgres World uses PostgreSQL as a durable backend:
344
344
 
345
345
  - **Storage**: Workflow runs, events, steps, and hooks are stored in PostgreSQL tables.
346
346
  - **Job queue**: [graphile-worker](https://github.com/graphile/worker) handles reliable job processing with retries.
347
- - **Streaming**: PostgreSQL NOTIFY/LISTEN enables real-time event distribution.
347
+ - **Streaming**: PostgreSQL NOTIFY/LISTEN enables real-time event distribution. If the database drops the `LISTEN` connection, the World reconnects every second and re-reads persisted chunks for open stream readers, so readers don't miss chunks written during the outage.
348
348
 
349
349
  This architecture ensures workflows survive application restarts with all state reliably persisted. For implementation details, see the [source code](https://github.com/vercel/workflow/tree/main/packages/world-postgres).
350
350
 
@@ -242,15 +242,23 @@ Maximum stream chunks written in one Vercel World request. Larger batches are sp
242
242
 
243
243
  ### `WORKFLOW_STREAMS_TRANSPORT`
244
244
 
245
- Experimental stream-write transport capability. Default: `http`. Set `WORKFLOW_STREAMS_TRANSPORT=ws` to attempt `workflow-stream-ws/v1`. The server authoritatively accepts or declines every upgrade; a decline goes directly to HTTP for that writer lifetime. Reads remain HTTP and demand-driven.
245
+ Stream writes upgrade to a WebSocket (`workflow-stream-ws/v1`) instead of one HTTP request per write group. Default: `ws`.
246
246
 
247
- This setting does not own tenant rollout policy and does not infer server support from package versions. HTTP remains the compatibility path. The protocol route (`/websockets/v1`) is versioned independently from REST v2/v4 and persisted workflow `specVersion` values.
247
+ Set `WORKFLOW_STREAMS_TRANSPORT=http` to opt out. That value is matched case-insensitively and ignoring surrounding whitespace; any other value, including unset, empty, or `ws`, uses the WebSocket. Stream reads always use HTTP.
248
248
 
249
- Writes and close requests execute serially. The first operation waits up to 250 ms for an opted-in socket to open; this is an implementation-level measurement knob, not protocol semantics. If the budget expires, or the upgrade fails or is declined before acceptance, the writer uses HTTP without racing the same operation over both transports. After the socket accepts a write, a missing acknowledgement has an unknown outcome: the writer fails rather than replaying the write over HTTP and risking a duplicate append. A throttled (429) write or close did not apply, so the writer retries it after the server's `Retry-After`, as the HTTP writer does, on the socket if it stays open (or its replacement, after a drain) and otherwise over HTTP. Past 30 seconds of cumulative wait, the write moves to HTTP, whose own 429 retry applies. A close that fails with a 5xx is retried over HTTP, since close is idempotent.
249
+ The setting is ignored when the World is configured with `projectConfig` and routes through the `api-workflow` proxy, which does not forward a WebSocket upgrade, so stream writes stay on HTTP.
250
+
251
+ The client only offers the upgrade. The server accepts or declines each one, and a writer whose upgrade is declined or fails writes over HTTP for the rest of its lifetime. This setting does not decide which tenants may upgrade and does not infer server support from package versions. The protocol route (`/websockets/v1`) is versioned independently from REST v2/v4 and persisted workflow `specVersion` values.
252
+
253
+ A writer's first write group always goes over HTTP, and so does its second. The socket starts opening in the background once the second group's request is sent, and later groups keep going over HTTP until it opens, so no write waits for the upgrade. A writer that closes after one or two groups never uses the socket. If the socket has not opened within 10 seconds, or the upgrade fails or is declined, the writer stays on HTTP.
254
+
255
+ Writes and close requests execute serially, so a write never overtakes an earlier one on the other transport. After the socket accepts a write, a missing acknowledgement has an unknown outcome: the writer fails rather than replaying the write over HTTP and risking a duplicate append. A throttled (429) write or close did not apply, so the writer retries it after the server's `Retry-After`, as the HTTP writer does, on the socket if it stays open (or its replacement, after a drain) and otherwise over HTTP. Past 30 seconds of cumulative wait, the write moves to HTTP, whose own 429 retry applies. A close that fails with a 5xx is retried over HTTP, since close is idempotent.
250
256
 
251
257
  Once a released writer's writes drain, its socket closes without closing the shared stream, and later writes through that same handle go over HTTP. Writers acquired with `getWritable()` inside a step release their socket when the step completes. External `getRun(runId).getWritable()` handles release it on the first `releaseLock()` after pending writes drain, so hold the writer lock for the whole burst to keep writing over the socket.
252
258
 
253
- Before routine authentication expiry or server max duration, the server sends a v1 `drain` control. The client stops sending, lets an already-admitted request receive its reply, and reconnects after the server closes with code 1001. Authentication drains re-resolve a fresh bearer. A request that was sent but receives no reply before close still has an unknown outcome and is never replayed.
259
+ Before routine authentication expiry or server max duration, the server sends a v1 `drain` control. The client stops sending, lets an already-admitted request receive its reply, and reconnects after the server closes with code 1001. If the new socket is not open within 250 ms, the writer continues over HTTP. Authentication drains re-resolve a fresh bearer. A request that was sent but receives no reply before close still has an unknown outcome and is never replayed.
260
+
261
+ The server sends WebSocket pings to keep an idle socket open, and the client must answer them. The `ws` library the Vercel World uses answers pings automatically, so there is nothing to configure.
254
262
 
255
263
  Each stream WebSocket message is at most [`WORKFLOW_WS_MAX_MESSAGE_BYTES`](#workflow_ws_max_message_bytes) bytes. A write group larger than the limit is sent as several ordered write requests. A single chunk too large for one message is written over HTTP instead, as are the rest of its writer's writes.
256
264
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workflow",
3
- "version": "5.1.0",
3
+ "version": "5.2.0",
4
4
  "description": "Workflow SDK - Build durable, resilient, and observable workflows",
5
5
  "main": "dist/typescript-plugin.cjs",
6
6
  "type": "module",
@@ -58,19 +58,19 @@
58
58
  }
59
59
  },
60
60
  "dependencies": {
61
- "@workflow/astro": "5.0.2",
62
- "@workflow/cli": "5.0.2",
63
- "@workflow/core": "5.1.0",
64
- "@workflow/errors": "5.0.2",
61
+ "@workflow/astro": "5.0.3",
62
+ "@workflow/cli": "5.0.3",
63
+ "@workflow/core": "5.2.0",
64
+ "@workflow/errors": "5.0.3",
65
65
  "@workflow/typescript-plugin": "5.0.0",
66
66
  "@workflow/utils": "5.0.1",
67
67
  "ms": "2.1.3",
68
- "@workflow/next": "5.0.2",
69
- "@workflow/nest": "5.1.0",
70
- "@workflow/nitro": "5.0.2",
71
- "@workflow/nuxt": "5.0.2",
72
- "@workflow/sveltekit": "5.0.2",
73
- "@workflow/rollup": "5.0.2"
68
+ "@workflow/next": "5.0.3",
69
+ "@workflow/nest": "5.1.1",
70
+ "@workflow/nitro": "5.0.3",
71
+ "@workflow/nuxt": "5.0.3",
72
+ "@workflow/sveltekit": "5.0.3",
73
+ "@workflow/rollup": "5.0.3"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@types/ms": "2.1.0",