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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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

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
NameType
@workflow/corePatch
workflowPatch
@workflow/buildersPatch
@workflow/cliPatch
@workflow/nextPatch
@workflow/nitroPatch
@workflow/vitestPatch
@workflow/web-sharedPatch
@workflow/webPatch
@workflow/world-testingPatch
@workflow/astroPatch
@workflow/nestPatch
@workflow/rollupPatch
@workflow/sveltekitPatch
@workflow/vitePatch
@workflow/nuxtPatch

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

vercelBot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actionsBot commented Jun 22, 2026

Copy link
Copy Markdown
ContributorAuthor

🧪 E2E Test Results

Some tests failed

Summary

PassedFailedSkippedTotal
✅ ▲ Vercel Production10440781122
✅ 💻 Local Development11380861224
✅ 📦 Local Production11380861224
✅ 🐘 Local Postgres11260981224
✅ 🪟 Windows10200102
❌ 🌍 Community Worlds76996181
✅ 📋 Other574038612
Total5198993925689

❌ 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
AppPassedFailedSkipped
✅ astro9408
✅ example9408
✅ express9408
✅ fastify9408
✅ hono9408
✅ nextjs-turbopack9903
✅ nextjs-webpack9903
✅ nitro9408
✅ nuxt9408
✅ sveltekit9408
✅ vite9408
✅ 💻 Local Development
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 📦 Local Production
AppPassedFailedSkipped
✅ astro-stable9606
✅ express-stable9606
✅ fastify-stable9606
✅ hono-stable9606
✅ nextjs-turbopack-canary83019
✅ nextjs-turbopack-stable10200
✅ nextjs-webpack-canary83019
✅ nextjs-webpack-stable10200
✅ nitro-stable9606
✅ nuxt-stable9606
✅ sveltekit-stable9606
✅ vite-stable9606
✅ 🐘 Local Postgres
AppPassedFailedSkipped
✅ astro-stable9507
✅ express-stable9507
✅ fastify-stable9507
✅ hono-stable9507
✅ nextjs-turbopack-canary82020
✅ nextjs-turbopack-stable10101
✅ nextjs-webpack-canary82020
✅ nextjs-webpack-stable10101
✅ nitro-stable9507
✅ nuxt-stable9507
✅ sveltekit-stable9507
✅ vite-stable9507
✅ 🪟 Windows
AppPassedFailedSkipped
✅ nextjs-turbopack10200
❌ 🌍 Community Worlds
AppPassedFailedSkipped
✅ mongodb-dev302
✅ redis-dev302
❌ redis64190
✅ turso-dev302
❌ turso3800
✅ 📋 Other
AppPassedFailedSkipped
✅ e2e-local-dev-nest-stable9606
✅ e2e-local-dev-tanstack-start-stable9606
✅ e2e-local-postgres-nest-stable9507
✅ e2e-local-postgres-tanstack-start-stable9507
✅ e2e-local-prod-nest-stable9606
✅ e2e-local-prod-tanstack-start-stable9606

📋 View full workflow run

@vercelvercelBot 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 stableJun 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 freeto 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

@VaguelySerious