Skip to content

ci(bench): gate the PR bench on exact work counters, pair its timing, and diff against the first parent - #1640

Merged
trueadm merged 6 commits into
mainfrom
ci/paired-pr-bench
Oct 3, 2026
Merged

trueadm merged 6 commits into
mainfrom
ci/paired-pr-bench

Conversation

@trueadm

@trueadm trueadm commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Reworks the PR bench (review findings H5 and H12) so it judges changes by exact numbers and compares against the right base:

  1. Deterministic gate. For each canonical js-framework operation (run, replace, add, update, select, swap, remove, runlots, select_lots, clear), on both Octane dialects, the harness counts production-bundle calls and DOM mutations. Any increase over the base fails the job.
  2. Wall time is a report only. Base and head are paired per sample in one browser, sub-20 ms operations are looped to about 20 ms, and a verdict is given only when the 95% interval of the head/base ratio lies entirely beyond ±3%.
  3. Base. The merge commit's first parent replaces pull_request.base.sha.
  4. Budgets. pr-report.mjs fails on any byte value over its committed same-run budget.

Why

Changes

  • benchmarks/js-framework/pair.mjs (new). The merge commit's harness builds both trees' octane-tsrx/octane-jsx fixtures, serves them (head 5176/5177, base 6176/6177) and drives both. A PR that changes the harness therefore cannot make its base look different.
    • Work counters. For each side, a --jitless Chromium runs the operations in a fixed order from a fresh seeded page.
      • calls_<op> is the sum of precise-coverage call counts over /assets/ scripts.
      • dom_<op> is the MutationObserver count of nodes added and removed, attribute writes and text writes, including every task the operation schedules.
      • live_inserts_* and fragment_commits_* mount gates run on both sides.
    • Timing. One browser, base and head pages, alternating ABBA per pair over 30 pairs.
      • update, select, swap, remove and select_lots repeat inside one sample until it takes about 20 ms; the repeat count is calibrated on head and shared by both sides.
      • The head stat carries paired: { ratio, low, high, pairs }, from pairedRatio in benchmarks/lib/stats.mjs: the median of per-pair log ratios with a seeded 2,000-resample bootstrap.
    • --work-only skips timing. With the same checkout as both trees, it is the determinism control.
  • benchmarks/js-framework/operations.mjs (new) holds the canonical operations, state setup, timed clicks, which now take a selector list and repeat count, and the mount gates. run.mjs imports them, so local and PR runs drive identical work.
  • benchmarks/pr-report.mjs.
    • Exits 1 for a budget breach (head target vs its -budget peer), any increase in a js-framework deterministic counter, or a suite that failed on the merge commit. A base-side failure stays a warning.
    • Timing rows show base ms, head ms, head/base ratio and 95% CI; the old margin-of-error rule and --rounds merging are gone.
    • The header names the first-parent base and, when it differs, how many commits main has moved past the recorded base (BASE_DRIFT from the compare API).
    • It still imports nothing outside Node, because the comment workflow loads it alone.
  • .github/workflows/pr-bench.yml.
    • fetch-depth: 2 and base=$(git rev-parse HEAD^1); the drift comes from gh api compare.
    • Playwright is installed once.
    • The paired harness replaces the four bench.mjs js-framework rounds.
    • A final step fails on the report's exit status after the artifact upload, so the comment still posts.
  • benchmarks/README.md describes the new report; the performance-audit skill notes the gate.

Validation

  • node --test benchmarks/pr-report.test.mjs benchmarks/lib/stats.test.mjs scripts/ci-workflow.test.mjs: 90/90 pass. The new tests cover budget breaches, work-counter increases and decreases, the ±3% CI rule, timing that never fails, the base-drift header, and the bootstrap's seeding and sensitivity.
  • Determinism control: pair.mjs --base-tree=. --work-only on main. All 40 counters match between base and head pages, and again across a second run. Sample: tsrx run 34,091 calls, 1,000 nodes; select 91 calls, 1 attribute.
  • Report rendered from those A/A counters with one counter bumped: it shows a 🔴 row and exits 1.
  • Paired timing path: not run locally (local timing runs are off-limits while many sessions load this machine). This PR's own PR-bench run is its first exercise; I'll read that report and fix anything it shows.
  • pnpm sync, pnpm rules:check, pnpm format:files:check on changed files.
  • pnpm format:check, pnpm typecheck, pnpm test: left to CI.

Risk / follow-ups

  • This PR's own PR-bench run reports main's current budget breaches (21) and fails until ci(bench): re-set every byte budget to measured + 32 bytes #1638 (budget reset) merges.
  • Gate strength. "PR bench" is not a required status check, so the work gate shows red but does not block merge. Making it required is a branch-protection setting for a maintainer.
  • Expected red. A PR that legitimately adds work per operation, such as a correctness fix, shows red and should say why in its description.
  • Job time. The paired step should take roughly as long as the four rounds it replaces: about 3–5 min for 2 dialects × 10 operations × 30 pairs, plus counting.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.


Note

Medium Risk
Changes CI gating and benchmark methodology for every PR; mis-tuned thresholds or harness bugs could cause false reds or miss regressions until validated in production runs.

Overview
Reworks PR bench so comparisons target the merge commit’s first parent (not pull_request.base.sha), with optional header text for how far main has drifted past the PR’s recorded base.

js-framework no longer runs four separate bench.mjs rounds. A new pair.mjs harness on the merge commit builds and serves both trees, counts exact production calls and DOM mutations per operation (job fails on any increase), and pairs wall-clock samples in one browser with bootstrap head/base ratios (±3% CI for slower/faster labels only—timing does not fail the job). Shared operations.mjs keeps local run.mjs and PR runs aligned.

pr-report.mjs now exits non-zero on byte budget breaches, increased js-framework work counters, or merge-commit suite failures; drops --rounds merging. Docs/skills and ci-workflow.test.mjs reflect the new gates and workflow order (report uploaded before fail step).

Reviewed by Cursor Bugbot for commit 7d6a7ff. Bugbot is set up for automated code reviews on this repo. Configure here.

… and diff against the first parent

The PR bench's timing verdict could not detect anything inside its own noise
(±20-66% per operation, 8 samples, rounds merged with `max`), yet it still
flagged pull requests that never touched the runtime. Its base was the pull
request's recorded base SHA, so a delta could include other merges.

- benchmarks/js-framework/pair.mjs, from the merge commit, builds and serves
  both trees' fixtures and drives them itself.
  - It counts each operation's production-bundle calls (Chromium precise
    coverage in a --jitless browser) and DOM mutations (a MutationObserver).
    These are exact for a fixed build, and an A/A run matches across pages and
    across runs.
  - It times base and head in one browser, alternating per sample across 30
    pairs. Repeatable operations loop to about 20ms per sample, clear of the
    0.1ms timer floor. The head result carries the median head/base ratio and
    its 95% bootstrap interval (stats.mjs pairedRatio).
- pr-report.mjs exits 1 for a byte value over its committed same-run budget, any
  increase in a js-framework work counter, or a suite that failed on the merge
  commit. Wall time is reported only: slower or faster only when the whole
  interval lies beyond ±3%. The report states how far main has moved past the
  pull request's recorded base.
- pr-bench.yml compares against the merge commit's first parent (HEAD^1), runs
  the paired harness once instead of four rounds, and fails after uploading
  the report when the report says so.
- js-framework/operations.mjs holds the shared operations and gates; run.mjs
  drives exactly the same work.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent ci PR: CI or build pipeline labels Oct 3, 2026
@github-actions
github-actions Bot marked this pull request as draft October 3, 2026 07:42

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Even swap repeats skip the commit check
    • Added a parity check in calibrate() to force swap repeat counts to odd, ensuring the timeClick commit check always verifies the row moved to index 998 rather than accepting the vacuous original-order comparison.

Create PR

Or push these changes by commenting:

@cursor push 015c0d1683
Preview (015c0d1683)
diff --git a/benchmarks/js-framework/pair.mjs b/benchmarks/js-framework/pair.mjs
--- a/benchmarks/js-framework/pair.mjs
+++ b/benchmarks/js-framework/pair.mjs
@@ -175,6 +175,9 @@
 	// A selection sample ends on the alternate row, so the next one starts by
 	// selecting a different row instead of re-selecting the current one.
 	if (op.alternateClick && repeat % 2 === 1) repeat++;
+	// Swap must use an odd repeat so the commit check in timeClick can verify
+	// the row actually moved (an even count restores the original order).
+	if (op.name === 'swap' && repeat % 2 === 0) repeat++;
 	return Math.max(repeat, 2);
 }

You can send follow-ups to the cloud agent here.

Comment thread benchmarks/js-framework/operations.mjs Resolved
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark report

  • ❌ bundle-size: 17 value(s) exceed their committed budget
  • ❌ bundle-reachability: 38 value(s) exceed their committed budget

Compares 950ef0b0b, the merge commit's first parent (main has moved 18 commit(s) past the pull request's recorded base 11a9da935) with b0c41f8aa on the same runner. A byte value over its committed budget or any increase in a js-framework work counter fails this check. Wall time is a report: base and head samples alternate in one browser, and an operation is called slower or faster only when the 95% confidence interval of its ratio excludes ±3%. Workflow run

js-framework: 1k/10k row operations

All 20 timed operations (20 without a verdict)
target operation base ms head ms head/base 95% CI
octane-tsrx run 3.800 3.650 −1.3% −2.9% … +3.1% ⚪ within noise
octane-tsrx replace 7.083 6.850 −0.7% −5.2% … +4.2% ⚪ within noise
octane-tsrx add 3.383 3.350 −0.0% −2.9% … +0.0% ⚪ within noise
octane-tsrx update 0.131 0.131 −2.7% −3.8% … −0.6% ⚪ within noise
octane-tsrx select 0.006 0.006 +0.7% −0.5% … +1.6% ⚪ within noise
octane-tsrx swap 0.043 0.043 −1.5% −4.0% … +0.0% ⚪ within noise
octane-tsrx remove 0.028 0.027 −2.5% −8.9% … +1.2% ⚪ within noise
octane-tsrx runlots 35.450 36.042 +2.4% −0.8% … +5.7% ⚪ within noise
octane-tsrx select_lots 0.006 0.006 −3.6% −5.7% … −0.8% ⚪ within noise
octane-tsrx clear 39.900 39.775 −1.7% −5.8% … +2.6% ⚪ within noise
octane-jsx run 3.833 3.942 −0.0% −2.7% … +2.8% ⚪ within noise
octane-jsx replace 8.125 7.350 +0.0% −1.4% … +3.3% ⚪ within noise
octane-jsx add 3.517 3.408 −1.3% −5.3% … +0.0% ⚪ within noise
octane-jsx update 0.284 0.263 −1.0% −1.8% … +0.6% ⚪ within noise
octane-jsx select 0.148 0.141 −1.7% −6.6% … +2.1% ⚪ within noise
octane-jsx swap 0.245 0.246 +0.6% −0.9% … +3.8% ⚪ within noise
octane-jsx remove 0.201 0.201 −0.6% −3.1% … +1.6% ⚪ within noise
octane-jsx runlots 31.208 31.742 +2.3% −0.6% … +3.7% ⚪ within noise
octane-jsx select_lots 1.790 1.787 +0.7% −1.8% … +4.5% ⚪ within noise
octane-jsx clear 42.017 40.142 −4.0% −8.5% … −0.7% ⚪ within noise

All 64 work counters are unchanged.

Application bundle size (bytes)

❌ 17 value(s) exceed their committed budget. Reduce the growth, or raise the budget in a separate pull request that names the bytes and the reason (CONTRIBUTING.md, "Size budgets").

target metric head budget over
octane-tsrx todo_fw_raw 135,425 134,272 +1,153
octane-tsrx todo_fw_gzip 43,913 43,712 +201
octane-tsrx todo_fw_brotli 38,571 38,464 +107
octane-tsrx todo_js_raw 140,535 139,616 +919
octane-tsrx todo_js_gzip 46,390 46,304 +86
octane-tsrx chat_fw_raw 133,002 131,744 +1,258
octane-tsrx chat_fw_gzip 43,338 43,136 +202
octane-tsrx chat_fw_brotli 38,076 37,888 +188
octane-tsrx chat_js_raw 139,655 138,656 +999
octane-tsrx chat_js_gzip 46,317 46,240 +77
octane-tsrx chat_js_brotli 40,712 40,640 +72
octane-jsx fw_raw 218,425 216,064 +2,361
octane-jsx fw_gzip 69,491 68,800 +691
octane-jsx fw_brotli 60,238 59,584 +654
octane-jsx js_raw 226,884 224,800 +2,084
octane-jsx js_gzip 72,427 71,872 +555
octane-jsx js_brotli 62,735 62,176 +559

No changes across 45 measured values.

Public-import reachability bundles (bytes)

❌ 38 value(s) exceed their committed budget. Reduce the growth, or raise the budget in a separate pull request that names the bytes and the reason (CONTRIBUTING.md, "Size budgets").

target metric head budget over
capture-only raw 11,406 10,688 +718
capture-only gzip 4,388 4,000 +388
capture-only brotli 3,924 3,616 +308
root-static-specialized raw 76,940 76,352 +588
root-static-specialized gzip 25,536 25,504 +32
root-static raw 203,121 201,472 +1,649
root-static gzip 64,616 64,032 +584
root-static brotli 55,909 55,488 +421
hydrate-root raw 173,260 148,352 +24,908
hydrate-root gzip 54,883 48,096 +6,787
hydrate-root brotli 47,892 42,048 +5,844
deferred-hydration raw 236,589 209,504 +27,085
deferred-hydration gzip 74,764 67,264 +7,500
deferred-hydration brotli 64,526 58,112 +6,414
suspense-transition raw 165,004 162,944 +2,060
suspense-transition gzip 52,958 52,672 +286
suspense-transition brotli 46,352 46,016 +336
server-render raw 65,077 54,048 +11,029
server-render gzip 22,432 18,912 +3,520
server-render brotli 20,253 17,056 +3,197
binding-base-ui-vite raw 213,352 211,968 +1,384
binding-base-ui-vite gzip 68,215 67,680 +535
binding-base-ui-vite brotli 59,116 58,720 +396
binding-base-ui-esbuild raw 211,307 209,984 +1,323
binding-base-ui-esbuild gzip 68,148 67,680 +468
binding-base-ui-esbuild brotli 59,119 58,624 +495
binding-radix-vite raw 215,284 213,952 +1,332
binding-radix-vite gzip 68,739 68,288 +451
binding-radix-vite brotli 59,636 59,200 +436
binding-radix-esbuild raw 213,199 211,904 +1,295
binding-radix-esbuild gzip 68,734 68,288 +446
binding-radix-esbuild brotli 59,795 59,104 +691
binding-apollo-client-vite raw 358,345 354,304 +4,041
binding-apollo-client-vite gzip 112,287 110,592 +1,695
binding-apollo-client-vite brotli 97,970 97,280 +690
binding-apollo-client-esbuild raw 361,292 357,376 +3,916
binding-apollo-client-esbuild gzip 114,485 113,664 +821
binding-apollo-client-esbuild brotli 99,713 99,328 +385

No changes across 105 measured values.

…k counters

An even number of swaps restores the original row order, which a swap that did
nothing would also leave, so the timed-click check could not tell them apart.
Calibration now keeps swap repetitions odd, so every sample ends swapped and is
verified.

The report also says when every js-framework work counter is unchanged, so a
green gate is visible beside the timing table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trueadm
trueadm marked this pull request as ready for review October 3, 2026 10:26
…ing shifts

The PR bench called tsrx `remove` 5.3% slower on a change that does not touch
the runtime. Calibration had sized the loop from one cold remove (~0.3ms), but a
warm looped remove takes ~0.03ms, so each sample lasted ~2ms. On Chromium's
0.1ms timer, every pair then differed by whole ticks (20/19 = +5.3%).

- Calibration now grows the repeat count on looped samples until one actually
  takes about 20ms. The caps are raised (select needs ~2,900 clicks; remove may
  take 800 of the 1,000 rows), and each stat records its median sample
  duration.
- The report gives a timing verdict only when the median shift also spans two
  0.1ms ticks of the sample, so a ~3ms create that cannot loop is not called
  slower on quantization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Head calibration dirties update labels
    • Added await ensureState(page, 'empty') at the end of calibrate to clear the head table after calibration loops, so the sampling loop rebuilds fresh rows symmetrically for both sides.

Create PR

Or push these changes by commenting:

@cursor push fdd471126a
Preview (fdd471126a)
diff --git a/benchmarks/js-framework/pair.mjs b/benchmarks/js-framework/pair.mjs
--- a/benchmarks/js-framework/pair.mjs
+++ b/benchmarks/js-framework/pair.mjs
@@ -181,6 +181,7 @@
 		if (elapsed >= SAMPLE_MS * 0.8 || repeat >= cap) break;
 		repeat = parityFor(op, Math.min(cap, Math.ceil((repeat * SAMPLE_MS) / Math.max(elapsed, 0.1))));
 	}
+	await ensureState(page, 'empty');
 	return Math.min(repeat, parityFor(op, cap));
 }

You can send follow-ups to the cloud agent here.

Comment thread benchmarks/js-framework/pair.mjs Resolved
`update` appends to every tenth label on each click, and ensureState keeps a
1,000-row table, so labels grew across looped samples. Head also started
longer, because calibration clicked only there. That asymmetry could read as an
update slowdown on identical builds.

- Every update sample, timed or calibrating, starts from freshly built rows.
- Calibration's trial loops are replayed on the base page, so both pages run
  the identical operation sequence and their seeded label streams stay in step.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vercel

vercel Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

2 Skipped Deployments
Project Deployment Actions Updated
octane-website Skipped Skipped Oct 3, 2026 10:44am UTC
octane-website-mcp Skipped Skipped Oct 3, 2026 10:44am UTC

Request Review

@vercel
vercel Bot temporarily deployed to Preview – octane-website October 3, 2026 10:44 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp October 3, 2026 10:44 Inactive
# Conflicts:
#	package.json

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

Bugbot Autofix prepared fixes for both issues found in the latest run.

  • ✅ Fixed: Update prepare misses rebuild commit
    • Changed prepare() to clear the table to 0 rows first so the subsequent ensureState rebuild waits for a real 0→1000 transition instead of a no-op check on an already-1000-row table.
  • ✅ Fixed: Over-budget rows marked within budget
    • Filtered budget-breached (target, op) pairs out of the larger list before emitting the 'within budget' headline note, so a metric cannot be reported as both exceeding its budget and growing within it.

Create PR

Or push these changes by commenting:

@cursor push fa9f94eb1b
Preview (fa9f94eb1b)
diff --git a/.agents/skills/performance-audit/SKILL.md b/.agents/skills/performance-audit/SKILL.md
--- a/.agents/skills/performance-audit/SKILL.md
+++ b/.agents/skills/performance-audit/SKILL.md
@@ -39,6 +39,10 @@
      a quick smoke result with a full result.
    - Treat a delta inside observed variance as inconclusive. Prefer ratio guards
      and deterministic counters when wall-clock noise is larger than the claim.
+   - The pull request benchmark gates js-framework production calls and DOM
+     mutations per operation against the merge commit's first parent: any
+     increase fails it. Wall time there is a paired report, called slower or
+     faster only when its 95% interval lies beyond ±3%.
 
 4. **Diagnose**
    - Runtime hot paths: scheduler queues, effect flushing, keyed reconciliation, event delegation, context propagation, refs.

diff --git a/.claude/skills/performance-audit/SKILL.md b/.claude/skills/performance-audit/SKILL.md
--- a/.claude/skills/performance-audit/SKILL.md
+++ b/.claude/skills/performance-audit/SKILL.md
@@ -39,6 +39,10 @@
      a quick smoke result with a full result.
    - Treat a delta inside observed variance as inconclusive. Prefer ratio guards
      and deterministic counters when wall-clock noise is larger than the claim.
+   - The pull request benchmark gates js-framework production calls and DOM
+     mutations per operation against the merge commit's first parent: any
+     increase fails it. Wall time there is a paired report, called slower or
+     faster only when its 95% interval lies beyond ±3%.
 
 4. **Diagnose**
    - Runtime hot paths: scheduler queues, effect flushing, keyed reconciliation, event delegation, context propagation, refs.

diff --git a/.cursor/skills/performance-audit/SKILL.md b/.cursor/skills/performance-audit/SKILL.md
--- a/.cursor/skills/performance-audit/SKILL.md
+++ b/.cursor/skills/performance-audit/SKILL.md
@@ -36,6 +36,10 @@
      a quick smoke result with a full result.
    - Treat a delta inside observed variance as inconclusive. Prefer ratio guards
      and deterministic counters when wall-clock noise is larger than the claim.
+   - The pull request benchmark gates js-framework production calls and DOM
+     mutations per operation against the merge commit's first parent: any
+     increase fails it. Wall time there is a paired report, called slower or
+     faster only when its 95% interval lies beyond ±3%.
 
 4. **Diagnose**
    - Runtime hot paths: scheduler queues, effect flushing, keyed reconciliation, event delegation, context propagation, refs.

diff --git a/.gemini/skills/performance-audit/SKILL.md b/.gemini/skills/performance-audit/SKILL.md
--- a/.gemini/skills/performance-audit/SKILL.md
+++ b/.gemini/skills/performance-audit/SKILL.md
@@ -39,6 +39,10 @@
      a quick smoke result with a full result.
    - Treat a delta inside observed variance as inconclusive. Prefer ratio guards
      and deterministic counters when wall-clock noise is larger than the claim.
+   - The pull request benchmark gates js-framework production calls and DOM
+     mutations per operation against the merge commit's first parent: any
+     increase fails it. Wall time there is a paired report, called slower or
+     faster only when its 95% interval lies beyond ±3%.
 
 4. **Diagnose**
    - Runtime hot paths: scheduler queues, effect flushing, keyed reconciliation, event delegation, context propagation, refs.

diff --git a/.github/skills/performance-audit/SKILL.md b/.github/skills/performance-audit/SKILL.md
--- a/.github/skills/performance-audit/SKILL.md
+++ b/.github/skills/performance-audit/SKILL.md
@@ -39,6 +39,10 @@
      a quick smoke result with a full result.
    - Treat a delta inside observed variance as inconclusive. Prefer ratio guards
      and deterministic counters when wall-clock noise is larger than the claim.
+   - The pull request benchmark gates js-framework production calls and DOM
+     mutations per operation against the merge commit's first parent: any
+     increase fails it. Wall time there is a paired report, called slower or
+     faster only when its 95% interval lies beyond ±3%.
 
 4. **Diagnose**
    - Runtime hot paths: scheduler queues, effect flushing, keyed reconciliation, event delegation, context propagation, refs.

diff --git a/.github/workflows/pr-bench.yml b/.github/workflows/pr-bench.yml
--- a/.github/workflows/pr-bench.yml
+++ b/.github/workflows/pr-bench.yml
@@ -1,10 +1,17 @@
 name: PR bench
 
-# Measures every ready pull request against its base commit on the SAME runner
-# and renders benchmarks/pr-report.mjs's Markdown report. Fork pull requests get
-# a read-only token here, so this job only uploads the report; the trusted
+# Measures every ready pull request against the main commit it would land on,
+# on the SAME runner, and renders benchmarks/pr-report.mjs's Markdown report.
+# That base is the merge commit's first parent, so every delta is this pull
+# request's own; the pull request's recorded base can trail main by several
+# merges, which the report states separately. Fork pull requests get a
+# read-only token here, so this job only uploads the report; the trusted
 # "PR bench comment" workflow posts it. Absolute numbers stay runner-specific:
 # the report compares base and merge commit from this one run only.
+#
+# The job fails when a byte value exceeds its committed budget, when a
+# js-framework work counter (production calls, DOM mutations) increases, or
+# when a benchmark fails on the merge commit. Wall time is reported only.
 
 on:
   pull_request:
@@ -29,23 +36,28 @@
     runs-on: blacksmith-4vcpu-ubuntu-2404
     timeout-minutes: 60
     env:
-      BASE_SHA: ${{ github.event.pull_request.base.sha }}
+      EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha }}
       HEAD_SHA: ${{ github.event.pull_request.head.sha }}
-      # Only Octane rows are reported; timing other frameworks would only add runtime.
-      JS_FRAMEWORK_TARGETS: '[{"name":"octane-tsrx","url":"http://localhost:5176/","ready":"#run"},{"name":"octane-jsx","url":"http://localhost:5177/","ready":"#run"}]'
 
     steps:
       - name: Checkout merge commit
         uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
         with:
           persist-credentials: false
+          # The merge commit and its parents: the first parent is the base.
+          fetch-depth: 2
 
       - name: Check out base commit
+        env:
+          GH_TOKEN: ${{ github.token }}
         run: |
+          base=$(git rev-parse HEAD^1)
+          echo "BASE_SHA=$base" >> "$GITHUB_ENV"
           echo "BASE_TREE=$RUNNER_TEMP/base" >> "$GITHUB_ENV"
           echo "RESULTS=$RUNNER_TEMP/pr-bench" >> "$GITHUB_ENV"
-          git fetch --no-tags --depth=1 origin "$BASE_SHA"
-          git worktree add --detach "$RUNNER_TEMP/base" "$BASE_SHA"
+          drift=$(gh api "repos/$GITHUB_REPOSITORY/compare/$EVENT_BASE_SHA...$base" --jq .ahead_by || true)
+          echo "BASE_DRIFT=$drift" >> "$GITHUB_ENV"
+          git worktree add --detach "$RUNNER_TEMP/base" "$base"
 
       - name: Install pnpm
         uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6
@@ -61,16 +73,13 @@
           pnpm install --prod false --frozen-lockfile
           pnpm --dir "$BASE_TREE" install --prod false --frozen-lockfile
 
+      # The merge commit's harness drives both trees, so only its browser is needed.
       - name: Install Playwright Chromium
-        run: |
-          pnpm --filter octane-js-framework-benchmarks exec playwright install --with-deps chromium
-          pnpm --dir "$BASE_TREE" --filter octane-js-framework-benchmarks exec playwright install chromium
+        run: pnpm --filter octane-js-framework-benchmarks exec playwright install --with-deps chromium
 
       # A failing suite is recorded in its result JSON and rendered in the
       # report, so both trees always run to completion before the verdict.
       # Byte suites are deterministic and run once per tree, both trees at once.
-      # js-framework runs base, head, head, base so runner drift over the job
-      # cancels out.
       - name: Benchmark bundle size
         id: bytes
         run: |
@@ -89,35 +98,35 @@
           done
           echo "status=$status" >> "$GITHUB_OUTPUT"
 
-      - name: Benchmark js-framework
-        id: timing
-        env:
-          TARGETS: ${{ env.JS_FRAMEWORK_TARGETS }}
+      # One harness, the merge commit's, builds and serves both trees' fixtures
+      # and drives them in one browser: exact work counters per operation, then
+      # base and head samples alternating pair by pair (js-framework/pair.mjs).
+      - name: Benchmark js-framework (paired)
         run: |
-          status=0
-          for round in base:1 head:1 head:2 base:2; do
-            side=${round%%:*}
-            tree=$GITHUB_WORKSPACE
-            if [ "$side" = base ]; then tree=$BASE_TREE; fi
-            if (cd "$tree" && node benchmarks/bench.mjs --results-dir="$RESULTS/$side-js-${round##*:}" --servers=octane-tsrx-jsbench,octane-jsx-jsbench js-framework); then :
-            elif [ "$side" = head ]; then status=1
-            else echo "::warning::base js-framework round failed"; fi
-          done
-          echo "status=$status" >> "$GITHUB_OUTPUT"
+          node benchmarks/js-framework/pair.mjs --base-tree="$BASE_TREE" \
+            --base-json="$RESULTS/base/js-framework.json" \
+            --head-json="$RESULTS/head/js-framework.json" \
+            || echo "::warning::paired js-framework benchmark failed; the report names the side"
 
+      # The report exits non-zero for a budget breach, an increased work
+      # counter, or a benchmark that failed on the merge commit. Record that and
+      # fail only after the report is uploaded for the comment workflow.
       - name: Render report
+        id: report
         env:
           RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
           MERGE_SHA: ${{ github.sha }}
           PR_NUMBER: ${{ github.event.pull_request.number }}
         run: |
           mkdir -p "$RESULTS/report"
+          status=0
           HEAD_SHA="$MERGE_SHA" node benchmarks/pr-report.mjs \
-            --base="$RESULTS/base" --head="$RESULTS/head" --rounds=2 \
-            --out="$RESULTS/report/report.md"
+            --base="$RESULTS/base" --head="$RESULTS/head" \
+            --out="$RESULTS/report/report.md" || status=$?
           printf '%s\n' "$PR_NUMBER" > "$RESULTS/report/pr-number"
           printf '%s\n' "$HEAD_SHA" > "$RESULTS/report/head-sha"
           cat "$RESULTS/report/report.md" >> "$GITHUB_STEP_SUMMARY"
+          echo "status=$status" >> "$GITHUB_OUTPUT"
 
       - name: Upload report
         uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
@@ -128,6 +137,6 @@
             ${{ env.RESULTS }}/*/*.json
           retention-days: 14
 
-      - name: Fail when the merge commit's benchmarks failed
-        if: steps.bytes.outputs.status != '0' || steps.timing.outputs.status != '0'
+      - name: Fail on a budget breach, added work, or a failed benchmark
+        if: steps.bytes.outputs.status != '0' || steps.report.outputs.status != '0'
         run: exit 1

diff --git a/.rulesync/skills/performance-audit/SKILL.md b/.rulesync/skills/performance-audit/SKILL.md
--- a/.rulesync/skills/performance-audit/SKILL.md
+++ b/.rulesync/skills/performance-audit/SKILL.md
@@ -38,6 +38,10 @@
      a quick smoke result with a full result.
    - Treat a delta inside observed variance as inconclusive. Prefer ratio guards
      and deterministic counters when wall-clock noise is larger than the claim.
+   - The pull request benchmark gates js-framework production calls and DOM
+     mutations per operation against the merge commit's first parent: any
+     increase fails it. Wall time there is a paired report, called slower or
+     faster only when its 95% interval lies beyond ±3%.
 
 4. **Diagnose**
    - Runtime hot paths: scheduler queues, effect flushing, keyed reconciliation, event delegation, context propagation, refs.

diff --git a/benchmarks/README.md b/benchmarks/README.md
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -150,7 +150,7 @@
   portable only across the same fixture and toolchain. Neither is a CI gate. See
   [`baselines/README.md`](baselines/README.md).
 
-**Pull request report:** `.github/workflows/pr-bench.yml` runs `js-framework` (Octane targets only), `bundle-size`, and `bundle-reachability` on every ready pull request, for both the base commit and the merge commit on the same runner. Byte suites run once per tree; `js-framework` runs base, head, head, base so runner drift during the job cancels out. [`pr-report.mjs`](pr-report.mjs) diffs the two result sets and `.github/workflows/pr-bench-comment.yml` posts the Markdown as one sticky comment. Byte and count changes are reported exactly; a timing change only becomes a verdict outside its combined margin of error (at least 5%), by more than one 0.1ms timer tick, with the fastest sample moving the same way. Timing verdicts are yellow because a single shared runner remains noisy; byte increases are red. The report is informational: it fails only when a suite fails on the merge commit. Reproduce it locally by running the same suites with `--results-dir` in two checkouts, then `node benchmarks/pr-report.mjs --base=<dir> --head=<dir>`. With `--rounds=<n>`, `js-framework` is read from `<dir>-js-1` … `<dir>-js-<n>` and a missing round fails the suite.
+**Pull request report:** `.github/workflows/pr-bench.yml` runs `bundle-size`, `bundle-reachability`, and a paired `js-framework` comparison (Octane targets only) on every ready pull request. The base is the merge commit's first parent, the main commit the pull request would land on, so every delta is the pull request's own; the report says separately how far main has moved past the pull request's recorded base. Byte suites run once per tree. [`js-framework/pair.mjs`](js-framework/pair.mjs), from the merge commit, builds and serves both trees' fixtures and drives them itself. It counts each operation's production-bundle calls (Chromium precise coverage in a `--jitless` browser) and DOM mutations (a `MutationObserver`), which are exact for a fixed build. It then times base and head in one browser, alternating per sample across 30 pairs and looping repeatable operations to about 20ms per sample, and reports the median head/base ratio with a 95% bootstrap interval. [`pr-report.mjs`](pr-report.mjs) diffs the two result sets and `.github/workflows/pr-bench-comment.yml` posts the Markdown as one sticky comment. The job fails when a byte value exceeds its committed budget, when any js-framework work counter increases, or when a suite fails on the merge commit. Wall time is a report only: an operation is called slower or faster when its whole interval lies beyond ±3%. Reproduce it locally from one checkout with another as the base: `node benchmarks/js-framework/pair.mjs --base-tree=<checkout> --base-json=<dir>/base/js-framework.json --head-json=<dir>/head/js-framework.json`, the byte suites with `--results-dir` in each checkout, then `node benchmarks/pr-report.mjs --base=<dir>/base --head=<dir>/head`.
 
 The **compare rule** is noise-aware: an op is a regression only if
 `score > 1.15× baseline` **and** `min > 1.10× baseline`; for sub-1ms ops it must

diff --git a/benchmarks/js-framework/operations.mjs b/benchmarks/js-framework/operations.mjs
new file mode 100644
--- /dev/null
+++ b/benchmarks/js-framework/operations.mjs
@@ -1,0 +1,303 @@
+// The js-framework-benchmark operations and their browser-side gates, shared by
+// the local runner (run.mjs) and the paired pull request harness (pair.mjs) so
+// both drive exactly the same work.
+
+export const ROW_COUNT = 1000;
+export const ROW_COUNT_LARGE = 10000; // matches the canonical suite's runlots / clear table size
+
+export const CANONICAL_OPS = [
+	{ name: 'run', pre: 'empty', click: '#run' },
+	{ name: 'replace', pre: 'rows', click: '#run' },
+	// Canonical krausest "append 1,000 rows to a table of 1,000 rows". The
+	// next op's ensureState sees 2000 rows ≠ 1000 and rebuilds via #run.
+	{ name: 'add', pre: 'rows', click: '#add' },
+	{ name: 'update', pre: 'rows', click: '#update' },
+	{
+		name: 'select',
+		pre: 'rows',
+		click: 'tbody tr:nth-child(5) td:nth-child(2) a',
+		alternateClick: 'tbody tr:nth-child(6) td:nth-child(2) a',
+	},
+	{ name: 'swap', pre: 'rows', click: '#swaprows' },
+	{ name: 'remove', pre: 'rows', click: 'tbody tr:nth-child(5) td:nth-child(3) a' },
+	{ name: 'runlots', pre: 'empty', click: '#runlots' },
+	{
+		name: 'select_lots',
+		pre: 'rows-large',
+		click: 'tbody tr:nth-child(5000) td:nth-child(2) a',
+		alternateClick: 'tbody tr:nth-child(5001) td:nth-child(2) a',
+	},
+	// Canonical js-framework-benchmark `clear` measures clearing the
+	// 10K-row table that `runlots` populated — NOT the 1K-row table from
+	// `run`. The previous `pre: 'rows'` rebuilt 1K rows before the timed
+	// click, so reported numbers were ~10x too fast and not comparable to
+	// the upstream suite. Use `rows-large` to ensure the 10K state first.
+	{ name: 'clear', pre: 'rows-large', click: '#clear' },
+];
+
+// Mount optimizations must retain ordinary live-parent insertion semantics.
+export const DIRECT_LIST_MOUNTS = [
+	{ name: '1k', button: 'run', initialRows: 0, addedRows: ROW_COUNT },
+	{ name: '10k', button: 'runlots', initialRows: 0, addedRows: ROW_COUNT_LARGE },
+	{ name: 'append_1k', button: 'add', initialRows: ROW_COUNT, addedRows: ROW_COUNT },
+	{
+		name: 'prepend_100',
+		button: 'prepend100',
+		initialRows: ROW_COUNT,
+		addedRows: 100,
+		insertion: 'prepend',
+	},
+	{ name: 'append_100', button: 'append100', initialRows: ROW_COUNT, addedRows: 100 },
+	{
+		name: 'middle_100',
+		button: 'insertmid100',
+		initialRows: ROW_COUNT,
+		addedRows: 100,
+		insertion: 'middle',
+	},
+];
+
+export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// Use the same data stream for every target. Label generation is inside the
+// measured create operations, so uncontrolled randomness would add dialect
+// noise through different string lengths and allocation patterns.
+export const seedRandom = (page) =>
+	page.evaluate(() => {
+		let state = 0x5eed5eed >>> 0;
+		Math.random = () => {
+			state = (state + 0x6d2b79f5) | 0;
+			let value = Math.imul(state ^ (state >>> 15), 1 | state);
+			value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
+			return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
+		};
+	});
+
+export async function ensureState(page, pre) {
+	if (pre === 'empty') {
+		await page.evaluate(() => {
+			const btn = document.getElementById('clear');
+			if (btn) btn.click();
+		});
+		await page.waitForFunction(() => document.querySelectorAll('tbody tr').length === 0, {
+			timeout: 5000,
+		});
+	} else if (pre === 'rows') {
+		const cnt = await page.evaluate(() => document.querySelectorAll('tbody tr').length);
+		if (cnt !== ROW_COUNT) {
+			await page.evaluate(() => document.getElementById('run').click());
+			await page.waitForFunction(
+				(n) => document.querySelectorAll('tbody tr').length === n,
+				ROW_COUNT,
+				{ timeout: 5000 },
+			);
+		}
+	} else if (pre === 'rows-large') {
+		const cnt = await page.evaluate(() => document.querySelectorAll('tbody tr').length);
+		if (cnt !== ROW_COUNT_LARGE) {
+			await page.evaluate(() => document.getElementById('runlots').click());
+			await page.waitForFunction(
+				(n) => document.querySelectorAll('tbody tr').length === n,
+				ROW_COUNT_LARGE,
+				{ timeout: 5000 },
+			);
+		}
+	}
+	await sleep(20);
+}
+
+// Time `repeat` clicks and their DOM commits without adding a frame or paint
+// wait, and return the elapsed milliseconds for all of them. A gc() right
+// before each sample keeps a surprise collection from inflating it.
+//
+// Click i targets selectors[i % selectors.length], so a repeated selection
+// alternates rows and every click does real work. Targets are resolved before
+// the timed window, except `remove`, whose target is the new fifth row each time.
+//
+// Targets that schedule a later commit expose window.__benchFlush: Octane uses
+// public flushSync and Vue awaits nextTick. The call stays in the timed window.
+// Verify the resulting DOM after t1, before any further async work, so this
+// semantic gate cannot inflate the timing or accidentally observe a later commit.
+export async function timeClick(page, op, selectors, repeat = 1) {
+	return await page.evaluate(
+		async ({ op, selectors, repeat }) => {
+			const query = (selector) => {
+				const el = document.querySelector(selector);
+				if (!el) throw new Error('selector not found: ' + selector);
+				return el;
+			};
+			const targets = op === 'remove' ? null : selectors.map(query);
+			const first = targets ? targets[0] : query(selectors[0]);
+			const last = targets ? targets[(repeat - 1) % targets.length] : null;
+			const tbody = document.querySelector('tbody');
+			const firstRow = tbody?.querySelector('tr');
+			const secondRow = op === 'swap' ? tbody?.rows[1] : null;
+			const removedRow = op === 'remove' ? first.closest('tr') : null;
+			const oldLabel =
+				op === 'update' ? firstRow?.querySelector('td:nth-child(2) a')?.textContent : null;
+			const flush = window.__benchFlush;
+			(window.gc || (() => {}))();
+			void document.body?.offsetHeight;
+			const t0 = performance.now();
+			for (let i = 0; i < repeat; i++) {
+				(targets ? targets[i % targets.length] : query(selectors[0])).click();
+				if (flush) await flush();
+			}
+			const elapsed = performance.now() - t0;
+			const expectedRows = {
+				run: 1000,
+				replace: 1000,
+				add: 2000,
+				update: 1000,
+				select: 1000,
+				swap: 1000,
+				remove: 1000 - repeat,
+				runlots: 10000,
+				select_lots: 10000,
+				clear: 0,
+				clear_1k: 0,
+			}[op];
+			if (tbody?.rows.length !== expectedRows) {
+				throw new Error(
+					`${op}: commit was not inside timed click (expected ${expectedRows} rows, found ${tbody?.rows.length})`,
+				);
+			}
+			// An even number of swaps restores the original order, so callers that
+			// need the swap verified repeat it an odd number of times.
+			const swappedRow = repeat % 2 === 1 ? tbody.rows[998] : tbody.rows[1];
+			if (
+				(op === 'replace' && firstRow === tbody.rows[0]) ||
+				(op === 'update' &&
+					oldLabel === tbody.rows[0]?.querySelector('td:nth-child(2) a')?.textContent) ||
+				(op === 'swap' && secondRow !== swappedRow) ||
+				(op === 'remove' && removedRow?.isConnected) ||
+				((op === 'select' || op === 'select_lots') &&
+					!last.closest('tr')?.classList.contains('danger'))
+			) {
+				throw new Error(`${op}: the expected DOM change was not committed inside the timed click`);
+			}
+			return elapsed;
+		},
+		{ op: op.name, selectors, repeat },
+	);
+}
+
+export async function verifySelection(page, selector) {
+	await page.evaluate((selector) => {
+		const expected = document.querySelector(selector)?.closest('tr');
+		const selected = document.querySelectorAll('tbody tr.danger');
+		if (expected && selected.length === 1 && selected[0] === expected) return;
+
+		const rowId = (row) => row.querySelector('td')?.textContent || '(missing id)';
+		throw new Error(
+			'selection gate failed: expected only ' +
+				(expected ? rowId(expected) : '(missing row)') +
+				', found ' +
+				(Array.from(selected, rowId).join(', ') || '(none)'),
+		);
+	}, selector);
+}
+
+// Mount optimizations must retain ordinary live-parent insertion semantics.
+// Keep browser-visible instrumentation entirely outside every timed sample.
+export async function verifyDirectListMount(page, operation) {
+	await ensureState(page, operation.initialRows === 0 ? 'empty' : 'rows');
+	return await page.evaluate(async (operation) => {
+		const tbody = document.querySelector('tbody');
+		if (!tbody?.isConnected) throw new Error('mount gate: missing connected table body');
+		const before = Array.from(tbody.querySelectorAll('tr'));
+		if (before.length !== operation.initialRows) {
+			throw new Error(`mount gate: expected ${operation.initialRows} initial rows`);
+		}
+		const rowId = (row) => Number(row.firstElementChild?.textContent);
+		const survivors = new Map(before.map((row) => [rowId(row), row]));
+
+		const work = { liveParentInsertions: 0, fragmentCommits: 0, fragmentRows: 0 };
+		const originals = [];
+		const instrument = (prototype, name) => {
+			const original = prototype[name];
+			if (typeof original !== 'function') return;
+			originals.push([prototype, name, original]);
+			prototype[name] = function (...args) {
+				if (this === tbody) {
+					work.liveParentInsertions++;
+					for (const node of args) {
+						if (node?.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
+							work.fragmentCommits++;
+							work.fragmentRows += node.querySelectorAll('tr').length;
+						}
+					}
+				}
+				return Reflect.apply(original, this, args);
+			};
+		};
+		for (const name of ['insertBefore', 'appendChild', 'replaceChild']) {
+			instrument(Node.prototype, name);
+		}
+		for (const name of ['append', 'prepend', 'replaceChildren']) {
+			instrument(Element.prototype, name);
+		}
+
+		try {
+			const button = document.getElementById(operation.button);
+			if (!button) throw new Error(`mount gate: missing #${operation.button}`);
+			button.click();
+			if (window.__benchFlush) await window.__benchFlush();
+		} finally {
+			for (const [prototype, name, original] of originals.reverse()) {
+				prototype[name] = original;
+			}
+		}
+
+		const rows = Array.from(tbody.querySelectorAll('tr'));
+		const expectedRows = operation.initialRows + operation.addedRows;
+		if (rows.length !== expectedRows) {
+			throw new Error(`mount gate: expected ${expectedRows} rows, found ${rows.length}`);
+		}
+		const insertionIndex =
+			operation.insertion === 'prepend'
+				? 0
+				: operation.insertion === 'middle'
+					? operation.initialRows >> 1
+					: operation.initialRows;
+		const inserted = rows.slice(insertionIndex, insertionIndex + operation.addedRows);
+		const firstInsertedId = rowId(inserted[0]);
+		if (!Number.isSafeInteger(firstInsertedId)) throw new Error('mount gate: invalid row id');
+		let survivorIndex = 0;
+		for (let index = 0; index < rows.length; index++) {
+			const row = rows[index];
+			const id = rowId(row);
+			const isInserted = index >= insertionIndex && index < insertionIndex + operation.addedRows;
+			if (!row.isConnected || !Number.isSafeInteger(id)) {
+				throw new Error(`mount gate: incorrect row identity or connectivity at ${index}`);
+			}
+			if (isInserted) {
+				if (survivors.has(id) || id !== firstInsertedId + index - insertionIndex) {
+					throw new Error(`mount gate: incorrect inserted-row order at ${index}`);
+				}
+			} else if (row !== before[survivorIndex++] || survivors.get(id) !== row) {
+				throw new Error(`mount gate: survivor order or DOM identity changed at ${index}`);
+			}
+		}
+		if (survivorIndex !== before.length) throw new Error('mount gate: missing surviving rows');
+
+		const selectedRow = inserted[Math.min(4, inserted.length - 1)];
+		const action = selectedRow.querySelector('td:nth-child(2) a');
+		if (!action) throw new Error('mount gate: missing row action');
+		action.click();
+		if (window.__benchFlush) await window.__benchFlush();
+		const selected = tbody.querySelectorAll('tr.danger');
+		if (selected.length !== 1 || selected[0] !== selectedRow) {
+			throw new Error('mount gate: inserted-row identity, delegated event, or selection failed');
+		}
+
+		if (work.liveParentInsertions !== operation.addedRows || work.fragmentCommits !== 0) {
+			throw new Error(
+				`mount gate: ${operation.name} required ${operation.addedRows} direct row insertions; ` +
+					`got ${work.liveParentInsertions} live-parent insertions, ` +
+					`${work.fragmentCommits} fragment commits, ${work.fragmentRows} fragment rows`,
+			);
+		}
+		return work;
+	}, operation);
+}

diff --git a/benchmarks/js-framework/pair.mjs b/benchmarks/js-framework/pair.mjs
new file mode 100644
--- /dev/null
+++ b/benchmarks/js-framework/pair.mjs
@@ -1,0 +1,417 @@
+// Paired base/head js-framework comparison: the pull request benchmark's timing
+// and work harness.
+//
+// Both builds are driven by THIS harness, so a pull request that changes the
+// harness cannot make its base look different. It produces two kinds of result
+// for each Octane dialect and each canonical operation:
+//
+// - Work counters (the gate). In a --jitless Chromium, Chromium's precise call
+//   coverage counts every production-bundle function call the operation makes,
+//   and a MutationObserver counts its DOM mutations (inserted and removed nodes,
+//   attribute writes, text writes). Both are exact for a fixed build, so any
+//   increase over the base is real extra work: `calls_<op>` and `dom_<op>`.
+// - Wall time (a report). Base and head pages live in one browser and alternate
+//   per sample, base-first on even pairs and head-first on odd ones, so runner
+//   drift moves both sides of a pair together. An operation that can repeat
+//   (update, select, swap, remove, select_lots) loops until a sample takes about
+//   20ms, which lifts it far off Chromium's 0.1ms timer floor. The head result
+//   carries the median head/base ratio and its 95% bootstrap interval.
+//
+// Run from the repository root:
+//   node benchmarks/js-framework/pair.mjs --base-tree=<checkout> \
+//     --base-json=<file> --head-json=<file> [--pairs=30] [--no-build] [--work-only]
+//
+// `--work-only` collects the exact counters without timing. With the same
+// checkout as both trees it is the determinism control: every counter must match.
+//
+// The head tree is this checkout. Each tree's fixtures are built with its own
+// dependencies and served from its own dist: head on 5176/5177, base on 6176/6177.
+
+import { spawn, spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import net from 'node:net';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { chromium } from 'playwright';
+import { pairedRatio, summarizeSamples, timingStatForJson } from '../lib/stats.mjs';
+import {
+	CANONICAL_OPS,
+	DIRECT_LIST_MOUNTS,
+	ensureState,
+	seedRandom,
+	sleep,
+	timeClick,
+	verifyDirectListMount,
+	verifySelection,
+} from './operations.mjs';
+
+const HEAD_TREE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const options = Object.fromEntries(
+	process.argv
+		.slice(2)
+		.filter((arg) => arg.startsWith('--'))
+		.map((arg) => {
+			const eq = arg.indexOf('=');
+			return eq === -1 ? [arg.slice(2), true] : [arg.slice(2, eq), arg.slice(eq + 1)];
+		}),
+);
+if (!options['base-tree'] || !options['base-json'] || !options['head-json']) {
+	console.error(
+		'usage: node benchmarks/js-framework/pair.mjs --base-tree=<checkout> --base-json=<file> --head-json=<file> [--pairs=30] [--no-build] [--work-only]',
+	);
+	process.exit(2);
+}
+const BASE_TREE = path.resolve(options['base-tree']);
+const PAIRS = Number(options.pairs ?? 30);
+if (!Number.isSafeInteger(PAIRS) || PAIRS < 2) throw new Error('--pairs must be an integer >= 2');
+const SAMPLE_MS = 20;
+const WARMUP = 3;
+// Upper bounds on the repetitions in one sample. Each `remove` deletes a row,
+// so it stays inside the 1,000-row table. A warm selection takes a few
+// microseconds, so it needs thousands of clicks to fill a sample.
+const MAX_REPEAT = { remove: 800, default: 5000 };
+const REPEATABLE = new Set(['update', 'select', 'swap', 'remove', 'select_lots']);
+const FIXTURES = [
+	{ name: 'octane-tsrx', directory: 'octane-tsrx', head: 5176, base: 6176 },
+	{ name: 'octane-jsx', directory: 'octane-jsx', head: 5177, base: 6177 },
+];
+const SIDES = ['base', 'head'];
+const exact = (value) => ({ median: value, min: value, samples: 1 });
+const treeOf = { base: BASE_TREE, head: HEAD_TREE };
+const urlOf = (fixture, side) => `http://localhost:${fixture[side]}/`;
+
+class SideError extends Error {
+	constructor(side, error) {
+		super(`${side}: ${error?.message ?? error}`, { cause: error });
+		this.side = side;
+	}
+}
+const onSide = async (side, work) => {
+	try {
+		return await work();
+	} catch (error) {
+		throw error instanceof SideError ? error : new SideError(side, error);
+	}
+};
+
+function build(side) {
+	const filters = FIXTURES.flatMap(({ name }) => ['--filter', `${name}-jsbench`]);
+	const result = spawnSync('pnpm', ['--dir', treeOf[side], ...filters, 'build'], {
+		stdio: 'inherit',
+	});
+	if (result.status !== 0) throw new SideError(side, `fixture build exited ${result.status}`);
+}
+
+function waitForPort(port, timeoutMs = 30_000) {
+	const deadline = Date.now() + timeoutMs;
+	return new Promise((resolve, reject) => {
+		const attempt = () => {
+			const socket = net.connect(port, 'localhost');
+			socket.once('connect', () => {
+				socket.destroy();
+				resolve();
+			});
+			socket.once('error', () => {
+				socket.destroy();
+				if (Date.now() > deadline) reject(new Error(`nothing listened on :${port}`));
+				else setTimeout(attempt, 200);
+			});
+		};
+		attempt();
+	});
+}
+
+async function serve(side, fixture) {
+	const child = spawn(
+		'pnpm',
+		['exec', 'vite', 'preview', '--port', String(fixture[side]), '--strictPort'],
+		{
+			cwd: path.join(treeOf[side], 'benchmarks/js-framework', fixture.directory),
+			detached: true,
+			stdio: 'ignore',
+		},
+	);
+	child.unref();
+	await onSide(side, () => waitForPort(fixture[side]));
+	return child;
+}
+
+async function openPage(context, fixture, side) {
+	return await onSide(side, async () => {
+		const page = await context.newPage();
+		const errors = [];
+		page.on('pageerror', (error) => errors.push(error.message));
+		page.errors = errors;
+		await page.goto(urlOf(fixture, side), { waitUntil: 'load' });
+		await page.waitForSelector('#run', { timeout: 10_000 });
+		await seedRandom(page);
+		return page;
+	});
+}
+
+const selectorsFor = (op, index, repeat) =>
+	op.alternateClick
+		? repeat > 1
+			? [op.click, op.alternateClick]
+			: [index % 2 === 1 ? op.alternateClick : op.click]
+		: [op.click];
+
+// Repetitions per sample, sized on the head page and shared by both sides, so
+// each pair compares the same work. A looped operation runs far faster than a
+// cold single one, so the count is refined on loops until a sample really takes
+// about SAMPLE_MS; a shorter sample quantizes on the 0.1ms timer.
+const parityFor = (op, repeat) => {
+	// A selection sample ends on the alternate row, so the next one starts by
+	// selecting a different row instead of re-selecting the current one.
+	if (op.alternateClick && repeat % 2 === 1) repeat++;
+	// An even number of swaps restores the original order, which a swap that
+	// did nothing would also leave. An odd count keeps every sample verifiable.
+	if (op.name === 'swap' && repeat % 2 === 0) repeat++;
+	return repeat;
+};
+
+// `update` appends to every tenth label on each click, so a looped sample
+// would leave longer labels for the next one. Each update sample starts from
+// freshly built rows instead.
+async function prepare(page, op) {
+	if (op.name === 'update') {
+		await page.evaluate(() => {
+			const btn = document.getElementById('clear');
+			if (btn) btn.click();
+		});
+		await page.waitForFunction(() => document.querySelectorAll('tbody tr').length === 0, {
+			timeout: 5000,
+		});
+	}
+	await ensureState(page, op.pre);
+}
+
+// Returns the repeat count and every trial count it ran. The trials are replayed
+// on the base page, so both pages run the identical operation sequence and their
+// seeded data streams stay in step.
+async function calibrate(page, op) {
+	if (!REPEATABLE.has(op.name)) return { repeat: 1, trials: [] };
+	const cap = MAX_REPEAT[op.name] ?? MAX_REPEAT.default;
+	const trials = [];
+	let repeat = parityFor(op, 2);
+	for (let round = 0; round < 5; round++) {
+		await prepare(page, op);
+		const elapsed = await timeClick(page, op, selectorsFor(op, 1, repeat), repeat);
+		trials.push(repeat);
+		await sleep(30);
+		if (elapsed >= SAMPLE_MS * 0.8 || repeat >= cap) break;
+		repeat = parityFor(op, Math.min(cap, Math.ceil((repeat * SAMPLE_MS) / Math.max(elapsed, 0.1))));
+	}
+	return { repeat: Math.min(repeat, parityFor(op, cap)), trials };
+}
+
+async function replayCalibration(page, op, trials) {
+	for (const repeat of trials) {
+		await prepare(page, op);
+		await timeClick(page, op, selectorsFor(op, 1, repeat), repeat);
+		await sleep(30);
+	}
+}
+
+async function timeFixture(fixture) {
+	const browser = await chromium.launch({
+		headless: true,
+		args: ['--disable-extensions', '--js-flags=--expose-gc'],
+	});
+	try {
+		const context = await browser.newContext();
+		const pages = {};
+		for (const side of SIDES) pages[side] = await openPage(context, fixture, side);
+		for (const side of SIDES) {
+			await onSide(side, async () => {
+				await pages[side].bringToFront();
+				for (let i = 0; i < WARMUP; i++) {
+					await pages[side].evaluate(() => document.getElementById('run').click());
+					await sleep(120);
+					await pages[side].evaluate(() => document.getElementById('clear').click());
+					await sleep(80);
+				}
+			});
+		}
+
+		const results = { base: {}, head: {} };
+		for (const op of CANONICAL_OPS) {
+			const { repeat, trials } = await onSide('head', async () => {
+				await pages.head.bringToFront();
+				return await calibrate(pages.head, op);
+			});
+			await onSide('base', async () => {
+				await pages.base.bringToFront();
... diff truncated: showing 800 of 2207 lines

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit 1e5e09d. Configure here.

Comment thread benchmarks/js-framework/pair.mjs Resolved
Comment thread benchmarks/pr-report.mjs Resolved
…out of within-budget notes

- The update rebuild clicked #run and then waited for 1,000 rows, which was
  already true, so the rebuild could still be in flight when the timed sample
  began. It now flushes and asserts the rows were replaced.
- A value over its committed budget was also counted as growth within budget in
  the headline. Breached values are now excluded from that note.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-authored Diff or issue body substantially produced by an AI agent ci PR: CI or build pipeline

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant