workflow 5.2.2 → 5.3.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 (53) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.d.ts.map +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/internal/errors.d.ts +1 -1
  5. package/dist/internal/errors.d.ts.map +1 -1
  6. package/dist/internal/errors.js +2 -2
  7. package/docs/api-reference/workflow/create-hook.mdx +8 -0
  8. package/docs/api-reference/workflow/fetch.mdx +6 -0
  9. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +10 -2
  10. package/docs/api-reference/workflow-api/get-run.mdx +4 -0
  11. package/docs/api-reference/workflow-api/resume-hook.mdx +58 -2
  12. package/docs/api-reference/workflow-api/start.mdx +68 -3
  13. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +6 -3
  14. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +68 -0
  15. package/docs/api-reference/workflow-errors/index.mdx +6 -0
  16. package/docs/api-reference/workflow-errors/meta.json +2 -0
  17. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +2 -0
  18. package/docs/api-reference/workflow-errors/workflow-start-error.mdx +58 -0
  19. package/docs/api-reference/workflow-errors/workflow-world-error.mdx +12 -1
  20. package/docs/api-reference/workflow-runtime/world/index.mdx +1 -1
  21. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -1
  22. package/docs/changelog/eager-processing.mdx +2 -0
  23. package/docs/changelog/index.mdx +1 -0
  24. package/docs/changelog/lazy-event-creation.md +1 -1
  25. package/docs/changelog/meta.json +1 -0
  26. package/docs/changelog/resilient-start.mdx +2 -0
  27. package/docs/changelog/spec-9.mdx +4019 -0
  28. package/docs/changelog/turbo-mode.md +4 -0
  29. package/docs/configuration/cli-and-web-ui.mdx +3 -1
  30. package/docs/configuration/runtime-tuning.mdx +65 -3
  31. package/docs/configuration/worlds.mdx +18 -1
  32. package/docs/cookbook/advanced/child-workflows.mdx +2 -2
  33. package/docs/cookbook/common-patterns/batching.mdx +3 -1
  34. package/docs/cookbook/common-patterns/idempotency.mdx +11 -12
  35. package/docs/errors/fetch-in-workflow.mdx +7 -1
  36. package/docs/errors/index.mdx +2 -2
  37. package/docs/errors/max-events-exceeded.mdx +80 -0
  38. package/docs/errors/replay-timeout.mdx +48 -0
  39. package/docs/errors/run-expired.mdx +3 -1
  40. package/docs/foundations/errors-and-retries.mdx +8 -2
  41. package/docs/foundations/hooks.mdx +3 -1
  42. package/docs/foundations/idempotency.mdx +190 -60
  43. package/docs/how-it-works/encryption.mdx +1 -1
  44. package/docs/how-it-works/event-sourcing.mdx +8 -2
  45. package/docs/observability/index.mdx +2 -0
  46. package/docs/observability/retention.mdx +8 -0
  47. package/docs/whats-new.mdx +4 -2
  48. package/docs/worlds/building-a-world.mdx +47 -8
  49. package/docs/worlds/local.mdx +6 -0
  50. package/docs/worlds/postgres.mdx +230 -129
  51. package/docs/worlds/upgrading-to-v5.mdx +8 -1
  52. package/docs/worlds/vercel.mdx +162 -8
  53. package/package.json +11 -11
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  title: Idempotency
3
- description: Make step retries safe and coordinate duplicate workflow starts with hook tokens.
3
+ description: Make step retries safe, and start a workflow run at most once per key with start({ hook }).
4
4
  type: conceptual
5
- summary: Use step IDs for retry-safe external calls, and route duplicate workflow-start requests through deterministic hook tokens.
5
+ summary: Use step IDs for retry-safe external calls, and pass a deterministic hook token to start() so a duplicate request is refused or routed to the run that owns it.
6
6
  prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
@@ -13,7 +13,7 @@ related:
13
13
 
14
14
  Idempotency is a property of an operation that ensures repeated attempts have the same effect as a single attempt.
15
15
 
16
- In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency coordinates duplicate requests that try to start the same workflow.
16
+ In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency makes duplicate requests start the same workflow run only once.
17
17
 
18
18
  ## Step idempotency
19
19
 
@@ -57,11 +57,190 @@ Why this works:
57
57
 
58
58
  Step idempotency protects side effects **inside** a workflow run. Run idempotency answers a different question: if the same API request is sent twice, should it create one workflow run or two?
59
59
 
60
- Because [hooks](/docs/foundations/hooks) already ensure globally unique active tokens, Workflow can use the same mechanism to coordinate duplicate requests while a run is active.
60
+ Workflow uses a [Hook](/docs/foundations/hooks) token as the idempotency key. Pick a token from your domain, such as an order ID, invoice ID, import ID, or request ID, and pass it to `start()`.
61
61
 
62
- Use a hook token as the idempotency key for an active workflow run. Hook tokens are globally unique while they are active: if another run tries to create a hook with the same token, the runtime records a conflict, `hook.getConflict()` resolves with a `Run` handle for the run that owns the token, and the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict) when the workflow awaits or iterates its payload.
62
+ ### Start a run once per key
63
63
 
64
- The token should come from your domain, such as an order ID, invoice ID, import ID, or request ID. Create the hook near the beginning of the workflow and check `await hook.getConflict()` before doing duplicate-sensitive work that depends on owning the active token. Calling `createHook()` alone does not register the hook; awaiting `getConflict()` suspends the workflow to commit the registration. Check it before calling any step: steps the workflow calls before it suspends are started alongside the hook's registration, so a duplicate run that only learns of the conflict later (for example, by awaiting the hook and letting `HookConflictError` end the run) may already have started them. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
64
+ ```typescript title="app/api/orders/route.ts" lineNumbers
65
+ import { start } from "workflow/api";
66
+ import { HookConflictError } from "workflow/errors";
67
+ import { processOrder } from "./workflows/process-order";
68
+
69
+ export async function POST(request: Request) {
70
+ const { orderId } = await request.json();
71
+
72
+ try {
73
+ const run = await start(processOrder, [orderId], {
74
+ hook: { token: `order:${orderId}` }, // [!code highlight]
75
+ });
76
+ return Response.json({ runId: run.runId, duplicate: false });
77
+ } catch (error) {
78
+ if (!HookConflictError.is(error)) throw error;
79
+ return Response.json({ runId: error.conflictingRunId, duplicate: true }); // [!code highlight]
80
+ }
81
+ }
82
+ ```
83
+
84
+ `start({ hook })` admits the run and creates its **start Hook** in one atomic step. Exactly one run owns the token. A duplicate `start()` with the same token throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) with the owner's `conflictingRunId`. The duplicate never becomes a run, and none of its code runs.
85
+
86
+ ### Start or route to the owner
87
+
88
+ A duplicate request often carries data the owner should receive, such as a follow-up message in a chat. Since the start Hook exists from the moment the run is admitted, you can resume it right away on a conflict, even before the owner starts executing:
89
+
90
+ ```typescript title="app/api/orders/route.ts" lineNumbers
91
+ import { resumeHook, start } from "workflow/api";
92
+ import { HookConflictError, HookNotFoundError } from "workflow/errors";
93
+ import { processOrder } from "./workflows/process-order";
94
+
95
+ export async function POST(request: Request) {
96
+ const { orderId, note } = await request.json();
97
+ const token = `order:${orderId}`;
98
+
99
+ let owner: string | undefined;
100
+ for (let attempt = 0; attempt < 3; attempt++) {
101
+ try {
102
+ const run = await start(processOrder, [orderId, note], { hook: { token } });
103
+ return Response.json({ runId: run.runId, started: true });
104
+ } catch (error) {
105
+ if (!HookConflictError.is(error)) throw error;
106
+ owner = error.conflictingRunId;
107
+ }
108
+
109
+ try {
110
+ const hook = await resumeHook(token, { note }); // [!code highlight]
111
+ return Response.json({ runId: hook.runId, started: false });
112
+ } catch (error) {
113
+ // The owner's Hook is no longer resumable (it ended, or disposed its
114
+ // start Hook): try to start again, which may take the token.
115
+ if (!HookNotFoundError.is(error)) throw error; // [!code highlight]
116
+ }
117
+ }
118
+
119
+ // Still refused: a finished owner holds the token for its retention, or
120
+ // the owner is a candidate that was admitted but never became a run.
121
+ throw new Error(`Run ${owner} holds ${token}; it can't be started or resumed`);
122
+ }
123
+ ```
124
+
125
+ Every caller either starts the run, delivers its payload to the owner, or learns which run holds the token. While the owner's start Hook is open, the loop needs at most two calls. A `HookNotFoundError` after a conflict means the owner's Hook is no longer resumable: the owner ended, or [disposed its start Hook](#take-care-with-the-start-hooks-lifecycle). The next `start()` may then take the token, or be refused again: by a finished owner that still holds it for its retention, or by another caller that started first.
126
+
127
+ If the token has a [retention](#keep-the-token-after-the-run-ends), a finished owner keeps refusing new starts until the retention passes, and its Hook can no longer be resumed, so the loop above gives up after its attempts and names that run. Use `getRun(owner)` to tell the caller what the finished run returned.
128
+
129
+ ### Receive the payloads in the workflow
130
+
131
+ To read the payloads, call `createHook()` in the workflow with the same token:
132
+
133
+ ```typescript title="workflows/process-order.ts" lineNumbers
134
+ import { createHook } from "workflow";
135
+
136
+ type OrderUpdate = { note: string; done?: boolean };
137
+ declare function recordNote(orderId: string, note: string): Promise<void>; // @setup
138
+
139
+ export async function processOrder(orderId: string, note: string) {
140
+ "use workflow";
141
+
142
+ await recordNote(orderId, note);
143
+
144
+ const updates = createHook<OrderUpdate>({ token: `order:${orderId}` }); // [!code highlight]
145
+ for await (const update of updates) {
146
+ await recordNote(orderId, update.note);
147
+ if (update.done) break;
148
+ }
149
+ }
150
+ ```
151
+
152
+ - `createHook({ token })` with the run's start token returns a handle bound to the start Hook. It doesn't register a new Hook, so it adds no step, and `await hook.getConflict()` resolves `null`.
153
+ - Payloads resumed before the workflow opens the Hook are kept, and are delivered in order once it does.
154
+ - If the workflow never opens it, the token was only an idempotency key. The run completes normally, and unread payloads are simply left unread.
155
+ - `metadata` and `experimental_minRetention` belong on `start({ hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to this `createHook()` throws.
156
+
157
+ ### Keep the token after the run ends
158
+
159
+ The start Hook follows the ordinary Hook lifecycle, like a `createHook()` in the run. Without a retention, the token is released when the run ends, and a later `start()` with the token is admitted as a new run.
160
+
161
+ To refuse late duplicates too, set `experimental_minRetention`. It accepts the same duration string, milliseconds, or `Date` as [`createHook({ experimental_minRetention })`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends), and a duration counts from `start()`:
162
+
163
+ ```typescript lineNumbers
164
+ import { start } from "workflow/api";
165
+ import { processOrder } from "./workflows/process-order";
166
+ declare const orderId: string; // @setup
167
+
168
+ const run = await start(processOrder, [orderId, ""], {
169
+ hook: {
170
+ token: `order:${orderId}`,
171
+ experimental_minRetention: "30 days", // [!code highlight]
172
+ metadata: { orderId },
173
+ },
174
+ });
175
+ ```
176
+
177
+ The run owns the token until it ends, even if the retention passes first. After the run ends, and until the retention passes:
178
+
179
+ - a duplicate `start()` throws `HookConflictError` naming the finished owner;
180
+ - [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) still returns the Hook, with the `start()` metadata;
181
+ - `resumeHook()` throws `HookNotFoundError`, because a finished run can't receive payloads.
182
+
183
+ There is no default retention.
184
+
185
+ Cancelling the owner ends the run, so it releases the token too, once any retention has passed.
186
+
187
+ ### Take care with the start Hook's lifecycle
188
+
189
+ <Callout type="warn">
190
+ The run holds its token only while its start Hook does. Disposing the start Hook, with `hook.dispose()` or when a `using` declaration in an inner scope ends, releases the token at once, as it does for any Hook. A later `start()` with the token is then admitted as a new run, even while this one is still running, and `experimental_minRetention` no longer applies: it only holds the token after a run that ends without disposing the Hook.
191
+ </Callout>
192
+
193
+ Open the start Hook with `const`, as in the examples above, and let the run's end release it. After disposing it, the run can call `createHook({ token })` again for a new Hook, but only if no other run has taken the token in the meantime; otherwise `getConflict()` names that run.
194
+
195
+ ### Dispose the start Hook with `using`
196
+
197
+ `using` disposes a Hook when its scope ends, which reads well when the workflow only needs the payloads for part of its work:
198
+
199
+ ```typescript title="workflows/process-order.ts" lineNumbers
200
+ import { createHook } from "workflow";
201
+
202
+ type OrderUpdate = { note: string; done?: boolean };
203
+ declare function recordNote(orderId: string, note: string): Promise<void>; // @setup
204
+ declare function shipOrder(orderId: string): Promise<void>; // @setup
205
+
206
+ export async function processOrder(orderId: string, note: string) {
207
+ "use workflow";
208
+
209
+ {
210
+ using updates = createHook<OrderUpdate>({ token: `order:${orderId}` }); // [!code highlight]
211
+ for await (const update of updates) {
212
+ await recordNote(orderId, update.note);
213
+ if (update.done) break;
214
+ }
215
+ } // The start Hook is disposed here, and the token is released.
216
+
217
+ await shipOrder(orderId);
218
+ }
219
+ ```
220
+
221
+ Disposing the start Hook ends the run's idempotency: from the end of that block, another `start()` with the token is admitted while this run ships the order. Use it when that is what you want. To keep duplicates out for the whole run, use `const`. A `using` at the top level of the workflow function disposes the Hook only as the run returns, but with a retention it releases the token then instead of holding it.
222
+
223
+ ### When `start()` can't confirm the outcome
224
+
225
+ If `start({ hook })` can't confirm whether its candidate run was queued or admitted, for example because the World timed out, it throws [`WorkflowStartError`](/docs/api-reference/workflow-errors/workflow-start-error) with the candidate's `runId`. The outcome is unknown, not failed. Retrying with the same token is safe: the retry either becomes the owner, or is refused with a `HookConflictError` naming the owner. Inside a workflow, the `start()` step retries it on its own.
226
+
227
+ ### World support
228
+
229
+ `start({ hook })` requires a World that supports atomic start Hooks (`capabilities.atomicStartHook`), and Hook retention when you set `experimental_minRetention`. Otherwise `start()` throws before it enqueues anything.
230
+
231
+ | World | Support |
232
+ | --- | --- |
233
+ | [Local World](/worlds/local) | Supported. |
234
+ | [Postgres World](/worlds/postgres) | Opt in with [`WORKFLOW_POSTGRES_EXPERIMENTAL_START_HOOK=1`](/worlds/postgres#workflow_postgres_experimental_start_hook), after applying migration `0028_add_start_hook_admissions` (required for every Postgres World on this version, with or without the flag). Stop workers running a previous version first. |
235
+ | [Vercel World](/worlds/vercel) | Opt in with [`WORKFLOW_VERCEL_EXPERIMENTAL_START_HOOK=1`](/worlds/vercel#workflow_vercel_experimental_start_hook), which needs a backend that supports start Hooks. |
236
+
237
+ See [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) for the full option reference.
238
+
239
+ ### Coordinate inside the workflow
240
+
241
+ On a World without atomic start Hooks, or when a run should decide for itself how to treat a duplicate, coordinate with `createHook()` and `getConflict()` in the workflow instead. Hook tokens are unique while active: if another run already owns the token, `await hook.getConflict()` resolves with a `Run` handle for the owner, and awaiting the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict).
242
+
243
+ Create the hook near the beginning of the workflow, and check `await hook.getConflict()` before calling any step. Awaiting it suspends the workflow to commit the registration; steps called before that suspension start alongside it, so a duplicate run that learns of the conflict later may already have started them. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
65
244
 
66
245
  ```typescript lineNumbers
67
246
  import { createHook } from "workflow";
@@ -96,62 +275,15 @@ export async function processOrder(orderId: string): Promise<OrderResult> {
96
275
  }
97
276
  ```
98
277
 
99
- The runtime creates the hook atomically. At most one hook can own `order:${orderId}`, so duplicate workflow runs converge on one owner. A duplicate run observes `getConflict()` resolving with the owner's `Run` and returns before it reaches `chargeOrder()`. The conflicting run's accessors (`status`, `returnValue`, `cancel()`, …) are durable steps, so the duplicate run can do more than report the owner. See [conflict-handling strategies](#conflict-handling-strategies) below.
100
-
101
- Outside the workflow, try to resume the hook first. If the hook is not registered yet, start the workflow and retry the resume until the new run creates the hook:
102
-
103
- ```typescript lineNumbers
104
- import { resumeHook, start } from "workflow/api";
105
- import { HookNotFoundError } from "workflow/errors";
106
- import { processOrder } from "./workflows/process-order";
107
-
108
- type OrderRequest = { confirmed: boolean };
109
-
110
- async function resumeOrder(token: string, payload: OrderRequest) {
111
- for (let attempt = 0; attempt < 5; attempt++) {
112
- try {
113
- return await resumeHook(token, payload); // [!code highlight]
114
- } catch (error) {
115
- if (!HookNotFoundError.is(error)) throw error;
116
- await new Promise((resolve) => setTimeout(resolve, 100));
117
- }
118
- }
119
-
120
- throw new Error("Order workflow did not register its hook in time");
121
- }
122
-
123
- export async function POST(request: Request) {
124
- const { orderId, confirmed } = await request.json();
125
- const token = `order:${orderId}`;
126
- const payload = { confirmed };
127
-
128
- try {
129
- const hook = await resumeHook(token, payload); // [!code highlight]
130
- return Response.json({ runId: hook.runId, reused: true });
131
- } catch (error) {
132
- if (!HookNotFoundError.is(error)) throw error;
133
- }
134
-
135
- const run = await start(processOrder, [orderId]); // [!code highlight]
136
- const resumed = await resumeOrder(token, payload);
137
-
138
- // A concurrent request's run may have won the race between `start()` // [!code highlight]
139
- // and hook registration. The resume always reaches the actual active // [!code highlight]
140
- // owner, so compare run IDs instead of waiting for this run to finish. // [!code highlight]
141
- return Response.json({ // [!code highlight]
142
- runId: resumed.runId, // [!code highlight]
143
- reused: resumed.runId !== run.runId, // [!code highlight]
144
- }); // [!code highlight]
145
- }
146
- ```
278
+ Outside the workflow, try `resumeHook()` first, and on `HookNotFoundError` call `start()` and retry the resume until the new run registers its hook.
147
279
 
148
280
  <Callout type="warn">
149
- This avoids creating a new run only after the first run has registered its hook. Because `start()` returns before the run body executes and calls `createHook()`, two concurrent requests can both observe "no hook yet" and each call `start()`. The race is resolved inside the workflow body, where the losing run observes `getConflict()` resolving with the active owner and returns without doing duplicate-sensitive work, and the route detects it by comparing the resumed hook's `runId` against the run it just started, without waiting for either run to finish. A native API for atomically starting a run and registering a hook is in the works. Until then, model recovery inside the workflow by checking `hook.getConflict()`.
281
+ Unlike `start({ hook })`, this doesn't stop a duplicate from becoming a run. Two concurrent requests can both see "no hook yet" and each call `start()`. The losing run is still created, queued, and started, and returns once `getConflict()` resolves with the owner. The route can detect it by comparing the resumed hook's `runId` with the run it started.
150
282
  </Callout>
151
283
 
152
- This coordinates active runs by default: the token becomes available when its workflow ends. Set `experimental_minRetention` to keep it unavailable to late duplicates. After the workflow ends, the Hook can still be found with `getHookByToken()` until retention ends, but it cannot be resumed. See [`createHook()` minimum retention](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) for examples and supported values.
284
+ The token becomes available when its workflow ends, unless you set `experimental_minRetention` on `createHook()`. See [`createHook()` minimum retention](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends).
153
285
 
154
- ### Conflict-handling strategies
286
+ #### Conflict-handling strategies
155
287
 
156
288
  Some workflow systems resolve duplicate IDs with a fixed, pre-declared policy, typically a static choice between rejecting the new execution, deferring to the existing one, or terminating it. Workflow has no policy enum. `hook.getConflict()` hands the duplicate run the conflicting `Run` itself, and the policy is ordinary code, including policies that inspect state before deciding, which static configuration can't express.
157
289
 
@@ -302,9 +434,7 @@ export async function processOrderNewestWins(orderId: string) {
302
434
 
303
435
  A run started at a Workflow spec version below 8, including runs started by older SDK releases, can't be taken from. In that case the forced Hook rejects with `HookConflictError`, as it would without `experimental_force`.
304
436
 
305
- If duplicate requests should only reuse the active run without sending data, use [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) as an advisory pre-check before calling `start()`. The workflow should still check `hook.getConflict()`, because the lookup and `start()` are not atomic.
306
-
307
- Because this pattern uses hooks for idempotency, duplicate requests can also inject additional data and steer the existing run. The route example above uses `resumeHook()` for that: if the hook already exists, the duplicate request resumes the active workflow; if the hook is not registered yet, the route starts the workflow and retries `resumeHook()` so the payload is not dropped.
437
+ [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) before `start()` is only an advisory pre-check in this pattern: the lookup and `start()` are not atomic, so the workflow should still check `hook.getConflict()`.
308
438
 
309
439
  ## Related docs
310
440
 
@@ -99,7 +99,7 @@ getEncryptionKeyForRun?(
99
99
  ): Promise<Uint8Array | undefined>;
100
100
  ```
101
101
 
102
- Use `getEncryptionKeyForRun(run)` when the run entity already exists. Use `getEncryptionKeyForRun(runId, context?)` in runtime paths like `start()` where the run has not been created yet but the world may still need context such as `deploymentId`.
102
+ Use `getEncryptionKeyForRun(run)` when the runtime already holds the run entity. Use `getEncryptionKeyForRun(runId, context?)` everywhere else: in paths like `start()` where the run does not exist yet, and in paths that have a run id but no reason to load the run's payloads, such as resolving the key for a stream read. Either way `context` carries whatever the World needs to find the key, such as `deploymentId`.
103
103
 
104
104
  To add encryption support to a custom `World`:
105
105
 
@@ -129,6 +129,8 @@ While a hook is active, its token is reserved and cannot be used by other workfl
129
129
 
130
130
  When a workflow ends, its hooks can no longer be resumed. They are normally removed, and their tokens become available again. With `experimental_minRetention`, a hook remains readable, and its token remains unavailable until retention ends. A `hook_disposed` event removes the hook and makes its token available immediately.
131
131
 
132
+ A hook disposed as the workflow returns or throws, such as one declared with `using` in the workflow function's top-level scope, is released by the run's `run_completed` or `run_failed` event, so the log records no separate `hook_disposed`. Disposing a hook that uses `experimental_minRetention` still records one, because it releases the token before retention ends.
133
+
132
134
  See [Hooks and webhooks](/docs/foundations/hooks) for more on how hooks and webhooks work.
133
135
 
134
136
  ### Wait lifecycle
@@ -207,7 +209,7 @@ Events are categorized by the entity type they affect. Each event contains metad
207
209
 
208
210
  Counting the events above is how you size a run. A step that succeeds on the first attempt contributes three events; a retry adds another `step_started`, preceded by a `step_retrying` when the World emits one; a sleep contributes two, and a hook at least two.
209
211
 
210
- A run's log is capped — the [Vercel World](/worlds/vercel#per-run-limits) fails anything past its ceiling with `MAX_EVENTS_EXCEEDED`. Replay reads the whole log, so a run gets slower as it grows and is worth splitting well before it fails: split into [child workflows](/cookbook/advanced/child-workflows) once a run would grow past a few thousand events. How much the growth costs depends on how often the run replays; [Steps and long runs](/docs/performance#steps-and-long-runs) shows how step-to-step overhead changes through a 1,020-step run.
212
+ A run's log is capped — the [Vercel World](/worlds/vercel#per-run-limits) fails anything past its ceiling with `MAX_EVENTS_EXCEEDED`. Replay reads the whole log, so a run gets slower as it grows and is worth splitting well before it fails: split into [child workflows](/cookbook/advanced/child-workflows) once a run would grow past a few thousand events. Runs on the QuickJS VM with snapshotting resume from a snapshot instead of replaying the whole log, and are exempt from the ceiling; see [max-events-exceeded](/docs/errors/max-events-exceeded). How much the growth costs depends on how often the run replays; [Steps and long runs](/docs/performance#steps-and-long-runs) shows how step-to-step overhead changes through a 1,020-step run.
211
213
 
212
214
  ## Terminal states
213
215
 
@@ -287,7 +289,7 @@ Both save a reload, so the rule for which writes send them is not about the even
287
289
  | `run_created` | `start()` | Nothing | No log exists yet. |
288
290
  | `run_started` | Replay, first write of a delivery | `eventCount` when a log is loaded; no cursor | The `run_started` response already carries the full log as a preload. |
289
291
  | `step_created`, `wait_created`, `hook_disposed`, `attr_set` | Suspension handler | `eventCount` | The handler keeps writing from this log and the replay resumes from it. |
290
- | `hook_created` | Suspension handler | `eventCount` and `sinceCursor` (only when the suspension creates exactly one hook) | The delta is how a hook whose payload already arrived resolves without another invocation. Two creates diffing against one cursor would give two deltas of which only the first could be taken. |
292
+ | `hook_created` | Suspension handler | `eventCount` and `sinceCursor` for a lone hook; independent concurrent Node.js registrations in a hooks-only suspension defer both | A lone create returns a delta. Concurrent registrations reconcile their committed events together and reload when the responses do not cover a consecutive history suffix. |
291
293
  | `hook_received` | Replay resuming a hook | `eventCount` | The replay continues from the log right after. |
292
294
  | `hook_received` | Webhook or `resumeHook()` | Nothing | Out-of-band. It enqueues a delivery that loads the log. |
293
295
  | `wait_completed` | Replay completing an elapsed wait | `eventCount` | The replay continues from the log right after. |
@@ -381,3 +383,7 @@ Step-to-step overhead (STSO) measures the time the runtime adds between two step
381
383
  <MetricVideo metric="stso" />
382
384
 
383
385
  See [Step-to-step overhead](/docs/performance#step-to-step-overhead-stso) on the Performance page for how it's measured and the latest results.
386
+
387
+ ## Spec 9 (experimental)
388
+
389
+ The experimental spec 9 runtime writes the same event types with a different model: one orchestrator per run writes every decision behind an in-band fence, step and wait events are plain appends, and an inline step is created by its first `step_started`. See [The event log on spec 9 runs](/docs/changelog/spec-9#the-event-log).
@@ -80,6 +80,8 @@ To inspect workflows running on Vercel, ensure you're logged in to the Vercel CL
80
80
  npx workflow inspect runs --backend vercel
81
81
  ```
82
82
 
83
+ Without an interactive `vercel login`, such as in CI, pass the auth token, project ID, team ID, and environment explicitly. See [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
84
+
83
85
  When deployed to Vercel, workflow data is [encrypted end-to-end](/docs/how-it-works/encryption). Encrypted fields display as locked placeholders until you choose to decrypt them using the **Decrypt** button in the web UI or the `--decrypt` flag in the CLI.
84
86
 
85
87
  ## More observability features
@@ -15,6 +15,14 @@ each of its steps, the payloads on its event log, and anything written to its
15
15
  streams. How long that data is kept is decided by the World you are running
16
16
  on, not by the SDK.
17
17
 
18
+ <Callout type="info">
19
+ For the [Vercel World](/worlds/vercel), retention is documented in the
20
+ [Vercel Workflows docs](https://vercel.com/docs/workflows/retention): how long
21
+ run payloads stay readable and when they're deleted, how long run metadata is
22
+ kept, where run data is stored, and how to check whether a run's data has
23
+ expired.
24
+ </Callout>
25
+
18
26
  `experimental_retention` on [`start()`](/docs/api-reference/workflow-api/start)
19
27
  lets a run ask for a specific retention period, rather than the World's default.
20
28
 
@@ -179,6 +179,8 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
179
179
 
180
180
  - **`start()` from inside a workflow.** Spawn a child run or hand off to a new run directly in a workflow function, without wrapping it in a step. See [Starting workflows](/docs/foundations/starting-workflows).
181
181
  - **Hook token takeover.** Pass `experimental_force: true` to [`createHook()`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds) when the newest run should own a token another run still holds. The previous owner is woken and its `await hook` rejects with [`HookForceClaimedError`](/docs/api-reference/workflow-errors/hook-force-claimed-error), while `resumeHook()` callers, including one already in flight, are routed to the new owner without noticing. Supported by all three first-party Worlds.
182
+ - **Idempotent starts.** Pass `hook: { token }` to [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) to admit at most one run per token. A duplicate throws `HookConflictError` naming the owner and never becomes a run, and the owner's start Hook can be resumed right away. See [Run idempotency](/docs/foundations/idempotency#start-a-run-once-per-key).
183
+ - **Resume a stored Hook without another lookup.** Pass the `Hook` returned by `getHookByToken()` or `resumeHook()` back to [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook#reuse-a-resolved-hook) instead of its token, and later deliveries skip the token lookup. The Hook survives JSON serialization, so you can keep it with your server-side session state. Supported on the Vercel World.
182
184
  - **Stronger hook coordination.** `hook.getConflict()` resolves with the conflicting [`Run`](/docs/api-reference/workflow-api/get-run) rather than a bare `{ runId }`, so a duplicate can `await conflict.status`, `await conflict.returnValue`, or `await conflict.cancel()` directly. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
183
185
  - **Support for more frameworks.** [React Router](/docs/getting-started/react-router) (v7 and v8, via Nitro) and [NestJS](/docs/getting-started/nestjs) are now supported.
184
186
  - **A misrouted delivery no longer fails a run.** Runs are pinned to the deployment that created them. A delivery that arrives at a different deployment is now re-routed to the pinned one with backoff instead of failing, and only gives up with the new [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) error once the recovery budget is spent. Nothing executes on the wrong deployment while this happens. In 4.x the same situation surfaced as an unexplained decryption failure.
@@ -199,13 +201,13 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
199
201
  | `hook.getConflict()` resolves with a `Run` | Replace `conflict.runId` round trips through `getRun()` inside a step with the accessors on `conflict` directly. `conflict.runId` still works. |
200
202
  | `hook.metadata` is a Promise on hooks returned by `getHookByToken()` and `resumeHook()` | Write `await hook.metadata` where you read it. Hydrating metadata can add network round trips, and those are now paid only by code that reads it, so the lookup itself is a single read. The `Hook` type is exported from `workflow/api`; the World-level record from `world.hooks.getByToken()` is unchanged. See [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token). |
201
203
  | `experimental_setAttributes` removed | Import `setAttributes` instead, and `SetAttributesOptions` in place of `ExperimentalSetAttributesOptions`. The deprecated aliases are gone. |
202
- | [`getWorld()`](/docs/api-reference/workflow-runtime/get-world), [`getWorldHandlers()`](/docs/api-reference/workflow-runtime/get-world-handlers), and [`createWorld()`](/docs/api-reference/workflow-runtime/create-world) are async | They resolve a `Promise` now, so await the call before reaching for anything on it: `const world = await getWorld();` then `await world.start?.();`. This mainly affects the `instrumentation.ts` bootstrap that starts a World with background workers, such as the [Postgres World](/worlds/postgres#starting-the-world). Under TypeScript the old shape fails the build; in plain JavaScript it does not, and `.start` reads as `undefined` on a promise, so the worker never starts and nothing is logged. Writing `await getWorld()` is also valid on 4.x, so the change can be made before upgrading. |
204
+ | [`getWorld()`](/docs/api-reference/workflow-runtime/get-world), [`getWorldHandlers()`](/docs/api-reference/workflow-runtime/get-world-handlers), and [`createWorld()`](/docs/api-reference/workflow-runtime/create-world) are async | They resolve a `Promise` now, so await the call before reaching for anything on it: `const world = await getWorld();` then `await world.start?.();`. This mainly affects the `instrumentation.ts` bootstrap that starts a World with background workers, such as the [Postgres World](/worlds/postgres#start-the-world-when-your-server-starts). Under TypeScript the old shape fails the build; in plain JavaScript it does not, and `.start` reads as `undefined` on a promise, so the worker never starts and nothing is logged. Writing `await getWorld()` is also valid on 4.x, so the change can be made before upgrading. |
203
205
  | Duplicate step or workflow IDs fail the build | 4.x resolved collisions across non-exported workspace files last-write-wins. If you start encountering build failures after upgrading, rename the colliding functions. |
204
206
  | The generated bundles are renamed, and the step route is gone | Only affects apps that wire the output of `workflow build` into their own server instead of using a framework integration. `flow.js` and `webhook.js` are now `flow.mjs` and `webhook.mjs` with named exports only, so a default import resolves to `undefined`. `step.js` became `__step_registrations.mjs`, an internal module that `flow.mjs` imports: delete the `POST /.well-known/workflow/v1/step` route rather than repointing it, because the flow handler now serves step deliveries too. See [Framework integrations](/docs/how-it-works/framework-integrations). |
205
207
  | Default trace mode is `linked` | Update dashboards that assume one trace per run, or set `WORKFLOW_TRACE_MODE=continuous`. |
206
208
  | The event-creation precondition guard is gone | `WORKFLOW_PRECONDITION_GUARD` no longer exists, and no World in the SDK rejects a write for a stale snapshot. Remove the variable if you set it. A replay that is behind now learns what it missed from the write it makes next instead of from a rejection, and [`PreconditionFailedError`](/docs/api-reference/workflow-errors/precondition-failed-error) remains only for a custom World that would still rather refuse. |
207
209
  | Event IDs are slot numbers, not ULIDs | An event ID is now its 1-based position in the run's log (`evnt_00000000000000000000000042`). It is unique only within a run, so pair it with the `runId` as a key, and it carries no timestamp: decoding one yields the Unix epoch rather than a creation time, so read `createdAt` off the event instead. Other entity IDs are unchanged. See [Event IDs](/docs/how-it-works/event-sourcing#event-ids). |
208
- | A per-run event limit is enforced | The World supplies the ceiling; for the Vercel World see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits). A run that reaches it fails with `MAX_EVENTS_EXCEEDED`. Split unbounded loops into [child workflows](/cookbook/advanced/child-workflows). [`WORKFLOW_MAX_EVENTS`](/docs/configuration/runtime-tuning#workflow_max_events) tunes the ceiling on the Local and Postgres Worlds; the Vercel World's is service-owned and the variable does not override it. |
210
+ | A per-run event limit is enforced | The World supplies the ceiling; for the Vercel World see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits). A run that reaches it fails with `MAX_EVENTS_EXCEEDED`. Split unbounded loops into [child workflows](/cookbook/advanced/child-workflows), or run long-running workflows on the QuickJS VM with snapshotting, which is [exempt from the default ceiling](/docs/errors/max-events-exceeded). [`WORKFLOW_MAX_EVENTS`](/docs/configuration/runtime-tuning#workflow_max_events) tunes the ceiling on the Local and Postgres Worlds; the Vercel World's is service-owned and the variable does not override it. |
209
211
  | Stream writes flush the first chunk immediately | The leading-edge flush window defaults to `0` instead of 10ms. Restore a window with `streamFlushIntervalMs` or `WORKFLOW_STREAM_FLUSH_INTERVAL_MS`. |
210
212
  | The workflow sandbox is stricter about nondeterminism | `WeakRef`, `FinalizationRegistry`, `Atomics.waitAsync`, and async `WebAssembly` compilation are no longer available inside workflow functions, and `crypto.subtle.digest` computes synchronously (same results, deterministic timing). Move code that needs them into a step. |
211
213
  | `Date()` without `new` returns a string inside workflow functions | This matches the language spec, and 4.x returned a `Date` object. Use `new Date()` where you need the object. Subclassing `Date` now works, so libraries like `TZDate` keep their identity across the sandbox boundary. |
@@ -41,6 +41,9 @@ interface WorldCapabilities {
41
41
  hookRetention?: {
42
42
  active: boolean;
43
43
  };
44
+ atomicStartHook?: {
45
+ active: boolean;
46
+ };
44
47
  maxConcurrency?: boolean;
45
48
  inBandFence?: boolean;
46
49
  hookForceClaim?: boolean;
@@ -56,6 +59,7 @@ interface World extends Storage, Queue, Streamer {
56
59
  getEncryptionKeyForRun?(run: WorkflowRun): Promise<Uint8Array | undefined>;
57
60
  getEncryptionKeyForRun?(runId: string, context?: Record<string, unknown>): Promise<Uint8Array | undefined>;
58
61
  createRunId?(options?: Readonly<Record<string, unknown>>): string;
62
+ regionForRunId?(runId: string): string | null;
59
63
  describeRun?(run: Readonly<Record<string, unknown>>): Record<string, string | null> | null | Promise<Record<string, string | null> | null>;
60
64
  processExitTriggersQueueRedelivery?: boolean;
61
65
  }
@@ -63,7 +67,7 @@ interface World extends Storage, Queue, Streamer {
63
67
 
64
68
  `specVersion` is required. See [Declaring the spec version](#declaring-the-spec-version).
65
69
 
66
- The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue supports `maxConcurrency`-limited consumption, which `WORKFLOW_SEQUENTIAL_REPLAYS=1` uses. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence).
70
+ The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue supports `maxConcurrency`-limited consumption, which `WORKFLOW_SEQUENTIAL_REPLAYS=1` uses. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence). Set `atomicStartHook.active` only when the World implements [atomic start Hook admission](#optional-atomic-start-hook-admission). Without it, `start({ hook })` throws before it enqueues anything.
67
71
 
68
72
  [Slot-numbered event IDs](#event-id-allocation) are a contract requirement rather than a capability, so there is no flag or fallback path.
69
73
 
@@ -73,20 +77,21 @@ The remaining optional members:
73
77
  - `start()` initializes background tasks (for example, queue polling); `close()` releases resources like connection pools and listeners.
74
78
  - `getEncryptionKeyForRun()` returns the AES-256 key used to encrypt data for a run; if it is not implemented, encryption is disabled.
75
79
  - `createRunId()` mints the ID for a new run. Implementations may embed World-specific metadata as long as the result remains a valid ULID. This is how [multi-region placement](/worlds/vercel#multi-region) works. `@workflow/world-vercel` reads `options.region` from the `start()` options and embeds a region tag. When omitted, the runtime generates a standard monotonic ULID.
80
+ - `regionForRunId()` is the inverse of `createRunId()` for Worlds that embed a region: it returns the region an existing run's data lives in, from the ID alone. `recreateRunFromExisting()` uses it so a replayed run lands in the original run's region. Return `null` for an ID you don't recognize; omit the method if your World has no regional dimension.
76
81
  - `describeRun()` returns world-specific display fields for a run (for example, a region decoded from its ID) that tooling like `workflow inspect` renders as extra columns. It must be cheap, tolerate missing fields, and never throw.
77
82
  - `processExitTriggersQueueRedelivery` tells the runtime how to handle an exhausted replay budget. When `true`, it exits and relies on queue redelivery. When `false` or absent, it attempts to write `run_failed` and returns.
78
83
 
79
84
  ### Declaring the spec version
80
85
 
81
- `specVersion` is the protocol version your World implements, and the version stamped on every run it creates. Export `SPEC_VERSION_CURRENT` from `@workflow/world` rather than writing a number:
86
+ `specVersion` is the protocol version your World implements, and the version stamped on every run it creates. Declare `mintedSpecVersion()` from `@workflow/world` rather than writing a number:
82
87
 
83
88
  {/* @skip-typecheck - partial World, the other members are elided */}
84
89
  ```typescript
85
- import { SPEC_VERSION_CURRENT } from '@workflow/world';
90
+ import { mintedSpecVersion } from '@workflow/world';
86
91
 
87
92
  export function createWorld(): World {
88
93
  return {
89
- specVersion: SPEC_VERSION_CURRENT,
94
+ specVersion: mintedSpecVersion(),
90
95
  // ...
91
96
  };
92
97
  }
@@ -94,7 +99,9 @@ export function createWorld(): World {
94
99
 
95
100
  The runtime checks this before it creates or replays anything and throws if the version is outside the range it supports, naming both the range and what your World declared. A version below the range means your World allocates event IDs the runtime cannot read positions out of; above it means your World speaks a protocol this runtime has not learned.
96
101
 
97
- Using the constant keeps that check passing across upgrades. It moves with the `@workflow/world` version your package resolves, so a spec bump raises your declaration and the runtime's requirement together. A hard-coded number leaves your World a version behind the next bump, and the runtime rejects it. Keep `@workflow/world` in the same release channel as the `workflow` version your users install.
102
+ `mintedSpecVersion()` returns the current spec version, or the slot-identity version when [`WORKFLOW_SEALED_LOG=0`](/docs/configuration/runtime-tuning#workflow_sealed_log) opts new runs out. Call it inside `createWorld()` so a process can create Worlds in both modes. It reads `process.env` by default; in a host without `process`, such as a browser, pass the environment as its argument.
103
+
104
+ Calling it keeps the check passing across upgrades. It moves with the `@workflow/world` version your package resolves, so a spec bump raises your declaration and the runtime's requirement together. A hard-coded number, or `SPEC_VERSION_CURRENT`, which does not follow `WORKFLOW_SEALED_LOG`, leaves your World out of step. Keep `@workflow/world` in the same release channel as the `workflow` version your users install. See [Spec versions](/worlds/upgrading-to-v5#spec-versions) for what each version requires of a World.
98
105
 
99
106
  ## The event log model
100
107
 
@@ -221,7 +228,7 @@ Two properties have to hold, and both are about what a reader can conclude from
221
228
  - **Uniqueness.** Two writers racing to append must not both take a position. Settle it where the store settles it, with a unique constraint on `(runId, eventId)` or a conditional write, rather than reading the maximum and adding one in your own process.
222
229
  - **Density.** Positions run from 1 with no holes, which is what lets a reader tell a complete log from a truncated one by its length alone. A writer that loses a race must re-derive its position from the store and take the next free one. Incrementing a local number after a loss leaves a permanent hole, and the runtime treats a hole as a log it cannot safely replay across.
223
230
 
224
- Allocate the position **at the commit** in the same operation that appends the event. This makes a reader's log a *prefix* of the run's log rather than a prefix with a hole. Nothing can land behind a position that a reader has passed. Assigning a position earlier, such as in a request handler, and committing later breaks the property that every replay depends on. This is the one case where you may need [a stale-write rejection](#optional-rejecting-a-stale-write) to compensate.
231
+ Allocate the position **at the commit** in the same operation that appends the event. This makes a reader's log a *prefix* of the run's log rather than a prefix with a hole. Nothing can land behind a position that a reader has passed. Assigning a position earlier, such as in a request handler, and committing later breaks the property that every replay depends on, unless you seal abandoned positions as described below. This is the one case where you may need [a stale-write rejection](#optional-rejecting-a-stale-write) to compensate.
225
232
 
226
233
  #### Optional: pre-assigned positions and `noop` sealing
227
234
 
@@ -235,6 +242,16 @@ The version a World stamps comes from `mintedSpecVersion()`: 8 by default or the
235
242
 
236
243
  Not every write carries `eventCount`, and a World is free to skip the report read for event types whose writer never holds a log to merge it into (the step executor's `step_started`, `step_retrying`, `step_completed`, and `step_failed`, and the run-terminal `run_completed`, `run_failed`, and `run_cancelled`). Which writes send `eventCount` or `sinceCursor`, and why, is tabulated in [Events returned on a write](/docs/how-it-works/event-sourcing#events-returned-on-a-write). When a write carries both, the `sinceCursor` delta is a superset of the report, so return the delta and skip the report.
237
244
 
245
+ Independent concurrent hook registrations in a hooks-only suspension deliberately omit `eventCount` and `sinceCursor`, even though the worker holds a loaded log. The Node.js runtime waits for every registration to settle and verifies that their returned events fill every position immediately after that log. A gap, incomplete response, or missing committed-event cursor keeps the normal history reload. Mixed suspensions, forced claims, and same-token lifecycle operations keep their usual catch-up parameters.
246
+
247
+ ### Optional: returning a committed-event cursor
248
+
249
+ An `events.create()` result may include `eventCursor`: a World-owned cursor that its own ascending `events.list()` accepts as an exclusive position immediately after the returned `event`. It is distinct from a history-page `cursor`, and does not assert that the caller has loaded earlier events.
250
+
251
+ Returning `eventCursor` opts into using the returned `event` as replay input. That event **must equal the event returned by `events.list()` for the same position and `resolveData` option**, including its stored `createdAt`, normalized `tokenRetentionUntil`, resolved metadata bytes, and any `hook_conflict` details such as `conflictingRunId` or `forceRefusedReason`. Return the persisted event rather than reconstructing it from the creation request.
252
+
253
+ The runtime uses the cursor only after proving that the committed responses extend its loaded prefix without a hole. This is optional: a World that omits `eventCursor` remains supported and retains the reload path. The runtime never interprets a World's cursor encoding.
254
+
238
255
  ### Optional: rejecting a stale write
239
256
 
240
257
  A replay writes events derived from the event log it loaded, so a write made from an event log that no longer matches the store can commit events no correct replay would produce. Rejecting one means answering `events.create()` with a `PreconditionFailedError` when the run's log already holds more events than the caller's `eventCount` says it had loaded.
@@ -246,7 +263,7 @@ Implement rejection when your store allocates positions outside the commit and c
246
263
  Two rules make this safe:
247
264
 
248
265
  - **Only reject on evidence.** If your record of a run's events is incomplete, expired, or cannot answer the question, accept the creation. A rejection must always indicate a real discrepancy because the runtime responds by discarding a replay.
249
- - **Accept a creation that carries no `eventCount`.** It came from a caller with no loaded log that could be stale, such as a queued step body or out-of-band writer, rather than a caller claiming the log is empty.
266
+ - **Accept a creation that carries no `eventCount`.** The caller is not claiming the log is empty. It may have no loaded log, as with a queued step body or out-of-band writer, or may deliberately defer catch-up until concurrent hook registrations settle. Without a count there is no evidence for count-based rejection; independent ownership checks and write fences still apply.
250
267
 
251
268
  A rejection may include the events the caller was missing as `{ events, cursor }` on the error's `details`. Include them only when you can prove that the set fully accounts for the discrepancy, isn't truncated, and contains only events from the run being written. The runtime merges them directly into the replay's event log, so incorrect data is worse than no delta. Otherwise, omit them, and the runtime performs a full reload.
252
269
 
@@ -256,7 +273,7 @@ The runtime handles a rejection wherever it arrives. It restarts the replay in-p
256
273
 
257
274
  The in-band writer fence keeps a run to one orchestrator writer when two orchestrator invocations of the same run overlap, for example a delivery that outlives its queue lease while a redelivery of the run is already running. A write made by the run's orchestrator is **in-band** (`params.inBand: true`). Everything else is **out-of-band**: a background step's own events, `hook_received` from `resumeHook()` and webhooks, `run_cancelled` from `cancel()`, and `attr_set` from `setAttributes()` outside the workflow.
258
275
 
259
- The fence is optional, and the runtime does not send `inBand` yet, so a World without it stays fully supported. Declare `capabilities.inBandFence: true` when you implement all of the following:
276
+ The fence is optional. The runtime sends `inBand` only on runs of the experimental spec 9 runtime, so a World without the fence stays fully supported and keeps creating spec 8 runs. Declare `capabilities.inBandFence: true` when you implement all of the following:
260
277
 
261
278
  - **Two counters per run.** Next to whatever allocates event positions, keep `seq`, the highest position allocated to any write, and `seqInBand`, the number of positions allocated to in-band writes. `run_created` counts as in-band and is never fenced itself, so a new run holds `seq = 1, seqInBand = 1` (`IN_BAND_SEQ_AT_RUN_CREATION` from `@workflow/world`).
262
279
  - **List snapshot, or counters on a refusal.** On every `events.list()` page of a slot-numbered run, return `snapshot: { seq, seqInBand }`, read before the listing. A full load, followed to `hasMore: false`, covers every position up to the first page's `seq`. A fenced writer takes its count from that first page, never from counting events, because a count cannot tell which positions were in-band. If your store cannot read the counters on a list, you may list no snapshot, as long as every refusal carries both counters, read together (see below).
@@ -277,6 +294,24 @@ A writer that was refused while writing stops writing from the log it held; only
277
294
 
278
295
  The conformance suite in [`packages/world/src/test-support/in-band-fence-conformance.ts`](https://github.com/vercel/workflow/blob/main/packages/world/src/test-support/in-band-fence-conformance.ts) checks each rule against a World's `events` storage, and `createTestSuite()` from `@workflow/world-testing` checks the counters (from the snapshot, or from a refusal where the World lists none) and a stale in-band write end to end when the World declares the capability.
279
296
 
297
+ ### Optional: atomic start Hook admission
298
+
299
+ [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) makes a start idempotent on a Hook token, and gives the run a **start Hook** that can be resumed from the moment the run is admitted. `start()` enqueues the candidate run first and then writes `run_created`; the queue consumer's `run_started` carries the same request in `eventData.startHook`, and either write may reach the World first. Declare `capabilities.atomicStartHook: { active: true }` when `events.create()` implements all of the following for a `run_created`, or a `run_started` that creates the run, carrying `eventData.startHook = { token, tokenRetentionUntil?, metadata? }`:
300
+
301
+ - **Atomic admission.** Claim the token, record the decision, and create the start Hook as one atomic step. A run must never exist for a candidate that was refused, and a crash partway through must be recoverable by retrying the candidate.
302
+ - **One immutable decision per candidate `runId`.** Every later attempt for the same `runId`, through either write, returns the first decision even if the token has since changed hands: an accepted candidate returns its run (never `EntityConflictError`), and a refused one throws `HookConflictError` with the same `conflictingRunId`.
303
+ - **The start Hook exists from admission.** Its id is `startHookId(runId)` from `@workflow/world`, and it is an ordinary Hook record with the start's `token`, `metadata` and `tokenRetentionUntil`, and `isWebhook: false`. `hooks.getByToken()` and `hooks.get()` return it as soon as admission is durable. `run_created` stands for its `hook_created`: never write a `hook_created` for it, and refuse a `hook_created` whose `correlationId` is `startHookId(runId)` with a 400-class validation error.
304
+ - **Echo.** The run returned from `run_created`, `run_started` and `runs.get` carries `startHook`, including its `hookId`. Keep `token`, `hookId` and `tokenRetentionUntil` in the `run_created` event's `eventData.startHook` (you may drop `metadata` there): the runtime binds the workflow's `createHook({ token })` to the start Hook from it on every replay.
305
+ - **Deliveries to a pending run.** Accept `hook_received` for `startHookId(runId)` while the run is `pending` or `running` (ordinary Hooks stay running-only), and wake the run as for any resume. Never commit a delivery before the run's `run_created` event. If your World admits the run in more than one write and the run doesn't exist yet when a delivery arrives, wait briefly, then answer a retryable error with a `retryAfter` rather than not found.
306
+ - **Ordinary lifecycle.** From then on the start Hook behaves like a Hook the run created. Another run's `start({ hook })` or `createHook()` with the token conflicts, naming the owner. `hook_disposed` for the start Hook frees the token at once, even when `tokenRetentionUntil` is set, and a later `createHook({ token })` in the run is an ordinary `hook_created`. At run end, release the Hook as for any other, or, with `tokenRetentionUntil`, keep it findable by `hooks.getByToken()` but refuse deliveries until that time.
307
+ - **Force claims.** A forced `createHook()` takes the start Hook like any other, including before the owning workflow opens it, and writes `hook_disposed` with `forceClaimedBy` for `startHookId(runId)` to the owner's log. If the owner's run does not exist yet and can still be created, answer a retryable refusal instead.
308
+ - **Orphans.** A candidate that was admitted but whose run was never created must not hold the token forever. A candidate older than `START_HOOK_CANDIDATE_MAX_AGE_MS` (the same bound `run_created` applies to client-minted run IDs) can never be created. While it can still be created, never release its token, and treat deliveries as for a pending run that doesn't exist yet. Once it can't, or once it is fenced, release the token and answer not found.
309
+ - **Permanent refusals.** A request you will never admit (an invalid retention, a candidate past the orphan bound) throws `WorkflowWorldError` with `code: START_HOOK_ADMISSION_REJECTED`, so the queued copy stops retrying. Every copy of the candidate must get the same answer. Set its `reason` to one of `invalid`, `expired`, `token_mismatch`, `ordinary_run` or `disabled` (`StartHookRejectionReason`), which `start()` and the queued copy record on their spans as `workflow.start_hook.rejection_reason`.
310
+ - **Cancelling an uncreated candidate.** A `run_cancelled` for a run ID with no run but an accepted decision fences the candidate (no copy can create it any more), releases its token as for an ended run, and throws `WorkflowWorldError` with `code: START_HOOK_CANDIDATE_CANCELLED`. With no decision, throw `WorkflowRunNotFoundError` as for any missing run.
311
+ - **Switching admission off.** If you can switch admission off, either record the refusal as the candidate's decision and answer `START_HOOK_ADMISSION_REJECTED`, or throw `WorkflowWorldError` with `code: START_HOOK_ADMISSION_DISABLED` and record nothing. The second is not final: `start()` reports it as `WorkflowStartError`, and the queued copy is redelivered, because another copy may be admitted once admission is back on.
312
+
313
+ `world-local` declares it; `world-postgres` declares it only with `WORKFLOW_POSTGRES_EXPERIMENTAL_START_HOOK=1`, and `world-vercel` only with `WORKFLOW_VERCEL_EXPERIMENTAL_START_HOOK=1`. The conformance suite in [`packages/world/src/test-support/atomic-start-hook-conformance.ts`](https://github.com/vercel/workflow/blob/main/packages/world/src/test-support/atomic-start-hook-conformance.ts) checks these rules against a World's storage.
314
+
280
315
  ## Queue interface
281
316
 
282
317
  The Queue interface handles asynchronous workflow execution, including queued step work:
@@ -666,3 +701,7 @@ Your World will then appear on the [Worlds ecosystem](/worlds) page with its com
666
701
  "docs": "https://github.com/you/your-world#readme"
667
702
  }
668
703
  ```
704
+
705
+ ## Supporting spec 9 runs (experimental)
706
+
707
+ Everything above is the contract for spec 8 runs, which every World needs. A World may also let its users opt in to the experimental spec 9 runtime (`WORKFLOW_SPEC_VERSION=9`). To do so it implements the [in-band writer fence](#optional-the-in-band-writer-fence), serializes each spec 9 run's orchestrator deliveries, follows the spec 9 queue and deduplication rules, declares `capabilities.inBandFence: true`, and passes it on as `mintedSpecVersion(process.env, { inBandFence: true })`. `mintedSpecVersion()` called with no options never returns 9, so a World that does none of this keeps creating spec 8 runs. See [Implementing spec 9 in a World](/docs/changelog/spec-9#implementing-spec-9-in-a-world) and [World contract changes](/docs/changelog/spec-9#world-contract-changes).
@@ -86,6 +86,12 @@ Whether queue deliveries go out through Node's built-in `node:http` and `node:ht
86
86
 
87
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`.
88
88
 
89
+ 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
+
91
+ 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
+
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`.
94
+
89
95
  ### `WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS`
90
96
 
91
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.