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): make ci-report sections safe for cross-workflow writers (#67995)

Paul D'Ambra825e75da6c7a
diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjs
index 051a875bc063..1408efcbeb02 100644
--- a/frontend/bin/ci-report/update-ci-report.mjs
+++ b/frontend/bin/ci-report/update-ci-report.mjs
@@ -1,13 +1,13 @@
#!/usr/bin/env node
import fs from 'node:fs'
-// One sticky comment shared by every frontend CI check. Each check owns a delimited
-// section and updates only its own; the collapsed summary lines and section order are
-// rebuilt from the fixed SECTIONS registry every time, so the layout never shifts
-// between runs and readers learn where each check lives. Safe as a plain
-// read-modify-write only because every writer runs sequentially in the single
-// frontend-bundle-size job — do not call this from parallel jobs without a locking
-// strategy.
+// One sticky comment shared by every CI check that joins it. Each check owns a
+// delimited section and updates only its own; the collapsed summary lines and section
+// order are rebuilt from the fixed SECTIONS registry every time, so the layout never
+// shifts between runs and readers learn where each check lives. Writers may run in
+// parallel jobs and workflows: GitHub has no compare-and-set for comment edits, so
+// postSection verifies its write survived and retries when a concurrent writer
+// clobbered it, and heals duplicate comments left by two writers racing to create.
export const MARKER = '<!-- posthog-ci-report -->'
// The single source of truth for which sections exist and the order they render in.
@@ -133,7 +133,10 @@ export async function gh(token, url, options = {}) {
},
})
if (!response.ok) {
- throw new Error(`GitHub API ${options.method || 'GET'} ${url} -> ${response.status}: ${await response.text()}`)
+ throw Object.assign(
+ new Error(`GitHub API ${options.method || 'GET'} ${url} -> ${response.status}: ${await response.text()}`),
+ { status: response.status }
+ )
}
return response.status === 204 ? null : response.json()
}
@@ -168,41 +171,132 @@ export async function listPrComments({ token, repo, prNumber }) {
return all
}
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
+
+function sectionEquals(a, b) {
+ return !!a && !!b && a.status === b.status && a.summary === b.summary && a.inner === b.inner
+}
+
+// Only the report comments this tooling wrote itself. The marker alone is not enough:
+// anyone can comment on a public-repo PR, and a human "Quote reply" of the report keeps
+// the marker inside `> ` prefixes — matching on substring would adopt, merge, or DELETE
+// comments we do not own. The login is the identity behind the `github.token` the
+// posting workflow steps pass — moving them to a custom app token changes the login and
+// would orphan every existing report comment, so handle that transition here too.
+function isReportComment(comment) {
+ return comment.user?.login === 'github-actions[bot]' && comment.body?.startsWith(MARKER)
+}
+
+// A concurrent healer racing us can delete the comment between our read and our write —
+// that surfaces as a 404 and is retryable. (A concurrent PATCH never 404s; the verify
+// pass catches it.) Anything else (403 on a fork's read-only token, 5xx) is not worth
+// retrying for a nicety comment.
+function isWriteConflict(err) {
+ return err.status === 404
+}
+
// 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 }) {
+//
+// Concurrent writers (other jobs, other workflows) race on the same comment with no
+// compare-and-set, so this is read-modify-write plus verify-and-retry: after writing,
+// re-read and check this section survived; if a concurrent writer clobbered it (they
+// read before our write and wrote after), merge again and rewrite. Two writers racing
+// to CREATE the comment can leave duplicates — every attempt merges all report
+// comments' sections into the oldest and deletes the rest, writing the merged content
+// BEFORE deleting so a cancelled job never loses sections that lived only in a duplicate.
+export async function postSection({ id, status, summary, body }, { maxAttempts = 3, retryDelayMs = 1000 } = {}) {
const context = resolvePrContext('comment')
if (!context) {
return
}
const { token, repo, prNumber } = context
+ // Round-trip the section through render/parse to get the form a re-read returns —
+ // renderComment normalizes summaries, so comparing against the raw input would
+ // never verify for a summary that needed normalizing.
+ const expected = parseSections(renderComment(upsertSection(new Map(), { id, status, summary, body }))).get(id)
+ // Jittered so two writers that collided do not retry in lockstep and re-collide on
+ // every attempt.
+ const backoff = () => sleep(retryDelayMs * (0.5 + Math.random()))
- let existing = null
- try {
- 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
- }
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ let reportComments
+ try {
+ reportComments = (await listPrComments(context)).filter(isReportComment)
+ } catch (err) {
+ console.warn(`Could not read PR comments (read-only token on fork PRs?): ${err.message}`)
+ return
+ }
- const sections = upsertSection(parseSections(existing?.body ?? ''), { id, status, summary, body })
- const rendered = renderComment(sections)
- try {
- if (existing) {
- await gh(token, `/repos/${repo}/issues/comments/${existing.id}`, {
- method: 'PATCH',
- body: JSON.stringify({ body: rendered }),
- })
- console.info(`Updated CI report section "${id}" on comment ${existing.id} (PR #${prNumber}).`)
- } else {
- await gh(token, `/repos/${repo}/issues/${prNumber}/comments`, {
- method: 'POST',
- body: JSON.stringify({ body: rendered }),
- })
- console.info(`Posted CI report with section "${id}" on PR #${prNumber}.`)
+ const merged = new Map()
+ for (const comment of reportComments) {
+ for (const [sectionId, section] of parseSections(comment.body)) {
+ merged.set(sectionId, section)
+ }
+ }
+ const rendered = renderComment(upsertSection(merged, { id, status, summary, body }))
+ const [primary, ...duplicates] = reportComments
+
+ try {
+ if (primary) {
+ await gh(token, `/repos/${repo}/issues/comments/${primary.id}`, {
+ method: 'PATCH',
+ body: JSON.stringify({ body: rendered }),
+ })
+ } else {
+ await gh(token, `/repos/${repo}/issues/${prNumber}/comments`, {
+ method: 'POST',
+ body: JSON.stringify({ body: rendered }),
+ })
+ }
+ } catch (err) {
+ if (isWriteConflict(err)) {
+ console.info(`CI report comment changed under section "${id}" — re-reading and retrying.`)
+ if (attempt < maxAttempts) {
+ await backoff()
+ }
+ continue
+ }
+ console.warn(`Could not post CI report (read-only token on fork PRs?): ${err.message}`)
+ return
+ }
+
+ for (const duplicate of duplicates) {
+ try {
+ await gh(token, `/repos/${repo}/issues/comments/${duplicate.id}`, { method: 'DELETE' })
+ console.info(`Merged and deleted duplicate CI report comment ${duplicate.id} (PR #${prNumber}).`)
+ } catch (err) {
+ if (!isWriteConflict(err)) {
+ console.warn(`Could not delete duplicate CI report comment ${duplicate.id}: ${err.message}`)
+ }
+ }
+ }
+
+ try {
+ // Success means this section is durable in the primary (oldest) comment —
+ // every racing writer converges on the same primary, so that is where a
+ // re-read must find it. Healing duplicates is best-effort: a duplicate whose
+ // DELETE keeps failing must not burn retries against a write that landed.
+ const after = (await listPrComments(context)).filter(isReportComment)
+ if (after.length > 0 && sectionEquals(parseSections(after[0].body).get(id), expected)) {
+ if (after.length > 1) {
+ console.warn(`CI report still has ${after.length - 1} duplicate comment(s) on PR #${prNumber}.`)
+ }
+ console.info(`Wrote CI report section "${id}" on PR #${prNumber} (attempt ${attempt}).`)
+ return
+ }
+ } catch (err) {
+ console.warn(`Could not verify CI report write: ${err.message}`)
+ return
+ }
+
+ if (attempt < maxAttempts) {
+ console.info(`CI report section "${id}" was clobbered by a concurrent writer — retrying.`)
+ await backoff()
}
- } catch (err) {
- console.warn(`Could not post CI report (read-only token on fork PRs?): ${err.message}`)
}
+ console.warn(
+ `Gave up writing CI report section "${id}" after ${maxAttempts} attempts — its next run will restore it.`
+ )
}
diff --git a/frontend/bin/ci-report/update-ci-report.test.ts b/frontend/bin/ci-report/update-ci-report.test.ts
index 2c5fbfa7ee68..027ed025d2d6 100644
--- a/frontend/bin/ci-report/update-ci-report.test.ts
+++ b/frontend/bin/ci-report/update-ci-report.test.ts
@@ -1,4 +1,8 @@
-import { MARKER, parseSections, renderComment, STATUS_EMOJI, upsertSection } from './update-ci-report.mjs'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { MARKER, parseSections, postSection, renderComment, STATUS_EMOJI, upsertSection } from './update-ci-report.mjs'
type SectionEntry = { status: string; summary: string; inner: string }
type SectionState = Map<string, SectionEntry>
@@ -149,4 +153,257 @@ describe('ci-report section helper', () => {
expect(rendered).toContain('old body')
expect(rendered.indexOf('<b>Bundle size</b>')).toBeLessThan(rendered.indexOf('legacy-check'))
})
+
+ describe('postSection concurrency', () => {
+ type StoredComment = { id: number; body: string; author: string }
+ type FireOnceHook = { fn: (() => void) | null }
+ // An in-memory GitHub issue-comments API — the network is the boundary being
+ // faked; assertions are on the surviving comment state, not call choreography.
+ // Missing-id writes 404 like real GitHub so the conflict paths are expressible;
+ // the fire-once hooks inject a concurrent writer at the two race points.
+ function fakeGitHub(initial: Array<{ body: string; author?: string }> = []): {
+ comments: StoredComment[]
+ afterNextWrite: FireOnceHook
+ afterNextRead: FireOnceHook
+ state: { patches: number; denyDeletes: boolean }
+ } {
+ let nextId = 100
+ const comments: StoredComment[] = initial.map(({ body, author }) => ({
+ id: ++nextId,
+ body,
+ author: author ?? 'github-actions[bot]',
+ }))
+ const afterNextWrite: FireOnceHook = { fn: null }
+ const afterNextRead: FireOnceHook = { fn: null }
+ const state = { patches: 0, denyDeletes: false }
+ const fireOnce = (hook: FireOnceHook): void => {
+ const fn = hook.fn
+ hook.fn = null
+ fn?.()
+ }
+ const json = (data: unknown): Response =>
+ ({ ok: true, status: 200, json: async () => data, text: async () => '' }) as unknown as Response
+ const notFound = (): Response =>
+ ({
+ ok: false,
+ status: 404,
+ json: async () => ({}),
+ text: async () => 'not found',
+ }) as unknown as Response
+ globalThis.fetch = async (url: RequestInfo | URL, options: RequestInit = {}): Promise<Response> => {
+ const method = options.method ?? 'GET'
+ if (method === 'GET') {
+ const page = Number(new URL(String(url)).searchParams.get('page') ?? '1')
+ const snapshot = comments.map(({ id, body, author }) => ({ id, body, user: { login: author } }))
+ fireOnce(afterNextRead)
+ return json(page === 1 ? snapshot : [])
+ }
+ if (method === 'POST') {
+ comments.push({
+ id: ++nextId,
+ body: JSON.parse(String(options.body)).body,
+ author: 'github-actions[bot]',
+ })
+ fireOnce(afterNextWrite)
+ return json(comments.at(-1))
+ }
+ const id = Number(String(url).split('/').pop())
+ if (method === 'PATCH') {
+ const target = comments.find((c) => c.id === id)
+ if (!target) {
+ return notFound()
+ }
+ state.patches += 1
+ target.body = JSON.parse(String(options.body)).body
+ fireOnce(afterNextWrite)
+ return json({})
+ }
+ if (method === 'DELETE') {
+ if (state.denyDeletes) {
+ return {
+ ok: false,
+ status: 403,
+ json: async () => ({}),
+ text: async () => 'forbidden',
+ } as unknown as Response
+ }
+ const index = comments.findIndex((c) => c.id === id)
+ if (index === -1) {
+ return notFound()
+ }
+ comments.splice(index, 1)
+ return {
+ ok: true,
+ status: 204,
+ json: async () => null,
+ text: async () => '',
+ } as unknown as Response
+ }
+ return notFound()
+ }
+ return { comments, afterNextWrite, afterNextRead, state }
+ }
+
+ const realFetch = globalThis.fetch
+ let tmpDir: string
+
+ beforeAll(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ci-report-test-'))
+ const eventPath = path.join(tmpDir, 'event.json')
+ fs.writeFileSync(eventPath, JSON.stringify({ pull_request: { number: 1 } }))
+ process.env.GITHUB_TOKEN = 'test-token'
+ process.env.GITHUB_REPOSITORY = 'PostHog/posthog'
+ process.env.GITHUB_EVENT_PATH = eventPath
+ })
+
+ afterAll(() => {
+ globalThis.fetch = realFetch
+ fs.rmSync(tmpDir, { recursive: true, force: true })
+ delete process.env.GITHUB_TOKEN
+ delete process.env.GITHUB_REPOSITORY
+ delete process.env.GITHUB_EVENT_PATH
+ })
+
+ const opts = { retryDelayMs: 0 }
+
+ it('creates the comment when none exists, then a second writer joins it', async () => {
+ const github = fakeGitHub()
+ await postSection({ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }, opts)
+ await postSection({ id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' }, opts)
+ expect(github.comments).toHaveLength(1)
+ const sections = parseSections(github.comments[0].body)
+ expect([...sections.keys()]).toEqual(['bundle-size', 'eager-graph'])
+ })
+
+ it('retries when a concurrent writer clobbers the section, keeping both', async () => {
+ // The other writer read the comment before our PATCH landed and wrote after
+ // it — its render is missing our section. The verify pass must catch that
+ // and re-merge, or cross-workflow sections silently vanish.
+ const github = fakeGitHub([
+ { body: renderComment(build([{ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }])) },
+ ])
+ const clobber = renderComment(
+ build([
+ { id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' },
+ { id: 'dist-size', status: 'info', summary: 'd', body: 'DIST' },
+ ])
+ )
+ github.afterNextWrite.fn = () => {
+ github.comments[0].body = clobber
+ }
+ await postSection({ id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' }, opts)
+ expect(github.comments).toHaveLength(1)
+ const sections = parseSections(github.comments[0].body) as SectionState
+ expect([...sections.keys()]).toEqual(['bundle-size', 'eager-graph', 'dist-size'])
+ expect(get(sections, 'eager-graph').inner).toBe('EAGER')
+ })
+
+ it('merges duplicate report comments into the oldest and deletes the rest', async () => {
+ const github = fakeGitHub([
+ { body: renderComment(build([{ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }])) },
+ { body: renderComment(build([{ id: 'dist-size', status: 'info', summary: 'd', body: 'DIST' }])) },
+ ])
+ await postSection({ id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' }, opts)
+ expect(github.comments).toHaveLength(1)
+ const sections = parseSections(github.comments[0].body)
+ expect([...sections.keys()]).toEqual(['bundle-size', 'eager-graph', 'dist-size'])
+ })
+
+ it('never adopts, merges, or deletes a human comment that carries the marker', async () => {
+ // Anyone can comment on a public-repo PR: a "Quote reply" of the report keeps
+ // the marker inside `> ` prefixes, and a pasted report body is a full match.
+ // Neither belongs to the bot — adopting one launders content under the bot's
+ // identity, and healing one DELETES a human's comment permanently.
+ const quoted = `> ${MARKER}\n> ## 🤖 CI report\n\nwow, look at this bundle jump`
+ const pasted = renderComment(
+ build([{ id: 'bundle-size', status: 'fail', summary: 'forged', body: 'FORGED' }])
+ )
+ const github = fakeGitHub([
+ { body: quoted, author: 'some-human' },
+ { body: pasted, author: 'some-human' },
+ ])
+ await postSection({ id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' }, opts)
+ expect(github.comments).toHaveLength(3)
+ expect(github.comments[0]).toMatchObject({ body: quoted, author: 'some-human' })
+ expect(github.comments[1]).toMatchObject({ body: pasted, author: 'some-human' })
+ const bot = github.comments[2]
+ expect(bot.author).toBe('github-actions[bot]')
+ expect([...parseSections(bot.body).keys()]).toEqual(['eager-graph'])
+ })
+
+ it('retries the write when the primary comment is deleted underneath it', async () => {
+ // A concurrent healer can delete the comment between our read and our PATCH.
+ // The 404 must re-enter the retry loop, not take the give-up path — otherwise
+ // the section is silently lost for the whole run.
+ const github = fakeGitHub([
+ { body: renderComment(build([{ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }])) },
+ ])
+ github.afterNextRead.fn = () => {
+ github.comments.splice(0)
+ }
+ await postSection({ id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' }, opts)
+ expect(github.comments).toHaveLength(1)
+ expect([...parseSections(github.comments[0].body).keys()]).toEqual(['eager-graph'])
+ })
+
+ it('swallows a duplicate that another healer already deleted', async () => {
+ // Two workflows can heal the same duplicate concurrently; the loser's DELETE
+ // 404s. That is success (the duplicate is gone), not a reason to abort.
+ const github = fakeGitHub([
+ { body: renderComment(build([{ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }])) },
+ { body: renderComment(build([{ id: 'dist-size', status: 'info', summary: 'd', body: 'DIST' }])) },
+ ])
+ const duplicateId = github.comments[1].id
+ github.afterNextRead.fn = () => {
+ github.comments.splice(
+ github.comments.findIndex((c) => c.id === duplicateId),
+ 1
+ )
+ }
+ await postSection({ id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' }, opts)
+ expect(github.comments).toHaveLength(1)
+ const sections = parseSections(github.comments[0].body)
+ expect([...sections.keys()]).toEqual(['bundle-size', 'eager-graph', 'dist-size'])
+ })
+
+ it('succeeds without burning retries when a duplicate cannot be deleted', async () => {
+ // Healing is best-effort: the section landed in the primary, which is what
+ // success means. Requiring the duplicate count to reach one would re-PATCH
+ // identical content on every attempt and log a lying give-up.
+ const github = fakeGitHub([
+ { body: renderComment(build([{ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }])) },
+ { body: renderComment(build([{ id: 'dist-size', status: 'info', summary: 'd', body: 'DIST' }])) },
+ ])
+ github.state.denyDeletes = true
+ await postSection({ id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' }, opts)
+ expect(github.comments).toHaveLength(2)
+ expect([...parseSections(github.comments[0].body).keys()]).toEqual([
+ 'bundle-size',
+ 'eager-graph',
+ 'dist-size',
+ ])
+ expect(github.state.patches).toBe(1)
+ })
+
+ it('gives up cleanly when a concurrent writer keeps clobbering', async () => {
+ // The comment is a nicety — exhausting maxAttempts must warn and resolve,
+ // never throw, or a comment race reddens the whole job.
+ const github = fakeGitHub([
+ { body: renderComment(build([{ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }])) },
+ ])
+ const clobber = renderComment(build([{ id: 'bundle-size', status: 'ok', summary: 'b', body: 'BUNDLE' }]))
+ const persist = (): void => {
+ github.comments[0].body = clobber
+ github.afterNextWrite.fn = persist
+ }
+ github.afterNextWrite.fn = persist
+ await expect(
+ postSection(
+ { id: 'eager-graph', status: 'warn', summary: 'e', body: 'EAGER' },
+ { ...opts, maxAttempts: 2 }
+ )
+ ).resolves.toBeUndefined()
+ expect([...parseSections(github.comments[0].body).keys()]).toEqual(['bundle-size'])
+ })
+ })
})