Skip to content

Backport #2472: perf(core): memoize step return value hydration across inline replays#2563

Merged
VaguelySerious merged 1 commit into
stablefrom
backport/pr-2472-to-stable
Jun 22, 2026
Merged

Backport #2472: perf(core): memoize step return value hydration across inline replays#2563
VaguelySerious merged 1 commit into
stablefrom
backport/pr-2472-to-stable

Conversation

@github-actions

Copy link
Copy Markdown
Contributor

Automated backport of #2472 to stable (backport job run).

AI recommendation: This is a self-contained performance optimization to packages/core (memoizing step-return-value hydration during inline replay), and I verified that all modified files (step.ts, workflow.ts, runtime.ts, private.ts) and the exact hotspot it targets (hydrateStepReturnValue inside the promiseQueue slot with pendingDeliveries) already exist on stable. The change is backward-compatible (new params/context field are optional, degrading to prior behavior) and doesn't depend on any main-only APIs, so it applies cleanly to the existing replay logic on stable.

Merge conflicts were resolved by AI (opencode with anthropic/claude-opus-4.8). Please review the conflict resolution carefully before merging.

…#2472)

* perf(core): memoize step return value hydration across replays

The inline replay loop re-executes the workflow body and re-consumes the
full event log on every iteration. For each already-completed step, the
step consumer re-decrypted and re-devalue-parsed the serialized result on
every replay — O(N^2) decrypt+parse operations across a single
invocation of a sequential N-step workflow.

Add a per-run memoization cache, owned by the inline loop in runtime.ts
(alongside cachedEvents) so it survives across replay iterations of the
same run but never leaks across runs. It is threaded into runWorkflow and
stored on the orchestrator context, and consulted in the step_completed
path keyed by the persisted event id. This makes a completed step's
hydrated result O(1) on subsequent replays, turning the aggregate cost
into O(N).

Determinism is preserved: the cache lookup happens inside the existing
ctx.promiseQueue slot and still resolves via the same resolve(), so a
cache hit occupies the identical position in the ordered delivery chain a
re-hydrate would have — pendingDeliveries accounting, delivery barriers,
and Promise.race/all replay are untouched.

Identity safety: hydrateStepReturnValue returns a fresh object graph each
call and each replay runs in a fresh VM, so sharing an object reference
across replays could let one replay's mutation leak into the next. Only
primitive results are memoized (immutable, reference-share == re-parse);
non-primitives re-hydrate fresh every replay, exactly as before. Hook,
wait, and abort hydration paths are intentionally left uncached.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* perf(core): bound memoized step-hydration cache by primitive size

Address the review note that the per-run step hydration cache was never
size-bounded: cached entries hold the decrypted/parsed plaintext of a
primitive step result for the whole invocation, on top of the serialized
bytes already retained in cachedEvents, so a long run returning large
strings could roughly double peak retained memory for those results.

Document the cache's memory characteristic (per-invocation, freed when the
invocation ends, bounded by primitive-returning step count) and cap the
only primitive types that can carry a large payload: string/bigint results
longer than MAX_MEMOIZED_PRIMITIVE_LENGTH (4 KiB) fall through to the
existing per-replay re-hydrate path instead of being memoized. Large
payloads are cheap to re-hydrate relative to their footprint, so this caps
the worst case at negligible cost. Other primitives are inherently small
and always memoized.

The cap only ever reduces what is cached, so deterministic replay is
unaffected: oversized values take the already-correct re-hydrate path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Pranay Prakash <pranay.gp@gmail.com>
@changeset-bot

changeset-bot Bot commented Jun 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 5d959da

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
@workflow/core Patch
workflow Patch
@workflow/builders Patch
@workflow/cli Patch
@workflow/next Patch
@workflow/nitro Patch
@workflow/vitest Patch
@workflow/web-shared Patch
@workflow/web Patch
@workflow/world-testing Patch
@workflow/astro Patch
@workflow/nest Patch
@workflow/rollup Patch
@workflow/sveltekit Patch
@workflow/vite Patch
@workflow/nuxt Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
example-nextjs-workflow-turbopack Ready Ready Preview, Comment Jun 22, 2026 8:40pm
example-nextjs-workflow-webpack Ready Ready Preview, Comment Jun 22, 2026 8:40pm
example-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-astro-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-express-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-fastify-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-hono-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-nitro-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-nuxt-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-sveltekit-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-tanstack-start-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workbench-vite-workflow Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workflow-docs Ready Ready Preview, Comment, Open in v0 Jun 22, 2026 8:40pm
workflow-swc-playground Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workflow-tarballs Ready Ready Preview, Comment Jun 22, 2026 8:40pm
workflow-web Ready Ready Preview, Comment Jun 22, 2026 8:40pm

