: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): route backend ci on github and relay the depot verdict (#100981)
Raúl Negrón-Otero3884b58528e7
diff --git a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md b/.agents/skills/depot-ci/references/posthog-check-run-semantics.mdindex 5aa38c8c0e3c..52e43efb5cfa 100644--- a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md+++ b/.agents/skills/depot-ci/references/posthog-check-run-semantics.md@@ -54,9 +54,13 @@ Depot names each check `<workflow name> / <job name>`. GitHub Actions names it `Matrix jobs differ: GitHub Actions posts one check per cell and appends the cell to the name, Depot posts one check for the whole job. Depot also posts internal expansion checks named `<file>:<job key>:_dynamicMatrix` for matrices built from `fromJSON`.+## When a check run appears++Depot creates a job's check run when it resolves the job, not when it creates the run: a job that starts gets its check in the same second as Depot's own `started_at` for the job, and a job that is skipped gets a `skipped` check when its dependencies settle. A job behind a long dependency chain therefore has no check run at all until it starts. Measured 2026-09-17 on three runs of `Backend CI on Depot` (for example run `bbtwxmr3b5`): the first job's check appeared 53 to 65 seconds after the run was created, and the gate job's check appeared 21 minutes later, when the matrix finished. GitHub Actions differs: it posts every job's check as `queued` when the run is created. A poller that treats "no check run yet" as "the run does not exist" is wrong on Depot; poll the first job in the `needs` graph to learn whether Depot picked the event up, and the gate to learn the verdict.+## Reruns-Retrying a failed Depot job updates the existing check run: same check run id, new timestamps and conclusion. GitHub Actions instead creates a fresh check run per attempt and leaves the old one behind, which is why a superseded GitHub Actions run can show a stale red check beside a green one of the same name. Read the latest check run per name when you script against either engine.+Retrying a failed Depot job creates a new check run with the same name and leaves the failed one behind (measured 2026-09-17 with `depot ci retry --failed` on run `jb7zh5rvnk`: the retried cell got check run `105270302262` while `105262890457` stayed `completed/failure`; only `filter=all` on the check-runs API lists both). GitHub Actions does the same per attempt, which is why a superseded run can show a stale red check beside a green one of the same name. Read the latest check run per name when you script against either engine: the API's default `filter=latest` already returns only the newest, and `max_by(.id)` does the same on a full listing. Two details matter when the read decides something: a GitHub Actions rerun queues a fresh check run for every job before any of them runs, so a script that wants the last verdict filters on `status == "completed"` before it takes the newest; and the check-runs API lists every pull request's checks for a head SHA, so a script that acts for one pull request filters on `pull_requests[].number` too (both engines populate it; measured 2026-09-17 on the throwaway and the stack heads).## Depot CI CLI recipesdiff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 4c4bb74e6e76..1b8a17ff2954 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -1,6 +1,6 @@-# Depot CI shadow of .github/workflows/ci-backend.yml. Lives under .depot/ so-# GitHub Actions ignores it; only Depot CI parses this file. Statuses posted-# from here are non-blocking; canonical is the authoritative signal.+# Depot CI copy of .github/workflows/ci-backend.yml. Lives under .depot/ so+# GitHub Actions ignores it; only Depot CI parses this file. Canonical's required+# `Django Tests Pass` relays this workflow's gate for the events routed here.## Apples-to-apples is the whole point — keep action pins, env vars, runner# sizes, and pytest flags in sync with the canonical workflow. A drift-check@@ -8,8 +8,10 @@# changes without a matching depot bump.## Intentional deltas vs canonical (everything else is kept apples-to-apples):-# - The `sample` job waits for GitHub Actions to hand the event off and exposes `sampled`-# and `side_effects`, both true only when GitHub Actions handed the tests to this engine.+# - The `wait-for-handoff` job waits for GitHub Actions to hand the event off and exposes+# `handed_off`, true only when GitHub Actions handed the tests to this engine. Canonical's+# `Django Tests Pass` gate then relays this workflow's gate verdict. Neither the hand-off+# job nor the relay has a counterpart here.# - runs-on: depot-* labels instead of ubuntu-latest# - action paths: ./.depot/actions/... instead of ./.github/actions/... (pnpm-install,# setup-sqlx-cli, setup-python-cached, setup-uv, setup-turbo, and paths-filter mirror@@ -64,7 +66,7 @@# status remains optional.# - events_json variants: gated on the test-new-events-schema label only; canonical also# doubles the matrices on workflow_dispatch, but shadow dispatches stay legacy-only so-# trial runs do the same work as sampled PR runs+# trial runs do the same work as handed-off PR runs# - per-segment split plans (.test_durations.core/.temporal): the restore steps mirror# canonical but miss until the depot timing refresher saves those files to Depot Cache;# shards fall back to the union .test_durations@@ -72,18 +74,19 @@# so shared keys with canonical (schema, uv, pnpm) do not collide# - hypothesis constants cache: the restore and save steps mirror canonical verbatim, but the# save only fires on master test-matrix runs and the shadow skips those, so the Depot Cache-# entry only exists after a master workflow_dispatch. Sampled PR shards run cold (they rebuild-# the pool, as canonical did before this cache existed) until then: bounded, documented, and-# harmless because the shadow never gates merges.+# entry only exists after a master workflow_dispatch. Routed PR shards run cold (they rebuild+# the pool, as canonical did before this cache existed) until then: bounded and documented.# - GITHUB_TOKEN / OTEL_SERVICE_NAME neutralized (ambient on Depot, not on GHA)# - GitHub App tokens: the mint steps' vars.* / secrets.* resolve from Depot's store, not# GitHub's. A name missing there makes the setup-action mints (continue-on-error) fall# back to the ambient GITHUB_TOKEN, the Depot Code Access installation token that every# Depot CI job across repos shares, and fails the paths-filter mint outright. Mints whose-# only consumer is a stripped side effect (migration-risk check run, OpenAPI auto-commit,-# snapshot commit, telemetry) are stripped with it.-# - `depot ci run` fires with event_name `api`; the sample gate treats it like-# workflow_dispatch. Depot caps an inline workflow at 64 KiB, which this file exceeds, so+# only consumer is a stripped side effect (OpenAPI auto-commit, snapshot commit,+# telemetry) are stripped with it. The migration-risk check run is published here+# because stamphog waits for it on every pull request.+# - `depot ci run` fires with event_name `api`; the hand-off wait treats it like+# workflow_dispatch: it runs only when GitHub Actions already handed the commit off.+# Depot caps an inline workflow at 64 KiB, which this file exceeds, so# trial a branch with `depot ci dispatch --workflow ci-backend.yml --ref <branch>` instead.# - Three data-modeling tests deselected (Depot-only MinIO 403 quarantine)# - COMPOSE_PROJECT_NAME pinned to posthog because bin/wait-for-docker filters by that@@ -103,9 +106,8 @@# - Test durations restored from Depot Cache (posthog-test-durations- prefix), refreshed by# .depot/workflows/ci-backend-update-test-timing.yml, so shard counts match GitHub Actions.# Committed .test_durations is the fallback.-# - master (push) runs only check-migrations to prime the shared schema cache; the-# test matrices are skipped on master (canonical runs them). Sampled source PRs and-# dispatches run the full graph — that is where the apples-to-apples comparison happens.+# - No push trigger: canonical primes the shared schema cache on master, and Depot Cache+# serves both engines. The `github.event_name != 'push'` guards stay to mirror canonical.# Trunk merge-queue PRs are excluded because they would repeat a source PR's trial run.# - Fresh-master cache waiting is canonical-only: it waits on the GitHub Actions# warmer, which cannot signal readiness for Depot's separate cache channel.@@ -114,19 +116,16 @@## Shards derive from .test_durations (Amdahl), restored from Depot Cache (else committed);# .depot/workflows/ci-backend-update-test-timing.yml keeps that cache fresh.-name: '[optional, does not block merge] Backend CI'-# OPTIONAL, non-blocking shadow of canonical Backend CI: its statuses must never gate-# merging (hence the "[optional, does not block merge]" name prefix). Each event runs on-# exactly one engine, and GitHub Actions picks it. The `sample` job waits for the+name: Backend CI on Depot+# Depot CI copy of canonical Backend CI. Branch protection requires only canonical's+# `Django Tests Pass`, which relays this workflow's gate when the event ran here. Each event runs on+# exactly one engine, and GitHub Actions picks it. The `wait-for-handoff` job waits for the# `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. Manual triggers always run here.+# workflow cascades off otherwise. A manual run needs that check on its commit too.# 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:- push:- branches:- - masterworkflow_dispatch:inputs:clickhouseServerVersion:@@ -140,7 +139,7 @@ on:# `no-ci` label silences the workflow on a draft entirely. No# labeled/unlabeled triggers, so a label takes effect from the next push# or from ready_for_review. Every event, merge-queue PRs included, runs here- # only when GitHub Actions hands it off (see the `sample` job).+ # only when GitHub Actions hands it off (see the `wait-for-handoff` job).types: [opened, synchronize, reopened, ready_for_review]concurrency:# PRs: one active run per branch, cancel stale. Push: per-SHA so master@@ -203,21 +202,20 @@ jobs:# GitHub Actions alone decides which engine runs an event. Every other job here# needs this one, so Depot CI runs nothing GitHub Actions did not hand off, and the# tests and their side effects never run on both engines.- sample:+ wait-for-handoff:if: >-github.event_name != 'pull_request'|| github.event.pull_request.draft != true|| !contains(github.event.pull_request.labels.*.name, 'no-ci')runs-on: depot-ubuntu-24.04timeout-minutes: 15- name: '[optional, does not block merge] Wait for GitHub Actions to hand off backend tests'+ name: Wait for GitHub Actions to hand off backend tests# Depot scopes the ambient token by this block, and the workflow-level block has no# `checks`, so without it the check-runs read below answers 403.permissions:checks: readoutputs:- sampled: ${{ steps.handoff.outputs.handed_off }}- side_effects: ${{ steps.handoff.outputs.handed_off }}+ handed_off: ${{ steps.handoff.outputs.handed_off }}steps:- name: Wait for the hand-off check from GitHub Actionsid: handoff@@ -230,6 +228,9 @@ jobs:# A no-ci draft marked ready keeps its SHA, so its earlier skipped hand-off# check is still on the commit. Only a check that started after this event counts.EVENT_AT: ${{ github.event.pull_request.updated_at }}+ # Two open PRs can share a head SHA, so only this PR's hand-off counts.+ # A manual run has no PR and accepts the newest hand-off from any PR.+ PR_NUMBER: ${{ github.event.pull_request.number }}# Must match the job name in .github/workflows/ci-backend.yml.HANDOFF_CHECK: Hand off backend tests to Depot CIGITHUB_ACTIONS_APP_ID: '15368'@@ -237,22 +238,27 @@ jobs:set -uo pipefailhanded_off=falsestate=absent- if [ "$EVENT" = workflow_dispatch ] || [ "$EVENT" = api ]; then- echo "::notice::A person started this run on Depot CI, so it runs here."- handed_off=true- elif [ "$IS_FORK" = true ]; then+ # A person's run does not wait: it runs only when GitHub Actions already handed+ # this commit off, so the tests never run on both engines.+ attempts=30+ [ "$EVENT" = pull_request ] || attempts=1+ 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" != 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.+ echo "::notice::$EVENT events never run on Depot CI."elseurl="https://api.github.com/repos/$REPO/commits/$SHA/check-runs?check_name=$(jq -rn --arg n "$HANDOFF_CHECK" '$n | @uri')&app_id=$GITHUB_ACTIONS_APP_ID"- for attempt in $(seq 1 60); do+ for attempt in $(seq 1 "$attempts"); do# curl rewrites the saved ETag empty on a 304, so promote it only after a 200.code=$(curl -s -o /tmp/handoff-body -w '%{http_code}' --max-time 15 --etag-compare /tmp/handoff-etag --etag-save /tmp/handoff-etag.new \-H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" "$url")case "$code" in200)mv /tmp/handoff-etag.new /tmp/handoff-etag- state=$(jq -r --arg since "$EVENT_AT" '[.check_runs[] | select((.started_at // "") >= $since)] | max_by(.id) | if . == null then "absent" elif .status == "completed" then .conclusion else .status end' /tmp/handoff-body)+ state=$(jq -r --arg since "$EVENT_AT" --argjson pr "${PR_NUMBER:-null}" '[.check_runs[] | select((.started_at // "") >= $since and ($pr == null or any(.pull_requests[]?; .number == $pr)))] | max_by(.id) | if . == null then "absent" elif .status == "completed" then .conclusion else .status end' /tmp/handoff-body);;304) ;;401|403) echo "::warning::check-runs API returned $code; cannot read the hand-off"; break ;;@@ -263,7 +269,7 @@ jobs:absent|queued|in_progress|pending|waiting|requested) ;;*) break ;;esac- [ "$attempt" -lt 60 ] && sleep 10+ [ "$attempt" -lt "$attempts" ] && sleep 20doneif [ "$handed_off" = true ]; thenecho "::notice::GitHub Actions handed the backend tests to Depot CI."@@ -275,10 +281,10 @@ jobs:# Job to decide if we should run backend ci# See .github/actions/paths-filter/README.md for filter semanticschanges:- # Root of the `needs` graph: skipped when `sample` says skip (or is itself skipped),+ # Root of the `needs` graph: skipped when `wait-for-handoff` saw no hand-off (or is itself skipped),# which cascades the whole workflow off.- needs: sample- if: needs.sample.outputs.sampled == 'true'+ needs: wait-for-handoff+ if: needs.wait-for-handoff.outputs.handed_off == 'true'runs-on: depot-ubuntu-24.04timeout-minutes: 5name: Determine need to run backend and migration checks@@ -368,6 +374,7 @@ jobs:# widening or fixing the script doesn't trigger# tests it controls.- 'products/*/package.json'+ - 'products/canvas/packages/canvas_builder/**'- bin/build-schema-latest-versions.py- bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py@@ -577,6 +584,9 @@ jobs:- 'services/mcp/src/tools/generated/**/*'- 'services/mcp/schema/generated-tool-definitions.json'- 'services/mcp/schema/tool-definitions-all.json'+ # Exec command reference templates - feed generate-exec-docs.ts+ - 'services/mcp/src/templates/sections/**/*'+ - 'services/mcp/schema/exec-command-reference.md'detect-snapshot-mode:name: Detect snapshot mode@@ -601,7 +611,7 @@ jobs:# Only needs pnpm + node — no Python, Docker, or services# Runs on depot for turbo remote cache access (cache status drives Django gating)turbo-discover:- needs: [sample, changes]+ needs: [wait-for-handoff, changes]# Not on master push: master only primes the schema cache; this cascades the matrices off.if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'runs-on: depot-ubuntu-24.04@@ -800,7 +810,7 @@ jobs:enable-cache: false- name: Snapshot the sharding plan for this run- if: ${{ needs.sample.outputs.side_effects == 'true' }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' }}# The timing caches float to their newest entry, so a re-run can shard# differently from attempt 1 and, under "re-run failed jobs", a failing# test can move to a shard that never re-runs while the gate goes green.@@ -873,7 +883,7 @@ jobs:# test-selection-verdict reads it instead of running the selector again. An# upload failure must not fail this job; the verdict regenerates the selection.continue-on-error: true- if: ${{ needs.sample.outputs.side_effects == 'true' && (always() && steps.select.outcome == 'success') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && steps.select.outcome == 'success') }}uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0with:name: select-tests-output@@ -1012,7 +1022,7 @@ jobs:turbo-tests:needs:[- sample,+ wait-for-handoff,changes,turbo-discover,prime-schema-cache,@@ -1191,7 +1201,7 @@ jobs:gh run download "$run_id" --repo "$GITHUB_REPOSITORY" --name test-durations --dir . \|| echo "::warning::Timing artifact of run $run_id unavailable, sharding without durations"- name: Download the run's sharding plan snapshot- if: ${{ needs.sample.outputs.side_effects == 'true' }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' }}# Same pinning as the Django job; falls back to the floating cache.id: pinned-plancontinue-on-error: true@@ -1201,7 +1211,7 @@ jobs:path: /tmp/test-durations-plan- name: Apply the pinned sharding plan- if: ${{ needs.sample.outputs.side_effects == 'true' && (steps.pinned-plan.outcome == 'success') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (steps.pinned-plan.outcome == 'success') }}shell: bashrun: |if [ ! -f /tmp/test-durations-plan/.test_durations ]; then@@ -1212,12 +1222,12 @@ jobs:echo "Sharding plan pinned to this run's snapshot"- name: Warn when a re-run reshards unpinned- if: ${{ needs.sample.outputs.side_effects == 'true' && (github.run_attempt != '1' && steps.pinned-plan.outcome != 'success') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (github.run_attempt != '1' && steps.pinned-plan.outcome != 'success') }}shell: bashrun: echo "::warning::Sharding-plan snapshot unavailable, this re-run reshards from the floating timing cache and may not re-execute tests that failed in earlier attempts"- name: Run product tests- continue-on-error: ${{ needs.sample.outputs.side_effects == 'true' }}+ continue-on-error: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' }}id: run-product-tests# --force: discover already decided this product needs testing, skip turbo cache# --log-order=stream: stream pytest output live instead of buffering until completion@@ -1254,8 +1264,8 @@ jobs:PYTEST_ADDOPTS: >---reuse-db--durations-path ../../.test_durations- ${{ needs.sample.outputs.side_effects == 'true' && github.ref == 'refs/heads/master' && '--store-durations' || '' }}- ${{ needs.sample.outputs.side_effects == 'true' && '--junitxml=junit-product.xml' || '' }}+ ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && github.ref == 'refs/heads/master' && '--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=xml:coverage.xml' || '' }}# turbo runs each product's backend:test with the product dir as CWD, so --cov=backend@@ -1316,7 +1326,7 @@ jobs:- name: Prepare product JUnit for Trunkid: prepare_product_junit- if: ${{ needs.sample.outputs.side_effects == 'true' && (always()) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always()) }}shell: bashenv:PRODUCT_FILTERS: ${{ matrix.filters }}@@ -1328,7 +1338,7 @@ jobs:- name: Quarantine gateid: quarantine_gatecontinue-on-error: true- if: ${{ needs.sample.outputs.side_effects == 'true' && (!cancelled() && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (!cancelled() && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true') }}uses: ./.github/actions/trunk-quarantine-gatewith:junit-paths: trunk-junit/junit-product-*.xml@@ -1336,12 +1346,12 @@ jobs:token: ${{ secrets.TRUNK_API_TOKEN }}- name: Fail on test failure- if: ${{ needs.sample.outputs.side_effects == 'true' && (!cancelled() && (steps.prepare_product_junit.outcome == 'failure' || (steps.run-product-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate.outcome != 'success')))) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (!cancelled() && (steps.prepare_product_junit.outcome == 'failure' || (steps.run-product-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate.outcome != 'success')))) }}shell: bashrun: exit 1- name: Stage product JUnit- if: ${{ needs.sample.outputs.side_effects == 'true' && (always()) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always()) }}shell: bashrun: |mkdir -p junit-staging@@ -1352,7 +1362,7 @@ jobs:- name: Upload product test resultsuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: ${{ needs.sample.outputs.side_effects == 'true' && (always()) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always()) }}with:name: product-junit-results-${{ strategy.job-index }}path: junit-staging/junit-product-*.xml@@ -1363,7 +1373,7 @@ jobs:uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0# Only the legacy-schema variant uploads durations — both schema variants run the# same test IDs, and two artifacts for the same tests would race in the merge.- if: ${{ needs.sample.outputs.side_effects == 'true' && (github.ref == 'refs/heads/master' && !matrix.new-events-schema) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (github.ref == 'refs/heads/master' && !matrix.new-events-schema) }}with:name: timing_data-Products-${{ strategy.job-index }}path: .test_durations@@ -1373,7 +1383,7 @@ jobs:- name: Stage product coverage# Rename each products/<name>/coverage.xml to <name>.xml so the product name# survives upload-artifact's least-common-ancestor path collapse.- if: ${{ needs.sample.outputs.side_effects == 'true' && (always() && github.event_name == 'pull_request') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && github.event_name == 'pull_request') }}shell: bashrun: |mkdir -p cov-staging@@ -1386,7 +1396,7 @@ jobs:- name: Upload product coverageuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0# always(): a failing test shard still has partial coverage worth reporting.- if: ${{ needs.sample.outputs.side_effects == 'true' && (always() && github.event_name == 'pull_request') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && github.event_name == 'pull_request') }}with:name: coverage-xml-${{ strategy.job-index }}path: cov-staging/*.xml@@ -1539,7 +1549,7 @@ jobs:# This job needs Docker + DB. Canonical master is checked out beside the comparison# branch so repository switches cannot disturb live Compose bind mounts.check-migrations:- needs: [sample, changes]+ needs: [wait-for-handoff, changes]# migration_replay is listed because it reaches files the others 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@@ -1703,11 +1713,85 @@ jobs:- name: Install python dependencies for this PRrun: |UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev- # Depot shadow: migration SQL-comment + risk-analysis-comment steps stripped.- # Keep the risk check itself so blocked migrations still fail the job.+ # The migration SQL preview and the CI report section stay stripped (see the+ # header). The check run is published, because stamphog waits for it on every+ # pull request and a routed PR would otherwise never get a verdict.- name: Run migration risk analysisif: github.event_name == 'pull_request'- run: python manage.py analyze_migration_risk --fail-on-blocked+ # A hang fails this step, which the publish below still reports as a verdict.+ timeout-minutes: 5+ run: python manage.py analyze_migration_risk --fail-on-blocked --output-json migration_analysis.json > migration_analysis.md 2>/dev/null++ - name: Get app token for Migration risk check+ # The posthog-tests app owns the check, so it lands in that app's own check+ # suite instead of under an arbitrary run. continue-on-error: a mint failure+ # must not redden migration validation; the publish step skips on an empty token.+ # !cancelled(): a superseded run leaves the verdict to the run that replaced it.+ if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false }}+ id: migration-risk-app-token+ continue-on-error: true+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1+ with:+ client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}+ private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}++ - name: Publish Migration risk check+ # Same contract as canonical: one completed `Migration risk` check on the head+ # commit for every pull request, with the stamphog marker first in the summary.+ # An analyzer crash publishes a failure, so consumers never wait forever.+ if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false && steps.migration-risk-app-token.outputs.token != '' }}+ env:+ GITHUB_TOKEN: ${{ steps.migration-risk-app-token.outputs.token }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ REPO: ${{ github.repository }}+ run: |+ if [ ! -f migration_analysis.json ]; then+ echo "No migration_analysis.json — analyzer didn't run; publishing failure check"+ jq -n \+ --arg name "Migration risk" \+ --arg head_sha "$HEAD_SHA" \+ '{name: $name, head_sha: $head_sha, status: "completed",+ conclusion: "failure",+ output: {title: "❌ Analyzer failed",+ summary: "<!-- stamphog:v1 [] -->\nMigration analyzer did not produce migration_analysis.json. Re-run the Backend CI job; if it keeps failing, inspect the analyzer step logs."}}' \+ | gh api "repos/$REPO/check-runs" --method POST --input -+ exit 0+ fi++ MAX_LEVEL=$(jq -r '.max_level // "none"' migration_analysis.json)++ case "$MAX_LEVEL" in+ "Safe") CONCLUSION=success; TITLE="✅ All migrations safe" ;;+ "Needs Review") CONCLUSION=neutral; TITLE="⚠️ Needs review" ;;+ "Blocked") CONCLUSION=failure; TITLE="❌ Blocked migrations" ;;+ "none"|"null")+ CONCLUSION=success+ TITLE="✅ No Django migrations to analyze"+ ;;+ *)+ echo "Unknown max_level '$MAX_LEVEL' — publishing failure"+ CONCLUSION=failure+ TITLE="❌ Unknown analyzer output"+ ;;+ esac++ # Stamphog scopes its deny-list bypass to exactly the files the analyzer+ # classified, so the marker stays first and survives truncation.+ ANALYZED_PATHS=$(jq -c '[.migrations[].file_path | select(. != null)]' migration_analysis.json 2>/dev/null || echo '[]')+ MARKER="<!-- stamphog:v1 ${ANALYZED_PATHS} -->"+ REPORT_BODY=$([ -s migration_analysis.md ] && head -c 59000 migration_analysis.md || echo "See the workflow log")+ SUMMARY=$(printf '%s\n%s' "$MARKER" "$REPORT_BODY")++ jq -n \+ --arg name "Migration risk" \+ --arg head_sha "$HEAD_SHA" \+ --arg conclusion "$CONCLUSION" \+ --arg title "$TITLE" \+ --arg summary "$SUMMARY" \+ '{name: $name, head_sha: $head_sha, status: "completed",+ conclusion: $conclusion,+ output: {title: $title, summary: $summary}}' \+ | gh api "repos/$REPO/check-runs" --method POST --input -- name: Run migrations for this PRrun: |# Run Django migrations first (excluding managed=False models)@@ -1755,7 +1839,7 @@ jobs:gunzip -t schema.sql.gz- name: Upload migrated schema artifact- if: ${{ needs.sample.outputs.side_effects == 'true' && (github.event_name == 'push') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (github.event_name == 'push') }}uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0with:name: migrated-schema@@ -2221,7 +2305,15 @@ jobs:echo "include=$include" >> "$GITHUB_OUTPUT"echo "Django matrix size: $(jq -r 'length' <<< "$include") (mode=$MODE)"django:- needs: [sample, changes, turbo-discover, detect-snapshot-mode, get_clickhouse_versions, build_django_matrix]+ needs:+ [+ wait-for-handoff,+ changes,+ turbo-discover,+ detect-snapshot-mode,+ get_clickhouse_versions,+ build_django_matrix,+ ]# Run legacy pytest if:# 1. Legacy code directly changed (ee/, posthog/)# 2. OR product changes affect legacy code (turbo-discover outputs run_legacy=true)@@ -2239,7 +2331,7 @@ jobs:needs.turbo-discover.outputs.run_legacy == 'true' ||(needs.turbo-discover.result != 'success' && needs.turbo-discover.result != 'skipped'))# increase for tmate testing- # 45 to match canonical; the shadow is non-blocking so no deploy-gate coupling.+ # 45 to match canonical.timeout-minutes: 45name: Django tests – ${{ matrix.segment }}${{ matrix.compat && ' compat' || '' }} (persons-on-events ${{ (matrix.segment == 'Core' && !matrix.person-on-events && !matrix.compat) && 'on' || 'off' }}, events schema ${{ matrix.new-events-schema && 'json' || 'legacy' }}), Py ${{ matrix.python-version }}, ${{ matrix.clickhouse-server-image }} (${{matrix.group}}/${{ matrix.concurrency }})# Match canonical's runner size. The shadow restores the same master-primed@@ -2599,7 +2691,7 @@ jobs:docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" || trueecho "==================================="- name: Download the run's sharding plan snapshot- if: ${{ needs.sample.outputs.side_effects == 'true' }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' }}# Pin every attempt to the plan turbo-discover snapshotted (rationale on# that step); a missing snapshot falls back to the floating caches above.id: pinned-plan@@ -2610,7 +2702,7 @@ jobs:path: /tmp/test-durations-plan- name: Apply the pinned sharding plan- if: ${{ needs.sample.outputs.side_effects == 'true' && (steps.pinned-plan.outcome == 'success') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (steps.pinned-plan.outcome == 'success') }}shell: bashrun: |if [ ! -f /tmp/test-durations-plan/.test_durations ]; then@@ -2626,12 +2718,12 @@ jobs:echo "Sharding plan pinned to this run's snapshot"- name: Warn when a re-run reshards unpinned- if: ${{ needs.sample.outputs.side_effects == 'true' && (github.run_attempt != '1' && steps.pinned-plan.outcome != 'success') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (github.run_attempt != '1' && steps.pinned-plan.outcome != 'success') }}shell: bashrun: echo "::warning::Sharding-plan snapshot unavailable, this re-run reshards from the floating timing caches and may not re-execute tests that failed in earlier attempts"- name: Run Core tests- continue-on-error: ${{ needs.sample.outputs.side_effects == 'true' }}+ continue-on-error: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' }}id: run-core-testsif: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' }}env:@@ -2738,7 +2830,7 @@ jobs:--ignore=posthog/test/repo_invariants \"${full_ignores[@]}" \--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \- --durations=1000 --durations-min=1.0 ${{ needs.sample.outputs.side_effects == 'true' && '--store-durations' || '' }} \+ --durations=1000 --durations-min=1.0 ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && '--store-durations' || '' }} \--pytest-durations=100 \--splitting-algorithm="$SPLITTING_ALGORITHM" \"${SPLIT_GRANULARITY[@]}" \@@ -2778,7 +2870,7 @@ jobs:docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" || trueecho "==================================="- name: Run Temporal tests- continue-on-error: ${{ needs.sample.outputs.side_effects == 'true' }}+ continue-on-error: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' }}id: run-temporal-testsif: ${{ needs.changes.outputs.backend == 'true' && matrix.segment == 'Temporal' }}shell: 'signal-fanout bash --noprofile --norc -eo pipefail {0}'@@ -2836,7 +2928,7 @@ jobs:# no protection beyond the job timeout.pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/signals/backend/emission -m "not async_migrations" \--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \- --durations=100 --durations-min=1.0 ${{ needs.sample.outputs.side_effects == 'true' && '--store-durations' || '' }} \+ --durations=100 --durations-min=1.0 ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && '--store-durations' || '' }} \--pytest-durations=100 \--splitting-algorithm="$SPLITTING_ALGORITHM" \"${SPLIT_GRANULARITY[@]}" \@@ -2881,7 +2973,7 @@ jobs:- name: Upload test resultsuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: ${{ needs.sample.outputs.side_effects == 'true' && (always()) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always()) }}with:# Re-run attempts suffix the name: a same-name upload supersedes attempt 1's# artifact, and the timing reporter needs both to pair a re-run recovery@@ -2893,7 +2985,7 @@ jobs:- name: Archive email rendersuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: ${{ needs.sample.outputs.side_effects == 'true' && (needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' && !matrix.person-on-events && !matrix.new-events-schema && !matrix.compat) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (needs.changes.outputs.backend == 'true' && matrix.segment == 'Core' && !matrix.person-on-events && !matrix.new-events-schema && !matrix.compat) }}with:name: email_renders-${{ github.sha }}-${{ github.run_attempt }}-${{ matrix.segment }}-${{ matrix.person-on-events }}-${{ matrix.group }}path: posthog/tasks/test/__emails__@@ -2901,7 +2993,7 @@ jobs:- name: Upload core coverageuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- if: ${{ needs.sample.outputs.side_effects == 'true' && (always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && github.event_name == 'pull_request' && needs.turbo-discover.outputs.mode != 'selected' && matrix.segment == 'Core') }}with:name: coverage-core-${{ strategy.job-index }}path: coverage-core.xml@@ -2912,7 +3004,7 @@ jobs:- name: Upload updated timing data as artifactsuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0# Upload on master, or on PRs that change timing/sharding scripts (for validation)- if: ${{ needs.sample.outputs.side_effects == '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' && ((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) }}with:name: timing_data-${{ matrix.segment }}-${{ matrix.group }}path: .test_durations@@ -2924,7 +3016,7 @@ jobs:# the PR head ref, which may predate the script. Without it the uploader keeps reading# .github/CODEOWNERS, as it did before.- name: Build the Trunk ownership map- if: ${{ needs.sample.outputs.side_effects == 'true' && (!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') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (!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') }}shell: bashrun: |script=.github/scripts/trunk-codeowners.sh@@ -2933,7 +3025,7 @@ jobs:- name: Quarantine gate (Core)id: quarantine_gate_corecontinue-on-error: true- if: ${{ needs.sample.outputs.side_effects == 'true' && (!cancelled() && matrix.segment == 'Core' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (!cancelled() && matrix.segment == 'Core' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true') }}uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2with:junit-paths: junit-core.xml,junit-core-retry-failures.xml@@ -2946,7 +3038,7 @@ jobs:- name: Quarantine gate (Temporal)id: quarantine_gate_temporalcontinue-on-error: true- if: ${{ needs.sample.outputs.side_effects == 'true' && (!cancelled() && matrix.segment == 'Temporal' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true') }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (!cancelled() && matrix.segment == 'Temporal' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true') }}uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2with:junit-paths: junit-temporal.xml,junit-temporal-retry-failures.xml@@ -2957,7 +3049,7 @@ jobs:token: ${{ secrets.TRUNK_API_TOKEN }}- name: Fail on test failure- if: ${{ needs.sample.outputs.side_effects == 'true' && (!cancelled() && ((steps.run-core-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate_core.outcome != 'success')) || (steps.run-temporal-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate_temporal.outcome != 'success')))) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (!cancelled() && ((steps.run-core-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate_core.outcome != 'success')) || (steps.run-temporal-tests.outcome == 'failure' && (vars.TRUNK_QUARANTINE_ENABLED != 'true' || steps.quarantine_gate_temporal.outcome != 'success')))) }}shell: bashrun: exit 1@@ -3053,7 +3145,7 @@ jobs:django_tests:needs:[- sample,+ wait-for-handoff,changes,get_clickhouse_versions,build_django_matrix,@@ -3066,13 +3158,13 @@ jobs:detect-snapshot-mode,repo-checks,]- name: '[optional, does not block merge] Django Tests Pass'+ name: Django Tests Pass on Depotruns-on: depot-ubuntu-24.04timeout-minutes: 8# !cancelled() collates skipped/failed matrix jobs without reporting failure on a- # superseded run (mirrors canonical); gated on the sampling result so it doesn't- # spin up a lone runner when this run was sampled out (or the shadow is off).- if: ${{ !cancelled() && needs.sample.outputs.sampled == 'true' }}+ # superseded run (mirrors canonical); gated on the hand-off so it doesn't+ # spin up a lone runner when GitHub Actions kept this event.+ if: ${{ !cancelled() && needs.wait-for-handoff.outputs.handed_off == 'true' }}steps:- name: Summarize dependency resultsrun: |@@ -3093,7 +3185,7 @@ jobs:} | tee -a "$GITHUB_STEP_SUMMARY"- name: Download shard JUnit results- if: ${{ needs.sample.outputs.side_effects == 'true' && (always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')) }}continue-on-error: trueuses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0with:@@ -3101,7 +3193,7 @@ jobs:path: /tmp/junit-gate/- name: Keep only each shard's latest attempt- if: ${{ needs.sample.outputs.side_effects == 'true' && (always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')) }}+ if: ${{ needs.wait-for-handoff.outputs.handed_off == 'true' && (always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')) }}continue-on-error: truerun: |cd /tmp/junit-gate 2>/dev/null || exit 0@@ -3114,10 +3206,7 @@ jobs:done- name: Check dependency results- env:- SIDE_EFFECTS: ${{ needs.sample.outputs.side_effects }}run: |- if [ "$SIDE_EFFECTS" = "true" ]; then# Per-test failure rollup, emitted from THIS step because GitHub only# auto-expands the failed step in the log view. Best-effort via `|| true`# so a parser hiccup never changes the verdict computed below.@@ -3181,8 +3270,6 @@ jobs:print(f"::error {loc}title={title}::{body}")PY- fi-check_required_result() {local label="$1"local result="$2"@@ -3203,7 +3290,7 @@ jobs:check_required_result "Django test matrix" "${{ needs.django.result }}"check_required_result "Migration checks" "${{ needs.check-migrations.result }}"check_required_result "OpenAPI type checks" "${{ needs.check-openapi-types.result }}"- check_required_result "Hand-off wait" "${{ needs.sample.result }}"+ check_required_result "Hand-off wait" "${{ needs.wait-for-handoff.result }}"check_required_result "Repo checks" "${{ needs.repo-checks.result }}"check_required_result "Turbo discover" "${{ needs.turbo-discover.result }}"check_required_result "Product test matrix build" "${{ needs.build-product-test-matrix.result }}"@@ -3211,4 +3298,4 @@ jobs:check_required_result "Snapshot mode detection" "${{ needs.detect-snapshot-mode.result }}"echo "All backend and product checks passed."- # Depot shadow: calculate-running-time is omitted so shadow runs are not recorded as canonical CI data.+ # calculate-running-time is omitted so Depot runs are not recorded as canonical CI data.diff --git a/.github/scripts/ci_backend_route.py b/.github/scripts/ci_backend_route.pynew file mode 100644index 000000000000..29741e5c30e4--- /dev/null+++ b/.github/scripts/ci_backend_route.py@@ -0,0 +1,183 @@+#!/usr/bin/env python3+"""Decide which CI engine runs a Backend CI event: GitHub Actions or Depot CI.++Only GitHub Actions runs this script. Its answer drives the `Hand off backend tests+to Depot CI` job, which Depot CI waits for before it runs anything, so Depot never+routes on its own and the tests never run on both engines. Once that job has concluded+for a commit, every later run of the same commit repeats its answer, whatever the+percent or the labels say by then. A read of that record that keeps failing fails the+run, so nothing is routed anywhere.+"""++import os+import sys+import json+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass+from typing import Any++LABEL_FORCE_GITHUB = "ci-backend-github"+LABEL_FORCE_DEPOT = "ci-backend-depot"+PERCENT_VARIABLE = "CI_BACKEND_DEPOT_PERCENT"+# The Trunk merge queue tests each batch through a draft pull request on this branch.+MERGE_QUEUE_PREFIX = "trunk-merge/"+HANDOFF_CHECK = "Hand off backend tests to Depot CI"+GITHUB_ACTIONS_APP_ID = 15368+ENGINE_BY_HANDOFF_CONCLUSION = {"success": "depot", "skipped": "github"}+API_ROOT = "https://api.github.com"+API_ATTEMPTS = 3+API_BACKOFF_SECONDS = 5+++class HandoffReadError(RuntimeError):+ """The durable routing record could not be read, so the event must not be routed."""+++@dataclass(frozen=True)+class Decision:+ engine: str+ reason: str+++def parse_percent(raw: str | None) -> int:+ value = raw.strip() if raw is not None else ""+ # isdecimal() accepts digits int() rejects, and int() refuses very long strings.+ if not value.isascii() or not value.isdecimal():+ return 0+ try:+ return min(int(value), 100)+ except ValueError:+ return 0+++def handoff_conclusion(check_runs: list[dict], pr_number: int) -> str | None:+ """The hand-off conclusion that already committed an engine to this commit for this pull request.++ A `success` means Depot ran the tests and a `skipped` means GitHub Actions did, and+ neither is undone by a later attempt that was cancelled or re-routed, so the first+ of those found wins over anything newer. GitHub queues a fresh check for every+ attempt, so only concluded ones count, and the API lists every pull request's checks+ for a head SHA, so only this one's count.+ """+ conclusions = [+ run.get("conclusion")+ for run in sorted(check_runs, key=lambda run: run["id"], reverse=True)+ if run.get("status") == "completed"+ and any(pr.get("number") == pr_number for pr in run.get("pull_requests") or [])+ ]+ for committed in ENGINE_BY_HANDOFF_CONCLUSION:+ if committed in conclusions:+ return committed+ return conclusions[0] if conclusions else None+++def decide(+ event: str,+ percent: int,+ pr_number: int | None,+ labels: list[str],+ is_fork: bool,+ is_draft: bool,+ prior_handoff: str | None = None,+ head_ref: str = "",+) -> Decision:+ if event != "pull_request":+ return Decision("github", f"{event} events stay on GitHub Actions")+ if head_ref.startswith(MERGE_QUEUE_PREFIX):+ return Decision("github", "merge queue batches stay on GitHub Actions")+ prior_engine = ENGINE_BY_HANDOFF_CONCLUSION.get(prior_handoff or "")+ if prior_engine:+ return Decision(prior_engine, f"an earlier run of this commit chose {prior_engine}")+ if LABEL_FORCE_GITHUB in labels:+ return Decision("github", f"label {LABEL_FORCE_GITHUB}")+ if is_fork:+ return Decision("github", "fork pull requests never run on Depot")+ if is_draft and "no-ci" in labels:+ return Decision("github", "no-ci drafts skip on GitHub Actions and run nowhere else")+ if LABEL_FORCE_DEPOT in labels:+ return Decision("depot", f"label {LABEL_FORCE_DEPOT}")+ if pr_number is None:+ return Decision("github", "no pull request number to hash")+ bucket = pr_number % 100+ if bucket < percent:+ return Decision("depot", f"bucket {bucket} < {percent}%")+ return Decision("github", f"bucket {bucket} >= {percent}%")+++def fetch_handoff_checks(repo: str, sha: str, token: str, *, opener: Any = None) -> list[dict]:+ """GET this commit's hand-off check runs, retrying transient failures only.++ 5xx and network errors are worth another attempt; 4xx is not, because with an+ empty rate-limit bucket or a missing permission a retry only spends more of it.+ """+ query = urllib.parse.urlencode(+ {"check_name": HANDOFF_CHECK, "app_id": GITHUB_ACTIONS_APP_ID, "filter": "all", "per_page": 100}+ )+ url = f"{API_ROOT}/repos/{repo}/commits/{sha}/check-runs?{query}"+ request = urllib.request.Request(+ url,+ headers={+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ "Authorization": f"Bearer {token}",+ },+ )+ do_open = opener or urllib.request.urlopen+ for attempt in range(1, API_ATTEMPTS + 1):+ try:+ with do_open(request, timeout=30) as response:+ return json.loads(response.read().decode("utf-8"))["check_runs"]+ except urllib.error.HTTPError as error:+ if error.code < 500 or attempt == API_ATTEMPTS:+ raise HandoffReadError(f"GET {url} failed with {error.code}") from error+ except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, KeyError, TypeError) as error:+ if attempt == API_ATTEMPTS:+ raise HandoffReadError(f"GET {url} failed: {error}") from error+ sys.stdout.write(f"::warning::Cannot read the earlier hand-off yet ({attempt}/{API_ATTEMPTS})\n")+ time.sleep(API_BACKOFF_SECONDS * attempt)+ raise HandoffReadError(f"GET {url} exhausted {API_ATTEMPTS} attempts")+++def main() -> int:+ env = os.environ+ event = env.get("EVENT", "")+ pr_raw = env.get("PR_NUMBER", "")+ pr_number = int(pr_raw) if pr_raw.isdigit() else None+ is_fork = env.get("IS_FORK", "false") == "true"+ labels = json.loads(env.get("LABELS") or "null") or []+ # Until the rollout variable exists, only a label can route a commit, so every other+ # pull request skips the read and its API call, and cannot fail on it.+ routing_possible = bool(env.get("PERCENT")) or bool({LABEL_FORCE_DEPOT, LABEL_FORCE_GITHUB} & set(labels))+ prior_handoff = None+ if event == "pull_request" and pr_number is not None and not is_fork and routing_possible:+ try:+ prior_handoff = handoff_conclusion(+ fetch_handoff_checks(env["REPO"], env["SHA"], env["GH_TOKEN"]), pr_number+ )+ except HandoffReadError as error:+ sys.stdout.write(f"::error::Cannot read the earlier hand-off, so this event is not routed: {error}\n")+ return 1+ sys.stdout.write(f"::notice::Earlier hand-off on this commit: {prior_handoff or 'none'}\n")+ decision = decide(+ event=event,+ percent=parse_percent(env.get("PERCENT")),+ pr_number=pr_number,+ labels=labels,+ is_fork=is_fork,+ is_draft=env.get("IS_DRAFT", "false") == "true",+ prior_handoff=prior_handoff,+ head_ref=env.get("HEAD_REF", ""),+ )+ sys.stdout.write(f"::notice::Backend CI engine: {decision.engine} ({decision.reason})\n")+ output_path = env.get("GITHUB_OUTPUT")+ if output_path:+ with open(output_path, "a", encoding="utf-8") as handle:+ handle.write(f"engine={decision.engine}\nreason={decision.reason}\n")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/scripts/test_ci_backend_route.py b/.github/scripts/test_ci_backend_route.pynew file mode 100644index 000000000000..68f645e09cf4--- /dev/null+++ b/.github/scripts/test_ci_backend_route.py@@ -0,0 +1,217 @@+import json+import urllib.error+import importlib.util+from collections.abc import Sequence+from pathlib import Path+from typing import Any++import pytest++SCRIPT_PATH = Path(__file__).with_name("ci_backend_route.py")+SPEC = importlib.util.spec_from_file_location("ci_backend_route", SCRIPT_PATH)+assert SPEC is not None+assert SPEC.loader is not None+route = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(route)+++def pr(+ percent: int = 25, number: int | None = 124, labels: Sequence[str] = (), fork: bool = False, draft: bool = False+) -> Any:+ return route.decide("pull_request", percent, number, list(labels), fork, draft)+++ "number,percent,expected",+ [(124, 25, "depot"), (125, 25, "github"), (100, 0, "github"), (199, 100, "depot"), (0, 1, "depot")],+)+def test_bucket_is_pr_number_mod_100(number: int, percent: int, expected: str) -> None:+ assert pr(number=number, percent=percent).engine == expected+++ "labels,fork,draft,expected",+ [+ (["ci-backend-github"], False, False, "github"),+ (["ci-backend-depot"], False, False, "depot"),+ (["ci-backend-depot", "ci-backend-github"], False, False, "github"),+ (["ci-backend-depot"], True, False, "github"),+ (["ci-backend-depot", "no-ci"], False, True, "github"),+ (["no-ci"], False, False, "depot"),+ ],+)+def test_overrides(labels: list[str], fork: bool, draft: bool, expected: str) -> None:+ assert pr(labels=labels, fork=fork, draft=draft).engine == expected++[email protected]("event", ["workflow_dispatch", "push", "schedule", "merge_group"])+def test_non_pull_request_events_stay_on_github(event: str) -> None:+ assert route.decide(event, 100, None, ["ci-backend-depot"], False, False, "success").engine == "github"+++def test_merge_queue_batches_stay_on_github() -> None:+ queued = route.decide("pull_request", 100, 124, ["ci-backend-depot"], False, True, "success", "trunk-merge/pr-1/x")+ assert queued.engine == "github"+ assert route.decide("pull_request", 100, 124, [], False, False, None, "feature/trunk-merge").engine == "depot"+++def test_missing_pr_number_stays_on_github() -> None:+ assert pr(number=None, percent=100).engine == "github"+++ "prior,labels,percent,expected",+ [+ ("success", ["ci-backend-github"], 0, "depot"),+ ("skipped", ["ci-backend-depot"], 100, "github"),+ ("cancelled", ["ci-backend-depot"], 0, "depot"),+ (None, [], 100, "depot"),+ ],+)+def test_earlier_run_of_the_commit_wins(prior: str | None, labels: list[str], percent: int, expected: str) -> None:+ assert route.decide("pull_request", percent, 124, labels, False, False, prior).engine == expected+++def check(run_id: int, status: str, conclusion: str | None, pr_number: int = 124) -> dict[str, Any]:+ return {"id": run_id, "status": status, "conclusion": conclusion, "pull_requests": [{"number": pr_number}]}+++ "check_runs,expected",+ [+ ([check(1, "completed", "success"), check(2, "queued", None)], "success"),+ ([check(1, "completed", "success"), check(2, "completed", "cancelled")], "success"),+ ([check(1, "completed", "success"), check(2, "completed", "skipped")], "success"),+ ([check(1, "completed", "skipped"), check(2, "completed", "cancelled")], "skipped"),+ ([check(1, "completed", "cancelled"), check(2, "completed", "failure")], "failure"),+ ([check(1, "completed", "success", pr_number=125)], None),+ ([{"id": 1, "status": "completed", "conclusion": "success", "pull_requests": []}], None),+ ([], None),+ ],+)+def test_handoff_conclusion_keeps_the_engine_that_already_ran_this_pull_request(+ check_runs: list[dict[str, Any]], expected: str | None+) -> None:+ assert route.handoff_conclusion(check_runs, 124) == expected+++class FakeResponse:+ def __init__(self, payload: Any) -> None:+ self.payload = payload++ def read(self) -> bytes:+ return json.dumps(self.payload).encode()++ def __enter__(self) -> "FakeResponse":+ return self++ def __exit__(self, *exc: object) -> None:+ return None+++def http_error(code: int) -> urllib.error.HTTPError:+ return urllib.error.HTTPError("https://api.github.com", code, "boom", {}, None) # type: ignore[arg-type]+++def opener_from(answers: list[Any]) -> Any:+ def opener(request: Any, timeout: int) -> Any:+ answer = answers.pop(0)+ if isinstance(answer, Exception):+ raise answer+ return FakeResponse(answer)++ return opener+++def test_fetch_retries_a_server_error_then_returns_the_checks(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(route.time, "sleep", lambda seconds: None)+ checks = [check(1, "completed", "success")]+ opener = opener_from([http_error(502), {"check_runs": checks}])+ assert route.fetch_handoff_checks("PostHog/posthog", "abc", "t", opener=opener) == checks+++ "answers,attempts_used",+ [([http_error(403)], 1), ([http_error(503)] * 3, 3), ([urllib.error.URLError("down")] * 3, 3)],+)+def test_fetch_fails_closed_without_retrying_client_errors(+ answers: list[Exception], attempts_used: int, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(route.time, "sleep", lambda seconds: None)+ remaining = list(answers)+ with pytest.raises(route.HandoffReadError):+ route.fetch_handoff_checks("PostHog/posthog", "abc", "t", opener=opener_from(remaining))+ assert len(answers) - len(remaining) == attempts_used+++ "raw,expected",+ [(None, 0), ("", 0), ("abc", 0), ("-5", 0), ("42", 42), ("250", 100), (" 7 ", 7), ("²", 0), ("9" * 5000, 0)],+)+def test_parse_percent_fails_closed(raw: str | None, expected: int) -> None:+ assert route.parse_percent(raw) == expected++[email protected]("labels", [json.dumps(["other"]), "null", ""])+def test_main_writes_outputs(labels: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ output = tmp_path / "out"+ monkeypatch.setenv("GITHUB_OUTPUT", str(output))+ monkeypatch.setenv("EVENT", "pull_request")+ monkeypatch.setenv("PERCENT", "50")+ monkeypatch.setenv("PR_NUMBER", "7")+ monkeypatch.setenv("LABELS", labels)+ monkeypatch.setattr(route, "fetch_handoff_checks", lambda repo, sha, token: [])+ monkeypatch.setenv("REPO", "PostHog/posthog")+ monkeypatch.setenv("SHA", "abc")+ monkeypatch.setenv("GH_TOKEN", "t")+ assert route.main() == 0+ assert output.read_text() == "engine=depot\nreason=bucket 7 < 50%\n"+++ "percent,labels,reads",+ [+ ("", "[]", 0),+ ("0", "[]", 1),+ ("", json.dumps(["ci-backend-depot"]), 1),+ ("", json.dumps(["ci-backend-github"]), 1),+ ],+)+def test_main_reads_the_handoff_only_when_routing_is_possible(+ percent: str, labels: str, reads: int, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ calls: list[str] = []++ def fetch(repo: str, sha: str, token: str) -> list[dict[str, Any]]:+ calls.append(sha)+ return []++ monkeypatch.setenv("GITHUB_OUTPUT", str(tmp_path / "out"))+ monkeypatch.setenv("EVENT", "pull_request")+ monkeypatch.setenv("PERCENT", percent)+ monkeypatch.setenv("PR_NUMBER", "7")+ monkeypatch.setenv("LABELS", labels)+ monkeypatch.setenv("REPO", "PostHog/posthog")+ monkeypatch.setenv("SHA", "abc")+ monkeypatch.setenv("GH_TOKEN", "t")+ monkeypatch.setattr(route, "fetch_handoff_checks", fetch)+ assert route.main() == 0+ assert len(calls) == reads+++def test_main_fails_when_the_earlier_handoff_cannot_be_read(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ def failing(repo: str, sha: str, token: str) -> list[dict[str, Any]]:+ raise route.HandoffReadError("boom")++ monkeypatch.setenv("GITHUB_OUTPUT", str(tmp_path / "out"))+ monkeypatch.setenv("EVENT", "pull_request")+ monkeypatch.setenv("PERCENT", "5")+ monkeypatch.setenv("PR_NUMBER", "7")+ monkeypatch.setenv("LABELS", "[]")+ monkeypatch.setenv("REPO", "PostHog/posthog")+ monkeypatch.setenv("SHA", "abc")+ monkeypatch.setenv("GH_TOKEN", "t")+ monkeypatch.setattr(route, "fetch_handoff_checks", failing)+ monkeypatch.setattr(route.time, "sleep", lambda seconds: None)+ assert route.main() == 1+ assert not (tmp_path / "out").exists()diff --git a/.github/workflows/ci-backend-shadow-drift.yml b/.github/workflows/ci-backend-shadow-drift.ymlindex 136e4c5e53a3..5ed8b3479b96 100644--- a/.github/workflows/ci-backend-shadow-drift.yml+++ b/.github/workflows/ci-backend-shadow-drift.yml@@ -9,10 +9,9 @@ name: Backend CI shadow drift check## Cheap to run: it triggers only on changes to the backend workflow, local actions, Depot files, or the check itself.# Always enforced (no variable gate): keeping the depot mirror in sync with canonical is-# a structural invariant worth holding whether or not the shadow is currently sampling —-# you want them already in sync the moment the shadow is switched on. The sampling rate-# lives in the CI_DEPOT_SHADOW_PERCENT Depot CI variable, which this check deliberately-# does not read.+# a structural invariant worth holding whatever the rollout percent is: you want them+# already in sync the moment an event is routed to Depot. The percent lives in the+# CI_BACKEND_DEPOT_PERCENT GitHub variable, which this check deliberately does not read.on:pull_request:diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 16a85e1d8bbc..263c81843368 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -96,6 +96,7 @@ permissions:contents: readactions: readpull-requests: write+ checks: read # the router reads this commit's earlier hand-off checkjobs:# Learning mode: nothing reads these outputs, so a recommendation cannot change what runs.@@ -164,14 +165,16 @@ jobs:timing_scripts: ${{ steps.filter.outputs.timing_scripts }}# Which engine runs this event's backend tests. Depot CI never decides on its# own: it waits for the hand-off job below and runs only when that succeeded.- engine: github+ engine: ${{ steps.route.outputs.engine || 'github' }}steps:# For pull requests it's not necessary to checkout the code, but we# also want this to run on master so we need to checkout- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:clean: false- sparse-checkout: .github/actions/paths-filter+ sparse-checkout: |+ .github/actions/paths-filter+ .github/scripts/ci_backend_route.pysparse-checkout-cone-mode: false- name: Clean up data directories with container permissionsrun: |@@ -185,6 +188,23 @@ jobs:with:client-id: ${{ vars.GH_APP_POSTHOG_PATHS_FILTER_APP_ID }}private-key: ${{ secrets.GH_APP_POSTHOG_PATHS_FILTER_PRIVATE_KEY }}+ - name: Pick the engine that runs the backend tests+ id: route+ if: github.event_name == 'pull_request'+ env:+ PERCENT: ${{ vars.CI_BACKEND_DEPOT_PERCENT }}+ EVENT: ${{ github.event_name }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }}+ IS_FORK: ${{ github.event.pull_request.head.repo.fork }}+ IS_DRAFT: ${{ github.event.pull_request.draft }}+ HEAD_REF: ${{ github.head_ref }}+ # The script reads this commit's earlier hand-off check, the durable record+ # of the engine that already ran its tests and side effects.+ GH_TOKEN: ${{ github.token }}+ REPO: ${{ github.repository }}+ SHA: ${{ github.event.pull_request.head.sha }}+ run: python3 .github/scripts/ci_backend_route.py- 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@@ -463,7 +483,7 @@ jobs:needs: [changes]# Master pushes skip the matrices (see the trigger comment); skipping this# root cascades to every downstream test job via their result checks.- if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'+ if: needs.changes.outputs.backend == 'true' && github.event_name != 'push' && needs.changes.outputs.engine != 'depot'outputs:mode: ${{ steps.detect.outputs.mode }}steps:@@ -502,7 +522,7 @@ jobs:needs: changes# Skipped on master push: the merge queue already ran the full matrices for# every landed commit, and the hourly scheduled run keeps master coverage.- if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'+ if: needs.changes.outputs.backend == 'true' && github.event_name != 'push' && needs.changes.outputs.engine != 'depot'runs-on: depot-ubuntu-24.04timeout-minutes: 20name: Discover product tests@@ -1316,7 +1336,7 @@ jobs: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'+ 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'timeout-minutes: 10outputs:deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}@@ -1473,6 +1493,7 @@ jobs:needs.changes.outputs.product_yamls == 'true' &&github.event_name == 'pull_request' &&github.event.pull_request.head.repo.full_name == github.repository+ && needs.changes.outputs.engine != 'depot'timeout-minutes: 5name: Validate product.yaml owners (ubuntu-latest)runs-on: ubuntu-latest@@ -1548,7 +1569,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.persons_sql == 'true' || needs.changes.outputs.migration_replay == 'true') && github.event_name != 'schedule'+ 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'# 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.@@ -2294,7 +2315,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'+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.openapi_types == 'true') && github.event_name != 'schedule' && needs.changes.outputs.engine != 'depot'timeout-minutes: 20outputs:deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}@@ -3785,7 +3806,7 @@ jobs:name: Get ClickHouse versionsneeds: [changes]# Only feeds the test matrices, which master pushes skip.- if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'+ if: needs.changes.outputs.backend == 'true' && github.event_name != 'push' && needs.changes.outputs.engine != 'depot'runs-on: depot-ubuntu-24.04timeout-minutes: 5outputs:@@ -3959,8 +3980,13 @@ jobs:]name: Django Tests Passruns-on: ubuntu-latest- # Headroom for downloading every shard's JUnit for the failure rollup.- timeout-minutes: 8+ permissions:+ contents: read+ actions: read # the failure rollup downloads each shard's JUnit artifact+ checks: read # the relay reads Depot's gate check run+ # Headroom for downloading every shard's JUnit for the failure rollup, or for+ # waiting out a full Depot run when this job only relays its verdict.+ timeout-minutes: ${{ needs.changes.outputs.engine == 'depot' && 95 || 8 }}# Intentional !cancelled(): the gate inspects failed dependencies and fails# closed on live runs; a superseded run records cancelled, not failure.# The deterministic-failure disjuncts cover this workflow cancelling its@@ -3971,7 +3997,97 @@ jobs:|| needs.repo-checks.outputs.deterministic_failure == 'true'|| needs.check-openapi-types.outputs.deterministic_failure == 'true'steps:+ # Depot posts a job's check run when the job starts, so the gate stays absent+ # while the matrix runs; the wait job starts first and tells a run Depot never+ # picked up from one that declined the hand-off. A `no-ci` draft marked ready+ # keeps its SHA and its earlier skipped checks, so only a check that started+ # after this event counts. 304 responses are free, so the poll stays off the+ # rate limit.+ - name: Relay the Depot verdict+ if: needs.changes.outputs.engine == 'depot'+ env:+ GH_TOKEN: ${{ github.token }}+ REPO: ${{ github.repository }}+ SHA: ${{ github.event.pull_request.head.sha }}+ EVENT_AT: ${{ github.event.pull_request.updated_at }}+ # Two open PRs can share a head SHA, so only this PR's check runs count.+ PR_NUMBER: ${{ github.event.pull_request.number }}+ # Must match the workflow and job names in .depot/workflows/ci-backend.yml.+ DEPOT_APP_ID: '219785'+ DEPOT_GATE_CHECK: Backend CI on Depot / Django Tests Pass on Depot+ DEPOT_WAIT_CHECK: Backend CI on Depot / Wait for GitHub Actions to hand off backend tests+ run: |+ set -uo pipefail+ relay_minutes=90+ absent_minutes=15+ deadline=$((SECONDS + relay_minutes * 60))+ absent_deadline=$((SECONDS + absent_minutes * 60))+ refusals=0+ gate=""+ wait_job=""+ api="https://api.github.com/repos/$REPO/commits/$SHA/check-runs?app_id=$DEPOT_APP_ID&check_name="+ gate_url="$api$(jq -rn --arg n "$DEPOT_GATE_CHECK" '$n | @uri')"+ wait_url="$api$(jq -rn --arg n "$DEPOT_WAIT_CHECK" '$n | @uri')"+ # Reads one Depot check run into the named variable: absent, a status, or a+ # conclusion. A 304 leaves it as it was.+ # shellcheck disable=SC2034 # the nameref writes the caller's variable+ read_check() {+ local url=$1+ local -n slot=$2+ local code+ # curl rewrites the saved ETag empty on a 304, so promote it only after a 200.+ code=$(curl -s -o "/tmp/relay-$2" -w '%{http_code}' --max-time 30 --etag-compare "/tmp/relay-$2.etag" --etag-save "/tmp/relay-$2.etag.new" \+ -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" "$url")+ case "$code" in+ 200)+ mv "/tmp/relay-$2.etag.new" "/tmp/relay-$2.etag"+ slot=$(jq -r --arg since "$EVENT_AT" --argjson pr "$PR_NUMBER" '[.check_runs[] | select((.started_at // "") >= $since and any(.pull_requests[]?; .number == $pr))] | max_by(.id) | if . == null then "absent" elif .status == "completed" then .conclusion else .status end' "/tmp/relay-$2")+ refusals=0+ ;;+ 304) refusals=0 ;;+ # 403 also covers a secondary rate limit, which does clear, so spend a+ # few retries before calling the credential broken.+ 401|403)+ refusals=$((refusals + 1))+ echo "::warning::check-runs API returned $code ($refusals in a row)"+ if [ "$refusals" -ge 5 ]; then+ echo "::error::Cannot read Depot's checks for $SHA; this job cannot relay a verdict"+ exit 1+ fi+ ;;+ *) echo "::warning::check-runs API returned $code" ;;+ esac+ }+ while [ "$SECONDS" -lt "$deadline" ]; do+ read_check "$gate_url" gate+ echo "Depot gate: ${gate:-unread}"+ case "$gate" in+ success) exit 0 ;;+ ""|absent)+ # The wait job cannot change once it concluded, so stop reading it then.+ [ "$wait_job" = success ] || read_check "$wait_url" wait_job+ case "$wait_job" in+ success|queued|in_progress|pending|waiting|requested) ;;+ ""|absent)+ if [ "$SECONDS" -ge "$absent_deadline" ]; then+ echo "::error::Depot CI never started for $SHA: no wait job after $absent_minutes minutes"+ exit 1+ fi+ ;;+ *) echo "::error::Depot declined the hand-off for $SHA (wait job: $wait_job)"; exit 1 ;;+ esac+ ;;+ queued|in_progress|pending|waiting|requested) ;;+ *) echo "::error::Depot gate concluded $gate for $SHA"; exit 1 ;;+ esac+ # The gate check only appears when the matrix is done, so once Depot has+ # started, a slower poll costs at most a minute of latency.+ if [ "$wait_job" = success ]; then sleep 60; else sleep 30; fi+ done+ echo "::error::No Depot verdict for $SHA within $relay_minutes minutes"+ exit 1- name: Summarize dependency results+ if: needs.changes.outputs.engine != 'depot'run: |{echo "### Backend CI dependency results"@@ -4003,7 +4119,7 @@ jobs:# on green runs (the common case) to avoid pulling every shard artifact for nothing.# continue-on-error so a flaky fetch can't fail this required gate.- name: Download shard JUnit results- if: always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')+ if: always() && needs.changes.outputs.engine != 'depot' && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')continue-on-error: trueuses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0with:@@ -4012,7 +4128,7 @@ jobs:# Re-run attempts upload under suffixed names, so superseded attempts must be dropped# here or the rollup below lists attempt-1 failures the re-run already recovered.- name: Keep only each shard's latest attempt- if: always() && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')+ if: always() && needs.changes.outputs.engine != 'depot' && (needs.django.result != 'success' || needs.turbo-tests.result != 'success')continue-on-error: truerun: |cd /tmp/junit-gate 2>/dev/null || exit 0@@ -4232,7 +4348,7 @@ jobs:calculate-running-time:name: Calculate running time- needs: [django_tests]+ needs: [changes, django_tests]runs-on: ubuntu-latesttimeout-minutes: 5# Run on pull requests to PostHog/posthog + on PostHog/posthog outside of PRs - but never on forks or Dependabot (no secrets access)@@ -4240,6 +4356,7 @@ jobs:!cancelled() && github.actor != 'dependabot[bot]' && ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') ||(github.event_name != 'pull_request' && github.repository == 'PostHog/posthog'))+ && needs.changes.outputs.engine != 'depot'permissions:contents: readactions: read@@ -4375,7 +4492,7 @@ jobs:backend-coverage-report:name: Backend coverage report- needs: [turbo-tests, django_tests, turbo-discover]+ needs: [changes, turbo-tests, django_tests, turbo-discover]runs-on: ubuntu-latestcontinue-on-error: true # report-only, never block a PRtimeout-minutes: 10@@ -4399,6 +4516,7 @@ jobs:needs.turbo-discover.outputs.mode != 'selected' &&github.event.pull_request.head.repo.full_name == 'PostHog/posthog' &&(needs.turbo-tests.result != 'skipped' || needs.django_tests.result != 'skipped')+ && needs.changes.outputs.engine != 'depot'steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:diff --git a/tools/workflow-plan/src/scenarios.ts b/tools/workflow-plan/src/scenarios.tsindex b74aaee935b4..8bc4f2330a64 100644--- a/tools/workflow-plan/src/scenarios.ts+++ b/tools/workflow-plan/src/scenarios.ts@@ -194,6 +194,8 @@ export const REPO_ROOT = fileURLToPath(new URL('../../../', import.meta.url))type ScriptStubs = Pick<Scenario, 'vars' | 'jobOutputs'>// Values only a script produces at runtime, without which a workflow's gates cannot be planned.+const DEPOT_BACKEND = '.depot/workflows/ci-backend.yml'+const SCRIPT_STUBS: Record<string, ScriptStubs> = {'.github/workflows/release.yml': {jobOutputs: {@@ -202,23 +204,30 @@ const SCRIPT_STUBS: Record<string, ScriptStubs> = {},},},- // The Depot shadow gates its whole graph on a sampling variable and a dice roll; plan it as sampled in.- '.depot/workflows/ci-backend.yml': {- vars: { CI_DEPOT_SHADOW_PERCENT: '100' },- jobOutputs: { sample: { sampled: 'true' } },+ // The Depot graph hangs off a hand-off check the planner cannot read; plan it as handed+ // off, which is the only case where its jobs do any work.+ [DEPOT_BACKEND]: {+ jobOutputs: { 'wait-for-handoff': { handed_off: 'true' } },},}+// The router keeps forks, merge queue batches, pushes and the schedule on GitHub Actions,+// so Depot's wait job declines those events; only same-repo pull requests and manual+// dispatches run there.+const NOT_HANDED_OFF: ScriptStubs = { jobOutputs: { 'wait-for-handoff': { handed_off: 'false' } } }+export function defaultScenarios(workflow: Workflow, workflowPath: string): Scenario[] {const steps = allFiltersChanged(workflow)- const common = { steps, ...SCRIPT_STUBS[path.relative(REPO_ROOT, workflowPath).split(path.sep).join('/')] }+ const key = path.relative(REPO_ROOT, workflowPath).split(path.sep).join('/')+ const common = { steps, ...SCRIPT_STUBS[key] }+ const keptOnGitHub = { ...common, ...(key === DEPOT_BACKEND ? NOT_HANDED_OFF : {}) }return [{ name: 'draft', github: pullRequest({ draft: true }), ...common },{ name: 'ready', github: pullRequest(), ...common },- { name: 'fork', github: pullRequest({ fork: true }), ...common },- { name: 'queued', github: mergeQueue(), ...common },- { name: 'merged', github: push(), ...common },- { name: 'scheduled', github: schedule(), ...common },+ { name: 'fork', github: pullRequest({ fork: true }), ...keptOnGitHub },+ { name: 'queued', github: mergeQueue(), ...keptOnGitHub },+ { name: 'merged', github: push(), ...keptOnGitHub },+ { name: 'scheduled', github: schedule(), ...keptOnGitHub },{ name: 'dispatched', github: workflowDispatch(), ...common },]}diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.tsindex 045fbd2c6d6a..b660ff109eb9 100644--- a/tools/workflow-plan/tests/workflows.test.ts+++ b/tools/workflow-plan/tests/workflows.test.ts@@ -136,6 +136,39 @@ const EXPECTATIONS: Expectation[] = [skipped: ['handle-snapshots', 'cancel-backend-on-openapi-check-failure', 'hand-off-to-depot'],}),+ // Handed off to Depot: it runs the tests and the side effects, GitHub Actions relays the+ // verdict. Every heavy job and every side effect here stands down, and the required gate+ // keeps reporting.+ backend(+ {+ name: 'ready PR handed off to Depot',+ steps: { changes: { route: { outputs: { engine: 'depot' } } } },+ },+ {+ runs: ['changes', 'hand-off-to-depot', 'django_tests'],+ skipped: [+ 'detect-snapshot-mode',+ 'turbo-discover',+ 'repo-checks',+ 'validate-product-yamls',+ 'check-migrations',+ 'check-openapi-types',+ 'get_clickhouse_versions',+ 'build_django_matrix',+ 'build-product-test-matrix',+ 'django',+ 'turbo-tests',+ 'handle-snapshots',+ 'test-selection-verdict',+ 'capture-test-selection',+ 'report-test-timings',+ 'calculate-running-time',+ 'backend-coverage-report',+ 'cancel-backend-on-repo-check-failure',+ 'cancel-backend-on-openapi-check-failure',+ ],+ }+ ),backend({ name: 'merge queue', github: mergeQueue() },{