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): hand backend ci to depot only once its run starts (#109153)

Raúl Negrón-Otero62c5e6e11e39
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 6fe16451541e..13824393cc50 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -10,10 +10,11 @@
# Intentional deltas vs canonical (everything else is kept apples-to-apples):
# - 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. 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
+# `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.
# - 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.
@@ -253,6 +254,19 @@ jobs:
client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
permission-checks: write
+ # .github/scripts/ci_backend_route.py waits for this check. Depot posts its own check
+ # for this job only when the job ends, which is after the hand-off.
+ - name: Tell GitHub Actions that Depot started a run for this event
+ if: github.event_name == 'pull_request' && steps.handoff-token.outputs.token != ''
+ continue-on-error: true
+ env:
+ GH_TOKEN: ${{ steps.handoff-token.outputs.token }}
+ REPO: ${{ github.repository }}
+ SHA: ${{ github.event.pull_request.head.sha }}
+ STARTED_CHECK: Backend CI on Depot / Depot run started (PR ${{ github.event.pull_request.number }}, event ${{ github.event.pull_request.updated_at }})
+ run: |
+ gh api "repos/$REPO/check-runs" --method POST -f name="$STARTED_CHECK" -f head_sha="$SHA" \
+ -f status=completed -f conclusion=success -f details_url="$DEPOT_JOB_URL" --silent
- name: Wait for the hand-off check from GitHub Actions
id: handoff
env:
diff --git a/.github/scripts/ci_backend_relay.py b/.github/scripts/ci_backend_relay.py
index 602bd918a8d9..01594066c2b4 100644
--- a/.github/scripts/ci_backend_relay.py
+++ b/.github/scripts/ci_backend_relay.py
@@ -145,8 +145,12 @@ class Progress:
root_check_id: int = 0
+def event_check_name(job: str, pr_number: int, event_at: str) -> str:
+ return f"{DEPOT_WORKFLOW} / {job}{EVENT_SUFFIX.format(pr=pr_number, event_at=event_at)}"
+
+
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)}"
+ return event_check_name(WAIT_JOB, pr_number, event_at)
def current_check(checks: Iterable[CheckRun], workflow: str | None) -> CheckRun | None:
diff --git a/.github/scripts/ci_backend_route.py b/.github/scripts/ci_backend_route.py
index 0821523ef6e7..52ff8bd18768 100644
--- a/.github/scripts/ci_backend_route.py
+++ b/.github/scripts/ci_backend_route.py
@@ -7,6 +7,13 @@ routes on its own and the tests never run on both engines. Once that job has con
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 stops routing, so a commit cannot run on both engines.
+
+Any other event goes to Depot only after Depot started a run for it. Depot compiles its run
+from the pull request's merge ref as soon as the event arrives, while GitHub Actions waits
+until GitHub has updated that ref. When the ref is missing, Depot ends the run with no
+workflows; when it stays stale, Depot fails to compile. Depot also cancels some runs under
+its concurrency policy before they start. Each case leaves the event with no Depot run, so
+it stays here.
"""
import os
@@ -17,9 +24,21 @@ import hashlib
import urllib.error
import urllib.parse
import urllib.request
+from collections.abc import Callable
from dataclasses import dataclass
+from datetime import UTC, datetime
from typing import Any
+from ci_backend_relay import (
+ EVENT_TIME,
+ MIRROR_APP_ID,
+ CheckReader,
+ CheckRunReader,
+ ReadFailedError,
+ ReadRefusedError,
+ event_check_name,
+)
+
LABEL_FORCE_GITHUB = "ci-backend-github"
LABEL_FORCE_DEPOT = "ci-backend-depot"
PERCENT_VARIABLE = "CI_BACKEND_DEPOT_PERCENT"
@@ -31,6 +50,11 @@ ENGINE_BY_HANDOFF_CONCLUSION = {"success": "depot", "skipped": "github"}
API_ROOT = "https://api.github.com"
API_ATTEMPTS = 3
API_BACKOFF_SECONDS = 5
+# The first step of Depot's wait job in .depot/workflows/ci-backend.yml posts this check; change both.
+STARTED_JOB = "Depot run started"
+# How long after the event Depot's wait job may take to start before the event stays on GitHub Actions.
+DEPOT_START_SECONDS = 180
+DEPOT_POLL_SECONDS = 10
class HandoffReadError(RuntimeError):
@@ -153,6 +177,36 @@ def fetch_handoff_checks(repo: str, sha: str, token: str, *, opener: Any = None)
raise HandoffReadError(f"GET {url} exhausted {API_ATTEMPTS} attempts")
+def depot_started(
+ reader: CheckReader,
+ pr_number: int,
+ event_at: str,
+ *,
+ clock: Callable[[], float] = time.time,
+ sleep: Callable[[float], None] = time.sleep,
+) -> bool:
+ """Whether Depot started a run for this event, waiting up to DEPOT_START_SECONDS after it.
+
+ The started check names the event, so it identifies this event's run and no other.
+ """
+ try:
+ deadline = datetime.strptime(event_at, EVENT_TIME).replace(tzinfo=UTC).timestamp() + DEPOT_START_SECONDS
+ except ValueError:
+ return False
+ name = event_check_name(STARTED_JOB, pr_number, event_at)
+ while True:
+ try:
+ if reader.read(name):
+ return True
+ except ReadFailedError:
+ pass
+ except ReadRefusedError:
+ return False
+ if clock() >= deadline:
+ return False
+ sleep(DEPOT_POLL_SECONDS)
+
+
def main() -> int:
env = os.environ
event = env.get("EVENT", "")
@@ -185,6 +239,17 @@ def main() -> int:
else:
sys.stdout.write(f"::notice::Earlier hand-off on this commit: {prior_handoff or 'none'}\n")
decision = route_with(prior_handoff)
+ if (
+ decision.engine == "depot"
+ and prior_handoff not in ENGINE_BY_HANDOFF_CONCLUSION
+ and pr_number is not None
+ and not depot_started(
+ CheckRunReader(env["REPO"], env["SHA"], env["GH_TOKEN"], pr_number=pr_number, app_ids=(MIRROR_APP_ID,)),
+ pr_number,
+ env.get("EVENT_AT", ""),
+ )
+ ):
+ decision = Decision("github", "Depot CI started no run for this event")
sys.stdout.write(f"::notice::Backend CI engine: {decision.engine} ({decision.reason})\n")
output_path = env.get("GITHUB_OUTPUT")
if output_path:
diff --git a/.github/scripts/test_ci_backend_route.py b/.github/scripts/test_ci_backend_route.py
index c98a7c5bd3ec..b21a642732c1 100644
--- a/.github/scripts/test_ci_backend_route.py
+++ b/.github/scripts/test_ci_backend_route.py
@@ -2,6 +2,7 @@ import json
import urllib.error
import importlib.util
from collections.abc import Sequence
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -14,6 +15,9 @@ assert SPEC.loader is not None
route = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(route)
+EVENT_AT = "2026-09-30T05:44:10Z"
+EVENT_EPOCH = datetime.strptime(EVENT_AT, route.EVENT_TIME).replace(tzinfo=UTC).timestamp()
+
def pr(
percent: int = 25, number: int | None = 125, labels: Sequence[str] = (), fork: bool = False, draft: bool = False
@@ -157,8 +161,19 @@ 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:
+ "labels,started,expected",
+ [
+ (json.dumps(["other"]), True, "engine=depot\nreason=bucket 30 < 50%\n"),
+ ("null", True, "engine=depot\nreason=bucket 30 < 50%\n"),
+ ("", True, "engine=depot\nreason=bucket 30 < 50%\n"),
+ ("[]", False, "engine=github\nreason=Depot CI started no run for this event\n"),
+ (json.dumps(["ci-backend-depot"]), False, "engine=github\nreason=Depot CI started no run for this event\n"),
+ ],
+)
+def test_main_writes_outputs(
+ labels: str, started: bool, expected: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
output = tmp_path / "out"
monkeypatch.setenv("GITHUB_OUTPUT", str(output))
monkeypatch.setenv("EVENT", "pull_request")
@@ -166,11 +181,12 @@ def test_main_writes_outputs(labels: str, tmp_path: Path, monkeypatch: pytest.Mo
monkeypatch.setenv("PR_NUMBER", "7")
monkeypatch.setenv("LABELS", labels)
monkeypatch.setattr(route, "fetch_handoff_checks", lambda repo, sha, token: [])
+ monkeypatch.setattr(route, "depot_started", lambda *_: started)
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 30 < 50%\n"
+ assert output.read_text() == expected
@pytest.mark.parametrize("percent", ["", "0", "5"])
@@ -190,6 +206,7 @@ def test_main_keeps_a_handed_off_commit_on_depot_after_rollback(
monkeypatch.setenv("SHA", "abc")
monkeypatch.setenv("GH_TOKEN", "t")
monkeypatch.setattr(route, "fetch_handoff_checks", fetch)
+ monkeypatch.setattr(route, "depot_started", lambda *_: False)
assert route.main() == 0
assert output.read_text().startswith("engine=depot\n")
@@ -224,3 +241,38 @@ def test_main_never_switches_engines_on_an_unreadable_handoff(
monkeypatch.setattr(route.time, "sleep", lambda seconds: None)
assert route.main() == 1
assert not output.exists()
+
+
+class FakeReader:
+ def __init__(self, polls: list[bool | Exception]) -> None:
+ self.polls = polls
+
+ def read(self, name: str) -> list[str]:
+ assert name == f"Backend CI on Depot / Depot run started (PR 7, event {EVENT_AT})"
+ answer = self.polls.pop(0) if len(self.polls) > 1 else self.polls[0]
+ if isinstance(answer, Exception):
+ raise answer
+ return ["check"] if answer else []
+
+
+ "polls,started,routed_after",
+ [
+ ([True], True, 15),
+ ([False, False, True], True, 15),
+ ([route.ReadFailedError("boom"), True], True, 15),
+ ([False], False, 15),
+ ([route.ReadRefusedError("refused")], False, 15),
+ ([False], False, 400),
+ ],
+)
+def test_depot_started_waits_for_the_started_check_of_the_event(
+ polls: list[bool | Exception], started: bool, routed_after: int
+) -> None:
+ now = [EVENT_EPOCH + routed_after]
+
+ def sleep(seconds: float) -> None:
+ now[0] += seconds
+
+ assert route.depot_started(FakeReader(polls), 7, EVENT_AT, clock=lambda: now[0], sleep=sleep) is started
+ assert now[0] <= max(EVENT_EPOCH + route.DEPOT_START_SECONDS + route.DEPOT_POLL_SECONDS, EVENT_EPOCH + routed_after)
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 0979ded67df0..ff284b15dc8a 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -190,6 +190,8 @@ jobs:
sparse-checkout: |
.github/actions/paths-filter
.github/scripts/ci_backend_route.py
+ .github/scripts/ci_backend_relay.py
+ .github/scripts/ci_backend_depot_failures.py
sparse-checkout-cone-mode: false
- name: Clean up data directories with container permissions
run: |
@@ -204,23 +206,6 @@ 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
@@ -499,6 +484,26 @@ jobs:
# Exec command reference templates - feed generate-exec-docs.ts
- 'services/mcp/src/templates/sections/**/*'
- 'services/mcp/schema/exec-command-reference.md'
+ # Last, so the paths filter runs while Depot starts its run for this event.
+ - 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, and the check of
+ # the Depot wait job that names this event.
+ GH_TOKEN: ${{ github.token }}
+ REPO: ${{ github.repository }}
+ SHA: ${{ github.event.pull_request.head.sha }}
+ EVENT_AT: ${{ github.event.pull_request.updated_at }}
+ run: python3 .github/scripts/ci_backend_route.py
# The only signal Depot CI acts on. Its wait job in .depot/workflows/ci-backend.yml
# polls this check by name and runs the backend tests only when it concluded