workflow 5.3.0 → 5.5.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.
- package/dist/observability.d.ts +1 -1
- package/dist/observability.d.ts.map +1 -1
- package/dist/observability.js +2 -2
- package/docs/ai/chat-session-modeling.mdx +1 -1
- package/docs/ai/resumable-streams.mdx +1 -1
- package/docs/api-reference/workflow/create-hook.mdx +3 -3
- package/docs/api-reference/workflow/create-webhook.mdx +1 -1
- package/docs/api-reference/workflow/fetch.mdx +1 -5
- package/docs/api-reference/workflow/get-step-metadata.mdx +19 -0
- package/docs/api-reference/workflow-ai/durable-agent.mdx +2 -1
- package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +4 -4
- package/docs/api-reference/workflow-api/get-hook-by-token.mdx +2 -2
- package/docs/api-reference/workflow-api/resume-hook.mdx +2 -2
- package/docs/api-reference/workflow-api/start.mdx +12 -8
- package/docs/api-reference/workflow-errors/hook-conflict-error.mdx +2 -2
- package/docs/api-reference/workflow-errors/index.mdx +1 -1
- package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +1 -1
- package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +1 -1
- package/docs/api-reference/workflow-errors/workflow-start-error.mdx +5 -5
- package/docs/api-reference/workflow-next/with-workflow.mdx +57 -0
- package/docs/api-reference/workflow-observability/create-state-resolver.mdx +56 -0
- package/docs/api-reference/workflow-observability/index.mdx +5 -0
- package/docs/api-reference/workflow-observability/meta.json +1 -0
- package/docs/api-reference/workflow-runtime/world/storage.mdx +2 -3
- package/docs/changelog/attributes-mvp.mdx +1 -1
- package/docs/changelog/batched-event-writes.mdx +0 -2
- package/docs/changelog/eager-processing.mdx +3 -1
- package/docs/changelog/lazy-event-creation.md +1 -1
- package/docs/changelog/spec-9.mdx +268 -120
- package/docs/changelog/step-message-ownership.mdx +2 -7
- package/docs/configuration/build-and-diagnostics.mdx +2 -0
- package/docs/configuration/cli-and-web-ui.mdx +13 -2
- package/docs/configuration/framework-options.mdx +7 -0
- package/docs/configuration/runtime-tuning.mdx +26 -74
- package/docs/configuration/worlds.mdx +55 -23
- package/docs/cookbook/advanced/child-workflows.mdx +126 -186
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +1 -1
- package/docs/cookbook/common-patterns/idempotency.mdx +2 -2
- package/docs/cookbook/common-patterns/sequential-and-parallel.mdx +1 -1
- package/docs/cookbook/common-patterns/workflow-composition.mdx +5 -5
- package/docs/cookbook/integrations/ai-sdk.mdx +2 -2
- package/docs/errors/corrupted-event-log.mdx +1 -1
- package/docs/errors/fetch-in-workflow.mdx +15 -35
- package/docs/errors/hook-force-claimed.mdx +1 -1
- package/docs/errors/runtime-decryption-failed.mdx +1 -1
- package/docs/foundations/errors-and-retries.mdx +3 -1
- package/docs/foundations/hooks.mdx +1 -1
- package/docs/foundations/idempotency.mdx +11 -11
- package/docs/foundations/serialization.mdx +80 -0
- package/docs/foundations/starting-workflows.mdx +3 -7
- package/docs/getting-started/next.mdx +2 -0
- package/docs/how-it-works/event-sourcing.mdx +2 -2
- package/docs/observability/index.mdx +2 -0
- package/docs/whats-new.mdx +4 -4
- package/docs/worlds/building-a-world.mdx +22 -7
- package/docs/worlds/local.mdx +11 -7
- package/docs/worlds/postgres.mdx +17 -24
- package/docs/worlds/upgrading-to-v5.mdx +3 -3
- package/docs/worlds/vercel.mdx +13 -12
- package/package.json +14 -14
|
@@ -74,7 +74,7 @@ Any number of runs can force the same token at once without leaving the token or
|
|
|
74
74
|
|
|
75
75
|
## Runs that cannot be taken from
|
|
76
76
|
|
|
77
|
-
A run that was started at a Workflow spec version below 8 (an older SDK release, a Python SDK run, or a deployment with `
|
|
77
|
+
A run that was started at a Workflow spec version below 8 (an older SDK release, a Python SDK run, or a deployment with `WORKFLOW_SPEC_VERSION` set below 8) would never learn that its hook was disposed. The World declines to take its token: the forced hook rejects with the ordinary [`HookConflictError`](/docs/errors/hook-conflict), whose `conflictingRunId` names that run, and the run keeps receiving its payloads. Handle it like any other conflict, for example by [delegating to the active run](/docs/errors/hook-conflict#delegate-to-the-active-run). A finished run holding a retained token is taken over at any version.
|
|
78
78
|
|
|
79
79
|
## Deciding who takes over
|
|
80
80
|
|
|
@@ -31,7 +31,7 @@ The thrown `RuntimeDecryptionError` carries a small `context` object with diagno
|
|
|
31
31
|
|
|
32
32
|
Common causes, in rough order of likelihood:
|
|
33
33
|
|
|
34
|
-
1. **Ciphertext mutation or truncation in transit.** The encrypted payload reached the SDK with bytes that differ from what storage holds. Possible sources include a truncated HTTP response from a
|
|
34
|
+
1. **Ciphertext mutation or truncation in transit.** The encrypted payload reached the SDK with bytes that differ from what storage holds. Possible sources include a truncated HTTP response from a world backend ref endpoint, an edge-cache miss returning a partial 200, or a proxy drop during streaming. A truncated body whose first 4 bytes happen to still spell `encr` produces the exact "auth tag mismatch" symptom.
|
|
35
35
|
2. **Key resolution mismatch.** The key used to decrypt is not the key that was used to encrypt, e.g. the run's `deploymentId` was not threaded through key resolution and the SDK fell back to the wrong deployment's key material.
|
|
36
36
|
3. **Malformed encrypted envelope.** The envelope is too short to contain the GCM nonce (12 bytes) and auth tag (16 bytes), so decryption is rejected before it begins.
|
|
37
37
|
|
|
@@ -136,7 +136,9 @@ callApi.maxRetries = 5; // Retry up to 5 times on failure (6 total attempts)
|
|
|
136
136
|
<Callout type="info">
|
|
137
137
|
Setting <code>maxRetries = 0</code> means the step will run once but will not
|
|
138
138
|
be retried on failure. The default is <code>maxRetries = 3</code>, meaning the
|
|
139
|
-
step can run up to 4 times total (1 initial attempt + 3 retries).
|
|
139
|
+
step can run up to 4 times total (1 initial attempt + 3 retries). Inside the
|
|
140
|
+
step, <code>getStepMetadata().maxAttempts</code> is that total, so a step can
|
|
141
|
+
<a href="/docs/api-reference/workflow/get-step-metadata#example-handle-the-last-attempt-differently">handle its last attempt differently</a>.
|
|
140
142
|
</Callout>
|
|
141
143
|
|
|
142
144
|
## Serialization failures
|
|
@@ -112,7 +112,7 @@ 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. A run started with [`start({
|
|
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
116
|
|
|
117
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).
|
|
118
118
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Idempotency
|
|
3
|
-
description: Make step retries safe, and start a workflow run at most once per key with start({
|
|
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
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:
|
|
@@ -71,7 +71,7 @@ export async function POST(request: Request) {
|
|
|
71
71
|
|
|
72
72
|
try {
|
|
73
73
|
const run = await start(processOrder, [orderId], {
|
|
74
|
-
|
|
74
|
+
experimental_hook: { token: `order:${orderId}` }, // [!code highlight]
|
|
75
75
|
});
|
|
76
76
|
return Response.json({ runId: run.runId, duplicate: false });
|
|
77
77
|
} catch (error) {
|
|
@@ -81,7 +81,7 @@ export async function POST(request: Request) {
|
|
|
81
81
|
}
|
|
82
82
|
```
|
|
83
83
|
|
|
84
|
-
`start({
|
|
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
85
|
|
|
86
86
|
### Start or route to the owner
|
|
87
87
|
|
|
@@ -99,7 +99,7 @@ export async function POST(request: Request) {
|
|
|
99
99
|
let owner: string | undefined;
|
|
100
100
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
101
101
|
try {
|
|
102
|
-
const run = await start(processOrder, [orderId, note], {
|
|
102
|
+
const run = await start(processOrder, [orderId, note], { experimental_hook: { token } });
|
|
103
103
|
return Response.json({ runId: run.runId, started: true });
|
|
104
104
|
} catch (error) {
|
|
105
105
|
if (!HookConflictError.is(error)) throw error;
|
|
@@ -152,7 +152,7 @@ export async function processOrder(orderId: string, note: string) {
|
|
|
152
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
153
|
- Payloads resumed before the workflow opens the Hook are kept, and are delivered in order once it does.
|
|
154
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({
|
|
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
156
|
|
|
157
157
|
### Keep the token after the run ends
|
|
158
158
|
|
|
@@ -166,7 +166,7 @@ import { processOrder } from "./workflows/process-order";
|
|
|
166
166
|
declare const orderId: string; // @setup
|
|
167
167
|
|
|
168
168
|
const run = await start(processOrder, [orderId, ""], {
|
|
169
|
-
|
|
169
|
+
experimental_hook: {
|
|
170
170
|
token: `order:${orderId}`,
|
|
171
171
|
experimental_minRetention: "30 days", // [!code highlight]
|
|
172
172
|
metadata: { orderId },
|
|
@@ -222,17 +222,17 @@ Disposing the start Hook ends the run's idempotency: from the end of that block,
|
|
|
222
222
|
|
|
223
223
|
### When `start()` can't confirm the outcome
|
|
224
224
|
|
|
225
|
-
If `start({
|
|
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
226
|
|
|
227
227
|
### World support
|
|
228
228
|
|
|
229
|
-
`start({
|
|
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
230
|
|
|
231
231
|
| World | Support |
|
|
232
232
|
| --- | --- |
|
|
233
233
|
| [Local World](/worlds/local) | Supported. |
|
|
234
|
-
| [Postgres World](/worlds/postgres) |
|
|
235
|
-
| [Vercel World](/worlds/vercel) |
|
|
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
236
|
|
|
237
237
|
See [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) for the full option reference.
|
|
238
238
|
|
|
@@ -278,7 +278,7 @@ export async function processOrder(orderId: string): Promise<OrderResult> {
|
|
|
278
278
|
Outside the workflow, try `resumeHook()` first, and on `HookNotFoundError` call `start()` and retry the resume until the new run registers its hook.
|
|
279
279
|
|
|
280
280
|
<Callout type="warn">
|
|
281
|
-
Unlike `start({
|
|
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.
|
|
282
282
|
</Callout>
|
|
283
283
|
|
|
284
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).
|
|
@@ -116,10 +116,90 @@ async function updateUserStep(user: { id: string; name: string; email: string })
|
|
|
116
116
|
}
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
+
<Callout>
|
|
120
|
+
Deeply frozen values are the exception: they come back frozen, and are stored by reference. See [Frozen values](#frozen-values).
|
|
121
|
+
</Callout>
|
|
122
|
+
|
|
119
123
|
**Custom classes:**
|
|
120
124
|
|
|
121
125
|
- Class instances that implement [`WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE`](#custom-class-serialization)
|
|
122
126
|
|
|
127
|
+
## Frozen values
|
|
128
|
+
|
|
129
|
+
State that grows across steps, such as a conversation history passed into every step, is stored again by every step that receives it, so total storage grows with the square of the number of steps. If you pass that state as a **deeply frozen** value, Workflow stores each step's change instead:
|
|
130
|
+
|
|
131
|
+
- A step input that holds a value Workflow already stored is written as a reference to it, about 80 bytes.
|
|
132
|
+
- A step output is written as its change from the stored value it was made from, for example "the previous history plus two messages".
|
|
133
|
+
|
|
134
|
+
Workflow finds what changed by identity. A frozen object can't change, so an object that appears in both versions is unchanged and needs no comparison.
|
|
135
|
+
|
|
136
|
+
The easiest way to make deeply frozen values is [immer](https://immerjs.github.io/immer/)'s `produce`, which freezes its results and shares every unchanged object with the previous value:
|
|
137
|
+
|
|
138
|
+
```typescript lineNumbers
|
|
139
|
+
import { produce } from "immer";
|
|
140
|
+
|
|
141
|
+
type Message = { role: "user" | "assistant"; content: string };
|
|
142
|
+
declare function reply(history: readonly Message[], text: string): Promise<string>; // @setup
|
|
143
|
+
declare const messages: AsyncIterable<{ text: string }>; // @setup
|
|
144
|
+
|
|
145
|
+
async function turn(history: readonly Message[], text: string) {
|
|
146
|
+
"use step";
|
|
147
|
+
const answer = await reply(history, text);
|
|
148
|
+
return produce(history, (draft) => {
|
|
149
|
+
draft.push({ role: "user", content: text }, { role: "assistant", content: answer });
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function chat() {
|
|
154
|
+
"use workflow";
|
|
155
|
+
let history: readonly Message[] = Object.freeze([]);
|
|
156
|
+
for await (const { text } of messages) {
|
|
157
|
+
history = await turn(history, text); // each input is a reference, each output a change
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Without immer, freeze every object you create, and reuse the frozen objects you didn't change:
|
|
163
|
+
|
|
164
|
+
```typescript lineNumbers
|
|
165
|
+
type Message = { role: "user" | "assistant"; content: string };
|
|
166
|
+
declare const history: readonly Message[]; // @setup
|
|
167
|
+
declare const text: string; // @setup
|
|
168
|
+
|
|
169
|
+
const next = Object.freeze([
|
|
170
|
+
...history, // unchanged messages, already frozen, reused as they are
|
|
171
|
+
Object.freeze({ role: "user" as const, content: text }),
|
|
172
|
+
]);
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Rules
|
|
176
|
+
|
|
177
|
+
- **Frozen values come back frozen.** Changing one in place throws a `TypeError`. Make the next version with `produce` (or a new frozen copy) instead.
|
|
178
|
+
- **`Date`, `Map`, `Set` and byte arrays are trusted.** Inside a frozen value they are treated as unchanging, even though JavaScript lets you change a `Date` or a `Map` after freezing. Change them only inside `produce` (see the note below).
|
|
179
|
+
- **Only deeply frozen plain data counts.** A value that isn't frozen, is only frozen at the top, or holds a class instance or another custom type, including inside a `Map` or `Set`, is stored in full.
|
|
180
|
+
- **Keep immer's auto-freeze on.** immer freezes what `produce` returns by default. With `setAutoFreeze(false)` its results aren't frozen, so they're stored in full every time: still correct, but the savings are gone. Turning it off is also how to opt a codebase out of storing values by reference.
|
|
181
|
+
- **A new value is linked by the objects it shares.** A value whose objects are all new, for example one made only of numbers and strings, is stored in full each time. That's fine for small values.
|
|
182
|
+
- **Some payloads are always stored in full:** run inputs, including values passed to another run through `start()`, workflow return values (so `run.returnValue` reads them as usual), and hook payloads.
|
|
183
|
+
- **Parallel steps.** Passing a frozen value to several parallel steps writes, in each step's input, a small reference if a step returned it unchanged, or only its change if you made the next version in workflow code with `produce` or `Object.freeze`. A frozen value built entirely in workflow code, sharing no objects with a step's output, is written in full to each input, because one step's input can't refer to another's.
|
|
184
|
+
- **A value is written whole again from time to time:** once its changes since the last whole copy pass half its size (for growing state, each time it doubles), or after 1,000 changes. That bounds how much a replay has to apply to about the value's own size.
|
|
185
|
+
- With `WORKFLOW_VM=quickjs`, values are stored in full, because that VM can't read references yet.
|
|
186
|
+
|
|
187
|
+
<Callout type="warn">
|
|
188
|
+
`Object.freeze` doesn't stop a `Map`, `Set` or `Date` from changing through its own methods (`map.set()`, `set.add()`, `date.setTime()`), and byte arrays can't be frozen at all. immer's `produce` makes the Maps and Sets it returns throw on those methods, but `Object.freeze` doesn't. Changing a `Date`, `Map`, `Set` or byte array in place inside a frozen value, for example with `date.setTime()`, `map.set()` or `bytes[0] = 1`, isn't recorded. A step that runs in the same invocation may still see the change, but a retried or queued step, and every replay, rebuilds the value from the stored records and sees the original. Make the change inside `produce` instead. Immer drafts a `Map` or `Set` once you call its `enableMapSet()`, and copies it when you change it. It doesn't draft a `Date` or a byte array, so replace those with new ones:
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
import { enableMapSet, produce } from "immer";
|
|
192
|
+
declare const state: { updatedAt: Date; tags: ReadonlySet<string> }; // @setup
|
|
193
|
+
|
|
194
|
+
enableMapSet(); // once, before producing state that holds a Map or Set
|
|
195
|
+
|
|
196
|
+
const next = produce(state, (draft) => {
|
|
197
|
+
draft.updatedAt = new Date(); // not draft.updatedAt.setTime(Date.now())
|
|
198
|
+
draft.tags.add("urgent"); // immer copies the Set
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
</Callout>
|
|
202
|
+
|
|
123
203
|
## Streaming
|
|
124
204
|
|
|
125
205
|
`ReadableStream` and `WritableStream` are supported as serializable types with special handling. These streams can be passed between workflow and step functions while maintaining their streaming capabilities.
|
|
@@ -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.
|
|
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`)
|
|
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
|
|
@@ -308,6 +308,8 @@ Add the following to your `turbo.json`:
|
|
|
308
308
|
|
|
309
309
|
Without this configuration, you may experience intermittent issues where workflows fail to register properly on cache hits, while working correctly on cache misses.
|
|
310
310
|
|
|
311
|
+
If you set [`workflows.experimentalRoutePrefix`](/docs/api-reference/workflow-next/with-workflow#workflow-route-prefix), include the prefix in these globs (for example `app/dashboard/.well-known/workflow/**`).
|
|
312
|
+
|
|
311
313
|
### `start()` says it received an invalid workflow function
|
|
312
314
|
|
|
313
315
|
If you see this error:
|
|
@@ -304,7 +304,7 @@ A World that supports this returns the page in `events`, `cursor`, and `hasMore`
|
|
|
304
304
|
|
|
305
305
|
## Sealed positions (noop events)
|
|
306
306
|
|
|
307
|
-
Runs at `specVersion` 7 and above use a *sealed log*. The backend gives each write its position from a per-run sequencer **before** the write commits, so concurrent writers hold distinct positions and never race for a slot. New runs use this behavior by default. [`
|
|
307
|
+
Runs at `specVersion` 7 and above use a *sealed log*. The backend gives each write its position from a per-run sequencer **before** the write commits, so concurrent writers hold distinct positions and never race for a slot. New runs use this behavior by default. [`WORKFLOW_SPEC_VERSION=6`](/docs/configuration/runtime-tuning#workflow_spec_version) returns a deployment to the previous scheme. Every runtime reads a sealed log regardless, and a run's version is fixed at creation, so changing the setting never affects an in-flight run. However, a writer can claim a position and then stop because of a crashed process or canceled transaction. This leaves a hole that no writer will fill, and a hole looks like an event the reader failed to load.
|
|
308
308
|
|
|
309
309
|
The backend restores the dense log at read time by **sealing** these positions. Once a hole is provably abandoned, bounded by the commit time of later positions, the backend writes a `noop` event into it. Positions are assigned in order, so a committed later position proves how long the hole has been open. A `noop` occupies its position, and length-based completeness checks, cursors, and pagination all count it. It has no other effect:
|
|
310
310
|
|
|
@@ -372,7 +372,7 @@ All entities in the Workflow SDK use a consistent ID format: a 4-character prefi
|
|
|
372
372
|
|
|
373
373
|
An event ID is a **slot number**: the event's 1-based position in the run's event log, zero-padded to the same width as a ULID. The world assigns it when the event is published, so two writers racing to append never claim the same position and a rejected write leaves no gap behind. Slots are dense, and unique only within a run, so an event ID identifies an event only when paired with its `runId`.
|
|
374
374
|
|
|
375
|
-
Density is what lets a reader tell a complete log from an incomplete one by its length alone. A replay that loads a log with a position missing below the highest one it can see cannot tell an event that was never written from one it failed to read, so it fails the run with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) rather than replay across the hole.
|
|
375
|
+
Density is what lets a reader tell a complete log from an incomplete one by its length alone. A replay that loads a log with a position missing below the highest one it can see cannot tell an event that was never written from one it failed to read, so it fails the run with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) rather than replay across the hole.
|
|
376
376
|
|
|
377
377
|
A slot ID carries no timestamp. Zero-padded decimal digits are a subset of the ULID alphabet, so a slot ID passes ULID validation and sorts correctly, but decoding its first 48 bits yields the Unix epoch instead of a creation time. Read `createdAt` on the event when you need to know when it was written, and don't decode the time from an `evnt_` ID you get back from an API, a log line, or a cursor.
|
|
378
378
|
|
|
@@ -65,6 +65,8 @@ npx workflow inspect run <run_id> --backend vercel --url
|
|
|
65
65
|
The Workflow SDK CLI can inspect data from any [World](/docs/deploying). By default, it inspects data in your local development environment. For example, if you are using Next.js to develop workflows locally, the
|
|
66
66
|
CLI will find the data in your `.next/workflow-data/` directory.
|
|
67
67
|
|
|
68
|
+
On the Local World, the CLI and web UI also read the app's queue key from that directory and send it with every delivery to the app, for example when they start or recreate a run. Run them from the app's project directory (or set `WORKFLOW_LOCAL_DATA_DIR` to the app's data directory), and keep them on the same release as the app's `@workflow/world-local`. See [`WORKFLOW_QUEUE_AUTH`](/worlds/local#workflow_queue_auth).
|
|
69
|
+
|
|
68
70
|
If you're deploying workflows to a production environment, but want to inspect the data by using the CLI, you can specify the world you are using by setting the `--backend` flag to your world's name or package name, e.g. `vercel`.
|
|
69
71
|
|
|
70
72
|
<Callout>
|
package/docs/whats-new.mdx
CHANGED
|
@@ -48,9 +48,9 @@ The largest change in v5 has no API surface: the runtime does far less work per
|
|
|
48
48
|
|
|
49
49
|
**Resuming a hook takes one round trip instead of two.** `resumeHook()` writes the `hook_received` event and dispatches the queue message concurrently, with a `(runId, resumeId)` dedup constraint keeping the two writers converging on exactly one event. See [Resilient hook resumption](/docs/changelog/resilient-resume).
|
|
50
50
|
|
|
51
|
-
**A suspension's writes go out as one batch.** The `step_created` and `wait_created` events a suspension produces are folded into a single durable write with a per-event outcome, instead of one request each, and a fan-out's inline step bodies start straight off that commit rather than each claiming its step first. This engages on Worlds that implement the batch API
|
|
51
|
+
**A suspension's writes go out as one batch.** The `step_created` and `wait_created` events a suspension produces are folded into a single durable write with a per-event outcome, instead of one request each, and a fan-out's inline step bodies start straight off that commit rather than each claiming its step first. This engages on Worlds that implement the batch API. See [Batched event writes](/docs/changelog/batched-event-writes).
|
|
52
52
|
|
|
53
|
-
**Concurrent writers no longer compete for a position in the log.** Each event's position used to be claimed by the write that filled it, so a wide fan-out serialized on that claim. Positions are now handed out ahead of the commit, which is what makes the fan-out above cheap. The cost is a position whose writer dies, which the backend closes with a `noop` event that replay steps over. Nothing about this is visible from workflow code; [`
|
|
53
|
+
**Concurrent writers no longer compete for a position in the log.** Each event's position used to be claimed by the write that filled it, so a wide fan-out serialized on that claim. Positions are now handed out ahead of the commit, which is what makes the fan-out above cheap. The cost is a position whose writer dies, which the backend closes with a `noop` event that replay steps over. Nothing about this is visible from workflow code; [`WORKFLOW_SPEC_VERSION=6`](/docs/configuration/runtime-tuning#workflow_spec_version) creates new runs on the previous scheme, and existing runs keep the scheme they were created on.
|
|
54
54
|
|
|
55
55
|
**Payloads are compressed** before they are encrypted and sent to the API. Repetitive payloads compress heavily; AI token streams average around 80% smaller. That is less stored data and less to move over the network.
|
|
56
56
|
|
|
@@ -179,7 +179,7 @@ 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 `
|
|
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
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.
|
|
184
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).
|
|
185
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.
|
|
@@ -188,7 +188,7 @@ All three first-party Worlds now implement it: Vercel accepts up to 30 days, and
|
|
|
188
188
|
- **An experimental QuickJS VM engine.** Set [`WORKFLOW_VM=quickjs`](/docs/configuration/runtime-tuning#workflow_vm) to run workflow functions in a QuickJS VM compiled to WebAssembly instead of `node:vm`, for platforms that do not provide `node:vm`. Replay semantics are identical, but the available globals are not: check the differences before switching an existing deployment. By default, an encrypted QuickJS run that passes 1,000 events resumes from a VM-memory snapshot instead of replaying its full event log (see [`WORKFLOW_SNAPSHOT_THRESHOLD`](/docs/configuration/runtime-tuning#workflow_snapshot_threshold)).
|
|
189
189
|
- **Experimental dynamic workflows.** Pass workflow source as a string to `start()` to run orchestration assembled after deployment over steps already deployed with your app. The code is stored with the run (encrypted on Vercel), so replays always execute the code the run started with. Off unless the deployment sets `WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS=1`. See [Dynamic Workflows](/docs/advanced/dynamic-workflows).
|
|
190
190
|
- **A WebSocket transport for event and stream writes** on the Vercel World, which sends a run's event writes and stream writes over a socket instead of one HTTP request each. It is the default; set [`WORKFLOW_EVENTS_TRANSPORT=http`](/worlds/vercel#workflow_events_transport) or [`WORKFLOW_STREAMS_TRANSPORT=http`](/worlds/vercel#workflow_streams_transport) to opt out. Tracing is unaffected: each write still emits an `http POST` client span, synthesized around the frame, with the transport on `workflow.events.transport`.
|
|
191
|
-
- **`await run.returnValue` waits instead of polling.** Reading a run's result long-polls the World until the run reaches a terminal status, rather than asking again on a fixed interval. A result is observed as soon as it exists, and an idle wait costs one open request instead of a request per tick. Worlds that do not implement the long poll keep the interval.
|
|
191
|
+
- **`await run.returnValue` waits instead of polling.** Reading a run's result long-polls the World until the run reaches a terminal status, rather than asking again on a fixed interval. A result is observed as soon as it exists, and an idle wait costs one open request instead of a request per tick. Worlds that do not implement the long poll keep the interval. Since 5.4.0, a parent awaiting a child run it started doesn't poll at all: it suspends on a system hook the child resumes when it finishes, so the wait uses no compute or worker slot. See [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits).
|
|
192
192
|
- **An event arriving mid-replay no longer fails the run.** A hook resume or step completion landing while a replay is in flight used to be able to fail it with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log). Writes now come back with the events the replay had not seen, and the event is held for whichever part of the workflow awaits it. A run only fails when the log is genuinely missing a position.
|
|
193
193
|
|
|
194
194
|
## Breaking changes
|
|
@@ -67,7 +67,7 @@ interface World extends Storage, Queue, Streamer {
|
|
|
67
67
|
|
|
68
68
|
`specVersion` is required. See [Declaring the spec version](#declaring-the-spec-version).
|
|
69
69
|
|
|
70
|
-
The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue supports `maxConcurrency`-limited consumption, which `WORKFLOW_SEQUENTIAL_REPLAYS=1` uses. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence). Set `atomicStartHook.active` only when the World implements [atomic start Hook admission](#optional-atomic-start-hook-admission). Without it, `start({
|
|
70
|
+
The optional `capabilities` object advertises additional behavior, and every capability **fails closed**. A missing member means "unsupported," and the runtime keeps its conservative behavior. Set `hookRetention.active` to `true` only when the World implements hook token retention. Set `maxConcurrency` only when the World's queue supports `maxConcurrency`-limited consumption, which `WORKFLOW_SEQUENTIAL_REPLAYS=1` uses. Set `hookForceClaim` only when the World implements [hook token takeover](/worlds/upgrading-to-v5#new-optional-surface). Without it, `createHook({ experimental_force: true })` fails the workflow when it registers the hook. Set `dynamicWorkflowCode` only when the World persists `dynamicWorkflowCode` from `run_created` (and from a `run_started` that creates the run), echoes it on the created run, and returns it from `runs.get` with `resolveData: 'all'`. Without it, `start()` refuses [dynamic workflows](/docs/advanced/dynamic-workflows). The code is sent inline unless the World also implements `uploadDynamicWorkflowCode` for large definitions. Set `inBandFence` only when the World implements the [in-band writer fence](#optional-the-in-band-writer-fence). Set `atomicStartHook.active` only when the World implements [atomic start Hook admission](#optional-atomic-start-hook-admission). Without it, `start({ experimental_hook })` throws before it enqueues anything.
|
|
71
71
|
|
|
72
72
|
[Slot-numbered event IDs](#event-id-allocation) are a contract requirement rather than a capability, so there is no flag or fallback path.
|
|
73
73
|
|
|
@@ -99,9 +99,9 @@ export function createWorld(): World {
|
|
|
99
99
|
|
|
100
100
|
The runtime checks this before it creates or replays anything and throws if the version is outside the range it supports, naming both the range and what your World declared. A version below the range means your World allocates event IDs the runtime cannot read positions out of; above it means your World speaks a protocol this runtime has not learned.
|
|
101
101
|
|
|
102
|
-
`mintedSpecVersion()` returns the current spec version, or the
|
|
102
|
+
`mintedSpecVersion()` returns the current spec version, or the version [`WORKFLOW_SPEC_VERSION`](/docs/configuration/runtime-tuning#workflow_spec_version) selects. Call it inside `createWorld()` so a process can create Worlds with different settings. It reads `process.env` by default; in a host without `process`, such as a browser, pass the environment as its argument.
|
|
103
103
|
|
|
104
|
-
Calling it keeps the check passing across upgrades. It moves with the `@workflow/world` version your package resolves, so a spec bump raises your declaration and the runtime's requirement together. A hard-coded number, or `SPEC_VERSION_CURRENT`, which does not follow `
|
|
104
|
+
Calling it keeps the check passing across upgrades. It moves with the `@workflow/world` version your package resolves, so a spec bump raises your declaration and the runtime's requirement together. A hard-coded number, or `SPEC_VERSION_CURRENT`, which does not follow `WORKFLOW_SPEC_VERSION`, leaves your World out of step. Keep `@workflow/world` in the same release channel as the `workflow` version your users install. See [Spec versions](/worlds/upgrading-to-v5#spec-versions) for what each version requires of a World.
|
|
105
105
|
|
|
106
106
|
## The event log model
|
|
107
107
|
|
|
@@ -236,7 +236,7 @@ Spec version 7 supports one alternative to allocate-at-commit for Worlds whose s
|
|
|
236
236
|
|
|
237
237
|
The runtime skips `noop` events during replay. It never delivers them to a consumer or uses them to advance the deterministic clock, so a sealed log replays identically to one whose writers filled the holes. `noop` isn't user-creatable and is never sent to `events.create()`. Only your read path may write one. Worlds that allocate at the commit, through a synchronous counter or unique-constraint append, maintain perfect density and don't need sealing. `world-local` and `world-postgres` never seal, and a World that allocates at the commit is spec 7 compliant without additional work.
|
|
238
238
|
|
|
239
|
-
The version a World stamps comes from `mintedSpecVersion()`: 8 by default or the
|
|
239
|
+
The version a World stamps comes from `mintedSpecVersion()`: 8 by default, or the version [`WORKFLOW_SPEC_VERSION`](/docs/configuration/runtime-tuning#workflow_spec_version) selects, such as the slot-identity version (6). Declare `mintedSpecVersion()` instead of a literal so your World moves with the fleet. A runtime other than the one that created a spec 7 run may read it, so readers must understand `noop` before anything stamps 7 in that environment.
|
|
240
240
|
|
|
241
241
|
`events.create()` params carry `eventCount`: how many events the writer held in the log it replayed from, which is the position it expects to land on minus one. Attempt `eventCount + 1`. When that position is taken, **do not reject the write**. Advance to the next free position, commit there, and return the events occupying the positions you skipped over on the success response, in `events` with a matching `cursor` and `hasMore`. The writer merges them into its own log and replays once, rather than paying a second round trip to discover it was behind. A caller with a stale count is the normal case for a fan-out, and rejecting it would serialize writes the runtime issues in parallel.
|
|
242
242
|
|
|
@@ -296,21 +296,21 @@ The conformance suite in [`packages/world/src/test-support/in-band-fence-conform
|
|
|
296
296
|
|
|
297
297
|
### Optional: atomic start Hook admission
|
|
298
298
|
|
|
299
|
-
[`start({
|
|
299
|
+
[`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) makes a start idempotent on a Hook token, and gives the run a **start Hook** that can be resumed from the moment the run is admitted. `start()` enqueues the candidate run first and then writes `run_created`; the queue consumer's `run_started` carries the same request in `eventData.startHook`, and either write may reach the World first. Declare `capabilities.atomicStartHook: { active: true }` when `events.create()` implements all of the following for a `run_created`, or a `run_started` that creates the run, carrying `eventData.startHook = { token, tokenRetentionUntil?, metadata? }`:
|
|
300
300
|
|
|
301
301
|
- **Atomic admission.** Claim the token, record the decision, and create the start Hook as one atomic step. A run must never exist for a candidate that was refused, and a crash partway through must be recoverable by retrying the candidate.
|
|
302
302
|
- **One immutable decision per candidate `runId`.** Every later attempt for the same `runId`, through either write, returns the first decision even if the token has since changed hands: an accepted candidate returns its run (never `EntityConflictError`), and a refused one throws `HookConflictError` with the same `conflictingRunId`.
|
|
303
303
|
- **The start Hook exists from admission.** Its id is `startHookId(runId)` from `@workflow/world`, and it is an ordinary Hook record with the start's `token`, `metadata` and `tokenRetentionUntil`, and `isWebhook: false`. `hooks.getByToken()` and `hooks.get()` return it as soon as admission is durable. `run_created` stands for its `hook_created`: never write a `hook_created` for it, and refuse a `hook_created` whose `correlationId` is `startHookId(runId)` with a 400-class validation error.
|
|
304
304
|
- **Echo.** The run returned from `run_created`, `run_started` and `runs.get` carries `startHook`, including its `hookId`. Keep `token`, `hookId` and `tokenRetentionUntil` in the `run_created` event's `eventData.startHook` (you may drop `metadata` there): the runtime binds the workflow's `createHook({ token })` to the start Hook from it on every replay.
|
|
305
305
|
- **Deliveries to a pending run.** Accept `hook_received` for `startHookId(runId)` while the run is `pending` or `running` (ordinary Hooks stay running-only), and wake the run as for any resume. Never commit a delivery before the run's `run_created` event. If your World admits the run in more than one write and the run doesn't exist yet when a delivery arrives, wait briefly, then answer a retryable error with a `retryAfter` rather than not found.
|
|
306
|
-
- **Ordinary lifecycle.** From then on the start Hook behaves like a Hook the run created. Another run's `start({
|
|
306
|
+
- **Ordinary lifecycle.** From then on the start Hook behaves like a Hook the run created. Another run's `start({ experimental_hook })` or `createHook()` with the token conflicts, naming the owner. `hook_disposed` for the start Hook frees the token at once, even when `tokenRetentionUntil` is set, and a later `createHook({ token })` in the run is an ordinary `hook_created`. At run end, release the Hook as for any other, or, with `tokenRetentionUntil`, keep it findable by `hooks.getByToken()` but refuse deliveries until that time.
|
|
307
307
|
- **Force claims.** A forced `createHook()` takes the start Hook like any other, including before the owning workflow opens it, and writes `hook_disposed` with `forceClaimedBy` for `startHookId(runId)` to the owner's log. If the owner's run does not exist yet and can still be created, answer a retryable refusal instead.
|
|
308
308
|
- **Orphans.** A candidate that was admitted but whose run was never created must not hold the token forever. A candidate older than `START_HOOK_CANDIDATE_MAX_AGE_MS` (the same bound `run_created` applies to client-minted run IDs) can never be created. While it can still be created, never release its token, and treat deliveries as for a pending run that doesn't exist yet. Once it can't, or once it is fenced, release the token and answer not found.
|
|
309
309
|
- **Permanent refusals.** A request you will never admit (an invalid retention, a candidate past the orphan bound) throws `WorkflowWorldError` with `code: START_HOOK_ADMISSION_REJECTED`, so the queued copy stops retrying. Every copy of the candidate must get the same answer. Set its `reason` to one of `invalid`, `expired`, `token_mismatch`, `ordinary_run` or `disabled` (`StartHookRejectionReason`), which `start()` and the queued copy record on their spans as `workflow.start_hook.rejection_reason`.
|
|
310
310
|
- **Cancelling an uncreated candidate.** A `run_cancelled` for a run ID with no run but an accepted decision fences the candidate (no copy can create it any more), releases its token as for an ended run, and throws `WorkflowWorldError` with `code: START_HOOK_CANDIDATE_CANCELLED`. With no decision, throw `WorkflowRunNotFoundError` as for any missing run.
|
|
311
311
|
- **Switching admission off.** If you can switch admission off, either record the refusal as the candidate's decision and answer `START_HOOK_ADMISSION_REJECTED`, or throw `WorkflowWorldError` with `code: START_HOOK_ADMISSION_DISABLED` and record nothing. The second is not final: `start()` reports it as `WorkflowStartError`, and the queued copy is redelivered, because another copy may be admitted once admission is back on.
|
|
312
312
|
|
|
313
|
-
`world-local
|
|
313
|
+
`world-local`, `world-postgres` and `world-vercel` declare it. The conformance suite in [`packages/world/src/test-support/atomic-start-hook-conformance.ts`](https://github.com/vercel/workflow/blob/main/packages/world/src/test-support/atomic-start-hook-conformance.ts) checks these rules against a World's storage.
|
|
314
314
|
|
|
315
315
|
## Queue interface
|
|
316
316
|
|
|
@@ -321,6 +321,10 @@ The Queue interface handles asynchronous workflow execution, including queued st
|
|
|
321
321
|
interface Queue {
|
|
322
322
|
getDeploymentId(): Promise<string>;
|
|
323
323
|
|
|
324
|
+
// How the runtime authenticates deliveries to the flow route. Optional:
|
|
325
|
+
// omitted means not checked. Required in SDK v6.
|
|
326
|
+
queueAuthMode?: 'loopback' | 'skip';
|
|
327
|
+
|
|
324
328
|
queue(
|
|
325
329
|
queueName: ValidQueueName,
|
|
326
330
|
message: QueuePayload,
|
|
@@ -354,6 +358,17 @@ interface Queue {
|
|
|
354
358
|
|
|
355
359
|
`meta.messageId` should be stable across redeliveries of one message. The optional `meta.deliveryCount` is 1 on a message's first delivery and increments on every redelivery; leave it `undefined` when your queue cannot say. The optional `meta.createdAt` is when the message was first enqueued, unchanged across its redeliveries.
|
|
356
360
|
|
|
361
|
+
### Authenticating deliveries
|
|
362
|
+
|
|
363
|
+
The Workflow SDK's flow route is mounted in the app like any other route, so a request from outside the app can reach it. Before it reads the body or touches any run, the runtime checks every request to that route against the World's `queueAuthMode` mode. The check runs in the flow route handler `@workflow/core` generates, not in `createQueueHandler()`, so a queue consumer's own route (served with `createQueueHandler()` and registered with `registerRoute()`) is not checked and must authenticate deliveries itself. The modes:
|
|
364
|
+
|
|
365
|
+
- `'loopback'`: for a queue that delivers back to the app's own flow route. The delivery must carry the app's queue key in the `QUEUE_AUTH_HEADER` (`x-workflow-auth`) header; a request without it gets a `401`, and no run is touched. "Loopback" means sent by the app's own processes, which share the key, not any request from `localhost`. The queue attaches the key to every delivery it sends, over HTTP or to an in-process handler, on every attempt. Set it when the delivery is sent, never store it with the message, and replace any copy a caller supplied in `opts.headers`. The runtime checks the key against the sources Worlds register with `setQueueAuthKeySource()` from `@workflow/utils`, one per data directory, accepting a key that matches any of them; when none is registered, it checks `getQueueAuthKey()`, a key held in memory by one process. `@workflow/world-local` registers the key in its data directory, which the app, the CLI and the web UI share (see [the Local World](/worlds/local#workflow_queue_auth)). A World whose queue reuses `@workflow/world-local`'s gets this for free. The mode is temporary: it exists while the Local World's queue delivers over the app's own HTTP route.
|
|
366
|
+
- `'skip'`: the runtime does not check. For a World whose platform guarantees that only its queue reaches the route, as the [Vercel World](/worlds/vercel#security) does with two layers: the route can be triggered only by Vercel Queues, and the handler receives only a message ID, and retrieves and leases the message through Vercel Queues. Declare `'skip'` only when both hold. `@workflow/world-postgres` declares it for now, until its messages are delivered in-process ([#5258](https://github.com/vercel/workflow/issues/5258)); its flow route accepts any well-formed request, so protect it at the network edge (see [the Postgres World](/worlds/postgres#protect-the-queue-route)).
|
|
367
|
+
|
|
368
|
+
A World that declares nothing is not checked, and the runtime logs a warning when its flow route starts (once, then at most once a minute when routes restart), saying the route is not authenticated and has to be protected at the network edge. The mode becomes required in SDK v6, so declare one now: `'loopback'` if the World's queue attaches the key, `'skip'` only when the route is protected as described above. Operators can turn the check off with [`WORKFLOW_QUEUE_AUTH=off`](/docs/configuration/runtime-tuning#workflow_queue_auth), except while dynamic workflows are enabled.
|
|
369
|
+
|
|
370
|
+
The runtime's `401` is marked: it carries the `x-workflow-auth-refused: 1` header (`QUEUE_AUTH_REFUSED_HEADER`) and `"code": "QUEUE_AUTH_REFUSED"` in its JSON body. A refused delivery carried a key other than the route's, for example one from before another process of the app wrote a new key. A queue that sees the marker (`isQueueAuthRefusal(response)` from `@workflow/utils`) should reload its key and retry at once if it changed, and otherwise retry a few times with a short backoff, then give the message up and log it once, rather than retry it for hours. A refused delivery reached no handler and touched no run, so retrying is safe, and it should not count as an attempt. `@workflow/world-local` gives up after 5 refusals its reload did not fix; a refusal followed by a new key is retried at once without counting, up to 16 times per message, after which it counts like any other. A `401` without the marker comes from something else in front of the app, such as a proxy, so keep retrying that one.
|
|
371
|
+
|
|
357
372
|
### Queue prefixes and delivery routes
|
|
358
373
|
|
|
359
374
|
A queue name is a prefix followed by an id. The Workflow SDK uses the prefix `__wkf_workflow_`, or `__{namespace}_wkf_workflow_` when a queue namespace is set. A library that keeps its own runs in a World and consumes its own messages, such as a durable agent harness, uses a namespace of its own (`__agent_wkf_workflow_session`) so that its messages never reach the Workflow SDK's handler, and the Workflow SDK's never reach it.
|
package/docs/worlds/local.mdx
CHANGED
|
@@ -54,6 +54,14 @@ Full base URL override for HTTPS or custom hostnames. Default: `http://localhost
|
|
|
54
54
|
|
|
55
55
|
Port resolution priority: `baseUrl` > `port` > `PORT` > auto-detected
|
|
56
56
|
|
|
57
|
+
### `WORKFLOW_QUEUE_AUTH`
|
|
58
|
+
|
|
59
|
+
Whether the flow route accepts only deliveries sent by the app's own processes. Default: `on`. Every delivery carries the app's queue key, and the route refuses a request without it with a `401` and touches no run.
|
|
60
|
+
|
|
61
|
+
The key is a random value in the file `queue-auth-key` in the [data directory](#data-directory-layout). The app writes a new one each time it starts, when it first uses its World and before it sends anything, so a restart needs no wait. A script that calls `start()` with the same data directory writes a new key the same way, and the app accepts it. The CLI and the web UI only read the key, so point them at the app's data directory (`WORKFLOW_LOCAL_DATA_DIR`). Several app processes on one data directory (PM2 with `-i N`, `node:cluster`, Nitro's `node-cluster` preset) end up on the newest key in the file.
|
|
62
|
+
|
|
63
|
+
A refused delivery is retried at once when the key in the file has changed, and otherwise a few times with a short backoff, then logged once and given up; its run is left as it was. Keep the CLI and the web UI on the same release as the app's `@workflow/world-local`: an older one sends no key. Set `off` on the app to accept deliveries from a process that cannot read its data directory, on a trusted machine only. `off` is refused while dynamic workflows are enabled. See [`WORKFLOW_QUEUE_AUTH`](/docs/configuration/runtime-tuning#workflow_queue_auth).
|
|
64
|
+
|
|
57
65
|
### `WORKFLOW_LOCAL_QUEUE_CONCURRENCY`
|
|
58
66
|
|
|
59
67
|
Maximum number of concurrent queue message handlers. Default: `1000`
|
|
@@ -62,12 +70,6 @@ Maximum number of concurrent queue message handlers. Default: `1000`
|
|
|
62
70
|
|
|
63
71
|
Maximum number of seconds a local queue message can stay hidden before the handler rechecks the run. Default: unlimited.
|
|
64
72
|
|
|
65
|
-
### `WORKFLOW_LOCAL_RUN_STATUS_POLL_INTERVAL_MS`
|
|
66
|
-
|
|
67
|
-
How often a wait for a terminal run status re-reads the run file, in milliseconds. Default: `100`.
|
|
68
|
-
|
|
69
|
-
`await run.returnValue` asks the World to wait for the run to finish. When the run and the caller share a process (the usual development server case), an in-process signal resolves the wait as soon as the run ends, and this interval never comes into play. The interval covers activity the signal cannot detect, primarily a second process awaiting a run over the same data directory, so it is set far below Workflow's own polling interval.
|
|
70
|
-
|
|
71
73
|
### `WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`
|
|
72
74
|
|
|
73
75
|
Maximum time in milliseconds to wait for a local queue handler to begin responding before redelivering the durable message. Default: `0` (no deadline).
|
|
@@ -151,6 +153,8 @@ Each run's event and step files are stored in their own directory (`events/<runI
|
|
|
151
153
|
|
|
152
154
|
A directory that mixes both layouts, or holds `.json` files in `events/` or `steps/` that the World did not write, is never deleted: starting fails with a `DataDirLayoutError` that lists the files.
|
|
153
155
|
|
|
156
|
+
The data directory also holds the app's queue key, `queue-auth-key` (see [`WORKFLOW_QUEUE_AUTH`](#workflow_queue_auth)). The file is readable and writable only by its owner (mode `0600`); Windows does not enforce that mode the same way, and the file gets the directory's permissions. The World writes a `.gitignore` containing `*` into the data directory when it has none, so neither the key nor the run data is committed, and never replaces one that is already there.
|
|
157
|
+
|
|
154
158
|
## Limitations
|
|
155
159
|
|
|
156
160
|
The Local World is designed for development, not production:
|
|
@@ -158,6 +162,6 @@ The Local World is designed for development, not production:
|
|
|
158
162
|
- **In-memory queue**: Workflow messages, including queued step invocations, do not persist across server restarts.
|
|
159
163
|
- **Filesystem storage**: Data is stored in local JSON files.
|
|
160
164
|
- **Single instance**: The Local World cannot handle distributed deployments.
|
|
161
|
-
- **
|
|
165
|
+
- **Minimal authentication**: The flow route accepts only deliveries carrying the app's queue key (see [`WORKFLOW_QUEUE_AUTH`](#workflow_queue_auth)), but nothing else is authenticated. Anyone who can read the data directory can read the key. The Local World is suitable only for local development.
|
|
162
166
|
|
|
163
167
|
For production deployments, use the [Vercel World](/worlds/vercel), which handles execution, persistence, multi-tenancy, scale, observability, and security for you on Vercel, or check out the [Postgres World](/worlds/postgres) - a tested reference implementation that implements the complete World spec and can be used to deploy workflows anywhere.
|