Repository navigation
Conversation
When a page streams deferred loader data, DeferredScriptOutputCoordinator passed every character of the document, shell included, through its per-char HTML tokenizer to find safe resolver insertion points. Text, tag and attribute names, attribute values, and script, style and comment bodies cannot change where a resolver may be inserted, so they are now consumed as whole runs (indexOf / char code scans) and only the chars that can change the tokenizer state still go through consume(). Complete name="value" attributes are consumed at once, and the char class helpers no longer evaluate a RegExp literal per char. Every field ends up as consuming char by char would leave it, so the emitted bytes, chunk splits, resolver positions and errors are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
🦋 Changeset detectedLatest commit: ba6eefc The changes in this PR will be included in the next version bump. This PR includes changesets to release 116 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 |
This branch has not been deployed
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
When a streaming SSR request has deferred loader data (
defer()or a Promise in loader data),DeferredScriptOutputCoordinator.writeReactfeeds every char of React's output, including the ~24 KB template shell, through an HTML tokenizer to find safe points for the router's resolver scripts. Each char costs up to twoisSafeBoundary()checks plus theconsume()switch, and the char-class helpers ran a RegExp. #9016 skipped this only when no resolver can be queued. On the two deferred bench pages below, the coordinator alone took about 2.0 ms and 7.6 ms per response.Most chars can only extend the current token. This PR consumes them as whole runs:
consumeRun(chunk, start)runs before eachconsume()inwriteReact:<.consume().<when no partial</tagmatch is pending. The$RC/$RS/$RX/$RB/$RRdetection tail is set to exactly the per-char value.>.consumeAttributes()adds whitespace and completename="value"attributes (ASCII name starting with a letter, closing quote in the same chunk) in one step.isAsciiAlpha/isWhitespacecompare char codes.consume()says both fast paths mirror it and must change with it.Behaviour: every state transition still happens in
consume(), and a run never leaves its state, soisSafeBoundary()cannot change inside a run. Emitted bytes, resolver positions and order, andfinish()errors are unchanged. On a 207 KB page,consume()calls drop from 207,667 to 24,065.Scope: only requests with deferred data, on the Node and worker stream paths (both use this coordinator). Requests without deferred data keep the #9016 pass-through. No API, config or output change.
Trade-off: non-React inputs dense in chars that still need
consume()(for example<every 2 chars in a script) are 9-24% slower in a micro-benchmark. React output does not have these shapes.中文摘要
defer()或 loader 数据中的 Promise)时,DeferredScriptOutputCoordinator.writeReact会把 React 输出的每个字符(包括约 24 KB 的模板 shell)逐个送进 HTML tokenizer,以找到 resolver 脚本的安全插入点。perf(runtime): skip deferred script tokenizing when no resolver can be queued #9016 只在不会有 resolver 时跳过这一步。下文两个 deferred 页面上,coordinator 每个响应约耗时 2.0 ms 和 7.6 ms。consumeRun(),整段消费只会追加到当前 token 的字符:文本跳到下一个<,属性值跳到闭合引号,ASCII 标签名和属性名整段转小写,script/style/textarea 原始文本在没有未完成的</tag匹配时跳到下一个<($RC等续传调用的检测按逐字符结果精确更新),注释、声明等跳到下一个>。consumeAttributes()一次写入完整的name="value"属性。字符类判断改为比较 char code。consume()中完成,输出字节、resolver 插入位置和顺序、finish()报错都不变。/bench/deferred每请求服务端 CPU -16.2%(-1.19 ms),/bench/deferred-large-19.9%(-4.30 ms),对照页/bench/small+0.1%,在噪声内。Benchmark
Environment: Node v22.21.1, Intel Xeon Platinum 8457C, 64 logical CPUs, shared machine (load average 13.7-24 at the start). Each server is pinned to one logical CPU with
taskset, and a guard process keeps other tasks off its hyperthread sibling while measuring.Method: A =
main(27beabb) build, B = this branch (ba6eefc) build of the same bench app, served side by side byNODE_ENV=production modern serve. A and B are loaded in parallel, with their CPUs swapped every other round. 6 x 10 s rounds at 32 keep-alive connections per server, after a 10 s warm-up. Primary metric: server CPU ms per request (utime + stime of the server process tree from/proc, divided by completed requests). Medians over rounds, plus the median [min…max] of paired per-round deltas. Functional checks passed on both servers, all runs had 0 non-2xx and 0 errors, and response sizes were identical.Noise floor: an A/A run (main vs main) gave CPU/req median deltas within ±0.6% on every URL and per-round paired deltas within ±2.1%. p99 moves by up to ±12% between identical servers, so it is not used as evidence.
/bench/deferred/bench/deferred-large/bench/small(control, no deferred data)Both deferred results are more than 25 times the ±0.6% A/A floor, and every round, on both CPU assignments, is well beyond the ±2.1% A/A per-round range.
Where the gain applies:
/bench/smallis unchanged, within the A/A floor.Supplementary micro-benchmark (outside the harness):
writeReactof both dists in one process on one pinned CPU, replaying the bodies captured from the two servers (resolver script removed, 2048-char chunks). 9 interleaved rounds, per stream:/bench/deferred/bench/deferred-largeThe coordinator saves 1.16 ms and 3.68 ms per stream, against 1.19 ms and 4.30 ms per request end to end. The extra ~0.6 ms on the large page is probably less GC work (on a 207 KB page, 399 GCs on
mainvs 110 on this branch per 200 coordinator runs). I did not profile it.Earlier micro-benchmarks (same setup, output equality asserted first). On synthetic React 19 pages the coordinator alone went from 1.136 to 0.434 ms (41 KB) and from 5.319 to 2.212 ms (207 KB), 2.4-2.8x over 3 runs, reproduced by reviewers. Through
createReadableStreamFromElementwith 4 deferred keys (stream post-processing only, 11 rounds):Node with replayed chunks: -42.0% / -47.0%. Over 3 runs the React-render rows were -27.6% to -30.4% (reviewer: -25.7% to -30.3%).
Not every input gets faster. Chars that still go through
consume()also pay for aconsumeRun()call that returns at once. React does not produce these shapes (serializeJsonescapes<in data scripts). 16 KB chunks, resolver pending, 9 rounds:<script>+a<x 80,000</scrip_x 20,000 in a script<!---->x 20,000Dense tiny tags,
a < btext and continuation scripts got 9%, 43% and 53% faster. An early return for thetag-open,markup-declarationandraw-end-tagstates did not help (+0.8% to +4.3% on the slow inputs), so it is not included.Bench app and harness
tests/integration/ssr/fixtures/streaming(streaming SSR, nested routes with loaders) plus untracked bench files: 127 routes on one entry, 122 with a loader. Every response carries a ~24 KB template (route manifest, 130rel="prefetch"links, rspack runtime)./bench/deferred: the loader returns{ immediate, deferred: Promise }(15 ms), rendered with<Suspense>/<Await>. After the shell come the resolver script (16 KB) and a hidden segment with 280 list items (39.5 KB) completed by$RC./bench/deferred-large: the same with 1400 items (200.6 KB, 80 KB resolver script)./bench/small: small page, plain loader, no deferred data.pnpm --filter @modern-js/runtime --filter @modern-js/server-core --filter @modern-js/runtime-utils build, thenNODE_ENV=production modern buildof the app (the SSR bundle inlines the runtime). Only the branch bundle containsconsumeRun.httpkeep-alive client on separate CPUs with a desktop Chrome User-Agent (so the runtime streams). It drains in-flight requests at the end of each window. CPU time comes from/proc/<pid>/statof the server process tree.Related Links
DeferredScriptOutputCoordinator.markNoResolvers()pass-through for requests without deferred data. This PR speeds up the remaining case.Validation Evidence
All checks ran on the final build of ba6eefc. Checks without a repo command used temporary scripts outside the repo.
mainand branch dists run in lockstep, comparing emitted chunks, thrown errors and the full internal tokenizer state after every operation.$RC/$RR/$RX, table, SVG and MathML segments, CJK), 39 handcrafted edge cases, 3000 generated documents per run.isAsciiAlpha/isWhitespacematch the old RegExp helpers for all 65,536 UTF-16 code units.createReadableStreamFromElement(Node and worker): byte-identical output for both builds across 290 runs each (3 pages, 4 byte chunkings including split UTF-8, deferred and rejected fixtures, several resolve timings, real React renders).cd tests && npx rstest run integration/ssr/tests/streaming: 22/22 passed.npx rstest runinpackages/runtime/plugin-runtime: 54 passed.pnpm --filter @modern-js/runtime build,tsc --noEmit,rs lintandrs fmton the changed files,pnpm check-changeset,pnpm check-test-governance --base origin/main --head HEAD: all pass.pnpm test:ut/pnpm test:frameworksuites. The E2E bench does not cover the worker/edge path, string SSR, the bot (all-ready) path or RSC. The GC effect was not profiled.Condensed differential harness (fuzz-mini.cjs)
Build
@modern-js/runtimeonmainand on this branch, then pass bothpackages/runtime/plugin-runtimedirectories as absolute paths:Retained Tests and Exceptions
No test files or fixtures are added or changed. Per the test governance rules, equivalence was shown with temporary scripts outside the repo. Since #9236 nothing in the repo exercises the coordinator directly, and the streaming integration tests cover the user flows. The condensed harness lets reviewers and future changes to
consume()rerun the differential check. No exceptions are requested.Checklist
pnpm run changeif published package behavior changes. (@modern-js/runtimepatch)🤖 Generated with Claude Code