perf(core): publish fan-out step messages before their creates commit; resilient step dispatch on by default - #4102
perf(core): publish fan-out step messages before their creates commit; resilient step dispatch on by default#4102pranaygp wants to merge 4 commits into
Conversation
🦋 Changeset detectedLatest commit: e408ace The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
📊 Workflow Benchmarkscommit Backend:
Streams
📈 STSO distribution vs main (inline / queue-hop histograms)1020 steps (inline) Cumulative STSO time: main 144758ms → this run 149679ms (Δ +4921ms, +3%) 📈 CRTT drill-down vs main (RTT distributions & profiles)RTT over stream progress (avg per tenth of stream, bars scaled min→max): RTT by chunk size (avg per log size bin, ~160B → ~12KB serialized, bars scaled min→max): Delivery jitter over stream progress (avg positive CDV per tenth of stream, bars scaled min→max): ℹ️ Metric definitions & methodologyStreams: first-chunk RTT (the stream-open path, before any buffering/backpressure), CRTT percentiles, and worst delivery stall (CDV max). Cells are medians across iterations; per-run values in the artifacts. No 🔴/🟢 marks until targets attach. The collapsed STSO distribution section above buckets every step gap, split inline (same warm process — pure framework overhead) vs queue-hop (fresh process — dispatch, reinit, replay). The collapsed CRTT drill-down: per-variant RTT histograms (fixed log bins, Best/P75/P90/P99 deltas compare against the most recent benchmark run on Metrics — TTFS: time to first step body (in-deployment start() → first step body) · Fan-out TTFS: fan-out time to first step (in-deployment start() → first of the parallel step bodies to complete) · Fan-out TTLS: fan-out time to last step (in-deployment start() → last of the parallel step bodies to complete, i.e. when the Promise.all resolves) · STSO: step-to-step overhead (gap between consecutive step bodies) · WO: workflow overhead (whole-run time outside step bodies, in-deployment anchored) · CRTT: chunk round-trip time (per-chunk write → read latency, one clock domain: deployment → stream backend → same deployment) · CDV: chunk delay variation / delivery jitter (inter-arrival gap minus inter-write gap per seq-adjacent pair; skew-free; the row is each run's MAX positive value, so one stall moves it) Scenarios — step: one trivial no-op step, no stream; no hooks, so the run stays in turbo mode (in-process fast path) · stream: one streaming step; no hooks, so the run stays in turbo mode (in-process fast path) · hook + stream: registers a hook before one step, which exits turbo mode (dispatch path) · 1020 steps: 1020 trivial sequential steps; STSO is measured between consecutive steps in the given step ranges, and WO is the whole-run overhead outside step bodies · Promise.all(100 steps): 100 trivial no-op steps started together in a single Promise.all; Fan-out TTFS is the first of them to complete and Fan-out TTLS the last, both from the in-deployment clientStart, so their gap is the spread the runtime adds across the fan-out · paced control (100/s, 60B): the control: 300 tiny (~60B) deltas metronome-paced at 100/s — zero workload structure, so it reads the transport floor and flush cadence, and disambiguates transport-wide vs workload-specific when a replay row moves · size sweep (100/s, 160B-12KB): same pacing as the control with deltas padded in rotation across seven log-spaced sizes (~160B–12KB) — rotation decouples size from stream position, so it isolates whether chunk size causes latency · replay gateway-gpt-5.4-nano-2000t (1x): raw provider SSE cadence captured at the AI gateway boundary (gpt-5.4-nano, the most popular gateway model; per-token deltas p50 208B = the modal production chunk size), replayed exactly as measured — the typical customer's workload; its CDV is the typical customer's real delivery jitter · replay eve-gpt-5.6-sol-2000t (1x): a captured eve turn (gpt-5.6-sol, the most-used demanding eve model; ~2000 output tokens = production p50 turn length) replayed exactly as measured — eve's envelope protocol re-ships the cumulative message so sizes ramp 142B→13KB; the demanding outlier tenant's reality · replay eve-gpt-5.6-sol-2000t (2x): the same eve capture at 2x — the headroom/stress row; real fast-tier models emit the same chunk sizes at proportionally higher rate, so time compression is a faithful speed model · first chunk (pooled): every run's seq-0 RTT pooled across all stream scenarios — the first chunk precedes any workload differentiation, so pooling samples one shared stream-open path with exact percentiles Replay cadences (semantic sha256) — eve-gpt-5.6-sol-2000t 🔴 marks a percentile over its target (within target is left unmarked). Targets (p75/p90/p99, ms) — TTFS 200/300/600 All timestamps are deployment-side; runs are triggered in-deployment, so the CI runner and api.vercel.com sit outside every measured window. TTFS = Cold starts stay in the numbers (real bursty-workload latency, inflates P75+); Best is the warm floor. |
🧪 E2E Test Results✅ All tests passed
|
| Passed | Failed | Skipped | Total | |
|---|---|---|---|---|
| ✅ ▲ Vercel Production | 3662 | 0 | 685 | 4347 |
| ✅ 💻 Local Development | 3998 | 0 | 510 | 4508 |
| ✅ 📦 Local Production | 3998 | 0 | 510 | 4508 |
| ✅ 🐘 Local Postgres | 3998 | 0 | 510 | 4508 |
| ✅ 🪟 Windows | 320 | 0 | 2 | 322 |
| ✅ 🌐 Cross-language Conformance | 68 | 0 | 74 | 142 |
| ✅ vercel-http-transport | 823 | 0 | 143 | 966 |
| ✅ vercel-multi-region | 27 | 0 | 0 | 27 |
| ✅ vercel-ws-transport | 557 | 0 | 87 | 644 |
| Total | 17451 | 0 | 2521 | 19972 |
Details by Category
✅ ▲ Vercel Production
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ astro-node | 133 | 0 | 28 |
| ✅ astro-quickjs | 133 | 0 | 28 |
| ✅ example-node | 133 | 0 | 28 |
| ✅ example-quickjs | 133 | 0 | 28 |
| ✅ express-node | 133 | 0 | 28 |
| ✅ express-quickjs | 133 | 0 | 28 |
| ✅ fastify-node | 133 | 0 | 28 |
| ✅ fastify-quickjs | 133 | 0 | 28 |
| ✅ hono-node | 133 | 0 | 28 |
| ✅ hono-quickjs | 133 | 0 | 28 |
| ✅ nest-node | 133 | 0 | 28 |
| ✅ nest-quickjs | 133 | 0 | 28 |
| ✅ nextjs-turbopack-node | 158 | 0 | 3 |
| ✅ nextjs-turbopack-quickjs | 158 | 0 | 3 |
| ✅ nextjs-webpack-node | 158 | 0 | 3 |
| ✅ nextjs-webpack-quickjs | 158 | 0 | 3 |
| ✅ nitro-node | 133 | 0 | 28 |
| ✅ nitro-quickjs | 133 | 0 | 28 |
| ✅ nuxt-node | 133 | 0 | 28 |
| ✅ nuxt-quickjs | 133 | 0 | 28 |
| ✅ python-node | 66 | 0 | 95 |
| ✅ sveltekit-node | 152 | 0 | 9 |
| ✅ sveltekit-quickjs | 152 | 0 | 9 |
| ✅ tanstack-start-node | 133 | 0 | 28 |
| ✅ tanstack-start-quickjs | 133 | 0 | 28 |
| ✅ vite-node | 133 | 0 | 28 |
| ✅ vite-quickjs | 133 | 0 | 28 |
✅ 💻 Local Development
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ astro-stable-node | 134 | 0 | 27 |
| ✅ astro-stable-quickjs | 134 | 0 | 27 |
| ✅ express-stable-node | 134 | 0 | 27 |
| ✅ express-stable-quickjs | 134 | 0 | 27 |
| ✅ fastify-stable-node | 134 | 0 | 27 |
| ✅ fastify-stable-quickjs | 134 | 0 | 27 |
| ✅ hono-stable-node | 134 | 0 | 27 |
| ✅ hono-stable-quickjs | 134 | 0 | 27 |
| ✅ nest-stable-node | 134 | 0 | 27 |
| ✅ nest-stable-quickjs | 134 | 0 | 27 |
| ✅ nextjs-turbopack-canary-node | 160 | 0 | 1 |
| ✅ nextjs-turbopack-canary-quickjs | 160 | 0 | 1 |
| ✅ nextjs-turbopack-stable-node | 160 | 0 | 1 |
| ✅ nextjs-turbopack-stable-quickjs | 160 | 0 | 1 |
| ✅ nextjs-webpack-canary-node | 160 | 0 | 1 |
| ✅ nextjs-webpack-canary-quickjs | 160 | 0 | 1 |
| ✅ nextjs-webpack-stable-node | 160 | 0 | 1 |
| ✅ nextjs-webpack-stable-quickjs | 160 | 0 | 1 |
| ✅ nitro-stable-node | 134 | 0 | 27 |
| ✅ nitro-stable-quickjs | 134 | 0 | 27 |
| ✅ nuxt-stable-node | 134 | 0 | 27 |
| ✅ nuxt-stable-quickjs | 134 | 0 | 27 |
| ✅ sveltekit-stable-node | 153 | 0 | 8 |
| ✅ sveltekit-stable-quickjs | 153 | 0 | 8 |
| ✅ tanstack-start-node | 134 | 0 | 27 |
| ✅ tanstack-start-quickjs | 134 | 0 | 27 |
| ✅ vite-stable-node | 134 | 0 | 27 |
| ✅ vite-stable-quickjs | 134 | 0 | 27 |
✅ 📦 Local Production
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ astro-stable-node | 134 | 0 | 27 |
| ✅ astro-stable-quickjs | 134 | 0 | 27 |
| ✅ express-stable-node | 134 | 0 | 27 |
| ✅ express-stable-quickjs | 134 | 0 | 27 |
| ✅ fastify-stable-node | 134 | 0 | 27 |
| ✅ fastify-stable-quickjs | 134 | 0 | 27 |
| ✅ hono-stable-node | 134 | 0 | 27 |
| ✅ hono-stable-quickjs | 134 | 0 | 27 |
| ✅ nest-stable-node | 134 | 0 | 27 |
| ✅ nest-stable-quickjs | 134 | 0 | 27 |
| ✅ nextjs-turbopack-canary-node | 160 | 0 | 1 |
| ✅ nextjs-turbopack-canary-quickjs | 160 | 0 | 1 |
| ✅ nextjs-turbopack-stable-node | 160 | 0 | 1 |
| ✅ nextjs-turbopack-stable-quickjs | 160 | 0 | 1 |
| ✅ nextjs-webpack-canary-node | 160 | 0 | 1 |
| ✅ nextjs-webpack-canary-quickjs | 160 | 0 | 1 |
| ✅ nextjs-webpack-stable-node | 160 | 0 | 1 |
| ✅ nextjs-webpack-stable-quickjs | 160 | 0 | 1 |
| ✅ nitro-stable-node | 134 | 0 | 27 |
| ✅ nitro-stable-quickjs | 134 | 0 | 27 |
| ✅ nuxt-stable-node | 134 | 0 | 27 |
| ✅ nuxt-stable-quickjs | 134 | 0 | 27 |
| ✅ sveltekit-stable-node | 153 | 0 | 8 |
| ✅ sveltekit-stable-quickjs | 153 | 0 | 8 |
| ✅ tanstack-start-node | 134 | 0 | 27 |
| ✅ tanstack-start-quickjs | 134 | 0 | 27 |
| ✅ vite-stable-node | 134 | 0 | 27 |
| ✅ vite-stable-quickjs | 134 | 0 | 27 |
✅ 🐘 Local Postgres
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ astro-stable-node | 134 | 0 | 27 |
| ✅ astro-stable-quickjs | 134 | 0 | 27 |
| ✅ express-stable-node | 134 | 0 | 27 |
| ✅ express-stable-quickjs | 134 | 0 | 27 |
| ✅ fastify-stable-node | 134 | 0 | 27 |
| ✅ fastify-stable-quickjs | 134 | 0 | 27 |
| ✅ hono-stable-node | 134 | 0 | 27 |
| ✅ hono-stable-quickjs | 134 | 0 | 27 |
| ✅ nest-stable-node | 134 | 0 | 27 |
| ✅ nest-stable-quickjs | 134 | 0 | 27 |
| ✅ nextjs-turbopack-canary-node | 160 | 0 | 1 |
| ✅ nextjs-turbopack-canary-quickjs | 160 | 0 | 1 |
| ✅ nextjs-turbopack-stable-node | 160 | 0 | 1 |
| ✅ nextjs-turbopack-stable-quickjs | 160 | 0 | 1 |
| ✅ nextjs-webpack-canary-node | 160 | 0 | 1 |
| ✅ nextjs-webpack-canary-quickjs | 160 | 0 | 1 |
| ✅ nextjs-webpack-stable-node | 160 | 0 | 1 |
| ✅ nextjs-webpack-stable-quickjs | 160 | 0 | 1 |
| ✅ nitro-stable-node | 134 | 0 | 27 |
| ✅ nitro-stable-quickjs | 134 | 0 | 27 |
| ✅ nuxt-stable-node | 134 | 0 | 27 |
| ✅ nuxt-stable-quickjs | 134 | 0 | 27 |
| ✅ sveltekit-stable-node | 153 | 0 | 8 |
| ✅ sveltekit-stable-quickjs | 153 | 0 | 8 |
| ✅ tanstack-start-node | 134 | 0 | 27 |
| ✅ tanstack-start-quickjs | 134 | 0 | 27 |
| ✅ vite-stable-node | 134 | 0 | 27 |
| ✅ vite-stable-quickjs | 134 | 0 | 27 |
✅ 🪟 Windows
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ nextjs-turbopack-node | 160 | 0 | 1 |
| ✅ nextjs-turbopack-quickjs | 160 | 0 | 1 |
✅ 🌐 Cross-language Conformance
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ python | 68 | 0 | 74 |
✅ vercel-http-transport
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ example | 133 | 0 | 28 |
| ✅ express | 133 | 0 | 28 |
| ✅ hono | 133 | 0 | 28 |
| ✅ nextjs-turbopack | 158 | 0 | 3 |
| ✅ nitro | 133 | 0 | 28 |
| ✅ vite | 133 | 0 | 28 |
✅ vercel-multi-region
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ nextjs-turbopack | 27 | 0 | 0 |
✅ vercel-ws-transport
| App | Passed | Failed | Skipped |
|---|---|---|---|
| ✅ example | 133 | 0 | 28 |
| ✅ express | 133 | 0 | 28 |
| ✅ nextjs-turbopack | 158 | 0 | 3 |
| ✅ vite | 133 | 0 | 28 |
Sim WorldSimulated world deterministic testing for races. Traces 🟠 world-sim scenario book — 1 fail of 41 total
Full trace: |
About these numbersSizes are gzip; parentheses show the change against
|
There was a problem hiding this comment.
🟡 Changes recommended
Critical runtime recovery issues and a moderate QuickJS coverage gap remain unresolved.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR reduces fan-out latency by publishing eligible step messages before batched creates commit and enables resilient dispatch by default.
Changes:
- Adds publish-first fan-out dispatch with deferred failure handling.
- Adds lazy consumer-side step recovery.
- Updates defaults, tests, documentation, and release metadata.
File summaries
| File | Summary |
|---|---|
packages/core/src/runtime/suspension-handler.ts |
Implements publish-first fan-out dispatch. |
packages/core/src/runtime/suspension-handler.test.ts |
Covers batching, ordering, payload limits, defaults, and failures. |
packages/core/src/runtime/constants.ts |
Enables resilient dispatch by default; moderate QuickJS coverage concern remains. |
packages/core/src/runtime.ts |
Adds lazy recovery; critical requeue payload and duplicate-consumer recovery issues remain. |
packages/core/src/runtime.test.ts |
Tests consumer recovery, conflicts, redelivery, and legacy messages. |
docs/content/docs/v5/configuration/runtime-tuning.mdx |
Documents runtime dispatch behavior; preview link is missing. |
docs/content/docs/v5/changelog/batched-event-writes.mdx |
Documents publish-first batching; preview link is missing. |
.changeset/publish-first-fanout.md |
Adds release metadata. |
Review details
Suppressed comments (3)
docs/content/docs/v5/changelog/batched-event-writes.mdx:65
- The PR description still contains
DOCS_PREVIEW_PLACEHOLDER, but these docs changes require a Docs Preview section with directworkflow-docspreview links for each changed page. Replace the placeholder with the actual preview links (including the runtime-tuning anchor and this batched-event-writes page) before merging.
**On by default.** The suspension handler folds a **clean fan-out** (the suspension's eager `step_created` and `wait_created` writes) into `createBatch` calls of at most 32 events (mirroring the server's transaction budgets). Chunks of a larger fan-out commit **concurrently**: slot assignment is the World's, so parallel chunks race for slot ranges exactly like the pre-fold path's parallel single writes did, and per-entity conditions, not commit order, carry correctness. The fold only engages when the World implements `createBatch`, the run is on slot identity, and the suspension carries no attribute writes and no hook writes; everything else keeps the single-event path byte-for-byte. [Resilient step dispatch](/docs/configuration/runtime-tuning#workflow_resilient_step_dispatch) composes with the fold: a folded step whose serialized input fits on the queue message is published, carrying that input, before its create commits.
docs/content/docs/v5/configuration/runtime-tuning.mdx:95
- The PR description still contains
DOCS_PREVIEW_PLACEHOLDER; replace it with a directworkflow-docspreview link for this changed page, including the#workflow_resilient_step_dispatchanchor, before merging.
### `WORKFLOW_RESILIENT_STEP_DISPATCH`
- Default: enabled
- When a suspension hands newly created steps to the queue, the runtime publishes each step's execution message without waiting for its `step_created` event write to commit, instead of sequencing the two. The message carries the serialized step input (`stepInput`), so a delivery that arrives before the write lands, or after a transient write failure (429 / 5xx / transport), still executes the step: the consumer's bare `step_started` finds no step, and it sends the start once more as a lazy `step_started` carrying that input, which every World turns into an atomic create-and-start (one round trip, the same write the inline path uses). If that lazy start loses to the producer's create landing in between (a `409`), one more bare start runs the step. A lazy `step_started` on a step that already exists is always a `409`, so the lazy start is only ever the recovery for a step-missing bare start, never the first attempt, and retries and redeliveries of a materialized step keep the bare start. This mirrors resilient start (`runInput`) and the legacy lazy hook resume's `hookInput` (which current producers no longer send; see [durable hook resume](/docs/changelog/lazy-hook-resume)).
packages/core/src/runtime/constants.ts:273
- This default flip also activates the existing QuickJS create/publish race, but the focused tests cover the node:vm suspension path and the consumer, not
dispatchPendingOpswith astepInput-carrying message. A regression in QuickJS could therefore omit the payload or restore create-before-publish while the new tests remain green. Add a QuickJS dispatch test covering the parallel publish and missing-step recovery path.
export function isResilientStepDispatchEnabled(): boolean {
const raw = process.env.WORKFLOW_RESILIENT_STEP_DISPATCH;
if (raw === undefined || raw === '') return true;
return !(raw === '0' || raw.toLowerCase() === 'false');
- Files reviewed: 8/8 changed files
- Comments generated: 2
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| // message carries `stepInput`, the executor is re-run | ||
| // ONCE with that input as a lazy `step_started`, which | ||
| // every World turns into an atomic create + start |
There was a problem hiding this comment.
Fixed in 728daa7. The queued-step re-route now forwards the incoming stepInput on the re-enqueued message (alongside stepId/stepName/timing, still without runInput), so a publish-first delivery misrouted before its create commits can materialize the step on the pinned deployment. There is no runContext field on the payload, so stepInput is the only payload-bearing field that needed carrying. Covered by the new test "re-routes a publish-first queued step execution with its stepInput intact" in runtime.test.ts.
| // the producer's step_created landed between the | ||
| // failed bare start and this write. The step now | ||
| // exists, so the bare start it wanted all along | ||
| // runs it. | ||
| return await executeQueuedStep(); |
There was a problem hiding this comment.
Good catch, fixed in 728daa7. After a skipped lazy start the consumer now reads the step entity (world.steps.get, resolveData: 'none', only on this rare 409 path) and arbitrates by status: pending means the producer's step_created won (created, never started) and the bare start runs it; running or a terminal status means a peer delivery on another instance won the lazy create-claim and is executing the body, so this delivery acks as the loser and returns skipped without executing, the same way an in-process single-flight loser does. Tests cover both branches (pending → bare start, body once; running/completed/failed → two starts written, body never run, acked) and that the read is skipped when the lazy start wins or the bare start succeeds.
Event Log Race Repro
Run History
Config
|
…; resilient step dispatch on by default Compose resilient step dispatch with the batched fan-out fold instead of making them mutually exclusive. Inside the fold, each queued step's message is published, carrying `stepInput`, as soon as its input is dehydrated and `run_started` has settled, concurrently with the `createBatch` commits; steps whose input cannot ride the message keep publish-after-chunk-commit. Early publishes ride the fold's trailing work (joined before ack) and are reported in `queuedStepCorrelationIds`. The queued-step consumer recovers a step-missing bare `step_started` with one lazy `step_started` carrying the message's input (atomic create + start on every World) instead of a `step_created` write plus a second bare start; a lazy start that loses to the producer's create (409) falls back to one more bare start. The eager redelivery pre-ensure is removed, as is the last `viaStepDispatch` sender. `isResilientStepDispatchEnabled()` now defaults on; `WORKFLOW_RESILIENT_STEP_DISPATCH=0`/`false` disables it. Since #3519 no World in this repository returns 412 for a stale write, and the Vercel backend skips its precondition check for slot-identity runs, so the window that justified "off" no longer exists there. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…ost lazy claim by step status; soften the publish-first ordering claim Review follow-ups on #4102: - The deployment-affinity requeue of a queued step execution now forwards the incoming `stepInput`, so a publish-first delivery misrouted before its step_created commits can still materialize the step on the pinned deployment. - After a lazy recovery start is skipped (409), read the step entity and bare-start only a `pending` step (the producer's create won). A `running` or terminal step means a peer delivery on another instance won the lazy create-claim and is executing the body; this delivery acks as the loser without executing, since runStepSingleFlight only serializes one process. - Reword the happens-before claim in the fold comment, the docs, and the changelog: publishes are initiated early and joined alongside the creates, both must succeed before ack, and a durable step_created does not by itself prove its message was published. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
db26166 to
49db6b0
Compare
|
Hold for review: possible regression on 49db6b0. The event-log-race-repro harness was 78/78 clean on the Vercel lane for the two earlier heads, but on this head it reports 1 stuck (run 34653938857 attempt 1) and then 3 stuck of 24 (attempt 2: step-storm ×1, blocked-branch ×2), and the Benchmark (vercel, nextjs-turbopack) lane timed out on 2 of 10 fan-out iterations waiting for |
…y instead of acknowledging it Publish-first delivers a fan-out step's message while the producer's step_created is still committing. The Vercel World's conditional bare start then misses the entity, and the re-read that phrases its rejection already sees the committed `pending` row, so the consumer receives a 409 saying "Cannot start workflow step … with status 'pending'. Operation requires status 'pending' or 'running'.". The executor mapped every 409 to `skipped` and the delivery was acknowledged, stranding the step: every later re-publish of it is deduplicated against the acknowledged message. This is the `stuck` blocked-branch run in #4102's race harness (4 of 50 Vercel-lane runs across two harness runs) and the pending-forever timedNoopStep steps that failed the Benchmark (vercel, nextjs-turbopack) lane on the same head. A `skipped` start is no longer taken as "already started" by itself. The consumer reads the step and lets the entity decide: `running` or terminal acknowledges the delivery as the loser (the only reading the executor assumed), a missing step is materialized from the message's input (the existing step-missing recovery), and a `pending` step gets its start retried once. A step still `pending` after that fails the delivery so the queue redelivers it rather than acknowledging a step nobody started. The lost-lazy-claim arbitration shares the same path, so its follow-up bare start is covered too. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Race harness
|
|
Addendum to the root-cause comment above, for the hold thread:
|
|
Server half of the fix is up: vercel/workflow-server#959 (retry the start patch when the read-back satisfies the start guard, bounded; honest 409 when spent; |
|
Hold lifted. On 17f81a3 the event-log-race-repro harness is 26/26 clean on the Vercel lane (run 34659002004; local and postgres 26/26), Performance Benchmarks passed (run 34659001999), and tests.yml is green including E2E Required Check. Deployment logs show the create-vs-start race still firing (~34 times during the harness) with every retry winning and zero exhausted redeliveries, so the arbitration is load-bearing. Server-side hardening for the contradictory 409 is in vercel/workflow-server#959. Ready for review. |
…s step_created Under publish-first fan-out a queued step's bare step_started can take a counter-sequenced position below the step_created it belongs to (workflow-server specs/StepStartRaceFirstAttempt.cfg). Cover that the consumer, the ordered walk, the suspension-handler creation filter, and the ownership scans all match by correlation id rather than pair order: the step resolves, nothing is re-created or re-dispatched, and the step-name fence still applies to the early start. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
|
Ordering quirk this PR opens (documented, tolerated, tracked server-side). With publish-first, a queued step's message can be consumed before the batch holding its The SDK tolerates it because the consumer matches by correlation id, not pair order: the Server-side fix tracked in vercel/workflow-server#960; model of the gap in workflow-server#959's |
Motivation
Today a clean fan-out folds its eager
step_createdwrites intocreateBatchchunks and publishes each chunk's queue messages only after that chunk commits. Resilient step dispatch (WORKFLOW_RESILIENT_STEP_DISPATCH=1, off by default since #3519, introduced in #3365) publishes in parallel with the create and carries the input on the message, but it was mutually exclusive with the batched fold (batchFanoutEligiblerequired!resilientDispatchEligible), and its consumer recovery cost three round trips (bare start, 404,step_createdwrite, bare start again).Measured on 32-branch fan-outs: queue messages left 100-400 ms after the suspension began because they waited on chunk commits (155-182 ms each), and the first queued step started ~440-650 ms after
run_created.This PR composes the two so the fold publishes first, and turns resilient dispatch on by default.
Design
Producer (
suspension-handler.ts). The!resilientDispatchEligibleterm is gone frombatchFanoutEligible. When both the fold and resilient dispatch are eligible, each foldedkind: 'step'entry whose dehydrated input is aUint8Arrayof at mostMAX_RESILIENT_STEP_INPUT_BYTESis published immediately by its prep op, onceensureRunReady()has settled (turbo still gates onrun_started), withstepInput: { input }, the samestepDispatchIdempotencyKey/traceCarrier/requestedAtshape as before. Those sends run concurrently with thecreateBatchPOSTs rather than after a chunk commits. Entries are flaggedearlyPublished, andpublishChunkStepsskips them; steps whose input is too large or non-binary keep publish-after-chunk-commit. Early publishes are recorded inqueuedStepCorrelationIdsup front and joined by the flush'strailingpromise (so they ridedeferredBatchWork, which the caller joins before ack; without the opt-in, the flush awaits them at return). The single-entry path joins them too viasettlePhase. A publish failure stays fatal for the pass. The pair rows (inline-created/inline-started) are untouched. Outside the fold (hooks/attrs in the suspension, nocreateBatch, pre-slot-identity run) the per-step create ∥ publish branch applies unchanged, and it remains the only placeresilientDispatchRecoveredincrements (in the fold a chunk failure is fatal as before, so there is no "recovered" outcome to count).Consumer (
runtime.ts). When astepInput-carrying message hits step-missing on the barestep_started, the executor is re-run once withlazyStepInput: stepInput.input(andsuppressOptimisticStart: true, so the claim is awaited and a 409 is seen before any body runs). Every World turns that into an atomic create + start with a syntheticstep_created(#2478). If the lazy start returnsskipped(409), the step now exists but the same 409 covers two winners, so the consumer reads the step entity (world.steps.get,resolveData: 'none', on this rare path only) and arbitrates: apendingstep means the producer's create landed in between and one more bare start runs it; arunningor terminal step means a peer delivery on another instance won the lazy create-claim and is executing the body, so this delivery acks as the loser without executing (runStepSingleFlightonly serializes one process).RunExpiredError→goneis preserved. The deployment-affinity requeue of a queued step forwards the incomingstepInput, so a publish-first delivery misrouted before its create commits can still materialize the step on the pinned deployment. The eager redelivery pre-ensure (metadata.attempt > 1) is removed: the in-band path covers a redelivered dispatch whose step is missing at the same round-trip count the eagerstep_createdwrite did, and a redelivery whose step exists (crash mid-body, throttle, the common case) no longer pays a conditional write that only ever came back 409. That also removes the lastviaStepDispatchsender; nothing sends it on astep_started(the server rejects it on any event type other thanstep_created).quickjs entrypoint.
dispatchPendingOpshas nocreateBatchfold (it never callscreateBatch), so its existing per-step create ∥ publish branch is already publish-in-parallel; there is nothing to compose. The default flip turns that branch on for it too.Default (
constants.ts).isResilientStepDispatchEnabled()defaults on;WORKFLOW_RESILIENT_STEP_DISPATCH=0orfalse(case-insensitive) disables it, mirroringisBatchTransitionsEnabled. This also means world-local and world-postgres (nocreateBatch) now publish overflow steps in parallel with their creates by default.Safety analysis
step_createdwhile the payload-carrying message was already out. Since [core] Drop pre-slot event ID support and preconditionGuard capability #3519 no World in this repository returns 412, the Vercel backend skips its precondition check entirely for slot-identity runs, and a duplicate-create 409 leaves the message deduped against the winner's dispatch on the shared idempotency key. The window no longer exists on slot-identity runs. The kill switch stays for operators running a World that does refuse.step_startedon an existing step is a 409 →skippedon every World, deliberately (it is the inline path's exactly-one-owner gate). So the lazy start is only ever the recovery for a step-missing bare start, never the first attempt, and retries/redeliveries of a materialized step keep the bare start.createBatchcommits and is joined alongside them (the flush's trailing work); both must succeed before the delivery acks. A durablestep_createdtherefore does NOT by itself prove its message was published: a slow or failed send can leave a committed create whose message only goes out on the next replay's re-dispatch (deduped by the idempotency key). The unconditional re-enqueue of pending steps stays load-bearing. Removing it would need either a real publish-before-create ordering (the create waits for the send's acknowledgment, giving back the latency this PR removes) or a durable publish marker the replay can consult; neither is in this PR.ensureRunReady().runContextexactly like every other producer, so a publish-first delivery takes the fetch-free prologue: with the resilient recovery in-band, a first delivery reads and writes NOTHING before itsstep_startedclaim. Carry run identity on step-dispatch messages; drop the blocking runs.get from the queued-step prologue #3457's eager redelivery re-ensure (ensureStepFromMessage) is gone on both prologues; the in-band lazy start covers a redelivered dispatch whose step is missing at the same round-trip count. The deployment-affinity re-route preserves bothstepInputandrunContext; the lazy-start recovery and the post-409 step read take deploymentId/specVersion fromrunContextwhen present and from the legacyruns.getotherwise.Out of scope
step_created(dropping the create entirely for queued steps).CreateEventParams.viaStepDispatchstays in@workflow/world(advisory, Worlds may ignore it); its doc comment still describes the old opt-in default and can be refreshed in a world-side follow-up.Tests
packages/core/src/runtime/suspension-handler.test.ts:stepInput, while all three gatedcreateBatchcalls (the pairs-only chunk from perf(core): commit pre-claimed inline pairs in their own batch chunk #4098, then 32 + 1 plain) are still pending; the message bytes are the create's bytes; no second send after the chunks commit.stepInput, still reported inqueuedStepCorrelationIds.WORKFLOW_RESILIENT_STEP_DISPATCH=0keeps today's per-chunk ordering (the former ordering test, now under the kill switch, asserting nostepInput).queuedStepCorrelationIdscovers every early publish at return time, before the deferred work settles.deferredBatchWork(opt-in) or rejects the handler (no opt-in); a lone eager step publishes ahead of its single-path create and the send is joined.runContext(deploymentId, specVersion, startedAt, rootRunId) and no persisted event data does; Carry run identity on step-dispatch messages; drop the blocking runs.get from the queued-step prologue #3457's queueBatch-shaped assertion of the same now runs underWORKFLOW_RESILIENT_STEP_DISPATCH=0, where publish-after-create is the only path that batches sends.commitSingle: 2 inline + 1 eager, the lone plain entry beside the pair chunk publishes first withstepInput, its guardedevents.create(not a one-rowcreateBatch) is joined bydeferredBatchWorkalong with the early send, and the single path never publishes it a second time. The same shape underWORKFLOW_RESILIENT_STEP_DISPATCH=0keeps perf(core): commit pre-claimed inline pairs in their own batch chunk #4098's publish-after-create assertion.0/false/FALSEkill-switch cases in the resilient describe.packages/core/src/runtime.test.ts(consumer):step_startedcarrying the input, nostep_createdwrite, noviaStepDispatchon any event, no ownership stamp, body runs once (world-vercel and world-local error shapes).pending→ one more bare start runs the body once;running/completed/failed→ acked as the loser with nothing further written and the body never run; the read never happens when the lazy start wins or the bare start succeeds.stepInputandrunContexton the re-enqueued message (alongside the existing fields, still withoutrunInput); Carry run identity on step-dispatch messages; drop the blocking runs.get from the queued-step prologue #3457's parameterized re-route test covers both prologues.runContext: zero reads before the step (noruns.get), and the in-band recovery is the one lazy start (bare start, lazy start, body), nostep_createdwrite; Carry run identity on step-dispatch messages; drop the blocking runs.get from the queued-step prologue #3457's fan-out last-completer tests (exactly one lazyruns.getbefore the inline replay) pass unchanged.attempt > 1) recovers in-band with no eagerstep_created; existing-step deliveries on attempts 1 and 2 write nothing extra; legacy no-stepInputpaths unchanged.cd packages/core && FORCE_COLOR=0 pnpm test(after rebasing ontomainat 03455a2, #3457): 114 files passed, 1 skipped; 2471 tests passed, 3 expected fail, 1 skipped.pnpm typecheckfor core is clean. No e2e run.Docs Preview
Preview deployment:
workflow-docs(behind deployment protection; requires Vercel team access).configuration/runtime-tuning(WORKFLOW_RESILIENT_STEP_DISPATCHsection)changelog/batched-event-writes(runtime integration section)No v4 page carries this text, so nothing was mirrored.
🤖 Generated with Claude Code