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
@@ -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
+ experimental_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 `experimental_hook.token`.
@@ -138,7 +138,7 @@ export async function birthdayWorkflow(
138
138
 
139
139
  1. **`await` is durable**: When the workflow awaits a step, the runtime persists the step's input, suspends the workflow, runs the step, and replays the workflow with the step's result on resume. The same applies to `sleep()` and `createWebhook()`.
140
140
  2. **`Promise.all` runs steps concurrently**: Each promise in the array is suspended on its own, and the workflow resumes only when all have settled. If any promise rejects, the whole `Promise.all` rejects.
141
- 3. **`Promise.race` resolves when the first promise settles**: The losing promises keep running in the background, but the workflow discards their results.
141
+ 3. **`Promise.race` resolves when the first promise settles**: As in plain JavaScript, the losing promises keep running in the background, but the workflow discards their results.
142
142
  4. **All primitives are promises**: `sleep("1 day")` and `createWebhook()` return promises, so they compose with `Promise.all` and `Promise.race` like steps do. This behavior enables patterns such as racing a webhook against a 24-hour deadline.
143
143
 
144
144
  ## Adapting to your use case
@@ -14,7 +14,7 @@ related:
14
14
  text="Compose these workflows. For direct composition, `await` the child workflow function from the parent &quot;use workflow&quot; function: the child's steps flatten into the parent's event log and run as a single run sharing the parent's lifecycle. For independent background work, spawn the child with `start()` from `workflow/api` called directly in the workflow (in v5, `start()` is step-backed and records a deterministic step boundary) and return `run.runId` so callers can track it with `getRun()`. Choose flattening when the parent needs the child's result; choose background spawn when the child should have its own run, retries, and lifetime. Keep all inputs and outputs serializable. Verify flattened execution, background spawn with a separate runId, and replay determinism."
15
15
  />
16
16
 
17
- Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or starts the child as an independent run (background spawn). For large fan-out operations with hook-based waiting and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
17
+ Workflows can call other workflows. Choose between two composition modes depending on whether the parent needs the child's result inline (direct await) or starts the child as an independent run (background spawn). For large fan-out operations, waiting on children, and partial-failure handling, see [Child Workflows](/cookbook/advanced/child-workflows).
18
18
 
19
19
  ## When to use this
20
20
 
@@ -100,7 +100,7 @@ If you want the child workflow to run on the latest deployment rather than the c
100
100
 
101
101
  | | Direct await | Background spawn (`start()`) |
102
102
  | --- | --- | --- |
103
- | Parent waits for child | Yes | No |
103
+ | Parent waits for child | Yes | Optional (`await run.returnValue`) |
104
104
  | Has its own `runId` | No (shares parent's) | Yes |
105
105
  | Has its own event log | No | Yes |
106
106
  | Has its own retry boundary | No | Yes |
@@ -108,9 +108,9 @@ If you want the child workflow to run on the latest deployment rather than the c
108
108
 
109
109
  ## Adapting to your use case
110
110
 
111
- - **Spawn many children at once**: call `start()` in a loop from the workflow. For more advanced fan-out (chunking, hook-based waiting, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
112
- - **Wait for a background child to finish**: combine `start()` with a completion hook the child resumes when done. The [Child Workflows](/cookbook/advanced/child-workflows) page covers the recommended `startAndWait()` pattern.
113
- - **Pass results back from background children**: the wrapped child resumes the parent's hook in `finally` with `{ status, value | error }`; the parent awaits the hook instead of polling `getRun().status`.
111
+ - **Spawn many children at once**: call `start()` in a loop from the workflow. For more advanced fan-out (chunking, partial-failure handling), graduate to the [Child Workflows](/cookbook/advanced/child-workflows) recipe.
112
+ - **Wait for a background child to finish**: `await run.returnValue` on the `Run` that `start()` returned. The parent suspends on a system hook the child resumes when it finishes, so it waits without polling. See [How the parent waits](/cookbook/advanced/child-workflows#how-the-parent-waits).
113
+ - **Hear from a background child before it finishes**: create a hook in the parent and pass its token to the child, which resumes it from a step. See [Signaling the parent before the child finishes](/cookbook/advanced/child-workflows#signaling-the-parent-before-the-child-finishes).
114
114
 
115
115
  ## Key APIs
116
116
 
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  title: fetch-in-workflow
3
- description: Use the workflow fetch step function instead of global fetch in workflows.
3
+ description: Make HTTP requests from step functions instead of workflow functions.
4
4
  type: troubleshooting
5
- summary: Resolve the fetch-in-workflow error by using the workflow fetch function.
5
+ summary: Resolve the fetch-in-workflow error by moving HTTP requests into a step function.
6
6
  prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
@@ -29,7 +29,7 @@ Many libraries make HTTP requests under the hood. For example, the AI SDK's `gen
29
29
 
30
30
  ## Quick fix
31
31
 
32
- Import the `fetch` step function from the `workflow` package and assign it to `globalThis.fetch` inside your workflow function. This version of `fetch` is a step function that wraps the standard `fetch` API, automatically handling serialization and providing retry capabilities. This will also make `fetch()` available to all functions and libraries in the current workflow function.
32
+ Move the code that makes the request into a step function, and call that step from the workflow. Steps have full Node.js access, so `fetch()` and libraries that call it work as usual.
33
33
 
34
34
  **Before:**
35
35
 
@@ -53,14 +53,11 @@ export async function chatWorkflow(prompt: string) {
53
53
 
54
54
  ```typescript lineNumbers title="workflows/ai.ts"
55
55
  import { generateText } from "ai";
56
- import { fetch } from "workflow"; // [!code highlight]
57
56
 
58
- export async function chatWorkflow(prompt: string) {
59
- "use workflow";
60
-
61
- globalThis.fetch = fetch; // [!code highlight]
57
+ async function generate(prompt: string) {
58
+ "use step"; // [!code highlight]
62
59
 
63
- // Now generateText() can make HTTP requests via the fetch step
60
+ // generateText calls fetch() under the hood
64
61
  const result = await generateText({
65
62
  model: "spacexai/grok-4.6",
66
63
  prompt,
@@ -68,36 +65,25 @@ export async function chatWorkflow(prompt: string) {
68
65
 
69
66
  return result.text;
70
67
  }
68
+
69
+ export async function chatWorkflow(prompt: string) {
70
+ "use workflow";
71
+
72
+ return await generate(prompt); // [!code highlight]
73
+ }
71
74
  ```
72
75
 
73
76
  ## Common scenarios
74
77
 
75
78
  ### AI SDK integration
76
79
 
77
- This is the most common scenario - using AI SDK functions that make HTTP requests:
78
-
79
- ```typescript lineNumbers
80
- import { generateText, streamText } from "ai";
81
- import { fetch } from "workflow"; // [!code highlight]
82
-
83
- export async function aiWorkflow(userMessage: string) {
84
- "use workflow";
80
+ For agents, use AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent) or [`HarnessAgent`](https://ai-sdk.dev/v7/docs/ai-sdk-harnesses/workflow-utilities), which run model calls as steps.
85
81
 
86
- globalThis.fetch = fetch; // [!code highlight]
87
-
88
- // generateText makes an HTTP request under the hood
89
- const response = await generateText({
90
- model: "spacexai/grok-4.6",
91
- prompt: userMessage,
92
- });
93
-
94
- return response.text;
95
- }
96
- ```
82
+ For single AI SDK calls, use a step function as shown above.
97
83
 
98
84
  ### Direct API calls
99
85
 
100
- You can also use the fetch step function directly for your own HTTP requests:
86
+ For simple requests, you can use the `fetch` step function from `workflow` directly:
101
87
 
102
88
  ```typescript lineNumbers
103
89
  import { fetch } from "workflow";
@@ -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.
@@ -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({ experimental_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
 
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  title: Idempotency
3
- description: Make step retries safe and coordinate duplicate workflow starts with hook tokens.
3
+ description: Make step retries safe, and start a workflow run at most once per key with start({ experimental_hook }).
4
4
  type: conceptual
5
- summary: Use step IDs for retry-safe external calls, and route duplicate workflow-start requests through deterministic hook tokens.
5
+ summary: Use step IDs for retry-safe external calls, and pass a deterministic hook token to start() so a duplicate request is refused or routed to the run that owns it.
6
6
  prerequisites:
7
7
  - /docs/foundations/workflows-and-steps
8
8
  related:
@@ -13,7 +13,7 @@ related:
13
13
 
14
14
  Idempotency is a property of an operation that ensures repeated attempts have the same effect as a single attempt.
15
15
 
16
- In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency coordinates duplicate requests that try to start the same workflow.
16
+ In Workflow, idempotency shows up in two related places: step idempotency makes external calls safe when a step retries, and run idempotency makes duplicate requests start the same workflow run only once.
17
17
 
18
18
  ## Step idempotency
19
19
 
@@ -57,11 +57,190 @@ Why this works:
57
57
 
58
58
  Step idempotency protects side effects **inside** a workflow run. Run idempotency answers a different question: if the same API request is sent twice, should it create one workflow run or two?
59
59
 
60
- Because [hooks](/docs/foundations/hooks) already ensure globally unique active tokens, Workflow can use the same mechanism to coordinate duplicate requests while a run is active.
60
+ Workflow uses a [Hook](/docs/foundations/hooks) token as the idempotency key. Pick a token from your domain, such as an order ID, invoice ID, import ID, or request ID, and pass it to `start()`.
61
61
 
62
- Use a hook token as the idempotency key for an active workflow run. Hook tokens are globally unique while they are active: if another run tries to create a hook with the same token, the runtime records a conflict, `hook.getConflict()` resolves with a `Run` handle for the run that owns the token, and the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict) when the workflow awaits or iterates its payload.
62
+ ### Start a run once per key
63
63
 
64
- The token should come from your domain, such as an order ID, invoice ID, import ID, or request ID. Create the hook near the beginning of the workflow and check `await hook.getConflict()` before doing duplicate-sensitive work that depends on owning the active token. Calling `createHook()` alone does not register the hook; awaiting `getConflict()` suspends the workflow to commit the registration. Check it before calling any step: steps the workflow calls before it suspends are started alongside the hook's registration, so a duplicate run that only learns of the conflict later (for example, by awaiting the hook and letting `HookConflictError` end the run) may already have started them. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
64
+ ```typescript title="app/api/orders/route.ts" lineNumbers
65
+ import { start } from "workflow/api";
66
+ import { HookConflictError } from "workflow/errors";
67
+ import { processOrder } from "./workflows/process-order";
68
+
69
+ export async function POST(request: Request) {
70
+ const { orderId } = await request.json();
71
+
72
+ try {
73
+ const run = await start(processOrder, [orderId], {
74
+ experimental_hook: { token: `order:${orderId}` }, // [!code highlight]
75
+ });
76
+ return Response.json({ runId: run.runId, duplicate: false });
77
+ } catch (error) {
78
+ if (!HookConflictError.is(error)) throw error;
79
+ return Response.json({ runId: error.conflictingRunId, duplicate: true }); // [!code highlight]
80
+ }
81
+ }
82
+ ```
83
+
84
+ `start({ experimental_hook })` admits the run and creates its **start Hook** in one atomic step. Exactly one run owns the token. A duplicate `start()` with the same token throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) with the owner's `conflictingRunId`. The duplicate never becomes a run, and none of its code runs.
85
+
86
+ ### Start or route to the owner
87
+
88
+ A duplicate request often carries data the owner should receive, such as a follow-up message in a chat. Since the start Hook exists from the moment the run is admitted, you can resume it right away on a conflict, even before the owner starts executing:
89
+
90
+ ```typescript title="app/api/orders/route.ts" lineNumbers
91
+ import { resumeHook, start } from "workflow/api";
92
+ import { HookConflictError, HookNotFoundError } from "workflow/errors";
93
+ import { processOrder } from "./workflows/process-order";
94
+
95
+ export async function POST(request: Request) {
96
+ const { orderId, note } = await request.json();
97
+ const token = `order:${orderId}`;
98
+
99
+ let owner: string | undefined;
100
+ for (let attempt = 0; attempt < 3; attempt++) {
101
+ try {
102
+ const run = await start(processOrder, [orderId, note], { experimental_hook: { token } });
103
+ return Response.json({ runId: run.runId, started: true });
104
+ } catch (error) {
105
+ if (!HookConflictError.is(error)) throw error;
106
+ owner = error.conflictingRunId;
107
+ }
108
+
109
+ try {
110
+ const hook = await resumeHook(token, { note }); // [!code highlight]
111
+ return Response.json({ runId: hook.runId, started: false });
112
+ } catch (error) {
113
+ // The owner's Hook is no longer resumable (it ended, or disposed its
114
+ // start Hook): try to start again, which may take the token.
115
+ if (!HookNotFoundError.is(error)) throw error; // [!code highlight]
116
+ }
117
+ }
118
+
119
+ // Still refused: a finished owner holds the token for its retention, or
120
+ // the owner is a candidate that was admitted but never became a run.
121
+ throw new Error(`Run ${owner} holds ${token}; it can't be started or resumed`);
122
+ }
123
+ ```
124
+
125
+ Every caller either starts the run, delivers its payload to the owner, or learns which run holds the token. While the owner's start Hook is open, the loop needs at most two calls. A `HookNotFoundError` after a conflict means the owner's Hook is no longer resumable: the owner ended, or [disposed its start Hook](#take-care-with-the-start-hooks-lifecycle). The next `start()` may then take the token, or be refused again: by a finished owner that still holds it for its retention, or by another caller that started first.
126
+
127
+ If the token has a [retention](#keep-the-token-after-the-run-ends), a finished owner keeps refusing new starts until the retention passes, and its Hook can no longer be resumed, so the loop above gives up after its attempts and names that run. Use `getRun(owner)` to tell the caller what the finished run returned.
128
+
129
+ ### Receive the payloads in the workflow
130
+
131
+ To read the payloads, call `createHook()` in the workflow with the same token:
132
+
133
+ ```typescript title="workflows/process-order.ts" lineNumbers
134
+ import { createHook } from "workflow";
135
+
136
+ type OrderUpdate = { note: string; done?: boolean };
137
+ declare function recordNote(orderId: string, note: string): Promise<void>; // @setup
138
+
139
+ export async function processOrder(orderId: string, note: string) {
140
+ "use workflow";
141
+
142
+ await recordNote(orderId, note);
143
+
144
+ const updates = createHook<OrderUpdate>({ token: `order:${orderId}` }); // [!code highlight]
145
+ for await (const update of updates) {
146
+ await recordNote(orderId, update.note);
147
+ if (update.done) break;
148
+ }
149
+ }
150
+ ```
151
+
152
+ - `createHook({ token })` with the run's start token returns a handle bound to the start Hook. It doesn't register a new Hook, so it adds no step, and `await hook.getConflict()` resolves `null`.
153
+ - Payloads resumed before the workflow opens the Hook are kept, and are delivered in order once it does.
154
+ - If the workflow never opens it, the token was only an idempotency key. The run completes normally, and unread payloads are simply left unread.
155
+ - `metadata` and `experimental_minRetention` belong on `start({ experimental_hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to this `createHook()` throws.
156
+
157
+ ### Keep the token after the run ends
158
+
159
+ The start Hook follows the ordinary Hook lifecycle, like a `createHook()` in the run. Without a retention, the token is released when the run ends, and a later `start()` with the token is admitted as a new run.
160
+
161
+ To refuse late duplicates too, set `experimental_minRetention`. It accepts the same duration string, milliseconds, or `Date` as [`createHook({ experimental_minRetention })`](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends), and a duration counts from `start()`:
162
+
163
+ ```typescript lineNumbers
164
+ import { start } from "workflow/api";
165
+ import { processOrder } from "./workflows/process-order";
166
+ declare const orderId: string; // @setup
167
+
168
+ const run = await start(processOrder, [orderId, ""], {
169
+ experimental_hook: {
170
+ token: `order:${orderId}`,
171
+ experimental_minRetention: "30 days", // [!code highlight]
172
+ metadata: { orderId },
173
+ },
174
+ });
175
+ ```
176
+
177
+ The run owns the token until it ends, even if the retention passes first. After the run ends, and until the retention passes:
178
+
179
+ - a duplicate `start()` throws `HookConflictError` naming the finished owner;
180
+ - [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) still returns the Hook, with the `start()` metadata;
181
+ - `resumeHook()` throws `HookNotFoundError`, because a finished run can't receive payloads.
182
+
183
+ There is no default retention.
184
+
185
+ Cancelling the owner ends the run, so it releases the token too, once any retention has passed.
186
+
187
+ ### Take care with the start Hook's lifecycle
188
+
189
+ <Callout type="warn">
190
+ The run holds its token only while its start Hook does. Disposing the start Hook, with `hook.dispose()` or when a `using` declaration in an inner scope ends, releases the token at once, as it does for any Hook. A later `start()` with the token is then admitted as a new run, even while this one is still running, and `experimental_minRetention` no longer applies: it only holds the token after a run that ends without disposing the Hook.
191
+ </Callout>
192
+
193
+ Open the start Hook with `const`, as in the examples above, and let the run's end release it. After disposing it, the run can call `createHook({ token })` again for a new Hook, but only if no other run has taken the token in the meantime; otherwise `getConflict()` names that run.
194
+
195
+ ### Dispose the start Hook with `using`
196
+
197
+ `using` disposes a Hook when its scope ends, which reads well when the workflow only needs the payloads for part of its work:
198
+
199
+ ```typescript title="workflows/process-order.ts" lineNumbers
200
+ import { createHook } from "workflow";
201
+
202
+ type OrderUpdate = { note: string; done?: boolean };
203
+ declare function recordNote(orderId: string, note: string): Promise<void>; // @setup
204
+ declare function shipOrder(orderId: string): Promise<void>; // @setup
205
+
206
+ export async function processOrder(orderId: string, note: string) {
207
+ "use workflow";
208
+
209
+ {
210
+ using updates = createHook<OrderUpdate>({ token: `order:${orderId}` }); // [!code highlight]
211
+ for await (const update of updates) {
212
+ await recordNote(orderId, update.note);
213
+ if (update.done) break;
214
+ }
215
+ } // The start Hook is disposed here, and the token is released.
216
+
217
+ await shipOrder(orderId);
218
+ }
219
+ ```
220
+
221
+ Disposing the start Hook ends the run's idempotency: from the end of that block, another `start()` with the token is admitted while this run ships the order. Use it when that is what you want. To keep duplicates out for the whole run, use `const`. A `using` at the top level of the workflow function disposes the Hook only as the run returns, but with a retention it releases the token then instead of holding it.
222
+
223
+ ### When `start()` can't confirm the outcome
224
+
225
+ If `start({ experimental_hook })` can't confirm whether its candidate run was queued or admitted, for example because the World timed out, it throws [`WorkflowStartError`](/docs/api-reference/workflow-errors/workflow-start-error) with the candidate's `runId`. The outcome is unknown, not failed. Retrying with the same token is safe: the retry either becomes the owner, or is refused with a `HookConflictError` naming the owner. Inside a workflow, the `start()` step retries it on its own.
226
+
227
+ ### World support
228
+
229
+ `start({ experimental_hook })` requires a World that supports atomic start Hooks (`capabilities.atomicStartHook`), and Hook retention when you set `experimental_minRetention`. Otherwise `start()` throws before it enqueues anything.
230
+
231
+ | World | Support |
232
+ | --- | --- |
233
+ | [Local World](/worlds/local) | Supported. |
234
+ | [Postgres World](/worlds/postgres) | Supported, after applying migration `0028_add_start_hook_admissions`. Stop workers running a previous version first; see [Start Hooks](/worlds/postgres#start-hooks). |
235
+ | [Vercel World](/worlds/vercel) | Supported. |
236
+
237
+ See [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) for the full option reference.
238
+
239
+ ### Coordinate inside the workflow
240
+
241
+ On a World without atomic start Hooks, or when a run should decide for itself how to treat a duplicate, coordinate with `createHook()` and `getConflict()` in the workflow instead. Hook tokens are unique while active: if another run already owns the token, `await hook.getConflict()` resolves with a `Run` handle for the owner, and awaiting the hook rejects with [`HookConflictError`](/docs/errors/hook-conflict).
242
+
243
+ Create the hook near the beginning of the workflow, and check `await hook.getConflict()` before calling any step. Awaiting it suspends the workflow to commit the registration; steps called before that suspension start alongside it, so a duplicate run that learns of the conflict later may already have started them. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
65
244
 
66
245
  ```typescript lineNumbers
67
246
  import { createHook } from "workflow";
@@ -96,62 +275,15 @@ export async function processOrder(orderId: string): Promise<OrderResult> {
96
275
  }
97
276
  ```
98
277
 
99
- The runtime creates the hook atomically. At most one hook can own `order:${orderId}`, so duplicate workflow runs converge on one owner. A duplicate run observes `getConflict()` resolving with the owner's `Run` and returns before it reaches `chargeOrder()`. The conflicting run's accessors (`status`, `returnValue`, `cancel()`, …) are durable steps, so the duplicate run can do more than report the owner. See [conflict-handling strategies](#conflict-handling-strategies) below.
100
-
101
- Outside the workflow, try to resume the hook first. If the hook is not registered yet, start the workflow and retry the resume until the new run creates the hook:
102
-
103
- ```typescript lineNumbers
104
- import { resumeHook, start } from "workflow/api";
105
- import { HookNotFoundError } from "workflow/errors";
106
- import { processOrder } from "./workflows/process-order";
107
-
108
- type OrderRequest = { confirmed: boolean };
109
-
110
- async function resumeOrder(token: string, payload: OrderRequest) {
111
- for (let attempt = 0; attempt < 5; attempt++) {
112
- try {
113
- return await resumeHook(token, payload); // [!code highlight]
114
- } catch (error) {
115
- if (!HookNotFoundError.is(error)) throw error;
116
- await new Promise((resolve) => setTimeout(resolve, 100));
117
- }
118
- }
119
-
120
- throw new Error("Order workflow did not register its hook in time");
121
- }
122
-
123
- export async function POST(request: Request) {
124
- const { orderId, confirmed } = await request.json();
125
- const token = `order:${orderId}`;
126
- const payload = { confirmed };
127
-
128
- try {
129
- const hook = await resumeHook(token, payload); // [!code highlight]
130
- return Response.json({ runId: hook.runId, reused: true });
131
- } catch (error) {
132
- if (!HookNotFoundError.is(error)) throw error;
133
- }
134
-
135
- const run = await start(processOrder, [orderId]); // [!code highlight]
136
- const resumed = await resumeOrder(token, payload);
137
-
138
- // A concurrent request's run may have won the race between `start()` // [!code highlight]
139
- // and hook registration. The resume always reaches the actual active // [!code highlight]
140
- // owner, so compare run IDs instead of waiting for this run to finish. // [!code highlight]
141
- return Response.json({ // [!code highlight]
142
- runId: resumed.runId, // [!code highlight]
143
- reused: resumed.runId !== run.runId, // [!code highlight]
144
- }); // [!code highlight]
145
- }
146
- ```
278
+ Outside the workflow, try `resumeHook()` first, and on `HookNotFoundError` call `start()` and retry the resume until the new run registers its hook.
147
279
 
148
280
  <Callout type="warn">
149
- This avoids creating a new run only after the first run has registered its hook. Because `start()` returns before the run body executes and calls `createHook()`, two concurrent requests can both observe "no hook yet" and each call `start()`. The race is resolved inside the workflow body, where the losing run observes `getConflict()` resolving with the active owner and returns without doing duplicate-sensitive work, and the route detects it by comparing the resumed hook's `runId` against the run it just started, without waiting for either run to finish. A native API for atomically starting a run and registering a hook is in the works. Until then, model recovery inside the workflow by checking `hook.getConflict()`.
281
+ Unlike `start({ experimental_hook })`, this doesn't stop a duplicate from becoming a run. Two concurrent requests can both see "no hook yet" and each call `start()`. The losing run is still created, queued, and started, and returns once `getConflict()` resolves with the owner. The route can detect it by comparing the resumed hook's `runId` with the run it started.
150
282
  </Callout>
151
283
 
152
- This coordinates active runs by default: the token becomes available when its workflow ends. Set `experimental_minRetention` to keep it unavailable to late duplicates. After the workflow ends, the Hook can still be found with `getHookByToken()` until retention ends, but it cannot be resumed. See [`createHook()` minimum retention](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends) for examples and supported values.
284
+ The token becomes available when its workflow ends, unless you set `experimental_minRetention` on `createHook()`. See [`createHook()` minimum retention](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends).
153
285
 
154
- ### Conflict-handling strategies
286
+ #### Conflict-handling strategies
155
287
 
156
288
  Some workflow systems resolve duplicate IDs with a fixed, pre-declared policy, typically a static choice between rejecting the new execution, deferring to the existing one, or terminating it. Workflow has no policy enum. `hook.getConflict()` hands the duplicate run the conflicting `Run` itself, and the policy is ordinary code, including policies that inspect state before deciding, which static configuration can't express.
157
289
 
@@ -302,9 +434,7 @@ export async function processOrderNewestWins(orderId: string) {
302
434
 
303
435
  A run started at a Workflow spec version below 8, including runs started by older SDK releases, can't be taken from. In that case the forced Hook rejects with `HookConflictError`, as it would without `experimental_force`.
304
436
 
305
- If duplicate requests should only reuse the active run without sending data, use [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) as an advisory pre-check before calling `start()`. The workflow should still check `hook.getConflict()`, because the lookup and `start()` are not atomic.
306
-
307
- Because this pattern uses hooks for idempotency, duplicate requests can also inject additional data and steer the existing run. The route example above uses `resumeHook()` for that: if the hook already exists, the duplicate request resumes the active workflow; if the hook is not registered yet, the route starts the workflow and retries `resumeHook()` so the payload is not dropped.
437
+ [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) before `start()` is only an advisory pre-check in this pattern: the lookup and `start()` are not atomic, so the workflow should still check `hook.getConflict()`.
308
438
 
309
439
  ## Related docs
310
440
 
@@ -100,16 +100,12 @@ export async function parentWorkflow(inputValue: number) {
100
100
  }
101
101
  ```
102
102
 
103
- When you call `start()` inside a workflow function, it automatically executes through an internal step to maintain deterministic replay. The returned `Run` object works as it does outside workflows. Properties such as `.runId`, `.status`, and `.returnValue`, and methods such as `.cancel()`, are all available. Each property access or method call executes as a separate step.
103
+ When you call `start()` inside a workflow function, it automatically executes through an internal step to maintain deterministic replay. The returned `Run` object works as it does outside workflows. Properties such as `.runId`, `.status`, and `.returnValue`, and methods such as `.cancel()`, are all available.
104
104
 
105
- If the child run fails or is canceled, `await childRun.returnValue` throws [`WorkflowRunFailedError`](/docs/api-reference/workflow-errors/workflow-run-failed-error) or [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error) on the first attempt.
105
+ Awaiting `childRun.returnValue` suspends the parent on a system hook that the child resumes when it finishes, so the parent waits without polling, uses no compute while it waits, and resumes as soon as the child is done. A child canceled without going through the SDK is noticed later, at the parent's next safety-net check; see [Cancellations that bypass the SDK](/cookbook/advanced/child-workflows#cancellations-that-bypass-the-sdk). If the child run fails or is canceled, `await childRun.returnValue` throws [`WorkflowRunFailedError`](/docs/api-reference/workflow-errors/workflow-run-failed-error) or [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error) on the first attempt.
106
106
 
107
107
  <Callout type="info">
108
- Inside workflow functions, each `Run` property access (e.g., `run.status`, `run.returnValue`) triggers a workflow step. This means each access is recorded in the event log and replayed deterministically.
109
- </Callout>
110
-
111
- <Callout type="warn">
112
- Awaiting `returnValue` polls the child run every second, and the polling step holds its worker slot open until the child finishes. Size worker-based Worlds to cover the peak number of these polls in flight. If the child workflow is long-running, spawn it without awaiting `returnValue` and have it resume a [hook](/docs/foundations/hooks) when it completes. See the [`startAndWait()` pattern](/cookbook/advanced/child-workflows).
108
+ Inside workflow functions, each `Run` property access (e.g., `run.status`, `run.returnValue`) is recorded in the event log and replayed deterministically. Most accessors run as one step; `returnValue` records the system hook and the steps that read the child's result.
113
109
  </Callout>
114
110
 
115
111
  ### Fire and forget
@@ -129,6 +129,8 @@ While a hook is active, its token is reserved and cannot be used by other workfl
129
129
 
130
130
  When a workflow ends, its hooks can no longer be resumed. They are normally removed, and their tokens become available again. With `experimental_minRetention`, a hook remains readable, and its token remains unavailable until retention ends. A `hook_disposed` event removes the hook and makes its token available immediately.
131
131
 
132
+ A hook disposed as the workflow returns or throws, such as one declared with `using` in the workflow function's top-level scope, is released by the run's `run_completed` or `run_failed` event, so the log records no separate `hook_disposed`. Disposing a hook that uses `experimental_minRetention` still records one, because it releases the token before retention ends.
133
+
132
134
  See [Hooks and webhooks](/docs/foundations/hooks) for more on how hooks and webhooks work.
133
135
 
134
136
  ### Wait lifecycle
@@ -381,3 +383,7 @@ Step-to-step overhead (STSO) measures the time the runtime adds between two step
381
383
  <MetricVideo metric="stso" />
382
384
 
383
385
  See [Step-to-step overhead](/docs/performance#step-to-step-overhead-stso) on the Performance page for how it's measured and the latest results.
386
+
387
+ ## Spec 9 (experimental)
388
+
389
+ The experimental spec 9 runtime writes the same event types with a different model: one orchestrator per run writes every decision behind an in-band fence, step and wait events are plain appends, and an inline step is created by its first `step_started`. See [The event log on spec 9 runs](/docs/changelog/spec-9#the-event-log).
@@ -179,6 +179,8 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
179
179
 
180
180
  - **`start()` from inside a workflow.** Spawn a child run or hand off to a new run directly in a workflow function, without wrapping it in a step. See [Starting workflows](/docs/foundations/starting-workflows).
181
181
  - **Hook token takeover.** Pass `experimental_force: true` to [`createHook()`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds) when the newest run should own a token another run still holds. The previous owner is woken and its `await hook` rejects with [`HookForceClaimedError`](/docs/api-reference/workflow-errors/hook-force-claimed-error), while `resumeHook()` callers, including one already in flight, are routed to the new owner without noticing. Supported by all three first-party Worlds.
182
+ - **Idempotent starts.** Pass `experimental_hook: { token }` to [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) to admit at most one run per token. A duplicate throws `HookConflictError` naming the owner and never becomes a run, and the owner's start Hook can be resumed right away. See [Run idempotency](/docs/foundations/idempotency#start-a-run-once-per-key).
183
+ - **Resume a stored Hook without another lookup.** Pass the `Hook` returned by `getHookByToken()` or `resumeHook()` back to [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook#reuse-a-resolved-hook) instead of its token, and later deliveries skip the token lookup. The Hook survives JSON serialization, so you can keep it with your server-side session state. Supported on the Vercel World.
182
184
  - **Stronger hook coordination.** `hook.getConflict()` resolves with the conflicting [`Run`](/docs/api-reference/workflow-api/get-run) rather than a bare `{ runId }`, so a duplicate can `await conflict.status`, `await conflict.returnValue`, or `await conflict.cancel()` directly. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
183
185
  - **Support for more frameworks.** [React Router](/docs/getting-started/react-router) (v7 and v8, via Nitro) and [NestJS](/docs/getting-started/nestjs) are now supported.
184
186
  - **A misrouted delivery no longer fails a run.** Runs are pinned to the deployment that created them. A delivery that arrives at a different deployment is now re-routed to the pinned one with backoff instead of failing, and only gives up with the new [`DEPLOYMENT_MISMATCH`](/docs/errors/deployment-mismatch) error once the recovery budget is spent. Nothing executes on the wrong deployment while this happens. In 4.x the same situation surfaced as an unexplained decryption failure.
@@ -199,7 +201,7 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
199
201
  | `hook.getConflict()` resolves with a `Run` | Replace `conflict.runId` round trips through `getRun()` inside a step with the accessors on `conflict` directly. `conflict.runId` still works. |
200
202
  | `hook.metadata` is a Promise on hooks returned by `getHookByToken()` and `resumeHook()` | Write `await hook.metadata` where you read it. Hydrating metadata can add network round trips, and those are now paid only by code that reads it, so the lookup itself is a single read. The `Hook` type is exported from `workflow/api`; the World-level record from `world.hooks.getByToken()` is unchanged. See [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token). |
201
203
  | `experimental_setAttributes` removed | Import `setAttributes` instead, and `SetAttributesOptions` in place of `ExperimentalSetAttributesOptions`. The deprecated aliases are gone. |
202
- | [`getWorld()`](/docs/api-reference/workflow-runtime/get-world), [`getWorldHandlers()`](/docs/api-reference/workflow-runtime/get-world-handlers), and [`createWorld()`](/docs/api-reference/workflow-runtime/create-world) are async | They resolve a `Promise` now, so await the call before reaching for anything on it: `const world = await getWorld();` then `await world.start?.();`. This mainly affects the `instrumentation.ts` bootstrap that starts a World with background workers, such as the [Postgres World](/worlds/postgres#starting-the-world). Under TypeScript the old shape fails the build; in plain JavaScript it does not, and `.start` reads as `undefined` on a promise, so the worker never starts and nothing is logged. Writing `await getWorld()` is also valid on 4.x, so the change can be made before upgrading. |
204
+ | [`getWorld()`](/docs/api-reference/workflow-runtime/get-world), [`getWorldHandlers()`](/docs/api-reference/workflow-runtime/get-world-handlers), and [`createWorld()`](/docs/api-reference/workflow-runtime/create-world) are async | They resolve a `Promise` now, so await the call before reaching for anything on it: `const world = await getWorld();` then `await world.start?.();`. This mainly affects the `instrumentation.ts` bootstrap that starts a World with background workers, such as the [Postgres World](/worlds/postgres#start-the-world-when-your-server-starts). Under TypeScript the old shape fails the build; in plain JavaScript it does not, and `.start` reads as `undefined` on a promise, so the worker never starts and nothing is logged. Writing `await getWorld()` is also valid on 4.x, so the change can be made before upgrading. |
203
205
  | Duplicate step or workflow IDs fail the build | 4.x resolved collisions across non-exported workspace files last-write-wins. If you start encountering build failures after upgrading, rename the colliding functions. |
204
206
  | The generated bundles are renamed, and the step route is gone | Only affects apps that wire the output of `workflow build` into their own server instead of using a framework integration. `flow.js` and `webhook.js` are now `flow.mjs` and `webhook.mjs` with named exports only, so a default import resolves to `undefined`. `step.js` became `__step_registrations.mjs`, an internal module that `flow.mjs` imports: delete the `POST /.well-known/workflow/v1/step` route rather than repointing it, because the flow handler now serves step deliveries too. See [Framework integrations](/docs/how-it-works/framework-integrations). |
205
207
  | Default trace mode is `linked` | Update dashboards that assume one trace per run, or set `WORKFLOW_TRACE_MODE=continuous`. |