: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
fix(ci): retry depot backend tests from a github re-run (#110137)
Raúl Negrón-Oteroe73087991b7a
diff --git a/.agents/skills/debugging-ci-failures/SKILL.md b/.agents/skills/debugging-ci-failures/SKILL.mdindex 10f2becf3866..bbc723edfede 100644--- a/.agents/skills/debugging-ci-failures/SKILL.md+++ b/.agents/skills/debugging-ci-failures/SKILL.md@@ -250,11 +250,11 @@ history, hand off to `fixing-flaky-tests`, which covers the `search-test` andA PR can route its backend tests to Depot CI.Then the GitHub Actions run holds only the relay: `Django Tests Pass` fails with "Backend tests on Depot CI concluded failure", and the GitHub run logs show nothing more.-`gh run rerun` reads the same Depot result again.-The log of the `Relay the Depot verdict` step prints the Depot run URL, the `depot ci` commands that diagnose and retry it, and the retry options that need no Depot access.+A re-run of that job is not read-only: it retries the failed Depot jobs and reports the new verdict, so the rule against re-running CI applies to it.+The log of the `Relay the Depot verdict` step prints the Depot run URL, each failed step with its log lines, and the label that sends the PR back to GitHub Actions.-Read the failure from Depot with the `depot` CLI, which the flox environment installs.-Run the `depot ci diagnose` command from the relay log, which already fills in the org and workflow ids.+Read more of the failure from Depot with the `depot` CLI, which the flox environment installs.+Run `depot ci diagnose --org <org> --workflow <workflow>` with the two ids from the Depot run URL in the relay log.For logs, artifacts, and test results, load the `depot-ci` skill.Its `references/posthog-check-run-semantics.md` gets Depot ids from a commit's check runs when you have no relay log.If a `depot` command fails to authenticate, check `DEPOT_TOKEN` first: it overrides the saved login, so a wrong one fails every command.diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex b9f7a7080ef4..94a955aa04b8 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -13,9 +13,10 @@# `Django Tests Pass` gate then relays this workflow's gate verdict. Its first step posts the# `Depot run started` check that canonical's router waits for. Neither the router, the# hand-off job, nor the relay has a counterpart here. A GitHub rerun does not restart this-# workflow, so the relay's failure log prints the `depot ci` commands that retry it, and the-# label that sends the PR back to GitHub Actions. It also prints each failed step and its log-# lines, read with `depot ci diagnose`, because Depot's own checks carry no output.+# workflow, so a re-run of the relay job retries this workflow's failed jobs with `depot ci retry`.+# The relay's failure log prints the label that sends the PR back to GitHub Actions, and each+# failed step and its log lines, read with `depot ci diagnose`, because Depot's own checks+# carry no output.# - runs-on: depot-* labels instead of GitHub-hosted ubuntu-24.04# - turbo-discover adds the `origin` remote before its history fetch when it is missing.# Depot CI serves an input-less actions/checkout from a fast clone that has no remote.diff --git a/.github/scripts/ci_backend_depot_failures.py b/.github/scripts/ci_backend_depot_failures.pyindex c87fe7c81aec..1a75a64a3cf1 100644--- a/.github/scripts/ci_backend_depot_failures.py+++ b/.github/scripts/ci_backend_depot_failures.py@@ -25,6 +25,13 @@ def escape_annotation(text: str) -> str:return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")+def depot_ci(*args: str) -> Any:+ result = subprocess.run(+ ["depot", "ci", *args, "--output", "json"], capture_output=True, text=True, check=True, timeout=60+ )+ return json.loads(result.stdout)++def explain(org: str, workflow: str) -> list[str]:"""Workflow commands: one error annotation per failed step, with its log lines as the message.@@ -32,14 +39,8 @@ def explain(org: str, workflow: str) -> list[str]:@actions/core escapes it, they stay on the annotation's line and cannot start a command."""try:- result = subprocess.run(- ["depot", "ci", "diagnose", "--workflow", workflow, "--org", org, "--output", "json"],- capture_output=True,- text=True,- check=True,- timeout=60,- )- messages = [message(attempt) for attempt in json.loads(result.stdout)["representative_attempts"]]+ diagnosis = depot_ci("diagnose", "--workflow", workflow, "--org", org)+ messages = [message(attempt) for attempt in diagnosis["representative_attempts"]]except Exception as error:return [f"::warning::Cannot read the Depot failure details: {type(error).__name__}"]return [f"::error title=Failed on Depot::{escape_annotation(text)}" for text in messages]diff --git a/.github/scripts/ci_backend_relay.py b/.github/scripts/ci_backend_relay.pyindex 01594066c2b4..cbeb09346c21 100644--- a/.github/scripts/ci_backend_relay.py+++ b/.github/scripts/ci_backend_relay.py@@ -31,6 +31,7 @@ import reimport sysimport jsonimport time+import subprocessimport http.clientimport urllib.errorimport urllib.parse@@ -41,7 +42,7 @@ from datetime import datetime, timedeltafrom enum import Enumfrom typing import Any, Protocol-from ci_backend_depot_failures import explain+from ci_backend_depot_failures import depot_ci, explainDEPOT_APP_ID = 219785DEPOT_ORG = "ntsdt08fpt"@@ -76,6 +77,12 @@ PAGE_SIZE = 100# A 403 also covers a secondary rate limit, which clears, so a few refusals in a row are tolerated.MAX_REFUSALS = 5PREREQUISITES = ("Repo checks (depot-ubuntu-24.04)", "Validate OpenAPI types")+# Depot's key for the `django_tests` job of .depot/workflows/ci-backend.yml, and how it names job states.+GATE_JOB_KEY = "ci-backend.yml:django_tests"+DEPOT_LIVE_STATES = frozenset({"queued", "waiting", "running"})+DEPOT_JOB_CONCLUSIONS = {"finished": "success", "failed": "failure"}+# Under the `timeout-minutes` of the `Django Tests Pass` job, so the relay reports before GitHub ends the job.+GATE_DEADLINE_MINUTES = 90class ReadRefusedError(RuntimeError):@@ -392,28 +399,91 @@ def poll(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'}",+def retry_failed_jobs(+ org: str,+ workflow: str,+ *,+ depot: Callable[..., Any] = depot_ci,+ clock: Callable[[], float] = time.monotonic,+ sleep: Callable[[float], None] = time.sleep,+) -> Progress | None:+ """Retries the workflow's failed jobs on Depot and returns the gate's new verdict, or None when Depot cannot be reached.++ Depot refuses a retry while the workflow runs, so the retry waits for the workflow to finish.+ A retry adds one execution to the workflow and queues the gate job in the same call. So the gate's+ state is the new verdict once the workflow has more executions than it had when the retry was sent.+ A gate that another retry turned green in the meantime is relayed as it is.+ """+ start = clock()+ url = f"https://depot.dev/orgs/{org}/workflows/{workflow}"+ executions_at_retry: int | None = None+ failures = 0+ while True:+ sending = False+ try:+ shown = depot("workflow", "show", workflow, "--org", org)+ gate = next(job["status"] for job in shown["jobs"] if job["job_key"] == GATE_JOB_KEY)+ executions = len(shown["executions"])+ status = shown["workflow"]["status"]+ sys.stdout.write(f"Depot workflow: {status}, gate {gate}\n")+ retried = executions_at_retry is not None and executions > executions_at_retry+ if gate == "finished" or (retried and gate not in DEPOT_LIVE_STATES):+ phase = Phase.CANCELLED if gate == "cancelled" else Phase.FINISHED+ return Progress(phase, DEPOT_JOB_CONCLUSIONS.get(gate, gate), url)+ failures = 0+ if executions_at_retry is None and status not in DEPOT_LIVE_STATES:+ sending = True+ depot("retry", shown["run"]["run_id"], "--workflow", workflow, "--org", org, "--failed")+ executions_at_retry = executions+ sys.stdout.write(f"Depot retries the failed jobs: {url}\n")+ except (subprocess.SubprocessError, OSError, ValueError, LookupError, TypeError, StopIteration) as error:+ failures += 1+ sys.stdout.write(f"::warning::Depot CLI call failed: {type(error).__name__}\n")+ # A retry that failed is not sent again, because Depot can have accepted it.+ if sending or failures >= MAX_REFUSALS:+ return None+ if clock() - start >= GATE_DEADLINE_MINUTES * 60:+ return Progress(Phase.RUNNING, details_url=url)+ sleep(30)+++def gate_verdict(+ reader: CheckReader,+ event: Event,+ *,+ rerun: bool,+ retry: Callable[[str, str], Progress | None] = retry_failed_jobs,+) -> Progress:+ """The gate verdict that this attempt of the relay job reports.++ A GitHub re-run starts nothing on Depot. So when a re-run finds a gate that already failed,+ the relay retries the failed Depot jobs and reports the new verdict. A failed prerequisite+ is not retried, because it fails the same way until a commit fixes it.+ """+ if rerun:+ settled = poll(reader, event, GATE_CHECK, deadline_minutes=0, absent_minutes=0)+ target = DEPOT_RUN_URL.match(settled.details_url)+ if target and settled.phase == Phase.FINISHED and settled.state != "success" and not settled.root_failure:+ retried = retry(*target.groups())+ if retried:+ return retried+ sys.stdout.write("::warning::Cannot retry on Depot CI. This is the earlier verdict.\n")+ return settled+ return poll(reader, event, GATE_CHECK, deadline_minutes=GATE_DEADLINE_MINUTES, absent_minutes=15)+++def retry_instructions(event: Event, details_url: str, run_id: str = "") -> list[str]:+ """The ways to run the tests again. A GitHub re-run retries a failed Depot run, so it is listed with a `run_id`."""+ rerun = [+ "Re-run this job on GitHub to retry the failed Depot jobs:",+ f" gh run rerun {run_id} --repo {event.repo} --failed","",]- 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",+ f"Backend tests for {event.sha} ran on Depot CI, not GitHub Actions.",+ f"Depot run: {details_url or 'not found'}","",+ *(rerun if run_id else []),"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",@@ -437,7 +507,7 @@ def relay_gate(result: Progress, event: Event, run_id: str) -> tuple[int, list[sif 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),+ *retry_instructions(event, result.details_url),]if result.phase == Phase.DECLINED:return 1, [f"::error::Depot declined the hand-off for {event.sha} (wait job: {result.state})"]@@ -454,7 +524,7 @@ def main(argv: Sequence[str]) -> int: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"], pr_number=event.pr_number)try:- result = poll(reader, event, GATE_CHECK, deadline_minutes=90, absent_minutes=15)+ result = gate_verdict(reader, event, rerun=env.get("GITHUB_RUN_ATTEMPT", "1") != "1")except ReadRefusedError as error:sys.stdout.write(f"::error::{error}\n")return 1diff --git a/.github/scripts/test_ci_backend_relay.py b/.github/scripts/test_ci_backend_relay.pyindex 201f5768a54e..2bee38a2313f 100644--- a/.github/scripts/test_ci_backend_relay.py+++ b/.github/scripts/test_ci_backend_relay.py@@ -1,5 +1,6 @@import reimport json+import subprocessimport http.clientimport urllib.errorimport urllib.parse@@ -306,12 +307,129 @@ def test_relay_gate_fails_closed(result: Any, exit_code: int, first_line: str |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"+def shown(workflow: str, gate: str, executions: int) -> dict[str, Any]:+ return {+ "workflow": {"status": workflow},+ "run": {"run_id": "r1"},+ "executions": [{}] * executions,+ "jobs": [+ {"job_key": "ci-backend.yml:changes", "status": "finished"},+ {"job_key": relay.GATE_JOB_KEY, "status": gate},+ ],+ }+++class FakeDepot:+ def __init__(self, shows: Sequence[Any]) -> None:+ self._shows = list(shows)+ self._last: dict[str, Any] = {}+ self.sent: list[tuple[str, ...]] = []++ def __call__(self, *args: str) -> Any:+ if args[0] != "workflow":+ # Depot refuses a retry of a workflow that still runs.+ assert self._last["workflow"]["status"] not in relay.DEPOT_LIVE_STATES+ self.sent.append(args)+ if self._last.get("refuses_retry"):+ raise subprocess.CalledProcessError(1, "depot")+ return {}+ answer = self._shows.pop(0) if len(self._shows) > 1 else self._shows[0]+ if isinstance(answer, Exception):+ raise answer+ self._last = answer+ return answer+++RETRY_FAILED = ("retry", "r1", "--workflow", "w1", "--org", "o1", "--failed")+++ "shows,expected,sent",+ [+ pytest.param(+ [+ shown("running", "failed", 1),+ shown("failed", "failed", 1),+ shown("failed", "failed", 1),+ shown("running", "queued", 2),+ shown("failed", "failed", 2),+ ],+ (relay.Phase.FINISHED, "failure"),+ [RETRY_FAILED],+ id="one retry, sent after the workflow finished, and the earlier verdict is not relayed",+ ),+ pytest.param(+ [shown("running", "queued", 2), shown("running", "finished", 2)],+ (relay.Phase.FINISHED, "success"),+ [],+ id="a gate that another retry turned green needs no retry",+ ),+ pytest.param(+ [shown("failed", "failed", 1), shown("running", "queued", 2)],+ (relay.Phase.RUNNING, ""),+ [RETRY_FAILED],+ id="a retry that never finishes hits the deadline",+ ),+ pytest.param([OSError("no depot CLI")], None, [], id="an unreachable Depot gives no verdict"),+ pytest.param(+ [{**shown("failed", "failed", 1), "refuses_retry": True}],+ None,+ [RETRY_FAILED],+ id="a refused retry is not sent again",+ ),+ ],+)+def test_retry_relays_only_the_verdict_of_the_new_execution(+ shows: list[Any], expected: tuple[Any, str] | None, sent: list[tuple[str, ...]]+) -> None:+ depot = FakeDepot(shows)+ clock = FakeClock()+ result = relay.retry_failed_jobs("o1", "w1", depot=depot, clock=clock, sleep=clock.sleep)+ assert (result and (result.phase, result.state)) == expected+ assert depot.sent == sent+++ "rerun,polls,prerequisite,retry_answer,expected,retries",+ [+ pytest.param(False, [run(10, "failure")], [], "success", "failure", 0, id="a first attempt retries nothing"),+ pytest.param(True, [run(10, "failure")], [], "success", "success", 1, id="a failed gate is retried"),+ pytest.param(True, [run(10, "success")], [], "failure", "success", 0, id="a passed gate is relayed"),+ pytest.param(True, [run(10, "failure")], [], None, "failure", 1, id="Depot unreachable"),+ pytest.param(True, [None, run(10, "success")], [], "failure", "success", 0, id="a running gate is awaited"),+ pytest.param(+ True,+ [run(10, "cancelled")],+ [run(20, "failure")],+ "success",+ "failure",+ 0,+ id="a failed prerequisite is not retried",+ ),+ ],+)+def test_only_a_rerun_with_a_failed_gate_retries_on_depot(+ rerun: bool, polls: list[Any], prerequisite: list[Any], retry_answer: str | None, expected: str, retries: int+) -> None:+ calls: list[tuple[str, str]] = []++ def retry(org: str, workflow: str) -> Any:+ calls.append((org, workflow))+ return retry_answer and relay.Progress(relay.Phase.FINISHED, retry_answer)++ reader = FakeReader(+ [+ {+ EVENT_WAIT: [run(1, "success")],+ relay.GATE_CHECK: [gate] if gate else [],+ f"{relay.DEPOT_WORKFLOW} / {relay.PREREQUISITES[0]}": prerequisite,+ }+ for gate in polls+ ])- 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 = relay.gate_verdict(reader, EVENT, rerun=rerun, retry=retry)+ assert result.state == expected+ assert calls == [(relay.DEPOT_ORG, "live")] * retriesdef api_check() -> dict[str, Any]: