workflow 5.4.0 → 5.6.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.
Files changed (111) hide show
  1. package/dist/api-workflow.js +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/astro.js +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/internal/builtins.js +1 -1
  6. package/dist/internal/class-serialization.js +1 -1
  7. package/dist/internal/errors.js +1 -1
  8. package/dist/nest-builder.js +1 -1
  9. package/dist/nest-vercel-builder.js +1 -1
  10. package/dist/nest.js +1 -1
  11. package/dist/next.cjs +1 -1
  12. package/dist/nitro.js +1 -1
  13. package/dist/nuxt.js +1 -1
  14. package/dist/observability.d.ts +1 -1
  15. package/dist/observability.js +2 -2
  16. package/dist/runtime.js +1 -1
  17. package/dist/stdlib.js +1 -1
  18. package/dist/sveltekit.js +1 -1
  19. package/dist/typescript-plugin.cjs +1 -1
  20. package/dist/vite.js +1 -1
  21. package/dist/workflow.js +1 -1
  22. package/docs/ai/chat-session-modeling.mdx +1 -1
  23. package/docs/ai/resumable-streams.mdx +1 -1
  24. package/docs/api-reference/workflow/create-hook.mdx +2 -2
  25. package/docs/api-reference/workflow/get-step-metadata.mdx +19 -0
  26. package/docs/api-reference/workflow-ai/durable-agent.mdx +2 -1
  27. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +4 -4
  28. package/docs/api-reference/workflow-api/get-run.mdx +0 -4
  29. package/docs/api-reference/workflow-api/resume-hook.mdx +1 -1
  30. package/docs/api-reference/workflow-api/start.mdx +1 -1
  31. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +0 -3
  32. package/docs/api-reference/workflow-errors/index.mdx +1 -1
  33. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +0 -2
  34. package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +1 -1
  35. package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +1 -1
  36. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +1 -1
  37. package/docs/api-reference/workflow-next/with-workflow.mdx +57 -0
  38. package/docs/api-reference/workflow-observability/create-state-resolver.mdx +56 -0
  39. package/docs/api-reference/workflow-observability/index.mdx +5 -0
  40. package/docs/api-reference/workflow-observability/meta.json +1 -0
  41. package/docs/api-reference/workflow-runtime/world/queue.mdx +70 -3
  42. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -2
  43. package/docs/comparisons/index.mdx +4 -1
  44. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +3 -1
  45. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +4 -1
  46. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +271 -28
  47. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +6 -2
  48. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +2 -0
  49. package/docs/configuration/build-and-diagnostics.mdx +2 -0
  50. package/docs/configuration/cli-and-web-ui.mdx +40 -1
  51. package/docs/configuration/framework-options.mdx +7 -0
  52. package/docs/configuration/runtime-tuning.mdx +31 -85
  53. package/docs/configuration/worlds.mdx +69 -40
  54. package/docs/cookbook/advanced/child-workflows.mdx +3 -3
  55. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +1 -1
  56. package/docs/cookbook/common-patterns/batching.mdx +1 -1
  57. package/docs/cookbook/integrations/ai-sdk.mdx +2 -2
  58. package/docs/errors/corrupted-event-log.mdx +1 -1
  59. package/docs/errors/hook-force-claimed.mdx +1 -1
  60. package/docs/errors/index.mdx +1 -0
  61. package/docs/errors/max-events-exceeded.mdx +2 -2
  62. package/docs/errors/replay-timeout.mdx +2 -2
  63. package/docs/errors/runtime-decryption-failed.mdx +1 -1
  64. package/docs/errors/workflow-not-registered.mdx +1 -1
  65. package/docs/foundations/errors-and-retries.mdx +4 -5
  66. package/docs/foundations/serialization.mdx +80 -0
  67. package/docs/getting-started/next.mdx +2 -0
  68. package/docs/how-it-works/event-sourcing.mdx +4 -7
  69. package/docs/how-it-works/framework-integrations.mdx +2 -2
  70. package/docs/internal/index.mdx +1 -0
  71. package/docs/internal/nitro-native-build.mdx +1 -0
  72. package/docs/internal/nitro-web-ui.mdx +1 -0
  73. package/docs/internal/serializable-abort-controller.mdx +1 -0
  74. package/docs/observability/index.mdx +4 -0
  75. package/docs/whats-new.mdx +5 -5
  76. package/docs/worlds/building-a-world.mdx +63 -6
  77. package/docs/worlds/local.mdx +115 -26
  78. package/docs/worlds/postgres.mdx +110 -33
  79. package/docs/worlds/upgrading-to-v5.mdx +6 -6
  80. package/docs/worlds/vercel.mdx +194 -81
  81. package/package.json +17 -15
  82. package/dist/api-workflow.d.ts.map +0 -1
  83. package/dist/api.d.ts.map +0 -1
  84. package/dist/astro.d.ts.map +0 -1
  85. package/dist/index.d.ts.map +0 -1
  86. package/dist/internal/builtins.d.ts.map +0 -1
  87. package/dist/internal/class-serialization.d.ts.map +0 -1
  88. package/dist/internal/errors.d.ts.map +0 -1
  89. package/dist/nest-builder.d.ts.map +0 -1
  90. package/dist/nest-vercel-builder.d.ts.map +0 -1
  91. package/dist/nest.d.ts.map +0 -1
  92. package/dist/nitro.d.ts.map +0 -1
  93. package/dist/nuxt.d.ts.map +0 -1
  94. package/dist/observability.d.ts.map +0 -1
  95. package/dist/runtime.d.ts.map +0 -1
  96. package/dist/stdlib.d.ts.map +0 -1
  97. package/dist/sveltekit.d.ts.map +0 -1
  98. package/dist/vite.d.ts.map +0 -1
  99. package/dist/workflow.d.ts.map +0 -1
  100. package/docs/changelog/attributes-mvp.mdx +0 -380
  101. package/docs/changelog/batched-event-writes.mdx +0 -79
  102. package/docs/changelog/eager-processing.mdx +0 -273
  103. package/docs/changelog/index.mdx +0 -19
  104. package/docs/changelog/lazy-event-creation.md +0 -127
  105. package/docs/changelog/lazy-hook-resume.mdx +0 -78
  106. package/docs/changelog/meta.json +0 -16
  107. package/docs/changelog/resilient-resume.mdx +0 -32
  108. package/docs/changelog/resilient-start.mdx +0 -77
  109. package/docs/changelog/spec-9.mdx +0 -4019
  110. package/docs/changelog/step-message-ownership.mdx +0 -360
  111. package/docs/changelog/turbo-mode.md +0 -91
@@ -38,67 +38,145 @@ Learn more in the [Observability](/docs/observability) documentation.
38
38
 
39
39
  ## Configuration
40
40
 
