Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ci): find the depot run of each event by name, not by time (#105886)

Raúl Negrón-Otero81aa80fe1f58
diff --git a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md b/.agents/skills/depot-ci/references/posthog-check-run-semantics.md
index f1b4d82505b3..123d6b318409 100644
--- a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md
+++ b/.agents/skills/depot-ci/references/posthog-check-run-semantics.md
@@ -60,7 +60,20 @@ Depot creates a job's check run when it resolves the job, not when it creates th
## Reruns
-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).
+Retrying a failed Depot job created a new check run with the same name and left the failed one behind in the measured 2026-09-17 run `jb7zh5rvnk`: the retried cell got check run `105270302262` while `105262890457` stayed `completed/failure`; only `filter=all` on the check-runs API listed 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` 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` when it is present.
+
+Depot's list can still be empty. The [check suites API](https://docs.github.com/en/rest/checks/suites) says a suite is created when code is pushed and an app usually receives one suite event per commit SHA even if that SHA is pushed to multiple branches. On commit `f786b640f2f0`, Depot's suite `97293642167` names a `posthog/rewrite-tmp/` branch and has `pull_requests: []`, while GitHub Actions suites on the same commit name PR 104868's branch and list that PR. Commit `749f24dd5b7a` shows the same split with a `-rebase-1` branch. This is consistent with the suite retaining an earlier push branch, but the suite records do not establish push order. Filtering those Depot checks by `pull_requests[].number` finds no check for the PR.
+
+## Cancelled runs
+
+In the following cancelled runs, an unstarted job received a `cancelled` check with `started_at` and `completed_at` set to the cancel time. A `started_at >= event time` filter kept the superseded run's check, which could be the newest one of its name. Measured 2026-09-24:
+
+- Depot: gate check `107582798883` of cancelled workflow `x17bxd5m0z` started and completed at 09:55:14, 54 seconds after the next event and before that event's gate appeared.
+- GitHub Actions: hand-off check `107604825793` of cancelled run `35990511352` started and completed at 11:05:40, after the next event (11:04:23) and 14 seconds before that event's hand-off check.
+
+## Finding one event's Depot run
+
+Check times and `pull_requests` did not pick out the Depot run in these cases, so the event goes into a check name. The Depot wait job's name ends with `(PR <number>, event <pull_request.updated_at>)`, and Depot renders expressions in job names into the check name. `.github/scripts/ci_backend_relay.py` builds the same name from the GitHub run's payload, reads that check, takes the Depot workflow id from its `details_url`, and reads the gate or migration check of that workflow only. Measured 2026-09-24 on PR 105886: Depot posted check `107656013423` named `… (PR 105886, event 2026-09-24T13:33:14Z)`, and GitHub relay job `107655803961` used `EVENT_AT: 2026-09-24T13:33:14Z` and relayed a successful gate.
## Depot CI CLI recipes
diff --git a/.depot/workflows/ci-backend-report.yml b/.depot/workflows/ci-backend-report.yml
index abcb1af73687..b6a21a174b9b 100644
--- a/.depot/workflows/ci-backend-report.yml
+++ b/.depot/workflows/ci-backend-report.yml
@@ -29,111 +29,28 @@ jobs:
runs-on: depot-ubuntu-24.04
timeout-minutes: 90
steps:
+ - name: Checkout the trusted relay script # nosemgrep: yaml.github-actions.security.pull-request-target-code-checkout.pull-request-target-code-checkout
+ # v6.0.2 checks out only the trusted base SHA below, never pull request code.
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
+ with:
+ repository: ${{ github.repository }}
+ ref: ${{ github.sha }}
+ path: trusted-relay
+ sparse-checkout: .github/scripts/ci_backend_relay.py
+ sparse-checkout-cone-mode: false
+ persist-credentials: false
+
+ # First confirm GitHub Actions handed this commit to Depot. The script then finds
+ # this event's Depot run by its wait check name and waits for its migration check.
- name: Find the handed-off Depot migration run
id: source
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
- HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ SHA: ${{ github.event.pull_request.head.sha }}
EVENT_AT: ${{ github.event.pull_request.updated_at }}
PR_NUMBER: ${{ github.event.pull_request.number }}
- HANDOFF_CHECK: Hand off backend tests to Depot CI
- MIGRATION_CHECK: Backend CI on Depot / Validate migrations
- GITHUB_ACTIONS_APP_ID: '15368'
- DEPOT_APP_ID: '219785'
- run: |
- set -euo pipefail
-
- read_check() {
- local url=$1
- local body=$2
- local code
- code=$(curl -s -o "$body" -w '%{http_code}' --max-time 15 \
- -H "Authorization: Bearer $GH_TOKEN" \
- -H "Accept: application/vnd.github+json" "$url")
- if [ "$code" != 200 ]; then
- echo "::warning::check-runs API returned $code"
- return 1
- fi
- }
-
- check_url() {
- local app_id=$1
- local name=$2
- printf 'https://api.github.com/repos/%s/commits/%s/check-runs?app_id=%s&check_name=%s' \
- "$REPO" "$HEAD_SHA" "$app_id" "$(jq -rn --arg n "$name" '$n | @uri')"
- }
-
- handoff_url=$(check_url "$GITHUB_ACTIONS_APP_ID" "$HANDOFF_CHECK")
- # A failed API read sets `unread`, so it never passes for a confirmed `absent`.
- handoff=unread
- # Matches the hand-off wait in ci-backend.yml: after it, Depot runs nothing to report.
- for _ in $(seq 1 30); do
- if read_check "$handoff_url" /tmp/handoff-checks.json; then
- handoff=$(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/handoff-checks.json)
- else
- handoff=unread
- fi
- case "$handoff" in
- unread|absent|queued|in_progress|pending|waiting|requested) sleep 20 ;;
- *) break ;;
- esac
- done
- case "$handoff" in
- success) ;;
- unread|queued|in_progress|pending|waiting|requested)
- echo "::error::Backend routing did not resolve within 10 minutes (hand-off check: $handoff)"
- exit 1
- ;;
- *)
- # `absent` covers a PR with merge conflicts: GitHub runs no pull_request
- # workflow for it, but this pull_request_target run still starts.
- echo "handed_off=false" >> "$GITHUB_OUTPUT"
- echo "GitHub Actions kept the backend tests (hand-off check: $handoff)."
- exit 0
- ;;
- esac
- echo "handed_off=true" >> "$GITHUB_OUTPUT"
-
- migration_url=$(check_url "$DEPOT_APP_ID" "$MIGRATION_CHECK")
- migration_state=absent
- details_url=''
- for _ in $(seq 1 210); do
- if read_check "$migration_url" /tmp/migration-checks.json; then
- readarray -t check < <(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", "" else (if .status == "completed" then .conclusion else .status end), (.details_url // "") end
- ' /tmp/migration-checks.json)
- migration_state=${check[0]:-absent}
- details_url=${check[1]:-}
- fi
- case "$migration_state" in
- success|failure|neutral|cancelled|skipped) break ;;
- absent|queued|in_progress|pending|waiting|requested) sleep 20 ;;
- *) echo "::error::Unexpected migration check state: $migration_state"; exit 1 ;;
- esac
- done
- echo "migration_state=$migration_state" >> "$GITHUB_OUTPUT"
- case "$migration_state" in
- success|failure|neutral) ;;
- cancelled|skipped)
- echo "No completed migration report is available (migration check: $migration_state)."
- exit 0
- ;;
- *) echo "::error::Depot migration check did not finish within 70 minutes"; exit 1 ;;
- esac
-
- if [[ "$details_url" =~ ^https://depot.dev/orgs/[^/]+/workflows/([a-z0-9]+) ]]; then
- echo "workflow_id=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"
- else
- echo "::error::Unexpected Depot migration check URL"
- exit 1
- fi
+ run: python3 trusted-relay/.github/scripts/ci_backend_relay.py migrations
- name: Set up Depot CLI
if: steps.source.outputs.workflow_id != ''
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 0701be8d3e9f..5e44c3bd8735 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -220,7 +220,9 @@ jobs:
|| !contains(github.event.pull_request.labels.*.name, 'no-ci')
runs-on: depot-ubuntu-24.04
timeout-minutes: 15
- name: Wait for GitHub Actions to hand off backend tests
+ # The check name carries the event, so GitHub Actions can tell this run's checks from other
+ # runs on the commit. .github/scripts/ci_backend_relay.py builds the same name; change both.
+ name: Wait for GitHub Actions to hand off backend tests${{ github.event_name == 'pull_request' && format(' (PR {0}, event {1})', github.event.pull_request.number, github.event.pull_request.updated_at) || '' }}
# 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:
@@ -261,7 +263,7 @@ jobs:
# runs every non-PR event itself.
echo "::notice::$EVENT events never run on Depot CI."
else
- url="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"
+ url="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&filter=all&per_page=100"
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 \
@@ -269,7 +271,10 @@ jobs:
case "$code" in
200)
mv /tmp/handoff-etag.new /tmp/handoff-etag
- 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)
+ # A cancelled hand-off comes from a GitHub run that was cancelled before its
+ # hand-off job finished, so it carries no decision, as in ci_backend_route.py.
+ # GitHub posts it with started_at set to the cancel time, which can follow this event.
+ state=$(jq -r --arg since "$EVENT_AT" --argjson pr "${PR_NUMBER:-null}" '[.check_runs[] | select(.conclusion != "cancelled" and (.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 ;;
diff --git a/.github/scripts/ci_backend_relay.py b/.github/scripts/ci_backend_relay.py
new file mode 100644
index 000000000000..fde59524daff
--- /dev/null
+++ b/.github/scripts/ci_backend_relay.py
@@ -0,0 +1,403 @@
+#!/usr/bin/env python3
+"""Follow the Depot CI run that took over one pull request event, and read one of its checks.
+
+GitHub Actions hands a pull request event to Depot CI (see ci_backend_route.py), and Depot
+starts a workflow for every pull request event. One commit can therefore carry Depot runs of
+earlier events, a duplicate run of the same event, and runs of another pull request with the
+same head. Depot check times and pull request lists cannot tell them apart:
+
+- When Depot cancels a superseded run, it posts a cancelled check for each job that had not
+ started, with `started_at` set to the cancel time.
+- Depot's checks sit in its app's check suite for the commit, which carries the branch of the
+ commit's first push. When that branch is not the pull request's head, the checks list no
+ pull request.
+
+.agents/skills/depot-ci/references/posthog-check-run-semantics.md has the measurements.
+So the Depot wait job's check name carries the event: the pull request number and its
+`updated_at`, which both engines read from the same event payload. That check identifies the
+event's run, and every other check of the run is matched by the Depot workflow id in its
+details URL.
+
+Standard library only: the relay job runs this with the runner's python3 before any install.
+"""
+
+import os
+import re
+import sys
+import json
+import time
+import http.client
+import urllib.error
+import urllib.parse
+import urllib.request
+from collections.abc import Callable, Iterable, Sequence
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, Protocol
+
+DEPOT_APP_ID = 219785
+DEPOT_WORKFLOW = "Backend CI on Depot"
+WAIT_JOB = "Wait for GitHub Actions to hand off backend tests"
+# Renders the same text as the wait job's name expression in .depot/workflows/ci-backend.yml.
+EVENT_SUFFIX = " (PR {pr}, event {event_at})"
+GATE_CHECK = f"{DEPOT_WORKFLOW} / Django Tests Pass on Depot"
+MIGRATION_CHECK = f"{DEPOT_WORKFLOW} / Validate migrations"
+CHANGES_CHECK = f"{DEPOT_WORKFLOW} / Determine need to run backend and migration checks"
+HANDOFF_CHECK = "Hand off backend tests to Depot CI"
+GITHUB_ACTIONS_APP_ID = 15368
+DEPOT_RUN_URL = re.compile(r"^https://depot\.dev/orgs/([^/?]+)/workflows/([a-z0-9]+)(?:[?/]|$)")
+PENDING_STATES = frozenset({"queued", "in_progress", "pending", "waiting", "requested"})
+API_ROOT = "https://api.github.com"
+PAGE_SIZE = 100
+# A 403 also covers a secondary rate limit, which clears, so a few refusals in a row are tolerated.
+MAX_REFUSALS = 5
+
+
+class ReadRefusedError(RuntimeError):
+ """The check-runs API keeps refusing the token, so no verdict can be read."""
+
+
+class HandoffUnresolvedError(RuntimeError):
+ """The report cannot determine which engine owns this event."""
+
+
+@dataclass(frozen=True)
+class CheckRun:
+ id: int
+ # The conclusion once the check completed, its status before that.
+ state: str
+ pull_requests: frozenset[int]
+ details_url: str
+
+ @classmethod
+ def from_api(cls, run: dict[str, Any]) -> "CheckRun":
+ return cls(
+ id=int(run["id"]),
+ state=str((run.get("conclusion") if run.get("status") == "completed" else run.get("status")) or ""),
+ pull_requests=frozenset(int(pr["number"]) for pr in run.get("pull_requests") or []),
+ details_url=str(run.get("details_url") or ""),
+ )
+
+ @property
+ def depot_workflow(self) -> str | None:
+ match = DEPOT_RUN_URL.match(self.details_url)
+ return match.group(2) if match else None
+
+
+class Phase(Enum):
+ ABSENT = "absent"
+ STARTING = "starting"
+ DECLINED = "declined"
+ CANCELLED = "cancelled"
+ RUNNING = "running"
+ FINISHED = "finished"
+
+
+@dataclass(frozen=True)
+class Progress:
+ phase: Phase
+ # The state of the check behind the phase, empty when there is none.
+ state: str = ""
+ details_url: str = ""
+
+
+def wait_check_name(pr_number: int, event_at: str) -> str:
+ return f"{DEPOT_WORKFLOW} / {WAIT_JOB}{EVENT_SUFFIX.format(pr=pr_number, event_at=event_at)}"
+
+
+def newest_live(runs: Sequence[CheckRun]) -> CheckRun | None:
+ """The newest run that was not cancelled, or the newest cancelled run when every run was."""
+ live = [run for run in runs if run.state != "cancelled"]
+ return max(live or runs, key=lambda run: run.id, default=None)
+
+
+def handoff_decision(runs: Iterable[CheckRun], pr_number: int) -> bool | None:
+ """Mirror the router's durable decision for this pull request and commit."""
+ states = {run.state for run in runs if pr_number in run.pull_requests}
+ if "success" in states:
+ return True
+ if "skipped" in states:
+ return False
+ return None
+
+
+def progress(
+ wait: CheckRun | None, checks: Iterable[CheckRun], skipped_dependency_checks: Iterable[CheckRun] = ()
+) -> Progress:
+ """Where the Depot run behind `wait` stands, judged by its check among `checks`."""
+ if wait is None:
+ return Progress(Phase.ABSENT)
+ if wait.state == "cancelled":
+ return Progress(Phase.CANCELLED, wait.state, wait.details_url)
+ if wait.state in PENDING_STATES:
+ return Progress(Phase.STARTING, wait.state, wait.details_url)
+ if wait.state != "success":
+ return Progress(Phase.DECLINED, wait.state, wait.details_url)
+ workflow = wait.depot_workflow
+ # A retried Depot job posts a new check in the same workflow, so the newest one is current.
+ check = max(
+ (run for run in checks if workflow is not None and run.depot_workflow == workflow),
+ key=lambda run: run.id,
+ default=None,
+ )
+ if check is None:
+ dependency = max(
+ (run for run in skipped_dependency_checks if workflow is not None and run.depot_workflow == workflow),
+ key=lambda run: run.id,
+ default=None,
+ )
+ if dependency is not None and dependency.state == "skipped":
+ return Progress(Phase.DECLINED, dependency.state, dependency.details_url)
+ if check is None or check.state in PENDING_STATES:
+ return Progress(Phase.RUNNING, check.state if check else "", wait.details_url)
+ if check.state == "cancelled":
+ return Progress(Phase.CANCELLED, check.state, check.details_url)
+ return Progress(Phase.FINISHED, check.state, check.details_url)
+
+
+class CheckReader(Protocol):
+ def read(self, name: str) -> list[CheckRun]: ...
+
+
+class CheckRunReader:
+ """Reads one commit's check runs for one app by name, with conditional requests.
+
+ A 304 answer is free against the rate limit, so polling stays cheap.
+ """
+
+ def __init__(
+ self,
+ repo: str,
+ sha: str,
+ token: str,
+ opener: Callable[..., Any] = urllib.request.urlopen,
+ app_id: int = DEPOT_APP_ID,
+ ) -> None:
+ self._repo = repo
+ self._sha = sha
+ self._token = token
+ self._opener = opener
+ self._app_id = app_id
+ self._cache: dict[str, tuple[str, list[CheckRun]]] = {}
+ self._refusals = 0
+
+ def _url(self, name: str, page: int) -> str:
+ query = urllib.parse.urlencode(
+ {"check_name": name, "app_id": self._app_id, "filter": "all", "per_page": PAGE_SIZE, "page": page}
+ )
+ return f"{API_ROOT}/repos/{self._repo}/commits/{self._sha}/check-runs?{query}"
+
+ def _get(self, url: str, etag: str = "") -> tuple[int, str, dict[str, Any]]:
+ headers = {
+ "Accept": "application/vnd.github+json",
+ "X-GitHub-Api-Version": "2022-11-28",
+ "Authorization": f"Bearer {self._token}",
+ }
+ if etag:
+ headers["If-None-Match"] = etag
+ try:
+ with self._opener(urllib.request.Request(url, headers=headers), timeout=30) as response:
+ return response.status, response.headers.get("ETag", ""), json.loads(response.read().decode("utf-8"))
+ except urllib.error.HTTPError as error:
+ return error.code, "", {}
+
+ def read(self, name: str) -> list[CheckRun]:
+ """Read every page, reusing a cached answer only when the API confirms it with 304."""
+ etag, cached = self._cache.get(name, ("", []))
+ raw: list[dict[str, Any]] = []
+ page = 1
+ new_etag = ""
+ try:
+ while True:
+ code, page_etag, body = self._get(self._url(name, page), etag if page == 1 else "")
+ if page == 1 and code == 304:
+ self._refusals = 0
+ return cached
+ if code in (401, 403):
+ self._refusals += 1
+ if self._refusals >= MAX_REFUSALS:
+ raise ReadRefusedError(f"Cannot read checks for {self._sha}")
+ if code != 200:
+ sys.stdout.write(f"::warning::check-runs API returned {code}\n")
+ return []
+ self._refusals = 0
+ if page == 1:
+ new_etag = page_etag
+ batch = body["check_runs"]
+ raw.extend(batch)
+ if len(batch) < PAGE_SIZE:
+ break
+ page += 1
+ except (OSError, http.client.HTTPException, ValueError) as error:
+ sys.stdout.write(f"::warning::check-runs API read failed: {error}\n")
+ return []
+ runs = [CheckRun.from_api(run) for run in raw]
+ # One page's ETag cannot validate the other pages of a paginated response.
+ self._cache[name] = (new_etag if page == 1 else "", runs)
+ return runs
+
+
+@dataclass(frozen=True)
+class Event:
+ repo: str
+ sha: str
+ pr_number: int
+ # The pull request's `updated_at` in this event's payload.
+ event_at: str
+
+
+def wait_for_handoff(
+ reader: CheckReader,
+ event: Event,
+ *,
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+) -> bool:
+ """The router's committed engine; an unread decision cannot suppress a report."""
+ start = clock()
+ while True:
+ decision = handoff_decision(reader.read(HANDOFF_CHECK), event.pr_number)
+ if decision is not None:
+ return decision
+ if clock() - start >= 10 * 60:
+ raise HandoffUnresolvedError(f"Cannot determine the backend hand-off for {event.sha}")
+ sleep(20)
+
+
+def poll(
+ reader: CheckReader,
+ event: Event,
+ check_name: str,
+ *,
+ deadline_minutes: int,
+ absent_minutes: int,
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+) -> Progress:
+ """Polls until the event's check finishes, Depot declines the hand-off, or a deadline passes.
+
+ A duplicate run of the same event can replace a cancelled one. The migration report
+ gives an absent or cancelled run the full deadline; the required gate uses a shorter grace period.
+ """
+ start = clock()
+ event_name = wait_check_name(event.pr_number, event.event_at)
+ while True:
+ wait = newest_live(reader.read(event_name))
+ checks = reader.read(check_name) if wait and wait.state == "success" else []
+ dependencies = (
+ reader.read(CHANGES_CHECK) if check_name == MIGRATION_CHECK and wait and wait.state == "success" else []
+ )
+ current = progress(wait, checks, dependencies)
+ sys.stdout.write(f"Depot run for this event: {current.phase.value} {current.state}".rstrip() + "\n")
+ elapsed = clock() - start
+ if current.phase in (Phase.FINISHED, Phase.DECLINED):
+ return current
+ if current.phase in (Phase.ABSENT, Phase.CANCELLED) and elapsed >= absent_minutes * 60:
+ return current
+ if elapsed >= deadline_minutes * 60:
+ return current
+ # The checked job only posts its check when the matrix is done, so once Depot has
+ # started, a slower poll costs at most a minute of latency.
+ sleep(60 if current.phase == Phase.RUNNING else 30)
+
+
+def retry_instructions(event: Event, details_url: str, run_id: str) -> list[str]:
+ lines = [
+ f"Backend tests for {event.sha} ran on Depot CI, not GitHub Actions. Re-running this job alone reads the same result.",
+ f"Depot run: {details_url or 'not found'}",
+ "",
+ ]
+ match = DEPOT_RUN_URL.match(details_url)
+ if match:
+ org, workflow = match.groups()
+ lines += [
+ f"Retry through the Depot CLI (needs access to the Depot org {org}):",
+ f" depot ci diagnose --org {org} --workflow {workflow} # the failures, and the run ID on the 'Run:' line",
+ f" depot ci retry <run ID> --org {org} --workflow {workflow} --failed",
+ f" depot ci status <run ID> --org {org} # repeat until the run finishes",
+ f" gh run rerun {run_id} --repo {event.repo} --failed # relays the new Depot result",
+ "",
+ ]
+ return [
+ *lines,
+ "Retry without Depot access: a new commit starts a fresh run.",
+ " git commit --allow-empty -m 'chore: retry backend ci' && git push",
+ "",
+ "Run on GitHub Actions instead: the ci-backend-github label routes the next commit of this PR there.",
+ f" gh pr edit {event.pr_number} --repo {event.repo} --add-label ci-backend-github",
+ " git commit --allow-empty -m 'chore: retry backend ci on github actions' && git push",
+ ]
+
+
+def relay_gate(result: Progress, event: Event, run_id: str) -> tuple[int, list[str]]:
+ """The exit code and log lines of the `Django Tests Pass` relay for the gate's progress."""
+ if result.phase == Phase.FINISHED and result.state == "success":
+ return 0, []
+ if result.phase == Phase.FINISHED:
+ return 1, [
+ f"::error::Backend tests on Depot CI concluded {result.state}. This step's log lists the retry options.",
+ *retry_instructions(event, result.details_url, run_id),
+ ]
+ if result.phase == Phase.CANCELLED:
+ return 1, [
+ f"::error::Depot CI cancelled its run for this event of {event.sha} and started no replacement.",
+ *retry_instructions(event, result.details_url, run_id),
+ ]
+ if result.phase == Phase.DECLINED:
+ return 1, [f"::error::Depot declined the hand-off for {event.sha} (wait job: {result.state})"]
+ if result.phase == Phase.ABSENT:
+ return 1, [f"::error::Depot CI started no run for this event of {event.sha}: no wait job for it"]
+ return 1, [f"::error::No Depot verdict for {event.sha} within the relay's deadline"]
+
+
+def report_migrations(result: Progress) -> tuple[int, list[str], dict[str, str]]:
+ """The exit code, log lines and step outputs of the migration report's source step."""
+ if result.phase == Phase.FINISHED and result.state in ("success", "failure", "neutral"):
+ match = DEPOT_RUN_URL.match(result.details_url)
+ if not match:
+ return 1, ["::error::Unexpected Depot migration check URL"], {}
+ return 0, [], {"migration_state": result.state, "workflow_id": match.group(2)}
+ if result.phase in (Phase.FINISHED, Phase.CANCELLED) and result.state in ("skipped", "cancelled"):
+ return 0, [f"No completed migration report is available (migration check: {result.state})."], {}
+ if result.phase == Phase.FINISHED:
+ return 1, [f"::error::Unexpected migration check state: {result.state}"], {}
+ if result.phase == Phase.ABSENT:
+ return 1, ["::error::Depot posted no event-matched wait check after a confirmed hand-off"], {}
+ if result.phase == Phase.DECLINED:
+ return 0, [f"Depot CI ran no backend tests for this event ({result.phase.value} {result.state})."], {}
+ return 1, ["::error::Depot migration check did not finish within the report's deadline"], {}
+
+
+def main(argv: Sequence[str]) -> int:
+ mode = argv[1] if len(argv) > 1 else ""
+ env = os.environ
+ event = Event(repo=env["REPO"], sha=env["SHA"], pr_number=int(env["PR_NUMBER"]), event_at=env["EVENT_AT"])
+ reader = CheckRunReader(event.repo, event.sha, env["GH_TOKEN"])
+ try:
+ if mode == "gate":
+ result = poll(reader, event, GATE_CHECK, deadline_minutes=90, absent_minutes=15)
+ code, lines = relay_gate(result, event, env.get("GITHUB_RUN_ID", ""))
+ outputs: dict[str, str] = {}
+ elif mode == "migrations":
+ handoff_reader = CheckRunReader(event.repo, event.sha, env["GH_TOKEN"], app_id=GITHUB_ACTIONS_APP_ID)
+ if wait_for_handoff(handoff_reader, event):
+ result = poll(reader, event, MIGRATION_CHECK, deadline_minutes=70, absent_minutes=70)
+ else:
+ result = Progress(Phase.DECLINED, "skipped")
+ code, lines, outputs = report_migrations(result)
+ else:
+ sys.stderr.write("usage: ci_backend_relay.py gate|migrations\n")
+ return 2
+ except (ReadRefusedError, HandoffUnresolvedError) as error:
+ sys.stdout.write(f"::error::{error}\n")
+ return 1
+ sys.stdout.writelines(f"{line}\n" for line in lines)
+ output_path = env.get("GITHUB_OUTPUT")
+ if output_path and outputs:
+ with open(output_path, "a", encoding="utf-8") as handle:
+ handle.writelines(f"{key}={value}\n" for key, value in outputs.items())
+ return code
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/.github/scripts/ci_backend_route.py b/.github/scripts/ci_backend_route.py
index 740e16d3cdc0..0821523ef6e7 100644
--- a/.github/scripts/ci_backend_route.py
+++ b/.github/scripts/ci_backend_route.py
@@ -6,8 +6,7 @@ to Depot CI` job, which Depot CI waits for before it runs anything, so Depot nev
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, even after the rollout variable is deleted. A read of
-that record that keeps failing fails the run when the event would go to Depot, so
-nothing is routed anywhere, and otherwise leaves the event on GitHub Actions.
+that record that keeps failing stops routing, so a commit cannot run on both engines.
"""
import os
@@ -181,14 +180,8 @@ def main() -> int:
fetch_handoff_checks(env["REPO"], env["SHA"], env["GH_TOKEN"]), pr_number
)
except HandoffReadError as error:
- if route_with(None).engine == "depot":
- sys.stdout.write(f"::error::Cannot read the earlier hand-off, so this event is not routed: {error}\n")
- return 1
- # Staying on GitHub Actions never sends a commit to Depot twice. The worst case is
- # a GitHub rerun of a commit Depot already tested, which costs runners, not safety.
- sys.stdout.write(
- f"::warning::Cannot read the earlier hand-off, so this event stays on GitHub Actions: {error}\n"
- )
+ sys.stdout.write(f"::error::Cannot read the earlier hand-off, so this event is not routed: {error}\n")
+ return 1
else:
sys.stdout.write(f"::notice::Earlier hand-off on this commit: {prior_handoff or 'none'}\n")
decision = route_with(prior_handoff)
diff --git a/.github/scripts/test_ci_backend_relay.py b/.github/scripts/test_ci_backend_relay.py
new file mode 100644
index 000000000000..9a1774226e4c
--- /dev/null
+++ b/.github/scripts/test_ci_backend_relay.py
@@ -0,0 +1,426 @@
+import re
+import json
+import http.client
+import urllib.error
+import urllib.parse
+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_relay.py")
+SPEC = importlib.util.spec_from_file_location("ci_backend_relay", SCRIPT_PATH)
+assert SPEC is not None
+assert SPEC.loader is not None
+relay = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(relay)
+
+DEPOT_WORKFLOW_FILE = Path(__file__).parents[2] / ".depot" / "workflows" / "ci-backend.yml"
+PR = 105723
+EVENT_AT = "2026-09-24T09:54:20Z"
+EVENT = relay.Event(repo="PostHog/posthog", sha="a8a3755cf964", pr_number=PR, event_at=EVENT_AT)
+EVENT_WAIT = relay.wait_check_name(PR, EVENT_AT)
+PLAIN_WAIT = f"{relay.DEPOT_WORKFLOW} / {relay.WAIT_JOB}"
+
+
+def run(
+ id: int,
+ state: str,
+ workflow: str = "live",
+ started_at: str = "2026-09-24T09:56:00Z",
+ prs: Sequence[int] = (PR,),
+) -> Any:
+ completed = state not in relay.PENDING_STATES
+ return relay.CheckRun.from_api(
+ {
+ "id": id,
+ "status": "completed" if completed else state,
+ "conclusion": state if completed else None,
+ "started_at": started_at,
+ "pull_requests": [{"number": number} for number in prs],
+ "details_url": f"https://depot.dev/orgs/org1/workflows/{workflow}?job=j1&repo=PostHog%2Fposthog",
+ }
+ )
+
+
+def test_wait_job_name_matches_the_depot_workflow() -> None:
+ text = DEPOT_WORKFLOW_FILE.read_text()
+ job = text[text.index("\n wait-for-handoff:") :]
+ name = re.search(r"\n name: (.+)\n", job)
+ assert name is not None
+ expected = (
+ relay.WAIT_JOB
+ + "${{ github.event_name == 'pull_request' && format('"
+ + relay.EVENT_SUFFIX.replace("{pr}", "{0}").replace("{event_at}", "{1}")
+ + "', github.event.pull_request.number, github.event.pull_request.updated_at) || '' }}"
+ )
+ assert name.group(1) == expected
+
+
+ "event_waits,gates,expected",
+ [
+ pytest.param([], [], (relay.Phase.ABSENT, ""), id="no run yet"),
+ pytest.param([run(1, "in_progress")], [], (relay.Phase.STARTING, "in_progress"), id="waiting for hand-off"),
+ pytest.param([run(1, "failure")], [], (relay.Phase.DECLINED, "failure"), id="depot declined"),
+ pytest.param([run(1, "cancelled")], [], (relay.Phase.CANCELLED, "cancelled"), id="run cancelled"),
+ pytest.param(
+ [run(1, "success")],
+ [run(9, "cancelled", workflow="stale", started_at="2026-09-24T09:55:14Z")],
+ (relay.Phase.RUNNING, ""),
+ id="superseded run's cancelled gate is ignored",
+ ),
+ pytest.param(
+ [run(1, "success")],
+ [run(9, "cancelled", workflow="stale"), run(10, "success")],
+ (relay.Phase.FINISHED, "success"),
+ id="this run's gate wins over a newer id elsewhere",
+ ),
+ pytest.param(
+ [run(1, "success", prs=())],
+ [run(10, "success", prs=())],
+ (relay.Phase.FINISHED, "success"),
+ id="checks that list no pull request",
+ ),
+ pytest.param(
+ [run(1, "cancelled", workflow="dup1"), run(2, "success", workflow="dup2")],
+ [run(10, "failure", workflow="dup2")],
+ (relay.Phase.FINISHED, "failure"),
+ id="duplicate run of the event replaces a cancelled one",
+ ),
+ pytest.param(
+ [run(1, "success")],
+ [run(10, "cancelled")],
+ (relay.Phase.CANCELLED, "cancelled"),
+ id="this run cancelled after the hand-off",
+ ),
+ pytest.param(
+ [run(1, "success")],
+ [run(10, "failure"), run(11, "success")],
+ (relay.Phase.FINISHED, "success"),
+ id="retried gate",
+ ),
+ ],
+)
+def test_progress_of_this_events_run(event_waits: list[Any], gates: list[Any], expected: tuple[Any, str]) -> None:
+ wait = relay.newest_live(event_waits)
+ result = relay.progress(wait, gates)
+ assert (result.phase, result.state) == expected
+
+
+class FakeReader:
+ def __init__(self, polls: Sequence[dict[str, list[Any]]], advance_on: str = EVENT_WAIT) -> None:
+ self._polls = list(polls)
+ self._advance_on = advance_on
+ self.poll = 0
+ self.reads: list[str] = []
+
+ def read(self, name: str) -> list[Any]:
+ self.reads.append(name)
+ if name == self._advance_on:
+ self.poll += 1
+ return self._polls[min(self.poll, len(self._polls)) - 1].get(name, [])
+
+
+class FakeClock:
+ def __init__(self) -> None:
+ self.now = 0.0
+
+ def __call__(self) -> float:
+ return self.now
+
+ def sleep(self, seconds: float) -> None:
+ self.now += seconds
+
+
+ "polls,expected,min_minutes",
+ [
+ pytest.param(
+ [{EVENT_WAIT: [run(1, "cancelled", workflow="dup1")]}] * 3
+ + [{EVENT_WAIT: [run(1, "cancelled", workflow="dup1"), run(2, "success", workflow="dup2")]}]
+ + [
+ {
+ EVENT_WAIT: [run(1, "cancelled", workflow="dup1"), run(2, "success", workflow="dup2")],
+ relay.GATE_CHECK: [run(10, "success", workflow="dup2")],
+ }
+ ],
+ (relay.Phase.FINISHED, "success"),
+ 0,
+ id="a cancelled run is replaced within the grace window",
+ ),
+ pytest.param(
+ [{EVENT_WAIT: [run(1, "cancelled")]}],
+ (relay.Phase.CANCELLED, "cancelled"),
+ 15,
+ id="a cancelled run fails only after the grace window",
+ ),
+ pytest.param([{}], (relay.Phase.ABSENT, ""), 15, id="no run fails after the grace window"),
+ pytest.param(
+ [{EVENT_WAIT: [run(1, "success")]}],
+ (relay.Phase.RUNNING, ""),
+ 90,
+ id="a running gate hits the overall deadline",
+ ),
+ ],
+)
+def test_poll_waits_out_a_replacement_before_failing(
+ polls: list[dict[str, list[Any]]], expected: tuple[Any, str], min_minutes: int
+) -> None:
+ clock = FakeClock()
+ result = relay.poll(
+ FakeReader(polls),
+ EVENT,
+ relay.GATE_CHECK,
+ deadline_minutes=90,
+ absent_minutes=15,
+ clock=clock,
+ sleep=clock.sleep,
+ )
+ assert (result.phase, result.state) == expected
+ assert clock.now >= min_minutes * 60
+
+
+def test_poll_does_not_use_an_ambiguous_plain_named_wait() -> None:
+ clock = FakeClock()
+ reader = FakeReader([{PLAIN_WAIT: [run(1, "success")], relay.GATE_CHECK: [run(2, "success")]}])
+ result = relay.poll(
+ reader, EVENT, relay.GATE_CHECK, deadline_minutes=90, absent_minutes=15, clock=clock, sleep=clock.sleep
+ )
+ assert result.phase == relay.Phase.ABSENT
+ assert PLAIN_WAIT not in reader.reads
+
+
+ "checks,decision",
+ [
+ ([run(1, "success"), run(2, "skipped")], True),
+ ([run(1, "skipped")], False),
+ ([run(1, "cancelled"), run(2, "success", prs=(PR + 1,))], None),
+ ],
+)
+def test_handoff_decision_matches_the_router(checks: list[Any], decision: bool | None) -> None:
+ assert relay.handoff_decision(checks, PR) is decision
+
+
+def test_report_requires_a_confirmed_handoff_before_waiting_for_depot() -> None:
+ clock = FakeClock()
+ reader = FakeReader(
+ [{relay.HANDOFF_CHECK: [run(1, "queued")]}] * 2 + [{relay.HANDOFF_CHECK: [run(1, "success")]}],
+ advance_on=relay.HANDOFF_CHECK,
+ )
+ assert relay.wait_for_handoff(reader, EVENT, clock=clock, sleep=clock.sleep)
+ assert clock.now == 40
+
+
+def test_report_fails_when_handoff_cannot_be_read() -> None:
+ clock = FakeClock()
+ reader = FakeReader([{}], advance_on=relay.HANDOFF_CHECK)
+ with pytest.raises(relay.HandoffUnresolvedError):
+ relay.wait_for_handoff(reader, EVENT, clock=clock, sleep=clock.sleep)
+ assert clock.now == 10 * 60
+
+
+def test_report_waits_past_ten_minutes_after_handoff() -> None:
+ clock = FakeClock()
+ reader = FakeReader(
+ [{}] * 23
+ + [
+ {
+ EVENT_WAIT: [run(1, "success")],
+ relay.MIGRATION_CHECK: [run(2, "success")],
+ }
+ ]
+ )
+ result = relay.poll(
+ reader, EVENT, relay.MIGRATION_CHECK, deadline_minutes=70, absent_minutes=70, clock=clock, sleep=clock.sleep
+ )
+ assert (result.phase, result.state) == (relay.Phase.FINISHED, "success")
+ assert clock.now > 10 * 60
+
+
+def test_migration_report_stops_when_depot_did_not_receive_the_handoff() -> None:
+ clock = FakeClock()
+ result = relay.poll(
+ FakeReader(
+ [
+ {
+ EVENT_WAIT: [run(1, "success")],
+ relay.CHANGES_CHECK: [run(2, "skipped")],
+ }
+ ]
+ ),
+ EVENT,
+ relay.MIGRATION_CHECK,
+ deadline_minutes=70,
+ absent_minutes=10,
+ clock=clock,
+ sleep=clock.sleep,
+ )
+ assert result.phase == relay.Phase.DECLINED
+ assert relay.report_migrations(result)[0] == 0
+ assert clock.now == 0
+
+
+def test_migration_report_waits_for_a_late_replacement_of_a_cancelled_run() -> None:
+ clock = FakeClock()
+ result = relay.poll(
+ FakeReader(
+ [{EVENT_WAIT: [run(1, "cancelled")]}] * 25
+ + [
+ {
+ EVENT_WAIT: [run(1, "cancelled"), run(2, "success", workflow="replacement")],
+ relay.MIGRATION_CHECK: [run(3, "success", workflow="replacement")],
+ }
+ ]
+ ),
+ EVENT,
+ relay.MIGRATION_CHECK,
+ deadline_minutes=70,
+ absent_minutes=70,
+ clock=clock,
+ sleep=clock.sleep,
+ )
+ assert (result.phase, result.state) == (relay.Phase.FINISHED, "success")
+ assert clock.now > 10 * 60
+
+
+ "result,exit_code,first_line",
+ [
+ (relay.Progress(relay.Phase.FINISHED, "success"), 0, None),
+ (
+ relay.Progress(relay.Phase.FINISHED, "failure", "https://depot.dev/orgs/o/workflows/w1?job=j"),
+ 1,
+ "concluded failure",
+ ),
+ (relay.Progress(relay.Phase.CANCELLED, "cancelled"), 1, "cancelled its run"),
+ (relay.Progress(relay.Phase.DECLINED, "failure"), 1, "declined the hand-off"),
+ (relay.Progress(relay.Phase.ABSENT), 1, "started no run"),
+ (relay.Progress(relay.Phase.RUNNING), 1, "No Depot verdict"),
+ ],
+)
+def test_relay_gate_fails_closed(result: Any, exit_code: int, first_line: str | None) -> None:
+ code, lines = relay.relay_gate(result, EVENT, "123")
+ assert code == exit_code
+ if first_line is None:
+ assert lines == []
+ else:
+ assert first_line in lines[0]
+
+
+def test_relay_gate_names_the_failed_depot_run_to_retry() -> None:
+ _, lines = relay.relay_gate(
+ relay.Progress(relay.Phase.FINISHED, "failure", "https://depot.dev/orgs/o1/workflows/w1?job=j"), EVENT, "123"
+ )
+ assert " depot ci retry <run ID> --org o1 --workflow w1 --failed" in lines
+ assert " gh run rerun 123 --repo PostHog/posthog --failed # relays the new Depot result" in lines
+
+
+ "result,exit_code,outputs",
+ [
+ (
+ relay.Progress(relay.Phase.FINISHED, "failure", "https://depot.dev/orgs/o/workflows/w1?job=j"),
+ 0,
+ {"migration_state": "failure", "workflow_id": "w1"},
+ ),
+ (relay.Progress(relay.Phase.FINISHED, "success", "https://example.com/not-depot"), 1, {}),
+ (relay.Progress(relay.Phase.FINISHED, "skipped"), 0, {}),
+ (relay.Progress(relay.Phase.CANCELLED, "cancelled"), 0, {}),
+ (relay.Progress(relay.Phase.ABSENT), 1, {}),
+ (relay.Progress(relay.Phase.FINISHED, "timed_out"), 1, {}),
+ (relay.Progress(relay.Phase.RUNNING), 1, {}),
+ ],
+)
+def test_report_migrations(result: Any, exit_code: int, outputs: dict[str, str]) -> None:
+ code, _, written = relay.report_migrations(result)
+ assert (code, written) == (exit_code, outputs)
+
+
+class FakeResponse:
+ def __init__(self, body: bytes, etag: str) -> None:
+ self.status = 200
+ self.headers = {"ETag": etag}
+ self._body = body
+
+ def read(self) -> bytes:
+ return self._body
+
+ def __enter__(self) -> "FakeResponse":
+ return self
+
+ def __exit__(self, *_: object) -> None:
+ return None
+
+
+def test_handoff_reader_uses_the_github_actions_app() -> None:
+ requested: list[str] = []
+
+ def opener(request: Any, timeout: int) -> FakeResponse:
+ requested.append(request.full_url)
+ return FakeResponse(
+ b'{"check_runs":[{"id":1,"status":"completed","conclusion":"success",'
+ b'"pull_requests":[{"number":105723}]}]}',
+ '"e1"',
+ )
+
+ reader = relay.CheckRunReader(
+ "PostHog/posthog", EVENT.sha, "token", opener=opener, app_id=relay.GITHUB_ACTIONS_APP_ID
+ )
+ assert relay.handoff_decision(reader.read(relay.HANDOFF_CHECK), PR) is True
+ assert urllib.parse.parse_qs(urllib.parse.urlsplit(requested[0]).query)["app_id"] == [
+ str(relay.GITHUB_ACTIONS_APP_ID)
+ ]
+
+
+def test_reader_reuses_its_answer_on_304_and_stops_on_repeated_refusals() -> None:
+ sent: list[dict[str, str]] = []
+ answers: list[Any] = [
+ FakeResponse(b'{"check_runs": [{"id": 1, "status": "completed", "conclusion": "success"}]}', '"e1"'),
+ urllib.error.HTTPError("url", 304, "Not Modified", {}, None), # type: ignore[arg-type]
+ *[urllib.error.HTTPError("url", 403, "Forbidden", {}, None) for _ in range(relay.MAX_REFUSALS)], # type: ignore[arg-type]
+ ]
+
+ def opener(request: Any, timeout: int) -> Any:
+ sent.append(dict(request.header_items()))
+ answer = answers.pop(0)
+ if isinstance(answer, Exception):
+ raise answer
+ return answer
+
+ reader = relay.CheckRunReader("PostHog/posthog", "abc", "token", opener=opener)
+ assert [check.state for check in reader.read(relay.GATE_CHECK)] == ["success"]
+ assert [check.state for check in reader.read(relay.GATE_CHECK)] == ["success"]
+ assert sent[1]["If-none-match"] == '"e1"'
+ for _ in range(relay.MAX_REFUSALS - 1):
+ reader.read(relay.GATE_CHECK)
+ with pytest.raises(relay.ReadRefusedError):
+ reader.read(relay.GATE_CHECK)
+
+
[email protected]("page", [1, 2])
+ "error",
+ [ConnectionResetError("reset"), http.client.IncompleteRead(b""), ValueError("invalid JSON")],
+)
+def test_reader_retries_interrupted_pages_without_reusing_a_stale_verdict(page: int, error: Exception) -> None:
+ payload = {"id": 1, "status": "completed", "conclusion": "success"}
+ answers: list[Any] = [FakeResponse(json.dumps({"check_runs": [payload]}).encode(), '"e1"')]
+ if page == 2:
+ answers.append(FakeResponse(json.dumps({"check_runs": [payload] * relay.PAGE_SIZE}).encode(), '"e2"'))
+ answers += [error, FakeResponse(b'{"check_runs": []}', '"e3"')]
+
+ def opener(request: Any, timeout: int) -> FakeResponse:
+ answer = answers.pop(0)
+ if isinstance(answer, Exception):
+ raise answer
+ return answer
+
+ reader = relay.CheckRunReader("PostHog/posthog", "abc", "token", opener=opener)
+ assert reader.read(relay.GATE_CHECK)[0].state == "success"
+ assert reader.read(relay.GATE_CHECK) == []
+ assert reader.read(relay.GATE_CHECK) == []
+ assert not answers
diff --git a/.github/scripts/test_ci_backend_route.py b/.github/scripts/test_ci_backend_route.py
index 5c5142e4c538..c98a7c5bd3ec 100644
--- a/.github/scripts/test_ci_backend_route.py
+++ b/.github/scripts/test_ci_backend_route.py
@@ -195,18 +195,18 @@ def test_main_keeps_a_handed_off_commit_on_depot_after_rollback(
@pytest.mark.parametrize(
- "percent,labels,exit_code",
+ "percent,labels",
[
- ("50", "[]", 1),
- ("", json.dumps(["ci-backend-depot"]), 1),
- ("5", "[]", 0),
- ("0", "[]", 0),
- ("", "[]", 0),
- ("50", json.dumps(["ci-backend-github"]), 0),
+ ("50", "[]"),
+ ("", json.dumps(["ci-backend-depot"])),
+ ("5", "[]"),
+ ("0", "[]"),
+ ("", "[]"),
+ ("50", json.dumps(["ci-backend-github"])),
],
)
-def test_main_fails_on_an_unreadable_handoff_only_when_depot_would_run(
- percent: str, labels: str, exit_code: int, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+def test_main_never_switches_engines_on_an_unreadable_handoff(
+ percent: str, labels: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
def failing(repo: str, sha: str, token: str) -> list[dict[str, Any]]:
raise route.HandoffReadError("boom")
@@ -222,8 +222,5 @@ def test_main_fails_on_an_unreadable_handoff_only_when_depot_would_run(
monkeypatch.setenv("GH_TOKEN", "t")
monkeypatch.setattr(route, "fetch_handoff_checks", failing)
monkeypatch.setattr(route.time, "sleep", lambda seconds: None)
- assert route.main() == exit_code
- if exit_code:
- assert not output.exists()
- else:
- assert output.read_text().startswith("engine=github\n")
+ assert route.main() == 1
+ assert not output.exists()
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index daba33b74e50..6b91104e4a1f 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -4188,12 +4188,16 @@ 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: Check out the relay script
+ if: needs.changes.outputs.engine == 'depot'
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ sparse-checkout: .github/scripts/ci_backend_relay.py
+ sparse-checkout-cone-mode: false
+ persist-credentials: false
+ # The script finds this event's Depot run by the event in its wait job's check
+ # name, then waits for that run's gate. Its docstring explains why check times
+ # and pull request lists cannot identify the run.
- name: Relay the Depot verdict
if: needs.changes.outputs.engine == 'depot'
env:
@@ -4201,110 +4205,8 @@ jobs:
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')"
- # shellcheck disable=SC2016 # $since and $pr are jq variables
- latest_run='[.check_runs[] | select((.started_at // "") >= $since and any(.pull_requests[]?; .number == $pr))] | max_by(.id)'
- # 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" "$latest_run"' | 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) ;;
- *)
- depot_url=$(jq -r --arg since "$EVENT_AT" --argjson pr "$PR_NUMBER" "$latest_run"' | .details_url // ""' /tmp/relay-gate)
- echo "::error::Backend tests on Depot CI concluded $gate. This step's log lists the retry options."
- printf '%s\n' \
- "Backend tests for $SHA ran on Depot CI, not GitHub Actions. Re-running this job alone reads the same result." \
- "Depot run: ${depot_url:-not found}" \
- ""
- if [[ $depot_url =~ ^https://depot\.dev/orgs/([^/]+)/workflows/([a-z0-9]+) ]]; then
- org=${BASH_REMATCH[1]}
- workflow=${BASH_REMATCH[2]}
- printf '%s\n' \
- "Retry through the Depot CLI (needs access to the Depot org $org):" \
- " depot ci diagnose --org $org --workflow $workflow # the failures, and the run ID on the 'Run:' line" \
- " depot ci retry <run ID> --org $org --workflow $workflow --failed" \
- " depot ci status <run ID> --org $org # repeat until the run finishes" \
- " gh run rerun $GITHUB_RUN_ID --repo $REPO --failed # relays the new Depot result" \
- ""
- fi
- printf '%s\n' \
- "Retry without Depot access: a new commit starts a fresh run." \
- " git commit --allow-empty -m 'chore: retry backend ci' && git push" \
- "" \
- "Run on GitHub Actions instead: the ci-backend-github label routes the next commit of this PR there." \
- " gh pr edit $PR_NUMBER --repo $REPO --add-label ci-backend-github" \
- " git commit --allow-empty -m 'chore: retry backend ci on github actions' && git push"
- 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
+ run: python3 .github/scripts/ci_backend_relay.py gate
- name: Summarize dependency results
if: needs.changes.outputs.engine != 'depot'
run: |
@@ -4576,6 +4478,7 @@ jobs:
(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'
+ && needs.changes.result == 'success'
permissions:
contents: read
actions: read
@@ -4738,6 +4641,7 @@ jobs:
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'
+ && needs.changes.result == 'success'
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
diff --git a/docs/published/handbook/engineering/fork-pull-requests.md b/docs/published/handbook/engineering/fork-pull-requests.md
index 209f0af739fd..2ea8ce299faa 100644
--- a/docs/published/handbook/engineering/fork-pull-requests.md
+++ b/docs/published/handbook/engineering/fork-pull-requests.md
@@ -6,6 +6,8 @@ sidebar: Handbook
Backend CI runs on one of two engines per pull request, decided by `.github/scripts/ci_backend_route.py`: GitHub Actions or Depot CI.
Depot CI never runs a fork's code, so the router sends every fork pull request to GitHub Actions.
The required `Django Tests Pass` check is a GitHub Actions job on every head, fork or not, and nothing about the merge queue changes for a fork.
+For in-repository PRs, an unreadable prior routing decision stops CI instead of switching engines.
+The Depot relay matches the PR event's named wait check and reads only that Depot workflow's verdict; it never starts GitHub tests after a timeout.
What a fork contributor sees:
diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.ts
index f37751b25c47..38b4a8b81652 100644
--- a/tools/workflow-plan/tests/workflows.test.ts
+++ b/tools/workflow-plan/tests/workflows.test.ts
@@ -227,6 +227,23 @@ const EXPECTATIONS: Expectation[] = [
],
}
),
+ backend(
+ { name: 'routing record unreadable', steps: { changes: { route: { outcome: 'failure' } } } },
+ {
+ runs: ['django_tests'],
+ results: { changes: 'failure' },
+ skipped: [
+ 'hand-off-to-depot',
+ 'django',
+ 'turbo-tests',
+ 'check-migrations',
+ 'handle-snapshots',
+ 'report-test-timings',
+ 'calculate-running-time',
+ 'backend-coverage-report',
+ ],
+ }
+ ),
backend(
{ name: 'merge queue', github: mergeQueue() },
{