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.

fix(ci): verify runs-index freshness in master alerter (#68664)

Raúl Negrón-Otero11dcaf2d9523
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.js
index 6cfd9152834f..5da6d9fdfc35 100644
--- a/.github/scripts/ci-alerts-devex.js
+++ b/.github/scripts/ci-alerts-devex.js
@@ -40,6 +40,13 @@ 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
+// Runs-index freshness bound (see fetchWorkflowRuns): fresh pages trail master's newest commit by
+// minutes, stale ones by days. Staleness is per-request, so retry before giving up.
+const RUN_INDEX_MAX_LAG_MINUTES = 180
+const STALE_PAGE_RETRIES = 2
+const STALE_PAGE_RETRY_DELAY_MS = 15000
+
+const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
// ---------------------------------------------------------------------------
// GitHub data
@@ -48,19 +55,30 @@ const STREAK_MAX_GAP_MINUTES = 180
// 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'
-// The freshest settled runs for a workflow, newest-first.
+// The freshest settled runs for a workflow, newest-first; throws (staleIndex) when the page can't
+// be trusted.
//
-// 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 runs-list index is eventually consistent and intermittently serves pages anchored days back —
+// trusting it produced the "red 70h"/"red 141h" phantom incidents, and dropping status=completed
+// didn't fix it (the branch/event filters hit the same index). So freshness is verified against
+// `freshAsOf` (master's newest commit, strongly consistent): every gating workflow runs on every
+// master push, so a page head trailing it by more than RUN_INDEX_MAX_LAG_MINUTES is stale —
+// retry, then unreadable, never green.
//
-// 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) {
+// Paging: `per_page` truncates the raw page BEFORE the client-side filter, so page until the
+// leading streak is settled (a kept non-failure bounds the walk) or the cap.
+async function fetchWorkflowRuns(github, owner, repo, workflowFile, perPage, { freshAsOf = null, sleep = defaultSleep } = {}) {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await fetchSettledRuns(github, owner, repo, workflowFile, perPage, freshAsOf)
+ } catch (err) {
+ if (!err.staleIndex || attempt >= STALE_PAGE_RETRIES) throw err
+ await sleep(STALE_PAGE_RETRY_DELAY_MS)
+ }
+ }
+}
+
+async function fetchSettledRuns(github, owner, repo, workflowFile, perPage, freshAsOf) {
const MAX_PAGES = 5
const settled = []
for (let page = 1; page <= MAX_PAGES; page++) {
@@ -73,6 +91,22 @@ async function fetchWorkflowRuns(github, owner, repo, workflowFile, perPage) {
per_page: perPage,
page,
})
+ // Freshness is judged on the raw page-1 head (any status) before paging deeper; an empty
+ // page is the same anomaly — every gating workflow has master-push history.
+ if (page === 1 && freshAsOf) {
+ const head = data.workflow_runs[0]
+ // Empty page → Infinity (stale); NaN (unparseable dates) falls through to fresh.
+ const lagMins = head
+ ? (new Date(freshAsOf).getTime() - new Date(head.created_at).getTime()) / 60000
+ : Infinity
+ if (lagMins > RUN_INDEX_MAX_LAG_MINUTES) {
+ const err = new Error(
+ `stale runs index: newest run ${head?.created_at || 'absent'} trails newest master commit ${freshAsOf}`
+ )
+ err.staleIndex = true
+ throw err
+ }
+ }
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.
@@ -155,7 +189,9 @@ async function fetchRecentCommits(github, owner, repo, perPage) {
html_url: c.html_url,
message: (c.commit?.message || '').split('\n')[0],
author: c.author?.login || c.commit?.author?.name || 'unknown',
- date: c.commit?.author?.date || null,
+ // Committer date = push time; squash-merge author dates can be days older and would
+ // suppress the activity gate and backdate durations.
+ date: c.commit?.committer?.date || c.commit?.author?.date || null,
}))
}
@@ -349,8 +385,9 @@ function buildRecoveryReply(durationMins) {
// Main
// ---------------------------------------------------------------------------
-module.exports = async ({ context, github, core }, { now: _now, slack: _slack, fetch: _fetch } = {}) => {
+module.exports = async ({ context, github, core }, { now: _now, slack: _slack, fetch: _fetch, sleep: _sleep } = {}) => {
const now = _now || new Date()
+ const sleep = _sleep || defaultSleep
const owner = context.repo.owner
const repo = context.repo.repo
const channel = process.env.SLACK_CHANNEL
@@ -368,26 +405,37 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
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
- // 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),
+ // Slack read is independent — start it first to overlap the GitHub reads.
+ const activePromise = findActiveIncident(slack, channel)
+
+ // Commits (strongly consistent) anchor the runs freshness check, so fetch them first. null
+ // (not []) on failure: with no anchor nothing is verifiable → every workflow is unreadable.
+ const commits = await fetchRecentCommits(github, owner, repo, commitsToFetch).catch((err) => {
+ core.warning(`Failed to fetch commits: ${err.message}`)
+ return null
+ })
+ const freshAsOf = commits?.[0]?.date || null
+
+ // null = unreadable (API error or persistently stale page), distinct from "no failures".
+ const [fetchedRuns, active] = await Promise.all([
+ commits === null
+ ? workflowFiles.map(() => null)
+ : Promise.all(
+ workflowFiles.map((wf) =>
+ fetchWorkflowRuns(github, owner, repo, wf, perPage, { freshAsOf, sleep }).catch((err) => {
+ core.warning(`No usable runs for ${wf}: ${err.message}`)
+ return null
+ })
+ )
+ ),
+ activePromise,
])
+ const knownRuns = fetchedRuns.filter((runs) => runs !== null)
+ // Reconciling an open incident on incomplete reads would let a stale page or a failed fetch
+ // masquerade as recovery.
+ const dataComplete = commits !== null && knownRuns.length === fetchedRuns.length
- const failing = buildFailingMap(allWorkflowRuns)
+ const failing = buildFailingMap(knownRuns)
// byDuration catches slow-velocity breakage that never stacks up a full failure streak.
const blocking = Object.values(failing)
.map((f) => {
@@ -404,13 +452,13 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
.filter((f) => f.byCount || f.byDuration)
.sort((a, b) => b.redForMins - a.redForMins) // most-severe (longest true red) first
- const latestCommit = commits[0] || null
+ 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)
+ classifyCommits(commits || [], knownRuns)
)
const commitActive = commitStreakCount >= commitThreshold
// Sustains/resolves an open incident — ungated, so a stale-red master stays unhealthy
@@ -433,7 +481,11 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
// Open incident: sustain while unhealthy, else resolve. No incident: open only if shouldOpen.
const shouldWriteAnchor = active ? unhealthy : shouldOpen
- if (shouldWriteAnchor) {
+ if (active && !dataComplete) {
+ // Unreadable data can't distinguish recovery from a stale read — hold; next tick reconciles.
+ core.warning('Incomplete CI data with an open incident — holding, no reconcile this tick')
+ action = 'hold'
+ } else 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 021d096a53f3..79c2b1700418 100644
--- a/.github/scripts/ci-alerts-devex.test.js
+++ b/.github/scripts/ci-alerts-devex.test.js
@@ -149,7 +149,7 @@ function run(github, { history = [], now = minutes(0), env = {} } = {}) {
})
return ciAlertsDevex(
{ context: { repo: { owner: 'PostHog', repo: 'posthog' } }, github, core },
- { now, slack }
+ { now, slack, sleep: () => Promise.resolve() }
).then(() => ({ slack, outputs }))
}
@@ -333,6 +333,12 @@ describe('ci-alerts-devex', () => {
const pushAt = (iso) => [
{ sha: 'push', html_url: 'https://github.com/commit/push', author: { login: 'dev' }, commit: { message: 'p', author: { name: 'dev', date: iso } } },
]
+ // A runs page anchored ~3 days back — the shape both observed phantoms ("red 70h", "red 141h")
+ // were built from.
+ const stalePage = (conclusion = 'failure') => [
+ { ...failureRun('Backend CI', 'stale1', minutes(-4200).toISOString(), minutes(-4186).toISOString()), conclusion },
+ { ...failureRun('Backend CI', 'stale2', minutes(-4215).toISOString(), minutes(-4201).toISOString()), conclusion },
+ ]
it('bridged stale failures do not inflate the displayed duration (regression)', async () => {
// Recent failure + stale failure (the cancelled runs between are dropped) → the detection
@@ -451,17 +457,13 @@ describe('ci-alerts-devex', () => {
// 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-backend.yml': status === 'completed' ? stalePage() : freshGreen,
'ci-frontend.yml': runs('Frontend CI', ['success']),
}
return Promise.resolve({ data: { workflow_runs: table[workflow_id] || [] } })
@@ -545,6 +547,93 @@ describe('ci-alerts-devex', () => {
assert.equal(outputs.blocking_count, '1')
})
+ // --- Stale pages on the branch/event-filtered index (the 141h phantom root cause) ---
+
+ // A github mock whose ci-backend runs read misbehaves (`backendResponse` thunk) while
+ // ci-frontend and commits stay healthy — the fixture for every unreadable-data case.
+ const brokenBackendGithub = (backendResponse, onBackendRead = () => {}) => ({
+ rest: {
+ actions: {
+ listWorkflowRuns: ({ workflow_id }) => {
+ if (workflow_id !== 'ci-backend.yml') {
+ return Promise.resolve({ data: { workflow_runs: runs('Frontend CI', ['success']) } })
+ }
+ onBackendRead()
+ return backendResponse()
+ },
+ },
+ repos: { listCommits: () => Promise.resolve({ data: pushAt(minutes(-3).toISOString()) }) },
+ },
+ })
+
+ it('a stale runs page anchored days back cannot open a phantom incident (regression)', async () => {
+ // The "red 141h 45m" phantom: even without status=completed, the branch/event-filtered
+ // index served a days-old page while master's newest commit was minutes old.
+ let backendReads = 0
+ const github = brokenBackendGithub(
+ () => Promise.resolve({ data: { workflow_runs: stalePage() } }),
+ () => backendReads++
+ )
+ const { slack, outputs } = await run(github)
+ assert.equal(backendReads, 3) // initial read + 2 retries before declaring the page unreadable
+ assert.equal(outputs.action, 'none')
+ assert.equal(slack.postMessage.calls.length, 0)
+ assert.equal(slack.update.calls.length, 0)
+ })
+
+ // Unreadable data — an ancient page, an empty page, or a fetch error — must hold an open
+ // incident, never read as "no failures" and strike through the anchor with a phantom recovery.
+ for (const [scenario, backendResponse] of [
+ ['a stale runs page', () => Promise.resolve({ data: { workflow_runs: stalePage('success') } })],
+ ['an empty runs page', () => Promise.resolve({ data: { workflow_runs: [] } })],
+ ['a failed runs fetch', () => Promise.reject(new Error('boom'))],
+ ]) {
+ it(`${scenario} cannot resolve an open incident (regression)`, async () => {
+ const { slack, outputs } = await run(brokenBackendGithub(backendResponse), {
+ history: [activeAnchor()],
+ })
+ assert.equal(outputs.action, 'hold')
+ assert.equal(slack.update.calls.length, 0)
+ assert.equal(slack.postMessage.calls.length, 0)
+ })
+ }
+
+ it('a failed commits fetch cannot open a phantom incident via the streak-count arm (regression)', async () => {
+ // Without the commits anchor no runs page is verifiable — a stale 5-failure page must not
+ // open through byCount (which is not gated on recent activity).
+ const github = {
+ rest: {
+ actions: {
+ listWorkflowRuns: ({ workflow_id }) => {
+ const table = {
+ 'ci-backend.yml': runs('Backend CI', Array(5).fill('failure')),
+ 'ci-frontend.yml': runs('Frontend CI', ['success']),
+ }
+ return Promise.resolve({ data: { workflow_runs: table[workflow_id] || [] } })
+ },
+ },
+ repos: { listCommits: () => Promise.reject(new Error('boom')) },
+ },
+ }
+ 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('activity gate uses the committer date, not squash-merge author dates (regression)', async () => {
+ // A squash merge keeps the branch's original author date (days old); the committer date is
+ // the push time. A just-merged commit must count as activity for the wall-clock arm.
+ const squashMerged = commitsAt(6000)
+ squashMerged[0].commit.committer = { name: 'dev', date: minutes(-3).toISOString() }
+ const github = createGithubMock(
+ { 'ci-backend.yml': failingFor(25), 'ci-frontend.yml': runs('Frontend CI', ['success']) },
+ { commits: squashMerged }
+ )
+ const { outputs } = await run(github)
+ assert.equal(outputs.action, 'create')
+ })
+
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.yml
index 5a3e0b0768db..93823534245b 100644
--- a/.github/workflows/ci-alerts-devex.yml
+++ b/.github/workflows/ci-alerts-devex.yml
@@ -47,6 +47,8 @@ env:
# 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.)
+ # Every workflow listed MUST run on every master push (no path filters) — the script verifies
+ # runs freshness against master's newest commit; one that legitimately lags would wedge resolution.
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: