Repository navigation
Conversation
…he entries as bytes
The SSR cache piped every rendered chunk through createTransformStream(),
which decoded it to a string and encoded it again only to pass it on. It
decoded each chunk on its own, so a character split across chunks reached
the client as U+FFFD. Every cache hit JSON.parse()d the whole entry and
encoded the HTML again, and every write JSON.stringify()d it.
- Pass the rendered bytes through an identity TransformStream. The HTML for
the cache is still decoded on the side with `stream: true`. Chunks that
are an ArrayBuffer or another ArrayBufferView are passed on as a
Uint8Array, as the decoding and encoding used to do.
- The default in-memory storage keeps each page as one byte array: the
cursor as a float64, followed by the bytes as they were rendered. Hits
and stale responses send those bytes (Response copies them), without
JSON or encoding. The memory container sizes the entry by its byte
length. Requests that share a render get the same bytes.
- The bytes are copied into a few slabs of growing size while they pass,
as the client may transfer the buffers it reads, then into the entry.
One copy per chunk cost much more for streams of many small chunks.
- Custom containers keep reading and writing the JSON of { val, cursor },
so entries already stored, e.g. in Redis, keep working. A JSON string
found in the default storage is still read as before.
- Remove the internal createTransformStream / transformResponse helpers,
which are no longer used and are not exported by the package.
- Run the hit, stale and expired tests against the default storage too,
which no test covered. The hit test now caches a page of about 120 KB
in chunks that split an emoji.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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
Problem (on
main; PR4 does not change this part)createTransformStream()decoded every rendered chunk and encoded it again, only to pass it on.stream: true, so a multi-byte character split across chunks became U+FFFD in miss and expired responses.JSON.parse()on the whole{ val, cursor }entry and encoded the HTML again. Every write ranJSON.stringify().Change (
plugins/render/ssrCache.ts)TransformStreamforwards the rendered bytes.stream: true, for theno-ssr-cache/renderLevelchecks and for custom containers.BufferSourcetypes are forwarded as aUint8Arrayover the same bytes.customContainer). A page is oneUint8Array: an 8-byte float64 cursor followed by the rendered bytes.Responsecopies them.byteLength(perf(runtime-utils): avoid json serialization when sizing memory cache entries #9013).{ val, cursor }, byte-identical tomain. Existing entries (e.g. in Redis) and rolling deploys work in both directions.createTransformStream/transformResponseare removed. Nothing uses them, and no entry point (.,./node,./hono) exports them:src/index.tsre-exports onlycreateErrorHtml,onErrorandErrorDigestfrom utils.Behaviour changes and scope
mainreplaced them with U+FFFD. Custom-container hits still replay the decoded HTML.heapUsed. Memory per page drops, by up to half for pages with non-Latin-1 characters.中文摘要
问题(
main上,PR4 未改动这部分):createTransformStream()把每个渲染 chunk 解码再编码,只为原样透传。stream: true,跨 chunk 的多字节字符会在 miss / expired 响应里变成 U+FFFD。这是潜在问题,Modern.js 自带的 Node 渲染器按字符边界切块。{ val, cursor }做JSON.parse(),再把 HTML 编码一次。JSON.stringify()。改动:
TransformStream原样透传字节。stream: true),用于no-ssr-cache/renderLevel判断和自定义容器。ArrayBuffer、DataView等 chunk 转成同一段内存上的Uint8Array。customContainer)把每个页面存成一个Uint8Array:8 字节 float64 cursor 加渲染出的原始字节。byteLength计量。main逐字节一致,Redis 等已有条目和滚动发布双向兼容。createTransformStream/transformResponse。行为变化:
heapUsed)。Benchmark
Environment: Node v22.21.1 (micro-benchmarks also on v24.22.2), Intel Xeon Platinum 8457C, 64 logical CPUs, on a shared machine. Each server is pinned to one logical CPU with
taskset, and a guard keeps other tasks off that CPU's sibling hyperthread.Method:
main(27beabb) and B is a build of this branch. Both run side by side undermodern servein production./proc, divided by completed requests.Noise floor. In an A/A run (
mainvsmain), CPU/req medians were within ±0.6% on every URL (/bench/cached-large −0.5%), and every paired round within ±2.1%. Cache-herd A/A: sustained CPU/req ±2%, req/s ±2.5%. p99 moved up to ±12%, so it is not cited alone.Attribution. This branch contains PR4, so run 1 measures PR4 and PR5 together. Run 3 compares
mainwith PR4 alone, in the same session and with the same URL order.E2E run 1:
mainvs this branch (PR4 + PR5)This PR's own share (CPU ms/req)
The share is (B/A in run 1) / (B/A in run 3) − 1:
E2E run 2: fresh servers, controls first (
mainvs this branch)Cache herd (10 expired bursts × 64 requests, then 20 s sustained at C=64)
Coalescing is unchanged from PR4 alone: 1 render per burst, and 19 in the sustained run. In the sustained run, this PR's own share is about −25% / −22% CPU/req and +32% / +29% req/s.
Where the gain applies
matchCacheControlreturnsundefined, sossrRendercalls the request handler directly.--cpu-profof the cached-large hit (not a measurement):main, the time goes togetCacheResultself time, i.e.JSON.parseof the entry (24.8%), undicitoUSVString(8.0%) and UTF-8 encoding (encode9.0% +encodeUtf8String7.4%).Responsecopying the bytes (extractBody13.3%) andwritev(13.9%).E2E run 3 in full:
mainvs PR4 only (isolation control)Bench app and commands
App. The bench app is
tests/integration/ssr/fixtures/streaming(streaming SSR, nested routes with loaders) plus untracked generated files. It has 127 routes and a ~24 KB template.Cache config.
server/cache.tsexports onlycacheOption, so the default memory storage is used:URLs.
/bench/cachedand/bench/cached-nosware ~26 KB pages, and their loader sleeps 20 ms./bench/cached-largeis ~196 KB: 1000 list items with CJK text, plus_ROUTER_DATA. It is a hit on every request after the first./bench/large(the same list page without the cache) and/bench/smallare the uncached controls.Load generator. A Node
httpkeep-alive client in a closed loop. Functional checks run on both servers before every measurement.Commands (temporary scripts outside the repo):
ab.sh <lane> <out> /bench/cached-large /bench/cached /bench/cached-nosw /bench/large /bench/small./bench/small /bench/large /bench/cached-large.cache-herd.sh <lane> <out>with the defaults.Micro-benchmarks
Method:
Bufferchunks unless noted. Pages are realistic markup plus_ROUTER_DATA. The custom container is aMap.main(default storage): about 70–85 µs at 50 KB, 345–390 µs at 210 KB and 1.1–1.2 ms at 210 KB CJK, on both Node versions.main.mainon Node 22 for 128 B chunk streams, which this PR more than offsets.Related Links
Uint8Arrayentries bybyteLength. The new default-storage entry relies on this.Validation Evidence
cd packages/server/core && npx rstest run: 162 passed, 0 failed.npx tsc --noEmit -p tsconfig.json: OK.rs fmt/rs linton the changed files: clean.pnpm check-changeset: exit 0.pnpm check-test-governance --base origin/main --head HEAD: passed.pnpm --filter @modern-js/server-core build: OK. The builtssrCache.jsis identical to the benchmarked build, and notransformStreamis left indist.cd tests && npx rstest run integration/ssr/tests/base.test.ts: 10 passed, 2 skipped.customContainer, then reverted): same result.mainvs branch. 913/913 checks pass. They cover:getRenderHandler. 3930/3930 checks pass. Inputs:Uint8Array, pooledBuffer,ArrayBuffer,DataViewandUint16Arraychunks;new Response(Uint8Array)copies the bytes (also checked on 22.16.0), so the cached entry stays intact when the client transfers a chunk.ArrayBuffer/DataViewchunks over HTTP. Both the miss and the hit are 200 with the full body.maincorrupts the miss with U+FFFD.main.main.ssrCache.test.ts. The suite fails if the full slab is not pushed, the slab's remainder is not filled, or the last slab is left out of the entry. It also fails for each of 3 entry-format mutants.x-render-cachesequence pass on both servers;Content-Typeistext/html; charset=UTF-8on both;mainand branch bodies differ only in the server port and the render timestamp.Uint8Arraychunks, foreign values in the default namespace, and one copy per chunk (now slabs).pnpm test:ut/test:framework/test:builder. The change is limited to server-core's SSR cache.Retained Tests and Exceptions
packages/server/core/tests/plugins/ssrCache.test.tswas updated. No test files or fixtures were added.describe.each). The default storage is used whenever nocustomContaineris set, and it is where the entry format changed, yet nothing covered it before.x-render-cache+ body) instead of container internals, so they do not depend on the storage format.Checklist
pnpm run changeif published package behavior changes. (@modern-js/server-corepatch)🤖 Generated with Claude Code