workflow 5.5.0 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +14 -12
  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,355 +0,0 @@
1
- ---
2
- title: Inline step message ownership
3
- description: Why inline step_started now records its owning queue message ID, why ownership is bounded by a lease, and why the alternatives, from queue serialization to heartbeats, were rejected. Fixes duplicate inline step execution (issue #2780).
4
- ---
5
-
6
- # Inline step message ownership
7
-
8
- > Fixes [#2780](https://github.com/vercel/workflow/issues/2780) (duplicate
9
- > inline step execution when a hook or wait wakes a run mid-step). This page
10
- > is the design defense for the change: what it does, why each choice was
11
- > made, and why the alternatives were rejected. Lease tuning:
12
- > `WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS` (see
13
- > [Runtime tuning](/docs/configuration/runtime-tuning)).
14
-
15
- ## What this change does
16
-
17
- The lazy `step_started` that creates an inline step now also records the queue message ID
18
- of the invocation running its body (`eventData.ownerMessageId`). While that ownership is
19
- active (until the step's first `step_retrying` or terminal event), a replay triggered by
20
- anything other than the owning message does **not** requeue the step. It instead ensures a
21
- *delayed backstop wake* exists, timed to the remainder of an ownership lease. Only a
22
- handler processing the owning message (the original invocation, or the queue's redelivery
23
- of it after a crash) may re-execute the step before that lease expires.
24
-
25
- ## The bug being fixed
26
-
27
- An inline step has no queue message: that is the point of inline execution (it saves the
28
- dispatch round-trip). But the runtime's crash-recovery rule queued every created,
29
- non-terminal step **unconditionally** on each replay, relying on the queue's
30
- `idempotencyKey = correlationId` to dedupe repeats. For inline steps there is no prior
31
- message to dedupe against, so any wake that replayed the run mid-step (`hook_received`,
32
- an elapsed wait continuation, a cancellation) enqueued a *first* message for that
33
- correlation ID. Its consumer sent a bare `step_started` on the `running` step (which is
34
- allowed: retries legitimately re-start non-terminal steps) and ran the body a second time,
35
- concurrently with the original. One `step_completed` won the terminal write; every side
36
- effect had already happened twice.
37
-
38
- Note what is *not* broken: the unconditional requeue is correct for eager steps and is
39
- itself the crash-recovery mechanism for a handler that wrote `step_created` and died
40
- before enqueueing. Any fix must suppress the requeue *only* while a live invocation is
41
- demonstrably running the body, which turns the bug into a liveness problem.
42
-
43
- ## The core problem is liveness, and why we did not build a liveness mechanism
44
-
45
- The missing primitive is the ability to distinguish "this attempt is in flight in a live
46
- invocation" from "this attempt died with its process." Stateless compute offers no death
47
- signal: a crashed function emits nothing, and the event log looks identical either way
48
- (`step_started`, no terminal event).
49
-
50
- The classic answers are heartbeats or a lock store: the executing invocation periodically
51
- renews a claim, and recovery waits for the claim to go stale. We rejected building one:
52
-
53
- - **It adds World API surface.** Every backend (Vercel, local filesystem, community
54
- Postgres/Turso/Redis worlds) would have to implement a renewable-claim store with
55
- expiry semantics. The event log is the World contract's one source of truth; a second,
56
- mutable liveness store beside it is a large contract change for a race fix.
57
- - **It adds steady-state write load.** Heartbeats cost a write per interval per in-flight
58
- step, paid by every healthy run to detect the rare crashed one.
59
- - **It does not remove the hard part.** A heartbeat still needs an expiry to survive a
60
- crashed heartbeater: that expiry *is* a lease. Any liveness design degenerates to
61
- "claim + bounded staleness"; the machinery around it is overhead.
62
-
63
- Instead, the design reuses a liveness signal the system already has: **the queue's
64
- delivery state**. An un-acked queue message is precisely "work that a live invocation may
65
- be processing, which will be redelivered if the processor died." Stamping the owning
66
- message ID on the step makes the queue's own at-least-once machinery serve as the claim,
67
- the crash detector, and the recovery driver, with zero new World surface and zero
68
- steady-state writes beyond one field on an event we already write.
69
-
70
- ### Why the identity is the queue `messageId`
71
-
72
- `createQueueHandler` already delivers `meta.messageId`, and one enqueued message keeps its
73
- ID across redelivery attempts. That stability is exactly the property recovery needs: "a
74
- delivery whose ID matches the stamp" means "the queue redelivered the work that crashed":
75
- permission to re-execute. The requirement is now documented in the
76
- [Queue contract](/docs/api-reference/workflow-runtime/world/queue); a World whose queue
77
- mints fresh IDs per delivery degrades gracefully (the owner check never matches, so
78
- crashed steps recover via the delayed backstop instead of immediately): it never wedges
79
- and never duplicates.
80
-
81
- ### Why ownership lives in the event log
82
-
83
- Ownership state is derived per-replay from the step's events, not held in memory or in a
84
- side store. Every replayer (the owner's redelivery, a hook wake, the backstop) computes
85
- the same answer from the same log, which is the workflow runtime's existing consistency
86
- model. The rules are chosen so the log alone is sufficient:
87
-
88
- - **Latest `step_started` wins.** A stamped start (inline execution, or owner recovery)
89
- sets the owner; an unstamped bare start (a retry attempt driven by a queued step
90
- message, or an older runtime) clears it. This is why owner recovery must *re-stamp* its
91
- bare start: an unstamped recovery start would read as "unowned" to a later wake, which
92
- would immediately requeue the step the owner is re-running, reintroducing the bug on
93
- the recovery path.
94
- - **`step_retrying` lapses ownership permanently** for the correlation ID. From the first
95
- retry on, the step is queue-owned: the retry handoff enqueues a real step message, and
96
- the ordinary `idempotencyKey = correlationId` dedupe works again. Extending ownership
97
- across retries was rejected deliberately: retry backoffs are delay-dominated (the
98
- owning invocation would hold compute open doing nothing), each attempt would pay a
99
- replay to re-derive state, and transferring ownership between attempts adds a state
100
- machine where the queue-owned path already recovers correctly.
101
- - **Eager steps are untouched.** Their execution is owned by their own step message and
102
- its idempotency dedupe; stamping the orchestrator's ID on them would claim work the
103
- orchestrator is not performing.
104
-
105
- ## Why ownership requires a lease
106
-
107
- Ownership cannot be unconditional. Note first what the lease is *not* for: an owner that
108
- crash-loops through the SDK's delivery budget does not wedge the run even without one.
109
- The flow handler fails the run when it receives an over-budget delivery
110
- (`metadata.attempt > maxQueueDeliveries`). The lease exists because that check, and owner
111
- recovery itself, both depend on assumptions the World contract does not actually promise:
112
-
113
- - **Owner-message loss the SDK never observes.** The exhaustion check only fires if the
114
- queue *delivers* the over-budget attempt. At-least-once doesn't guarantee that: a
115
- queue-side redrive policy can dead-letter the message below the SDK's budget (a
116
- community SQS world with a small `maxReceiveCount`), retention can expire it, an
117
- operator can purge it. The run is then still `running`, the step stamped and
118
- non-terminal, and no message exists. With unbounded ownership every future wake defers
119
- to a ghost, a permanent wedge; with the lease, the already-armed backstop (or the
120
- first wake after expiry) recovers the step.
121
- - **Worlds with unstable message IDs: there the lease is the *entire* recovery
122
- mechanism.** If a queue mints a fresh ID per delivery, the owner check never matches,
123
- including on the crashed owner's own redelivery. Unbounded ownership would defer
124
- forever to a stamp no delivery can ever match, while each deferring replay acks its own
125
- message: the run drains to zero messages while still `running`. The lease is what
126
- makes the graceful-degradation claim in the Queue contract true.
127
- - **Insurance on the ack invariant.** Correctness leans on "no path acks the owning
128
- message while an owned step is non-terminal" (see the decision-table invariants). That
129
- is an audited property of today's code, not of the contract; a future refactor or a
130
- queue implementation bug could violate it. The lease caps the cost of any such bug at
131
- one bounded stall instead of a permanent wedge.
132
- - **Failure granularity for poison steps.** Even on the well-behaved exhaustion path,
133
- lease expiry lets a poison step execute and fail on the background path, a
134
- *step-level*, `catch`-able failure the workflow can handle. Unbounded ownership funnels
135
- the same poison into run-level "exceeded max deliveries", which kills the whole run
136
- uncatchably, and only after the full backed-off delivery budget.
137
-
138
- In short: unbounded ownership is a bet that message-ID stability, queue delivery
139
- guarantees, and the ack invariant all hold, forever, on every World. The lease caps the
140
- cost of losing any of those bets at a single bounded stall.
141
-
142
- So ownership is honored only for a bounded window: `leaseRemaining = min(lease, max(0,
143
- lastStartedAt + lease − now))`, anchored at the latest `step_started`'s server-assigned
144
- timestamp. Within the window, non-owner replays defer (and arm the backstop); after it,
145
- dispatch falls back to the pre-existing immediate enqueue. The lease is the upper bound on
146
- "how long a dead owner can delay recovery," and equally the lower bound on "how long a
147
- live owner is protected from duplicates."
148
-
149
- The upper clamp exists for clock skew: `lastStartedAt` is server-stamped while `now` is
150
- the local clock, so a client running behind the server would otherwise compute a remainder
151
- *longer* than the lease, and above 900s, a `delaySeconds` that SQS-backed queues reject
152
- outright.
153
-
154
- ### Why a fixed constant, and why 860 seconds
155
-
156
- The correct lease is "longer than any invocation can possibly live". Beyond that point
157
- the owner is provably dead on platforms that kill invocations. Ideally we would derive it
158
- from the workflow route's resolved `maxDuration`. **No such signal exists**: builders emit
159
- `maxDuration: 'max'`, which the platform resolves per-plan at deploy time; there is no
160
- environment variable, request-context deadline, or build-time value to read. Deriving the
161
- lease was rejected because there is nothing to derive it from.
162
-
163
- 860s is justified by a platform rule rather than a measurement: durations above 800s
164
- require explicit per-function numeric configuration, so `'max'` resolves to ≤ 800s for
165
- any builder-emitted workflow route, and 860 dominates it with headroom. The constant is
166
- configurable through an environment variable (`WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS`, clamped from 1 to 900, where 900 is the
167
- queue's maximum per-message delay, so a single delayed backstop message always suffices
168
- and no delay chaining is needed). The code comment carries the 30-minute-`maxDuration`
169
- beta caveat so the constant is revisited when the platform ceiling moves.
170
-
171
- On worlds with **no** invocation kill bound (world-local's single process, self-hosted
172
- deployments), no constant is a death proof, which is why the in-process single-flight
173
- below is a required layer, not an optimization.
174
-
175
- ## Why the non-owner action is a delayed backstop wake: not a skip, and not a step message
176
-
177
- The naive non-owner behavior is to *skip* the requeue. Rejected: a pure skip makes
178
- lease expiry useless, because nothing is scheduled to *observe* the expiry. If the owner
179
- dies and no external wake happens to arrive later, the run wedges. The escape hatch has to
180
- be folded into the suppression itself.
181
-
182
- So the non-owner enqueues a **plain run continuation** (no `stepId`) with `delaySeconds =
183
- leaseRemaining`. When it fires, it replays the run and re-enters the same dispatch
184
- decision table, which handles every state the step can be in by then: terminal → nothing
185
- pending; queue-owned after `step_retrying` → normal keyed dispatch; owner dead with lease
186
- expired → immediate dispatch, preserving *step-level* failure semantics for poison steps
187
- (the step fails and the workflow's `catch` sees it, rather than the run dying on a
188
- delivery-budget backstop); lease refreshed by owner recovery → re-arm for the new
189
- remainder.
190
-
191
- Two shapes of this backstop were tried and rejected by hard evidence, and both lessons are
192
- now encoded in `backstopIdempotencyKey`:
193
-
194
- 1. **The backstop must not be the step's own message.** The first implementation enqueued
195
- the step message itself (keyed `correlationId`) with the lease delay. But the owner's
196
- retry handoff enqueues the step under that *same* key with a ~1s backoff, and the
197
- pending backstop absorbed it, turning a 1-second retry into a full-lease stall. Caught
198
- by the abort-mid-flight e2e wedging on every world-local lane.
199
- 2. **The backstop key must change when ownership is re-stamped.** Queues dedupe an
200
- idempotency key for the original message's lifetime, *including while a delivery is
201
- in flight*. With a fixed `${correlationId}:backstop` key, a backstop firing during a
202
- lease that owner recovery had refreshed could never publish its own replacement (the
203
- re-arm deduped against the in-flight backstop itself and was dropped); if the
204
- recovered owner then died with its redelivery budget exhausted, no escape hatch
205
- remained. Caught in review. The key is therefore scoped to the **ownership epoch**:
206
- `${correlationId}:backstop:${lastStartedAt}`. Wakes within one epoch still dedupe to a
207
- single pending backstop; each owner-recovery re-stamp opens a new epoch with a fresh
208
- key; pending backstops stay bounded by the owning message's redelivery budget.
209
-
210
- ## The dispatch decision table
211
-
212
- For each pending step in the replay's suspension set that is not designated for lazy
213
- inline execution:
214
-
215
- | Step state | Action |
216
- |---|---|
217
- | Uncreated (`!hasCreatedEvent`) | Unchanged: lazy-inline candidate or eager create+queue |
218
- | Created, ownership active, `owner === myMessageId` | **Execute in this invocation** (owned recovery, alongside the lazy-inline batch; input hydrates from the step entity; the bare `step_started` re-stamps) |
219
- | Created, ownership active, `owner !== myMessageId` | **Ensure backstop wake**: plain run continuation, `delaySeconds = leaseRemaining`, epoch-scoped idempotency key |
220
- | Created, ownership lapsed (`step_retrying` seen), never owned (eager / old events), lease expired, or kill-switched | Unchanged: immediate enqueue, `idempotencyKey = correlationId` |
221
- | Terminal | Unchanged: not in the pending set |
222
-
223
- Two invariants keep the table sound:
224
-
225
- - **No path acks the owning message while an owned step is non-terminal.** Ack means
226
- handler return or `reinvoke()` (which acks and continues under a *new* message ID); an
227
- acked owner can never be redelivered, so recovery would fall to the backstop for the
228
- full lease. All inline bodies are awaited before any ack path, a dev assertion
229
- (`error`-level log) guards the ordering against refactors, and turbo's `reinvoke()`
230
- paths are safe by construction: turbo requires delivery attempt 1, while owned-recovery
231
- steps can only exist on redeliveries (attempt ≥ 2), since a previous delivery of the same
232
- message must have stamped them. That mutual exclusion is documented at turbo's
233
- engagement gate.
234
- - **Owned recovery must not be silently orphaned by early returns.** The background-step
235
- fast path used to return without replaying when other steps were still pending; it now
236
- falls through to the main loop when one of those pending steps is owned by the arriving
237
- message, so a redelivered owner actually performs its recovery instead of leaving it to
238
- the backstop.
239
-
240
- ## Why in-process single-flight is a required layer
241
-
242
- The lease bounds *cross-instance* duplication only on platforms that kill invocations. On
243
- world-local (one process, no kill bound) a delayed backstop can fire while the owning
244
- execution is still mid-body *in the same process*, and on Fluid Compute, an owner
245
- redelivery and a backstop can land on the same instance. A module-level map keyed
246
- `runId:correlationId` absorbs both: the loser awaits the winner's settlement and then acks
247
- **without executing**.
248
-
249
- The loser must not ack-and-skip early (before the winner settles): a crash after an early
250
- ack would consume the loser's message while the winner's outcome is unknown, potentially
251
- orphaning the step with no message left to drive it. Awaiting settlement first keeps the
252
- at-least-once envelope intact: if the loser's own invocation hits its deadline while
253
- waiting, its message redelivers and re-checks, degrading gracefully to polling.
254
-
255
- Cross-instance duplicates on multi-instance *self-hosted* worlds during steps longer than
256
- the lease remain the documented residual (mitigate by raising the lease environment variable). This equals
257
- the trade-off every lease-based system makes; eliminating it entirely requires the
258
- heartbeat machinery rejected above.
259
-
260
- ## Alternatives considered and rejected
261
-
262
- - **Flow-route queue concurrency = 1 (serialize all run messages)**: Removes the
263
- parallelism the wake mechanism exists for: `Promise.race(step, sleep)` works because
264
- the wait continuation fires in a *separate* invocation while the inline step blocks
265
- its handler. With one slot, the sleep could never win. It is also a queue-backend
266
- feature the World contract does not guarantee, and it serializes unrelated work
267
- (hooks, cancellations) behind long step bodies. Noted as a long-term option only if
268
- ownership proves unmaintainable.
269
- - **Inline-eligibility latch (never inline while hooks/waits are open).** The cheapest
270
- hotfix (the condition is already computed for turbo's latch), but it permanently
271
- forfeits inline execution for exactly the workflows that use hooks, taxing every run to
272
- prevent a race that needs an in-flight step to matter. And it is incomplete:
273
- cancellation can wake *any* run mid-step, hooks or not.
274
- - **Inline retries / transferring ownership across attempts.** Rejected above: backoffs
275
- are delay-dominated, attempts would pay replay costs to stay inline, and the
276
- queue-owned retry path already recovers correctly. Ownership deliberately ends at
277
- `step_retrying`.
278
- - **Heartbeat / lock-store liveness.** Rejected above: new World surface for every
279
- backend, steady-state write amplification, and it still needs a lease to survive a
280
- crashed heartbeater. All cost, same bound.
281
- - **Deriving the lease from the route's `maxDuration`.** Nothing to derive from: builders
282
- emit `'max'`, resolved per-plan by the platform at deploy; no runtime or build-time API
283
- exposes the resolved value.
284
- - **Fixing it in the backend.** The server sees the same event log and has the same
285
- liveness blind spot; it would need its own claim mechanism, and world-local plus every
286
- community World would remain broken. The dispatch semantics live in the runtime, so the
287
- fix does too.
288
-
289
- ## Wire format, compatibility, and rollout
290
-
291
- - `ownerMessageId` is an optional field on the `step_started` eventData schema
292
- (`@workflow/world`). In `@workflow/world-vercel` it rides the v4 frame meta; the
293
- compile-time wire guard (`assertEventDataWireContractExhaustive`) fails the build if a
294
- schema field is not explicitly routed, which is what forces the split/merge sites to be
295
- handled. The backend persists it verbatim on the event row (the lazy-input strip on
296
- `step_started` leaves it untouched, and the synthetic `step_created` never carries it)
297
- and re-emits it on event lists.
298
- - **Deploy order: backend before SDK.** An older backend silently drops the meta field →
299
- replays see unowned steps → exactly today's behavior. Safe, but a pointless window to
300
- ship into.
301
- - **Version skew is a non-issue**: runs are pinned to their deployment, and old events
302
- lack the field → unowned → current behavior. Nothing to migrate.
303
- - **Degraded modes are all "today's behavior", never worse**: unstable message IDs (owner
304
- check never matches → backstop-lease recovery), missing/unusable event timestamps
305
- (lease remaining 0 → immediate enqueue), old backend (field dropped → unowned).
306
-
307
- ## Accepted residual risks
308
-
309
- - **Redelivery-while-alive** (visibility lapse or heartbeat partition inside the queue):
310
- the owner check passes on a redelivery racing the live owner → duplicate. This equals
311
- the queue's at-least-once envelope (the floor for any client-side design) and is
312
- strictly rarer than the every-wake duplication being fixed. The in-process single-flight
313
- absorbs the same-instance case.
314
- - **Multi-instance self-hosted worlds with steps longer than the lease** (see
315
- single-flight section): raise the lease environment variable.
316
- - **A backstop per ownership epoch**: an owner crash-looping through its redelivery
317
- budget arms up to one delayed wake per re-stamp. Bounded by the queue's delivery
318
- budget; each fires as a cheap replay no-op if the step completed.
319
-
320
- ## Observability
321
-
322
- - Span attributes on `workflow.execute`:
323
- `workflow.inline_ownership.owned_recovery_steps` (crash recovery re-executed owned
324
- steps) and `workflow.inline_ownership.backstop_wakes_armed` (a replay suppressed an
325
- immediate requeue).
326
- - Always-printed `warn` logs when owned recovery runs (a prior delivery died mid-body)
327
- and when the single-flight absorbs a would-be duplicate (a burst of these means leases
328
- are expiring under live executions: raise the lease environment variable). Invariant violations log at
329
- `error`. Backstop arming logs at `debug` (`DEBUG=workflow:runtime:*`), since it can
330
- legitimately fire on every wake replay during a long inline step.
331
-
332
- ## How the design is protected by tests
333
-
334
- - The **#2780 repro** (`workbench/vitest/test/inline-step-ownership.test.ts`): hook
335
- resume mid-inline-step → side-effect marker fires exactly once.
336
- - **Unit**: the ownership state machine (stamp → wake sees owner → retrying clears → bare
337
- start clears → re-stamp restores), lease math including the clock-skew clamp, and the
338
- backstop key's epoch behavior, including a regression test walking the full
339
- owner-recovery re-arm sequence against a dedupe model matching world-local's in-flight
340
- key retention; single-flight winner/loser semantics.
341
- - **Wire**: schema round-trip tests on both sides, plus backend integration tests
342
- asserting the field survives materialization and the lazy-input strip, and never leaks
343
- into synthetic `step_created`.
344
- - **End-to-end (E2E)**: The full suite including the abort/cancellation lanes that caught backstop
345
- shape #1: world-vercel prod lanes are mandatory for sign-off, since world-local's
346
- synchronous single-process behavior masks distributed races.
347
-
348
- ## Open questions
349
-
350
- 1. Confirm platform behavior: `'max'` resolves ≤ 800s even for accounts in the 30-minute
351
- beta, and users cannot raise a generated workflow route's `maxDuration` via
352
- `vercel.json` `functions` config without the builder seeing it (if they can, the
353
- builder should detect the override and fail or bake it into the lease).
354
- 2. Does world-postgres's handler meta deliver a stable ID across retries? If not:
355
- document degraded (backstop-lease) mode for community worlds, don't block on it.
@@ -1,91 +0,0 @@
1
- ---
2
- title: Turbo mode (fast first invocation)
3
- description: Fast-path the first delivery of the first invocation by backgrounding run_started, skipping the initial event-log load, and forcing optimistic inline start. A no-op for everything else.
4
- ---
5
-
6
- # Turbo mode
7
-
8
- ## Motivation
9
-
10
- The first invocation of a workflow run is where time-to-first-step matters most, yet it pays the most fixed network latency before any user code runs. Three round-trips sit on that critical path today:
11
-
12
- 1. **`run_started` is awaited.** The handler writes `run_started` and waits for it to return the run entity before doing anything else.
13
- 2. **The event log is loaded.** A full `events.list` runs before the first replay, even though on the first delivery nothing has written any events yet.
14
- 3. **Optimistic inline start is off by default.** The [optimistic inline start](./lazy-event-creation#optimistic-inline-start-opt-in-off-by-default) optimization (running a step body before its `step_started` is confirmed) is off by default because under contention two handlers can both run a body and corrupt non-idempotent side effects.
15
-
16
- Turbo mode removes all three costs **for the first delivery of the first invocation only**, where each is provably safe to remove, then gets out of the way. For every subsequent invocation it is a complete no-op.
17
-
18
- ## What turbo mode does
19
-
20
- When the handler detects the first delivery of the first invocation, it:
21
-
22
- 1. **Backgrounds `run_started`.** The event is written without awaiting; the run entity is synthesized locally from the queued run input (status `running`, `startedAt` now) so replay can begin immediately. The `run_started` round-trip overlaps replay instead of blocking it. This reuses the [resilient start](./resilient-start) contract: `run_started` carrying the run input creates the run on the fly (synthetic `run_created`) if it doesn't exist yet. Because turbo uses this `run_started` purely as a write barrier and never reads its response, it also asks the World to **skip the `run_started` event-log preload** (the list+resolve the World normally returns so a run can skip its first `events.list`). That preload would be wasted work here. Since the first `step_started` is chained on the `run_started` barrier, trimming the `run_started` request directly shortens the wait before the first durable `step_started` (and therefore time-to-second-step). A World that ignores the hint stays correct; the runtime falls back to `events.list` if it ever needs the log.
23
- 2. **Skips the initial event-log load.** Nothing has been written, so the first replay runs against an empty log. The second loop iteration does a normal incremental load once the first step's events exist.
24
- 3. **Forces optimistic inline start** for that invocation, independent of `WORKFLOW_OPTIMISTIC_INLINE_START`. The step body runs immediately against locally-synthesized state; only the `step_started` network write waits for the backgrounded `run_started`.
25
-
26
- The first step body starts after the in-process replay, with `run_started` and `step_started` happening in the background around it and no `events.list` before it.
27
-
28
- ## Why this is safe (and where it stops)
29
-
30
- ### Detection
31
-
32
- The first-invocation message is the only one that carries the queued **run input**, and the queue delivery **attempt is 1** (a redelivery is attempt ≥ 2). Together with "not a background-step invocation" and "not a divergence recovery", that uniquely identifies the first delivery of the first invocation without a new message field or world/backend change.
33
-
34
- ### The single-handler guarantee
35
-
36
- Forcing optimistic start is unsafe *in general* because two handlers racing the same step's create-claim can both run the body before one wins. On the first delivery of the first invocation there is **no concurrent peer handler**. The run was created moments ago by `start()`, and only this one message is in flight. The body therefore runs exactly once, and forcing optimistic start is safe here even though the global flag is off.
37
-
38
- ### Turbo exits on the first hook or wait
39
-
40
- That single-handler guarantee ends the moment the run creates a **hook** or **wait** (or writes attributes) because those introduce later resume/parallel invocations that *can* race. Turbo stops forcing optimistic start as soon as a suspension creates any of them. The inline steps of that suspension fall back to the normal await-then-run path, and the rest of the run behaves exactly as it does today. A pure-step suspension (the common hot path) stays on the fast path.
41
-
42
- ### Write ordering is preserved
43
-
44
- Because `run_started` is backgrounded, every event write is gated on a run-ready barrier so nothing is written before the run exists:
45
-
46
- - The optimistic `step_started` is **chained** on the barrier. The body still runs immediately; only the network write waits.
47
- - The suspension handler **awaits** the barrier before any eager write (`hook_created`, `wait_created`, overflow `step_created`). The pure inline hot path defers all its steps and writes nothing here, so it never blocks on the barrier.
48
- - Terminal run writes (`run_completed` / `run_failed`) await the barrier too, so a workflow that finishes with no steps still orders its completion after `run_started`.
49
-
50
- The event log therefore still reads `run_created → run_started → step_created → step_started → step_completed`. If the backgrounded `run_started` genuinely fails (e.g. the run was canceled in the meantime), the chained writes surface the real error (`gone` / run-not-found) and the message redelivers as a normal, non-turbo attempt.
51
-
52
- The barrier orders **event** writes. The forced-optimistic first step **body** runs immediately, so any side effects it performs *before* the terminal write (stream writes via `getWritable()` and the per-step ops flush) are **not** gated on the barrier and can reach the world before the backgrounded `run_started` lands (and are orphaned if it ultimately fails). This is the same exposure as optimistic inline start and is covered by the stream-safety caveat below; deployments whose first step writes to the workflow stream and require strict `run_created → run_started` ordering of stream data should set `WORKFLOW_TURBO=0`.
53
-
54
- ### A run cancelled before its first delivery still runs the first step body
55
-
56
- The non-turbo path awaits `run_started` up front and, if the run was canceled or expired between `start()` and this delivery, returns before any workflow/step code runs. Turbo synthesizes `status: 'running'` and runs the first step body optimistically, so such a cancellation is only observed when the backgrounded `run_started` (and the barrier-chained `step_started`) rejects, *after* the body's side effects have executed (they are then discarded via reconciliation). For non-idempotent first steps this is the same "body runs before ownership is confirmed" tradeoff as optimistic inline start; `WORKFLOW_TURBO=0` restores the up-front skip.
57
-
58
- ### `workflowStartedAt` reflects the first delivery's clock
59
-
60
- Replay matching (step/wait/hook correlation IDs, the VM seed, and the in-VM `Date.now()`) is derived from a replay-stable timestamp recovered from the run ID, so it does **not** depend on `startedAt` and is identical on every delivery. The one value that still tracks `startedAt` is the user-facing `getWorkflowMetadata().workflowStartedAt`: under turbo the first delivery synthesizes it from the local clock, while a later (non-turbo) delivery loads the server-canonical `startedAt`, so the two can differ by the start→first-delivery latency. Treat `workflowStartedAt` as an approximate, human-facing timestamp. **Do not** branch workflow control flow on it (e.g. `Date.now() - +workflowStartedAt > threshold`), since that can take different paths across deliveries and diverge on replay. For timing logic that must survive replay, use the in-VM `Date.now()` / `new Date()`, which is replay-stable.
61
-
62
- ### Attributes seeded at `start()` survive the skipped event load
63
-
64
- `start({ attributes })` does **not** disable turbo, and it needs no synthetic event in the empty log. Seed attributes are folded into the `run_created` event's data (not separate `attr_set` events) and ride along in the queued run input, so the locally-synthesized run snapshot carries them. Turbo loses nothing by skipping the initial `events.list`.
65
-
66
- This is safe specifically because **attributes are write-only inside a workflow**: there is no in-workflow read API today, and `run_created` is consumed structurally during replay without inspecting its attributes. So an empty initial event log replays identically whether or not the run was seeded with attributes.
67
-
68
- That safety is a standing invariant for any future change: if an in-workflow attribute *read* API is ever added, it MUST read from the run snapshot (which turbo populates from the run input) and **not** by replaying `run_created` / `attr_set` events. Reading from the event log would surface seed attributes as empty on the first turbo delivery only, causing a turbo-exclusive divergence from the non-turbo path. `start()` cannot seed hooks or waits, so there is no start-seeded suspension state for the skipped load to miss.
69
-
70
- ## Configuration
71
-
72
- Turbo mode is **on by default**. Set `WORKFLOW_TURBO=0` (or `false`) to disable it. Every invocation then takes the existing awaited path. This is a useful kill-switch for deployments whose first-step bodies are not idempotent and stream-safe (the same caveat as optimistic inline start), or for isolating behavior while debugging.
73
-
74
- Turbo forces optimistic inline start on the first invocation regardless of `WORKFLOW_OPTIMISTIC_INLINE_START` (its single-handler guarantee removes the double-execution race that flag guards against). It does, however, **honor an explicit `WORKFLOW_OPTIMISTIC_INLINE_START=0`**: because forced optimistic start still runs the body before `step_started`/`run_started` is confirmed, an operator who has explicitly disabled optimistic start keeps the await-then-run path even under turbo (the rest of turbo, including backgrounded `run_started` and the skipped initial load, still applies). With the flag unset (the default), turbo forces it on.
75
-
76
- Turbo mode is purely client-side and builds on the lazy/optimistic inline start support already shipped, so it requires no world or backend changes.
77
-
78
- ## Considered: running ahead of durable writes (not implemented)
79
-
80
- Turbo overlaps the *start* round-trips with a step's body, but it still **awaits each `step_completed` before advancing** to the next step. We explored going further with "run-ahead": within a single invocation, execute the workflow forward across a sequential chain *without* awaiting each step's event writes, draining `step_started`/`step_completed` through a background FIFO queue and only blocking on a full drain before acking. A run of three sub-millisecond steps would then fire all the bodies back-to-back while the six event posts caught up in the background, turning per-step latency into `max(Σ body, Σ post)` instead of `Σ(body + post)`.
81
-
82
- We decided **not** to ship it, for two reasons:
83
-
84
- 1. **Re-execution blast radius on failure.** Awaiting each completion means a crash re-runs essentially one in-flight step. Running ahead leaves many completions undrained at once, so a crash or `maxDuration` SIGTERM re-runs *all* of them on redelivery. This creates a much larger at-least-once blast radius, precisely on the latency-sensitive runs most likely to pack many steps into one invocation.
85
- 2. **Divergent branches from non-durable results.** Advancing past a step before its result is durable lets the workflow commit to a forward path that a crash-and-redeliver can re-decide differently. A `Promise.race([B, C])` resolved by local timing can pick `B`, run `D(B)`, then crash before `step_completed_B` is durable. The redelivery may re-resolve to `C`, so `D` executed against a winner the durable history never records. The same shape appears for a branch on a non-deterministic step output (`B(v1)` runs, crash, redelivery commits `B(v2)`). Idempotency doesn't cover these because `D(B)`/`D(C)` and `B(v1)`/`B(v2)` are *different* operations, not retries of one. A "run ahead only while at most one result is undurable" gate would contain the race case (a race needs ≥2 concurrent undurable steps) but not the non-deterministic-output case, and that residual hazard plus the re-execution blast radius outweighed the gain.
86
-
87
- So turbo deliberately stops at forced-optimistic *start* and awaits each `step_completed` before moving on: re-execution after a crash stays deterministic (each step re-runs against the same durable inputs) and bounded (roughly one step, not the whole chain). The idea is recorded here in case a future change (e.g. a determinism signal on steps, or deterministic race resolution) makes run-ahead safe enough to revisit.
88
-
89
- ## Spec 9 runs
90
-
91
- This page describes turbo on spec 8 runs, the default. The experimental spec 9 runtime has its own turbo path, and runs ahead of durable writes within bounds that address the two reasons above. See [Turbo](/docs/changelog/spec-9#turbo) and [Run-ahead](/docs/changelog/spec-9#run-ahead) on the spec 9 page.