Skip to content

perf(runtime): skip deferred script tokenizing when no resolver can be queued - #9016

Merged
GiveMe-A-Name merged 3 commits into
mainfrom
perf/stream-ssr-skip-deferred-coordinator
Oct 20, 2026
Merged

GiveMe-A-Name merged 3 commits into
mainfrom
perf/stream-ssr-skip-deferred-coordinator

Conversation

@deepcoldy

Copy link
Copy Markdown
Contributor

Summary

Every streamed SSR response, both Node (createReadableStream.ts) and edge (createReadableStream.worker.ts), writes all of React's output through DeferredScriptOutputCoordinator.writeReact. That method feeds every character into a small HTML tokenizer so that resolver scripts for defer() 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 reads activeDeferreds / deferredScriptKeys synchronously, 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, enqueueResolver is never called. With an empty queue, the existing writeReact emits each chunk exactly once and unchanged, finish() cannot throw, and markShellFinished() / abort() have no effect on the output. In that case the tokenizer's work is simply thrown away.

Changes:

  • hasDeferredResolvers(entries, deferredScriptKeys) in deferredScript.ts answers whether enqueueFromEntries would emit anything. It shares the key-selection helper with enqueueFromEntries.
  • Both call sites call enqueueFromEntries only when that check is true. Otherwise they call the new coordinator.markNoResolvers(), which makes writeReact forward chunks as-is. The existing closed / empty-chunk handling stays in front of it, so abort() and finish() still stop output.
  • Guard: in this mode flushResolvers() never emits. A resolver that shows up anyway (a contract violation) is therefore never injected at an unknown position, and the existing finish() error reports it.
  • This covers pages without loaders and pages whose loaders return plain data. A loader that returns a plain object is still wrapped in DeferredData, so checking entries.length > 0 alone would miss most real apps.
  • Small exact fast path for pages that do stream deferred data: inside <script> / <style> text, when rawTextSearch is empty and the char is not <, consumeRawText returns early. The tracking of $RC / $RS / ... continuation calls still runs first. The skipped getSuffix call 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 the origin/main dist and the "after" column is this branch's dist. Both are loaded side by side in one process and drive the real exported createReadableStreamFromElement (Node and worker variants). React output is replaced by fixed 4 KB byte chunks through a processStream extender. The worker uses a stubbed renderSSRStream. 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.

scenario before after change
node: suspense-heavy 365 KB page (60 KB shell), no loader data 14.34 ms 2.93 ms -79.6% (4.9x)
worker: suspense-heavy 365 KB page (60 KB shell), no loader data 12.72 ms 1.77 ms -86.1% (7.2x)
node: suspense-heavy 365 KB page (60 KB shell), loader data, no defer 14.37 ms 3.19 ms -77.8% (4.5x)
worker: suspense-heavy 365 KB page (60 KB shell), loader data, no defer 13.34 ms 1.77 ms -86.7% (7.5x)
node: suspense-heavy 365 KB page (60 KB shell), 3 deferred keys 14.31 ms 13.38 ms -6.5% (1.1x)
worker: suspense-heavy 365 KB page (60 KB shell), 3 deferred keys 13.08 ms 11.74 ms -10.2% (1.1x)
node: shell-heavy 356 KB page (259 KB shell), no loader data 34.88 ms 24.14 ms -30.8% (1.4x)
worker: shell-heavy 356 KB page (259 KB shell), no loader data 21.49 ms 11.45 ms -46.7% (1.9x)
node: shell-heavy 356 KB page (259 KB shell), loader data, no defer 35.86 ms 24.84 ms -30.7% (1.4x)
worker: shell-heavy 356 KB page (259 KB shell), loader data, no defer 21.41 ms 11.41 ms -46.7% (1.9x)
node: shell-heavy 356 KB page (259 KB shell), 3 deferred keys 35.10 ms 35.05 ms -0.1% (1.0x)
worker: shell-heavy 356 KB page (259 KB shell), 3 deferred keys 21.80 ms 20.60 ms -5.5% (1.1x)

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-buffer PR. 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 (writeReact over the page in 4 KB string chunks, median of 3 runs):

page before (tokenizing) after, deferred data present (tokenizing + raw-text fast path) after, no resolvers (markNoResolvers)
markup-heavy 356 KB, 13% script/style text 10.84 ms 10.08 ms (-7%) < 0.01 ms
data-heavy 362 KB, 45% script/style text 11.72 ms 8.65 ms (-26%) < 0.01 ms
Benchmark scripts

Setup: copy the origin/main build of packages/runtime/plugin-runtime/dist to ./dist and this branch's build to ./new-fast/dist. Both directories get a node_modules symlink to packages/runtime/plugin-runtime/node_modules.

Run:

  • ./run3.sh: end-to-end table, 3 processes of NODE_ENV=production node bench.cjs
  • node coordinator-bench.cjs ./ base && node coordinator-bench.cjs ./new-fast branch
  • NODE_ENV=production node e2e-diff.cjs and node coordinator-diff.cjs: differential checks

harness.cjs

// Loads a built @modern-js/runtime dist (baseline copy or branch build) and
// drives the real createReadableStreamFromElement (Node + worker variants).
const Module = require('module');
const { Readable } = require('stream');

let workerChunks = [];
const fakeRender = {
  renderSSRStream: async () =>
    Object.assign(
      new ReadableStream({
        start(controller) {
          for (const chunk of workerChunks) controller.enqueue(new Uint8Array(chunk));
          controller.close();
        },
      }),
      { allReady: Promise.resolve() },
    ),
};
const originalLoad = Module._load;
Module._load = function (request, parent, isMain) {
  if (request === '@modern-js/render/ssr') return fakeRender;
  return originalLoad.call(this, request, parent, isMain);
};

const SHELL_BEFORE = '<html><body><div id="root">';
const SHELL_AFTER = '</div></body></html>';
const HTML_TEMPLATE = `${SHELL_BEFORE}<!--<?- html ?>-->${SHELL_AFTER}`;

module.exports = function load(root) {
  const req = Module.createRequire(`${root}/dist/cjs/index.js`);
  const ctx = req('./core/context/index.js');
  const nodeMod = req('./core/server/stream/createReadableStream.js');
  const workerMod = req('./core/server/stream/createReadableStream.worker.js');
  const common = req('./common.js');
  const { storage } = req('@modern-js/runtime-utils/node');
  const React = req('react');

  const options = {
    runtimeContext: {
      ssrContext: { request: { pathname: '/', url: 'http://localhost/' } },
      routes: [],
    },
    config: {},
    ssrConfig: {},
    htmlTemplate: HTML_TEMPLATE,
    entryName: 'main',
    rscRoot: React.createElement('div'),
    onError: () => {},
  };

  const run = (create, element, deferreds) =>
    storage.run(
      {
        activeDeferreds: deferreds?.activeDeferreds ?? new Map(),
        deferredScriptKeys: deferreds?.deferredScriptKeys ?? new Map(),
      },
      () => create(new Request('http://localhost/'), element, options),
    );

  const setExtender = processStream =>
    ctx.setGlobalInternalRuntimeContext({
      hooks: {
        extendStreamSSR: { call: () => (processStream ? [{ processStream }] : []) },
      },
    });

  return {
    React,
    common,
    SHELL_BEFORE,
    SHELL_AFTER,
    // Node variant fed with exact byte chunks (React output is discarded).
    async nodeChunks(chunks, deferreds) {
      setExtender(reactStream => {
        reactStream.resume();
        return Readable.from(chunks);
      });
      const stream = await run(
        nodeMod.createReadableStreamFromElement,
        React.createElement('div'),
        deferreds,
      );
      return Buffer.from(await new Response(stream).arrayBuffer());
    },
    // Node variant rendering a real React element end to end.
    async nodeElement(element, deferreds) {
      setExtender(undefined);
      const stream = await run(nodeMod.createReadableStreamFromElement, element, deferreds);
      return Buffer.from(await new Response(stream).arrayBuffer());
    },
    // Worker variant fed with exact byte chunks via a fake renderSSRStream.
    async workerChunks(chunks, deferreds) {
      workerChunks = chunks;
      const stream = await run(
        workerMod.createReadableStreamFromElement,
        React.createElement('div'),
        deferreds,
      );
      return Buffer.from(await new Response(stream).arrayBuffer());
    },
  };
};

page.cjs

// Builds a realistic streamed SSR page (React 19 markup shapes) and the
// matching deferred-data fixtures.
const css = Array.from({ length: 200 }, (_, i) => `.c${i}{color:#${(i * 4021).toString(16).padStart(6, '0').slice(0, 6)};margin:${i % 7}px;}`).join('');
const routerData = JSON.stringify({
  loaderData: {
    page: { items: Array.from({ length: 300 }, (_, i) => ({ id: i, title: `Product ${i}`, price: i % 100, tags: ['a', 'b', 'c'], description: `Description for product ${i} with some extra text` })) },
  },
});

function card(i) {
  return `<div class="card c${i % 200}" data-id="${i}"><img src="/static/img/${i}.png" alt="Product ${i}" loading="lazy"/><a href="/product/${i}" title="Open product ${i}">Product <!-- -->${i}</a><span class="price">¥<!-- -->${i % 100}<!-- -->.99</span><p>Lightweight description text for item ${i}, rendered on the server. 中文描述</p></div>`;
}

// Returns { shell, afterShell } where shell is what React emits before the
// shell end marker and afterShell is the streamed Suspense content.
function makePage({ shellCards, lateCards }) {
  const shell =
    `<div id="app"><header class="top"><nav>${Array.from({ length: 20 }, (_, i) => `<a href="/c/${i}">Category ${i}</a>`).join('')}</nav></header>` +
    `<style>${css}</style>` +
    `<main>${Array.from({ length: shellCards }, (_, i) => card(i)).join('')}</main>` +
    `<!--$?--><template id="modern-js-B:0"></template><div class="skeleton">loading</div><!--/$-->` +
    `<script>window._ROUTER_DATA = ${routerData}</script></div>`;
  const afterShell =
    `<div hidden id="modern-js-S:0"><section>${Array.from({ length: lateCards }, (_, i) => card(10000 + i)).join('')}</section></div>` +
    `<script>$RC=function(b,c,e){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(e)b.data="$!",a.setAttribute("data-dgst",e);else{e=b.parentNode;a=b.nextSibling;var f=0;do{if(a&&8===a.nodeType){var d=a.data;if("/$"===d)if(0===f)break;else f--;else"$"!==d&&"$?"!==d&&"$!"!==d||f++}d=a.nextSibling;e.removeChild(a);a=d}while(a);for(;c.firstChild;)e.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}};$RC("modern-js-B:0","modern-js-S:0")</script>`;
  return { shell, afterShell };
}

function deferredFixtures(count) {
  const data = {};
  const keys = [];
  for (let i = 0; i < count; i++) {
    data[`key${i}`] = new Promise(resolve => setTimeout(() => resolve({ value: i, text: `deferred ${i}` }), 1));
    keys.push(`key${i}`);
  }
  return {
    activeDeferreds: new Map([['page', { data, pendingKeys: keys }]]),
    deferredScriptKeys: new Map([['page', keys]]),
  };
}

function chunk(buf, size) {
  const out = [];
  for (let i = 0; i < buf.length; i += size) out.push(buf.subarray(i, i + size));
  return out;
}

module.exports = { makePage, deferredFixtures, chunk };

bench.cjs

// End-to-end: real createReadableStreamFromElement (Node + worker), baseline dist vs branch dist.
// Usage: NODE_ENV=production node bench.cjs [branchDistRoot]
const load = require('./harness.cjs');
const { makePage, chunk } = require('./page.cjs');
const base = load('./');
const next = load(process.argv[2] || './new-fast');
const MARK = base.common.ESCAPED_SHELL_STREAM_END_MARK;

// Deferred fixtures are rebuilt per request (fresh Maps), with already-settled
// promises so resolver placement is deterministic.
const fixtures = {
  'no loader data': () => undefined,
  'loader data, no defer': () => ({
    activeDeferreds: new Map([['page', { data: { items: [1, 2, 3] }, pendingKeys: [] }]]),
    deferredScriptKeys: new Map([['page', []]]),
  }),
  '3 deferred keys': () => {
    const keys = ['user', 'recommendations', 'reviews'];
    const data = Object.fromEntries(keys.map((k, i) => [k, Promise.resolve({ k, i })]));
    return {
      activeDeferreds: new Map([['page', { data, pendingKeys: keys }]]),
      deferredScriptKeys: new Map([['page', keys]]),
    };
  },
};

