workflow 5.5.0 → 5.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/api-workflow.js +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/astro.js +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/internal/builtins.js +1 -1
  6. package/dist/internal/class-serialization.js +1 -1
  7. package/dist/internal/errors.js +1 -1
  8. package/dist/nest-builder.js +1 -1
  9. package/dist/nest-vercel-builder.js +1 -1
  10. package/dist/nest.js +1 -1
  11. package/dist/next.cjs +1 -1
  12. package/dist/nitro.js +1 -1
  13. package/dist/nuxt.js +1 -1
  14. package/dist/observability.js +1 -1
  15. package/dist/runtime.js +1 -1
  16. package/dist/stdlib.js +1 -1
  17. package/dist/sveltekit.js +1 -1
  18. package/dist/typescript-plugin.cjs +1 -1
  19. package/dist/vite.js +1 -1
  20. package/dist/workflow.js +1 -1
  21. package/docs/api-reference/workflow-api/get-run.mdx +0 -4
  22. package/docs/api-reference/workflow-api/resume-hook.mdx +1 -1
  23. package/docs/api-reference/workflow-api/start.mdx +1 -1
  24. package/docs/api-reference/workflow-errors/in-band-superseded-error.mdx +0 -3
  25. package/docs/api-reference/workflow-errors/index.mdx +1 -1
  26. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +0 -2
  27. package/docs/api-reference/workflow-errors/workflow-not-registered-error.mdx +1 -1
  28. package/docs/api-reference/workflow-runtime/world/queue.mdx +70 -3
  29. package/docs/comparisons/index.mdx +4 -1
  30. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +3 -1
  31. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +4 -1
  32. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +271 -28
  33. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +6 -2
  34. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +2 -0
  35. package/docs/configuration/cli-and-web-ui.mdx +31 -1
  36. package/docs/configuration/runtime-tuning.mdx +9 -8
  37. package/docs/configuration/worlds.mdx +18 -21
  38. package/docs/cookbook/advanced/child-workflows.mdx +1 -1
  39. package/docs/cookbook/common-patterns/batching.mdx +1 -1
  40. package/docs/errors/index.mdx +1 -0
  41. package/docs/errors/max-events-exceeded.mdx +2 -2
  42. package/docs/errors/replay-timeout.mdx +2 -2
  43. package/docs/errors/workflow-not-registered.mdx +1 -1
  44. package/docs/foundations/errors-and-retries.mdx +1 -4
  45. package/docs/how-it-works/event-sourcing.mdx +2 -5
  46. package/docs/how-it-works/framework-integrations.mdx +2 -2
  47. package/docs/internal/index.mdx +1 -0
  48. package/docs/internal/nitro-native-build.mdx +1 -0
  49. package/docs/internal/nitro-web-ui.mdx +1 -0
  50. package/docs/internal/serializable-abort-controller.mdx +1 -0
  51. package/docs/observability/index.mdx +2 -0
  52. package/docs/whats-new.mdx +3 -3
  53. package/docs/worlds/building-a-world.mdx +46 -4
  54. package/docs/worlds/local.mdx +110 -25
  55. package/docs/worlds/postgres.mdx +107 -27
  56. package/docs/worlds/upgrading-to-v5.mdx +4 -4
  57. package/docs/worlds/vercel.mdx +190 -82
  58. package/package.json +16 -14
  59. package/dist/api-workflow.d.ts.map +0 -1
  60. package/dist/api.d.ts.map +0 -1
  61. package/dist/astro.d.ts.map +0 -1
  62. package/dist/index.d.ts.map +0 -1
  63. package/dist/internal/builtins.d.ts.map +0 -1
  64. package/dist/internal/class-serialization.d.ts.map +0 -1
  65. package/dist/internal/errors.d.ts.map +0 -1
  66. package/dist/nest-builder.d.ts.map +0 -1
  67. package/dist/nest-vercel-builder.d.ts.map +0 -1
  68. package/dist/nest.d.ts.map +0 -1
  69. package/dist/nitro.d.ts.map +0 -1
  70. package/dist/nuxt.d.ts.map +0 -1
  71. package/dist/observability.d.ts.map +0 -1
  72. package/dist/runtime.d.ts.map +0 -1
  73. package/dist/stdlib.d.ts.map +0 -1
  74. package/dist/sveltekit.d.ts.map +0 -1
  75. package/dist/vite.d.ts.map +0 -1
  76. package/dist/workflow.d.ts.map +0 -1
  77. package/docs/changelog/attributes-mvp.mdx +0 -380
  78. package/docs/changelog/batched-event-writes.mdx +0 -77
  79. package/docs/changelog/eager-processing.mdx +0 -273
  80. package/docs/changelog/index.mdx +0 -19
  81. package/docs/changelog/lazy-event-creation.md +0 -127
  82. package/docs/changelog/lazy-hook-resume.mdx +0 -78
  83. package/docs/changelog/meta.json +0 -16
  84. package/docs/changelog/resilient-resume.mdx +0 -32
  85. package/docs/changelog/resilient-start.mdx +0 -77
  86. package/docs/changelog/spec-9.mdx +0 -4167
  87. package/docs/changelog/step-message-ownership.mdx +0 -355
  88. package/docs/changelog/turbo-mode.md +0 -91
@@ -1,273 +0,0 @@
1
- ---
2
- title: Eager processing of steps and incremental event replay
3
- description: Combine workflow event replay and step bundles to do work inline where possible, only deferring to the queue for parallelism.
4
- type: overview
5
- ---
6
-
7
- # Eager processing of steps and incremental event replay
8
-
9
- **Date**: March 2026
10
-
11
- This is a major internal architecture change to how Workflow DevKit executes workflows and steps. It reduces function invocations and queue overhead by executing steps _inline_ within the same function invocation as the workflow replay, rather than dispatching every step to a separate function via the queue.
12
-
13
- ## Previous architecture
14
-
15
- The previous architecture used two separate routes, each backed by its own queue trigger:
16
-
17
- ```text
18
- Queue: __wkf_workflow_* --> /.well-known/workflow/v1/flow (workflow replay in VM)
19
- |
20
- suspension (step needed)
21
- |
22
- queue step to __wkf_step_*
23
- |
24
- Queue: __wkf_step_* --> /.well-known/workflow/v1/step (step execution in Node.js)
25
- |
26
- step completes
27
- |
28
- queue continuation to __wkf_workflow_*
29
- v
30
- (cycle repeats for each step)
31
- ```
32
-
33
- Each step required **2 queue messages** (step invocation and workflow continuation) and **2 function invocations**, plus cold-start overhead for each. A serial workflow with 10 steps needed approximately 21 function invocations.
34
-
35
- ## New architecture
36
-
37
- The two routes are merged into a single handler at `/.well-known/workflow/v1/flow` using `workflowEntrypoint()`. The step route is no longer generated.
38
-
39
- The handler runs an inline execution loop:
40
-
41
- ```text
42
- receive queue message
43
- |
44
- +-- if message has stepId+stepName: execute that step, queue workflow continuation, exit
45
- |
46
- v
47
- replay workflow in VM
48
- |
49
- +-- workflow completed --> create run_completed event, exit
50
- +-- workflow failed --> create run_failed event, exit
51
- |
52
- v
53
- suspension with pending operations
54
- |
55
- +-- process hooks and waits (unchanged)
56
- |
57
- +-- 0 pending steps --> return (waits/hooks only)
58
- +-- 1 pending step --> execute inline, loop back to replay
59
- +-- N pending steps --> queue N-1 to self (with stepId),
60
- | execute 1 inline, loop back to replay
61
- |
62
- +-- timeout check: if wall-clock time >= threshold,
63
- | re-schedule self via queue and exit
64
- |
65
- v
66
- (loop continues until completion, timeout, or non-step suspension)
67
- ```
68
-
69
- A serial workflow with 10 steps now completes in **1 function invocation**.
70
-
71
- ## Background steps (parallel execution)
72
-
73
- When a workflow suspends with multiple pending steps (for example, from `Promise.all`), the handler creates `step_created` events for all of them, queues N-1 back to `__wkf_workflow_*` with `stepId` and `stepName` in the message payload, executes 1 step inline, and loops back to replay.
74
-
75
- Each background step message is handled by a separate function invocation of the same handler. When a message arrives with `stepId` and `stepName`, the handler executes that specific step, then checks if all parallel steps from the batch are done by comparing `step_created` events against terminal events (`step_completed`/`step_failed`):
76
-
77
- - **All steps done**: The handler replays the workflow inline, continuing the execution loop without a queue roundtrip.
78
- - **Steps still pending**: The handler returns without queuing a continuation. The last handler to complete its step will see all steps done and replay inline.
79
- - **Pending ops (stream writes)**: The handler queues a continuation and returns, so `waitUntil` can flush the pending stream data.
80
-
81
- The inline steps of one invocation do not wait for each other. When one of them completes while its siblings are still running, the handler replays the workflow right away, so the branch it belongs to can start its next step inline. The siblings stay owned by this handler. If the workflow returns or throws first, the run ends right away; the handler still lets the siblings' bodies finish before it returns, so their step events can follow `run_completed` or `run_failed` in the log, and a sibling whose attempt fails retryably is not retried.
82
-
83
- ### Convergence after parallel steps
84
-
85
- When multiple background steps complete near-simultaneously, multiple handlers may observe "all steps done" and attempt to advance the workflow concurrently. The event-sourced architecture plus the invariants below ensure safe convergence:
86
-
87
- - **`step_created` idempotency**: Duplicate creates return 409; exactly one handler owns each step.
88
- - **`step_completed` / `step_failed` idempotency**: Only the first invocation to record a terminal result wins.
89
- - **Queue idempotency keys**: Background step messages use `correlationId` as the idempotency key.
90
- - **Deterministic replay**: All invocations produce the same result given the same event log.
91
-
92
- ### Single inline executor per step
93
-
94
- Inline step execution combined with background-step dispatch introduces a new coordination requirement: when multiple handlers reach the same `Promise.all` batch concurrently, we need to guarantee that each step body runs at most once via the inline path. Without that guarantee, the event log accumulates duplicate `step_started` events (including some written *after* `step_completed`, which orphans them on replay) and step bodies run redundantly.
95
-
96
- The design enforces one invariant: **exactly one handler owns each step, and only the owner may execute it inline**. Ownership is established by the atomicity of `step_created`:
97
-
98
- 1. **Atomic `step_created`**: `events.create('step_created', correlationId=X)` is serialized per correlation ID in every world. Exactly one concurrent caller succeeds; the rest receive `EntityConflictError`.
99
- 2. **Suspension handler reports ownership**: Only `step_created` writes that succeeded (not those that caught 409) count toward ownership.
100
- 3. **Inline execution is gated on ownership**: A handler that didn't win any `step_created` race performs no inline execution.
101
- 4. **Queueing is unconditional**: For every pending step except the one being executed inline, the handler enqueues a background step message with `idempotencyKey: correlationId`. This makes crash recovery work: if a prior handler wrote `step_created` but crashed before enqueueing, a later handler will enqueue the orphaned step. Concurrent handlers' redundant enqueues deduplicate on the idempotency key.
102
-
103
- Together these give: every `step_created` event has exactly one inline executor **and** at least one queued dispatch. Step bodies are never executed concurrently, and `step_started` events never land in the log after `step_completed` for the same step.
104
-
105
- **Retry semantics are preserved**: a step that is currently running (status=`running`) still accepts a second `step_started` write with an incremented attempt counter: this is how queue redelivery after a SIGKILL mid-execution legitimately re-runs the step.
106
-
107
- ## Incremental event loading
108
-
109
- The handler caches the event log in memory across loop iterations. Instead of re-fetching the entire event log on each replay:
110
-
111
- 1. **First iteration**: Load all events and return the final pagination cursor.
112
- 2. **Subsequent iterations**: Fetch only events created after the saved cursor and append them to the cached array.
113
-
114
- For a 10-step serial workflow completing in one invocation, the 10th replay loads ~2 new events instead of re-fetching all ~30.
115
-
116
- Incremental loading depends on the World returning a cursor even on the final page of results. If a World implementation does not return a cursor after the initial load, the handler logs an error and falls back to a full reload.
117
-
118
- ## Timeout handling
119
-
120
- The inline execution loop checks wall-clock time before each replay iteration. If the elapsed time exceeds a configurable threshold (110s by default for a 120-second function limit), the handler reschedules itself through the queue and returns. Configure the threshold with `WORKFLOW_V2_TIMEOUT_MS`.
121
-
122
- If a single step takes longer than the timeout threshold, the step runs to completion (or SIGKILL). There is no interruption mechanism for in-progress step execution. This is the same behavior as the previous architecture.
123
-
124
- ## Queue message changes
125
-
126
- The `WorkflowInvokePayload` schema has two new optional fields: `stepId` and `stepName`. When `stepId` is present, the handler executes that specific step before (or instead of) replaying the workflow. Background steps are queued with both set, so the handler knows which step function to call without loading the event log. Previously, `stepName` was resolved by loading all events and searching for the `step_created` event matching the `stepId`, an O(N) operation on the full event history for every background step arrival.
127
-
128
- The queue trigger configuration uses `WORKFLOW_QUEUE_TRIGGER` on the `__wkf_workflow_*` topic. The `__wkf_step_*` topic and its separate trigger are no longer generated.
129
-
130
- ## Generated file layout
131
-
132
- ```text
133
- .well-known/workflow/v1/
134
- flow/
135
- route.js # Handler (workflowEntrypoint)
136
- __step_registrations.js # Step function registrations (side effects)
137
- webhook/
138
- [token]/
139
- route.js # Webhook handler (unchanged)
140
- manifest.json # Workflow/step/class manifest (unchanged)
141
- config.json # Functions config (single trigger)
142
- ```
143
-
144
- The `step/` directory is no longer generated.
145
-
146
- ## Design notes and tradeoffs
147
-
148
- ### Parent→child polling holds worker slots
149
-
150
- `Run#returnValue` is implemented as a polling step: the workflow awaits the child run's terminal status inside a step body. In worker-based Worlds (notably `world-postgres`), each such poll occupies a queue worker slot until the child run finishes. Parent workflows that fan out to many child runs, such as recursive workflows like `fibonacciWorkflow`, can therefore consume a large fraction of available workers while holding positions in `Promise.all([...children.map(c => c.returnValue)])`.
151
-
152
- If `queueConcurrency` is smaller than the peak number of concurrent parent polls plus the workers needed for any in-flight children, the system deadlocks: every slot is held by a parent waiting on a child, but no child can acquire a slot to start.
153
-
154
- For `world-postgres`, the default `queueConcurrency` is set to **50**. Workflows that fan out more aggressively must raise this ceiling.
155
-
156
- To prevent deadlock when polling is executed inline by the step executor, `Run#pollReturnValue()` detects when it's running inside a step executor and throws `TooEarlyError` instead of polling in a blocking loop. The step executor handles `TooEarlyError` by re-queueing the step with a 1-second delay, freeing the worker. Unlike `RetryableError`, `TooEarlyError` does NOT count against `maxRetries`, so polling steps can retry indefinitely until the child completes.
157
-
158
- **Follow-up**: Replace the worker-pool sizing requirement with a polling design that does not occupy a worker slot. Options under consideration: moving child-completion polling out of the step body into the suspension layer, or emitting a `run_completed` notification on the parent's stream/queue so the parent only resumes when the child actually finishes.
159
-
160
- **Update**: A parent awaiting `returnValue` of a child it started now suspends on a system hook the child resumes when it finishes, so it holds no worker slot while it waits. Only `returnValue` awaits that fall back to polling (inside a step, or with `WORKFLOW_CHILD_RUN_COMPLETION_HOOK=0`) still count toward this sizing. See [Child Workflows](/cookbook/advanced/child-workflows#how-the-parent-waits).
161
-
162
- ### Mixed suspensions
163
-
164
- A suspension may contain steps, hooks, and waits simultaneously. The handler creates events for all, then dispatches everything we are not running inline as a single parallel batch of queue messages:
165
-
166
- ```text
167
- ownedPendingSteps = pendingSteps.filter(owned by this handler)
168
- inlineStep = ownedPendingSteps[0] // optional
169
-
170
- dispatches = [
171
- ...for each non-inline pendingStep: queue stepId message (idempotency=correlationId),
172
- ...if soonest pending wait: queue delayed continuation
173
- (delaySeconds=min(remaining, maxDelay),
174
- idempotency=waitCorrelationId[:hop|:secondBucket]),
175
- ]
176
- await Promise.all(dispatches)
177
-
178
- if (!inlineStep) return
179
- await executeStep(inlineStep)
180
- ```
181
-
182
- The wait timer is queued as its own continuation rather than encoded in the handler's return value (`{ timeoutSeconds }`). This is what makes `Promise.race(step, sleep)` behave correctly: even when the inline step blocks the handler for the full step duration, the wait continuation fires in a separate function invocation. If the sleep wins, that parallel invocation observes `wait_completed` via the "complete elapsed waits" pass and finishes the run; if the step wins, the wait continuation fires later and no-ops on the terminal run via the existing terminal-event check.
183
-
184
- Step queueing remains unconditional (covers crash recovery: if a prior handler wrote `step_created` but crashed before queueing, a later handler will queue it; idempotency keys dedupe redundant queues across concurrent handlers).
185
-
186
- Wait continuations are likewise deduplicated, keyed on the wait's correlation ID: while a wait is pending, every replay pass over the run re-observes it and would otherwise enqueue another delayed continuation. A key is attached in all cases, since some worlds serialize key-less workflow messages per run, which would park the continuation behind the handler's own inline step execution.
187
-
188
- Two situations deliver a continuation while its wait is still pending, and each varies the key so the re-enqueue isn't dropped by a world's dedupe window (which outlives the first delivery): waits longer than the maximum queue delay (23h, bounded by VQS's 24h message retention) are clamped and chained across hops, with the hop index suffixed to the key so each hop dedupes within its window but the chain always advances; and near-elapsed waits (≤2s remaining) use a second-bucketed key suffix so a continuation delivered marginally early (clock skew) can enqueue a fresh short-delay retry. See `runtime/wait-continuation.ts` for the full selection logic.
189
-
190
- The retry/throttle and hook-conflict paths still return `{ timeoutSeconds }` since their semantics are "redeliver THIS message after a delay" rather than "schedule a fresh wait timer." Those can be unified in a follow-up.
191
-
192
- The unified dispatch requires `world-local` to honor `delaySeconds` on the queue (added in the same PR series). Without it, the wait continuation would fire instantly in dev and trigger a spurious replay before the wait elapsed (recoverable via redelivery, but inefficient and observable as duplicate `step_started` events under contention).
193
-
194
- ### VM sandboxing
195
-
196
- Workflow code still runs in a Node.js VM for determinism and sandboxing. Step code runs in the Node.js host context. The only change is that both happen within the same function invocation.
197
-
198
- ### Bundle size and cold start
199
-
200
- The combined bundle is larger (contains both step code and workflow VM code). Cold start time increases slightly. The reduction in total function invocations more than compensates.
201
-
202
- ### Step retries
203
-
204
- When an inline step fails with retries remaining:
205
-
206
- - `RetryableError` with explicit `retryAfter` delay: Requeue to self with `stepId` and a delay.
207
- - Transient errors with immediate retry: Requeue to self with `stepId` and a 1s delay.
208
- - `FatalError`: Fail immediately.
209
-
210
- ### Encryption key resolution
211
-
212
- Encryption keys are resolved once before the inline execution loop starts (after the run status is confirmed as `running`) and reused across all iterations. Background step executions resolve the key independently. The key does not change within a run.
213
-
214
- ### Module scope duplication in re-bundled output
215
-
216
- Builders that rebundle the combined output into a single file (standalone Workflow CLI, Vercel Build Output API, and NestJS) produce a layout where esbuild creates isolated module scopes for each source module, even within the same output file. Without intervention, `registerStepFunction` and `getStepFunction` operate on different `Map` instances: steps are registered into one `Map` but looked up from another.
217
-
218
- The step function registry and the step context storage are `globalThis` singletons (via `Symbol.for`) to ensure all module scopes share the same instances. The same pattern is used for the World singleton and the class serialization registry.
219
-
220
- ### Inline step execution with pending stream operations
221
-
222
- When a step's arguments or return value include serialized streams (e.g., `WritableStream` from `getWritable()`, or AI SDK streaming steps), the serialization layer creates background `flushablePipe` operations that pipe data to S3. These ops are tracked in an `ops` array and need to complete before the stream data is readable by external consumers.
223
-
224
- In V1, each step ran in a separate function invocation. After the step completed, `waitUntil(ops)` kept the function alive to flush the ops. In V2, the inline execution loop continues immediately after the step body returns, so we need to know whether to keep looping or break out and let `waitUntil` flush.
225
-
226
- `executeStep()` attempts a 500ms `Promise.race` between the ops settling and a timeout. If ops settle in time (data confirmed on server), it returns `hasPendingOps: false` and the V2 handler continues the inline loop. If ops don't settle in 500ms (e.g., `WritableStream` kept open across steps), it returns `hasPendingOps: true` and the V2 handler breaks the loop and queues a continuation so `waitUntil` can flush them.
227
-
228
- **Follow-up**: Shrink the 500ms inline-ops budget once we have confidence that the flush-waiter path settles deterministically across all worlds. A signaled "ops drained" event from the world layer would let `executeStep()` proceed without the timeout in the common case.
229
-
230
- ### Buffered stream flush with waiter promises
231
-
232
- `WorkflowServerWritableStream` buffers writes and flushes via a 10ms `setTimeout` for batching. Naively, `write()` could return immediately after buffering, but that would cause the `flushablePipe`'s `pendingOps` counter to reach 0 before data actually reached the server: the V2 inline loop would see ops as settled prematurely and produce data-loss races on every step with `WritableStream` serialization.
233
-
234
- `write()` returns a promise that resolves only after the scheduled flush completes. Multiple writes within the 10ms window still share a single batched HTTP request (the batching optimization is preserved). Each write registers a `{resolve, reject}` pair in a `flushWaiters` array. When the `setTimeout` fires and `flush()` completes the HTTP round-trip, all waiters are resolved (or rejected on error). This makes `pendingOps` accurately reflect server-side data state while keeping network-efficient batching.
235
-
236
- ### Lock-release polling interval
237
-
238
- `flushablePipe`'s `pollWritableLock` / `pollReadableLock` use `setInterval` to detect when a user releases their stream lock without closing the stream, since the Web Streams API has no event for that state. The V2 step executor's `opsSettled` race waits for this poll to resolve after each writable-bearing step body returns, so the polling interval sits on the critical path of every streaming step.
239
-
240
- The interval was lowered from 100ms to 10ms. Per-step wait drops from ~50ms average to ~5ms (scaling linearly with the number of writable-bearing steps in a workflow). Per-tick work is `writable.locked` plus a `getWriter()`/`releaseLock()` probe (microsecond-scale), so 10× more ticks is not measurable in practice.
241
-
242
- **Follow-up**: Replace polling entirely with an event-driven release signal (wrap the writable returned from the `WritableStream` reviver with a writer that fires on `releaseLock()`), bringing the wait to ~0ms. This would also remove a source of timing drift between worlds with synchronous storage (`world-local`) and worlds with HTTP-deferred storage (`world-vercel`).
243
-
244
- ### Concurrent `step_started` and attempt counter
245
-
246
- When the V2 handler dispatches N parallel steps as background messages, each background step completion queues a workflow continuation. Up to N continuations may replay concurrently, and each may attempt to start the same not-yet-completed step (since `step_started` succeeds for already-running steps). Each call atomically increments the `attempt` counter, so with N=5 parallel steps, the counter can reach 5 on the first genuine execution.
247
-
248
- The max retries check in `executeStep()` only enforces when `step.error` exists, distinguishing actual retries (failed → retry with error) from concurrent first-attempt races (multiple handlers start the same step simultaneously without any prior failure). Concurrent starts are harmless since `step_completed` idempotency ensures only the first completion wins.
249
-
250
- ### Unconsumed event check two-phase drain
251
-
252
- The `EventsConsumer`'s unconsumed event check uses a two-phase promise queue drain: yield once after the first drain (via `setTimeout(0)`) so cross-VM promise chains can append follow-up async work, then re-drain before checking. This improves timing for scenarios like `step_completed` → for-await loop resume → next hook hydration.
253
-
254
- The check additionally arms a `DEFERRED_CHECK_DELAY_MS = 100` `setTimeout` after the second drain, since Node.js does not guarantee that `setTimeout(0)` fires after all cross-context microtasks settle. Any `subscribe()` call arriving during that 100ms window cancels the check via version invalidation + `clearTimeout`, so the delay only adds latency to genuine corruption, never to the happy path.
255
-
256
- **Follow-up**: 100ms is a heuristic chosen empirically. A deterministic settlement signal (for example, a "VM idle" callback exposed by the workflow VM bridge that fires only after all pending cross-context promise chains have resolved) would let the consumer fire the unconsumed-event check immediately on quiescence instead of waiting for a wall-clock timeout.
257
-
258
- ### Lazy World loading
259
-
260
- Static imports of `world-local` and `world-vercel` from the runtime caused two distinct build-time issues: Next.js production builds pulled both worlds (including their Node-only deps like `debug`'s `tty` requires) into the route module, and Turbopack's NFT (Node File Trace) errored on `process.cwd()` and dynamic `import()` patterns it couldn't statically analyze.
261
-
262
- A `getWorldLazy()` accessor (backed by a `globalThis` `Symbol.for` cache) replaces the static import in step-side modules. This breaks the static import chain from step code to `world.ts`, preventing both worlds from being bundled into the step registrations.
263
-
264
- Because tree-shaking can otherwise drop `world.ts`'s module-load registration entirely, a server-only side-effect module (`@workflow/core/runtime/world-init`) imports `./world.js` purely for its module-load side effect. It's wired via package conditions:
265
-
266
- - `default` maps to the real module and loads `world.ts`.
267
- - `workflow` maps to an empty stub used by VM and step bundles.
268
-
269
- This guarantees the world is loaded for routes that consume `start()` without going through the queue-driven flow handler first, while keeping `world.ts` and its server-only deps out of the workflow sandbox bundle.
270
-
271
- ### Community Worlds and the `world.streams` API
272
-
273
- Community world adapters must implement the `world.streams.*` interface. The runtime legacy stream normalization was removed as part of this work.
@@ -1,19 +0,0 @@
1
- ---
2
- title: Changelog
3
- description: Latest updates and new features in Workflow SDK.
4
- type: overview
5
- ---
6
-
7
- # Changelog
8
-
9
- Stay up to date with the latest changes to Workflow SDK.
10
-
11
- ---
12
-
13
- ## 2026
14
-
15
- - [Spec 9: single orchestrator](/docs/changelog/spec-9), opt-in (October 2026)
16
- - [Durable hook resume](/docs/changelog/lazy-hook-resume) (August 2026)
17
- - [Resilient hook resume](/docs/changelog/resilient-resume) (July 2026)
18
- - [Eager processing of steps and incremental event replay](/docs/changelog/eager-processing) (March 2026)
19
- - Serializable AbortController and AbortSignal (March 12, 2026)
@@ -1,127 +0,0 @@
1
- ---
2
- title: Lazy inline step start
3
- description: Defer step_created for the inline step and fold it into a single step_started, saving one world round-trip per inline step.
4
- ---
5
-
6
- # Lazy inline step start
7
-
8
- ## Motivation
9
-
10
- The owned-inline runtime path used to write two separate world events for a step it already owns and is about to run inline:
11
-
12
- 1. `step_created`, written by the suspension handler (`suspension-handler.ts`)
13
- 2. `step_started`, written by `executeStep` (`step-executor.ts`)
14
- 3. `step_completed` / `step_failed`, written by `executeStep`
15
-
16
- On the Vercel world each `world.events.create` is a network round-trip, so for a sequential `"use step"` workflow this is pure latency between steps. Steps (1) and (2) are two round-trips for a step we already own and are about to execute in the same invocation.
17
-
18
- This change defers `step_created` for that one inline step: `executeStep` sends a single `step_started` carrying the step input, and the world creates the step on the fly. This materializes the step entity **and** a synthetic `step_created` event so replay still observes it. **Two writes per inline step instead of three.** It mirrors the existing [resilient `run_started` → `run_created`](./resilient-start) pattern.
19
-
20
- Steps that are *queued* (not run inline) keep their eager `step_created` and are unchanged. Only the single inline step per suspension is made lazy.
21
-
22
- ## Design
23
-
24
- ### Suspension handler
25
-
26
- - `handleSuspension` selects exactly one step to defer: the first uncreated step (`stepItems.find(item => stepsNeedingCreation.has(...))`), which matches the inline candidate the caller would have picked.
27
- - For that step it **skips** the `step_created` write and instead returns it as `lazyInlineStep = { correlationId, stepName, dehydratedInput }`. It is **not** added to `createdStepCorrelationIds` because ownership is no longer decided here.
28
- - A `lazyInlineStep` is designated only when there is no `hook.getConflict()` awaiter (`hasAwaitedHookCreation === false`). With an awaiter present nothing runs inline, so nothing is deferred.
29
-
30
- ### `executeStep`
31
-
32
- - A new `lazyStepInput` parameter carries the already-dehydrated input. When present, the `step_started` event includes `input` so the world creates the step on the fly. When absent, `step_started` carries only `stepName` (the legacy contract).
33
- - For an **unregistered** step on the lazy path, `executeStep` sends the lazy `step_started` first to materialize the step, *then* writes `step_failed` (see [Materialize before failing](#materialize-before-failing-unregistered-steps) below).
34
-
35
- ### World contract
36
-
37
- - `step_started` accepts an optional `input`. When provided for a non-existent step, the world atomically creates the step entity plus a **synthetic `step_created`** event (so the event log reads `created → started → completed`), then records `step_started`.
38
- - A `stepCreated` signal is added to the event result so callers can tell whether the lazy `step_started` created the step or attached to an existing one.
39
- - Worlds updated: `world-local`, `world-postgres`, `world-vercel`.
40
-
41
- ## Interactions with inline execution
42
-
43
- ### Exactly-one-owner is preserved (the race moved)
44
-
45
- The guarantee that exactly one handler runs a step's body inline is intact, but it resolves at a different event:
46
-
47
- - **Before:** ownership was won at the atomic `step_created` claim in the suspension handler; the loser caught `EntityConflictError` and queued instead.
48
- - **After:** two concurrent handlers may both *select* the same `lazyInlineStep` (selection is optimistic, before any race). The race is now the world's atomic create-claim inside the lazy `step_started` (lock file in world-local, `onConflictDoNothing` + unique index in world-postgres, `attribute_not_exists` on the server). The loser gets `EntityConflictError`, which `executeStep` maps to `{ type: 'skipped' }`, so it never runs the body.
49
-
50
- This is safe **because a lazy `step_started` is only ever sent for a brand-new step**. The suspension handler defers only steps with no prior `step_created` (`!hasCreatedEvent`).
51
-
52
- ### Crash recovery is unchanged
53
-
54
- On crash recovery the step already has a `step_created` event in the log (`hasCreatedEvent === true`), so it is **not** a lazy candidate. It is re-queued and re-run via a normal **non-lazy** `step_started`, which re-starts a `running` step. At-least-once execution is preserved exactly as before.
55
-
56
- ### Materialize before failing unregistered steps
57
-
58
- The inline path previously assumed an invariant: *by the time `executeStep` runs, the step entity already exists* (the suspension handler created it). The unregistered-step branch relied on this and writes `step_failed` directly, with no preceding `step_started`.
59
-
60
- With the `step_created` deferred, the entity no longer exists when `executeStep` bails for an unregistered step, so the `step_failed` write hits the world's "step must exist" ordering guard and is rejected, wedging the run until it times out. On the lazy path, send the lazy `step_started` first (creating the entity + synthetic `step_created`), then write `step_failed`. The lazy `step_started`'s atomic create-claim still preserves exactly-one-owner. A concurrent winner makes our create reject with `EntityConflictError` → `skipped`, so the failure is never written twice.
61
-
62
- This is the general rule the deferral introduces: **any inline path that writes a terminal step event must first ensure the deferred step has been materialized.**
63
-
64
- ### Replay correctness and the inline-delta fast path
65
-
66
- The client step consumer (`step.ts`) sets `hasCreatedEvent` only when it observes a `step_created` event, and checks step-name divergence against `stepName`. The lazy path stays replay-correct only because the world writes a **synthetic `step_created`**: replay still sees `created → started → completed`. The input lives on the synthetic `step_created`; the `step_started` row drops the input but keeps `stepName` for the divergence check.
67
-
68
- This intersects with the inline-delta optimization. The delta returned on the `step_completed` write is consumed by the *next* replay in place of an `events.list`, diffed against `preInlineWriteCursor` (snapshotted before replay). Because the synthetic `step_created`, `step_started`, and `step_completed` are all written *after* that cursor, the world's "events since cursor" delta carries the full triple, so the next replay does not diverge. The delta gate (one step, no hooks/waits, the lone pending step is the inline one) is unchanged.
69
-
70
- ### Pre-emption by attributes / hook conflicts
71
-
72
- When `attr_set` events force an immediate in-process replay, or a hook conflict forces a re-invocation, the handler skips the dispatch loop for that pass. The deferred step is therefore **neither created nor queued** on that pass; it is recreated and run on the following replay (where it is still a lazy candidate).
73
-
74
- This is a small behavioral improvement: previously the eager `step_created` left an orphan "created but never started" event when a step lost an attribute/hook race (e.g. `Promise.race([setAttributes(), step()])` where the attribute write wins and completes the run). With deferral, a step that loses the race is never created, reducing event-log garbage.
75
-
76
- ### `hook.getConflict()` awaiter
77
-
78
- When a `hook.getConflict()` awaiter is present, no `lazyInlineStep` is designated, nothing runs inline, every step gets its eager `step_created` and is queued, and the handler re-invokes immediately so replay resolves the awaiter. This is identical to the pre-change behavior. The deferral never serializes the awaiter's parallel continuation behind an inline step.
79
-
80
- ## Rollout and compatibility
81
-
82
- Server-first. The matching world-vercel backend change must deploy before this ships; the Vercel world targets a single backend whose spec version is always at least the SDK's, so the new SDK only ever talks to an already-upgraded backend. An old SDK against a new backend is safe because the lazy path is strictly additive. It triggers only when `step_started` carries both `stepName` and `input`, which old SDKs never send. For `world-local` / `world-postgres` the world ships in the same package as the runtime, so there is no version skew. Detection is by `input` presence on the event, mirroring resilient `run_started`, so no capability negotiation is needed.
83
-
84
- # Parallel inline steps + optimistic start
85
-
86
- A follow-up builds two more latency wins on top of lazy inline start. Both are client-side only; they reuse the world's lazy create-on-`step_started` support and need no further world/backend changes.
87
-
88
- ## Inline up to N steps in parallel
89
-
90
- Previously the owned-inline path ran **exactly one** step inline per suspension and queued the rest. For a `Promise.all([stepA(), stepB(), stepC()])` fan-out that meant one branch ran inline while the others paid a queue round-trip each before making any progress.
91
-
92
- The suspension handler now defers `step_created` for up to **`WORKFLOW_MAX_INLINE_STEPS` (default 3)** steps and returns them as `lazyInlineSteps`. The runtime runs that batch inline **in parallel**, each via its own lazy `step_started`, and queues only the steps beyond the cap. The runtime replays as soon as one step of the batch settles, so steps still running hold their slots and a later suspension gets fewer.
93
-
94
- - **Selection:** the first N uncreated steps, matching the previous single-step inline candidate. Steps beyond N keep their eager `step_created` and are queued exactly as before.
95
- - **Result aggregation:** `retry` steps (whose `step_started` succeeded, so the step exists) are re-queued per-step as background steps with their own delay. `throttled` steps are different: a throttle rejects the lazy `step_started` on the create-claim, so the step was *never created* and has no recoverable input. Re-queuing it as an input-less background step would make the world reject the bare `step_started` with "Step not found" and redeliver until it fails. Any throttle instead **defers redelivery of the orchestrator** (by the longest throttle backoff in the batch), which re-runs the throttled step inline *with its input* on replay. The runtime only loops back to replay in-process once every inline step has reached a terminal state.
96
- - **Inline-delta fast path:** still used only for the single-step sequential case (`lazyInlineSteps.length === 1`). With more than one inline step each writes its own events, so a per-write delta would be partial; multi-step batches fall back to a normal incremental `events.list`.
97
- - **Config:** `WORKFLOW_MAX_INLINE_STEPS` is clamped to 1..16. Setting it to `1` reproduces the previous single-inline-step behavior exactly (a useful kill-switch). Inline bodies run in parallel within one function invocation, so the cap also bounds per-handler memory/CPU fan-out.
98
-
99
- ## Optimistic inline start (opt-in, off by default)
100
-
101
- Normally `executeStep` awaits `step_started` (the lazy create-claim round-trip) before running the body. Because the inline path already holds the step input locally, it doesn't actually need that round-trip to begin.
102
-
103
- When `WORKFLOW_OPTIMISTIC_INLINE_START` is enabled (set it to `1`/`true`; it is **off by default**), an inline step fires `step_started` **without awaiting it** and starts running the body immediately against locally-synthesized state. A lazy step is always brand-new, so attempt is 1, there is no prior error, and `startedAt` is now. All values are known without the server. The in-flight `step_started` is reconciled immediately before the terminal write:
104
-
105
- - **Lost the create-claim (409 / `EntityConflictError`)** → discard the body result and return `skipped`; the winning handler owns the terminal write.
106
- - **Run gone / throttled / too-early** → discard the body result and surface `gone` / `throttled` / `retry`.
107
- - **Transient (non-translatable) failure** → propagate it, so the queue redelivers exactly as the await path does today.
108
- - **Success** → write `step_completed` / `step_failed` / `step_retrying` as usual. Awaiting `step_started` before the terminal write keeps the event log ordered (`created → started → completed`).
109
-
110
- ### Safety and the idempotency tradeoff
111
-
112
- - **Exactly-one terminal write is preserved.** Optimistic start changes only *when the body runs*, never who writes the terminal event. The terminal event is still gated by the lazy `step_started` create-claim, which is awaited before the terminal write. Losers return `skipped`.
113
- - **Bounded to attempt 1.** Only brand-new (`!hasCreatedEvent`) steps are lazy; a retried step already has a `step_created`, so it takes the normal await-then-run path with the real attempt counter. Synthesizing `attempt = 1` locally is therefore always correct.
114
- - **Why wider double-execution is off by default.** Running the body before confirming ownership means two handlers racing for the same step's create-claim can *both* run the side effects before either wins (previously the loser 409'd on `step_created` and skipped before running anything). This is unsafe for non-idempotent steps. In particular, two concurrent runs of a step that writes to the **workflow stream** (e.g. an AI agent streaming tokens) can interleave and **corrupt the stream data**. The optimization therefore ships **disabled**; enable it (`WORKFLOW_OPTIMISTIC_INLINE_START=1`) only for deployments whose inline step bodies are idempotent and stream-safe.
115
-
116
- ## Queue messages: inline steps don't pay a round-trip
117
-
118
- Inline steps that **complete** never enqueue a per-step flow-route message. When every step in an inline batch reaches a terminal state with no pending background ops, the runtime continues its in-process loop and replays. A sequential chain (or a clean parallel fan-out) of inline steps therefore runs entirely within one invocation with **zero** queue messages. A workflow whose only work is three parallel inline steps issues no `queue()` calls.
119
-
120
- The only flow-route messages produced around an inline batch are:
121
-
122
- - **Pre-batch dispatch:** The steps *beyond* the inline cap (and any pending wait/sleep continuation). Inline steps are explicitly excluded from this dispatch.
123
- - **`retry` results:** One delayed message per retried step. A retry *is* the step becoming its own background invocation, so this is expected.
124
- - **`throttled` results:** A single deferral of the orchestrator message (see above).
125
- - **Pending background ops:** If any inline step left unflushed stream writes (e.g. output streams to blob storage), the loop breaks and enqueues **one** continuation (aggregated across the batch, not per-step) so `waitUntil` can flush before the next replay reads them.
126
-
127
- In other words: completed inline steps cost no queue round-trips; only steps that genuinely run as their own background invocations create new flow-route messages.
@@ -1,78 +0,0 @@
1
- ---
2
- title: Durable hook resume
3
- description: resumeHook() durably writes hook_received and only then publishes the workflow wake, so a resolved call can never be lost to a disposal race.
4
- ---
5
-
6
- # Durable hook resume
7
-
8
- ## Motivation
9
-
10
- The previous lazy path published the serialized hook payload on the workflow
11
- queue and left the queue consumer to create `hook_received`. If the hook was
12
- disposed after `resumeHook()` returned but before the consumer write committed,
13
- that write was rejected and the acknowledged queue delivery could not resume the
14
- workflow: the caller was told the resume succeeded, and it was lost.
15
-
16
- `resumeHook()` now resolves only after both the durable event write and the
17
- workflow wake have succeeded, in that order.
18
-
19
- ## Design
20
-
21
- The dispatch is strictly serial:
22
-
23
- 1. The hook is resolved by token. An unknown token throws `HookNotFoundError`.
24
- 2. The producer writes `hook_received` durably into the run's event log. A
25
- client-minted `resumeId` and payload digest ride the write when the backend
26
- supports atomic resume claims, so transport-level retries of the same write
27
- converge on exactly one committed event. A write refused because the hook
28
- was disposed or the run ended throws `HookNotFoundError`.
29
- 3. Only after the write is acknowledged does the producer publish the workflow
30
- wake. The wake carries no payload — the payload lives in the event log — so
31
- nothing rides on the queue message but the trigger. Publication is retried
32
- a bounded number of times.
33
-
34
- Because the event is committed before the wake exists, a disposal or run
35
- completion racing the queue delivery cannot erase a resume the caller was told
36
- succeeded: the delivery replays the committed event from the log.
37
-
38
- - `ResumedHook.resilientResume` remains on the type for source compatibility
39
- and is no longer set. The internal `resumeHookDurable()` entry point is
40
- removed; `resumeHook()` itself now provides the durable guarantee.
41
-
42
- A resolved call proves that the event is durable and the wake was accepted.
43
- `HookNotFoundError` proves this invocation committed no event. Any other thrown
44
- error is ambiguous only in *dispatch*, never in durability: a wake failure
45
- after the write leaves the event committed, and any later wake of the run
46
- (from any source) delivers it. A fresh `resumeHook()` invocation mints a new
47
- `resumeId`, so blindly retrying a failed call can append a second
48
- `hook_received`; callers that need at-most-once behavior across separate
49
- invocations must deduplicate on their own request key.
50
-
51
- ## Behavior change: resumes against an ended run
52
-
53
- The lazy path never observed the server's rejection — it published a message
54
- and resolved, so a resume against a run that had already ended reported
55
- success (reachable whenever the hook record outlives its run, e.g. token
56
- retention). The durable write restores the check: **a resume against an ended
57
- run now throws `HookNotFoundError`**, and a late webhook delivery to a
58
- finished run answers 404 where it previously answered 202. Senders that treat
59
- 4xx as terminal will stop retrying such deliveries; that is the correct
60
- signal, since nothing can resume an ended run.
61
-
62
- A transient write conflict (HTTP 409, e.g. an event-slot conflict that
63
- escaped the server's internal retry budget under contention) is no longer
64
- re-keyed to `HookNotFoundError`. It surfaces as a retryable error, and its
65
- rejected transaction committed nothing, so retrying the resume is safe.
66
-
67
- ## Compatibility
68
-
69
- Nothing about the queue message changes: the wake has the same shape the
70
- sequential path always published, so no consumer, backend, or server
71
- coordination is needed and either side can roll back independently.
72
-
73
- Consumers continue to accept legacy `hookInput` messages from older producers,
74
- materializing their payload before replay. This permits rolling upgrades
75
- without a coordinated producer and consumer deployment.
76
-
77
- `WORKFLOW_DISABLE_LAZY_HOOK_RESUME` no longer gates anything and is ignored:
78
- there is no lazy path left to disable.
@@ -1,16 +0,0 @@
1
- {
2
- "title": "Changelog",
3
- "pages": [
4
- "index",
5
- "spec-9",
6
- "lazy-hook-resume",
7
- "eager-processing",
8
- "resilient-resume",
9
- "resilient-start",
10
- "lazy-event-creation",
11
- "turbo-mode",
12
- "step-message-ownership",
13
- "batched-event-writes"
14
- ],
15
- "defaultOpen": false
16
- }
@@ -1,32 +0,0 @@
1
- ---
2
- title: Resilient hook resume
3
- description: resumeHook() now tolerates transient event storage failures when the queue is healthy instead of failing the resume.
4
- ---
5
-
6
- # Resilient `resumeHook()`
7
-
8
- <Callout type="info">
9
- Superseded by [durable hook resume](/docs/changelog/lazy-hook-resume):
10
- `resumeHook()` now writes the `hook_received` event durably and only then
11
- publishes the workflow wake, so the two-writer design, the queue-carried
12
- payload, and the `resilientResume` flag described below are historical. The
13
- `(runId, resumeId)` constraint remains, converging transport-level retries
14
- of the producer's own write (and legacy `hookInput` redeliveries from older
15
- producers).
16
- </Callout>
17
-
18
- ## Motivation
19
-
20
- `resumeHook()` used to write the `hook_received` event and dispatch the workflow queue message strictly one after the other, so every resume paid two sequential round trips and a transient event-storage failure failed the whole resume even when the queue was healthy. This change runs both writes **concurrently** (cutting a round trip off resume latency) and, on the same path, brings `resumeHook()` to parity with [resilient `start()`](/docs/changelog/resilient-start): a transient event-write failure no longer fails the resume when the payload can still be delivered through the queue.
21
-
22
- ## Design
23
-
24
- - On the fast path, `resumeHook()` writes the `hook_received` event and dispatches the workflow queue message **concurrently** (`Promise.allSettled`). The queue message carries a `hookInput` payload: the dehydrated hook payload plus a client-minted `resumeId` idempotency key, the hook token, and a payload digest.
25
- - A `(runId, resumeId)` dedup constraint keeps the two writers converging on **exactly one** `hook_received` event: whichever lands first wins, and the other is resolved server-side as success rather than a duplicate. The queue consumer idempotently re-ensures the event from `hookInput` before replay, so the resume is guaranteed even if the direct write never commits.
26
- - Replay also deduplicates: `hook_received` events sharing a `resumeId` belong to the same resume attempt, and only the first in the event log is delivered to workflow code. Even if a redelivery materializes the event twice, the payload reaches the workflow exactly once.
27
- - **Queue dispatch failure is fatal**: The run was not retriggered, so no consumer will re-ensure the event, and `resumeHook()` throws. A transient event-write failure (429/5xx, a transport error, or an expected `(runId, resumeId)` conflict with the consumer's own re-ensure) is swallowed because the queue delivery still guarantees the resume; a terminal run surfaces as `HookNotFoundError`, and any other event-write error is rethrown.
28
- - `resumeHook()` returns `ResumedHook` (exported from `workflow/api`), which extends `Hook` with an optional `resilientResume` flag. The flag is `true` only when the direct write failed transiently and the resume was recovered through the queue; on the happy path and the sequential fallback it is absent.
29
-
30
- ## Compatibility
31
-
32
- The parallel fast path is gated per resume: it activates only when both the target run's queue consumer and the live backend independently attest dedup support (re-checked on every resume, so rollout and rollback both degrade safely). Otherwise (for oversized payloads or legacy runs), `resumeHook()` falls back to the original sequential write-then-dispatch path. Because runs keep executing on the deployment they were created on, a resume targeting a run from an older deployment uses the sequential path.