test: cover Flight chunk hydration and first settlement #90
Openmamal72(GitHub profile, opens in a new tab)wants to merge 3 commits into
main fromrefs/pull/90/headopened tannerlinsley changed the title
- benchmarks/framework-bundles/browser-checks.json line 15@@ -0,0 +1,15 @@1+{2+ "version": "0.2.0",3+ "verifiedAt": "2026-10-26T00:07:36.528Z",4+ "browser": "in-app browser",5+ "consoleErrors": [],6+ "results": [7+ {8+ "framework": "Start",9+ "renderer": "react",10+ "passed": true,11+ "checks": [12+ "hydration",13+ "counter update",14+ "controlled input",15+ "renderer identity"packages/redact/src/dom/dom.ts line 11@@ -8,4 +8,4 @@88 const IDL_ATTRS = /^(value|checked|selected|disabled|multiple|muted|readonly)$/;99 export const isSvgElement = (el: Element): boolean => (el.namespaceURI === SVG_NS);1010 export function setProp(el: Element, name: string, next: any, prev: any, isSvg: boolean): void {11- if (isReservedProp(name))11+ if (isReservedProp(name) || name === 'autoFocus')packages/redact/src/dom/features/suspense-hydration/full.ts line 161@@ -0,0 +141,21 @@141+ // React owns this pending server range until its reveal script runs.142+ // Hydrating the fallback would consume the transport template as a host.143+ fiber.b.w = true;144+ (startMark as any)._reactRetry = () => {145+ if (!fiber.u)146+ scheduleRetry(fiber);147+ };148+ advanceCursorPast(fiber.p!, endMark);149+ fiber.m = props;150+ return;151+ }152+ // Pending: fallback DOM lives inside <div id="B:ID">. Hydrate the fallback153+ // React subtree against that div's children.154+ const bDiv = document.getElementById(`B:${id}`);155+ try {156+ if (bDiv) {157+ setHydrationCursor(fiber, new HydrationCursor(bDiv));158+ reconcileRaw(fiber, props.fallback);159+ }160+ else {161+ // Couldn't find fallback container — render fresh (non-adopting)packages/redact/src/dom/features/suspense-hydration/full.ts lines 171 to 175@@ -0,0 +155,21 @@155+ try {156+ if (bDiv) {157+ setHydrationCursor(fiber, new HydrationCursor(bDiv));158+ reconcileRaw(fiber, props.fallback);159+ }160+ else {161+ // Couldn't find fallback container — render fresh (non-adopting)162+ reconcileRaw(fiber, props.fallback);163+ }164+ }165+ catch (e) {166+ if (!isHydrationBailout(e) || !bDiv)167+ throw e;168+ recoverBoundaryHydration(fiber, props.fallback, bDiv, null, null);169+ }170+ finally {171+ clearHydrationCursor(fiber);172+ }173+ advanceCursorPast(fiber.p!, endMark);174+ (globalThis as any).$RH?.(id, () => rehydrateBoundary(fiber));175+ // If the inline runtime isn't present, nothing external will mark us dy.packages/redact/src/dom/root.ts line 43@@ -40,3 +40,4 @@4040 })4141 },4242 unmount() {43+ discardPendingWork(root)packages/redact/src/server/walk.ts lines 101 to 102@@ -104,5 +98,5 @@10498 // flat string/number child content. Matches DOM semantics (`option.value`10599 // defaults to `textContent` when no attribute is set).106100 if (children == null) return ''107- if (typeof children === 'string' || typeof children === 'number') return '' + children101+ if (isTextContent(children)) return '' + children108102 if (Array.isArray(children)) return children.map(optionChildText).join('')scripts/compatibility-size-budget.mjs line 364@@ -0,0 +344,21 @@344+ '.changeset/late-mounted-autofocus.md'345+]346+export function autofocusFingerprint(root = new URL('../', import.meta.url)) {347+ return fingerprintInputs(autofocusInputs, root)348+}349+export function autofocusAllowance(base, row, metric, fingerprint) {350+ if (base !== autofocusApproval.base || fingerprint !== autofocusApproval.fingerprint)351+ return 0352+ const value = autofocusApproval.rows[`${row.profile}:${row.entry}:${row.target}`]?.[metric]353+ return typeof value === 'number' ? value : 0354+}355+356+// Tanner approved this exact server-only shell-release cost on 2026-11-02.357+const shellReleaseBase = '2a76bd9dfdb72e53357c49e5b87d3f64e3fab6b5'358+const shellReleaseHash = '2b37faa65dd412be2166c19506c01b0a2801aff32b6f16dd43515243b001348d'359+export function shellReleaseFingerprint(root = new URL('../', import.meta.url)) {360+ return fingerprintInputs(['packages/redact/src', 'packages/redact/package.json', 'scripts/build.mjs', 'scripts/measure-size.mjs', 'scripts/test-react-compatibility-size.mjs', 'pnpm-lock.yaml', '.nvmrc', '.changeset/release-ssr-shell.md'], root)361+}362+export function shellReleaseAllowance(base, row, metric, fingerprint) {363+ if (base !== shellReleaseBase || fingerprint !== shellReleaseHash || row.entry !== 'server/index' || !['full', 'default', 'nano'].includes(row.profile) || !['react18', 'react19'].includes(row.target)) return 0364+ return ({min: 11, gzip: 4, brotli: 18})[metric] || 0scripts/test-browser-reload.mjs line 31@@ -28,4 +28,4 @@2828 for (const engine of engines) {2929 const browser = await types[engine].launch({ headless: true })3030 try {31- for (const mode of ['normal', 'interrupted', 'canceled', 'server-error', 'redirected']) {31+ for (const mode of ['normal', 'interrupted', 'canceled', 'server-error', 'redirected', 'missing-response-event', 'server-error-missing-response-event']) {tests/server-completion-notifier.test.ts lines 13 to 15@@ -0,0 +1,15 @@1+import {createElement as h, Suspense} from 'react'2+import {renderToReadableStream,renderToString,renderToPipeableStream} from 'react-dom/server'3+async function check(mode:string){4+ const events:string[]=[],controller=new AbortController(),ready=[false,false],failed=[false,false],release:Array<()=>void>=[]5+ const promises=[0,1].map(i=>new Promise<void>(resolve=>{release[i]=()=>{ready[i]=true;resolve()}}))6+ function Child({i}:{i:number}){if(!ready[i])throw promises[i];if(failed[i])throw Error('failure'+i);return h('b',null,'child'+i)}7+ const stream=await renderToReadableStream(h('main',null,...[0,1].map(i=>h(Suspense,{fallback:'wait'+i},h(Child,{i})))),{signal:controller.signal,onError(error:any){events.push('error:'+error.message);events.push('nested:'+renderToString(h('i',null,'nested')))}})8+ const reader=stream.getReader(),decoder=new TextDecoder();let html='';const read=async()=>{const part=await reader.read();if(part.done)return false;html+=decoder.decode(part.value,{stream:true});return true}9+ await read();events.push('shell')10+ const draining=(async()=>{try{while(await read()){}events.push('end')}catch(e:any){events.push('reader:'+e.message)}})()11+ const settled=stream.allReady.then(()=>events.push('ready'),(e:any)=>events.push('ready-error:'+e.message))12+ if(mode==='abort'){controller.abort(Error('stop'));await settled;release[0]!();release[1]!()}13+ else if(mode==='reject'){failed[0]=true;release[0]!();while(!events.some(e=>e==='error:failure0'))await Promise.resolve();events.push('release-sibling');release[1]!()}14+ else if(mode==='both-errors'){failed.fill(true);release[0]!();release[1]!()}15+ else {release[1]!();while(!html.includes('child1'))await Promise.resolve();events.push('release-first');release[0]!()}
- benchmarks/results/ssr-completion-notifier/allocation-repeat.mjs line 7@@ -0,0 +1,7 @@1+import {build} from 'esbuild';import {Session} from 'node:inspector/promises';import {spawnSync} from 'node:child_process';import fs from 'node:fs';import path from 'node:path';import {fileURLToPath,pathToFileURL} from 'node:url';import {createHash} from 'node:crypto';2+const dir=process.env.RD_ROOT,root=process.env.RD_ROOT;3+if(process.argv[2]==='child'){4+ const [bundle,name,variant,repeat]=process.argv.slice(3);const {run}=await import(pathToFileURL(bundle));for(let i=0;i<3;i++)await run(name,20);const session=new Session();session.connect();await session.post('HeapProfiler.enable');await session.post('HeapProfiler.collectGarbage');await session.post('HeapProfiler.startSampling',{samplingInterval:4096,includeObjectsCollectedByMajorGC:true,includeObjectsCollectedByMinorGC:true});const {html,ms,...checked}=await run(name,100);const {profile}=await session.post('HeapProfiler.stopSampling');session.disconnect();let sampledBytes=0;const functions={};function visit(n){sampledBytes+=n.selfSize;const k=n.callFrame.functionName||'(anonymous)';functions[k]=(functions[k]||0)+n.selfSize;for(const c of n.children)visit(c)}visit(profile.head);fs.writeFileSync(`${dir}/notifier-repeat-alloc-${variant}-${name}-${repeat}.heapprofile`,JSON.stringify(profile));console.log(JSON.stringify({variant,name,repeat:Number(repeat),sampledBytes,checked,outputSHA2565+}else{6+ const variants=['base','control','notifier-reuse'];const inputs={};for(const v of variants){const src=root+'/'+(v==='control'?'base':v)+'/src';const paths={react:src+'/react/index.ts','react-dom/server':src+'/server/index.ts'};const b=await build({entryPoints:[root+'/staggered-workload.ts'],bundle:true,write:false,metafile:true,platform:'node',format:'esm',minifySyntax:true,minifyWhitespace:true,target:'node24',tsconfigRaw:{compilerOptions:{}},define:{'process.env.NODE_ENV':'"production"'},plugins:[{name:'renderer',setup(b){b.onResolve({filter:/^(react|react-dom\/server)$/},a=>({path:paths[a.path]}))}}]});fs.writeFileSync(dir+'/notifier-repeat-alloc-'+v+'.mjs',b.outputFiles[0].text);inputs[v]={sha256:createHash('sha256').update(b.outputFiles[0].text).digest('hex'),files:Object.keys(b.metafile.inputs).map(p=>({path:p,sha256:createHash('sha256').update(fs.readFileSync(p)).digest('hex')}))}}7+ const rows=[];for(const name of ['staggered-128'])for(let repeat=0;repeat<5;repeat++)for(const v of variants){const result=spawnSync(process.execPath,[fileURLToPath(import.meta.url),'child',dir+'/notifier-repeat-alloc-'+v+'.mjs',name,v,String(repeat)],{encoding:'utf8',maxBuffer:10*1024*1024});if(result.status!==0)throw Error(result.stderr);rows.push(JSON.parse(result.stdout));fs.writeFileSync(dir+'/notifier-repeat-allocation.json',JSON.stringify({node:process.version,versions:process.versions,iterations:100,samplingInterval:4096,inputs,rows},null,2));console.log(name,repeat,v)}benchmarks/results/ssr-completion-notifier/broad.mjs line 5@@ -0,0 +1,5 @@1+import {build} from 'esbuild';import {fork} from 'node:child_process';import fs from 'node:fs';import {fileURLToPath,pathToFileURL} from 'node:url';import {createHash} from 'node:crypto';import {random,shuffle,compareBlocks} from '../../stats.mjs';2+const dir=process.env.RD_ROOT,root=process.env.RD_ROOT,runner=fileURLToPath(import.meta.url);3+if(process.argv[2]==='child'){const mod=await import(pathToFileURL(process.argv[3]));process.on('message',async m=>{try{process.send({id:m.id,result:await mod.run(m.name,m.count)})}catch(e){process.send({id:m.id,error:String(e.stack)})}});process.send({ready:true})}4+else{const variants=['base','control','notifier-reuse'],out={node:process.version,rows:[],inputs:{},blocks:5,rounds:3,iterations:3000};const hash=s=>createHash('sha256').update(s).digest('hex');for(const v of variants){const src=root+'/'+(v==='control'?'base':v)+'/src',paths={react:src+'/react/index.ts','react-dom/server':src+'/server/index.ts'};const b=await build({entryPoints:[root+'/nested-workload.ts'],bundle:true,write:false,metafile:true,platform:'node',format:'esm',minify:true,target:'node24',tsconfigRaw:{compilerOptions:{}},define:{'process.env.NODE_ENV':'"production"'},plugins:[{name:'renderer',setup(b){b.onResolve({filter:/^(react|react-dom\/server)$/},a=>({path:paths[a.path]}))}}]});fs.writeFileSync(dir+'/notifier-broad-timing-'+v+'.mjs',b.outputFiles[0].text);out.inputs[v]={sha256:hash(b.outputFiles[0].text),files:Object.keys(b.metafile.inputs).map(p=>({path:p,sha256:hash(fs.readFileSync(p))}))}}5+const rng=random(93427),expected=new Map();let id=0;for(let block=0;block<5;block++){const children={};try{for(const v of variants){const child=fork(runner,['child',dir+'/notifier-broad-timing-'+v+'.mjs'],{stdio:['ignore','inherit','inherit','ipc']});await new Promise((resolve,reject)=>{child.once('message',resolve);child.once('error',reject)});children[v]=child}const run=(v,name,count)=>new Promise((resolve,reject)=>{const child=children[v],request=++id;child.once('message',m=>{if(m.error)reject(Error(m.error));else resolve(m.result)});child.send({id:request,name,count})});for(const name of shuffle(['string-ready','stream-ready','stream-delayed'],rng)){for(const v of shuffle(variants,rng))for(let warm=0;warm<5;warm++)await run(v,name,1000);const order=shuffle(variants,rng);for(let round=0;round<3;round++)for(const v of [...order.slice(round%variants.length),...order.slice(0,round%variants.length)]){const {html,...result}=await run(v,name,3000);const signature=JSON.stringify([hash(htmlbenchmarks/results/ssr-completion-notifier/notifier-semantics.ts lines 13 to 15@@ -0,0 +1,15 @@1+import {createElement as h, Suspense} from 'react'2+import {renderToReadableStream,renderToString,renderToPipeableStream} from 'react-dom/server'3+export async function check(mode:string){4+ const events:string[]=[],controller=new AbortController(),ready=[false,false],failed=[false,false],release:Array<()=>void>=[]5+ const promises=[0,1].map(i=>new Promise<void>(resolve=>{release[i]=()=>{ready[i]=true;resolve()}}))6+ function Child({i}:{i:number}){if(!ready[i])throw promises[i];if(failed[i])throw Error('failure'+i);return h('b',null,'child'+i)}7+ const stream=await renderToReadableStream(h('main',null,...[0,1].map(i=>h(Suspense,{fallback:'wait'+i},h(Child,{i})))),{signal:controller.signal,onError(error:any){events.push('error:'+error.message);events.push('nested:'+renderToString(h('i',null,'nested')))}})8+ const reader=stream.getReader(),decoder=new TextDecoder();let html='';const read=async()=>{const part=await reader.read();if(part.done)return false;html+=decoder.decode(part.value,{stream:true});return true}9+ await read();events.push('shell')10+ const draining=(async()=>{try{while(await read()){}events.push('end')}catch(e:any){events.push('reader:'+e.message)}})()11+ const settled=stream.allReady.then(()=>events.push('ready'),(e:any)=>events.push('ready-error:'+e.message))12+ if(mode==='abort'){controller.abort(Error('stop'));await settled;release[0]!();release[1]!()}13+ else if(mode==='reject'){failed[0]=true;release[0]!();while(!events.some(e=>e==='error:failure0'))await Promise.resolve();events.push('release-sibling');release[1]!()}14+ else if(mode==='both-errors'){failed.fill(true);release[0]!();release[1]!()}15+ else {release[1]!();while(!html.includes('child1'))await Promise.resolve();events.push('release-first');release[0]!()}benchmarks/results/ssr-completion-notifier/prepare.mjs line 11@@ -0,0 +1,11 @@1+import fs from 'node:fs'2+import path from 'node:path'3+import { execFileSync } from 'node:child_process'4+import { fileURLToPath } from 'node:url'5+6+const fixtures = path.dirname(fileURLToPath(import.meta.url))7+const repo = path.resolve(fixtures, '../../..')8+const output = process.env.RD_ROOT9+if (!output || fs.existsSync(output)) throw new Error('Set RD_ROOT to a new output directory')10+const prefix = 'packages/redact/src/'11+for (const [variant, revision] of [['base', '37c051c9'], ['rejected', '9f59c78f']]) {benchmarks/results/ssr-completion-notifier/README.md line 23@@ -0,0 +3,21 @@3+Repeated Promise.race scans visit every outstanding boundary task whenever a streamed Suspense boundary settles. The ECMAScript [PerformPromiseRace algorithm](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-performpromiserace) motivates replacing those repeated scans with a pending count and a wake signal. A one-slot box stores the first rejection reason separately from that signal. Consuming its value releases the error, and the empty box prevents later failures from being stored.4+5+The candidate also uses a fixed private suspension record, removes an unused fallback copy and updates the pending thenable in place on retry. No public API or application authoring changes. Baseline: `37c051c9`, Node 24.22.0 on macOS arm64. Exact source hashes are included in `data/source-hashes.json`.6+7+## Repeated measurements8+9+Each timing series uses five independent blocks and three balanced rounds with an independently bundled identical control. Completed HTML hashes, byte counts and chunk counts match. These are workload-specific results, not a general SSR speed claim.10+11+| Staggered boundaries | First time change | Repeat time change |12+| --- | ---: | ---: |13+| 8 | -9.58% | -9.10% |14+| 32 | -20.29% | -24.35% |15+| 128 | -36.10% | -36.71% |16+| 512 | -50.50% | -49.66% |17+18+At 128 boundaries, two independent allocation series use five samples per variant and a 4 KiB sampling interval, including collected objects. This measures allocation pressure, not retained heap.19+20+notifier-staggered-allocation: candidate -29.09%, identical control -0.03%.21+notifier-repeat-allocation: candidate -28.94%, identical control -0.02%.22+23+Ordinary-workload results below include identical controls. Short cases are noisy, so these estimates should not be interpreted as precise small wins or losses. Firefox string-ready is +3.49% against baseline while its control is +1.37%; its 95% block interval spans -2.74% to +20.27%, so this short case does not establish a precise cost. Raw block samples and bootstrap intervals are in `data/summary.json`.benchmarks/results/ssr-completion-notifier/timing-repeat.mjs line 5@@ -0,0 +1,5 @@1+import {build} from 'esbuild';import {fork} from 'node:child_process';import fs from 'node:fs';import {fileURLToPath,pathToFileURL} from 'node:url';import {createHash} from 'node:crypto';import {random,shuffle,compareBlocks} from '../../stats.mjs';2+const dir=process.env.RD_ROOT,root=process.env.RD_ROOT,runner=fileURLToPath(import.meta.url);3+if(process.argv[2]==='child'){const mod=await import(pathToFileURL(process.argv[3]));process.on('message',async m=>{try{process.send({id:m.id,result:await mod.run(m.name,m.count)})}catch(e){process.send({id:m.id,error:String(e.stack)})}});process.send({ready:true})}4+else{const variants=['base','control','notifier-reuse'],out={node:process.version,rows:[],inputs:{},blocks:5,rounds:3,iterations:20};const hash=s=>createHash('sha256').update(s).digest('hex');for(const v of variants){const src=root+'/'+(v==='control'?'base':v)+'/src',paths={react:src+'/react/index.ts','react-dom/server':src+'/server/index.ts'};const b=await build({entryPoints:[root+'/staggered-workload.ts'],bundle:true,write:false,metafile:true,platform:'node',format:'esm',minify:true,target:'node24',tsconfigRaw:{compilerOptions:{}},define:{'process.env.NODE_ENV':'"production"'},plugins:[{name:'renderer',setup(b){b.onResolve({filter:/^(react|react-dom\/server)$/},a=>({path:paths[a.path]}))}}]});fs.writeFileSync(dir+'/reuse-staggered-timing-'+v+'.mjs',b.outputFiles[0].text);out.inputs[v]={sha256:hash(b.outputFiles[0].text),files:Object.keys(b.metafile.inputs).map(p=>({path:p,sha256:hash(fs.readFileSync(p))}))}}5+const rng=random(93426),expected=new Map();let id=0;for(let block=0;block<5;block++){const children={};try{for(const v of variants){const child=fork(runner,['child',dir+'/reuse-staggered-timing-'+v+'.mjs'],{stdio:['ignore','inherit','inherit','ipc']});await new Promise((resolve,reject)=>{child.once('message',resolve);child.once('error',reject)});children[v]=child}const run=(v,name,count)=>new Promise((resolve,reject)=>{const child=children[v],request=++id;child.once('message',m=>{if(m.error)reject(Error(m.error));else resolve(m.result)});child.send({id:request,name,count})});for(const name of shuffle(['staggered-8','staggered-32','staggered-128','staggered-512'],rng)){for(const v of shuffle(variants,rng))for(let warm=0;warm<2;warm++)await run(v,name,5);const order=shuffle(variants,rng);for(let round=0;round<3;round++)for(const v of [...order.slice(round%variants.length),...order.slice(0,round%variants.length)]){const {html,...result}=await run(v,name,20);const signature=JSON.stringify(benchmarks/results/ssr-completion-notifier/timing.mjs line 5@@ -0,0 +1,5 @@1+import {build} from 'esbuild';import {fork} from 'node:child_process';import fs from 'node:fs';import {fileURLToPath,pathToFileURL} from 'node:url';import {createHash} from 'node:crypto';import {random,shuffle,compareBlocks} from '../../stats.mjs';2+const dir=process.env.RD_ROOT,root=process.env.RD_ROOT,runner=fileURLToPath(import.meta.url);3+if(process.argv[2]==='child'){const mod=await import(pathToFileURL(process.argv[3]));process.on('message',async m=>{try{process.send({id:m.id,result:await mod.run(m.name,m.count)})}catch(e){process.send({id:m.id,error:String(e.stack)})}});process.send({ready:true})}4+else{const variants=['base','control','notifier-reuse'],out={node:process.version,rows:[],inputs:{},blocks:5,rounds:3,iterations:20};const hash=s=>createHash('sha256').update(s).digest('hex');for(const v of variants){const src=root+'/'+(v==='control'?'base':v)+'/src',paths={react:src+'/react/index.ts','react-dom/server':src+'/server/index.ts'};const b=await build({entryPoints:[root+'/staggered-workload.ts'],bundle:true,write:false,metafile:true,platform:'node',format:'esm',minify:true,target:'node24',tsconfigRaw:{compilerOptions:{}},define:{'process.env.NODE_ENV':'"production"'},plugins:[{name:'renderer',setup(b){b.onResolve({filter:/^(react|react-dom\/server)$/},a=>({path:paths[a.path]}))}}]});fs.writeFileSync(dir+'/reuse-staggered-timing-'+v+'.mjs',b.outputFiles[0].text);out.inputs[v]={sha256:hash(b.outputFiles[0].text),files:Object.keys(b.metafile.inputs).map(p=>({path:p,sha256:hash(fs.readFileSync(p))}))}}5+const rng=random(93425),expected=new Map();let id=0;for(let block=0;block<5;block++){const children={};try{for(const v of variants){const child=fork(runner,['child',dir+'/reuse-staggered-timing-'+v+'.mjs'],{stdio:['ignore','inherit','inherit','ipc']});await new Promise((resolve,reject)=>{child.once('message',resolve);child.once('error',reject)});children[v]=child}const run=(v,name,count)=>new Promise((resolve,reject)=>{const child=children[v],request=++id;child.once('message',m=>{if(m.error)reject(Error(m.error));else resolve(m.result)});child.send({id:request,name,count})});for(const name of shuffle(['staggered-8','staggered-32','staggered-128','staggered-512'],rng)){for(const v of shuffle(variants,rng))for(let warm=0;warm<2;warm++)await run(v,name,5);const order=shuffle(variants,rng);for(let round=0;round<3;round++)for(const v of [...order.slice(round%variants.length),...order.slice(0,round%variants.length)]){const {html,...result}=await run(v,name,20);const signature=JSON.stringify(
Sign in to join this conversation.
⚠️ No Changeset found#
Latest commit: 4121aa8622983b9fa8941d01184a417996fd553f
Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.
This PR includes no changesets
When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types
Click here to learn what changesets are, and how to add one.
Click here if you're a maintainer who wants to add a changeset to this PR