workflow 5.4.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 +2 -2
- 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-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-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 +1 -2
- package/docs/changelog/attributes-mvp.mdx +1 -1
- package/docs/changelog/batched-event-writes.mdx +0 -2
- package/docs/changelog/eager-processing.mdx +1 -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 +9 -0
- package/docs/configuration/framework-options.mdx +7 -0
- package/docs/configuration/runtime-tuning.mdx +22 -77
- package/docs/configuration/worlds.mdx +54 -22
- package/docs/cookbook/advanced/child-workflows.mdx +3 -3
- package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +1 -1
- package/docs/cookbook/integrations/ai-sdk.mdx +2 -2
- package/docs/errors/corrupted-event-log.mdx +1 -1
- 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/serialization.mdx +80 -0
- 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 +3 -3
- package/docs/worlds/building-a-world.mdx +18 -3
- package/docs/worlds/local.mdx +11 -7
- package/docs/worlds/postgres.mdx +10 -13
- package/docs/worlds/upgrading-to-v5.mdx +2 -2
- package/docs/worlds/vercel.mdx +10 -5
- package/package.json +14 -14
|
@@ -8,8 +8,7 @@ description: Why inline step_started now records its owning queue message ID, wh
|
|
|
8
8
|
> Fixes [#2780](https://github.com/vercel/workflow/issues/2780) (duplicate
|
|
9
9
|
> inline step execution when a hook or wait wakes a run mid-step). This page
|
|
10
10
|
> is the design defense for the change: what it does, why each choice was
|
|
11
|
-
> made, and why the alternatives were rejected.
|
|
12
|
-
> `WORKFLOW_INLINE_OWNERSHIP=0`; lease tuning:
|
|
11
|
+
> made, and why the alternatives were rejected. Lease tuning:
|
|
13
12
|
> `WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS` (see
|
|
14
13
|
> [Runtime tuning](/docs/configuration/runtime-tuning)).
|
|
15
14
|
|
|
@@ -301,9 +300,6 @@ heartbeat machinery rejected above.
|
|
|
301
300
|
ship into.
|
|
302
301
|
- **Version skew is a non-issue**: runs are pinned to their deployment, and old events
|
|
303
302
|
lack the field → unowned → current behavior. Nothing to migrate.
|
|
304
|
-
- **Kill switch**: `WORKFLOW_INLINE_OWNERSHIP=0` reverts dispatch to the unconditional
|
|
305
|
-
immediate requeue. Stamping continues (it is inert data), so the switch is purely a
|
|
306
|
-
dispatch-behavior toggle.
|
|
307
303
|
- **Degraded modes are all "today's behavior", never worse**: unstable message IDs (owner
|
|
308
304
|
check never matches → backstop-lease recovery), missing/unusable event timestamps
|
|
309
305
|
(lease remaining 0 → immediate enqueue), old backend (field dropped → unowned).
|
|
@@ -336,8 +332,7 @@ heartbeat machinery rejected above.
|
|
|
336
332
|
## How the design is protected by tests
|
|
337
333
|
|
|
338
334
|
- The **#2780 repro** (`workbench/vitest/test/inline-step-ownership.test.ts`): hook
|
|
339
|
-
resume mid-inline-step → side-effect marker fires exactly once.
|
|
340
|
-
with `WORKFLOW_INLINE_OWNERSHIP=0` the marker fires twice.
|
|
335
|
+
resume mid-inline-step → side-effect marker fires exactly once.
|
|
341
336
|
- **Unit**: the ownership state machine (stamp → wake sees owner → retrying clears → bare
|
|
342
337
|
start clears → re-stamp restores), lease math including the clock-skew clamp, and the
|
|
343
338
|
backstop key's epoch behavior, including a regression test walking the full
|
|
@@ -49,6 +49,8 @@ Accepted values:
|
|
|
49
49
|
- Framework option: `discoverWorkflowsInNodeModules` where supported
|
|
50
50
|
- Default: enabled
|
|
51
51
|
- Controls whether workflow discovery descends into `node_modules`. By default, dependencies that declare a `workflow`/`@workflow/*` dependency can ship `"use workflow"`/`"use step"` files that are discovered and compiled into your app's bundles.
|
|
52
|
+
- Dependencies without that declaration are not walked, but the file each import of them resolves to is still checked for serialization classes, and registered in the step bundle if it defines one. This is how AI SDK provider models (`@ai-sdk/openai`, `@ai-sdk/google`, and others) created inside a `"use workflow"` function deserialize in the steps they are passed to.
|
|
53
|
+
- Only that one file is checked: the class must be defined in the file your import resolves to. A class the file re-exports from another package or from a code-split chunk (`export { Model } from './chunk-….js'`) is not found this way. To register such a class, import the package that defines it directly, or reference it from a `"use step"` function so the step bundle loads it.
|
|
52
54
|
- Set `0` or `false` to opt out: imports from your application code that resolve into `node_modules` are not followed, so the build never reads, scans, or descends into dependency file graphs. This skips the cost of scanning `node_modules` and stops third-party workflow/step/serde code from being discovered. Useful when a dependency ships workflow code you don't want compiled into your app, or trips discovery with directive strings you don't intend to run.
|
|
53
55
|
- The SDK's own runtime serde classes (for example, `Run`) stay registered because they are reached through a seeded entry point, and imports *within* `node_modules` are still followed.
|
|
54
56
|
- Explicit framework config wins over this environment variable.
|
|
@@ -224,6 +224,14 @@ per flag.
|
|
|
224
224
|
- Local server port for health checks.
|
|
225
225
|
- The flag writes `WORKFLOW_LOCAL_BASE_URL`.
|
|
226
226
|
|
|
227
|
+
### `--base-path`
|
|
228
|
+
|
|
229
|
+
- Command: `workflow health`
|
|
230
|
+
- Environment variable: none
|
|
231
|
+
- Default: unset, so the check targets `/.well-known/workflow/v1/flow` at the server root
|
|
232
|
+
- Path the workflow routes are served under on the local server: Next.js' `basePath` followed by [`workflows.experimentalRoutePrefix`](/docs/api-reference/workflow-next/with-workflow#workflow-route-prefix). For example, `--base-path /v2/dashboard` checks `/v2/dashboard/.well-known/workflow/v1/flow`.
|
|
233
|
+
- Appended to the URL from `--port`, `WORKFLOW_LOCAL_BASE_URL` or `PORT`.
|
|
234
|
+
|
|
227
235
|
## Verbose logging and updates
|
|
228
236
|
|
|
229
237
|
### `--verbose` / `-v`
|
|
@@ -251,3 +259,4 @@ per flag.
|
|
|
251
259
|
- CLI flag: none
|
|
252
260
|
- Default: inferred
|
|
253
261
|
- Explicit path to the workflow manifest for the web UI.
|
|
262
|
+
- Inferred from `app/`, `src/app/` and `.well-known/` at the project root first, then from a manifest generated below a [route prefix](/docs/api-reference/workflow-next/with-workflow#workflow-route-prefix), such as `app/dashboard/.well-known/workflow/v1/manifest.json`. Set it when more than one prefixed manifest exists.
|
|
@@ -28,6 +28,13 @@ Framework options are read at build or dev-server startup. Use them for settings
|
|
|
28
28
|
- Controls source maps for generated workflow bundles.
|
|
29
29
|
- Explicit config wins over `WORKFLOW_SOURCEMAP`.
|
|
30
30
|
|
|
31
|
+
### `workflows.experimentalRoutePrefix`
|
|
32
|
+
|
|
33
|
+
- Environment override: none
|
|
34
|
+
- Default: none, so the routes are generated at the app root
|
|
35
|
+
- Experimental. Emits the generated workflow routes below a route segment the app owns, such as `/dashboard/.well-known/workflow/v1/flow`, for apps that cannot own the origin's root paths.
|
|
36
|
+
- See [`withWorkflow`](/docs/api-reference/workflow-next/with-workflow#workflow-route-prefix) for the generated paths and the Turborepo caching caveat.
|
|
37
|
+
|
|
31
38
|
```typescript title="next.config.ts" lineNumbers
|
|
32
39
|
import { withWorkflow } from "workflow/next";
|
|
33
40
|
|
|
@@ -38,13 +38,6 @@ The runtime reads these variables where workflows execute. Set them on the deplo
|
|
|
38
38
|
- Runs longer than roughly `WORKFLOW_RETURN_VALUE_MAX_LONG_POLLS` x `WORKFLOW_RETURN_VALUE_WAIT_MS` therefore spend most of their life interval polling, which costs more requests than continuing to wait would. Raise it if you routinely await long runs.
|
|
39
39
|
- Read by the process awaiting `Run.returnValue`, like the interval above.
|
|
40
40
|
|
|
41
|
-
### `WORKFLOW_RETURN_VALUE_LONG_POLL`
|
|
42
|
-
|
|
43
|
-
- Default: enabled
|
|
44
|
-
- Set to `0` or `false` to stop `Run.returnValue` from waiting and restore fixed-interval polling on `WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS` exactly.
|
|
45
|
-
- The kill switch for the wait. Worlds that do not implement waiting are already on the interval path, so this changes nothing for them.
|
|
46
|
-
- Read by the process awaiting `Run.returnValue`, like the interval above.
|
|
47
|
-
|
|
48
41
|
### `WORKFLOW_CHILD_RUN_COMPLETION_HOOK`
|
|
49
42
|
|
|
50
43
|
- Default: enabled
|
|
@@ -75,6 +68,19 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
75
68
|
- Delivery attempts before a run or step is failed gracefully.
|
|
76
69
|
- Can only be lowered. Workflow calibrates the default to record failure before the queue expires the message.
|
|
77
70
|
|
|
71
|
+
### `WORKFLOW_QUEUE_AUTH`
|
|
72
|
+
|
|
73
|
+
- Default: `on`
|
|
74
|
+
- Applies to the [Local World](/worlds/local), and to any World that declares `queueAuthMode: 'loopback'`. A World that declares nothing is not checked; the runtime logs a warning when its flow route starts (once, then at most once a minute when routes restart). With `on`, the Workflow SDK's flow route (`POST /.well-known/workflow/v1/flow`) accepts only deliveries sent by the app's own processes. A queue consumer's own route (built with `world.createQueueHandler()` and registered with `registerRoute()`) is not checked; it must authenticate deliveries itself, or sit behind the network edge.
|
|
75
|
+
- Every delivery the Local World sends carries the app's queue key. The route refuses a request that does not carry the key with a `401`, before it reads the body, and does not touch any run. A request from outside the app therefore cannot start a run, fail a running one, re-trigger a step, or replay a delivery.
|
|
76
|
+
- The key is a random value in the file `queue-auth-key` in the Local World's data directory, readable only by its owner (Windows does not enforce that the same way). The app writes a new key each time it starts, before it sends any delivery, and the data directory gets a `.gitignore` that keeps the key out of git. See [the Local World's data directory](/worlds/local#data-directory-layout).
|
|
77
|
+
- The usual setups need nothing: the app's own queue, the CLI, the web UI, a script calling `start()` or `resumeHook()`, and several app processes all use the same data directory, so they send a key the app accepts. Point the CLI and the web UI at the app's data directory (`WORKFLOW_LOCAL_DATA_DIR`). Set `off` on the app only when a delivery comes from a process that cannot read that directory.
|
|
78
|
+
- `off` accepts unauthenticated deliveries. Use it only for local development or on a trusted network. The runtime logs a warning when a route starts with `off`.
|
|
79
|
+
- `off` is refused while [dynamic workflows](/docs/advanced/dynamic-workflows) are enabled (`WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS`). Both variables are read on every delivery, so the check comes back on as soon as dynamic workflows are enabled.
|
|
80
|
+
- The `401` is marked as the runtime's own refusal (an `x-workflow-auth-refused: 1` header). The Local World's queue then reads the key file again: if another process wrote a new key, it retries at once with that key. Otherwise it retries a few times with its short backoff, then logs one line and gives the message up. A refused delivery reaches no handler and touches no run, so retrying it is safe and it does not count as an attempt. A given-up message's run is left as it was. A `401` without the marker, for example from a proxy, gets the queue's normal retries.
|
|
81
|
+
- Each refusal increments the OpenTelemetry counter `workflow.queue.delivery.refused` (when a meter provider is registered). Its attributes are `workflow.world`, `http.route`, and `workflow.queue.refusal_reason` (`no-key` or `wrong-key`). A refusal right after the app, the CLI or a script starts is expected: it wrote a new key, and the sender reloads it and retries on its own. Alert on refusals that persist, which mean forged requests or a sender that cannot get the app's key. The refusal log is rate-limited to one line a minute per process; the counter counts every refusal.
|
|
82
|
+
- Any value other than `off` leaves the check on. Worlds that declare `queueAuthMode: 'skip'` are not checked and are not affected. The [Vercel World](/worlds/vercel) delivers to a route only Vercel Queues can trigger (see its [security section](/worlds/vercel#security)). The [Postgres World](/worlds/postgres) relies on its database credentials to control who can enqueue, and its flow route accepts any well-formed request, so protect that route at the network edge, as its [security section](/worlds/postgres#protect-the-queue-route) describes.
|
|
83
|
+
|
|
78
84
|
### `WORKFLOW_MAX_EVENTS`
|
|
79
85
|
|
|
80
86
|
- Default: `25000`
|
|
@@ -114,25 +120,6 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
114
120
|
- A World that does refuse should only ever do so on evidence, and accept the write in every other case. A rejection then always means the position was stale, while the absence of one proves nothing about currency.
|
|
115
121
|
- Two runtime behaviors follow from the properties above rather than from any fence. The per-step event-log delta optimization (consuming the delta returned by a step's terminal write instead of issuing an extra `events.list` per step) stays active while the run has an open hook. A `hook_received` event missed by the delta window is observed one iteration later, and the next write brings it back. While a hook is open, inline steps take the await-then-run path even when optimistic inline start is enabled. Several invocations race for one step's claim there, and awaiting it means the body runs only for the writer that won.
|
|
116
122
|
|
|
117
|
-
### `WORKFLOW_SLOT_GAP_CHECK`
|
|
118
|
-
|
|
119
|
-
- Default: enabled
|
|
120
|
-
- A replay checks that the [event log](/docs/how-it-works/event-sourcing#event-ids) it loaded is dense before it runs, and fails the run with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) when a position below the log's highest holds no event. A log missing only its first position, meaning a run whose `run_created` is still being written, is left alone.
|
|
121
|
-
- A position can be briefly empty while the write that occupies it is still committing, so the check re-reads the log a few times before it decides, and the replay continues from whichever log it settled on.
|
|
122
|
-
- The check trades one failure for another. Most holes stand for an event that never happened, and replaying past those is correct. A hole standing for an event that did happen looks identical, and replaying past that one produces a run whose result is silently wrong. Failing is the recoverable side of that trade.
|
|
123
|
-
- Set `0` to replay across holes instead.
|
|
124
|
-
|
|
125
|
-
### `WORKFLOW_SEALED_LOG`
|
|
126
|
-
|
|
127
|
-
- Default: enabled
|
|
128
|
-
- New runs are created at the sealed-log spec version, in which the World's backend assigns each event its position *before* the write commits rather than letting concurrent writers race for one. Concurrent writes then never contend for a position, which is what makes a wide fan-out cheap.
|
|
129
|
-
- The price of assigning positions in advance is that a writer which claims one and then dies leaves a position no writer will ever fill. The backend closes such a position by writing a `noop` event into it once it can prove the position was abandoned, so a reader still sees the dense log it needs. Replay steps over a `noop` without delivering it to the workflow or advancing the deterministic clock. Its timestamp belongs to whichever reader sealed it, not to the run.
|
|
130
|
-
- Set `0` to put a deployment back on the previous scheme, where each position is allocated by the write that occupies it. Use this as the kill switch if position assignment turns out to be at fault for event-log problems.
|
|
131
|
-
- Setting `0` also stamps new runs below spec version 8, so another run can't take their hook tokens over with [`experimental_force`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds). A forced hook in another run gets `HookConflictError` instead. Runs created with `0` can still take tokens over from others.
|
|
132
|
-
- Existing runs are unaffected either way. A run's spec version is stamped once, at creation, and read from the run for the rest of its life, so flipping this changes only what *new* runs get, and a run in flight keeps the scheme it started on. Every build reads sealed logs regardless of the setting.
|
|
133
|
-
- A run created at the sealed-log version can only be replayed by a reader that knows to skip `noop` events. That includes every runtime on this release train, but a runtime that pins its own accepted spec range separately, such as the Python runtime, has to catch up before it can read these runs. Switch this off in an environment where it has not.
|
|
134
|
-
- Only the Vercel World seals. The Local and Postgres Worlds allocate each position at the commit that occupies it, so they cannot leave a hole and never write a `noop`; the setting still moves the version they stamp, so the fleet stays on one spec.
|
|
135
|
-
|
|
136
123
|
### `WORKFLOW_PRECONDITION_MAX_INPROCESS_RESTARTS`
|
|
137
124
|
|
|
138
125
|
- Default: `3`
|
|
@@ -151,16 +138,6 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
151
138
|
- Delay before a re-invocation caused by a rejected event creation.
|
|
152
139
|
- Unlike an in-process restart, which re-reads immediately, a re-invocation only happens after the in-process budget fails to catch up. The delay gives the other writers time to quiesce.
|
|
153
140
|
|
|
154
|
-
### `WORKFLOW_LOG_ORDER_DRAWS`
|
|
155
|
-
|
|
156
|
-
- Default: enabled
|
|
157
|
-
- Experimental. Pins correlation-ID draw order to event-log order. A branch-deciding delivery (a step result, hook payload, or wait completion) resolves to the workflow only after every earlier-in-log delivery's continuation has fully quiesced, and never ahead of a lower-slot delivery that is committed to happening.
|
|
158
|
-
- Without it, a delivery that resolves while an earlier delivery's continuation is still a few microtask hops from its next step/hook/wait call can overtake it on the run's shared correlation-ID sequence. Draw order, and therefore correlation IDs, then depends on how much of the event log a replay had loaded. Two concurrent replays holding different-length prefixes can bind one ID to two different entities, failing the run with `CORRUPTED_EVENT_LOG`.
|
|
159
|
-
- Costs one event-loop turn (roughly 15 to 20 microseconds via `setImmediate`) per branch-deciding delivery during replay, and more when continuations genuinely overlap. Measurements on a 100-step sequential replay show about 2 ms added end to end.
|
|
160
|
-
- Only applies to the default Node.js VM engine. `WORKFLOW_VM=quickjs` has its own event feed and correlation-ID sequence and is unaffected by this setting.
|
|
161
|
-
- Correlation IDs of runs created before the setting changed are not affected on platforms where a run keeps replaying on the deployment it started on. Elsewhere, only change it while no runs are in flight.
|
|
162
|
-
- Set `0` to opt back into arrival-order delivery resolution. Only the literal value `0` opts out; `false` or `off` leave it enabled.
|
|
163
|
-
|
|
164
141
|
## Inline execution
|
|
165
142
|
|
|
166
143
|
### `WORKFLOW_V2_TIMEOUT_MS`
|
|
@@ -177,18 +154,6 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
177
154
|
- Number of newly-created steps one invocation runs inline in parallel before queueing the rest.
|
|
178
155
|
- Steps started beside an awaited hook registration (`hook.getConflict()`) count against the same cap. They are held for the pass that observes the registration and then run inline on it, so the registration still precedes them; only the steps past the cap are queued.
|
|
179
156
|
|
|
180
|
-
### `WORKFLOW_INLINE_EARLY_ADVANCE`
|
|
181
|
-
|
|
182
|
-
- Default: enabled
|
|
183
|
-
- Spec 8 runs on the Node.js VM engine only (not QuickJS, and not spec 9 runs). When one inline step of a parallel batch completes or fails while its siblings are still running, the invocation replays the workflow right away instead of waiting for the slowest sibling. A branch of a `Promise.all` can then start its next step without waiting for the other branches.
|
|
184
|
-
- Steps still running stay owned by the invocation that started them. They count against `WORKFLOW_MAX_INLINE_STEPS`, so fewer new steps run inline while they run. A branch that fans out while its siblings still run queues the steps past the remaining slots as background steps.
|
|
185
|
-
- When the workflow returns or throws while one of its inline steps is still running (for example a `Promise.race` loser), the run completes or fails right away. That step gets only its current attempt: the invocation lets its body finish, and the bundled Worlds record its `step_completed`, `step_failed` or `step_retrying` after the run's terminal event, but a retry is never run, so a step whose attempt fails retryably stays pending. This matches what happens when a `sleep()` or hook wins a race. `run_completed` or `run_failed` is therefore not always the last event of a run. With this setting off, the run waits for the loser and its retries. The `workflow.inline.running_at_terminal` and `workflow.inline.discarded_outcomes` span attributes, and an info log, report these steps.
|
|
186
|
-
- A step that retries, is throttled, or leaves stream writes unflushed waits for its whole batch, as with this setting off.
|
|
187
|
-
- Branches whose steps were queued because the batch exceeded `WORKFLOW_MAX_INLINE_STEPS` still advance only when the last pending step of the batch completes.
|
|
188
|
-
- When the invocation hands the run off (its replay budget or inline window is spent), it waits for every inline step still running first, so branches advance in lockstep at that point, as with this setting off. An info log marks the hand-off.
|
|
189
|
-
- `workflow.inline.early_advances` counts early replays and `workflow.inline.slots_held_back` counts steps queued because running steps held the inline slots.
|
|
190
|
-
- Set `0` or `false` to wait for every inline step of a batch before replaying.
|
|
191
|
-
|
|
192
157
|
### `WORKFLOW_TURBO`
|
|
193
158
|
|
|
194
159
|
- Default: enabled
|
|
@@ -211,12 +176,6 @@ For example, a workflow can run a 10-minute inline step even with `WORKFLOW_REPL
|
|
|
211
176
|
- Step inputs made of plain data (objects, arrays, primitives) and standard built-ins (`Map`, `Set`, `Date`, `RegExp`, typed arrays, `ArrayBuffer`, `URL`, `Headers`) keep the VM retained. Patching or polyfilling built-in prototypes doesn't change that because serialization never calls them. A boundary falls back to a full replay only when serializing its arguments runs code the workflow controls, such as a getter, a proxy, or a custom class serializer, or computes an `Error`'s stack trace.
|
|
212
177
|
- Set `0` or `false` to replay the Node.js workflow from scratch in a fresh VM on every iteration.
|
|
213
178
|
|
|
214
|
-
### `WORKFLOW_INLINE_OWNERSHIP`
|
|
215
|
-
|
|
216
|
-
- Default: enabled
|
|
217
|
-
- Records which queue message owns each inline step execution, so a wake (hook resume, elapsed wait) that replays the run mid-step schedules a delayed backstop instead of immediately redispatching and reexecuting the step. See [Inline step message ownership](/docs/changelog/step-message-ownership).
|
|
218
|
-
- Set `0` or `false` to revert to the previous unconditional immediate re-dispatch.
|
|
219
|
-
|
|
220
179
|
### `WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS`
|
|
221
180
|
|
|
222
181
|
- Default: `860`
|
|
@@ -315,12 +274,7 @@ What a snapshot contains, and how it is protected:
|
|
|
315
274
|
|
|
316
275
|
## Transport
|
|
317
276
|
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
- Default: enabled
|
|
321
|
-
- On the Vercel World, lets concurrent event-log requests share one HTTP/2 connection instead of one connection per in-flight request.
|
|
322
|
-
- Set `0` to take the event-log requests off HTTP/2 entirely, back to one request per HTTP/1.1 connection. Use this as the kill switch if HTTP/2 turns out to be at fault for event delivery problems.
|
|
323
|
-
- Has no effect when `WORKFLOW_NODE_HTTP` is enabled, which takes the whole HTTP/2 path away.
|
|
277
|
+
The Vercel World's own transport settings (HTTP/2 multiplexing and the queue client's deadline and connection pool) are listed under [Vercel World](/docs/configuration/worlds#vercel-world).
|
|
324
278
|
|
|
325
279
|
### `WORKFLOW_NODE_HTTP`
|
|
326
280
|
|
|
@@ -339,21 +293,6 @@ Connection pooling, keep-alive, and the request, header, and body deadlines are
|
|
|
339
293
|
|
|
340
294
|
A `dispatcher` passed to `createVercelWorld()` still wins over this variable. The variable chooses which transport the World builds when you have not supplied one.
|
|
341
295
|
|
|
342
|
-
### `WORKFLOW_VERCEL_QUEUE_TIMEOUT_MS`
|
|
343
|
-
|
|
344
|
-
- Default: `30000`
|
|
345
|
-
- Total deadline for one request the Vercel World's queue client makes, measured from the moment it is handed to the transport, so it also covers time the request spends waiting for a free connection.
|
|
346
|
-
- Clamped to `[5000, 120000]`.
|
|
347
|
-
- This is the only request path the World cannot bound with `WORKFLOW_REQUEST_TIMEOUT_MS`, because the queue client makes its own calls and accepts no override for them. Without a deadline here, a queue acknowledgement that never completes holds the invocation until the platform kills it, and a killed invocation never acknowledges, so the message is redelivered.
|
|
348
|
-
- Keep it below the queue's visibility-renewal interval (60 seconds) so a failed call has room to surface and be retried before the message lease lapses.
|
|
349
|
-
|
|
350
|
-
### `WORKFLOW_VERCEL_QUEUE_CONNECTIONS`
|
|
351
|
-
|
|
352
|
-
- Default: `64`
|
|
353
|
-
- Connections the Vercel World's queue client may open to the queue service.
|
|
354
|
-
- Clamped to `[1, 1024]`.
|
|
355
|
-
- Sized much higher than the World's other connection pools on purpose. The queue client makes roughly two small requests per invocation, so its concurrency tracks how many invocations a compute instance is serving at once rather than any per-request fan-out. Lower it only if you have a reason to cap sockets; too low turns invocation concurrency into the limit on how fast messages can be acknowledged.
|
|
356
|
-
|
|
357
296
|
## Queue namespace
|
|
358
297
|
|
|
359
298
|
### `WORKFLOW_QUEUE_NAMESPACE`
|
|
@@ -446,8 +385,9 @@ Everything above describes spec 8 runs, the default. The experimental spec 9 run
|
|
|
446
385
|
|
|
447
386
|
### `WORKFLOW_SPEC_VERSION`
|
|
448
387
|
|
|
449
|
-
- Default: unset. New runs use spec version 8
|
|
388
|
+
- Default: unset. New runs use spec version 8.
|
|
450
389
|
- `9` creates spec 9 runs on a World that declares the in-band fence (the Vercel, Local and Postgres Worlds do). `6` to `8` select that version. A run keeps the version it was created with.
|
|
390
|
+
- `6` creates new runs on the scheme from before the [sealed log](/docs/how-it-works/event-sourcing), where each event position is allocated by the write that occupies it. Use it in an environment shared with a runtime that cannot read sealed logs yet, such as one that pins its own accepted spec range (the Python runtime). Runs below `8` cannot have their hook tokens taken over with [`experimental_force`](/docs/api-reference/workflow/create-hook#take-over-a-token-another-run-holds): a forced hook in another run gets `HookConflictError` instead.
|
|
451
391
|
- Upgrade every deployment and process that shares the World before setting it, and do not roll back below this release once spec 9 runs exist. See [Opting in](/docs/changelog/spec-9#opting-in).
|
|
452
392
|
|
|
453
393
|
### `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS`
|
|
@@ -463,7 +403,12 @@ Everything above describes spec 8 runs, the default. The experimental spec 9 run
|
|
|
463
403
|
### `WORKFLOW_ORCHESTRATOR_LINGER_MS`
|
|
464
404
|
|
|
465
405
|
- Default: `30000`
|
|
466
|
-
- How long an orchestrator with nothing left to run stays live on the event feed while the run waits on
|
|
406
|
+
- How long an orchestrator with nothing left to run stays live on the event feed while the run waits on a background step. `0` turns it off, for hooks too.
|
|
407
|
+
|
|
408
|
+
### `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`
|
|
409
|
+
|
|
410
|
+
- Default: `5000`, and never more than [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](#workflow_orchestrator_linger_ms)
|
|
411
|
+
- How long an orchestrator with nothing left to run stays live on the event feed while the run waits only on open hooks. Any hook that is created and not disposed counts, however rarely it is resumed. `0` turns it off.
|
|
467
412
|
|
|
468
413
|
### `WORKFLOW_ORCHESTRATOR_READ_TIMEOUT_MS`
|
|
469
414
|
|
|
@@ -62,6 +62,7 @@ The Local World is the default outside Vercel and is intended for development.
|
|
|
62
62
|
- Environment variable: `WORKFLOW_LOCAL_DATA_DIR`
|
|
63
63
|
- Default: `.workflow-data`
|
|
64
64
|
- Directory where runs, steps, events, hooks, streams, and the local manifest are written.
|
|
65
|
+
- Also holds the app's queue key (`queue-auth-key`), which the CLI and web UI read to send deliveries, so point them at the same directory. See [`WORKFLOW_QUEUE_AUTH`](/worlds/local#workflow_queue_auth).
|
|
65
66
|
|
|
66
67
|
### `baseUrl`
|
|
67
68
|
|
|
@@ -180,12 +181,11 @@ The Postgres World is a self-hosted durable backend for long-running server proc
|
|
|
180
181
|
### `jobLockStaleSeconds`
|
|
181
182
|
|
|
182
183
|
- Environment variable: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`
|
|
183
|
-
- Default:
|
|
184
|
-
- Seconds a running delivery's job lock may go unrenewed before another process releases
|
|
184
|
+
- Default: unset. Every delivery renews its job lock, and a job in a spec 9 run's named queue whose process died is redelivered after 300 seconds unrenewed, if its holder registered as renewing. Other jobs keep Graphile Worker's fixed 4 hour reset.
|
|
185
|
+
- Seconds a running delivery's job lock may go unrenewed before another process releases any of this World's jobs for redelivery. Setting it extends the release from spec 9 named queues to every job, whoever holds it.
|
|
185
186
|
- `30` is a good value when more than one process shares the database. Use the same value on every process, and keep it well above the longest a process can block its event loop.
|
|
186
|
-
- `0` leaves recovery to Graphile Worker's fixed 4 hour reset and to restarts.
|
|
187
|
-
-
|
|
188
|
-
- To turn it on, set the same value on every process that shares the database once all of them run a version that includes this option. See [Postgres World: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](/worlds/postgres#workflow_postgres_job_lock_stale_seconds).
|
|
187
|
+
- `0` turns renewal and release off, and leaves recovery to Graphile Worker's fixed 4 hour reset and to restarts.
|
|
188
|
+
- Set it only once every process that shares the database runs a version that includes this option. A process on an earlier version neither renews its locks nor fences its acknowledgement on the lock holder, so while it shares the database with a process that has this set, its deliveries that run longer than the window are redelivered, and finishing one can delete the redelivered job. The default is safe for this: it never releases the job of a holder that did not register as renewing. See [Postgres World: `WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`](/worlds/postgres#workflow_postgres_job_lock_stale_seconds).
|
|
189
189
|
|
|
190
190
|
### `maxPoolSize`
|
|
191
191
|
|
|
@@ -193,6 +193,25 @@ The Postgres World is a self-hosted durable backend for long-running server proc
|
|
|
193
193
|
- Default: `pg` default
|
|
194
194
|
- Maximum size of the internal `pg.Pool` when the World creates the pool.
|
|
195
195
|
|
|
196
|
+
### `enableInvoke`
|
|
197
|
+
|
|
198
|
+
- Environment variable: `WORKFLOW_POSTGRES_INVOKE` (`1` enables)
|
|
199
|
+
- Default: `false`
|
|
200
|
+
- Experimental. Delivers hook resumes to the run's executor instead of writing the hook event and enqueueing a wake-up. Apply the migrations and upgrade producers and workers together before enabling it. See [experimental invocation delivery](/worlds/postgres#experimental-invocation-delivery).
|
|
201
|
+
|
|
202
|
+
### `WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`
|
|
203
|
+
|
|
204
|
+
- Factory option: none
|
|
205
|
+
- Default: `0` (no deadline)
|
|
206
|
+
- Maximum time a queue delivery waits for the workflow handler to begin responding before it is failed and redelivered.
|
|
207
|
+
- A delivery runs the workflow inline, so a deadline shorter than your longest inline step redelivers a healthy delivery and runs its steps twice. See [`WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS`](/worlds/postgres#workflow_postgres_headers_timeout_ms).
|
|
208
|
+
|
|
209
|
+
### `WORKFLOW_POSTGRES_BODY_TIMEOUT_MS`
|
|
210
|
+
|
|
211
|
+
- Factory option: none
|
|
212
|
+
- Default: `0` (no deadline)
|
|
213
|
+
- Maximum gap between response body chunks from the workflow handler before the delivery is failed and redelivered. The same caution as `WORKFLOW_POSTGRES_HEADERS_TIMEOUT_MS` applies.
|
|
214
|
+
|
|
196
215
|
### `WORKFLOW_POSTGRES_HOOK_RETENTION_LIMIT_DAYS`
|
|
197
216
|
|
|
198
217
|
- Factory option: none
|
|
@@ -278,7 +297,7 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
|
|
|
278
297
|
- Factory option: none
|
|
279
298
|
- CLI flag: none
|
|
280
299
|
- Default: unset
|
|
281
|
-
- Direct
|
|
300
|
+
- Direct Vercel World backend URL override for testing or custom infrastructure. Normal deployments do not need it.
|
|
282
301
|
|
|
283
302
|
### `VERCEL_QUEUE_MAX_DELAY_SECONDS`
|
|
284
303
|
|
|
@@ -296,16 +315,9 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
|
|
|
296
315
|
- CLI flag: none
|
|
297
316
|
- Default: `60000`
|
|
298
317
|
- Clamp: `10000` to `120000` (values outside are clamped, with a warning)
|
|
299
|
-
- Per-request timeout for Vercel World HTTP calls to
|
|
318
|
+
- Per-request timeout for Vercel World HTTP calls to its backend.
|
|
300
319
|
- At the `10000` floor the run-status long poll disables itself, because its budget is this value minus 10s of headroom.
|
|
301
320
|
|
|
302
|
-
### `WORKFLOW_MAX_CHUNKS_PER_REQUEST`
|
|
303
|
-
|
|
304
|
-
- Factory option: none
|
|
305
|
-
- CLI flag: none
|
|
306
|
-
- Default: `1000`
|
|
307
|
-
- Maximum stream chunks written in one Vercel World request. Larger batches are split.
|
|
308
|
-
|
|
309
321
|
### `WORKFLOW_STREAMS_TRANSPORT`
|
|
310
322
|
|
|
311
323
|
- Factory option: none
|
|
@@ -325,14 +337,6 @@ Platform-provided values such as `VERCEL_DEPLOYMENT_ID`, `VERCEL_PROJECT_ID`, an
|
|
|
325
337
|
- Default: disabled
|
|
326
338
|
- Set `1` to turn off the World's metadata-only `analytics` read namespace, forcing `workflow inspect` and web UI list views onto strongly consistent primary storage. Intended for tests and tooling that read entities immediately after writing them.
|
|
327
339
|
|
|
328
|
-
### `WORKFLOW_BATCH_TRANSITIONS`
|
|
329
|
-
|
|
330
|
-
- Surface: environment variable
|
|
331
|
-
- Default: on
|
|
332
|
-
- Set to `0` (or `false`) to **disable** batched event writes, the escape hatch that restores the exact prior one-write-per-event path.
|
|
333
|
-
|
|
334
|
-
When enabled (the default), a suspension's eager `step_created` and `wait_created` writes fold into batched `events.createBatch` calls (one durable write with per-event outcomes) on Worlds that implement the optional batch API. The fold only engages when the World implements `events.createBatch` (the Vercel World does; Local and Postgres do not), the run's spec version supports slot identity (≥ 6), and the suspension carries no attribute writes. Hook writes in the same suspension go through the single-event path concurrently with the batch. Everything else keeps the single-event path unchanged, so disabling is only needed as an operational escape hatch. Batches are capped at 16 events; larger fan-outs commit in several batches at once. See the [batched event writes changelog](/docs/changelog/batched-event-writes) for the World API contract.
|
|
335
|
-
|
|
336
340
|
### `WORKFLOW_EVENTS_TRANSPORT`
|
|
337
341
|
|
|
338
342
|
- Factory option: none
|
|
@@ -359,3 +363,31 @@ When enabled (the default), a suspension's eager `step_created` and `wait_create
|
|
|
359
363
|
- Largest WebSocket message the Vercel World sends, header included, for both the events and stream-write transports. The ceiling is the 16 MiB WebSocket message limit.
|
|
360
364
|
- Events: a larger frame is sent as several messages and rebuilt on the other side.
|
|
361
365
|
- Stream writes: a larger write group is split into several ordered write requests; a single chunk too large for one message is written over HTTP, as are the rest of that writer's writes.
|
|
366
|
+
|
|
367
|
+
### `WORKFLOW_H2_MULTIPLEX`
|
|
368
|
+
|
|
369
|
+
- Factory option: none
|
|
370
|
+
- CLI flag: none
|
|
371
|
+
- Default: enabled
|
|
372
|
+
- On the Vercel World, lets concurrent event-log requests share one HTTP/2 connection instead of one connection per in-flight request.
|
|
373
|
+
- Set `0` to take the event-log requests off HTTP/2 entirely, back to one request per HTTP/1.1 connection. Use this as the kill switch if HTTP/2 turns out to be at fault for event delivery problems.
|
|
374
|
+
- Has no effect when [`WORKFLOW_NODE_HTTP`](/docs/configuration/runtime-tuning#workflow_node_http) is enabled, which takes the whole HTTP/2 path away.
|
|
375
|
+
|
|
376
|
+
### `WORKFLOW_VERCEL_QUEUE_TIMEOUT_MS`
|
|
377
|
+
|
|
378
|
+
- Factory option: none
|
|
379
|
+
- CLI flag: none
|
|
380
|
+
- Default: `30000`
|
|
381
|
+
- Total deadline for one request the Vercel World's queue client makes, measured from the moment it is handed to the transport, so it also covers time the request spends waiting for a free connection.
|
|
382
|
+
- Clamped to `[5000, 120000]`.
|
|
383
|
+
- This is the only request path the World cannot bound with `WORKFLOW_REQUEST_TIMEOUT_MS`, because the queue client makes its own calls and accepts no override for them. Without a deadline here, a queue acknowledgement that never completes holds the invocation until the platform kills it, and a killed invocation never acknowledges, so the message is redelivered.
|
|
384
|
+
- Keep it below the queue's visibility-renewal interval (60 seconds) so a failed call has room to surface and be retried before the message lease lapses.
|
|
385
|
+
|
|
386
|
+
### `WORKFLOW_VERCEL_QUEUE_CONNECTIONS`
|
|
387
|
+
|
|
388
|
+
- Factory option: none
|
|
389
|
+
- CLI flag: none
|
|
390
|
+
- Default: `64`
|
|
391
|
+
- Connections the Vercel World's queue client may open to the queue service.
|
|
392
|
+
- Clamped to `[1, 1024]`.
|
|
393
|
+
- Sized much higher than the World's other connection pools on purpose. The queue client makes roughly two small requests per invocation, so its concurrency tracks how many invocations a compute instance is serving at once rather than any per-request fan-out. Lower it only if you have a reason to cap sockets; too low turns invocation concurrency into the limit on how fast messages can be acknowledged.
|
|
@@ -67,9 +67,9 @@ export async function processDocumentBatch(documentIds: string[]) {
|
|
|
67
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:
|
|
68
68
|
|
|
69
69
|
1. `start()` records the parent's run ID on the child, and remembers the parent on the returned `Run`.
|
|
70
|
-
2. When the parent awaits a child, it registers its completion hook (a system hook whose token is derived from the parent's run ID)
|
|
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
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.
|
|
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.
|
|
73
73
|
|
|
74
74
|
This gives you:
|
|
75
75
|
|
|
@@ -244,7 +244,7 @@ export async function reviewDocument(documentId: string) {
|
|
|
244
244
|
|
|
245
245
|
## Tips
|
|
246
246
|
|
|
247
|
-
- **Await only the children you need**:
|
|
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.
|
|
248
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.
|
|
249
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
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.
|
|
@@ -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";
|
|
@@ -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
|
|
@@ -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
|
|
@@ -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.
|
|
@@ -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
|
|