@workflow/core 5.3.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/classify-error.d.ts +1 -1
- package/dist/classify-error.js +4 -4
- package/dist/create-hook.d.ts +15 -0
- package/dist/create-hook.d.ts.map +1 -1
- package/dist/create-hook.js +1 -1
- package/dist/events-consumer.d.ts +1 -1
- package/dist/events-consumer.js +1 -1
- package/dist/flushable-stream.js +11 -2
- package/dist/private.d.ts +2 -2
- package/dist/private.d.ts.map +1 -1
- package/dist/private.js +11 -49
- package/dist/replay-payload-cache.d.ts +3 -0
- package/dist/replay-payload-cache.d.ts.map +1 -1
- package/dist/replay-payload-cache.js +4 -1
- package/dist/runtime/after-terminal-write.d.ts +33 -0
- package/dist/runtime/after-terminal-write.d.ts.map +1 -0
- package/dist/runtime/after-terminal-write.js +23 -0
- package/dist/runtime/child-run-completion-notify.d.ts +36 -0
- package/dist/runtime/child-run-completion-notify.d.ts.map +1 -0
- package/dist/runtime/child-run-completion-notify.js +97 -0
- package/dist/runtime/child-run-completion.d.ts +46 -0
- package/dist/runtime/child-run-completion.d.ts.map +1 -0
- package/dist/runtime/child-run-completion.js +264 -0
- package/dist/runtime/delivery.d.ts +5 -2
- package/dist/runtime/delivery.d.ts.map +1 -1
- package/dist/runtime/delivery.js +6 -4
- package/dist/runtime/deployment-guard.d.ts.map +1 -1
- package/dist/runtime/deployment-guard.js +3 -3
- package/dist/runtime/helpers.d.ts +13 -20
- package/dist/runtime/helpers.d.ts.map +1 -1
- package/dist/runtime/helpers.js +11 -21
- package/dist/runtime/invocations.d.ts +1 -1
- package/dist/runtime/out-of-band-observation.d.ts +29 -2
- package/dist/runtime/out-of-band-observation.d.ts.map +1 -1
- package/dist/runtime/out-of-band-observation.js +20 -2
- package/dist/runtime/queue-auth.d.ts +53 -0
- package/dist/runtime/queue-auth.d.ts.map +1 -0
- package/dist/runtime/queue-auth.js +149 -0
- package/dist/runtime/quickjs-log-view.d.ts +42 -0
- package/dist/runtime/quickjs-log-view.d.ts.map +1 -1
- package/dist/runtime/quickjs-log-view.js +90 -1
- package/dist/runtime/quickjs-runtime.d.ts +37 -2
- package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
- package/dist/runtime/quickjs-runtime.js +150 -178
- package/dist/runtime/quickjs-serde.js +2 -2
- package/dist/runtime/replay-budget.d.ts.map +1 -1
- package/dist/runtime/replay-budget.js +4 -4
- package/dist/runtime/resume-hook.d.ts +9 -1
- package/dist/runtime/resume-hook.d.ts.map +1 -1
- package/dist/runtime/resume-hook.js +29 -10
- package/dist/runtime/run.d.ts +28 -9
- package/dist/runtime/run.d.ts.map +1 -1
- package/dist/runtime/run.js +78 -23
- package/dist/runtime/runs.d.ts +3 -2
- package/dist/runtime/runs.d.ts.map +1 -1
- package/dist/runtime/runs.js +44 -27
- package/dist/runtime/spec8/constants.d.ts +1 -49
- package/dist/runtime/spec8/constants.d.ts.map +1 -1
- package/dist/runtime/spec8/constants.js +2 -65
- package/dist/runtime/spec8/delivery.d.ts.map +1 -1
- package/dist/runtime/spec8/delivery.js +35 -35
- package/dist/runtime/spec8/inline-steps-in-flight.d.ts +5 -5
- package/dist/runtime/spec8/inline-steps-in-flight.d.ts.map +1 -1
- package/dist/runtime/spec8/inline-steps-in-flight.js +6 -8
- package/dist/runtime/spec8/quickjs-entrypoint.d.ts.map +1 -1
- package/dist/runtime/spec8/quickjs-entrypoint.js +4 -4
- package/dist/runtime/spec8/step-executor.d.ts +8 -0
- package/dist/runtime/spec8/step-executor.d.ts.map +1 -1
- package/dist/runtime/spec8/step-executor.js +17 -3
- package/dist/runtime/spec8/step-single-flight.d.ts +1 -1
- package/dist/runtime/spec8/step-single-flight.js +2 -2
- package/dist/runtime/spec8/suspension-handler.d.ts +1 -1
- package/dist/runtime/spec8/suspension-handler.d.ts.map +1 -1
- package/dist/runtime/spec8/suspension-handler.js +6 -4
- package/dist/runtime/spec9/consume-after-commit.d.ts +5 -1
- package/dist/runtime/spec9/consume-after-commit.d.ts.map +1 -1
- package/dist/runtime/spec9/consume-after-commit.js +8 -3
- package/dist/runtime/spec9/delivery.d.ts.map +1 -1
- package/dist/runtime/spec9/delivery.js +269 -110
- package/dist/runtime/spec9/in-band-writer.d.ts +7 -0
- package/dist/runtime/spec9/in-band-writer.d.ts.map +1 -1
- package/dist/runtime/spec9/in-band-writer.js +18 -3
- package/dist/runtime/spec9/live-feed.d.ts +55 -9
- package/dist/runtime/spec9/live-feed.d.ts.map +1 -1
- package/dist/runtime/spec9/live-feed.js +90 -13
- package/dist/runtime/spec9/log-index.d.ts +74 -0
- package/dist/runtime/spec9/log-index.d.ts.map +1 -0
- package/dist/runtime/spec9/log-index.js +199 -0
- package/dist/runtime/spec9/log-state.d.ts +26 -8
- package/dist/runtime/spec9/log-state.d.ts.map +1 -1
- package/dist/runtime/spec9/log-state.js +42 -14
- package/dist/runtime/spec9/quickjs-entrypoint.d.ts +18 -5
- package/dist/runtime/spec9/quickjs-entrypoint.d.ts.map +1 -1
- package/dist/runtime/spec9/quickjs-entrypoint.js +823 -47
- package/dist/runtime/spec9/run-ahead.d.ts +11 -2
- package/dist/runtime/spec9/run-ahead.d.ts.map +1 -1
- package/dist/runtime/spec9/run-ahead.js +3 -2
- package/dist/runtime/spec9/step-delivery.d.ts +35 -0
- package/dist/runtime/spec9/step-delivery.d.ts.map +1 -1
- package/dist/runtime/spec9/step-delivery.js +47 -1
- package/dist/runtime/spec9/step-executor.d.ts +8 -0
- package/dist/runtime/spec9/step-executor.d.ts.map +1 -1
- package/dist/runtime/spec9/step-executor.js +17 -3
- package/dist/runtime/spec9/step-handler.d.ts.map +1 -1
- package/dist/runtime/spec9/step-handler.js +43 -4
- package/dist/runtime/start-hook-binding.d.ts +9 -8
- package/dist/runtime/start-hook-binding.d.ts.map +1 -1
- package/dist/runtime/start-hook-binding.js +13 -10
- package/dist/runtime/start-hook-delivery.d.ts +3 -3
- package/dist/runtime/start-hook-delivery.js +4 -4
- package/dist/runtime/start-hook-holder.d.ts +1 -1
- package/dist/runtime/start-hook-holder.js +2 -2
- package/dist/runtime/start.d.ts +7 -7
- package/dist/runtime/start.d.ts.map +1 -1
- package/dist/runtime/start.js +59 -24
- package/dist/runtime/step-latency.js +2 -2
- package/dist/runtime/world-compatibility.d.ts +4 -4
- package/dist/runtime/world-compatibility.js +5 -5
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +52 -17
- package/dist/serialization/codec-devalue.d.ts.map +1 -1
- package/dist/serialization/codec-devalue.js +26 -1
- package/dist/serialization/codec.d.ts +15 -0
- package/dist/serialization/codec.d.ts.map +1 -1
- package/dist/serialization/codec.js +1 -1
- package/dist/serialization/state-recovery.d.ts +21 -0
- package/dist/serialization/state-recovery.d.ts.map +1 -0
- package/dist/serialization/state-recovery.js +104 -0
- package/dist/serialization/state-refs.d.ts +229 -0
- package/dist/serialization/state-refs.d.ts.map +1 -0
- package/dist/serialization/state-refs.js +981 -0
- package/dist/serialization/step.d.ts.map +1 -1
- package/dist/serialization/step.js +22 -4
- package/dist/serialization/types.d.ts +1 -1
- package/dist/serialization/types.d.ts.map +1 -1
- package/dist/serialization/types.js +1 -1
- package/dist/serialization-format.d.ts +8 -15
- package/dist/serialization-format.d.ts.map +1 -1
- package/dist/serialization-format.js +41 -4
- package/dist/serialization.d.ts +5 -2
- package/dist/serialization.d.ts.map +1 -1
- package/dist/serialization.js +70 -8
- package/dist/state-resolver.d.ts +44 -0
- package/dist/state-resolver.d.ts.map +1 -0
- package/dist/state-resolver.js +40 -0
- package/dist/state.d.ts +56 -0
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +202 -0
- package/dist/step/get-step-metadata.d.ts +11 -0
- package/dist/step/get-step-metadata.d.ts.map +1 -1
- package/dist/step/get-step-metadata.js +1 -1
- package/dist/step.js +4 -4
- package/dist/telemetry/semantic-conventions.d.ts +18 -10
- package/dist/telemetry/semantic-conventions.d.ts.map +1 -1
- package/dist/telemetry/semantic-conventions.js +17 -11
- package/dist/telemetry.d.ts +12 -0
- package/dist/telemetry.d.ts.map +1 -1
- package/dist/telemetry.js +27 -1
- package/dist/test-support/append-only-world.d.ts +23 -2
- package/dist/test-support/append-only-world.d.ts.map +1 -1
- package/dist/test-support/append-only-world.js +34 -8
- package/dist/test-support/orchestrator-harness.d.ts +2 -0
- package/dist/test-support/orchestrator-harness.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +2 -2
- package/dist/workflow/abort-controller.d.ts.map +1 -1
- package/dist/workflow/abort-controller.js +3 -4
- package/dist/workflow/hook.d.ts +6 -0
- package/dist/workflow/hook.d.ts.map +1 -1
- package/dist/workflow/hook.js +26 -3
- package/dist/workflow.d.ts.map +1 -1
- package/dist/workflow.js +17 -122
- package/docs/api-reference/create-hook.mdx +3 -3
- package/docs/api-reference/create-webhook.mdx +1 -1
- package/docs/api-reference/fetch.mdx +1 -5
- package/docs/api-reference/get-step-metadata.mdx +19 -0
- package/docs/foundations/errors-and-retries.mdx +3 -1
- package/docs/foundations/hooks.mdx +1 -1
- package/docs/foundations/idempotency.mdx +11 -11
- package/docs/foundations/serialization.mdx +80 -0
- package/docs/foundations/starting-workflows.mdx +3 -7
- package/docs/how-it-works/event-sourcing.mdx +2 -2
- package/package.json +19 -18
|
@@ -180,7 +180,7 @@ On a conflict, the resolved value is a `Run` handle for the run that owns the to
|
|
|
180
180
|
|
|
181
181
|
Work started *beside* the awaiter, rather than after it, is not slowed down by it. In `await Promise.all([hook.getConflict(), prepare()])` the registration and the step are scheduled together: the runtime commits the registration, resolves the awaiter in the same invocation, and then runs `prepare()` there too, so the step does not pay an extra round trip through the queue for having been started next to a `getConflict()`.
|
|
182
182
|
|
|
183
|
-
This is a scheduling improvement, not an ordering guarantee. Only the steps the invocation runs inline start after the registration is recorded: the first [`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps) of them, less any inline steps the invocation is still running from an earlier part of the workflow
|
|
183
|
+
This is a scheduling improvement, not an ordering guarantee. Only the steps the invocation runs inline start after the registration is recorded: the first [`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps) of them, less any inline steps the invocation is still running from an earlier part of the workflow. A wider fan-out beside the awaiter has its remaining steps created and queued alongside the hook, exactly as described above, so they can start before the registration commits and can start even if it conflicts. When the ordering is what you need, await `hook.getConflict()` *before* calling the step.
|
|
184
184
|
|
|
185
185
|
<Callout type="info">
|
|
186
186
|
Custom hook tokens are the recommended way to coordinate active workflow runs. Use a deterministic token from your domain, such as an order ID or conversation ID, create the hook near the beginning of the workflow, and check `await hook.getConflict()` before work that depends on owning the token. See [Run idempotency](/docs/foundations/idempotency#run-idempotency).
|
|
@@ -188,7 +188,7 @@ Custom hook tokens are the recommended way to coordinate active workflow runs. U
|
|
|
188
188
|
|
|
189
189
|
### Open the run's start Hook
|
|
190
190
|
|
|
191
|
-
A run started with [`start(workflow, args, {
|
|
191
|
+
A run started with [`start(workflow, args, { experimental_hook: { token } })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token through its start Hook. Calling `createHook({ token })` with that token in the run returns a handle bound to the start Hook instead of registering a new one: it adds no step, `await hook.getConflict()` resolves `null`, and payloads resumed before the call are delivered in order. Set `metadata` and `experimental_minRetention` on `start({ experimental_hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to this `createHook()` throws. Open it with `const`: disposing the handle frees the token, as for any Hook, and a later `start()` with it is then admitted as a new run (see [Take care with the start Hook's lifecycle](/docs/api-reference/workflow-api/start#take-care-with-the-start-hooks-lifecycle)). See [Receive the payloads in the workflow](/docs/foundations/idempotency#receive-the-payloads-in-the-workflow).
|
|
192
192
|
|
|
193
193
|
### Keep a token unavailable after the run ends
|
|
194
194
|
|
|
@@ -266,7 +266,7 @@ With `experimental_force`, this run always ends up owning the token:
|
|
|
266
266
|
The takeover is durable. If either run's compute fails partway through, the next request for the token completes it, so the token never ends up held by nobody or by both runs. The previous owner's wake is durable too: if the new owner's compute fails between registering the Hook and waking the previous owner, the new owner's next invocation republishes the wake, whatever else the new owner has recorded since (a step it started alongside the Hook, for example). Every invocation of the new owner within 24 hours of the takeover republishes it under the same idempotency key, which collapses the repeats into one wake; a repeat that does get through only replays the previous owner, which finds nothing new.
|
|
267
267
|
|
|
268
268
|
<Callout type="info">
|
|
269
|
-
A token can only be taken from a run whose runtime understands being taken from. Runs started at a Workflow spec version below 8, which includes every run started by an older SDK release, a Python SDK run, or a deployment with `
|
|
269
|
+
A token can only be taken from a run whose runtime understands being taken from. Runs started at a Workflow spec version below 8, which includes every run started by an older SDK release, a Python SDK run, or a deployment with `WORKFLOW_SPEC_VERSION` set below 8, would never learn that their Hook was disposed. The World declines to take their token and the forced Hook rejects with the ordinary [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) instead, exactly as if `experimental_force` had not been set. Finished runs holding a retained token are taken over at any version.
|
|
270
270
|
</Callout>
|
|
271
271
|
|
|
272
272
|
`hook.getConflict()` on a forced Hook resolves with `null` once the takeover succeeds: the token is this run's by construction. If the World declines the takeover because the current owner predates spec version 8, `getConflict()` behaves as it does for an ordinary conflict and resolves with that owner's `Run`. Read `hook.claimedFrom` on the value returned by [`getHookByToken()`](/docs/api-reference/workflow-api/get-hook-by-token) to find out which run, if any, the token was taken from.
|
|
@@ -53,7 +53,7 @@ showSections={['returns']}
|
|
|
53
53
|
|
|
54
54
|
The returned `Webhook` object has:
|
|
55
55
|
|
|
56
|
-
- `url`: The HTTP endpoint URL that external systems can call
|
|
56
|
+
- `url`: The HTTP endpoint URL that external systems can call. On Vercel, it uses the deployment URL. Elsewhere, it's `http://localhost` on the `PORT` environment variable, or on the detected server port when `PORT` is unset
|
|
57
57
|
- `token`: The unique token identifying this webhook
|
|
58
58
|
- `getConflict()`: A promise that resolves with the conflicting run if another active hook already owns this token, or `null` once the webhook endpoint has been registered. The endpoint is registered alongside the steps the workflow starts at the same time, not ahead of them, so await `getConflict()` before a step that hands `url` to a caller who may request it right away. See [Registering a hook before a step uses it](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
|
|
59
59
|
- Implements `AsyncIterable<T>` for handling multiple requests, where `T` is `Request` (default) or `RequestWithResponse` (manual mode)
|
|
@@ -91,11 +91,7 @@ We call `fetch()` with a URL and optional request options, like the standard fet
|
|
|
91
91
|
|
|
92
92
|
This API lets you use `fetch` in a workflow. You can also implement a custom fetch for different error handling and retry logic.
|
|
93
93
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
Inside a workflow function, `response.json()`, `response.text()`, and `response.arrayBuffer()` each read the body through a step, so the result is recorded in the event log and replays deterministically.
|
|
97
|
-
|
|
98
|
-
`response.body` can also be read with `getReader()` or `for await`, which is how libraries such as the AI SDK read responses. The whole body is loaded through a single step and delivered as one chunk. The body is not marked as used after a read: each new reader or body method runs its own step, so read the body once and reuse the result. Incremental streaming APIs such as `pipeThrough()` and `tee()` are not available in workflow functions. To process a response as a stream, read it inside a step function.
|
|
94
|
+
Libraries that call `fetch` internally, like AI SDK calls, should be called from a step function. For agents, use AI SDK's [`WorkflowAgent`](https://ai-sdk.dev/v7/docs/agents/workflow-agent#workflowagent). See [`fetch-in-workflow`](/docs/errors/fetch-in-workflow).
|
|
99
95
|
|
|
100
96
|
### Customizing fetch behavior
|
|
101
97
|
|
|
@@ -61,6 +61,25 @@ async function chargeUser(userId: string, amount: number) {
|
|
|
61
61
|
<a href="/docs/foundations/idempotency">Idempotency</a> guide.
|
|
62
62
|
</Callout>
|
|
63
63
|
|
|
64
|
+
### Example: handle the last attempt differently
|
|
65
|
+
|
|
66
|
+
```typescript lineNumbers
|
|
67
|
+
import { getStepMetadata } from "workflow";
|
|
68
|
+
|
|
69
|
+
async function welcomeUser(userId: string) {
|
|
70
|
+
"use step";
|
|
71
|
+
const { attempt, maxAttempts } = getStepMetadata();
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
return await sendWelcomeEmail(userId);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (attempt < maxAttempts) throw error; // [!code highlight]
|
|
77
|
+
console.error(`Giving up on the welcome email for ${userId}`, error);
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
64
83
|
## API signature
|
|
65
84
|
|
|
66
85
|
### Parameters
|
|
@@ -136,7 +136,9 @@ callApi.maxRetries = 5; // Retry up to 5 times on failure (6 total attempts)
|
|
|
136
136
|
<Callout type="info">
|
|
137
137
|
Setting <code>maxRetries = 0</code> means the step will run once but will not
|
|
138
138
|
be retried on failure. The default is <code>maxRetries = 3</code>, meaning the
|
|
139
|
-
step can run up to 4 times total (1 initial attempt + 3 retries).
|
|
139
|
+
step can run up to 4 times total (1 initial attempt + 3 retries). Inside the
|
|
140
|
+
step, <code>getStepMetadata().maxAttempts</code> is that total, so a step can
|
|
141
|
+
<a href="/docs/api-reference/workflow/get-step-metadata#example-handle-the-last-attempt-differently">handle its last attempt differently</a>.
|
|
140
142
|
</Callout>
|
|
141
143
|
|
|
142
144
|
## Serialization failures
|
|
@@ -112,7 +112,7 @@ export async function orderWorkflow(orderId: string) {
|
|
|
112
112
|
}
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
-
Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies. A run started with [`start({
|
|
115
|
+
Calling `createHook()` on its own does not register the hook; registration is only committed when the workflow suspends. Awaiting `hook.getConflict()` suspends the workflow to commit the hook registration, then resolves with `null` once the hook is registered and ready to receive payloads, or with a `Run` handle for the run that owns the token (see [`HookConflictError`](/docs/errors/hook-conflict)). For `hook_conflict` events persisted by older worlds that did not record the owning run's ID, `getConflict()` rejects with `HookConflictError` instead of resolving with an incomplete handle. The conflicting run's accessors are durable steps, so the workflow can inspect `await conflict.status`, wait on `await conflict.returnValue`, or cancel the owner with `await conflict.cancel()`. See [Run idempotency](/docs/foundations/idempotency#run-idempotency) for these strategies. A run started with [`start({ experimental_hook })`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) already owns its token: `createHook({ token })` with that token binds to the run's start Hook, and `getConflict()` resolves `null` without suspending.
|
|
116
116
|
|
|
117
117
|
Awaiting the registration costs one write, not a round trip through the queue: the invocation that commits the registration is the one that carries on past the awaiter, and it runs the steps the workflow started beside the awaiter — as in `await Promise.all([hook.getConflict(), prepare()])` — in that same invocation, once the registration is recorded. That covers the steps the invocation runs inline; a fan-out wider than the free inline slots ([`WORKFLOW_MAX_INLINE_STEPS`](/docs/configuration/runtime-tuning#workflow_max_inline_steps), less any inline steps the invocation is still running) queues the rest alongside the hook, so await `hook.getConflict()` before the step when the ordering itself matters. See [`createHook()`](/docs/api-reference/workflow/create-hook#registering-a-hook-before-a-step-uses-it).
|
|
118
118
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Idempotency
|
|
3
|
-
description: Make step retries safe, and start a workflow run at most once per key with start({
|
|
3
|
+
description: Make step retries safe, and start a workflow run at most once per key with start({ experimental_hook }).
|
|
4
4
|
type: conceptual
|
|
5
5
|
summary: Use step IDs for retry-safe external calls, and pass a deterministic hook token to start() so a duplicate request is refused or routed to the run that owns it.
|
|
6
6
|
prerequisites:
|
|
@@ -71,7 +71,7 @@ export async function POST(request: Request) {
|
|
|
71
71
|
|
|
72
72
|
try {
|
|
73
73
|
const run = await start(processOrder, [orderId], {
|
|
74
|
-
|
|
74
|
+
experimental_hook: { token: `order:${orderId}` }, // [!code highlight]
|
|
75
75
|
});
|
|
76
76
|
return Response.json({ runId: run.runId, duplicate: false });
|
|
77
77
|
} catch (error) {
|
|
@@ -81,7 +81,7 @@ export async function POST(request: Request) {
|
|
|
81
81
|
}
|
|
82
82
|
```
|
|
83
83
|
|
|
84
|
-
`start({
|
|
84
|
+
`start({ experimental_hook })` admits the run and creates its **start Hook** in one atomic step. Exactly one run owns the token. A duplicate `start()` with the same token throws [`HookConflictError`](/docs/api-reference/workflow-errors/hook-conflict-error) with the owner's `conflictingRunId`. The duplicate never becomes a run, and none of its code runs.
|
|
85
85
|
|
|
86
86
|
### Start or route to the owner
|
|
87
87
|
|
|
@@ -99,7 +99,7 @@ export async function POST(request: Request) {
|
|
|
99
99
|
let owner: string | undefined;
|
|
100
100
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
101
101
|
try {
|
|
102
|
-
const run = await start(processOrder, [orderId, note], {
|
|
102
|
+
const run = await start(processOrder, [orderId, note], { experimental_hook: { token } });
|
|
103
103
|
return Response.json({ runId: run.runId, started: true });
|
|
104
104
|
} catch (error) {
|
|
105
105
|
if (!HookConflictError.is(error)) throw error;
|
|
@@ -152,7 +152,7 @@ export async function processOrder(orderId: string, note: string) {
|
|
|
152
152
|
- `createHook({ token })` with the run's start token returns a handle bound to the start Hook. It doesn't register a new Hook, so it adds no step, and `await hook.getConflict()` resolves `null`.
|
|
153
153
|
- Payloads resumed before the workflow opens the Hook are kept, and are delivered in order once it does.
|
|
154
154
|
- If the workflow never opens it, the token was only an idempotency key. The run completes normally, and unread payloads are simply left unread.
|
|
155
|
-
- `metadata` and `experimental_minRetention` belong on `start({
|
|
155
|
+
- `metadata` and `experimental_minRetention` belong on `start({ experimental_hook })`; a start Hook can't be a webhook or force-claim its token. Passing any of `metadata`, `experimental_minRetention`, `isWebhook` or `experimental_force` to this `createHook()` throws.
|
|
156
156
|
|
|
157
157
|
### Keep the token after the run ends
|
|
158
158
|
|
|
@@ -166,7 +166,7 @@ import { processOrder } from "./workflows/process-order";
|
|
|
166
166
|
declare const orderId: string; // @setup
|
|
167
167
|
|
|
168
168
|
const run = await start(processOrder, [orderId, ""], {
|
|
169
|
-
|
|
169
|
+
experimental_hook: {
|
|
170
170
|
token: `order:${orderId}`,
|
|
171
171
|
experimental_minRetention: "30 days", // [!code highlight]
|
|
172
172
|
metadata: { orderId },
|
|
@@ -222,17 +222,17 @@ Disposing the start Hook ends the run's idempotency: from the end of that block,
|
|
|
222
222
|
|
|
223
223
|
### When `start()` can't confirm the outcome
|
|
224
224
|
|
|
225
|
-
If `start({
|
|
225
|
+
If `start({ experimental_hook })` can't confirm whether its candidate run was queued or admitted, for example because the World timed out, it throws [`WorkflowStartError`](/docs/api-reference/workflow-errors/workflow-start-error) with the candidate's `runId`. The outcome is unknown, not failed. Retrying with the same token is safe: the retry either becomes the owner, or is refused with a `HookConflictError` naming the owner. Inside a workflow, the `start()` step retries it on its own.
|
|
226
226
|
|
|
227
227
|
### World support
|
|
228
228
|
|
|
229
|
-
`start({
|
|
229
|
+
`start({ experimental_hook })` requires a World that supports atomic start Hooks (`capabilities.atomicStartHook`), and Hook retention when you set `experimental_minRetention`. Otherwise `start()` throws before it enqueues anything.
|
|
230
230
|
|
|
231
231
|
| World | Support |
|
|
232
232
|
| --- | --- |
|
|
233
233
|
| [Local World](/worlds/local) | Supported. |
|
|
234
|
-
| [Postgres World](/worlds/postgres) |
|
|
235
|
-
| [Vercel World](/worlds/vercel) |
|
|
234
|
+
| [Postgres World](/worlds/postgres) | Supported, after applying migration `0028_add_start_hook_admissions`. Stop workers running a previous version first; see [Start Hooks](/worlds/postgres#start-hooks). |
|
|
235
|
+
| [Vercel World](/worlds/vercel) | Supported. |
|
|
236
236
|
|
|
237
237
|
See [`start()`](/docs/api-reference/workflow-api/start#prevent-duplicate-starts) for the full option reference.
|
|
238
238
|
|
|
@@ -278,7 +278,7 @@ export async function processOrder(orderId: string): Promise<OrderResult> {
|
|
|
278
278
|
Outside the workflow, try `resumeHook()` first, and on `HookNotFoundError` call `start()` and retry the resume until the new run registers its hook.
|
|
279
279
|
|
|
280
280
|
<Callout type="warn">
|
|
281
|
-
Unlike `start({
|
|
281
|
+
Unlike `start({ experimental_hook })`, this doesn't stop a duplicate from becoming a run. Two concurrent requests can both see "no hook yet" and each call `start()`. The losing run is still created, queued, and started, and returns once `getConflict()` resolves with the owner. The route can detect it by comparing the resumed hook's `runId` with the run it started.
|
|
282
282
|
</Callout>
|
|
283
283
|
|
|
284
284
|
The token becomes available when its workflow ends, unless you set `experimental_minRetention` on `createHook()`. See [`createHook()` minimum retention](/docs/api-reference/workflow/create-hook#keep-a-token-unavailable-after-the-run-ends).
|
|
@@ -116,10 +116,90 @@ async function updateUserStep(user: { id: string; name: string; email: string })
|
|
|
116
116
|
}
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
+
<Callout>
|
|
120
|
+
Deeply frozen values are the exception: they come back frozen, and are stored by reference. See [Frozen values](#frozen-values).
|
|
121
|
+
</Callout>
|
|
122
|
+
|
|
119
123
|
**Custom classes:**
|
|
120
124
|
|
|
121
125
|
- Class instances that implement [`WORKFLOW_SERIALIZE` and `WORKFLOW_DESERIALIZE`](#custom-class-serialization)
|
|
122
126
|
|
|
127
|
+
## Frozen values
|
|
128
|
+
|
|
129
|
+
State that grows across steps, such as a conversation history passed into every step, is stored again by every step that receives it, so total storage grows with the square of the number of steps. If you pass that state as a **deeply frozen** value, Workflow stores each step's change instead:
|
|
130
|
+
|
|
131
|
+
- A step input that holds a value Workflow already stored is written as a reference to it, about 80 bytes.
|
|
132
|
+
- A step output is written as its change from the stored value it was made from, for example "the previous history plus two messages".
|
|
133
|
+
|
|
134
|
+
Workflow finds what changed by identity. A frozen object can't change, so an object that appears in both versions is unchanged and needs no comparison.
|
|
135
|
+
|
|
136
|
+
The easiest way to make deeply frozen values is [immer](https://immerjs.github.io/immer/)'s `produce`, which freezes its results and shares every unchanged object with the previous value:
|
|
137
|
+
|
|
138
|
+
```typescript lineNumbers
|
|
139
|
+
import { produce } from "immer";
|
|
140
|
+
|
|
141
|
+
type Message = { role: "user" | "assistant"; content: string };
|
|
142
|
+
declare function reply(history: readonly Message[], text: string): Promise<string>; // @setup
|
|
143
|
+
declare const messages: AsyncIterable<{ text: string }>; // @setup
|
|
144
|
+
|
|
145
|
+
async function turn(history: readonly Message[], text: string) {
|
|
146
|
+
"use step";
|
|
147
|
+
const answer = await reply(history, text);
|
|
148
|
+
return produce(history, (draft) => {
|
|
149
|
+
draft.push({ role: "user", content: text }, { role: "assistant", content: answer });
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function chat() {
|
|
154
|
+
"use workflow";
|
|
155
|
+
let history: readonly Message[] = Object.freeze([]);
|
|
156
|
+
for await (const { text } of messages) {
|
|
157
|
+
history = await turn(history, text); // each input is a reference, each output a change
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Without immer, freeze every object you create, and reuse the frozen objects you didn't change:
|
|
163
|
+
|
|
164
|
+
```typescript lineNumbers
|
|
165
|
+
type Message = { role: "user" | "assistant"; content: string };
|
|
166
|
+
declare const history: readonly Message[]; // @setup
|
|
167
|
+
declare const text: string; // @setup
|
|
168
|
+
|
|
169
|
+
const next = Object.freeze([
|
|
170
|
+
...history, // unchanged messages, already frozen, reused as they are
|
|
171
|
+
Object.freeze({ role: "user" as const, content: text }),
|
|
172
|
+
]);
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Rules
|
|
176
|
+
|
|
177
|
+
- **Frozen values come back frozen.** Changing one in place throws a `TypeError`. Make the next version with `produce` (or a new frozen copy) instead.
|
|
178
|
+
- **`Date`, `Map`, `Set` and byte arrays are trusted.** Inside a frozen value they are treated as unchanging, even though JavaScript lets you change a `Date` or a `Map` after freezing. Change them only inside `produce` (see the note below).
|
|
179
|
+
- **Only deeply frozen plain data counts.** A value that isn't frozen, is only frozen at the top, or holds a class instance or another custom type, including inside a `Map` or `Set`, is stored in full.
|
|
180
|
+
- **Keep immer's auto-freeze on.** immer freezes what `produce` returns by default. With `setAutoFreeze(false)` its results aren't frozen, so they're stored in full every time: still correct, but the savings are gone. Turning it off is also how to opt a codebase out of storing values by reference.
|
|
181
|
+
- **A new value is linked by the objects it shares.** A value whose objects are all new, for example one made only of numbers and strings, is stored in full each time. That's fine for small values.
|
|
182
|
+
- **Some payloads are always stored in full:** run inputs, including values passed to another run through `start()`, workflow return values (so `run.returnValue` reads them as usual), and hook payloads.
|
|
183
|
+
- **Parallel steps.** Passing a frozen value to several parallel steps writes, in each step's input, a small reference if a step returned it unchanged, or only its change if you made the next version in workflow code with `produce` or `Object.freeze`. A frozen value built entirely in workflow code, sharing no objects with a step's output, is written in full to each input, because one step's input can't refer to another's.
|
|
184
|
+
- **A value is written whole again from time to time:** once its changes since the last whole copy pass half its size (for growing state, each time it doubles), or after 1,000 changes. That bounds how much a replay has to apply to about the value's own size.
|
|
185
|
+
- With `WORKFLOW_VM=quickjs`, values are stored in full, because that VM can't read references yet.
|
|
186
|
+
|
|
187
|
+
<Callout type="warn">
|
|
188
|
+
`Object.freeze` doesn't stop a `Map`, `Set` or `Date` from changing through its own methods (`map.set()`, `set.add()`, `date.setTime()`), and byte arrays can't be frozen at all. immer's `produce` makes the Maps and Sets it returns throw on those methods, but `Object.freeze` doesn't. Changing a `Date`, `Map`, `Set` or byte array in place inside a frozen value, for example with `date.setTime()`, `map.set()` or `bytes[0] = 1`, isn't recorded. A step that runs in the same invocation may still see the change, but a retried or queued step, and every replay, rebuilds the value from the stored records and sees the original. Make the change inside `produce` instead. Immer drafts a `Map` or `Set` once you call its `enableMapSet()`, and copies it when you change it. It doesn't draft a `Date` or a byte array, so replace those with new ones:
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
import { enableMapSet, produce } from "immer";
|
|
192
|
+
declare const state: { updatedAt: Date; tags: ReadonlySet<string> }; // @setup
|
|
193
|
+
|
|
194
|
+
enableMapSet(); // once, before producing state that holds a Map or Set
|
|
195
|
+
|
|
196
|
+
const next = produce(state, (draft) => {
|
|
197
|
+
draft.updatedAt = new Date(); // not draft.updatedAt.setTime(Date.now())
|
|
198
|
+
draft.tags.add("urgent"); // immer copies the Set
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
</Callout>
|
|
202
|
+
|
|
123
203
|
## Streaming
|
|
124
204
|
|
|
125
205
|
`ReadableStream` and `WritableStream` are supported as serializable types with special handling. These streams can be passed between workflow and step functions while maintaining their streaming capabilities.
|
|
@@ -100,16 +100,12 @@ export async function parentWorkflow(inputValue: number) {
|
|
|
100
100
|
}
|
|
101
101
|
```
|
|
102
102
|
|
|
103
|
-
When you call `start()` inside a workflow function, it automatically executes through an internal step to maintain deterministic replay. The returned `Run` object works as it does outside workflows. Properties such as `.runId`, `.status`, and `.returnValue`, and methods such as `.cancel()`, are all available.
|
|
103
|
+
When you call `start()` inside a workflow function, it automatically executes through an internal step to maintain deterministic replay. The returned `Run` object works as it does outside workflows. Properties such as `.runId`, `.status`, and `.returnValue`, and methods such as `.cancel()`, are all available.
|
|
104
104
|
|
|
105
|
-
If the child run fails or is canceled, `await childRun.returnValue` throws [`WorkflowRunFailedError`](/docs/api-reference/workflow-errors/workflow-run-failed-error) or [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error) on the first attempt.
|
|
105
|
+
Awaiting `childRun.returnValue` suspends the parent on a system hook that the child resumes when it finishes, so the parent waits without polling, uses no compute while it waits, and resumes as soon as the child is done. A child canceled without going through the SDK is noticed later, at the parent's next safety-net check; see [Cancellations that bypass the SDK](/cookbook/advanced/child-workflows#cancellations-that-bypass-the-sdk). If the child run fails or is canceled, `await childRun.returnValue` throws [`WorkflowRunFailedError`](/docs/api-reference/workflow-errors/workflow-run-failed-error) or [`WorkflowRunCancelledError`](/docs/api-reference/workflow-errors/workflow-run-cancelled-error) on the first attempt.
|
|
106
106
|
|
|
107
107
|
<Callout type="info">
|
|
108
|
-
Inside workflow functions, each `Run` property access (e.g., `run.status`, `run.returnValue`)
|
|
109
|
-
</Callout>
|
|
110
|
-
|
|
111
|
-
<Callout type="warn">
|
|
112
|
-
Awaiting `returnValue` polls the child run every second, and the polling step holds its worker slot open until the child finishes. Size worker-based Worlds to cover the peak number of these polls in flight. If the child workflow is long-running, spawn it without awaiting `returnValue` and have it resume a [hook](/docs/foundations/hooks) when it completes. See the [`startAndWait()` pattern](/cookbook/advanced/child-workflows).
|
|
108
|
+
Inside workflow functions, each `Run` property access (e.g., `run.status`, `run.returnValue`) is recorded in the event log and replayed deterministically. Most accessors run as one step; `returnValue` records the system hook and the steps that read the child's result.
|
|
113
109
|
</Callout>
|
|
114
110
|
|
|
115
111
|
### Fire and forget
|
|
@@ -304,7 +304,7 @@ A World that supports this returns the page in `events`, `cursor`, and `hasMore`
|
|
|
304
304
|
|
|
305
305
|
## Sealed positions (noop events)
|
|
306
306
|
|
|
307
|
-
Runs at `specVersion` 7 and above use a *sealed log*. The backend gives each write its position from a per-run sequencer **before** the write commits, so concurrent writers hold distinct positions and never race for a slot. New runs use this behavior by default. [`
|
|
307
|
+
Runs at `specVersion` 7 and above use a *sealed log*. The backend gives each write its position from a per-run sequencer **before** the write commits, so concurrent writers hold distinct positions and never race for a slot. New runs use this behavior by default. [`WORKFLOW_SPEC_VERSION=6`](/docs/configuration/runtime-tuning#workflow_spec_version) returns a deployment to the previous scheme. Every runtime reads a sealed log regardless, and a run's version is fixed at creation, so changing the setting never affects an in-flight run. However, a writer can claim a position and then stop because of a crashed process or canceled transaction. This leaves a hole that no writer will fill, and a hole looks like an event the reader failed to load.
|
|
308
308
|
|
|
309
309
|
The backend restores the dense log at read time by **sealing** these positions. Once a hole is provably abandoned, bounded by the commit time of later positions, the backend writes a `noop` event into it. Positions are assigned in order, so a committed later position proves how long the hole has been open. A `noop` occupies its position, and length-based completeness checks, cursors, and pagination all count it. It has no other effect:
|
|
310
310
|
|
|
@@ -372,7 +372,7 @@ All entities in the Workflow SDK use a consistent ID format: a 4-character prefi
|
|
|
372
372
|
|
|
373
373
|
An event ID is a **slot number**: the event's 1-based position in the run's event log, zero-padded to the same width as a ULID. The world assigns it when the event is published, so two writers racing to append never claim the same position and a rejected write leaves no gap behind. Slots are dense, and unique only within a run, so an event ID identifies an event only when paired with its `runId`.
|
|
374
374
|
|
|
375
|
-
Density is what lets a reader tell a complete log from an incomplete one by its length alone. A replay that loads a log with a position missing below the highest one it can see cannot tell an event that was never written from one it failed to read, so it fails the run with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) rather than replay across the hole.
|
|
375
|
+
Density is what lets a reader tell a complete log from an incomplete one by its length alone. A replay that loads a log with a position missing below the highest one it can see cannot tell an event that was never written from one it failed to read, so it fails the run with [`CORRUPTED_EVENT_LOG`](/docs/errors/corrupted-event-log) rather than replay across the hole.
|
|
376
376
|
|
|
377
377
|
A slot ID carries no timestamp. Zero-padded decimal digits are a subset of the ULID alphabet, so a slot ID passes ULID validation and sorts correctly, but decoding its first 48 bits yields the Unix epoch instead of a creation time. Read `createdAt` on the event when you need to know when it was written, and don't decode the time from an `evnt_` ID you get back from an API, a log line, or a cursor.
|
|
378
378
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@workflow/core",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.5.0",
|
|
4
4
|
"description": "Core runtime and engine for Workflow SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -84,39 +84,40 @@
|
|
|
84
84
|
"./_workflow": "./dist/workflow/index.js"
|
|
85
85
|
},
|
|
86
86
|
"dependencies": {
|
|
87
|
-
"@aws-sdk/credential-provider-web-identity": "3.972.
|
|
87
|
+
"@aws-sdk/credential-provider-web-identity": "3.972.88",
|
|
88
88
|
"@jridgewell/trace-mapping": "0.3.31",
|
|
89
|
-
"@standard-schema/spec": "1.
|
|
89
|
+
"@standard-schema/spec": "1.1.0",
|
|
90
90
|
"@types/ms": "2.1.0",
|
|
91
|
-
"@vercel/functions": "^3.
|
|
92
|
-
"@workflow/errors": "5.1.
|
|
91
|
+
"@vercel/functions": "^3.11.1",
|
|
92
|
+
"@workflow/errors": "5.1.1",
|
|
93
93
|
"@workflow/serde": "5.0.0",
|
|
94
|
-
"@workflow/utils": "5.0
|
|
95
|
-
"@workflow/world": "5.
|
|
96
|
-
"@workflow/world-local": "5.
|
|
97
|
-
"@workflow/world-vercel": "5.
|
|
98
|
-
"acorn": "8.
|
|
94
|
+
"@workflow/utils": "5.1.0",
|
|
95
|
+
"@workflow/world": "5.2.0",
|
|
96
|
+
"@workflow/world-local": "5.3.0",
|
|
97
|
+
"@workflow/world-vercel": "5.5.0",
|
|
98
|
+
"acorn": "8.19.0",
|
|
99
99
|
"debug": "4.4.3",
|
|
100
100
|
"devalue": "6.0.3",
|
|
101
101
|
"ms": "2.1.3",
|
|
102
102
|
"quickjs-wasi": "3.4.0",
|
|
103
103
|
"seedrandom": "3.0.5",
|
|
104
|
-
"semver": "7.
|
|
105
|
-
"ulid": "~3.0.
|
|
106
|
-
"zod": "~4.
|
|
104
|
+
"semver": "7.8.6",
|
|
105
|
+
"ulid": "~3.0.2",
|
|
106
|
+
"zod": "~4.6.7"
|
|
107
107
|
},
|
|
108
108
|
"devDependencies": {
|
|
109
109
|
"@opentelemetry/api": "1.9.0",
|
|
110
110
|
"@opentelemetry/context-async-hooks": "1.30.1",
|
|
111
111
|
"@opentelemetry/core": "1.30.1",
|
|
112
112
|
"@opentelemetry/sdk-trace-base": "1.30.1",
|
|
113
|
-
"@types/debug": "4.1.
|
|
114
|
-
"@types/node": "22.19.
|
|
113
|
+
"@types/debug": "4.1.13",
|
|
114
|
+
"@types/node": "22.19.21",
|
|
115
115
|
"@types/seedrandom": "3.0.8",
|
|
116
|
-
"@types/semver": "7.
|
|
116
|
+
"@types/semver": "7.8.0",
|
|
117
117
|
"@workflow/tsconfig": "5.0.0",
|
|
118
118
|
"cross-env": "10.1.0",
|
|
119
119
|
"genversion": "3.2.0",
|
|
120
|
+
"immer": "10.1.1",
|
|
120
121
|
"typescript": "^6.0.3"
|
|
121
122
|
},
|
|
122
123
|
"peerDependencies": {
|
|
@@ -131,8 +132,8 @@
|
|
|
131
132
|
"build": "genversion --es6 src/version.ts && node scripts/build-quickjs-assets.js && tsc",
|
|
132
133
|
"dev": "genversion --es6 src/version.ts && tsc --watch",
|
|
133
134
|
"clean": "tsc --build --clean && rm -rf dist src/version.ts docs ||:",
|
|
134
|
-
"test": "cross-env WORKFLOW_TARGET_WORLD=local vitest run src e2e/utils.test.ts",
|
|
135
|
-
"test:e2e": "vitest run e2e",
|
|
135
|
+
"test": "cross-env WORKFLOW_TARGET_WORLD=local vitest run --config=../../vitest.config.ts src e2e/utils.test.ts",
|
|
136
|
+
"test:e2e": "vitest run --config=../../vitest.config.ts e2e",
|
|
136
137
|
"typecheck": "genversion --es6 src/version.ts && tsc --noEmit"
|
|
137
138
|
}
|
|
138
139
|
}
|