@github-actions

github-actions Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

🧪 E2E Test Results

Some tests failed

Summary

Passed Failed Skipped Total
✅ ▲ Vercel Production 1044 0 78 1122
✅ 💻 Local Development 1138 0 86 1224
✅ 📦 Local Production 1138 0 86 1224
✅ 🐘 Local Postgres 1126 0 98 1224
✅ 🪟 Windows 102 0 0 102
❌ 🌍 Community Worlds 76 99 6 181
✅ 📋 Other 574 0 38 612
Total 5198 99 392 5689

❌ Failed Tests

🌍 Community Worlds (99 failed)

redis (19 failed):

  • hookWorkflow | wrun_01KVRGWAZ8X4JA6BN294K4QJX9
  • hookWorkflow is not resumable via public webhook endpoint | wrun_01KVRGWJBZT910DZBVQBHEW4HA
  • parallelStepsThenWebhookWorkflow - no hook_conflict from same-tick replay race | wrun_01KVRGWYF8FK1Y3EPM1DN0337Y
  • sleepingWorkflow | wrun_01KVRGYABQ1MRCWQHFJ64DJTSV
  • outputStreamWorkflow negative startIndex (reads from end)
  • outputStreamWorkflow - getTailIndex and getStreamChunks getTailIndex returns correct index after stream completes
  • outputStreamWorkflow - getTailIndex and getStreamChunks getTailIndex returns -1 before any chunks are written
  • outputStreamWorkflow - getTailIndex and getStreamChunks getStreamChunks returns same content as reading the stream
  • concurrent hook token conflict - two workflows cannot use the same hook token simultaneously | wrun_01KVRH6HY6M7A2EN80SSHKX12E
  • hookGetConflictWorkflow - awaiting hook.getConflict() registers hook without payload | wrun_01KVRH6YX5KHBRW4NFQM6HY04Z
  • hookGetConflictThenStepParallelWorkflow - hook.getConflict() continuation step runs alongside other steps | wrun_01KVRH79KMZ31WJGA9JE58E78K
  • hookGetConflictWorkflow - hook.getConflict() resolves with the conflicting run when token is already registered | wrun_01KVRH7R78NG7X3SPHK1T997RN
  • hookClaimOnlyMutexWorkflow - hook works as a pure run mutex without payload data | wrun_01KVRH8M3N04FTEG2V30F5TW1H
  • hookAdoptOwnerResultWorkflow - duplicate adopts the owner result via conflict.returnValue | wrun_01KVRH8TDBWGKWENVG2PYP0PJV
  • hookSignalOwnerWorkflow - duplicate forwards its payload to the owner via resumeHook | wrun_01KVRH94DGZKWG3Y9VE57JY28S
  • hookSupersedeOwnerWorkflow - duplicate cancels the owner and claims the released token | wrun_01KVRH9AV55YH5RY0NYH7BDE2T
  • resume-or-start route pattern - resumeHook retried after start() reaches the new run | wrun_01KVRH9N8A3M4PM2C3DXDSPW30
  • pages router sleepingWorkflow via pages router
  • resilient start: addTenWorkflow completes when run_created returns 500 | wrun_01KVRHGDG0AVPK0Z10AM9C01CK

