The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Shape the bundle load benchmark with tc netem, and make its rows comparable between runners (#83827)
Romeo Van Snick0901122171fc
diff --git a/.github/scripts/upload-bundle-load-stats.ts b/.github/scripts/upload-bundle-load-stats.tsindex 3178e002bed..1cf68c275da 100644--- a/.github/scripts/upload-bundle-load-stats.ts+++ b/.github/scripts/upload-bundle-load-stats.ts@@ -1,8 +1,9 @@// Appends the measured load times to the "Bundle Load Times" table in// eng-stats-importer. Reads ROWS (the JSON matrix.js prints) and API_KEY from-// env, and stamps each row with the commit it came from.+// env, and stamps each row with the commit it came from. Writes the same rows to+// a CSV file next to ROWS, and appends them only when UPLOAD is "true".-import { readFileSync } from "node:fs";+import { readFileSync, writeFileSync } from "node:fs";import { importStats } from "./stats-import";@@ -17,6 +18,8 @@ interface Condition {warmMs: number;steadyMs: number;coldSpreadPercent: number;+ warmSpreadPercent: number;+ steadySpreadPercent: number;coldTtfbMs: number;coldFirstPaintMs: number;coldAppMountedMs: number;@@ -32,6 +35,8 @@ interface Condition {cssKb: number;totalKb: number;runs: number;+ cpuModel: string;+ calibrationMs: number;}interface CommitStamp {@@ -65,6 +70,10 @@ function buildRows("Warm ms": condition.warmMs,"Steady ms": condition.steadyMs,"Cold spread %": condition.coldSpreadPercent,+ // The returning-user readings carry their own spread, because each comes+ // from a batch of short series rather than from one load.+ "Warm spread %": condition.warmSpreadPercent,+ "Steady spread %": condition.steadySpreadPercent,// The cold load broken up. A zero means the browser or the route never// reported that one, rather than that it happened at time zero."Cold ttfb ms": condition.coldTtfbMs,@@ -82,9 +91,21 @@ function buildRows("Css kb": condition.cssKb,"Total kb": condition.totalKb,Runs: condition.runs,+ "CPU model": condition.cpuModel,+ "Calibration ms": condition.calibrationMs,}));}+function toCsv(rows: LoadTimeRow[]): string {+ const columns = Object.keys(rows[0]);+ const toCell = (value: string | number) => {+ const text = String(value);+ return /[",\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;+ };+ const lines = [columns, ...rows.map((row) => columns.map((key) => row[key]))];+ return lines.map((cells) => cells.map(toCell).join(",")).join("\n") + "\n";+}+async function main() {const path = process.env.ROWS || "artifacts/load-times.json";// matrix.js wrote this file, and Condition is the shape it prints.@@ -93,10 +114,18 @@ async function main() {const rows = buildRows(conditions, {sha: process.env.HEAD_SHA || "",subject: process.env.COMMIT_MESSAGE || "",- timestamp: new Date(process.env.COMMIT_TIMESTAMP || Date.now()).toISOString(),+ timestamp: new Date(+ process.env.COMMIT_TIMESTAMP || Date.now(),+ ).toISOString(),});console.table(rows);+ writeFileSync(path.replace(/\.json$/, ".csv"), toCsv(rows));++ if (process.env.UPLOAD !== "true") {+ console.log("UPLOAD is not true, so the rows stay in the CSV file");+ return;+ }try {await importStats({ table: "bundle_load_times", rows });diff --git a/.github/workflows/test.bundle-load-stats.yml b/.github/workflows/test.bundle-load-stats.ymlindex ebc2a4732e0..50b20c80e61 100644--- a/.github/workflows/test.bundle-load-stats.yml+++ b/.github/workflows/test.bundle-load-stats.yml@@ -24,6 +24,20 @@ on:type: stringrequired: falsedefault: ""+ harness_ref:+ description: >+ Ref to take the benchmark and its scripts from. Defaults to the+ measured commit, which is what the per-merge path wants. A backfill+ passes one ref for every commit it measures, so the harness is held+ still and only the jar changes.+ type: string+ required: false+ default: ""+ upload:+ description: "Append the rows to eng-stats-importer."+ type: boolean+ required: false+ default: false# A later attempt must not cancel the first one: the concurrency group applies# before any job `if`, so a run that goes on to skip every job still cancels.@@ -59,7 +73,7 @@ jobs:needs: [uberjar-built]if: ${{ needs.uberjar-built.outputs.found == 'true' }}runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}- timeout-minutes: 20+ timeout-minutes: 30env:HEAD_SHA: ${{ inputs.commit || github.event.workflow_run.head_sha }}MB_JETTY_PORT: "4000"@@ -74,7 +88,9 @@ jobs:- name: Check out the codeuses: actions/checkout@v7with:- ref: ${{ env.HEAD_SHA }}+ # Only the harness comes from this tree. The app under test is the+ # downloaded uberjar, so a backfill can hold this still.+ ref: ${{ inputs.harness_ref || env.HEAD_SHA }}- uses: ./.github/actions/prepare-node-bun- name: Prepare JDK 25uses: actions/[email protected]@@ -135,13 +151,33 @@ jobs:- name: Show the Metabase log if something went wrongif: failure()run: tail -100 artifacts/metabase.log || true+ - name: Resolve the commit stamp+ if: ${{ inputs.commit != '' }}+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ # `workflow_run.head_commit` is empty on a workflow_call, and the tree+ # checked out above is the harness rather than the measured commit, so+ # the subject and the date come from the API.+ commit=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${HEAD_SHA}")+ subject=$(printf '%s' "$commit" | jq -r '.commit.message' | head -1)+ # A random delimiter, because the subject is untrusted text that could+ # otherwise close the heredoc early.+ delimiter="STAMP_$(openssl rand -hex 8)"+ {+ echo "COMMIT_SUBJECT<<${delimiter}"+ echo "$subject"+ echo "${delimiter}"+ printf 'COMMIT_STAMP=%s\n' "$(printf '%s' "$commit" | jq -r '.commit.committer.date')"+ } >> "$GITHUB_ENV"+- name: Import load times into Stats- if: ${{ inputs.commit == '' }}env:+ UPLOAD: ${{ inputs.commit == '' || inputs.upload }}# Passed via env (not interpolated into the shell) so the commit# message can't inject commands; the script keeps only the subject.- COMMIT_MESSAGE: ${{ github.event.workflow_run.head_commit.message }}- COMMIT_TIMESTAMP: ${{ github.event.workflow_run.head_commit.timestamp }}+ COMMIT_MESSAGE: ${{ github.event.workflow_run.head_commit.message || env.COMMIT_SUBJECT }}+ COMMIT_TIMESTAMP: ${{ github.event.workflow_run.head_commit.timestamp || env.COMMIT_STAMP }}ENG_STATS_URL: ${{ secrets.ENG_STATS_URL }}API_KEY: ${{ secrets.ENG_STATS_API_KEY }}run: |@@ -150,3 +186,10 @@ jobs:ROWS="artifacts/load-times-${locale}.json" \bun .github/scripts/upload-bundle-load-stats.tsdone+ - name: Keep the rows of a called run+ if: ${{ inputs.commit != '' }}+ uses: actions/upload-artifact@v7+ with:+ name: bundle-load-rows-${{ env.HEAD_SHA }}+ path: artifacts/load-times-*.csv+ if-no-files-found: errordiff --git a/frontend/test/bench/README.md b/frontend/test/bench/README.mdindex 347186b1284..efba9b55173 100644--- a/frontend/test/bench/README.md+++ b/frontend/test/bench/README.md@@ -58,17 +58,59 @@ it.Each state reports the readings of a single load. It does not take a separatemedian for each reading.-For cold and steady, the harness runs the page several times and then picks the-run whose DOMContentLoaded is the median of that series. Every reading in the-state comes from that one run. The second visit happens once per browser-profile, so that state is the run itself.+For cold, the harness runs the page several times and then picks the run whose+DOMContentLoaded is the median of that series. Every cold reading comes from+that one run.A separate median per reading describes a load that never happened. It can alsoput the readings out of order, and print a page-ready that precedes the TTFBbeside it.-`Cold spread %` still comes from all the cold runs, because a spread is a-property of the series rather than of one load.+A second visit happens once per browser profile, so one cache-kept series can+only ever produce one of them. The harness therefore runs several short+cache-kept series, each in its own profile, and picks the series whose reading is+the median of the batch. The warm and the steady state pick their series+independently, because they are different loads already. Three profiles of three+loads cost about what one series of eight did.++The spreads come from every run or series behind a state, because a spread is a+property of the batch rather than of one load. All three states carry one, so a+reading can be told from noise without a second run of the job.++## How the network is shaped++The network comes from `tc netem` on the loopback interface, not from the+browser. Browser throttling is applied per request, so it charges every byte the+bandwidth rate wherever that byte sits in the response. A layout that pushes the+script tags past the initial congestion window costs a whole round trip instead,+and only packet-level shaping reproduces that. Measured on the slow condition,+the two models disagree by about 7x on a document that crosses the boundary.++This makes the harness Linux only, and it needs root for `tc`. CI runs on Ubuntu+with passwordless sudo, which is the only place it has to work.++Three details decide whether a reading means anything:++- **Loopback runs at a 65536-byte MTU.** The window is counted in segments, so+ at that MTU the initial ten-segment window holds about 640 kB. Every document+ fits in one flight and the reading comes out the same whatever the layout+ does. `measure.ts` forces `lo` to 1500 and puts it back on exit.+- **Only the backend port is shaped.** The harness drives Chrome over CDP on+ loopback as well. Delaying that channel would move the moment each reading is+ taken without moving the load the reading describes, so a `prio` qdisc and+ four `u32` filters scope netem to the port in the measured URL.+- **A packet crosses `lo` egress once per direction**, so netem is given half of+ `NETWORK_LATENCY`. The variable stays a round trip, the same thing it meant+ when the browser supplied it.++`measure.ts` reads back the MTU and the qdisc after it applies them, and exits+non-zero when either is missing. An unshaped run still reports plausible times,+so a silent failure would be read as a result.++Every load opens its own connection. Chrome would otherwise reuse the one the+load before it left open and skip the handshake, which on the slow network is+150 ms the reading then lacks. `measure.ts` closes the connections to the+backend before each load, and exits non-zero when any stays open.## Running it against a real Metabase@@ -126,12 +168,16 @@ WARM=1 CPU_THROTTLE=4 bun frontend/test/bench/measure.ts http://127.0.0.1:8099/| ----------------- | ------------ | -------------------------------------------------------- || `CPU_THROTTLE` | `4` | CPU slowdown, so a laptop stands in for a slower machine || `NETWORK_MBPS` | `10` | throughput, `0` to leave the network alone |-| `NETWORK_LATENCY` | `40` | added latency in ms |+| `NETWORK_LATENCY` | `40` | added round trip in ms, split half per direction || `WARM` | unset | keep the cache between runs, to measure a returning user || `SESSION_COOKIE` | unset | `metabase.SESSION`, to load the page signed in || `PORT_OFFSET` | `0` | added to the debugging port `9222` || `CHROME_PATH` | macOS Chrome | the browser binary |+Setting `NETWORK_MBPS=0` leaves the network alone, which also leaves the MTU+alone. Those numbers answer a question about parse and execute, and they cannot+be compared against a shaped run.+## What CI records`.github/workflows/test.bundle-load-stats.yml` runs the matrix on every master@@ -142,7 +188,25 @@ does not create one on demand, and a push to a table it does not know returns a4xx. The upload treats any failure as a warning and leaves the run green, so amissing table shows up as an empty chart rather than a red build.+A called run, which is how a backfill measures a commit, also keeps its rows as+a `bundle-load-rows-<sha>` artifact with one CSV file per locale. The columns are+the columns of the table, so the files of a run can be joined and imported by+hand.++The workflow that calls it for a list of old commits is not on master. It is+`test.bundle-load-stats-backfill.yml` on the `bundle-load-backfill-parallel`+branch, and it can be dispatched from there. It builds an uberjar for a commit+whose jar has expired, since CI keeps one for 30 days.++`Scripts`, `Script kb`, `Css kb` and `Total kb` count what the page fetched+before DOMContentLoaded. A chunk that a route loads after that event is not in+them, which keeps the counts the same for a build that records no performance+marks.+The conditions are a fast and a slow network crossed with a fast and a slow CPU.+Neither CPU condition runs unthrottled: a throttle of 1 leaves the reading at the+mercy of whichever CPU the runner drew, which is the largest source of spread in+this table.The split matters: a slow network dominates the cold reading, because that isbytes on the wire, and a slow CPU dominates the warm one, because that is parseand execute. A change that trades bytes for execution moves one and not the@@ -150,6 +214,21 @@ other.Times are relative to the machine that runs them. A CI runner is slower than alaptop, so read a number against the same runner's history and not against a-number from anywhere else. Each row carries `Cold spread %`, the interquartile+number from anywhere else. Each row carries `Cold spread %`, `Warm spread %` and+`Steady spread %`, the interquartilespread of its cold runs, which is what tells a real regression from a busyrunner.++The spread is measured inside one job, so it does not show the difference+between runners. Runners of the same class have different CPU models, and the+same page loads up to 1.7 times faster on one than on another. Each row+therefore carries two more columns:++- `CPU model`, from `/proc/cpuinfo`.+- `Calibration ms`, how long a fixed workload takes in the same Chrome under the+ same CPU throttle. It runs before and after the loads of each series.++A reading divided by what its CPU model and its calibration predict varies by+about 0.5% to 4% between runners, where the raw reading varies by 3% to 17%.+The calibration alone does not compare across CPU models, so the correction+needs a factor per model, fitted from the rows of the table.diff --git a/frontend/test/bench/matrix.ts b/frontend/test/bench/matrix.tsindex a0ac89029a1..ad8fe0bbfbf 100644--- a/frontend/test/bench/matrix.ts+++ b/frontend/test/bench/matrix.ts@@ -19,6 +19,7 @@* signed in.*/import { spawn } from "node:child_process";+import fs from "node:fs";import path from "node:path";/** One reading, as `timings` in `measure.ts` builds it. */@@ -43,6 +44,7 @@ interface Series {secondLoad: Timings | null;steady: Timings | null;everyRunMs: number[];+ calibrationMs: number;}interface Conditions {@@ -51,6 +53,8 @@ interface Conditions {throttle: number;warm: boolean;offset: number;+ /** Loads in this series. Defaults to the run count on the command line. */+ loads?: number;}const url = process.argv[2];@@ -75,22 +79,63 @@ const NETWORKS = {slow: { mbps: 5, latency: 150 },};-/** CPU slowdown, where 1 leaves the runner at its own speed. */-const CPUS = { fast: 1, slow: 4 };+/**+ * CPU slowdown. Neither condition is 1, because 1 leaves the reading at the+ * mercy of whichever CPU the runner happened to draw, and a throttle absorbs+ * some of that spread rather than passing it straight through.+ */+const CPUS = { fast: 2, slow: 4 };++/**+ * A second visit happens once per browser profile, so one cache-kept series can+ * only ever produce one of them. Several short series in their own profiles give+ * that reading a median and a spread for about the loads one long series costs.+ */+const WARM_PROFILES = 3;+const WARM_LOADS = 3;++/**+ * A series takes a minute or two. A Chrome that stops answering leaves+ * `measure.ts` waiting on its debugging socket without a bound, so past this+ * the series is stopped and measured again.+ */+const SERIES_TIMEOUT_MS = 5 * 60 * 1000;+const RETRY_PORT_OFFSET = 1000;-function measure({+async function measure(conditions: Conditions): Promise<Series> {+ try {+ return await measureOnce(conditions);+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ console.error(`${reason}, measuring the series again`);+ // A new port, because the Chrome that hung may still hold the old one.+ return measureOnce({+ ...conditions,+ offset: conditions.offset + RETRY_PORT_OFFSET,+ });+ }+}++function measureOnce({mbps,latency,throttle,warm,offset,+ loads,}: Conditions): Promise<Series> {return new Promise<Series>((resolve, reject) => {const child = spawn(process.execPath,- [path.join(import.meta.dirname, "measure.ts"), url, String(runs)],+ [+ path.join(import.meta.dirname, "measure.ts"),+ url,+ String(loads ?? runs),+ ],{stdio: ["ignore", "pipe", "inherit"],+ // Its own process group, so stopping it also stops its Chrome.+ detached: true,env: {...process.env,NETWORK_MBPS: String(mbps),@@ -104,13 +149,22 @@ function measure({},);+ const timeout = setTimeout(() => {+ if (child.pid) {+ process.kill(-child.pid, "SIGKILL");+ }+ }, SERIES_TIMEOUT_MS);+let output = "";child.stdout.on("data", (chunk) => (output += chunk));- child.on("exit", (code) =>- code === 0- ? resolve(JSON.parse(output))- : reject(new Error(`measure.ts exited with ${code}`)),- );+ child.on("exit", (code, signal) => {+ clearTimeout(timeout);+ if (code === 0) {+ resolve(JSON.parse(output));+ } else {+ reject(new Error(`measure.ts exited with ${code ?? signal}`));+ }+ });});}@@ -133,6 +187,34 @@ function required(timings: Timings | null, name: string): Timings {return timings;}+/**+ * The series whose reading is the median of the batch.+ *+ * Picking a series rather than averaging each reading keeps a state's readings+ * in order with each other, the same reason `measure.ts` reports one load per+ * state instead of a median per reading.+ */+function representativeSeries(+ batch: Series[],+ of: (series: Series) => Timings,+): Series {+ const sorted = [...batch].sort(+ (a, b) => of(a).domContentLoadedMs - of(b).domContentLoadedMs,+ );+ return sorted[Math.floor(sorted.length / 2)];+}++function readProc(file: string): string {+ try {+ return fs.readFileSync(file, "utf8");+ } catch {+ return "";+ }+}++const cpuModel =+ readProc("/proc/cpuinfo").match(/^model name\s*:\s*(.+)$/m)?.[1] ?? "";+function spreadPercent(values: number[]) {const sorted = [...values].sort((a, b) => a - b);const at = (fraction: number) => sorted[Math.floor(sorted.length * fraction)];@@ -159,13 +241,31 @@ function spreadPercent(values: number[]) {warm: false,offset: offset++,});- const warm = await measure({- mbps,- latency,- throttle,- warm: true,- offset: offset++,- });+ const warmBatch = [];+ for (let profile = 0; profile < WARM_PROFILES; profile++) {+ warmBatch.push(+ await measure({+ mbps,+ latency,+ throttle,+ warm: true,+ offset: offset++,+ loads: WARM_LOADS,+ }),+ );+ }++ // Each state picks its own series, because the second visit and the+ // steady state are different loads already.+ const warm = representativeSeries(warmBatch, (series) =>+ required(series.secondLoad, "secondLoad"),+ );+ const steadiest = representativeSeries(warmBatch, (series) =>+ required(series.steady, "steady"),+ );+ const calibrations = [cold, ...warmBatch]+ .map((series) => series.calibrationMs)+ .sort((a, b) => a - b);// Every cold reading in the row comes from `cold.median`, and every warm// reading from `warm.secondLoad`. Each is one load, so the readings in a@@ -179,8 +279,19 @@ function spreadPercent(values: number[]) {cpuThrottle: throttle,coldMs: cold.median.domContentLoadedMs,warmMs: required(warm.secondLoad, "secondLoad").domContentLoadedMs,- steadyMs: required(warm.steady, "steady").domContentLoadedMs,+ steadyMs: required(steadiest.steady, "steady").domContentLoadedMs,coldSpreadPercent: spreadPercent(cold.everyRunMs),+ warmSpreadPercent: spreadPercent(+ warmBatch.map(+ (series) =>+ required(series.secondLoad, "secondLoad").domContentLoadedMs,+ ),+ ),+ steadySpreadPercent: spreadPercent(+ warmBatch.map(+ (series) => required(series.steady, "steady").domContentLoadedMs,+ ),+ ),// The cold load broken up, in the order a user meets it: bytes start// arriving, something is drawn, the shell commits, the page has its// data.@@ -195,15 +306,17 @@ function spreadPercent(values: number[]) {// DOMContentLoaded alone.warmLargestPaintMs: required(warm.secondLoad, "secondLoad").largestContentfulPaintMs,- steadyLargestPaintMs: required(warm.steady, "steady")+ steadyLargestPaintMs: required(steadiest.steady, "steady").largestContentfulPaintMs,- steadyPageReadyMs: required(warm.steady, "steady").pageReadyMs,+ steadyPageReadyMs: required(steadiest.steady, "steady").pageReadyMs,locale: cold.locale,scripts: cold.scripts,scriptKb: cold.scriptKb,cssKb: cold.cssKb,totalKb: cold.totalKb,runs: cold.runs,+ cpuModel,+ calibrationMs: calibrations[Math.floor(calibrations.length / 2)],});console.error(`measured ${cpu} cpu on a ${network} network`);diff --git a/frontend/test/bench/measure.ts b/frontend/test/bench/measure.tsindex a0a1c201159..b1263e8a0c2 100644--- a/frontend/test/bench/measure.ts+++ b/frontend/test/bench/measure.ts@@ -12,8 +12,15 @@* The first load fills the HTTP cache, the second fills V8's code cache, and the* loads after that are the steady state a returning user sees. Both are* reported, because a chunk layout can help one and hurt the other.+ *+ * The network is shaped with tc netem rather than by the browser, because+ * browser throttling is applied per request and so prices every byte at the+ * bandwidth rate wherever it sits in the response. A layout that pushes the+ * script tags past the initial congestion window costs a whole round trip+ * instead, which only packet-level shaping reproduces. Linux only, and it needs+ * root: this runs on a CI runner.*/-import { spawn } from "node:child_process";+import { spawn, spawnSync } from "node:child_process";import fs from "node:fs";import http from "node:http";@@ -40,6 +47,112 @@ if (!url) {process.exit(1);}+const backendPort = Number(new URL(url).port || 80);+const shapeNetwork = mbps > 0 || latency > 0;++/** What a real link carries. Loopback defaults to 65536. */+const LOOPBACK_MTU = 1500;+const LOOPBACK_MTU_DEFAULT = 65536;++const privileged = (process.getuid?.() ?? 0) === 0 ? [] : ["sudo"];++function asRoot(command: string): { ok: boolean; stderr: string } {+ const [executable, ...args] = [...privileged, "sh", "-c", command];+ const result = spawnSync(executable, args, { encoding: "utf8" });+ return { ok: result.status === 0, stderr: (result.stderr || "").trim() };+}++function shellOutput(command: string): string {+ return spawnSync("sh", ["-c", command], { encoding: "utf8" }).stdout || "";+}++/**+ * The window is counted in segments, so loopback's 65536-byte MTU makes the+ * initial ten-segment window about 640 kB. Every document this harness loads+ * fits in one flight at that size, and the reading comes out the same whatever+ * the layout does. Forcing 1500 is what makes the boundary observable.+ */+function shapeLoopback(): void {+ // A packet crosses lo's egress once in each direction, so the round trip is+ // twice the one-way delay netem is given.+ const perDirectionMs = Math.round(latency / 2);+ const bitsPerSecond = mbps * 1024 * 1024;++ asRoot(`ip link set dev lo mtu ${LOOPBACK_MTU}`);+ // Nothing to delete on a fresh runner, so this one is allowed to fail.+ asRoot("tc qdisc del dev lo root");++ const steps = [+ "tc qdisc add dev lo root handle 1: prio bands 3",+ `tc qdisc add dev lo parent 1:1 handle 10: netem delay ${perDirectionMs}ms rate ${bitsPerSecond}bit`,+ // Only the backend is shaped. The harness drives Chrome over CDP on+ // loopback as well, and delaying that channel would move the moment each+ // reading is taken without moving the load the reading describes.+ ...["dport", "sport"].flatMap((direction) => [+ `tc filter add dev lo parent 1: protocol ip prio 1 u32 match ip ${direction} ${backendPort} 0xffff flowid 1:1`,+ `tc filter add dev lo parent 1: protocol ipv6 prio 2 u32 match ip6 ${direction} ${backendPort} 0xffff flowid 1:1`,+ ]),+ ];++ for (const step of steps) {+ const { ok, stderr } = asRoot(step);+ if (!ok) {+ console.error(`could not shape the network: ${step}\n${stderr}`);+ process.exit(1);+ }+ }++ // An unshaped run still reports plausible times, so a shaping failure would+ // read as a result rather than as an error. Check it took.+ const link = shellOutput("ip link show lo");+ const qdisc = shellOutput("tc qdisc show dev lo");+ const problems = [+ !link.includes(`mtu ${LOOPBACK_MTU}`) &&+ `lo is not at mtu ${LOOPBACK_MTU}: ${link.split("\n")[0].trim()}`,+ !qdisc.includes("netem") && `no netem qdisc on lo: ${qdisc.trim()}`,+ perDirectionMs > 0 &&+ !qdisc.includes(`delay ${perDirectionMs}ms`) &&+ `netem is not delaying ${perDirectionMs}ms: ${qdisc.trim()}`,+ ].filter(Boolean);++ if (problems.length > 0) {+ console.error(`the network shaping did not take:\n${problems.join("\n")}`);+ process.exit(1);+ }+}++/**+ * A first visit opens a connection, and so does a return visit. A load here+ * follows the one before it by seconds, and Chrome would reuse the connection+ * that one left open. That skips the handshake, a whole round trip the reading+ * then lacks, and how often it happens moves with the timing between loads.+ * Closing the connections makes every load pay for its own.+ */+async function closeBackendConnections(): Promise<void> {+ const sockets = `'( dport = :${backendPort} or sport = :${backendPort} )'`;+ let open = "";++ // More than once, because a request the last page had in flight can still+ // open a connection after the first pass.+ for (let attempt = 0; attempt < 20; attempt++) {+ asRoot(`ss -K -t ${sockets}`);+ open = shellOutput(`ss -H -t state established ${sockets}`).trim();+ if (!open) {+ return;+ }+ await sleep(50);+ }++ // A kernel without socket destroy leaves them open and reports nothing.+ console.error(`connections to the backend stayed open:\n${open}`);+ process.exit(1);+}++function unshapeLoopback(): void {+ asRoot("tc qdisc del dev lo root");+ asRoot(`ip link set dev lo mtu ${LOOPBACK_MTU_DEFAULT}`);+}+/** What READ_METRICS evaluates to in the page. */interface Run {href: string;@@ -118,9 +231,13 @@ class Session {// and when the page has its data. See metabase/utils/performance-marks.ts.const READ_METRICS = `JSON.stringify((() => {const nav = performance.getEntriesByType("navigation")[0];- const scripts = performance+ // Only what arrived before DOMContentLoaded is counted. That set is fixed+ // once the event fires, so the counts do not depend on when this runs, and a+ // build that records no marks is counted at the same moment as one that does.+ const resources = performance.getEntriesByType("resource")- .filter((entry) => entry.name.endsWith(".js"));+ .filter((entry) => nav && entry.responseEnd <= nav.domContentLoadedEventEnd);+ const scripts = resources.filter((entry) => entry.name.endsWith(".js"));const paint = (name) => {const entry = performance.getEntriesByName(name)[0];return entry ? entry.startTime : 0;@@ -140,14 +257,13 @@ const READ_METRICS = `JSON.stringify((() => {lastScriptEnd: Math.max(0, ...scripts.map((entry) => entry.responseEnd)),scriptCount: scripts.length,scriptBytes: scripts.reduce((total, entry) => total + entry.encodedBodySize, 0),- styleBytes: performance- .getEntriesByType("resource")+ styleBytes: resources.filter((entry) => entry.name.endsWith(".css")).reduce((total, entry) => total + entry.encodedBodySize, 0),- // Every byte the page fetched so far, compressed as it arrived: the document- // itself, then each script, stylesheet, font, image and API response.- totalBytes: (nav ? nav.encodedBodySize : 0) + performance- .getEntriesByType("resource")+ // Every byte the page fetched before DOMContentLoaded, compressed as it+ // arrived: the document itself, then each script, stylesheet, font, image+ // and API response.+ totalBytes: (nav ? nav.encodedBodySize : 0) + resources.reduce((total, entry) => total + entry.encodedBodySize, 0),};})())`;@@ -168,6 +284,58 @@ const OBSERVE_LARGEST_PAINT = `}).observe({ type: "largest-contentful-paint", buffered: true });`;+// A fixed workload with the three kinds of work a page load does: parse and+// compile, allocate and sort, build and lay out. How long it takes is the speed+// this runner gives the page right now, under the same throttle as the loads.+const CALIBRATE = `(() => {+ const start = performance.now();+ let source = "";+ for (let index = 0; index < 4000; index++) {+ source += "function f" + index + "(a, b) { return a * " + index + " + b; }\\n";+ }+ // Unique each time, so the compile is never served from a cache.+ new Function(source + "return f3999(1, " + Math.random() + ");")();+ const items = Array.from({ length: 200000 }, (_, index) => ({+ key: (index * 2654435761) % 1000003,+ label: "item " + index,+ }));+ items.sort((a, b) => a.key - b.key);+ const root = document.createElement("div");+ for (let index = 0; index < 3000; index++) {+ const paragraph = document.createElement("p");+ paragraph.textContent = items[index].label;+ root.appendChild(paragraph);+ }+ document.body.appendChild(root);+ root.getBoundingClientRect();+ root.remove();+ return performance.now() - start;+})()`;++const CALIBRATION_REPEATS = 5;++async function calibrate(): Promise<number[]> {+ const target = await devtools("/json/new?about:blank", "PUT");+ const socket = new WebSocket(target.webSocketDebuggerUrl);+ await new Promise((resolve) => socket.addEventListener("open", resolve));+ const session = new Session(socket);+ await session.send("Emulation.setCPUThrottlingRate", { rate: cpuThrottle });++ const readings = [];+ // One extra at the front, discarded, so no reading pays for a cold renderer.+ for (let repeat = 0; repeat <= CALIBRATION_REPEATS; repeat++) {+ const { result } = await session.send("Runtime.evaluate", {+ expression: CALIBRATE,+ returnByValue: true,+ });+ readings.push(Number(result.value));+ }++ socket.close();+ await devtools(`/json/close/${target.id}`);+ return readings.slice(1);+}+async function launchChrome() {const chrome = spawn(CHROME, ["--headless=new",@@ -195,6 +363,10 @@ async function launchChrome() {}async function loadOnce() {+ if (shapeNetwork) {+ await closeBackendConnections();+ }+const target = await devtools("/json/new?about:blank", "PUT");const socket = new WebSocket(target.webSocketDebuggerUrl);await new Promise((resolve) => socket.addEventListener("open", resolve));@@ -205,15 +377,6 @@ async function loadOnce() {await session.send("Network.setCacheDisabled", { cacheDisabled: !keepCache });await session.send("Emulation.setCPUThrottlingRate", { rate: cpuThrottle });- if (mbps > 0) {- await session.send("Network.emulateNetworkConditions", {- offline: false,- latency,- downloadThroughput: (mbps * 1024 * 1024) / 8,- uploadThroughput: (mbps * 1024 * 1024) / 8,- });- }-if (sessionCookie) {await session.send("Network.setCookie", {name: "metabase.SESSION",@@ -283,6 +446,18 @@ async function loadOnce() {socket.close();await devtools(`/json/close/${target.id}`);+ // The close is only a request. Wait for the page to be gone, so it cannot+ // open a connection while the next load is closing them.+ for (let attempt = 0; attempt < 40; attempt++) {+ const targets = await devtools("/json/list");+ if (+ !Array.isArray(targets) ||+ targets.every((open) => open.id !== target.id)+ ) {+ break;+ }+ await sleep(50);+ }return metrics;}@@ -317,9 +492,18 @@ function timings(run: Run) {}(async () => {+ if (shapeNetwork) {+ shapeLoopback();+ // Registered on exit so the early returns below put lo back too.+ process.on("exit", unshapeLoopback);+ }+const chrome = await launchChrome();const results = [];+ // Before and after the loads, so the reading covers the time they ran in.+ const calibration = await calibrate();+for (let run = 0; run < runs; run++) {const metrics = await loadOnce();if (metrics) {@@ -327,6 +511,9 @@ function timings(run: Run) {}}+ calibration.push(...(await calibrate()));+ calibration.sort((a, b) => a - b);+chrome.kill();if (results.length === 0) {@@ -363,6 +550,9 @@ function timings(run: Run) {everyRunMs: results.map((result) =>Math.round(result.domContentLoaded),),+ calibrationMs: Number(+ calibration[Math.floor(calibration.length / 2)].toFixed(1),+ ),},null,2,