async function measure(fn, { warmup = 10, rounds = 5, iterations = 20 } = {}) {
  for (let i = 0; i < warmup; i++) await fn();
  const results = [];
  for (let r = 0; r < rounds; r++) {
    const start = process.hrtime.bigint();
    for (let i = 0; i < iterations; i++) await fn();
    results.push(Number(process.hrtime.bigint() - start) / 1e6 / iterations);
  }
  results.sort((a, b) => a - b);
  return results[Math.floor(results.length / 2)];
}

const scenarios = [];

async function compare(name, makeRun) {
  const a = makeRun(base);
  const b = makeRun(next);
  const [oa, ob] = [await a(), await b()];
  if (!oa.equals(ob)) throw new Error(`${name}: outputs differ`);
  scenarios.push({ name, a, b });
}

async function report({ name, a, b }) {
  const before = [];
  const after = [];
  for (let k = 0; k < 3; k++) {
    before.push(await measure(a));
    after.push(await measure(b));
  }
  const med = xs => xs.sort((x, y) => x - y)[1];
  const mb = med(before);
  const ma = med(after);
  console.log(`| ${name} | ${mb.toFixed(2)} ms | ${ma.toFixed(2)} ms | ${(((ma - mb) / mb) * 100).toFixed(1)}% |`);
}

(async () => {
  console.log(`Node ${process.version}, nproc ${require('os').cpus().length}`);
  const pages = {
    'suspense-heavy 365 KB page (60 KB shell)': makePage({ shellCards: 50, lateCards: 950 }),
    'shell-heavy 356 KB page (259 KB shell)': makePage({ shellCards: 700, lateCards: 300 }),
  };
  console.log('| scenario | before | after | change |');
  console.log('| --- | --- | --- | --- |');
  for (const [pageName, { shell, afterShell }] of Object.entries(pages)) {
    const chunks = chunk(Buffer.from(`${shell}${MARK}${afterShell}`), 4096);
    for (const [fixtureName, fixture] of Object.entries(fixtures)) {
      for (const variant of ['nodeChunks', 'workerChunks']) {
        await compare(`${variant === 'nodeChunks' ? 'node' : 'worker'}: ${pageName}, ${fixtureName}`, h => () => h[variant](chunks, fixture()));
      }
    }
  }
  // global warm-up so every code path is optimized before any timing
  for (let i = 0; i < 30; i++) for (const { a, b } of scenarios) { await a(); await b(); }
  for (const scenario of scenarios) await report(scenario);
})();

run3.sh

#!/usr/bin/env bash
# Runs bench.cjs 3 times in fresh processes and prints the per-row median.
cd "$(dirname "$0")"
for i in 1 2 3; do NODE_ENV=production node bench.cjs "$@" | grep '^| [nw]' > ./run$i.txt; done
python3 - <<'PY'
import re, statistics
rows = {}
order = []
for i in (1, 2, 3):
    for line in open(f'./run{i}.txt'):
        cells = [c.strip() for c in line.strip().strip('|').split('|')]
        name, before, after = cells[0], float(cells[1].split()[0]), float(cells[2].split()[0])
        if name not in rows:
            rows[name] = ([], []); order.append(name)
        rows[name][0].append(before); rows[name][1].append(after)
print('| scenario | before | after | change |')
print('| --- | --- | --- | --- |')
for name in order:
    b = statistics.median(rows[name][0]); a = statistics.median(rows[name][1])
    print(f'| {name} | {b:.2f} ms | {a:.2f} ms | {(a - b) / b * 100:+.1f}% ({b / a:.1f}x) |')
PY

coordinator-bench.cjs

// Coordinator-only cost for ~360 KB pages written in 4 KB string chunks.
// Usage: node coordinator-bench.cjs <distRoot> [label]
const { makePage } = require('./page.cjs');
const root = process.argv[2];
const { DeferredScriptOutputCoordinator } = require(`${root}/dist/cjs/core/server/stream/deferredScriptOutputCoordinator.js`);

function toChunks(page) {
  const chunks = [];
  for (let i = 0; i < page.length; i += 4096) chunks.push(page.slice(i, i + 4096));
  return chunks;
}

const { shell, afterShell } = makePage({ shellCards: 700, lateCards: 300 });
const markupPage = shell + afterShell;
// Same size, but a third of it is an inline data script (large loader data).
const data = JSON.stringify(Array.from({ length: 1200 }, (_, i) => ({ id: i, title: `Product ${i}`, description: `Description for product ${i} with some extra text` })));
const small = makePage({ shellCards: 450, lateCards: 200 });
const dataPage = `${small.shell}<script>window._DATA = ${data}</script>${small.afterShell}`;

function rawTextShare(page) {
  let n = 0;
  page.replace(/<(script|style)[^>]*>([\s\S]*?)<\/\1>/g, (_, __, body) => { n += body.length; return ''; });
  return n / page.length;
}

function run(chunks, total, passThrough) {
  let out = 0;
  const c = new DeferredScriptOutputCoordinator(s => { out += s.length; });
  if (passThrough) c.markNoResolvers();
  c.markShellFinished();
  for (const ch of chunks) c.writeReact(ch);
  c.finish();
  if (out !== total) throw new Error('bad output');
}

function measure(fn, iterations = 30, rounds = 9) {
  for (let i = 0; i < 30; i++) fn();
  const rs = [];
  for (let r = 0; r < rounds; r++) {
    const s = process.hrtime.bigint();
    for (let i = 0; i < iterations; i++) fn();
    rs.push(Number(process.hrtime.bigint() - s) / 1e6 / iterations);
  }
  rs.sort((a, b) => a - b);
  return rs[Math.floor(rs.length / 2)];
}

const label = process.argv[3] || root;
for (const [name, page] of [['markup-heavy', markupPage], ['data-heavy', dataPage]]) {
  const chunks = toChunks(page);
  const line = [`${label} ${name} (${(Buffer.byteLength(page) / 1024).toFixed(0)} KB, ${(rawTextShare(page) * 100).toFixed(0)}% script/style text)`];
  line.push(`tokenizing ${measure(() => run(chunks, page.length, false)).toFixed(2)} ms`);
  if (DeferredScriptOutputCoordinator.prototype.markNoResolvers) {
    line.push(`pass-through ${measure(() => run(chunks, page.length, true)).toFixed(3)} ms`);
  }
  console.log(line.join(' | '));
}

coordinator-diff.cjs

// Differential check of DeferredScriptOutputCoordinator: baseline dist vs branch dist.
// 1) tracking mode with resolvers enqueued at many points must emit identical chunk sequences
// 2) branch pass-through (markNoResolvers) must emit exactly what baseline emits with no resolvers
const { makePage } = require('./page.cjs');
const load = root => require(`${root}/dist/cjs/core/server/stream/deferredScriptOutputCoordinator.js`).DeferredScriptOutputCoordinator;
const Base = load('./');
const Next = load(process.argv[2] || './new-fast');

const small = makePage({ shellCards: 3, lateCards: 2 });
const docs = [
  small.shell + small.afterShell,
  '<!DOCTYPE html><html><head><title>t</title><style>a::before{content:"</style"}</style><STYLE>b{}</STYLE ></head><body>',
  '<script>const s = "</scr" + "ipt>"; if (a < b && c <\/script) {}</script ><script type="module">x</SCRIPT>',
  '<textarea>a < b </textarea\n><title>x</title><xmp><p></xmp><iframe><b></iframe><noembed>a</noembed><noframes>b</noframes>',
  '<div hidden id="modern-js-S:1"><span>x</span></div><script>window.x = 1</script><script>$RC("modern-js-B:1","modern-js-S:1")</script><p>after</p>',
  '<table hidden><tbody id="modern-js-S:2"><tr><td>x</td></tr></tbody></table><script>$RS("a","b")</script>',
  '<svg aria-hidden="true" style="display:none" id="modern-js-S:3"><circle/></svg><script>$RX("b",1)</script>',
  '<!-- comment <script> --><!----><!---><![CDATA[x]]><?xml x?><a href="/x?a=1&b=2" title=\'q"\' data-x=unq>t</a><br/><img src=x>',
  '<p>中文 🚀 <b>粗体</b></p><div class="a>b">x</div><input value="<script>">',
];

let seed = 7;
const rand = n => ((seed = (seed * 1103515245 + 12345) % 2 ** 31), seed % n);

function runCase(Coordinator, chunks, plan, passThrough) {
  const out = [];
  const c = new Coordinator(s => out.push(s));
  if (passThrough) c.markNoResolvers();
  let err = null;
  try {
    if (plan.shellAt === -1) c.markShellFinished();
    chunks.forEach((chunk, i) => {
      for (const r of plan.resolvers.filter(r => r.at === i)) c.enqueueResolver(`<script data-r="${r.id}"></script>`);
      c.writeReact(chunk);
      if (plan.shellAt === i) c.markShellFinished();
    });
    for (const r of plan.resolvers.filter(r => r.at >= chunks.length)) c.enqueueResolver(`<script data-r="${r.id}"></script>`);
    c.finish();
  } catch (e) {
    err = e.message;
  }
  return JSON.stringify({ out, err });
}

let trackingCases = 0;
let passCases = 0;
let failures = 0;
for (const doc of docs) {
  const chunkings = [];
  for (const size of [1, 2, 3, 5, 8, 13, 64, doc.length]) {
    const c = [];
    for (let i = 0; i < doc.length; i += size) c.push(doc.slice(i, i + size));
    chunkings.push(c);
  }
  for (let r = 0; r < 100; r++) {
    const cuts = [...new Set(Array.from({ length: 1 + rand(10) }, () => rand(doc.length)))].sort((a, b) => a - b);
    const c = [];
    let prev = 0;
    for (const cut of [...cuts, doc.length]) {
      if (cut > prev) c.push(doc.slice(prev, cut));
      prev = Math.max(prev, cut);
    }
    chunkings.push(c);
  }
  for (const chunks of chunkings) {
    // no resolvers: pass-through must equal baseline tracking output
    const plan0 = { shellAt: -1, resolvers: [] };
    if (runCase(Base, chunks, plan0, false) !== runCase(Next, chunks, plan0, true)) failures++;
    if (runCase(Base, chunks, plan0, false) !== runCase(Next, chunks, plan0, false)) failures++;
    passCases++;
    // tracking with resolvers at random points
    for (let k = 0; k < 6; k++) {
      const plan = {
        shellAt: rand(3) === 0 ? -1 : rand(chunks.length),
        resolvers: Array.from({ length: 1 + rand(3) }, (_, id) => ({ id, at: rand(chunks.length + 1) })),
      };
      if (runCase(Base, chunks, plan, false) !== runCase(Next, chunks, plan, false)) failures++;
      trackingCases++;
    }
  }
}
console.log(`no-resolver cases: ${passCases}, tracking cases with resolvers: ${trackingCases}, mismatches: ${failures}`);

e2e-diff.cjs

// End-to-end differential check: baseline dist vs branch dist through the real
// createReadableStreamFromElement (Node + worker) for several deferred fixtures
// and chunkings. Settled promises keep resolver placement deterministic.
const load = require('./harness.cjs');
const { makePage, chunk } = require('./page.cjs');
const base = load('./');
const next = load(process.argv[2] || './new-fast');
const MARK = base.common.ESCAPED_SHELL_STREAM_END_MARK;

const fixtures = {
  none: () => undefined,
  plainLoaderData: () => ({
    activeDeferreds: new Map([['page', { data: { items: [1, 2] }, pendingKeys: [] }]]),
    deferredScriptKeys: new Map([['page', []]]),
  }),
  unserializedDeferred: () => ({
    activeDeferreds: new Map([['page', { data: { a: Promise.resolve(1) }, pendingKeys: ['a'] }]]),
    deferredScriptKeys: new Map(),
  }),
  deferred: () => {
    const keys = ['a', 'b', 'c'];
    return {
      activeDeferreds: new Map([['page', { data: Object.fromEntries(keys.map(k => [k, Promise.resolve({ k })])), pendingKeys: keys }]]),
      deferredScriptKeys: new Map([['page', keys]]),
    };
  },
  rejectedDeferred: () => ({
    activeDeferreds: new Map([['page', { data: { a: Promise.reject(new Error('boom')) }, pendingKeys: ['a'] }]]),
    deferredScriptKeys: new Map([['page', ['a']]]),
  }),
};

