: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): read fresh run index in master alerter (#67405)
Raúl Negrón-Otero9453ae18a6e4
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.jsindex e5ebbacb908d..6cfd9152834f 100644--- a/.github/scripts/ci-alerts-devex.js+++ b/.github/scripts/ci-alerts-devex.js@@ -45,35 +45,61 @@ const STREAK_MAX_GAP_MINUTES = 180// GitHub data// ----------------------------------------------------------------------------async function fetchWorkflowRuns(github, owner, repo, workflowFile, perPage) {- const { data } = await github.rest.actions.listWorkflowRuns({- owner,- repo,- workflow_id: workflowFile,- branch: 'master',- event: 'push',- per_page: perPage,- status: 'completed',- })+// The single definition of a "red" run conclusion, shared by the streak and commit checks.+const isFailure = (run) => run.conclusion === 'failure' || run.conclusion === 'timed_out'- // Filter out cancelled/skipped — only real conclusions count- return data.workflow_runs- .filter((run) => run.conclusion !== 'cancelled' && run.conclusion !== 'skipped')- .map((run) => ({- name: run.name,- conclusion: run.conclusion,- sha: run.head_sha,- run_url: run.html_url,- updated_at: run.updated_at,- created_at: run.created_at, // immutable; updated_at is bumped by re-runs- workflow_file: workflowFile,- }))+// The freshest settled runs for a workflow, newest-first.+//+// We deliberately do NOT pass `status: 'completed'`. That server-side filter is served from an+// eventually-consistent index that intermittently returns a page anchored hours/days in the past —+// so the newest run it reports is stale. The alerter then reads an ancient failure as the newest run+// and backdates a phantom multi-day outage (opened+resolved in minutes, "red for 70h"). The+// unfiltered index is fresh, so we read it and drop non-terminal/cancelled runs client-side.+//+// The catch: `per_page` truncates the raw page BEFORE our client-side filter, so a head full of+// in-progress/cancelled runs could push real completed failures off a single page and silently miss+// an incident. So we page until the leading streak is settled (a kept non-failure bounds the walk)+// or we hit a bounded cap.+async function fetchWorkflowRuns(github, owner, repo, workflowFile, perPage) {+ const MAX_PAGES = 5+ const settled = []+ for (let page = 1; page <= MAX_PAGES; page++) {+ const { data } = await github.rest.actions.listWorkflowRuns({+ owner,+ repo,+ workflow_id: workflowFile,+ branch: 'master',+ event: 'push',+ per_page: perPage,+ page,+ })+ for (const run of data.workflow_runs) {+ // In-progress/queued must neither count as nor break a failure streak (mirroring how+ // unreported commits classify 'unknown'); cancelled/skipped never reflect real health.+ if (run.status !== 'completed') continue+ if (run.conclusion === 'cancelled' || run.conclusion === 'skipped') continue+ settled.push({+ name: run.name,+ conclusion: run.conclusion,+ sha: run.head_sha,+ run_url: run.html_url,+ updated_at: run.updated_at,+ created_at: run.created_at, // immutable; updated_at is bumped by re-runs+ workflow_file: workflowFile,+ })+ }+ // Once a kept run is a non-failure it terminates the leading streak, so we have all we need.+ // A short raw page means there are no older runs to fetch.+ const streakBounded = settled.some((r) => !isFailure(r))+ if (streakBounded || data.workflow_runs.length < perPage) break+ }+ return settled}function countConsecutiveFailures(runs) {let count = 0for (const run of runs) {- if (run.conclusion === 'failure' || run.conclusion === 'timed_out') {+ if (isFailure(run)) {count++} else {break@@ -147,7 +173,7 @@ function classifyCommits(commits, allWorkflowRuns) {return commits.map((commit) => {const runs = runsBySha.get(commit.sha) || []if (runs.length === 0) return { ...commit, status: 'unknown' }- const red = runs.some((r) => r.conclusion === 'failure' || r.conclusion === 'timed_out')+ const red = runs.some(isFailure)return { ...commit, status: red ? 'red' : 'green' }})}@@ -335,8 +361,11 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, fconst minutesThreshold = parseInt(process.env.WORKFLOW_FAILURE_MINUTES_THRESHOLD || '20', 10)const activityWindowMins = parseInt(process.env.ACTIVITY_WINDOW_MINUTES || '120', 10)const commitThreshold = parseInt(process.env.COMMIT_FAILURE_STREAK_THRESHOLD || '10', 10)- // Over-fetch to survive cancelled/skipped runs (force-pushes, concurrency cancels).- const perPage = Math.max(workflowThreshold * 3, 20)+ // Page size for the run fetch. fetchWorkflowRuns pages until the streak is settled, so this only+ // trades round-trips against page size; keep it wide enough to resolve the common case in one page+ // despite the in-progress/cancelled runs it now drops client-side. Clamp to GitHub's per_page max+ // of 100 (silently capped otherwise) so a tuned-up streak threshold can't quietly lose capacity.+ const perPage = Math.min(Math.max(workflowThreshold * 6, 40), 100)const commitsToFetch = Math.max(commitThreshold * 2, 25)// Recompute master health from the API and read the Slack incident state (the@@ -473,3 +502,4 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f}module.exports.formatDuration = formatDuration+module.exports.fetchWorkflowRuns = fetchWorkflowRunsdiff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.jsindex 3a7d46aa79f7..021d096a53f3 100644--- a/.github/scripts/ci-alerts-devex.test.js+++ b/.github/scripts/ci-alerts-devex.test.js@@ -26,6 +26,7 @@ function recordingFn(impl) {function runs(name, conclusions) {return conclusions.map((conclusion, i) => ({name,+ status: 'completed',conclusion,head_sha: `sha_${name}_${i}`,html_url: `https://github.com/runs/${name}/${i}`,@@ -35,6 +36,17 @@ function runs(name, conclusions) {const failingRuns = (name, failCount) => runs(name, [...Array(failCount).fill('failure'), ...Array(5).fill('success')])+// A non-terminal Backend CI run (no conclusion yet); status defaults to in_progress.+const nonTerminalRun = (key, status = 'in_progress') => ({+ name: 'Backend CI',+ status,+ conclusion: null,+ head_sha: key,+ html_url: `https://github.com/runs/${key}`,+ created_at: minutes(0).toISOString(),+ updated_at: minutes(0).toISOString(),+})+const allPassing = () => ({'ci-backend.yml': runs('Backend CI', ['success']),'ci-frontend.yml': runs('Frontend CI', ['success']),@@ -55,6 +67,7 @@ function commitsWithRuns(perCommitConclusions) {if (!runsByWorkflow[wf]) runsByWorkflow[wf] = []runsByWorkflow[wf].push({name: wf === 'ci-backend.yml' ? 'Backend CI' : 'Frontend CI',+ status: 'completed',conclusion,head_sha: `commit_sha_${i}`,html_url: `https://github.com/runs/${wf}/${i}`,@@ -105,8 +118,8 @@ const activeAnchor = (payload = {}) => ({// One failure that landed `redMins` ago, preceded by a green run. count=1 (below the streak// threshold), so this drives the wall-clock arm in isolation; redForMins == redMins.const failingFor = (redMins, name = 'Backend CI') => [- { name, conclusion: 'failure', head_sha: `f_${redMins}`, html_url: `https://github.com/runs/${name}/f`, updated_at: minutes(-redMins).toISOString() },- { name, conclusion: 'success', head_sha: `g_${redMins}`, html_url: `https://github.com/runs/${name}/g`, updated_at: minutes(-(redMins + 30)).toISOString() },+ { name, status: 'completed', conclusion: 'failure', head_sha: `f_${redMins}`, html_url: `https://github.com/runs/${name}/f`, updated_at: minutes(-redMins).toISOString() },+ { name, status: 'completed', conclusion: 'success', head_sha: `g_${redMins}`, html_url: `https://github.com/runs/${name}/g`, updated_at: minutes(-(redMins + 30)).toISOString() },]// A single commit `ageMins` old — drives recentActivity. No matching run SHA, so it classifies@@ -310,6 +323,7 @@ describe('ci-alerts-devex', () => {// --- Stale-bridge duration ---const failureRun = (name, key, createdAt, updatedAt) => ({name,+ status: 'completed',conclusion: 'failure',head_sha: `${name}_${key}`,html_url: `https://github.com/runs/${name}/${key}`,@@ -429,6 +443,108 @@ describe('ci-alerts-devex', () => {assert.match(body, /red for 1h 13m/)})+ // --- Stale / non-terminal fetch (the 70h phantom-flap root cause) ---++ it('does not open a phantom incident when the status=completed index serves a stale page (regression)', async () => {+ // Reproduces the observed GitHub quirk behind the "opened + resolved in 4 minutes, red 70h"+ // flap: the status=completed index intermittently returns a page anchored days back (its+ // newest run an ancient failure), while master is actually green. The fix reads the fresh+ // (unfiltered) index, so a stale filtered page must never reach detection.+ const freshGreen = runs('Backend CI', ['success', 'success', 'success'])+ const stalePage = [+ failureRun('Backend CI', 'stale1', minutes(-4200).toISOString(), minutes(-4186).toISOString()),+ failureRun('Backend CI', 'stale2', minutes(-4215).toISOString(), minutes(-4201).toISOString()),+ ]+ const github = {+ rest: {+ actions: {+ // Serve the stale page ONLY to a status=completed request — exactly the API's behavior.+ listWorkflowRuns: ({ workflow_id, status }) => {+ const table = {+ 'ci-backend.yml': status === 'completed' ? stalePage : freshGreen,+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ }+ return Promise.resolve({ data: { workflow_runs: table[workflow_id] || [] } })+ },+ },+ repos: { listCommits: () => Promise.resolve({ data: pushAt(minutes(-3).toISOString()) }) },+ },+ }+ const { slack, outputs } = await run(github)+ assert.equal(outputs.action, 'none') // fresh index shows green → no incident+ assert.equal(slack.postMessage.calls.length, 0)+ assert.equal(slack.update.calls.length, 0)+ })++ it('fetchWorkflowRuns reads the fresh index and drops non-terminal runs (regression)', async () => {+ const page = [+ nonTerminalRun('ip'),+ nonTerminalRun('q', 'queued'),+ failureRun('Backend CI', 'f', minutes(-5).toISOString(), minutes(-5).toISOString()),+ { ...failureRun('Backend CI', 'x', minutes(-10).toISOString(), minutes(-10).toISOString()), conclusion: 'cancelled' },+ runs('Backend CI', ['success'])[0],+ ]+ let capturedParams+ const github = {+ rest: {+ actions: {+ listWorkflowRuns: (params) => {+ capturedParams = params+ return Promise.resolve({ data: { workflow_runs: page } })+ },+ },+ },+ }+ const result = await ciAlertsDevex.fetchWorkflowRuns(github, 'PostHog', 'posthog', 'ci-backend.yml', 40)+ // The root-cause guard: never request the eventually-consistent status=completed index.+ assert.equal(capturedParams.status, undefined)+ // in_progress/queued/cancelled dropped; settled runs kept, newest-first order preserved.+ assert.deepEqual(+ result.map((r) => r.conclusion),+ ['failure', 'success']+ )+ })++ it('pages past a head full of non-terminal runs to reach real failures (regression)', async () => {+ // A push burst leaves the newest page full of in-progress runs; per_page truncates the raw page+ // before the client-side status filter, so the completed failures sit on a later page. The+ // alerter must page to them rather than silently miss the incident (the inverse of the flap).+ const inProgress = (n) => Array.from({ length: n }, (_, i) => nonTerminalRun(`ip_${i}`))+ const failures = runs('Backend CI', Array(5).fill('failure'))+ const github = {+ rest: {+ actions: {+ listWorkflowRuns: ({ workflow_id, per_page, page }) => {+ if (workflow_id !== 'ci-backend.yml') {+ return Promise.resolve({ data: { workflow_runs: runs('Frontend CI', ['success']) } })+ }+ // First page fills the whole page with in-progress (forcing a second fetch); page 2+ // carries the genuine completed failures the raw page-1 truncation hid. A single-page+ // fetch (page undefined) only ever sees the in-progress head, so it must miss the incident.+ return Promise.resolve({ data: { workflow_runs: page >= 2 ? failures : inProgress(per_page) } })+ },+ },+ repos: { listCommits: () => Promise.resolve({ data: pushAt(minutes(-3).toISOString()) }) },+ },+ }+ const { outputs } = await run(github)+ assert.equal(outputs.action, 'create')+ assert.equal(outputs.blocking_count, '1')+ })++ it('an in-progress run at the head does not mask a real failure streak (regression)', async () => {+ // A just-started run sits atop the fresh page; the 5 completed failures beneath it must still+ // page. Since we now fetch non-terminal runs (no server-side status filter), dropping them+ // client-side — rather than letting the head short-circuit the streak walk — is what holds.+ const github = createGithubMock({+ 'ci-backend.yml': [nonTerminalRun('ip'), ...runs('Backend CI', Array(5).fill('failure'))],+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ })+ const { outputs } = await run(github)+ assert.equal(outputs.action, 'create')+ assert.equal(outputs.blocking_count, '1')+ })+it('stays silent when red past the threshold but no recent push (quiet weekend)', async () => {const github = createGithubMock({ 'ci-backend.yml': failingFor(2400), 'ci-frontend.yml': runs('Frontend CI', ['success']) },