@samitouri / QOS-React-2 / commits / dc631ef588

[Flight] Outline and dedupe repeated strings (#37147)

Flight has two ways to write a string: 1. Small ones are inlined into the JSON model. 2. Large ones (>= 1024 chars) are outlined into a binary text row so they don't get double-encoded and double-parsed. Neither is ever deduplicated. That's most visible in client reference metadata, where a route repeats the same bundler chunk URLs across every client reference (for example, https://github.com/vercel/next.js/issues/95559). **This PR adds a dedupe map for strings inside import metadata.** A string is written once into its own row, and every occurrence is a reference to it. ## How it works When we're about to write a string in import metadata at least as long as the threshold, we look it up in the request's map: - **If it's not in the map:** Emit a row containing the string, store that row's reference in the map, and write the reference here. - **If it is:** Write the reference. So every string goes on the wire once, and every occurrence costs a few bytes. An earlier version waited for the second occurrence before outlining, which is the right default for arbitrary strings where most never repeat (it's what #27537 does for objects). Import metadata is the opposite case: a chunk is listed by every client module that lives in it, so a chunk name that appears once is the exception. In the bench app's three routes, every chunk string at least 16 characters long appears more than 20 times and none appears once. Outlining on first sight saves the inline copy, and a string that never repeats costs 7 bytes more than inlining it. Import metadata needs its own map and its own queue. The client resolves a client reference as soon as it parses the import row, and import chunks flush ahead of model rows, so the string row has to be in the same queue to arrive first. The client needs no protocol changes. It already resolves `$N` references, and a row holding a string resolves to that string. It does get a check that import metadata never blocks on a row that hasn't arrived, which is the other end of the queue ordering above, and `getOutlinedModel` stops allocating a path array for references without one. Model strings are left alone. An earlier version of this PR deduped them too, but we're not going to do this now per review (maybe in a follow-up). Metadata on the debug channel is also left alone: it's a separate serialization path, and deduping across the two would make the main payload depend on whether a debug channel is attached. ## Threshold The trigger is 16, low compared to what a model-side threshold would want, because import metadata is repetitive but its parts are short. How much this saves depends on how many client references share a chunk list, so measuring one string on its own is misleading. For a chunk path of realistic length today: | references sharing the chunk | before | after | |---|---|---| | 1 | 80 B | 87 B | | 2 | 160 B | 122 B | | 3 | 240 B | 157 B | | 5 | 401 B | 228 B | | 10 | 813 B | 416 B | | 40 | 3273 B | 1526 B | | 80 | 6594 B | 3047 B | (Import and string rows only.) It costs 7 bytes at 1 reference and wins from 2. Chunk paths in this app are 47 characters, so a threshold of 48 or higher saves nothing at all here. That's why it's 16: picking a number just under one bundler's path length gives you something that quietly stops working on the next bundler. The map is bounded by the combined length of the strings it holds, 32 KiB. Once the budget is spent, new strings are written inline every time while strings already outlined keep deduping. That makes the savings depend on the order strings are first seen: a shared chunk URL first encountered after 32 KiB of unique module ids won't be deduped. That's main's behavior, so it's a missed win rather than a regression, but a manifest-heavy dev route could hit it. ## Byte measurements Three routes of a Next.js app, serial requests: | route | Flight | document | document (gzip) | |---|---|---|---| | `/dashboard` | −48.4% (710.1 → 366.5 KB) | −34.3% | −7.8% | | `/docs` | −5.8% (555.2 → 523.1 KB) | −5.0% | −0.7% | | `/blog` | −5.4% (878.8 → 831.7 KB) | −4.4% | −1.7% | The difference between the routes is how many client references each one has. On `/dashboard` the import rows shrink from 388.0 KB to about 32 KB with the row *count* unchanged at 114, because every client reference repeats the same 49 chunk URLs. gzip already collapses repeated strings, so −48.4% raw is only −7.8% compressed. The bytes still have to be escaped, encoded and copied before they reach the compressor, which is where most of the speedup below comes from. ## Speed measurements Benchmarked end-to-end through a Next.js app on Vercel Sandbox VMs (x86 Xeon), 16 boots, paired ABBA within each boot, boot as the unit of replication. Base is the merge-base with main, `eafeac09`; candidate is the current head, `e0b4614c`. | cell | effect | 95% CI | p | |---|---|---|---| | `/dashboard` serial req/s | **+16.9%** | ±1.7 | <0.0001 | | `/dashboard` serial p95 latency | −18.2% | ±2.4 | <0.0001 | | `/dashboard` serial TTFB | −23.2% | ±1.2 | <0.0001 | | `/dashboard` under load req/s | **+17.0%** | ±3.4 | <0.0001 | | `/dashboard` under load median latency | −13.9% | ±2.5 | <0.0001 | | `/docs` serial req/s | +3.0% | ±1.4 | 0.0003 | | `/docs` serial TTFB | −3.1% | ±1.0 | <0.0001 | | `/blog` serial req/s | +2.4% | ±1.0 | 0.0001 | | `/blog` serial median latency | −2.4% | ±0.7 | <0.0001 | No detected difference: `/blog` and `/docs` under load (p=0.13–0.56). All 16 boots are positive on both `/dashboard` cells. The `/dashboard` headline has now been measured in four separate 16-boot runs across four heads of this branch and is p<0.0001 in each; the small routes cleared p<0.01 only on this head, after the serializer change below, having sat at p=0.02–0.06 on the three earlier heads. The previous head, `4569e1d6`, which outlined on the second occurrence rather than the first, measured +14.9% ±2.3 on `/dashboard` serial req/s and −17.3% ±5.7 on TTFB against the same base. Those intervals overlap the ones above, so the switch is not a measurable speedup on its own; the bytes it saves are about 1% of the payload. In a real browser on `/dashboard` (measured on an earlier commit of this branch, `aed4d523`), hydration is −2.8% ±1.3 (p=0.0003) / −2.4% ±0.9 (p=0.0001) and LCP is −5.3% ±2.0 (p<0.0001) / −3.6% ±2.6 (p=0.009). Client navigation is under the noise floor in both. ### Where the time goes 32 CPU profiles, taken after the timed runs with an identical request count in both arms, so absolute sampled milliseconds are comparable. One pass per boot, no replication statistics — directional, not a claim. These profiles are from `aed4d523`. The current head also walks the metadata into a copy before a plain `stringify`, after a detour through a `stringify` replacer that measured 2.3× slower in isolation (a replacer function takes V8 off its fast path for the whole call); the `transformImportMetadata` frame below is a fair proxy for the current cost. Cheaper: | base | candidate | frame | | ---: | ---: | --- | | 23.6 s | 5.7 s | ReactDOM `preinitScript` | | 24.9 s | 10.6 s | `serializeClientReference` | | 81.8 s | 67.3 s | `utf8Write` | | 93.9 s | 80.8 s | `createFromString` | | 50.7 s | 39.2 s | Next's `htmlEscapeJsonString` | More expensive: | base | candidate | frame | | ---: | ---: | --- | | 0 | 9.3 s | `transformImportMetadata` | | 2.0 s | 10.3 s | `getOutlinedModel` (SSR-side Flight client) | | 7.7 s | 11.7 s | `parseModelString` | | 154.8 s | 158.2 s | `resolveModelToJSON` | About +31 s of new work against −79 s inside the runtime bundle and −45 s in node's buffer and string layer. `getOutlinedModel` resolving references is the mechanism working, not a warning sign. Next.js runs a Flight client on the server to read its own payload, and a `/dashboard` payload goes from 0 references inside import rows to 4964, so a frame that barely ran before now runs once per reference. Each call is a lookup on a row that has already been initialized: the string row goes into the import queue ahead of the import row that reads it, so it has always arrived and nothing blocks. `parseModelString` grows for the same reason. `preinitScript` doesn't get cheaper from writing fewer bytes. It does two dictionary lookups keyed by the chunk URL per call, and the call count and argument values are unchanged — the resolved models are identical. What changes is string identity: in the base build every one of the 5013 chunk-URL occurrences is a fresh string out of `JSON.parse` whose hash has to be computed before the lookup, and with dedupe the 49 distinct URLs are parsed once and every reference yields the same string, so V8's cached hash makes the repeat lookups nearly free. Some of the `htmlEscapeJsonString` and buffer-layer drops have the same cause. ### React-level CPU in isolation The e2e numbers above include everything downstream of React (escaping, encoding, compression, the SSR client). To see React's own serialization cost, 114 import rows of dashboard-shaped metadata (49 shared 74-character chunk names per row) were rendered against one request on the production bundles with a no-op destination, arms interleaved, median of 5 rounds × 200: | | main | this PR | |---|---|---| | 49 names shared by all rows | 0.502 ms | **0.322 ms** (−36%) | | 5586 unique names, nothing to dedupe | 0.477 ms | 0.771 ms (+62%) | The second row is the worst case for this change, a manifest where every chunk name appears once. It costs about 40 ns per unique string, plus about 130 ns for each row the budget lets it outline, against a payload that is otherwise unchanged. The metadata is serialized by copying it with the strings already replaced and then calling plain `JSON.stringify`; a `stringify` replacer function would keep V8 off its fast path for the whole call (measured 2.3× slower than plain in isolation, even writing a sixth of the bytes). The copy covers plain JSON only and falls back to the replacer for anything else (`toJSON`, class instances, keys that exist on `Object.prototype`, depth over four, which is how cycles end up throwing stringify's own error). Equivalence of the two paths was checked by a harness that runs both on identical requests and compares the JSON and the resulting request state: 2,656,142 cases, including exhaustive enumeration of small trees over adversarial atoms, 100k seeded random values, and the cases from two independent adversarial reviews — 0 divergences outside four stated assumptions that no bundler manifest violates (no Proxies, no index accessors polluted onto `Array.prototype`, no primitive wrappers with a swapped prototype, side-effect-free property access). ## Cost where there's nothing to dedupe React's own `flight-ssr-bench` fixture has about ten client modules and no repeated chunk paths, so the dedupe never fires and the change can only cost. It costs a little, if anything. Over 16 boots at `aed4d523` the Flight+Fizz Node sync variant was +0.9% ±0.7 on median inject time (p=0.008), worse on 14 of 16 boots. On the current head the four Flight+Fizz inject cells are between +0.4% and +0.8% on the median, none below p=0.07; across all 88 fixture metrics (Fizz and Flight+Fizz, Node and Edge, sync and async, inject and HTTP at c=1/c=10) nothing reaches p<0.01 and `heapMb` is flat to ±0.1%. So the no-dedupe cost is somewhere around half a percent of inject time on this fixture, at the edge of what it can resolve. I couldn't localize it past that. It isn't the per-request `Map`, which is about 22 ns against a 14 ms render, and it isn't allocation — `gcMs` and `heapMb` are flat. Using the Fizz-only variants as a within-boot control, since nothing in `ReactFlightServer.js` can reach them, the Flight-specific residual on that cell is +0.8% ±0.5 and the other three variants scatter around zero (+0.4%, +0.1%, −0.2%). A build that re-inlines `escapeStringValue` back into the string branch, which is the only change here that runs for every string in the model rather than only for import metadata, doesn't recover it either (+0.2% ±0.3 on the same cell, another 16 boots). So this looks like code layout rather than a specific added operation, and it's near the resolution limit of the fixture. <details> <summary>Verification</summary> - Both arms' payloads for `/dashboard` were parsed and their `$`-references resolved recursively, then deep-compared: the resolved models are identical. The 49 extra model rows are exactly the 49 distinct chunk URLs. All 114 import rows match after resolution. - Arms fingerprint distinctly (`a898f40a7bbd` vs `87fb4b7ba15e`), so the two builds are genuinely different. - Build fingerprints differ between arms (`04440a11435d` vs `43d09027ce58`) and the arm version strings carry the expected shas. - Per-boot deltas are printed by the harness; on `/dashboard` serial req/s all 16 boots are positive (range +11.2% to +22.9%). - The bench fixture sets a deployment id, so every chunk URL carries a `?dpl=` query param that exactly doubles its length (74 chars vs 37). An app without one would see roughly half the absolute byte saving on this route. The CPU wins that come from string identity rather than byte count should degrade less than proportionally, but that wasn't measured. - Not measured: payloads that exceed the 32 KiB tracking budget, and whether 16 is optimal rather than merely low enough. </details> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

dan committed Aug 23, 2026 at 18:46 UTC dc631ef588bd10a63eeb9a1c4c133117755c83d7
4 files changed +505 -12
packages/react-client/src/ReactFlightClient.js
+24 -6
@@ -2173,6 +2173,10 @@ function transferReferencedDebugInfo(
2173 }
2174 }
2175
2176 +// Most references have no path, so they can all share the same empty array.
2177 +// It's never mutated because only paths with entries get spliced in place.
2178 +const EMPTY_REFERENCE_PATH: Array<string> = [];
2179 +
2180 function getOutlinedModel<T>(
2181 response: Response,
2182 reference: string,
@@ -2180,8 +2184,10 @@ function getOutlinedModel<T>(
2184 key: string,
2185 map: (response: Response, model: any, parentObject: Object, key: string) => T,
2186 ): T {
2183 - const path = reference.split(':');
2184 - const id = parseInt(path[0], 16);
2187 + // parseInt stops at the ':' so we only need to split when there's a path.
2188 + const id = parseInt(reference, 16);
2189 + const path =
2190 + reference.indexOf(':') === -1 ? EMPTY_REFERENCE_PATH : reference.split(':');
2191 const chunk = getChunk(response, id);
2192 if (enableProfilerTimer && enableComponentPerformanceTrack) {
2193 if (initializingChunk !== null && isArray(initializingChunk._children)) {
@@ -3246,10 +3252,22 @@ function resolveModule(
3252 ): void {
3253 const chunks = response._chunks;
3254 const chunk = chunks.get(id);
3249 - const clientReferenceMetadata: ClientReferenceMetadata = parseModel(
3250 - response,
3251 - model,
3252 - );
3255 + const prevHandler = initializingHandler;
3256 + initializingHandler = null;
3257 + let clientReferenceMetadata: ClientReferenceMetadata;
3258 + try {
3259 + clientReferenceMetadata = parseModel(response, model);
3260 + if (initializingHandler !== null) {
3261 + // We resolve the client reference below and have nothing to wait on,
3262 + // so the metadata can't reference a row that hasn't arrived.
3263 + throw new Error(
3264 + 'A client reference was blocked on a row that has not been received yet. ' +
3265 + 'This is a bug in React.',
3266 + );
3267 + }
3268 + } finally {
3269 + initializingHandler = prevHandler;
3270 + }
3271 const clientReference = resolveClientReference<$FlowFixMe>(
3272 response._bundlerConfig,
3273 clientReferenceMetadata,
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMEdge-test.js
+287
@@ -1107,6 +1107,233 @@ describe('ReactFlightDOMEdge', () => {
1107 expect(items[5]).toEqual(items[10]);
1108 });
1109
1110 + function clientComponent(name, chunkFilename) {
1111 + return clientExports(
1112 + function Client() {
1113 + return <span>{name}</span>;
1114 + },
1115 + 'chunk-' + name,
1116 + chunkFilename,
1117 + Promise.resolve(),
1118 + );
1119 + }
1120 +
1121 + async function renderClients(chunkFilenames) {
1122 + const Clients = chunkFilenames.map(chunkFilename =>
1123 + clientComponent('Client', chunkFilename),
1124 + );
1125 + const stream = await serverAct(() =>
1126 + ReactServerDOMServer.renderToReadableStream(
1127 + <div>
1128 + {Clients.map((Client, i) => (
1129 + <Client key={i} />
1130 + ))}
1131 + </div>,
1132 + webpackMap,
1133 + ),
1134 + );
1135 + const [stream1, stream2] = passThrough(stream).tee();
1136 + const payload = await readResult(stream1);
1137 + const model = await ReactServerDOMClient.createFromReadableStream(stream2, {
1138 + serverConsumerManifest: {
1139 + moduleMap: null,
1140 + moduleLoading: null,
1141 + },
1142 + });
1143 + const ssrStream = await serverAct(() =>
1144 + ReactDOMServer.renderToReadableStream(model),
1145 + );
1146 + expect(await readResult(ssrStream)).toBe(
1147 + '<div>' + '<span>Client</span>'.repeat(Clients.length) + '</div>',
1148 + );
1149 + return payload;
1150 + }
1151 +
1152 + it('should dedupe strings inside client reference metadata', async () => {
1153 + // Bundlers repeat the same chunk in the metadata of every client reference
1154 + // that needs it.
1155 + const chunk = 'shared/hashed-chunk-0f1e2d3c4b5a6978.js';
1156 + const shared = await renderClients(new Array(10).fill(chunk));
1157 + // The same length, so sharing is the only difference between the two.
1158 + const distinct = await renderClients(
1159 + Array.from(
1160 + {length: 10},
1161 + (_, i) => 'unique/hashed-chunk-' + ('' + i).padStart(16, '0') + '.js',
1162 + ),
1163 + );
1164 +
1165 + // However many references there are, the chunk goes on the wire once, as a
1166 + // row that every import row points at.
1167 + expect(shared.split(chunk).length - 1).toBe(1);
1168 + expect(distinct.length - shared.length).toBeGreaterThan(8 * chunk.length);
1169 +
1170 + // The client resolves a client reference while parsing its row, so the
1171 + // outlined copy has to arrive before every row that points at it. The
1172 + // chunk id is too short to be outlined, so it counts the rows.
1173 + const beforeOutlinedCopy = shared.slice(0, shared.indexOf(chunk));
1174 + expect(beforeOutlinedCopy).not.toContain('chunk-Client');
1175 + });
1176 +
1177 + it('should escape strings inside client reference metadata', async () => {
1178 + // A leading $ has to be escaped whether the string gets outlined or not.
1179 + const outlinedChunk = '$shared/hashed-chunk-0f1e2d3c4b5a6978.js';
1180 + const inlineChunk = '$chunk.js';
1181 + const outlined = await renderClients(new Array(3).fill(outlinedChunk));
1182 + const inline = await renderClients(new Array(3).fill(inlineChunk));
1183 +
1184 + expect(outlined.split('$' + outlinedChunk).length - 1).toBe(1);
1185 + expect(inline.split('$' + inlineChunk).length - 1).toBe(3);
1186 + });
1187 +
1188 + it('should not dedupe import strings below the size limit', async () => {
1189 + // A short string costs more to reference than to repeat.
1190 + const shortChunk = 'abc/chunk-15.js';
1191 + const longChunk = 'abcd/chunk-16.js';
1192 + const short = await renderClients(new Array(10).fill(shortChunk));
1193 + const long = await renderClients(new Array(10).fill(longChunk));
1194 +
1195 + expect(short.split(shortChunk).length - 1).toBe(10);
1196 + expect(long.split(longChunk).length - 1).toBe(1);
1197 + // The longer chunk is the one that produces the smaller payload.
1198 + expect(long.length).toBeLessThan(short.length);
1199 + });
1200 +
1201 + it('should stop tracking new import strings once the budget is spent', async () => {
1202 + // Every chunk is outlined the first time it's seen, so chunks that never
1203 + // repeat spend budget too. 32 fillers of 1 KiB fill the 32 KiB budget.
1204 + const chunk = 'shared/hashed-chunk-0f1e2d3c4b5a6978.js';
1205 + const repeats = new Array(10).fill(chunk);
1206 + const filler = (count, length) =>
1207 + Array.from({length: count}, (_, i) =>
1208 + ('filler/chunk-' + i + '-').padEnd(length - 3, 'x').concat('.js'),
1209 + );
1210 + const fitsInTheRest = await renderClients(filler(31, 1024).concat(repeats));
1211 + const findsItSpent = await renderClients(filler(32, 1024).concat(repeats));
1212 +
1213 + expect(fitsInTheRest.split(chunk).length - 1).toBe(1);
1214 + expect(findsItSpent.split(chunk).length - 1).toBe(10);
1215 +
1216 + // A string outlined before the budget is spent keeps deduping after.
1217 + const lastFiller = filler(1, 32768 - 31 * 1024 - chunk.length);
1218 + const trackedBefore = await renderClients(
1219 + [chunk].concat(filler(31, 1024), lastFiller, repeats),
1220 + );
1221 +
1222 + expect(trackedBefore.split(chunk).length - 1).toBe(1);
1223 +
1224 + const bigChunk = 'path/to/' + 'a'.repeat(40000) + '.js';
1225 + const big = await renderClients(new Array(3).fill(bigChunk));
1226 +
1227 + expect(big.split(bigChunk).length - 1).toBe(3);
1228 + });
1229 +
1230 + it('should dedupe import strings produced by toJSON', async () => {
1231 + const chunk = 'shared/hashed-chunk-0f1e2d3c4b5a6978.js';
1232 + const payload = await renderClients(
1233 + Array.from({length: 3}, () => ({
1234 + toJSON() {
1235 + return chunk;
1236 + },
1237 + })),
1238 + );
1239 +
1240 + expect(payload.split(chunk).length - 1).toBe(1);
1241 + });
1242 +
1243 + it('should error on circular client reference metadata', async () => {
1244 + const circular = [];
1245 + circular.push(circular);
1246 + const Client = clientComponent('Client', circular);
1247 +
1248 + const errors = [];
1249 + const stream = await serverAct(() =>
1250 + ReactServerDOMServer.renderToReadableStream(<Client />, webpackMap, {
1251 + onError(error) {
1252 + errors.push(error.message);
1253 + },
1254 + }),
1255 + );
1256 + await readResult(stream);
1257 +
1258 + expect(errors).toEqual([
1259 + expect.stringContaining('Converting circular structure to JSON'),
1260 + ]);
1261 + });
1262 +
1263 + it('should not dedupe strings in the model', async () => {
1264 + // Only import metadata is deduped. Keying a map on arbitrary model strings
1265 + // would hold them in memory for the rest of the request.
1266 + const text = 'a repeated model string well past the import threshold';
1267 + const model = new Array(10).fill(text);
1268 +
1269 + const stream = await serverAct(() =>
1270 + ReactServerDOMServer.renderToReadableStream(model),
1271 + );
1272 + const [stream1, stream2] = passThrough(stream).tee();
1273 +
1274 + const payload = await readResult(stream1);
1275 + expect(payload.split(text).length - 1).toBe(10);
1276 +
1277 + const result = await ReactServerDOMClient.createFromReadableStream(
1278 + stream2,
1279 + {
1280 + serverConsumerManifest: {
1281 + moduleMap: null,
1282 + moduleLoading: null,
1283 + },
1284 + },
1285 + );
1286 + expect(result).toEqual(model);
1287 + });
1288 +
1289 + // @gate __DEV__
1290 + it('should not dedupe import metadata on the debug channel', async () => {
1291 + // The debug channel is a separate transport, so a row it emits can't be
1292 + // referenced from the main stream and vice versa.
1293 + const chunk = 'shared/hashed-chunk-0f1e2d3c4b5a6978.js';
1294 + const A = clientComponent('Client', chunk);
1295 + const B = clientComponent('Client', chunk);
1296 + const C = clientComponent('Client', chunk);
1297 +
1298 + function Server({a, b, c}) {
1299 + return ReactServer.createElement('div', null, a, b, c);
1300 + }
1301 +
1302 + let debugContent = '';
1303 + const debugChannel = {
1304 + writable: new WritableStream({
1305 + write(value) {
1306 + debugContent += Buffer.from(value).toString('utf8');
1307 + },
1308 + }),
1309 + };
1310 +
1311 + const stream = await serverAct(() =>
1312 + ReactServerDOMServer.renderToReadableStream(
1313 + // We can't use JSX here because it'll use the Client React.
1314 + ReactServer.createElement(Server, {
1315 + a: ReactServer.createElement(A),
1316 + b: ReactServer.createElement(B),
1317 + c: ReactServer.createElement(C),
1318 + }),
1319 + webpackMap,
1320 + {debugChannel},
1321 + ),
1322 + );
1323 + const payload = await readResult(stream);
1324 +
1325 + // The main stream dedupes as usual.
1326 + expect(payload.split(chunk).length - 1).toBe(1);
1327 +
1328 + // The debug channel can't point at that row, so every import row it writes
1329 + // spells the chunk out. The chunk id is too short to be outlined, so it
1330 + // counts those rows.
1331 + expect(debugContent).toContain('chunk-Client');
1332 + expect(debugContent.split(chunk).length).toBe(
1333 + debugContent.split('chunk-Client').length,
1334 + );
1335 + });
1336 +
1337 it('warns if passing a this argument to bind() of a server reference', async () => {
1338 const ServerModule = serverExports({
1339 greet: function () {},
@@ -2370,6 +2597,66 @@ describe('ReactFlightDOMEdge', () => {
2597 );
2598 });
2599
2600 + async function renderThroughDebugChannel(chunkFilename) {
2601 + const Client = clientComponent('Client', chunkFilename);
2602 + // The client reference shows up in the owner's props on the debug channel.
2603 + function Server({component}) {
2604 + return ReactServer.createElement(component, null);
2605 + }
2606 +
2607 + let debugReadableStreamController;
2608 + const debugReadableStream = new ReadableStream({
2609 + start(controller) {
2610 + debugReadableStreamController = controller;
2611 + },
2612 + });
2613 +
2614 + const stream = await serverAct(() =>
2615 + ReactServerDOMServer.renderToReadableStream(
2616 + ReactServer.createElement(Server, {component: Client}),
2617 + webpackMap,
2618 + {
2619 + debugChannel: {
2620 + writable: new WritableStream({
2621 + write(chunk) {
2622 + debugReadableStreamController.enqueue(chunk);
2623 + },
2624 + close() {
2625 + debugReadableStreamController.close();
2626 + },
2627 + }),
2628 + },
2629 + },
2630 + ),
2631 + );
2632 +
2633 + const response = ReactServerDOMClient.createFromReadableStream(stream, {
2634 + serverConsumerManifest: {moduleMap: null, moduleLoading: null},
2635 + debugChannel: {readable: debugReadableStream},
2636 + });
2637 +
2638 + function ClientRoot() {
2639 + return use(response);
2640 + }
2641 +
2642 + const ssrStream = await serverAct(() =>
2643 + ReactDOMServer.renderToReadableStream(<ClientRoot />),
2644 + );
2645 + return readResult(ssrStream);
2646 + }
2647 +
2648 + it('can resolve a client reference while debug info is still blocked', async () => {
2649 + const result = await renderThroughDebugChannel('path/to/chunk.js');
2650 +
2651 + expect(result).toBe('<span>Client</span>');
2652 + });
2653 +
2654 + it('should escape strings in import metadata on the debug channel', async () => {
2655 + const result = await renderThroughDebugChannel('$path/to/chunk.js');
2656 +
2657 + expect(result).toBe('<span>Client</span>');
2658 + });
2659 +
2660 it('should properly resolve with deduped objects', async () => {
2661 const obj = {foo: 'hi'};
2662
packages/react-server/src/ReactFlightServer.js
+192 -5
@@ -616,6 +616,9 @@ export type Request = {
616 writtenClientReferences: Map<ClientReferenceKey, number>,
617 writtenServerReferences: Map<ServerReference<any>, number>,
618 writtenObjects: WeakMap<Reference, string>,
619 + writtenImportStrings: Map<string, string>,
620 + // The combined length of the keys in writtenImportStrings.
621 + writtenImportStringsSize: number,
622 temporaryReferences: void | TemporaryReferenceSet,
623 identifierPrefix: string,
624 identifierCount: number,
@@ -741,6 +744,8 @@ function RequestInstance(
744 this.writtenClientReferences = new Map();
745 this.writtenServerReferences = new Map();
746 this.writtenObjects = new WeakMap();
747 + this.writtenImportStrings = new Map();
748 + this.writtenImportStringsSize = 0;
749 this.temporaryReferences = temporaryReferences;
750 this.identifierPrefix = identifierPrefix || '';
751 this.identifierCount = 1;
@@ -2250,6 +2255,16 @@ let canEmitDebugInfo: boolean = false;
2255 let serializedSize = 0;
2256 const MAX_ROW_SIZE = 3200;
2257
2258 +// Bundler metadata repeats the same chunk URLs across every client reference of
2259 +// a route, so strings in it at least this long get outlined and deduplicated
2260 +// when they repeat. The threshold is bounded away from zero because outlining
2261 +// something as short as an export name costs more than copying it.
2262 +const MIN_DEDUPLICATED_IMPORT_STRING_LENGTH = 16;
2263 +
2264 +// Tracked strings are retained for the rest of the request, so their combined
2265 +// length is capped.
2266 +const MAX_DEDUPLICATED_IMPORT_STRINGS_SIZE = 32768;
2267 +
2268 function deferTask(request: Request, task: Task): ReactJSONValue {
2269 // Like outlineTask but instead the item is scheduled to be serialized
2270 // after its parent in the stream.
@@ -3172,9 +3187,15 @@ function serializeClientReference(
3187 try {
3188 const clientReferenceMetadata: ClientReferenceMetadata =
3189 resolveClientReferenceMetadata(request.bundlerConfig, clientReference);
3190 + // Stringify before claiming a chunk id so a throw can't leave it pending.
3191 + const json = stringifyImportMetadata(
3192 + request,
3193 + clientReferenceMetadata,
3194 + false,
3195 + );
3196 request.pendingChunks++;
3197 const importId = request.nextChunkId++;
3177 - emitImportChunk(request, importId, clientReferenceMetadata, false);
3198 + emitImportChunk(request, importId, json, false);
3199 writtenClientReferences.set(clientReferenceKey, importId);
3200 if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
3201 // If we're encoding the "type" of an element, we can refer
@@ -3222,9 +3243,14 @@ function serializeDebugClientReference(
3243 try {
3244 const clientReferenceMetadata: ClientReferenceMetadata =
3245 resolveClientReferenceMetadata(request.bundlerConfig, clientReference);
3246 + const json = stringifyImportMetadata(
3247 + request,
3248 + clientReferenceMetadata,
3249 + true,
3250 + );
3251 request.pendingDebugChunks++;
3252 const importId = request.nextChunkId++;
3227 - emitImportChunk(request, importId, clientReferenceMetadata, true);
3253 + emitImportChunk(request, importId, json, true);
3254 if (parent[0] === REACT_ELEMENT_TYPE && parentPropertyName === '1') {
3255 // If we're encoding the "type" of an element, we can refer
3256 // to that by a lazy reference instead of directly since React
@@ -3594,6 +3620,41 @@ function escapeStringValue(value: string): string {
3620 }
3621 }
3622
3623 +function serializeImportString(request: Request, value: string): string {
3624 + // No maximum length because import strings are short and repeat often.
3625 + // Deduping model strings too would need one to skip very long strings.
3626 + if (value.length < MIN_DEDUPLICATED_IMPORT_STRING_LENGTH) {
3627 + return escapeStringValue(value);
3628 + }
3629 + const writtenStrings = request.writtenImportStrings;
3630 + const existing = writtenStrings.get(value);
3631 + if (existing !== undefined) {
3632 + return existing;
3633 + }
3634 + const size = request.writtenImportStringsSize + value.length;
3635 + if (size > MAX_DEDUPLICATED_IMPORT_STRINGS_SIZE) {
3636 + // The map is full. Strings already outlined keep deduping; new ones are
3637 + // written out every time.
3638 + return escapeStringValue(value);
3639 + }
3640 + request.writtenImportStringsSize = size;
3641 + // Chunk names are almost always shared, so the first occurrence is outlined
3642 + // right away instead of waiting for a repeat.
3643 + request.pendingChunks++;
3644 + const outlinedId = request.nextChunkId++;
3645 + // $FlowFixMe[incompatible-type] stringify can return null
3646 + const json: string = stringify(escapeStringValue(value));
3647 + // The client reads import metadata synchronously, so this row has to have
3648 + // been written by the time the referencing row arrives. Import chunks are
3649 + // flushed ahead of regular ones, which regular chunks can't guarantee.
3650 + request.completedImportChunks.push(
3651 + stringToChunk(outlinedId.toString(16) + ':' + json + '\n'),
3652 + );
3653 + const ref = serializeByValueID(outlinedId);
3654 + writtenStrings.set(value, ref);
3655 + return ref;
3656 +}
3657 +
3658 let modelRoot: null | ReactClientValue = false;
3659
3660 function renderModel(
@@ -4584,14 +4645,140 @@ function emitErrorChunk(
4645 }
4646 }
4647
4648 +// Null on the debug channel, which can't reference rows in the main stream.
4649 +let importStringRequest: null | Request = null;
4650 +
4651 +function importMetadataReplacer(key: string, value: mixed): mixed {
4652 + if (typeof value === 'string') {
4653 + const request = importStringRequest;
4654 + if (request === null) {
4655 + return escapeStringValue(value);
4656 + }
4657 + return serializeImportString(request, value);
4658 + }
4659 + return value;
4660 +}
4661 +
4662 +function stringifyImportMetadataWithReplacer(
4663 + request: Request,
4664 + clientReferenceMetadata: ClientReferenceMetadata,
4665 + debug: boolean,
4666 +): string {
4667 + const prevRequest = importStringRequest;
4668 + importStringRequest = __DEV__ && debug ? null : request;
4669 + try {
4670 + // $FlowFixMe[incompatible-type] stringify can return null
4671 + return stringify(clientReferenceMetadata, importMetadataReplacer);
4672 + } finally {
4673 + importStringRequest = prevRequest;
4674 + }
4675 +}
4676 +
4677 +// Bundler metadata is two or three levels deep. The bound is only there so a
4678 +// cycle ends up in stringify itself, which throws its own error for it.
4679 +const MAX_IMPORT_METADATA_DEPTH = 16;
4680 +
4681 +const NOT_PLAIN_IMPORT_METADATA = {};
4682 +
4683 +// Copies the metadata with every string replaced by its serialized form, so
4684 +// that stringify can run without a replacer. Anything stringify would treat
4685 +// specially (toJSON, boxed primitives, class instances) makes this give up
4686 +// instead, because the copy would not reproduce that treatment.
4687 +function transformImportMetadata(
4688 + request: Request,
4689 + value: mixed,
4690 + depth: number,
4691 +): mixed {
4692 + switch (typeof value) {
4693 + case 'string':
4694 + return serializeImportString(request, value);
4695 + case 'number':
4696 + case 'boolean':
4697 + case 'undefined':
4698 + return value;
4699 + case 'object': {
4700 + if (value === null) {
4701 + return null;
4702 + }
4703 + if (depth > MAX_IMPORT_METADATA_DEPTH) {
4704 + return NOT_PLAIN_IMPORT_METADATA;
4705 + }
4706 + if (typeof (value as any).toJSON === 'function') {
4707 + return NOT_PLAIN_IMPORT_METADATA;
4708 + }
4709 + if (isArray(value)) {
4710 + const length = value.length;
4711 + const copy: Array<mixed> = new Array(length);
4712 + for (let i = 0; i < length; i++) {
4713 + const element = value[i];
4714 + if (typeof element === 'string') {
4715 + copy[i] = serializeImportString(request, element);
4716 + continue;
4717 + }
4718 + const child = transformImportMetadata(request, element, depth + 1);
4719 + if (child === NOT_PLAIN_IMPORT_METADATA) {
4720 + return NOT_PLAIN_IMPORT_METADATA;
4721 + }
4722 + copy[i] = child;
4723 + }
4724 + return copy;
4725 + }
4726 + const proto = getPrototypeOf(value);
4727 + if (proto !== ObjectPrototype && proto !== null) {
4728 + return NOT_PLAIN_IMPORT_METADATA;
4729 + }
4730 + const keys = Object.keys(value);
4731 + const copy: {[string]: mixed} = {};
4732 + for (let i = 0; i < keys.length; i++) {
4733 + const key = keys[i];
4734 + if (key in ObjectPrototype) {
4735 + // The copy inherits from Object.prototype, so assigning this key would
4736 + // hit an accessor like __proto__ or, if the prototype is frozen, throw.
4737 + return NOT_PLAIN_IMPORT_METADATA;
4738 + }
4739 + const element = (value as any)[key];
4740 + if (typeof element === 'string') {
4741 + copy[key] = serializeImportString(request, element);
4742 + continue;
4743 + }
4744 + const child = transformImportMetadata(request, element, depth + 1);
4745 + if (child === NOT_PLAIN_IMPORT_METADATA) {
4746 + return NOT_PLAIN_IMPORT_METADATA;
4747 + }
4748 + copy[key] = child;
4749 + }
4750 + return copy;
4751 + }
4752 + default:
4753 + return NOT_PLAIN_IMPORT_METADATA;
4754 + }
4755 +}
4756 +
4757 +function stringifyImportMetadata(
4758 + request: Request,
4759 + clientReferenceMetadata: ClientReferenceMetadata,
4760 + debug: boolean,
4761 +): string {
4762 + if (!(__DEV__ && debug)) {
4763 + const copy = transformImportMetadata(request, clientReferenceMetadata, 0);
4764 + if (copy !== NOT_PLAIN_IMPORT_METADATA) {
4765 + // $FlowFixMe[incompatible-type] stringify can return null
4766 + return stringify(copy);
4767 + }
4768 + }
4769 + return stringifyImportMetadataWithReplacer(
4770 + request,
4771 + clientReferenceMetadata,
4772 + debug,
4773 + );
4774 +}
4775 +
4776 function emitImportChunk(
4777 request: Request,
4778 id: number,
4590 - clientReferenceMetadata: ClientReferenceMetadata,
4779 + json: string,
4780 debug: boolean,
4781 ): void {
4593 - // $FlowFixMe[incompatible-type] stringify can return null
4594 - const json: string = stringify(clientReferenceMetadata);
4782 const row = serializeRowHeader('I', id) + json + '\n';
4783 const processedChunk = stringToChunk(row);
4784 if (__DEV__ && debug) {
scripts/error-codes/codes.json
+2 -1
@@ -592,5 +592,6 @@
592 "604": "The server render could not complete because client rendering was requested outside a Suspense boundary. See this error's cause for additional details.",
593 "605": "Recoverable Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render so a downstream renderer can recover it. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.",
594 "606": "Expected a suspended recoverable. This is a bug in React. Please file an issue.",
595 - "607": "This library called use() to suspend in a previous render but did not call use() when it finished. This indicates an incorrect use of use(). Learn more: https://react.dev/warnings/conditional-use-of-use"
595 + "607": "This library called use() to suspend in a previous render but did not call use() when it finished. This indicates an incorrect use of use(). Learn more: https://react.dev/warnings/conditional-use-of-use",
596 + "608": "A client reference was blocked on a row that has not been received yet. This is a bug in React."
597 }