(async () => {
  const { shell, afterShell } = makePage({ shellCards: 20, lateCards: 30 });
  const doc = Buffer.from(`${shell}${MARK}${afterShell}`);
  let total = 0;
  let mismatches = 0;
  for (const variant of ['nodeChunks', 'workerChunks']) {
    for (const [name, fixture] of Object.entries(fixtures)) {
      for (const size of [7, 64, 512, 4096, doc.length]) {
        const chunks = chunk(doc, size);
        const a = await base[variant](chunks, fixture());
        const b = await next[variant](chunks, fixture());
        total++;
        if (!a.equals(b)) {
          mismatches++;
          console.log('MISMATCH', variant, name, size);
        }
      }
    }
  }
  console.log(`end-to-end cases: ${total}, mismatches: ${mismatches}`);
})();

Validation

  • New tests in tests/ssr/deferredScriptOutputCoordinator.test.ts (14 new tests, 30 in the file):
    • The pass-through coordinator emits exactly the same chunk sequence as the tokenizing coordinator with no resolvers. The input is representative HTML: inline script and style with near-miss end tags, comments, quoted > in attributes, a continuation segment plus $RC, a textarea and multi-byte text, split at sizes 1 / 7 / 64 / whole. A spy on the private consume shows 0 calls in pass-through mode and one call per char otherwise.
    • Pass-through mode never inserts a late resolver: finish() reports it. abort() still stops output.
    • Raw-text end tag detection still works after near misses (<b, </scr, </scripts, "<</script", <<</ followed by SCRIPT> across chunks).
    • hasDeferredResolvers matches whether enqueueFromEntries actually emits a script, across 8 cases: no entries, non-deferred values, plain loader data, a pending key, an unserialized key, the pendingKeys fallback, a non-promise key, and mixed routes.
    • Through the real Node createReadableStreamFromElement: with no loader data, or loader data without pending keys, the output is the expected document and consume is never called. With a pending deferred key, the stream is tokenized and the resolver script follows the shell.
  • npx rstest in packages/runtime/plugin-runtime: 17 files, 80 tests passed.
  • Revert checks:
    • With only createReadableStream.ts restored to origin/main, both "does not tokenize the stream" tests fail (consume called 395 times).
    • With deferredScriptOutputCoordinator.ts restored, 4 tests fail.
    • With only the raw-text fast path removed, all 30 tests still pass. It is an output-equivalent micro-optimization.
  • Differential checks against the origin/main dist:
    • coordinator-diff.cjs: 972 no-resolver runs (pass-through against the old tokenizer) and 5832 tokenizing runs, with resolvers and markShellFinished at 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 fmt on the changed files: clean. npx tsc --noEmit -p packages/runtime/plugin-runtime/tsconfig.json: clean. No new errors under tests/tsconfig.json.
  • This branch and perf/stream-ssr-shell-buffer merge cleanly in either order and produce identical trees. The merged tree passes tsc and all 85 tests.

Checklist

  • I have added changeset via pnpm run change.
  • I have updated the documentation.
  • I have added tests to cover my changes.

🤖 Generated with Claude Code

…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-bot

changeset-bot Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: eb4eb92

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

This PR includes changesets to release 120 packages
Name Type
@modern-js/runtime Patch
@modern-js/plugin-bff Patch
@modern-js/plugin-styled-components Patch
@modern-js/plugin-i18n Patch
@integration-test/alias-set Patch
app-document Patch
async-entry-test Patch
tmp Patch
bff-api-app Patch
bff-client-app Patch
bff-indep-client-app Patch
bff-hono Patch
integration-clean-dist-path Patch
integration-compatibility Patch
integration-custom-dist-path Patch
custom-file-system-entry Patch
integration-custom-template Patch
deploy Patch
deploy-server Patch
dev-server Patch
integration-disable-html Patch
app-custom-entries Patch
app-custom-routes-runtime Patch
app-custom Patch
app-entry Patch
app-route Patch
app-entry-server Patch
i18n-app-csr-html-lang Patch
i18n-app Patch
i18n-app-ssr-html-lang Patch
i18n-app-ssr Patch
i18n-custom-i18n-wrapper Patch
i18n-mf-app-provider Patch
i18n-mf-component-provider Patch
i18n-mf-consumer Patch
i18n-routes Patch
i18n-routes-ssr Patch
@integration-test/image-component Patch
main-entry-name Patch
nonce Patch
pure-esm-project Patch
react-compiler-test Patch
routes-match Patch
routes Patch
app-rsbuild-hooks Patch
rsc-csr-app Patch
rsc-csr-routes Patch
rsc-ssr-app Patch
rsc-ssr-routes Patch
basic-app-rstest-browser Patch
basic-app-rstest Patch
runtime-custom-plugin Patch
runtime-custom-config-plugin Patch
select-mul-entry-test Patch
select-one-entry-test Patch
server-config Patch
server-esm-tsx Patch
server-json-script Patch
server-monitors Patch
server-prod Patch
server-routes Patch
@source-code-build/app Patch
ssg-fixtures-mega-list-routes Patch
ssg-fixtures-nested-routes Patch
ssg-fixtures-simple Patch
ssg-fixtures-web-server Patch
ssr-base-async-entry-test Patch
ssr-base-async-pre-entry-test Patch
ssr-base-json-test Patch
ssr-base-test Patch
ssr-base-fallback-test Patch
init Patch
ssr-base-loadable Patch
ssr-partial-test Patch
rsc-closing-tags-test Patch
ssr-script-loading Patch
ssr-useid-test Patch
ssr-streaming-inline-test Patch
ssr-streaming-lazy-test Patch
ssr-streaming-test Patch
styled-components-stream Patch
styled-components-string Patch
integration-tailwindcss-v2 Patch
integration-tailwindcss-v3 Patch
integration-tailwindcss-v4-tools Patch
integration-tailwindcss-v4 Patch
tmp-dir Patch
tools-plugin-options-test Patch
write-to-dist Patch
@modern-js/bundle-diff-benchmark Patch
@modern-js/main-doc Patch
@modern-js/tsconfig Patch
@modern-js/adapter-rstest Patch
@modern-js/builder Patch
@modern-js/plugin-data-loader Patch
@modern-js/plugin-ssg Patch
@modern-js/image Patch
@modern-js/render Patch
@modern-js/bff-core Patch
@modern-js/bff-runtime Patch
@modern-js/server-core Patch
@modern-js/create-request Patch
@modern-js/plugin-polyfill Patch
@modern-js/prod-server Patch
@modern-js/server-runtime Patch
@modern-js/server Patch
@modern-js/server-utils Patch
@modern-js/app-tools Patch
@modern-js/create Patch
@modern-js/i18n-utils Patch
@modern-js/plugin Patch
@modern-js/runtime-utils Patch
@modern-js/sandpack-react Patch
@modern-js/types Patch
@modern-js/utils Patch
@modern-js/rslib Patch
@scripts/prebundle Patch
@scripts/rstest-config Patch
entries-app-builder Patch
@scripts/release-node Patch

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

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

@netlify

netlify Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for modernjs-byted ready!

Name Link
🔨 Latest commit eb4eb92
🔍 Latest deploy log https://app.netlify.com/projects/modernjs-byted/deploys/6ad72518dba30406720b5b12
😎 Deploy Preview https://deploy-preview-9016--modernjs-byted.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 99 (no change from production)
Accessibility: 100 (no change from production)
Best Practices: 100 (no change from production)
SEO: 91 (no change from production)
PWA: -
View the detailed breakdown and full score reports
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions

Copy link
Copy Markdown
Contributor

Rsdoctor Bundle Diff Analysis

📊 Quick Summary
Project Total Size Change
bundle-diff 502.0 KB 0

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
deepcoldy enabled auto-merge (squash) October 17, 2026 18:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants