workflow 5.2.3 → 5.4.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 (48) 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/create-webhook.mdx +1 -1
  9. package/docs/api-reference/workflow/fetch.mdx +2 -0
  10. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +5 -1
  11. package/docs/api-reference/workflow-api/get-run.mdx +4 -0
  12. package/docs/api-reference/workflow-api/resume-hook.mdx +58 -2
  13. package/docs/api-reference/workflow-api/start.mdx +70 -3
  14. package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +6 -3
  15. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +68 -0
  16. package/docs/api-reference/workflow-errors/index.mdx +6 -0
  17. package/docs/api-reference/workflow-errors/meta.json +2 -0
  18. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +2 -0
  19. package/docs/api-reference/workflow-errors/workflow-start-error.mdx +58 -0
  20. package/docs/api-reference/workflow-errors/workflow-world-error.mdx +12 -1
  21. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -1
  22. package/docs/changelog/eager-processing.mdx +4 -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/spec-9.mdx +4019 -0
  27. package/docs/changelog/turbo-mode.md +4 -0
  28. package/docs/configuration/cli-and-web-ui.mdx +4 -2
  29. package/docs/configuration/runtime-tuning.mdx +68 -2
  30. package/docs/configuration/worlds.mdx +13 -1
  31. package/docs/cookbook/advanced/child-workflows.mdx +127 -187
  32. package/docs/cookbook/common-patterns/batching.mdx +3 -1
  33. package/docs/cookbook/common-patterns/idempotency.mdx +11 -12
  34. package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +1 -1
  35. package/docs/cookbook/common-patterns/workflow-composition.mdx +5 -5
  36. package/docs/errors/fetch-in-workflow.mdx +15 -29
  37. package/docs/foundations/errors-and-retries.mdx +6 -0
  38. package/docs/foundations/hooks.mdx +3 -1
  39. package/docs/foundations/idempotency.mdx +190 -60
  40. package/docs/foundations/starting-workflows.mdx +3 -7
  41. package/docs/how-it-works/event-sourcing.mdx +6 -0
  42. package/docs/whats-new.mdx +3 -1
  43. package/docs/worlds/building-a-world.mdx +28 -3
  44. package/docs/worlds/local.mdx +6 -0
  45. package/docs/worlds/postgres.mdx +208 -146
  46. package/docs/worlds/upgrading-to-v5.mdx +7 -1
  47. package/docs/worlds/vercel.mdx +9 -7
  48. 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.
@@ -10,7 +10,7 @@ related:
10
10
 
11
11
  The Workflow CLI uses flags first, then environment variables, then defaults or local inference.
12
12
 
13
- Vercel project and auth settings can often be inferred from `.vercel/project.json` and your Vercel CLI login.
13
+ Vercel project and auth settings can often be inferred from `.vercel/project.json` and your Vercel CLI login. In a monorepo, the CLI uses the nearest `.vercel/project.json` before the repository's `.vercel/repo.json`.
14
14
 
15
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
16
 
@@ -32,13 +32,15 @@ Whichever way they are resolved, the CLI ends up building a Vercel World from an
32
32
 
33
33
  - Environment variable: `WORKFLOW_VERCEL_PROJECT`
34
34
  - Default: inferred when possible
35
- - Vercel project ID for `--backend vercel`.
35
+ - Vercel project ID or slug for `--backend vercel`.
36
+ - Takes precedence over the project in the `.vercel` link. When `--project` names a different project, pass `--team` too, or the CLI uses the linked team and logs a warning.
36
37
 
37
38
  ### `--team`
38
39
 
39
40
  - Environment variable: `WORKFLOW_VERCEL_TEAM`
40
41
  - Default: inferred when possible
41
42
  - Vercel team ID for `--backend vercel`.
43
+ - Takes precedence over the team in the `.vercel` link.
42
44
 
43
45
  ### `WORKFLOW_VERCEL_PROJECT_NAME`
44
46
 
@@ -45,6 +45,13 @@ The runtime reads these variables where workflows execute. Set them on the deplo
45
45
  - The kill switch for the wait. Worlds that do not implement waiting are already on the interval path, so this changes nothing for them.