41
- The Local World requires no configuration, but you can customize its behavior through environment variables or programmatically through `createWorld()`.
41
+ The Local World requires no configuration, but you can customize its behavior through environment variables or programmatically through `createWorld()` (see [Programmatic configuration](#programmatic-configuration)).
42
+
43
+ **Common**
44
+
45
+ | Variable | Default | What it does |
46
+ | --- | --- | --- |
47
+ | [`WORKFLOW_LOCAL_DATA_DIR`](#workflow_local_data_dir) | `.workflow-data/` | Where the workflow database is stored |
48
+ | [`PORT`](#port) | auto-detected | App port that queue messages are delivered to |
49
+ | [`WORKFLOW_LOCAL_BASE_URL`](#workflow_local_base_url) | `http://localhost:{port}` | Base URL override for HTTPS or custom hostnames |
50
+
51
+ **Advanced**
52
+
53
+ | Variable | Default | What it does |
54
+ | --- | --- | --- |
55
+ | [`WORKFLOW_QUEUE_AUTH`](#workflow_queue_auth) | `on` | Flow route accepts only the app's own deliveries |
56
+ | [`WORKFLOW_LOCAL_QUEUE_CONCURRENCY`](#workflow_local_queue_concurrency) | `1000` | Concurrent queue message handlers |
57
+ | [`WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY`](#workflow_local_queue_max_visibility) | unlimited | Longest a queue message stays hidden |
58
+ | [`WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`](#workflow_local_headers_timeout_ms) | `0` ms (no deadline) | Hung delivery detection |
59
+ | [`WORKFLOW_LOCAL_BODY_TIMEOUT_MS`](#workflow_local_body_timeout_ms) | `0` ms (no deadline) | Stalled response detection |
60
+ | [`WORKFLOW_NODE_HTTP`](#workflow_node_http) | disabled | Deliveries through Node's built-in HTTP modules |
61
+ | [`WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS`](#workflow_local_recover_active_runs) | `true` | Re-enqueues active runs on start |
62
+ | [`WORKFLOW_LOCAL_SQLITE_KEEP_CONNECTIONS`](#workflow_local_sqlite_keep_connections) | `1`; `brief` on Windows | How long the database connection stays open |
63
+ | [`WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS`](#workflow_local_hook_retention_limit_days) | `30` days | Maximum hook retention |
64
+ | [`WORKFLOW_STREAM_FLUSH_INTERVAL_MS`](#workflow_stream_flush_interval_ms) | `0` ms | Stream write batching |
42
65
 
43
66
  ### `WORKFLOW_LOCAL_DATA_DIR`
44
67
 
45
- Directory for storing workflow data as JSON files. Default: `.workflow-data/`
68
+ - Default: `.workflow-data/`
69
+ - Factory option: `dataDir`
70
+
71
+ Directory for the workflow database, `world.db` (SQLite). See [Data directory layout](#data-directory-layout).
46
72
 
47
73
  ### `PORT`
48
74
 
49
- The application dev server port. Used to deliver workflow queue messages to the combined flow route. Default: auto-detected
75
+ - Default: auto-detected
76
+ - Factory option: `port`
77
+
78
+ The application dev server port. Used to deliver workflow queue messages to the combined flow route.
50
79
 
51
80
  ### `WORKFLOW_LOCAL_BASE_URL`
52
81
 
53
- Full base URL override for HTTPS or custom hostnames. Default: `http://localhost:{port}`
82
+ - Default: `http://localhost:{port}`
83
+ - Factory option: `baseUrl`
84
+
85
+ Full base URL override for HTTPS or custom hostnames.
86
+
87
+ Port resolution priority: `baseUrl` > `WORKFLOW_LOCAL_BASE_URL` > `port` > `PORT` > auto-detected
88
+
89
+ ### `WORKFLOW_QUEUE_AUTH`
90
+
91
+ - Default: `on`
92
+
93
+ Whether the flow route accepts only deliveries sent by the app's own processes.
94
+
95
+ Change it when: a process that cannot read the app's data directory has to send deliveries, on a trusted machine only. Set `off` on the app. `off` is refused while dynamic workflows are enabled.
96
+
97
+ Every delivery carries the app's queue key, and the route refuses a request without it with a `401` and touches no run. The key is kept in the [data directory](#data-directory-layout), so point the CLI and the web UI at the app's data directory (`WORKFLOW_LOCAL_DATA_DIR`), and keep them on the same release as the app's `@workflow/world-local`: an older one sends no key.
54
98
 
55
- Port resolution priority: `baseUrl` > `port` > `PORT` > auto-detected
99
+ A refused delivery is retried at once when the key in the file has changed, and otherwise a few times with a short backoff, then logged once and given up; its run is left as it was. See [`WORKFLOW_QUEUE_AUTH`](/docs/configuration/runtime-tuning#workflow_queue_auth).
56
100
 
57
101
  ### `WORKFLOW_LOCAL_QUEUE_CONCURRENCY`
58
102
 
59
- Maximum number of concurrent queue message handlers. Default: `1000`
103
+ - Default: `1000`
104
+
105
+ Maximum number of concurrent queue message handlers.
60
106
 
61
107
  ### `WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY`
62
108
 
63
- Maximum number of seconds a local queue message can stay hidden before the handler rechecks the run. Default: unlimited.
109
+ - Default: unlimited
64
110
 
65
- ### `WORKFLOW_LOCAL_RUN_STATUS_POLL_INTERVAL_MS`
111
+ Maximum number of seconds a local queue message can stay hidden before the handler rechecks the run.
66
112
 
67
- How often a wait for a terminal run status re-reads the run file, in milliseconds. Default: `100`.
113
+ ### `WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`
68
114
 
69
- `await run.returnValue` asks the World to wait for the run to finish. When the run and the caller share a process (the usual development server case), an in-process signal resolves the wait as soon as the run ends, and this interval never comes into play. The interval covers activity the signal cannot detect, primarily a second process awaiting a run over the same data directory, so it is set far below Workflow's own polling interval.
115
+ - Default: `0` (no deadline)
70
116
 
71
- ### `WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`
117
+ Maximum time in milliseconds to wait for a local queue handler to begin responding before redelivering the durable message.
72
118
 
73
- Maximum time in milliseconds to wait for a local queue handler to begin responding before redelivering the durable message. Default: `0` (no deadline).
119
+ Change it when: you would rather a hung handler be redelivered. Set it above the longest inline work you expect.
74
120
 
75
- A delivery executes inline steps before the handler responds, so a deadline shorter than your longest step redelivers a healthy delivery while it is still running and executes the same step again. Set this only if you would rather a hung handler be redelivered, and set it above the longest inline work you expect.
121
+ A delivery executes inline steps before the handler responds, so a deadline shorter than your longest step redelivers a healthy delivery while it is still running and executes the same step again.
76
122
 
77
123
  ### `WORKFLOW_LOCAL_BODY_TIMEOUT_MS`
78
124
 
79
- Maximum gap in milliseconds between response body chunks from a local queue handler before redelivering the durable message. Default: `0` (no deadline). The same caution as `WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS` applies.
125
+ - Default: `0` (no deadline)
126
+
127
+ Maximum gap in milliseconds between response body chunks from a local queue handler before redelivering the durable message.
128
+
129
+ The same caution as [`WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`](#workflow_local_headers_timeout_ms) applies.
80
130
 
81
131
  ### `WORKFLOW_NODE_HTTP`
82
132
 
83
- Whether queue deliveries go out through Node's built-in `node:http` and `node:https` modules instead of the HTTP client library this World normally uses. Default: disabled. Set to `1` to switch to Node's modules. Socket pooling, keep-alive, and both timeouts above apply either way. See [`WORKFLOW_NODE_HTTP`](/docs/configuration/runtime-tuning#workflow_node_http) for what else changes.
133
+ - Default: disabled
134
+
135
+ Whether queue deliveries go out through Node's built-in `node:http` and `node:https` modules instead of the HTTP client library this World normally uses. Set to `1` to switch to Node's modules.
136
+
137
+ Socket pooling, keep-alive, and both timeouts above apply either way. See [`WORKFLOW_NODE_HTTP`](/docs/configuration/runtime-tuning#workflow_node_http) for what else changes.
84
138
 
85
139
  ### `WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS`
86
140
 
87
- Whether pending and running runs found in the data directory are re-enqueued when the World starts. Set to `0` or `false` to skip recovery and leave stale runs untouched. Default: `true`.
141
+ - Default: `true`
142
+ - Factory option: `recoverActiveRuns`
143
+
144
+ Whether pending and running runs found in the data directory are re-enqueued when the World starts. Set to `0` or `false` to skip recovery and leave stale runs untouched.
145
+
146
+ Change it when: several processes or workers run workflows on one data directory. Turn recovery off, or give each one its own `tag` (see [Programmatic configuration](#programmatic-configuration)).
147
+
148
+ The Local World's queue is in memory, so a restart loses the messages runs had queued. Recovery re-enqueues each run, and that delivery re-arms the run's wait timers (a `sleep()` or a timeout): a spec 8 run suspends on its open waits again, and the recovery marker on the message makes a single-orchestrator (spec 9) delivery send the run's step messages and wait timers again. As a backstop, recovery also sends each recovered run a wake for every open wait due within about 24.8 days (the queue's longest timer), due when the wait is.
88
149
 
89
150
  Recovery also hands back to the queue any step that was running inline when the previous process exited. The step runs again right away instead of after the inline-ownership lease (about 14 minutes), and the interrupted attempt counts toward its retries. A step with `maxRetries: 0` that was interrupted mid-body therefore fails on restart with an "exceeded max retries" error instead of running again once the lease expires, as it already does after a crash on the Vercel World.
90
151
 
91
152
  If you turn recovery off and re-enqueue runs yourself, call `releaseOrphanedSteps(runId)` before re-enqueueing each run. It is a method of `LocalWorld`, the type `createWorld()` from `@workflow/world-local` returns. The `World` type that `getWorld()` returns does not declare it, so a caller holding a `World` needs the `LocalWorld` type to call it.
92
153
 
93
- A step counts as abandoned only if it started before the Local World loaded in the current process or worker thread. Steps started since then are never released, so runs this process picks up during or after recovery are not affected, and calling `releaseOrphanedSteps()` late is safe. Recovery assumes that nothing else is running workflows on the same data directory and `tag`. That includes an earlier worker thread of the same process: some dev servers reload into a new worker thread, and until the old one stops, the new one may dispatch a step the old one is still running, so the step can run twice. If several processes or workers run workflows on one data directory, turn recovery off or give each one its own `tag`.
154
+ A step counts as abandoned only if it started before the Local World loaded in the current process or worker thread. Steps started since then are never released, so runs this process picks up during or after recovery are not affected, and calling `releaseOrphanedSteps()` late is safe. Recovery assumes that nothing else is running workflows on the same data directory and `tag`. That includes an earlier worker thread of the same process: some dev servers reload into a new worker thread, and until the old one stops, the new one may dispatch a step the old one is still running, so the step can run twice.
155
+
156
+ ### `WORKFLOW_LOCAL_SQLITE_KEEP_CONNECTIONS`
157
+
158
+ - Default: `1`, except on Windows, where it is `brief`
159
+
160
+ How long a process keeps its connection to `world.db` open between operations.
161
+
162
+ `1` keeps it until it has been idle for a few seconds. `brief` closes it once a burst of operations ends; it is the default on Windows, where an open database file cannot be deleted, so the data directory stays removable while the app runs. `0` opens and closes a connection for every operation, which is slower; the repository's own tests use it on Windows because they delete their data directory right after using it. Any other value, including `true` or `false`, uses the default.
94
163
 
95
164
  ### `WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS`
96
165
 
97
- Maximum [`experimental_minRetention`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) accepted by the Local World, in days. Default: `30`. Set this to the same limit as your production World so oversized values fail during local development.
166
+ - Default: `30`
167
+
168
+ Maximum [`experimental_minRetention`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) accepted by the Local World, in days.
169
+
170
+ Change it when: your production World uses a different limit. Set the same limit so oversized values fail during local development.
98
171
 
99
172
  ### `WORKFLOW_STREAM_FLUSH_INTERVAL_MS`
100
173
 
101
- Group-commit window, in milliseconds, for the leading chunk of an idle stream. Default: `0` (dispatch immediately). A positive value holds the first chunk up to that long to collect a group, trading first-chunk latency for fewer requests. Chunks arriving while a request is in flight always coalesce into the next group regardless.
174
+ - Default: `0` (dispatch immediately)
175
+ - Factory option: `streamFlushIntervalMs`
176
+
177
+ Group-commit window, in milliseconds, for the leading chunk of an idle stream.
178
+
179
+ A positive value holds the first chunk up to that long to collect a group, trading first-chunk latency for fewer requests. Chunks arriving while a request is in flight always coalesce into the next group regardless.
102
180
 
103
181
  ### Programmatic configuration
104
182
 
@@ -121,7 +199,7 @@ export default createWorld({
121
199
  WORKFLOW_TARGET_WORLD="./my-world.ts"
122
200
  ```
123
201
 
124
- `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.
202
+ `createWorld()` also accepts `tag`, which scopes the runs and streams a World writes, and which runs its startup recovery re-enqueues, so several Worlds can share one data directory without seeing each other's data. A tagged World also reads untagged runs, and its `clear()` deletes only its own data. It is mainly used by test harnesses that share one `.workflow-data` directory with the app.
125
203
 
126
204
  ### Queue consumers other than the Workflow SDK
127
205
 
@@ -147,17 +225,28 @@ export async function registerAgentQueue(
147
225
 
148
226
  ## Data directory layout
149
227
 
150
- Each run's event and step files are stored in their own directory (`events/<runId>/`, `steps/<runId>/`). Data written by `@workflow/world-local` releases before 5.1.0 uses a flat layout and is not migrated: when the World starts on a data directory that holds only flat-layout files, it logs a warning, deletes the directory, and starts with an empty one. The CLI and web UI only read the data directory and never delete it. Older releases see no events or steps in the new layout, so clear `.workflow-data` by hand before downgrading.
228
+ Everything the Local World stores is in one SQLite database, `world.db` in the data directory (with SQLite's `world.db-wal` and `world.db-shm` files next to it): runs, their event logs, steps, waits, hooks, stream chunks and snapshots. Queue messages are not stored: a message is an HTTP request to the app (or a call to an in-process handler) made by the process that enqueued it, held only in that process's memory while it waits for a delay or a retry. It is opened with the runtime's built-in driver, `node:sqlite` on Node.js 22.13 or later and `bun:sqlite` on Bun, so there is no native dependency to install. Node.js 22.x still marks `node:sqlite` as experimental; the World drops the `ExperimentalWarning` it prints for that, and only that one.
229
+
230
+ Each World write is one transaction: an event and every change it makes to its run, step, wait and hook commit together or not at all, so a process that is killed mid-write leaves nothing half-written behind. Several processes can use one data directory at once (an app and a test runner, say). SQLite orders their writes, and the lock it takes is released by the operating system when a process exits, however it exits.
231
+
232
+ To look at the data directly, open it with any SQLite client:
233
+
234
+ ```bash
235
+ sqlite3 .workflow-data/world.db "select seq, event_type, correlation_id from events where run_id = 'wrun_…' order by seq"
236
+ ```
237
+
238
+ Earlier releases stored one JSON file per entity (`runs/`, `events/`, `steps/`, `hooks/`, `.locks/` and so on). That data is not migrated, and it is not deleted either: the World leaves those directories where they are, does not read them, and starts with an empty database next to them. When `world.db` is created in a data directory that still holds them, the World says so once in the log, naming the directories. Delete them by hand once you no longer need them. Older releases do not read `world.db`, so runs created with this release are not visible after a downgrade, and a `world.db` written by a newer release is refused rather than read.
239
+
240
+ The database needs a filesystem that supports SQLite's shared-memory file. A data directory on a network filesystem (NFS, SMB), or shared between a host and a container through a VM-backed mount, is not supported when more than one machine or VM writes to it.
151
241
 
152
- 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.
242
+ The data directory also holds the app's queue key, `queue-auth-key` (see [`WORKFLOW_QUEUE_AUTH`](#workflow_queue_auth)), a random value. The app writes a new one each time it starts, when it first uses its World and before it sends anything, so a restart needs no wait. A script that calls `start()` with the same data directory writes a new key the same way, and the app accepts it. The CLI and the web UI only read the key. Several app processes on one data directory (PM2 with `-i N`, `node:cluster`, Nitro's `node-cluster` preset) end up on the newest key in the file. The file is readable and writable only by its owner (mode `0600`); Windows does not enforce that mode the same way, and the file gets the directory's permissions. The World writes a `.gitignore` containing `*` into the data directory when it has none, so neither the key nor the run data is committed, and never replaces one that is already there.
153
243
 
154
244
  ## Limitations
155
245
 
156
246
  The Local World is designed for development, not production:
157
247
 
158
- - **In-memory queue**: Workflow messages, including queued step invocations, do not persist across server restarts.
159
- - **Filesystem storage**: Data is stored in local JSON files.
160
- - **Single instance**: The Local World cannot handle distributed deployments.
161
- - **No authentication**: The Local World is suitable only for local development.
248
+ - **In-memory queue**: Queue messages, including delayed ones and retries, do not survive a restart. Startup recovery re-enqueues active runs, which re-arms their open waits. A process that exits right after sending a message (the CLI, a script) gives the app up to 10 seconds to take it.
249
+ - **Single machine**: The data directory is a local SQLite database, so the Local World cannot handle distributed deployments.
250
+ - **Minimal authentication**: The flow route accepts only deliveries carrying the app's queue key (see [`WORKFLOW_QUEUE_AUTH`](#workflow_queue_auth)), but nothing else is authenticated. Anyone who can read the data directory can read the key. The Local World is suitable only for local development.
162
251
 
163
252
  For production deployments, use the [Vercel World](/worlds/vercel), which handles execution, persistence, multi-tenancy, scale, observability, and security for you on Vercel, or check out the [Postgres World](/worlds/postgres) - a tested reference implementation that implements the complete World spec and can be used to deploy workflows anywhere.
@@ -232,6 +232,8 @@ Unlike the [Vercel World](/worlds/vercel), which authenticates and [encrypts](/d
232
232
 
233
233
  `POST /.well-known/workflow/v1/flow` is where the worker delivers workflow orchestration and queued step invocations. It is mounted in your application like any other route, so it is publicly reachable by default, and it accepts any request whose headers and body are well-formed: there is no signature, shared secret, or caller check. Anyone who can reach it can forge or replay a workflow or step invocation, including steps your application would only reach after its own gating. Restrict it before you expose the app.
234
234
 
235
+ The runtime does not check deliveries to this route with a [queue key](/worlds/building-a-world#authenticating-deliveries): the Postgres World declares `queueAuthMode: 'skip'` until its messages are delivered in-process and the route is denied ([#5258](https://github.com/vercel/workflow/issues/5258)).
236
+
235
237
  The other routes under `/.well-known/workflow/v1/` differ:
236
238
 
237
239
  - `webhook/:token`, created by [`createWebhook()`](/docs/api-reference/workflow/create-webhook), is authorized by the token in the URL and nothing else. Use [`createHook()`](/docs/api-reference/workflow/create-hook) behind your own authenticated route and [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook) when you need more than that.
@@ -275,103 +277,178 @@ Learn more in the [Observability](/docs/observability) documentation.
275
277
 
276
278
  ## Configuration
277
279
 
278
- The defaults work for a single process on a local database, so most apps set only `WORKFLOW_TARGET_WORLD` and `WORKFLOW_POSTGRES_URL`. You can set every option through environment variables, or programmatically through `createWorld()` (see [Programmatic configuration](#programmatic-configuration)).
280
+ The defaults work for a single process on a local database, so most apps set only `WORKFLOW_TARGET_WORLD` and `WORKFLOW_POSTGRES_URL`, and every option can also be set programmatically through `createWorld()` (see [Programmatic configuration](#programmatic-configuration)).
281
+
282
+ **Common**
279
283
 
280
- | Variable | Default | Controls |
284
+ | Variable | Default | What it does |
281
285
  | --- | --- | --- |
282
286
  | [`WORKFLOW_POSTGRES_URL`](#workflow_postgres_url) | `DATABASE_URL`, then `postgres://world:world@localhost:5432/world` | Database connection |
283
287
  | [`WORKFLOW_POSTGRES_JOB_PREFIX`](#workflow_postgres_job_prefix) | `workflow_` | Job name prefix, for sharing a database between apps |
288
+
289
+ **Advanced**
290
+
291
+ | Variable | Default | What it does |
292
+ | --- | --- | --- |
293
+ | [`WORKFLOW_POSTGRES_DEPLOYMENT_ID`](#workflow_postgres_deployment_id) | unset | Pins each run to the deployment that started it |
284
294
  | [`WORKFLOW_POSTGRES_WORKER_CONCURRENCY`](#workflow_postgres_worker_concurrency) | `50` | Concurrent jobs per process |
285
295
  | [`WORKFLOW_POSTGRES_POLL_INTERVAL_MS`](#workflow_postgres_poll_interval_ms) | `500` ms | Idle job polling |
286
296
  | [`WORKFLOW_POSTGRES_MAX_POOL_SIZE`](#workflow_postgres_max_pool_size) | `10` | Connection pool size |
287
297
  | [`WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN`](#workflow_postgres_application_managed_shutdown) | off | Who coordinates shutdown |
288
- | [`WORKFLOW_POSTGRES_RUN_STATUS_POLL_INTERVAL_MS`](#workflow_postgres_run_status_poll_interval_ms) | `1000` ms | Backstop for `await run.returnValue` |
289
298
  | [`WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`](#workflow_postgres_headers_timeout_ms) | `0` ms (no deadline) | Hung delivery detection |
290
299
  | [`WORKFLOW_POSTGRES_BODY_TIMEOUT_MS`](#workflow_postgres_body_timeout_ms) | `0` ms (no deadline) | Stalled response detection |
291
- | [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) | `0` s (off) | Redelivery after a process dies |
300
+ | [`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 |
292
301
  | [`WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS`](#workflow_postgres_hook_retention_limit_days) | `30` days | Maximum hook retention |
293
302
  | [`WORKFLOW_QUEUE_NAMESPACE`](#workflow_queue_namespace) | unset | Queue topic namespace |
294
303
  | [`WORKFLOW_STREAM_FLUSH_INTERVAL_MS`](#workflow_stream_flush_interval_ms) | `0` ms | Stream write batching |
295
- | [`WORKFLOW_POSTGRES_INVOKE`](#experimental-invocation-delivery) | off | Experimental: hook resumes only |
304
+
305
+ **Experimental**
306
+
307
+ | Variable | Default | What it does |
308
+ | --- | --- | --- |
309
+ | [`WORKFLOW_POSTGRES_INVOKE`](#experimental-invocation-delivery) | off | Invocation delivery, for hook resumes only |
296
310
 
297
311
  ### `WORKFLOW_POSTGRES_URL`
298
312
 
299
- PostgreSQL connection string used by the runtime World.
313
+ - Default: `DATABASE_URL`, then `postgres://world:world@localhost:5432/world`
314
+ - Factory option: `connectionString`
300
315
 
301
- Precedence: `WORKFLOW_POSTGRES_URL` > `DATABASE_URL` > `postgres://world:world@localhost:5432/world`
316
+ PostgreSQL connection string used by the runtime World.
302
317
 
303
- The `bootstrap` migration command uses the same precedence.
318
+ Precedence: `WORKFLOW_POSTGRES_URL` > `DATABASE_URL` > `postgres://world:world@localhost:5432/world`. The `bootstrap` migration command uses the same precedence.
304
319
 
305
320
  ### `WORKFLOW_POSTGRES_JOB_PREFIX`
306
321
 
307
- Prefix for graphile-worker queue job names. Default: `workflow_`
322
+ - Default: `workflow_`
323
+ - Factory option: `jobPrefix`
308
324
 
309
- Give each application that shares a database its own prefix. A World claims jobs only under its own prefix and stamps that prefix on every run it creates. On `start()`, it re-enqueues only the active runs stamped with its prefix, so restarting one application does not hand another application's runs to its worker. `WORKFLOW_QUEUE_NAMESPACE` does not separate applications that share a database.
325
+ Prefix for graphile-worker queue job names.
326
+
327
+ Change it when: more than one application shares the database. Give each one its own prefix.
328
+
329
+ A World claims jobs only under its own prefix and stamps that prefix on every run it creates. On `start()`, it re-enqueues only the active runs stamped with its prefix, so restarting one application does not hand another application's runs to its worker. `WORKFLOW_QUEUE_NAMESPACE` does not separate applications that share a database.
310
330
 
311
331
  Set the prefix through `WORKFLOW_POSTGRES_JOB_PREFIX` rather than only in code. The CLI and the observability UI build their World from the environment, so a run they create, such as a re-run, is stamped with the prefix they see, and only a World with that prefix runs and recovers it.
312
332
 
333
+ ### `WORKFLOW_POSTGRES_DEPLOYMENT_ID`
334
+
335
+ - Default: unset
336
+ - Factory option: `deploymentId`
337
+
338
+ Pins every run to the deployment that started it, the way the [Vercel World](/worlds/vercel) does.
339
+
340
+ Set it to a value that names one immutable build, such as a container image tag or a commit SHA: letters, digits, `.`, `-`, `_` and `@`, but not `postgres`. It becomes part of Graphile job and queue names, which are limited to 128 characters, so it can be at most 72 characters with the default job prefix (the job prefix and the deployment ID together, at most 81).
341
+
342
+ When it is set:
343
+
344
+ - **Each deployment claims only its own runs.** The deployment ID becomes part of the World's job prefix (`${jobPrefix}${deploymentId}_`), so a deployment's processes claim only the jobs of runs it started. On `start()`, they re-enqueue only those runs.
345
+ - **Messages follow the run.** A message for a run that another deployment started, such as the wake-up when a newer deployment calls `resumeHook()`, is routed to that deployment's jobs.
346
+ - **`getDeploymentId()` returns the value,** and the World declares deployment affinity. If a delivery still reaches the wrong deployment, the runtime sends it back to the run's own deployment instead of replaying the run there.
347
+
348
+ Keep at least one process of a deployment running, or able to start, until its runs finish. Nothing else claims them, so a run whose deployment is gone waits for it.
349
+
350
+ Unset, every process that shares the job prefix claims every run. A run started before a deploy then continues on the new code, which must replay it the same way.
351
+
352
+ Runs started before you set it stay unpinned: they record the deployment ID `postgres`, and only a process without `WORKFLOW_POSTGRES_DEPLOYMENT_ID` claims them. Messages for them are routed there, including from pinned processes. When you turn pinning on, keep one process without it running until those runs finish.
313
353
 
314
354
  ### `WORKFLOW_POSTGRES_WORKER_CONCURRENCY`
315
355
 
316
- Number of concurrent workers polling for jobs. Default: `50`.
356
+ - Default: `50`
357
+ - Factory option: `queueConcurrency`
358
+
359
+ Number of concurrent workers polling for jobs.
360
+
361
+ Change it when: you need more jobs in flight per process, including `returnValue` polls that hold a worker slot (see below).
317
362
 
318
363
  A parent workflow awaiting `childRun.returnValue` of a child it started does not hold a worker slot: it suspends on a system hook the child resumes when it finishes (see [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits)). A `returnValue` that falls back to polling still does, for example one awaited inside a step, or any await while `WORKFLOW_CHILD_RUN_COMPLETION_HOOK=0` is set. Each of those holds a worker slot until its child run terminates, so raise this ceiling above the peak number of such polls in flight.
319
364
 
320
365
  ### `WORKFLOW_POSTGRES_POLL_INTERVAL_MS`
321
366
 
322
- Milliseconds between idle job fetches per worker. Each worker polls on its own, so an idle process runs about `queueConcurrency × 1000 / pollInterval` fetches per second. Default: `500`.
367
+ - Default: `500`
368
+ - Factory option: `pollInterval`
369
+
370
+ Milliseconds between idle job fetches per worker.
371
+
372
+ Each worker polls on its own, so an idle process runs about `queueConcurrency × 1000 / pollInterval` fetches per second.
323
373
 
324
374
  ### `WORKFLOW_POSTGRES_MAX_POOL_SIZE`
325
375
 
326
- Maximum size of the internal `pg.Pool` used when `createWorld()` constructs the pool. Default: the `pg` default (`10`).
376
+ - Default: the `pg` default (`10`)
377
+ - Factory option: `maxPoolSize`
327
378
 
328
- For higher worker concurrency, Graphile Worker recommends setting `maxPoolSize` to `10` or `queueConcurrency + 2`, whichever is larger.
379
+ Maximum size of the internal `pg.Pool` used when `createWorld()` constructs the pool.
329
380
 
330
- ### `WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN`
381
+ Change it when: you raise worker concurrency. Graphile Worker recommends setting `maxPoolSize` to `10` or `queueConcurrency + 2`, whichever is larger.
331
382
 
332
- Set to `1` when the application or framework coordinates shutdown and awaits `world.close()` before closing its workflow HTTP server and any caller-owned pool. Default: unset (`false`).
383
+ ### `WORKFLOW_POSTGRES_APPLICATION_MANAGED_SHUTDOWN`
333
384
 
334
- ### `WORKFLOW_POSTGRES_RUN_STATUS_POLL_INTERVAL_MS`
385
+ - Default: unset (`false`)
386
+ - Factory option: `applicationManagedShutdown`
335
387
 
336
- How often a wait for a terminal run status re-reads the run, in milliseconds. Default: `1000`.
388
+ Whether the application, instead of Graphile Worker, coordinates shutdown. Set to `1` to enable.
337
389
 
338
- `await run.returnValue` asks the World to wait for the run to finish, and the Postgres World parks that wait on a `NOTIFY` issued by the run-terminal write. This interval is only the backstop: it bounds how long a lost notification can go unnoticed, so lowering it costs a query per waiting run per interval and buys nothing while notifications are arriving.
390
+ 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).
339
391
 
340
392
  ### `WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`
341
393
 
342
- Maximum time in milliseconds a queue delivery waits for the workflow handler to begin responding before the delivery is failed and Graphile Worker redelivers the message. Default: `0` (no deadline).
394
+ - Default: `0` (no deadline)
395
+
396
+ Maximum time in milliseconds a queue delivery waits for the workflow handler to begin responding before the delivery is failed and Graphile Worker redelivers the message.
397
+
398
+ Change it when: you would rather a hung handler be redelivered than hold its worker slot until the process restarts. Set it above the longest inline work you expect.
343
399
 
344
- A delivery executes the workflow body inline, so the handler responds only once that work is done. A deadline shorter than your longest inline step declares a healthy delivery crashed and redelivers it while the original is still running, executing the same steps twice. Set this only if you would rather a hung handler be redelivered than hold its worker slot until the process restarts, and set it above the longest inline work you expect.
400
+ A delivery executes the workflow body inline, so the handler responds only once that work is done. A deadline shorter than your longest inline step declares a healthy delivery crashed and redelivers it while the original is still running, executing the same steps twice.
345
401
 
346
402
  ### `WORKFLOW_POSTGRES_BODY_TIMEOUT_MS`
347
403
 
348
- Maximum gap in milliseconds between response body chunks from the workflow handler before the delivery is failed and redelivered. Default: `0` (no deadline). The same caution as `WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS` applies.
404
+ - Default: `0` (no deadline)
405
+
406
+ Maximum gap in milliseconds between response body chunks from the workflow handler before the delivery is failed and redelivered.
407
+
408
+ The same caution as [`WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`](#workflow_postgres_headers_timeout_ms) applies.
349
409
 
350
410
  ### `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`
351
411
 
352
- Seconds a running delivery's job lock may go unrenewed before another process releases the job for redelivery. Default: `0` (off). `30` is a good value when more than one process shares the database. Programmatic option: `jobLockStaleSeconds`.
412
+ - Default: unset (see below)
413
+ - Factory option: `jobLockStaleSeconds`
414
+
415
+ Seconds a running delivery's job lock may go unrenewed before another process releases the job for redelivery.
353
416
 
354
- When set, a running delivery renews its lock every quarter of this window, and at least every 10 seconds. When a process dies mid-delivery, another process redelivers its jobs within about one and a half windows (about 45 seconds at `30`), instead of after Graphile Worker's fixed 4 hour stale-lock reset or the next restart.
417
+ Change it when: more than one process shares the database, once every one of them runs a version that includes this option. `30` is a good value. Use the same value on every process that shares the database.
355
418
 
356
- Use the same value on every process that shares the database, and keep it well above the longest a process can go without running its timers (synchronous work that blocks the event loop) or getting a pool connection. A delivery whose renewals stall past the window is redelivered while it still runs.
419
+ A running delivery renews its lock every quarter of the window, and at least every 10 seconds. When a process dies mid-delivery, another process redelivers its jobs within about one and a half windows (about 45 seconds at `30`), instead of after Graphile Worker's fixed 4 hour stale-lock reset or the next restart.
357
420
 
358
- It's off by default because of rolling upgrades. A process on an earlier version doesn't renew its locks, so a process that has this on would redeliver any of that process's deliveries that run longer than the window. When the earlier-version process then finishes such a delivery, its acknowledgement, which isn't fenced on the lock holder, can delete the redelivered job's row, and the redelivery loses its retry.
421
+ Unset, every delivery still renews its lock, and its worker registers as renewing in `workflow.workflow_job_lock_holders` (migration 0030, which `bootstrap` applies). Then only the jobs holding a spec 9 run's delivery lease (its orchestrator deliveries, and invoke mode's executor lane; migration 0031) are released, after 300 seconds unrenewed, and only those whose holder registered. A spec 9 run whose worker was killed therefore continues within about 8 minutes (one and a half windows) instead of 4 hours. A job held by a process on an earlier version, which does not register, is never released this way, so the default is safe during a rolling upgrade. `0` turns renewal and release off.
359
422
 
360
- To turn it on, set `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS=30` (or `jobLockStaleSeconds: 30`) on every process that shares the database, once all of them run a version that includes this option.
423
+ Keep the value well above the longest a process can go without running its timers (synchronous work that blocks the event loop) or getting a pool connection. A delivery whose renewals stall past the window is redelivered while it still runs.
424
+
425
+ Setting it releases every job of this World, whoever holds it, so set it only after a rolling upgrade has finished. A process on an earlier version doesn't renew its locks, so a process that has this set would redeliver any of that process's deliveries that run longer than the window. When the earlier-version process then finishes such a delivery, its acknowledgement, which isn't fenced on the lock holder, can delete the redelivered job's row, and the redelivery loses its retry.
361
426
 
362
427
  ### `WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS`
363
428
 
364
- Maximum [`experimental_minRetention`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) accepted by the Postgres World, in days. Default: `30`. Set this to the same limit as your production World so oversized values fail during development.
429
+ - Default: `30`
430
+
431
+ Maximum [`experimental_minRetention`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) accepted by the Postgres World, in days.
432
+
433
+ Change it when: your production World uses a different limit. Set the same limit so oversized values fail during development.
365
434
 
366
435
  ### `WORKFLOW_QUEUE_NAMESPACE`
367
436
 
368
- Queue topic namespace shared by build output and the Postgres World. Default: unset.
437
+ - Default: unset
438
+ - Factory option: `namespace`
439
+
440
+ Queue topic namespace shared by build output and the Postgres World.
369
441
 
370
442
  For example, `custom` changes the queue topic prefix from `__wkf_workflow_` to `__custom_wkf_workflow_`. The value must be lowercase alphanumeric and start with a letter.
371
443
 
372
444
  ### `WORKFLOW_STREAM_FLUSH_INTERVAL_MS`
373
445
 
374
- Group-commit window, in milliseconds, for the leading chunk of an idle stream. Default: `0` (dispatch immediately). A positive value holds the first chunk up to that long to collect a group, trading first-chunk latency for fewer requests. Chunks arriving while a request is in flight always coalesce into the next group regardless.
446
+ - Default: `0` (dispatch immediately)
447
+ - Factory option: `streamFlushIntervalMs`
448
+
449
+ Group-commit window, in milliseconds, for the leading chunk of an idle stream.
450
+
451
+ A positive value holds the first chunk up to that long to collect a group, trading first-chunk latency for fewer requests. Chunks arriving while a request is in flight always coalesce into the next group regardless.
375
452
 
376
453
  ## Upgrading
377
454
 
@@ -472,9 +549,9 @@ To turn it on, set `WORKFLOW_POSTGRES_INVOKE=1` or pass `enableInvoke: true` to
472
549
 
473
550
  Workflow user code can consume the event later. The World stores inputs and responses in `workflow.workflow_invocations`. Inserting an input and enqueueing a workflow execution job share one transaction. Retries also enqueue an execution job, including when a retained response already exists, so committed events can be replayed after a runner failure.
474
551
 
475
- With the default job prefix, Graphile uses `workflow_flows_executor` for workflow execution and `workflow_flows` for step jobs and health checks. Execution jobs use a named queue per run, `workflow_flows:<runId>:executor`. Graphile permits one active job on each named queue across workers. Other runs, steps, and health checks can run concurrently. `queueConcurrency` limits total active jobs per worker process and defaults to 50. A custom job prefix replaces `workflow_` in these names.
552
+ With the default job prefix, Graphile uses `workflow_flows_executor` for workflow execution and `workflow_flows` for step jobs and health checks. Each execution job takes its run's delivery lease, a row in `workflow.workflow_run_delivery_leases` that exists only while a delivery holds it, so one execution job runs per run across workers. A delivery that finds the lease held leaves its message for the holder, which re-adds it when it releases. Other runs, steps, and health checks can run concurrently. `queueConcurrency` limits total active jobs per worker process and defaults to 50. A custom job prefix replaces `workflow_` in these names.
476
553
 
477
- The HTTP receiver checks each execution request against its active Graphile job before processing pending inputs. Updated workers and receivers move legacy orchestration requests to the run's named queue. Before acknowledging an execution job, the World finishes any input already being processed and replays newly committed events. These entry checks do not stop an old handler from writing after its job is reclaimed.
554
+ The HTTP receiver checks each execution request against its active Graphile job before processing pending inputs. Updated workers and receivers move legacy orchestration requests to the executor task. Before acknowledging an execution job, the World finishes any input already being processed and replays newly committed events. These entry checks do not stop an old handler from writing after its job is reclaimed.
478
555
 
479
556
  The caller receives a stored return value or a restored Workflow error. Terminal errors are retained as outcomes; transient or unrecognized failures leave inputs pending for Graphile to retry. Migration 0022 preserves the meaning of responses stored by earlier previews. Failure to store or read a response leaves the processing outcome unknown. Durable resume identities deduplicate the hook event when response storage must be retried.
480
557
 
@@ -490,7 +567,7 @@ The Postgres World uses PostgreSQL as a durable backend:
490
567
 
491
568
  - **Storage**: Workflow runs, events, steps, and hooks are stored in PostgreSQL tables.
492
569
  - **Job queue**: [graphile-worker](https://github.com/graphile/worker) handles reliable job processing with retries.
493
- - **Crash recovery**: The next `start()` re-enqueues active runs. With [`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](#workflow_postgres_job_lock_stale_seconds) set, a running delivery also renews its job lock, and if its process dies, any other process redelivers the job once its lock has gone unrenewed for that many seconds.
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.
494
571
  - **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.
495
572
 
496
573
  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).
@@ -52,7 +52,7 @@ export function createWorld(): World {
52
52
 
53
53
  In v4 the runtime required that number to equal its own current version exactly. In v5 it checks the declaration against a range before it creates or replays anything, and refuses a World outside it with an error naming both the range and what your World declared. The floor is the version that introduced [slot-numbered event IDs](#event-id-allocation), because a World below it allocates IDs the runtime cannot read positions out of, and admitting one would only move the failure from startup into the middle of a run. The ceiling is the highest version this runtime can read.
54
54
 
55
- `mintedSpecVersion()` is a function rather than a constant because the version a World stamps is a deployment-level choice. It answers with the sealed-log version by default, and with the slot-identity version when [`WORKFLOW_SEALED_LOG=0`](/docs/configuration/runtime-tuning#workflow_sealed_log) opts new runs out. Both sit inside the accepted range, so either answer is a valid declaration. Reading it per `createWorld()` call rather than once at module load is what lets a single process create Worlds in both modes.
55
+ `mintedSpecVersion()` is a function rather than a constant because the version a World stamps is a deployment-level choice. It answers with the sealed-log version by default, and with the version [`WORKFLOW_SPEC_VERSION`](/docs/configuration/runtime-tuning#workflow_spec_version) selects, such as the slot-identity version (6), when that is set. Every version it accepts sits inside the accepted range, so any answer is a valid declaration. Reading it per `createWorld()` call rather than once at module load is what lets a single process create Worlds with different settings.
56
56
 
57
57
  Calling it is also what keeps the check passing across upgrades, since it moves with the `@workflow/world` version your package resolves. A hard-coded number leaves your World a version behind the next bump and gets it rejected by the runtime it ships alongside. That includes the constants: `SPEC_VERSION_CURRENT` and `SPEC_VERSION_SUPPORTS_SLOT_IDENTITY` are literals by another name for this purpose, since neither follows the sealed-log setting. Keep `@workflow/world` in the same release channel as the `workflow` version your users install.
58
58
 
@@ -63,7 +63,7 @@ The sealed-log version exists for a World whose store makes allocating a positio
63
63
  Two consequences for an implementation:
64
64
 
65
65
  - **If you allocate at the commit, you are already compliant** and have nothing to build. No write can leave a position empty, so you have no holes to seal and will never emit a `noop`. `@workflow/world-local` and `@workflow/world-postgres` are in this position.
66
- - **What the version actually gates is the reader.** A run stamped at the sealed-log version can only be replayed by a reader that knows to skip `noop`. That is every runtime on this release train, but a runtime pinning its own accepted range separately, such as the Python runtime, has to catch up first. `WORKFLOW_SEALED_LOG=0` is the switch for an environment where it has not.
66
+ - **What the version actually gates is the reader.** A run stamped at the sealed-log version can only be replayed by a reader that knows to skip `noop`. That is every runtime on this release train, but a runtime pinning its own accepted range separately, such as the Python runtime, has to catch up first. `WORKFLOW_SPEC_VERSION=6` is the setting for an environment where it has not.
67
67
 
68
68
  Runs carry a spec version too, and a run keeps the version it was created under for its whole life. Read the stamped version off the run rather than assuming every run matches what your World declares today. Changing what you stamp does not reach runs already in your store: their version is persisted, every version test in the runtime is a lower bound, and a run's event ID scheme is resolved from what is stored.
69
69
 
@@ -99,7 +99,7 @@ This bites rather than merely wasting memory because the runtime caches the *Wor
99
99
 
100
100
  **One World per process.** The workflow entrypoint's queue handler is now built from the runtime World that `getWorld()` returns, rather than from `getWorldHandlers()`. A stateful World is no longer instantiated twice in one process, so it stops getting duplicate connection pools and duplicate queue workers. If you added your own de-duplication to work around that, it is now redundant, though harmless if it keys on process-wide state.
101
101
 
102
- **Your own transport is your own business, except for the tracing.** How a World ships events to its backend is unconstrained: `@workflow/world-vercel` uses a WebSocket by default and falls back to HTTP. What is constrained is what a reader of a trace sees. A non-HTTP transport still has to emit the per-event client span that an HTTP write would, or the per-event view of a run silently disappears. See [`WORKFLOW_EVENTS_TRANSPORT`](/worlds/vercel#workflow_events_transport) for the span shape and attributes the Vercel World uses, including a separate span for the handshake.
102
+ **Your own transport is your own business, except for the tracing.** How a World ships events to its backend is unconstrained: `@workflow/world-vercel` uses a WebSocket by default and falls back to HTTP. What is constrained is what a reader of a trace sees. A non-HTTP transport still has to emit the per-event client span that an HTTP write would, or the per-event view of a run silently disappears. See [`WORKFLOW_EVENTS_TRANSPORT`](/worlds/vercel#event-writes-over-websocket) for the span shape and attributes the Vercel World uses, including a separate span for the handshake.
103
103
 
104
104
  **Replay reads the event log with `resolveData: 'skip-step-inputs'`.** A World may leave `input` out of `step_created` and `step_started` events for this value, and must otherwise treat it as `'all'`. A World that tests `resolveData === 'all'`, or validates against `['none', 'all']`, strips step results or rejects the read, and every replay fails. Test for `'none'` instead, or map with `entityResolveData()` from `@workflow/world`. `@workflow/world-testing` covers this case.
105
105
 
@@ -137,7 +137,7 @@ None of this is required. Each entry is a hook the runtime uses if your World pr
137
137
  | Member | What it buys |
138
138
  | --- | --- |
139
139
  | `capabilities` | Advertises `hookRetention.active`, `hookResumeDedup`, `hookForceClaim`, `atomicStartHook.active`, `deploymentAffinity`, `maxConcurrency`, `inBandFence`, and `dynamicWorkflowCode`. See the contract note above about failing closed. Event ID allocation is *not* in here: it is a requirement, not a capability. |
140
- | `events.createBatch` | Appends an ordered list of events in one durable write, with a per-event outcome for each. Implementing the method *is* the declaration: the runtime folds a suspension's `step_created` / `wait_created` writes into batches only when it exists, and otherwise takes the single-event path unchanged. Implement it with real atomicity per attempt, so a lost race leaves nothing behind, or leave it out. See [Batched event writes](/docs/changelog/batched-event-writes). |
140
+ | `events.createBatch` | Appends an ordered list of events in one durable write, with a per-event outcome for each. Implementing the method *is* the declaration: the runtime folds a suspension's `step_created` / `wait_created` writes into batches only when it exists, and otherwise takes the single-event path unchanged. Implement it with real atomicity per attempt, so a lost race leaves nothing behind, or leave it out. |
141
141
  | `runs.waitForTerminalStatus` | Long-polls until a run reaches a terminal status. `await run.returnValue` uses it when present, instead of polling on an interval. |
142
142
  | `analytics` | A metadata-only read namespace for observability surfaces. Payload-bearing reads stay on `runs`, `steps`, `events`, and `hooks`. |
143
143
  | `runs.experimentalSetAttributes` | Backs `setAttributes()` from application code. Without it, run attributes are unavailable. |
@@ -153,7 +153,7 @@ None of this is required. Each entry is a hook the runtime uses if your World pr
153
153
  | `streams.streamFlushIntervalMs` | Sets the stream flush window. The v5 default is `0`, so the first chunk flushes immediately; set a value to coalesce writes again. |
154
154
  | Hook token retention | `Hook.tokenRetentionUntil` marks the earliest time a token may become available after its run ends. Keep the owning run readable at least that long, and honor `hook_disposed` as an immediate release. Declare `capabilities.hookRetention.active` only once this is implemented, since the runtime otherwise rejects retained hooks before registration. |
155
155
  | Atomic start Hooks | Backs [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts): admit a run and create its start Hook in one atomic step, so a duplicate start is refused naming the owner and the start Hook can be resumed from admission. Declare `capabilities.atomicStartHook.active` only once you implement [the contract](/worlds/building-a-world#optional-atomic-start-hook-admission). |
156
- | Hook resume dedup | `resumeHook()` writes `hook_received` and dispatches the queue message in parallel when the backend collapses concurrent writes carrying the same `(runId, resumeId)` onto one committed event. Declare `capabilities.hookResumeDedup` only if you enforce that constraint **and** `events.list()` returns the committed event's top-level `resumeId`. A World that omits either guarantee must leave the flag unset, which keeps the sequential path. See [Durable hook resume](/docs/changelog/lazy-hook-resume). |
156
+ | Hook resume dedup | `resumeHook()` writes `hook_received` and dispatches the queue message in parallel when the backend collapses concurrent writes carrying the same `(runId, resumeId)` onto one committed event. Declare `capabilities.hookResumeDedup` only if you enforce that constraint **and** `events.list()` returns the committed event's top-level `resumeId`. A World that omits either guarantee must leave the flag unset, which keeps the sequential path. |
157
157
  | Resolved hook resume | Lets `resumeHook()` deliver to a stored [`Hook`](/docs/api-reference/workflow-api/resume-hook#reuse-a-resolved-hook) without looking up its token again. Declare `capabilities.resolvedHookResume` only if a write carrying `requireHookResumeDedup` either commits with atomic resume deduplication or is refused (400/404) before anything is written. The runtime then looks the token up and delivers as usual. Without the flag, a stored Hook is delivered through the existing path. |
158
158
  | Hook token takeover | Backs [`createHook({ experimental_force: true })`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds). When a forced `hook_created` names a token another live run holds, append `hook_disposed` with `forceClaimedBy: { runId, hookId }` to the holder's log and refuse later `hook_received` writes to it, then re-point the token to the claimer and record `Hook.claimedFrom`. Refuse the takeover with an ordinary `hook_conflict` carrying `forceRefusedReason: 'victim-spec-version'` when the holder was stamped below spec version 8, and answer a `hook_received` refused by a takeover with `HookForceClaimedError` so `resumeHook()` can follow the token. Declare `capabilities.hookForceClaim` only once you give these guarantees. Without it, the runtime fails a forced `createHook()` at registration. |
159
159
 
@@ -187,4 +187,4 @@ The first-party implementations in `packages/world-local` and `packages/world-po
187
187
 
188
188
  ## Spec 9 (experimental)
189
189
 
190
- A World does not need to implement anything for the experimental spec 9 runtime to migrate to v5: `mintedSpecVersion()` with no options keeps creating spec 8 runs. A World that opts in must tell its users to upgrade every deployment and process that shares it before they set `WORKFLOW_SPEC_VERSION=9`, and not to roll back below that release once spec 9 runs exist. See [Implementing spec 9 in a World](/docs/changelog/spec-9#implementing-spec-9-in-a-world) and [The rollback floor](/docs/changelog/spec-9#the-rollback-floor).
190
+ A World does not need to implement anything for the experimental spec 9 runtime to migrate to v5: `mintedSpecVersion()` with no options keeps creating spec 8 runs. A World that opts in must tell its users to upgrade every deployment and process that shares it before they set `WORKFLOW_SPEC_VERSION=9`, and not to roll back below that release once spec 9 runs exist.