workflow 5.6.1 → 5.7.1

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.
@@ -1,7 +1,8 @@
1
- export type { CancelRunOptions, Event, StartOptions, StopSleepOptions, StopSleepResult, WorkflowReadableStreamOptions, WorkflowRun, WorkflowRunWritableStreamOptions, } from '@workflow/core/runtime';
1
+ export type { CancelRunOptions, DeleteRunDataResult, DeleteRunsDataResult, Event, StartOptions, StopSleepOptions, StopSleepResult, WorkflowReadableStreamOptions, WorkflowRun, WorkflowRunWritableStreamOptions, } from '@workflow/core/runtime';
2
2
  export { Run } from '@workflow/core/runtime/run';
3
3
  export { start } from '@workflow/core/runtime/start';
4
4
  export declare const getRun: () => never;
5
+ export declare const deleteRuns: () => never;
5
6
  export declare const getHookByToken: () => never;
6
7
  export declare const resumeHook: () => never;
7
8
  export declare const resumeWebhook: () => never;
@@ -4,6 +4,7 @@ const workflowStub = (item) => {
4
4
  throw new Error(`The workflow environment doesn't allow this runtime usage of ${item}. Move this call to a step function ("use step") or call it outside the workflow context.`);
5
5
  };
6
6
  export const getRun = () => workflowStub('getRun');
7
+ export const deleteRuns = () => workflowStub('deleteRuns');
7
8
  export const getHookByToken = () => workflowStub('getHookByToken');
8
9
  export const resumeHook = () => workflowStub('resumeHook');
9
10
  export const resumeWebhook = () => workflowStub('resumeWebhook');
@@ -11,4 +12,4 @@ export const runStep = () => workflowStub('runStep');
11
12
  export const registerLifecycleHooks = () => {
12
13
  throw new Error('registerLifecycleHooks 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
  };
14
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBpLXdvcmtmbG93LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2FwaS13b3JrZmxvdy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFXQSxPQUFPLEVBQUUsR0FBRyxFQUFFLE1BQU0sNEJBQTRCLENBQUM7QUFDakQsT0FBTyxFQUFFLEtBQUssRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBRXJELE1BQU0sWUFBWSxHQUFHLENBQUMsSUFBWSxFQUFFLEVBQUU7SUFDcEMsTUFBTSxJQUFJLEtBQUssQ0FDYixnRUFBZ0UsSUFBSSwyRkFBMkYsQ0FDaEssQ0FBQztBQUNKLENBQUMsQ0FBQztBQUVGLE1BQU0sQ0FBQyxNQUFNLE1BQU0sR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsUUFBUSxDQUFDLENBQUM7QUFDbkQsTUFBTSxDQUFDLE1BQU0sY0FBYyxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxnQkFBZ0IsQ0FBQyxDQUFDO0FBQ25FLE1BQU0sQ0FBQyxNQUFNLFVBQVUsR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsWUFBWSxDQUFDLENBQUM7QUFDM0QsTUFBTSxDQUFDLE1BQU0sYUFBYSxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxlQUFlLENBQUMsQ0FBQztBQUNqRSxNQUFNLENBQUMsTUFBTSxPQUFPLEdBQUcsR0FBRyxFQUFFLENBQUMsWUFBWSxDQUFDLFNBQVMsQ0FBQyxDQUFDO0FBQ3JELE1BQU0sQ0FBQyxNQUFNLHNCQUFzQixHQUFHLEdBQUcsRUFBRTtJQUN6QyxNQUFNLElBQUksS0FBSyxDQUNiLDRMQUE0TCxDQUM3TCxDQUFDO0FBQ0osQ0FBQyxDQUFDIn0=
15
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBpLXdvcmtmbG93LmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2FwaS13b3JrZmxvdy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFhQSxPQUFPLEVBQUUsR0FBRyxFQUFFLE1BQU0sNEJBQTRCLENBQUM7QUFDakQsT0FBTyxFQUFFLEtBQUssRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBRXJELE1BQU0sWUFBWSxHQUFHLENBQUMsSUFBWSxFQUFFLEVBQUU7SUFDcEMsTUFBTSxJQUFJLEtBQUssQ0FDYixnRUFBZ0UsSUFBSSwyRkFBMkYsQ0FDaEssQ0FBQztBQUNKLENBQUMsQ0FBQztBQUVGLE1BQU0sQ0FBQyxNQUFNLE1BQU0sR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsUUFBUSxDQUFDLENBQUM7QUFDbkQsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxZQUFZLENBQUMsQ0FBQztBQUMzRCxNQUFNLENBQUMsTUFBTSxjQUFjLEdBQUcsR0FBRyxFQUFFLENBQUMsWUFBWSxDQUFDLGdCQUFnQixDQUFDLENBQUM7QUFDbkUsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHLEdBQUcsRUFBRSxDQUFDLFlBQVksQ0FBQyxZQUFZLENBQUMsQ0FBQztBQUMzRCxNQUFNLENBQUMsTUFBTSxhQUFhLEdBQUcsR0FBRyxFQUFFLENBQUMsWUFBWSxDQUFDLGVBQWUsQ0FBQyxDQUFDO0FBQ2pFLE1BQU0sQ0FBQyxNQUFNLE9BQU8sR0FBRyxHQUFHLEVBQUUsQ0FBQyxZQUFZLENBQUMsU0FBUyxDQUFDLENBQUM7QUFDckQsTUFBTSxDQUFDLE1BQU0sc0JBQXNCLEdBQUcsR0FBRyxFQUFFO0lBQ3pDLE1BQU0sSUFBSSxLQUFLLENBQ2IsNExBQTRMLENBQzdMLENBQUM7QUFDSixDQUFDLENBQUMifQ==
package/dist/api.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import '@workflow/core/runtime/world-init';
2
- export type { CancelRunOptions, Event, StopSleepOptions, StopSleepResult, WorkflowRun, } from '@workflow/core/runtime';
2
+ export type { CancelRunOptions, DeleteRunDataResult, DeleteRunsDataResult, Event, StopSleepOptions, StopSleepResult, WorkflowRun, } from '@workflow/core/runtime';
3
+ export { deleteRuns } from '@workflow/core/runtime/delete-runs';
3
4
  export { type RunCompletedHookParams, type RunFailedHookParams, registerLifecycleHooks, type WorkflowLifecycleHooks, } from '@workflow/core/runtime/lifecycle-hooks';
4
5
  export { getHookByToken, type Hook, type ResumedHook, resumeHook, resumeWebhook, } from '@workflow/core/runtime/resume-hook';
5
6
  export { getRun, Run, type WorkflowReadableStream, type WorkflowReadableStreamOptions, type WorkflowRunWritableStreamOptions, } from '@workflow/core/runtime/run';
package/dist/api.js CHANGED
@@ -6,8 +6,9 @@
6
6
  // stays host-only.
7
7
  // See `@workflow/core/src/runtime/world-init.ts` for the full rationale.
8
8
  import '@workflow/core/runtime/world-init';
9
+ export { deleteRuns } from '@workflow/core/runtime/delete-runs';
9
10
  export { registerLifecycleHooks, } from '@workflow/core/runtime/lifecycle-hooks';
10
11
  export { getHookByToken, resumeHook, resumeWebhook, } from '@workflow/core/runtime/resume-hook';
11
12
  export { getRun, Run, } from '@workflow/core/runtime/run';
12
13
  export { start, } from '@workflow/core/runtime/start';
13
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBpLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2FwaS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxxRUFBcUU7QUFDckUseUVBQXlFO0FBQ3pFLDJFQUEyRTtBQUMzRSw0RUFBNEU7QUFDNUUsNkVBQTZFO0FBQzdFLG1CQUFtQjtBQUNuQix5RUFBeUU7QUFDekUsT0FBTyxtQ0FBbUMsQ0FBQztBQVMzQyxPQUFPLEVBR0wsc0JBQXNCLEdBRXZCLE1BQU0sd0NBQXdDLENBQUM7QUFDaEQsT0FBTyxFQUNMLGNBQWMsRUFHZCxVQUFVLEVBQ1YsYUFBYSxHQUNkLE1BQU0sb0NBQW9DLENBQUM7QUFDNUMsT0FBTyxFQUNMLE1BQU0sRUFDTixHQUFHLEdBSUosTUFBTSw0QkFBNEIsQ0FBQztBQUNwQyxPQUFPLEVBTUwsS0FBSyxHQUNOLE1BQU0sOEJBQThCLENBQUMifQ==
14
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBpLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2FwaS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxxRUFBcUU7QUFDckUseUVBQXlFO0FBQ3pFLDJFQUEyRTtBQUMzRSw0RUFBNEU7QUFDNUUsNkVBQTZFO0FBQzdFLG1CQUFtQjtBQUNuQix5RUFBeUU7QUFDekUsT0FBTyxtQ0FBbUMsQ0FBQztBQVczQyxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sb0NBQW9DLENBQUM7QUFDaEUsT0FBTyxFQUdMLHNCQUFzQixHQUV2QixNQUFNLHdDQUF3QyxDQUFDO0FBQ2hELE9BQU8sRUFDTCxjQUFjLEVBR2QsVUFBVSxFQUNWLGFBQWEsR0FDZCxNQUFNLG9DQUFvQyxDQUFDO0FBQzVDLE9BQU8sRUFDTCxNQUFNLEVBQ04sR0FBRyxHQUlKLE1BQU0sNEJBQTRCLENBQUM7QUFDcEMsT0FBTyxFQU1MLEtBQUssR0FDTixNQUFNLDhCQUE4QixDQUFDIn0=
@@ -1,2 +1,2 @@
1
- export { EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
1
+ export { DynamicWorkflowsNotEnabledError, EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
2
2
  //# sourceMappingURL=errors.d.ts.map
@@ -1,2 +1,2 @@
1
- export { EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2ludGVybmFsL2Vycm9ycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQ0wsbUJBQW1CLEVBQ25CLGlCQUFpQixFQUNqQixxQkFBcUIsRUFDckIsaUJBQWlCLEVBQ2pCLHFCQUFxQixFQUNyQix1QkFBdUIsRUFDdkIsZUFBZSxFQUNmLG9CQUFvQixFQUNwQixzQkFBc0IsRUFDdEIsV0FBVyxFQUNYLGFBQWEsRUFDYixhQUFhLEVBQ2IsYUFBYSxFQUNiLDBCQUEwQixFQUMxQix5QkFBeUIsRUFDekIsc0JBQXNCLEVBQ3RCLDRCQUE0QixFQUM1Qix3QkFBd0IsRUFDeEIsb0JBQW9CLEVBQ3BCLGtCQUFrQixFQUNsQixrQkFBa0IsR0FDbkIsTUFBTSxrQkFBa0IsQ0FBQyJ9
1
+ export { DynamicWorkflowsNotEnabledError, EntityConflictError, HookConflictError, HookForceClaimedError, HookNotFoundError, InBandSupersededError, PreconditionFailedError, RunExpiredError, RunNotSupportedError, StepNotRegisteredError, StreamError, ThrottleError, TooEarlyError, WorkflowError, WorkflowNotRegisteredError, WorkflowRunCancelledError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRunNotFoundError, WorkflowRuntimeError, WorkflowStartError, WorkflowWorldError, } from '@workflow/errors';
2
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2ludGVybmFsL2Vycm9ycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQ0wsK0JBQStCLEVBQy9CLG1CQUFtQixFQUNuQixpQkFBaUIsRUFDakIscUJBQXFCLEVBQ3JCLGlCQUFpQixFQUNqQixxQkFBcUIsRUFDckIsdUJBQXVCLEVBQ3ZCLGVBQWUsRUFDZixvQkFBb0IsRUFDcEIsc0JBQXNCLEVBQ3RCLFdBQVcsRUFDWCxhQUFhLEVBQ2IsYUFBYSxFQUNiLGFBQWEsRUFDYiwwQkFBMEIsRUFDMUIseUJBQXlCLEVBQ3pCLHNCQUFzQixFQUN0Qiw0QkFBNEIsRUFDNUIsd0JBQXdCLEVBQ3hCLG9CQUFvQixFQUNwQixrQkFBa0IsRUFDbEIsa0JBQWtCLEdBQ25CLE1BQU0sa0JBQWtCLENBQUMifQ==
@@ -73,8 +73,8 @@ WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1
73
73
 
74
74
  Only `1` or `true` (case-insensitive) enables them; any other value, or no value, leaves them off. The runtime reads the variable where workflows execute, when it needs it, so set it on the deployment or dev server rather than at build time. It controls three things:
75
75
 
76
- - **Starting.** `start()` with source throws before it contacts the World, creates a run, or enqueues anything unless this process has opted in.
77
- - **Delivery.** When a dynamic run reaches a deployment that has not opted in, the runtime does not execute its stored code. It fails the run with a `RUNTIME_ERROR` rather than retrying it.
76
+ - **Starting.** `start()` with source throws [`DynamicWorkflowsNotEnabledError`](/docs/api-reference/workflow-errors/dynamic-workflows-not-enabled-error) before it contacts the World, creates a run, or enqueues anything unless this process has opted in. The error is fatal, so a step that calls `start()` fails without retrying, and a run that fails on it is recorded as `USER_ERROR`.
77
+ - **Delivery.** When a dynamic run reaches a deployment that has not opted in, the runtime does not execute its stored code. It fails the run with `DynamicWorkflowsNotEnabledError` and a `USER_ERROR` code rather than retrying it.
78
78
  - **Health check.** A deployment advertises dynamic support in its [health check](/docs/api-reference/workflow-runtime/health-check) only when it has opted in.
79
79
 
80
80
  ### Same deployment only
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "title": "Advanced",
3
- "pages": ["dynamic-workflows"],
3
+ "pages": ["dynamic-workflows", "quickjs-runtime"],
4
4
  "defaultOpen": false
5
5
  }
@@ -0,0 +1,77 @@
1
+ ---
2
+ title: QuickJS Runtime
3
+ description: Keep long-running workflows fast by resuming from a saved snapshot instead of replaying every event.
4
+ type: guide
5
+ summary: Run workflow functions on the QuickJS runtime with snapshotting so resume cost stays flat and runs are exempt from the per-run event limit.
6
+ prerequisites:
7
+ - /docs/how-it-works/event-sourcing
8
+ related:
9
+ - /docs/configuration/runtime-tuning#workflow_vm
10
+ - /docs/errors/max-events-exceeded
11
+ - /docs/errors/replay-timeout
12
+ ---
13
+
14
+ Every time a workflow resumes, it re-executes from the top and replays its [event log](/docs/how-it-works/event-sourcing) to get back to where it left off. That takes milliseconds for most runs. For agents, chat sessions, and loops that run for days, the log keeps growing, so each resume gets slower and the run eventually fails with [`MAX_EVENTS_EXCEEDED`](/docs/errors/max-events-exceeded) or [`REPLAY_TIMEOUT`](/docs/errors/replay-timeout).
15
+
16
+ The QuickJS runtime fixes this. It runs your workflow functions in a [QuickJS](https://github.com/quickjs-ng/quickjs) VM instead of the default `node:vm` context and, once a run has processed 1,000 events, saves the VM's memory when the run suspends. The next resume restores that snapshot and replays only the events recorded since, so resume cost stays roughly flat however long the run gets. Runs on the QuickJS runtime with snapshotting are also exempt from the default per-run event limit.
17
+
18
+ Step functions are not affected. They always run with full Node.js access.
19
+
20
+ ## Enable it
21
+
22
+ Set `WORKFLOW_VM=quickjs` in the environment that starts runs, which is the process that calls [`start()`](/docs/api-reference/workflow-api/start):
23
+
24
+ ```bash
25
+ WORKFLOW_VM=quickjs
26
+ ```
27
+
28
+ Snapshotting is on by default under QuickJS, so that is the only variable you need. See [Tuning](#tuning) to change how often a run snapshots.
29
+
30
+ <Callout type="info">
31
+ The exemption from the per-run event limit needs `workflow` 5.2.3 or later. Earlier versions snapshot the same way, but only record the snapshot policy on the run when you also set `WORKFLOW_SNAPSHOT_THRESHOLD`.
32
+ </Callout>
33
+
34
+ Only runs started after the change use the QuickJS runtime. A run keeps the VM and snapshot policy it started with, so runs already in progress are not changed, and a run that already failed is not revived. Start it again.
35
+
36
+ The setting applies to every workflow the process starts.
37
+
38
+ ### World support
39
+
40
+ Snapshots are stored by your World, next to the run's event log:
41
+
42
+ | World | Snapshots | Notes |
43
+ | --- | --- | --- |
44
+ | Vercel World | Encrypted | Each run has an encryption key, and its snapshots are encrypted and authenticated with it. |
45
+ | Local World, Postgres World | Plaintext | Runs have no encryption key, so snapshots are stored the same way as the event log and payloads. Protect snapshot storage like the rest of the World's storage. |
46
+ | Other Worlds | Depends on the World | A World that implements snapshot storage snapshots by default, encrypted when it provides a run encryption key. Without snapshot storage, runs still execute on QuickJS and replay the full log on every resume. |
47
+
48
+ The exemption from the per-run event limit applies on the Local World and the Vercel World.
49
+
50
+ ## Check your workflow code first
51
+
52
+ QuickJS does not provide a few globals inside workflow functions. If your workflow functions use any of these, move the call into a step:
53
+
54
+ | Not available in workflow functions | What to do |
55
+ | --- | --- |
56
+ | `Intl.*`, and `toLocaleString()`-style methods called with an explicit locale | Format in a step |
57
+ | `crypto.subtle.*`, including `digest` | Hash or sign in a step |
58
+ | `WebAssembly`, `Atomics` | Use them in a step |
59
+
60
+ `crypto.randomUUID()` and `crypto.getRandomValues()` still work and stay deterministic. See [`WORKFLOW_VM`](/docs/configuration/runtime-tuning#workflow_vm) for the full list.
61
+
62
+ ## Tuning
63
+
64
+ Snapshotting needs no configuration. To change how often a run snapshots, set `WORKFLOW_SNAPSHOT_THRESHOLD`. This is the same entry as on the [Runtime tuning](/docs/configuration/runtime-tuning#workflow_snapshot_threshold) page:
65
+
66
+ <include>../configuration/runtime-tuning.mdx#workflow_snapshot_threshold</include>
67
+
68
+ ## On Vercel
69
+
70
+ Add `WORKFLOW_VM=quickjs` to your project's environment variables, then redeploy. You can add it in two ways:
71
+
72
+ - **From a run.** When a run fails at the event limit, times out while replaying, or passes 20,000 events, its page in the Workflows observability tab shows an **Optimize Long Runs** button. It adds the variable to Production and prompts you to redeploy.
73
+ - **From project settings.** Open **Settings**, then **Environment Variables**, add the variable, and redeploy.
74
+
75
+ Runs on Vercel keep executing on the deployment they started on, so the redeploy does not affect runs in progress.
76
+
77
+ For every setting and what a snapshot contains, see [Runtime tuning](/docs/configuration/runtime-tuning#workflow-vm-engine).
@@ -0,0 +1,57 @@
1
+ ---
2
+ title: deleteRuns
3
+ description: Delete the stored data of finished workflow runs in one call.
4
+ type: reference
5
+ summary: Use deleteRuns to delete the inputs, outputs, streams, and hook payloads of up to 100 finished runs.
6
+ related:
7
+ - /docs/observability/retention
8
+ - /docs/api-reference/workflow-api/get-run
9
+ ---
10
+
11
+ Deletes the stored data of up to 100 finished runs: their inputs, outputs and errors, their steps' and events' payloads, their hook payloads, and their stream contents. Metadata is not deleted: the runs stay listed, and so do their steps, events and hooks, with their IDs, names, statuses, timestamps and attributes. Only the payloads go, reading back as expired. This cannot be undone. See [Data retention](/docs/observability/retention#deleting-a-finished-runs-data).
12
+
13
+ For a single run, call [`run.delete()`](/docs/api-reference/workflow-api/get-run#delete-a-finished-runs-data) instead.
14
+
15
+ {/* @skip-typecheck: abbreviated usage; the run IDs are the reader's own */}
16
+ ```typescript lineNumbers
17
+ import { deleteRuns } from "workflow/api";
18
+
19
+ const { summary, results } = await deleteRuns([runIdA, runIdB]); // [!code highlight]
20
+ ```
21
+
22
+ `deleteRuns()` never cancels a run: a run that hasn't finished is answered `skipped` and keeps running. Cancel it first to delete its data now.
23
+
24
+ ## API signature
25
+
26
+ ### Parameters
27
+
28
+ <TSDoc
29
+ definition={`
30
+ import { deleteRuns } from "workflow/api";
31
+ export default deleteRuns;`}
32
+ showSections={["parameters"]}
33
+ />
34
+
35
+ ### Returns
36
+
37
+ A summary that counts each outcome, and one result per run in the order of `runIds`. Each result has one of these outcomes:
38
+
39
+ | Outcome | Meaning |
40
+ | --- | --- |
41
+ | `deleted` | The run's data was deleted. |
42
+ | `already_deleted` | The run's data was already gone, from an earlier deletion or `experimental_retention: 0`. |
43
+ | `skipped` | The run hasn't finished, so nothing was deleted. `status` is the run's status. |
44
+ | `not_created` | The run was cancelled before it was created. What it held is deleted. |
45
+ | `not_found` | No run has this ID. |
46
+ | `failed` | The deletion didn't complete. `code` says why, and `retryable` says whether retrying can succeed. |
47
+
48
+ ## Retries
49
+
50
+ Deletion is idempotent, so retrying is always safe: a run that was already handled answers `already_deleted`.
51
+
52
+ - Inside a step, runs answered `failed` with `retryable: true` are sent again once, on their own, a second later. If any still fail, or the World rate-limits a request, it throws a [`RetryableError`](/docs/api-reference/workflow/retryable-error) so the step retries the whole batch, after the World's requested delay, or 10 seconds when it gives none.
53
+ - Outside a step, `failed` results are returned as they are, so retry the runs answered `failed` with `retryable: true` yourself. A rate limit throws the World's `ThrottleError`, whose `retryAfter` is the number of seconds to wait.
54
+
55
+ ## Errors
56
+
57
+ `deleteRuns()` throws when `runIds` is empty, contains duplicates, or has more than 100 IDs, and when the configured World doesn't support deleting run data. Send more runs in batches of 100. The World enforces the same limit.
@@ -199,6 +199,39 @@ export async function POST(req: Request) {
199
199
 
200
200
  The options object is optional: `await run.cancel()` cancels the run without recording a reason.
201
201
 
202
+ ### Delete a finished run's data
203
+
204
+ Delete the stored data of a run that has finished: its input, output and error, its steps' and events' payloads, its hook payloads, and its stream contents. Metadata is not deleted: the run stays listed, and so do its steps, events and hooks, with their IDs, names, statuses, timestamps and attributes. Only the payloads go, reading back as expired. This cannot be undone. See [Data retention](/docs/observability/retention#deleting-a-finished-runs-data).
205
+
206
+ ```typescript lineNumbers
207
+ import { getRun } from "workflow/api";
208
+
209
+ export async function POST(req: Request) {
210
+ const { runId } = await req.json();
211
+
212
+ const result = await getRun(runId).delete(); // [!code highlight]
213
+ switch (result.outcome) {
214
+ case "deleted":
215
+ case "already_deleted":
216
+ case "not_created":
217
+ return Response.json({ deleted: true });
218
+ case "skipped":
219
+ // The run hasn't finished. Cancel it first to delete its data now.
220
+ return Response.json({ deleted: false, status: result.status }, { status: 409 });
221
+ case "not_found":
222
+ return Response.json({ deleted: false }, { status: 404 });
223
+ case "failed":
224
+ // Deletion is idempotent: a retryable failure can be requested again.
225
+ return Response.json(
226
+ { deleted: false, retryable: result.retryable },
227
+ { status: 503 }
228
+ );
229
+ }
230
+ }
231
+ ```
232
+
233
+ `delete()` never cancels a run: a run that hasn't finished answers `skipped` and keeps running. It runs as a step, so inside a workflow a retryable failure throws a `RetryableError` and the step retries. It throws if the configured World doesn't support deleting run data. To delete the data of many runs in one call, use [`deleteRuns()`](/docs/api-reference/workflow-api/delete-runs).
234
+
202
235
  ## Related functions
203
236
 
204
237
  - [`start()`](/docs/api-reference/workflow-api/start): Start a new workflow and get its run ID.
@@ -25,6 +25,9 @@ The `workflow/api` package provides runtime functions to inspect runs, start new
25
25
  <Card href="/docs/api-reference/workflow-api/get-run" title="getRun()">
26
26
  Get workflow run status and metadata without waiting for completion.
27
27
  </Card>
28
+ <Card href="/docs/api-reference/workflow-api/delete-runs" title="deleteRuns()">
29
+ Delete the stored data of finished runs.
30
+ </Card>
28
31
  <Card href="/docs/api-reference/workflow-api/register-lifecycle-hooks" title="registerLifecycleHooks()">
29
32
  Observe run completions and failures with global handlers.
30
33
  </Card>
@@ -268,6 +268,6 @@ async function workflow(input) {
268
268
 
269
269
  The return type is `Run<unknown>`: the source's shape is only known to whatever generated it, so there is nothing to infer. The workflow ID is derived from the source and its step bindings — it cannot be supplied.
270
270
 
271
- A dynamic start throws a `WorkflowRuntimeError`, before anything is written, when the deployment has not opted in, when `deploymentId` targets another deployment (including `'latest'` resolving to one), or when the World's backend does not support dynamic-source storage.
271
+ A dynamic start throws before anything is written when the deployment has not opted in ([`DynamicWorkflowsNotEnabledError`](/docs/api-reference/workflow-errors/dynamic-workflows-not-enabled-error)), and a `WorkflowRuntimeError` when `deploymentId` targets another deployment (including `'latest'` resolving to one) or when the World's backend does not support dynamic-source storage. Earlier releases threw `WorkflowRuntimeError` for the opt-in refusal too, so code that checked for it with `WorkflowRuntimeError.is()` should use `DynamicWorkflowsNotEnabledError.is()`.
272
272
 
273
273
  See [Dynamic Workflows](/docs/advanced/dynamic-workflows) for the opt-in, the source rules and limits, the predefined runtime bindings (`steps`, `sleep`, `createHook`), how the code is stored, and the security model.
@@ -0,0 +1,57 @@
1
+ ---
2
+ title: DynamicWorkflowsNotEnabledError
3
+ description: Thrown when a dynamic workflow is started or delivered on a deployment that has not enabled dynamic workflows.
4
+ type: reference
5
+ summary: Catch DynamicWorkflowsNotEnabledError when start() is given workflow source on a deployment without WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1.
6
+ related:
7
+ - /docs/advanced/dynamic-workflows
8
+ - /docs/api-reference/workflow-api/start
9
+ ---
10
+
11
+ `DynamicWorkflowsNotEnabledError` is thrown when your project has not enabled [dynamic workflows](/docs/advanced/dynamic-workflows):
12
+
13
+ - `start()` is given workflow source on a deployment that has not opted in. No run is created.
14
+ - A dynamic run is delivered to a deployment that has not opted in. Its stored code is not executed, and the run fails.
15
+
16
+ This is a configuration problem in your project, not an SDK error, so a run that fails on it is recorded with the `USER_ERROR` code. The error is fatal: a step that calls `start()` fails on the first attempt instead of retrying.
17
+
18
+ To fix it, set the `WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1` environment variable on your project, then redeploy (or restart your dev server) so the new value takes effect. See [Enabling dynamic workflows](/docs/advanced/dynamic-workflows#enabling-dynamic-workflows).
19
+
20
+ ```typescript lineNumbers
21
+ import { DynamicWorkflowsNotEnabledError } from "workflow/errors"
22
+ declare const error: unknown; // @setup
23
+
24
+ if (DynamicWorkflowsNotEnabledError.is(error)) { // [!code highlight]
25
+ console.error("Dynamic workflows are not enabled:", error.message);
26
+ }
27
+ ```
28
+
29
+ ## API signature
30
+
31
+ ### Properties
32
+
33
+ <TSDoc
34
+ definition={`
35
+ interface DynamicWorkflowsNotEnabledError {
36
+ /** Always true: retrying cannot succeed until the project opts in. */
37
+ fatal: true;
38
+ /** The error message, including how to enable dynamic workflows. */
39
+ message: string;
40
+ }
41
+ export default DynamicWorkflowsNotEnabledError;`}
42
+ />
43
+
44
+ ### Static methods
45
+
46
+ #### `DynamicWorkflowsNotEnabledError.is(value)`
47
+
48
+ Type-safe check for `DynamicWorkflowsNotEnabledError` instances. Preferred over `instanceof` because it works across module boundaries and virtual machine contexts.
49
+
50
+ ```typescript
51
+ import { DynamicWorkflowsNotEnabledError } from "workflow/errors"
52
+ declare const error: unknown; // @setup
53
+
54
+ if (DynamicWorkflowsNotEnabledError.is(error)) {
55
+ // error is typed as DynamicWorkflowsNotEnabledError
56
+ }
57
+ ```
@@ -54,6 +54,9 @@ All errors extend [`WorkflowError`](/docs/api-reference/workflow-errors/workflow
54
54
  <Card href="/docs/api-reference/workflow-errors/workflow-start-error" title="WorkflowStartError">
55
55
  Thrown when `start({ experimental_hook })` cannot confirm whether its run was queued or admitted.
56
56
  </Card>
57
+ <Card href="/docs/api-reference/workflow-errors/dynamic-workflows-not-enabled-error" title="DynamicWorkflowsNotEnabledError">
58
+ Thrown when a dynamic workflow is started or delivered on a deployment that has not enabled dynamic workflows.
59
+ </Card>
57
60
  <Card href="/docs/api-reference/workflow-errors/run-expired-error" title="RunExpiredError">
58
61
  Thrown when a workflow run has expired and can no longer be operated on.
59
62
  </Card>
@@ -13,6 +13,7 @@
13
13
  "workflow-run-not-completed-error",
14
14
  "workflow-runtime-error",
15
15
  "workflow-start-error",
16
+ "dynamic-workflows-not-enabled-error",
16
17
  "workflow-world-error",
17
18
  "throttle-error",
18
19
  "entity-conflict-error",
@@ -247,6 +247,8 @@ To cancel a run, create a `run_cancelled` event through `world.events.create()`
247
247
 
248
248
  To cancel a batch in one call, a world may implement the optional `runs.cancelMany({ runIds })`. It returns a summary plus a per-run outcome (`cancelled`, `already_cancelled`, `not_cancellable`, `not_found`, or `failed`). Backends that omit it fall back to per-run cancellation automatically.
249
249
 
250
+ To delete the stored data of finished runs, a world may implement the optional `runs.deleteDataMany({ runIds })`. It deletes run payloads but not metadata: it keeps the run, step, event and hook records listed, with their IDs, names, statuses, timestamps and the run's attributes. It must delete only the data of finished runs and answer every other run `skipped` without cancelling it. It returns a summary plus a per-run outcome, in the order of `runIds`: `deleted`, `already_deleted` (the data was already gone; anything left behind is deleted too), `skipped` (with a `reason` and the run's `status`), `not_created`, `not_found`, or `failed` (with a `code`, and `retryable` when retrying can succeed). Deletion must be idempotent. Backends that omit it have no fallback: `deleteRuns()` throws.
251
+
250
252
  ### WorkflowRun type
251
253
 
252
254
  | Field | Type | Description |
@@ -2,7 +2,7 @@
2
2
  title: CLI and Web UI
3
3
  description: CLI flags and environment variables for inspecting local, Postgres, and Vercel Workflow runs.
4
4
  type: reference
5
- summary: Configure workflow inspect, workflow cancel, workflow web, workflow health, workflow migrate, and observability tooling.
5
+ summary: Configure workflow inspect, workflow cancel, workflow delete, workflow web, workflow health, workflow migrate, and observability tooling.
6
6
  related:
7
7
  - /docs/observability
8
8
  - /docs/configuration/worlds
@@ -210,10 +210,37 @@ per flag.
210
210
 
211
211
  ### `--confirm` / `-y`
212
212
 
213
- - Command: `workflow cancel`
213
+ - Command: `workflow cancel`, `workflow delete`
214
214
  - Default: disabled
215
215
  - Skips the interactive confirmation prompt.
216
216
 
217
+ ## Delete
218
+
219
+ `workflow delete <runId>...` deletes the stored data of finished runs: their inputs, outputs and errors, their steps' and events' payloads, their hook payloads, and their stream contents. Metadata is not deleted: the runs, steps, events and hooks stay listed with their IDs, names, statuses, timestamps and attributes, and only the payloads read back as expired. This cannot be undone, so the command asks for confirmation unless you pass [`--confirm` / `-y`](#--confirm---y), and aborts without a terminal to ask on. The local [Web UI](#web-ui) doesn't offer it. For runs on Vercel, you can also delete run data from the [Vercel dashboard](https://vercel.com/docs/workflows/retention#delete-the-data-of-finished-runs).
220
+
221
+ ```bash
222
+ pnpx workflow delete <runId>
223
+ ```
224
+
225
+ Pass several run IDs to delete the data of several runs, and [`--backend`](#--backend---b) to pick the World, such as `--backend vercel`. To delete many runs, pass `-` to read the run IDs from stdin, one per line or separated by whitespace. Reading from stdin requires `-y`.
226
+
227
+ ```bash
228
+ cat run-ids.txt | pnpx workflow delete - -y --strict
229
+ ```
230
+
231
+ - Only finished runs have their data deleted. A run that hasn't finished is reported as skipped and keeps running; cancel it first to delete its data now.
232
+ - Run IDs are sent in batches of 100, the most the World accepts in one request.
233
+ - A run that fails with a retryable error is retried, as is a rate-limited request, up to four attempts in all, after the delay the World asks for when it gives one.
234
+ - The command prints a line for each run that was skipped, not found, or failed, then a summary. The summary counts runs that were cancelled before they were created (`not_created`) as deleted. With `--json`, it prints the per-run results instead, which keep them separate.
235
+ - It exits with `1` when a run still failed after its retries, and `0` otherwise, including when runs were skipped or not found. Running it again is safe: runs already handled are reported as already deleted.
236
+ - The configured World must support deleting run data; see [Data retention](/docs/observability/retention#deleting-a-finished-runs-data).
237
+
238
+ ### `--strict`
239
+
240
+ - Command: `workflow delete`
241
+ - Default: disabled
242
+ - Exits with `1` unless the data of every run is gone: also when a run isn't found (a mistyped ID, or a run from another project) or hasn't finished. Use it in scripts that must delete every run they name.
243
+
217
244
  ## Migrate from Inngest
218
245
 
219
246
  `workflow migrate inngest [paths...]` rewrites Inngest functions as Workflow SDK code in place: each `createFunction()` becomes a `"use workflow"` function, and each `step.run()` closure becomes a `"use step"` function whose parameters are the variables the closure captured. It prints every step it lifted with its captured variables, and marks what needs a decision with `TODO(workflow-migrate)` comments. See [Migrating from Inngest](/docs/comparisons/workflow-sdk-vs-inngest#run-the-codemod) for what it changes.
@@ -158,8 +158,10 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
158
158
 
159
159
  - Default: enabled
160
160
  - Fast path for a run's first delivery.
161
+ - Applies only while that delivery's queue message is at most 15 seconds old. An older one, such as a platform re-running a crashed invocation, loads the event log first.
161
162
  - Stops forcing optimistic inline step start once the run creates a hook or wait.
162
- - Set `0` or `false` to disable.
163
+ - A run started with `start({ experimental_hook })` never runs steps before `run_started` returns, but its first delivery still writes `run_started` without loading the event log first.
164
+ - Set `0` or `false` to disable, including for such runs.
163
165
 
164
166
  ### `WORKFLOW_OPTIMISTIC_INLINE_START`
165
167
 
@@ -191,7 +193,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
191
193
  - Values: `node` or `quickjs`
192
194
  - Selects the sandboxed VM engine that executes workflow functions (`"use workflow"`). Step functions are unaffected and always run with full Node.js access.
193
195
  - `node` (default) runs workflow code in a [`node:vm`](https://nodejs.org/api/vm.html) context. Every resume replays the run's full event log, so resume cost grows with the log, and runs are subject to the World's default [per-run event limit](/docs/errors/max-events-exceeded).
194
- - `quickjs` runs workflow code in a [QuickJS](https://github.com/quickjs-ng/quickjs) VM compiled to WebAssembly (via [`quickjs-wasi`](https://github.com/vercel-labs/quickjs-wasi)). **Use it for long-running workflows**: agents, chat sessions, and loops that wait on hooks or sleeps, or any run with many steps. With snapshotting (on by default for encrypted runs, see [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold); on world-local and world-postgres also set [`WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED`](#workflow_snapshot_allow_unencrypted)), a run resumes from a VM-memory snapshot and replays only the events recorded since, so resume cost stays roughly flat as the log grows, and the run is exempt from the default per-run event limit on the Local and Vercel Worlds. It also runs on platforms that do not implement `node:vm`.
196
+ - `quickjs` runs workflow code in a [QuickJS](https://github.com/quickjs-ng/quickjs) VM compiled to WebAssembly (via [`quickjs-wasi`](https://github.com/vercel-labs/quickjs-wasi)). **Use it for long-running workflows**: agents, chat sessions, and loops that wait on hooks or sleeps, or any run with many steps. With snapshotting (on by default, see [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold)), a run resumes from a VM-memory snapshot and replays only the events recorded since, so resume cost stays roughly flat as the log grows, and the run is exempt from the default per-run event limit on the Local and Vercel Worlds. It also runs on platforms that do not implement `node:vm`.
195
197
  - Both engines implement the same event-replay execution model (seeded PRNG, deterministic clock, and correlation-ID sequences are identical), so workflow code that sticks to plain JavaScript and the Workflow APIs runs unchanged. To switch, set `WORKFLOW_VM=quickjs` in the environment that starts runs, and runs started after that use QuickJS. The few globals QuickJS does not provide in workflow functions are listed below.
196
198
  - Global-surface differences under `quickjs` apply to workflow functions only. Step functions always have full Node.js, so the fix for each is to move that call into a step:
197
199
  - `crypto.getRandomValues()` and `crypto.randomUUID()` are provided and deterministic (seeded like the node engine's). All `crypto.subtle.*` methods, including `digest`, throw with guidance to move to a step function. The node engine supports `digest`.
@@ -226,16 +228,11 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
226
228
  What a snapshot contains, and how it is protected:
227
229
 
228
230
  - A snapshot is the workflow VM's memory: the workflow's code and in-memory state, including step results and hook payloads it holds, and the copy of `process.env` the VM exposes. It is executable state, so write access to snapshot storage is equivalent to running code in the workflow VM.
229
- - Snapshots are compressed and then encrypted with the run's encryption key. The encryption also authenticates the snapshot: on restore, the runtime rejects any snapshot that isn't encrypted with the run's key, or whose stored metadata doesn't match the metadata sealed inside it.
230
- - By default, runs without an encryption key are never snapshotted. Only world-vercel provides run encryption keys. On world-local and world-postgres, set `WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED=1` on the workflow handler to snapshot anyway. Those snapshots are stored in plaintext (in `.workflow-data/snapshots/` or the `workflow_snapshots` table) and are not authenticated, so only enable this where snapshot storage is as trusted as your deployment.
231
+ - When the run has an encryption key, its snapshots are compressed and then encrypted with that key. The encryption also authenticates the snapshot: on restore, the runtime rejects any snapshot that isn't encrypted with the run's key, or whose stored metadata doesn't match the metadata sealed inside it.
232
+ - Runs without an encryption key (world-local, world-postgres, and any World that doesn't implement `getEncryptionKeyForRun()`) are snapshotted in plaintext, the same as their event log and payloads (in `.workflow-data/snapshots/` or the `workflow_snapshots` table). Those snapshots are not authenticated, so snapshot storage needs the same protection as the rest of the World's storage.
231
233
  - A restored run sees `process.env` as of the current invocation, the same as a full replay.
232
234
  - Snapshots are deleted after the run reaches a terminal state. world-local and world-postgres have no separate retention for them, so a snapshot of a run that ends without any invocation observing it (for example, one cancelled externally) stays until you remove it.
233
235
 
234
- ### `WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED`
235
-
236
- - Default: disabled
237
- - Set `1` or `true` on the workflow handler to let the QuickJS engine persist VM snapshots for runs without an encryption key. See [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold) for what that stores.
238
-
239
236
  ## Dynamic workflows
240
237
 
241
238
  ### `WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS`
@@ -403,13 +400,18 @@ Everything above describes spec 8 runs, the default. The experimental spec 9 run
403
400
 
404
401
  ### `WORKFLOW_ORCHESTRATOR_LINGER_MS`
405
402
 
406
- - Default: `30000`
407
- - How long an orchestrator with nothing left to run stays live on the event feed while the run waits on a background step. `0` turns it off, for hooks too.
403
+ - Default: `5000`
404
+ - How long an orchestrator with nothing left to run stays live on the event feed while the run waits on a background step. A step that takes longer ends the invocation, and its outcome starts a new one. `0` turns it off, for hooks and sleeps too.
408
405
 
409
406
  ### `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`
410
407
 
411
408
  - Default: `5000`, and never more than [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](#workflow_orchestrator_linger_ms)
412
- - How long an orchestrator with nothing left to run stays live on the event feed while the run waits only on open hooks. Any hook that is created and not disposed counts, however rarely it is resumed. `0` turns it off.
409
+ - How long an orchestrator with nothing left to run stays live on the event feed while the run waits only on open hooks. Set it below `WORKFLOW_ORCHESTRATOR_LINGER_MS` to keep background steps on a longer window than hooks. Any hook that is created and not disposed counts, however rarely it is resumed. `0` turns it off.
410
+
411
+ ### `WORKFLOW_ORCHESTRATOR_WAIT_LINGER_MS`
412
+
413
+ - Default: [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](#workflow_orchestrator_linger_ms) (`5000`), and never more than it
414
+ - How far ahead a `sleep()` may end for an orchestrator with nothing left to run to stay live on the event feed until it does, instead of ending the invocation and starting a new one when the sleep's timer fires. A sleep up to 1 second longer than this still counts, so a sleep as long as the window lingers despite small clock differences. Only for a sleep that ends before the invocation's inline window less [`WORKFLOW_INLINE_STEP_DEADLINE_MARGIN_MS`](#workflow_inline_step_deadline_margin_ms), and only on a World with a live event feed (such as world-vercel and world-postgres; world-local has none, so it never lingers). On those Worlds, a `run.wakeUp()` sent during such a sleep is not applied, so the sleep runs its full length. `0` turns it off.
413
415
 
414
416
  ### `WORKFLOW_ORCHESTRATOR_READ_TIMEOUT_MS`
415
417
 
@@ -185,6 +185,15 @@ The Postgres World is a self-hosted durable backend for long-running server proc
185
185
  - Set to `true` only when the application awaits `world.close()` before closing its workflow HTTP server and caller-owned pool.
186
186
  - Prevents Graphile Worker's default handler from terminating the process before the application's remaining cleanup finishes.
187
187
 
188
+ ### `skipWorkers`
189
+
190
+ - Environment variable: `WORKFLOW_POSTGRES_SKIP_WORKERS` (`1` enables)
191
+ - Default: `false`
192
+ - Runs no workers in this process. It can still start runs, resume hooks, cancel runs and read them, but it claims none of the jobs those create and doesn't recover interrupted runs at startup.
193
+ - At least one process with workers must share the database, `jobPrefix` and, when one is set, `deploymentId`: it executes those runs. A run on a deployment ID no worker claims stays pending.
194
+ - A run this process created but didn't get to enqueue (it stopped in between) is recovered the next time a process with workers starts.
195
+ - Use it for processes that should send work but not execute it, such as those in a region far from the database. See [Postgres World: `WORKFLOW_POSTGRES_SKIP_WORKERS`](/worlds/postgres#workflow_postgres_skip_workers).
196
+
188
197
  ### `jobLockStaleSeconds`
189
198
 
190
199
  - Environment variable: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`
@@ -15,7 +15,7 @@ When a workflow run fails, its `errorCode` identifies the failure category. You
15
15
 
16
16
  | Code | Description |
17
17
  | --- | --- |
18
- | `USER_ERROR` | An error thrown by workflow or step code, including an unhandled step failure or `FatalError`. |
18
+ | `USER_ERROR` | An error thrown by workflow or step code, including an unhandled step failure or `FatalError`, or a project configuration problem such as [`DynamicWorkflowsNotEnabledError`](/docs/api-reference/workflow-errors/dynamic-workflows-not-enabled-error). |
19
19
  | `RUNTIME_ERROR` | The Workflow runtime encountered an internal error, such as missing runtime data or an invariant failure. Persistent occurrences should be [reported](https://github.com/vercel/workflow/issues). |
20
20
  | [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) | The run's event log cannot be replayed because it contains orphaned or mismatched events, a gap, or an unreadable stored payload. |
21
21
  | [`REPLAY_DIVERGENCE`](/docs/errors/replay-divergence) | One replay could not consume the event log deterministically. The runtime automatically retries before treating repeated divergence as a corrupted event log. |
@@ -56,7 +56,6 @@ A run qualifies when its `executionContext` records `workflowVm: "quickjs"` and
56
56
 
57
57
  - Only runs started after the change are exempt. Runs keep the VM and snapshot policy they started with.
58
58
  - Runs that have already failed with `MAX_EVENTS_EXCEEDED` are not revived. Start them again.
59
- - On the Local World and Postgres World, snapshots are only stored when [`WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED=1`](/docs/configuration/runtime-tuning#workflow_snapshot_allow_unencrypted) is set. Without it, exempt runs still replay the full log on every invocation.
60
59
 
61
60
  ### Split the work into child workflows
62
61
 
@@ -10,7 +10,7 @@ related:
10
10
  ---
11
11
 
12
12
  <CopyPrompt
13
- text="In this NestJS app, run `npm i workflow @workflow/nest` and `npm i -D @swc/cli @swc/core`. Configure `nest-cli.json` with `compilerOptions.builder: &quot;swc&quot;` and `deleteOutDir: true`. Run `npx @workflow/nest init`, add `.swcrc` to `.gitignore`, and set package scripts `prebuild: &quot;npx @workflow/nest init --force&quot;` and `start:dev: &quot;npx @workflow/nest init --force && nest start --watch&quot;`. Import `WorkflowModule.forRoot()` from `@workflow/nest` in `src/app.module.ts` (use `{ moduleType: &quot;commonjs&quot;, distDir: &quot;dist&quot; }` if compiling CommonJS). Create `src/workflows/user-signup.ts` with `&quot;use workflow&quot;`, `sleep`, and `&quot;use step&quot;` helpers. Add a `POST /signup` controller method that reads `email`, calls `start(handleUserSignup, [email])` from `workflow/api`, and returns JSON. Run `npm run start:dev`, call `curl -X POST --json '{&quot;email&quot;:&quot;hello@example.com&quot;}' http://localhost:3000/signup`, and inspect with `npx workflow web` or `npx workflow inspect runs`."
13
+ text="In this NestJS app, run `npm i workflow @workflow/nest` and `npm i -D @swc/cli @swc/core@~1.15.18`. Configure `nest-cli.json` with `compilerOptions.builder: &quot;swc&quot;` and `deleteOutDir: true`. Run `npx @workflow/nest init`, add `.swcrc` to `.gitignore`, and set package scripts `prebuild: &quot;npx @workflow/nest init --force&quot;` and `start:dev: &quot;npx @workflow/nest init --force && nest start --watch&quot;`. Import `WorkflowModule.forRoot()` from `@workflow/nest` in `src/app.module.ts` (use `{ moduleType: &quot;commonjs&quot;, distDir: &quot;dist&quot; }` if compiling CommonJS). Create `src/workflows/user-signup.ts` with `&quot;use workflow&quot;`, `sleep`, and `&quot;use step&quot;` helpers. Add a `POST /signup` controller method that reads `email`, calls `start(handleUserSignup, [email])` from `workflow/api`, and returns JSON. Run `npm run start:dev`, call `curl -X POST --json '{&quot;email&quot;:&quot;hello@example.com&quot;}' http://localhost:3000/signup`, and inspect with `npx workflow web` or `npx workflow inspect runs`."
14
14
  />
15
15
 
16
16
  Set up your first durable workflow in a NestJS app and learn the core Workflow SDK concepts.
@@ -92,12 +92,14 @@ export class AppModule {}
92
92
 
93
93
  NestJS supports SWC as an alternative compiler for faster builds. The Workflow SDK uses an SWC plugin to transform workflow files.
94
94
 
95
- Install the required SWC packages:
95
+ Install the required SWC packages. `@swc/core` is pinned to 1.15.x because the Workflow SWC plugin does not run on `@swc/core` 1.16 yet:
96
96
 
97
97
  ```package-install
98
- npm i -D @swc/cli @swc/core
98
+ npm i -D @swc/cli @swc/core@~1.15.18
99
99
  ```
100
100
 
101
+ Don't upgrade `@swc/core` past 1.15 (for example with `pnpm update --latest`, Dependabot or Renovate) until the Workflow SWC plugin supports 1.16; `npx @workflow/nest init` warns if the installed version isn't 1.15.x.
102
+
101
103
  Ensure your `nest-cli.json` has SWC as the builder:
102
104
 
103
105
  ```json title="nest-cli.json" lineNumbers
@@ -91,6 +91,50 @@ caller can tell a successful run whose result is gone from a failed one whose
91
91
  error is gone. If the run's metadata is gone too, the World reports the run as
92
92
  missing and you get `WorkflowRunNotFoundError` instead.
93
93
 
94
+ ## Deleting a finished run's data
95
+
96
+ To delete the data of a run that has already finished, call
97
+ [`run.delete()`](/docs/api-reference/workflow-api/get-run#delete-a-finished-runs-data),
98
+ call [`deleteRuns()`](/docs/api-reference/workflow-api/delete-runs)
99
+ for up to 100 runs at once, or run `workflow delete` from the
100
+ [CLI](/docs/configuration/cli-and-web-ui#delete). The World deletes the
101
+ same data a run started with `experimental_retention: 0` has deleted when it
102
+ ends. Metadata is not deleted: the runs stay listed, and so do their steps,
103
+ events and hooks, with their IDs, names, statuses, timestamps and attributes.
104
+
105
+ {/* @skip-typecheck: abbreviated usage; the run IDs are the reader's own */}
106
+ ```typescript lineNumbers
107
+ import { deleteRuns, getRun } from 'workflow/api'
108
+
109
+ await getRun(runId).delete() // [!code highlight]
110
+ await deleteRuns([runIdA, runIdB]) // [!code highlight]
111
+ ```
112
+
113
+ ```bash
114
+ pnpx workflow delete <runId>
115
+ ```
116
+
117
+ Only finished runs have their data deleted. A run that is still running,
118
+ sleeping, or waiting on a hook is answered `skipped` and left untouched:
119
+ deleting data never cancels a run. To delete an active run's data now, cancel
120
+ it first, then delete its data. Each run gets its own outcome: `deleted`,
121
+ `already_deleted` (its data was already gone), `skipped`, `not_created`,
122
+ `not_found`, or `failed`. A `failed` outcome with `retryable: true` can be
123
+ retried, since deletion is idempotent. Inside a step, a retryable failure
124
+ throws a `RetryableError`, so the step retries on its own.
125
+
126
+ Deleting run data is optional for a World to implement, and there is no
127
+ fallback: on a World that doesn't support it, `run.delete()` and
128
+ `deleteRuns()` throw, and `workflow delete` exits with an error. The
129
+ [Local World](/worlds/local), the [Postgres World](/worlds/postgres) and the
130
+ [Vercel World](/worlds/vercel) support it. Deleting run data doesn't change
131
+ how a run is billed; see the
132
+ [Vercel Workflows docs](https://vercel.com/docs/workflows/retention).
133
+
134
+ Nothing records that a run's data was deleted: the run reads back as expired,
135
+ the same as a run whose retention ended. If you need a record of the deletion,
136
+ keep it yourself.
137
+
94
138
  ## Retention is implemented by the World
95
139
 
96
140
  The SDK records your preference; it does not enforce it. `start()` writes the
@@ -220,6 +220,20 @@ Before you go live, make sure that:
220
220
  - `/.well-known/workflow/v1/flow` is restricted so untrusted clients cannot reach it (see [Security](#security))
221
221
  - If more than one process shares the database, you have set [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) to the same value on every process, so another process picks up the jobs of one that dies
222
222
 
223
+ ### Kubernetes
224
+
225
+ The package includes a Helm chart for Kubernetes in its `chart` directory, and the helpers it relies on in `@workflow/world-postgres/kubernetes`. Each release pins its runs to its image tag with [`WORKFLOW_POSTGRES_DEPLOYMENT_ID`](#workflow_postgres_deployment_id), and older releases keep worker pods that finish their own runs:
226
+
227
+ - **Workers per version.** Each release gets a worker Deployment that runs only the runs it started. A rollout leaves the previous release's workers in place.
228
+ - **Scale to zero.** KEDA scales each version's workers on its due deliveries, which the application reports through `createBacklogEndpoints`. Workers drop to zero while that version's runs sleep or wait on a hook.
229
+ - **Pruning.** A CronJob deletes a version's workers once all its runs have finished, and recreates them for a version that still has unfinished runs. A run with `experimental_retention: 0` counts as unfinished until its data deletion is confirmed, about a minute after it ends.
230
+ - **Graceful shutdown.** `createLifecycle` stops a pod from receiving traffic, then lets its running deliveries finish before it exits.
231
+ - **Migrations.** An optional init container runs `bootstrap` before each pod starts.
232
+
233
+ The chart needs KEDA in the cluster, and an image whose entrypoint reads `WORKFLOW_ROLE` (`service`, `worker` or `prune`). The chart's README, in the same directory, covers the entrypoint, the image, and how long old versions keep running. To deploy workers with your own tooling instead, run `npx workflow-postgres-prune` after each deploy.
234
+ The package includes a Helm chart for Kubernetes in its `chart` directory, as an optional way for production deployments into Kubernetes clusters. It works by pinning each run to its image tag, and by keeping around older releases' worker pods until their runs finish. It's scale-to-zero and supports pruning.
235
+
236
+ See [`chart/README.md`](./chart/README.md) for more information.
223
237
  <Callout type="info">
224
238
  The Postgres World is not compatible with Vercel deployments. On Vercel, workflows automatically use the [Vercel World](/worlds/vercel) with zero configuration.
225
239
  </Callout>
@@ -295,6 +309,7 @@ The defaults work for a single process on a local database, so most apps set onl
295
309
  | [`WORKFLOW_POSTGRES_POLL_INTERVAL_MS`](#workflow_postgres_poll_interval_ms) | `500` ms | Idle job polling |
296
310
  | [`WORKFLOW_POSTGRES_MAX_POOL_SIZE`](#workflow_postgres_max_pool_size) | `10` | Connection pool size |
297
311
  | [`WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN`](#workflow_postgres_application_managed_shutdown) | off | Who coordinates shutdown |
312
+ | [`WORKFLOW_POSTGRES_SKIP_WORKERS`](#workflow_postgres_skip_workers) | off | Send work without executing it |
298
313
  | [`WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`](#workflow_postgres_headers_timeout_ms) | `0` ms (no deadline) | Hung delivery detection |
299
314
  | [`WORKFLOW_POSTGRES_BODY_TIMEOUT_MS`](#workflow_postgres_body_timeout_ms) | `0` ms (no deadline) | Stalled response detection |
300
315
  | [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) | unset: 300 s for spec 9 run-lease jobs only | Redelivery after a process dies |
@@ -389,6 +404,17 @@ Whether the application, instead of Graphile Worker, coordinates shutdown. Set t
389
404
 
390
405
  Change it when: the application or framework coordinates shutdown and awaits `world.close()` before closing its workflow HTTP server and any caller-owned pool. See [Application-managed shutdown](#application-managed-shutdown).
391
406
 
407
+ ### `WORKFLOW_POSTGRES_SKIP_WORKERS`
408
+
409
+ - Default: unset (`false`)
410
+ - Factory option: `skipWorkers`
411
+
412
+ Runs no workers in this process. Set to `1` to enable. The process can still start runs, resume hooks, cancel runs and read them, but it claims none of the jobs those create, and it doesn't recover interrupted runs at startup.
413
+
414
+ Its runs execute on processes with workers on the same database, `WORKFLOW_POSTGRES_JOB_PREFIX` and, when one is set, `WORKFLOW_POSTGRES_DEPLOYMENT_ID`, so at least one must be running. A run on a deployment ID that no worker claims stays pending. A run this process created but didn't get to enqueue (it stopped in between) is recovered the next time a process with workers starts. At startup the process logs the job prefix and deployment ID its runs need.
415
+
416
+ Change it when: some processes should send work without executing it, for example application instances in a region far from the database, whose step executions would wait on many cross-region round trips. Run the workers near the database.
417
+
392
418
  ### `WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`
393
419
 
394
420
  - Default: `0` (no deadline)
@@ -567,7 +593,7 @@ The Postgres World uses PostgreSQL as a durable backend:
567
593
 
568
594
  - **Storage**: Workflow runs, events, steps, and hooks are stored in PostgreSQL tables.
569
595
  - **Job queue**: [graphile-worker](https://github.com/graphile/worker) handles reliable job processing with retries.
570
- - **Crash recovery**: The next `start()` re-enqueues active runs. A running delivery also renews its job lock. If its process dies, any other process redelivers a spec 9 run's orchestrator job once its lock has gone unrenewed for 300 seconds, and with [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) set, any job of this World once its lock has gone unrenewed for that many seconds.
596
+ - **Crash recovery**: The next `start()` re-enqueues active runs, except a run parked on a hook or a wait that is not yet due with no wake left to deliver and no delivery in progress. A run's recovery job is keyed by the run, so repeated boots do not stack duplicates. A running delivery also renews its job lock. If its process dies, any other process redelivers a spec 9 run's orchestrator job once its lock has gone unrenewed for 300 seconds, and with [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) set, any job of this World once its lock has gone unrenewed for that many seconds.
571
597
  - **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.
572
598
 
573
599
  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).
@@ -137,6 +137,8 @@ Retention for the Vercel World is documented in the [Vercel Workflows docs](http
137
137
 
138
138
  To delete a run's payloads as soon as it finishes, start it with [`experimental_retention: 0`](/docs/observability/retention).
139
139
 
140
+ To delete the payloads of runs that have already finished, call [`run.delete()`](/docs/api-reference/workflow-api/get-run#delete-a-finished-runs-data) or [`deleteRuns()`](/docs/api-reference/workflow-api/delete-runs), run [`workflow delete`](/docs/configuration/cli-and-web-ui#delete), or select **Delete Data** in the Vercel dashboard.
141
+
140
142
  ## Queue consumers other than the Workflow SDK
141
143
 
142
144
  The Vercel World delivers each queue message to the functions subscribed to its topic, not to a fixed path. The Workflow SDK's build integration subscribes the generated flow route to `__wkf_workflow_*` (or `__{namespace}_wkf_workflow_*`). A library that consumes messages of its own on the same World, such as a durable agent harness, uses its own queue prefix and subscribes its own route to that prefix's topics:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "workflow",
3
- "version": "5.6.1",
3
+ "version": "5.7.1",
4
4
  "description": "Workflow SDK - Build durable, resilient, and observable workflows",
5
5
  "main": "dist/typescript-plugin.cjs",
6
6
  "type": "module",
@@ -60,19 +60,19 @@
60
60
  }
61
61
  },
62
62
  "dependencies": {
63
- "@workflow/astro": "5.0.11",
64
- "@workflow/cli": "5.2.0",
65
- "@workflow/core": "5.6.1",
66
- "@workflow/errors": "5.1.3",
63
+ "@workflow/astro": "5.0.13",
64
+ "@workflow/cli": "5.3.1",
65
+ "@workflow/core": "5.7.1",
66
+ "@workflow/errors": "5.1.5",
67
67
  "@workflow/typescript-plugin": "5.0.1",
68
68
  "@workflow/utils": "5.1.1",
69
69
  "ms": "2.1.3",
70
- "@workflow/next": "5.1.2",
71
- "@workflow/nest": "5.1.9",
72
- "@workflow/nitro": "5.0.11",
73
- "@workflow/nuxt": "5.0.11",
74
- "@workflow/sveltekit": "5.0.11",
75
- "@workflow/rollup": "5.0.11"
70
+ "@workflow/next": "5.1.4",
71
+ "@workflow/nest": "5.1.11",
72
+ "@workflow/nitro": "5.0.13",
73
+ "@workflow/nuxt": "5.0.13",
74
+ "@workflow/sveltekit": "5.0.13",
75
+ "@workflow/rollup": "5.0.13"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@types/ms": "2.1.0",