: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): bound master-red alert duration + fire on CI events (#67045)
Raúl Negrón-Oteroeda11b869218
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.jsindex 138528dc0aab..e5ebbacb908d 100644--- a/.github/scripts/ci-alerts-devex.js+++ b/.github/scripts/ci-alerts-devex.js@@ -37,6 +37,9 @@ const HISTORY_LIMIT = 100// Attachment side-bar colors (Slack's red / green).const ACTIVE_COLOR = '#E01E5A'const RESOLVED_COLOR = '#2EB67D'+// Caps the *displayed* red duration only (not detection): the shown span won't bridge a gap this+// wide between kept failures, so it can't anchor to a stale run.+const STREAK_MAX_GAP_MINUTES = 180// ---------------------------------------------------------------------------// GitHub data@@ -62,6 +65,7 @@ async function fetchWorkflowRuns(github, owner, repo, workflowFile, perPage) {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-runsworkflow_file: workflowFile,}))}@@ -78,6 +82,19 @@ function countConsecutiveFailures(runs) {return count}+// Display-only "red since": oldest failure reachable from the newest without crossing a gap wider+// than STREAK_MAX_GAP_MINUTES. Uses immutable created_at so re-runs can't collapse the span.+function contiguousFailureSince(runs, count) {+ const dispatchedAt = (run) => run.created_at || run.updated_at+ let oldest = runs[0]+ for (let i = 1; i < count; i++) {+ const gapMins = (new Date(dispatchedAt(runs[i - 1])).getTime() - new Date(dispatchedAt(runs[i])).getTime()) / 60000+ if (!(gapMins <= STREAK_MAX_GAP_MINUTES)) break // NaN-safe+ oldest = runs[i]+ }+ return dispatchedAt(oldest)+}+// Workflows whose newest run starts a failure streak, keyed by display name.function buildFailingMap(allWorkflowRuns) {const failing = {}@@ -89,7 +106,8 @@ function buildFailingMap(allWorkflowRuns) {const oldest = runs[count - 1]failing[latest.name] = {name: latest.name,- since: oldest.updated_at,+ since: oldest.updated_at, // detection (full streak)+ displaySince: contiguousFailureSince(runs, count), // display only (gap-bounded)run_url: latest.run_url,workflow_file: latest.workflow_file,consecutive_failures: count,@@ -237,8 +255,8 @@ function buildAnchorMessage({// Duration-only blockers show just the red time — no sub-threshold "N failed runs" count.const lines = blocking.map((wf) =>wf.byCount- ? `• ${workflowLink(wf)} — ${plural(wf.consecutive_failures, 'failed run')} in a row · red for ${formatDuration(wf.redForMins)}`- : `• ${workflowLink(wf)} — red for ${formatDuration(wf.redForMins)}`+ ? `• ${workflowLink(wf)} — ${plural(wf.consecutive_failures, 'failed run')} in a row · red for ${formatDuration(wf.displayRedForMins)}`+ : `• ${workflowLink(wf)} — red for ${formatDuration(wf.displayRedForMins)}`)if (commitActive) {lines.push(`• _${plural(commitStreakCount, 'commit')} in a row failed a required check_`)@@ -348,13 +366,14 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, freturn {...f,runsUrl: runsUrlFor(owner, repo, f.workflow_file),- redForMins,+ redForMins, // detection: byDuration + open/resolve thresholds+ displayRedForMins: Math.round((now.getTime() - new Date(f.displaySince).getTime()) / 60000),byCount: f.consecutive_failures >= workflowThreshold,byDuration: redForMins >= minutesThreshold,}}).filter((f) => f.byCount || f.byDuration)- .sort((a, b) => b.redForMins - a.redForMins) // longest red first+ .sort((a, b) => b.redForMins - a.redForMins) // most-severe (longest true red) firstconst latestCommit = commits[0] || null// Fail closed: no dated commit → not recent → the wall-clock arm won't open.@@ -373,9 +392,9 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, fconst allFailingRunsUrl = `https://github.com/${owner}/${repo}/actions?query=branch%3Amaster+is%3Afailure`- // Earliest start across both active signals (preserve original on update).+ // Earliest start across both active signals (preserve original on update); gap-bounded displaySince.const computeSince = () => {- const times = blocking.map((b) => new Date(b.since).getTime())+ const times = blocking.map((b) => new Date(b.displaySince).getTime())if (commitActive && commitStreakSince) times.push(new Date(commitStreakSince).getTime())return times.length ? new Date(Math.min(...times)).toISOString() : now.toISOString()}diff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.jsindex 7b7259bcd509..3a7d46aa79f7 100644--- a/.github/scripts/ci-alerts-devex.test.js+++ b/.github/scripts/ci-alerts-devex.test.js@@ -307,6 +307,128 @@ describe('ci-alerts-devex', () => {assert.doesNotMatch(body, /failed runs? in a row/) // duration-only bullet omits the count})+ // --- Stale-bridge duration ---+ const failureRun = (name, key, createdAt, updatedAt) => ({+ name,+ conclusion: 'failure',+ head_sha: `${name}_${key}`,+ html_url: `https://github.com/runs/${name}/${key}`,+ created_at: createdAt,+ updated_at: updatedAt,+ })+ const pushAt = (iso) => [+ { sha: 'push', html_url: 'https://github.com/commit/push', author: { login: 'dev' }, commit: { message: 'p', author: { name: 'dev', date: iso } } },+ ]++ it('bridged stale failures do not inflate the displayed duration (regression)', async () => {+ // Recent failure + stale failure (the cancelled runs between are dropped) → the detection+ // streak spans multiple days. Must still open, but report the recent contiguous red.+ const now = minutes(13)+ const github = createGithubMock(+ {+ 'ci-rust.yml': [+ failureRun('Rust CI', 'recent', minutes(-9).toISOString(), minutes(5).toISOString()),+ failureRun('Rust CI', 'stale', minutes(-3600).toISOString(), minutes(-3586).toISOString()),+ ],+ 'ci-backend.yml': [+ failureRun('Backend CI', 'recent', minutes(-21).toISOString(), minutes(6).toISOString()),+ failureRun('Backend CI', 'stale', minutes(-3590).toISOString(), minutes(-3576).toISOString()),+ ],+ },+ { commits: pushAt(minutes(8).toISOString()) }+ )+ const { slack, outputs } = await run(github, { now, env: { GATING_WORKFLOWS: 'ci-rust.yml,ci-backend.yml' } })++ assert.equal(outputs.action, 'create') // detection unchanged: full-span byDuration still opens+ const anchor = slack.postMessage.calls[0][0]+ const body = JSON.stringify(anchor.attachments)+ assert.match(body, /Rust CI/)+ assert.match(body, /Backend CI/)+ assert.doesNotMatch(body, /\d{2,}h/) // no stale multi-day duration survives+ assert.match(anchor.text, /\(\d+m\)/) // summary duration is minutes of recent contiguous red+ // anchored to the recent failure, not the stale run+ assert.equal(anchor.metadata.event_payload.since, minutes(-21).toISOString())+ })++ it('does not falsely resolve an open incident while the newest run is still failing (regression)', async () => {+ // Newest run still failing, prior failure >180m back — detection uses the full span, so the+ // incident must stay open (never a false "master recovered").+ const now = minutes(13)+ const github = createGithubMock({+ 'ci-backend.yml': [+ failureRun('Backend CI', 'recent', minutes(-10).toISOString(), minutes(5).toISOString()),+ failureRun('Backend CI', 'stale', minutes(-3600).toISOString(), minutes(-3586).toISOString()),+ ],+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ })+ const { slack, outputs } = await run(github, { now, history: [activeAnchor()] })+ assert.equal(outputs.action, 'update') // stays open — not 'resolve'+ assert.equal(slack.update.calls[0][0].attachments[0].color, '#E01E5A')+ assert.equal(slack.update.calls[0][0].metadata.event_payload.status, 'active')+ })++ it('still pages for a sparse workflow whose genuine failures are far apart (regression)', async () => {+ // Sparse workflow: two genuine failures >180m apart, no green between. Must still open.+ const now = minutes(13)+ const github = createGithubMock(+ {+ 'ci-rust.yml': [+ failureRun('Rust CI', 'recent', minutes(-5).toISOString(), minutes(2).toISOString()),+ failureRun('Rust CI', 'older', minutes(-270).toISOString(), minutes(-255).toISOString()),+ ],+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ },+ { commits: pushAt(minutes(8).toISOString()) }+ )+ const { slack, outputs } = await run(github, { now, env: { GATING_WORKFLOWS: 'ci-rust.yml,ci-frontend.yml' } })+ assert.equal(outputs.action, 'create') // old gap-break would have missed this entirely+ const body = JSON.stringify(slack.postMessage.calls[0][0].attachments)+ assert.match(body, /red for \d+m/) // shows the recent contiguous red, not the ~4.5h span+ assert.doesNotMatch(body, /red for \d+h/)+ })++ it('re-running a run inside the streak does not collapse the shown duration to ~0', async () => {+ // Oldest failure re-run (updated_at bumped to ~now) — created_at anchor keeps the full span.+ const now = minutes(13)+ const f = (key, created, updated) => failureRun('Backend CI', key, created, updated)+ const github = createGithubMock({+ 'ci-backend.yml': [+ f('f5', minutes(0).toISOString(), minutes(7).toISOString()),+ f('f4', minutes(-5).toISOString(), minutes(2).toISOString()),+ f('f3', minutes(-10).toISOString(), minutes(-3).toISOString()),+ f('f2', minutes(-15).toISOString(), minutes(-8).toISOString()),+ f('f1', minutes(-20).toISOString(), minutes(11).toISOString()), // oldest, re-run → updated bumped+ ],+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ })+ const { slack, outputs } = await run(github, { now })+ assert.equal(outputs.action, 'create')+ const body = JSON.stringify(slack.postMessage.calls[0][0].attachments)+ assert.match(body, /5 failed runs in a row/)+ assert.match(body, /red for 33m/) // from f1's created_at, not its re-run updated_at+ })++ it('reports the honest full duration for a genuinely-continuous outage', async () => {+ // Dense failures, no gap > 180m — the cap must NOT fire, so the full ~1h13m is reported.+ const now = minutes(13)+ const f = (key, created, updated) => failureRun('Backend CI', key, created, updated)+ const github = createGithubMock(+ {+ 'ci-backend.yml': [+ f('c3', minutes(-5).toISOString(), minutes(5).toISOString()),+ f('c2', minutes(-30).toISOString(), minutes(-20).toISOString()),+ f('c1', minutes(-60).toISOString(), minutes(-50).toISOString()),+ ],+ 'ci-frontend.yml': runs('Frontend CI', ['success']),+ },+ { commits: pushAt(minutes(8).toISOString()) }+ )+ const { slack, outputs } = await run(github, { now })+ assert.equal(outputs.action, 'create')+ const body = JSON.stringify(slack.postMessage.calls[0][0].attachments)+ assert.match(body, /red for 1h 13m/)+ })+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']) },diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.ymlindex 4f7414a71502..5a3e0b0768db 100644--- a/.github/workflows/ci-alerts-devex.yml+++ b/.github/workflows/ci-alerts-devex.yml@@ -13,6 +13,13 @@ name: Master CI Alerts# state to race or lose). See .github/scripts/ci-alerts-devex.js.on:+ # Reconcile ~a minute after master CI finishes; GitHub throttles the cron below to ~hourly under+ # load. A reconcile reads all gating workflows anyway, so one hook on Backend CI (the long-pole on+ # ~every push) suffices. branches:[master] skips PR completions; cron stays a backstop.+ workflow_run:+ workflows: ['Backend CI']+ types: [completed]+ branches: [master]schedule:- cron: '*/5 * * * *'workflow_dispatch: # manual trigger for testing@@ -44,6 +51,9 @@ env:jobs:check-master:+ # only reconcile on push completions (branches:[master] already scopes the trigger to master)+ if: >-+ github.event_name != 'workflow_run' || github.event.workflow_run.event == 'push'runs-on: ubuntu-latesttimeout-minutes: 5steps: