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): alert and trace on the hourly master matrices (#90953)

Georges-Antoine Assib57c522be140
diff --git a/.agents/skills/debugging-ci-failures/references/master-red-incident.md b/.agents/skills/debugging-ci-failures/references/master-red-incident.md
index c691066e4d6d..138bc68b9548 100644
--- a/.agents/skills/debugging-ci-failures/references/master-red-incident.md
+++ b/.agents/skills/debugging-ci-failures/references/master-red-incident.md
@@ -20,6 +20,10 @@ Setting the workflow up is `master-red-workflow-setup.md` in this directory.
The alert text, which names the failing workflows, how long each has been red, and the newest commit on master.
It does not carry run ids, so start by resolving the alert's workflow names to their latest failing runs on master, then follow the parent skill from there.
+A name with a `(scheduled)` suffix is not a separate workflow.
+It is the cron-triggered master run of the workflow before the suffix, which the alerter tracks apart from that workflow's master-push runs because the two run different jobs.
+`Backend CI (scheduled)` means the hourly full test matrices, so resolve it to Backend CI's newest failing `schedule` run rather than its push runs.
+
## The verdict
Classify with the parent skill's table, then reduce it to one of three answers a reader can act on: **infrastructure** (no code change fixes it), **flaky test**, or **real regression**.
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.js
index d396ed7edb70..43ff26686a32 100644
--- a/.github/scripts/ci-alerts-devex.js
+++ b/.github/scripts/ci-alerts-devex.js
@@ -18,6 +18,12 @@
// workflows — rotating-culprit breakage where no single workflow crosses its
// own threshold but master is still consistently red.
//
+// Runs are read per *lane*, which is one (workflow file, trigger event) stream of master runs.
+// Most gating workflows have only a push lane. Backend CI has two, because its master-push run
+// carries the per-commit checks while the test matrices run from an hourly `schedule` trigger.
+// Each lane gets its own streak, its own thresholds, and its own line in the incident, so a
+// green push run cannot mask a red matrix run.
+//
// 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
@@ -47,11 +53,62 @@ 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
+// A scheduled lane gets one run per cron tick, so its newest run legitimately trails master's
+// newest commit by up to a cron period, and by more when GitHub throttles the schedule trigger
+// under load. Holding it to the push bound would read a healthy hourly lane as unreadable, which
+// wedges incident resolution.
+const SCHEDULED_RUN_INDEX_MAX_LAG_MINUTES = 360
+// Suffix that separates a scheduled lane from its workflow's push lane in the incident.
+const SCHEDULED_LANE_LABEL = '(scheduled)'
const STALE_PAGE_RETRIES = 2
const STALE_PAGE_RETRY_DELAY_MS = 15000
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
+// ---------------------------------------------------------------------------
+// Lanes
+// ---------------------------------------------------------------------------
+
+// The lanes to evaluate, read from the workflow's env. GATING_WORKFLOWS gives every workflow a
+// master-push lane; SCHEDULED_GATING_WORKFLOWS adds a second, independently-evaluated lane for a
+// workflow whose master coverage comes from a cron instead. A workflow can appear in both (Backend
+// CI does: push runs the per-commit checks, the schedule runs the test matrices).
+function buildLanes(env) {
+ const list = (value) =>
+ (value || '')
+ .split(',')
+ .map((entry) => entry.trim())
+ .filter(Boolean)
+ const lanes = list(env.GATING_WORKFLOWS).map((workflowFile) => ({
+ workflowFile,
+ event: 'push',
+ label: '',
+ maxLagMinutes: RUN_INDEX_MAX_LAG_MINUTES,
+ streakThreshold: parseInt(env.WORKFLOW_FAILURE_STREAK_THRESHOLD || '5', 10),
+ minutesThreshold: parseInt(env.WORKFLOW_FAILURE_MINUTES_THRESHOLD || '20', 10),
+ // Push runs only exist while people push, so a run streak is already confined to
+ // active hours.
+ countNeedsActivity: false,
+ }))
+ for (const workflowFile of list(env.SCHEDULED_GATING_WORKFLOWS)) {
+ lanes.push({
+ workflowFile,
+ event: 'schedule',
+ label: SCHEDULED_LANE_LABEL,
+ maxLagMinutes: SCHEDULED_RUN_INDEX_MAX_LAG_MINUTES,
+ // Own thresholds: at one run per cron tick, the push streak threshold of 5 needs five
+ // hours to trip, while the push wall-clock arm pages on a single flaky run held for one
+ // tick. Both scheduled arms need more than one red tick behind them.
+ streakThreshold: parseInt(env.SCHEDULED_FAILURE_STREAK_THRESHOLD || '2', 10),
+ minutesThreshold: parseInt(env.SCHEDULED_FAILURE_MINUTES_THRESHOLD || '150', 10),
+ // A cron keeps firing through a quiet weekend, so this lane's run streak needs the same
+ // activity gate the wall-clock arm has, because otherwise it pages with nobody pushing.
+ countNeedsActivity: true,
+ })
+ }
+ return lanes
+}
+
// ---------------------------------------------------------------------------
// GitHub data
// ---------------------------------------------------------------------------
@@ -59,22 +116,30 @@ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
// 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; throws (staleIndex) when the page can't
+// The freshest settled runs for one lane, newest-first; throws (staleIndex) when the page can't
// be trusted.
//
// 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.
+// `freshAsOf` (master's newest commit, strongly consistent): a page head trailing it by more than
+// the lane's `maxLagMinutes` is stale: retry, then unreadable, never green. The bound is per lane
+// because the cadences differ: a push lane runs on every master commit, and a scheduled lane runs
+// once per cron tick.
//
// 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 } = {}) {
+async function fetchWorkflowRuns(
+ github,
+ owner,
+ repo,
+ workflowFile,
+ perPage,
+ { event = 'push', maxLagMinutes = RUN_INDEX_MAX_LAG_MINUTES, freshAsOf = null, sleep = defaultSleep } = {}
+) {
for (let attempt = 0; ; attempt++) {
try {
- return await fetchSettledRuns(github, owner, repo, workflowFile, perPage, freshAsOf)
+ return await fetchSettledRuns(github, owner, repo, workflowFile, perPage, { event, maxLagMinutes, freshAsOf })
} catch (err) {
if (!err.staleIndex || attempt >= STALE_PAGE_RETRIES) {throw err}
await sleep(STALE_PAGE_RETRY_DELAY_MS)
@@ -82,7 +147,7 @@ async function fetchWorkflowRuns(github, owner, repo, workflowFile, perPage, { f
}
}
-async function fetchSettledRuns(github, owner, repo, workflowFile, perPage, freshAsOf) {
+async function fetchSettledRuns(github, owner, repo, workflowFile, perPage, { event, maxLagMinutes, freshAsOf }) {
const MAX_PAGES = 5
const settled = []
for (let page = 1; page <= MAX_PAGES; page++) {
@@ -91,21 +156,21 @@ async function fetchSettledRuns(github, owner, repo, workflowFile, perPage, fres
repo,
workflow_id: workflowFile,
branch: 'master',
- event: 'push',
+ event,
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.
+ // page is the same anomaly — every lane has master run 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) {
+ if (lagMins > maxLagMinutes) {
const err = new Error(
- `stale runs index: newest run ${head?.created_at || 'absent'} trails newest master commit ${freshAsOf}`
+ `stale runs index: newest ${event} run ${head?.created_at || 'absent'} trails newest master commit ${freshAsOf}`
)
err.staleIndex = true
throw err
@@ -159,17 +224,22 @@ function contiguousFailureSince(runs, count) {
return dispatchedAt(oldest)
}
-// Workflows whose newest run starts a failure streak, keyed by display name.
-function buildFailingMap(allWorkflowRuns) {
+// Lanes whose newest run starts a failure streak, keyed by the name shown in the incident. A
+// workflow with two lanes reports each under its own key, so its push and scheduled runs never
+// overwrite one another.
+function buildFailingMap(laneRuns) {
const failing = {}
- for (const runs of allWorkflowRuns) {
+ for (const { lane, runs } of laneRuns) {
if (runs.length === 0) {continue}
const count = countConsecutiveFailures(runs)
if (count > 0) {
const latest = runs[0]
const oldest = runs[count - 1]
- failing[latest.name] = {
- name: latest.name,
+ const name = lane.label ? `${latest.name} ${lane.label}` : latest.name
+ failing[name] = {
+ name,
+ workflowName: latest.name, // unlabeled, for the run-history link
+ lane,
since: oldest.updated_at, // detection (full streak)
displaySince: contiguousFailureSince(runs, count), // display only (gap-bounded)
run_url: latest.run_url,
@@ -400,16 +470,16 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
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 minutesThreshold = parseInt(process.env.WORKFLOW_FAILURE_MINUTES_THRESHOLD || '20', 10)
+ const lanes = buildLanes(process.env)
const activityWindowMins = parseInt(process.env.ACTIVITY_WINDOW_MINUTES || '120', 10)
const commitThreshold = parseInt(process.env.COMMIT_FAILURE_STREAK_THRESHOLD || '10', 10)
// Page size for the run fetch. fetchWorkflowRuns pages until the streak is settled, so this only
// trades round-trips against page size; keep it wide enough to resolve the common case in one page
- // despite the in-progress/cancelled runs it now drops client-side. Clamp to GitHub's per_page max
- // of 100 (silently capped otherwise) so a tuned-up streak threshold can't quietly lose capacity.
- const perPage = Math.min(Math.max(workflowThreshold * 6, 40), 100)
+ // despite the in-progress/cancelled runs it now drops client-side. Sized off the widest lane
+ // threshold and clamped to GitHub's per_page max of 100 (silently capped otherwise), so a
+ // tuned-up streak threshold can't quietly lose capacity.
+ const widestStreakThreshold = Math.max(5, ...lanes.map((lane) => lane.streakThreshold))
+ const perPage = Math.min(Math.max(widestStreakThreshold * 6, 40), 100)
const commitsToFetch = Math.max(commitThreshold * 2, 25)
// Slack read is independent — start it first to overlap the GitHub reads.
@@ -426,34 +496,42 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
// null = unreadable (API error or persistently stale page), distinct from "no failures".
const [fetchedRuns, active] = await Promise.all([
commits === null
- ? workflowFiles.map(() => null)
+ ? lanes.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}`)
+ lanes.map((lane) =>
+ fetchWorkflowRuns(github, owner, repo, lane.workflowFile, perPage, {
+ event: lane.event,
+ maxLagMinutes: lane.maxLagMinutes,
+ freshAsOf,
+ sleep,
+ }).catch((err) => {
+ core.warning(`No usable ${lane.event} runs for ${lane.workflowFile}: ${err.message}`)
return null
})
)
),
activePromise,
])
- const knownRuns = fetchedRuns.filter((runs) => runs !== null)
+ const knownLaneRuns = lanes
+ .map((lane, i) => ({ lane, runs: fetchedRuns[i] }))
+ .filter(({ runs }) => runs !== null)
+ const knownRuns = knownLaneRuns.map(({ runs }) => runs)
// 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 dataComplete = commits !== null && knownLaneRuns.length === lanes.length
- const failing = buildFailingMap(knownRuns)
+ const failing = buildFailingMap(knownLaneRuns)
// byDuration catches slow-velocity breakage that never stacks up a full failure streak.
const blocking = Object.values(failing)
.map((f) => {
const redForMins = Math.round((now.getTime() - new Date(f.since).getTime()) / 60000)
return {
...f,
- runsUrl: runsUrlFor(owner, repo, f.name),
+ runsUrl: runsUrlFor(owner, repo, f.workflowName),
redForMins, // detection: byDuration + open/resolve thresholds
displayRedForMins: Math.round((now.getTime() - new Date(f.displaySince).getTime()) / 60000),
- byCount: f.consecutive_failures >= workflowThreshold,
- byDuration: redForMins >= minutesThreshold,
+ byCount: f.consecutive_failures >= f.lane.streakThreshold,
+ byDuration: redForMins >= f.lane.minutesThreshold,
}
})
.filter((f) => f.byCount || f.byDuration)
@@ -471,8 +549,14 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
// 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))
+ // Gates OPENING a new incident on recent push activity — the weekend-safety gate. The
+ // wall-clock arm is always gated. A run streak is gated too when its lane keeps producing runs
+ // while nobody pushes, which is true of a cron lane and false of a push lane.
+ const shouldOpen =
+ commitActive ||
+ blocking.some(
+ (f) => (f.byCount && (!f.lane.countNeedsActivity || recentActivity)) || (f.byDuration && recentActivity)
+ )
const allFailingRunsUrl = `https://github.com/${owner}/${repo}/actions?query=branch%3Amaster+is%3Afailure`
diff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.js
index d5efa4b92f69..345d036d3f90 100644
--- a/.github/scripts/ci-alerts-devex.test.js
+++ b/.github/scripts/ci-alerts-devex.test.js
@@ -140,9 +140,12 @@ function run(github, { history = [], now = minutes(0), env = {} } = {}) {
Object.assign(process.env, {
SLACK_CHANNEL: 'C0AS64N6DJL',
GATING_WORKFLOWS: 'ci-backend.yml,ci-frontend.yml',
+ SCHEDULED_GATING_WORKFLOWS: '',
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',
+ SCHEDULED_FAILURE_STREAK_THRESHOLD: '2',
+ SCHEDULED_FAILURE_MINUTES_THRESHOLD: '150',
ACTIVITY_WINDOW_MINUTES: '120',
COMMIT_FAILURE_STREAK_THRESHOLD: '10',
...env,
@@ -504,6 +507,7 @@ describe('ci-alerts-devex', () => {
const result = await ciAlertsDevex.fetchWorkflowRuns(github, 'PostHog', 'posthog', 'ci-backend.yml', 40)
// The root-cause guard: never request the eventually-consistent status=completed index.
assert.equal(capturedParams.status, undefined)
+ assert.equal(capturedParams.event, 'push') // one lane per trigger event; push is the default
// in_progress/queued/cancelled dropped; settled runs kept, newest-first order preserved.
assert.deepEqual(
result.map((r) => r.conclusion),
@@ -678,6 +682,96 @@ describe('ci-alerts-devex', () => {
})
}
+ // --- Scheduled lanes ---
+
+ // Backend CI covers master through two lanes: its push run carries the per-commit checks and
+ // its hourly scheduled run carries the test matrices.
+ const scheduledEnv = { GATING_WORKFLOWS: 'ci-backend.yml', SCHEDULED_GATING_WORKFLOWS: 'ci-backend.yml' }
+
+ // listWorkflowRuns keyed by `<workflow file>:<event>`, so a lane that requests the wrong
+ // trigger reads an empty page instead of the other lane's runs.
+ const laneGithub = (laneRuns, commits) => ({
+ rest: {
+ actions: {
+ listWorkflowRuns: ({ workflow_id, event }) =>
+ Promise.resolve({ data: { workflow_runs: laneRuns[`${workflow_id}:${event}`] || [] } }),
+ },
+ repos: { listCommits: () => Promise.resolve({ data: commits }) },
+ },
+ })
+
+ // (push conclusions, schedule conclusions) → action + the workflow names carried on the anchor.
+ for (const [scenario, { push, schedule }, expected] of [
+ [
+ 'a red scheduled lane pages while its push lane is green',
+ { push: ['success'], schedule: ['failure', 'failure'] },
+ { action: 'create', blocking: ['Backend CI (scheduled)'] },
+ ],
+ [
+ 'both lanes of one workflow report under their own names',
+ { push: Array(5).fill('failure'), schedule: ['failure', 'failure'] },
+ { action: 'create', blocking: ['Backend CI', 'Backend CI (scheduled)'] },
+ ],
+ [
+ 'a single scheduled failure stays below the lane threshold',
+ { push: ['success'], schedule: ['failure', 'success'] },
+ { action: 'none', blocking: [] },
+ ],
+ ['a green scheduled lane stays quiet', { push: ['success'], schedule: ['success'] }, { action: 'none', blocking: [] }],
+ ]) {
+ it(`scheduled lane: ${scenario}`, async () => {
+ const github = laneGithub(
+ {
+ 'ci-backend.yml:push': runs('Backend CI', push),
+ 'ci-backend.yml:schedule': runs('Backend CI', schedule),
+ },
+ pushAt(minutes(-3).toISOString())
+ )
+ const { slack, outputs } = await run(github, { env: scheduledEnv })
+ assert.equal(outputs.action, expected.action)
+ assert.equal(outputs.blocking_count, String(expected.blocking.length))
+ const anchored = slack.postMessage.calls[0]?.[0]?.metadata?.event_payload?.workflows || []
+ assert.deepEqual(
+ anchored.map((w) => w.name).sort(),
+ expected.blocking
+ )
+ })
+ }
+
+ it('a red scheduled lane stays quiet while nobody is pushing (weekend gate)', async () => {
+ // A cron keeps producing runs through a quiet weekend, so unlike a push lane its run
+ // streak alone must not open an incident.
+ const github = laneGithub(
+ {
+ 'ci-backend.yml:push': runs('Backend CI', ['success']),
+ 'ci-backend.yml:schedule': runs('Backend CI', ['failure', 'failure']),
+ },
+ pushAt(minutes(-3000).toISOString())
+ )
+ const { slack, outputs } = await run(github, { env: scheduledEnv })
+ assert.equal(outputs.action, 'none')
+ assert.equal(slack.postMessage.calls.length, 0)
+ })
+
+ it('a scheduled lane trailing master by hours is still readable (regression)', async () => {
+ // The push freshness bound assumes a run per master commit. An hourly lane legitimately
+ // trails master's newest commit, and judging it by the push bound would read the matrices
+ // as unreadable, which drops them from detection and holds every open incident.
+ const github = laneGithub(
+ {
+ 'ci-backend.yml:push': runs('Backend CI', ['success']),
+ 'ci-backend.yml:schedule': [
+ failureRun('Backend CI', 'sched1', minutes(-240).toISOString(), minutes(-215).toISOString()),
+ failureRun('Backend CI', 'sched2', minutes(-300).toISOString(), minutes(-275).toISOString()),
+ ],
+ },
+ pushAt(minutes(-3).toISOString())
+ )
+ const { outputs } = await run(github, { env: scheduledEnv })
+ assert.equal(outputs.action, 'create')
+ assert.equal(outputs.blocking_count, '1')
+ })
+
describe('formatDuration', () => {
for (const [mins, expected] of [
[5, '5m'],
diff --git a/.github/scripts/report_workflow_run_traces.py b/.github/scripts/report_workflow_run_traces.py
index 08ee9cdefeea..53ff34131877 100644
--- a/.github/scripts/report_workflow_run_traces.py
+++ b/.github/scripts/report_workflow_run_traces.py
@@ -7,9 +7,9 @@
# "opentelemetry-exporter-otlp-proto-http~=1.27",
# ]
# ///
-"""Emit OTLP traces for completed master-push workflow runs.
+"""Emit OTLP traces for completed master workflow runs.
-Scans the Actions API for master pushes that finished since the last successful
+Scans the Actions API for master runs that finished since the last successful
run of this reporter and emits one trace per (run_id, run_attempt), shaped:
<workflow> (root, one trace per run attempt)
@@ -75,6 +75,12 @@ INSTRUMENTATION_VERSION = "0.1.0"
# Workflow file whose own run history is the watermark.
SELF_WORKFLOW_FILE = "ci-master-run-traces.yml"
+# Workflows that cover master from a cron instead of from every push, scanned on their
+# `schedule` runs as well. ci-backend.yml runs only the per-commit checks on a master push
+# and its full test matrices hourly, so a push-only scan drops the heaviest CI workload in
+# the repo. Hand-synced with SCHEDULED_GATING_WORKFLOWS in ci-alerts-devex.yml, which reads
+# the same lanes for alerting.
+SCHEDULED_MASTER_WORKFLOWS = ("ci-backend.yml",)
DEFAULT_LOOKBACK_HOURS = 6.0
DEFAULT_MAX_RUNS = 200
@@ -278,27 +284,46 @@ def watermark(repo: str, token: str, *, lookback_hours: float, now: datetime, op
def scan_runs(repo: str, token: str, since: datetime, *, opener: Any = None) -> list[dict]:
- """Completed master-push runs whose completion lands at or after `since`.
+ """Completed master runs whose completion lands at or after `since`, newest first.
+
+ One scan per trigger event, because the API filters on a single event at a time. The
+ repo-wide scan covers push, and each workflow in SCHEDULED_MASTER_WORKFLOWS is scanned
+ for its `schedule` runs by workflow file. A repo-wide schedule scan would instead pull in
+ every unrelated cron in the repo, and the frequent ones would crowd real CI runs out of
+ the --max-runs cap.
The API can only filter on `created`, so widen the window by a day and narrow
on `updated_at` — which for a completed run is when it finished.
"""
created_floor = (since - timedelta(days=1)).date().isoformat()
- query = urllib.parse.urlencode(
- {
- "branch": "master",
- "event": "push",
- "status": "completed",
- "exclude_pull_requests": "true",
- "created": f">={created_floor}",
- }
- )
- raw = _paginate(f"repos/{repo}/actions/runs?{query}", token, "workflow_runs", opener=opener)
+
+ def query(event: str) -> str:
+ return urllib.parse.urlencode(
+ {
+ "branch": "master",
+ "event": event,
+ "status": "completed",
+ "exclude_pull_requests": "true",
+ "created": f">={created_floor}",
+ }
+ )
+
+ paths = [f"repos/{repo}/actions/runs?{query('push')}"]
+ paths += [
+ f"repos/{repo}/actions/workflows/{workflow_file}/runs?{query('schedule')}"
+ for workflow_file in SCHEDULED_MASTER_WORKFLOWS
+ ]
fresh = []
- for run in raw:
- updated = parse_iso_utc(run.get("updated_at") or "")
- if updated is not None and updated >= since:
- fresh.append(run)
+ for path in paths:
+ for run in _paginate(path, token, "workflow_runs", opener=opener):
+ updated = parse_iso_utc(run.get("updated_at") or "")
+ if updated is not None and updated >= since:
+ fresh.append(run)
+ # Merging two scans breaks the API's newest-first order, which the --max-runs cap relies
+ # on to keep the freshest runs.
+ fresh.sort(
+ key=lambda run: parse_iso_utc(run.get("updated_at") or "") or datetime.min.replace(tzinfo=UTC), reverse=True
+ )
return fresh
@@ -727,7 +752,7 @@ def collect_runs(args: argparse.Namespace, token: str, now: datetime) -> Collect
# would pair one attempt's jobs with another attempt's window.
logger.warning("--run-attempt only applies with --run-id; ignoring it for the scan")
since = parse_iso_utc(args.since) or watermark(args.repo, token, lookback_hours=args.lookback_hours, now=now)
- logger.info("scanning master pushes completed since %s", since.isoformat())
+ logger.info("scanning master runs completed since %s", since.isoformat())
raw_runs = scan_runs(args.repo, token, since)
if len(raw_runs) > args.max_runs:
# Not an incomplete tick: holding the watermark here would re-scan the same
@@ -777,7 +802,7 @@ def main(argv: list[str] | None = None) -> int:
return EXIT_INCOMPLETE
if not collection.runs:
- logger.info("no completed master-push runs to trace")
+ logger.info("no completed master runs to trace")
return EXIT_OK if collection.complete else EXIT_INCOMPLETE
if args.dry_run or os.environ.get("DRY_RUN") == "1":
diff --git a/.github/scripts/test_report_workflow_run_traces.py b/.github/scripts/test_report_workflow_run_traces.py
index 32b735a56251..3a038e457b5b 100644
--- a/.github/scripts/test_report_workflow_run_traces.py
+++ b/.github/scripts/test_report_workflow_run_traces.py
@@ -407,6 +407,23 @@ class TestScan:
assert "event=push" in url
assert "status=completed" in url
+ def test_also_scans_the_scheduled_lane_of_cron_covered_workflows(self) -> None:
+ # ci-backend.yml runs the per-commit checks on a master push and its test matrices
+ # hourly, so a push-only scan drops the heaviest CI workload in the repo.
+ workflow_file = reporter.SCHEDULED_MASTER_WORKFLOWS[0]
+ opener = _FakeOpener(
+ {
+ "/actions/runs": {"workflow_runs": [{"id": 1, "updated_at": _iso(400)}]},
+ f"/workflows/{workflow_file}/runs": {"workflow_runs": [{"id": 2, "updated_at": _iso(500)}]},
+ }
+ )
+ fresh = reporter.scan_runs("PostHog/posthog", "t", RUN_START, opener=opener)
+ # Newest first across both scans, because that is the order --max-runs caps on.
+ assert [run["id"] for run in fresh] == [2, 1]
+ scheduled_url = next(url for url in opener.calls if workflow_file in url)
+ assert "branch=master" in scheduled_url
+ assert "event=schedule" in scheduled_url
+
class TestAttemptSelection:
def test_selected_attempt_uses_that_attempts_window(self) -> None:
diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.yml
index d9981d436ad3..6f1969b7c7e7 100644
--- a/.github/workflows/ci-alerts-devex.yml
+++ b/.github/workflows/ci-alerts-devex.yml
@@ -7,6 +7,11 @@ name: Master CI Alerts
# wall-clock arm only opens while master is being pushed (ACTIVITY_WINDOW_MINUTES),
# so a quiet weekend doesn't page.
#
+# A workflow is read as one lane per trigger event, each with its own streak and thresholds.
+# Backend CI has two: master push (the per-commit checks) and the hourly scheduled run (the test
+# matrices). Without the second lane a broken matrix never pages, because the push lane it shares
+# a workflow with stays green.
+#
# 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
@@ -15,7 +20,8 @@ name: Master CI Alerts
on:
# Reconcile ~a minute after master CI finishes; GitHub throttles the cron below to ~hourly under
# load. A reconcile reads all gating workflows anyway, so one hook on Backend CI (the long-pole on
- # ~every push) suffices. branches:[master] skips PR completions; cron stays a backstop.
+ # ~every push, and the workflow that runs the hourly master matrices) suffices.
+ # branches:[master] skips PR completions; cron stays a backstop.
workflow_run:
workflows: ['Backend CI']
types: [completed]
@@ -50,13 +56,30 @@ env:
# 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.
+ # A workflow whose master coverage moved to a cron belongs in SCHEDULED_GATING_WORKFLOWS below,
+ # and stays here only for whatever it still runs per commit.
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'
+ # Workflows that also cover master from a `schedule` trigger. Each gets a second lane, read and
+ # evaluated on its own, so a green master-push run can't mask a red scheduled run. Backend CI is
+ # split this way: master push runs only the per-commit checks (migrations, OpenAPI types, repo
+ # checks), and the test matrices run hourly.
+ SCHEDULED_GATING_WORKFLOWS: 'ci-backend.yml'
+ # A scheduled lane produces one run an hour, so it needs its own arms: the push streak of 5
+ # would take 5 hours to trip, while the push wall-clock arm of 60 minutes pages on a single
+ # flaky run held for one tick. Two red ticks in a row, or red across two ticks, is the honest
+ # sustained signal. Both arms are gated on recent master activity, because a cron keeps
+ # producing runs when nobody is pushing.
+ SCHEDULED_FAILURE_STREAK_THRESHOLD: '2'
+ SCHEDULED_FAILURE_MINUTES_THRESHOLD: '150'
jobs:
check-master:
- # only reconcile on push completions (branches:[master] already scopes the trigger to master)
+ # Only reconcile on the master run completions the alerter reads: pushes and the hourly
+ # scheduled matrices (branches:[master] already scopes the trigger to master).
if: >-
- github.event_name != 'workflow_run' || github.event.workflow_run.event == 'push'
+ github.event_name != 'workflow_run' ||
+ github.event.workflow_run.event == 'push' ||
+ github.event.workflow_run.event == 'schedule'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
diff --git a/.github/workflows/ci-master-run-traces.yml b/.github/workflows/ci-master-run-traces.yml
index 120e8f6caa46..5d98b198a844 100644
--- a/.github/workflows/ci-master-run-traces.yml
+++ b/.github/workflows/ci-master-run-traces.yml
@@ -1,9 +1,11 @@
name: Master run traces
-# Emits one OTLP trace per completed master-push workflow run: root span = the run,
+# Emits one OTLP trace per completed master workflow run: root span = the run,
# a span per job beneath it, a span per step beneath those. Covers every workflow,
# including the ones with no telemetry of their own (Container Images CD, the
-# container CD lane, the Rust image builds).
+# container CD lane, the Rust image builds). Master pushes are scanned repo-wide;
+# workflows that cover master from a cron are scanned on their scheduled runs too
+# (see SCHEDULED_MASTER_WORKFLOWS in the script).
#
# Complements .github/scripts/report_test_timings.py, which emits per-test traces
# from JUnit XML under its own trace IDs. Those stay separate traces.