: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
fix(ci): toolbar bundle guards — output-based, on the shared CI comment (#72583)
Paul D'Ambraaca4f7a8a1ed
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.ymlindex ea56d816cd82..5268a231bbd4 100644--- a/.github/workflows/ci-frontend.yml+++ b/.github/workflows/ci-frontend.yml@@ -409,6 +409,15 @@ jobs:- name: Check toolbar graph stays inside its module boundaryrun: pnpm --filter=@posthog/frontend check-toolbar-graph+ # Keep the PR-side poster available after the base reset below. This is especially+ # important on the PR that introduces or updates the poster itself.+ - name: Preserve PR toolbar report poster+ if: github.event_name == 'pull_request'+ run: |+ if [ -f frontend/bin/post-toolbar-size-comment.mjs ]; then+ cp frontend/bin/post-toolbar-size-comment.mjs frontend/bin/post-toolbar-size-comment-pr.mjs+ fi+- name: Build base branch for size comparison# A broken base build (install/esbuild — which --report-only does not cover) must# only cost the vs-base delta, never redden every open PR's job. The comment steps@@ -478,6 +487,19 @@ jobs:echo "Skipping dist size section — script not present on this checkout"fi+ - name: Post CI report — toolbar bundle+ if: always() && github.event_name == 'pull_request'+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ if [ -f frontend/bin/post-toolbar-size-comment-pr.mjs ]; then+ node frontend/bin/post-toolbar-size-comment-pr.mjs+ elif [ -f frontend/bin/post-toolbar-size-comment.mjs ]; then+ node frontend/bin/post-toolbar-size-comment.mjs+ else+ echo "Skipping toolbar bundle section — script not present on this checkout"+ fi+- name: Check eager graph budgets (warn only)if: always() && github.event_name == 'pull_request'run: |diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex ec88696f8e97..7d67b2436c35 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -38,8 +38,8 @@ const ROOTS = [root: 'src/index.tsx',label: 'entry (logged-out pages, app bootstrap)',// 2026-07-01: 3.75 MiB eager output (2.73 MiB JS + 1.02 MiB eager CSS, 21 chunks).- // ~15% headroom so routine churn doesn't trip the warn; ratchet down on a split win.- budgetBytes: 4_500_000,+ // ~20% headroom so routine churn doesn't trip the warn; ratchet down on a split win.+ budgetBytes: 4_725_000,forbidden: ['node_modules/monaco-editor/','src/lib/components/ActivityLog/describers',@@ -65,8 +65,8 @@ const ROOTS = [label: 'authenticated shell (every logged-in page)',// 2026-07-07: 8.02 MiB eager output after moving all @posthog/brand/hoggies usage in// eager code to PNG stubs (lib/brand/hoggies) — the inline-SVG modules are now a- // forbidden module below. ~15% headroom so routine churn doesn't trip the warn.- budgetBytes: 9_700_000,+ // forbidden module below. ~21% headroom so routine churn doesn't trip the warn.+ budgetBytes: 10_185_000,forbidden: ['node_modules/monaco-editor/','src/lib/components/ActivityLog/describers',diff --git a/frontend/bin/check-toolbar-graph.mjs b/frontend/bin/check-toolbar-graph.mjsindex 7df2fc8a6e4c..32c32f0782d9 100644--- a/frontend/bin/check-toolbar-graph.mjs+++ b/frontend/bin/check-toolbar-graph.mjs@@ -23,8 +23,10 @@ const baselinePath = path.join(__dirname, 'toolbar-graph-baseline.json')// 2. Packages on the toolbar denylist (toolbar-config.mjs) must stay absent entirely —// their presence means the deny plugin regressed.//-// 3. A coarse total-input-bytes ratchet backstops everything else. The eager/shipped-size-// budget lives in check-toolbar-size.mjs; this one only catches graph-reachability creep.+// This check enforces the module BOUNDARY only; it does not measure or gate on size. Shipped+// size is owned by check-toolbar-size.mjs, measured from the esbuild OUTPUT (post-tree-shake)+// and surfaced in the shared CI comment — the right place to look at toolbar size. Input-graph+// source bytes count code that tree-shakes away, so this check deliberately reports no byte size.const ENTRY = 'src/toolbar/index.tsx'const APP_ZONE = [/^src\/products/, /^src\/scenes\//, /^src\/layout\//, /^src\/models\//, /^\.\.\/products\//]@@ -38,20 +40,11 @@ const FORBIDDEN_PACKAGES = ['node_modules/hls.js/',]-// Ratchet policy: when an edge is cut, lower the budget to lock it in; raise it only as a-// conscious, reviewed decision in the PR that needs it. There is headroom for churn, but any-// reintroduced leak jumps the graph back toward ~100 MiB and fails loudly.-const TOTAL_INPUT_BYTES_BUDGET = 14_500_000-function fail(message) {console.error(`\n❌ ${message}`)process.exitCode = 1}-function formatMiB(bytes) {- return `${(bytes / 1024 / 1024).toFixed(2)} MiB`-}-if (!fs.existsSync(metaPath)) {fail(`Metafile not found at ${metaPath} — run \`pnpm --filter=@posthog/frontend build\` first.`)process.exit(1)@@ -120,30 +113,11 @@ for (const pkg of forbiddenHits) {)}-let totalBytes = 0-let survivorBytes = 0-for (const [file, info] of Object.entries(inputs)) {- totalBytes += info.bytes- if (survivors.has(file)) {- survivorBytes += info.bytes- }-}--if (totalBytes > TOTAL_INPUT_BYTES_BUDGET) {- fail(- `Toolbar graph totals ${formatMiB(totalBytes)} of source input, over the ` +- `${formatMiB(TOTAL_INPUT_BYTES_BUDGET)} budget. Something new is reachable from the toolbar ` +- `entry. Find it with \`pnpm --filter=@posthog/frontend visualize-toolbar-bundle\`, or raise the ` +- `budget in frontend/bin/check-toolbar-graph.mjs as a conscious decision in this PR.`- )-}-const status = process.exitCode ? '🟡' : '🟢'console.info(- `${status} toolbar graph: ${Object.keys(inputs).length} files, ${formatMiB(totalBytes)} source input (budget ${formatMiB(TOTAL_INPUT_BYTES_BUDGET)})`+ `${status} toolbar graph boundary: ${crossingEdges.size} toolbar -> app crossing edge(s) ` ++ `(baseline ${baselineEdges.size}), ${survivors.size} survivor files reachable from the entry`)-console.info(` survivors (toolbar-owned closure): ${survivors.size} files, ${formatMiB(survivorBytes)}`)-console.info(` toolbar -> app crossing edges: ${crossingEdges.size} (baseline ${baselineEdges.size})`)if (process.env.GITHUB_STEP_SUMMARY) {fs.appendFileSync(@@ -151,10 +125,10 @@ if (process.env.GITHUB_STEP_SUMMARY) {['## Toolbar graph check','',- '| Metric | Value | Limit |',- '| --- | --- | --- |',- `| ${status} total source input | ${formatMiB(totalBytes)} | ${formatMiB(TOTAL_INPUT_BYTES_BUDGET)} |`,- `| toolbar -> app edges | ${crossingEdges.size} | baseline ${baselineEdges.size} |`,+ '| Metric | Value |',+ '| --- | --- |',+ `| ${status} toolbar -> app crossing edges | ${crossingEdges.size} (baseline ${baselineEdges.size}) |`,+ `| survivor files (toolbar-owned closure) | ${survivors.size} |`,].join('\n') + '\n')}diff --git a/frontend/bin/check-toolbar-size.mjs b/frontend/bin/check-toolbar-size.mjsindex 8b9585f8ac5c..30062afb5122 100644--- a/frontend/bin/check-toolbar-size.mjs+++ b/frontend/bin/check-toolbar-size.mjs@@ -1,8 +1,16 @@-import fs from 'fs'-import path from 'path'+import { execSync } from 'node:child_process'+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'import { eagerOutputs, findEntryOutput, jsOutputs, readToolbarMetafile } from './toolbar-metafile.mjs'+// --report-only: write toolbar-size-report.json (the shipped-size numbers) for the shared CI+// comment, exactly like check-eager-graph, without failing the build. build:with-report runs it+// for both the PR and base builds so the comment can show a vs-base delta. The enforcing run+// (no flag) stays a hard-fail CI step.+const reportOnly = process.argv.includes('--report-only')+// Size guards for the split toolbar build (dist/toolbar.js loader + dist/toolbar/ ESM app).//// 1. Per-file CloudFront gzip ceiling. CloudFront only compresses responses whose body is@@ -13,10 +21,10 @@ import { eagerOutputs, findEntryOutput, jsOutputs, readToolbarMetafile } from '.// close again; if one does, split it rather than raising the limit.const MAX_FILE_BYTES = 10_000_000-// 2. Eager-set budget: the entry plus everything statically imported from it — the bytes every-// toolbar load fetches before any feature runs. Ratchet policy: when an edge is cut, lower the-// budget to lock it in; raise it only as a conscious, reviewed decision in the PR that needs it.-const MAX_EAGER_BYTES = 1_660_000+// 2. Eager-set budget: the entry, entry CSS, and everything statically imported from them. This+// aggregate guardrail catches unexpectedly eager features well before any individual output+// reaches CloudFront's 10 MB compression cutoff.+const MAX_EAGER_BYTES = 6_000_000// 3. The loader is injected on every customer page that enables the toolbar and must stay tiny.const MAX_LOADER_BYTES = 20_000@@ -56,9 +64,11 @@ function main() {// Per-file ceiling across every shipped artifact (app outputs + loader + copied CSS).const shippedFiles = Object.keys(outputs).filter((o) => !o.endsWith('.map'))+ const oversizeFiles = []for (const file of [...shippedFiles, 'dist/toolbar.css']) {const bytes = outputs[file]?.bytes ?? statBytes(file)if (bytes !== null && bytes > MAX_FILE_BYTES) {+ oversizeFiles.push({ file, bytes })fail(`${file} is ${humanBytes(bytes)}, over the ${humanBytes(MAX_FILE_BYTES)} CloudFront gzip limit — ` +'CloudFront serves files this large uncompressed. Split it further.'@@ -72,6 +82,7 @@ function main() {// make the owning feature import its styles statically (or hoist the style import).// Note: with code splitting, every dynamically-imported module also carries an entryPoint// in the metafile — findEntryOutput matches the real toolbar entry specifically.+ const cssIncomplete = []const entryCss = outputs[findEntryOutput(outputs)]?.cssBundleif (entryCss) {const entryCssInputs = new Set(Object.keys(outputs[entryCss].inputs || {}))@@ -81,6 +92,7 @@ function main() {}const missing = Object.keys(output.inputs || {}).filter((inp) => !entryCssInputs.has(inp))if (missing.length) {+ cssIncomplete.push({ file, missing })fail(`${file} contains styles missing from the entry stylesheet (${missing.join(', ')}) — ` +'they would never load into the shadow root. Import them statically.'@@ -91,27 +103,92 @@ function main() {// Eager-set budget.const eagerJs = [...eagerOutputs(outputs)].filter((o) => o.endsWith('.js'))- const eagerBytes = eagerJs.reduce((sum, o) => sum + outputs[o].bytes, 0)+ const eagerFiles = entryCss ? [...eagerJs, entryCss] : eagerJs+ const eagerBytes = eagerFiles.reduce((sum, o) => sum + outputs[o].bytes, 0)const lazyJs = jsOutputs(outputs).filter((o) => !eagerJs.includes(o))const lazyBytes = lazyJs.reduce((sum, o) => sum + outputs[o].bytes, 0)if (eagerBytes > MAX_EAGER_BYTES) {fail(- `Eager toolbar JS is ${humanBytes(eagerBytes)} across ${eagerJs.length} files, over the ` ++ `Eager toolbar output is ${humanBytes(eagerBytes)} across ${eagerFiles.length} files, over the ` +`${humanBytes(MAX_EAGER_BYTES)} budget. Something newly reachable through static imports — ` +'lazy-load it (import()) or cut the import edge.')}+ if (reportOnly) {+ writeReport({+ loaderBytes,+ eagerBytes,+ eagerFiles,+ lazyBytes,+ lazyFiles: lazyJs.length,+ oversizeFiles,+ cssIncomplete,+ outputs,+ })+ // Never fail in report-only mode: the shared CI comment surfaces the numbers and the+ // enforcing run (no flag) is a separate CI step that hard-fails.+ return+ }+if (failed) {process.exit(1)}console.info(`✓ Toolbar sizes OK: loader ${humanBytes(loaderBytes)} (max ${humanBytes(MAX_LOADER_BYTES)}), ` +- `eager JS ${humanBytes(eagerBytes)} in ${eagerJs.length} files (budget ${humanBytes(MAX_EAGER_BYTES)}), ` ++ `eager output ${humanBytes(eagerBytes)} in ${eagerFiles.length} files (budget ${humanBytes(MAX_EAGER_BYTES)}), ` +`deferred JS ${humanBytes(lazyBytes)} in ${lazyJs.length} files, ` +`every file under the ${humanBytes(MAX_FILE_BYTES)} CloudFront gzip limit.`)}+// Written for the shared CI comment (post-toolbar-size-comment.mjs). Mirrors the eager-graph+// report shape: numbers plus the built tree's HEAD sha so the PR build's report is found by sha+// and the plain file (last write = base build) doubles as the vs-base baseline.+function writeReport({+ loaderBytes,+ eagerBytes,+ eagerFiles,+ lazyBytes,+ lazyFiles,+ oversizeFiles,+ cssIncomplete,+ outputs,+}) {+ const frontendDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')+ const largest = eagerFiles+ .map((o) => ({ file: o, bytes: outputs[o].bytes }))+ .sort((a, b) => b.bytes - a.bytes)+ .slice(0, 10)+ const report = {+ loaderBytes,+ loaderBudget: MAX_LOADER_BYTES,+ loaderOverBudget: loaderBytes !== null && loaderBytes > MAX_LOADER_BYTES,+ eagerBytes,+ eagerFiles: eagerFiles.length,+ budgetBytes: MAX_EAGER_BYTES,+ overBudget: eagerBytes > MAX_EAGER_BYTES,+ lazyBytes,+ lazyFiles,+ maxFileBytes: MAX_FILE_BYTES,+ oversizeFiles,+ cssIncomplete,+ largest,+ }+ try {+ report.sha = execSync('git rev-parse HEAD', { cwd: frontendDir, encoding: 'utf-8' }).trim()+ } catch (err) {+ console.error(`Could not resolve HEAD sha for the toolbar report: ${err.message}`)+ }+ const serialized = JSON.stringify(report, null, 2)+ fs.writeFileSync(path.join(frontendDir, 'toolbar-size-report.json'), serialized)+ if (report.sha) {+ fs.writeFileSync(path.join(frontendDir, `toolbar-size-report-${report.sha}.json`), serialized)+ }+ console.info(+ `Wrote toolbar-size-report.json (eager ${humanBytes(eagerBytes)} / budget ${humanBytes(MAX_EAGER_BYTES)}).`+ )+}+main()diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjsindex 49594e463943..61d550094e27 100644--- a/frontend/bin/ci-report/update-ci-report.mjs+++ b/frontend/bin/ci-report/update-ci-report.mjs@@ -16,6 +16,7 @@ export const MARKER = '<!-- posthog-ci-report -->'export const SECTIONS = [{ id: 'bundle-size', title: 'Bundle size' },{ id: 'eager-graph', title: 'Eager graph' },+ { id: 'toolbar-size', title: 'Toolbar bundle' },{ id: 'dist-size', title: 'Dist folder size' },{ id: 'mcp-ui-apps', title: 'MCP UI apps size' },{ id: 'playwright', title: 'Playwright' },diff --git a/frontend/bin/post-toolbar-size-comment.mjs b/frontend/bin/post-toolbar-size-comment.mjsnew file mode 100644index 000000000000..7620ce880691--- /dev/null+++ b/frontend/bin/post-toolbar-size-comment.mjs@@ -0,0 +1,92 @@+#!/usr/bin/env node+import { formatBytes, formatDelta } from './ci-report/format.mjs'+import { resolvePrAndBaseReport } from './ci-report/report-files.mjs'+import { postSection } from './ci-report/update-ci-report.mjs'++const resolved = resolvePrAndBaseReport('toolbar-size-report', 'toolbar bundle')+if (!resolved) {+ process.exit(0)+}+const { report, baseReport } = resolved++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)}`+}++const oversizeCount = report.oversizeFiles?.length ?? 0+const cssIncompleteCount = report.cssIncomplete?.length ?? 0+const loaderOverBudget = Boolean(report.loaderOverBudget)+const anyFailure = Boolean(report.overBudget || oversizeCount || loaderOverBudget || cssIncompleteCount)+const summary = report.overBudget+ ? `eager ${formatBytes(report.eagerBytes)} over budget`+ : loaderOverBudget+ ? `loader ${formatBytes(report.loaderBytes)} over budget`+ : oversizeCount+ ? `${oversizeCount} file(s) over the CloudFront gzip limit`+ : cssIncompleteCount+ ? `${cssIncompleteCount} chunk stylesheet(s) missing from the entry`+ : `eager ${formatBytes(report.eagerBytes)} within budget`++const lines = [+ 'What the toolbar ships to customer pages, measured from the esbuild *output* (minified, post-tree-shake). ' ++ 'The eager set is the entry plus everything statically imported from it — fetched before any feature runs; ' ++ `deferred chunks load lazily. The eager guardrail is ${formatBytes(report.budgetBytes)}. ` ++ 'Each output file must also stay below 10 MB, ' ++ 'where CloudFront stops compressing it. The module boundary is enforced separately by ' ++ '[check-toolbar-graph](https://github.com/PostHog/posthog/blob/master/frontend/bin/check-toolbar-graph.mjs).',+ '',+ '| Metric | Size | Δ vs base | Budget |',+ '| --- | --- | --- | --- |',+ `| ${report.overBudget ? '🟡 ' : ''}**Eager (shipped)**<br/>entry + static imports | ${formatBytes(report.eagerBytes)} · ${report.eagerFiles.toLocaleString()} files | ${formatDelta(report.eagerBytes, baseReport?.eagerBytes, { noBaseline: '_(no base measurement)_' })} | ${budgetBar(report.eagerBytes, report.budgetBytes)} |`,+ `| **Deferred (lazy)** | ${formatBytes(report.lazyBytes)} · ${report.lazyFiles.toLocaleString()} files | ${formatDelta(report.lazyBytes, baseReport?.lazyBytes, { noBaseline: '_(no base measurement)_' })} | _n/a — loads on demand_ |`,+ `| ${loaderOverBudget ? '🟡 ' : ''}**Loader** \`dist/toolbar.js\` | ${formatBytes(report.loaderBytes)} | ${formatDelta(report.loaderBytes, baseReport?.loaderBytes, { noBaseline: '_(no base measurement)_' })} | ${budgetBar(report.loaderBytes, report.loaderBudget)} |`,+]+lines.push('')++if (report.overBudget) {+ lines.push(+ `🟡 Eager toolbar output is ${formatBytes(report.eagerBytes)}, over the ${formatBytes(report.budgetBytes)} budget. ` ++ 'Something newly reachable through static imports — lazy-load it (`import()`) or cut the import edge.',+ ''+ )+}+if (loaderOverBudget) {+ lines.push(+ `🟡 Loader \`dist/toolbar.js\` is ${formatBytes(report.loaderBytes)}, over the ${formatBytes(report.loaderBudget)} budget. ` ++ 'It ships on every toolbar load before anything runs — app code belongs in the ESM entry.',+ ''+ )+}+for (const { file, bytes } of report.oversizeFiles ?? []) {+ lines.push(+ `🟡 \`${file}\` is ${formatBytes(bytes)}, over the ${formatBytes(report.maxFileBytes)} CloudFront gzip limit — split it further.`,+ ''+ )+}+for (const { file, missing } of report.cssIncomplete ?? []) {+ lines.push(+ `🟡 \`${file}\` contains styles missing from the entry stylesheet (${missing.join(', ')}) — ` ++ 'they would never load into the shadow root. Import them statically.',+ ''+ )+}++lines.push('<details><summary>Largest eagerly-shipped chunks</summary>', '')+lines.push('| Size | File |', '| --- | --- |')+for (const { file, bytes } of (report.largest ?? []).slice(0, 10)) {+ lines.push(`| ${formatBytes(bytes)} | \`${file}\` |`)+}+lines.push('', '</details>', '')+lines.push(+ '<sub>Posted automatically by [check-toolbar-size](https://github.com/PostHog/posthog/blob/master/frontend/bin/check-toolbar-size.mjs) · sizes are toolbar output bytes (shipped, post-tree-shake) from the esbuild metafile</sub>'+)++await postSection({+ id: 'toolbar-size',+ status: anyFailure ? 'warn' : 'ok',+ summary,+ body: lines.join('\n'),+})diff --git a/frontend/package.json b/frontend/package.jsonindex 86a7645796d5..38a827659424 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 && node ./bin/build-bundle-size-report.mjs && node ./bin/check-eager-graph.mjs --report-only",+ "build:with-report": "pnpm build && node ./bin/build-bundle-report.mjs && node ./bin/build-bundle-size-report.mjs && node ./bin/check-eager-graph.mjs --report-only && node ./bin/check-toolbar-size.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",