Skip to content

: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.

chore(ci): consolidate frontend size checks into one comment (#67325)

Paul D'Ambra73cfaafd5dae
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index a9090a29b403..e1ba5721e8b6 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -415,6 +415,11 @@ jobs:
- name: Build frontend (bundle-size + eager-graph report)
run: pnpm --filter=@posthog/frontend build:with-report
+ # Measured before the base build overwrites dist/. Untracked, so it survives the
+ # git reset --hard onto the base tree; the dist-size section reads it back.
+ - name: Measure PR dist size
+ run: du -sb frontend/dist | cut -f1 > frontend/dist-size-pr.txt
+
- 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
@@ -428,12 +433,25 @@ jobs:
git reset --hard "$BASE_SHA"
pnpm --filter=@posthog/frontend... install
pnpm --filter=@posthog/frontend build:with-report
+ du -sb frontend/dist | cut -f1 > frontend/dist-size-base.txt
+
+ # Each frontend check contributes one section to a single ci-report comment
+ # (how a section writer picks the PR vs base report is report-files.mjs's story).
+ # After the base build the tree is on the BASE branch, so guard for the scripts'
+ # absence (also covers branches predating a check). Budgets are surfaced
+ # warn-only further down.
+ - name: Clean up legacy per-check CI comments
+ if: always() && github.event_name == 'pull_request'
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ if [ -f frontend/bin/ci-report/delete-legacy-comments.mjs ]; then
+ node frontend/bin/ci-report/delete-legacy-comments.mjs
+ else
+ echo "Skipping legacy CI comment cleanup — script not present on this checkout"
+ fi
- # The bundle-size and eager-graph comments read the PR build's report by its
- # checkout sha (the base build overwrites the plain filename). After the base
- # build the tree is on the BASE branch, so guard for the scripts' absence (also
- # covers branches predating a check). Budgets are surfaced warn-only.
- - name: Post eager graph comment
+ - name: Post CI report — eager graph
if: always() && github.event_name == 'pull_request'
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -441,10 +459,10 @@ jobs:
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"
+ echo "Skipping eager graph section — script not present on this checkout"
fi
- - name: Post bundle size comment
+ - name: Post CI report — bundle size
if: always() && github.event_name == 'pull_request'
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -452,7 +470,18 @@ jobs:
if [ -f frontend/bin/post-bundle-size-comment.mjs ]; then
node frontend/bin/post-bundle-size-comment.mjs
else
- echo "Skipping bundle size comment — script not present on this checkout"
+ echo "Skipping bundle size section — script not present on this checkout"
+ fi
+
+ - name: Post CI report — dist size
+ if: always() && github.event_name == 'pull_request'
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: |
+ if [ -f frontend/bin/post-dist-size-comment.mjs ]; then
+ node frontend/bin/post-dist-size-comment.mjs
+ else
+ echo "Skipping dist size section — script not present on this checkout"
fi
- name: Check eager graph budgets (warn only)
@@ -477,8 +506,12 @@ jobs:
- name: Calculate dist folder size
id: dist-size
+ # After the base build the workspace's dist/ holds the BASE branch's build, so
+ # read back the PR measurement taken before it — the captured metric must be
+ # the PR's size. The du fallback covers runs where that file wasn't written
+ # (dist/ is still the PR's own build then).
run: |
- size_bytes=$(du -sb frontend/dist | cut -f1)
+ size_bytes=$(cat frontend/dist-size-pr.txt 2>/dev/null || du -sb frontend/dist | cut -f1)
echo "size_bytes=${size_bytes}" >> $GITHUB_OUTPUT
echo "Frontend dist folder size: ${size_bytes} bytes ($(numfmt --to=iec-i --suffix=B ${size_bytes}))"
diff --git a/frontend/bin/ci-report/delete-legacy-comments.mjs b/frontend/bin/ci-report/delete-legacy-comments.mjs
new file mode 100644
index 000000000000..79223937f1f8
--- /dev/null
+++ b/frontend/bin/ci-report/delete-legacy-comments.mjs
@@ -0,0 +1,30 @@
+#!/usr/bin/env node
+import { gh, listPrComments, resolvePrContext } from './update-ci-report.mjs'
+
+// The frontend checks used to each post their own PR comment. They now share one
+// ci-report comment, so delete any leftover standalone comments once, on the first
+// consolidated run, to stop a PR from showing both. Transitional — safe to remove
+// after all open PRs have re-run.
+const LEGACY_MARKERS = ['<!-- posthog-eager-graph-check -->', '<!-- posthog-bundle-size-check -->']
+
+const context = resolvePrContext('cleanup')
+if (!context) {
+ process.exit(0)
+}
+const { token, repo, prNumber } = context
+
+try {
+ const stale = (await listPrComments(context)).filter((c) =>
+ LEGACY_MARKERS.some((marker) => c.body?.includes(marker))
+ )
+ for (const comment of stale) {
+ await gh(token, `/repos/${repo}/issues/comments/${comment.id}`, { method: 'DELETE' })
+ console.info(`Deleted legacy CI comment ${comment.id} on PR #${prNumber}.`)
+ }
+ if (!stale.length) {
+ console.info('No legacy CI comments to delete.')
+ }
+} catch (err) {
+ // Fork PRs run with a read-only token — cleanup is best-effort, never worth a red job.
+ console.warn(`Could not clean up legacy CI comments (read-only token on fork PRs?): ${err.message}`)
+}
diff --git a/frontend/bin/ci-report/format.mjs b/frontend/bin/ci-report/format.mjs
new file mode 100644
index 000000000000..9a576c1bc303
--- /dev/null
+++ b/frontend/bin/ci-report/format.mjs
@@ -0,0 +1,48 @@
+export 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`
+}
+
+// Human-readable change vs a baseline, with an at-a-glance arrow. Used verbatim in the
+// header summary and the section table so a reader sees the same phrasing in both.
+// `noBaseline` overrides the wording when there is nothing to compare against.
+export function formatDelta(bytes, baselineBytes, { noBaseline } = {}) {
+ if (baselineBytes === undefined || baselineBytes === null) {
+ return noBaseline ?? `🔺 +${formatBytes(bytes)} (new)`
+ }
+ const delta = bytes - baselineBytes
+ if (delta === 0) {
+ return 'no change'
+ }
+ const sign = delta > 0 ? '+' : '-'
+ const magnitude = `${delta > 0 ? '🔺' : '🟢'} ${sign}${formatBytes(Math.abs(delta))}`
+ if (baselineBytes === 0) {
+ return `${magnitude} (new)`
+ }
+ const percent = ((Math.abs(delta) / baselineBytes) * 100).toFixed(1)
+ return `${magnitude} (${sign}${percent}%)`
+}
+
+// One total compared against the base branch: the body line, header summary, and status
+// for a size section, with the missing-baseline presentation handled once — growth warns,
+// shrink/flat is ok, and no baseline is informational rather than a bogus "new" delta.
+export function totalComparison(bytes, baselineBytes) {
+ if (baselineBytes === null || baselineBytes === undefined) {
+ return {
+ status: 'info',
+ summary: 'no base branch to compare',
+ totalLine: `**Total:** ${formatBytes(bytes)} _(no base branch measurement to compare against yet)_`,
+ }
+ }
+ return {
+ status: bytes > baselineBytes ? 'warn' : 'ok',
+ summary: formatDelta(bytes, baselineBytes),
+ totalLine: `**Total:** ${formatBytes(bytes)} · ${formatDelta(bytes, baselineBytes)}`,
+ }
+}
diff --git a/frontend/bin/ci-report/report-files.mjs b/frontend/bin/ci-report/report-files.mjs
new file mode 100644
index 000000000000..a44f2649448d
--- /dev/null
+++ b/frontend/bin/ci-report/report-files.mjs
@@ -0,0 +1,50 @@
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const frontendDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
+
+// The CI bundle-size job 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 — the PR checks out the
+// merge ref (GITHUB_SHA); head sha covers non-merge-ref checkouts. The base build runs
+// last, so the plain file doubles as the baseline, but only when its sha differs from the
+// PR's (otherwise the base build didn't emit a report — a base branch that predates the
+// check — and the plain file is just the PR's own).
+export function resolvePrAndBaseReport(basename, label) {
+ const eventPath = process.env.GITHUB_EVENT_PATH
+ const event = eventPath ? JSON.parse(fs.readFileSync(eventPath, 'utf-8')) : {}
+ const shaCandidates = [process.env.GITHUB_SHA, event.pull_request?.head?.sha].filter(Boolean)
+ const plainPath = path.join(frontendDir, `${basename}.json`)
+ const shaReportPath = shaCandidates
+ .map((sha) => path.join(frontendDir, `${basename}-${sha}.json`))
+ .find((p) => fs.existsSync(p))
+ const reportPath = shaReportPath ?? plainPath
+ if (!fs.existsSync(reportPath)) {
+ console.info(`No ${label} report found — nothing to post (branch may predate the check).`)
+ return null
+ }
+ 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'))
+ let baseReport = null
+ if (fs.existsSync(plainPath)) {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(plainPath, 'utf-8'))
+ if (parsed.sha && report.sha && parsed.sha !== report.sha) {
+ baseReport = parsed
+ }
+ } catch {
+ baseReport = null
+ }
+ }
+ if (!baseReport) {
+ console.warn(`No base-branch report found — the ${label} section will not show a vs-base delta.`)
+ }
+ return { report, baseReport }
+}
diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjs
index 9fb8fbf65888..1876df1d4719 100644
--- a/frontend/bin/ci-report/update-ci-report.mjs
+++ b/frontend/bin/ci-report/update-ci-report.mjs
@@ -104,7 +104,7 @@ export function renderComment(sections) {
return [MARKER, '## 🤖 CI report', '', ...header, '', ...blocks].join('\n')
}
-async function gh(token, url, options = {}) {
+export async function gh(token, url, options = {}) {
const response = await fetch(`https://api.github.com${url}`, {
...options,
headers: {
@@ -117,36 +117,52 @@ async function gh(token, url, options = {}) {
if (!response.ok) {
throw new Error(`GitHub API ${options.method || 'GET'} ${url} -> ${response.status}: ${await response.text()}`)
}
- return response.json()
+ return response.status === 204 ? null : response.json()
}
-// Post or update this run's section into the shared comment. Fork PRs run with a
-// read-only token, so a failure to read or write is warned and swallowed — the comment
-// is a nicety, never worth a red job.
-export async function postSection({ id, status, summary, body }) {
+// Resolve the PR-comment context from the Actions environment, or null (reason logged)
+// when this run cannot comment — missing env or not a pull_request event.
+export function resolvePrContext(activity) {
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.')
- return
+ console.info(`Missing GitHub environment (token/repository/event) — skipping ${activity}.`)
+ return null
}
- const event = JSON.parse(fs.readFileSync(eventPath, 'utf-8'))
- const prNumber = event.pull_request?.number
+ const prNumber = JSON.parse(fs.readFileSync(eventPath, 'utf-8')).pull_request?.number
if (!prNumber) {
- console.info('Not a pull request event — skipping comment.')
+ console.info(`Not a pull request event — skipping ${activity}.`)
+ return null
+ }
+ return { token, repo, prNumber }
+}
+
+export async function listPrComments({ token, repo, prNumber }) {
+ const all = []
+ for (let page = 1; page <= 50; page++) {
+ const comments = await gh(token, `/repos/${repo}/issues/${prNumber}/comments?per_page=100&page=${page}`)
+ all.push(...comments)
+ if (comments.length < 100) {
+ break
+ }
+ }
+ return all
+}
+
+// Post or update this run's section into the shared comment. Fork PRs run with a
+// read-only token, so a failure to read or write is warned and swallowed — the comment
+// is a nicety, never worth a red job.
+export async function postSection({ id, status, summary, body }) {
+ const context = resolvePrContext('comment')
+ if (!context) {
return
}
+ const { token, repo, prNumber } = context
let existing = null
try {
- for (let page = 1; page <= 50 && !existing; page++) {
- const comments = await gh(token, `/repos/${repo}/issues/${prNumber}/comments?per_page=100&page=${page}`)
- existing = comments.find((c) => c.body?.includes(MARKER)) ?? null
- if (comments.length < 100) {
- break
- }
- }
+ existing = (await listPrComments(context)).find((c) => c.body?.includes(MARKER)) ?? null
} catch (err) {
console.warn(`Could not read PR comments (read-only token on fork PRs?): ${err.message}`)
return
diff --git a/frontend/bin/post-bundle-size-comment.mjs b/frontend/bin/post-bundle-size-comment.mjs
index c22fd2b48795..40751c708074 100644
--- a/frontend/bin/post-bundle-size-comment.mjs
+++ b/frontend/bin/post-bundle-size-comment.mjs
@@ -1,137 +1,21 @@
#!/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-bundle-size-check -->'
+import { formatBytes, formatDelta, totalComparison } from './ci-report/format.mjs'
+import { resolvePrAndBaseReport } from './ci-report/report-files.mjs'
+import { postSection } from './ci-report/update-ci-report.mjs'
// A file whose size moves by less than this is treated as unchanged, matching the
// compressed-size-action `minimum-change-threshold: 1000` this replaces.
const MINIMUM_CHANGE_BYTES = 1000
-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)
-}
-
-// The base build runs last in the same workspace, so the plain report filename holds the
-// base branch's numbers. The PR build's report carries its checkout sha in the filename —
-// the PR checks out the merge ref (GITHUB_SHA); 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, `bundle-size-report-${sha}.json`))
- .find((p) => fs.existsSync(p))
-const reportPath = shaReportPath ?? path.join(frontendDir, 'bundle-size-report.json')
-if (!fs.existsSync(reportPath)) {
- console.info('No bundle size report found — nothing to post (branch may predate the check).')
+const resolved = resolvePrAndBaseReport('bundle-size-report', 'bundle size')
+if (!resolved) {
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'))
-
-// The plain filename is the base measurement only when its sha differs from the PR's —
-// otherwise the base build didn't emit a report (base branch predates the check) and the
-// plain file is just the PR's own report.
-const baseReport = (() => {
- const candidate = path.join(frontendDir, 'bundle-size-report.json')
- if (!fs.existsSync(candidate)) {
- return null
- }
- try {
- const parsed = JSON.parse(fs.readFileSync(candidate, 'utf-8'))
- if (parsed.sha && report.sha && parsed.sha !== report.sha) {
- return parsed
- }
- } catch {
- return null
- }
- return null
-})()
-if (!baseReport) {
- console.warn('No base-branch report found — the comment will not show a vs-base delta.')
-}
+const { report, baseReport } = resolved
const baseBytes = Object.fromEntries((baseReport?.files ?? []).map((f) => [f.file, f.bytes]))
-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, baselineBytes) {
- if (baselineBytes === undefined) {
- return `🔺 +${formatBytes(bytes)} (new)`
- }
- const delta = bytes - baselineBytes
- if (delta === 0) {
- return 'no change'
- }
- const sign = delta > 0 ? '+' : '-'
- const magnitude = `${delta > 0 ? '🔺' : '🟢'} ${sign}${formatBytes(Math.abs(delta))}`
- if (baselineBytes === 0) {
- return `${magnitude} (new)`
- }
- const percent = ((Math.abs(delta) / baselineBytes) * 100).toFixed(1)
- return `${magnitude} (${sign}${percent}%)`
-}
-
-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)
-}
-
// Only diff per file when there is a baseline. Without one every file looks "new", which
-// would flood the comment with the whole manifest and make every delta a bogus increase.
+// would flood the section with the whole manifest and make every delta a bogus increase.
const prFiles = new Map(report.files.map((f) => [f.file, f.bytes]))
const changed = []
if (baseReport) {
@@ -146,21 +30,14 @@ if (baseReport) {
}
changed.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta))
-const baseTotal = baseReport?.total
-const totalDelta = report.total - (baseTotal ?? 0)
+const total = totalComparison(report.total, baseReport?.total ?? null)
const lines = [
- MARKER,
- `## ${baseReport && totalDelta > 0 ? '🔺' : '📦'} Bundle size`,
- '',
'Uncompressed size of every built `.js` bundle, compared against the base branch.',
'',
- baseReport
- ? `**Total:** ${formatBytes(report.total)} · ${formatDelta(report.total, baseTotal)}`
- : `**Total:** ${formatBytes(report.total)} _(no base branch measurement to compare against yet)_`,
+ total.totalLine,
'',
]
-
if (baseReport && changed.length) {
lines.push('| File | Size | Δ vs base |', '| --- | --- | --- |')
for (const { identity, prBytes, base } of changed) {
@@ -171,21 +48,13 @@ if (baseReport && changed.length) {
} else if (baseReport) {
lines.push(`No file changed by more than ${formatBytes(MINIMUM_CHANGE_BYTES)}.`, '')
}
-
lines.push(
'<sub>Posted automatically by [build-bundle-size-report](https://github.com/PostHog/posthog/blob/master/frontend/bin/build-bundle-size-report.mjs) · uncompressed bytes from dist-report</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 bundle size comment ${existing.id} on PR #${prNumber}.`)
- } else {
- await gh(`/repos/${repo}/issues/${prNumber}/comments`, { method: 'POST', body: JSON.stringify({ body }) })
- console.info(`Posted bundle size 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 bundle size comment (read-only token on fork PRs?): ${err.message}`)
-}
+await postSection({
+ id: 'bundle-size',
+ status: total.status,
+ summary: total.summary,
+ body: lines.join('\n'),
+})
diff --git a/frontend/bin/post-dist-size-comment.mjs b/frontend/bin/post-dist-size-comment.mjs
new file mode 100644
index 000000000000..95e856509095
--- /dev/null
+++ b/frontend/bin/post-dist-size-comment.mjs
@@ -0,0 +1,46 @@
+#!/usr/bin/env node
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+import { totalComparison } from './ci-report/format.mjs'
+import { postSection } from './ci-report/update-ci-report.mjs'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const frontendDir = path.resolve(__dirname, '..')
+
+// The workflow measures `du -sb frontend/dist` after the PR build and after the base
+// build, writing each into these files. They are untracked, so both survive the
+// git reset --hard onto the base tree.
+function readBytes(name) {
+ const file = path.join(frontendDir, name)
+ if (!fs.existsSync(file)) {
+ return null
+ }
+ const value = Number.parseInt(fs.readFileSync(file, 'utf-8').trim(), 10)
+ return Number.isFinite(value) ? value : null
+}
+
+const prBytes = readBytes('dist-size-pr.txt')
+if (prBytes === null) {
+ console.info('No PR dist size measurement found — nothing to post.')
+ process.exit(0)
+}
+const baseBytes = readBytes('dist-size-base.txt')
+if (baseBytes === null) {
+ console.warn('No base dist size measurement found — the section will not show a vs-base delta.')
+}
+
+const total = totalComparison(prBytes, baseBytes)
+const body = [
+ 'Total size of the built `frontend/dist` folder (all assets), compared against the base branch.',
+ '',
+ total.totalLine,
+].join('\n')
+
+await postSection({
+ id: 'dist-size',
+ status: total.status,
+ summary: total.summary,
+ body,
+})
diff --git a/frontend/bin/post-eager-graph-comment.mjs b/frontend/bin/post-eager-graph-comment.mjs
index f0bfc8b38a7b..d0da4f3e4bc9 100644
--- a/frontend/bin/post-eager-graph-comment.mjs
+++ b/frontend/bin/post-eager-graph-comment.mjs
@@ -1,103 +1,14 @@
#!/usr/bin/env node
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
+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 __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.')
+const resolved = resolvePrAndBaseReport('eager-graph-report', 'eager graph')
+if (!resolved) {
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)
-}
-
-// The CI bundle-size job 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'))
-
-// The base build runs last (see the write-side comment in check-eager-graph.mjs),
-// so the plain report filename holds the base branch's measurement — the comparison
-// baseline, like the compressed-size check's. The embedded sha guards against the
-// plain file being this PR's own report (the base build didn't run the check, e.g.
-// a base branch that predates it).
-const baseReport = (() => {
- const candidate = path.join(frontendDir, 'eager-graph-report.json')
- if (!fs.existsSync(candidate)) {
- return null
- }
- try {
- const parsed = JSON.parse(fs.readFileSync(candidate, 'utf-8'))
- if (parsed.sha && report.sha && parsed.sha !== report.sha) {
- return parsed
- }
- } catch {
- return null
- }
- return null
-})()
+const { report, baseReport } = resolved
const baseBytes = Object.fromEntries((baseReport?.roots ?? []).map((r) => [r.root, r.bytes]))
-if (!baseReport) {
- console.warn('No base-branch report found — the comment will not show a vs-base delta.')
-}
-
-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, baselineBytes) {
- if (baselineBytes === undefined) {
- return '_(no base measurement)_'
- }
- const delta = bytes - baselineBytes
- if (delta === 0) {
- return 'no change'
- }
- const sign = delta > 0 ? '+' : '-'
- const magnitude = `${delta > 0 ? '🔺' : '🟢'} ${sign}${formatBytes(Math.abs(delta))}`
- if (baselineBytes === 0) {
- return `${magnitude} (new)`
- }
- const percent = ((Math.abs(delta) / baselineBytes) * 100).toFixed(1)
- return `${magnitude} (${sign}${percent}%)`
-}
function budgetBar(bytes, budgetBytes) {
const ratio = Math.min(bytes / budgetBytes, 1)
@@ -106,102 +17,47 @@ function budgetBar(bytes, budgetBytes) {
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 anyFailure = report.roots.some((r) => r.overBudget || r.forbiddenHits.length > 0) || report.errors?.length > 0
+const errorCount = report.errors?.length ?? 0
+const overBudgetRoots = report.roots.filter((r) => r.overBudget).length
+const forbiddenCount = report.roots.reduce((n, r) => n + r.forbiddenHits.length, 0)
+const anyFailure = Boolean(errorCount || overBudgetRoots || forbiddenCount)
-// A comment on every PR teaches people to ignore it — stay silent unless something
-// actually moved (or there is a failure to explain). An existing comment from an
-// earlier significant push is still updated so it never shows stale numbers.
-// A missing baseline is itself significant: with no base report the absolute numbers
-// are the signal, and a root absent from (or zero in) the base report is brand new —
-// the biggest change there is.
-const SIGNIFICANT_CHANGE_PERCENT = 2
-const significantChange =
- !baseReport ||
- report.roots.some((r) => {
- const base = baseBytes[r.root]
- if (base === undefined || base === 0) {
- return true
- }
- return (Math.abs(r.bytes - base) / base) * 100 >= SIGNIFICANT_CHANGE_PERCENT
- })
-if (!anyFailure && !significantChange && !existing) {
- console.info(
- `No eager graph root changed by >= ${SIGNIFICANT_CHANGE_PERCENT}% vs base and no budget/forbidden failures — not posting a comment.`
- )
- process.exit(0)
-}
+const problems = [
+ overBudgetRoots && `${overBudgetRoots} over budget`,
+ forbiddenCount && `${forbiddenCount} forbidden import(s)`,
+].filter(Boolean)
+const summary = errorCount ? `${errorCount} error(s)` : problems.join(', ') || 'within budget'
const lines = [
- MARKER,
- `## ${anyFailure ? '🟡' : '🟢'} Eager graph`,
- '',
'How much code each root ships on the *eager* path — downloaded and parsed before the surface is interactive. Measured from the esbuild output chunks (post-tree-shake, static imports only); lazy `import()` / `React.lazy` chunks are not counted.',
'',
'| Root | Eager (shipped) | Δ vs base | 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, baseBytes[r.root])} | ${budgetBar(r.bytes, r.budgetBytes)} |`
+ `| ${status}**${r.label}**<br/>\`${r.root}\` | ${formatBytes(r.bytes)} · ${r.files.toLocaleString()} files | ${formatDelta(r.bytes, baseBytes[r.root], { noBaseline: '_(no base measurement)_' })} | ${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}\` ships eagerly from \`${r.root}\`:`)
- lines.push('')
- lines.push('```')
- lines.push(hit.chain.join('\n -> '))
- lines.push('```')
+ lines.push('', '```', hit.chain.join('\n -> '), '```')
} 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(`<details><summary>Largest files eagerly shipped 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}\` |`)
@@ -213,16 +69,9 @@ lines.push(
'<sub>Posted automatically by [check-eager-graph](https://github.com/PostHog/posthog/blob/master/frontend/bin/check-eager-graph.mjs) · sizes are eager output bytes (shipped, post-tree-shake) 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}`)
-}
+await postSection({
+ id: 'eager-graph',
+ status: anyFailure ? 'warn' : 'ok',
+ summary,
+ body: lines.join('\n'),
+})