turso (80 failed):

  • addTenWorkflow | wrun_01KVRGV9RQM837K4XW3F56GJN3
  • addTenWorkflow | wrun_01KVRGV9RQM837K4XW3F56GJN3
  • deploymentId: 'latest' is a no-op in non-Vercel worlds
  • wellKnownAgentWorkflow (.well-known/agent) | wrun_01KVRGXGP79X0AYZ1S62B1FBXZ
  • should work with react rendering in step
  • promiseAllWorkflow | wrun_01KVRGVJ0M8SY1KSP50PWNJ1AR
  • promiseRaceWorkflow | wrun_01KVRGVPZAWR3HCYHDPQ4NQN6Y
  • promiseAnyWorkflow | wrun_01KVRGVTMS96R58VEFKDK4CSQ1
  • importedStepOnlyWorkflow | wrun_01KVRGXZGCBGC7E90S2B72FX9F
  • readableStreamWorkflow | wrun_01KVRGVX44023HJ7EYA72YC7M0
  • hookWorkflow | wrun_01KVRGWAZ8X4JA6BN294K4QJX9
  • hookWorkflow is not resumable via public webhook endpoint | wrun_01KVRGWJBZT910DZBVQBHEW4HA
  • webhookWorkflow | wrun_01KVRGWQQ0PQC6A44E7YJ7SRV3
  • parallelStepsThenWebhookWorkflow - no hook_conflict from same-tick replay race | wrun_01KVRGWYF8FK1Y3EPM1DN0337Y
  • sleepingWorkflow | wrun_01KVRGYABQ1MRCWQHFJ64DJTSV
  • parallelSleepWorkflow | wrun_01KVRGYTFPWQE9G5H7R63HY1E0
  • nullByteWorkflow | wrun_01KVRGYZ8XCFW52BTGB6QGG7N6
  • workflowAndStepMetadataWorkflow | wrun_01KVRGZ1K2H0KQ17E83TJMYM03
  • outputStreamWorkflow no startIndex (reads all chunks)
  • outputStreamWorkflow positive startIndex (skips first chunk)
  • outputStreamWorkflow negative startIndex (reads from end)
  • outputStreamWorkflow - getTailIndex and getStreamChunks getTailIndex returns correct index after stream completes
  • outputStreamWorkflow - getTailIndex and getStreamChunks getTailIndex returns -1 before any chunks are written
  • outputStreamWorkflow - getTailIndex and getStreamChunks getStreamChunks returns same content as reading the stream
  • outputStreamInsideStepWorkflow - getWritable() called inside step functions | wrun_01KVRH1N4H40S7T1HF3JEK6TT4
  • writableForwardedFromWorkflowWorkflow | wrun_01KVRH22VG36QKNTG1ZJ3KPNH7
  • writableForwardedFromStepWorkflow | wrun_01KVRH27DREKR2VQREA2GXAEYK
  • fetchWorkflow | wrun_01KVRH2CFQ40SY2W2ZDGVAW73J
  • promiseRaceStressTestWorkflow | wrun_01KVRH2G40315XT5AS0CZV7HF0
  • error handling error propagation workflow errors nested function calls preserve message and stack trace
  • error handling error propagation workflow errors cross-file imports preserve message and stack trace
  • error handling error propagation step errors basic step error preserves message and stack trace
  • error handling error propagation step errors cross-file step error preserves message and function names in stack
  • error handling retry behavior regular Error retries until success
  • error handling retry behavior FatalError fails immediately without retries
  • error handling retry behavior RetryableError respects custom retryAfter delay
  • error handling retry behavior maxRetries=0 disables retries
  • error handling catchability FatalError can be caught and detected with FatalError.is()
  • error handling not registered WorkflowNotRegisteredError fails the run when workflow does not exist
  • error handling not registered StepNotRegisteredError fails the step but workflow can catch it
  • error handling not registered StepNotRegisteredError fails the run when not caught in workflow
  • hookCleanupTestWorkflow - hook token reuse after workflow completion | wrun_01KVRH63Z4Y4613JZ973SXG0QN
  • concurrent hook token conflict - two workflows cannot use the same hook token simultaneously | wrun_01KVRH6HY6M7A2EN80SSHKX12E
  • hookGetConflictWorkflow - awaiting hook.getConflict() registers hook without payload | wrun_01KVRH6YX5KHBRW4NFQM6HY04Z
  • 'hookGetConflictWithPriorStepWorkflow' - hook.getConflict() does not block step execution | wrun_01KVRH72GDGK5N8HZ9SDZ9PMHB
  • 'hookGetConflictWithParallelStepWorkfl…' - hook.getConflict() does not block step execution | wrun_01KVRH76TCSN3MM9TE0S4PD6NW
  • hookGetConflictThenStepParallelWorkflow - hook.getConflict() continuation step runs alongside other steps | wrun_01KVRH79KMZ31WJGA9JE58E78K
  • hookGetConflictWorkflow - hook.getConflict() resolves with the conflicting run when token is already registered | wrun_01KVRH7R78NG7X3SPHK1T997RN
  • hookClaimOnlyMutexWorkflow - hook works as a pure run mutex without payload data | wrun_01KVRH8M3N04FTEG2V30F5TW1H
  • hookAdoptOwnerResultWorkflow - duplicate adopts the owner result via conflict.returnValue | wrun_01KVRH8TDBWGKWENVG2PYP0PJV
  • hookSignalOwnerWorkflow - duplicate forwards its payload to the owner via resumeHook | wrun_01KVRH94DGZKWG3Y9VE57JY28S
  • hookSupersedeOwnerWorkflow - duplicate cancels the owner and claims the released token | wrun_01KVRH9AV55YH5RY0NYH7BDE2T
  • resume-or-start route pattern - resumeHook retried after start() reaches the new run | wrun_01KVRH9N8A3M4PM2C3DXDSPW30
  • hookDisposeTestWorkflow - hook token reuse after explicit disposal while workflow still running | wrun_01KVRH9YC73JD5G78BA017V0G4
  • stepFunctionPassingWorkflow - step function references can be passed as arguments (without closure vars) | wrun_01KVRHAH2EBJSJC190FFABE271
  • stepFunctionWithClosureWorkflow - step function with closure variables passed as argument | wrun_01KVRHAWCDW1H6B47MB4FMKM5P
  • closureVariableWorkflow - nested step functions with closure variables | wrun_01KVRHB2MCZFXD0F4WSEX0AKCQ
  • spawnWorkflowFromStepWorkflow - spawning a child workflow using start() inside a step | wrun_01KVRHB58NMVZQG9DEDDS3X7W4
  • health check (queue-based) - workflow and step endpoints respond to health check messages
  • health check (CLI) - workflow health command reports healthy endpoints
  • pathsAliasWorkflow - TypeScript path aliases resolve correctly | wrun_01KVRHBNPE9Q1VFBM9YDMW57N6
  • Calculator.calculate - static workflow method using static step methods from another class | wrun_01KVRHBW567GDB760FWMGW1XSG
  • AllInOneService.processNumber - static workflow method using sibling static step methods | wrun_01KVRHC3NK1S5BMREG0Q4GDVHW
  • ChainableService.processWithThis - static step methods using this to reference the class | wrun_01KVRHCAXV8M0RJT7NGSH1HRGB
  • thisSerializationWorkflow - step function invoked with .call() and .apply() | wrun_01KVRHCJAQ2BMW3CJX4HFCMC6H
  • customSerializationWorkflow - custom class serialization with WORKFLOW_SERIALIZE/WORKFLOW_DESERIALIZE | wrun_01KVRHCTW1RF964RDFAS7S9JC9
  • instanceMethodStepWorkflow - instance methods with "use step" directive | wrun_01KVRHD3XXW2PN8V1YTTGFG0HF
  • crossContextSerdeWorkflow - classes defined in step code are deserializable in workflow context | wrun_01KVRHDJRCHDYWT10QV9TNC1F3
  • stepFunctionAsStartArgWorkflow - step function reference passed as start() argument | wrun_01KVRHDWJWKFY3W9633S8Y40EV
  • cancelRun - cancelling a running workflow | wrun_01KVRHE5ZCDF863BJAH7V1BQ41
  • cancelRun via CLI - cancelling a running workflow | wrun_01KVRHEGGR34D0WPK3AFXK4ZC7
  • pages router addTenWorkflow via pages router
  • pages router promiseAllWorkflow via pages router
  • pages router sleepingWorkflow via pages router
  • hookWithSleepWorkflow - hook payloads delivered correctly with concurrent sleep | wrun_01KVRHEXBED0G837367CT7XH9M
  • sleepInLoopWorkflow - sleep inside loop with steps actually delays each iteration | wrun_01KVRHFHM67PBKDDZJAQAAGNTN
  • sleepWithSequentialStepsWorkflow - sequential steps work with concurrent sleep (control) | wrun_01KVRHFWRT71XCVX4K5CV2H03K
  • importMetaUrlWorkflow - import.meta.url is available in step bundles | wrun_01KVRHG6YAW43K9RQSSS7JKMXD
  • metadataFromHelperWorkflow - getWorkflowMetadata/getStepMetadata work from module-level helper (#1577) | wrun_01KVRHGAXG2HPKAAQAYTYXKFEV
  • resilient start: addTenWorkflow completes when run_created returns 500 | wrun_01KVRHGDG0AVPK0Z10AM9C01CK

Details by Category

✅ ▲ Vercel Production
App Passed Failed Skipped
✅ astro 94 0 8
✅ example 94 0 8
✅ express 94 0 8
✅ fastify 94 0 8
✅ hono 94 0 8
✅ nextjs-turbopack 99 0 3
✅ nextjs-webpack 99 0 3
✅ nitro 94 0 8
✅ nuxt 94 0 8
✅ sveltekit 94 0 8
✅ vite 94 0 8
✅ 💻 Local Development
App Passed Failed Skipped
✅ astro-stable 96 0 6
✅ express-stable 96 0 6
✅ fastify-stable 96 0 6
✅ hono-stable 96 0 6
✅ nextjs-turbopack-canary 83 0 19
✅ nextjs-turbopack-stable 102 0 0
✅ nextjs-webpack-canary 83 0 19
✅ nextjs-webpack-stable 102 0 0
✅ nitro-stable 96 0 6
✅ nuxt-stable 96 0 6
✅ sveltekit-stable 96 0 6
✅ vite-stable 96 0 6
✅ 📦 Local Production
App Passed Failed Skipped
✅ astro-stable 96 0 6
✅ express-stable 96 0 6
✅ fastify-stable 96 0 6
✅ hono-stable 96 0 6
✅ nextjs-turbopack-canary 83 0 19
✅ nextjs-turbopack-stable 102 0 0
✅ nextjs-webpack-canary 83 0 19
✅ nextjs-webpack-stable 102 0 0
✅ nitro-stable 96 0 6
✅ nuxt-stable 96 0 6
✅ sveltekit-stable 96 0 6
✅ vite-stable 96 0 6
✅ 🐘 Local Postgres
App Passed Failed Skipped
✅ astro-stable 95 0 7
✅ express-stable 95 0 7
✅ fastify-stable 95 0 7
✅ hono-stable 95 0 7
✅ nextjs-turbopack-canary 82 0 20
✅ nextjs-turbopack-stable 101 0 1
✅ nextjs-webpack-canary 82 0 20
✅ nextjs-webpack-stable 101 0 1
✅ nitro-stable 95 0 7
✅ nuxt-stable 95 0 7
✅ sveltekit-stable 95 0 7
✅ vite-stable 95 0 7
✅ 🪟 Windows
App Passed Failed Skipped
✅ nextjs-turbopack 102 0 0
❌ 🌍 Community Worlds
App Passed Failed Skipped
✅ mongodb-dev 3 0 2
✅ redis-dev 3 0 2
❌ redis 64 19 0
✅ turso-dev 3 0 2
❌ turso 3 80 0
✅ 📋 Other
App Passed Failed Skipped
✅ e2e-local-dev-nest-stable 96 0 6
✅ e2e-local-dev-tanstack-start-stable 96 0 6
✅ e2e-local-postgres-nest-stable 95 0 7
✅ e2e-local-postgres-tanstack-start-stable 95 0 7
✅ e2e-local-prod-nest-stable 96 0 6
✅ e2e-local-prod-tanstack-start-stable 96 0 6

📋 View full workflow run

@vercel vercel Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional Suggestion:

The step-hydration memoization cache is never instantiated or passed to runWorkflow in production, so ctx.stepHydrationCache is always undefined and the entire optimization is dead code.

Fix on Vercel

@VaguelySerious VaguelySerious merged commit 0a5e2aa into stable Jun 22, 2026
94 of 97 checks passed
@VaguelySerious VaguelySerious deleted the backport/pr-2472-to-stable branch June 22, 2026 22:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant