Repository navigation
perf(runtime): skip deferred script tokenizing when no resolver can be queued - #9016
Merged
Merged
Conversation
…e queued Every streamed SSR response went through DeferredScriptOutputCoordinator, which tokenizes React output character by character to find safe points for deferred resolver scripts. Resolver scripts only come from deferred data registered before React output starts, so when none was registered (no loader data, or loader data without pending deferred keys) nothing can ever be inserted and the output is forwarded unchanged. Inside inline script/style text, also skip the end tag suffix search until a `<` shows up, since it would leave the search state empty anyway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
🦋 Changeset detectedLatest commit: eb4eb92 The changes in this PR will be included in the next version bump. This PR includes changesets to release 120 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
✅ Deploy Preview for modernjs-byted ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Contributor
Rsdoctor Bundle Diff Analysis📊 Quick Summary
Generated by Rsdoctor GitHub Action |
A resolver queued after the stream was marked as having no resolvers was reported as ending outside a safe HTML boundary, which hides the real cause. Report the contract violation instead. Also restore the global runtime context after the stream tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deepcoldy
enabled auto-merge (squash)
October 17, 2026 18:09
GiveMe-A-Name
approved these changes
Oct 20, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Summary
Every streamed SSR response, both Node (
createReadableStream.ts) and edge (createReadableStream.worker.ts), writes all of React's output throughDeferredScriptOutputCoordinator.writeReact. That method feeds every character into a small HTML tokenizer so that resolver scripts fordefer()data can be inserted at safe HTML boundaries. It costs about 30 ns per character, or ~11 ms of CPU for a 356 KB page, and it runs even when the response has no deferred data at all.Resolver scripts can only come from
enqueueFromEntries. It readsactiveDeferreds/deferredScriptKeyssynchronously, before React output starts flowing to the coordinator, and registers a resolver only for serialized keys whose value is a promise. If it registers none,enqueueResolveris never called. With an empty queue, the existingwriteReactemits each chunk exactly once and unchanged,finish()cannot throw, andmarkShellFinished()/abort()have no effect on the output. In that case the tokenizer's work is simply thrown away.Changes:
hasDeferredResolvers(entries, deferredScriptKeys)indeferredScript.tsanswers whetherenqueueFromEntrieswould emit anything. It shares the key-selection helper withenqueueFromEntries.enqueueFromEntriesonly when that check is true. Otherwise they call the newcoordinator.markNoResolvers(), which makeswriteReactforward chunks as-is. The existingclosed/ empty-chunk handling stays in front of it, soabort()andfinish()still stop output.flushResolvers()never emits. A resolver that shows up anyway (a contract violation) is therefore never injected at an unknown position, and the existingfinish()error reports it.DeferredData, so checkingentries.length > 0alone would miss most real apps.<script>/<style>text, whenrawTextSearchis empty and the char is not<,consumeRawTextreturns early. The tracking of$RC/$RS/ ... continuation calls still runs first. The skippedgetSuffixcall would return''in that case: no suffix of a char other than<is a prefix of</tag. So the tokenizer state is identical.When deferred data is present nothing else changes: the tokenizer runs as before.
Benchmark
Environment: Node v22.21.1,
nproc= 64 (shared machine),NODE_ENV=production. The baseline is theorigin/maindist and the "after" column is this branch's dist. Both are loaded side by side in one process and drive the real exportedcreateReadableStreamFromElement(Node and worker variants). React output is replaced by fixed 4 KB byte chunks through aprocessStreamextender. The worker uses a stubbedrenderSSRStream. Output bytes are asserted identical before timing. Each cell is the median of 3 processes, and each process reports the median of 3 interleaved series × 5 rounds × 20 requests.Most of the time left in the shell-heavy rows comes from the quadratic shell-marker buffering, which is fixed separately in the
stream-ssr-shell-bufferPR. With both changes applied, the shell-heavy page with no deferred data goes from 35.6 ms to 2.8 ms on Node and from 22.4 ms to 2.1 ms on the worker.Coordinator alone (
writeReactover the page in 4 KB string chunks, median of 3 runs):markNoResolvers)Benchmark scripts
Setup: copy the
origin/mainbuild ofpackages/runtime/plugin-runtime/distto./distand this branch's build to./new-fast/dist. Both directories get anode_modulessymlink topackages/runtime/plugin-runtime/node_modules.Run:
./run3.sh: end-to-end table, 3 processes ofNODE_ENV=production node bench.cjsnode coordinator-bench.cjs ./ base && node coordinator-bench.cjs ./new-fast branchNODE_ENV=production node e2e-diff.cjsandnode coordinator-diff.cjs: differential checksharness.cjspage.cjsbench.cjsrun3.shcoordinator-bench.cjscoordinator-diff.cjse2e-diff.cjsValidation
tests/ssr/deferredScriptOutputCoordinator.test.ts(14 new tests, 30 in the file):>in attributes, a continuation segment plus$RC, a textarea and multi-byte text, split at sizes 1 / 7 / 64 / whole. A spy on the privateconsumeshows 0 calls in pass-through mode and one call per char otherwise.finish()reports it.abort()still stops output.<b,</scr,</scripts,"<</script",<<</followed bySCRIPT>across chunks).hasDeferredResolversmatches whetherenqueueFromEntriesactually emits a script, across 8 cases: no entries, non-deferred values, plain loader data, a pending key, an unserialized key, thependingKeysfallback, a non-promise key, and mixed routes.createReadableStreamFromElement: with no loader data, or loader data without pending keys, the output is the expected document andconsumeis never called. With a pending deferred key, the stream is tokenized and the resolver script follows the shell.npx rstestinpackages/runtime/plugin-runtime: 17 files, 80 tests passed.createReadableStream.tsrestored toorigin/main, both "does not tokenize the stream" tests fail (consumecalled 395 times).deferredScriptOutputCoordinator.tsrestored, 4 tests fail.origin/maindist:coordinator-diff.cjs: 972 no-resolver runs (pass-through against the old tokenizer) and 5832 tokenizing runs, with resolvers andmarkShellFinishedat random points. Inputs are 9 HTML documents, each split at fixed sizes plus 100 random splittings. Result: 0 mismatches in emitted chunk sequences and errors. A sanity variant that wrongly compares against pass-through reports 4911 mismatches, so the harness does catch differences.e2e-diff.cjs: 50 end-to-end Node and worker runs covering no data, plain loader data, an unserialized deferred key, resolved and rejected deferred keys, and 5 chunkings. Result: byte-identical.pnpm exec rs lint/pnpm exec rs fmton the changed files: clean.npx tsc --noEmit -p packages/runtime/plugin-runtime/tsconfig.json: clean. No new errors undertests/tsconfig.json.perf/stream-ssr-shell-buffermerge cleanly in either order and produce identical trees. The merged tree passestscand all 85 tests.Checklist
pnpm run change.🤖 Generated with Claude Code