workflow 5.4.0 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/observability.d.ts +1 -1
  2. package/dist/observability.d.ts.map +1 -1
  3. package/dist/observability.js +2 -2
  4. package/docs/ai/chat-session-modeling.mdx +1 -1
  5. package/docs/ai/resumable-streams.mdx +1 -1
  6. package/docs/api-reference/workflow/create-hook.mdx +2 -2
  7. package/docs/api-reference/workflow/get-step-metadata.mdx +19 -0
  8. package/docs/api-reference/workflow-ai/durable-agent.mdx +2 -1
  9. package/docs/api-reference/workflow-ai/workflow-chat-transport.mdx +4 -4
  10. package/docs/api-reference/workflow-errors/workflow-run-cancelled-error.mdx +1 -1
  11. package/docs/api-reference/workflow-errors/workflow-run-failed-error.mdx +1 -1
  12. package/docs/api-reference/workflow-next/with-workflow.mdx +57 -0
  13. package/docs/api-reference/workflow-observability/create-state-resolver.mdx +56 -0
  14. package/docs/api-reference/workflow-observability/index.mdx +5 -0
  15. package/docs/api-reference/workflow-observability/meta.json +1 -0
  16. package/docs/api-reference/workflow-runtime/world/storage.mdx +1 -2
  17. package/docs/changelog/attributes-mvp.mdx +1 -1
  18. package/docs/changelog/batched-event-writes.mdx +0 -2
  19. package/docs/changelog/eager-processing.mdx +1 -1
  20. package/docs/changelog/lazy-event-creation.md +1 -1
  21. package/docs/changelog/spec-9.mdx +268 -120
  22. package/docs/changelog/step-message-ownership.mdx +2 -7
  23. package/docs/configuration/build-and-diagnostics.mdx +2 -0
  24. package/docs/configuration/cli-and-web-ui.mdx +9 -0
  25. package/docs/configuration/framework-options.mdx +7 -0
  26. package/docs/configuration/runtime-tuning.mdx +22 -77
  27. package/docs/configuration/worlds.mdx +54 -22
  28. package/docs/cookbook/advanced/child-workflows.mdx +3 -3
  29. package/docs/cookbook/agent-patterns/human-in-the-loop.mdx +1 -1
  30. package/docs/cookbook/integrations/ai-sdk.mdx +2 -2
  31. package/docs/errors/corrupted-event-log.mdx +1 -1
  32. package/docs/errors/hook-force-claimed.mdx +1 -1
  33. package/docs/errors/runtime-decryption-failed.mdx +1 -1
  34. package/docs/foundations/errors-and-retries.mdx +3 -1
  35. package/docs/foundations/serialization.mdx +80 -0
  36. package/docs/getting-started/next.mdx +2 -0
  37. package/docs/how-it-works/event-sourcing.mdx +2 -2
  38. package/docs/observability/index.mdx +2 -0
  39. package/docs/whats-new.mdx +3 -3
  40. package/docs/worlds/building-a-world.mdx +18 -3
  41. package/docs/worlds/local.mdx +11 -7
  42. package/docs/worlds/postgres.mdx +10 -13
  43. package/docs/worlds/upgrading-to-v5.mdx +2 -2
  44. package/docs/worlds/vercel.mdx +10 -5
  45. package/package.json +14 -14
@@ -49,7 +49,7 @@ Set [`WORKFLOW_SPEC_VERSION=9`](/docs/configuration/runtime-tuning#workflow_spec
49
49
 
50
50
  Once spec 9 runs exist, do not roll back below this release. An older SDK fails writes to a spec 9 run: `RunNotSupportedError` on the Local and Postgres Worlds, an HTTP 400 on Vercel. Reads still work, and nothing is corrupted.
51
51
 
52
- - **On Vercel**, a spec 9 run's deliveries go only to the deployment that created it, so only an older process's `resumeHook()` and `cancel()` fail. The run itself keeps going.
52
+ - **On Vercel**, a spec 9 run's deliveries go only to the deployment that created it, so only an older process's `cancel()` (and any other write besides a hook resume) fails. The run itself keeps going. An older process's `resumeHook()` and webhooks still work: the backend writes their `hook_received` out-of-band (see [An older SDK and a spec 9 run](#an-older-sdk-and-a-spec-9-run)).
53
53
  - **On a shared Local or Postgres queue**, an older process can also take the run's orchestrator, step and timer messages, and every write it makes for them fails, so the run stalls while it does.
54
54
  - **After re-upgrading**, the run continues, unless the older release used up a message's delivery budget ([`WORKFLOW_MAX_QUEUE_DELIVERIES`](/docs/configuration/runtime-tuning#workflow_max_queue_deliveries), 48 by default). Past it, the older release gives up on the message: its attempt to fail the run is refused too, so it logs that the run stays in its current state and acknowledges the message. On world-local the restart re-enqueues the run with a recovery marker, which re-sends its steps and timers. On world-postgres the re-enqueued message carries no such marker, so steps and timers whose messages the older release acknowledged stay lost until something else wakes the run, and the run can need a manual wake.
55
55
 
@@ -61,7 +61,7 @@ One knob, `WORKFLOW_SPEC_VERSION`, gates minting only: the version a World stamp
61
61
 
62
62
  | `WORKFLOW_SPEC_VERSION` | World passes `inBandFence: true` | Minted |
63
63
  |---|---|---|
64
- | unset | any | 8 (6 when `WORKFLOW_SEALED_LOG=0`) |
64
+ | unset | any | 8 |
65
65
  | `9` | yes | 9 |
66
66
  | `9` | no | 8, with a one-time warning ("the World does not declare the in-band writer fence") |
67
67
  | `6` to `8` | any | that value |
@@ -116,24 +116,22 @@ Settings that apply to every run, read differently on spec 9 runs:
116
116
  - **`WORKFLOW_OPEN_WAIT_CLOCK_SKEW_MS`**: the same window decides a different thing: an open wait due within the inline window plus this allowance makes [run-ahead](#workflow_run_ahead_depth) wait for its writes at that boundary.
117
117
  - **`WORKFLOW_MAX_INLINE_STEPS`**: clamped to `0` to `16`. `0` enqueues every step, each on its own message, and a step's execution mode is fixed when its `step_created` is written: an inline step runs in the orchestrator (and runs again in the next orchestrator delivery if that invocation dies), and an enqueued step never runs inline. An inline step whose retry is due moves to the background. On spec 8 runs `0` is read as unset.
118
118
  - **`WORKFLOW_OPTIMISTIC_INLINE_START`**: only `0` or `false` has an effect: it keeps step bodies waiting for their start to commit on turbo's first delivery, under run-ahead, and for background steps under [`WORKFLOW_OPTIMISTIC_BACKGROUND_START`](#workflow_optimistic_background_start). A step declared with `maxRetries: 0` always waits for its start to commit there, whatever this is set to.
119
- - **`WORKFLOW_SEALED_LOG`**: deprecated in favour of [`WORKFLOW_SPEC_VERSION`](#workflow_spec_version), and read only while that is unset.
120
- - **Not read for spec 9 runs**: `WORKFLOW_INLINE_OWNERSHIP`, `WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS`, `WORKFLOW_BATCH_TRANSITIONS` (which writes a suspension's step creations in batches on spec 8 runs, `0` or `false` writing one event at a time), and the `WORKFLOW_PRECONDITION_*` settings. Spec 9 runs have no precondition guard (the 412 on a stale snapshot, with in-process restarts and re-invocations, that spec 8 runs keep). The fence replaces it.
119
+ - **Not read for spec 9 runs**: `WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS` and the `WORKFLOW_PRECONDITION_*` settings. Spec 9 runs have no precondition guard (the 412 on a stale snapshot, with in-process restarts and re-invocations, that spec 8 runs keep). The fence replaces it.
121
120
 
122
121
  Settings that exist only for spec 9 runs:
123
122
 
124
123
  #### `WORKFLOW_SPEC_VERSION`
125
124
 
126
- - Default: unset. New runs use spec version 8, or 6 with [`WORKFLOW_SEALED_LOG=0`](/docs/configuration/runtime-tuning#workflow_sealed_log).
125
+ - Default: unset. New runs use spec version 8.
127
126
  - Values: an integer from `6` to `9` (surrounding whitespace is ignored). Any other value is ignored, and the runtime logs a one-time warning naming it.
128
127
  - Set `9` to create spec 9 runs, which the runtime drives with the single orchestrator: one orchestrator invocation per run makes every decision, and the World's in-band fence keeps the run to one writer. The Vercel, Local and Postgres Worlds implement the fence. A World that does not declare the fence (`capabilities.inBandFence`) keeps creating spec 8 runs, and the runtime logs a one-time warning.
129
128
  - A run keeps the version it was created with, so the setting changes only what new runs get. Everything that reads, routes or writes to an existing run follows that run's version, never this setting. A run in flight keeps its orchestrator either way: the Vercel World may raise a running run's version only across versions that change no log format, never from 8 to 9.
130
- - When it is set, it takes precedence over [`WORKFLOW_SEALED_LOG`](/docs/configuration/runtime-tuning#workflow_sealed_log), and the runtime logs a one-time warning if both are set.
131
129
  - On the Vercel World, the events of a spec 9 run go through version 5 of the events API; every other run's events stay on the routes earlier releases use, whatever this is set to.
132
130
  - A custom World chooses the versions it can create by what it declares as `specVersion` (see [Building a World](#implementing-spec-9-in-a-world)).
133
131
 
134
132
  Before opting in:
135
133
 
136
- - **Upgrade the whole fleet first.** Every deployment and process that calls `start()`, resumes hooks, receives webhooks, cancels runs or consumes the World's queue must run this release or later before anyone sets `WORKFLOW_SPEC_VERSION=9`. An older SDK fails writes to a spec 9 run: `RunNotSupportedError` on the Local and Postgres Worlds, an HTTP 400 on Vercel. Reads still work, and nothing is corrupted. On Vercel a run's deliveries go only to the deployment that created it, so there only an older process's `resumeHook()` and `cancel()` fail. On a shared Local or Postgres queue, an older process can also take the run's messages, and the run stalls while it does. The run continues after re-upgrading unless the older release used up a message's delivery budget ([`WORKFLOW_MAX_QUEUE_DELIVERIES`](/docs/configuration/runtime-tuning#workflow_max_queue_deliveries), 48 by default): it then gives up on that message, and the run can need a manual wake.
134
+ - **Upgrade the whole fleet first.** Every deployment and process that calls `start()`, resumes hooks, receives webhooks, cancels runs or consumes the World's queue must run this release or later before anyone sets `WORKFLOW_SPEC_VERSION=9`. An older SDK fails writes to a spec 9 run: `RunNotSupportedError` on the Local and Postgres Worlds, an HTTP 400 on Vercel. Reads still work, and nothing is corrupted. On Vercel a run's deliveries go only to the deployment that created it, so there only an older process's `cancel()` and other non-resume writes fail; its `resumeHook()` and webhooks still reach the run. On a shared Local or Postgres queue, an older process can also take the run's messages, and the run stalls while it does. The run continues after re-upgrading unless the older release used up a message's delivery budget ([`WORKFLOW_MAX_QUEUE_DELIVERIES`](/docs/configuration/runtime-tuning#workflow_max_queue_deliveries), 48 by default): it then gives up on that message, and the run can need a manual wake.
137
135
  - **Set it on every caller of `start()`, not only the target.** A start that targets another deployment stamps the lower of the two deployments' versions, so a spec 9 run needs `WORKFLOW_SPEC_VERSION=9` on the caller and on the target.
138
136
  - **Rollback floor.** Once spec 9 runs exist, rolling a deployment back to a release older than this one stalls those runs as described above. To stop creating spec 9 runs, unset the variable (or set `8`) on a deployment of this release or later instead. That is safe for runs already created as spec 9: they keep their orchestrator, and hook resumes, webhooks, `cancel()` and `wakeUp()` from the deployment with the variable unset still work for them.
139
137
  - Spec 8 runs are unaffected: upgrading in place, rolling back and running old and new processes against one World work as on earlier releases.
@@ -167,6 +165,7 @@ An out-of-band terminal event has these effects, all of them benign:
167
165
  - Default: `2000`
168
166
  - While an orchestrator is busy running inline steps, it polls the run's log tail, and also listens on the World's live event feed when the World has one. Events other writers commit (a background step's outcome, a hook payload, a cancellation) then reach the running workflow without a queue hop.
169
167
  - This is the poll's interval while no live feed covers the run: the World has none, the subscription was refused or ended, or the feed showed it missed an event. While the feed is up, the poll runs at [`WORKFLOW_ORCHESTRATOR_FEED_POLL_INTERVAL_MS`](#workflow_orchestrator_feed_poll_interval_ms) instead.
168
+ - Without a live feed the poll backs off: each poll that finds nothing doubles the interval, up to 10 seconds (`ORCHESTRATOR_POLL_MAX_INTERVAL_MS`, never below this value). A poll that delivers an event, a failed poll, feed trouble, or a write the delivery commits itself puts it back at this value at once. A 10-minute inline body on world-local costs about 65 reads instead of 300, and an event another writer commits during a quiet stretch reaches the delivery up to 10 seconds later. No event is lost.
170
169
  - `0` turns polling off, leaving the live feed and queue wakes.
171
170
 
172
171
  #### `WORKFLOW_ORCHESTRATOR_FEED_POLL_INTERVAL_MS`
@@ -179,11 +178,17 @@ An out-of-band terminal event has these effects, all of them benign:
179
178
  #### `WORKFLOW_ORCHESTRATOR_LINGER_MS`
180
179
 
181
180
  - Default: `30000`
182
- - When an orchestrator has nothing left to run, but the run is still waiting on an open hook or on a step running from its own queue message, the orchestrator stays live on the World's live event feed for this long before acknowledging its message.
181
+ - When an orchestrator has nothing left to run, but the run is still waiting on a step running from its own queue message, the orchestrator stays live on the World's live event feed for this long before acknowledging its message. A run that waits only on open hooks lingers for the shorter [`WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`](#workflow_orchestrator_hook_linger_ms) instead.
183
182
  - Each event another writer commits in that time (a hook payload, a background step's outcome, a cancellation) starts another pass in the same invocation. The next pass that again finds nothing to run starts the time over. A burst of resumes or step outcomes is then handled by one warm invocation instead of one queued wake each.
184
- - Only used while the World's live event feed (`events.subscribe`), such as the Vercel World's, is up. A World without one does not linger, and a subscription that fails, at the start or during the linger, ends it: on the tail poll alone, an invocation would stay open for a poll's latency per event. It never runs past the invocation's inline-step deadline.
185
- - An open hook alone is enough, however rarely it is resumed. Any hook the run created and has not disposed keeps an invocation that has nothing left to run lingering for up to this long after each pass, including a pass that just armed a much longer sleep. Each such invocation stays open, and holds the run, for that time.
186
- - Avoid a long-lived hook beside a polling `sleep()`. A cancel or approval hook that stays open for the run's whole life, next to a loop that sleeps and checks something, makes every timer wake hold a function for up to this long, although the wake's own work takes milliseconds. Dispose the hook once it is no longer needed, or give the loop a structure that does not keep one open. If the pattern is needed, lower this value for that deployment, or set it to `0`; `0` also turns off the linger for background steps, whose outcomes usually arrive within it.
183
+ - Only used while the World's live event feed (`events.subscribe`), such as the Vercel or Postgres World's, is up. A World without one (world-local) does not linger, and a subscription that fails, at the start or during the linger, ends it: on the tail poll alone, an invocation would stay open for a poll's latency per event. It never runs past the invocation's inline-step deadline.
184
+ - On world-postgres a lingering delivery holds a Graphile worker slot, so at most half of a process's `queueConcurrency` slots keep a live feed at once. A delivery whose subscription is refused past that cap polls instead, and does not linger.
185
+ - `0` turns it off, for background steps and hooks alike.
186
+
187
+ #### `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`
188
+
189
+ - Default: `5000`, and never more than [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](#workflow_orchestrator_linger_ms).
190
+ - How long an orchestrator with nothing left to run lingers when the run waits on open hooks and no step running from its own message. Each hook payload in that time starts another pass, and the next idle pass starts the time over, so a burst of resumes still lands on one warm invocation.
191
+ - An open hook alone is enough, however rarely it is resumed. Any hook the run created and has not disposed keeps an invocation that has nothing left to run lingering for up to this long after each pass, including a pass that just armed a much longer sleep. The default keeps that cost small: a long-lived cancel or approval hook beside a polling `sleep()` holds each timer wake for up to 5 seconds, where it held it for the full 30-second linger before. Dispose a hook once it is no longer needed, or set this to `0` for a deployment with that pattern; background steps keep their linger.
187
192
  - `0` turns it off.
188
193
 
189
194
  #### `WORKFLOW_ORCHESTRATOR_READ_TIMEOUT_MS`
@@ -277,7 +282,7 @@ A hook create made alone in a suspension also asks for the events after the curs
277
282
 
278
283
  On spec 9 runs, `wakeUp()` returns once the run's orchestrator has been asked to complete the sleeps: the orchestrator writes their `wait_completed` events itself, in order with the run's other decisions, shortly after. `stoppedCount` is the number of sleeps it asked to complete, not the number completed.
279
284
 
280
- On spec 9 runs the request is best-effort on the Vercel World while an orchestrator invocation of the run is running. The request is a queue message to the run's orchestrator, and Vercel Queues folds such a message into the running invocation, which only re-reads the event log and so never sees which sleeps to complete. The sleeps then run their full length, and `stoppedCount` still counts them. An invocation also stays live for up to [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](#workflow_orchestrator_linger_ms) (30 seconds by default) after its last pass while the run waits on an open hook or a background step, so a wake-up sent shortly after such a run was active can be dropped too. When no invocation of the run is live, the message is delivered on its own and completes the sleeps. The Local and Postgres Worlds hold the message until the running invocation ends, then deliver it. On spec 9 runs this is the intended behavior for this release; if you need a sleep to end reliably while the run is active, resume a hook the workflow races against the sleep instead.
285
+ On spec 9 runs the request is best-effort on the Vercel and Postgres Worlds while an orchestrator invocation of the run is running. The request is a queue message to the run's orchestrator, Vercel Queues folds such a message into the running invocation, and world-postgres covers it with a re-run of the running delivery. Either way the invocation only re-reads the event log and so never sees which sleeps to complete. The sleeps then run their full length, and `stoppedCount` still counts them. An invocation also stays live after its last pass while the run waits on a background step, for up to [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](#workflow_orchestrator_linger_ms) (30 seconds by default), or on open hooks alone, for up to [`WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`](#workflow_orchestrator_hook_linger_ms) (5 seconds by default), so a wake-up sent shortly after such a run was active can be dropped too. When no invocation of the run is live, the message is delivered on its own and completes the sleeps. The Local World holds the message until the running invocation ends, then delivers it. On spec 9 runs this is the intended behavior, and a durable `wakeUp()` is not planned; if you need a sleep to end reliably while the run is active, resume a hook the workflow races against the sleep instead.
281
286
 
282
287
  In `@workflow/vitest`, `waitForSleep()` skips a sleep that `wakeUp()` already named in this process while the run completes it. See [`run.wakeUp()`](#runwakeup) and [`run.wakeUp()` stays best-effort](#runwakeup-stays-best-effort) for the mechanism.
283
288
 
@@ -289,9 +294,11 @@ The world-local run gate is in-process: it serializes the orchestrator deliverie
289
294
 
290
295
  **world-postgres.** A spec 9 run's orchestrator deliveries (starts, wakes after a step outcome, hook resumes, cancellations and timers) execute one at a time, with or without invocation. Each one is a Graphile job in the run's named queue, `workflow_flows:<runId>:executor`, and Graphile permits one active job per named queue across worker processes. Step jobs and health checks carry no named queue, so a run's steps execute concurrently with each other and with its orchestrator. An orchestrator blocked on an inline step reads new events, such as a hook payload, from the log while it waits, so it never needs a second delivery of its own run to make progress. A spec 8 run's deliveries (without invocation) carry no named queue either: a spec 8 orchestrator can hold an inline step until another wake of the same run aborts it. A delayed job does not hold its queue. This is the queue half of the single-writer guarantee; the other half is the in-band fence on event writes, which refuses a stale orchestrator that outlived its job's lock.
291
296
 
292
- A worker that is killed mid-job (`SIGKILL`, out of memory, container eviction) leaves that run's named queue locked. Graphile Worker only takes jobs from an unlocked queue, and it clears a stale lock only once it is older than 4 hours (`resetLockedAt`). Until then every later orchestrator delivery of that run (step completions, hook resumes, timers) waits, so a spec 9 run whose worker was hard-killed can stall for up to 4 hours. A graceful shutdown releases the lock. With `jobLockStaleSeconds` set, another process releases the job and the queue lock once they go unrenewed for that window (see [Postgres World](/worlds/postgres#workflow_postgres_job_lock_stale_seconds)). Spec 8 runs without invocation use no named queue and are not affected.
297
+ A worker that is killed mid-job (`SIGKILL`, out of memory, container eviction) leaves that run's named queue locked. Graphile Worker only takes jobs from an unlocked queue, and it clears a stale lock only once it is older than 4 hours (`resetLockedAt`). Every later orchestrator delivery of that run (step completions, hook resumes, timers) waits behind it. A graceful shutdown releases the lock. Every delivery renews its job lock and its named queue's, and by default another process releases a named-queue job and its queue lock once they have gone unrenewed for 300 seconds, if the holder registered as renewing (`workflow.workflow_job_lock_holders`, migration 0030). A spec 9 run whose worker was hard-killed therefore continues within about 8 minutes. A job held by a process on an earlier version, which does not register, keeps Graphile's 4 hour reset. With `jobLockStaleSeconds` set, every job of the World is released after that window instead (see [Postgres World](/worlds/postgres#workflow_postgres_job_lock_stale_seconds)). Spec 8 runs without invocation use no named queue and are not affected.
293
298
 
294
- With invocation disabled, a spec 9 run's workflow execution jobs use the `workflow_flows` task identifier in the same per-run named queue. A message sent with an idempotency key becomes a Graphile job with that job key. A spec 9 run's keyed messages (a step's execution message, a near-due wait timer) use the `unsafe_dedupe` job key mode: a send is a no-op while any job holds the key, locked (being delivered), delayed, or in retry backoff, so a re-send from a later orchestrator delivery never adds a second job for a step, which another worker could run, and never resets a job's attempts or `run_at`. The key is free once the job completes and is deleted. This meets the queue contract's dedupe window (`QUEUE_MIN_STEP_KEY_DEDUPE_WINDOW_MS` in `@workflow/world`) while the step's message lives. A reschedule (a handoff, a retry in place) is sent while its job is locked, and keyed messages of earlier runs keep their behaviour, so both use `preserve_run_at`.
299
+ With invocation disabled, a spec 9 run's workflow execution jobs use the `workflow_flows` task identifier in the same per-run named queue. A message sent with an idempotency key becomes a Graphile job with that job key. A spec 9 run's keyed messages (a step's execution message, a near-due wait timer) use the `unsafe_dedupe` job key mode: a send is a no-op while any job holds the key, locked (being delivered), delayed, or in retry backoff, so a re-send from a later orchestrator delivery never adds a second job for a step, which another worker could run, and never resets a job's attempts or `run_at`. The key is free once the job completes and is deleted. This meets the queue contract's dedupe window (`QUEUE_MIN_STEP_KEY_DEDUPE_WINDOW_MS` in `@workflow/world`) while the step's message lives. A step's execution message of an earlier run (spec 8) uses `unsafe_dedupe` too (#5275). A reschedule (a handoff, a retry in place) is sent while its job is locked, and the other keyed messages of earlier runs (timers, hook wakes, backstops) keep their behaviour, so both use `preserve_run_at`.
300
+
301
+ A spec 9 orchestrator on world-postgres listens on a live event feed (`events.subscribe`, `packages/world-postgres/src/run-events.ts`): after a spec 9 event write commits, the writer sends `pg_notify('workflow_run_events', runId)` outside the write's transaction, and each subscription reads the run's log after the last slot it delivered from one shared `LISTEN` connection per process. A delivery with nothing left to run lingers on it (see [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](#workflow_orchestrator_linger_ms)). When a spec 9 orchestrator delivery acknowledges, its worker takes the run's orchestrator messages that queued behind it on the named queue and runs the handler again, instead of delivering each one (see [world-local and world-postgres](#world-local-and-world-postgres)). An orchestrator message without a spec stamp is checked against the run's stored `spec_version` when a worker takes it, and a spec 9 run's is stamped and moved to the run's named queue (see [An unstamped message](#an-unstamped-message)).
295
302
 
296
303
  **world-vercel.** Spec 9 runs run one orchestrator invocation at a time without `WORKFLOW_SEQUENTIAL_REPLAYS=1`: their orchestrator messages carry the run's id as a [Vercel Queues](https://vercel.com/docs/queues) concurrency key on the shared flow topic, and world-vercel fences the orchestrator's writes. Spec 8 runs, the default, are the ones this variable serializes. Under `WORKFLOW_SEQUENTIAL_REPLAYS=1`, spec 9 runs use the same per-run and per-step topics, and their messages are sent without a concurrency key: Vercel Queues refuses a keyed send to a topic that a `maxConcurrency` consumer reads. The per-run topic then serializes their orchestrator, and nothing is coalesced, so a burst of step completions wakes the orchestrator once per completion instead of being folded into the running invocation.
297
304
 
@@ -373,7 +380,7 @@ The first 412 stops the writer for good: that write and every later one throw `O
373
380
  2. sends what its own committed writes owe the queue, from the writer's accepted events (`sendOwedMessages`): the message of each background step whose `step_created` it committed, the message of each inline step whose retry it moved to the background, and the timers of the wait chains it owns. When its own delivery count is above 1 it also sends what the re-send rule sends (`stepsToReenqueue`);
374
381
  3. returns `{ timeoutSeconds: 1 }` (`FENCE_REFUSAL_REDELIVERY_SECONDS`): a counted redelivery of its own message. It sends no wake and does not acknowledge.
375
382
 
376
- The redelivery is not its message's first delivery, so it re-sends every background step that has a `step_created` and no `step_started`, created less than 23 hours ago, under the step's stable key: whatever a second delivery of the same message committed and died before sending. Where the World counts the redelivery as an attempt (world-vercel, world-local), a run refused on every pass fails at the delivery cap.
383
+ The redelivery is not its message's first delivery, so it re-sends every background step that has a `step_created` and no `step_started`, created less than 23 hours ago, under the step's stable key: whatever a second delivery of the same message committed and died before sending. Every first-party World counts the redelivery as an attempt (world-vercel, world-local, and world-postgres since #5275), so a run refused on every pass fails at the delivery cap.
377
384
 
378
385
  ```mermaid
379
386
  flowchart TD
@@ -388,7 +395,7 @@ flowchart TD
388
395
  M --> R["Re-send pass: unstarted background steps, stable keys"]
389
396
  N --> R
390
397
  R --> J{"Refused again on every pass?"}
391
- J -->|"yes"| K["Delivery cap fails the run (world-vercel, world-local)"]
398
+ J -->|"yes"| K["Delivery cap fails the run"]
392
399
  J -->|"no"| L["The run continues"]
393
400
  ```
394
401
 
@@ -397,7 +404,7 @@ Why it asks for a redelivery instead of acknowledging:
397
404
  - A refusal does not prove that another orchestrator is running. world-vercel also answers 412 `in-band-superseded` when it sealed the writer's own position, and a 409 it returns after it allocated the position moves `seqInBand` past the writer's count, so the writer's next write gets the 412. In both cases nothing else is queued for the run.
398
405
  - The other writer may be a second delivery of the same message: one of the two outlived its lease. That delivery can commit a `step_created` and die before the step's message goes out. An acknowledgment plus a plain wake would leave that step with no message, because the wake is the first delivery of a different message and re-sends nothing. The redelivery is counted above 1, so the re-send rule sends it.
399
406
 
400
- What the redelivery costs: one more invocation after about a second (Vercel Queues clamps the delay to 5 seconds at least). On world-vercel the message keeps the run's key during the delay, so a wake sent meanwhile is coalesced into the redelivery, which reads the log anyway; a live winner that still holds the key absorbs the redelivery as a coalesced message. On world-local and world-postgres it is delivered after the running delivery. Repeated refusals count toward the delivery cap where the World counts the redelivery as an attempt (world-vercel, world-local), so a run refused on every pass fails with `MAX_DELIVERIES_EXCEEDED` instead of looping; world-postgres starts `attempt` over on a `{ timeoutSeconds: n > 0 }` reschedule (see [Known limitations](#known-limitations)). The streak is logged at warn. Tests in `spec9/fenced-overlap.runtime.test.ts`, both engines.
407
+ What the redelivery costs: one more invocation after about a second (Vercel Queues clamps the delay to 5 seconds at least). On world-vercel the message keeps the run's key during the delay, so a wake sent meanwhile is coalesced into the redelivery, which reads the log anyway; a live winner that still holds the key absorbs the redelivery as a coalesced message. On world-local and world-postgres it is delivered after the running delivery; on world-postgres, a redelivery that is due when the running delivery acknowledges is covered by that delivery's re-run instead. Repeated refusals count toward the delivery cap on every first-party World (world-postgres carries `attempt` over on a spec 9 orchestrator message's `{ timeoutSeconds: n > 0 }` reschedule since #5275), so a run refused on every pass fails with `MAX_DELIVERIES_EXCEEDED` instead of looping. The streak is logged at warn. Tests in `spec9/fenced-overlap.runtime.test.ts`, both engines, and `world-postgres/test/queue-spec9-delivery.test.ts`.
401
408
 
402
409
  #### Two overlapping orchestrators
403
410
 
@@ -529,7 +536,7 @@ sequenceDiagram
529
536
 
530
537
  - **Refusal while bodies run.** Bodies already running settle, their outcome writes are refused, and supersession wins over any other failure (`packages/core/src/runtime/spec9/delivery.ts`).
531
538
  - **Refused turbo `run_started`.** A fence refusal of the backgrounded `run_started` stops every later write and the delivery asks for a redelivery; the redelivery is not turbo (tested in `packages/core/src/runtime/spec9/turbo.runtime.test.ts`).
532
- - **Refused on every pass.** Each refused pass asks for a redelivery of the same message, each an attempt on world-vercel and world-local, so the delivery cap fails the run with `MAX_DELIVERIES_EXCEEDED`; the streak is logged at warn (tested in `packages/core/src/runtime/spec9/fenced-overlap.runtime.test.ts`). world-postgres starts `attempt` over on a delayed reschedule, so there the loop is not capped (see [Follow-ups](#follow-ups)).
539
+ - **Refused on every pass.** Each refused pass asks for a redelivery of the same message, each an attempt on world-vercel, world-local and world-postgres, so the delivery cap fails the run with `MAX_DELIVERIES_EXCEEDED`; the streak is logged at warn (tested in `packages/core/src/runtime/spec9/fenced-overlap.runtime.test.ts`). Before #5275, world-postgres started `attempt` over on a delayed reschedule, so there the loop was not capped.
533
540
  - **Retained VM after a refusal.** The retained session is discarded and the redelivery replays to the same result (`fenced-overlap.runtime.test.ts`).
534
541
  - **Overlap through a hook or timer wake.** A parked delivery is fenced out when a hook or wait wake overlaps it, and the final log replays from cold to the same result (`fenced-overlap.runtime.test.ts`).
535
542
  - **Timer delivery refused on its `wait_completed`.** It re-sends its own timer, and its own message is redelivered too (`packages/core/src/runtime/spec9/orchestrator.runtime.test.ts`); a duplicate timer finds its wait completed and arms nothing.
@@ -730,7 +737,9 @@ Each lands at the next slot when it commits. The orchestrator sees it in three w
730
737
 
731
738
  Run-ahead starts work before the writes it depends on commit: it hands an inline step's outcome to the workflow before its `step_completed` commits. [Turbo](#turbo) does the same on a run's first delivery. Every write still goes through the one in-band writer, in decision order.
732
739
 
733
- `WORKFLOW_RUN_AHEAD_DEPTH` is 10 by default, clamped to 0..16, and 0 turns it off (`RUN_AHEAD_DEPTH` in `packages/core/src/runtime/constants.ts`). It caps how many step outcomes are unconfirmed at once. Run-ahead exists on the node:vm engine only: the QuickJS entry point has no run-ahead code.
740
+ `WORKFLOW_RUN_AHEAD_DEPTH` is 10 by default, clamped to 0..16, and 0 turns it off (`RUN_AHEAD_DEPTH` in `packages/core/src/runtime/constants.ts`). It caps how many step outcomes are unconfirmed at once. Both engines run ahead; see [QuickJS run-ahead](#quickjs-run-ahead) for where the QuickJS engine differs.
741
+
742
+ Run-ahead's per-step cost stays flat however many inline steps a delivery runs, because each hazard check reads only the boundaries whose speculative writes are still in flight, at most the depth's worth. The `workflow.execute` span records the most such boundaries held at once as `workflow.run_ahead.contexts_max`.
734
743
 
735
744
  #### When a boundary may run ahead
736
745
 
@@ -754,7 +763,19 @@ flowchart TD
754
763
  H -->|"no"| PC["Creations committed first, outcomes still run ahead"]
755
764
  ```
756
765
 
757
- A hook the workflow has created but not awaited is inert on node:vm: its payload is buffered as an unarmed delivery and moves neither step results nor the clock (`out-of-band-observation.ts`).
766
+ A hook the workflow has created but not awaited is inert on node:vm: its payload is buffered as an unarmed delivery and moves neither step results nor the clock (`out-of-band-observation.ts`). On QuickJS the payload is buffered too, but the VM advances its clock to every event it reads, an unread payload included, so a payload that lands below a speculative event changes the `Date.now()` a replay reads after it. QuickJS makes up for that with a clock gate, described below.
767
+
768
+ #### QuickJS run-ahead
769
+
770
+ The QuickJS entry point (`packages/core/src/runtime/spec9/quickjs-entrypoint.ts`) runs ahead with the same writer, classification, depth and hazard rules, with these differences:
771
+
772
+ - **Which hooks are observed.** The VM reports its open hooks, and a hook counts as observed while a resolver is registered for its next payload (`openHooks`, `packages/core/src/runtime/quickjs-runtime.ts`). A suspension's pending operations leave out a created hook nothing awaits, so the classification reads hooks from there.
773
+ - **The clock gate.** The QuickJS clock advances to the `createdAt` of every event the VM reads (`processEvents`, `quickjs-runtime.ts`), not only events that reach workflow code as on node:vm. An event another writer lands below a speculative one, such as a payload for a hook nothing awaits or an `attr_set` from a step body, therefore gives a replay a later `Date.now()` after it than the workflow read. The session counts the VM's clock reads (`clockReads`). Once code reads the clock while the VM holds a speculative event no write has confirmed at its position, the next boundary is treated as not inert: it waits for the speculative writes to settle before deciding anything. A displaced write then restarts the delivery before a decision made from that clock reading is written (`clockReadOnSpeculation`, `spec9/quickjs-entrypoint.ts`; `workflow.run_ahead.clock_drained_boundaries` counts these boundaries). A decision made without a clock read cannot tell where such an event landed: a payload is buffered either way, and an attribute is invisible to workflow code. A workflow that reads the clock on every step therefore waits for each outcome, as without run-ahead.
774
+ - **Speculative events are fed in position order.** The VM consumes events once, in log order, through `continueWithEvents`. A speculative event is queued at the slot the writer predicts and fed like any other queued event, only once every slot below it is fed (`queueSpeculative`, `packages/core/src/runtime/quickjs-log-view.ts`). It never counts as a slot the view has seen, so a write still names only confirmed positions. A prediction at a slot the view already knows is stale; the write then takes the awaited path.
775
+ - **A displaced write restarts the delivery.** The live VM cannot take back an event it consumed, so a speculative write another writer displaced is not repaired. Once the writes in flight settle, the pass ends in a `RunAheadStopError`, and the delivery restarts in place from a fresh load with run-ahead off for the rest of it (`MAX_RUN_AHEAD_RESTARTS`). An inert displacement stops nothing the delivery decided. A path-changing one also stops its decisions first, as on node. A displaced write whose skipped-slot report was truncated is treated as path-changing.
776
+ - **Speculative creation needs only inline steps.** A turn's new inline steps go out as one speculative batch of creation-bearing `step_started` events when the boundary is inert, no step left by an earlier delivery runs in the same turn, and the batch fits `MAX_BATCH_EVENTS` and `MAX_IN_BAND_CREATION_BATCH_BYTES`. None of the steps may declare `maxRetries: 0`, and `WORKFLOW_OPTIMISTIC_INLINE_START` must not be `0`. On a run's first delivery under [turbo](#turbo), the batch also waits for the backgrounded `run_started` to commit, since a body started from it does not wait for that write the way an optimistic body's writes do. Other steps are created on the awaited path and start once their start committed (except under turbo), and their outcomes still run ahead.
777
+ - **An outcome runs ahead only while the latest boundary is inert.** A body that settles after a later boundary was found not inert writes its outcome on the awaited path.
778
+ - **Snapshots.** A VM snapshot is taken only once no speculative event is unconfirmed.
758
779
 
759
780
  #### A clean run-ahead
760
781
 
@@ -888,7 +909,7 @@ sequenceDiagram
888
909
  Note over O: a suspension with a hook or a wait ends optimistic starts for the delivery
889
910
  ```
890
911
 
891
- The optimistic start applies only while every step of the boundary is inline and the boundary has no wait and no step that failed to serialize (`spec9/delivery.ts`). A boundary with a background step commits its creations first.
912
+ The optimistic start applies while the boundary has no wait and no step that failed to serialize, and each of its inline steps allows retries (`spec9/delivery.ts`). A boundary of only inline steps starts its bodies while their creation commits. A fan-out, with background steps beside the inline ones, does the same for its inline bodies: they start while the creation batches commit, and each inline start is the creation-bearing `step_started` those batches carry, in one batch or more when inputs pass the batch byte budget. Each background step's message still goes out only once its own creation committed, so nothing runs elsewhere before it is durable. On QuickJS a fan-out commits its creations first.
892
913
 
893
914
  #### Why turbo is safe on spec 9 runs (and where it stops)
894
915
 
@@ -898,7 +919,7 @@ The first message is the only one that carries the queued **run input**. Turbo e
898
919
 
899
920
  ##### One orchestrator, one writer
900
921
 
901
- Starting a body before its start commits is unsafe in general: if the in-band fence then refuses the start because another orchestrator invocation of the run holds it, the body ran without a durable record and runs again. On the first delivery of the first message there is no other orchestrator yet: the run was created moments ago by `start()`, and this one message is the only one in flight. The body therefore runs once.
922
+ Starting a body before its start commits is unsafe in general: if the in-band fence then refuses the start because another orchestrator invocation of the run holds it, the body ran without a durable record and runs again. On the first delivery of the first message there is no other orchestrator yet: the run was created moments ago by `start()`, and this one message is the only orchestrator message in flight. The body therefore runs once. A fan-out puts its background steps' messages in flight too, but only once every inline start committed, and each sends a completion wake that is coalesced into this invocation or delivered after it, as a delivery that is not the first.
902
923
 
903
924
  ##### Turbo stops on the first hook or wait
904
925
 
@@ -1096,7 +1117,9 @@ Every send of a run's message in this runtime names the run's version, for spec
1096
1117
 
1097
1118
  ### An unstamped message
1098
1119
 
1099
- A message to a spec 9 run without a stamp still reaches the right orchestrator, because `resolveRunSpec` falls through to `runs.get`. The World treats it as spec 8: on world-vercel it is sent unkeyed and a `{ timeoutSeconds }` result continues on a new message; on world-local and world-postgres it skips the per-run gate. It then runs next to the keyed holder, and the in-band fence keeps that safe: the loser's write gets a 412, and it asks for a redelivery of its own message (see [The in-band fence and its 412s](#the-in-band-fence)). The log stays linear, but the overlap can cost more than one invocation: a spec 9 inline step's start carries no owner, so the unserialized delivery can start and run the body of an inline step the holder is still running, and the fence refuses only the later outcome write. Every producer in this runtime stamps its messages for that reason, including the restart recovery of world-local and world-postgres (`reenqueueActiveRuns`). A producer outside it can still send an unstamped message, or one stamped below 9, for a spec 9 run, and nothing in the runtime can prevent that; a hint below 9 reaches the spec 8 orchestrator first, which hands the message on once it loads the run. The comments on `resolveRunSpec` and on `messageRunSpecVersion` in `@workflow/world` record this.
1120
+ A message to a spec 9 run without a stamp still reaches the right orchestrator, because `resolveRunSpec` falls through to `runs.get`. world-vercel and world-local treat it as spec 8: on world-vercel it is sent unkeyed and a `{ timeoutSeconds }` result continues on a new message; on world-local it skips the per-run gate (both of world-local's gates key on the stamp, `singleOrchestratorRunIdOf`). It then runs next to the keyed holder, and the in-band fence keeps that safe: the loser's write gets a 412, and it asks for a redelivery of its own message (see [The in-band fence and its 412s](#the-in-band-fence)). The log stays linear, but the overlap can cost more than one invocation: a spec 9 inline step's start carries no owner, so the unserialized delivery can start and run the body of an inline step the holder is still running, and the fence refuses only the later outcome write. Every producer in this runtime stamps its messages for that reason, including the restart recovery of world-local and world-postgres (`reenqueueActiveRuns`). A producer outside it can still send an unstamped message, or one stamped below 9, for a spec 9 run, and nothing in the runtime can prevent that; a hint below 9 reaches the spec 8 orchestrator first, which hands the message on once it loads the run. The comments on `resolveRunSpec` and on `messageRunSpecVersion` in `@workflow/world` record this.
1121
+
1122
+ world-postgres resolves it from the run row instead (#5275). A message without a stamp is published outside any named queue. When a worker takes an orchestrator message (`orchestratorRunIdOf`) whose payload has no stamp (`messageRunSpecVersion` is `undefined`), it reads the run's `spec_version` from `workflow.workflow_runs`. For a spec 9 run it adds the message again with `runSpecVersion` set to that version, on the run's named queue and with the same attempt and delivery counts, and completes the original job without delivering it. The message then waits behind the run's live delivery, which may cover it with a re-run. A spec 8 run, a run that is not found, or a failed read leaves the message delivered as before, where the fence keeps it safe. Only unstamped messages pay the read. In invoke mode every orchestrator message already goes to the run's executor lane. Tested in `world-postgres/test/queue-spec9-delivery.test.ts`.
1100
1123
 
1101
1124
  ```mermaid
1102
1125
  sequenceDiagram
@@ -1156,16 +1179,25 @@ Writes made outside a delivery (cancel, resume, wake-up, attributes) stamp the r
1156
1179
 
1157
1180
  ### An older SDK and a spec 9 run
1158
1181
 
1159
- The world-vercel backend accepts writes to a spec 9 run only over its API version 5. Every older API version gets 400 `spec-version-requires-api-v5` on a write, while reads stay available. An older SDK (a deployment rolled back, or another deployment's `resumeHook()`) therefore fails on the write, before it sends any wake. It cannot resume a hook or cancel a spec 9 run. On the Local and Postgres Worlds the same write fails with `RunNotSupportedError`. See [The rollback floor](#the-rollback-floor) for what happens to the run.
1182
+ The world-vercel backend accepts writes to a spec 9 run over its API version 5, with one exception: a `hook_received` over an older API version. A deployment rolled back to an older SDK keeps receiving the webhooks and `resumeHook()` calls of the spec 9 runs its successor created, so the backend writes that event as an out-of-band writer and stamps it with the run's own spec version (an older SDK stamps 8). A hook payload is a plain append on spec 9 that moves no in-band position, so it needs no fence. Every other write over an older API version, such as `run_cancelled` or a hook disposal, gets 400 `spec-version-requires-api-v5`, before the SDK sends any wake. Reads stay available on every version.
1183
+
1184
+ After its write, the older SDK sends its usual wake: no `runSpecVersion` stamp and no concurrency key. It reaches the spec 9 orchestrator through `runs.get` ([An unstamped message](#an-unstamped-message)), and can run beside a keyed delivery that is lingering after its last pass; the in-band fence keeps the log linear, at the cost described there. A retried resume that carries the `(resumeId, resumePayloadDigest)` claim, which `resumeHook()` sends by default, converges on the first `hook_received`.
1185
+
1186
+ On the Local and Postgres Worlds an older SDK's writes, hook resumes included, still fail with `RunNotSupportedError`. See [The rollback floor](#the-rollback-floor) for what happens to the run.
1160
1187
 
1161
1188
  ```mermaid
1162
1189
  sequenceDiagram
1163
1190
  participant Old as Older SDK
1164
1191
  participant B as world-vercel backend
1165
1192
  participant Q as Vercel Queues
1166
- Old->>B: hook_received or run_cancelled on a spec 9 run, API below 5
1193
+ participant O as Spec 9 orchestrator
1194
+ Old->>B: hook_received on a spec 9 run, API below 5
1195
+ B-->>Old: 200, written out-of-band, stamped with the run's spec
1196
+ Old->>Q: wake, no stamp, no key
1197
+ Q->>O: runs.get says 9, spec 9 orchestrator replays
1198
+ Old->>B: run_cancelled on a spec 9 run, API below 5
1167
1199
  B-->>Old: 400 spec-version-requires-api-v5
1168
- Note over Old,Q: no wake is sent, the run is unchanged
1200
+ Note over Old,Q: no wake is sent for a refused write
1169
1201
  ```
1170
1202
 
1171
1203
  ### Events API routing on world-vercel
@@ -1190,7 +1222,7 @@ The delivery bodies and step executors were left separate: they are mostly diffe
1190
1222
  - The in-band fence is checked where a spec 9 run is created (`start()`) and where its orchestrator delivery begins writing (the `InBandWriter`); a World that declares spec 8 creates spec 8 runs and is not checked (`assertWorldSupportsInBandFence`, `packages/core/src/runtime/world-compatibility.ts`).
1191
1223
  - On world-vercel, the events API route follows the run: spec 8 and below on v4, spec 9 on v5. Writes route by the version stamped on the event, reads by the `specVersion` hint the spec 9 orchestrator passes; a read without it uses v4. Spec 8 batches always go over HTTP (`eventsApiVersion`, `packages/world-vercel/src/events-v4.ts`).
1192
1224
  - `WORKFLOW_SPEC_VERSION` accepts an integer from 6 to 9; any other value is ignored with a one-time warning and the default (8) is minted, and 9 on a World without the fence mints 8 with a warning (`mintedSpecVersion`, `packages/world/src/spec-version.ts`).
1193
- - An older SDK's 400 is answered on the write, so no stale wake is left queued for a spec 9 run.
1225
+ - An older SDK's 400 (any write but `hook_received`) is answered on the write, so a refused write leaves no stale wake queued for a spec 9 run. An admitted `hook_received` is followed by the older SDK's unstamped wake, which routing resolves through `runs.get`.
1194
1226
 
1195
1227
  ## World contract changes
1196
1228
 
@@ -1213,7 +1245,7 @@ A World written to the earlier "Building a World" guide (`specVersion: mintedSpe
1213
1245
  | Per-entity `createBatch` order | Part of the spec 9 storage contract, no capability. world-vercel's backend orders batches; world-local and world-postgres have no `createBatch`. |
1214
1246
  | `step_started.creatorMessageId` | Removed. Only a background step's `step_created`, a `wait_created` and an orchestrator's `step_retrying` record their creator; nothing reads an inline step's. A background step's creator is kept for diagnostics: the re-send rule no longer reads it. |
1215
1247
 
1216
- world-local and world-postgres declare the fence and serialize orchestrator deliveries per run for spec 9 runs only, with an in-process per-run gate and a per-run Graphile named queue. Spec 8 runs are not serialized there, as in earlier releases: a spec 8 delivery can hold an inline step until another wake of the same run aborts it, and run-level exclusion would hold that wake back. Neither coalesces, and both mint spec 9 runs only when `WORKFLOW_SPEC_VERSION=9` is set (see [world-local and world-postgres do not coalesce](#world-local-and-world-postgres-do-not-coalesce)).
1248
+ world-local and world-postgres declare the fence and serialize orchestrator deliveries per run for spec 9 runs only, with an in-process per-run gate and a per-run Graphile named queue. Spec 8 runs are not serialized there, as in earlier releases: a spec 8 delivery can hold an inline step until another wake of the same run aborts it, and run-level exclusion would hold that wake back. world-postgres coalesces the orchestrator messages queued behind a running delivery into re-runs of it, and world-local does not; both mint spec 9 runs only when `WORKFLOW_SPEC_VERSION=9` is set (see [world-local does not coalesce](#world-local-does-not-coalesce)).
1217
1249
 
1218
1250
  ### The dedupe contract
1219
1251
 
@@ -1250,15 +1282,17 @@ world-vercel retains a step message for at least a day; world-local and world-po
1250
1282
  |---|---|---|---|
1251
1283
  | `queue()`, spec 9 keyed message | the idempotency key | `unsafe_dedupe` | Sent only to be deduplicated; a second job is a second owner. |
1252
1284
  | `queue()`, keyless message (every wake) | its message id | either; never collides | One job per message. |
1253
- | `queue()`, keyed message of a run below spec 9 | the idempotency key | `preserve_run_at` (unchanged) | Spec 8 behaviour is not changed here; see below. |
1285
+ | `queue()`, step message of a run below spec 9 | the idempotency key | `unsafe_dedupe` (since #5275) | A second job ran a spec 8 body twice; see below. |
1286
+ | `queue()`, other keyed message of a run below spec 9 (timers, hook wakes, backstops) | the idempotency key | `preserve_run_at` (unchanged) | Spec 8 behaviour is not changed beyond step messages. |
1254
1287
  | Reschedule after `{ timeoutSeconds }` (handoff, retry in place, fence-refusal redelivery) | the message's key, or its id | `preserve_run_at` (unchanged) | Sent while the job it continues is locked, so it must insert a second job; `unsafe_dedupe` would drop the continuation. |
1255
1288
  | Transfer of a legacy orchestration to the executor | `<executor task>:transfer:<messageId>` | `preserve_run_at` (unchanged) | A distinct key next to the still-locked legacy job. |
1289
+ | Move of an unstamped orchestrator message of a spec 9 run to its named queue (#5275) | `<task>:stamped:<messageId>` | `preserve_run_at` | A distinct key next to the still-locked original job. |
1256
1290
  | pg-boss migration | the pg-boss singleton key | Graphile's default (unchanged) | One-time import. |
1257
1291
  | `invoke()` wake | none | | Every invocation gets a wake. |
1258
1292
 
1259
1293
  What a re-send does now: next to a locked job, nothing, and the running delivery stays the only owner; next to a job in retry backoff, nothing, and its attempts and `run_at` are kept, so the step delivery cap counts; once the job completes it is deleted and the key is free again. So world-postgres deduplicates while the job exists, not for a fixed 24 hours; a step message lives until its step has an outcome, which is what the re-send rule needs, and a re-send of a step whose job completed finds a `step_started` in the log and is not made. A job that exhausted its Graphile attempts stays in the table and keeps its key, so a later re-send of that step is a no-op; that needs 73 failed deliveries, past the delivery cap at 49.
1260
1294
 
1261
- Spec 8 has the same exposure and is not changed here: its runtime republishes a delivery's step messages under their keys after a failed send (`queueMessages`), and a republish next to a locked job inserts a second job. Whether that runs a spec 8 body twice across processes was not verified.
1295
+ Spec 8 had the same exposure: its runtime republishes a delivery's step messages under their keys after a failed send (`queueMessages`), and a republish next to a locked job inserted a second job. A Docker Postgres repro confirmed that it runs a spec 8 body twice across processes (`world-postgres/test/spec8-step-dedupe.test.ts`): a spec 8 run fans out to five steps, of which spec 8 runs up to three inline and queues the rest; sending the queued steps' messages again while their jobs were locked, with a second World's workers idle, ran one body twice (`[1, 2, 3, 4, 4, 5]`). Fixed in #5275: `jobKeyModeFor` uses `unsafe_dedupe` for every keyed step message (`stepId` set), whatever the run's spec. A step's retry is a reschedule of its own job, so it is unaffected. Spec 8's other keyed publishes (timers, hook wakes, backstops) keep `preserve_run_at`.
1262
1296
 
1263
1297
  Tests, against Docker Postgres (`world-postgres/test/queue-dedupe.test.ts`): a locked job plus a re-send leaves one job; a job in backoff (attempts 5, `run_at` an hour out) keeps both; a free key takes a new job; and a spec 9 run whose step message is re-sent while its body runs, with a second World's worker idle, runs the body once (the runtime's in-process single flight is bypassed in that test, as it would be across processes). Without the fix the first two fail, and the run test runs the body twice. Unit tests in `world-postgres/src/queue.test.ts` pin the mode per send.
1264
1298
 
@@ -1298,8 +1332,12 @@ The runtime refuses to create or drive a spec 9 run on a World that does not dec
1298
1332
 
1299
1333
  **Inline steps are created by their first `step_started` (spec 9).** A step the orchestrator runs inline has no `step_created`: its first `step_started` (`attempt: 1`) carries what a `step_created` carries, `stepName`, `workflowName`, `input` and `inline: true` (but no `creatorMessageId`, which only a background step's creation needs), and is the step's creation. Store it as one event, keep its `input` (as for a `step_created`), and write no `step_created` beside it. A background step keeps `step_created` followed by its invocation's own `step_started`. Only a step's first start carries an input; later starts are ordinary starts. The runtime still reads logs with a `step_created` for an inline step, so a World does not rewrite older runs.
1300
1334
 
1335
+ **A resilient start may store its `run_started` as the run's creation (spec 9).** When `run_created` never landed and a `run_started` carrying the creation data creates the run, a World may store that `run_started` alone at the run's first slot, with the data a `run_created` carries (`input`, `deploymentId`, `workflowName`, `executionContext`, `attributes`, `encryptionPublicKey`, `startHook`), and write no `run_created`. The runtime reads either shape. Keep the in-band count a log with a `run_created` would have: the creation holds the first in-band position and the start the next, so that `run_started` write reports `allocated: 1`.
1336
+
1301
1337
  Persist the fields the runtime adds to `eventData` and return them from `events.list()`: `inline` and `creatorMessageId` on `step_created`, `inline` on an inline step's first `step_started`, `creatorMessageId` on `wait_created`, `attempt` on `step_started`, `attempt` on `step_retrying` and `step_failed`, and `stepName` on every step event.
1302
1338
 
1339
+ A `hook_received` that `resumeHook()` or `resumeWebhook()` writes on a spec 9 run also carries the run's `workflowName` in `eventData`, as a creating `step_started` does, so a World that keys stored data by workflow name doesn't need to read the run first. Older runtimes omit it, so treat it as optional.
1340
+
1303
1341
  **In-band and out-of-band writes.** Every write says whether the run's orchestrator made it (`params.inBand`). In-band writes also carry `params.expectedSeqInBand` and `params.eventCount`, and your World must fence them: see [Single-writer guarantee and the in-band fence](#single-writer-guarantee-and-the-in-band-fence).
1304
1342
 
1305
1343
  **Batch writes (spec 9).** The runtime writes a suspension's step and wait creations (inline steps' `step_started`, background steps' `step_created`, and `wait_created`) as one batch only when the method exists, and otherwise writes them one at a time. The events land in request order at consecutive positions. On a spec 9 run a batch is not atomic: an item may fail while the others commit, and each item reports its own outcome. Batch params carry `inBand`, `expectedSeqInBand` and `eventCount` for the whole block; the World allocates the block in one conditional allocation and returns the block's skipped-slot report and `allocated` count at the top level of the result. Reject the whole batch, with a request-level error, for anything other than step and wait events, and for a batch over your own size caps.
@@ -1524,7 +1562,7 @@ export async function resizeAll(urls: string[]) {
1524
1562
  }
1525
1563
  ```
1526
1564
 
1527
- The 50 step invocations finish over a few seconds, and each one sends the orchestrator one plain wake, without reading the log first. While the orchestrator is running, every wake is coalesced into it. When it finishes a pass and tries to acknowledge, it is told how many wakes arrived, reads the log once, and sees all the outcomes that landed. The run is woken a few times instead of 50, and there is never a second orchestrator to refuse. Without coalescing (world-local, world-postgres, and world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1`), each of the 50 wakes is its own orchestrator delivery, one after another (see [Known limitations](#known-limitations)).
1565
+ The 50 step invocations finish over a few seconds, and each one sends the orchestrator one plain wake, without reading the log first. While the orchestrator is running, every wake is coalesced into it. When it finishes a pass and tries to acknowledge, it is told how many wakes arrived, reads the log once, and sees all the outcomes that landed. The run is woken a few times instead of 50, and there is never a second orchestrator to refuse. world-postgres covers the wakes that queued behind a running delivery with re-runs of it in the same way (see [world-local and world-postgres](#world-local-and-world-postgres)). Without coalescing (world-local, and world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1`), each of the 50 wakes is its own orchestrator delivery, one after another (see [Known limitations](#known-limitations)).
1528
1566
 
1529
1567
  Coalescing is safe because every producer commits what the wake is for (a step outcome, a `hook_received`) before it sends the wake, so the holder's next read sees it. The exceptions are `run.wakeUp()`, which is best-effort (see [Known limitations](#known-limitations)), and a timer, which names its wait (see [Timers and waits](#timers-and-waits)).
1530
1568
 
@@ -1679,7 +1717,7 @@ Then it returns `{ timeoutSeconds: 1 }` (`FENCE_REFUSAL_REDELIVERY_SECONDS`): a
1679
1717
  - A refusal does not prove that another orchestrator is running. The world-vercel backend also answers 412 `in-band-superseded` when it sealed the writer's own position (its put outlived the staleness bound), and a 409 it returns after it allocated the position moves `seqInBand` past the writer's count, so the writer's next write gets the 412. In both cases nothing else is queued for the run (see [A refused write with no other orchestrator stranded the run](#a-refused-write-with-no-other-orchestrator-stranded-the-run)).
1680
1718
  - The other writer may be a second delivery of the same message: one of the two outlived its lease. That delivery can commit a `step_created` and die before the step's message goes out. An acknowledgment plus a plain wake left that step with no message, because the wake is the first delivery of a different message and re-sends nothing ([4365355467](https://github.com/vercel/workflow/pull/4661#discussion_r4365355467), reproduced on both engines). The redelivery is counted above 1, so the re-send rule sends it.
1681
1719
 
1682
- What the redelivery costs: one more invocation after about a second (Vercel Queues clamps the delay to 5 seconds at least). On world-vercel the message keeps the run's key during the delay, so a wake sent meanwhile is coalesced into the redelivery, which reads the log anyway; a live winner that still holds the key absorbs the redelivery as a coalesced message. On world-local and world-postgres it is delivered after the running delivery. Repeated refusals count toward the delivery cap where the World counts the redelivery as an attempt (world-vercel, world-local), so a run refused on every pass fails with `MAX_DELIVERIES_EXCEEDED` instead of looping ([4365355583](https://github.com/vercel/workflow/pull/4661#discussion_r4365355583)); world-postgres starts `attempt` over on a `{ timeoutSeconds: n > 0 }` reschedule (see [Known limitations](#known-limitations)). The streak is still logged at warn (`a26b9a431d`). Tests in `spec9/fenced-overlap.runtime.test.ts`, both engines: the two-deliveries-of-one-message case completes, a self-refused write completes on a serializing and on a coalescing queue, and a run refused on every pass reaches the cap (commit `6b4c0cea3b`).
1720
+ What the redelivery costs: one more invocation after about a second (Vercel Queues clamps the delay to 5 seconds at least). On world-vercel the message keeps the run's key during the delay, so a wake sent meanwhile is coalesced into the redelivery, which reads the log anyway; a live winner that still holds the key absorbs the redelivery as a coalesced message. On world-local and world-postgres it is delivered after the running delivery; on world-postgres, one that is due when the running delivery acknowledges is covered by that delivery's re-run. Repeated refusals count toward the delivery cap on every first-party World, so a run refused on every pass fails with `MAX_DELIVERIES_EXCEEDED` instead of looping ([4365355583](https://github.com/vercel/workflow/pull/4661#discussion_r4365355583)). world-postgres started `attempt` over on a `{ timeoutSeconds: n > 0 }` reschedule until #5275, which carries it over for a spec 9 orchestrator message. The streak is still logged at warn (`a26b9a431d`). Tests in `spec9/fenced-overlap.runtime.test.ts`, both engines: the two-deliveries-of-one-message case completes, a self-refused write completes on a serializing and on a coalescing queue, and a run refused on every pass reaches the cap (commit `6b4c0cea3b`).
1683
1721
 
1684
1722
  **Run-ahead stop.** The delivery lets the outcomes a hazard stop still allows commit, sends what its writes owe (as above), takes a fresh writer, reloads the log and replays from cold in the same delivery, with run-ahead off for the rest of the delivery. With run-ahead off a second stop cannot occur; `MAX_RUN_AHEAD_RESTARTS` (1) still bounds the restarts, and a stop past it hands the message off. The inline deadline applies to the restarted pass as to any other. A hazard stop detects a classification gap rather than recovering from one: the check runs on the report of a write that already committed, and a coalesced run-ahead group can commit the decisions made without the event in the same batch. It is logged at error level with `possibleLogCorruption: true`.
1685
1723
 
@@ -1687,17 +1725,20 @@ What the redelivery costs: one more invocation after about a second (Vercel Queu
1687
1725
 
1688
1726
  ### world-local and world-postgres
1689
1727
 
1690
- Both declare the fence, mint spec 9 runs when `WORKFLOW_SPEC_VERSION=9` is set (`mintedSpecVersion(process.env, { inBandFence })` in `packages/world-local/src/index.ts` and `packages/world-postgres/src/index.ts`), and serialize a spec 9 run's orchestrator deliveries with `singleOrchestratorRunIdOf` (spec 9 by stamp, then `orchestratorRunIdOf`). Spec 8 runs, step messages, health checks and intermediate hops are not gated. Neither coalesces: a second orchestrator message waits and is delivered after the running one, so every background completion's wake is its own orchestrator delivery.
1728
+ Both declare the fence, mint spec 9 runs when `WORKFLOW_SPEC_VERSION=9` is set (`mintedSpecVersion(process.env, { inBandFence })` in `packages/world-local/src/index.ts` and `packages/world-postgres/src/index.ts`), and serialize a spec 9 run's orchestrator deliveries with `singleOrchestratorRunIdOf` (spec 9 by stamp, then `orchestratorRunIdOf`). Spec 8 runs, step messages, health checks and intermediate hops are not gated. world-local does not coalesce: a second orchestrator message waits and is delivered after the running one, so every background completion's wake is its own orchestrator delivery. world-postgres coalesces since #5275: a delivery covers the orchestrator messages that queued behind it with re-runs.
1691
1729
 
1692
1730
  | | world-local | world-postgres |
1693
1731
  |---|---|---|
1694
1732
  | Per-run gate | In-process run gate (`createRunGate`, `packages/world-local/src/queue.ts`) | Graphile named queue per run (`serialRunId`, `packages/world-postgres/src/queue.ts`) |
1695
- | Handoff | Same message, `handoffs++`, `attempt = delivery + 1 - handoffs` (`packages/world-local/src/queue.ts`, `queue.ts`), up to 10,000 handoffs. The delivery releases the run gate and takes it again in FIFO order, so orchestrator messages already waiting run first | Reschedule on a new Graphile job with the same `messageId`, no delay, on the run's named queue behind jobs already there (`packages/world-postgres/src/queue.ts`) |
1696
- | `attempt` after a handoff | Unchanged | Carried over (`attemptOffset`); a delayed reschedule starts it over |
1697
- | Coalescing | None | None |
1698
- | Dedupe of a keyed send | While the first message lives | While a Graphile job holds the key: `unsafe_dedupe` for a spec 9 run's keyed sends, `preserve_run_at` for a reschedule and for earlier runs |
1699
- | Re-runs with the gate held, coalesced count | None | None |
1700
- | `invocationStartedAt` | Not passed | Not passed |
1733
+ | Handoff | Same message, `handoffs++`, `attempt = delivery + 1 - handoffs` (`packages/world-local/src/queue.ts`, `queue.ts`), up to 10,000 handoffs. The delivery releases the run gate and takes it again in FIFO order, so orchestrator messages already waiting run first | Reschedule on a new Graphile job with the same `messageId`, no delay, on the run's named queue, with priority `-1` so it runs before the jobs already waiting there (`HANDOFF_JOB_PRIORITY`, `packages/world-postgres/src/queue.ts`) |
1734
+ | `attempt` after a handoff | Unchanged | Carried over (`attemptOffset`); a spec 9 orchestrator message's delayed reschedule carries it over too, a step's retry in place starts it over |
1735
+ | Coalescing | None | The jobs waiting behind a delivery on the run's named queue (due, unlocked, the same run's orchestrator messages, not a start message carrying `runInput`) are deleted with Graphile's `complete_jobs` when it acknowledges (`takeCoalescedJobs`). Not on invoke mode's executor lane |
1736
+ | Dedupe of a keyed send | While the first message lives | While a Graphile job holds the key: `unsafe_dedupe` for a spec 9 run's keyed sends and every run's step messages, `preserve_run_at` for a reschedule and for earlier runs' other keyed sends |
1737
+ | Re-runs with the gate held, coalesced count | None | Handler called again in the same worker with `deliveryCount + rerun` and the same `attempt`, while it finds jobs to take, up to `MAX_COALESCED_RERUNS` (32). Past the cap the remaining jobs are delivered as usual, so no handoff is needed. A failed re-run is retried as the original job, counted above 1 |
1738
+ | `invocationStartedAt` | Not passed | Passed, the same for every re-run (`x-workflow-postgres-invocation-started-at`) |
1739
+ | Live event feed | None | `events.subscribe` over `LISTEN`/`NOTIFY` (`packages/world-postgres/src/run-events.ts`), at most half of a process's `queueConcurrency` slots live at once |
1740
+
1741
+ On world-local:
1701
1742
 
1702
1743
  ```mermaid
1703
1744
  sequenceDiagram
@@ -1712,18 +1753,39 @@ sequenceDiagram
1712
1753
  G->>O2: deliver m2, attempt 1
1713
1754
  ```
1714
1755
 
1715
- #### Follow-up: coalescing on world-local and world-postgres
1756
+ On world-postgres:
1716
1757
 
1717
- A fan-out of `n` background steps sends `n` wakes, and here each is one orchestrator delivery, in series. A delivery that finds the log tail at the position this process last consumed acknowledges after one tail read (`packages/core/src/runtime/spec9/consumed-position.ts`); every other one loads the full log and replays. world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` has the same shape, with each wake one function invocation, because its spec 9 messages are unkeyed on per-run topics.
1758
+ ```mermaid
1759
+ sequenceDiagram
1760
+ participant P as Producer
1761
+ participant Q as Run's named queue
1762
+ participant W as Worker
1763
+ participant H as Handler
1764
+ Q->>W: job m1
1765
+ W->>H: deliver m1, deliveryCount 1
1766
+ P->>Q: wakes m2, m3 for the same spec 9 run
1767
+ Note over Q: m2, m3 wait behind m1
1768
+ H-->>W: acknowledged
1769
+ W->>Q: complete_jobs(m2, m3)
1770
+ W->>H: re-run m1, deliveryCount 2, same attempt and invocationStartedAt
1771
+ H-->>W: acknowledged, nothing more queued
1772
+ W->>Q: m1 completed
1773
+ ```
1774
+
1775
+ #### Follow-up: coalescing on world-local
1718
1776
 
1719
- What these Worlds would need to match world-vercel:
1777
+ **Done on world-postgres** (#5275), as described above: items 1 to 4 below, with the difference that the worker takes the waiting jobs when the holder acknowledges instead of dropping them as they arrive, and leaves them queued past the cap instead of handing off. Tests in `world-postgres/test/queue-spec9-delivery.test.ts` and `world-postgres/test/spec9-run-feed.test.ts`. Still open on world-local.
1778
+
1779
+ A fan-out of `n` background steps sends `n` wakes, and on world-local each is one orchestrator delivery, in series. A delivery that finds the log tail at the position this process last consumed acknowledges after one tail read (`packages/core/src/runtime/spec9/consumed-position.ts`); every other one loads the full log and replays. world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` has the same shape, with each wake one function invocation, because its spec 9 messages are unkeyed on per-run topics.
1780
+
1781
+ What world-local would need to match world-vercel:
1720
1782
 
1721
1783
  1. Drop an orchestrator message for a spec 9 run that arrives while the run's delivery holds the gate, and count it on the holder.
1722
1784
  2. When the holder's handler returns, run it again in the same process while counted messages are uncovered, reporting `deliveryCount + rerun` and the same `attempt`, and the first run's `invocationStartedAt`.
1723
1785
  3. Cap the re-runs (world-vercel: 32) and hand off past the cap.
1724
1786
  4. Give a handoff the front of the run's queue, instead of a place behind the waiting wakes.
1725
1787
 
1726
- Intermediate wait hops are already ungated and must stay that way, since a hop's delivery depends on its own message. Every other spec 9 orchestrator message is safe to coalesce (see [No orchestrator message carries state the log needs](#no-orchestrator-message-carries-state-the-log-needs)). Not implemented.
1788
+ Intermediate wait hops are already ungated and must stay that way, since a hop's delivery depends on its own message. Every other spec 9 orchestrator message is safe to coalesce (see [No orchestrator message carries state the log needs](#no-orchestrator-message-carries-state-the-log-needs)). Not implemented on world-local.
1727
1789
 
1728
1790
  ### Queue edge cases
1729
1791
 
@@ -1735,8 +1797,9 @@ Intermediate wait hops are already ungated and must stay that way, since a hop's
1735
1797
  - Vercel Queues bounds handoffs per message and past the bound applies an ordinary reschedule (`limit_reached`), which counts as an attempt; world-local mirrors this with `MAX_LOCAL_HANDOFFS` (`packages/world-local/src/queue.ts`).
1736
1798
  - The client logs the queue's answer to a handoff (`accepted` at debug, `not_immediate` at info, `limit_reached` at warn) by wrapping the `@vercel/queue` API object found under `Symbol.for('@vercel/queue.apiClient')`; if a `@vercel/queue` release moves that object, the lines stop silently (`observeHandoffOutcomes`, `packages/world-vercel/src/queue.ts`).
1737
1799
  - A spec 8 continuation sends its new message before acknowledging, so a crash in between duplicates the wake instead of losing it (`packages/world-vercel/src/queue.ts`).
1738
- - world-postgres publishes a spec 9 run's keyed message (a step message, a wait timer's hop) with Graphile's `unsafe_dedupe`, a no-op while any job holds the key. With `preserve_run_at` a re-send next to a locked job inserted a second job, which another worker ran as a first delivery, and a re-send next to a job in backoff reset its attempts and `run_at`. A reschedule keeps `preserve_run_at`, because it is sent while the job it continues is locked and must insert one (`jobKeyModeFor`, `packages/world-postgres/src/queue.ts`).
1739
- - world-postgres starts `attempt` over on a delayed reschedule, because the new Graphile job starts its own count and `attemptOffset` is carried unchanged; a spec 9 handoff carries `attempt` over (`attemptOffset: attempt - 1`, `1f7b912923`), and `deliveryCount` carries over on both (`deliveryOffset`) (`packages/world-postgres/src/queue.ts`, `queue.ts`). See [Edge cases](#edge-cases-and-failure-handling).
1800
+ - world-postgres publishes a spec 9 run's keyed message (a step message, a wait timer's hop), and any run's step message, with Graphile's `unsafe_dedupe`, a no-op while any job holds the key. With `preserve_run_at` a re-send next to a locked job inserted a second job, which another worker ran as a first delivery, and a re-send next to a job in backoff reset its attempts and `run_at`. A reschedule keeps `preserve_run_at`, because it is sent while the job it continues is locked and must insert one (`jobKeyModeFor`, `packages/world-postgres/src/queue.ts`).
1801
+ - world-postgres starts `attempt` over on a step message's delayed reschedule (a retry in place), because the new Graphile job starts its own count and `attemptOffset` is carried unchanged. A spec 9 handoff carries `attempt` over (`attemptOffset: attempt - 1`, `1f7b912923`), and so does a spec 9 orchestrator message's delayed reschedule (`attemptOffset: attempt`, #5275); `deliveryCount` carries over on all of them (`deliveryOffset`) (`packages/world-postgres/src/queue.ts`, `queue.ts`). See [Edge cases](#edge-cases-and-failure-handling).
1802
+ - world-postgres coalesces only jobs that are due: a delayed reschedule or timer still waiting out its delay stays queued. A start message (`runInput`) is never coalesced, since it carries the run's input for a start whose `run_created` may not have committed (`takeCoalescedJobs`, `packages/world-postgres/src/queue.ts`).
1740
1803
  - An intermediate wait hop has no key, so it is delivered beside a running orchestrator; its delivery writes nothing (`packages/world/src/queue.ts`). See [Timers and waits](#timers-and-waits).
1741
1804
 
1742
1805
  ## Lifecycles and flows
@@ -1919,12 +1982,12 @@ The dotted exits are exceptions caught around the whole pass (`spec9/delivery.ts
1919
1982
  - **Stream writes still flushing.** An inline step that returned with stream writes pending makes the delivery hand off once no body runs (`spec9/delivery.ts`).
1920
1983
  - **Hook conflict.** A hook conflict the workflow has to consume in a fresh pass hands off (`spec9/delivery.ts`).
1921
1984
  - **An event that landed after the VM decided.** Before suspending, a foreign event above the pass's consumed slot starts another pass instead of acknowledging, because its own wake would find the position already recorded (`spec9/delivery.ts`).
1922
- - **Linger.** While the World's live feed is up (`LiveLogFeed.isLive`), a delivery with an open hook or a background step stays live up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (30s), capped by the inline-start margin, and runs a pass for each foreign event (`lingerForExternalWork` in `spec9/delivery.ts`, `DEFAULT_ORCHESTRATOR_LINGER_MS` in `packages/core/src/runtime/spec9/live-feed.ts`).
1985
+ - **Linger.** While the World's live feed is up (`LiveLogFeed.isLive`), a delivery with a background step stays live up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (30s), and one with open hooks alone up to `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` (5s), capped by the inline-start margin, and runs a pass for each foreign event (`lingerForExternalWork` in `spec9/delivery.ts`, `getOrchestratorLingerMsFor` and `DEFAULT_ORCHESTRATOR_LINGER_MS` in `packages/core/src/runtime/spec9/live-feed.ts`).
1923
1986
  - **Throttled inline start.** A throttled inline start defers the run by the longest backoff once every sibling settled (`spec9/delivery.ts`).
1924
1987
  - **Out-of-band terminal event first.** A `run_completed` that loses to an earlier `run_cancelled` or `run_failed` by position does not dispatch completion hooks (`spec9/delivery.ts`).
1925
1988
  - **Background step after its body.** The step's invocation writes its outcome once its `step_started` committed (the body starts after that commit; only under `WORKFLOW_OPTIMISTIC_BACKGROUND_START=1` does a plain first delivery start it while the start is in flight), then sends one plain orchestrator wake without reading the log (`packages/core/src/runtime/spec9/step-handler.ts`, `wakeOrchestrator`). That wake is the only thing that moves the run on. A redelivery of the step message that finds the step terminal sends the wake again, so a wake whose send failed is not lost; one that finds the run terminal sends nothing (commit `76643fe621`).
1926
- - **Uncoalesced wakes.** On world-local, world-postgres, and world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1`, each background outcome's wake is its own orchestrator delivery, delivered after the running one. A fan-out's wakes are then a series of deliveries; one that finds nothing new since the last consumed position acknowledges after one tail read, the others load the log and replay (see [Known limitations](#known-limitations)).
1927
- - **QuickJS engine.** The same delivery hands the run to the QuickJS entry point after setup, with the same writer; it has no run-ahead and no divergence recovery (`spec9/delivery.ts`).
1989
+ - **Uncoalesced wakes.** On world-local, and world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1`, each background outcome's wake is its own orchestrator delivery, delivered after the running one. world-postgres covers the wakes queued behind a running delivery with re-runs of it (#5275). A fan-out's wakes are then a series of deliveries; one that finds nothing new since the last consumed position acknowledges after one tail read, the others load the log and replay (see [Known limitations](#known-limitations)).
1990
+ - **QuickJS engine.** The same delivery hands the run to the QuickJS entry point after setup, with the same writer and run-ahead depth; it has no divergence recovery (`spec9/delivery.ts`). See [QuickJS run-ahead](#quickjs-run-ahead).
1928
1991
 
1929
1992
  ### Event posting with consume-after-commit
1930
1993
 
@@ -1970,12 +2033,13 @@ export async function resizeAll(urls: string[]) {
1970
2033
  | Step messages per Vercel Queues batch request | 100, world-vercel's ceiling | `MAX_QUEUE_SEND_BATCH` in `packages/world-vercel/src/queue.ts` |
1971
2034
  | Inline window | 2 min, or 5 min when the function may run 10 min or more, or 10 min at 25 min or more; `WORKFLOW_V2_TIMEOUT_MS` overrides | `getMaxInlineDurationMs` in `packages/core/src/runtime/delivery.ts` |
1972
2035
  | `WORKFLOW_INLINE_STEP_DEADLINE_MARGIN_MS` | 60 s: no inline step starts this close to the window's end | `DEFAULT_INLINE_STEP_DEADLINE_MARGIN_MS` in `packages/core/src/runtime/spec9/deadline.ts` |
1973
- | `WORKFLOW_ORCHESTRATOR_LINGER_MS` | 30 s, only on a World with a live feed | `DEFAULT_ORCHESTRATOR_LINGER_MS` in `packages/core/src/runtime/spec9/live-feed.ts` |
2036
+ | `WORKFLOW_ORCHESTRATOR_LINGER_MS` | 30 s while a background step is open, only on a World with a live feed | `DEFAULT_ORCHESTRATOR_LINGER_MS` in `packages/core/src/runtime/spec9/live-feed.ts` |
2037
+ | `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` | 5 s while only hooks are open, at most the linger above | `DEFAULT_ORCHESTRATOR_HOOK_LINGER_MS` in `packages/core/src/runtime/spec9/live-feed.ts` |
1974
2038
  | Coalesced re-runs per delivery | 32 | `MAX_COALESCED_RERUNS` in `packages/world-vercel/src/queue.ts` |
1975
2039
 
1976
2040
  #### How the creations are split
1977
2041
 
1978
- The suspension's events are the inline steps' creation-bearing `step_started` events first, then the background steps' `step_created` (`packages/core/src/runtime/spec9/step-wait-creation.ts`). They go out in batches of up to `MAX_IN_BAND_CREATION_BATCH_EVENTS` (64) events and 512 KiB, in order, so the inline starts share the first batch with background creations (`batchChunks`). The inline bodies start once that first batch commits. This is the node engine's path (`spec9/delivery.ts`); the QuickJS engine writes a suspension's creations through its own code in `spec9/quickjs-entrypoint.ts`, which these numbers were not checked against.
2042
+ The suspension's events are the inline steps' creation-bearing `step_started` events first, then the background steps' `step_created` (`packages/core/src/runtime/spec9/step-wait-creation.ts`). They go out in batches of up to `MAX_IN_BAND_CREATION_BATCH_EVENTS` (64) events and 512 KiB, in order, so the inline starts share the first batch with background creations (`batchChunks`). The inline bodies start once that first batch commits, except on a turbo first delivery, where they start while it commits (see [Turbo](#turbo)). This is the node engine's path (`spec9/delivery.ts`); the QuickJS engine writes a suspension's creations through its own code in `spec9/quickjs-entrypoint.ts`, which these numbers were not checked against.
1979
2043
 
1980
2044
  | `WORKFLOW_MAX_INLINE_STEPS` | Events | Batches | First batch | Later batches | Step-message sends |
1981
2045
  |---|---|---|---|---|---|
@@ -2028,7 +2092,7 @@ sequenceDiagram
2028
2092
 
2029
2093
  #### Timeline with the default numbers
2030
2094
 
2031
- Times below are positions in the delivery, not measurements. Measurements on record are under [Benchmarks](#benchmarks).
2095
+ Times below are positions in the delivery, not measurements. Measurements on record are under [Benchmarks](#benchmarks). This is a fan-out on a delivery after the run's first. On the first delivery, [turbo](#turbo) starts the 3 inline bodies at step 1, while batch 1 commits.
2032
2096
 
2033
2097
  | Order | What happens | Count |
2034
2098
  |---|---|---|
@@ -2048,7 +2112,7 @@ If the steps take longer than the linger allows, the delivery acknowledges and t
2048
2112
 
2049
2113
  #### Fan-out on world-local
2050
2114
 
2051
- world-local has no `createBatch`, so the 100 creations are 100 single in-band writes, all committed before the inline bodies start (`spec9/delivery.ts`). It has no `queueBatch` either, so the 97 messages are sent as parallel single sends (`packages/core/src/runtime/helpers.ts`). It has no live-feed push, so the orchestrator polls every 2 s while bodies run, and it never lingers. It does not coalesce, so each of the 97 completion wakes is its own orchestrator delivery, delivered after the running one, one at a time: a delivery that finds nothing new since the last consumed position acknowledges after one tail read, the others load the log and replay. world-postgres behaves the same through its per-run Graphile queue, and so does world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1`. Coalescing there is an open follow-up (see [world-local and world-postgres do not coalesce](#world-local-and-world-postgres-do-not-coalesce)).
2115
+ world-local has no `createBatch`, so the 100 creations are 100 single in-band writes, all committed before the inline bodies start (`spec9/delivery.ts`). It has no `queueBatch` either, so the 97 messages are sent as parallel single sends (`packages/core/src/runtime/helpers.ts`). It has no live-feed push, so the orchestrator polls the log while bodies run, every 2 s backing off to 10 s while nothing new arrives, and it never lingers. It does not coalesce, so each of the 97 completion wakes is its own orchestrator delivery, delivered after the running one, one at a time: a delivery that finds nothing new since the last consumed position acknowledges after one tail read, the others load the log and replay. world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` behaves the same. Coalescing there is an open follow-up (see [world-local does not coalesce](#world-local-does-not-coalesce)). world-postgres has no `createBatch` or `queueBatch` either, but since #5275 its orchestrator sees the outcomes on its live feed while it runs or lingers, and the completion wakes that queue behind it on the run's named queue are covered by re-runs of its delivery instead of one delivery each.
2052
2116
 
2053
2117
  #### Fan-out edge cases
2054
2118
 
@@ -2231,7 +2295,7 @@ flowchart LR
2231
2295
  - **Run terminal.** A step message for a run that ended acknowledges without a body (`step-delivery.ts`, `resolveRunIdentity` in `packages/core/src/runtime/spec9/step-handler.ts`).
2232
2296
  - **Large inputs.** An input over 128 KiB is not carried on the message, and the step's invocation reads it from the step's creation event (`MAX_STEP_MESSAGE_INPUT_BYTES` in `packages/core/src/runtime/spec9/log-state.ts`, `resolveStepInput` in `step-handler.ts`).
2233
2297
  - **Unserializable arguments.** The step is finalized as `step_created` with a placeholder input plus `step_failed`, so the workflow observes the error (`finalizeUnserializableStep` in `packages/core/src/runtime/spec9/step-wait-creation.ts`).
2234
- - **world-postgres restarts `attempt` on a delayed reschedule.** A handoff keeps it (`1f7b912923`), and the re-send rule reads `deliveryCount`, so nothing strands; a fence refusal's redelivery does not count toward the delivery cap there (see [Known limitations](#known-limitations)).
2298
+ - **world-postgres restarts `attempt` on a step's retry in place.** A delayed reschedule of a step message starts `attempt` over, so a step retried in place many times on one message is not failed by the delivery cap. A handoff keeps it (`1f7b912923`), and so does a spec 9 orchestrator message's delayed reschedule, such as a fence refusal's redelivery (#5275); the re-send rule reads `deliveryCount`, so nothing strands.
2235
2299
 
2236
2300
  ### Hooks
2237
2301
 
@@ -2265,7 +2329,7 @@ sequenceDiagram
2265
2329
 
2266
2330
  ##### Resume while the orchestrator is running
2267
2331
 
2268
- A spec 9 delivery that has nothing left to run, while the run waits on an open hook or a background step, lingers for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (30 seconds by default), bounded by the inline deadline minus the inline-start margin (`lingerForExternalWork`, `packages/core/src/runtime/spec9/delivery.ts`). It lingers only while the World's `events.subscribe` feed is live (world-vercel implements it in `packages/world-vercel/src/storage.ts`; world-local and world-postgres do not). world-vercel defines `subscribe` even when its push transport is unavailable and then reports the failure through `onError`, so the linger checks `LiveLogFeed.isLive` after starting the feed and after every wake, and the feed's `onFeedDown` callback wakes it to end at once (`packages/core/src/runtime/spec9/live-feed.ts`). A subscription that never acknowledges and never errors still counts as live ([Live event feed](#linger-interaction)). While it lingers, or while it waits on inline bodies, a live feed pushes other writers' events and starts a new pass in the same delivery.
2332
+ A spec 9 delivery that has nothing left to run, while the run waits on a background step, lingers for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (30 seconds by default), and while it waits on open hooks alone for up to `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` (5 seconds by default), bounded by the inline deadline minus the inline-start margin (`lingerForExternalWork`, `packages/core/src/runtime/spec9/delivery.ts`). It lingers only while the World's `events.subscribe` feed is live (world-vercel implements it in `packages/world-vercel/src/storage.ts`, world-postgres in `packages/world-postgres/src/run-events.ts` since #5275; world-local does not). world-vercel defines `subscribe` even when its push transport is unavailable and then reports the failure through `onError`, so the linger checks `LiveLogFeed.isLive` after starting the feed and after every wake, and the feed's `onFeedDown` callback wakes it to end at once (`packages/core/src/runtime/spec9/live-feed.ts`). A subscription that never acknowledges and never errors still counts as live ([Live event feed](#linger-interaction)). While it lingers, or while it waits on inline bodies, a live feed pushes other writers' events and starts a new pass in the same delivery.
2269
2333
 
2270
2334
  ```mermaid
2271
2335
  sequenceDiagram
@@ -2281,13 +2345,20 @@ sequenceDiagram
2281
2345
  C->>Q: wake, keyed
2282
2346
  Note over Q: key held, wake coalesced
2283
2347
  O->>Q: acknowledge, refused
2284
- Note over O: re-run, nothing past the consumed position, exits without a replay
2348
+ Note over O: re-run reads the log, finds nothing more to do, acknowledges
2285
2349
  else no live feed or the delivery is busy, world-vercel
2286
2350
  C->>Q: wake, keyed
2287
2351
  Note over Q: key held, wake coalesced
2288
2352
  O->>Q: acknowledge, refused
2289
2353
  Note over O: re-run reads the log, acts on the payload
2290
- else world-local or world-postgres
2354
+ else world-postgres, live feed
2355
+ W-->>O: pushed event at the next slot
2356
+ Note over O: new pass in the same delivery, acts on the payload
2357
+ C->>Q: wake
2358
+ Note over Q: waits on the run's named queue
2359
+ O->>Q: acknowledges, takes the waiting wake
2360
+ Note over O: re-run reads the log, finds nothing more to do, acknowledges
2361
+ else world-local
2291
2362
  C->>Q: wake
2292
2363
  Note over Q: per-run gate holds it
2293
2364
  Q->>O: delivered after the running delivery ends
@@ -2398,7 +2469,7 @@ flowchart TD
2398
2469
  - A spec 9 wake without an idempotency key can be duplicated by a retried publish; the extra delivery exits without a replay when nothing new is in the log (`packages/core/src/runtime/resume-hook.ts`).
2399
2470
  - Linger is skipped when the remaining time to the inline deadline minus the margin is zero, so a late delivery does not hold the invocation (`packages/core/src/runtime/spec9/delivery.ts`).
2400
2471
  - A payload for an unawaited hook may land below speculative writes and is admitted; once the workflow awaits the hook, the boundary drains instead of running ahead (`admitBelowSpeculation` in `packages/core/src/runtime/spec9/run-ahead.ts`, `packages/core/src/runtime/spec9/delivery.ts`). See [Edge cases](#edge-cases-and-failure-handling).
2401
- - An older SDK's `resumeHook()` on a spec 9 run gets 400 `spec-version-requires-api-v5` from the world-vercel backend on the `hook_received` write, before it sends a wake. See [Spec routing](#spec-8-and-spec-9-side-by-side).
2472
+ - An older SDK's `resumeHook()` on a spec 9 run is admitted out-of-band by the world-vercel backend, then sends an unstamped wake; on the Local and Postgres Worlds it still fails with `RunNotSupportedError`. See [An older SDK and a spec 9 run](#an-older-sdk-and-a-spec-9-run).
2402
2473
  - A force-claim victim with no recorded `workflowName` (a legacy hook) gets no wake, and reads the disposal on its next invocation for any reason (`packages/core/src/runtime/hook-wake.ts`).
2403
2474
 
2404
2475
  ### Timers and waits
@@ -2616,19 +2687,19 @@ Every spec 9 timer carries an idempotency key of the form `wait:<correlationId>:
2616
2687
 
2617
2688
  A delivery that is still running inline steps completes a due wait itself. `waitForProgress` sleeps at most until the earliest open wait's deadline (`nextTimerAt`), and the next pass writes `wait_completed`. The timer message also goes out before the delivery waits (`armTimers` in `awaitInlineProgress`), so the wait is covered if the delivery ends first. When it comes due while the delivery still holds the key, it is coalesced and costs a re-run that finds nothing to do.
2618
2689
 
2619
- After its last pass, a delivery on a World with a live event feed (`events.subscribe`, world-vercel) lingers for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (default 30 seconds, capped by the inline deadline) when the run waits on an open hook or a background step (`awaitsExternalWork`, `lingerForExternalWork`). A sleep alone never makes it linger. While it lingers:
2690
+ After its last pass, a delivery on a World with a live event feed (`events.subscribe`, world-vercel and world-postgres) lingers when the run waits on a background step, for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (default 30 seconds), or on open hooks alone, for up to `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` (default 5 seconds), capped by the inline deadline (`externalWorkOf`, `lingerForExternalWork`). A sleep alone never makes it linger. While it lingers:
2620
2691
 
2621
2692
  - a wait that falls due ends the linger and the next pass completes it in process, the same as during inline work;
2622
- - it still holds the run's concurrency key, so a timer or a `run.wakeUp()` message arriving then is coalesced into it ("`run.wakeUp()`" below);
2693
+ - it still holds the run's concurrency key (world-postgres: its named queue), so a timer or a `run.wakeUp()` message arriving then is coalesced into it ("`run.wakeUp()`" below);
2623
2694
  - timers for the chains it owns are armed when the linger ends without new work, on the suspend path (`armNearDueTimers`, then `armTimers`). The first timer of a wait it created went out before the creation anyway.
2624
2695
 
2625
- **Guidance.** A run with a long-lived hook (an approval or cancel token held for days) next to a polling `sleep()` lingers for the whole window on every wake, so each poll costs up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` of function time. Dispose a hook once it is no longer needed, or lower the linger for such a deployment. A burst-aware hook linger is [follow-up 4](#2-hook-linger-policy).
2696
+ **Guidance.** A run with a long-lived hook (an approval or cancel token held for days) next to a polling `sleep()` lingers for the hook window on every wake, so each poll costs up to `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` (5 seconds by default) of function time. Dispose a hook once it is no longer needed, or set the hook linger to `0` for such a deployment (see [follow-up 2](#2-hook-linger-policy)).
2626
2697
 
2627
2698
  #### `run.wakeUp()`
2628
2699
 
2629
2700
  On a spec 9 run, `wakeUpRun` does not write `wait_completed`. It sends one orchestrator message with `completeWaits`, the waits to complete now, and returns `stoppedCount` as the number of waits it asked to complete, not the number completed (`packages/core/src/runtime/runs.ts`). The orchestrator completes the named waits on its first pass, whatever their `resumeAt` (`dueWaits` with `wakeUpWaits`, `spec9/log-state.ts`). On a spec 8 run, `wakeUpRun` writes each `wait_completed` out-of-band and then sends a wake, as before, and `stoppedCount` counts those writes.
2630
2701
 
2631
- The message is an ordinary keyed orchestrator message, so on spec 9 it is best-effort for this release:
2702
+ The message is an ordinary keyed orchestrator message, so on spec 9 it is best-effort, and a durable `wakeUp()` is not planned ([follow-up 1](#1-durable-runwakeup-on-spec-9)):
2632
2703
 
2633
2704
  ```mermaid
2634
2705
  sequenceDiagram
@@ -2646,14 +2717,19 @@ sequenceDiagram
2646
2717
  Q-->>Q: coalesced into the holder
2647
2718
  O->>L: re-run reads only the log
2648
2719
  Note over O: completeWaits lost, w1 runs its full length
2649
- else world-local or world-postgres, a delivery is running
2720
+ else world-postgres, a delivery is running or lingering
2721
+ Q-->>Q: waits on the run's named queue
2722
+ O->>Q: acknowledges, takes the waiting message
2723
+ O->>L: re-run reads only the log
2724
+ Note over O: completeWaits lost, w1 runs its full length
2725
+ else world-local, a delivery is running
2650
2726
  Q->>Q: per-run gate holds the message
2651
2727
  Q->>O: delivered after the running delivery
2652
2728
  O->>L: wait_completed w1
2653
2729
  end
2654
2730
  ```
2655
2731
 
2656
- On world-local the running delivery does not linger past its work, because world-local has no `events.subscribe`, so `@workflow/vitest`'s `waitForSleep()` and `wakeUp()` keep working. A durable wake-up is [follow-up 3](#1-durable-runwakeup-on-spec-9). See also [`run.wakeUp()` lost under coalescing](#runwakeup-lost-under-coalescing).
2732
+ On world-local the running delivery does not linger past its work, because world-local has no `events.subscribe`, so `@workflow/vitest`'s `waitForSleep()` and `wakeUp()` keep working. A durable wake-up is not planned ([follow-up 1](#1-durable-runwakeup-on-spec-9)). See also [`run.wakeUp()` lost under coalescing](#runwakeup-lost-under-coalescing).
2657
2733
 
2658
2734
  #### Why `wait_completed` is in-band only
2659
2735
 
@@ -2689,8 +2765,8 @@ If a `wait_completed` committed below `fetchUpdates`'s outcome, the live run saw
2689
2765
  | Longest delay of one message | 23 hours by default (`VERCEL_QUEUE_MAX_DELAY_SECONDS`, below the 24-hour message retention) | `setTimeout`, capped at about 24.8 days | A job's `run_at`, no cap |
2690
2766
  | Hop length | 82800 seconds on every World (`WAIT_CONTINUATION_MAX_DELAY_SECONDS`), so a hop never exceeds world-vercel's limit | the same | the same |
2691
2767
  | Timer key dedupe | `min(retention, 24h)` after the first send | while the first message lives | while a job holds the key (`unsafe_dedupe`) |
2692
- | A final timer while a delivery runs | Coalesced into it (concurrency key) | Held behind the run's gate, then delivered | Held behind the run's named queue, then delivered |
2693
- | A due wait during linger | Completed in process | No linger (no live feed) | No linger (no live feed) |
2768
+ | A final timer while a delivery runs | Coalesced into it (concurrency key) | Held behind the run's gate, then delivered | Held behind the run's named queue, then covered by the delivery's re-run if due when it acknowledges, else delivered |
2769
+ | A due wait during linger | Completed in process | No linger (no live feed) | Completed in process |
2694
2770
  | Timers after a restart | Survive (the queue is a service) | Lost; re-armed by the recovery delivery | Survive (jobs in the database); a hard-killed worker's job waits for its lock to clear ([follow-up 7](#5-world-postgres-stale-named-queue-lock-after-a-hard-kill)) |
2695
2771
 
2696
2772
  On world-vercel, a `delaySeconds` with a fraction is rounded up, so a timer can land up to a second after its deadline.
@@ -2786,6 +2862,16 @@ The feed is a timed tail read of the run's event log on the backend. Each read g
2786
2862
 
2787
2863
  `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS=0` turns the poll off. The live interval is never below the no-feed one.
2788
2864
 
2865
+ ##### Heartbeats
2866
+
2867
+ world-vercel lists `run-heartbeat` in its upgrade flags. A backend that sends heartbeats says so on the `subscribe_ack` (`heartbeatMs`, 10 s). Its feed then sends `{ reqId, type: 'run_heartbeat', slot }` after a successful read once it has sent nothing for `heartbeatMs`, naming the highest slot it has pushed. A feed whose reads fail sends none. On such an ack, `subscribeRunEvents` (`packages/world-vercel/src/events-live-feed.ts`) watches the feed, within the `subscribe` contract (`onEvent` and `onError` only):
2868
+
2869
+ - No push and no heartbeat for 3 × `heartbeatMs` (30 s) ends the feed through `onError` (`run-feed-silent`): a half-open socket, a feed that stopped without its `end` notice, or reads failing for that long.
2870
+ - A heartbeat naming a slot above the last one delivered means pushes went missing (a replacement subscription on the connection that started above what this subscriber held). The feed reads the log after its last delivered slot (`events.list`, cursor `eid:<eventId>`) and delivers what continues the sequence from there, in slot order. A read that fails ends the feed (`run-feed-gap`). The feed's guarantee stays increasing slots, each at most once: a push above the gap that lands while the read is in flight can still leave one, which the runtime's own poll fills as it does for any push that skips a slot.
2871
+ - A heartbeat under another `reqId` after the subscription's ack ends the feed (`run-feed-replaced`): a later `subscribe` on the connection replaced it.
2872
+
2873
+ The runtime's poll is unchanged: 10 s to 20 s while the feed is up. Against a backend that predates heartbeats the ack has no `heartbeatMs` and nothing is armed.
2874
+
2789
2875
  ##### One dedupe for both sources
2790
2876
 
2791
2877
  `offer()` (`live-feed.ts`) takes a push or a poll page the same way:
@@ -2809,7 +2895,19 @@ A clean poll doubles the interval, up to 20 s. Any other poll sets it back to 2
2809
2895
 
2810
2896
  ##### Worlds without a push
2811
2897
 
2812
- world-local and world-postgres have no `events.subscribe`. Their feed is the 2 s poll alone, `feedLive` is never true, and a delivery on them never lingers.
2898
+ world-local has no `events.subscribe`. Its feed is the poll alone, `feedLive` is never true, and a delivery on it never lingers. Without a push the poll backs off: each poll that delivers nothing doubles the interval from 2 s up to 10 s (`ORCHESTRATOR_POLL_MAX_INTERVAL_MS`), and a poll that delivers an event, a failed poll, or a write the delivery commits itself (`InBandWriter.addCommitListener`, `LiveLogFeed.noteActivity`, both engines) sets it back to 2 s. The same backoff applies on world-vercel and world-postgres while their feed is down or was refused.
2899
+
2900
+ ##### world-postgres over LISTEN/NOTIFY
2901
+
2902
+ world-postgres implements `events.subscribe` over `LISTEN`/`NOTIFY` (`packages/world-postgres/src/run-events.ts`, #5275):
2903
+
2904
+ - After an event write whose `specVersion` is 9 or above commits, the writer sends `pg_notify('workflow_run_events', runId)`, outside the write's transaction and without awaiting it, like the run-terminal `NOTIFY`. A `NOTIFY` inside the transaction could fail the write itself.
2905
+ - One `LISTEN` connection per process, opened on the first subscription, serves every subscription. A subscription reads once the connection listens, then on each announcement of its run: `events.list` after the last slot it delivered, `resolveData: 'all'`, in pages of 200. It delivers what continues the slot sequence, each slot once, and stops at a hole until a later announcement fills it. The notification is a signal only, so a duplicated or merged `NOTIFY` changes nothing.
2906
+ - A dropped `LISTEN` connection ends every live subscription through `onError` (`onDisconnect` on `listenChannel`), and a failed read ends its subscription. The connection reconnects for later subscriptions; a first `LISTEN` that fails refuses new subscriptions for 5 seconds.
2907
+ - A subscription ends (`onError`) at a hook resume another writer made with `resumeHook()` or a webhook (a `hook_received` with a `resumeId`), instead of delivering it. The resume's wake carries its producer's timing (`hookResumeTiming`), which is where the runtime starts the hook-resume latency measurement (`workflow.resume.total_ms`). A delivery that picked the resume up from the feed would consume it with no timing, and the wake would then find nothing to run. With the feed ended, a delivery that is only waiting stops lingering and acknowledges, and the wake, delivered or coalesced into that delivery's re-run with its timing, consumes the resume and measures it. A delivery running an inline body falls back to its log poll, as before the feed existed. The workflow's own `hook_received` (an `AbortController` abort) carries no `resumeId` and is delivered.
2908
+ - At most `floor(queueConcurrency / 2)` subscriptions are live per process, and none at `queueConcurrency: 1`. Past that a subscription is refused through `onError`, so its delivery polls instead of lingering. A lingering delivery holds a Graphile worker slot, and the cap keeps lingering deliveries from taking every slot while their own background steps wait for one.
2909
+
2910
+ There is no backend timed read as on world-vercel. A lost announcement (the writer died between its commit and its `NOTIFY`) is found by the next announcement of the run, or by the client poll at 10 to 20 s.
2813
2911
 
2814
2912
  #### How the two polls relate
2815
2913
 
@@ -2830,12 +2928,12 @@ Signalled failures (a refused `subscribe`, an `end` notice, a closed socket) are
2830
2928
 
2831
2929
  #### Linger interaction
2832
2930
 
2833
- A delivery with nothing left to run, while the run waits on an open hook or a background step, lingers for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (30 s), capped by the inline deadline minus the inline-start margin (`lingerForExternalWork`, `spec9/delivery.ts`).
2931
+ A delivery with nothing left to run lingers while the run waits on a background step, for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` (30 s), or on open hooks alone, for up to `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` (5 s), capped by the inline deadline minus the inline-start margin (`lingerForExternalWork`, `spec9/delivery.ts`).
2834
2932
 
2835
2933
  - **Only while the feed is live.** The linger starts the feed and checks `LiveLogFeed.isLive` (`feedLive && !stopped`) first, and again after every wake. A World without `events.subscribe` never lingers. Lingering on the poll alone would hold a function open for a poll's latency.
2836
2934
  - **A down feed ends it.** `onFeedDown` is `notifyProgress`, so `onError` wakes the linger, which sees `isLive` false and ends at once.
2837
2935
  - **What `isLive` cannot see.** A subscription that never acknowledges and never errors still counts as live, and so does every silent case above. The linger then runs to its end on the poll alone, and the poll's 20 s cap bounds what it can miss.
2838
- - **Long-lived hooks.** Any open hook is enough to linger, so a run with a long-lived approval or cancel hook holds each of its deliveries for the linger window after its last pass, and keeps a feed and a socket open for that time (see [Follow-up 2](#2-hook-linger-policy)).
2936
+ - **Long-lived hooks.** Any open hook is enough to linger, so a run with a long-lived approval or cancel hook holds each of its deliveries for the hook linger window (5 s by default) after its last pass, and keeps a feed and a socket open for that time (see [Follow-up 2](#2-hook-linger-policy)).
2839
2937
 
2840
2938
  #### Sequence
2841
2939
 
@@ -2888,11 +2986,11 @@ Each scenario has a timeline, the outcome, and the section that explains the mec
2888
2986
  | [Lost completion wake](#lost-completion-wake) | Fixed (`76643fe621`) |
2889
2987
  | [Inline `maxRetries: 0` step after an orchestrator crash](#inline-maxretries-0-step-after-an-orchestrator-crash) | Fixed (`75ddd45207`) |
2890
2988
  | [Background body before a refused start](#background-body-before-a-refused-start) | Behavior change, accepted |
2891
- | [Uncoalesced wakes on world-local and world-postgres](#uncoalesced-wakes-on-world-local-and-world-postgres) | Open follow-up |
2989
+ | [Uncoalesced wakes on world-local and world-postgres](#uncoalesced-wakes-on-world-local-and-world-postgres) | Fixed on world-postgres (#5275); open follow-up on world-local |
2892
2990
  | [Coalesced timer losing its re-arm](#coalesced-timer-losing-its-re-arm) | Fixed |
2893
2991
  | [Rotated start message re-entering turbo](#rotated-start-message-re-entering-turbo) | Fixed (`1a02e52b42`) |
2894
2992
  | [Near-due re-arms on every delivery](#near-due-re-arms-on-every-delivery) | Fixed (`dcddeb7378`) |
2895
- | [world-postgres re-send next to a locked job](#world-postgres-re-send-next-to-a-locked-job) | Fixed (`ab3713146b`) |
2993
+ | [world-postgres re-send next to a locked job](#world-postgres-re-send-next-to-a-locked-job) | Fixed (`ab3713146b`; spec 8 step messages #5275) |
2896
2994
  | [Two concurrent sleeps](#two-concurrent-sleeps) | Fixed |
2897
2995
  | [Run-ahead stop re-runs step bodies](#run-ahead-stop-re-runs-step-bodies) | Accepted, bounded |
2898
2996
  | [Replay divergence recovered in place](#replay-divergence-recovered-in-place) | Handled |
@@ -2902,7 +3000,7 @@ Each scenario has a timeline, the outcome, and the section that explains the mec
2902
3000
  | [`run.wakeUp()` lost under coalescing](#runwakeup-lost-under-coalescing) | Accepted |
2903
3001
  | [Spec 8 retry chains over 12 hours](#spec-8-retry-chains-over-12-hours) | Fixed |
2904
3002
  | [Older SDK after a rollback](#older-sdk-after-a-rollback) | Known limitation |
2905
- | [world-postgres resets `attempt`](#world-postgres-resets-attempt) | Handoff fixed; delayed reschedule still resets |
3003
+ | [world-postgres resets `attempt`](#world-postgres-resets-attempt) | Fixed (handoff `1f7b912923`, orchestrator reschedule #5275) |
2906
3004
  | [Inline retry re-sent past the 24-hour dedupe](#inline-retry-re-sent-past-the-24-hour-dedupe) | Fixed |
2907
3005
  | [Long step retries on Vercel](#long-step-retries-on-vercel) | Known cost |
2908
3006
  | [QuickJS differences](#quickjs-differences) | Known differences |
@@ -3039,7 +3137,7 @@ sequenceDiagram
3039
3137
  Note over M,W: now
3040
3138
  M->>Q: w1's timer, key wait:w1:R:R
3041
3139
  M->>W: wait_created w1
3042
- Note over M: dies; the timer is already out
3140
+ Note over M: dies, the timer is already out
3043
3141
  ```
3044
3142
 
3045
3143
  **Outcome.** Fixed (`e3018c00c3`): a pass sends the timer of its chain's earliest new wait before the `wait_created` commits, on both engines. If the commit then fails, the stray timer finds no wait or re-arms the one the redelivery created. Tests: `spec9/wait-chains.runtime.test.ts`, both engines, for a failed timer send and a lost creation response. Mechanism: [Timers and waits](#who-arms-a-timer).
@@ -3158,7 +3256,7 @@ sequenceDiagram
3158
3256
 
3159
3257
  ### Uncoalesced wakes on world-local and world-postgres
3160
3258
 
3161
- Both mint spec 9 runs when `WORKFLOW_SPEC_VERSION=9` is set and serialize a run's orchestrator deliveries, but neither coalesces.
3259
+ Both mint spec 9 runs when `WORKFLOW_SPEC_VERSION=9` is set and serialize a run's orchestrator deliveries. Neither coalesced; world-postgres does since #5275. On world-local:
3162
3260
 
3163
3261
  ```mermaid
3164
3262
  sequenceDiagram
@@ -3176,7 +3274,7 @@ sequenceDiagram
3176
3274
  end
3177
3275
  ```
3178
3276
 
3179
- **Outcome.** Open follow-up: a fan-out of `n` background steps costs `n` orchestrator deliveries in series. world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` has the same shape with one function invocation per wake. What the two Worlds would need (re-runs with the gate held, the coalesced count, `invocationStartedAt`, a handoff at the front of the run's queue) is on [Queue topology](#follow-up-coalescing-on-world-local-and-world-postgres).
3277
+ **Outcome.** Fixed on world-postgres (#5275): when a delivery acknowledges, its worker takes the run's orchestrator messages that queued behind it on the named queue and runs the handler again, with `deliveryCount + rerun`, the same `attempt` and the same `invocationStartedAt`, up to 32 times, and a handoff goes to the front of the run's queue. On world-local it is still an open follow-up: a fan-out of `n` background steps costs `n` orchestrator deliveries in series. world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` has the same shape with one function invocation per wake. What world-local would need is on [Queue topology](#follow-up-coalescing-on-world-local).
3180
3278
 
3181
3279
  ### Coalesced timer losing its re-arm
3182
3280
 
@@ -3253,7 +3351,7 @@ sequenceDiagram
3253
3351
  Note over G: current: unsafe_dedupe, J1 holds the key, no J2
3254
3352
  ```
3255
3353
 
3256
- **Outcome.** Fixed (`ab3713146b`): a spec 9 run's keyed sends use `unsafe_dedupe`, so a re-send next to a locked job adds nothing, and one next to a job in retry backoff keeps its attempts and `run_at`. Spec 8 keyed sends keep `preserve_run_at` and the same exposure, unverified. Tests: `packages/world-postgres/test/queue-dedupe.test.ts`, against Docker Postgres. Mechanism: [Queue topology](#world-local-and-world-postgres).
3354
+ **Outcome.** Fixed (`ab3713146b`): a spec 9 run's keyed sends use `unsafe_dedupe`, so a re-send next to a locked job adds nothing, and one next to a job in retry backoff keeps its attempts and `run_at`. Spec 8 step messages had the same exposure, verified to run a body twice; they use `unsafe_dedupe` too since #5275, and spec 8's other keyed sends keep `preserve_run_at`. Tests: `packages/world-postgres/test/queue-dedupe.test.ts` and `spec8-step-dedupe.test.ts`, against Docker Postgres. Mechanism: [Queue topology](#world-local-and-world-postgres).
3257
3355
 
3258
3356
  ### Two concurrent sleeps
3259
3357
 
@@ -3394,7 +3492,7 @@ sequenceDiagram
3394
3492
  Note over O: w1 runs its full length
3395
3493
  ```
3396
3494
 
3397
- **Outcome.** Accepted: `wakeUp()` is best-effort on world-vercel while an orchestrator delivery holds the key, and reliable when the run is suspended and on world-local and world-postgres (`wakeUpRun` in `packages/core/src/runtime/runs.ts`). The unkeyed wake it replaced had two bugs when an orchestrator was running: a fence-losing wake dropped `completeWaits`, and a fence-winning one refused the running orchestrator's `step_completed`, so an open inline step's body ran twice. Mechanism: [Timers and waits](#timers-and-waits).
3495
+ **Outcome.** Accepted, and a durable `wakeUp()` is not planned (see [follow-up 1](#1-durable-runwakeup-on-spec-9)): `wakeUp()` is best-effort on world-vercel while an orchestrator delivery holds the key, and on world-postgres while one runs, since #5275 coalesces the messages queued behind it. It is reliable when the run is suspended, and on world-local (`wakeUpRun` in `packages/core/src/runtime/runs.ts`). The unkeyed wake it replaced had two bugs when an orchestrator was running: a fence-losing wake dropped `completeWaits`, and a fence-winning one refused the running orchestrator's `step_completed`, so an open inline step's body ran twice. Mechanism: [Timers and waits](#timers-and-waits).
3398
3496
 
3399
3497
  ### Spec 8 retry chains over 12 hours
3400
3498
 
@@ -3422,16 +3520,16 @@ A deployment on an SDK without spec 9 writes to a spec 9 run, for example a roll
3422
3520
  sequenceDiagram
3423
3521
  participant Old as Older SDK deployment
3424
3522
  participant B as world-vercel backend
3425
- Old->>B: hook_received or run_cancelled, API below 5
3523
+ Old->>B: run_cancelled, API below 5
3426
3524
  B-->>Old: 400 spec-version-requires-api-v5
3427
3525
  Note over Old: no wake is sent, the run is unchanged
3428
3526
  ```
3429
3527
 
3430
- **Outcome.** The older SDK cannot resume hooks on, or cancel, spec 9 runs. Reads still work. On Vercel the run's own deliveries stay on the deployment that created it, so the run keeps going; only callers on the older SDK fail. On a shared Local or Postgres queue the older process can also take the run's messages, and the run stalls until it is upgraded again (see [The rollback floor](#the-rollback-floor)). Mechanism: [Spec routing](#spec-8-and-spec-9-side-by-side).
3528
+ **Outcome.** The older SDK cannot cancel spec 9 runs. Reads still work. On Vercel its hook resumes and webhooks still reach the run, written out-of-band ([An older SDK and a spec 9 run](#an-older-sdk-and-a-spec-9-run)); on the Local and Postgres Worlds they fail too. On Vercel the run's own deliveries stay on the deployment that created it, so the run keeps going; only the older SDK's other writes fail. On a shared Local or Postgres queue the older process can also take the run's messages, and the run stalls until it is upgraded again (see [The rollback floor](#the-rollback-floor)). Mechanism: [Spec routing](#spec-8-and-spec-9-side-by-side).
3431
3529
 
3432
3530
  ### world-postgres resets `attempt`
3433
3531
 
3434
- Every `{ timeoutSeconds }` result on world-postgres reschedules on a new Graphile job. `attempt` comes from that job's own counter plus an `attemptOffset`. A spec 9 handoff now carries the attempts so far as `attemptOffset` (`1f7b912923`); a delayed reschedule does not.
3532
+ Every `{ timeoutSeconds }` result on world-postgres reschedules on a new Graphile job. `attempt` comes from that job's own counter plus an `attemptOffset`. A spec 9 handoff now carries the attempts so far as `attemptOffset` (`1f7b912923`), and so does a spec 9 orchestrator message's delayed reschedule (#5275). A step message's delayed reschedule, its retry in place, still starts `attempt` over, so a step retried in place many times on one message is not failed by the delivery cap.
3435
3533
 
3436
3534
  ```mermaid
3437
3535
  sequenceDiagram
@@ -3443,10 +3541,10 @@ sequenceDiagram
3443
3541
  O-->>G: timeoutSeconds 0, handoff
3444
3542
  G->>O: job 2, attempt 2, deliveryCount 3
3445
3543
  O-->>G: timeoutSeconds 1, a fence refusal
3446
- G->>O: job 3, attempt 1, deliveryCount 4
3544
+ G->>O: job 3, attempt 3, deliveryCount 4 (attempt 1 before #5275)
3447
3545
  ```
3448
3546
 
3449
- **Outcome.** The handoff case is fixed. The crash-then-handoff strand is also gone because the re-send rule reads `deliveryCount`, not `attempt`. Still open: a delayed reschedule starts `attempt` over, so on world-postgres a fence refusal's redelivery does not count toward the delivery cap (see [Follow-ups](#follow-ups)). Mechanism: [Queue topology](#queue-topology-handoffs-and-rotation).
3547
+ **Outcome.** Fixed. The handoff case was fixed first. The crash-then-handoff strand is also gone because the re-send rule reads `deliveryCount`, not `attempt`. Since #5275 a spec 9 orchestrator message's delayed reschedule carries `attempt` over (`attemptOffset: attempt`), so on world-postgres a run refused on every pass reaches the delivery cap (see [follow-up 12](#12-world-postgres-count-a-fence-refusal-redelivery-toward-the-delivery-cap)). Tested in `world-postgres/test/queue-spec9-delivery.test.ts`. Mechanism: [Queue topology](#queue-topology-handoffs-and-rotation).
3450
3548
 
3451
3549
  ### Inline retry re-sent past the 24-hour dedupe
3452
3550
 
@@ -3490,12 +3588,13 @@ flowchart LR
3490
3588
  N["node engine"] --> RA["Run-ahead"]
3491
3589
  N --> DR["Divergence recovery in place"]
3492
3590
  N --> DL["Deadline handoff, verified on Vercel"]
3493
- Q["QuickJS engine"] --> NRA["No run-ahead, waits for every write"]
3591
+ Q["QuickJS engine"] --> NRA["Run-ahead, restarts in place on a displaced write"]
3494
3592
  Q --> NDR["No divergence recovery, fails the run"]
3495
- Q --> QC["Continuations hand off, covered by typecheck only"]
3593
+ Q --> QD["Deadline handoff and inline-start margin, as on node"]
3594
+ Q --> QC["Other continuations hand off, covered by typecheck only"]
3496
3595
  ```
3497
3596
 
3498
- **Outcome.** On QuickJS, run-ahead stops, their restarts and the out-of-band `wait_completed` hazard never occur, and a VM failure fails the run as before this change (`packages/core/src/runtime/spec9/quickjs-entrypoint.ts` has no run-ahead or divergence-recovery code). Its exit continuations (replay budget, an elapsed wait, an unread write of its own) hand off through `continueInNextDelivery` (`packages/core/src/runtime/spec9/delivery.ts`), and no test triggers them. Mechanism: [Run-ahead and turbo](#run-ahead).
3597
+ **Outcome.** QuickJS runs ahead as node does, but a speculative write another writer displaced restarts the delivery in place instead of being repaired (see [QuickJS run-ahead](#quickjs-run-ahead)). A VM failure fails the run as before this change (`packages/core/src/runtime/spec9/quickjs-entrypoint.ts` has no divergence-recovery code). It hands off at the invocation's inline deadline and keeps new steps out of the inline-start margin as the node engine does (`inlineDeadlineMs`, covered by `spec9/world-vercel-queue.contract.test.ts` on both engines). Its other exit continuations (replay budget, an elapsed wait, an unread write of its own) hand off through `continueInNextDelivery` (`packages/core/src/runtime/spec9/delivery.ts`), and no test triggers them. Mechanism: [Run-ahead and turbo](#run-ahead).
3499
3598
 
3500
3599
  ## Decisions and trade-offs
3501
3600
 
@@ -3583,7 +3682,7 @@ export async function digest(userId: string) {
3583
3682
 
3584
3683
  If the `wait_completed` committed below `fetchUpdates`'s outcome, the live run saw the step first and the replay sees the wait first. A reliable wake-up under a running orchestrator would be a new out-of-band "wake requested" event, written like `hook_received` and turned into an in-band `wait_completed` by the orchestrator. Not implemented.
3585
3684
 
3586
- **Decision.** `wakeUp()` on spec 9 stays best-effort for this release. The post-pass linger makes the drop window common rather than rare: a run with an open hook or a background step keeps a delivery live for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` after each pass, and a wake-up in that window is folded away while `stoppedCount` still counts it. That is documented (`594cc5f6e5`: `wakeUpRun`, `Run.wakeUp()`, `StopSleepResult.stoppedCount`, the `getRun` docs and [Known limitations](#known-limitations)). The durable "wake requested" event above is the more thorough fix and a possible follow-up (see [Follow-ups](#follow-ups)). A confirm-and-resend loop was rejected: it makes `wakeUp()` block for at least a linger window and still has no upper bound if every resend lands in one.
3685
+ **Decision.** `wakeUp()` on spec 9 stays best-effort for this release. The post-pass linger makes the drop window common rather than rare: a run with an open hook or a background step keeps a delivery live after each pass (up to `WORKFLOW_ORCHESTRATOR_LINGER_MS` for a background step, `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` for open hooks alone), and a wake-up in that window is folded away while `stoppedCount` still counts it. That is documented (`594cc5f6e5`: `wakeUpRun`, `Run.wakeUp()`, `StopSleepResult.stoppedCount`, the `getRun` docs and [Known limitations](#known-limitations)). The durable "wake requested" event above is the more thorough fix and a possible follow-up (see [Follow-ups](#follow-ups)). A confirm-and-resend loop was rejected: it makes `wakeUp()` block for at least a linger window and still has no upper bound if every resend lands in one.
3587
3686
 
3588
3687
  Callers of `run.wakeUp()`: the public API (`Run.wakeUp()`), `@workflow/vitest`'s `waitForSleep()` pattern, the local observability UI (`packages/web`), and the Vercel dashboard's wake-up action. The dashboard calls `wakeUpRun` from a pinned `@workflow/core` release that writes `wait_completed` out-of-band, which the backend refuses on spec 9 runs. Its wake-up therefore does not work on spec 9 runs until it moves to a release with this change.
3589
3688
 
@@ -3591,12 +3690,12 @@ Callers of `run.wakeUp()`: the public API (`Run.wakeUp()`), `@workflow/vitest`'s
3591
3690
 
3592
3691
  - **Opt-in.** Spec 9 is opt-in: minting only reads `WORKFLOW_SPEC_VERSION`, events route by each run's own spec (option B), and one e2e lane runs spec 9 (see [How new runs get their version](#how-new-runs-get-their-version), done).
3593
3692
  - **Background starts are awaited (3a).** A background step's body starts once its `step_started` committed; `WORKFLOW_OPTIMISTIC_BACKGROUND_START=1` restores the optimistic start. The trade-off is one start round trip of latency per background body, against a step queued before `run.cancel()` running its side effects and a throttled start running its body more than once (see [Known limitations](#known-limitations)).
3594
- - **Linger guidance (3b).** An open hook keeps every pass lingering for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS`. For this release that is documented with guidance (dispose a hook once it is no longer needed, or lower the linger for a deployment with a long-lived hook beside a polling `sleep()`); a burst-aware hook linger is a follow-up (see [Follow-ups](#follow-ups)).
3693
+ - **Linger guidance (3b).** An open hook keeps every pass lingering. Since [follow-up 2](#2-hook-linger-policy), open hooks alone linger for `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` (5 s by default) instead of the full `WORKFLOW_ORCHESTRATOR_LINGER_MS`, and the guidance stands (dispose a hook once it is no longer needed, or turn the hook linger off for a deployment with a long-lived hook beside a polling `sleep()`).
3595
3694
  - **Linger only while the feed is live (3c).** A delivery lingers only while `LiveLogFeed.isLive` holds, and the feed's `onFeedDown` ends the linger at once (`6292be4ee8`).
3596
3695
  - **`run.wakeUp()` stays best-effort (3d)** for this release (see [Known limitations](#known-limitations)).
3597
3696
  - **Full-log reads on step retry hops (4.1)** are a post-release monitoring item (see [Follow-ups](#follow-ups)).
3598
3697
  - **QuickJS creation batching (4.2)** landed (`a09d3138df`).
3599
- - **world-postgres LISTEN/NOTIFY and the no-push poll backoff (4.3)** are follow-ups before default-on (see [Follow-ups](#follow-ups)).
3698
+ - **world-postgres LISTEN/NOTIFY and the no-push poll backoff (4.3)** are done (#5275; see [Follow-ups](#follow-ups)).
3600
3699
  - **Step start latency.** A background step's message carries its step's creation time, and on world-vercel its first `step_started` reports it, so the latency from a step's creation to its start can be read off the start alone. world-local and world-postgres ignore it.
3601
3700
 
3602
3701
  ### The near-due re-arm is gated and keyed
@@ -3662,8 +3761,8 @@ Why `resumeAt` is in the key: two deadlines must never share a key. A wait's `re
3662
3761
 
3663
3762
  ## Known limitations
3664
3763
 
3665
- - **`run.wakeUp()` is best-effort on Vercel.** A wake-up that arrives while an orchestrator invocation of the run is live is folded into it and lost, and the sleeps run their full length. An invocation stays live after its last pass for up to [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](/docs/configuration/runtime-tuning#workflow_orchestrator_linger_ms) while the run waits on an open hook or a background step, so a wake-up sent shortly after such a run was active can be lost too. `stoppedCount` counts the sleeps the call asked to complete, not completions. This release keeps `run.wakeUp()` best-effort on spec 9 by decision. A durable wake request, recorded as an event the orchestrator turns into the sleep's completion, would make it reliable and is a possible follow-up.
3666
- - **An open hook keeps every invocation lingering.** Any hook that is created and not disposed makes an invocation that has nothing left to run stay live for up to the linger window ([`WORKFLOW_ORCHESTRATOR_LINGER_MS`](/docs/configuration/runtime-tuning#workflow_orchestrator_linger_ms), 30 seconds by default) after each pass, however rarely the hook is resumed. A run that keeps a hook open for its whole life pays up to the window after every pass, including one that just armed a long sleep. A long-lived approval or cancel hook beside a polling `sleep()` loop is therefore a pattern to avoid: each timer wake then holds a function for the linger window. Where it is needed, lower `WORKFLOW_ORCHESTRATOR_LINGER_MS`, or set it to `0`, which also ends the linger for background steps. A linger policy that lingers on hooks only while a burst of resumes is plausible is a follow-up.
3764
+ - **`run.wakeUp()` is best-effort on Vercel and Postgres.** A wake-up that arrives while an orchestrator invocation of the run is live is folded into it (on world-postgres, covered by a re-run of the running delivery) and lost, and the sleeps run their full length. An invocation stays live after its last pass for up to [`WORKFLOW_ORCHESTRATOR_LINGER_MS`](/docs/configuration/runtime-tuning#workflow_orchestrator_linger_ms) while the run waits on a background step, or [`WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`](/docs/configuration/runtime-tuning#workflow_orchestrator_hook_linger_ms) while it waits on open hooks alone, so a wake-up sent shortly after such a run was active can be lost too. `stoppedCount` counts the sleeps the call asked to complete, not completions. `run.wakeUp()` stays best-effort on spec 9 by decision; a durable wake request is not planned ([follow-up 1](#1-durable-runwakeup-on-spec-9)).
3765
+ - **An open hook keeps every invocation lingering.** Any hook that is created and not disposed makes an invocation that has nothing left to run stay live for up to the hook linger window ([`WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`](/docs/configuration/runtime-tuning#workflow_orchestrator_hook_linger_ms), 5 seconds by default) after each pass, however rarely the hook is resumed. A run that keeps a hook open for its whole life pays up to that window after every pass, including one that just armed a long sleep, so a long-lived approval or cancel hook beside a polling `sleep()` loop holds a function for up to 5 seconds on each timer wake. Where that matters, dispose the hook once it is no longer needed, or set `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS` to `0`; background steps keep their linger.
3667
3766
  - **A step left without a message for 23 hours stays without one.** A background step whose invocation died between its `step_created` and its message, and that sees no orchestrator delivery other than a first one for 23 hours, is not sent again: a later send could outlive the queue's deduplication window and give the step a second message. It is logged, and counted on the delivery's span as `workflow.reenqueue.skipped_too_old`.
3668
3767
  - **Local World restarts.** The Local World's queue is in memory, so a restart loses the step messages and timers it held. Its recovery messages are marked as such, and the delivery of one sends every open step's message again, started steps included, and arms the timer of every open sleep.
3669
3768
 
@@ -3671,21 +3770,21 @@ Why `resumeAt` is in the key: two deadlines must never share a key. A wait's `re
3671
3770
 
3672
3771
  When a hazard stops run-ahead, a step whose body started ahead of its creation, and whose creation the stop then refused, has no committed start, so the restarted pass runs its body again. Per-entity batch order is now part of the spec 9 contract, so one refused speculative batch can carry up to `WORKFLOW_RUN_AHEAD_DEPTH` such steps (10 by default): up to that many bodies can run twice per stop, where earlier versions of spec 9 ran at most one. A stop needs the speculative writes to fail or be overtaken: a refused entry in a speculative batch, a World that did not store a write at its `occurredAt`, or another writer's path-changing event landing below them (`spec9/delivery.ts`, `runAheadHazard` in `spec9/run-ahead.ts`). An awaited hook is not one of them: it makes the boundary path-changing, so the orchestrator waits for its writes instead of running ahead. Which real-world writers can still produce a stop is not verified; see [Run-ahead and turbo](#run-ahead). A step declared with `maxRetries: 0` never starts before its start commits (`mayRunBeforeItsStart` in `spec9/step-executor.ts`), so it is never one of the steps run twice.
3673
3772
 
3674
- ### world-local and world-postgres do not coalesce
3773
+ ### world-local does not coalesce
3675
3774
 
3676
- Both mint spec 9 runs when `WORKFLOW_SPEC_VERSION=9` is set (`mintedSpecVersion(process.env, { inBandFence })` in `packages/world-local/src/index.ts` and `packages/world-postgres/src/index.ts`). Both serialize a spec 9 run's orchestrator deliveries, but neither coalesces orchestrator messages, so every background completion's wake becomes its own orchestrator delivery, run one after another behind the run's gate. A 97-step fan-out sends 97 wakes and gets 97 orchestrator deliveries. A delivery that finds the log tail at the position this process last consumed acknowledges after one tail read (`consumed-position.ts`); every other one loads the full log and replays. world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` has the same shape: its spec 9 messages are unkeyed on per-run topics, so nothing is coalesced and each wake is one function invocation.
3775
+ Both mint spec 9 runs when `WORKFLOW_SPEC_VERSION=9` is set (`mintedSpecVersion(process.env, { inBandFence })` in `packages/world-local/src/index.ts` and `packages/world-postgres/src/index.ts`). Both serialize a spec 9 run's orchestrator deliveries. world-local does not coalesce orchestrator messages, so every background completion's wake becomes its own orchestrator delivery, run one after another behind the run's gate. A 97-step fan-out sends 97 wakes and gets 97 orchestrator deliveries. world-postgres did the same until #5275, which coalesces them (see [world-local and world-postgres](#world-local-and-world-postgres)). A delivery that finds the log tail at the position this process last consumed acknowledges after one tail read (`consumed-position.ts`); every other one loads the full log and replays. world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` has the same shape: its spec 9 messages are unkeyed on per-run topics, so nothing is coalesced and each wake is one function invocation.
3677
3776
 
3678
3777
  What they implement today of the handoff semantics, from the code:
3679
3778
 
3680
3779
  | | world-local | world-postgres | world-vercel (keyed) |
3681
3780
  |---|---|---|---|
3682
- | `{ timeoutSeconds: 0 }` on a spec 9 message | Same message again, `attempt` unchanged (up to 10,000 handoffs), but the delivery releases the run gate and takes it again in FIFO order, so wakes already waiting run first | A new Graphile job on the run's named queue with no delay, behind jobs already queued; `attempt` and the delivery count carry over (`attemptOffset`, `deliveryOffset`), and only a delayed reschedule starts `attempt` over (see [world-postgres restarts `attempt` on a delayed reschedule](#world-postgres-restarts-attempt-on-a-delayed-reschedule)) | Lease handoff, same message at once |
3683
- | A message for a run whose delivery is running | Waits behind the gate, delivered later | Waits behind the named queue, delivered later | Coalesced into the running delivery |
3684
- | Re-run with the lease held | None | None | Up to 32 (`MAX_COALESCED_RERUNS`) |
3685
- | Coalesced count reported to the handler | None | None | `deliveryCount + rerun`, same `attempt` |
3686
- | `invocationStartedAt` | Not passed | Not passed | Passed to every re-run |
3781
+ | `{ timeoutSeconds: 0 }` on a spec 9 message | Same message again, `attempt` unchanged (up to 10,000 handoffs), but the delivery releases the run gate and takes it again in FIFO order, so wakes already waiting run first | A new Graphile job on the run's named queue with no delay and priority `-1`, ahead of jobs already queued; `attempt` and the delivery count carry over (`attemptOffset`, `deliveryOffset`), and only a step's delayed reschedule starts `attempt` over (see [world-postgres restarts `attempt` on a step's delayed reschedule](#world-postgres-restarts-attempt-on-a-steps-delayed-reschedule)) | Lease handoff, same message at once |
3782
+ | A message for a run whose delivery is running | Waits behind the gate, delivered later | Waits behind the named queue; covered by the delivery's re-run if due when it acknowledges | Coalesced into the running delivery |
3783
+ | Re-run with the lease held | None | Up to 32 (`MAX_COALESCED_RERUNS`); past it the remaining jobs are delivered as usual | Up to 32 (`MAX_COALESCED_RERUNS`) |
3784
+ | Coalesced count reported to the handler | None | `deliveryCount + rerun`, same `attempt` | `deliveryCount + rerun`, same `attempt` |
3785
+ | `invocationStartedAt` | Not passed | Passed to every re-run | Passed to every re-run |
3687
3786
 
3688
- What coalescing needs there: drop an orchestrator message claimed while the run's delivery holds the gate and count it on the holder; when the holder's handler returns, run it again in the same process with the next `deliveryCount`, the same `attempt` and the first run's `invocationStartedAt`, until no counted message is left uncovered; cap the re-runs and hand off past the cap, as world-vercel does. A message with state the log does not hold must not be dropped: an intermediate wait hop is already ungated, and every other spec 9 orchestrator message is safe to coalesce (see [No orchestrator message carries state the log needs](#no-orchestrator-message-carries-state-the-log-needs)). A handoff should also go to the front of the run's queue rather than behind waiting wakes. Not implemented.
3787
+ What coalescing needs there: drop an orchestrator message claimed while the run's delivery holds the gate and count it on the holder; when the holder's handler returns, run it again in the same process with the next `deliveryCount`, the same `attempt` and the first run's `invocationStartedAt`, until no counted message is left uncovered; cap the re-runs and hand off past the cap, as world-vercel does. A message with state the log does not hold must not be dropped: an intermediate wait hop is already ungated, and every other spec 9 orchestrator message is safe to coalesce (see [No orchestrator message carries state the log needs](#no-orchestrator-message-carries-state-the-log-needs)). A handoff should also go to the front of the run's queue rather than behind waiting wakes. Implemented on world-postgres (#5275); not on world-local.
3689
3788
 
3690
3789
  ### Spec detection rests on the payload stamp
3691
3790
 
@@ -3693,20 +3792,20 @@ Topic, key and continuation are chosen from the spec version the message carries
3693
3792
 
3694
3793
  Every spec 9 send site in this runtime now names the run's spec version (`specVersion` on the queue options, which `withRunSpecVersion` stamps as `runSpecVersion`; a step message carries `runContext`): the orchestrator's wakes and timers (from the routed spec, `WorkflowDelivery.runSpecVersion`), the QuickJS engine's wakes and timers, and the step handler's wakes. The spec 8 orchestrator's wakes, timers and requeues stamp it too. Routing keeps no per-process memory of run spec versions; an earlier version did, and sends that relied on it went out unstamped after 10,000 other runs in one process. `spec9/spec-stamp.runtime.test.ts` checks every message of a spec 9 run on both engines, and `spec-stamp-world-local.test.ts` checks spec 8 and spec 9 runs end to end on world-local.
3695
3794
 
3696
- Producers outside this runtime can still send a spec 9 run a message that is unstamped or stamped below 9: `resumeHook()` and `cancel()` callers in deployments on an older SDK, or any other client of the World. Nothing in the runtime can prevent that. Such a message is treated as spec 8 by the World: world-vercel sends it unkeyed, so it can run next to the keyed orchestrator. Routing still gets it to the spec 9 orchestrator (an unstamped message through `runs.get`, a low hint through the hand-off), and the in-band fence keeps the log correct (the loser stands down with a redelivery of its message). The cost is wasted orchestrator work, which can include a second run of an inline step's body, not a corrupted log.
3795
+ Producers outside this runtime can still send a spec 9 run a message that is unstamped or stamped below 9: `resumeHook()` and `cancel()` callers in deployments on an older SDK, or any other client of the World. Nothing in the runtime can prevent that. Such a message is treated as spec 8 by world-vercel and world-local: world-vercel sends it unkeyed, so it can run next to the keyed orchestrator. world-postgres reads an unstamped orchestrator message's run from its row and moves it to the run's named queue (see [An unstamped message](#an-unstamped-message)). Routing still gets it to the spec 9 orchestrator (an unstamped message through `runs.get`, a low hint through the hand-off), and the in-band fence keeps the log correct (the loser stands down with a redelivery of its message). The cost is wasted orchestrator work, which can include a second run of an inline step's body, not a corrupted log.
3697
3796
 
3698
3797
  ### Long step retries cost an invocation every 900 seconds on Vercel
3699
3798
 
3700
3799
  A spec 9 step retries in place: its message is redelivered after `retryAfter` (`{ timeoutSeconds: n }`). Vercel Queues caps a redelivery's delay at 900 seconds, so a retry more than 15 minutes out is reached in 900-second redeliveries, each an invocation that reads the log and asks again: about 96 a day for a day-long backoff, where spec 8 sends a new message of up to 23 hours (about 2 a day). Not measured.
3701
3800
 
3702
- ### world-postgres restarts `attempt` on a delayed reschedule
3801
+ ### world-postgres restarts `attempt` on a step's delayed reschedule
3703
3802
 
3704
- world-postgres computes `attempt` from the Graphile job's own attempt counter. A spec 9 handoff (`{ timeoutSeconds: 0 }`) now carries `attempt` over (`1f7b912923`), as the contract asks. A `{ timeoutSeconds: n }` reschedule with `n > 0` still starts it over, on purpose, so that a step retried in place many times on one message is not failed by the delivery cap. Two consequences:
3803
+ world-postgres computes `attempt` from the Graphile job's own attempt counter. A spec 9 handoff (`{ timeoutSeconds: 0 }`) now carries `attempt` over (`1f7b912923`), as the contract asks, and so does a spec 9 orchestrator message's `{ timeoutSeconds: n }` reschedule with `n > 0` (#5275). A step message's such reschedule still starts it over, on purpose, so that a step retried in place many times on one message is not failed by the delivery cap. Two consequences:
3705
3804
 
3706
3805
  - The crash-then-handoff strand described here earlier is gone for another reason too: the re-send rule reads `deliveryCount`, which keeps counting across every reschedule, not `attempt`.
3707
- - A fence-refused delivery's redelivery is such a reschedule, so on world-postgres repeated refusals do not reach the delivery cap. The streak is still logged at warn. Not fixed here.
3806
+ - A fence-refused delivery's redelivery is an orchestrator reschedule, so on world-postgres repeated refusals reach the delivery cap. Before #5275 they did not, and the streak was only logged at warn.
3708
3807
 
3709
- A re-send of an unstarted step used to reset the job's attempt counter and backoff, and next to a locked job to insert a second one (graphile-worker 0.16.6, `preserve_run_at`). Fixed (`ab3713146b`): a spec 9 run's keyed sends use `unsafe_dedupe` and leave any job holding the key as it is (see [How world-postgres deduplicates a spec 9 run's keyed sends](#how-world-postgres-deduplicates-a-spec-9-runs-keyed-sends)).
3808
+ A re-send of an unstarted step used to reset the job's attempt counter and backoff, and next to a locked job to insert a second one (graphile-worker 0.16.6, `preserve_run_at`). Fixed (`ab3713146b`): a spec 9 run's keyed sends, and since #5275 every run's step messages, use `unsafe_dedupe` and leave any job holding the key as it is (see [How world-postgres deduplicates a spec 9 run's keyed sends](#how-world-postgres-deduplicates-a-spec-9-runs-keyed-sends)).
3710
3809
 
3711
3810
  ### Billing
3712
3811
 
@@ -3714,11 +3813,12 @@ Vercel Queues bills operations on keyed messages at its premium rate (2x) for th
3714
3813
 
3715
3814
  ### QuickJS
3716
3815
 
3717
- Spec 9 runs on both engines. Every spec 9 runtime test file runs on both, except the run-ahead suite, and the QuickJS Vercel Prod lanes pass what the node lanes pass. Differences and gaps:
3816
+ Spec 9 runs on both engines. Every spec 9 runtime test file runs on both, the run-ahead suite included (two of its cases are engine-specific: node's in-place repair and QuickJS's restart), and the QuickJS Vercel Prod lanes pass what the node lanes pass. Differences and gaps:
3718
3817
 
3719
- - **No run-ahead.** QuickJS always waits for its writes to commit, so run-ahead stops, their restarts, and the out-of-band `wait_completed` hazard in the `wakeUp()` section never occur on it.
3818
+ - **Run-ahead restarts instead of repairing.** See [QuickJS run-ahead](#quickjs-run-ahead).
3720
3819
  - **No replay-divergence recovery.** As before this change, QuickJS fails the run on a VM failure.
3721
- - **Continuations covered by typecheck only.** Its exit continuations (replay budget, an elapsed wait, an unread write of its own) hand off through `continueInNextDelivery`. No test triggers them, because QuickJS keeps its VM live through inline steps. The deadline handoff verified on Vercel was on the node engine.
3820
+ - **Deadline handoff and inline-start margin, as on node.** A turn that begins at or past the invocation's inline deadline starts nothing more: the bodies still running settle, and the run continues in the next delivery through `continueInNextDelivery`, a handoff on the same message. Within `WORKFLOW_INLINE_STEP_DEADLINE_MARGIN_MS` of the deadline, new steps are background steps (`inlineDeadlineMs` in `spec9/quickjs-entrypoint.ts`; [follow-up 15](#15-quickjs-hand-off-at-the-invocation-deadline)). The adapter contract test covers both on both engines. The deadline handoff verified on Vercel was on the node engine.
3821
+ - **Other continuations covered by typecheck only.** Its other exit continuations (replay budget, an elapsed wait, an unread write of its own) hand off through `continueInNextDelivery`. No test triggers them, because QuickJS keeps its VM live through inline steps.
3722
3822
  - **Fence refusal** shares the node path's handling, through the catch in `spec9/delivery.ts`; QuickJS reports its sent step and timer messages back (`onStepMessageSent`, `onWaitTimerSent`). Covered by the orchestrator tests that run on both engines; QuickJS inline-step retries have no dedicated test.
3723
3823
 
3724
3824
  ### A long sequential run reaches the inline-start margin before the deadline
@@ -3872,31 +3972,65 @@ Larger follow-ups, one issue each. The list matches the one in the pull request
3872
3972
 
3873
3973
  ### 1. Durable `run.wakeUp()` on spec 9
3874
3974
 
3875
- `wakeUp()` names the sleeps to complete on a keyed orchestrator message, so one that is folded into a running or lingering delivery is dropped while `stoppedCount` still counts it. This release keeps it best-effort (see [Known limitations](#known-limitations)). The thorough fix is an out-of-band "wake requested" event, written like `hook_received` and turned into an in-band `wait_completed` by the orchestrator, so a coalesced wake loses nothing. It needs a new event type and world-vercel backend support. A confirm-and-resend loop was rejected. [4365355511](https://github.com/vercel/workflow/pull/4661#discussion_r4365355511).
3975
+ **Won't do.** `wakeUp()` stays best-effort on spec 9 runs, as [`run.wakeUp()` and `waitForSleep()`](#runwakeup-and-waitforsleep) describes. A sleep that has to end reliably while the run is active can race a hook instead.
3976
+
3977
+ Before: `wakeUp()` names the sleeps to complete on a keyed orchestrator message, so one that is folded into a running or lingering delivery is dropped while `stoppedCount` still counts it. This release keeps it best-effort (see [Known limitations](#known-limitations)). The thorough fix is an out-of-band "wake requested" event, written like `hook_received` and turned into an in-band `wait_completed` by the orchestrator, so a coalesced wake loses nothing. It needs a new event type and world-vercel backend support. A confirm-and-resend loop was rejected. [4365355511](https://github.com/vercel/workflow/pull/4661#discussion_r4365355511).
3876
3978
 
3877
3979
  ### 2. Hook-linger policy
3878
3980
 
3879
- Any open, undisposed hook makes every spec 9 pass linger for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS`, even right after arming a long timer, so a run with a long-lived approval or cancel hook beside a polling `sleep()` holds a function for the window on every wake (documented in `runtime-tuning.mdx`). Before default-on, linger on hooks only while a burst is plausible: a `hook_received` within one linger window, or one handled by this delivery. Background steps keep the full linger. Optionally a separate `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`. It also shrinks the window in which `wakeUp()` is dropped. [4365355574](https://github.com/vercel/workflow/pull/4661#discussion_r4365355574).
3981
+ **Done.** A run that waits only on open hooks now lingers for `WORKFLOW_ORCHESTRATOR_HOOK_LINGER_MS`, 5 seconds by default and never more than `WORKFLOW_ORCHESTRATOR_LINGER_MS`, instead of the full 30-second window. A run with a background step or an inline step's retry still open keeps the full linger, on both engines (`externalWorkOf` in `spec9/log-state.ts`, `getOrchestratorLingerMsFor` in `spec9/live-feed.ts`). Each payload still starts the window again, so a burst of resumes stays on one warm invocation, while a long-lived approval or cancel hook beside a polling `sleep()` costs up to 5 seconds per wake instead of 30, and the window in which `wakeUp()` is dropped shrinks with it. The burst-aware policy (linger on hooks only after a recent `hook_received`) was not needed for that and is not implemented. Tests: `spec9/orchestrator-linger.runtime.test.ts` and `spec9/small-rules.test.ts`.
3982
+
3983
+ Before: any open, undisposed hook made every spec 9 pass linger for up to `WORKFLOW_ORCHESTRATOR_LINGER_MS`, even right after arming a long timer, so a run with a long-lived approval or cancel hook beside a polling `sleep()` held a function for the whole window on every wake. [4365355574](https://github.com/vercel/workflow/pull/4661#discussion_r4365355574).
3880
3984
 
3881
3985
  ### 3. Back off the no-push tail poll
3882
3986
 
3883
- On a World without `events.subscribe` (world-local, world-postgres), and on world-vercel after feed trouble, the orchestrator's tail poll runs at a flat `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS` (2 s) for the whole of every inline body; it never backs off. Before default-on, back off empty polls to about 10 s, and reset on a poll that delivered events, a failed poll, feed trouble or a write by this delivery. Trade-off: on world-local and world-postgres a background outcome reaches a running delivery up to the cap later; no event is lost. The main concern is Postgres read load for self-hosters who opt in. [4365355575](https://github.com/vercel/workflow/pull/4661#discussion_r4365355575).
3987
+ **Done** (#5275). While no live push covers the run, each poll that finds nothing doubles the interval from `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS` up to 10 seconds (`ORCHESTRATOR_POLL_MAX_INTERVAL_MS` in `packages/core/src/runtime/spec9/live-feed.ts`, a constant, never below the configured interval). A poll that delivers an event, a failed poll, feed trouble (`onError`, or a pushed event that skips a position), or a write the delivery commits itself puts it back at the configured interval at once. The delivery's own writes reach the feed through `InBandWriter.addCommitListener`, which calls `LiveLogFeed.noteActivity` on both engines; it does nothing while the push is live. It applies on world-local, on world-postgres while its feed is down or was refused, and on world-vercel after feed trouble. A 10-minute inline body without a feed costs about 65 polls instead of 300, and an outcome another writer commits during a quiet stretch reaches the delivery up to 10 seconds later. Tests: `spec9/live-feed.test.ts`.
3988
+
3989
+ Before: on a World without `events.subscribe` (world-local, world-postgres), and on world-vercel after feed trouble, the orchestrator's tail poll runs at a flat `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS` (2 s) for the whole of every inline body; it never backs off. Before default-on, back off empty polls to about 10 s, and reset on a poll that delivered events, a failed poll, feed trouble or a write by this delivery. Trade-off: on world-local and world-postgres a background outcome reaches a running delivery up to the cap later; no event is lost. The main concern is Postgres read load for self-hosters who opt in. [4365355575](https://github.com/vercel/workflow/pull/4661#discussion_r4365355575).
3884
3990
 
3885
3991
  ### 4. `events.subscribe` for world-postgres via LISTEN/NOTIFY
3886
3992
 
3887
- world-postgres has no live event feed, so a spec 9 delivery there never lingers and picks up other writers' events only through the tail poll. Implementing `events.subscribe` with Postgres LISTEN/NOTIFY (notify per appended event, slot order, `onError` on a dropped connection) gives it warm handling of bursts and removes most polling. Before default-on. [4365355575](https://github.com/vercel/workflow/pull/4661#discussion_r4365355575).
3993
+ **Done** (#5275). After an event write whose `specVersion` is 9 or above commits, the writer sends `pg_notify('workflow_run_events', runId)` outside the write's transaction, without awaiting it. One `LISTEN` connection per process serves every subscription. On each announcement of its run a subscription reads the log after the last slot it delivered and delivers what continues the slot sequence, each slot once, stopping at a hole until a later announcement fills it. A dropped `LISTEN` connection, or a failed read, ends the subscriptions it affects through `onError`. At most half of a process's `queueConcurrency` subscriptions are live at once, since a delivery lingering on its feed holds a Graphile worker slot; a subscription past that is refused, and its delivery polls instead of lingering. Spec 9 deliveries on world-postgres now linger (30 seconds on a background step, 5 seconds on hooks alone). The feed ends at a `resumeHook()` resume rather than delivering it, so the resume's wake consumes it with its timing and hook-resume latency is still measured. See [world-postgres over LISTEN/NOTIFY](#world-postgres-over-listennotify). Tests: `world-postgres/test/run-events-feed.test.ts` and `spec9-run-feed.test.ts`, against Docker Postgres.
3994
+
3995
+ Before: world-postgres had no live event feed, so a spec 9 delivery there never lingers and picks up other writers' events only through the tail poll. Implementing `events.subscribe` with Postgres LISTEN/NOTIFY (notify per appended event, slot order, `onError` on a dropped connection) gives it warm handling of bursts and removes most polling. Before default-on. [4365355575](https://github.com/vercel/workflow/pull/4661#discussion_r4365355575).
3888
3996
 
3889
3997
  ### 5. world-postgres stale named-queue lock after a hard kill
3890
3998
 
3891
- Every spec 9 orchestrator delivery on world-postgres goes through a Graphile named queue. A worker killed mid-job leaves the queue row locked until Graphile's `resetLockedAt` clears locks older than 4 hours, so the run stalls for up to 4 hours (documented in the README, `4ed4f074ca`). [#4759](https://github.com/vercel/workflow/pull/4759) adds the mechanism, opt-in: with `jobLockStaleSeconds` (`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`) set, a running delivery renews its job lock and its named queue's, and another process releases both once they go unrenewed for that window. It is off by default because of rolling upgrades, so by default a hard-killed spec 9 run on world-postgres can still stall for up to 4 hours. Default the stale window on for spec 9 runs before spec 9 is default-on on world-postgres. It is not defaulted on here, for three reasons. The sweep is per process and scoped by task identifier, and a spec 9 run's orchestrator jobs share the `workflow_flows` task with spec 8's, so a spec-9-only default needs a sweep scoped to the per-run named queues. The rolling-upgrade hazard applies to spec 9 jobs too: an earlier-version process sharing the database claims them, does not renew, and completes them unfenced, so releasing one of its long deliveries lets its completion delete the redelivery's row. And a window short enough to matter turns an event-loop stall longer than it into a second owner of a running inline step, which the fence keeps off the log but not off the step body. Turn it on once every supported version renews (or the sweep can tell renewing holders apart), scoped to the named queues, with a window well above an inline step's longest synchronous stretch, and add a Docker Postgres test that a SIGKILLed worker's spec 9 run gets a later wake within the window while a live slow delivery that renews is not released. [4365355604](https://github.com/vercel/workflow/pull/4661#discussion_r4365355604).
3999
+ **Done.** The stale window is on by default for spec 9 named queues. With `jobLockStaleSeconds` unset, every delivery renews its job lock and its named queue's. Its worker registers as renewing in `workflow.workflow_job_lock_holders` (migration 0030) before the delivery runs, and every process releases the jobs of this World's per-run named queues (`<prefix>flows:<runId>:executor`) whose holder registered and whose lock went unrenewed for 300 seconds (`resolveJobLeasePolicy`, `namedQueueSweepSql` in `packages/world-postgres/src/job-lease.ts`). The three reasons it was off are handled:
4000
+
4001
+ - **Scope.** The default sweep is scoped to the per-run named queues, not the `workflow_flows` task that spec 8 shares.
4002
+ - **Rolling upgrades.** A 5.1.0 process on its default neither renews nor registers, so its jobs are never released under it, and its unfenced completion cannot delete a redelivery's row.
4003
+ - **Window.** 300 seconds is well above an inline step's longest synchronous stretch.
4004
+
4005
+ An explicit `jobLockStaleSeconds` above `0` keeps releasing every job of the World, and `0` turns renewal off. Without the migration, deliveries still run and renew, nothing registers, and nothing is released; a warning names the migration. Tests: `test/queue-lease-default.test.ts` (Docker Postgres) shows a SIGKILLed worker's spec 9 run redelivered within the window, a live slow delivery that renews not released, and neither an unregistered holder's spec 9 job nor a registered holder's job outside the named queues released.
4006
+
4007
+ Before: every spec 9 orchestrator delivery on world-postgres goes through a Graphile named queue. A worker killed mid-job leaves the queue row locked until Graphile's `resetLockedAt` clears locks older than 4 hours, so the run stalls for up to 4 hours (documented in the README, `4ed4f074ca`). [#4759](https://github.com/vercel/workflow/pull/4759) adds the mechanism, opt-in: with `jobLockStaleSeconds` (`WORKFLOW_POSTGRES_JOB_LOCK_STALE_SECONDS`) set, a running delivery renews its job lock and its named queue's, and another process releases both once they go unrenewed for that window. It is off by default because of rolling upgrades, so by default a hard-killed spec 9 run on world-postgres can still stall for up to 4 hours. Default the stale window on for spec 9 runs before spec 9 is default-on on world-postgres. It is not defaulted on here, for three reasons. The sweep is per process and scoped by task identifier, and a spec 9 run's orchestrator jobs share the `workflow_flows` task with spec 8's, so a spec-9-only default needs a sweep scoped to the per-run named queues. The rolling-upgrade hazard applies to spec 9 jobs too: an earlier-version process sharing the database claims them, does not renew, and completes them unfenced, so releasing one of its long deliveries lets its completion delete the redelivery's row. And a window short enough to matter turns an event-loop stall longer than it into a second owner of a running inline step, which the fence keeps off the log but not off the step body. Turn it on once every supported version renews (or the sweep can tell renewing holders apart), scoped to the named queues, with a window well above an inline step's longest synchronous stretch, and add a Docker Postgres test that a SIGKILLed worker's spec 9 run gets a later wake within the window while a live slow delivery that renews is not released. [4365355604](https://github.com/vercel/workflow/pull/4661#discussion_r4365355604).
3892
4008
 
3893
4009
  ### 6. Incremental log state in the node engine
3894
4010
 
3895
- Each in-band write rescans the whole log (`maxEventSlot`, `appendUniqueEvents`, a full sort in `mergeReportedEvents`, `findEventSlotGap`), so CPU per step grows with log length, about O(n) per write and O(n²) per delivery. The duplicate `slotSnapshot()` is gone (`b489e7561b`). Before default-on: a running max slot, an id `Set` owned by the log and a dense-prefix watermark, reset on full load and repair, plus a ms-per-step benchmark at 250 against 2000 steps. Spec 8 has the same linear shape at a smaller constant. [4365355561](https://github.com/vercel/workflow/pull/4661#discussion_r4365355561).
4011
+ **Done.** The node engine keeps an `EventLogIndex` (`spec9/log-index.ts`) beside its loaded log: the id `Set`, a running max slot and a dense-prefix watermark. It is updated as events are merged and built again when the log is replaced (a full load, a gap settle) or changed outside it (a run-ahead repair removing speculative events). A write's slot snapshot, `absorbWrite`, the incremental read, the live feed's merge and `consumeOwnResolvingWrite` now read and merge through it. A merge appends events above the tail, inserts a few below it in place, and sorts only a large out-of-order batch. The per-pass hole check answers from the watermark and runs `settleEventSlotGap` only when the log has a hole. A slot snapshot taken while run-ahead holds speculative events walks down past them from the tail instead of filtering the whole log.
4012
+
4013
+ Measured with `spec9/log-growth.bench.runtime.test.ts` (opt-in, `WORKFLOW_LOG_GROWTH_BENCH=1`): one delivery of sequential inline steps on the in-memory World, two runs each on a devbox. Most of a step's time there is the in-memory World's own work, so the totals overstate the runtime's share.
4014
+
4015
+ | Steps | ms per step, before | ms per step, after |
4016
+ |---:|---:|---:|
4017
+ | 250 | 9.9 to 10.3 | 9.8 |
4018
+ | 2000 | 18.0 to 18.7 | 11.8 to 12.4 |
4019
+ | 2000 / 250 | 1.82 | 1.20 to 1.26 |
4020
+
4021
+ What still grows with the log is per pass, not per write: `analyzeLogSteps`, `openWaits`, `dueWaits` and the terminal-event check each read the replayed log once or twice a pass. In the 2000-step profile they were about 2 s of 13 s of busy CPU, against about 11 s for the per-write scans before. Spec 8 keeps its linear shape at a smaller constant.
4022
+
4023
+ Before: each in-band write rescanned the whole log (`maxEventSlot`, `appendUniqueEvents`, a full sort in `mergeReportedEvents`, `findEventSlotGap`), so CPU per step grew with log length, about O(n) per write and O(n²) per delivery. [4365355561](https://github.com/vercel/workflow/pull/4661#discussion_r4365355561).
3896
4024
 
3897
4025
  ### 7. Monitor full-log reads on background step retry hops and redeliveries
3898
4026
 
3899
- Every non-first delivery of a background step's message, each retry hop included, reads the run's whole log to decide, so N retrying steps cost O(N x log length) reads, and a long `retryAfter` pays one full read per 900-second hop on world-vercel. A per-step read is not a cheaper replacement, because it is also an event-log read on the same backend. Performance looks acceptable so far, so this is a post-release monitoring item: watch read volume and latency for runs with many retrying background steps, and revisit if it shows up. [4365355492](https://github.com/vercel/workflow/pull/4661#discussion_r4365355492).
4027
+ **Done.** A delivery of a background step's message that may be a retry's early redelivery (counted above 1, or the first delivery of an inline step's retry moved to the background) first reads only the step's latest event: `events.listByCorrelationId` with the run id, newest first, limit 1, `resolveData: 'none'` (`readPendingRetry` in `spec9/step-handler.ts`). While that event is a `step_retrying` whose `retryAfter` is still ahead, the delivery asks for a redelivery after the rest without reading the whole log (`pendingRetryDecision`, `spec9/step-delivery.ts`). Anything else, a failed read included, takes the full read as before. A `retryAfter: '1d'` step on world-vercel now costs one small read per 900-second hop instead of one full log read.
4028
+
4029
+ Deferring is the only decision the short read makes, so a stale or eventually consistent read is safe. While the latest `step_retrying` names a time still ahead, nothing newer can exist for the step, because only a delivery of this message writes the step's next start, after a full read past `retryAfter`. An older `step_retrying` always names a time already past. A terminal run or step the read missed only delays the acknowledgement to `retryAfter`. Past the delivery cap, the full read would not fail the step either, since a pending `retryAfter` counts as activity. Each delivery's span records what it read (`step.delivery.log_read`: `none`, `step_tail` or `full_log`), which is what to watch from here.
4030
+
4031
+ On world-vercel the backend serves that read by scanning the run's partition from the tail with a correlation filter and no payloads, so it stops at the step's latest event; for a step waiting out its retry that is near the tail.
4032
+
4033
+ Before: Every non-first delivery of a background step's message, each retry hop included, reads the run's whole log to decide, so N retrying steps cost O(N x log length) reads, and a long `retryAfter` pays one full read per 900-second hop on world-vercel. A per-step read is not a cheaper replacement, because it is also an event-log read on the same backend. Performance looks acceptable so far, so this is a post-release monitoring item: watch read volume and latency for runs with many retrying background steps, and revisit if it shows up. [4365355492](https://github.com/vercel/workflow/pull/4661#discussion_r4365355492).
3900
4034
 
3901
4035
  ### 8. Not coalescing speculative creations under run-ahead (measure first)
3902
4036
 
@@ -3904,22 +4038,28 @@ The run-ahead hazard check runs on a write that has already committed, and coale
3904
4038
 
3905
4039
  ### 9. world-local and world-postgres: resolve an unstamped message's spec from the run row
3906
4040
 
3907
- Both Worlds gate and key a spec 9 run's orchestrator messages by the spec stamp on the message. A message from a producer that does not stamp it (an older SDK's `resumeHook()` or `cancel()`) skips the run gate and runs next to the live delivery, where the fence keeps it safe at the cost of an overlapping invocation. Before default-on, the Worlds read the run's spec from their own run row before gating an unstamped orchestrator message. [4365355540](https://github.com/vercel/workflow/pull/4661#discussion_r4365355540).
4041
+ **Done on world-postgres** (#5275). When a worker takes an orchestrator message without a spec stamp, it reads the run's `spec_version`, and for a spec 9 run adds the message again, stamped with that version, on the run's named queue, carrying its attempt and delivery counts, and completes the original job without delivering it. A spec 8 run, a run that is not found, or a failed read leaves it delivered as before. See [An unstamped message](#an-unstamped-message). Still open on world-local, whose handler gate (#5145) also keys on the stamp.
4042
+
4043
+ Before: both Worlds gate and key a spec 9 run's orchestrator messages by the spec stamp on the message. A message from a producer that does not stamp it (an older SDK's `resumeHook()` or `cancel()`) skips the run gate and runs next to the live delivery, where the fence keeps it safe at the cost of an overlapping invocation. Before default-on, the Worlds read the run's spec from their own run row before gating an unstamped orchestrator message. [4365355540](https://github.com/vercel/workflow/pull/4661#discussion_r4365355540).
3908
4044
 
3909
4045
  ### 10. Orchestrator-message coalescing in world-local and world-postgres
3910
4046
 
3911
- Neither World coalesces a run's orchestrator messages, so every background completion's wake is its own delivery behind the run's gate (a 97-step fan-out gets 97 deliveries), and a handoff goes behind waiting wakes. Coalescing needs re-runs under the held gate with the coalesced count, the same `attempt` and the first run's `invocationStartedAt`, a re-run cap with handoff, and a handoff that goes to the front of the run's queue (see [world-local and world-postgres do not coalesce](#world-local-and-world-postgres-do-not-coalesce)).
4047
+ **Done on world-postgres** (#5275). When a spec 9 orchestrator delivery acknowledges, its worker deletes the run's orchestrator messages waiting behind it on the named queue (due, unlocked, not a start message carrying `runInput`) with Graphile's `complete_jobs`, and runs the handler again with `deliveryCount + rerun`, the same `attempt` and the same `invocationStartedAt`, while it finds any, up to 32 times. Past the cap the remaining messages are delivered as usual, so no handoff is needed. A handoff's job gets priority `-1`, ahead of the waiting messages. See [world-local and world-postgres](#world-local-and-world-postgres). Still open on world-local.
4048
+
4049
+ Before: neither World coalesced a run's orchestrator messages, so every background completion's wake is its own delivery behind the run's gate (a 97-step fan-out gets 97 deliveries), and a handoff goes behind waiting wakes. Coalescing needs re-runs under the held gate with the coalesced count, the same `attempt` and the first run's `invocationStartedAt`, a re-run cap with handoff, and a handoff that goes to the front of the run's queue (see [world-local does not coalesce](#world-local-does-not-coalesce)).
3912
4050
 
3913
4051
  ### 11. Smaller deferred work
3914
4052
 
3915
- - A spec 8 conformance suite for world-postgres, as world-local has.
4053
+ - **Done** (#5275): a spec 8 conformance suite for world-postgres, as world-local has. The shared world-testing suite (`createTestSuite`) runs against world-postgres pinned to spec 8 (`test/spec.test.ts`) and to spec 9 (`test/spec9.test.ts`), and `test/spec8-step-dedupe.test.ts` checks that a spec 8 step message sent again while its job runs adds no second job (see [How world-postgres deduplicates a spec 9 run's keyed sends](#how-world-postgres-deduplicates-a-spec-9-runs-keyed-sends)).
3916
4054
  - Further sharing of the spec 8 and spec 9 delivery bodies and step executors, once spec 8 is on its way out.
3917
4055
  - world-vercel under `WORKFLOW_SEQUENTIAL_REPLAYS=1` has the same uncoalesced shape as entry 12: spec 9 messages go unkeyed on per-run topics, one invocation per wake.
3918
4056
  - A step message whose deliveries throw before the delivery cap check (in `resolveRunIdentity`, `guardDeployment`, the log read, or the fail path's encryption key fetch) is redelivered with no bound until the World gives up on it. Bounding it needs those reads moved behind the cap check or their failures caught into the stall path, which needs the run and the log the stall check reads.
3919
4057
 
3920
4058
  ### 12. world-postgres: count a fence-refusal redelivery toward the delivery cap
3921
4059
 
3922
- On world-postgres a `{ timeoutSeconds: n > 0 }` reschedule starts `attempt` over, so a run whose every pass the fence refuses never reaches `WORKFLOW_MAX_QUEUE_DELIVERIES` there; it is only logged at warn. Count a spec 9 orchestrator reschedule as an attempt, or have the runtime count refusals itself. A re-send of an unstarted step no longer mutates its live Graphile job (`ab3713146b`, `unsafe_dedupe`).
4060
+ **Done** (#5275). A spec 9 orchestrator message's `{ timeoutSeconds: n > 0 }` reschedule (a fence refusal's redelivery, a run deferred for load) carries `attempt` over (`attemptOffset: attempt`), so a run refused on every pass reaches `MAX_DELIVERIES_EXCEEDED`. A step message's retry in place still starts `attempt` over. Tests: `world-postgres/test/queue-spec9-delivery.test.ts`.
4061
+
4062
+ Before: on world-postgres a `{ timeoutSeconds: n > 0 }` reschedule starts `attempt` over, so a run whose every pass the fence refuses never reaches `WORKFLOW_MAX_QUEUE_DELIVERIES` there; it is only logged at warn. Count a spec 9 orchestrator reschedule as an attempt, or have the runtime count refusals itself. A re-send of an unstarted step no longer mutates its live Graphile job (`ab3713146b`, `unsafe_dedupe`).
3923
4063
 
3924
4064
  ### 13. A required host contract for the spec 9 QuickJS orchestrator
3925
4065
 
@@ -3931,11 +4071,19 @@ Both engines implement owned-chain filtering, pre-completion sends, near-due key
3931
4071
 
3932
4072
  ### 15. QuickJS: hand off at the invocation deadline
3933
4073
 
3934
- The QuickJS orchestrator does not hand off when an inline step runs past the invocation deadline, and it starts the next inline step after it: the adapter contract test sees both of a run's slow inline steps run in one delivery that the node engine hands off after the first. On world-vercel such a delivery can run into the function's maximum duration. Apply the node engine's deadline check and inline-start margin to the QuickJS loop.
4074
+ **Done.** The QuickJS loop applies the node engine's deadline check and inline-start margin. A turn that begins at or past the invocation's inline deadline starts nothing more, lets the bodies still running settle, and continues the run in the next delivery through `continueInNextDelivery` (a handoff on the same message, not an attempt). Within `WORKFLOW_INLINE_STEP_DEADLINE_MARGIN_MS` of the deadline, new steps are created as background steps. The QuickJS loop also caps its linger at the deadline minus the margin, as before. `runWorkflowWithQuickJS` takes `inlineDeadlineMs` (the invocation's start plus its inline window) in place of `lingerDeadlineMs`. An inline step an earlier delivery left open still runs once per delivery inside the margin on QuickJS; the node engine leaves it unstarted there. Tests: `spec9/world-vercel-queue.contract.test.ts` now runs its deadline handoff and near-expiry continuation cases on both engines, plus a step created inside the margin running from its own message.
4075
+
4076
+ Before: the QuickJS orchestrator did not hand off when an inline step ran past the invocation deadline, and it started the next inline step after it, so on world-vercel such a delivery could run into the function's maximum duration.
3935
4077
 
3936
4078
  ### 16. Live-feed heartbeat and client watchdog
3937
4079
 
3938
- The client's tail poll (10 s backing off to 20 s while the push is live) is the only backstop for a world-vercel feed that stops pushing while the client still sees it as live: a feed stuck before its first timed read, a feed loop that throws without an `end` notice, the drain window, a half-open socket during a linger, and a replacement subscription that skips slots. Before default-on, have the backend feed send a heartbeat frame while idle, carrying the highest slot it has read through, and add a client watchdog: a missing heartbeat fails the feed, a heartbeat slot above what the client holds triggers a poll, and a heartbeat for another subscription is feed trouble. Use a new frame type, since a `run_event` with no event fails today's client feed. Then lengthen the live poll to 60 s or more, or keep it only as the 2 s fallback after trouble. See [Live event feed](#follow-ups).
4080
+ **Done.** The backend feed sends a `run_heartbeat` frame, a new frame type, to a client that lists the `run-heartbeat` upgrade flag. It goes out after a successful read once the feed has sent nothing for 10 seconds, and carries the highest slot it has pushed. The backend confirms this on each `subscribe_ack` (`heartbeatMs`). world-vercel then watches the feed: 30 seconds of silence fails it, a heartbeat slot above what the client holds makes world-vercel read the missing events from the log and deliver them itself, and a heartbeat for another subscription is feed trouble. See [Heartbeats](#heartbeats).
4081
+
4082
+ The `subscribe` contract is unchanged (`onEvent`, `onError`), so the runtime keeps its live poll at 10 to 20 seconds. Lengthening it would need the runtime to know the feed is watched, which no World reports today.
4083
+
4084
+ A client that does not list the flag gets no heartbeats, because an older client fails its connection on an unknown frame type. A client talking to a backend that predates heartbeats gets an ack without `heartbeatMs` and arms nothing.
4085
+
4086
+ Before: The client's tail poll (10 s backing off to 20 s while the push is live) is the only backstop for a world-vercel feed that stops pushing while the client still sees it as live: a feed stuck before its first timed read, a feed loop that throws without an `end` notice, the drain window, a half-open socket during a linger, and a replacement subscription that skips slots. Before default-on, have the backend feed send a heartbeat frame while idle, carrying the highest slot it has read through, and add a client watchdog: a missing heartbeat fails the feed, a heartbeat slot above what the client holds triggers a poll, and a heartbeat for another subscription is feed trouble. Use a new frame type, since a `run_event` with no event fails today's client feed. Then lengthen the live poll to 60 s or more, or keep it only as the 2 s fallback after trouble. See [Live event feed](#follow-ups).
3939
4087
 
3940
4088
  ### 17. Live-feed fixes in world-vercel: bounded subscribe wait and end notices
3941
4089
 
@@ -3994,7 +4142,7 @@ What the numbers show:
3994
4142
  - **TTLS** is below `main` at every width, by about 6x at 256 branches and 8x at 1024. The 64-branch regression is gone.
3995
4143
  - **First branch** is 200 to 600 ms behind `main` from 64 branches up. Two causes, from the run timelines:
3996
4144
  - The inline bodies waited for the dispatch, about 85 to 135 ms of it, which `670ea7bdfe` removes. Estimated first branch after it: about 590 ms at 64 branches. Not re-measured.
3997
- - The rest is the single 64-event first creation batch. world-vercel's commit time grows with the batch size, about 5 to 6 ms per event: 60 to 100 ms for 16 events and 300 to 420 ms for 64. The inline starts ride that batch, so the inline bodies wait for the whole fan-out's creations. `main` commits about 13 events per chunk in parallel and starts its inline steps after the first.
4145
+ - The rest is the single 64-event first creation batch. world-vercel's commit time grows with the batch size, about 5 to 6 ms per event: 60 to 100 ms for 16 events and 300 to 420 ms for 64. The inline starts ride that batch, so the inline bodies wait for the whole fan-out's creations. `main` commits about 13 events per chunk in parallel and starts its inline steps after the first. Since then, a fan-out on a run's first delivery starts its inline bodies while the batch commits ([Turbo](#turbo)), so its first branch no longer waits for it; later deliveries still do.
3998
4146
  - **Join at 1024 branches** regressed: p50 84.5 s against 2.8 s. In half of the runs every branch started within 13 s and the join took 80 to 105 s; in the others, late branch starts took the same time out of the join instead, so E2E is close to `main` (p50 113 s against 96 s).
3999
4147
  - **Cause.** In a clean run, every outcome had committed 18 s after the start, and the orchestrator held every event 25 s in, through the live feed and tail polls. It stayed in its one invocation, CPU-bound, until it continued past the join 100 s in: polls scheduled every 2 s fired every 5 to 6 s, and a lease renewal took 5.8 s on the client. Every step still pending when the event walk reaches the end of the log signals a suspension, and each signal started its own idle poll (`scheduleWhenIdle`), which polled until the run went idle. Spec 9 resumes its retained session once per batch of incoming outcomes, a new suspension generation each time, so polls piled up as generations times pending steps, and those of past generations kept polling. Spec 8 replays once per wake and never stacks generations. The code is the same on both.
4000
4148
  - **Measured locally** on the in-memory World, node engine, all steps in the background: timers set per run grew with about the cube of the width (1.1 k at 32 branches, 8.5 k at 64, 104 k at 128, 1.1 M at 256, 92 M at 1024), and the join after the last outcome took 14 to 25 s at 1024.
@@ -4007,7 +4155,7 @@ Cold world-vercel backend instances behind the step invocations' events WebSocke
4007
4155
 
4008
4156
  Not done yet, in order of expected gain:
4009
4157
 
4010
- - **A small first creation batch.** The inline starts and about 16 creations first, so the inline bodies and the first background steps start after a 60 to 100 ms commit instead of a 300 to 420 ms one. Estimated 200 to 320 ms off the first branch from 64 branches up. Partly reverts `5b53481478`; the reason not to do it before, that a 64-wide fan-out would gain nothing at one 64-event batch, does not hold once the commit cost is per event. Each later batch's steps already go out as it commits (`8a79811aa6`), so the early branches' out-of-band writes already land while later creation batches commit. They do not move the in-band fence, and the orchestrator wakes they send are the same count as before, earlier; their cost on world-vercel's per-run sequence item is not measured.
4158
+ - **A small first creation batch.** The inline starts and about 16 creations first, so the inline bodies and the first background steps start after a 60 to 100 ms commit instead of a 300 to 420 ms one. Estimated 200 to 320 ms off the first branch from 64 branches up. Partly reverts `5b53481478`; the reason not to do it before, that a 64-wide fan-out would gain nothing at one 64-event batch, does not hold once the commit cost is per event. Each later batch's steps already go out as it commits (`8a79811aa6`), so the early branches' out-of-band writes already land while later creation batches commit. They do not move the in-band fence, and the orchestrator wakes they send are the same count as before, earlier; their cost on world-vercel's per-run sequence item is not measured. A run's first delivery no longer waits on this batch for its inline bodies (see [Turbo](#turbo)); a smaller batch would still start the first background steps sooner.
4011
4159
  - **A lower per-event commit cost in world-vercel**, which would help every width.
4012
4160
 
4013
4161
  ### Handoffs verified on Vercel