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 master CI alert more responsive (#64123)

Raúl Negrón-Otero6543cae9bfef
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.js
index 297bd4a652a0..138528dc0aab 100644
--- a/.github/scripts/ci-alerts-devex.js
+++ b/.github/scripts/ci-alerts-devex.js
@@ -5,11 +5,15 @@
// the bot's own anchor message (tagged via Slack message metadata) and reconciles.
// There is no external state store, so there are no cache races and the alerter
// self-heals: delete the anchor and the next run reposts; a missed run just
-// reconciles on the next tick.
+// reconciles on the next tick. (A duration-only incident deleted during a quiet period
+// reposts only once pushes resume.)
//
// Two signals make master "unhealthy" (folded into one incident):
-// 1. any gating workflow with >= WORKFLOW_FAILURE_STREAK_THRESHOLD consecutive
-// failures on master — a single workflow broken run after run.
+// 1. any gating workflow failing run-after-run (>= WORKFLOW_FAILURE_STREAK_THRESHOLD
+// consecutive failures) OR red for >= WORKFLOW_FAILURE_MINUTES_THRESHOLD minutes. The
+// wall-clock arm only OPENS an incident while master is still being pushed (a commit
+// within ACTIVITY_WINDOW_MINUTES), so a master sitting red over a quiet weekend doesn't
+// page; an open incident still resolves only on green.
// 2. >= COMMIT_FAILURE_STREAK_THRESHOLD consecutive red commits across the gating
// workflows — rotating-culprit breakage where no single workflow crosses its
// own threshold but master is still consistently red.
@@ -18,8 +22,8 @@
// - Anchor: one top-level message, edited silently each tick to keep the live
// summary current. On resolve its header is struck through and a green line
// prepended — the close is visible, nothing is erased.
-// - Thread: append-only replies, one per *real change* (workflow crossed
-// threshold / recovered, commit-streak started, master green). An unchanged
+// - Thread: append-only replies, one per *real change* (workflow started failing
+// / recovered, commit-streak started, master green). An unchanged
// tick refreshes the anchor duration only — no thread noise.
//
// GitHub API rate-limit observability is handled by the separate
@@ -230,8 +234,11 @@ function buildAnchorMessage({
durationMins,
allFailingRunsUrl,
}) {
- const lines = blocking.map(
- (wf) => `• ${workflowLink(wf)} — ${plural(wf.consecutive_failures, 'failed run')} in a row`
+ // 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)}`
)
if (commitActive) {
lines.push(`• _${plural(commitStreakCount, 'commit')} in a row failed a required check_`)
@@ -281,7 +288,8 @@ function buildResolvedMessage({ previousWorkflows, durationMins }) {
function buildThreadReply({ created = [], added = [], removed = [], commitStarted = false }) {
const parts = []
if (created.length) {
- parts.push(...created.map((wf) => `:red_circle: ${workflowLink(wf)} crossed the failure threshold`))
+ // Arm-neutral wording: the anchor bullet already says count vs. duration.
+ parts.push(...created.map((wf) => `:red_circle: ${workflowLink(wf)} is now failing master`))
}
if (added.length) parts.push(`:heavy_plus_sign: now also failing: ${added.map(workflowLink).join(', ')}`)
if (removed.length) parts.push(`:white_check_mark: recovered: ${removed.map(workflowLink).join(', ')}`)
@@ -306,6 +314,8 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
const workflowFiles = (process.env.GATING_WORKFLOWS || '').split(',').filter(Boolean)
const workflowThreshold = parseInt(process.env.WORKFLOW_FAILURE_STREAK_THRESHOLD || '5', 10)
+ const 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)
@@ -331,17 +341,35 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
])
const failing = buildFailingMap(allWorkflowRuns)
+ // byDuration catches slow-velocity breakage that never stacks up a full failure streak.
const blocking = Object.values(failing)
- .filter((f) => f.consecutive_failures >= workflowThreshold)
- .sort((a, b) => b.consecutive_failures - a.consecutive_failures) // longest streak first
- .map((b) => ({ ...b, runsUrl: runsUrlFor(owner, repo, b.workflow_file) }))
+ .map((f) => {
+ const redForMins = Math.round((now.getTime() - new Date(f.since).getTime()) / 60000)
+ return {
+ ...f,
+ runsUrl: runsUrlFor(owner, repo, f.workflow_file),
+ redForMins,
+ byCount: f.consecutive_failures >= workflowThreshold,
+ byDuration: redForMins >= minutesThreshold,
+ }
+ })
+ .filter((f) => f.byCount || f.byDuration)
+ .sort((a, b) => b.redForMins - a.redForMins) // longest red first
const latestCommit = commits[0] || null
+ // Fail closed: no dated commit → not recent → the wall-clock arm won't open.
+ const recentActivity =
+ latestCommit?.date != null && now.getTime() - new Date(latestCommit.date).getTime() <= activityWindowMins * 60000
+
const { count: commitStreakCount, since: commitStreakSince } = leadingRedStreak(
classifyCommits(commits, allWorkflowRuns)
)
const commitActive = commitStreakCount >= commitThreshold
+ // Sustains/resolves an open incident — ungated, so a stale-red master stays unhealthy
+ // and an open incident resolves only on genuine green.
const unhealthy = blocking.length > 0 || commitActive
+ // Gates OPENING a new incident on recent push activity — the weekend-safety gate.
+ const shouldOpen = commitActive || blocking.some((f) => f.byCount || (f.byDuration && recentActivity))
const allFailingRunsUrl = `https://github.com/${owner}/${repo}/actions?query=branch%3Amaster+is%3Afailure`
@@ -354,7 +382,10 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
let action = 'none'
- if (unhealthy) {
+ // Open incident: sustain while unhealthy, else resolve. No incident: open only if shouldOpen.
+ const shouldWriteAnchor = active ? unhealthy : shouldOpen
+
+ if (shouldWriteAnchor) {
// Carry name + runs link in metadata so later ticks can diff and re-link by name.
const workflows = blocking.map((b) => ({ name: b.name, runsUrl: b.runsUrl }))
const since = active?.payload?.since || computeSince()
diff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.js
index c272fea70e8e..7b7259bcd509 100644
--- a/.github/scripts/ci-alerts-devex.test.js
+++ b/.github/scripts/ci-alerts-devex.test.js
@@ -102,6 +102,24 @@ 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() },
+]
+
+// A single commit `ageMins` old — drives recentActivity. No matching run SHA, so it classifies
+// 'unknown' and does not trip the commit-streak arm.
+const commitsAt = (ageMins) => [
+ {
+ sha: 'c0',
+ html_url: 'https://github.com/commit/c0',
+ author: { login: 'dev' },
+ commit: { message: 'c', author: { name: 'dev', date: minutes(-ageMins).toISOString() } },
+ },
+]
+
function run(github, { history = [], now = minutes(0), env = {} } = {}) {
const outputs = {}
const core = { setOutput: (k, v) => (outputs[k] = v), info: () => {}, warning: () => {} }
@@ -110,6 +128,9 @@ function run(github, { history = [], now = minutes(0), env = {} } = {}) {
SLACK_CHANNEL: 'C0AS64N6DJL',
GATING_WORKFLOWS: 'ci-backend.yml,ci-frontend.yml',
WORKFLOW_FAILURE_STREAK_THRESHOLD: '5',
+ // Reset to production defaults every run so a per-test override can't leak via process.env.
+ WORKFLOW_FAILURE_MINUTES_THRESHOLD: '20',
+ ACTIVITY_WINDOW_MINUTES: '120',
COMMIT_FAILURE_STREAK_THRESHOLD: '10',
...env,
})
@@ -156,7 +177,7 @@ describe('ci-alerts-devex', () => {
const thread = slack.postMessage.calls[1][0]
assert.equal(thread.thread_ts, '111.222')
assert.match(thread.text, /Backend CI/)
- assert.match(thread.text, /crossed the failure threshold/)
+ assert.match(thread.text, /is now failing master/)
})
}
@@ -272,6 +293,60 @@ describe('ci-alerts-devex', () => {
assert.equal(slack.update.calls.length, 0)
})
+ it('opens via the wall-clock arm when red past the threshold and master is being pushed', async () => {
+ // 1 failure (below the 5-streak) but red 25m, recent push → time arm trips.
+ const github = createGithubMock(
+ { 'ci-backend.yml': failingFor(25), 'ci-frontend.yml': runs('Frontend CI', ['success']) },
+ { commits: commitsAt(3) }
+ )
+ const { slack, outputs } = await run(github)
+ assert.equal(outputs.action, 'create')
+ const body = JSON.stringify(slack.postMessage.calls[0][0].attachments)
+ assert.match(body, /Backend CI/)
+ assert.match(body, /red for 25m/)
+ assert.doesNotMatch(body, /failed runs? in a row/) // duration-only bullet omits the count
+ })
+
+ 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']) },
+ { commits: commitsAt(3000) }
+ )
+ const { slack, outputs } = await run(github)
+ assert.equal(outputs.action, 'none')
+ assert.equal(slack.postMessage.calls.length, 0)
+ assert.equal(slack.update.calls.length, 0)
+ })
+
+ it('keeps a stale-red incident open (updates, never resolves) once activity goes quiet', async () => {
+ const github = createGithubMock(
+ { 'ci-backend.yml': failingFor(2400), 'ci-frontend.yml': runs('Frontend CI', ['success']) },
+ { commits: commitsAt(3000) }
+ )
+ const { slack, outputs } = await run(github, { history: [activeAnchor()] })
+ assert.equal(outputs.action, 'update')
+ assert.equal(slack.update.calls[0][0].attachments[0].color, '#E01E5A')
+ assert.equal(slack.update.calls[0][0].metadata.event_payload.status, 'active')
+ })
+
+ // Wall-clock arm gate: (red minutes, last-push age, threshold override) → action.
+ for (const [scenario, { red, commitAge, env = {} }, expected] of [
+ ['stays quiet below the minutes threshold', { red: 15, commitAge: 3 }, 'none'],
+ ['fails closed with no commit data', { red: 25 }, 'none'],
+ ['honors a custom minutes threshold', { red: 12, commitAge: 3, env: { WORKFLOW_FAILURE_MINUTES_THRESHOLD: '10' } }, 'create'],
+ ['opens just inside the activity window', { red: 30, commitAge: 119 }, 'create'],
+ ['stays quiet just outside the activity window', { red: 30, commitAge: 121 }, 'none'],
+ ]) {
+ it(`wall-clock arm ${scenario}`, async () => {
+ const github = createGithubMock(
+ { 'ci-backend.yml': failingFor(red), 'ci-frontend.yml': runs('Frontend CI', ['success']) },
+ commitAge == null ? {} : { commits: commitsAt(commitAge) }
+ )
+ const { outputs } = await run(github, { env })
+ assert.equal(outputs.action, expected)
+ })
+ }
+
describe('formatDuration', () => {
for (const [mins, expected] of [
[5, '5m'],
diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.yml
index cf93ace4805c..4f7414a71502 100644
--- a/.github/workflows/ci-alerts-devex.yml
+++ b/.github/workflows/ci-alerts-devex.yml
@@ -1,9 +1,11 @@
name: Master CI Alerts
# Cron-based rolling-window alert for sustained master failures, posted to
-# #alerts-devex. Only alerts on *sustained* breakage (a workflow failing 5+
-# runs in a row, or 10+ consecutive red commits across gating workflows) so
-# transient flakes that self-heal stay quiet.
+# #alerts-devex. Only alerts on *sustained* breakage — a workflow failing 5+
+# runs in a row OR red for 1+ hour, or 10+ consecutive red commits across
+# gating workflows — so transient flakes that self-heal stay quiet. The
+# wall-clock arm only opens while master is being pushed (ACTIVITY_WINDOW_MINUTES),
+# so a quiet weekend doesn't page.
#
# The script owns the whole flow: it recomputes master health from the GitHub
# API every tick and reconciles a single Slack incident (Slack is the source of
@@ -12,7 +14,7 @@ name: Master CI Alerts
on:
schedule:
- - cron: '*/10 * * * *'
+ - cron: '*/5 * * * *'
workflow_dispatch: # manual trigger for testing
# Serialize ticks so two runs never reconcile the same incident at once.
@@ -26,6 +28,12 @@ permissions:
env:
SLACK_CHANNEL: 'C0AS64N6DJL' # #alerts-devex
WORKFLOW_FAILURE_STREAK_THRESHOLD: '5'
+ # Wall-clock arm: a workflow red at least this long blocks even before a full failure
+ # streak. ci-backend runs ~28m, so 60m ≈ one red result that stayed red — not a transient flake.
+ WORKFLOW_FAILURE_MINUTES_THRESHOLD: '60'
+ # The wall-clock arm only opens an incident if master saw a push within this window, so a
+ # quiet weekend doesn't page. Keep it well above the typical gap between master pushes.
+ ACTIVITY_WINDOW_MINUTES: '120'
COMMIT_FAILURE_STREAK_THRESHOLD: '10'
# The master ruleset's required status checks that run on master push — a failure
# here means master is genuinely broken. Hand-synced with the ruleset; there is no