46
46
  - Read by the process awaiting `Run.returnValue`, like the interval above.
47
47
 
48
+ ### `WORKFLOW_CHILD_RUN_COMPLETION_HOOK`
49
+
50
+ - Default: enabled
51
+ - Inside a workflow, awaiting `returnValue` of a run that workflow started suspends the parent on a system hook the child resumes when it finishes, instead of polling. See [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits).
52
+ - Set to `0` or `false` to stop `start()` from marking new child runs for the hook, so their parents poll `returnValue` inside a step on the variables above.
53
+ - Read by the deployment calling `start()` from a workflow. A child already marked keeps resuming its parent, so a parent waiting on it is never stranded.
54
+
48
55
  ## Replay and queue delivery
49
56
 
50
57
  ### `WORKFLOW_REPLAY_TIMEOUT_MS`
@@ -168,6 +175,19 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
168
175
  - Default: `3`
169
176
  - Clamp: `1` to `16`
170
177
  - Number of newly-created steps one invocation runs inline in parallel before queueing the rest.
178
+ - 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.
179
+
180
+ ### `WORKFLOW_INLINE_EARLY_ADVANCE`
181
+
182
+ - Default: enabled
183
+ - 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.
184
+ - 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.
185
+ - 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.
186
+ - A step that retries, is throttled, or leaves stream writes unflushed waits for its whole batch, as with this setting off.
187
+ - 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.
188
+ - 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.
189
+ - `workflow.inline.early_advances` counts early replays and `workflow.inline.slots_held_back` counts steps queued because running steps held the inline slots.
190
+ - Set `0` or `false` to wait for every inline step of a batch before replaying.
171
191
 
172
192
  ### `WORKFLOW_TURBO`
173
193
 
@@ -187,7 +207,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
187
207
 
188
208
  - Default: enabled
189
209
  - 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.
190
- - 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.
210
+ - 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.
191
211
  - 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.
192
212
  - Set `0` or `false` to replay the Node.js workflow from scratch in a fresh VM on every iteration.
193
213
 
@@ -241,7 +261,7 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
241
261
  - Set `0` to opt out and always replay the full event log.
242
262
  - 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.
243
263
  - 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.
244
- - 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.
264
+ - 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.
245
265
 
246
266
  What a snapshot contains, and how it is protected:
247
267
 
@@ -419,3 +439,49 @@ These variables are primarily for tests, debugging, or unusual deployments.
419
439
  - 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.
420
440
  - 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).
421
441
  - QuickJS runs with snapshotting are exempt from the World's default limit, but this override still applies to them.
