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): run the hourly backend ci on depot (#111973)

Raúl Negrón-Otero27ea936d4219
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.md
index 09708cd89315..f111346c327c 100644
--- a/.agents/skills/authoring-ci-workflows/SKILL.md
+++ b/.agents/skills/authoring-ci-workflows/SKILL.md
@@ -468,7 +468,7 @@ Crons are offset so the runs do not all fire at once, and the offsets live here
| ----------------------------------- | ------ |
| `ci-frontend.yml` | 7 |
| `ci-nodejs.yml` | 13 |
-| `ci-backend.yml` | 23 |
+| `.depot/workflows/ci-backend.yml` | 23 |
| `ci-dagster.yml` | 33 |
| `ci-python.yml` | 43 |
| `ci-mcp.yml` | 53 |
@@ -488,7 +488,6 @@ group: ${{ github.workflow }}-${{ github.event_name == 'schedule' && 'scheduled'
```
That keeps hourly runs queueing behind each other rather than stacking, and leaves push behavior untouched.
-`ci-backend.yml` reaches the same place from the other side: its push arm is already keyed per SHA, so pushes never share a group with the cron.
Prefer the `'scheduled'` key when the push lane still runs real per-commit work, because a per-SHA push arm also gives up the deduplication that collapses a burst of master pushes into one run.
**The paths filter must be skipped on `schedule`, and every output it feeds must default to `true`.**
@@ -502,6 +501,10 @@ Any _step_ that reads a filter output needs the same `schedule` arm.
A lane that stops producing runs is invisible to the master-red alerter: it reads run completions, so a dropped cron reads as unreadable and drops out of evaluation rather than paging.
Add every converted workflow to `SCHEDULED_GATING_WORKFLOWS` in `ci-alerts-devex.yml` in the same change, or its failures stop paging altogether.
+Backend CI's hourly run is the one test suite whose cron is on Depot CI: `.depot/workflows/ci-backend.yml` has the `schedule` trigger and `.github/workflows/ci-backend.yml` has none.
+GitHub has no runs or artifacts for it, so its readers go through `.github/scripts/depot_scheduled_runs.py`: the alerter names it in `DEPOT_SCHEDULED_GATING_WORKFLOW`, and `ci-backend-update-test-timing.yml` finds and downloads its artifacts from Depot.
+The master run trace reporter reads the same Depot lane. Depot's public API exposes workflow and job timestamps, so those traces omit step and job-queue spans.
+
## Backwards-compat with unrebased PRs
A workflow edit hits every open PR the instant it merges (it runs against PR-merged-with-master), but companion changes — a new dependency, file, or config — only reach a branch when it rebases.
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 6d57f0cc6280..58a7ff6ac408 100644
--- a/.agents/skills/debugging-ci-failures/references/master-red-incident.md
+++ b/.agents/skills/debugging-ci-failures/references/master-red-incident.md
@@ -110,7 +110,10 @@ These identify the incident without proving it is still active; the first-step l
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 use Backend CI's `schedule` runs in the first-step lookup rather than its push runs.
+`Backend CI (scheduled)` means the hourly full test matrices, which run on Depot CI, so GitHub has no `schedule` runs for it and the `gh api` lookup above does not apply.
+Its run ID is a Depot run ID and its URL is on depot.dev.
+List that lane with `python3 .github/scripts/depot_scheduled_runs.py gate-runs`, which prints the newest hourly runs in the same shape, and read a failed run with `depot ci diagnose --run <run-id>`.
+Apply the same six-hour freshness bound to the first entry.
## Verdict gates
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 18f32229d74f..6a137263893a 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -42,14 +42,11 @@
# - Artifact uploads, run-scoped sharding plans, and the failing-test rollup
# require side effects, including duration writes. Depot stores these separately
# from GitHub Actions.
-# - Hourly scheduled master run: canonical no longer runs the test matrices on master push
-# (the merge queue's trunk-merge/** run gates every commit) and runs them from an hourly
-# `schedule` trigger instead — the shape this shadow always had (its `!= 'push'` gates on
-# turbo-discover / get_clickhouse_versions). A sampling trial must not run on a timer, so
-# the schedule trigger and canonical's per-commit-vs-scheduled splits (the `!= 'schedule'`
-# gates on check-migrations / check-openapi-types / repo-checks, report-test-timings' push
-# exclusion, the paths-filter schedule skip, and build_django_matrix's RUN_JSON_TARGETS
-# check of the EVENTS_JSON_SCHEDULE cron) are depot-exempt.
+# - Hourly scheduled master run: only this workflow has the `schedule` trigger, so the run
+# needs no hand-off and `wait-for-handoff` accepts it outright. Every `schedule` arm
+# here is depot-only: the paths-filter skip, the `!= 'schedule'` gates on the per-commit
+# checks, the events_json cron in build_django_matrix, the events schema recording and
+# its upload, and POSTHOG_PYTEST_HARD_EXIT.
# - mirror-schema-cache: canonical's master run copies the migrated schema dump out of the
# migrated-schema artifact into GitHub Actions Cache, so fork PRs (which run without
# secrets and cannot authenticate to Depot Cache) prime instead of migrating from scratch.
@@ -145,9 +142,19 @@ name: Backend CI on Depot
# `Hand off backend tests to Depot CI` check from .github/workflows/ci-backend.yml and
# `changes` (root of the needs graph) only runs when that check succeeded, so the whole
# workflow cascades off otherwise. A manual run needs that check on its commit too.
+# The hourly master run is the exception: only this workflow has a schedule trigger, so that
+# run starts here with no hand-off.
# The drift check (.github/workflows/ci-backend-shadow-drift.yml) keeps this file in sync
# with canonical; it runs whenever either file changes, independent of the percent.
on:
+ schedule:
+ # Hourly full-matrix run against the newest master state. The merge queue's
+ # trunk-merge/** run already gated every commit before it landed, so this is where
+ # master's matrix coverage, flaky-test baseline, and per-test timing data come from.
+ # GitHub Actions has no schedule trigger for Backend CI, so this run needs no hand-off.
+ # Keep the events_json cadence tied to the trigger, even when a job starts late.
+ - cron: '23 */3 * * *'
+ - cron: '23 1,2,4,5,7,8,10,11,13,14,16,17,19,20,22,23 * * *'
workflow_dispatch:
inputs:
clickhouseServerVersion:
@@ -202,6 +209,8 @@ env:
# The root conftest ends a green pytest session with os._exit once every report is written.
# That also hides a crash during interpreter teardown, so the hourly schedule exits normally.
POSTHOG_PYTEST_HARD_EXIT: ${{ github.event_name == 'schedule' && '0' || '1' }}
+ # Scheduled runs test master even when Depot does not populate github.ref.
+ IS_MASTER: ${{ github.event_name == 'schedule' || github.ref == 'refs/heads/master' }}
# Depot CI runners expose OTEL_SERVICE_NAME=ci-worker ambient; GitHub Actions test steps do not.
# Left set, it leaks into settings.OTEL_SERVICE_NAME (personhog metric client_name label) and
# diverges from test assertions. Blank it to match the GHA environment. Depot also injects
@@ -306,6 +315,10 @@ jobs:
if [ "$IS_FORK" = true ]; then
# The fork controls its own copy of the GitHub Actions workflow, so its hand-off is not trusted.
echo "::notice::Fork pull requests never run on Depot CI."
+ elif [ "$EVENT" = schedule ]; then
+ # Only this workflow has the hourly trigger, so no other engine can run it.
+ handed_off=true
+ echo "::notice::The hourly master run belongs to Depot CI."
elif [ "$EVENT" != pull_request ] && [ "$EVENT" != workflow_dispatch ] && [ "$EVENT" != api ]; then
# A reused commit can still carry a pull request's hand-off, and GitHub Actions
# runs every non-PR event itself.
@@ -443,12 +456,11 @@ jobs:
private-key: ${{ secrets.GH_APP_POSTHOG_PATHS_FILTER_PRIVATE_KEY }}
- uses: ./.depot/actions/paths-filter
id: filter
- # No `!= 'schedule'` arm, unlike canonical: this shadow has no `schedule`
- # trigger (depot-exempt, see the header), so there is no cron run whose
- # filter could narrow to a single commit. Canonical's reason for the extra
- # arm is "The hourly master lane" in
- # .agents/skills/authoring-ci-workflows/SKILL.md.
- if: github.event_name != 'push' # Run all tests on master push
+ # Skipped on master push and on the hourly schedule: every output then
+ # defaults to true. See "The hourly master lane" in
+ # .agents/skills/authoring-ci-workflows/SKILL.md for why a cron cannot
+ # diff, and what breaks if this guard is dropped.
+ if: github.event_name != 'push' && github.event_name != 'schedule'
with:
token: ${{ steps.app-token.outputs.token || github.token }}
list-files: 'escape'
@@ -1462,7 +1474,7 @@ jobs:
PYTEST_ADDOPTS: >-
--reuse-db
--durations-path ../../.test_durations
- ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && github.ref == 'refs/heads/master' && '--store-durations' || '' }}
+ ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && env.IS_MASTER == 'true' && '--store-durations' || '' }}
${{ needs.wait-for-handoff.outputs.handed_off == 'true' && '--junitxml=junit-product.xml' || '' }}
${{ needs.detect-snapshot-mode.outputs.mode == 'update' && '--snapshot-update --snapshot-warn-unused' || '' }}
${{ github.event_name == 'pull_request' && '--cov=backend --cov-report=' || '' }}
@@ -1573,7 +1585,7 @@ jobs:
# timings either. Its artifact would hold only the restored map, and the timing
# refresh then rejects the whole Products slice because the timing and JUnit shard
# sets differ.
- if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (github.ref == 'refs/heads/master' && !matrix.new-events-schema && hashFiles('junit-staging/junit-product-*.xml') != '') }}
+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (env.IS_MASTER == 'true' && !matrix.new-events-schema && hashFiles('junit-staging/junit-product-*.xml') != '') }}
with:
name: timing_data-Products-${{ strategy.job-index }}
path: .test_durations
@@ -1651,7 +1663,7 @@ jobs:
# bots rewrite manifests across majors, so this is the block. Stdlib only, no venv.
sdk-major-guard:
needs: [changes]
- if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'push'
+ if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'push' && github.event_name != 'schedule'
timeout-minutes: 5
permissions: {}
name: SDK major-version guard (depot-ubuntu-24.04)
@@ -1664,7 +1676,7 @@ jobs:
repo-checks:
needs: [changes]
# product_yamls: ownership-only PRs still need the owners.yaml lint below.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'push'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'push' && github.event_name != 'schedule'
timeout-minutes: 10
outputs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
@@ -1865,7 +1877,7 @@ jobs:
# products/db_routing.yaml is neither Python nor under a backend/ directory, and
# a migration in a future top-level app matches none of them. Without it the
# replay gate could be on while the job that runs it never starts.
- if: needs.changes.outputs.backend == 'true' || needs.changes.outputs.migrations == 'true' || needs.changes.outputs.migration_replay == 'true'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.migrations == 'true' || needs.changes.outputs.migration_replay == 'true') && github.event_name != 'schedule'
# On master this job replays the full migration history from scratch to
# produce the schema dump every PR job restores, and a merge queue batch that
# changes a Django migration replays it a second time onto an empty database.
@@ -1917,7 +1929,7 @@ jobs:
version: '0.12.13'
enable-cache: true
cache-dependency-glob: uv.lock
- save-cache: ${{ github.ref == 'refs/heads/master' }}
+ save-cache: ${{ env.IS_MASTER == 'true' }}
- name: Install SAML (python3-saml) dependencies
if: steps.setup-uv.outputs.cache-hit != 'true'
run: |
@@ -2576,7 +2588,7 @@ jobs:
check-openapi-types:
needs: [changes]
# Not on master push: master only primes the schema cache.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && github.event_name != 'push'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && github.event_name != 'push' && github.event_name != 'schedule'
timeout-minutes: 20
outputs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
@@ -2624,7 +2636,7 @@ jobs:
version: '0.12.13'
enable-cache: true
cache-dependency-glob: uv.lock
- save-cache: ${{ github.ref == 'refs/heads/master' }}
+ save-cache: ${{ env.IS_MASTER == 'true' }}
- name: Install SAML (python3-saml) dependencies
if: steps.setup-uv.outputs.cache-hit != 'true'
run: |
@@ -2833,6 +2845,7 @@ jobs:
# that takes the whole list.
JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files }}
JSON_TARGETS_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_shards }}
+ RUN_JSON_TARGETS: ${{ github.event_name != 'schedule' || github.event.schedule == '23 */3 * * *' }}
# Same rule as the django job's condition: the suite runs for a legacy
# edit, for a product change that reaches legacy code, and when discovery
# failed, which leaves run_legacy empty. Without it only the events_json
@@ -3144,6 +3157,11 @@ jobs:
json_targets_count="${JSON_TARGETS_SHARDS:-0}"
fi
+ if [[ "$RUN_JSON_TARGETS" != "true" ]]; then
+ echo "Skipping the events_json rows on this hourly run"
+ json_targets_count=0
+ fi
+
# The events_json rows: Core jobs over the listed paths with the
# native-JSON events table. They keep Core's person-on-events default.
json_targets=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$json_targets_count" '
@@ -3296,7 +3314,7 @@ jobs:
toolchain: 1.91.1
components: cargo
- name: Save Python tool cache
- if: github.ref == 'refs/heads/master' && steps.python-toolcache.outputs.cache-hit != 'true'
+ if: env.IS_MASTER == 'true' && steps.python-toolcache.outputs.cache-hit != 'true'
uses: actions/cache/save@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
with:
path: ${{ runner.tool_cache }}/Python/${{ matrix.python-version }}
@@ -3309,7 +3327,7 @@ jobs:
version: '0.12.13'
enable-cache: true
cache-dependency-glob: uv.lock
- save-cache: ${{ github.ref == 'refs/heads/master' }}
+ save-cache: ${{ env.IS_MASTER == 'true' }}
- name: Install SAML (python3-saml) dependencies
if: ${{ needs.changes.outputs.backend == 'true' && steps.setup-uv-tests.outputs.cache-hit != 'true' }}
shell: bash
@@ -3890,7 +3908,7 @@ jobs:
# cache miss must never red a green run.
continue-on-error: true
if: |
- github.ref == 'refs/heads/master' &&
+ env.IS_MASTER == 'true' &&
matrix.segment == 'Core' &&
matrix.group == 1 &&
!matrix.person-on-events &&
@@ -3952,7 +3970,7 @@ jobs:
- name: Upload updated timing data as artifacts
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
# Upload on master, or on PRs that change timing/sharding scripts (for validation)
- if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && ((github.ref == 'refs/heads/master' || needs.changes.outputs.timing_scripts == 'true') && needs.changes.outputs.backend == 'true' && !matrix.person-on-events && !matrix.new-events-schema && matrix.clickhouse-server-image == needs.get_clickhouse_versions.outputs.oldest_supported_image) }}
+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && ((env.IS_MASTER == 'true' || needs.changes.outputs.timing_scripts == 'true') && needs.changes.outputs.backend == 'true' && !matrix.person-on-events && !matrix.new-events-schema && matrix.clickhouse-server-image == needs.get_clickhouse_versions.outputs.oldest_supported_image) }}
with:
name: timing_data-${{ matrix.segment }}-${{ matrix.group }}
path: .test_durations
@@ -4624,6 +4642,7 @@ jobs:
github.repository == 'PostHog/posthog' &&
(needs.django.result != 'skipped' || needs.turbo-tests.result != 'skipped') &&
(
+ github.event_name == 'schedule' ||
(github.event_name != 'pull_request' && github.event_name != 'push' && github.ref == 'refs/heads/master') ||
(github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name == 'PostHog/posthog')
diff --git a/.github/scripts/ci-alerts-devex.js b/.github/scripts/ci-alerts-devex.js
index 5ae10f7d72da..e23b3fe78660 100644
--- a/.github/scripts/ci-alerts-devex.js
+++ b/.github/scripts/ci-alerts-devex.js
@@ -35,6 +35,8 @@
// GitHub API rate-limit observability is handled by the separate
// monitor-github-rate-limit workflow, which emits to PostHog as time series.
+const fs = require('node:fs')
+
const SLACK_API = 'https://slack.com/api'
const INCIDENT_EVENT_TYPE = 'master_ci_incident'
// Per-workflow links point at the engineering analytics workflow-detail page (not GitHub), scoped
@@ -96,9 +98,41 @@ function buildLanes(env) {
// active hours.
countNeedsActivity: false,
}))
- for (const workflowFile of list(env.SCHEDULED_GATING_WORKFLOWS)) {
+ const scheduled = list(env.SCHEDULED_GATING_WORKFLOWS).map((workflowFile) => ({ workflowFile }))
+ // The workflow whose cron runs on Depot CI has no GitHub runs to list. Its lane reads the file
+ // that .github/scripts/depot_scheduled_runs.py wrote, which holds the runs in GitHub's shape.
+ // A missing or unparseable file throws, so the lane reads as unreadable, never green.
+ if (env.DEPOT_SCHEDULED_GATING_WORKFLOW) {
+ scheduled.push({
+ workflowFile: env.DEPOT_SCHEDULED_GATING_WORKFLOW,
+ listRuns: (page) => {
+ if (page !== 1) {
+ return []
+ }
+ const runs = JSON.parse(fs.readFileSync(env.DEPOT_SCHEDULED_RUNS_FILE, 'utf8'))
+ if (
+ !Array.isArray(runs) ||
+ runs.length === 0 ||
+ runs.some(
+ (run) =>
+ !run ||
+ !['completed', 'in_progress'].includes(run.status) ||
+ !Number.isFinite(Date.parse(run.created_at)) ||
+ (run.status === 'completed' &&
+ !['success', 'failure', 'cancelled'].includes(run.conclusion))
+ )
+ ) {
+ throw new Error('Depot scheduled runs file contains invalid run data')
+ }
+ return runs
+ },
+ // GitHub has no run history for this lane, so the alert links its failing run.
+ linkFailingRun: true,
+ })
+ }
+ for (const source of scheduled) {
lanes.push({
- workflowFile,
+ ...source,
event: 'schedule',
label: SCHEDULED_LANE_LABEL,
maxLagMinutes: SCHEDULED_RUN_INDEX_MAX_LAG_MINUTES,
@@ -141,11 +175,19 @@ async function fetchWorkflowRuns(
repo,
workflowFile,
perPage,
- { event = 'push', maxLagMinutes = RUN_INDEX_MAX_LAG_MINUTES, freshAsOf = null, sleep = defaultSleep } = {}
+ { event = 'push', maxLagMinutes = RUN_INDEX_MAX_LAG_MINUTES, freshAsOf = null, sleep = defaultSleep, listRuns } = {}
) {
+ // One raw page of the lane's runs, newest first. A lane brings its own source when its runs
+ // are not GitHub workflow runs.
+ const listPage =
+ listRuns ||
+ ((page) =>
+ github.rest.actions
+ .listWorkflowRuns({ owner, repo, workflow_id: workflowFile, branch: 'master', event, per_page: perPage, page })
+ .then(({ data }) => data.workflow_runs))
for (let attempt = 0; ; attempt++) {
try {
- return await fetchSettledRuns(github, owner, repo, workflowFile, perPage, { event, maxLagMinutes, freshAsOf })
+ return await fetchSettledRuns(listPage, workflowFile, perPage, { event, maxLagMinutes, freshAsOf })
} catch (err) {
if (!err.staleIndex || attempt >= STALE_PAGE_RETRIES) {throw err}
await sleep(STALE_PAGE_RETRY_DELAY_MS)
@@ -153,23 +195,15 @@ async function fetchWorkflowRuns(
}
}
-async function fetchSettledRuns(github, owner, repo, workflowFile, perPage, { event, maxLagMinutes, freshAsOf }) {
+async function fetchSettledRuns(listPage, workflowFile, perPage, { event, maxLagMinutes, freshAsOf }) {
const MAX_PAGES = 5
const settled = []
for (let page = 1; page <= MAX_PAGES; page++) {
- const { data } = await github.rest.actions.listWorkflowRuns({
- owner,
- repo,
- workflow_id: workflowFile,
- branch: 'master',
- event,
- per_page: perPage,
- page,
- })
+ const runs = await listPage(page)
// Freshness is judged on the raw page-1 head (any status) before paging deeper; an empty
// page is the same anomaly — every lane has master run history.
if (page === 1 && freshAsOf) {
- const head = data.workflow_runs[0]
+ const head = 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
@@ -182,7 +216,7 @@ async function fetchSettledRuns(github, owner, repo, workflowFile, perPage, { ev
throw err
}
}
- for (const run of data.workflow_runs) {
+ for (const run of 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.
if (run.status !== 'completed') {continue}
@@ -201,7 +235,7 @@ async function fetchSettledRuns(github, owner, repo, workflowFile, perPage, { ev
// Once a kept run is a non-failure it terminates the leading streak, so we have all we need.
// A short raw page means there are no older runs to fetch.
const streakBounded = settled.some((r) => !isFailure(r))
- if (streakBounded || data.workflow_runs.length < perPage) {break}
+ if (streakBounded || runs.length < perPage) {break}
}
return settled
}
@@ -541,6 +575,7 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
maxLagMinutes: lane.maxLagMinutes,
freshAsOf,
sleep,
+ listRuns: lane.listRuns,
}).catch((err) => {
core.warning(`No usable ${lane.event} runs for ${lane.workflowFile}: ${err.message}`)
return null
@@ -564,7 +599,7 @@ module.exports = async ({ context, github, core }, { now: _now, slack: _slack, f
const redForMins = Math.round((now.getTime() - new Date(f.since).getTime()) / 60000)
return {
...f,
- runsUrl: runsUrlFor(owner, repo, f.workflowName),
+ runsUrl: f.lane.linkFailingRun ? f.run_url : 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 >= f.lane.streakThreshold,
diff --git a/.github/scripts/ci-alerts-devex.test.js b/.github/scripts/ci-alerts-devex.test.js
index 47bc7a154bba..badb6eee3cb4 100644
--- a/.github/scripts/ci-alerts-devex.test.js
+++ b/.github/scripts/ci-alerts-devex.test.js
@@ -6,6 +6,9 @@
const { describe, it } = require('node:test')
const assert = require('node:assert/strict')
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
const ciAlertsDevex = require('./ci-alerts-devex')
@@ -840,6 +843,45 @@ describe('ci-alerts-devex', () => {
})
}
+ // (contents of the Depot runs file, or null for no file) → action.
+ for (const [scenario, depotRuns, expected] of [
+ ['pages on a red streak', runs('Backend CI', ['failure', 'failure']), { action: 'create', blocking: '1' }],
+ ['stays quiet when green', runs('Backend CI', ['success', 'failure']), { action: 'none', blocking: '0' }],
+ ['holds an open incident when the file is missing', null, { action: 'hold', blocking: '0' }],
+ ['holds an open incident for a non-array payload', 'invalid', { action: 'hold', blocking: '0' }],
+ ['holds an open incident for an empty payload', [], { action: 'hold', blocking: '0' }],
+ [
+ 'holds an open incident for missing run timestamps',
+ [{ status: 'completed', conclusion: 'success' }],
+ { action: 'hold', blocking: '0' },
+ ],
+ ['holds an open incident for null run entries', [null], { action: 'hold', blocking: '0' }],
+ ]) {
+ it(`scheduled lane read from Depot CI: ${scenario}`, async (t) => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'depot-runs-'))
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }))
+ const runsFile = path.join(dir, 'runs.json')
+ if (depotRuns) {
+ fs.writeFileSync(runsFile, JSON.stringify(depotRuns))
+ }
+ const github = laneGithub(
+ { 'ci-backend.yml:push': runs('Backend CI', ['success']) },
+ pushAt(minutes(-3).toISOString())
+ )
+ const { slack, outputs } = await run(github, {
+ env: {
+ GATING_WORKFLOWS: 'ci-backend.yml',
+ DEPOT_SCHEDULED_GATING_WORKFLOW: 'ci-backend.yml',
+ DEPOT_SCHEDULED_RUNS_FILE: runsFile,
+ },
+ history: expected.action === 'hold' ? [activeAnchor({ workflows: ['Backend CI (scheduled)'] })] : [],
+ })
+ assert.equal(outputs.action, expected.action)
+ assert.equal(outputs.blocking_count, expected.blocking)
+ assert.equal(slack.update.calls.length, 0)
+ })
+ }
+
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.
diff --git a/.github/scripts/depot_scheduled_runs.py b/.github/scripts/depot_scheduled_runs.py
new file mode 100644
index 000000000000..f10476c9cf54
--- /dev/null
+++ b/.github/scripts/depot_scheduled_runs.py
@@ -0,0 +1,240 @@
+#!/usr/bin/env python3
+"""Read the hourly Backend CI runs on Depot CI: their verdicts and their artifacts.
+
+The hourly master run of Backend CI lives on Depot CI, which keeps its runs and artifacts
+apart from GitHub Actions. This is the Depot counterpart of listing workflow runs with
+`gh api` and fetching artifacts with `gh run download`.
+
+ depot_scheduled_runs.py find --prefix timing_data- --min-artifacts 38 --limit 5
+ depot_scheduled_runs.py download <run-id> --pattern 'timing_data-Core-*' --dir timing
+ depot_scheduled_runs.py gate-runs
+
+`find` prints one `<run-id> <sha>` line per successful run, newest first. `download` unpacks
+each matching artifact into `<dir>/<artifact name>/`, the layout `gh run download` produces.
+`gate-runs` prints the newest runs as JSON, each with the conclusion of its gate job, in the
+shape .github/scripts/ci-alerts-devex.js reads GitHub workflow runs in.
+Needs the `depot` CLI and DEPOT_TOKEN.
+"""
+
+from __future__ import annotations
+
+import sys
+import json
+import time
+import fnmatch
+import zipfile
+import argparse
+import tempfile
+import subprocess
+from concurrent.futures import ThreadPoolExecutor
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import TypedDict, cast
+
+REPO = "PostHog/posthog"
+# Both match .github/scripts/ci_backend_relay.py, which reads the same workflow for pull requests.
+WORKFLOW_NAME = "Backend CI on Depot"
+GATE_JOB_KEY = "ci-backend.yml:django_tests"
+GATE_CONCLUSIONS = {"finished": "success", "failed": "failure", "cancelled": "cancelled"}
+ENDED = frozenset(GATE_CONCLUSIONS)
+# Short enough that the alerter's read of GATE_RUNS_LISTED runs ends inside its step timeout.
+CLI_TIMEOUT_SECONDS = 10
+DOWNLOAD_TIMEOUT_SECONDS = 120
+PARALLEL_CLI_CALLS = 8
+# The Depot CLI returns at most 200 workflows, which is 8 days of hourly runs.
+MAX_LISTED = 200
+# The alerter resolves an incident when no listed run is a settled failure, so the window has
+# to outlast a stretch of hung or cancelled runs.
+GATE_RUNS_LISTED = 12
+
+
+class ListedWorkflow(TypedDict):
+ workflow_id: str
+ run_id: str
+ sha: str
+ status: str
+ created_at: str
+
+
+class Artifact(TypedDict):
+ artifact_id: str
+ name: str
+ created_at: str
+
+
+class Job(TypedDict, total=False):
+ job_key: str
+ status: str
+ finished_at: str
+
+
+class ShownWorkflow(TypedDict):
+ org_id: str
+ jobs: list[Job]
+
+
+class GateRun(TypedDict):
+ id: str
+ name: str
+ status: str
+ conclusion: str | None
+ head_sha: str
+ html_url: str
+ created_at: str
+ updated_at: str
+
+
+def depot(*args: str, timeout: int = CLI_TIMEOUT_SECONDS) -> str:
+ # stderr passes through, so a failed call explains itself in the job log.
+ result = subprocess.run(["depot", "ci", *args], check=True, stdout=subprocess.PIPE, text=True, timeout=timeout)
+ return result.stdout
+
+
+def scheduled_workflows(statuses: list[str], limit: int, *, repo: str = REPO) -> list[ListedWorkflow]:
+ """The hourly Backend CI workflows in the given states, newest first."""
+ args = ["workflow", "list", "--repo", repo, "--name", WORKFLOW_NAME, "--trigger", "schedule", "-n", str(limit)]
+ for status in statuses:
+ args += ["--status", status]
+ # The CLI prints `null` when nothing matches.
+ try:
+ output = depot(*args, "--output", "json")
+ except subprocess.TimeoutExpired:
+ output = depot(*args, "--output", "json")
+ workflows = cast(list[ListedWorkflow], json.loads(output or "null") or [])
+ return sorted(workflows, key=lambda w: w["created_at"], reverse=True)
+
+
+def artifacts(run_id: str) -> list[Artifact]:
+ listed = json.loads(depot("artifacts", "list", run_id, "--output", "json") or "null") or {}
+ return cast(list[Artifact], listed.get("artifacts") or [])
+
+
+def newest_per_name(run_artifacts: list[Artifact]) -> list[Artifact]:
+ """A retried job uploads its artifact again under the same name. Keep the newest."""
+ newest: dict[str, Artifact] = {}
+ for artifact in sorted(run_artifacts, key=lambda a: a["created_at"]):
+ newest[artifact["name"]] = artifact
+ return list(newest.values())
+
+
+def find(prefix: str, min_artifacts: int, limit: int, max_age_days: int) -> list[ListedWorkflow]:
+ cutoff = (datetime.now(UTC) - timedelta(days=max_age_days)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ found: list[ListedWorkflow] = []
+ for workflow in scheduled_workflows(["finished"], MAX_LISTED):
+ if workflow["created_at"] < cutoff:
+ break
+ try:
+ names = {a["name"] for a in artifacts(workflow["run_id"]) if a["name"].startswith(prefix)}
+ except (subprocess.SubprocessError, json.JSONDecodeError) as error:
+ sys.stderr.write(f"Run {workflow['run_id']}: could not list artifacts, skipping it: {error!r}\n")
+ continue
+ sys.stderr.write(f"Run {workflow['run_id']} has {len(names)} {prefix}* artifacts\n")
+ if len(names) >= min_artifacts:
+ found.append(workflow)
+ if len(found) >= limit:
+ break
+ return found
+
+
+def download(run_id: str, patterns: list[str], directory: Path) -> int:
+ matching = [
+ a for a in newest_per_name(artifacts(run_id)) if any(fnmatch.fnmatchcase(a["name"], p) for p in patterns)
+ ]
+ with tempfile.TemporaryDirectory() as scratch:
+
+ def fetch(artifact: Artifact) -> None:
+ archive = Path(scratch) / f"{artifact['artifact_id']}.zip"
+ for attempt in range(3):
+ try:
+ depot(
+ "artifacts",
+ "download",
+ artifact["artifact_id"],
+ "--output-file",
+ str(archive),
+ timeout=DOWNLOAD_TIMEOUT_SECONDS,
+ )
+ break
+ except subprocess.SubprocessError:
+ # The CLI refuses to overwrite a file left by a partial download.
+ archive.unlink(missing_ok=True)
+ if attempt == 2:
+ raise
+ sys.stderr.write(f"Artifact {artifact['name']}: download failed, retrying\n")
+ time.sleep(2**attempt)
+ target = directory / artifact["name"]
+ target.mkdir(parents=True, exist_ok=True)
+ with zipfile.ZipFile(archive) as bundle:
+ bundle.extractall(target)
+
+ # One CLI call per artifact, and an hourly refresh downloads several hundred.
+ with ThreadPoolExecutor(max_workers=PARALLEL_CLI_CALLS) as pool:
+ list(pool.map(fetch, matching))
+ return len(matching)
+
+
+def gate_run(listed: ListedWorkflow) -> GateRun:
+ """One workflow as a GitHub-shaped run. A workflow whose gate job has not ended is not completed."""
+ shown = cast(ShownWorkflow, json.loads(depot("workflow", "show", listed["workflow_id"], "--output", "json")))
+ gate = next((job for job in shown.get("jobs") or [] if job.get("job_key") == GATE_JOB_KEY), None)
+ conclusion: str | None = None
+ if gate and gate.get("status") in GATE_CONCLUSIONS:
+ conclusion = GATE_CONCLUSIONS[gate["status"]]
+ elif listed["status"] in ENDED:
+ # An hourly run that ended without a gate verdict ran no tests. The alerter drops
+ # skipped runs, so reporting one as skipped would hide a lane that tests nothing.
+ conclusion = "cancelled" if listed["status"] == "cancelled" else "failure"
+ return {
+ "id": listed["run_id"],
+ "name": "Backend CI",
+ "status": "completed" if conclusion else "in_progress",
+ "conclusion": conclusion,
+ "head_sha": listed["sha"],
+ "html_url": f"https://depot.dev/orgs/{shown['org_id']}/workflows/{listed['workflow_id']}",
+ "created_at": listed["created_at"],
+ "updated_at": (gate or {}).get("finished_at") or listed["created_at"],
+ }
+
+
+def gate_runs() -> list[GateRun]:
+ listed = scheduled_workflows(["queued", "running", *sorted(ENDED)], GATE_RUNS_LISTED)
+ with ThreadPoolExecutor(max_workers=PARALLEL_CLI_CALLS) as pool:
+ runs = list(pool.map(gate_run, listed))
+ # An empty or inconclusive window must not resolve an existing CI incident.
+ if not any(
+ run["status"] == "completed" and run["conclusion"] not in (None, "cancelled", "skipped") for run in runs
+ ):
+ raise ValueError("No settled Backend CI verdict in the scheduled run window")
+ return runs
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ commands = parser.add_subparsers(dest="command", required=True)
+ find_parser = commands.add_parser("find")
+ find_parser.add_argument("--prefix", required=True)
+ find_parser.add_argument("--min-artifacts", type=int, default=1)
+ find_parser.add_argument("--limit", type=int, default=1)
+ find_parser.add_argument("--max-age-days", type=int, default=14)
+ download_parser = commands.add_parser("download")
+ download_parser.add_argument("run_id")
+ download_parser.add_argument("--pattern", action="append", required=True)
+ download_parser.add_argument("--dir", type=Path, required=True)
+ commands.add_parser("gate-runs")
+ args = parser.parse_args()
+
+ if args.command == "find":
+ for workflow in find(args.prefix, args.min_artifacts, args.limit, args.max_age_days):
+ sys.stdout.write(f"{workflow['run_id']} {workflow['sha']}\n")
+ return 0
+ if args.command == "gate-runs":
+ json.dump(gate_runs(), sys.stdout)
+ return 0
+ count = download(args.run_id, args.pattern, args.dir)
+ sys.stderr.write(f"Downloaded {count} artifacts matching {args.pattern} from run {args.run_id}\n")
+ # `gh run download` fails when nothing matches, and the callers rely on that.
+ return 0 if count else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/.github/scripts/report_workflow_run_traces.py b/.github/scripts/report_workflow_run_traces.py
index 53ff34131877..79f5da04fc74 100644
--- a/.github/scripts/report_workflow_run_traces.py
+++ b/.github/scripts/report_workflow_run_traces.py
@@ -6,6 +6,8 @@
# "opentelemetry-sdk~=1.27",
# "opentelemetry-exporter-otlp-proto-http~=1.27",
# ]
+# [tool.ty.environment]
+# root = ["."]
# ///
"""Emit OTLP traces for completed master workflow runs.
@@ -53,10 +55,11 @@ import urllib.error
import urllib.parse
import urllib.request
from collections.abc import Iterator, Mapping, Sequence
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import Any, TypedDict, cast
+import depot_scheduled_runs
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
@@ -75,12 +78,6 @@ 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
@@ -129,7 +126,7 @@ class Step:
@dataclass(frozen=True)
class Job:
- id: int
+ id: int | str
name: str
status: str
conclusion: str
@@ -153,11 +150,11 @@ class Job:
@dataclass(frozen=True)
class WorkflowRun:
- id: int
+ id: int | str
attempt: int
name: str
path: str
- workflow_id: int
+ workflow_id: int | str
run_number: int
event: str
status: str
@@ -174,6 +171,7 @@ class WorkflowRun:
end: datetime
jobs: tuple[Job, ...] = ()
dropped_jobs: int = 0
+ provider: str = "github"
@property
def duration_seconds(self) -> float:
@@ -286,11 +284,7 @@ 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 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.
+ GitHub supplies master pushes; scheduled Backend CI runs are read from Depot separately.
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.
@@ -309,10 +303,6 @@ def scan_runs(repo: str, token: str, since: datetime, *, opener: Any = None) ->
)
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 path in paths:
for run in _paginate(path, token, "workflow_runs", opener=opener):
@@ -352,6 +342,49 @@ def fetch_run(repo: str, run_id: int, token: str, *, attempt: int = 0, opener: A
# ---------- Parsing ----------
+def resource_id(value: object) -> int | str:
+ if not isinstance(value, (int, str)):
+ raise ValueError(f"Invalid CI resource identifier: {value!r}")
+ return value
+
+
+class DepotWorkflow(TypedDict):
+ workflow_id: str
+ workflow_path: str
+ status: str
+ created_at: str
+ started_at: str
+ finished_at: str
+
+
+class DepotRun(TypedDict):
+ run_id: str
+ repo: str
+ sha: str
+ trigger: str
+
+
+class DepotJob(TypedDict, total=False):
+ job_id: str
+ job_key: str
+ job_display_name: str
+ status: str
+ started_at: str
+ finished_at: str
+
+
+class DepotExecution(TypedDict):
+ execution: int
+
+
+class DepotShownWorkflow(TypedDict):
+ org_id: str
+ run: DepotRun
+ workflow: DepotWorkflow
+ jobs: list[DepotJob]
+ executions: list[DepotExecution]
+
+
def parse_iso_utc(value: str) -> datetime | None:
"""Parse an ISO 8601 timestamp; treat a naive one as UTC."""
if not value:
@@ -424,7 +457,7 @@ def parse_job(raw: Mapping[str, Any]) -> Job | None:
steps = [step for step in (parse_step(s, (start, end)) for s in raw.get("steps") or []) if step is not None]
steps.sort(key=lambda step: step.number)
return Job(
- id=int(raw.get("id") or 0),
+ id=resource_id(raw.get("id") or 0),
name=str(raw.get("name") or ""),
status=str(raw.get("status") or ""),
conclusion=str(raw.get("conclusion") or ""),
@@ -462,11 +495,11 @@ def parse_run(raw: Mapping[str, Any], raw_jobs: list[dict]) -> WorkflowRun | Non
end = max((job.end for job in jobs), default=None) or parse_iso_utc(raw.get("updated_at") or "") or start
start, end = clamp(start, end)
return WorkflowRun(
- id=int(raw.get("id") or 0),
+ id=resource_id(raw.get("id") or 0),
attempt=int(raw.get("run_attempt") or 1),
name=str(raw.get("name") or ""),
path=str(raw.get("path") or ""),
- workflow_id=int(raw.get("workflow_id") or 0),
+ workflow_id=resource_id(raw.get("workflow_id") or 0),
run_number=int(raw.get("run_number") or 0),
event=str(raw.get("event") or ""),
status=str(raw.get("status") or ""),
@@ -486,10 +519,85 @@ def parse_run(raw: Mapping[str, Any], raw_jobs: list[dict]) -> WorkflowRun | Non
)
+def parse_depot_run(shown: DepotShownWorkflow) -> WorkflowRun | None:
+ context, workflow = shown["run"], shown["workflow"]
+ url = f"https://depot.dev/orgs/{shown['org_id']}/workflows/{workflow['workflow_id']}"
+ jobs = [
+ {
+ "id": job["job_id"],
+ "name": job.get("job_display_name") or job["job_key"],
+ "status": "completed",
+ "conclusion": depot_scheduled_runs.GATE_CONCLUSIONS.get(job["status"], job["status"]),
+ "html_url": f"{url}?job={job['job_id']}",
+ "created_at": job.get("started_at"),
+ "started_at": job.get("started_at"),
+ "completed_at": job.get("finished_at"),
+ "runner_name": "depot-ci",
+ }
+ for job in shown["jobs"]
+ if not job["job_key"].endswith(":_dynamicMatrix")
+ ]
+ run = parse_run(
+ {
+ "id": f"depot:{context['run_id']}",
+ "run_attempt": max((execution["execution"] for execution in shown["executions"]), default=1),
+ "name": "Backend CI",
+ "path": f".depot/workflows/{workflow['workflow_path'].removeprefix('.depot/workflows/')}",
+ "workflow_id": workflow["workflow_id"],
+ "event": context["trigger"],
+ "status": "completed",
+ "conclusion": depot_scheduled_runs.GATE_CONCLUSIONS[workflow["status"]],
+ "head_sha": context["sha"],
+ "head_branch": "master",
+ "repository": {"full_name": context["repo"]},
+ "html_url": url,
+ "created_at": workflow["created_at"],
+ "run_started_at": workflow["started_at"],
+ "updated_at": workflow["finished_at"],
+ },
+ jobs,
+ )
+ if run is None:
+ return None
+ finished = parse_iso_utc(workflow["finished_at"])
+ if finished is None:
+ raise ValueError("Completed Depot workflow has no finish timestamp")
+ return replace(run, provider="depot", end=max(run.end, finished))
+
+
+def collect_depot_runs(repo: str, since: datetime) -> Collection:
+ runs: list[WorkflowRun] = []
+ complete = True
+ created_floor = since - timedelta(days=1)
+ listed = depot_scheduled_runs.scheduled_workflows(sorted(depot_scheduled_runs.ENDED), 200, repo=repo)
+ for workflow in listed:
+ created = parse_iso_utc(workflow["created_at"])
+ if created is not None and created < created_floor:
+ break
+ try:
+ shown = cast(
+ DepotShownWorkflow,
+ json.loads(depot_scheduled_runs.depot("workflow", "show", workflow["workflow_id"], "--output", "json")),
+ )
+ finished = parse_iso_utc(shown["workflow"]["finished_at"])
+ if finished is None:
+ raise ValueError("Completed Depot workflow has no finish timestamp")
+ if finished < since:
+ continue
+ run = parse_depot_run(shown)
+ if run is None:
+ raise ValueError("Completed Depot workflow has no start timestamp")
+ runs.append(run)
+ except Exception:
+ logger.exception("could not read Depot workflow %s", workflow["workflow_id"])
+ complete = False
+ return Collection(runs=tuple(runs), complete=complete)
+
+
# ---------- OTLP export ----------
-def deterministic_trace_id(run_id: int, run_attempt: int) -> int:
+def deterministic_trace_id(run_id: int | str, run_attempt: int) -> int:
"""One trace per run attempt. Distinct from report_test_timings.py's per-shard keys."""
digest = hashlib.sha256(f"{run_id}:{run_attempt}:workflow-run".encode()).digest()
return int.from_bytes(digest[:16], "big") # OTLP trace IDs are 128-bit.
@@ -532,6 +640,7 @@ def run_resource_attributes(run: WorkflowRun) -> dict[str, str | int]:
"""
attrs: dict[str, str | int] = {
"service.name": SERVICE_NAME,
+ "ci.provider": run.provider,
"ci.workflow": run.name,
"ci.workflow_path": run.path,
"ci.workflow_id": run.workflow_id,
@@ -783,6 +892,14 @@ def collect_runs(args: argparse.Namespace, token: str, now: datetime) -> Collect
run = parse_run(raw, raw_jobs)
if run is not None:
runs.append(run)
+ if not args.run_id:
+ try:
+ depot_runs = collect_depot_runs(args.repo, since)
+ runs.extend(depot_runs.runs)
+ complete = complete and depot_runs.complete
+ except Exception:
+ logger.exception("could not collect scheduled Depot runs")
+ complete = False
return Collection(runs=tuple(runs), complete=complete)
diff --git a/.github/scripts/test_depot_scheduled_runs.py b/.github/scripts/test_depot_scheduled_runs.py
new file mode 100644
index 000000000000..594e0b02d4b4
--- /dev/null
+++ b/.github/scripts/test_depot_scheduled_runs.py
@@ -0,0 +1,162 @@
+import json
+import zipfile
+import subprocess
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import ci_backend_relay
+import depot_scheduled_runs as script
+
+
+ "workflow_status,gate_status,expected",
+ [
+ pytest.param("finished", "finished", ("completed", "success"), id="green"),
+ pytest.param("failed", "failed", ("completed", "failure"), id="gate_failed"),
+ pytest.param("failed", "finished", ("completed", "success"), id="non_gating_job_failed"),
+ pytest.param("running", "finished", ("completed", "success"), id="gate_done_tail_jobs_running"),
+ pytest.param("running", "queued", ("in_progress", None), id="still_running"),
+ pytest.param("failed", None, ("completed", "failure"), id="failed_before_the_gate"),
+ pytest.param("failed", "skipped", ("completed", "failure"), id="gate_skipped_after_a_failure"),
+ pytest.param("finished", "skipped", ("completed", "failure"), id="ran_no_tests"),
+ pytest.param("cancelled", "cancelled", ("completed", "cancelled"), id="cancelled"),
+ ],
+)
+def test_gate_run_reports_the_gate_verdict(
+ monkeypatch: pytest.MonkeyPatch, workflow_status: str, gate_status: str | None, expected: tuple[str, str | None]
+) -> None:
+ jobs: list[dict[str, Any]] = [{"job_key": "ci-backend.yml:report-test-timings", "status": "failed"}]
+ if gate_status:
+ jobs.append({"job_key": script.GATE_JOB_KEY, "status": gate_status, "finished_at": "2026-10-05T13:00:00Z"})
+ shown = {"org_id": "org", "jobs": jobs}
+ monkeypatch.setattr(script, "depot", lambda *args: json.dumps(shown))
+ listed = {
+ "workflow_id": "wf",
+ "run_id": "run",
+ "sha": "abc",
+ "status": workflow_status,
+ "created_at": "2026-10-05T12:23:00Z",
+ }
+
+ run = script.gate_run(listed)
+
+ assert (run["status"], run["conclusion"]) == expected
+ assert run["head_sha"] == "abc"
+
+
+def test_names_the_workflow_and_gate_job_the_relay_reads() -> None:
+ assert script.WORKFLOW_NAME == ci_backend_relay.DEPOT_WORKFLOW
+ assert script.GATE_JOB_KEY == ci_backend_relay.GATE_JOB_KEY
+
+
+def test_retries_a_workflow_listing_timeout_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = 0
+
+ def depot_response(*args: str) -> str:
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ raise subprocess.TimeoutExpired("depot", script.CLI_TIMEOUT_SECONDS)
+ return "[]"
+
+ monkeypatch.setattr(script, "depot", depot_response)
+
+ assert script.scheduled_workflows(["finished"], 5) == []
+ assert calls == 2
+
+
[email protected]("status", [None, "running", "cancelled", "finished", "failed"])
+def test_gate_window_requires_a_settled_verdict(monkeypatch: pytest.MonkeyPatch, status: str | None) -> None:
+ def depot_response(*args: str) -> str:
+ if args[:2] == ("workflow", "list"):
+ return json.dumps(
+ [
+ {
+ "workflow_id": "wf",
+ "run_id": "run",
+ "sha": "abc",
+ "status": status,
+ "created_at": "2026-10-05T12:23:00Z",
+ }
+ ]
+ if status
+ else []
+ )
+ return json.dumps({"org_id": "org", "jobs": [{"job_key": script.GATE_JOB_KEY, "status": status}]})
+
+ monkeypatch.setattr(script, "depot", depot_response)
+
+ if status in ("finished", "failed"):
+ assert script.gate_runs()[0]["conclusion"] == script.GATE_CONCLUSIONS[status]
+ else:
+ with pytest.raises(ValueError, match="No settled Backend CI verdict"):
+ script.gate_runs()
+
+
+def test_gate_window_keeps_in_progress_runs_alongside_a_settled_verdict(monkeypatch: pytest.MonkeyPatch) -> None:
+ def depot_response(*args: str) -> str:
+ if args[:2] == ("workflow", "list"):
+ return json.dumps(
+ [
+ {
+ "workflow_id": status,
+ "run_id": status,
+ "sha": "abc",
+ "status": status,
+ "created_at": "2026-10-05T12:23:00Z",
+ }
+ for status in ("finished", "running")
+ ]
+ )
+ return json.dumps({"org_id": "org", "jobs": [{"job_key": script.GATE_JOB_KEY, "status": args[2]}]})
+
+ monkeypatch.setattr(script, "depot", depot_response)
+
+ assert [run["status"] for run in script.gate_runs()] == ["completed", "in_progress"]
+
+
+def test_download_keeps_the_newest_artifact_per_name() -> None:
+ artifacts = [
+ {"name": "timing_data-Core-1", "artifact_id": "retry", "created_at": "2026-10-05T12:40:00Z"},
+ {"name": "timing_data-Core-1", "artifact_id": "first", "created_at": "2026-10-05T12:30:00Z"},
+ {"name": "timing_data-Core-2", "artifact_id": "only", "created_at": "2026-10-05T12:31:00Z"},
+ ]
+
+ assert sorted(a["artifact_id"] for a in script.newest_per_name(artifacts)) == ["only", "retry"]
+
+
[email protected]("persistent_failure", [False, True])
+def test_download_recovers_from_partial_transfers_or_fails_closed(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, persistent_failure: bool
+) -> None:
+ failed = False
+
+ def depot_response(*args: str, timeout: int = script.CLI_TIMEOUT_SECONDS) -> str:
+ nonlocal failed
+ if args[:2] == ("artifacts", "list"):
+ return json.dumps(
+ {"artifacts": [{"artifact_id": "artifact", "name": "timing_data-Core-1", "created_at": "2026-01-01"}]}
+ )
+ archive = Path(args[args.index("--output-file") + 1])
+ if archive.exists():
+ raise FileExistsError(archive)
+ if persistent_failure or not failed:
+ failed = True
+ archive.write_bytes(b"partial archive")
+ raise subprocess.CalledProcessError(1, args)
+ with zipfile.ZipFile(archive, "w") as bundle:
+ bundle.writestr(".test_durations", "{}")
+ return ""
+
+ monkeypatch.setattr(script, "depot", depot_response)
+ monkeypatch.setattr("time.sleep", lambda _: None)
+
+ if persistent_failure:
+ with pytest.raises(subprocess.CalledProcessError):
+ script.download("run", ["timing_data-*"], tmp_path)
+ assert not (tmp_path / "timing_data-Core-1").exists()
+ else:
+ assert script.download("run", ["timing_data-*"], tmp_path) == 1
+ assert (tmp_path / "timing_data-Core-1" / ".test_durations").read_text() == "{}"
diff --git a/.github/scripts/test_report_workflow_run_traces.py b/.github/scripts/test_report_workflow_run_traces.py
index 3a038e457b5b..1e4bd44ec236 100644
--- a/.github/scripts/test_report_workflow_run_traces.py
+++ b/.github/scripts/test_report_workflow_run_traces.py
@@ -407,22 +407,81 @@ 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)}]},
- }
+ def test_scheduled_backend_runs_are_not_read_from_github(self) -> None:
+ opener = _FakeOpener({"/actions/runs": {"workflow_runs": []}})
+ reporter.scan_runs("PostHog/posthog", "t", RUN_START, opener=opener)
+ assert len(opener.calls) == 1
+ assert "event=push" in opener.calls[0]
+
+
+class TestDepotTraces:
+ @pytest.mark.parametrize("workflow_path", ["ci-backend.yml", ".depot/workflows/ci-backend.yml"])
+ @pytest.mark.parametrize(
+ "status,conclusion", [("finished", "success"), ("failed", "failure"), ("cancelled", "cancelled")]
+ )
+ def test_reads_the_completed_workflow_and_job_timestamps(
+ self, monkeypatch: pytest.MonkeyPatch, status: str, conclusion: str, workflow_path: str
+ ) -> None:
+ shown = {
+ "org_id": "org",
+ "run": {"run_id": "run", "repo": "PostHog/posthog", "sha": "abc", "trigger": "schedule"},
+ "workflow": {
+ "workflow_id": "wf",
+ "workflow_path": workflow_path,
+ "status": status,
+ "created_at": _iso(0),
+ "started_at": _iso(5),
+ "finished_at": _iso(120),
+ },
+ "executions": [{"execution": 2}],
+ "jobs": [
+ {
+ "job_id": "job",
+ "job_key": "ci-backend.yml:django",
+ "status": status,
+ "started_at": _iso(10),
+ "finished_at": _iso(60),
+ }
+ ],
+ }
+ monkeypatch.setattr(
+ reporter.depot_scheduled_runs,
+ "scheduled_workflows",
+ lambda *args, **kwargs: [
+ {"workflow_id": "wf", "created_at": _iso(0)},
+ {"workflow_id": "old", "created_at": _iso(-100)},
+ ],
)
- 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
+
+ def depot_response(*args: str) -> str:
+ if args[2] == "old":
+ return json.dumps({**shown, "workflow": {**shown["workflow"], "finished_at": _iso(-1)}})
+ return json.dumps(shown)
+
+ monkeypatch.setattr(reporter.depot_scheduled_runs, "depot", depot_response)
+
+ collection = reporter.collect_depot_runs("PostHog/posthog", RUN_START)
+
+ assert collection.complete
+ assert len(collection.runs) == 1
+ run = collection.runs[0]
+ assert (run.id, run.attempt, run.provider, run.conclusion) == ("depot:run", 2, "depot", conclusion)
+ assert run.path == ".depot/workflows/ci-backend.yml"
+ assert run.end == RUN_START + timedelta(seconds=120)
+ assert (run.jobs[0].id, run.jobs[0].duration_seconds, run.step_count) == ("job", 50, 0)
+ exporter = InMemorySpanExporter()
+ reporter.emit_trace(run, "https://example.com", "token", exporter=exporter)
+ assert len(exporter.get_finished_spans()) == 2
+ assert reporter.run_resource_attributes(run)["ci.provider"] == "depot"
+
+ def test_failed_depot_reads_hold_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def unavailable(*args: object) -> reporter.Collection:
+ raise RuntimeError("unavailable")
+
+ monkeypatch.setattr(reporter, "scan_runs", lambda *args: [])
+ monkeypatch.setattr(reporter, "collect_depot_runs", unavailable)
+ collection = reporter.collect_runs(reporter.parse_args(["--since", _iso(0)]), "token", RUN_START)
+ assert not collection.complete
class TestAttemptSelection:
diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.yml
index 9d1f31000cfb..f85cfd45d10f 100644
--- a/.github/workflows/ci-alerts-devex.yml
+++ b/.github/workflows/ci-alerts-devex.yml
@@ -20,7 +20,7 @@ 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, and the workflow that runs the hourly master matrices) suffices.
+ # ~every push) suffices.
# branches:[master] skips PR completions; cron stays a backstop.
workflow_run:
workflows: ['Backend CI']
@@ -66,7 +66,10 @@ env:
# Frontend CI is split the same way: jest runs hourly, while typecheck, format and bundle size
# run on every push. For Node.js, Dagster, Python and MCP the whole suite is on the cron, so
# their push lane only proves the run dispatched and the scheduled lane carries the coverage.
- SCHEDULED_GATING_WORKFLOWS: 'ci-backend.yml,ci-frontend.yml,ci-nodejs.yml,ci-dagster.yml,ci-python.yml,ci-mcp.yml'
+ SCHEDULED_GATING_WORKFLOWS: 'ci-frontend.yml,ci-nodejs.yml,ci-dagster.yml,ci-python.yml,ci-mcp.yml'
+ # Backend CI's hourly run is on Depot CI (.depot/workflows/ci-backend.yml), so GitHub has no
+ # runs for that lane. The reconcile job writes its runs to DEPOT_SCHEDULED_RUNS_FILE first.
+ DEPOT_SCHEDULED_GATING_WORKFLOW: '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
@@ -77,21 +80,39 @@ env:
jobs:
check-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).
+ # Only reconcile on the master run completions the alerter reads
+ # (branches:[master] already scopes the trigger to master).
if: >-
github.event_name != 'workflow_run' ||
- github.event.workflow_run.event == 'push' ||
- github.event.workflow_run.event == 'schedule'
+ github.event.workflow_run.event == 'push'
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
+ persist-credentials: false
sparse-checkout: |
.github/scripts/ci-alerts-devex.js
+ .github/scripts/depot_scheduled_runs.py
sparse-checkout-cone-mode: false
+ # Both Depot steps are capped, so a slow Depot API cannot use up the job's
+ # timeout and cancel the reconcile of every other lane.
+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
+ continue-on-error: true
+ timeout-minutes: 1
+
+ # A failed read leaves no file, and the script then treats the lane as unreadable.
+ - name: Read the hourly Backend CI runs from Depot CI
+ id: depot-runs
+ continue-on-error: true
+ timeout-minutes: 1
+ env:
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
+ run: |
+ python3 .github/scripts/depot_scheduled_runs.py gate-runs > "$RUNNER_TEMP/runs.json"
+ mv "$RUNNER_TEMP/runs.json" "$RUNNER_TEMP/depot-backend-scheduled-runs.json"
+
# Ticks list runs for every gating workflow (dozens of calls at worst)
# exactly when master push volume peaks, so read through the posthog-tests App
# bucket (it has actions:read; ci-backend-update-test-timing lists runs with
@@ -115,8 +136,16 @@ jobs:
# variable rather than a secret, because this repo sits two under GitHub's cap of
# 100 secrets; the script masks the value so a public log cannot leak it.
DIAGNOSIS_WEBHOOK_URL: ${{ vars.MASTER_RED_DIAGNOSIS_WEBHOOK_URL }}
+ DEPOT_SCHEDULED_RUNS_FILE: ${{ runner.temp }}/depot-backend-scheduled-runs.json
with:
github-token: ${{ steps.app-token.outputs.token || github.token }}
script: |
const script = require('./.github/scripts/ci-alerts-devex.js')
await script({ github, context, core })
+
+ # Reconcile the other lanes before surfacing a broken monitoring input.
+ - name: Report a failed Depot read
+ if: always() && steps.depot-runs.outcome == 'failure'
+ run: |
+ echo "::error::The scheduled Backend CI lane could not be read from Depot CI"
+ exit 1
diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.yml
index 53c471c53df6..ee322aa444ec 100644
--- a/.github/workflows/ci-backend-update-test-timing.yml
+++ b/.github/workflows/ci-backend-update-test-timing.yml
@@ -4,7 +4,7 @@ on:
workflow_dispatch:
inputs:
backend_run_id:
- description: 'Backend CI run ID (leave empty to use latest successful run)'
+ description: 'Depot CI run ID of an hourly Backend CI run (leave empty to use latest successful run)'
required: false
type: string
dagster_run_id:
@@ -50,10 +50,12 @@ jobs:
with:
enable-cache: false
+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
+
- name: Find Backend CI run to use
id: find-backend-run
env:
- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
INPUT_RUN_ID: ${{ inputs.backend_run_id }}
# Optional org/repo variable to tune how many runs the per-segment plan averages
# (default 5). Unset renders empty and the shell default kicks in.
@@ -66,12 +68,7 @@ jobs:
exit 0
fi
- # Find recent successful ci-backend.yml runs with timing artifacts.
- # Only the hourly scheduled runs carry them. Master pushes run the per-commit
- # checks only, but those take longer than the duration filter below, so
- # without the event filter they fill the candidate window and the search
- # finds nothing.
- # Only consider runs from the past 14 days to ensure artifacts haven't expired
+ # Only the hourly master runs carry timing artifacts, and they run on Depot CI.
echo "Searching for Backend CI runs with timing artifacts..."
# The per-segment file-mode plans (.test_durations.core/.temporal) and the
@@ -81,31 +78,12 @@ jobs:
# de-tax still use the newest run alone (the primary). N stays small because
# every extra run downloads its product timing artifacts, the largest set.
N="${BACKEND_RUNS_TO_AVERAGE:-5}"
- # Guard a mis-set variable: a non-integer would make the `-ge` test below error
- # out (never breaking the loop) and silently average every candidate run.
[[ "$N" =~ ^[1-9][0-9]*$ ]] || N=5
- found=0 # counts qualifying runs inside the loop below
- # Calculate date 14 days ago in ISO 8601 format
- cutoff_date=$(date -u -d '14 days ago' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-14d +%Y-%m-%dT%H:%M:%SZ)
- # Newest first: runs that ran tests (>5 min) and uploaded a full set of timing
- # artifacts (>=38), up to N. Scan N plus a margin so a run with expired or
- # partial artifacts does not end the search early; the margin also bounds
- # the artifact API calls when nothing qualifies.
- run_ids=$(gh api "repos/${{ github.repository }}/actions/workflows/ci-backend.yml/runs?status=success&branch=master&event=schedule&per_page=100&created=>=$cutoff_date" \
- --jq '.workflow_runs[] | select(
- (.updated_at | fromdateiso8601) - (.run_started_at | fromdateiso8601) > 300
- ) | .id' | head -n "$((N + 20))" | \
- while read id; do
- count=$(gh api "repos/${{ github.repository }}/actions/runs/$id/artifacts?per_page=100" \
- --jq '[.artifacts[] | select(.name | startswith("timing_data-")) | select(.expired == false)] | length' 2>/dev/null)
- echo "Run $id has $count timing artifacts" >&2
- if [ "$count" -ge "38" ]; then
- echo "$id"
- found=$((found + 1))
- [ "$found" -ge "$N" ] && break
- fi
- done)
+ # Newest first: successful hourly runs on Depot CI that uploaded a full set of
+ # timing artifacts (>=38), up to N.
+ run_ids=$(python3 .github/scripts/depot_scheduled_runs.py find \
+ --prefix timing_data- --min-artifacts 38 --limit "$N" | cut -d' ' -f1)
primary=$(echo "$run_ids" | head -1)
if [ -z "$primary" ]; then
@@ -191,15 +169,19 @@ jobs:
- name: Download timing artifacts
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
BACKEND_RUN_ID: ${{ steps.find-backend-run.outputs.run_id }}
BACKEND_RUN_IDS: ${{ steps.find-backend-run.outputs.run_ids }}
DAGSTER_RUN_ID: ${{ steps.find-dagster-run.outputs.run_id }}
run: |
+ # Backend runs live on Depot CI, Dagster runs on GitHub Actions.
+ depot_download() { python3 .github/scripts/depot_scheduled_runs.py download "$@"; }
+
# Download backend timing artifacts. Use segment-specific patterns
# so we don't accidentally pull Dagster artifacts here when the same
# run ID is provided for both jobs (they share the timing_data- prefix
# and would otherwise collide on extraction into the same dir).
- gh run download "$BACKEND_RUN_ID" \
+ depot_download "$BACKEND_RUN_ID" \
--pattern "timing_data-Core-*" \
--pattern "timing_data-Temporal-*" \
--pattern "timing_data-Products-*" \
@@ -208,7 +190,7 @@ jobs:
# JUnit artifacts power precise per-shard carrier detection.
# Without these, optimize_test_durations.py silently takes the
# statistical fallback and the JUnit-arg becomes a no-op.
- gh run download "$BACKEND_RUN_ID" \
+ depot_download "$BACKEND_RUN_ID" \
--pattern "junit-results-backend-core-*" \
--pattern "junit-results-backend-temporal-*" \
--pattern "product-junit-results-*" \
@@ -221,11 +203,11 @@ jobs:
# the union/JUnit steps above stay untouched. A run with no JUnit just gets its
# per-segment slice skipped, same fallback as the single-run path.
for rid in $BACKEND_RUN_IDS; do
- gh run download "$rid" \
+ depot_download "$rid" \
--pattern "timing_data-Core-*" \
--pattern "timing_data-Temporal-*" \
--dir "runs/$rid/timing" || { echo "::warning::No timing for run $rid — skipping it"; continue; }
- gh run download "$rid" \
+ depot_download "$rid" \
--pattern "junit-results-backend-core-*" \
--pattern "junit-results-backend-temporal-*" \
--dir "runs/$rid/junit" || echo "::warning::No JUnit for run $rid — its per-segment slice is skipped"
@@ -233,9 +215,9 @@ jobs:
# junit_artifacts. Product timing artifacts are the largest set, so do not
# download them twice.
if [ "$rid" != "$BACKEND_RUN_ID" ]; then
- gh run download "$rid" --pattern "timing_data-Products-*" --dir "runs/$rid/timing" \
+ depot_download "$rid" --pattern "timing_data-Products-*" --dir "runs/$rid/timing" \
|| echo "::warning::No Products timing for run $rid — its products slice is skipped"
- gh run download "$rid" --pattern "product-junit-results-*" --dir "runs/$rid/junit" \
+ depot_download "$rid" --pattern "product-junit-results-*" --dir "runs/$rid/junit" \
|| echo "::warning::No Products JUnit for run $rid — its products slice is skipped"
fi
done
@@ -456,27 +438,33 @@ jobs:
runs-on: depot-ubuntu-24.04
timeout-minutes: 15
steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ sparse-checkout: .github/scripts/depot_scheduled_runs.py
+ sparse-checkout-cone-mode: false
+
+ # The checkout of the recorded commit below replaces the tree, and an older commit
+ # does not have the script.
+ - name: Keep the Depot run reader
+ run: cp .github/scripts/depot_scheduled_runs.py "$RUNNER_TEMP/depot_scheduled_runs.py"
+
+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
+
- name: Find the newest scheduled Backend CI run with recordings
id: find-run
env:
- GH_TOKEN: ${{ github.token }}
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
run: |
- # Only the scheduled runs that take the events_json rows record. A successful
- # one carries every shard's recording, because a shard that wrote none fails.
- # Without the created filter the API can return runs that are weeks old.
- cutoff=$(date -u -d '2 days ago' +%Y-%m-%dT%H:%M:%SZ)
- gh api "repos/$GITHUB_REPOSITORY/actions/workflows/ci-backend.yml/runs?status=success&branch=master&event=schedule&per_page=10&created=>=$cutoff" \
- --jq '.workflow_runs[] | "\(.id) \(.head_sha)"' | while read -r id sha; do
- count=$(gh api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$id/artifacts?per_page=100" \
- --jq '[.artifacts[] | select((.name | startswith("events-schema-record-")) and .expired == false)] | length' | jq -s add)
- if [ "${count:-0}" -gt 0 ]; then
- echo "Using run $id at $sha, with $count recordings"
- echo "run_id=$id" >> "$GITHUB_OUTPUT"
- echo "revision=$sha" >> "$GITHUB_OUTPUT"
- break
- fi
- done
- if ! grep -q '^run_id=' "$GITHUB_OUTPUT"; then
+ # Only the hourly runs on Depot CI that take the events_json rows record. A
+ # successful one carries every shard's recording, because a shard that wrote
+ # none fails.
+ read -r id sha < <(python3 "$RUNNER_TEMP/depot_scheduled_runs.py" find \
+ --prefix events-schema-record- --max-age-days 2) || true
+ if [ -n "${id:-}" ]; then
+ echo "Using run $id at $sha"
+ echo "run_id=$id" >> "$GITHUB_OUTPUT"
+ echo "revision=$sha" >> "$GITHUB_OUTPUT"
+ else
echo "::error::No recent successful scheduled Backend CI run has events_json recordings, so the prune manifest stays as it is"
exit 1
fi
@@ -503,13 +491,17 @@ jobs:
with:
enable-cache: false
- - name: Build the manifest
+ # Its own step, so the Depot token stays out of the step that installs from PyPI.
+ - name: Download the recordings
if: steps.cached.outputs.cache-hit != 'true'
env:
- GH_TOKEN: ${{ github.token }}
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
RUN_ID: ${{ steps.find-run.outputs.run_id }}
+ run: python3 "$RUNNER_TEMP/depot_scheduled_runs.py" download "$RUN_ID" --pattern 'events-schema-record-*' --dir events-schema-records
+
+ - name: Build the manifest
+ if: steps.cached.outputs.cache-hit != 'true'
run: |
- gh run download "$RUN_ID" --pattern 'events-schema-record-*' --dir events-schema-records
uv run --no-project --with pytest python posthog/test/events_schema_prune.py \
--output events-schema-prune.json events-schema-records/*/events-schema-record.json
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index c1c6401e575e..d1ccf40a5595 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -7,16 +7,8 @@ on:
push:
branches:
- master
- schedule:
- # Hourly full-matrix run against the newest master state. Master pushes no
- # longer run the test matrices per commit — the merge queue's trunk-merge/**
- # run already gated every commit before it landed — so this is where master's
- # matrix coverage, flaky-test baseline, and per-test timing data come from.
- # Only the every-third-hour cron runs the events_json leg. The merge queue
- # already runs that leg before every commit lands, and this cadence still gives
- # Trunk's master monitors enough runs. EVENTS_JSON_SCHEDULE in env repeats this string.
- - cron: '23 */3 * * *'
- - cron: '23 1,2,4,5,7,8,10,11,13,14,16,17,19,20,22,23 * * *'
+ # No schedule trigger: the hourly full-matrix master run is on Depot CI, from the schedule
+ # trigger of .depot/workflows/ci-backend.yml.
workflow_dispatch:
inputs:
clickhouseServerVersion:
@@ -54,8 +46,6 @@ on:
concurrency:
# PRs: one active run per branch, cancel stale. Push: per-SHA so master
# pushes never cancel each other (check-migrations always completes).
- # Scheduled runs share the ref group without cancellation, so a slow hourly
- # run queues the next one instead of stacking runs.
group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.head_ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
@@ -85,11 +75,8 @@ env:
CLICKHOUSE_TEST_CLUSTER_VERIFY: 'False'
TEST: 1
# The root conftest ends a green pytest session with os._exit once every report is written.
- # That also hides a crash during interpreter teardown, so the hourly schedule exits normally.
- POSTHOG_PYTEST_HARD_EXIT: ${{ github.event_name == 'schedule' && '0' || '1' }}
- # The on.schedule cron whose runs keep the events_json leg. GitHub cannot reference a cron
- # from an expression, so this copy must match it.
- EVENTS_JSON_SCHEDULE: '23 */3 * * *'
+ # The hourly run on Depot CI turns this off, because it also hides a crash during interpreter teardown.
+ POSTHOG_PYTEST_HARD_EXIT: '1'
CLICKHOUSE_SERVER_IMAGE_VERSION: ${{ github.event.inputs.clickhouseServerVersion || '' }}
CLICKHOUSE_COMPAT_PYTEST_TARGETS: 'posthog/clickhouse ee/clickhouse'
OBJECT_STORAGE_ENABLED: 'True'
@@ -211,11 +198,8 @@ jobs:
client-id: ${{ vars.GH_APP_POSTHOG_PATHS_FILTER_APP_ID }}
private-key: ${{ secrets.GH_APP_POSTHOG_PATHS_FILTER_PRIVATE_KEY }}
- uses: ./.github/actions/paths-filter
- # Skipped on master push and on the hourly schedule: every output then
- # defaults to true. See "The hourly master lane" in
- # .agents/skills/authoring-ci-workflows/SKILL.md for why a cron cannot
- # diff, and what breaks if this guard is dropped.
- if: github.event_name != 'push' && github.event_name != 'schedule'
+ # Skipped on master push: every output then defaults to true.
+ if: github.event_name != 'push'
id: filter
with:
token: ${{ steps.app-token.outputs.token || github.token }}
@@ -1443,7 +1427,7 @@ jobs:
# bots rewrite manifests across majors, so this is the block. Stdlib only, no venv.
sdk-major-guard:
needs: [changes]
- if: needs.changes.outputs.sdk_manifests == 'true' && github.event_name != 'schedule' && needs.changes.outputs.engine != 'depot'
+ if: needs.changes.outputs.sdk_manifests == 'true' && needs.changes.outputs.engine != 'depot'
timeout-minutes: 5
permissions: {}
name: SDK major-version guard
@@ -1456,8 +1440,7 @@ jobs:
repo-checks:
needs: [changes]
# product_yamls: ownership-only PRs still need the owners.yaml lint below.
- # A per-commit check — the hourly scheduled run skips it as already covered.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'schedule' && needs.changes.outputs.engine != 'depot'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && needs.changes.outputs.engine != 'depot'
timeout-minutes: 10
outputs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
@@ -1694,13 +1677,11 @@ jobs:
# in check-openapi-types below.
check-migrations:
needs: [changes]
- # A per-commit check — every master push runs it (it saves the schema dump
- # caches), so the hourly scheduled run skips it as already covered.
# migration_replay is listed because it reaches files the other three miss:
# products/db_routing.yaml is neither Python nor under a backend/ directory, and
# a migration in a future top-level app matches none of them. Without it the
# replay gate could be on while the job that runs it never starts.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.migrations == 'true' || needs.changes.outputs.persons_sql == 'true' || needs.changes.outputs.migration_replay == 'true') && github.event_name != 'schedule' && needs.changes.outputs.engine != 'depot'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.migrations == 'true' || needs.changes.outputs.persons_sql == 'true' || needs.changes.outputs.migration_replay == 'true') && needs.changes.outputs.engine != 'depot'
# On master this job replays the full migration history from scratch to
# produce the schema dump every PR job restores, and a merge queue batch that
# changes a Django migration replays it a second time onto an empty database.
@@ -2459,8 +2440,7 @@ jobs:
check-openapi-types:
needs: [changes]
- # A per-commit check — the hourly scheduled run skips it as already covered.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && github.event_name != 'schedule' && needs.changes.outputs.engine != 'depot'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && needs.changes.outputs.engine != 'depot'
timeout-minutes: 20
outputs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
@@ -2753,7 +2733,6 @@ jobs:
# that takes the whole list.
JSON_TARGETS_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_files }}
JSON_TARGETS_SHARDS: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').json_targets_shards }}
- RUN_JSON_TARGETS: ${{ github.event_name != 'schedule' || github.event.schedule == env.EVENTS_JSON_SCHEDULE }}
# Same rule as the django job's condition: the suite runs for a legacy
# edit, for a product change that reaches legacy code, and when discovery
# failed, which leaves run_legacy empty. Without it only the events_json
@@ -3069,11 +3048,6 @@ jobs:
json_targets_count="${JSON_TARGETS_SHARDS:-0}"
fi
- if [[ "$RUN_JSON_TARGETS" != "true" ]]; then
- echo "Skipping the events_json rows on this hourly run"
- json_targets_count=0
- fi
-
# The events_json rows: Core jobs over the listed paths with the
# native-JSON events table. They keep Core's person-on-events default.
json_targets=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson n "$json_targets_count" '
@@ -3717,11 +3691,7 @@ jobs:
JSON_SPLIT=(--splits "${{ matrix.concurrency }}" --group "${{ matrix.group }}"
--splitting-algorithm="$SPLITTING_ALGORITHM" "${SPLIT_GRANULARITY[@]}")
fi
- if [[ "$GITHUB_EVENT_NAME" == "schedule" ]]; then
- # The hourly run keeps every listed test and records which ones read the
- # JSON tables. The timing workflow builds the prune manifest from it.
- export POSTHOG_EVENTS_SCHEMA_RECORD_PATH=events-schema-record.json
- elif [[ "$GITHUB_EVENT_NAME" == "pull_request" && "$GITHUB_HEAD_REF" != trunk-merge/* && -f events-schema-prune.json ]]; then
+ if [[ "$GITHUB_EVENT_NAME" == "pull_request" && "$GITHUB_HEAD_REF" != trunk-merge/* && -f events-schema-prune.json ]]; then
# Skips the tests that a recording showed never read the JSON tables. The
# merge queue runs every listed test, so a skipped test whose code starts
# to read those tables still fails before the change reaches master.
@@ -4030,17 +4000,6 @@ jobs:
junit-*.xml
!junit-*-retry-failures.xml
- - name: Upload events schema recording
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
- if: ${{ always() && matrix.json-targets && github.event_name == 'schedule' }}
- with:
- name: events-schema-record-${{ matrix.artifact_key }}${{ github.run_attempt != '1' && format('-attempt{0}', github.run_attempt) || '' }}
- path: events-schema-record.json
- # A successful run must carry every shard's recording, because the prune
- # manifest is built from successful runs only.
- if-no-files-found: error
- retention-days: 14
-
# The helper sets TRUNK_CODEOWNERS_PATH so Trunk attributes uploaded tests to their owners.
- name: Build the Trunk ownership map
if: ${{ !cancelled() && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}
@@ -4676,7 +4635,7 @@ jobs:
# Runs on every attempt: a re-run passing what an earlier attempt failed is the same-commit
# flake proof the test-health queue reads, and the shards a re-run re-executed upload under
# attempt-suffixed artifact names so only they are emitted for the new attempt.
- # Scheduled master runs and all in-repo PRs. Skip forks (no secrets access)
+ # Manual master runs and all in-repo PRs. Skip forks (no secrets access)
# and master pushes (their matrices are skipped, so there are no traces).
# Both matrices skipped also means no JUnit was uploaded, so there are no
# traces to emit. This job sits on the tail of the run, so skipping it takes
diff --git a/.github/workflows/ci-master-run-traces.yml b/.github/workflows/ci-master-run-traces.yml
index 419cf4f693f4..e4a5314deab2 100644
--- a/.github/workflows/ci-master-run-traces.yml
+++ b/.github/workflows/ci-master-run-traces.yml
@@ -4,8 +4,8 @@ name: Master run traces
# 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). 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).
+# Backend CI's scheduled runs are read from Depot. Depot exposes workflow and job
+# timestamps, but not step or job-queue timestamps, so those traces stop at jobs.
#
# Complements .github/scripts/report_test_timings.py, which emits per-test traces
# from JUnit XML under its own trace IDs. Those stay separate traces.
@@ -55,8 +55,10 @@ jobs:
# receives the project token, which cannot happen here.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
+ persist-credentials: false
sparse-checkout: |
.github/scripts/report_workflow_run_traces.py
+ .github/scripts/depot_scheduled_runs.py
.github/actions/setup-uv
sparse-checkout-cone-mode: false
@@ -77,12 +79,17 @@ jobs:
with:
enable-cache: false
+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1
+ continue-on-error: true
+ timeout-minutes: 1
+
# Deliberately not continue-on-error: a red tick is what holds the watermark
# at the last clean one, so the next tick re-covers the window. This workflow
# gates nothing, so failing costs a notification rather than a blocked merge.
- name: Emit master run traces
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token || github.token }}
+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
SINCE: ${{ inputs.since }}
POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}
# dual emission while CI traces migrate to the project behind POSTHOG_API_TOKEN
diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.ts
index f6c1e42575a1..9e9d13c786be 100644
--- a/tools/workflow-plan/tests/workflows.test.ts
+++ b/tools/workflow-plan/tests/workflows.test.ts
@@ -1,9 +1,12 @@
// These tests check the workflows under .github/workflows, not the planner. A failure here means a
// job condition in a workflow file changed what runs; the planner itself is covered by plan.test.ts.
-import { readdirSync } from 'node:fs'
+import { spawnSync } from 'node:child_process'
+import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
+import os from 'node:os'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
+import { evaluateValue, planFunctions } from '../src/expressions.ts'
import {
type Outcome,
type Scenario,
@@ -341,13 +344,6 @@ const EXPECTATIONS: Expectation[] = [
],
}
),
- backend(
- { name: 'hourly schedule', github: schedule() },
- {
- runs: ['changes', 'turbo-tests', 'django', 'django_tests'],
- skipped: ['repo-checks', 'sdk-major-guard', 'check-migrations', 'check-openapi-types', 'mirror-schema-cache'],
- }
- ),
backend(
{ name: 'ready PR, superseded and cancelled', cancelled: true },
{
@@ -482,16 +478,16 @@ const E2E_DISPATCH: Scenario = {
}
const STEP_EXPECTATIONS: StepExpectation[] = [
+ {
+ file: 'ci-frontend.yml',
+ job: 'changes',
+ step: 'filter',
+ scenario: { name: 'hourly schedule', github: schedule() },
+ runs: false,
+ },
...PINNED_WORKFLOWS.flatMap((file) => [
{ file, job: 'changes', step: 'filter', scenario: { name: 'ready PR', github: pullRequest() }, runs: true },
{ file, job: 'changes', step: 'filter', scenario: { name: 'master push', github: push() }, runs: false },
- {
- file,
- job: 'changes',
- step: 'filter',
- scenario: { name: 'hourly schedule', github: schedule() },
- runs: false,
- },
{ file, job: 'changes', step: 'app-token', scenario: { name: 'ready PR', github: pullRequest() }, runs: true },
{
file,
@@ -536,29 +532,81 @@ describe('.github/workflows run plans', () => {
},
})
expect(plan.errors).toEqual([])
- const steps = plan.jobs['update-sandbox-agent-version'].steps
+ const steps = plan.jobs['update-sandbox-agent-version']?.steps ?? []
expect(steps.find((step) => step.id === 'commit')?.runs).toBe(action === 'bump')
expect(steps.find((step) => step.id === 'enqueue')?.runs).toBe(enqueue)
expect(steps.find((step) => step.id === 'nightly-smoke')?.runs).toBe(nightly)
})
it('Phrocs executes tests even when setup-go restores a warm build cache', () => {
- const testStep = workflow('ci-phrocs.yml').jobs.test.steps?.find((step) => step.name === 'Run tests')
+ const testStep = workflow('ci-phrocs.yml').jobs.test?.steps?.find((step) => step.name === 'Run tests')
expect(testStep?.run).toMatch(/\bgo test\s+-count=1\b/)
})
- it('Backend CI runs once every hour and keeps the events_json leg on one of its crons', () => {
- const backend = workflow('ci-backend.yml')
- const crons = (backend.on as { schedule: { cron: string }[] }).schedule.map((entry) => entry.cron)
- const cronHours = (field: string): number[] =>
- field.startsWith('*/')
- ? [...Array(24).keys()].filter((hour) => hour % Number(field.slice(2)) === 0)
- : field.split(',').map(Number)
+ it('Backend CI runs once every hour, on Depot CI only', () => {
+ const crons = (file: string): string[] =>
+ ((loadWorkflow(path.join(REPO_ROOT, file)).on as { schedule?: { cron: string }[] }).schedule ?? []).map(
+ (entry) => entry.cron
+ )
- expect(crons).toContain(backend.env?.EVENTS_JSON_SCHEDULE)
- expect(crons.flatMap((cron) => cronHours(cron.split(' ')[1])).sort((a, b) => a - b)).toEqual([
- ...Array(24).keys(),
+ expect(crons('.depot/workflows/ci-backend.yml')).toEqual([
+ '23 */3 * * *',
+ '23 1,2,4,5,7,8,10,11,13,14,16,17,19,20,22,23 * * *',
])
+ expect(crons('.github/workflows/ci-backend.yml')).toEqual([])
+ })
+
+ it.each(['refs/heads/master', ''])('the hourly Depot run keeps master coverage with ref %j', (ref) => {
+ const depot = loadWorkflow(path.join(REPO_ROOT, '.depot/workflows/ci-backend.yml'))
+ const plan = planWorkflow(depot, {
+ name: 'hourly schedule',
+ github: { ...schedule(), ref },
+ steps: {
+ ...allFiltersChanged(depot),
+ ...backendSelectors,
+ 'wait-for-handoff': { handoff: { outputs: { handed_off: 'true' } } },
+ },
+ })
+ expect(plan.errors).toEqual([])
+ const running = new Set(runningJobs(plan))
+ const perCommit = ['repo-checks', 'sdk-major-guard', 'check-migrations', 'check-openapi-types']
+ expect({
+ didNotRun: ['changes', 'turbo-tests', 'django', 'django_tests', 'report-test-timings'].filter(
+ (id) => !running.has(id)
+ ),
+ didNotSkip: perCommit.filter((id) => plan.jobs[id]?.result !== 'skipped'),
+ filterRuns: plan.jobs.changes?.steps.find((step) => step.id === 'filter')?.runs,
+ productTimings: plan.jobs['turbo-tests']?.steps.find((step) => step.name === 'Upload timing data')?.runs,
+ }).toEqual({ didNotRun: [], didNotSkip: [], filterRuns: false, productTimings: true })
+ })
+
+ it('the scheduled Depot hand-off succeeds without a GitHub receipt', () => {
+ const depot = loadWorkflow(path.join(REPO_ROOT, '.depot/workflows/ci-backend.yml'))
+ const script = depot.jobs['wait-for-handoff']?.steps?.find((step) => step.id === 'handoff')?.run
+ expect(script).toBeTypeOf('string')
+ const directory = mkdtempSync(path.join(os.tmpdir(), 'depot-handoff-'))
+ const output = path.join(directory, 'output')
+ try {
+ const result = spawnSync('/bin/bash', ['-c', String(script)], {
+ env: { EVENT: 'schedule', IS_FORK: 'false', GITHUB_OUTPUT: output },
+ encoding: 'utf8',
+ })
+ expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' })
+ expect(readFileSync(output, 'utf8')).toContain('handed_off=true')
+ } finally {
+ rmSync(directory, { recursive: true, force: true })
+ }
+ })
+
+ it.each([
+ ['23 */3 * * *', true],
+ ['23 1,2,4,5,7,8,10,11,13,14,16,17,19,20,22,23 * * *', false],
+ ])('the events_json leg follows the scheduled trigger %s', (cron, runs) => {
+ const depot = loadWorkflow(path.join(REPO_ROOT, '.depot/workflows/ci-backend.yml'))
+ const step = depot.jobs.build_django_matrix?.steps?.find((step) => step.id === 'build')
+ const github = { ...schedule(), event: { schedule: cron } }
+ const functions = planFunctions({ dependenciesSucceeded: true, dependenciesFailed: false, cancelled: false })
+ expect(evaluateValue(step?.env?.RUN_JSON_TARGETS, { github }, functions)).toBe(runs)
})
it.each([
@@ -577,7 +625,7 @@ describe('.github/workflows run plans', () => {
},
})
expect(plan.errors).toEqual([])
- expect(plan.jobs['code-quality'].steps.find((step) => step.name === 'Save mypy cache')?.runs).toBe(runs)
+ expect(plan.jobs['code-quality']?.steps.find((step) => step.name === 'Save mypy cache')?.runs).toBe(runs)
})
it.each(['success', 'failure'] as const)(
@@ -597,8 +645,8 @@ describe('.github/workflows run plans', () => {
},
})
expect(plan.errors).toEqual([])
- expect(plan.jobs.build.steps.find((step) => step.name === 'Report sccache counters')?.runs).toBe(true)
- expect(plan.jobs.build.result).toBe(outcome)
+ expect(plan.jobs.build?.steps.find((step) => step.name === 'Report sccache counters')?.runs).toBe(true)
+ expect(plan.jobs.build?.result).toBe(outcome)
}
)