:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): add eager graph budget check for frontend bundles (#63099)
Paul D'Ambrac38e2feed4e7
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.ymlindex fc82dce9dc1f..dc3113673741 100644--- a/.github/workflows/ci-frontend.yml+++ b/.github/workflows/ci-frontend.yml@@ -221,6 +221,42 @@ jobs:order-by: 'Size:desc'strip-hash: "-[A-Za-z0-9]{8}\\.js$"+ # The eager graph check runs in --report-only mode inside build:with-report+ # (compressed-size-action runs that for the PR AND base builds — a failing+ # base build must not abort the action for every open PR). These steps post+ # the sticky PR comment and enforce the budgets from the PR build's report,+ # which carries the checkout sha in its filename because the base build+ # overwrites the plain one. After compressed-size-action the tree is on the+ # BASE branch, so guard for the scripts' absence (also covers branches+ # predating the check).+ - name: Post eager graph comment+ if: always() && github.event_name == 'pull_request'+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ if [ -f frontend/bin/post-eager-graph-comment.mjs ]; then+ node frontend/bin/post-eager-graph-comment.mjs+ else+ echo "Skipping eager graph comment — script not present on this checkout"+ fi++ - name: Enforce eager graph budgets+ if: always() && github.event_name == 'pull_request'+ run: |+ if [ ! -f frontend/bin/check-eager-graph.mjs ]; then+ echo "Skipping eager graph enforcement — script not present on this checkout"+ exit 0+ fi+ REPORT="frontend/eager-graph-report-${GITHUB_SHA}.json"+ if [ ! -f "$REPORT" ]; then+ REPORT="frontend/eager-graph-report.json"+ fi+ if [ ! -f "$REPORT" ]; then+ echo "Skipping eager graph enforcement — no report found (branch may predate the check)"+ exit 0+ fi+ node frontend/bin/check-eager-graph.mjs --assert-report "$REPORT"+- name: Check toolbar for CSP eval violationsrun: pnpm --filter=@posthog/frontend check-toolbar-csp-evaldiff --git a/.gitignore b/.gitignoreindex 54067d95d565..39273b3cc75e 100644--- a/.gitignore+++ b/.gitignore@@ -130,6 +130,7 @@ frontend/.cache/frontend/@posthog/apps-common/dist/frontend/dist/frontend/dist-report/+frontend/eager-graph-report*.jsonfrontend/pnpm-error.logfrontend/public/Matter*.woff*frontend/tmpdiff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsnew file mode 100644index 000000000000..04e4c80ed0c7--- /dev/null+++ b/frontend/bin/check-eager-graph.mjs@@ -0,0 +1,227 @@+#!/usr/bin/env node+import { execSync } from 'node:child_process'+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const frontendDir = path.resolve(__dirname, '..')+const metaPath = path.join(frontendDir, 'posthog-app-esbuild-meta.json')++// --report-only: record results without failing the build. Used by build:with-report+// because compressed-size-action runs that script for BOTH the PR build and the base+// build — a base-branch budget breach must not abort the action for every open PR.+// Enforcement happens in the dedicated workflow step via --assert-report.+const reportOnly = process.argv.includes('--report-only')++// --assert-report <path>: skip measuring; read a previously written report and exit+// non-zero if it records violations.+const assertReportIndex = process.argv.indexOf('--assert-report')++// The eager graph is everything reachable from a root through STATIC imports only —+// the code a browser must download and decode before that surface is interactive,+// regardless of how the bytes are distributed across chunks. Total dist size can't+// see regressions here (a fake-lazy require() moves no bytes, but makes them eager),+// which is why this check exists alongside the compressed-size check.+//+// Budgets are input-source bytes (pre-minification): stable across builds and+// proportional to decoded-script memory cost per renderer (see #32479).+// Ratchet policy: when a bundle-splitting win lands, lower the budget to lock it in;+// raise a budget only as a conscious, reviewed decision in the PR that needs it.+const ROOTS = [+ {+ root: 'src/index.tsx',+ label: 'entry (logged-out pages, app bootstrap)',+ // master 2026-06-11: 14.59 MiB / 749 files (post #62923)+ budgetBytes: 17_000_000,+ forbidden: ['node_modules/monaco-editor/'],+ },+ {+ root: 'src/scenes/AuthenticatedShell.tsx',+ label: 'authenticated shell (every logged-in page)',+ // master 2026-06-11: 55.51 MiB / 8,325 files (ratchet down once #62957 / #62967 land)+ budgetBytes: 64_000_000,+ forbidden: [],+ },+]++function fail(message) {+ console.error(`\n❌ ${message}`)+ process.exitCode = 1+}++function assertReport(reportFilePath) {+ if (!fs.existsSync(reportFilePath)) {+ fail(`Report not found at ${reportFilePath} — did the build run the check?`)+ return+ }+ const reportToAssert = JSON.parse(fs.readFileSync(reportFilePath, 'utf-8'))+ for (const message of reportToAssert.errors ?? []) {+ fail(message)+ }+ for (const r of reportToAssert.roots) {+ if (r.overBudget) {+ fail(+ `Eager graph for '${r.root}' is ${formatMiB(r.bytes)}, over the ${formatMiB(r.budgetBytes)} budget.\n` ++ `Largest files in the closure:\n` ++ r.largest.map(({ file, bytes }) => ` ${formatMiB(bytes).padStart(9)} ${file}`).join('\n') ++ `\nMake the offending import lazy (React.lazy / dynamic import()), or raise the budget in ` ++ `frontend/bin/check-eager-graph.mjs as a conscious decision in this PR.`+ )+ }+ for (const hit of r.forbiddenHits) {+ fail(+ `'${hit.module}' is statically reachable from '${r.root}' — it must stay behind a dynamic import.\n` ++ `Import chain:\n ${hit.chain.join('\n -> ')}`+ )+ }+ if (!process.exitCode) {+ console.info(`✅ ${r.label}: ${formatMiB(r.bytes)} within ${formatMiB(r.budgetBytes)}`)+ }+ }+}++if (assertReportIndex !== -1) {+ assertReport(process.argv[assertReportIndex + 1])+ if (process.exitCode) {+ console.error('\nEager graph check failed — see above.')+ } else {+ console.info('\nAll eager graph budgets respected.')+ }+ process.exit(process.exitCode ?? 0)+}++function formatMiB(bytes) {+ return `${(bytes / 1024 / 1024).toFixed(2)} MiB`+}++function eagerClosure(inputs, root) {+ const parentOf = new Map()+ const seen = new Set([root])+ const queue = [root]+ while (queue.length) {+ const file = queue.shift()+ for (const imp of inputs[file]?.imports || []) {+ if (imp.kind === 'dynamic-import' || seen.has(imp.path) || !inputs[imp.path]) {+ continue+ }+ seen.add(imp.path)+ parentOf.set(imp.path, file)+ queue.push(imp.path)+ }+ }+ return { seen, parentOf }+}++function chainTo(parentOf, target) {+ const chain = []+ let cur = target+ while (cur !== undefined && chain.length < 50) {+ chain.unshift(cur)+ cur = parentOf.get(cur)+ }+ return chain+}++if (!fs.existsSync(metaPath)) {+ fail(`Metafile not found at ${metaPath} — run \`pnpm --filter=@posthog/frontend build\` first.`)+ process.exit(1)+}++const inputs = JSON.parse(fs.readFileSync(metaPath, 'utf-8')).inputs+const summaryLines = ['## Eager graph check', '', '| Root | Eager size | Budget | Files |', '| --- | --- | --- | --- |']+const report = { roots: [], errors: [] }++for (const { root, label, budgetBytes, forbidden } of ROOTS) {+ if (!inputs[root]) {+ const candidates = Object.keys(inputs)+ .filter((k) => k.endsWith(path.basename(root)))+ .slice(0, 5)+ const message = `Root '${root}' not found in metafile. Was it moved/renamed? Candidates: ${candidates.join(', ')}`+ report.errors.push(message)+ fail(message)+ continue+ }++ const { seen, parentOf } = eagerClosure(inputs, root)+ let totalBytes = 0+ for (const file of seen) {+ totalBytes += inputs[file].bytes+ }+ const largest = [...seen]+ .map((f) => [f, inputs[f].bytes])+ .sort((a, b) => b[1] - a[1])+ .slice(0, 15)++ const overBudget = totalBytes > budgetBytes+ const forbiddenHits = []+ for (const forbiddenSubstr of forbidden) {+ const hit = [...seen].find((f) => f.includes(forbiddenSubstr))+ if (hit) {+ forbiddenHits.push({ module: forbiddenSubstr, chain: chainTo(parentOf, hit) })+ }+ }++ const status = overBudget || forbiddenHits.length > 0 ? '❌' : '✅'+ console.info(`${status} ${label}`)+ console.info(` root: ${root}`)+ console.info(` eager closure: ${seen.size} files, ${formatMiB(totalBytes)} (budget ${formatMiB(budgetBytes)})`)+ summaryLines.push(`| ${status} \`${root}\` | ${formatMiB(totalBytes)} | ${formatMiB(budgetBytes)} | ${seen.size} |`)++ if (overBudget) {+ fail(+ `Eager graph for '${root}' is ${formatMiB(totalBytes)}, over the ${formatMiB(budgetBytes)} budget.\n` ++ `Something newly reachable through static imports is inflating it. Largest files in the closure:\n` ++ largest.map(([f, b]) => ` ${formatMiB(b).padStart(10)} ${f}`).join('\n') ++ `\nMake the offending import lazy (React.lazy / dynamic import()), or raise the budget in ` ++ `frontend/bin/check-eager-graph.mjs as a conscious decision in this PR.`+ )+ }++ for (const hit of forbiddenHits) {+ fail(+ `'${hit.module}' is statically reachable from '${root}' — it must stay behind a dynamic import.\n` ++ `Import chain:\n ${hit.chain.join('\n -> ')}`+ )+ }++ report.roots.push({+ root,+ label,+ bytes: totalBytes,+ files: seen.size,+ budgetBytes,+ overBudget,+ forbidden,+ forbiddenHits,+ largest: largest.map(([f, b]) => ({ file: f, bytes: b })),+ })+}++// Consumed by the workflow's comment + enforcement steps; written even on failure so+// the PR comment can show what went over. The filename carries the built tree's HEAD+// sha because compressed-size-action runs this for BOTH the PR build and the base+// build in the same workspace — a plain filename would be overwritten by the base+// build, making downstream steps report the wrong branch.+const serialized = JSON.stringify(report, null, 2)+fs.writeFileSync(path.join(frontendDir, 'eager-graph-report.json'), serialized)+try {+ const headSha = execSync('git rev-parse HEAD', { cwd: frontendDir, encoding: 'utf-8' }).trim()+ fs.writeFileSync(path.join(frontendDir, `eager-graph-report-${headSha}.json`), serialized)+} catch (err) {+ console.error(`Could not write sha-specific report: ${err.message}`)+}++if (process.env.GITHUB_STEP_SUMMARY) {+ fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, summaryLines.join('\n') + '\n')+}++if (process.exitCode) {+ console.error('\nEager graph check failed — see above.')+ if (reportOnly) {+ console.error('Running with --report-only: violations recorded in the report, not failing the build.')+ process.exit(0)+ }+} else {+ console.info('\nAll eager graph budgets respected.')+}diff --git a/frontend/bin/post-eager-graph-comment.mjs b/frontend/bin/post-eager-graph-comment.mjsnew file mode 100644index 000000000000..65c17daa95a1--- /dev/null+++ b/frontend/bin/post-eager-graph-comment.mjs@@ -0,0 +1,183 @@+#!/usr/bin/env node+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const frontendDir = path.resolve(__dirname, '..')++const MARKER = '<!-- posthog-eager-graph-check -->'++const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN+const repo = process.env.GITHUB_REPOSITORY+const eventPath = process.env.GITHUB_EVENT_PATH++if (!token || !repo || !eventPath) {+ console.info('Missing GitHub environment (token/repository/event) — skipping comment.')+ process.exit(0)+}+const event = JSON.parse(fs.readFileSync(eventPath, 'utf-8'))+const prNumber = event.pull_request?.number+if (!prNumber) {+ console.info('Not a pull request event — skipping comment.')+ process.exit(0)+}++// compressed-size-action builds the PR branch and then the base branch in the same+// workspace, so the plain report filename holds the LAST build's (the base's) numbers.+// The PR build's report carries its checkout sha in the filename — that's the one to+// post. The PR build checks out the merge ref, so its sha is GITHUB_SHA; the head sha+// covers non-merge-ref checkouts.+const shaCandidates = [process.env.GITHUB_SHA, event.pull_request?.head?.sha].filter(Boolean)+const shaReportPath = shaCandidates+ .map((sha) => path.join(frontendDir, `eager-graph-report-${sha}.json`))+ .find((p) => fs.existsSync(p))+const reportPath = shaReportPath ?? path.join(frontendDir, 'eager-graph-report.json')+if (!fs.existsSync(reportPath)) {+ console.info('No eager graph report found — nothing to post (branch may predate the check).')+ process.exit(0)+}+if (!shaReportPath) {+ console.warn(+ `No report found for shas [${shaCandidates.join(', ')}]; falling back to ${reportPath} — ` ++ `its numbers may be from a different checkout.`+ )+}++const report = JSON.parse(fs.readFileSync(reportPath, 'utf-8'))++function formatBytes(bytes) {+ const abs = Math.abs(bytes)+ if (abs >= 1024 * 1024) {+ return `${(bytes / 1024 / 1024).toFixed(2)} MiB`+ }+ if (abs >= 1024) {+ return `${(bytes / 1024).toFixed(1)} KiB`+ }+ return `${bytes} B`+}++function formatDelta(bytes, previousBytes) {+ if (previousBytes === undefined) {+ return '_(first run)_'+ }+ const delta = bytes - previousBytes+ if (delta === 0) {+ return 'no change'+ }+ return `${delta > 0 ? '+' : '-'}${formatBytes(Math.abs(delta))}`+}++function budgetBar(bytes, budgetBytes) {+ const ratio = Math.min(bytes / budgetBytes, 1)+ const filled = Math.round(ratio * 10)+ const bar = '█'.repeat(filled) + '░'.repeat(10 - filled)+ return `\`${bar}\` ${((bytes / budgetBytes) * 100).toFixed(1)}% of ${formatBytes(budgetBytes)}`+}++async function gh(url, options = {}) {+ const response = await fetch(`https://api.github.com${url}`, {+ ...options,+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: 'application/vnd.github+json',+ 'Content-Type': 'application/json',+ ...options.headers,+ },+ })+ if (!response.ok) {+ throw new Error(`GitHub API ${options.method || 'GET'} ${url} -> ${response.status}: ${await response.text()}`)+ }+ return response.json()+}++let existing = null+try {+ for (let page = 1; page <= 50 && !existing; page++) {+ const comments = await gh(`/repos/${repo}/issues/${prNumber}/comments?per_page=100&page=${page}`)+ existing = comments.find((c) => c.body?.includes(MARKER)) ?? null+ if (comments.length < 100) {+ break+ }+ }+} catch (err) {+ // Fork PRs run with a read-only token — the comment is a nicety, never worth a red job.+ console.warn(`Could not read PR comments (read-only token on fork PRs?): ${err.message}`)+ process.exit(0)+}++const previous = (() => {+ const match = existing?.body?.match(/<!-- posthog-eager-graph-data (.*?) -->/s)+ try {+ return match ? JSON.parse(match[1]) : {}+ } catch {+ return {}+ }+})()++const anyFailure = report.roots.some((r) => r.overBudget || r.forbiddenHits.length > 0) || report.errors?.length > 0+const lines = [+ MARKER,+ `<!-- posthog-eager-graph-data ${JSON.stringify(Object.fromEntries(report.roots.map((r) => [r.root, r.bytes])))} -->`,+ `## ${anyFailure ? '❌' : '🕸️'} Eager graph`,+ '',+ "How much code each root forces the browser to download and decode through *static* imports — the regression class total bundle size can't see.",+ '',+ '| Root | Eager closure | Δ this PR run | Budget |',+ '| --- | --- | --- | --- |',+]++for (const r of report.roots) {+ const status = r.overBudget ? '❌ ' : ''+ lines.push(+ `| ${status}**${r.label}**<br/>\`${r.root}\` | ${formatBytes(r.bytes)} · ${r.files.toLocaleString()} files | ${formatDelta(r.bytes, previous[r.root])} | ${budgetBar(r.bytes, r.budgetBytes)} |`+ )+}+lines.push('')++for (const message of report.errors ?? []) {+ lines.push(`❌ ${message}`, '')+}++for (const r of report.roots) {+ for (const forbiddenModule of r.forbidden) {+ const hit = r.forbiddenHits.find((h) => h.module === forbiddenModule)+ if (hit) {+ lines.push(`❌ \`${forbiddenModule}\` is statically reachable from \`${r.root}\`:`)+ lines.push('')+ lines.push('```')+ lines.push(hit.chain.join('\n -> '))+ lines.push('```')+ } else {+ lines.push(`✅ \`${forbiddenModule}\` stays out of \`${r.root}\``)+ }+ }+}+lines.push('')++for (const r of report.roots) {+ lines.push(`<details><summary>Largest files eagerly reachable from <code>${r.root}</code></summary>`, '')+ lines.push('| Size | File |', '| --- | --- |')+ for (const { file, bytes } of r.largest.slice(0, 10)) {+ lines.push(`| ${formatBytes(bytes)} | \`${file}\` |`)+ }+ lines.push('', '</details>')+}+lines.push('')+lines.push(+ '<sub>Posted automatically by [check-eager-graph](https://github.com/PostHog/posthog/blob/master/frontend/bin/check-eager-graph.mjs) · sizes are input-source bytes from the esbuild metafile · part of #32479</sub>'+)++const body = lines.join('\n')+try {+ if (existing) {+ await gh(`/repos/${repo}/issues/comments/${existing.id}`, { method: 'PATCH', body: JSON.stringify({ body }) })+ console.info(`Updated eager graph comment ${existing.id} on PR #${prNumber}.`)+ } else {+ await gh(`/repos/${repo}/issues/${prNumber}/comments`, { method: 'POST', body: JSON.stringify({ body }) })+ console.info(`Posted eager graph comment on PR #${prNumber}.`)+ }+} catch (err) {+ // Fork PRs run with a read-only token — the comment is a nicety, never worth a red job.+ console.warn(`Could not post eager graph comment (read-only token on fork PRs?): ${err.message}`)+}diff --git a/frontend/package.json b/frontend/package.jsonindex b68a54e02788..1b6484236c16 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -19,7 +19,7 @@"copy-scripts": "mkdir -p dist/ && ./bin/copy-posthog-js","clean": "rm -rf dist && mkdir dist","build": "pnpm copy-scripts && pnpm build:esbuild",- "build:with-report": "pnpm build && node ./bin/build-bundle-report.mjs",+ "build:with-report": "pnpm build && node ./bin/build-bundle-report.mjs && node ./bin/check-eager-graph.mjs --report-only","build:esbuild": "DEBUG=0 node ./build.mjs","build:products": "DEBUG=0 node build-products.mjs","build:app-urls": "node bin/build-app-url-manifest.mjs",