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): rebuild master CI alerts (#61126)

Raúl Negrón-Otero645f184dcf7c
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.js
index 5c0ab2b659e8..297bd4a652a0 100644
--- a/.github/scripts/ci-alerts-devex.js
+++ b/.github/scripts/ci-alerts-devex.js
@@ -1,37 +1,42 @@
-// Master CI Alerts - Cron-based rolling window alert for sustained master failures
+// Master CI Alerts — a single self-updating Slack incident for sustained master failures.
//
-// Polls the GitHub API every 10 minutes. Emits two independent signals:
+// Detection is stateless: every run recomputes master health from the GitHub API.
+// Slack itself is the source of truth for incident continuity — each run reads back
+// 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.
//
-// 1. Per-workflow streak: alerts when any watched workflow has
-// WORKFLOW_FAILURE_STREAK_THRESHOLD (default 5) consecutive failures on master.
-// Catches a single workflow broken run after run.
+// 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.
+// 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.
//
-// 2. Commit-level health: alerts when COMMIT_FAILURE_STREAK_THRESHOLD (default 10)
-// consecutive commits on master each had at least one critical workflow
-// fail. Catches rotating-culprit breakage (3 dagster flakes, 3 storybook
-// flakes, etc.) where no single workflow hits the per-workflow threshold
-// but master is still consistently red.
+// Message model (chosen for UX: never lose history, never orphan a stuck message):
+// - 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
+// tick refreshes the anchor duration only — no thread noise.
//
// GitHub API rate-limit observability is handled by the separate
// monitor-github-rate-limit workflow, which emits to PostHog as time series.
-//
-// State structure (persisted via GitHub Actions cache as .alerts-devex):
-// {
-// failing: { [workflow]: { since: ISO, sha, run_url, workflow_file, consecutive_failures } },
-// alerted: boolean,
-// slack_ts: string | null,
-// slack_channel: string | null,
-// last_failing_list: string,
-// last_failing_detail: string, // preserved for resolve messages
-// resolved: boolean,
-// commit_failure_streak_alerted: boolean,
-// commit_failure_streak_slack_ts: string | null,
-// commit_failure_streak_slack_channel: string | null,
-// commit_failure_streak_last_count: number,
-// commit_failure_streak_last_sample: string, // preserved for resolve messages
-// }
-
-const STATE_FILE = '.alerts-devex'
+
+const SLACK_API = 'https://slack.com/api'
+const INCIDENT_EVENT_TYPE = 'master_ci_incident'
+// One page of channel history. #alerts-devex is low-traffic, so the open anchor
+// reliably stays within the newest 100 messages; a busier channel would need paging.
+const HISTORY_LIMIT = 100
+// Attachment side-bar colors (Slack's red / green).
+const ACTIVE_COLOR = '#E01E5A'
+const RESOLVED_COLOR = '#2EB67D'
+
+// ---------------------------------------------------------------------------
+// GitHub data
+// ---------------------------------------------------------------------------
async function fetchWorkflowRuns(github, owner, repo, workflowFile, perPage) {
const { data } = await github.rest.actions.listWorkflowRuns({
@@ -69,6 +74,7 @@ function countConsecutiveFailures(runs) {
return count
}
+// Workflows whose newest run starts a failure streak, keyed by display name.
function buildFailingMap(allWorkflowRuns) {
const failing = {}
for (const runs of allWorkflowRuns) {
@@ -78,8 +84,8 @@ function buildFailingMap(allWorkflowRuns) {
const latest = runs[0]
const oldest = runs[count - 1]
failing[latest.name] = {
+ name: latest.name,
since: oldest.updated_at,
- sha: latest.sha,
run_url: latest.run_url,
workflow_file: latest.workflow_file,
consecutive_failures: count,
@@ -89,78 +95,6 @@ function buildFailingMap(allWorkflowRuns) {
return failing
}
-function getMaxConsecutiveFailures(failing) {
- const counts = Object.values(failing).map((f) => f.consecutive_failures || 0)
- return counts.length > 0 ? Math.max(...counts) : 0
-}
-
-function getOldestFailingSince(failing) {
- const times = Object.values(failing).map((f) => new Date(f.since).getTime())
- return times.length > 0 ? Math.min(...times) : null
-}
-
-// Decision matrix (hasFailures × wasAlerted × thresholdReached):
-// no failures, not alerted → none
-// no failures, alerted → resolve
-// failures, not alerted, under → none
-// failures, not alerted, at/over → create
-// failures, alerted, set changed → update
-// failures, alerted, set unchanged → none
-function determineAction(state, failing, workflowFailureStreakThreshold) {
- const failingNames = Object.keys(failing).sort()
- const failingList = failingNames.join(', ')
- const hasFailures = failingNames.length > 0
- const wasAlerted = state?.alerted === true
-
- if (!hasFailures && !wasAlerted) {
- return { action: 'none', failingList }
- }
-
- if (!hasFailures && wasAlerted) {
- return { action: 'resolve', failingList }
- }
-
- const maxConsecutive = getMaxConsecutiveFailures(failing)
- const thresholdReached = maxConsecutive >= workflowFailureStreakThreshold
-
- if (!thresholdReached && !wasAlerted) {
- return { action: 'none', failingList }
- }
-
- if (thresholdReached && !wasAlerted) {
- return { action: 'create', failingList }
- }
-
- // Already alerted — check if the failing set changed
- const previousList = state.last_failing_list || ''
- if (failingList !== previousList) {
- return { action: 'update', failingList }
- }
-
- return { action: 'none', failingList }
-}
-
-function buildFailingDetail(failing, criticalWorkflows) {
- const blocking = []
- const nonBlocking = []
- for (const [name, info] of Object.entries(failing)) {
- const link = `<${info.run_url}|${name}>`
- const entry = `${link} (${info.consecutive_failures} consecutive failures)`
- if (info.workflow_file && criticalWorkflows.has(info.workflow_file)) {
- blocking.push(entry)
- } else {
- nonBlocking.push(entry)
- }
- }
- let detail = ''
- if (blocking.length > 0) detail += `*Blocking:* ${blocking.join(', ')}`
- if (nonBlocking.length > 0) {
- if (detail) detail += '\n'
- detail += `*Non-blocking:* ${nonBlocking.join(', ')}`
- }
- return detail
-}
-
async function fetchRecentCommits(github, owner, repo, perPage) {
const { data } = await github.rest.repos.listCommits({
owner,
@@ -172,246 +106,320 @@ async function fetchRecentCommits(github, owner, repo, perPage) {
sha: c.sha,
html_url: c.html_url,
message: (c.commit?.message || '').split('\n')[0],
- author: c.commit?.author?.name || 'unknown',
+ author: c.author?.login || c.commit?.author?.name || 'unknown',
+ date: c.commit?.author?.date || null,
}))
}
-// Classify each commit by looking up critical-workflow runs that share its SHA.
-// Non-critical workflow runs are intentionally ignored — they're the noisy ones,
-// and per-workflow alerting already covers sticky non-critical breakage.
-function classifyCommits(commits, allWorkflowRuns, criticalWorkflows) {
+// Classify each commit by the gating workflow runs that share its SHA: red if any
+// failed, green if all reported and passed, unknown if none have reported yet
+// (CI still running / path-filtered).
+function classifyCommits(commits, allWorkflowRuns) {
const runsBySha = new Map()
for (const runs of allWorkflowRuns) {
for (const run of runs) {
- if (!criticalWorkflows.has(run.workflow_file)) continue
if (!runsBySha.has(run.sha)) runsBySha.set(run.sha, [])
runsBySha.get(run.sha).push(run)
}
}
return commits.map((commit) => {
const runs = runsBySha.get(commit.sha) || []
- if (runs.length === 0) {
- return { ...commit, status: 'unknown', redWorkflows: [] }
- }
- const red = runs.filter((r) => r.conclusion === 'failure' || r.conclusion === 'timed_out')
- if (red.length > 0) {
- return { ...commit, status: 'red', redWorkflows: red.map((r) => r.name) }
- }
- return { ...commit, status: 'green', redWorkflows: [] }
+ if (runs.length === 0) return { ...commit, status: 'unknown' }
+ const red = runs.some((r) => r.conclusion === 'failure' || r.conclusion === 'timed_out')
+ return { ...commit, status: red ? 'red' : 'green' }
})
}
-// Walk newest-to-oldest, count reds, stop at the first green.
-// Unknowns (workflows still running, path-filtered, etc.) are skipped: they
-// neither count nor break the streak. Rationale: a freshly-pushed commit
-// whose CI hasn't completed yet should not mask a real underlying streak.
-function countConsecutiveRedCommits(classified) {
+// Walk newest-to-oldest over the leading red streak, returning its length and the
+// oldest red commit's timestamp (for incident duration). Stop at the first green;
+// unknowns (CI still running, path-filtered) neither count nor break the streak, so
+// a freshly-pushed commit whose CI hasn't completed does not mask a real streak.
+function leadingRedStreak(classified) {
let count = 0
+ let since = null
for (const commit of classified) {
if (commit.status === 'green') break
- if (commit.status === 'red') count++
+ if (commit.status !== 'red') continue
+ count++
+ if (commit.date) since = commit.date
}
- return count
+ return { count, since }
}
-function determineCommitFailureStreakAction(state, count, threshold) {
- const wasAlerted = state?.commit_failure_streak_alerted === true
- const atOrOver = count >= threshold
-
- if (!atOrOver && !wasAlerted) return 'none'
- if (!atOrOver && wasAlerted) return 'resolve'
- if (atOrOver && !wasAlerted) return 'create'
- // Already alerted AND still at/over threshold — update only when count grew
- const prev = state?.commit_failure_streak_last_count || 0
- if (count > prev) return 'update'
- return 'none'
+// ---------------------------------------------------------------------------
+// Slack client (injectable for tests)
+// ---------------------------------------------------------------------------
+
+function defaultSlackClient(token, fetchImpl) {
+ const doFetch = fetchImpl || fetch
+ const post = async (method, body) => {
+ const res = await doFetch(`${SLACK_API}/${method}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json; charset=utf-8', Authorization: `Bearer ${token}` },
+ body: JSON.stringify(body),
+ })
+ const data = await res.json()
+ if (!data.ok) throw new Error(`slack ${method} failed: ${data.error}`)
+ return data
+ }
+ return {
+ postMessage: (args) => post('chat.postMessage', args),
+ update: (args) => post('chat.update', args),
+ // conversations.history is a read method — pass params in the query string.
+ history: async ({ channel, limit }) => {
+ const url = new URL(`${SLACK_API}/conversations.history`)
+ url.searchParams.set('channel', channel)
+ url.searchParams.set('limit', String(limit))
+ url.searchParams.set('include_all_metadata', 'true')
+ const res = await doFetch(url.toString(), { headers: { Authorization: `Bearer ${token}` } })
+ const data = await res.json()
+ if (!data.ok) throw new Error(`slack conversations.history failed: ${data.error}`)
+ return data
+ },
+ }
}
-function buildCommitFailureStreakDetail(classified, count) {
- if (count === 0) return ''
- const redOnly = classified.filter((c) => c.status === 'red').slice(0, count)
- const lines = redOnly.map((c) => {
- const shortSha = c.sha.slice(0, 7)
- const workflows = c.redWorkflows.join(', ')
- return `• <${c.html_url}|${shortSha}> — ${workflows}`
- })
- return lines.join('\n')
+// The bot's own open incident, identified purely by message metadata — no other
+// app sets this event_type, so it is unambiguous without knowing our bot id.
+async function findActiveIncident(slack, channel) {
+ const { messages = [] } = await slack.history({ channel, limit: HISTORY_LIMIT })
+ for (const message of messages) {
+ const payload = message.metadata?.event_payload
+ if (message.metadata?.event_type === INCIDENT_EVENT_TYPE && payload?.status === 'active') {
+ return { ts: message.ts, payload }
+ }
+ }
+ return null
}
-module.exports = async ({ github, context, core }, { fs: _fs, now: _now } = {}) => {
- const fs = _fs || require('fs')
- const now = _now || new Date()
-
- const owner = context.repo.owner
- const repo = context.repo.repo
+// ---------------------------------------------------------------------------
+// Formatting
+// ---------------------------------------------------------------------------
- const workflowFiles = (process.env.WATCHED_WORKFLOWS || '').split(',').filter(Boolean)
- const criticalWorkflows = new Set((process.env.CRITICAL_WORKFLOWS || '').split(',').filter(Boolean))
- const workflowFailureStreakThreshold = parseInt(process.env.WORKFLOW_FAILURE_STREAK_THRESHOLD || '5', 10)
- const commitFailureStreakThreshold = parseInt(process.env.COMMIT_FAILURE_STREAK_THRESHOLD || '10', 10)
- // Over-fetch to survive cancelled/skipped runs (force-pushes, concurrency cancels).
- // If the filtered set ends up smaller than workflowFailureStreakThreshold, we log a warning.
- const perPage = Math.max(workflowFailureStreakThreshold * 3, 20)
- const commitsToFetch = Math.max(commitFailureStreakThreshold * 2, 25)
-
- // Load existing state
- let state = null
- if (fs.existsSync(STATE_FILE)) {
- try {
- const raw = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'))
- if (raw.resolved) {
- console.log('Found resolved incident, treating as no active state')
- state = {
- failing: {},
- commit_failure_streak_alerted: raw.commit_failure_streak_alerted ?? false,
- commit_failure_streak_slack_ts: raw.commit_failure_streak_slack_ts ?? null,
- commit_failure_streak_slack_channel: raw.commit_failure_streak_slack_channel ?? null,
- commit_failure_streak_last_count: raw.commit_failure_streak_last_count ?? 0,
- commit_failure_streak_last_sample: raw.commit_failure_streak_last_sample ?? '',
- }
- } else {
- state = { failing: {}, ...raw }
- console.log('Loaded existing state')
- }
- } catch (e) {
- console.log('Failed to parse state file, treating as fresh')
- }
- }
+const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`
- // Fetch recent runs for each watched workflow
- console.log(`Checking ${workflowFiles.length} workflows (last ${perPage} runs each)...`)
- const allWorkflowRuns = await Promise.all(
- workflowFiles.map((wf) =>
- fetchWorkflowRuns(github, owner, repo, wf, perPage).catch((err) => {
- console.log(`Failed to fetch ${wf}: ${err.message}`)
- return []
- })
- )
- )
+function formatDuration(mins) {
+ if (mins < 60) return `${mins}m`
+ const h = Math.floor(mins / 60)
+ const m = mins % 60
+ return m === 0 ? `${h}h` : `${h}h ${m}m`
+}
- for (const runs of allWorkflowRuns) {
- if (runs.length > 0) {
- const count = countConsecutiveFailures(runs)
- console.log(
- ` ${runs[0].name}: ${runs[0].conclusion}${count > 0 ? ` (${count} consecutive failures)` : ''}`
- )
- if (runs.length < workflowFailureStreakThreshold) {
- console.log(
- ` ! Only ${runs.length} non-cancelled runs available for ${runs[0].name} — below threshold of ${workflowFailureStreakThreshold}`
- )
- }
- }
- }
+// Slack mrkdwn requires escaping these three in user-supplied text.
+const slackEscape = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
- // Build failing map from API data (recomputed each tick, no stale state)
- const failing = buildFailingMap(allWorkflowRuns)
+// A workflow's run history on master — where you can see all of its runs at a glance.
+function runsUrlFor(owner, repo, workflowFile) {
+ return `https://github.com/${owner}/${repo}/actions/workflows/${workflowFile}?query=branch%3Amaster`
+}
- // Determine action
- const { action, failingList } = determineAction(state, failing, workflowFailureStreakThreshold)
-
- console.log(`Action: ${action}`)
- console.log(`Failing: ${failingList || 'none'}`)
-
- // Build failing detail for Slack messages
- const failingDetail = buildFailingDetail(failing, criticalWorkflows)
-
- // Commit-level health: independent signal tracking consecutive red commits
- // across critical workflows. Fetches real commit order via listCommits so
- // force-pushes don't confuse the streak.
- let classified = []
- let commitFailureStreakCount = 0
- let commitFailureStreakAction = 'none'
- try {
- const commits = await fetchRecentCommits(github, owner, repo, commitsToFetch)
- classified = classifyCommits(commits, allWorkflowRuns, criticalWorkflows)
- commitFailureStreakCount = countConsecutiveRedCommits(classified)
- commitFailureStreakAction = determineCommitFailureStreakAction(state, commitFailureStreakCount, commitFailureStreakThreshold)
- console.log(`Red commits streak: ${commitFailureStreakCount} (action: ${commitFailureStreakAction})`)
- } catch (err) {
- console.log(`Failed to compute red commits: ${err.message}`)
- }
- const commitFailureStreakDetail = buildCommitFailureStreakDetail(classified, commitFailureStreakCount)
-
- // Save when there's an action or evolving failure counts to track
- const shouldSave = action !== 'none' || Object.keys(failing).length > 0
- const saveCommitFailureStreak = commitFailureStreakAction !== 'none' || commitFailureStreakCount > 0
-
- // Build new state
- const newState = {
- failing,
- alerted: action === 'create' || (state?.alerted === true && action !== 'resolve'),
- slack_ts: state?.slack_ts || null,
- slack_channel: state?.slack_channel || null,
- last_failing_list: failingList,
- last_failing_detail: failingDetail || state?.last_failing_detail || '',
- resolved: action === 'resolve',
- commit_failure_streak_alerted:
- commitFailureStreakAction === 'create' ||
- (state?.commit_failure_streak_alerted === true && commitFailureStreakAction !== 'resolve'),
- commit_failure_streak_slack_ts: state?.commit_failure_streak_slack_ts || null,
- commit_failure_streak_slack_channel: state?.commit_failure_streak_slack_channel || null,
- commit_failure_streak_last_count: commitFailureStreakAction === 'resolve' ? 0 : commitFailureStreakCount,
- commit_failure_streak_last_sample: commitFailureStreakDetail || state?.commit_failure_streak_last_sample || '',
+// Read-boundary normalizer for persisted incident workflows: tolerate an older
+// bare-name format so a metadata schema change can't break the resolve/diff path.
+const normalizeWorkflows = (list) => (list || []).map((w) => (typeof w === 'string' ? { name: w } : w))
+
+// Bold, linked workflow name → its master run history.
+const workflowLink = (wf) => `*<${wf.runsUrl}|${slackEscape(wf.name)}>*`
+
+// The anchor: a red-barred Block Kit message. `text` is the notification/a11y fallback;
+// the rich content lives in one attachment so it gets the colored side bar.
+function buildAnchorMessage({
+ blocking,
+ commitActive,
+ commitStreakCount,
+ latestCommit,
+ durationMins,
+ allFailingRunsUrl,
+}) {
+ const lines = blocking.map(
+ (wf) => `• ${workflowLink(wf)} — ${plural(wf.consecutive_failures, 'failed run')} in a row`
+ )
+ if (commitActive) {
+ lines.push(`• _${plural(commitStreakCount, 'commit')} in a row failed a required check_`)
}
- if (shouldSave || saveCommitFailureStreak) {
- fs.writeFileSync(STATE_FILE, JSON.stringify(newState, null, 2))
+ const meta = [`failing for *${formatDuration(durationMins)}*`]
+ if (latestCommit) {
+ const sha = latestCommit.sha.slice(0, 7)
+ const msg = slackEscape((latestCommit.message || '').slice(0, 80))
+ meta.push(`latest <${latestCommit.html_url}|\`${sha}\`> ${msg} · *${slackEscape(latestCommit.author)}*`)
}
+ meta.push(`<${allFailingRunsUrl}|all failing runs ↗>`)
+
+ const blocks = [
+ { type: 'header', text: { type: 'plain_text', text: ':red_circle: Master is red', emoji: true } },
+ { type: 'section', text: { type: 'mrkdwn', text: lines.join('\n') } },
+ { type: 'context', elements: [{ type: 'mrkdwn', text: meta.join(' · ') }] },
+ ]
+ const summary = blocking.length
+ ? `Master is red — ${plural(blocking.length, 'workflow')} failing (${formatDuration(durationMins)})`
+ : `Master is red — ${plural(commitStreakCount, 'commit')} in a row failed a required check (${formatDuration(durationMins)})`
+ return { text: summary, attachments: [{ color: ACTIVE_COLOR, blocks }] }
+}
- // Set outputs
- core.setOutput('action', action)
- core.setOutput('save_cache', shouldSave || saveCommitFailureStreak ? 'true' : 'false')
- core.setOutput('delete_old_caches', action === 'create' ? 'true' : 'false')
- core.setOutput('failing_workflows', failingList)
- core.setOutput('failing_count', String(Object.keys(failing).length))
-
- if (action === 'create' || action === 'update') {
- const maxConsecutive = getMaxConsecutiveFailures(failing)
- const oldest = getOldestFailingSince(failing)
- const mins = oldest ? Math.round((now.getTime() - oldest) / 60000) : 0
- core.setOutput('max_consecutive', String(maxConsecutive))
- core.setOutput('duration_mins', String(mins))
- core.setOutput('failing_detail', failingDetail)
+// The resolved anchor: green bar, recovery header, and the cleared workflows struck through.
+function buildResolvedMessage({ previousWorkflows, durationMins }) {
+ const cleared = previousWorkflows.length
+ ? previousWorkflows.map((w) => slackEscape(w.name)).join(', ')
+ : 'required-check failures'
+ const blocks = [
+ { type: 'header', text: { type: 'plain_text', text: ':large_green_circle: Master recovered', emoji: true } },
+ {
+ type: 'context',
+ elements: [
+ { type: 'mrkdwn', text: `was red for *${formatDuration(durationMins)}* · cleared: ~${cleared}~` },
+ ],
+ },
+ ]
+ return {
+ text: `Master recovered — was red ${formatDuration(durationMins)}`,
+ attachments: [{ color: RESOLVED_COLOR, blocks }],
}
+}
- if (action === 'update') {
- core.setOutput('slack_ts', state?.slack_ts || '')
- core.setOutput('slack_channel', state?.slack_channel || '')
-
- // Determine what changed for thread reply
- const prevNames = new Set((state?.last_failing_list || '').split(', ').filter(Boolean))
- const currNames = new Set(failingList.split(', ').filter(Boolean))
- const added = [...currNames].filter((n) => !prevNames.has(n))
- const removed = [...prevNames].filter((n) => !currNames.has(n))
- core.setOutput('added_workflows', added.join(', '))
- core.setOutput('removed_workflows', removed.join(', '))
+// One thread reply summarizing what changed this tick — the initial failing set on
+// create, or the delta on later ticks. Workflow names link to their run history.
+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`))
}
+ 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(', ')}`)
+ if (commitStarted) parts.push(`:red_circle: commit-failure streak crossed the threshold`)
+ return parts.join('\n')
+}
- if (action === 'resolve') {
- const previousFailing = state?.failing || {}
- const maxConsecutive = getMaxConsecutiveFailures(previousFailing)
- const oldest = getOldestFailingSince(previousFailing)
- const mins = oldest ? Math.round((now.getTime() - oldest) / 60000) : 0
- core.setOutput('max_consecutive', String(maxConsecutive))
- core.setOutput('duration_mins', String(mins))
- core.setOutput('slack_ts', state?.slack_ts || '')
- core.setOutput('slack_channel', state?.slack_channel || '')
- core.setOutput('last_failing_list', state?.last_failing_list || '')
- core.setOutput('last_failing_detail', state?.last_failing_detail || '')
- }
+function buildRecoveryReply(durationMins) {
+ return `:white_check_mark: master green again — was red ${formatDuration(durationMins)}`
+}
- // Commit-failure-streak outputs
- core.setOutput('commit_failure_streak_action', commitFailureStreakAction)
- core.setOutput('commit_failure_streak_count', String(commitFailureStreakCount))
- if (commitFailureStreakAction === 'create' || commitFailureStreakAction === 'update') {
- core.setOutput('commit_failure_streak_detail', commitFailureStreakDetail)
- }
- if (commitFailureStreakAction === 'update' || commitFailureStreakAction === 'resolve') {
- core.setOutput('commit_failure_streak_slack_ts', state?.commit_failure_streak_slack_ts || '')
- core.setOutput('commit_failure_streak_slack_channel', state?.commit_failure_streak_slack_channel || '')
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+module.exports = async ({ context, github, core }, { now: _now, slack: _slack, fetch: _fetch } = {}) => {
+ const now = _now || new Date()
+ const owner = context.repo.owner
+ const repo = context.repo.repo
+ const channel = process.env.SLACK_CHANNEL
+ const slack = _slack || defaultSlackClient(process.env.SLACK_BOT_TOKEN, _fetch)
+
+ const workflowFiles = (process.env.GATING_WORKFLOWS || '').split(',').filter(Boolean)
+ const workflowThreshold = parseInt(process.env.WORKFLOW_FAILURE_STREAK_THRESHOLD || '5', 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)
+ const commitsToFetch = Math.max(commitThreshold * 2, 25)
+
+ // Recompute master health from the API and read the Slack incident state (the
+ // source of truth for whether an incident is open). All three are independent
+ // network calls, so run them concurrently.
+ const [allWorkflowRuns, commits, active] = await Promise.all([
+ Promise.all(
+ workflowFiles.map((wf) =>
+ fetchWorkflowRuns(github, owner, repo, wf, perPage).catch((err) => {
+ core.warning(`Failed to fetch ${wf}: ${err.message}`)
+ return []
+ })
+ )
+ ),
+ fetchRecentCommits(github, owner, repo, commitsToFetch).catch((err) => {
+ core.warning(`Failed to fetch commits: ${err.message}`)
+ return []
+ }),
+ findActiveIncident(slack, channel),
+ ])
+
+ const failing = buildFailingMap(allWorkflowRuns)
+ 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) }))
+
+ const latestCommit = commits[0] || null
+ const { count: commitStreakCount, since: commitStreakSince } = leadingRedStreak(
+ classifyCommits(commits, allWorkflowRuns)
+ )
+ const commitActive = commitStreakCount >= commitThreshold
+ const unhealthy = blocking.length > 0 || commitActive
+
+ const allFailingRunsUrl = `https://github.com/${owner}/${repo}/actions?query=branch%3Amaster+is%3Afailure`
+
+ // Earliest start across both active signals (preserve original on update).
+ const computeSince = () => {
+ const times = blocking.map((b) => new Date(b.since).getTime())
+ if (commitActive && commitStreakSince) times.push(new Date(commitStreakSince).getTime())
+ return times.length ? new Date(Math.min(...times)).toISOString() : now.toISOString()
}
- if (commitFailureStreakAction === 'resolve') {
- core.setOutput('commit_failure_streak_last_count', String(state?.commit_failure_streak_last_count || 0))
- core.setOutput('commit_failure_streak_last_sample', state?.commit_failure_streak_last_sample || '')
+
+ let action = 'none'
+
+ if (unhealthy) {
+ // 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()
+ const durationMins = Math.round((now.getTime() - new Date(since).getTime()) / 60000)
+ const message = buildAnchorMessage({
+ blocking,
+ commitActive,
+ commitStreakCount,
+ latestCommit,
+ durationMins,
+ allFailingRunsUrl,
+ })
+ const metadata = {
+ event_type: INCIDENT_EVENT_TYPE,
+ event_payload: { status: 'active', since, workflows, commitActive },
+ }
+
+ if (!active) {
+ const posted = await slack.postMessage({ channel, ...message, metadata, unfurl_links: false })
+ await slack.postMessage({
+ channel,
+ thread_ts: posted.ts,
+ text: buildThreadReply({ created: workflows, commitStarted: commitActive }),
+ })
+ action = 'create'
+ } else {
+ await slack.update({ channel, ts: active.ts, ...message, metadata, unfurl_links: false })
+ // Diff against the previous set to decide whether the timeline moved.
+ const prevWorkflows = normalizeWorkflows(active.payload?.workflows)
+ const prevNames = new Set(prevWorkflows.map((w) => w.name))
+ const currNames = new Set(workflows.map((w) => w.name))
+ const added = workflows.filter((w) => !prevNames.has(w.name))
+ const removed = prevWorkflows.filter((w) => !currNames.has(w.name))
+ const commitStarted = commitActive && !active.payload?.commitActive
+ if (added.length || removed.length || commitStarted) {
+ await slack.postMessage({
+ channel,
+ thread_ts: active.ts,
+ text: buildThreadReply({ added, removed, commitStarted }),
+ })
+ }
+ action = 'update'
+ }
+ } else if (active) {
+ const since = active.payload?.since
+ const durationMins = since ? Math.round((now.getTime() - new Date(since).getTime()) / 60000) : 0
+ const previousWorkflows = normalizeWorkflows(active.payload?.workflows)
+ const message = buildResolvedMessage({ previousWorkflows, durationMins })
+ await slack.update({
+ channel,
+ ts: active.ts,
+ ...message,
+ metadata: { event_type: INCIDENT_EVENT_TYPE, event_payload: { status: 'resolved' } },
+ unfurl_links: false,
+ })
+ await slack.postMessage({ channel, thread_ts: active.ts, text: buildRecoveryReply(durationMins) })
+ action = 'resolve'
}
+
+ core.info(
+ `Action: ${action} | blocking: ${blocking.map((b) => b.name).join(', ') || 'none'} | commit streak: ${commitStreakCount}`
+ )
+ core.setOutput('action', action)
+ core.setOutput('blocking_count', String(blocking.length))
+ core.setOutput('commit_streak', String(commitStreakCount))
}
+
+module.exports.formatDuration = formatDuration
diff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.js
index f308cc779c5a..c272fea70e8e 100644
--- a/.github/scripts/ci-alerts-devex.test.js
+++ b/.github/scripts/ci-alerts-devex.test.js
@@ -1,13 +1,28 @@
-const fs = require('fs')
+// Run with: node --test .github/scripts/ci-alerts-devex.test.js
+//
+// Detection from the GitHub API is exercised alongside Slack reconciliation:
+// Slack is the source of truth, so the key cases are "open incident found in
+// history → update, never a duplicate" and the resolve/strikethrough lifecycle.
-jest.mock('fs')
+const { describe, it } = require('node:test')
+const assert = require('node:assert/strict')
const ciAlertsDevex = require('./ci-alerts-devex')
const T_BASE = new Date('2026-04-09T12:00:00Z')
const minutes = (n) => new Date(T_BASE.getTime() + n * 60000)
-// Helper: array of workflow-run objects. conclusions newest-first.
+// Minimal call-recording mock (no jest in the node:test runner).
+function recordingFn(impl) {
+ const fn = (...args) => {
+ fn.calls.push(args)
+ return impl ? impl(...args) : undefined
+ }
+ fn.calls = []
+ return fn
+}
+
+// Workflow-run objects in raw listWorkflowRuns shape, conclusions newest-first.
function runs(name, conclusions) {
return conclusions.map((conclusion, i) => ({
name,
@@ -18,23 +33,21 @@ function runs(name, conclusions) {
}))
}
-// Helper: N failures followed by 5 successes.
-const failingRuns = (name, failCount) =>
- runs(name, [...Array(failCount).fill('failure'), ...Array(5).fill('success')])
+const failingRuns = (name, failCount) => runs(name, [...Array(failCount).fill('failure'), ...Array(5).fill('success')])
const allPassing = () => ({
'ci-backend.yml': runs('Backend CI', ['success']),
'ci-frontend.yml': runs('Frontend CI', ['success']),
})
-// Helper: build listCommits + listWorkflowRuns mocks aligned by SHA.
-// Each element of perCommitConclusions is a {workflowFile: conclusion} map
-// for one commit (newest first).
+// listCommits + listWorkflowRuns aligned by SHA. Each element is a
+// {workflowFile: conclusion} map for one commit (newest first).
function commitsWithRuns(perCommitConclusions) {
const commits = perCommitConclusions.map((_, i) => ({
sha: `commit_sha_${i}`,
html_url: `https://github.com/commit/commit_sha_${i}`,
- commit: { message: `commit ${i}`, author: { name: 'dev' } },
+ author: { login: 'dev' },
+ commit: { message: `commit ${i}`, author: { name: 'dev', date: minutes(-(i * 5)).toISOString() } },
}))
const runsByWorkflow = {}
perCommitConclusions.forEach((conclusionsMap, i) => {
@@ -56,187 +69,220 @@ function createGithubMock(workflowRuns, { commits = [] } = {}) {
return {
rest: {
actions: {
- listWorkflowRuns: jest.fn(({ workflow_id }) =>
- Promise.resolve({ data: { workflow_runs: workflowRuns[workflow_id] || [] } })
- ),
+ listWorkflowRuns: ({ workflow_id }) =>
+ Promise.resolve({ data: { workflow_runs: workflowRuns[workflow_id] || [] } }),
},
repos: {
- listCommits: jest.fn(() => Promise.resolve({ data: commits })),
+ listCommits: () => Promise.resolve({ data: commits }),
},
},
}
}
-function run(github, { state = null, now = minutes(0) } = {}) {
- const outputs = {}
- const core = { setOutput: jest.fn((k, v) => (outputs[k] = v)) }
- const mockFs = {
- existsSync: jest.fn(() => state !== null),
- readFileSync: jest.fn(() => (state ? JSON.stringify(state) : '{}')),
- writeFileSync: jest.fn(),
+function makeSlack(history = []) {
+ return {
+ postMessage: recordingFn(() => ({ ok: true, ts: '111.222' })),
+ update: recordingFn(() => ({ ok: true })),
+ history: recordingFn(() => ({ ok: true, messages: history })),
}
-
- process.env.WATCHED_WORKFLOWS = 'ci-backend.yml,ci-frontend.yml'
- process.env.WORKFLOW_FAILURE_STREAK_THRESHOLD = '5'
- process.env.COMMIT_FAILURE_STREAK_THRESHOLD = '10'
- process.env.CRITICAL_WORKFLOWS = 'ci-backend.yml'
-
- return ciAlertsDevex({ github, context: { repo: { owner: 'PostHog', repo: 'posthog' } }, core }, { fs: mockFs, now }).then(() => ({
- outputs,
- writtenState: mockFs.writeFileSync.mock.calls[0]
- ? JSON.parse(mockFs.writeFileSync.mock.calls[0][1])
- : null,
- }))
}
-afterEach(() => {
- delete process.env.WATCHED_WORKFLOWS
- delete process.env.WORKFLOW_FAILURE_STREAK_THRESHOLD
- delete process.env.COMMIT_FAILURE_STREAK_THRESHOLD
- delete process.env.CRITICAL_WORKFLOWS
-})
-
-const alertedState = () => ({
- failing: {
- 'Backend CI': {
- since: minutes(-25).toISOString(),
- sha: 'sha_Backend CI_4',
- run_url: 'https://github.com/runs/Backend CI/0',
- workflow_file: 'ci-backend.yml',
- consecutive_failures: 5,
+// An open incident anchor as conversations.history would return it.
+const activeAnchor = (payload = {}) => ({
+ ts: '999.000',
+ metadata: {
+ event_type: 'master_ci_incident',
+ event_payload: {
+ status: 'active',
+ since: minutes(-30).toISOString(),
+ workflows: ['Backend CI'],
+ commitActive: false,
+ ...payload,
},
},
- alerted: true,
- slack_ts: '123.456',
- slack_channel: 'C123',
- last_failing_list: 'Backend CI',
- last_failing_detail: '*Blocking:* <https://github.com/runs/Backend CI/0|Backend CI> (5 consecutive failures)',
})
+function run(github, { history = [], now = minutes(0), env = {} } = {}) {
+ const outputs = {}
+ const core = { setOutput: (k, v) => (outputs[k] = v), info: () => {}, warning: () => {} }
+ const slack = makeSlack(history)
+ Object.assign(process.env, {
+ SLACK_CHANNEL: 'C0AS64N6DJL',
+ GATING_WORKFLOWS: 'ci-backend.yml,ci-frontend.yml',
+ WORKFLOW_FAILURE_STREAK_THRESHOLD: '5',
+ COMMIT_FAILURE_STREAK_THRESHOLD: '10',
+ ...env,
+ })
+ return ciAlertsDevex(
+ { context: { repo: { owner: 'PostHog', repo: 'posthog' } }, github, core },
+ { now, slack }
+ ).then(() => ({ slack, outputs }))
+}
+
describe('ci-alerts-devex', () => {
- it('no-op when all workflows pass', async () => {
- const { outputs, writtenState } = await run(createGithubMock(allPassing()))
- expect(outputs.action).toBe('none')
- expect(writtenState).toBeNull()
+ it('no-op when all workflows pass and no incident is open', async () => {
+ const { slack, outputs } = await run(createGithubMock(allPassing()))
+ assert.equal(outputs.action, 'none')
+ assert.equal(slack.postMessage.calls.length, 0)
+ assert.equal(slack.update.calls.length, 0)
})
- it.each(['failure', 'timed_out'])('creates alert on 5 consecutive %s', async (conclusion) => {
+ for (const conclusion of ['failure', 'timed_out']) {
+ it(`posts a new anchor + initial thread on 5 consecutive ${conclusion}`, async () => {
+ const github = createGithubMock({
+ 'ci-backend.yml': runs('Backend CI', Array(5).fill(conclusion)),
+ 'ci-frontend.yml': runs('Frontend CI', ['success']),
+ })
+ const { slack, outputs } = await run(github)
+
+ assert.equal(outputs.action, 'create')
+ assert.equal(slack.update.calls.length, 0)
+ assert.equal(slack.postMessage.calls.length, 2)
+
+ const anchor = slack.postMessage.calls[0][0]
+ assert.match(anchor.text, /Master is red/) // notification fallback
+ assert.equal(anchor.attachments[0].color, '#E01E5A')
+ const body = JSON.stringify(anchor.attachments)
+ assert.match(body, /Backend CI/)
+ assert.match(body, /5 failed runs in a row/)
+ assert.match(body, /actions\/workflows\/ci-backend\.yml\?query=branch/) // per-workflow runs link
+ assert.equal(anchor.metadata.event_type, 'master_ci_incident')
+ assert.equal(anchor.metadata.event_payload.status, 'active')
+ assert.deepEqual(
+ anchor.metadata.event_payload.workflows.map((w) => w.name),
+ ['Backend CI']
+ )
+
+ 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/)
+ })
+ }
+
+ it('updates the existing anchor instead of posting a duplicate (regression)', async () => {
const github = createGithubMock({
- 'ci-backend.yml': runs('Backend CI', Array(5).fill(conclusion)),
+ 'ci-backend.yml': runs('Backend CI', Array(8).fill('failure')),
'ci-frontend.yml': runs('Frontend CI', ['success']),
})
- const { outputs, writtenState } = await run(github)
- expect(outputs.action).toBe('create')
- expect(outputs.max_consecutive).toBe('5')
- expect(outputs.failing_detail).toMatch(/\*Blocking:\*.*Backend CI/)
- expect(writtenState.alerted).toBe(true)
+ const { slack, outputs } = await run(github, { history: [activeAnchor()] })
+
+ assert.equal(outputs.action, 'update')
+ assert.equal(slack.update.calls.length, 1)
+ // Same failing set → anchor refresh only, no thread spam, no new anchor.
+ assert.equal(slack.postMessage.calls.length, 0)
+ assert.equal(slack.update.calls[0][0].ts, '999.000')
+ assert.equal(slack.update.calls[0][0].attachments[0].color, '#E01E5A')
+ assert.equal(slack.update.calls[0][0].metadata.event_payload.status, 'active')
})
- it('updates Slack when failing set changes after alert', async () => {
+ it('threads a reply when a new workflow joins the failing set', async () => {
const github = createGithubMock({
'ci-backend.yml': failingRuns('Backend CI', 5),
'ci-frontend.yml': failingRuns('Frontend CI', 5),
})
- const { outputs } = await run(github, { state: alertedState() })
- expect(outputs.action).toBe('update')
- expect(outputs.added_workflows).toBe('Frontend CI')
- })
+ const { slack, outputs } = await run(github, { history: [activeAnchor({ workflows: ['Backend CI'] })] })
- it('resolves and preserves failing detail', async () => {
- const { outputs, writtenState } = await run(createGithubMock(allPassing()), { state: alertedState() })
- expect(outputs.action).toBe('resolve')
- expect(outputs.last_failing_detail).toContain('Backend CI')
- expect(writtenState.resolved).toBe(true)
+ assert.equal(outputs.action, 'update')
+ assert.equal(slack.update.calls.length, 1)
+ assert.equal(slack.postMessage.calls.length, 1)
+ const thread = slack.postMessage.calls[0][0].text
+ assert.match(thread, /now also failing/)
+ assert.match(thread, /Frontend CI/)
+ assert.match(thread, /actions\/workflows\/ci-frontend\.yml\?query=branch/)
})
- it('filters cancelled and skipped runs from consecutive count', async () => {
- const github = createGithubMock({
- 'ci-backend.yml': runs('Backend CI', ['failure', 'cancelled', 'failure', 'skipped', 'failure', 'failure', 'failure', 'success']),
- 'ci-frontend.yml': runs('Frontend CI', ['success']),
+ it('strikes through the anchor and threads recovery on resolve', async () => {
+ const { slack, outputs } = await run(createGithubMock(allPassing()), {
+ history: [activeAnchor({ workflows: ['Backend CI', 'E2E CI Playwright'] })],
})
- const { outputs } = await run(github)
- expect(outputs.action).toBe('create')
- expect(outputs.max_consecutive).toBe('5')
+
+ assert.equal(outputs.action, 'resolve')
+ const resolved = slack.update.calls[0][0]
+ assert.equal(resolved.ts, '999.000')
+ assert.match(resolved.text, /Master recovered/) // notification fallback
+ assert.equal(resolved.attachments[0].color, '#2EB67D')
+ const body = JSON.stringify(resolved.attachments)
+ assert.match(body, /Master recovered/)
+ assert.match(body, /~Backend CI, E2E CI Playwright~/) // struck-through cleared list
+ assert.equal(resolved.metadata.event_payload.status, 'resolved')
+ assert.match(slack.postMessage.calls[0][0].text, /master green again/)
})
- it('splits critical vs non-critical failures in detail', async () => {
- const github = createGithubMock({
- 'ci-backend.yml': failingRuns('Backend CI', 5),
- 'ci-frontend.yml': failingRuns('Frontend CI', 5),
- })
- const { outputs } = await run(github)
- expect(outputs.failing_detail).toMatch(/^\*Blocking:\*.*Backend CI/)
- expect(outputs.failing_detail).toMatch(/\*Non-blocking:\*.*Frontend CI/)
+ it('opens an incident on a commit-failure streak with no single-workflow streak', async () => {
+ // Alternating culprits: every commit is red, but neither workflow
+ // reaches 5 consecutive failures on its own.
+ const { commits, runsByWorkflow } = commitsWithRuns(
+ Array.from({ length: 10 }, (_, i) =>
+ i % 2 === 0
+ ? { 'ci-backend.yml': 'failure', 'ci-frontend.yml': 'success' }
+ : { 'ci-backend.yml': 'success', 'ci-frontend.yml': 'failure' }
+ )
+ )
+ const { slack, outputs } = await run(createGithubMock(runsByWorkflow, { commits }))
+
+ assert.equal(outputs.action, 'create')
+ assert.equal(outputs.commit_streak, '10')
+ const anchor = slack.postMessage.calls[0][0]
+ const body = JSON.stringify(anchor.attachments)
+ assert.match(body, /10 commits in a row failed a required check/)
+ // No workflow crossed its own threshold → no per-workflow bullet lines.
+ assert.doesNotMatch(body, /failed runs? in a row/)
+ assert.equal(anchor.metadata.event_payload.commitActive, true)
})
- describe('red commit streak', () => {
- const greenCommits = (n) => commitsWithRuns(Array(n).fill({ 'ci-backend.yml': 'success' }))
- const redCommits = (n) => commitsWithRuns(Array(n).fill({ 'ci-backend.yml': 'failure' }))
-
- it('no-op below threshold, creates alert at threshold', async () => {
- // 9 red → no alert
- let { commits, runsByWorkflow } = redCommits(9)
- let { outputs } = await run(createGithubMock(runsByWorkflow, { commits }))
- expect(outputs.commit_failure_streak_action).toBe('none')
- expect(outputs.commit_failure_streak_count).toBe('9')
-
- // 10 red → create, with detail listing culprit per commit
- ;({ commits, runsByWorkflow } = redCommits(10))
- ;({ outputs } = await run(createGithubMock(runsByWorkflow, { commits })))
- expect(outputs.commit_failure_streak_action).toBe('create')
- expect(outputs.commit_failure_streak_count).toBe('10')
- expect(outputs.commit_failure_streak_detail.split('\n')).toHaveLength(10)
- expect(outputs.commit_failure_streak_detail).toMatch(/Backend CI/)
- })
+ it('merges both signals into one anchor', async () => {
+ const { commits, runsByWorkflow } = commitsWithRuns(Array(10).fill({ 'ci-backend.yml': 'failure' }))
+ const { slack, outputs } = await run(createGithubMock(runsByWorkflow, { commits }))
- it('unknown commits skip, non-critical failures ignored, green breaks streak', async () => {
- // newest 2 unknown, then 1 green, then 8 red → green breaks before threshold
- const { commits, runsByWorkflow } = commitsWithRuns([
- {},
- {},
- { 'ci-backend.yml': 'success' },
- ...Array(8).fill({ 'ci-backend.yml': 'failure', 'ci-frontend.yml': 'failure' }),
- ])
- const { outputs } = await run(createGithubMock(runsByWorkflow, { commits }))
- expect(outputs.commit_failure_streak_count).toBe('0')
- expect(outputs.commit_failure_streak_action).toBe('none')
- })
+ assert.equal(outputs.action, 'create')
+ const body = JSON.stringify(slack.postMessage.calls[0][0].attachments)
+ assert.match(body, /Backend CI/)
+ assert.match(body, /10 failed runs in a row/)
+ assert.match(body, /10 commits in a row failed a required check/)
+ })
- it('non-critical-only failures do not mark commits red', async () => {
- const { commits, runsByWorkflow } = commitsWithRuns(
- Array(10).fill({ 'ci-backend.yml': 'success', 'ci-frontend.yml': 'failure' })
- )
- const { outputs } = await run(createGithubMock(runsByWorkflow, { commits }))
- expect(outputs.commit_failure_streak_count).toBe('0')
+ it('filters cancelled and skipped runs from the consecutive count', async () => {
+ const github = createGithubMock({
+ 'ci-backend.yml': runs('Backend CI', [
+ 'failure',
+ 'cancelled',
+ 'failure',
+ 'skipped',
+ 'failure',
+ 'failure',
+ 'failure',
+ 'success',
+ ]),
+ 'ci-frontend.yml': runs('Frontend CI', ['success']),
})
+ const { slack, outputs } = await run(github)
+ assert.equal(outputs.action, 'create')
+ assert.match(JSON.stringify(slack.postMessage.calls[0][0].attachments), /5 failed runs in a row/)
+ })
- it('updates when streak grows, resolves when drops below threshold', async () => {
- const stateAlerted = {
- failing: {},
- commit_failure_streak_alerted: true,
- commit_failure_streak_slack_ts: '999.999',
- commit_failure_streak_slack_channel: 'Cred',
- commit_failure_streak_last_count: 10,
- }
-
- // 14 red after alerted-at-10 → update
- let { commits, runsByWorkflow } = redCommits(14)
- let { outputs } = await run(createGithubMock(runsByWorkflow, { commits }), { state: stateAlerted })
- expect(outputs.commit_failure_streak_action).toBe('update')
- expect(outputs.commit_failure_streak_count).toBe('14')
-
- // 10 red with last_count already 10 → no-op (idempotent at/over threshold, no growth)
- ;({ commits, runsByWorkflow } = redCommits(10))
- ;({ outputs } = await run(createGithubMock(runsByWorkflow, { commits }), { state: stateAlerted }))
- expect(outputs.commit_failure_streak_action).toBe('none')
- expect(outputs.commit_failure_streak_count).toBe('10')
-
- // All green after alerted → resolve
- ;({ commits, runsByWorkflow } = greenCommits(12))
- let writtenState
- ;({ outputs, writtenState } = await run(createGithubMock(runsByWorkflow, { commits }), { state: stateAlerted }))
- expect(outputs.commit_failure_streak_action).toBe('resolve')
- expect(writtenState.commit_failure_streak_alerted).toBe(false)
+ it('stays quiet below threshold with no open incident', async () => {
+ const github = createGithubMock({
+ 'ci-backend.yml': runs('Backend CI', ['failure', 'failure', 'success']),
+ 'ci-frontend.yml': runs('Frontend CI', ['success']),
})
+ 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)
+ })
+
+ describe('formatDuration', () => {
+ for (const [mins, expected] of [
+ [5, '5m'],
+ [59, '59m'],
+ [60, '1h'],
+ [88, '1h 28m'],
+ [192, '3h 12m'],
+ ]) {
+ it(`formats ${mins} minutes as ${expected}`, () => {
+ assert.equal(ciAlertsDevex.formatDuration(mins), expected)
+ })
+ }
})
})
diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.yml
index 870729c61329..9be871c2b604 100644
--- a/.github/workflows/ci-alerts-devex.yml
+++ b/.github/workflows/ci-alerts-devex.yml
@@ -1,27 +1,38 @@
name: Master CI Alerts
-# Cron-based rolling window alert for sustained master failures.
-# Only alerts when a workflow has 5+ consecutive failures,
-# filtering out transient flakes that self-heal.
+# 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.
#
-# See also: ci-master-status.yml (event-driven, alerts on first failure)
+# 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
+# truth — the open anchor is found via message metadata, so there is no cache
+# state to race or lose). See .github/scripts/ci-alerts-devex.js.
on:
schedule:
- cron: '*/10 * * * *'
workflow_dispatch: # manual trigger for testing
+# Serialize ticks so two runs never reconcile the same incident at once.
+concurrency:
+ group: ci-alerts-devex
+ cancel-in-progress: false
+
permissions:
contents: read
- actions: write
env:
SLACK_CHANNEL: 'C0AS64N6DJL' # #alerts-devex
WORKFLOW_FAILURE_STREAK_THRESHOLD: '5'
COMMIT_FAILURE_STREAK_THRESHOLD: '10'
- # Keep in sync with ci-master-status.yml watched workflows
- WATCHED_WORKFLOWS: 'ci-backend.yml,ci-nodejs.yml,ci-frontend.yml,ci-storybook.yml,ci-security.yaml,ci-dagster.yml,ci-e2e-playwright.yml,ci-rust.yml'
- CRITICAL_WORKFLOWS: 'ci-backend.yml,ci-frontend.yml,ci-e2e-playwright.yml'
+ # 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
+ # automated reconciliation, so update this when the required checks change.
+ # (container-images-ci and shellcheck are also required but only run on PR/merge_group,
+ # so this push-based alerter can't observe them.)
+ GATING_WORKFLOWS: 'ci-python.yml,ci-backend.yml,ci-nodejs.yml,ci-frontend.yml,ci-storybook.yml,ci-security.yaml,ci-dagster.yml,ci-e2e-playwright.yml,ci-rust.yml,ci-mcp.yml,ci-llm-gateway.yml'
jobs:
check-master:
@@ -29,221 +40,16 @@ jobs:
timeout-minutes: 5
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
-
- - name: Restore state
- uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
with:
- path: .alerts-devex
- key: alerts-devex-${{ github.run_id }}
- restore-keys: alerts-devex-
+ sparse-checkout: |
+ .github/scripts/ci-alerts-devex.js
+ sparse-checkout-cone-mode: false
- - name: Check master status
- id: check
+ - name: Reconcile master CI incident with Slack
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
- with:
- script: |
- const script = require('./.github/scripts/ci-alerts-devex.js');
- await script({ github, context, core });
-
- # ============ SLACK: CREATE ============
-
- - name: Post new alert to Slack
- if: steps.check.outputs.action == 'create'
- id: slack_new
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
- with:
- method: chat.postMessage
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- errors: true
- payload: |
- channel: "${{ env.SLACK_CHANNEL }}"
- text: ":red_circle: Master is red — ${{ steps.check.outputs.failing_count }} workflow(s) failing (${{ steps.check.outputs.max_consecutive }}+ consecutive failures, ~${{ steps.check.outputs.duration_mins }} min)"
- blocks:
- - type: "section"
- text:
- type: "mrkdwn"
- text: ":red_circle: *Master is red* — ${{ steps.check.outputs.failing_count }} workflow(s) failing (~${{ steps.check.outputs.duration_mins }} min)"
- - type: "section"
- text:
- type: "mrkdwn"
- text: "${{ steps.check.outputs.failing_detail }}"
-
- - name: Save Slack info to state
- if: steps.check.outputs.action == 'create'
- env:
- SLACK_CHANNEL_ID: ${{ steps.slack_new.outputs.channel_id }}
- SLACK_TS: ${{ steps.slack_new.outputs.ts }}
- run: |
- jq \
- --arg channel "$SLACK_CHANNEL_ID" \
- --arg ts "$SLACK_TS" \
- '. + {slack_channel: $channel, slack_ts: $ts}' \
- .alerts-devex > .alerts-devex.tmp
- mv .alerts-devex.tmp .alerts-devex
-
- # ============ SLACK: UPDATE ============
-
- - name: Update Slack message
- if: steps.check.outputs.action == 'update'
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
- with:
- method: chat.update
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- errors: true
- payload: |
- channel: "${{ steps.check.outputs.slack_channel }}"
- ts: "${{ steps.check.outputs.slack_ts }}"
- text: ":red_circle: Master is red — ${{ steps.check.outputs.failing_count }} workflow(s) failing (${{ steps.check.outputs.max_consecutive }}+ consecutive failures, ~${{ steps.check.outputs.duration_mins }} min)"
- blocks:
- - type: "section"
- text:
- type: "mrkdwn"
- text: ":red_circle: *Master is red* — ${{ steps.check.outputs.failing_count }} workflow(s) failing (~${{ steps.check.outputs.duration_mins }} min)"
- - type: "section"
- text:
- type: "mrkdwn"
- text: "${{ steps.check.outputs.failing_detail }}"
-
- - name: Thread reply with changes
- if: steps.check.outputs.action == 'update' && (steps.check.outputs.added_workflows != '' || steps.check.outputs.removed_workflows != '')
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
- with:
- method: chat.postMessage
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- payload: |
- channel: "${{ steps.check.outputs.slack_channel }}"
- thread_ts: "${{ steps.check.outputs.slack_ts }}"
- text: "${{ steps.check.outputs.added_workflows != '' && format(':x: Now also failing: {0}', steps.check.outputs.added_workflows) || '' }}${{ steps.check.outputs.added_workflows != '' && steps.check.outputs.removed_workflows != '' && '\n' || '' }}${{ steps.check.outputs.removed_workflows != '' && format(':white_check_mark: Recovered: {0}', steps.check.outputs.removed_workflows) || '' }}"
-
- # ============ SLACK: RESOLVE ============
-
- - name: Update Slack to resolved
- if: steps.check.outputs.action == 'resolve'
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
- with:
- method: chat.update
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- errors: true
- payload: |
- channel: "${{ steps.check.outputs.slack_channel }}"
- ts: "${{ steps.check.outputs.slack_ts }}"
- text: ":large_green_circle: Master recovered (was red for ${{ steps.check.outputs.max_consecutive }} consecutive runs, ~${{ steps.check.outputs.duration_mins }} min)"
- blocks:
- - type: "section"
- text:
- type: "mrkdwn"
- text: ":large_green_circle: *Master recovered* (was red for ${{ steps.check.outputs.max_consecutive }} consecutive runs, ~${{ steps.check.outputs.duration_mins }} min)"
- - type: "section"
- text:
- type: "mrkdwn"
- text: "Previously failing: ${{ steps.check.outputs.last_failing_list }}"
-
- - name: Thread reply with resolution
- if: steps.check.outputs.action == 'resolve'
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
- with:
- method: chat.postMessage
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- payload: |
- channel: "${{ steps.check.outputs.slack_channel }}"
- thread_ts: "${{ steps.check.outputs.slack_ts }}"
- text: ":white_check_mark: All watched workflows are passing again"
-
- # ============ COMMIT FAILURE STREAK: CREATE ============
-
- - name: Post commit-failure-streak alert to Slack
- if: steps.check.outputs.commit_failure_streak_action == 'create'
- id: slack_commit_streak
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
- with:
- method: chat.postMessage
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- errors: true
- payload: |
- channel: "${{ env.SLACK_CHANNEL }}"
- text: ":large_orange_circle: Master unstable — ${{ steps.check.outputs.commit_failure_streak_count }} consecutive commits had a critical workflow fail"
- blocks:
- - type: "section"
- text:
- type: "mrkdwn"
- text: ":large_orange_circle: *Master unstable* — ${{ steps.check.outputs.commit_failure_streak_count }} consecutive commits had a critical workflow fail\nCulprit rotates across workflows, so no single workflow crosses its own threshold — but master is effectively red."
- - type: "section"
- text:
- type: "mrkdwn"
- text: "${{ steps.check.outputs.commit_failure_streak_detail }}"
-
- - name: Save commit-failure-streak Slack info to state
- if: steps.check.outputs.commit_failure_streak_action == 'create'
env:
- SLACK_CHANNEL_ID: ${{ steps.slack_commit_streak.outputs.channel_id }}
- SLACK_TS: ${{ steps.slack_commit_streak.outputs.ts }}
- run: |
- jq \
- --arg channel "$SLACK_CHANNEL_ID" \
- --arg ts "$SLACK_TS" \
- '. + {commit_failure_streak_slack_channel: $channel, commit_failure_streak_slack_ts: $ts}' \
- .alerts-devex > .alerts-devex.tmp
- mv .alerts-devex.tmp .alerts-devex
-
- # ============ COMMIT FAILURE STREAK: UPDATE ============
-
- - name: Update commit-failure-streak Slack message
- if: steps.check.outputs.commit_failure_streak_action == 'update'
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
+ SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
with:
- method: chat.update
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- errors: true
- payload: |
- channel: "${{ steps.check.outputs.commit_failure_streak_slack_channel }}"
- ts: "${{ steps.check.outputs.commit_failure_streak_slack_ts }}"
- text: ":large_orange_circle: Master unstable — ${{ steps.check.outputs.commit_failure_streak_count }} consecutive commits had a critical workflow fail"
- blocks:
- - type: "section"
- text:
- type: "mrkdwn"
- text: ":large_orange_circle: *Master unstable* — ${{ steps.check.outputs.commit_failure_streak_count }} consecutive commits had a critical workflow fail\nCulprit rotates across workflows, so no single workflow crosses its own threshold — but master is effectively red."
- - type: "section"
- text:
- type: "mrkdwn"
- text: "${{ steps.check.outputs.commit_failure_streak_detail }}"
-
- # ============ COMMIT FAILURE STREAK: RESOLVE ============
-
- - name: Update commit-failure-streak Slack to resolved
- if: steps.check.outputs.commit_failure_streak_action == 'resolve'
- uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1
- with:
- method: chat.update
- token: ${{ secrets.SLACK_BOT_TOKEN }}
- errors: true
- payload: |
- channel: "${{ steps.check.outputs.commit_failure_streak_slack_channel }}"
- ts: "${{ steps.check.outputs.commit_failure_streak_slack_ts }}"
- text: ":large_green_circle: Master stable again (streak ended after ${{ steps.check.outputs.commit_failure_streak_last_count }} consecutive red commits)"
- blocks:
- - type: "section"
- text:
- type: "mrkdwn"
- text: ":large_green_circle: *Master stable again* (streak ended after ${{ steps.check.outputs.commit_failure_streak_last_count }} consecutive red commits)"
-
- # ============ CACHE ============
-
- - name: Delete old caches on new alert
- if: steps.check.outputs.delete_old_caches == 'true'
- continue-on-error: true
- env:
- GH_TOKEN: ${{ github.token }}
- run: |
- echo "Deleting old alert caches..."
- gh cache list --key alerts-devex- --json id,key -q '.[] | "\(.id) \(.key)"' | while read id key; do
- echo "Deleting cache: $key"
- gh cache delete "$id" || true
- done
-
- - name: Save state to cache
- if: steps.check.outputs.save_cache == 'true'
- uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
- with:
- path: .alerts-devex
- key: alerts-devex-${{ github.run_id }}
+ script: |
+ const script = require('./.github/scripts/ci-alerts-devex.js')
+ await script({ github, context, core })
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index 40412d3cde3d..d29dd146559a 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -45,3 +45,6 @@ jobs:
# Shells out to schema_usage_scan.py via python3 (preinstalled on ubuntu).
- name: Schema-impact tests (Node)
run: node --test .github/scripts/schema-impact.test.js
+
+ - name: Master CI alerts tests (Node)
+ run: node --test .github/scripts/ci-alerts-devex.test.js
diff --git a/.github/workflows/monitor-github-rate-limit.yml b/.github/workflows/monitor-github-rate-limit.yml
index 1bba85e4ccab..7d4ee4db7436 100644
--- a/.github/workflows/monitor-github-rate-limit.yml
+++ b/.github/workflows/monitor-github-rate-limit.yml
@@ -11,6 +11,17 @@ name: Monitor GitHub Rate Limit
#
# Alerting belongs downstream in PostHog (windowed thresholds, attribution by
# repo) — not in the workflow itself. Keep this file focused on emission.
+#
+# A burn-rate alert is wired up downstream in PostHog (DevEx project, id 347861) —
+# these are live PostHog resources, not config in this repo:
+# - Insight "GitHub core rate-limit — early-window peak utilization" (short id
+# iGGXQ1mF): per hour, the peak `core` utilization among samples with >30 min
+# left in the reset window (reset_in_seconds > 1800), which filters out the
+# harmless pre-reset sawtooth peak.
+# - A PostHog alert on that insight fires when it exceeds 0.8 (80%) — i.e. the
+# bucket is burning early, not just spiking right before its hourly reset.
+# - A Slack destination relays the firing alert to #alerts-devex (and email).
+# To change the threshold/window, edit the insight + alert in PostHog, not here.
on:
pull_request: