Performance Testing
performance-tests/ measures rendering and interaction performance with Playwright + CDP traces. It is a standalone package outside the pnpm workspace (own package.json, node_modules, ESLint config). Each scenario traces one interaction, parses the trace into DevTools categories (scripting, rendering, painting, idle), and produces a markdown PR comment plus an HTML report compared against a golden baseline from develop. Fuller reference: performance-tests/README.md.
Package structure
scripts/run.mjs (build HOT UMD, copy to fixtures/, run Playwright), scripts/replay-goldens.mjs (replays gh-pages develop goldens to re-derive the gate's lines), trace-parser.mjs, lib/ (trace-runner.mjs owns HARNESS_VERSION; environment.mjs, snapshot-store.mjs, median-snapshot.mjs, thresholds.mjs, hook-timing.mjs, scroll-utils.mjs, fs-utils.mjs, teardown.mjs, report builders), scenarios/<name>/{scenario.config.mjs, fixture.html, <name>.spec.ts}. Playwright runs sequentially, 1 worker, 5 min timeout, chromium only. fixtures/, golden/ (fetched from gh-pages) and output/ are gitignored.
Adding a scenario
Three files in scenarios/<name>/.
1. scenario.config.mjs
// Grid: <rows> x <cols> -- <rationale for this grid size>
export default {
name: 'my-scenario', // must equal the directory name
warmupRuns: 1,
iterations: 3,
measurementVersion: 1,
};
name determines output/<name>/, and teardown reads measurementVersion by that name. Comment the grid size and why.
Bump measurementVersion when the spec changes what the marked window contains or when iterations changes: the median baseline draws only on develop goldens at the same version. HARNESS_VERSION covers runner-wide changes; when both change in one PR the harness bump already restarts the golden pool, so skip the scenario bump and say so in the config comment.
2. fixture.html
Standalone page that exposes the instance as window.__hot:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Scenario</title>
<link rel="stylesheet" href="../../fixtures/handsontable.css">
<script src="../../fixtures/handsontable.full.js"></script>
<script src="../../fixtures/test-license-key.js"></script>
</head>
<body>
<div id="hot"></div>
<script>
window.__hot = new Handsontable(document.getElementById('hot'), {
data: Handsontable.helper.createSpreadsheetData(5000, 10),
rowHeaders: true, colHeaders: true, width: 1280, height: 600,
autoRowSize: false, autoColumnSize: false,
licenseKey: window.htTestLicenseKey,
});
</script>
</body>
</html>
Set autoRowSize: false and autoColumnSize: false (async sizing interferes with measurements). CSS is handsontable.css (no full CSS variant); JS is handsontable.full.js.
The license key comes from window.htTestLicenseKey, set by fixtures/test-license-key.js, never as a literal: a grid without a valid key gets the lock screen, so a new test key is a one-line change there. scripts/__tests__/test-license-key.test.mjs (root test:tooling) fails on a literal key in a fixture. That file is the one .js in fixtures/ git tracks; both .gitignore files there ignore the copied bundles and keep it by name.
3. Spec
import { test } from '@playwright/test';
import path from 'node:path';
import { runTracedScenario } from '../../lib/trace-runner.mjs';
import config from './scenario.config.mjs';
const fixturePath = path.resolve(import.meta.dirname, 'fixture.html');
test(config.name, async({ page }) => {
await page.goto(`file://${fixturePath}`);
await page.waitForFunction(() => (window as any).__hot, undefined, { polling: 100 });
await runTracedScenario({
page,
warmupRuns: config.warmupRuns,
iterations: config.iterations,
outputDir: path.resolve('output', config.name),
actionFn: async() => { /* measured action */ },
// optional: setupFn, resetFn, afterActionFn, skipSettle
});
});
runTracedScenario creates the output dir, runs untraced warmups, runs traced iterations, and writes iteration-{n}.json. Add a resetFn for repeatable actions, otherwise iterations 2+ start from iteration 1's end state.
Hook timing (filtering/sorting)
import { injectHookTimer, getHookTiming, saveHookTimings } from '../../lib/hook-timing.mjs';
await injectHookTimer(page, 'beforeFilter', 'afterFilter'); // before tracing; call again in resetFn (idempotent, resets the store)
const hookDeltas: number[] = [];
// in runTracedScenario:
afterActionFn: async() => { // afterActionFn, because getHookTiming is a page.evaluate and inside actionFn its CDP round trip is measured as part of the operation
const timing = await getHookTiming(page, 'beforeFilter', 'afterFilter');
if (timing.deltaMs != null) hookDeltas.push(timing.deltaMs);
},
await saveHookTimings(path.resolve('output', config.name), hookDeltas); // writes hook-timing.json; teardown picks it up
Scroll helpers
scrollToRow(page, row) and scrollToColumn(page, col) from lib/scroll-utils.mjs combine scrollViewportTo() with a deterministic waitForFunction on the index mapper; use them in place of waitForTimeout.
Existing scenarios
Listed under scenarios/: scroll-down/up/right/left (500 wheel events each; up and left pre-scroll via scrollToRow/scrollToColumn), row-selection-scroll (scroll-down with rowSelection and every other row selected), column-autosize-refill (a column resize that makes wrapped rows shrink and refills the row band), filtering, sorting, cell-editing (5000x10), initial-load, initial-load-autosize (the same build at 100000x50 with the default autoColumnSize; guards the cell budget of the column sweep's synchronous part), source-data-validator-load (initial-load's fixture plus the one option), undo-edit, undo-sort, undo-remove-rows (redo in resetFn), set-cell-meta-loop (50000 setCellMeta() calls, one undo step each; the per-step undo bookkeeping), row-selection-select-all, row-selection-deselect-all, checkbox-header-toggle, checkbox-column-set-data (the PRO-87 row selection and "check all" paths), sheetsbar-structural-ops (a row insert and a removal in a 10-sheet SheetsBar workbook on one HyperFormula engine; the Formulas plugin's per-sheet peer cache), paste-extend-rows (a 10000x10 copyPaste.paste() on the last row of a 100x10 grid, so the grid creates the missing rows; guards the batched row creation), validate-cells (a validateCells() pass over a 5000x20 grid of text and numeric columns, awaited to its callback; guards the per-cell microtask bookkeeping in core), get-data (a full-grid getData(); guards the per-column work of a bulk read), pagination-next-page (twenty nextPage() calls on a 100000x20 grid with pageSize: 50; guards the single write of the page's hiding map), search-query (a search.query() over a freshly loaded 100000x20 grid; guards that the query keeps cell meta for its matches only). Filtering, sorting, paste-extend-rows and the undo scenarios use hook timing. Grids are 10000x50 (vertical scroll), 10x5000 (horizontal scroll), 100000x50 (row-selection-scroll, initial-load-autosize), 2000x200 (column-autosize-refill), 10 sheets of 10000x10 (sheetsbar-structural-ops), 100x10 (paste-extend-rows), 5000x20 (validate-cells), 100000x20 (pagination-next-page, search-query), 10000x50 (set-cell-meta-loop), 100000x100 (the rest).
Iterations: 3 for scroll, row-selection-scroll, cell-editing, column-autosize-refill, set-cell-meta-loop and initial-load-autosize; 5 for filtering, sorting, initial-load, source-data-validator-load, undo-edit, undo-sort, undo-remove-rows, row-selection-select-all, row-selection-deselect-all, checkbox-header-toggle, checkbox-column-set-data, sheetsbar-structural-ops, paste-extend-rows, validate-cells, get-data, pagination-next-page, search-query. Each of those seventeen states its reason in its scenario.config.mjs (short windows on a 300 to 350 MB heap where one GC pause moves a mean of three by 10 to 20%; for source-data-validator-load, a 20% run-to-run spread after removing the runner factor). lib/__tests__/scenario-configs.test.mjs pins the counts, so change config and test together. Keep the scroll scenarios at 3: each iteration is 500 wheel round trips.
Run commands
cd performance-tests && node scripts/run.mjs # build HOT + copy fixtures + run all
npx playwright test --grep "scroll-down" # one scenario (fixtures must exist)
PERF_MODE=golden node scripts/run.mjs # save baseline snapshot
PERF_MODE=compare node scripts/run.mjs # load golden, generate delta report
npm run lint
npm run typecheck # spec files
handsontable/dist/ and handsontable/styles/ must exist before running npx playwright test directly; scripts/run.mjs builds them.
CI workflow
Two entry points on the single self-hosted runner:
pushtodevelop(develop.yml→.github/workflows/performance-tests.yml): runs all scenarios ingoldenmode, deployssnapshots.json+report.htmltogh-pagesunderperformance-reports/develop/<timestamp>/, updateslatest.json(the pointer for PR comparisons), and builds a history index page. The run is also compared against the trailing median of compatible develop goldens, for its report, job summary and one::warningannotation per regressed scenario. The snapshot it saves is never derived from history (teardown saves before it loads). Never gated.pull_request(test.yml→.github/workflows/performance.yml→ the.github/actions/performance-runcomposite): fetches the last 20 develop goldens intogolden/history/(pluslatest.jsonas a single-file fallback), runs all scenarios incomparemode, re-runs the failing ones, posts a sticky PR comment (the gate's verdict, the scenarios that need attention, the full table folded), deploys the HTML report toperformance-reports/<branch-slug>/, and ends with the regression gate.
Push retries with rebase (up to 3 attempts) for concurrent gh-pages writes.
Baseline compatibility and provenance
All in lib/environment.mjs. A Playwright bump (new Chromium) once shifted initial-load by -18% and sorting by -20% in one develop push, and the median-of-5 baseline carried the old browser's numbers for five more pushes.
- Provenance.
lib/setup.mjs(PlaywrightglobalSetup) records the Chromium build (browser.version()), CPU model and count, memory, platform and GitHub runner image intooutput/environment.json. Teardown stamps it on the snapshot (environment,harnessVersion); both reports print it in the footer. - Compatibility key.
{ chromium, platform, harnessVersion }per snapshot,measurementVersionper scenario.computeMedianSnapshot(..., { compatibleWith })draws only on goldens with the same key, and within a scenario only on entries at the samemeasurementVersion. A golden without the provenance fields is excluded, as a pre-marks golden is bywindowSource. With no compatible golden the comment says "no comparable baseline" and why (describeKeyMismatch, or one ofBASELINE_REFUSALSinsnapshot-store.mjs: empty history, no marks-valid golden, every scenario redefined, disjoint scenarios, emptylatest.json). With exactly one, the single-file fallback serves and the footer says "single develop run"; the median needs two. BumpHARNESS_VERSIONintrace-runner.mjswhen the runner changes what a window contains (settle, GC between iterations, work moved in or out); bump a scenario'smeasurementVersionwhen only that spec's definition changes. - Run shift. The comment's
Δ vs shiftcolumn and the footer'sRun shiftline give the median delta across scenarios (how much faster or slower this runner ran than the baseline's; within ±1% on the Apple M1 runner since 2026-09-15, 0.63x–1.12x on the shared runners before it). The gate judges the rawΔ Total, because a change that slows every scenario alike is invisible to a median; a shift above +5% fails the run on its own.
scripts/replay-goldens.mjs groups goldens by key before replaying; its Compatibility groups block shows the counts per group.
Regression gate
The rules, the numbers behind them, and the approval flow are in performance-tests/README.md → "Thresholds" and "Regression gate". lib/gate.mjs decides the verdict in the teardown; scripts/enforce-gate.mjs (the composite's last step) exports verdict; performance.yml's approve job waits on the performance-approval environment when it is regressed. Traps:
globalSetupandglobalTeardownrun on everyplaywright testcall, so the confirm re-run (a secondplaywright testover the failing spec files,scripts/run.mjs) runs the teardown again. That teardown knows it is the re-run fromPERF_CONFIRM_PASSand mergesoutput/verdict-first-pass.json. The first traces go tooutput/first-pass/<name>/, one level down, because the teardown reads onlyiteration-*.jsondirectly insideoutput/<name>/; anything at that level would be averaged in.- An unset
verdictmust only ever come with a red job.approvekeys on the output, so a green run with no output would skip the approval and merge a regression unreviewed. The enforce step stays last, has nocontinue-on-error, and writesGITHUB_OUTPUTbefore it sets the exit code;approvecarries!failure()..github/scripts/__tests__/perf-gate-step.test.mjspins all of it, including thatapprove'sif:keys onOUTCOMES.REGRESSED. - The re-run clears only what it measured again. "Not failing on the second pass" is not "cleared": a re-run scenario whose capture came back incomplete, or that left no traces, is in neither list.
confirmVerdictclears from the second pass'sjudgednames only and keeps any other first-pass failure asrerun.unconfirmed, which still fails. Same principle as the unsetverdict: the gate never passes what it could not see. - The run shift is decided once, on the first pass. The second pass's rows mix re-run rows with first-pass rows, so its median is not a measurement of anything: with up to 4 rows re-run it can clear a real shift failure or, through a fast row that failed on heap, invent one.
confirmVerdicttakesshift,newestShift,shiftFailedandreasonfrom the first pass, and both reports show that number. - The confirm re-run is part of the job's time budget.
perf-artifact-download.test.mjsderives the PR job'stimeout-minutesfrom the scenario count, the Playwright timeout andCONFIRM_MAX_SCENARIOS; raise one and the test asks for the matching timeout. The re-run, the rules line and the "what happens next" text are on only where the run setsPERF_GATED(isGatedRun): the composite's pull request path.performance-tests.ymlalso compares on onepull_requestpath, with no enforce step, noapprovejob and a 166-minute budget, so it must never set it; the test holds each job'sconfirmsequal to whether it does. - A line moves only through the replay. Change
GATE_*or a heap threshold afternode scripts/replay-goldens.mjs --since <date>says where the knee is, and quote its gate section in the pull request. The reports' red band followsGATE_TIMING_THRESHOLD. - Warn first.
GATE_MODEinlib/gate.mjsis'warn'until the warn period'sperf-gatenotices show no false would-fail (count them from the check run's annotations: the job log prints them as##[notice]status=…and drops the title);'block'also needs theperformance-approvalenvironment to exist with required reviewers.
The trace pipeline
The measured window (read before adding a scenario)
Everything published describes the slice between the two performance.marks that runTracedScenario() writes around the action.
- Keep harness round trips out of
actionFn: apage.evaluatethat reads a value back is measured as part of the operation. Put readbacks inafterActionFn, which runs after the end mark. - Script run straight from
page.evaluatecounts only on a named frame. No trace event wraps it (a timer, event or frame callback would), sotrace-parser.mjsbills it from CPU samples, andcomputeProfileCallScriptingdrops a sample whose frame name is empty (''is inIDLE_NAMES). Anonymous functions have that name, and V8 inlining moves a small named helper's samples onto its caller. A 15 ms busy-wait in an anonymouspage.evaluatecallback read as +2 ms on CI; pass a named function declaration instead. The same rule hides Handsontable's own anonymous callbacks on that path, 12–16% of scripting in the checkbox, filtering and undo-remove-rows scenarios. Counting''changes those numbers, so it needs aHARNESS_VERSIONbump. - A
resetFnmust leave no frame behind. The runner settles aftersetupFnandresetFn, andskipSettledoes not turn those off.scrollToRow/scrollToColumnreport trimming, not scroll position, so theirwaitForFunctionreturns before the scroll has rendered.
A category measured as exactly 0, or a CV of sqrt(n) × 100% (one nonzero iteration among zeros: 173.21% at three iterations, 223.61% at five, using the sample standard deviation calcCv uses), means the window is wrong, not that the operation was cheap.
- Spec calls
runTracedScenario(): forced GC (over a control CDP session),Tracing.start, start mark, action, settle, end mark,afterActionFn, forced GC +Runtime.getHeapUsagereadback,Tracing.end-> raw JSON per iteration, plusheap-after-gc.jsonper scenario. The GC before tracing keeps the previous reset's garbage out of the window (initial-load's third iteration read ~50% slower before it); the readback is recorded asupdateCounters.jsHeapAfterGcBytes. Both are part ofHARNESS_VERSION2. - Teardown (
lib/teardown.mjs) runsparseTrace()(trace-parser.mjs) onoutput/*/iteration-*.json, measuring the marked window (the auto-zoomed window only for traces recorded without marks), averages viaaverageParsedTraces(), collects per-iteration values for CV%, and strips_iterationValuesand_debugfrom saved snapshots. PERF_MODE=golden:snapshot-store.mjssaves averaged results for gh-pages.PERF_MODE=compare: teardown loads the golden and the report shows deltas.
Shared utilities
Import from lib/ (fs-utils.mjs exists, scroll-utils.mjs, hook-timing.mjs, environment.mjs, thresholds.mjs) in specs and scripts. thresholds.mjs is the single source of the gate's lines and the colour bands: reference them from there, never restate either number elsewhere, and derive any retune from scripts/replay-goldens.mjs, never by eye. Heap has per-scenario overrides in HEAP_THRESHOLDS_BY_SCENARIO (the horizontal-scroll scenarios' peak heap is GC timing, CV 4.4-6.3%); read them through heapThresholdFor(name). Never read REGRESSION_CALLOUT_THRESHOLD_HEAP directly at a render site: a bypass disagrees with the gate.
.mjs convention
Follow node-scripts-dev. .mjs files are plain JavaScript: use /** @type {any} */ (window) JSDoc casts instead of as any.
Common mistakes
| Mistake | Fix |
|---|---|
| npx playwright test without built fixtures | Run node scripts/run.mjs or build HOT and copy dist files |
| waitForFunction() without { polling } | The rAF default is starved on a loaded machine. Pass undefined, { polling: 100 }; the tier's eslint config bans the default |
| waitForTimeout() for scroll/render waits | scrollToRow() / scrollToColumn(), or waitForFunction with a renderable-index check |
| Changing a window's contents without a version bump | Bump HARNESS_VERSION (lib/trace-runner.mjs) for a runner change, or the scenario's measurementVersion for a spec change; otherwise the median averages two definitions of the scenario for five develop pushes |
| Gating on Δ vs shift | Gate on the raw delta; the shift is a median across scenarios and is shown beside it for the reader to weigh |
| Tuning a gate line by eye | Re-run scripts/replay-goldens.mjs and move the line to the knee of its curve; it replays the gate rule for rule |