: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): cancel superseded depot backend runs in event order (#108682)
Raúl Negrón-Otero7d265d900cbd
diff --git a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md b/.agents/skills/depot-ci/references/posthog-check-run-semantics.mdindex c192b8bc198e..864a47222778 100644--- a/.agents/skills/depot-ci/references/posthog-check-run-semantics.md+++ b/.agents/skills/depot-ci/references/posthog-check-run-semantics.md@@ -87,6 +87,15 @@ GitHub Actions alone does the same. Among the 946 `ci-backend.yml` pull requestThe newest check per name tells you the verdict. It does not tell you whether the PR can merge. A cancelled run on the same head keeps its checks, and when one of them is a required check, GitHub's merge box and Trunk keep the PR blocked until that run is rerun. `/merging-prs` has the recipe.+### Superseded runs++Depot's concurrency policy keeps the workflow it created last, and a Depot run gets its workflow some time after the run itself, so the policy can keep an older event. Measured 2026-09-29 on 284 `ci-backend.yml` pull request workflows: the workflow followed its run by 55 seconds at the median and 120 seconds at most, and in 11 of 165 consecutive run pairs of one pull request the older run's workflow was created first or in the same second. Two of those cancelled the event that GitHub Actions had handed off, and the relay failed with "Depot CI started no run for this event":++- PR 107856: run `wq9rjmvr7z` for head `056fb05982` was created at 16:09:59Z and got its workflow at 16:11:10Z. Run `0k16ml32s1` for the newer head `b9fbb26201` was created at 16:10:18Z and got its workflow at 16:11:09Z, so Depot cancelled `0k16ml32s1`.+- PR 108622: two events of `d484f7a101` at 18:29:23Z and 18:29:34Z. GitHub Actions kept the second. Depot kept the first, whose gate passed, and the relay's 2-second racing window did not reach it.++Run creation keeps event order: across 138 pairs of distinct events, each run's `created_at` followed its event by 1 to 12 seconds and never inverted. Across 356 consecutive run pairs of one pull request, Depot's run order matched GitHub Actions' run order in 355, and the other pair was a same-second tie on GitHub. So `.depot/workflows/ci-backend.yml` gives each event its own concurrency group, and its `cancel-superseded-runs` job orders the pull request's runs by run `created_at`, and the run id breaks a same-second tie on one commit. Each run cancels the older runs it sees, and cancels itself when it sees a newer run, so the run whose workflow Depot creates last settles each pair.+## pull_request_target checksDepot can post a `pull_request_target` job's check on another pull request's head commit. A `pull_request_target` run's `github.sha` is the base branch head, so pull requests opened against the same master commit share it, and every misplaced check measured sat on a commit whose own run shared that base commit. Measured 2026-09-25 on a migration report workflow that ran on `pull_request_target`: 35 of its 42 checks sat on the wrong commit. For example, check `108123656729` on PR 106758's head `0295b92b41` links Depot workflow `ljv421dmlt`, whose run `vpg4b1kvh7` tested PR 106767's head `fb236b6c26`, and both runs had base `7af9307723`. The jobs' own writes, a check posted with an explicit `head_sha` and a comment on an explicit PR number, reached the right pull request. Post pull-request-facing results from a `pull_request` workflow, whose checks land on the right head.diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 1207adb25d71..6fe16451541e 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -53,6 +53,9 @@# secrets and cannot authenticate to Depot Cache) prime instead of migrating from scratch.# The shadow routes cache writes to Depot Cache, so it must not fill the GitHub# cache. This job and the mig_schema_key output that feeds it remain depot-exempt.+# - Superseded-run cancel: Depot's concurrency policy can keep an older event, so each event gets+# its own group and `cancel-superseded-runs` cancels older runs. See "Superseded runs" in+# .agents/skills/depot-ci/references/posthog-check-run-semantics.md.# - Deterministic-failure self-cancel: `depot ci cancel` with DEPOT_CI_CANCEL_TOKEN replaces# `gh run cancel` with github.token, which only reaches GitHub Actions runs.# - calculate-running-time: canonical's PostHog/posthog-github-action reads the run from the@@ -158,9 +161,9 @@ on:# the doubled matrices in place of that leg.types: [opened, synchronize, reopened, ready_for_review]concurrency:- # PRs: one active run per branch, cancel stale. Push: per-SHA so master+ # PRs: one group per event; cancel-superseded-runs cancels stale runs. Push: per-SHA so master# pushes never cancel each other (check-migrations always completes).- group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.head_ref || github.ref }}+ group: ${{ github.workflow }}-${{ github.event_name == 'push' && github.sha || github.event_name == 'pull_request' && format('pr-{0}-{1}-{2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.updated_at) || github.head_ref || github.ref }}cancel-in-progress: ${{ github.event_name == 'pull_request' }}env:# Schema cache epoch. Bump to abandon every shared schema cache entry at once@@ -333,6 +336,26 @@ jobs:}post "$WAIT_CHECK" success[ "$HANDED_OFF" = true ] || post "$GATE_CHECK" skipped+ cancel-superseded-runs:+ if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository+ runs-on: depot-ubuntu-24.04+ timeout-minutes: 5+ name: Cancel superseded Backend CI runs+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ sparse-checkout: .github/scripts/cancel_superseded_depot_runs.py+ sparse-checkout-cone-mode: false+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1+ - name: Cancel this PR's older runs+ continue-on-error: true+ env:+ DEPOT_TOKEN: ${{ secrets.DEPOT_CI_CANCEL_TOKEN }}+ REPO: ${{ github.repository }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ run: python3 .github/scripts/cancel_superseded_depot_runs.py# Job to decide if we should run backend ci# See .github/actions/paths-filter/README.md for filter semanticschanges:diff --git a/.github/scripts/cancel_superseded_depot_runs.py b/.github/scripts/cancel_superseded_depot_runs.pynew file mode 100644index 000000000000..de6140796e10--- /dev/null+++ b/.github/scripts/cancel_superseded_depot_runs.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""Cancel the Backend CI runs on Depot CI that a later event of the same pull request superseded.++Depot's concurrency policy keeps the workflow it created last, and Depot can create an older+event's workflow after a newer one's. Runs keep event order, so this script orders by run.+A run cancels the older runs it sees, and cancels itself when it sees a newer one, so the run+whose workflow Depot creates last settles each pair.+See "Superseded runs" in .agents/skills/depot-ci/references/posthog-check-run-semantics.md.++Standard library only: the job runs this with the runner's python3 before any install.+"""++import os+import re+import sys+import json+import subprocess+from collections.abc import Sequence+from dataclasses import dataclass+from datetime import datetime++WORKFLOW_PATH = "ci-backend.yml"+ACTIVE = ("queued", "running")+ALL = (*ACTIVE, "finished", "failed", "cancelled")+DEPOT_JOB_URL = re.compile(r"^https://depot\.dev/orgs/[^/?]+/workflows/([a-z0-9]+)")+CLI_TIMEOUT_SECONDS = 60+++@dataclass(frozen=True, kw_only=True, slots=True)+class Run:+ run_id: str+ created_at: datetime+ head_sha: str++ def supersedes(self, other: "Run") -> bool:+ # The run id cannot tell which of two commits is the PR's head, so a same-second tie between commits keeps both.+ if self.created_at != other.created_at:+ return self.created_at > other.created_at+ return self.head_sha == other.head_sha and self.run_id > other.run_id+++@dataclass(frozen=True, kw_only=True, slots=True)+class Workflow:+ workflow_id: str+ run_id: str+ path: str+++def superseded(own_workflow_id: str, active_workflows: Sequence[Workflow], runs: Sequence[Run]) -> list[Workflow]:+ runs_by_id = {run.run_id: run for run in runs}+ own = {workflow.workflow_id: workflow for workflow in active_workflows}[own_workflow_id]+ me = runs_by_id[own.run_id]+ if any(run.supersedes(me) for run in runs):+ return [own]+ return [+ workflow+ for workflow in active_workflows+ if workflow.path == WORKFLOW_PATH+ and workflow.run_id in runs_by_id+ and me.supersedes(runs_by_id[workflow.run_id])+ ]+++def depot(*args: str) -> list[dict[str, str]]:+ result = subprocess.run(+ ["depot", "ci", *args], check=True, capture_output=True, text=True, timeout=CLI_TIMEOUT_SECONDS+ )+ # `depot ci run list` prints `null` when nothing matches.+ return json.loads(result.stdout) or []+++def list_pr(noun: str, repo: str, pr_number: str, statuses: Sequence[str]) -> list[dict[str, str]]:+ scope = ["--repo", repo, "--pr", pr_number, "--trigger", "pull_request", "-n", "200", "-o", "json"]+ return depot(noun, "list", *scope, *(flag for status in statuses for flag in ("--status", status)))+++def main() -> int:+ match = DEPOT_JOB_URL.match(os.environ.get("DEPOT_JOB_URL", ""))+ if not match:+ sys.stdout.write("::warning::DEPOT_JOB_URL names no workflow, so no run was cancelled.\n")+ return 0+ repo, pr_number = os.environ["REPO"], os.environ["PR_NUMBER"]+ try:+ # Workflows first, so the run of every listed workflow is in the run list.+ workflows = [+ Workflow(workflow_id=row["workflow_id"], run_id=row["run_id"], path=row["workflow_path"])+ for row in list_pr("workflow", repo, pr_number, ACTIVE)+ ]+ runs = [+ Run(run_id=row["run_id"], created_at=datetime.fromisoformat(row["created_at"]), head_sha=row["head_sha"])+ for row in list_pr("run", repo, pr_number, ALL)+ ]+ targets = superseded(match[1], workflows, runs)+ except (subprocess.SubprocessError, KeyError, ValueError) as error:+ sys.stdout.write(f"::warning::Could not read this PR's Depot runs, so no run was cancelled: {error!r}\n")+ return 0+ for workflow in targets:+ sys.stdout.write(f"Cancelling superseded run {workflow.run_id} (workflow {workflow.workflow_id})\n")+ try:+ subprocess.run(+ ["depot", "ci", "cancel", workflow.run_id, "--workflow", workflow.workflow_id],+ check=True,+ timeout=CLI_TIMEOUT_SECONDS,+ )+ except subprocess.SubprocessError:+ sys.stdout.write(f"::warning::Could not cancel run {workflow.run_id}\n")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/scripts/test_cancel_superseded_depot_runs.py b/.github/scripts/test_cancel_superseded_depot_runs.pynew file mode 100644index 000000000000..5f47f721c6c0--- /dev/null+++ b/.github/scripts/test_cancel_superseded_depot_runs.py@@ -0,0 +1,46 @@+import importlib.util+from datetime import datetime+from pathlib import Path++import pytest++SCRIPT_PATH = Path(__file__).with_name("cancel_superseded_depot_runs.py")+SPEC = importlib.util.spec_from_file_location("cancel_superseded_depot_runs", SCRIPT_PATH)+assert SPEC is not None+assert SPEC.loader is not None+script = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(script)+++def run(run_id: str, second: int, head_sha: str = "head") -> "script.Run":+ return script.Run(+ run_id=run_id, created_at=datetime.fromisoformat(f"2026-09-30T12:00:{second:02d}Z"), head_sha=head_sha+ )+++def workflow(run_id: str, path: str = "ci-backend.yml") -> "script.Workflow":+ return script.Workflow(workflow_id=f"w{run_id}", run_id=run_id, path=path)+++ "runs,others,expected",+ [+ pytest.param([run("old", 0), run("me", 5)], ["old"], ["old"], id="older_run"),+ pytest.param([run("me", 0), run("new", 5)], ["new"], ["me"], id="newer_run_cancels_self"),+ pytest.param([run("old", 0), run("me", 5), run("new", 9)], ["old", "new"], ["me"], id="newer_run_leaves_older"),+ pytest.param([run("me", 0), run("new", 5)], [], ["me"], id="newer_run_already_ended"),+ pytest.param([run("a", 5), run("me", 5)], ["a"], ["a"], id="same_commit_tie_higher_id_wins"),+ pytest.param([run("me", 5), run("z", 5)], ["z"], ["me"], id="same_commit_tie_lower_id_loses"),+ pytest.param([run("a", 5, "other"), run("me", 5), run("z", 5, "other")], ["a", "z"], [], id="two_commit_tie"),+ ],+)+def test_superseded(runs: list["script.Run"], others: list[str], expected: list[str]) -> None:+ workflows = [workflow("me"), *(workflow(run_id) for run_id in others)]++ assert [target.run_id for target in script.superseded("wme", workflows, runs)] == expected+++def test_superseded_ignores_other_workflow_files() -> None:+ workflows = [workflow("me"), workflow("old", path="other.yml")]++ assert script.superseded("wme", workflows, [run("old", 0), run("me", 5)]) == []