442
+
443
+ ## Spec 9 (experimental)
444
+
445
+ 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.
446
+
447
+ ### `WORKFLOW_SPEC_VERSION`
448
+
449
+ - Default: unset. New runs use spec version 8, or 6 with [`WORKFLOW_SEALED_LOG=0`](#workflow_sealed_log), which this setting takes precedence over.
450
+ - `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.
451
+ - 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).
452
+
453
+ ### `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS`
454
+
455
+ - Default: `2000`
456
+ - Log-tail poll interval of a busy orchestrator while no live event feed covers the run. `0` turns polling off.
457
+
458
+ ### `WORKFLOW_ORCHESTRATOR_FEED_POLL_INTERVAL_MS`
459
+
460
+ - Default: `10000`
461
+ - Log-tail poll interval while the World's live event feed is up.
462
+
463
+ ### `WORKFLOW_ORCHESTRATOR_LINGER_MS`
464
+
465
+ - Default: `30000`
466
+ - 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.
467
+
468
+ ### `WORKFLOW_ORCHESTRATOR_READ_TIMEOUT_MS`
469
+
470
+ - Default: `5000`
471
+ - Deadline for one incremental read of the event log before the orchestrator sends it again. `0` turns the deadline off.
472
+
473
+ ### `WORKFLOW_INLINE_STEP_DEADLINE_MARGIN_MS`
474
+
475
+ - Default: `60000`
476
+ - How long before the inline window ends the orchestrator stops starting inline steps.
477
+
478
+ ### `WORKFLOW_OPTIMISTIC_BACKGROUND_START`
479
+
480
+ - Default: unset
481
+ - `1` or `true` starts a background step's body before its `step_started` commits. Use only when background step bodies are idempotent.
482
+
483
+ ### `WORKFLOW_RUN_AHEAD_DEPTH`
484
+
485
+ - Default: `10`
486
+ - Clamp: `0` to `16`
487
+ - How many inline step outcomes may be unconfirmed at once while the orchestrator runs ahead of its writes. `0` disables run-ahead.
@@ -154,13 +154,14 @@ The Postgres World is a self-hosted durable backend for long-running server proc
154
154
  - Environment variable: `WORKFLOW_POSTGRES_JOB_PREFIX`
155
155
  - Default: `workflow_`
156
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).
157
158
 
158
159
  ### `queueConcurrency`
159
160
 
160
161
  - Environment variable: `WORKFLOW_POSTGRES_WORKER_CONCURRENCY`
161
162
  - Default: `50`
162
163
  - Number of concurrent workers polling for jobs.
163
- - Also bounds concurrent parent-to-child workflow return-value polls.
164
+ - Also bounds concurrent `returnValue` polls that run inside steps. A parent workflow awaiting a child it started suspends on a system hook instead and holds no worker (see [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits)).
164
165
 
165
166
  ### `pollInterval`
166
167
 
@@ -176,6 +177,16 @@ The Postgres World is a self-hosted durable backend for long-running server proc
176
177
  - Set to `true` only when the application awaits `world.close()` before closing its workflow HTTP server and caller-owned pool.
177
178
  - Prevents Graphile Worker's default handler from terminating the process before the application's remaining cleanup finishes.
178
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
+
179
190
  ### `maxPoolSize`
180
191
 
181
192
  - Environment variable: `WORKFLOW_POSTGRES_MAX_POOL_SIZE`
@@ -253,6 +264,7 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
253
264
  - CLI flag: none
254
265
  - Default: `https://api.vercel.com/v1/workflow`
255
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.
256
268
 
257
269
  ### `WORKFLOW_SEQUENTIAL_REPLAYS`
258
270
 
@@ -1,14 +1,14 @@
1
1
  ---
2
2
  title: Child Workflows
3
- description: Spawn child workflows from a parent and wait for completion via hook resume.
3
+ description: Spawn child workflows from a parent and wait for them without polling.
4
4
  type: guide
5
- summary: Orchestrate independent child workflows from a parent using start(), defineHook(), and startAndWait(). The child resumes the parent's hook when done instead of polling getRun().status.
5
+ summary: Orchestrate independent child workflows from a parent with start() and await run.returnValue. The parent suspends on a system hook the child resumes when it finishes, so waiting costs no compute and never polls.
6
6
  related:
7
7
  - /docs/api-reference/workflow-api/start
8
8
  ---
9
9
 
10
10
  <CopyPrompt
11
- text="Refactor this workflow to use child workflows. Keep the parent as an exported `&quot;use workflow&quot;` function. Move independent units of durable work into separate exported child workflow functions. From the parent, call `start(childWorkflow, [args])` from `workflow/api` or the documented `startAndWait`/hook pattern where completion must resume the parent. Pass only serializable state to children. For fan-out, start children in parallel with `Promise.all` or bounded batches, collect run IDs, handle partial failures with `Promise.allSettled`, and use `getRun(runId)` when status, cancellation, streams, or return values are needed. Verify child start, completion, failure, and parent resume behavior."
11
+ text="Refactor this workflow to use child workflows. Keep the parent as an exported `&quot;use workflow&quot;` function. Move independent units of durable work into separate exported child workflow functions. From the parent, call `start(childWorkflow, [args])` from `workflow/api` and `await run.returnValue` where the parent needs the child's result: the parent suspends on a system hook the child resumes when it finishes, so no polling or hand-written completion hook is needed. Pass only serializable state to children. For fan-out, start children in parallel with `Promise.all` or bounded batches, handle partial failures with `Promise.allSettled`, and catch `WorkflowRunFailedError` / `WorkflowRunCancelledError` for failed or canceled children. Verify child start, completion, failure, and parent resume behavior."
12
12
  />
13
13
 
14
14
  Use child workflows when a single workflow needs to orchestrate many independent units of work. Each child runs as its own workflow with a separate event log, retry boundary, and failure scope. If one child fails, it doesn't take down the parent or siblings.
@@ -21,73 +21,21 @@ 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
 
28
- ## Basic pattern: spawn and wait via hook
28
+ ## Waiting for a child
29
29
 
30
- The recommended pattern has four parts:
31
-
32
- 1. A **completion hook** the parent creates and awaits, with zero compute while waiting
33
- 2. A **wrapped child export** that runs the real child in try/catch/finally and resumes the parent's hook from a step in `finally`
34
- 3. A **`start()` call** that spawns the wrapped child with the hook token (directly from the workflow in v5)
35
- 4. A **`startAndWait()` helper** that ties the hook, spawn, and typed result together
30
+ Start the child with [`start()`](/docs/api-reference/workflow-api/start) and await its `returnValue`:
36
31
 
37
32
  ```typescript
38
- import { defineHook, getWorkflowMetadata } from "workflow";
39
33
  import { start } from "workflow/api";
40
- import { z } from "zod";
41
34
 
42
35
  declare function fetchDocument(documentId: string): Promise<string>; // @setup
43
36
  declare function analyzeContent(content: string): Promise<string>; // @setup
44
37
  declare function generateSummary(analysis: string): Promise<string>; // @setup
45
38
 
46
- const childCompletionHook = defineHook({
47
- schema: z.discriminatedUnion("status", [
48
- z.object({ status: z.literal("completed"), value: z.unknown() }),
49
- z.object({ status: z.literal("failed"), error: z.string() }),
50
- ]),
51
- });
52
-
53
- function completionToken(parentRunId: string, key: string) {
54
- return `child-completion:${parentRunId}:${key}`;
55
- }
56
-
57
- async function resumeParentCompletion(
58
- token: string,
59
- result:
60
- | { status: "completed"; value: unknown }
61
- | { status: "failed"; error: string }
62
- ) {
63
- "use step";
64
- await childCompletionHook.resume(token, result);
65
- }
66
-
67
- async function withChildCompletionHook<TResult>(
68
- runChild: () => Promise<TResult>,
69
- completionTokenArg: string
70
- ) {
71
- let result:
72
- | { status: "completed"; value: TResult }
73
- | { status: "failed"; error: string }
74
- | undefined;
75
-
76
- try {
77
- const value = await runChild();
78
- result = { status: "completed", value };
79
- } catch (error) {
80
- result = {
81
- status: "failed",
82
- error: error instanceof Error ? error.message : String(error),
83
- };
84
- } finally {
85
- if (result) {
86
- await resumeParentCompletion(completionTokenArg, result);
87
- }
88
- }
89
- }
90
-
91
39
  // Child workflow -- processes a single document
92
40
  export async function processDocument(documentId: string) {
93
41
  "use workflow";
@@ -99,77 +47,86 @@ export async function processDocument(documentId: string) {
99
47
  return { documentId, summary };
100
48
  }
101
49
 
102
- // Spawnable wrapper -- explicit export so `start()` can register it
103
- export async function processDocumentWithCompletion(
104
- documentId: string,
105
- completionTokenArg: string
106
- ) {
50
+ // Parent workflow -- orchestrates document processing
51
+ export async function processDocumentBatch(documentIds: string[]) {
107
52
  "use workflow";
108
53
 
109
- await withChildCompletionHook(
110
- () => processDocument(documentId),
111
- completionTokenArg
54
+ const runs = await Promise.all(
55
+ documentIds.map((documentId) => start(processDocument, [documentId])) // [!code highlight]
112
56
  );
57
+ const results = await Promise.all(runs.map((run) => run.returnValue)); // [!code highlight]
58
+
59
+ return { processed: results.length, results };
113
60
  }
61
+ ```
114
62
 
115
- async function startAndWait<TResult>(
116
- key: string,
117
- startChild: (completionTokenArg: string) => Promise<void>
118
- ): Promise<TResult> {
119
- const { workflowRunId } = getWorkflowMetadata();
120
- const token = completionToken(workflowRunId, key);
121
- const hook = childCompletionHook.create({ token }); // [!code highlight]
63
+ `returnValue` is typed from the child's return type. A child that fails or is canceled rejects it with [`WorkflowRunFailedError`](/docs/api-reference/workflow-errors/workflow-run-failed-error) or [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error).
122
64
 
123
- await startChild(token);
65
+ ### How the parent waits
124
66
 
125
- const completion = await hook; // [!code highlight]
126
- if (completion.status === "failed") {
127
- throw new Error(completion.error);
128
- }
129
- return completion.value as TResult;
130
- }
67
+ Awaiting `returnValue` of a run the workflow started does not poll. The SDK waits on a **system hook**, the same handshake you would otherwise write by hand, but with one hook for the whole parent rather than one per child:
131
68
 
132
- // Parent workflow -- orchestrates document processing
133
- export async function processDocumentBatch(documentIds: string[]) {
134
- "use workflow";
69
+ 1. `start()` records the parent's run ID on the child, and remembers the parent on the returned `Run`.
70
+ 2. When the parent awaits a child, it registers its completion hook (a system hook whose token is derived from the parent's run ID) if it is not already open, then reads every child it started waiting on since its last read, in one step. A child that already finished is answered from that read.
71
+ 3. Otherwise the parent suspends on the hook. When a child completes, fails, or is canceled, its runtime resumes the parent's hook with that child's run ID, and the parent reads that child's result.
72
+ 4. Once the parent is no longer waiting on any child, it disposes the hook, so children it never awaits do not wake it.
135
73
 
136
- const results = await Promise.all(
137
- documentIds.map((documentId) =>
138
- startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
139
- start(processDocumentWithCompletion, [documentId, token]).then(() => undefined) // [!code highlight]
140
- )
141
- )
142
- );
74
+ This gives you:
143
75
 
144
- return { processed: results.length, results };
145
- }
146
- ```
76
+ - **Zero compute while waiting**: The parent is suspended rather than waking on a poll interval, and holds no worker slot. Worker-based Worlds such as [Postgres](/worlds/postgres) do not need a slot per waiting parent.
77
+ - **Immediate wake-up**: The parent resumes as soon as a child finishes, not on the next poll tick.
78
+ - **A slim parent log**: Fanning out to many children adds one system hook and one status read to the parent, plus, per child, the notification and the read of its result.
79
+ - **No wiring**: There is no hook to define, no token to pass, and no wrapper workflow to export.
80
+
81
+ The `Run` keeps this behavior when it travels within the parent: a step of the parent that calls `start()` and returns the `Run` hands the parent a handle it can await the same way. Awaiting the same child twice shares one wait.
82
+
83
+ ### Cancellations that bypass the SDK
147
84
 
148
- ### Why hooks instead of polling?
85
+ <Callout type="warn">
86
+ A parent is notified **immediately** only when the child's own runtime records its outcome, or when the child is canceled through the SDK. A cancellation written to the World without going through the SDK is not delivered to the parent, which keeps waiting until its next safety-net check.
87
+ </Callout>
149
88
 
150
- Polling with `getRun().status` in a `sleep()` loop works, but hook resume is preferable because:
89
+ | How the child finished | Parent resumes |
90
+ | --- | --- |
91
+ | The child completed or failed | Immediately |
92
+ | Canceled with `run.cancel()`, `cancelRun()`, or `cancelRuns()` | Immediately |
93
+ | Canceled with `workflow cancel` or from `workflow web` | Immediately (both call `cancelRun()`) |
94
+ | Canceled by any other tool that writes the cancellation to the World or its backend directly, without the SDK | At the next safety-net check |
95
+ | The child's invocation crashed after recording its outcome but before resuming the parent | At the next safety-net check |
151
96
 
152
- - **Zero compute while waiting**: The parent suspends on the hook instead of waking every poll interval.
153
- - **Immediate wake-up**: The parent resumes as soon as the child finishes, not on the next poll tick.
154
- - **Typed payloads**: The child sends `{ status, value | error }` directly, with no separate `returnValue` fetch step.
155
- - **No worker-pool pressure**: `Run#returnValue` polling inside steps can hold worker slots while waiting for children (see [Eager Processing](/docs/changelog/eager-processing)).
97
+ The safety net: while a parent waits on children, it keeps one sleep open and, when it fires, reads every child it is still waiting on. The first check runs 5 minutes after the parent starts waiting, then the interval doubles up to every 6 hours. A missed notification therefore delays the parent but never strands it. Each check costs the parent one sleep and one step, so a child that runs for a day adds about a dozen of each.
156
98
 
157
- When a parent calls a child workflow inline with `await` (flattened into the same run), the same wrapper and hook handshake still works: pass the token and `await processDocumentWithCompletion(...)` inside `startAndWait()` instead of calling `start()`.
99
+ If a parent must react to a cancellation faster than that, cancel children through the SDK.
100
+
101
+ ### When `returnValue` polls instead
102
+
103
+ `returnValue` falls back to polling the child, inside a step that holds its worker slot until the child finishes, when the waiting code is not the workflow that started it:
104
+
105
+ - a step, API route, or other server code (for example, a step that calls `start()` and awaits the result itself)
106
+ - a different workflow that was handed the `Run` as an argument
107
+
108
+ It also polls for a child started on another deployment (`deploymentId`) whose SDK predates the system hook, and for every child started while [`WORKFLOW_CHILD_RUN_COMPLETION_HOOK=0`](/docs/configuration/runtime-tuning#workflow_child_run_completion_hook) is set.
158
109
 
159
110
  ## Fan-out pattern: chunked spawning
160
111
 
161
- When spawning hundreds of children, batch the `start()` calls to avoid overwhelming the system. Each child still gets its own completion hook keyed by a stable identifier (document ID, report ID, index).
112
+ When spawning hundreds of children, batch the `start()` calls to avoid overwhelming the system. Each awaited child gets its own system hook, so a chunk costs nothing while it waits.
162
113
 
163
114
  ```typescript
164
115
  import { start } from "workflow/api";
165
116
 
166
- declare function startAndWait<TResult>(
167
- key: string,
168
- startChild: (completionTokenArg: string) => Promise<void>
169
- ): Promise<TResult>; // @setup
117
+ declare function queryDatabase(reportId: string, query: string): Promise<string>; // @setup
118
+ declare function formatReport(reportId: string, data: string): Promise<string>; // @setup
170
119
 
171
120
  const CHUNK_SIZE = 10;
172
121
 
122
+ export async function generateReport(reportId: string, query: string) {
123
+ "use workflow";
124
+
125
+ const data = await queryDatabase(reportId, query);
126
+ const formatted = await formatReport(reportId, data);
127
+ return { reportId, formatted };
128
+ }
129
+
173
130
  export async function largeReportBatch(
174
131
  reportConfigs: Array<{ id: string; query: string }>
175
132
  ) {
@@ -178,82 +135,36 @@ export async function largeReportBatch(
178
135
  const results = [];
179
136
  for (let i = 0; i < reportConfigs.length; i += CHUNK_SIZE) {
180
137
  const chunk = reportConfigs.slice(i, i + CHUNK_SIZE);
181
- const chunkResults = await Promise.all(
182
- chunk.map((config) =>
183
- startAndWait<{ reportId: string; formatted: string }>(config.id, (token) =>
184
- start(generateReportWithCompletion, [
185
- config.id,
186
- config.query,
187
- token,
188
- ]).then(() => undefined)
189
- )
190
- )
138
+ const runs = await Promise.all(
139
+ chunk.map((config) => start(generateReport, [config.id, config.query]))
191
140
  );
192
- results.push(...chunkResults);
141
+ results.push(...(await Promise.all(runs.map((run) => run.returnValue))));
193
142
  }
194
143
 
195
144
  return { total: results.length, results };
196
145
  }
197
-
198
- async function generateReportWithCompletion(
199
- reportId: string,
200
- query: string,
201
- completionTokenArg: string
202
- ) {
203
- "use workflow";
204
-
205
- await withChildCompletionHook(
206
- () => generateReport(reportId, query),
207
- completionTokenArg
208
- );
209
- }
210
-
211
- async function generateReport(reportId: string, query: string) {
212
- "use workflow";
213
-
214
- const data = await queryDatabase(reportId, query);
215
- const formatted = await formatReport(reportId, data);
216
- return { reportId, formatted };
217
- }
218
-
219
- declare function queryDatabase(reportId: string, query: string): Promise<string>; // @setup
220
- declare function formatReport(reportId: string, data: string): Promise<string>; // @setup
221
- declare function withChildCompletionHook<TResult>(
222
- runChild: () => Promise<TResult>,
223
- completionTokenArg: string
224
- ): Promise<void>; // @setup
225
146
  ```
226
147
 
227
148
  ## Error handling
228
149
 
229
150
  ### Tolerating partial failures
230
151
 
231
- Use `Promise.allSettled` with `startAndWait()` so one failing child doesn't abort siblings. The hook payload already carries `{ status: "failed", error }`, so no status polling is required.
152
+ Use `Promise.allSettled` over the children's `returnValue` so one failing child doesn't abort its siblings. A failed child's entry is rejected with `WorkflowRunFailedError`, whose `cause` is the error the child threw.
232
153
 
233
154
  ```typescript
234
155
  import { start } from "workflow/api";
235
156
 
236
- declare function startAndWait<TResult>(
237
- key: string,
238
- startChild: (completionTokenArg: string) => Promise<void>
239
- ): Promise<TResult>; // @setup
240
- declare function processDocumentWithCompletion(
241
- documentId: string,
242
- completionTokenArg: string
243
- ): Promise<void>; // @setup
157
+ declare function processDocument(
158
+ documentId: string
159
+ ): Promise<{ documentId: string; summary: string }>; // @setup
244
160
 
245
161
  export async function processDocumentBatchTolerant(documentIds: string[]) {
246
162
  "use workflow";
247
163
 
248
- const settled = await Promise.allSettled(
249
- documentIds.map((documentId) =>
250
- startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
251
- start(processDocumentWithCompletion, [documentId, token]).then(
252
- () => undefined
253
- )
254
- )
255
- )
164
+ const runs = await Promise.all(
165
+ documentIds.map((documentId) => start(processDocument, [documentId]))
256
166
  );
167
+ const settled = await Promise.allSettled(runs.map((run) => run.returnValue));
257
168
 
258
169
  const results = settled
259
170
  .filter(
@@ -270,52 +181,81 @@ export async function processDocumentBatchTolerant(documentIds: string[]) {
270
181
 
271
182
  ### Retrying failed children
272
183
 
273
- When a child fails, spawn a replacement with a fresh hook token. Track restart counts to prevent infinite retry loops.
184
+ When a child fails, start a replacement. Track restart counts to prevent infinite retry loops.
274
185
 
275
186
  ```typescript
276
- declare function startAndWait<TResult>(
277
- key: string,
278
- startChild: (completionTokenArg: string) => Promise<void>
279
- ): Promise<TResult>; // @setup
280
- declare function spawnProcessDocument(
281
- documentId: string,
282
- completionTokenArg: string
283
- ): Promise<void>; // @setup
187
+ import { start } from "workflow/api";
188
+
189
+ declare function processDocument(
190
+ documentId: string
191
+ ): Promise<{ documentId: string; summary: string }>; // @setup
284
192
 
285
- async function startAndWaitWithRetries(
193
+ async function processDocumentWithRetries(
286
194
  documentId: string,
287
195
  maxRestarts: number
288
196
  ): Promise<{ documentId: string; summary: string }> {
289
- for (let attempt = 0; attempt <= maxRestarts; attempt++) {
197
+ for (let attempt = 0; ; attempt++) {
198
+ const run = await start(processDocument, [documentId]);
290
199
  try {
291
- return await startAndWait<{ documentId: string; summary: string }>(
292
- `${documentId}:${attempt}`,
293
- (token) => spawnProcessDocument(documentId, token)
294
- );
200
+ return await run.returnValue;
295
201
  } catch (error) {
296
- if (attempt === maxRestarts) throw error;
202
+ if (attempt >= maxRestarts) throw error;
297
203
  }
298
204
  }
205
+ }
206
+ ```
207
+
208
+ ## Signaling the parent before the child finishes
209
+
210
+ The system hook fires only when the child finishes. When the parent needs to hear from a child mid-run (a progress milestone, an approval request, a partial result), create a [hook](/docs/foundations/hooks) in the parent and pass its token to the child, which resumes it from a step:
211
+
212
+ ```typescript
213
+ import { createHook } from "workflow";
214
+ import { resumeHook, start } from "workflow/api";
215
+
216
+ declare function prepareDraft(documentId: string): Promise<string>; // @setup
217
+ declare function publishDraft(draft: string): Promise<void>; // @setup
218
+
219
+ async function notifyDraftReady(token: string, draft: string) {
220
+ "use step";
221
+ await resumeHook(token, { draft });
222
+ }
223
+
224
+ export async function draftDocument(documentId: string, draftToken: string) {
225
+ "use workflow";
226
+
227
+ const draft = await prepareDraft(documentId);
228
+ await notifyDraftReady(draftToken, draft); // the parent continues from here
229
+ await publishDraft(draft);
230
+ return { documentId, published: true };
231
+ }
232
+
233
+ export async function reviewDocument(documentId: string) {
234
+ "use workflow";
235
+
236
+ const draftReady = createHook<{ draft: string }>();
237
+ const run = await start(draftDocument, [documentId, draftReady.token]);
299
238
 
300
- throw new Error("unreachable");
239
+ const { draft } = await draftReady; // mid-run signal from the child
240
+ const result = await run.returnValue; // completion, via the system hook
241
+ return { draft, ...result };
301
242
  }
302
243
  ```
303
244
 
304
245
  ## Tips
305
246
 
306
- - **Call `defineHook().resume()` from a step**: The wrapped child's `finally` block calls a step that resumes the parent hook.
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
- - **Use stable hook keys**: Document IDs, job IDs, or indexes prevent token collisions between parallel children in one parent run.
247
+ - **Await only the children you need**: A child whose parent is not waiting on any child when it finishes costs one extra hook lookup and nothing in the parent. One that finishes while the parent waits on its siblings adds a notification to the parent's log.
309
248
  - **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.
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.
249
+ - **Watch the parent's log too**: The parent records events for spawning and collecting every child (the spawn step, the child's notification on the parent's completion hook, and the step that reads its result). 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.
250
+ - **Account for each child's retry semantics**: Steps inside child workflows retry independently. The parent only sees the child's final result or error.
251
+ - **Cancel children through the SDK**: [`run.cancel()`](/docs/api-reference/workflow-api/get-run), `cancelRun()`, `cancelRuns()`, `workflow cancel`, and `workflow web` resume a waiting parent immediately. Any other cancellation reaches the parent only at its next safety-net check; see [Cancellations that bypass the SDK](#cancellations-that-bypass-the-sdk).
312
252
  - **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
253
 
314
254
  ## Key APIs
315
255
 
316
- - [`start()`](/docs/api-reference/workflow-api/start): Spawns a new workflow run and returns its run ID.
317
- - [`defineHook()`](/docs/api-reference/workflow/define-hook): Defines a typed hook for parent-child completion handshakes.
318
- - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes a waiting parent from a step called by the child wrapper.
319
- - [`getWorkflowMetadata()`](/docs/api-reference/workflow/get-workflow-metadata): Returns the parent run ID for deterministic hook tokens.
256
+ - [`start()`](/docs/api-reference/workflow-api/start): Spawns a new workflow run and returns a `Run` whose `returnValue` the parent can await.
257
+ - [`getRun()`](/docs/api-reference/workflow-api/get-run): Documents the `Run` handle, with `returnValue`, `status`, and `cancel()`.
258
+ - [`createHook()`](/docs/api-reference/workflow/create-hook): Creates a hook for signals from a child before it finishes.
259
+ - [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes a parent's hook from a step in the child.
320
260
  - [`"use workflow"`](/docs/foundations/workflows-and-steps): Marks the orchestrator function.
321
261
  - [`"use step"`](/docs/foundations/workflows-and-steps): Marks functions with full Node.js access.