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): read depot push runs on master through github (#118608)

Raúl Negrón-Oterobdad453cc703
diff --git a/.github/scripts/depot_backend_runs.py b/.github/scripts/depot_backend_runs.py
index f83ebfef64e9..497ce75d0a39 100644
--- a/.github/scripts/depot_backend_runs.py
+++ b/.github/scripts/depot_backend_runs.py
@@ -15,11 +15,12 @@ it lists successful runs unless `--status` says otherwise.
`gh run download` produces. `gate-runs` writes the newest runs of one trigger as JSON, each
with the conclusion of its gate job, in the shape .github/scripts/ci-alerts-devex.js reads
GitHub workflow runs in.
-Needs the `depot` CLI and DEPOT_TOKEN.
+Needs the `depot` CLI and DEPOT_TOKEN. Reading push runs also needs the `gh` CLI and a GitHub token.
"""
from __future__ import annotations
+import re
import sys
import json
import time
@@ -28,6 +29,7 @@ import zipfile
import argparse
import tempfile
import subprocess
+from collections.abc import Iterable
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime, timedelta
from pathlib import Path
@@ -47,6 +49,10 @@ PARALLEL_CLI_CALLS = 8
MAX_LISTED = 200
TRIGGERS = ("push", "schedule")
MASTER_REF = "refs/heads/master"
+# Master is the compare base, so these statuses mean master contains the commit.
+ON_MASTER_STATUSES = frozenset({"BEHIND", "IDENTICAL"})
+COMMIT_SHA = re.compile(r"[0-9a-f]{40}")
+GITHUB_TIMEOUT_SECONDS = 30
class ListedWorkflow(TypedDict):
@@ -69,14 +75,8 @@ class Job(TypedDict, total=False):
finished_at: str
-class ShownRun(TypedDict):
- trigger: str
- ref: str
-
-
class ShownWorkflow(TypedDict):
org_id: str
- run: ShownRun
jobs: list[Job]
@@ -97,8 +97,38 @@ def depot(*args: str, timeout: int = CLI_TIMEOUT_SECONDS) -> str:
return result.stdout
-def master_workflows(statuses: list[str], limit: int, *, trigger: str, repo: str = REPO) -> list[ListedWorkflow]:
- """The master Backend CI workflows of one trigger in the given states, newest first."""
+def commits_on_master(shas: Iterable[str], repo: str = REPO) -> frozenset[str]:
+ """A commit GitHub cannot resolve fails the whole query."""
+ candidates = sorted({sha for sha in shas if COMMIT_SHA.fullmatch(sha)})
+ if not candidates:
+ return frozenset()
+ owner, name = repo.split("/")
+ # Without headTarget, GitHub answers IDENTICAL for a commit it does not have.
+ fields = " ".join(
+ f'c{i}: compare(headRef: "{sha}") {{ status headTarget {{ oid }} }}' for i, sha in enumerate(candidates)
+ )
+ query = (
+ f"query($owner: String!, $name: String!) {{ repository(owner: $owner, name: $name) "
+ f'{{ ref(qualifiedName: "{MASTER_REF}") {{ {fields} }} }} }}'
+ )
+ result = subprocess.run(
+ ["gh", "api", "graphql", "-f", f"query={query}", "-f", f"owner={owner}", "-f", f"name={name}"],
+ check=True,
+ stdout=subprocess.PIPE,
+ text=True,
+ timeout=GITHUB_TIMEOUT_SECONDS,
+ )
+ compared = json.loads(result.stdout)["data"]["repository"]["ref"]
+ return frozenset(
+ sha
+ for i, sha in enumerate(candidates)
+ if (comparison := compared.get(f"c{i}"))
+ and comparison["status"] in ON_MASTER_STATUSES
+ and comparison["headTarget"]["oid"] == sha
+ )
+
+
+def listed_workflows(statuses: list[str], limit: int, *, trigger: str, repo: str = REPO) -> list[ListedWorkflow]:
args = ["workflow", "list", "--repo", repo, "--name", WORKFLOW_NAME, "--trigger", trigger, "-n", str(limit)]
for status in statuses:
args += ["--status", status]
@@ -111,6 +141,21 @@ def master_workflows(statuses: list[str], limit: int, *, trigger: str, repo: str
return sorted(workflows, key=lambda w: w["created_at"], reverse=True)
+def master_only(workflows: list[ListedWorkflow], *, trigger: str, repo: str = REPO) -> list[ListedWorkflow]:
+ """A branch can add itself to the push trigger in its own copy of the workflow, and Depot
+ records a push run's ref as its sha, so only GitHub can say a push ran on master.
+ """
+ if trigger == "schedule":
+ return workflows
+ on_master = commits_on_master((w["sha"] for w in workflows), repo)
+ return [w for w in workflows if w["sha"] in on_master]
+
+
+def master_workflows(statuses: list[str], limit: int, *, trigger: str, repo: str = REPO) -> list[ListedWorkflow]:
+ """The master Backend CI workflows of one trigger in the given states, newest first."""
+ return master_only(listed_workflows(statuses, limit, trigger=trigger, repo=repo), trigger=trigger, repo=repo)
+
+
def show(workflow_id: str) -> ShownWorkflow:
return cast(ShownWorkflow, json.loads(depot("workflow", "show", workflow_id, "--output", "json")))
@@ -139,10 +184,6 @@ def find(
try:
names = {a["name"] for a in artifacts(workflow["run_id"]) if a["name"].startswith(prefix)}
sys.stderr.write(f"Run {workflow['run_id']} has {len(names)} {prefix}* artifacts\n")
- # Only a candidate push run pays for the extra CLI call that reads its ref.
- if len(names) >= min_artifacts and trigger == "push" and not ran_on_master(show(workflow["workflow_id"])):
- sys.stderr.write(f"Run {workflow['run_id']} did not run on master, skipping it\n")
- continue
except (subprocess.SubprocessError, json.JSONDecodeError) as error:
sys.stderr.write(f"Run {workflow['run_id']}: could not read it, skipping it: {error!r}\n")
continue
@@ -190,21 +231,9 @@ def download(run_id: str, patterns: list[str], directory: Path) -> int:
return len(matching)
-def ran_on_master(shown: ShownWorkflow) -> bool:
- """A branch can add itself to the push trigger in its own copy of the workflow.
-
- Depot leaves a scheduled run's ref empty, and the schedule fires only on the default branch.
- Any other run counts as master only when its ref says so, so a payload without a ref fails closed.
- """
- run = shown.get("run") or {}
- return run.get("trigger") == "schedule" or run.get("ref") == MASTER_REF
-
-
-def gate_run(listed: ListedWorkflow) -> GateRun | None:
+def gate_run(listed: ListedWorkflow) -> GateRun:
"""One workflow as a GitHub-shaped run. A workflow whose gate job has not ended is not completed."""
shown = show(listed["workflow_id"])
- if not ran_on_master(shown):
- return None
gate = next((job for job in shown.get("jobs") or [] if job.get("job_key") == GATE_JOB_KEY), None)
conclusion: str | None = None
if gate and gate.get("status") in GATE_CONCLUSIONS:
@@ -228,7 +257,7 @@ def gate_run(listed: ListedWorkflow) -> GateRun | None:
def gate_runs(trigger: str, limit: int) -> list[GateRun]:
listed = master_workflows(["queued", "running", *sorted(ENDED)], limit, trigger=trigger)
with ThreadPoolExecutor(max_workers=PARALLEL_CLI_CALLS) as pool:
- runs = [run for run in pool.map(gate_run, listed) if run is not None]
+ runs = list(pool.map(gate_run, listed))
# An empty or inconclusive window must not resolve an existing CI incident.
if not any(
run["status"] == "completed" and run["conclusion"] not in (None, "cancelled", "skipped") for run in runs
diff --git a/.github/scripts/report_workflow_run_traces.py b/.github/scripts/report_workflow_run_traces.py
index 90e9febe2a08..59e049c0d205 100644
--- a/.github/scripts/report_workflow_run_traces.py
+++ b/.github/scripts/report_workflow_run_traces.py
@@ -580,16 +580,19 @@ def _depot_workflows_since(
) -> tuple[list[depot_backend_runs.ListedWorkflow], bool]:
"""The workflows created since the floor, and whether the listing reached the floor at all."""
kept: list[depot_backend_runs.ListedWorkflow] = []
- listed = depot_backend_runs.master_workflows(
+ # The cap check needs the listing before branch runs are dropped from it.
+ listed = depot_backend_runs.listed_workflows(
sorted(depot_backend_runs.ENDED), depot_backend_runs.MAX_LISTED, repo=repo, trigger=trigger
)
+ reached_floor = len(listed) < depot_backend_runs.MAX_LISTED
for workflow in listed:
created = parse_iso_utc(workflow["created_at"])
if created is not None and created < created_floor:
- return kept, True
+ reached_floor = True
+ break
kept.append(workflow)
# The CLI caps a listing, so a window that fills it may continue past what was listed.
- return kept, len(listed) < depot_backend_runs.MAX_LISTED
+ return depot_backend_runs.master_only(kept, trigger=trigger, repo=repo), reached_floor
def _read_depot_run(workflow: depot_backend_runs.ListedWorkflow, since: datetime) -> WorkflowRun | None:
@@ -597,8 +600,6 @@ def _read_depot_run(workflow: depot_backend_runs.ListedWorkflow, since: datetime
DepotShownWorkflow,
json.loads(depot_backend_runs.depot("workflow", "show", workflow["workflow_id"], "--output", "json")),
)
- if not depot_backend_runs.ran_on_master(cast(depot_backend_runs.ShownWorkflow, shown)):
- return None
finished = parse_iso_utc(shown["workflow"]["finished_at"])
if finished is None:
raise ValueError("Completed Depot workflow has no finish timestamp")
diff --git a/.github/scripts/test_depot_backend_runs.py b/.github/scripts/test_depot_backend_runs.py
index 62ca2d800245..d3acdbdde02a 100644
--- a/.github/scripts/test_depot_backend_runs.py
+++ b/.github/scripts/test_depot_backend_runs.py
@@ -1,3 +1,4 @@
+import re
import json
import zipfile
import subprocess
@@ -9,7 +10,8 @@ import pytest
import ci_backend_relay
import depot_backend_runs as script
-SCHEDULED_RUN = {"trigger": "schedule", "ref": ""}
+MASTER_SHA = "a" * 40
+BRANCH_SHA = "b" * 40
@pytest.mark.parametrize(
@@ -32,7 +34,7 @@ def test_gate_run_reports_the_gate_verdict(
jobs: list[dict[str, Any]] = [{"job_key": "ci-backend.yml:report-test-timings", "status": "failed"}]
if gate_status:
jobs.append({"job_key": script.GATE_JOB_KEY, "status": gate_status, "finished_at": "2026-10-05T13:00:00Z"})
- shown = {"org_id": "org", "run": SCHEDULED_RUN, "jobs": jobs}
+ shown = {"org_id": "org", "jobs": jobs}
monkeypatch.setattr(script, "depot", lambda *args: json.dumps(shown))
listed = {
"workflow_id": "wf",
@@ -54,17 +56,12 @@ def test_names_the_workflow_and_gate_job_the_relay_reads() -> None:
@pytest.mark.parametrize(
- "run,kept",
- [
- ({"trigger": "push", "ref": "refs/heads/master"}, 1),
- ({"trigger": "push", "ref": "refs/heads/feature"}, 0),
- (SCHEDULED_RUN, 1),
- ({}, 0),
- ],
- ids=["master", "branch", "schedule", "no-ref"],
+ "trigger,sha,kept",
+ [("push", MASTER_SHA, 1), ("push", BRANCH_SHA, 0), ("schedule", BRANCH_SHA, 1)],
+ ids=["master", "branch", "schedule"],
)
def test_gate_runs_drop_runs_from_other_branches(
- monkeypatch: pytest.MonkeyPatch, run: dict[str, str], kept: int
+ monkeypatch: pytest.MonkeyPatch, trigger: str, sha: str, kept: int
) -> None:
def depot_response(*args: str) -> str:
if args[:2] == ("workflow", "list"):
@@ -73,27 +70,22 @@ def test_gate_runs_drop_runs_from_other_branches(
{
"workflow_id": "wf",
"run_id": "run",
- "sha": "abc",
+ "sha": sha,
"status": "finished",
"created_at": "2026-10-05T12:23:00Z",
}
]
)
- return json.dumps(
- {
- "org_id": "org",
- "run": run,
- "jobs": [{"job_key": script.GATE_JOB_KEY, "status": "finished"}],
- }
- )
+ return json.dumps({"org_id": "org", "jobs": [{"job_key": script.GATE_JOB_KEY, "status": "finished"}]})
monkeypatch.setattr(script, "depot", depot_response)
+ monkeypatch.setattr(script, "commits_on_master", lambda shas, *_: frozenset(shas) & {MASTER_SHA})
if kept:
- assert len(script.gate_runs("push", 40)) == 1
+ assert len(script.gate_runs(trigger, 40)) == 1
else:
with pytest.raises(ValueError, match="No settled Backend CI verdict"):
- script.gate_runs("push", 40)
+ script.gate_runs(trigger, 40)
def test_retries_a_workflow_listing_timeout_once(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -129,9 +121,7 @@ def test_gate_window_requires_a_settled_verdict(monkeypatch: pytest.MonkeyPatch,
if status
else []
)
- return json.dumps(
- {"org_id": "org", "run": SCHEDULED_RUN, "jobs": [{"job_key": script.GATE_JOB_KEY, "status": status}]}
- )
+ return json.dumps({"org_id": "org", "jobs": [{"job_key": script.GATE_JOB_KEY, "status": status}]})
monkeypatch.setattr(script, "depot", depot_response)
@@ -157,19 +147,15 @@ def test_gate_window_keeps_in_progress_runs_alongside_a_settled_verdict(monkeypa
for status in ("finished", "running")
]
)
- return json.dumps(
- {"org_id": "org", "run": SCHEDULED_RUN, "jobs": [{"job_key": script.GATE_JOB_KEY, "status": args[2]}]}
- )
+ return json.dumps({"org_id": "org", "jobs": [{"job_key": script.GATE_JOB_KEY, "status": args[2]}]})
monkeypatch.setattr(script, "depot", depot_response)
assert [run["status"] for run in script.gate_runs("schedule", 12)] == ["completed", "in_progress"]
- "ref,found", [("refs/heads/master", ["run-master"]), ("refs/heads/feature", [])], ids=["master", "branch"]
-)
-def test_find_trusts_only_push_runs_on_master(monkeypatch: pytest.MonkeyPatch, ref: str, found: list[str]) -> None:
[email protected]("sha,found", [(MASTER_SHA, ["run-master"]), (BRANCH_SHA, [])], ids=["master", "branch"])
+def test_find_trusts_only_push_runs_on_master(monkeypatch: pytest.MonkeyPatch, sha: str, found: list[str]) -> None:
def depot_response(*args: str, **kwargs: object) -> str:
if args[:2] == ("workflow", "list"):
return json.dumps(
@@ -177,25 +163,42 @@ def test_find_trusts_only_push_runs_on_master(monkeypatch: pytest.MonkeyPatch, r
{
"workflow_id": "wf",
"run_id": "run-master",
- "sha": "abc",
+ "sha": sha,
"status": "finished",
"created_at": "2099-01-01T00:00:00Z",
}
]
)
- if args[:2] == ("workflow", "show"):
- return json.dumps({"org_id": "org", "run": {"trigger": "push", "ref": ref}, "jobs": []})
if args[:2] == ("artifacts", "list"):
return json.dumps({"artifacts": [{"artifact_id": "a", "name": "migrated-schema", "created_at": "x"}]})
raise AssertionError(args)
monkeypatch.setattr(script, "depot", depot_response)
+ monkeypatch.setattr(script, "commits_on_master", lambda shas, *_: frozenset(shas) & {MASTER_SHA})
workflows = script.find("migrated-schema", 1, 1, 2, trigger="push", statuses=["finished"])
assert [workflow["run_id"] for workflow in workflows] == found
+def test_commits_on_master_trusts_only_comparisons_of_the_commit_asked_about(monkeypatch: pytest.MonkeyPatch) -> None:
+ unknown_sha = "c" * 40
+ comparisons: dict[str, dict[str, Any]] = {
+ MASTER_SHA: {"status": "BEHIND", "headTarget": {"oid": MASTER_SHA}},
+ BRANCH_SHA: {"status": "DIVERGED", "headTarget": {"oid": BRANCH_SHA}},
+ unknown_sha: {"status": "IDENTICAL", "headTarget": {"oid": "d" * 40}},
+ }
+
+ def github_response(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ query = next(arg for arg in args if arg.startswith("query="))
+ compared = {alias: comparisons[sha] for alias, sha in re.findall(r'(c\d+): compare\(headRef: "(\w+)"\)', query)}
+ return subprocess.CompletedProcess(args, 0, json.dumps({"data": {"repository": {"ref": compared}}}))
+
+ monkeypatch.setattr(subprocess, "run", github_response)
+
+ assert script.commits_on_master([MASTER_SHA, BRANCH_SHA, unknown_sha, "not-a-sha"]) == {MASTER_SHA}
+
+
def test_download_keeps_the_newest_artifact_per_name() -> None:
artifacts = [
{"name": "timing_data-Core-1", "artifact_id": "retry", "created_at": "2026-10-05T12:40:00Z"},
diff --git a/.github/scripts/test_report_workflow_run_traces.py b/.github/scripts/test_report_workflow_run_traces.py
index f4535cc75d90..9d68f046294a 100644
--- a/.github/scripts/test_report_workflow_run_traces.py
+++ b/.github/scripts/test_report_workflow_run_traces.py
@@ -450,11 +450,12 @@ class TestDepotTraces:
listed_triggers.append(str(kwargs["trigger"]))
# Newest first, as the CLI lists them; the old one must end this trigger's walk only.
return [
- {"workflow_id": "wf", "created_at": _iso(0)},
- {"workflow_id": "old", "created_at": _iso(-100000)},
+ {"workflow_id": "wf", "sha": "a" * 40, "created_at": _iso(0)},
+ {"workflow_id": "old", "sha": "a" * 40, "created_at": _iso(-100000)},
]
- monkeypatch.setattr(reporter.depot_backend_runs, "master_workflows", list_workflows)
+ monkeypatch.setattr(reporter.depot_backend_runs, "listed_workflows", list_workflows)
+ monkeypatch.setattr(reporter.depot_backend_runs, "commits_on_master", lambda shas, *_: frozenset(shas))
def depot_response(*args: str) -> str:
if args[2] == "old":
@@ -478,6 +479,23 @@ class TestDepotTraces:
assert len(exporter.get_finished_spans()) == 2
assert reporter.run_resource_attributes(run)["ci.provider"] == "depot"
+ def test_a_capped_listing_stays_incomplete_after_branch_runs_are_dropped(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ listing = [
+ {"workflow_id": f"wf{i}", "sha": f"{i:040x}", "created_at": _iso(-i)}
+ for i in range(reporter.depot_backend_runs.MAX_LISTED)
+ ]
+ monkeypatch.setattr(reporter.depot_backend_runs, "listed_workflows", lambda *args, **kwargs: listing)
+ monkeypatch.setattr(
+ reporter.depot_backend_runs, "commits_on_master", lambda shas, *_: frozenset(shas) - {f"{0:040x}"}
+ )
+
+ kept, reached_floor = reporter._depot_workflows_since("PostHog/posthog", "push", RUN_START - timedelta(days=1))
+
+ assert len(kept) == reporter.depot_backend_runs.MAX_LISTED - 1
+ assert not reached_floor
+
def test_failed_depot_reads_hold_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:
def unavailable(*args: object) -> reporter.Collection:
raise RuntimeError("unavailable")
diff --git a/.github/workflows/ci-alerts-devex.yml b/.github/workflows/ci-alerts-devex.yml
index d1c65a6fb451..3c649a9c5487 100644
--- a/.github/workflows/ci-alerts-devex.yml
+++ b/.github/workflows/ci-alerts-devex.yml
@@ -108,6 +108,7 @@ jobs:
timeout-minutes: 2
env:
DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
+ GH_TOKEN: ${{ github.token }}
RUNS_DIR: ${{ runner.temp }}/depot-runs
run: |
mkdir -p "$RUNS_DIR"
diff --git a/.github/workflows/ci-backend-schema-mirror.yml b/.github/workflows/ci-backend-schema-mirror.yml
index 503a47fc8aed..8acba0016bfd 100644
--- a/.github/workflows/ci-backend-schema-mirror.yml
+++ b/.github/workflows/ci-backend-schema-mirror.yml
@@ -51,7 +51,8 @@ jobs:
echo "::warning::No Depot master run with a schema dump in the last two days"
exit 0
fi
- if ! [[ "$run_id" =~ ^[a-z0-9]{1,32}$ && "$sha" =~ ^[0-9a-f]{40}$ ]]; then
+ # Depot push run ids carry a `ps_` prefix.
+ if ! [[ "$run_id" =~ ^(ps_)?[a-z0-9]{1,32}$ && "$sha" =~ ^[0-9a-f]{40}$ ]]; then
echo "::error::Unexpected run id or sha from the Depot listing"
exit 1
fi
diff --git a/.github/workflows/ci-master-run-traces.yml b/.github/workflows/ci-master-run-traces.yml
index e5614785e8f6..34d2d847cd40 100644
--- a/.github/workflows/ci-master-run-traces.yml
+++ b/.github/workflows/ci-master-run-traces.yml
@@ -89,6 +89,8 @@ jobs:
- name: Emit master run traces
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token || github.token }}
+ # The commit comparison needs contents read, which github.token has.
+ GH_TOKEN: ${{ github.token }}
DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}
SINCE: ${{ inputs.since }}
POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}