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
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Child Workflows
|
|
3
|
-
description: Spawn child workflows from a parent and wait for
|
|
3
|
+
description: Spawn child workflows from a parent and wait for them without polling.
|
|
4
4
|
type: guide
|
|
5
|
-
summary: Orchestrate independent child workflows from a parent
|
|
5
|
+
summary: Orchestrate independent child workflows from a parent with start() and await run.returnValue. The parent suspends on a system hook the child resumes when it finishes, so waiting costs no compute and never polls.
|
|
6
6
|
related:
|
|
7
7
|
- /docs/api-reference/workflow-api/start
|
|
8
8
|
---
|
|
9
9
|
|
|
10
10
|
<CopyPrompt
|
|
11
|
-
text="Refactor this workflow to use child workflows. Keep the parent as an exported `"use workflow"` function. Move independent units of durable work into separate exported child workflow functions. From the parent, call `start(childWorkflow, [args])` from `workflow/api`
|
|
11
|
+
text="Refactor this workflow to use child workflows. Keep the parent as an exported `"use workflow"` function. Move independent units of durable work into separate exported child workflow functions. From the parent, call `start(childWorkflow, [args])` from `workflow/api` and `await run.returnValue` where the parent needs the child's result: the parent suspends on a system hook the child resumes when it finishes, so no polling or hand-written completion hook is needed. Pass only serializable state to children. For fan-out, start children in parallel with `Promise.all` or bounded batches, handle partial failures with `Promise.allSettled`, and catch `WorkflowRunFailedError` / `WorkflowRunCancelledError` for failed or canceled children. Verify child start, completion, failure, and parent resume behavior."
|
|
12
12
|
/>
|
|
13
13
|
|
|
14
14
|
Use child workflows when a single workflow needs to orchestrate many independent units of work. Each child runs as its own workflow with a separate event log, retry boundary, and failure scope. If one child fails, it doesn't take down the parent or siblings.
|
|
@@ -25,69 +25,17 @@ Child workflows are the right choice when:
|
|
|
25
25
|
|
|
26
26
|
For simpler cases where steps share a single event log, use [direct await composition](/cookbook/common-patterns/workflow-composition#direct-await-flattening) instead.
|
|
27
27
|
|
|
28
|
-
##
|
|
28
|
+
## Waiting for a child
|
|
29
29
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
1. A **completion hook** the parent creates and awaits, with zero compute while waiting
|
|
33
|
-
2. A **wrapped child export** that runs the real child in try/catch/finally and resumes the parent's hook from a step in `finally`
|
|
34
|
-
3. A **`start()` call** that spawns the wrapped child with the hook token (directly from the workflow in v5)
|
|
35
|
-
4. A **`startAndWait()` helper** that ties the hook, spawn, and typed result together
|
|
30
|
+
Start the child with [`start()`](/docs/api-reference/workflow-api/start) and await its `returnValue`:
|
|
36
31
|
|
|
37
32
|
```typescript
|
|
38
|
-
import { defineHook, getWorkflowMetadata } from "workflow";
|
|
39
33
|
import { start } from "workflow/api";
|
|
40
|
-
import { z } from "zod";
|
|
41
34
|
|
|
42
35
|
declare function fetchDocument(documentId: string): Promise<string>; // @setup
|
|
43
36
|
declare function analyzeContent(content: string): Promise<string>; // @setup
|
|
44
37
|
declare function generateSummary(analysis: string): Promise<string>; // @setup
|
|
45
38
|
|
|
46
|
-
const childCompletionHook = defineHook({
|
|
47
|
-
schema: z.discriminatedUnion("status", [
|
|
48
|
-
z.object({ status: z.literal("completed"), value: z.unknown() }),
|
|
49
|
-
z.object({ status: z.literal("failed"), error: z.string() }),
|
|
50
|
-
]),
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
function completionToken(parentRunId: string, key: string) {
|
|
54
|
-
return `child-completion:${parentRunId}:${key}`;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function resumeParentCompletion(
|
|
58
|
-
token: string,
|
|
59
|
-
result:
|
|
60
|
-
| { status: "completed"; value: unknown }
|
|
61
|
-
| { status: "failed"; error: string }
|
|
62
|
-
) {
|
|
63
|
-
"use step";
|
|
64
|
-
await childCompletionHook.resume(token, result);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
async function withChildCompletionHook<TResult>(
|
|
68
|
-
runChild: () => Promise<TResult>,
|
|
69
|
-
completionTokenArg: string
|
|
70
|
-
) {
|
|
71
|
-
let result:
|
|
72
|
-
| { status: "completed"; value: TResult }
|
|
73
|
-
| { status: "failed"; error: string }
|
|
74
|
-
| undefined;
|
|
75
|
-
|
|
76
|
-
try {
|
|
77
|
-
const value = await runChild();
|
|
78
|
-
result = { status: "completed", value };
|
|
79
|
-
} catch (error) {
|
|
80
|
-
result = {
|
|
81
|
-
status: "failed",
|
|
82
|
-
error: error instanceof Error ? error.message : String(error),
|
|
83
|
-
};
|
|
84
|
-
} finally {
|
|
85
|
-
if (result) {
|
|
86
|
-
await resumeParentCompletion(completionTokenArg, result);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
39
|
// Child workflow -- processes a single document
|
|
92
40
|
export async function processDocument(documentId: string) {
|
|
93
41
|
"use workflow";
|
|
@@ -99,77 +47,86 @@ export async function processDocument(documentId: string) {
|
|
|
99
47
|
return { documentId, summary };
|
|
100
48
|
}
|
|
101
49
|
|
|
102
|
-
//
|
|
103
|
-
export async function
|
|
104
|
-
documentId: string,
|
|
105
|
-
completionTokenArg: string
|
|
106
|
-
) {
|
|
50
|
+
// Parent workflow -- orchestrates document processing
|
|
51
|
+
export async function processDocumentBatch(documentIds: string[]) {
|
|
107
52
|
"use workflow";
|
|
108
53
|
|
|
109
|
-
await
|
|
110
|
-
() => processDocument
|
|
111
|
-
completionTokenArg
|
|
54
|
+
const runs = await Promise.all(
|
|
55
|
+
documentIds.map((documentId) => start(processDocument, [documentId])) // [!code highlight]
|
|
112
56
|
);
|
|
57
|
+
const results = await Promise.all(runs.map((run) => run.returnValue)); // [!code highlight]
|
|
58
|
+
|
|
59
|
+
return { processed: results.length, results };
|
|
113
60
|
}
|
|
61
|
+
```
|
|
114
62
|
|
|
115
|
-
|
|
116
|
-
key: string,
|
|
117
|
-
startChild: (completionTokenArg: string) => Promise<void>
|
|
118
|
-
): Promise<TResult> {
|
|
119
|
-
const { workflowRunId } = getWorkflowMetadata();
|
|
120
|
-
const token = completionToken(workflowRunId, key);
|
|
121
|
-
const hook = childCompletionHook.create({ token }); // [!code highlight]
|
|
63
|
+
`returnValue` is typed from the child's return type. A child that fails or is canceled rejects it with [`WorkflowRunFailedError`](/docs/api-reference/workflow-errors/workflow-run-failed-error) or [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error).
|
|
122
64
|
|
|
123
|
-
|
|
65
|
+
### How the parent waits
|
|
124
66
|
|
|
125
|
-
|
|
126
|
-
if (completion.status === "failed") {
|
|
127
|
-
throw new Error(completion.error);
|
|
128
|
-
}
|
|
129
|
-
return completion.value as TResult;
|
|
130
|
-
}
|
|
67
|
+
Awaiting `returnValue` of a run the workflow started does not poll. The SDK waits on a **system hook**, the same handshake you would otherwise write by hand, but with one hook for the whole parent rather than one per child:
|
|
131
68
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
69
|
+
1. `start()` records the parent's run ID on the child, and remembers the parent on the returned `Run`.
|
|
70
|
+
2. When the parent first awaits a child, it registers its completion hook (a system hook whose token is derived from the parent's run ID), which stays open for the rest of the run. Reading `run.returnValue` without awaiting it does nothing yet: the wait starts at the first `await`, `then`, `catch` or `finally`. On each await the parent reads every child it started waiting on since its last read, in one step. A child that already finished is answered from that read.
|
|
71
|
+
3. Otherwise the parent suspends on the hook. When a child completes, fails, or is canceled, its runtime resumes the parent's hook with that child's run ID, and the parent reads that child's result.
|
|
72
|
+
4. Between waits the hook stays open but the parent does not listen on it, so it does not hold up run-ahead on the single-orchestrator runtime. A child the parent never awaits still resumes the hook when it finishes, which wakes the parent briefly without changing what it does.
|
|
135
73
|
|
|
136
|
-
|
|
137
|
-
documentIds.map((documentId) =>
|
|
138
|
-
startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
|
|
139
|
-
start(processDocumentWithCompletion, [documentId, token]).then(() => undefined) // [!code highlight]
|
|
140
|
-
)
|
|
141
|
-
)
|
|
142
|
-
);
|
|
74
|
+
This gives you:
|
|
143
75
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
76
|
+
- **Zero compute while waiting**: The parent is suspended rather than waking on a poll interval, and holds no worker slot. Worker-based Worlds such as [Postgres](/worlds/postgres) do not need a slot per waiting parent.
|
|
77
|
+
- **Immediate wake-up**: The parent resumes as soon as a child finishes, not on the next poll tick.
|
|
78
|
+
- **A slim parent log**: Fanning out to many children adds one system hook and one status read to the parent, plus, per child, the notification and the read of its result.
|
|
79
|
+
- **No wiring**: There is no hook to define, no token to pass, and no wrapper workflow to export.
|
|
80
|
+
|
|
81
|
+
The `Run` keeps this behavior when it travels within the parent: a step of the parent that calls `start()` and returns the `Run` hands the parent a handle it can await the same way. Awaiting the same child twice shares one wait.
|
|
82
|
+
|
|
83
|
+
### Cancellations that bypass the SDK
|
|
147
84
|
|
|
148
|
-
|
|
85
|
+
<Callout type="warn">
|
|
86
|
+
A parent is notified **immediately** only when the child's own runtime records its outcome, or when the child is canceled through the SDK. A cancellation written to the World without going through the SDK is not delivered to the parent, which keeps waiting until its next safety-net check.
|
|
87
|
+
</Callout>
|
|
149
88
|
|
|
150
|
-
|
|
89
|
+
| How the child finished | Parent resumes |
|
|
90
|
+
| --- | --- |
|
|
91
|
+
| The child completed or failed | Immediately |
|
|
92
|
+
| Canceled with `run.cancel()`, `cancelRun()`, or `cancelRuns()` | Immediately |
|
|
93
|
+
| Canceled with `workflow cancel` or from `workflow web` | Immediately (both call `cancelRun()`) |
|
|
94
|
+
| Canceled by any other tool that writes the cancellation to the World or its backend directly, without the SDK | At the next safety-net check |
|
|
95
|
+
| The child's invocation crashed after recording its outcome but before resuming the parent | At the next safety-net check |
|
|
151
96
|
|
|
152
|
-
|
|
153
|
-
- **Immediate wake-up**: The parent resumes as soon as the child finishes, not on the next poll tick.
|
|
154
|
-
- **Typed payloads**: The child sends `{ status, value | error }` directly, with no separate `returnValue` fetch step.
|
|
155
|
-
- **No worker-pool pressure**: `Run#returnValue` polling inside steps can hold worker slots while waiting for children (see [Eager Processing](/docs/changelog/eager-processing)).
|
|
97
|
+
The safety net: while a parent waits on children, it keeps one sleep open and, when it fires, reads every child it is still waiting on. The first check runs 5 minutes after the parent starts waiting, then the interval doubles up to every 6 hours. A missed notification therefore delays the parent but never strands it. Each check costs the parent one sleep and one step, so a child that runs for a day adds about a dozen of each.
|
|
156
98
|
|
|
157
|
-
|
|
99
|
+
If a parent must react to a cancellation faster than that, cancel children through the SDK.
|
|
100
|
+
|
|
101
|
+
### When `returnValue` polls instead
|
|
102
|
+
|
|
103
|
+
`returnValue` falls back to polling the child, inside a step that holds its worker slot until the child finishes, when the waiting code is not the workflow that started it:
|
|
104
|
+
|
|
105
|
+
- a step, API route, or other server code (for example, a step that calls `start()` and awaits the result itself)
|
|
106
|
+
- a different workflow that was handed the `Run` as an argument
|
|
107
|
+
|
|
108
|
+
It also polls for a child started on another deployment (`deploymentId`) whose SDK predates the system hook, and for every child started while [`WORKFLOW_CHILD_RUN_COMPLETION_HOOK=0`](/docs/configuration/runtime-tuning#workflow_child_run_completion_hook) is set.
|
|
158
109
|
|
|
159
110
|
## Fan-out pattern: chunked spawning
|
|
160
111
|
|
|
161
|
-
When spawning hundreds of children, batch the `start()` calls to avoid overwhelming the system. Each child
|
|
112
|
+
When spawning hundreds of children, batch the `start()` calls to avoid overwhelming the system. Each awaited child gets its own system hook, so a chunk costs nothing while it waits.
|
|
162
113
|
|
|
163
114
|
```typescript
|
|
164
115
|
import { start } from "workflow/api";
|
|
165
116
|
|
|
166
|
-
declare function
|
|
167
|
-
|
|
168
|
-
startChild: (completionTokenArg: string) => Promise<void>
|
|
169
|
-
): Promise<TResult>; // @setup
|
|
117
|
+
declare function queryDatabase(reportId: string, query: string): Promise<string>; // @setup
|
|
118
|
+
declare function formatReport(reportId: string, data: string): Promise<string>; // @setup
|
|
170
119
|
|
|
171
120
|
const CHUNK_SIZE = 10;
|
|
172
121
|
|
|
122
|
+
export async function generateReport(reportId: string, query: string) {
|
|
123
|
+
"use workflow";
|
|
124
|
+
|
|
125
|
+
const data = await queryDatabase(reportId, query);
|
|
126
|
+
const formatted = await formatReport(reportId, data);
|
|
127
|
+
return { reportId, formatted };
|
|
128
|
+
}
|
|
129
|
+
|
|
173
130
|
export async function largeReportBatch(
|
|
174
131
|
reportConfigs: Array<{ id: string; query: string }>
|
|
175
132
|
) {
|
|
@@ -178,82 +135,36 @@ export async function largeReportBatch(
|
|
|
178
135
|
const results = [];
|
|
179
136
|
for (let i = 0; i < reportConfigs.length; i += CHUNK_SIZE) {
|
|
180
137
|
const chunk = reportConfigs.slice(i, i + CHUNK_SIZE);
|
|
181
|
-
const
|
|
182
|
-
chunk.map((config) =>
|
|
183
|
-
startAndWait<{ reportId: string; formatted: string }>(config.id, (token) =>
|
|
184
|
-
start(generateReportWithCompletion, [
|
|
185
|
-
config.id,
|
|
186
|
-
config.query,
|
|
187
|
-
token,
|
|
188
|
-
]).then(() => undefined)
|
|
189
|
-
)
|
|
190
|
-
)
|
|
138
|
+
const runs = await Promise.all(
|
|
139
|
+
chunk.map((config) => start(generateReport, [config.id, config.query]))
|
|
191
140
|
);
|
|
192
|
-
results.push(...
|
|
141
|
+
results.push(...(await Promise.all(runs.map((run) => run.returnValue))));
|
|
193
142
|
}
|
|
194
143
|
|
|
195
144
|
return { total: results.length, results };
|
|
196
145
|
}
|
|
197
|
-
|
|
198
|
-
async function generateReportWithCompletion(
|
|
199
|
-
reportId: string,
|
|
200
|
-
query: string,
|
|
201
|
-
completionTokenArg: string
|
|
202
|
-
) {
|
|
203
|
-
"use workflow";
|
|
204
|
-
|
|
205
|
-
await withChildCompletionHook(
|
|
206
|
-
() => generateReport(reportId, query),
|
|
207
|
-
completionTokenArg
|
|
208
|
-
);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
async function generateReport(reportId: string, query: string) {
|
|
212
|
-
"use workflow";
|
|
213
|
-
|
|
214
|
-
const data = await queryDatabase(reportId, query);
|
|
215
|
-
const formatted = await formatReport(reportId, data);
|
|
216
|
-
return { reportId, formatted };
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
declare function queryDatabase(reportId: string, query: string): Promise<string>; // @setup
|
|
220
|
-
declare function formatReport(reportId: string, data: string): Promise<string>; // @setup
|
|
221
|
-
declare function withChildCompletionHook<TResult>(
|
|
222
|
-
runChild: () => Promise<TResult>,
|
|
223
|
-
completionTokenArg: string
|
|
224
|
-
): Promise<void>; // @setup
|
|
225
146
|
```
|
|
226
147
|
|
|
227
148
|
## Error handling
|
|
228
149
|
|
|
229
150
|
### Tolerating partial failures
|
|
230
151
|
|
|
231
|
-
Use `Promise.allSettled`
|
|
152
|
+
Use `Promise.allSettled` over the children's `returnValue` so one failing child doesn't abort its siblings. A failed child's entry is rejected with `WorkflowRunFailedError`, whose `cause` is the error the child threw.
|
|
232
153
|
|
|
233
154
|
```typescript
|
|
234
155
|
import { start } from "workflow/api";
|
|
235
156
|
|
|
236
|
-
declare function
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
): Promise<TResult>; // @setup
|
|
240
|
-
declare function processDocumentWithCompletion(
|
|
241
|
-
documentId: string,
|
|
242
|
-
completionTokenArg: string
|
|
243
|
-
): Promise<void>; // @setup
|
|
157
|
+
declare function processDocument(
|
|
158
|
+
documentId: string
|
|
159
|
+
): Promise<{ documentId: string; summary: string }>; // @setup
|
|
244
160
|
|
|
245
161
|
export async function processDocumentBatchTolerant(documentIds: string[]) {
|
|
246
162
|
"use workflow";
|
|
247
163
|
|
|
248
|
-
const
|
|
249
|
-
documentIds.map((documentId) =>
|
|
250
|
-
startAndWait<{ documentId: string; summary: string }>(documentId, (token) =>
|
|
251
|
-
start(processDocumentWithCompletion, [documentId, token]).then(
|
|
252
|
-
() => undefined
|
|
253
|
-
)
|
|
254
|
-
)
|
|
255
|
-
)
|
|
164
|
+
const runs = await Promise.all(
|
|
165
|
+
documentIds.map((documentId) => start(processDocument, [documentId]))
|
|
256
166
|
);
|
|
167
|
+
const settled = await Promise.allSettled(runs.map((run) => run.returnValue));
|
|
257
168
|
|
|
258
169
|
const results = settled
|
|
259
170
|
.filter(
|
|
@@ -270,52 +181,81 @@ export async function processDocumentBatchTolerant(documentIds: string[]) {
|
|
|
270
181
|
|
|
271
182
|
### Retrying failed children
|
|
272
183
|
|
|
273
|
-
When a child fails,
|
|
184
|
+
When a child fails, start a replacement. Track restart counts to prevent infinite retry loops.
|
|
274
185
|
|
|
275
186
|
```typescript
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
documentId: string,
|
|
282
|
-
completionTokenArg: string
|
|
283
|
-
): Promise<void>; // @setup
|
|
187
|
+
import { start } from "workflow/api";
|
|
188
|
+
|
|
189
|
+
declare function processDocument(
|
|
190
|
+
documentId: string
|
|
191
|
+
): Promise<{ documentId: string; summary: string }>; // @setup
|
|
284
192
|
|
|
285
|
-
async function
|
|
193
|
+
async function processDocumentWithRetries(
|
|
286
194
|
documentId: string,
|
|
287
195
|
maxRestarts: number
|
|
288
196
|
): Promise<{ documentId: string; summary: string }> {
|
|
289
|
-
for (let attempt = 0;
|
|
197
|
+
for (let attempt = 0; ; attempt++) {
|
|
198
|
+
const run = await start(processDocument, [documentId]);
|
|
290
199
|
try {
|
|
291
|
-
return await
|
|
292
|
-
`${documentId}:${attempt}`,
|
|
293
|
-
(token) => spawnProcessDocument(documentId, token)
|
|
294
|
-
);
|
|
200
|
+
return await run.returnValue;
|
|
295
201
|
} catch (error) {
|
|
296
|
-
if (attempt
|
|
202
|
+
if (attempt >= maxRestarts) throw error;
|
|
297
203
|
}
|
|
298
204
|
}
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## Signaling the parent before the child finishes
|
|
209
|
+
|
|
210
|
+
The system hook fires only when the child finishes. When the parent needs to hear from a child mid-run (a progress milestone, an approval request, a partial result), create a [hook](/docs/foundations/hooks) in the parent and pass its token to the child, which resumes it from a step:
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
import { createHook } from "workflow";
|
|
214
|
+
import { resumeHook, start } from "workflow/api";
|
|
215
|
+
|
|
216
|
+
declare function prepareDraft(documentId: string): Promise<string>; // @setup
|
|
217
|
+
declare function publishDraft(draft: string): Promise<void>; // @setup
|
|
218
|
+
|
|
219
|
+
async function notifyDraftReady(token: string, draft: string) {
|
|
220
|
+
"use step";
|
|
221
|
+
await resumeHook(token, { draft });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export async function draftDocument(documentId: string, draftToken: string) {
|
|
225
|
+
"use workflow";
|
|
226
|
+
|
|
227
|
+
const draft = await prepareDraft(documentId);
|
|
228
|
+
await notifyDraftReady(draftToken, draft); // the parent continues from here
|
|
229
|
+
await publishDraft(draft);
|
|
230
|
+
return { documentId, published: true };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export async function reviewDocument(documentId: string) {
|
|
234
|
+
"use workflow";
|
|
235
|
+
|
|
236
|
+
const draftReady = createHook<{ draft: string }>();
|
|
237
|
+
const run = await start(draftDocument, [documentId, draftReady.token]);
|
|
299
238
|
|
|
300
|
-
|
|
239
|
+
const { draft } = await draftReady; // mid-run signal from the child
|
|
240
|
+
const result = await run.returnValue; // completion, via the system hook
|
|
241
|
+
return { draft, ...result };
|
|
301
242
|
}
|
|
302
243
|
```
|
|
303
244
|
|
|
304
245
|
## Tips
|
|
305
246
|
|
|
306
|
-
- **
|
|
307
|
-
- **Export wrapped children at module scope**: The SDK registers `"use workflow"` functions statically, so a runtime higher-order function returned from `withChildCompletionHook()` cannot be passed to `start()`.
|
|
308
|
-
- **Use stable hook keys**: Document IDs, job IDs, or indexes prevent token collisions between parallel children in one parent run.
|
|
247
|
+
- **Await only the children you need**: Until the parent first awaits a child's `returnValue`, it has no completion hook open, so a child that finishes costs one extra hook lookup and nothing in the parent. Once the parent has awaited a child, the hook stays open for the rest of the run, so every child that finishes afterwards adds a notification to the parent's log and wakes it, including children it never awaits and children that finish between waits. If a parent starts many children it never waits for, start them from an intermediate run that does not await any child, so their completions do not wake the parent.
|
|
309
248
|
- **Use chunked spawning for large batches**: Starting 500 children at once can create a large burst of work. Break the work into chunks of 10–50.
|
|
310
|
-
- **Watch the parent's log too**: The parent records events for spawning and collecting every child. On the default runtime, count those events against the parent's [event limit](/worlds/vercel#per-run-limits) and consider another layer of intermediate runs if needed. QuickJS with snapshotting reduces replay overhead and exempts eligible parent runs from the default event cap, but does not reduce their event count or remove payload and storage limits.
|
|
311
|
-
- **Account for each child's retry semantics**: Steps inside child workflows retry independently. The parent sees the final
|
|
249
|
+
- **Watch the parent's log too**: The parent records events for spawning and collecting every child (the spawn step, the child's notification on the parent's completion hook, and the step that reads its result). On the default runtime, count those events against the parent's [event limit](/worlds/vercel#per-run-limits) and consider another layer of intermediate runs if needed. QuickJS with snapshotting reduces replay overhead and exempts eligible parent runs from the default event cap, but does not reduce their event count or remove payload and storage limits.
|
|
250
|
+
- **Account for each child's retry semantics**: Steps inside child workflows retry independently. The parent only sees the child's final result or error.
|
|
251
|
+
- **Cancel children through the SDK**: [`run.cancel()`](/docs/api-reference/workflow-api/get-run), `cancelRun()`, `cancelRuns()`, `workflow cancel`, and `workflow web` resume a waiting parent immediately. Any other cancellation reaches the parent only at its next safety-net check; see [Cancellations that bypass the SDK](#cancellations-that-bypass-the-sdk).
|
|
312
252
|
- **Use `deploymentId: "latest"` when children should run on the most recent deployment**: See [Versioning](/docs/foundations/versioning) for the full model and the [`start()` API reference](/docs/api-reference/workflow-api/start#using-deploymentid-latest) for compatibility considerations.
|
|
313
253
|
|
|
314
254
|
## Key APIs
|
|
315
255
|
|
|
316
|
-
- [`start()`](/docs/api-reference/workflow-api/start): Spawns a new workflow run and returns
|
|
317
|
-
- [`
|
|
318
|
-
- [`
|
|
319
|
-
- [`
|
|
256
|
+
- [`start()`](/docs/api-reference/workflow-api/start): Spawns a new workflow run and returns a `Run` whose `returnValue` the parent can await.
|
|
257
|
+
- [`getRun()`](/docs/api-reference/workflow-api/get-run): Documents the `Run` handle, with `returnValue`, `status`, and `cancel()`.
|
|
258
|
+
- [`createHook()`](/docs/api-reference/workflow/create-hook): Creates a hook for signals from a child before it finishes.
|
|
259
|
+
- [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes a parent's hook from a step in the child.
|
|
320
260
|
- [`"use workflow"`](/docs/foundations/workflows-and-steps): Marks the orchestrator function.
|
|
321
261
|
- [`"use step"`](/docs/foundations/workflows-and-steps): Marks functions with full Node.js access.
|
|
@@ -159,7 +159,7 @@ Approval requests arrive as typed tool parts with `state: "approval-requested"`.
|
|
|
159
159
|
"use client";
|
|
160
160
|
|
|
161
161
|
import { useChat } from "@ai-sdk/react";
|
|
162
|
-
import { WorkflowChatTransport } from "@ai-sdk/workflow";
|
|
162
|
+
import { WorkflowChatTransport } from "@ai-sdk/workflow/client";
|
|
163
163
|
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai";
|
|
164
164
|
import { useMemo } from "react";
|
|
165
165
|
import type { BookingAgentUIMessage } from "@/workflows/booking-agent";
|
|
@@ -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, reused: false });
|
|
77
77
|
} catch (error) {
|
|
@@ -91,4 +91,4 @@ The run's start Hook can be resumed as soon as `start()` returns, so a duplicate
|
|
|
91
91
|
- [`createHook()`](/docs/api-reference/workflow/create-hook): Creates a hook with an optional deterministic token.
|
|
92
92
|
- [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token): Finds the hook that owns a token.
|
|
93
93
|
- [`resumeHook()`](/docs/api-reference/workflow-api/resume-hook): Resumes the active hook when the duplicate request carries data.
|
|
94
|
-
- [`start()`](/docs/api-reference/workflow-api/start): Starts a new workflow run, at most once per `
|
|
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**:
|
|
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 "use workflow" 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
|
|
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 |
|
|
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,
|
|
112
|
-
- **Wait for a background child to finish**:
|
|
113
|
-
- **
|
|
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
|
|
|
@@ -17,7 +17,7 @@ related:
|
|
|
17
17
|
|
|
18
18
|
[AI SDK](https://ai-sdk.dev/) is Vercel's framework-agnostic TypeScript toolkit for building AI-powered apps and agents. It provides unified provider access, streaming, tool calling, structured output, and UI hooks. Workflow SDK makes the multi-turn loop durable, so the conversation state, hooks, and per-turn responses survive restarts and timeouts. In this pattern, the durability boundary is the entire turn, and individual tool calls inside a turn are **not** durable on their own (see [Pitfalls](#tools-are-not-individually-durable)).
|
|
19
19
|
|
|
20
|
-
For the full AI SDK reference, including providers, `streamText`, `
|
|
20
|
+
For the full AI SDK reference, including providers, `streamText`, structured output with `Output.object`, `useChat`, and tool calling, see the [AI SDK docs](https://ai-sdk.dev/docs). This page covers the Workflow-specific integration points.
|
|
21
21
|
|
|
22
22
|
<Callout type="info">
|
|
23
23
|
For most agent use cases, prefer AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent), which implements the same agent loop as [`streamText`](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text), manages tool calling automatically, and runs tools at workflow scope: each tool can be marked `"use step"` for per-call durability and retries, or stay at workflow level to use primitives like `sleep()` and hooks. Use this page's raw `streamText()` pattern when you want the exact AI SDK API (for example `toUIMessageStream()`, `onChunk`, or `generateText`), or when the durability boundary should be an entire user turn in one step, accepting that tool calls inside that turn are not individually durable.
|
|
@@ -256,7 +256,7 @@ Store the `runId` in a ref and pass it in the body of every follow-up. `Workflow
|
|
|
256
256
|
"use client";
|
|
257
257
|
|
|
258
258
|
import { useChat } from "@ai-sdk/react";
|
|
259
|
-
import { WorkflowChatTransport } from "@ai-sdk/workflow";
|
|
259
|
+
import { WorkflowChatTransport } from "@ai-sdk/workflow/client";
|
|
260
260
|
import { useMemo, useRef, useState } from "react";
|
|
261
261
|
|
|
262
262
|
export function SupportChat() {
|
|
@@ -49,7 +49,7 @@ Common scenarios that produce this error:
|
|
|
49
49
|
|
|
50
50
|
- **An unclaimed event that repeats nothing**: A duplicate of a kind the log already records for that entity is read past rather than failing the run, so a second `step_completed` or `wait_completed` is not this error (see [Duplicate Events](/docs/how-it-works/event-sourcing#duplicate-events)). What fails is an unclaimed event with no earlier counterpart to defer to: a `step_started` behind a `step_completed` on a log that never recorded a `step_started`, for instance. No consumer remains for the step, and there is no earlier event of that kind the replay could be reading instead.
|
|
51
51
|
- **Orphaned events**: A `step_completed` or `wait_completed` event whose `correlationId` doesn't match any step or sleep in the workflow code, so the replay reaches its end still holding it.
|
|
52
|
-
- **A hole in the log**: Events are numbered by their position in the run's log, and those positions are dense, so a position below the log's highest that holds no event means the log the replay loaded is incomplete. The runtime cannot tell a position no write ever occupied from one whose event it failed to read, so it refuses to replay rather than produce a result that may be silently wrong.
|
|
52
|
+
- **A hole in the log**: Events are numbered by their position in the run's log, and those positions are dense, so a position below the log's highest that holds no event means the log the replay loaded is incomplete. The runtime cannot tell a position no write ever occupied from one whose event it failed to read, so it refuses to replay rather than produce a result that may be silently wrong.
|
|
53
53
|
- **An unreadable stored payload**: An event row still references a payload object, but the World reports that the object no longer exists in its storage. The same log would fail on every replay, so the run fails immediately instead of retrying forever.
|
|
54
54
|
|
|
55
55
|
## What to do
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: fetch-in-workflow
|
|
3
|
-
description:
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
59
|
-
"use
|
|
60
|
-
|
|
61
|
-
globalThis.fetch = fetch; // [!code highlight]
|
|
57
|
+
async function generate(prompt: string) {
|
|
58
|
+
"use step"; // [!code highlight]
|
|
62
59
|
|
|
63
|
-
//
|
|
60
|
+
// generateText calls fetch() under the hood
|
|
64
61
|
const result = await generateText({
|
|
65
62
|
model: "spacexai/grok-4.6",
|
|
66
63
|
prompt,
|
|
@@ -68,42 +65,25 @@ export async function chatWorkflow(prompt: string) {
|
|
|
68
65
|
|
|
69
66
|
return result.text;
|
|
70
67
|
}
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
## Common scenarios
|
|
74
68
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
This is the most common scenario - using AI SDK functions that make HTTP requests:
|
|
78
|
-
|
|
79
|
-
```typescript lineNumbers
|
|
80
|
-
import { generateText } from "ai";
|
|
81
|
-
import { fetch } from "workflow"; // [!code highlight]
|
|
82
|
-
|
|
83
|
-
export async function aiWorkflow(userMessage: string) {
|
|
69
|
+
export async function chatWorkflow(prompt: string) {
|
|
84
70
|
"use workflow";
|
|
85
71
|
|
|
86
|
-
|
|
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
|
-
maxRetries: 0, // [!code highlight]
|
|
93
|
-
});
|
|
94
|
-
|
|
95
|
-
return response.text;
|
|
72
|
+
return await generate(prompt); // [!code highlight]
|
|
96
73
|
}
|
|
97
74
|
```
|
|
98
75
|
|
|
99
|
-
|
|
76
|
+
## Common scenarios
|
|
77
|
+
|
|
78
|
+
### AI SDK integration
|
|
79
|
+
|
|
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.
|
|
100
81
|
|
|
101
|
-
|
|
102
|
-
- **Streaming is not supported.** `streamText()` and other streaming calls pipe the response through web streams, which are not available in workflow functions. Use [`DurableAgent`](/docs/api-reference/workflow-ai/durable-agent), or call `streamText()` inside a step function.
|
|
82
|
+
For single AI SDK calls, use a step function as shown above.
|
|
103
83
|
|
|
104
84
|
### Direct API calls
|
|
105
85
|
|
|
106
|
-
|
|
86
|
+
For simple requests, you can use the `fetch` step function from `workflow` directly:
|
|
107
87
|
|
|
108
88
|
```typescript lineNumbers
|
|
109
89
|
import { fetch } from "workflow";
|