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
@@ -85,3 +85,7 @@ We decided **not** to ship it, for two reasons:
85
85
  2. **Divergent branches from non-durable results.** Advancing past a step before its result is durable lets the workflow commit to a forward path that a crash-and-redeliver can re-decide differently. A `Promise.race([B, C])` resolved by local timing can pick `B`, run `D(B)`, then crash before `step_completed_B` is durable. The redelivery may re-resolve to `C`, so `D` executed against a winner the durable history never records. The same shape appears for a branch on a non-deterministic step output (`B(v1)` runs, crash, redelivery commits `B(v2)`). Idempotency doesn't cover these because `D(B)`/`D(C)` and `B(v1)`/`B(v2)` are *different* operations, not retries of one. A "run ahead only while at most one result is undurable" gate would contain the race case (a race needs ≥2 concurrent undurable steps) but not the non-deterministic-output case, and that residual hazard plus the re-execution blast radius outweighed the gain.
86
86
 
87
87
  So turbo deliberately stops at forced-optimistic *start* and awaits each `step_completed` before moving on: re-execution after a crash stays deterministic (each step re-runs against the same durable inputs) and bounded (roughly one step, not the whole chain). The idea is recorded here in case a future change (e.g. a determinism signal on steps, or deterministic race resolution) makes run-ahead safe enough to revisit.
88
+
89
+ ## Spec 9 runs
90
+
91
+ This page describes turbo on spec 8 runs, the default. The experimental spec 9 runtime has its own turbo path, and runs ahead of durable writes within bounds that address the two reasons above. See [Turbo](/docs/changelog/spec-9#turbo) and [Run-ahead](/docs/changelog/spec-9#run-ahead) on the spec 9 page.
@@ -12,6 +12,8 @@ The Workflow CLI uses flags first, then environment variables, then defaults or
12
12
 
13
13
  Vercel project and auth settings can often be inferred from `.vercel/project.json` and your Vercel CLI login.
14
14
 
15
+ Whichever way they are resolved, the CLI ends up building a Vercel World from an auth token plus a project ID, team ID, and environment — the same four values any external client needs. Set them explicitly when there is no interactive `vercel login` to infer from, or when writing your own script instead of using the CLI; see [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
16
+
15
17
  ## Target backend
16
18
 
17
19
  ### `--backend` / `-b`
@@ -49,7 +51,7 @@ Vercel project and auth settings can often be inferred from `.vercel/project.jso
49
51
  - Environment variable: `WORKFLOW_VERCEL_ENV`
50
52
  - Default: `production`
51
53
  - Vercel environment for `--backend vercel`.
52
- - Accepts `production` or `preview`.
54
+ - Accepts `production` or `preview`; any other value, including one set through `WORKFLOW_VERCEL_ENV`, is rejected. To reach a custom environment, configure the World programmatically with the environment's slug instead; see [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
53
55
 
54
56
  ## Web UI
55
57
 
@@ -74,6 +74,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
74
74
  - Positive-integer event limit reported by the Local World and enforced by the runtime as `MAX_EVENTS_EXCEEDED`.
75
75
  - The Local and Postgres Worlds also use it as the maximum number of events returned when `events.list()` is called without a limit. If more events exist, the response includes `hasMore: true` and a continuation cursor.
76
76
  - The Vercel World receives its event limit from the service; this environment variable does not override that service-owned value. See [Vercel World limits](/worlds/vercel#per-run-limits).
77
+ - Runs started on the QuickJS engine with snapshotting enabled (see [`WORKFLOW_SNAPSHOT_THRESHOLD`](#workflow_snapshot_threshold)) are exempt from this limit on the Local and Vercel Worlds. See [max-events-exceeded](/docs/errors/max-events-exceeded).
77
78
  - Invalid or non-positive values fall back to the default.
78
79
 
79
80
  ### `WORKFLOW_REPLAY_DIVERGENCE_MAX_RETRIES`
@@ -167,6 +168,19 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
167
168
  - Default: `3`
168
169
  - Clamp: `1` to `16`
169
170
  - Number of newly-created steps one invocation runs inline in parallel before queueing the rest.
171
+ - Steps started beside an awaited hook registration (`hook.getConflict()`) count against the same cap. They are held for the pass that observes the registration and then run inline on it, so the registration still precedes them; only the steps past the cap are queued.
172
+
173
+ ### `WORKFLOW_INLINE_EARLY_ADVANCE`
174
+
175
+ - Default: enabled
176
+ - Spec 8 runs on the Node.js VM engine only (not QuickJS, and not spec 9 runs). When one inline step of a parallel batch completes or fails while its siblings are still running, the invocation replays the workflow right away instead of waiting for the slowest sibling. A branch of a `Promise.all` can then start its next step without waiting for the other branches.
177
+ - Steps still running stay owned by the invocation that started them. They count against `WORKFLOW_MAX_INLINE_STEPS`, so fewer new steps run inline while they run. A branch that fans out while its siblings still run queues the steps past the remaining slots as background steps.
178
+ - When the workflow returns or throws while one of its inline steps is still running (for example a `Promise.race` loser), the run completes or fails right away. That step gets only its current attempt: the invocation lets its body finish, and the bundled Worlds record its `step_completed`, `step_failed` or `step_retrying` after the run's terminal event, but a retry is never run, so a step whose attempt fails retryably stays pending. This matches what happens when a `sleep()` or hook wins a race. `run_completed` or `run_failed` is therefore not always the last event of a run. With this setting off, the run waits for the loser and its retries. The `workflow.inline.running_at_terminal` and `workflow.inline.discarded_outcomes` span attributes, and an info log, report these steps.
179
+ - A step that retries, is throttled, or leaves stream writes unflushed waits for its whole batch, as with this setting off.
180
+ - Branches whose steps were queued because the batch exceeded `WORKFLOW_MAX_INLINE_STEPS` still advance only when the last pending step of the batch completes.
181
+ - When the invocation hands the run off (its replay budget or inline window is spent), it waits for every inline step still running first, so branches advance in lockstep at that point, as with this setting off. An info log marks the hand-off.
182
+ - `workflow.inline.early_advances` counts early replays and `workflow.inline.slots_held_back` counts steps queued because running steps held the inline slots.
183
+ - Set `0` or `false` to wait for every inline step of a batch before replaying.
170
184
 
171
185
  ### `WORKFLOW_TURBO`
172
186
 
@@ -186,7 +200,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
186
200
 
187
201
  - Default: enabled
188
202
  - Node.js VM engine only. Keeps the suspended workflow VM alive across inline steps within one invocation, so each iteration of the inline loop appends only the newly written events instead of replaying the whole event log in a fresh VM. QuickJS manages its own retained inline loop independently of this setting.
189
- - A step- or attribute-driven suspension can keep the VM retained even when hooks or waits are open or created at the same boundary. Hook- or wait-only suspensions park the invocation because nothing in the current delivery can advance them, with one exception: when the hook's own create is what the workflow is waiting on (a `hook.getConflict()` awaiter, or a create whose token is already claimed), the invocation resumes the retained VM over the committed `hook_created` or `hook_conflict` instead of re-invoking through the queue. Any replay divergence falls back to a full replay.
203
+ - A step- or attribute-driven suspension can keep the VM retained even when hooks or waits are open or created at the same boundary. Hook- or wait-only suspensions park the invocation because nothing in the current delivery can advance them, with one exception: when the hook's own create is what the workflow is waiting on (a `hook.getConflict()` awaiter, or a create whose token is already claimed), the invocation resumes the retained VM over the committed `hook_created` or `hook_conflict` instead of re-invoking through the queue, and runs the steps started at that same boundary on the pass after it. Any replay divergence falls back to a full replay.
190
204
  - Step inputs made of plain data (objects, arrays, primitives) and standard built-ins (`Map`, `Set`, `Date`, `RegExp`, typed arrays, `ArrayBuffer`, `URL`, `Headers`) keep the VM retained. Patching or polyfilling built-in prototypes doesn't change that because serialization never calls them. A boundary falls back to a full replay only when serializing its arguments runs code the workflow controls, such as a getter, a proxy, or a custom class serializer, or computes an `Error`'s stack trace.
191
205
  - Set `0` or `false` to replay the Node.js workflow from scratch in a fresh VM on every iteration.
192
206
 
@@ -238,8 +252,9 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
238
252
  - Choosing a value: a restore costs roughly the same regardless of log length (tens of milliseconds to decompress and restore the heap, plus fetching the snapshot), while a full replay grows with the log (tens of milliseconds at a few hundred events, seconds at several thousand). Restoring starts to pay off at a few hundred events, so values in the hundreds suit most long-running workflows. Very low values mostly add snapshot saves to runs that replay quickly anyway.
239
253
  - Snapshots are an optimization, not a source of truth: the event log remains authoritative, and a missing, corrupt, oversized, or incompatible snapshot automatically falls back to a full replay. Snapshots over 32 MB uncompressed are not saved.
240
254
  - Set `0` to opt out and always replay the full event log.
241
- - Like `WORKFLOW_VM`, an explicitly set policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. Runs without a stamped policy use the handler's value, or the default. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
242
- - A snapshot can only be restored by the exact QuickJS engine build that captured it. On Vercel, runs keep executing on the deployment they started on, so deploys don't affect in-flight snapshots. If your deployment serves in-flight runs from new code (for example, a self-hosted rolling update), an upgrade that changes the embedded engine makes every in-flight run fall back to a full replay at its next resume, all at once, before re-snapshotting at its next qualifying suspension. Plan for that one-time replay load when upgrading.
255
+ - Like `WORKFLOW_VM`, the policy is stamped into the run's `executionContext` at start, so a run keeps the snapshot policy it started with. Runs started with `WORKFLOW_VM=quickjs` are stamped with this value, or the default when unset. Runs without a stamped policy use the handler's value, or the default. `start()` rejects an invalid value. An invalid value on the workflow handler disables snapshotting with a warning.
256
+ - Runs stamped with `workflowVm: "quickjs"` and a positive threshold are exempt from the default [per-run event limit](/docs/errors/max-events-exceeded) on the Local and Vercel Worlds.
257
+ - A snapshot can only be restored by the exact QuickJS engine build that captured it. On Vercel, runs keep executing on the deployment they started on, so deploys don't affect in-flight snapshots. If your deployment serves in-flight runs from new code (for example, a self-hosted rolling update), an upgrade that changes the embedded engine or the snapshot format makes every in-flight run fall back to a full replay at its next resume, all at once, before re-snapshotting at its next qualifying suspension. Plan for that one-time replay load when upgrading.
243
258
 
244
259
  What a snapshot contains, and how it is protected:
245
260
 
@@ -416,3 +431,50 @@ These variables are primarily for tests, debugging, or unusual deployments.
416
431
  - Lowers the per-run event ceiling supplied by the World. A run whose event log reaches the ceiling fails with `MAX_EVENTS_EXCEEDED`, which stops a runaway loop from growing its log without bound.
417
432
  - Clamp-down only: it never raises the World's limit, and it applies even when the World supplies none. With no World limit and no override, nothing is enforced.
418
433
  - The Local and Vercel Worlds both supply a limit; the Local World defaults to 25,000 and is configurable with [`WORKFLOW_MAX_EVENTS`](/docs/configuration/worlds#workflow_max_events). The Vercel World's ceiling is documented under [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits).
434
+ - QuickJS runs with snapshotting are exempt from the World's default limit, but this override still applies to them.
435
+
436
+ ## Spec 9 (experimental)
437
+
438
+ Everything above describes spec 8 runs, the default. The experimental spec 9 runtime is opt-in with `WORKFLOW_SPEC_VERSION=9`, reads some of the settings above differently, and adds the settings below. See [Settings and behaviour on spec 9 runs](/docs/changelog/spec-9#settings-and-behaviour-on-spec-9-runs) for each one in full.
439
+
440
+ ### `WORKFLOW_SPEC_VERSION`
441
+
442
+ - Default: unset. New runs use spec version 8, or 6 with [`WORKFLOW_SEALED_LOG=0`](#workflow_sealed_log), which this setting takes precedence over.
443
+ - `9` creates spec 9 runs on a World that declares the in-band fence (the Vercel, Local and Postgres Worlds do). `6` to `8` select that version. A run keeps the version it was created with.
444
+ - Upgrade every deployment and process that shares the World before setting it, and do not roll back below this release once spec 9 runs exist. See [Opting in](/docs/changelog/spec-9#opting-in).
445
+
446
+ ### `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS`
447
+
448
+ - Default: `2000`
449
+ - Log-tail poll interval of a busy orchestrator while no live event feed covers the run. `0` turns polling off.
450
+
451
+ ### `WORKFLOW_ORCHESTRATOR_FEED_POLL_INTERVAL_MS`
452
+
453
+ - Default: `10000`
454
+ - Log-tail poll interval while the World's live event feed is up.
455
+
456
+ ### `WORKFLOW_ORCHESTRATOR_LINGER_MS`
457
+
458
+ - Default: `30000`
459
+ - How long an orchestrator with nothing left to run stays live on the event feed while the run waits on an open hook or a background step. `0` turns it off.
460
+
461
+ ### `WORKFLOW_ORCHESTRATOR_READ_TIMEOUT_MS`
462
+
463
+ - Default: `5000`
464
+ - Deadline for one incremental read of the event log before the orchestrator sends it again. `0` turns the deadline off.
465
+
466
+ ### `WORKFLOW_INLINE_STEP_DEADLINE_MARGIN_MS`
467
+
468
+ - Default: `60000`
469
+ - How long before the inline window ends the orchestrator stops starting inline steps.
470
+
471
+ ### `WORKFLOW_OPTIMISTIC_BACKGROUND_START`
472
+
473
+ - Default: unset
474
+ - `1` or `true` starts a background step's body before its `step_started` commits. Use only when background step bodies are idempotent.
475
+
476
+ ### `WORKFLOW_RUN_AHEAD_DEPTH`
477
+
478
+ - Default: `10`
479
+ - Clamp: `0` to `16`
480
+ - How many inline step outcomes may be unconfirmed at once while the orchestrator runs ahead of its writes. `0` disables run-ahead.
@@ -129,6 +129,7 @@ The Local World is the default outside Vercel and is intended for development.
129
129
 
130
130
  - Default: `25000`
131
131
  - Per-run event ceiling reported to the runtime. A run whose event log reaches it fails with `MAX_EVENTS_EXCEEDED`, bounding a runaway loop. See [`WORKFLOW_MAX_EVENTS_OVERRIDE`](/docs/configuration/runtime-tuning#workflow_max_events_override) for the runtime-side clamp.
132
+ - Runs started on the QuickJS engine with snapshotting enabled are exempt, matching the Vercel World. See [max-events-exceeded](/docs/errors/max-events-exceeded).
132
133
 
133
134
  ## Postgres World
134
135
 
@@ -146,12 +147,14 @@ The Postgres World is a self-hosted durable backend for long-running server proc
146
147
  - Environment variable: none
147
148
  - Default: new `pg.Pool`
148
149
  - Existing `pg.Pool` to use instead of constructing one from `connectionString`.
150
+ - The World attaches no `'error'` listeners to a pool you pass. Listen on the pool and on each client it connects, or a connection the server ends will end the process. See [passing a `pg.Pool`](/worlds/postgres#programmatic-configuration).
149
151
 
150
152
  ### `jobPrefix`
151
153
 
152
154
  - Environment variable: `WORKFLOW_POSTGRES_JOB_PREFIX`
153
155
  - Default: `workflow_`
154
156
  - Prefix for Graphile Worker job names.
157
+ - Use a distinct prefix for each application that shares a database. `start()` re-enqueues only the active runs created under this prefix, plus runs created by earlier versions, which have no prefix. See [`WORKFLOW_POSTGRES_JOB_PREFIX`](/worlds/postgres#workflow_postgres_job_prefix).
155
158
 
156
159
  ### `queueConcurrency`
157
160
 
@@ -174,6 +177,16 @@ The Postgres World is a self-hosted durable backend for long-running server proc
174
177
  - Set to `true` only when the application awaits `world.close()` before closing its workflow HTTP server and caller-owned pool.
175
178
  - Prevents Graphile Worker's default handler from terminating the process before the application's remaining cleanup finishes.
176
179
 
180
+ ### `jobLockStaleSeconds`
181
+
182
+ - Environment variable: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`
183
+ - Default: `0` (off)
184
+ - Seconds a running delivery's job lock may go unrenewed before another process releases the job for redelivery. When set, a running delivery renews its lock, so this bounds how long the job of a process that died stays locked.
185
+ - `30` is a good value when more than one process shares the database. Use the same value on every process, and keep it well above the longest a process can block its event loop.
186
+ - `0` leaves recovery to Graphile Worker's fixed 4 hour reset and to restarts.
187
+ - Off by default because of rolling upgrades. A process on an earlier version neither renews its locks nor fences its acknowledgement on the lock holder, so while it shares the database with a process that has this on, its deliveries that run longer than the window are redelivered, and finishing one can delete the redelivered job.
188
+ - To turn it on, set the same value on every process that shares the database once all of them run a version that includes this option. See [Postgres World: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](/worlds/postgres#workflow_postgres_job_lock_stale_seconds).
189
+
177
190
  ### `maxPoolSize`
178
191
 
179
192
  - Environment variable: `WORKFLOW_POSTGRES_MAX_POOL_SIZE`
@@ -205,6 +218,8 @@ The Vercel World is configured automatically inside Vercel deployments. The plat
205
218
 
206
219
  Most applications should not set `WORKFLOW_VERCEL_*` variables on Vercel. They configure tooling that talks to a Vercel Workflow project from outside a deployment, such as the Workflow CLI, the web user interface (UI), continuous integration (CI), or tests. The runtime warns if these variables are set in a deployed Vercel Function because they do not control runtime configuration there.
207
220
 
221
+ The entries below are the individual knobs. For a walkthrough of authenticating a local script or a CI job with a Vercel auth token — which variables are needed together, and how to pass them to the World factory — see [Connecting from outside a deployment](/worlds/vercel#connecting-from-outside-a-deployment).
222
+
208
223
  Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, and `VERCEL_DEPLOYMENT_KEY` are read by the runtime inside Vercel deployments. Do not set them yourself; keep [system environment variables](/worlds/vercel#system-environment-variables) enabled for the project so that Vercel provides them.
209
224
 
210
225
  ### `token`
@@ -213,13 +228,14 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
213
228
  - CLI flag: `--authToken`
214
229
  - Default: inferred when possible
215
230
  - Vercel API token for external tooling. Keep it secret.
231
+ - Only meaningful alongside `projectConfig.projectId` and `projectConfig.teamId` — set all three together. Supplying both IDs but no token throws rather than failing later with a `401`.
216
232
 
217
233
  ### `projectConfig.environment`
218
234
 
219
235
  - Environment variable: `WORKFLOW_VERCEL_ENV`
220
236
  - CLI flag: `--env` or `-e`
221
237
  - Default: `production`
222
- - Vercel environment targeted by tooling. Accepts `production` or `preview`.
238
+ - Vercel environment targeted by tooling. Accepts `production`, `preview`, or a custom environment's **slug** — configure the slug, not the environment's ID.
223
239
 
224
240
  ### `projectConfig.projectId`
225
241
 
@@ -248,6 +264,7 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
248
264
  - CLI flag: none
249
265
  - Default: `https://api.vercel.com/v1/workflow`
250
266
  - Workflow API proxy URL for external tooling.
267
+ - The Vercel World doesn't follow HTTP redirects, so the URL must answer directly. A `3xx` response fails the request.
251
268
 
252
269
  ### `WORKFLOW_SEQUENTIAL_REPLAYS`
253
270
 
@@ -21,7 +21,7 @@ Child workflows are the right choice when:
21
21
  - **You need isolated failure boundaries**: A failing child should not abort unrelated work. The parent decides how to handle failures.
22
22
  - **You want large fan-out**: Spawning 50 or 500 children is practical because each runs on its own infrastructure. The parent still pays for each spawn, so start them in chunks rather than all at once (see [Chunked spawning](#fan-out-pattern-chunked-spawning)).
23
23
  - **You need per-item observability**: Each child workflow has its own run ID, status, and event log for monitoring.
24
- - **One run would otherwise get too big**: A run's event log and step count are both capped, see [Vercel World limits](/worlds/vercel#per-run-limits). Replay reads the whole log, so split before the cap: a run headed for more than a few thousand events belongs in several runs.
24
+ - **You want to bound each run's event log**: Splitting work gives each child a separate event log. On the default runtime, a growing log can add replay overhead and reach the [per-run event limit](/worlds/vercel#per-run-limits). [QuickJS](/docs/configuration/runtime-tuning#workflow_vm) is an alternative for long single runs: it reduces replay overhead and exempts eligible runs from the default event cap. Choose child workflows when separate run histories or failure boundaries also help your application.
25
25
 
26
26
  For simpler cases where steps share a single event log, use [direct await composition](/cookbook/common-patterns/workflow-composition#direct-await-flattening) instead.
27
27
 
@@ -307,7 +307,7 @@ async function startAndWaitWithRetries(
307
307
  - **Export wrapped children at module scope**: The SDK registers `"use workflow"` functions statically, so a runtime higher-order function returned from `withChildCompletionHook()` cannot be passed to `start()`.
308
308
  - **Use stable hook keys**: Document IDs, job IDs, or indexes prevent token collisions between parallel children in one parent run.
309
309
  - **Use chunked spawning for large batches**: Starting 500 children at once can create a large burst of work. Break the work into chunks of 10–50.
310
- - **Watch the parent's log too**: Each child bounds its own log, but the parent records events for spawning and for collecting every child, so the parent's log grows with the number of children. Count those events per child against the parent's own [run limits](/worlds/vercel#per-run-limits); when the parent alone would exceed them, add a layer, so each parent spawns a modest number of intermediate runs that in turn spawn the leaves.
310
+ - **Watch the parent's log too**: The parent records events for spawning and collecting every child. On the default runtime, count those events against the parent's [event limit](/worlds/vercel#per-run-limits) and consider another layer of intermediate runs if needed. QuickJS with snapshotting reduces replay overhead and exempts eligible parent runs from the default event cap, but does not reduce their event count or remove payload and storage limits.
311
311
  - **Account for each child's retry semantics**: Steps inside child workflows retry independently. The parent sees the final `{ status, value | error }` payload from the hook.
312
312
  - **Use `deploymentId: "latest"` when children should run on the most recent deployment**: See [Versioning](/docs/foundations/versioning) for the full model and the [`start()` API reference](/docs/api-reference/workflow-api/start#using-deploymentid-latest) for compatibility considerations.
313
313
 
@@ -99,7 +99,9 @@ async function processRecord(record: Record): Promise<string> {
99
99
 
100
100
  - **Use `Promise.allSettled` instead of `Promise.all`**: Use this pattern when you want to continue even if some items fail. `Promise.all` rejects on the first failure, while `allSettled` waits for everything and identifies failures.
101
101
  - **Tune batch size to your downstream API limits**: If the API allows 10 concurrent requests, use `batchSize: 10`.
102
- - **Batching bounds concurrency, not the run's total size**: Every batch still appends to the same [event log](/docs/how-it-works/event-sourcing#how-fast-a-log-grows), so a long enough list walks one run toward its [run limits](/worlds/vercel#per-run-limits) no matter how small the batches are. To shrink the run itself, bundle more items per step so one step covers many items, or spawn a [child workflow](/cookbook/advanced/child-workflows) per batch. Reach for one of those once a single run would grow past a few thousand events.
102
+ - **Batching bounds concurrency, not total event count**: Every record processed in its own step adds events to the same [event log](/docs/how-it-works/event-sourcing#how-fast-a-log-grows), regardless of batch size.
103
+ - **Consider using the QuickJS engine for long-running batches**: [Set `WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to use the experimental QuickJS runtime, which compresses and snapshots the event log and only loads events since the last snapshot on resume. This reduces replay overhead as the log grows and exempts eligible runs from the default [per-run event limit](/worlds/vercel#per-run-limits) ([`MAX_EVENTS_EXCEEDED`](/docs/errors/max-events-exceeded)). It does not reduce event count or speed up the work inside each step.
104
+ - **Choose the retry and run boundaries you need**: Keep one step per record when independent retries and visibility matter. To write fewer events, process multiple records within each step and make the grouped work idempotent, since a retry can repeat the whole group. Use a [child workflow](/cookbook/advanced/child-workflows) per batch when you need separate run histories and failure boundaries.
103
105
  - **Add pacing with `sleep()`**: Add a delay between batches to respect rate limits. The sleep is durable and survives cold starts.
104
106
  - **Treat each `processRecord` call as an independent step**: If one call fails, it retries up to three times without affecting other items in the batch.
105
107
 
@@ -59,30 +59,29 @@ See [Step Idempotency](/docs/foundations/idempotency#step-idempotency) for why `
59
59
 
60
60
  ## Run idempotency
61
61
 
62
- For duplicate workflow-start requests, derive a hook token from your domain key. You can avoid obvious duplicate starts by checking whether an active hook already owns that token before calling `start()`:
62
+ For duplicate workflow-start requests, derive a hook token from your domain key and pass it to `start()`. Exactly one run owns the token, and a duplicate start throws `HookConflictError` naming the owner instead of creating a run:
63
63
 
64
64
  ```typescript
65
- import { getHookByToken, start } from "workflow/api";
66
- import { HookNotFoundError } from "workflow/errors";
65
+ import { start } from "workflow/api";
66
+ import { HookConflictError } from "workflow/errors";
67
67
  import { processOrder } from "./workflows/process-order";
68
68
 
69
69
  export async function POST(request: Request) {
70
70
  const { orderId } = await request.json();
71
- const token = `order:${orderId}`;
72
71
 
73
72
  try {
74
- const hook = await getHookByToken(token); // [!code highlight]
75
- return Response.json({ runId: hook.runId, reused: true });
73
+ const run = await start(processOrder, [orderId], {
74
+ hook: { token: `order:${orderId}` }, // [!code highlight]
75
+ });
76
+ return Response.json({ runId: run.runId, reused: false });
76
77
  } catch (error) {
77
- if (!HookNotFoundError.is(error)) throw error;
78
+ if (!HookConflictError.is(error)) throw error;
79
+ return Response.json({ runId: error.conflictingRunId, reused: true }); // [!code highlight]
78
80
  }
79
-
80
- const run = await start(processOrder, [orderId]); // [!code highlight]
81
- return Response.json({ runId: run.runId, reused: false });
82
81
  }
83
82
  ```
84
83
 
85
- The workflow should create the deterministic hook and check `await hook.getConflict()` before duplicate-sensitive work: awaiting `getConflict()` suspends the workflow to commit the hook registration and resolves with the conflicting run when another active run already owns the token (or `null` once the hook is registered). See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for the full pattern, including how to steer an active run with `resumeHook()` and how to handle the current race between `start()` and hook registration.
84
+ The run's start Hook can be resumed as soon as `start()` returns, so a duplicate request that carries data can `resumeHook()` the owner on a conflict, and the workflow reads it with `createHook({ token })`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for the full pattern, retention, and World support, and for coordinating inside the workflow with `hook.getConflict()` on Worlds without atomic start Hooks.
86
85
 
87
86
  ## Key APIs
88
87
 
@@ -92,4 +91,4 @@ The workflow should create the deterministic hook and check `await hook.getConfl
92
91
  - [`createHook()`](/docs/api-reference/workflow/create-hook): Creates a hook with an optional deterministic token.
93
92
  - [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token): Finds the hook that owns a token.
94
93
  - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes the active hook when the duplicate request carries data.
95
- - [`start()`](/docs/api-reference/workflow-api/start): Starts a new workflow run.
94
+ - [`start()`](/docs/api-reference/workflow-api/start): Starts a new workflow run, at most once per `hook.token`.
@@ -77,7 +77,7 @@ export async function chatWorkflow(prompt: string) {
77
77
  This is the most common scenario - using AI SDK functions that make HTTP requests:
78
78
 
79
79
  ```typescript lineNumbers
80
- import { generateText, streamText } from "ai";
80
+ import { generateText } from "ai";
81
81
  import { fetch } from "workflow"; // [!code highlight]
82
82
 
83
83
  export async function aiWorkflow(userMessage: string) {
@@ -89,12 +89,18 @@ export async function aiWorkflow(userMessage: string) {
89
89
  const response = await generateText({
90
90
  model: "spacexai/grok-4.6",
91
91
  prompt: userMessage,
92
+ maxRetries: 0, // [!code highlight]
92
93
  });
93
94
 
94
95
  return response.text;
95
96
  }
96
97
  ```
97
98
 
99
+ #### AI SDK limitations in workflow functions
100
+
101
+ - **Set `maxRetries: 0`.** When a provider returns a retryable status such as 429 or 5xx, the AI SDK waits with `setTimeout` before it retries, and [timers are not available in workflow functions](/docs/errors/timeout-in-workflow). With the default `maxRetries`, the run fails with a timer error instead of the provider's error. To retry these calls, put the `generateText()` call inside a step function, which the workflow retries on failure.
102
+ - **Streaming is not supported.** `streamText()` and other streaming calls pipe the response through web streams, which are not available in workflow functions. Use [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent), or call `streamText()` inside a step function.
103
+
98
104
  ### Direct API calls
99
105
 
100
106
  You can also use the fetch step function directly for your own HTTP requests:
@@ -20,8 +20,8 @@ When a workflow run fails, its `errorCode` identifies the failure category. You
20
20
  | [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) | The run's event log cannot be replayed because it contains orphaned or mismatched events, a gap, or an unreadable stored payload. |
21
21
  | [`REPLAY_DIVERGENCE`](/docs/errors/replay-divergence) | One replay could not consume the event log deterministically. The runtime automatically retries before treating repeated divergence as a corrupted event log. |
22
22
  | `MAX_DELIVERIES_EXCEEDED` | The run exceeded the maximum number of queue deliveries, usually because a persistent failure kept causing redelivery. |
23
- | `MAX_EVENTS_EXCEEDED` | The run reached the World's per-run event limit. Split unbounded work into child workflows before reaching the limit. |
24
- | `REPLAY_TIMEOUT` | Workflow replay exceeded the configured duration limit. This measures workflow execution and event-log replay between step boundaries, not time spent inside step functions. |
23
+ | [`MAX_EVENTS_EXCEEDED`](/docs/errors/max-events-exceeded) | The run reached the World's per-run event limit. Run long-running workflows on the QuickJS VM with snapshotting, which is exempt from the default limit, or split unbounded work into child workflows. |
24
+ | [`REPLAY_TIMEOUT`](/docs/errors/replay-timeout) | Workflow replay exceeded the configured duration limit. This measures workflow execution and event-log replay between step boundaries, not time spent inside step functions. |
25
25
  | `STREAM_ERROR` | Workflow stream infrastructure failed while reading or writing data. This is an SDK or backend failure rather than an error in workflow code. |
26
26
  | `WORLD_CONTRACT_ERROR` | A World returned data that violated the SDK contract and could not be retried safely. This usually indicates a World implementation bug. |
27
27
  | [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) | A run was delivered to a deployment other than the one it is pinned to, and automatic re-routing did not recover it. |
@@ -0,0 +1,80 @@
1
+ ---
2
+ title: max-events-exceeded
3
+ description: A workflow run reached the World's per-run event limit and was failed.
4
+ type: troubleshooting
5
+ summary: Run long-running workflows on the QuickJS VM with snapshotting, which is exempt from the default event limit, or split the work into child workflows.
6
+ prerequisites:
7
+ - /docs/how-it-works/event-sourcing
8
+ related:
9
+ - /docs/configuration/runtime-tuning#workflow_vm
10
+ - /docs/errors/replay-timeout
11
+ - /cookbook/advanced/child-workflows
12
+ ---
13
+
14
+ Every step, hook, sleep, and lifecycle transition adds events to a run's [event log](/docs/how-it-works/event-sourcing). The World supplies a per-run ceiling on that log, and the runtime fails a run whose log reaches it with the `MAX_EVENTS_EXCEEDED` error code. The ceiling is a backstop against runaway loops that would otherwise grow a log without bound.
15
+
16
+ For the Vercel World's ceiling, see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits). The Local World's ceiling is set by [`WORKFLOW_MAX_EVENTS`](/docs/configuration/runtime-tuning#workflow_max_events).
17
+
18
+ ## Error message
19
+
20
+ ```text
21
+ Workflow exceeded the maximum of <limit> events per run
22
+ ├▶ hint: Run long-running workflows on the QuickJS VM with snapshotting by setting WORKFLOW_VM=quickjs ...
23
+ ╰▶ docs: https://workflow-sdk.dev/err/max-events-exceeded
24
+ ```
25
+
26
+ Before a run reaches the limit, the runtime logs a warning in your function logs at 50%, 80%, and 95% of the ceiling:
27
+
28
+ ```text
29
+ Workflow run is approaching the per-run event limit (<count> of <limit> events, 50%). ...
30
+ ```
31
+
32
+ ## Why it happens
33
+
34
+ - **The workflow is long-running by design.** Agents, chat sessions, and loops that wait on hooks or sleeps for days accumulate events with every iteration.
35
+ - **The workflow has unbounded work.** For example, a loop that keeps creating steps without a termination condition.
36
+
37
+ ## How to fix it
38
+
39
+ ### Run on the QuickJS VM with snapshotting
40
+
41
+ <Callout type="warn">
42
+ The QuickJS engine is experimental, and its global surface differs from the default engine. Review the [differences](/docs/configuration/runtime-tuning#workflow_vm) before switching an existing deployment.
43
+ </Callout>
44
+
45
+ Runs that execute on the QuickJS VM with snapshotting enabled are exempt from the default per-run event limit. A snapshotted run restores its VM memory and replays only the events recorded since the last snapshot, so its resume cost doesn't grow with the length of the log.
46
+
47
+ Set `WORKFLOW_VM=quickjs` in the environment that starts runs (the process that calls [`start()`](/docs/api-reference/workflow-api/start)). On Vercel that's your project's environment variables:
48
+
49
+ ```bash
50
+ WORKFLOW_VM=quickjs
51
+ ```
52
+
53
+ Snapshotting is on by default under QuickJS. Leave [`WORKFLOW_SNAPSHOT_THRESHOLD`](/docs/configuration/runtime-tuning#workflow_snapshot_threshold) unset, or set it to a positive integer. `WORKFLOW_SNAPSHOT_THRESHOLD=0` disables snapshotting, and those runs keep the limit.
54
+
55
+ A run qualifies when its `executionContext` records `workflowVm: "quickjs"` and a positive `snapshotThreshold`. `start()` records both when the run is created, so:
56
+
57
+ - Only runs started after the change are exempt. Runs keep the VM and snapshot policy they started with.
58
+ - Runs that have already failed with `MAX_EVENTS_EXCEEDED` are not revived. Start them again.
59
+ - On the Local World and Postgres World, snapshots are only stored when [`WORKFLOW_SNAPSHOT_ALLOW_UNENCRYPTED=1`](/docs/configuration/runtime-tuning#workflow_snapshot_allow_unencrypted) is set. Without it, exempt runs still replay the full log on every invocation.
60
+
61
+ ### Split the work into child workflows
62
+
63
+ If a run doesn't need to be a single long-lived run, start [child workflows](/cookbook/advanced/child-workflows) for each batch or session and keep the parent's log small. This also works on the default engine.
64
+
65
+ ### Fix unbounded loops
66
+
67
+ If the run wasn't expected to grow this large, check the workflow function for loops that create steps, hooks, or sleeps without terminating.
68
+
69
+ ## This error cannot be caught
70
+
71
+ `MAX_EVENTS_EXCEEDED` is recorded by the runtime, not thrown into your workflow function. Check the run status from outside instead:
72
+
73
+ ```typescript lineNumbers
74
+ import { getRun } from "workflow/api";
75
+
76
+ const run = getRun("wrun_abc123");
77
+ if ((await run.status) === "failed") {
78
+ console.error("Run failed");
79
+ }
80
+ ```
@@ -0,0 +1,48 @@
1
+ ---
2
+ title: replay-timeout
3
+ description: Workflow replay exceeded its time budget on repeated deliveries and the run was failed.
4
+ type: troubleshooting
5
+ summary: Reduce replay cost by running on the QuickJS VM with snapshotting, or by moving heavy synchronous work out of the workflow function.
6
+ prerequisites:
7
+ - /docs/how-it-works/event-sourcing
8
+ related:
9
+ - /docs/configuration/runtime-tuning#workflow_replay_timeout_ms
10
+ - /docs/errors/max-events-exceeded
11
+ ---
12
+
13
+ Each time a run resumes, the runtime re-runs the workflow function against the recorded [event log](/docs/how-it-works/event-sourcing) to rebuild its state. That replay has a time budget per handler invocation ([`WORKFLOW_REPLAY_TIMEOUT_MS`](/docs/configuration/runtime-tuning#workflow_replay_timeout_ms)). Time spent inside `"use step"` bodies doesn't count against it.
14
+
15
+ When replay exceeds the budget, the delivery is retried. After [`WORKFLOW_REPLAY_TIMEOUT_MAX_RETRIES`](/docs/configuration/runtime-tuning#workflow_replay_timeout_max_retries) attempts, the run is failed with the `REPLAY_TIMEOUT` error code.
16
+
17
+ ## Error message
18
+
19
+ ```text
20
+ Workflow replay exceeded maximum duration (240s) after 4 attempts
21
+ ├▶ hint: Replay time grows with the size of the event log. Run long-running workflows on the QuickJS VM with snapshotting ...
22
+ ╰▶ docs: https://workflow-sdk.dev/err/replay-timeout
23
+ ```
24
+
25
+ ## Why it happens
26
+
27
+ - **The event log is very large.** On the default engine, replay time grows with the number of events in the run.
28
+ - **The workflow function does heavy synchronous work** outside of steps, such as parsing large payloads or tight loops.
29
+
30
+ ## How to fix it
31
+
32
+ ### Run on the QuickJS VM with snapshotting
33
+
34
+ <Callout type="warn">
35
+ The QuickJS engine is experimental, and its global surface differs from the default engine. Review the [differences](/docs/configuration/runtime-tuning#workflow_vm) before switching an existing deployment.
36
+ </Callout>
37
+
38
+ Under QuickJS with snapshotting, a run restores its VM memory from a snapshot and replays only the events recorded since, so replay time stays roughly constant as the log grows. These runs are also exempt from the default [per-run event limit](/docs/errors/max-events-exceeded).
39
+
40
+ Set `WORKFLOW_VM=quickjs` in the environment that starts runs. Snapshotting is on by default under QuickJS. Only runs started after the change use the new engine. See [max-events-exceeded](/docs/errors/max-events-exceeded#run-on-the-quickjs-vm-with-snapshotting) for the full eligibility rules.
41
+
42
+ ### Move heavy work into steps
43
+
44
+ Steps run with full Node.js access, their results are recorded once, and replay reuses those results without re-running the body. Move expensive parsing, transformation, and computation out of the workflow function into steps.
45
+
46
+ ### Raise the budget
47
+
48
+ As a short-term mitigation, raise [`WORKFLOW_REPLAY_TIMEOUT_MS`](/docs/configuration/runtime-tuning#workflow_replay_timeout_ms). This doesn't reduce replay cost, which keeps growing with the log on the default engine.
@@ -38,7 +38,9 @@ Two ways to reach it:
38
38
  error rather than treating it as an edge case. See
39
39
  [Data retention](/docs/observability/retention).
40
40
  - **The run simply aged out.** It finished long enough ago that the World's
41
- default retention window has passed.
41
+ default retention window has passed. For the Vercel World's retention
42
+ rules, see the
43
+ [Vercel Workflows docs](https://vercel.com/docs/workflows/retention).
42
44
 
43
45
  ## How to respond
44
46
 
@@ -170,6 +170,8 @@ On Vercel, backend connection failures and interrupted event streams use the exi
170
170
 
171
171
  The SDK also replaces its shared events connection pool after repeated HTTP/2 session failures, and retries event-log reads whose HTTP/2 stream the backend resets. An events request that receives no response data for 60 seconds fails and is retried instead of stalling the invocation. Invalid backend URLs, including unsupported protocols and embedded credentials, fail immediately. Fetch requests to blocked ports or with unsupported headers (such as `Expect`) also fail without retrying. Interrupted event writes retain their existing retries; caller cancellations do not trigger another write.
172
172
 
173
+ Writing to a stream forwarded from another run looks up that run's encryption key first. A transient lookup failure (a connection error, a timeout, an HTTP `429`, or a `5xx`) uses the step's retry policy. Any other lookup failure, such as an HTTP `404` when the owner run no longer exists, fails the step without retrying, with a `EncryptionKeyLookupError` whose `cause` is the original failure.
174
+
173
175
  A connection failure does not prove that the backend rejected a write: it may have accepted it before the response was lost. Continue to make step side effects [idempotent](/docs/foundations/idempotency).
174
176
 
175
177
  Failed-run logs include the underlying error causes and their codes, exposing socket, DNS, or TLS errors behind messages such as `TypeError: fetch failed`. If a cause cannot be read, the log includes `[unavailable cause]` and the run can still be recorded as failed.
@@ -201,9 +203,9 @@ try {
201
203
  | Code | Meaning |
202
204
  | --- | --- |
203
205
  | `USER_ERROR` | An error thrown in your workflow or step code (including propagated step failures like `FatalError`) |
204
- | `MAX_EVENTS_EXCEEDED` | The run reached the World's per-run event ceiling (for the Vercel World, see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits)). Split unbounded loops into [child workflows](/cookbook/advanced/child-workflows) well before the ceiling; see [Vercel World limits](/worlds/vercel#per-run-limits) and [Limits](/docs/configuration/runtime-tuning#limits) |
206
+ | `MAX_EVENTS_EXCEEDED` | The run reached the World's per-run event ceiling (for the Vercel World, see [Workflow run limits](https://vercel.com/docs/workflows/pricing#workflow-run-limits)). Run long-running workflows on the QuickJS VM with snapshotting, which is exempt from the default ceiling, or split unbounded loops into [child workflows](/cookbook/advanced/child-workflows) well before the ceiling. See [max-events-exceeded](/docs/errors/max-events-exceeded) |
205
207
  | `MAX_DELIVERIES_EXCEEDED` | The run exceeded the maximum number of queue deliveries |
206
- | `REPLAY_TIMEOUT` | A workflow replay exceeded the maximum allowed duration |
208
+ | `REPLAY_TIMEOUT` | A workflow replay exceeded the maximum allowed duration. See [replay-timeout](/docs/errors/replay-timeout) |
207
209
  | `REPLAY_DIVERGENCE` | A replay could not consume the event log deterministically, usually because of non-deterministic workflow code. |
208
210
  | `CORRUPTED_EVENT_LOG` | The event log cannot be replayed: it contains orphaned or mismatched events, or one of its stored payloads is no longer readable from the World's storage. If you see this, please [file an issue](https://github.com/vercel/workflow/issues) |
209
211
  | `STREAM_ERROR` | Workflow stream infrastructure failed while reading or writing data. This is an SDK or backend failure rather than an error in workflow code; retry the run and report persistent failures with the `runId` |
@@ -272,3 +274,7 @@ export async function placeOrderSaga(orderId: string) {
272
274
  }
273
275
  }
274
276
  ```
277
+
278
+ ## Spec 9 (experimental)
279
+
280
+ The experimental spec 9 runtime retries steps differently: a failed step is retried after about a second by default on its one queue message, and a `maxRetries = 0` step whose invocation dies after it started fails instead of running again. See [Retries on spec 9 runs](/docs/changelog/spec-9#retries).
@@ -112,7 +112,9 @@ export async function orderWorkflow(orderId: string) {
112
112
  }
113
113
  ```
114
114
 
115
- Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies.
115
+ Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies. A run started with [`start({ hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token: `createHook({ token })` with that token binds to the run's start Hook, and `getConflict()` resolves `null` without suspending.
116
+
117
+ Awaiting the registration costs one write, not a round trip through the queue: the invocation that commits the registration is the one that carries on past the awaiter, and it runs the steps the workflow started beside the awaiter — as in `await Promise.all([hook.getConflict(), prepare()])` — in that same invocation, once the registration is recorded. That covers the steps the invocation runs inline; a fan-out wider than the free inline slots ([`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps), less any inline steps the invocation is still running) queues the rest alongside the hook, so await `hook.getConflict()` before the step when the ordering itself matters. See [`createHook()`](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
116
118
 
117
119
  ### Custom tokens for deterministic hooks
118
120