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.

feat(ci): relay the depot verdict from app-posted checks (#107914)

Raúl Negrón-Otero2286c8ac7962
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index f94feb9458e3..11b2e76c921a 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -233,17 +233,17 @@ jobs:
outputs:
handed_off: ${{ steps.handoff.outputs.handed_off }}
steps:
- # Depot hands out ambient tokens from more than one installation, and one can be spent
- # for the hour. A spent token answers 403, and the wait would decline a real hand-off.
- - name: Mint hand-off read token
+ # Depot's ambient token can come from an installation spent for the hour. It answers 403,
+ # and the wait would decline a real hand-off. The same token posts the relay's checks.
+ - name: Mint hand-off token
id: handoff-token
- if: github.event.pull_request.head.repo.fork != true
+ if: contains(fromJSON('["pull_request", "workflow_dispatch", "api"]'), github.event_name) && github.event.pull_request.head.repo.fork != true
continue-on-error: true
uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
with:
client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
- permission-checks: read
+ permission-checks: write
- name: Wait for the hand-off check from GitHub Actions
id: handoff
env:
@@ -308,6 +308,25 @@ jobs:
fi
fi
echo "handed_off=$handed_off" >> "$GITHUB_OUTPUT"
+ # Mirrors Depot's own checks for .github/scripts/ci_backend_relay.py (see MIRROR_APP_ID).
+ # A declined event also gets the gate's skipped check, as Depot posts it.
+ - name: Post the hand-off checks for the relay
+ 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 }}
+ WAIT_CHECK: Backend CI on Depot / Wait for GitHub Actions to hand off backend tests (PR ${{ github.event.pull_request.number }}, event ${{ github.event.pull_request.updated_at }})
+ GATE_CHECK: Backend CI on Depot / Django Tests Pass on Depot
+ HANDED_OFF: ${{ steps.handoff.outputs.handed_off }}
+ run: |
+ post() {
+ gh api "repos/$REPO/check-runs" --method POST -f name="$1" -f head_sha="$SHA" \
+ -f status=completed -f conclusion="$2" -f details_url="$DEPOT_JOB_URL" --silent
+ }
+ post "$WAIT_CHECK" success
+ [ "$HANDED_OFF" = true ] || post "$GATE_CHECK" skipped
# Job to decide if we should run backend ci
# See .github/actions/paths-filter/README.md for filter semantics
changes:
@@ -4174,6 +4193,7 @@ jobs:
done
- name: Check dependency results
+ id: verdict
run: |
# Per-test failure rollup, emitted from THIS step because GitHub only
# auto-expands the failed step in the log view. Best-effort via `|| true`
@@ -4275,6 +4295,30 @@ jobs:
check_required_result "Snapshot commit job" "${{ needs.handle-snapshots.result }}"
echo "All backend and product checks passed."
+
+ # A separate checks:write token, minted in a job that runs no pull request code.
+ - name: Mint gate check token
+ id: gate-token
+ if: ${{ always() && github.event_name == 'pull_request' }}
+ continue-on-error: true
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ client-id: ${{ secrets.GH_APP_POSTHOG_TESTS_APP_ID }}
+ private-key: ${{ secrets.GH_APP_POSTHOG_TESTS_PRIVATE_KEY }}
+ permission-checks: write
+ # Mirrors Depot's own check for .github/scripts/ci_backend_relay.py (see MIRROR_APP_ID).
+ - name: Post the gate check for the relay
+ if: ${{ always() && steps.gate-token.outputs.token != '' }}
+ continue-on-error: true
+ env:
+ GH_TOKEN: ${{ steps.gate-token.outputs.token }}
+ REPO: ${{ github.repository }}
+ SHA: ${{ github.event.pull_request.head.sha }}
+ GATE_CHECK: Backend CI on Depot / Django Tests Pass on Depot
+ CONCLUSION: ${{ job.status == 'cancelled' && 'cancelled' || (steps.verdict.outcome == 'success' && 'success' || 'failure') }}
+ run: |
+ gh api "repos/$REPO/check-runs" --method POST -f name="$GATE_CHECK" \
+ -f head_sha="$SHA" -f status=completed -f conclusion="$CONCLUSION" -f details_url="$DEPOT_JOB_URL" --silent
test-selection-verdict:
needs: [django, turbo-tests, changes, turbo-discover]
name: Test selection verdict
diff --git a/.github/scripts/ci_backend_relay.py b/.github/scripts/ci_backend_relay.py
index ecf18bc26f52..adc410de9eea 100644
--- a/.github/scripts/ci_backend_relay.py
+++ b/.github/scripts/ci_backend_relay.py
@@ -43,6 +43,9 @@ from typing import Any, Protocol
DEPOT_APP_ID = 219785
DEPOT_ORG = "ntsdt08fpt"
+# The PostHog tests GitHub App. Depot's wait and gate jobs post the same checks with it, because
+# Depot posts its own checks from a budget that runs out at peak and then delivers them late.
+MIRROR_APP_ID = 2492437
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.
@@ -77,12 +80,19 @@ class ReadRefusedError(RuntimeError):
"""The check-runs API keeps refusing the token, so no verdict can be read."""
+class ReadFailedError(RuntimeError):
+ """One read of the check-runs API failed, so this poll cannot tell which checks exist."""
+
+
@dataclass(frozen=True)
class CheckRun:
id: int
# The conclusion once the check completed, its status before that.
state: str
details_url: str
+ app_id: int = DEPOT_APP_ID
+ # The job attempt in a mirrored check's URL. Depot's own checks carry none.
+ attempt: str = ""
@classmethod
def from_api(cls, run: dict[str, Any]) -> "CheckRun":
@@ -91,17 +101,21 @@ class CheckRun:
parsed = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(parsed.query)
match = re.fullmatch(rf"/orgs/{re.escape(DEPOT_ORG)}/workflows/([a-z0-9]+)", parsed.path)
+ attempt = ""
if parsed.scheme == "https" and parsed.netloc == "depot.dev" and match:
job = query.get("job", [""])[0]
url = f"https://depot.dev/orgs/{DEPOT_ORG}/workflows/{match[1]}"
if re.fullmatch(r"[a-z0-9]+", job):
url += f"?job={job}"
+ attempt = query.get("attempt", [""])[0]
else:
url = ""
return cls(
id=int(run["id"]),
state=state if state in PENDING_STATES | CONCLUSIONS else "unknown",
details_url=url,
+ app_id=int(run["app"]["id"]),
+ attempt=attempt if re.fullmatch(r"[a-z0-9]+", attempt) else "",
)
@property
@@ -133,10 +147,27 @@ 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 current_check(checks: Iterable[CheckRun], workflow: str | None) -> CheckRun | None:
+ """The check of the newest attempt of one job in `workflow`, from either app that posts it.
+
+ Depot posts one check per job attempt but can deliver it late, so its check ids do not order
+ its checks against the mirror's. The mirror posts one check per attempt that ran, in order,
+ but a post can fail. The mirror decides while it has posted at least as many attempts as
+ Depot shows. Otherwise the mirror missed an attempt, and Depot's newest check decides.
+ """
+ own = [check for check in checks if workflow is not None and check.depot_workflow == workflow]
+ mirrored = [check for check in own if check.app_id == MIRROR_APP_ID]
+ native = [check for check in own if check.app_id != MIRROR_APP_ID]
+ if mirrored and len(native) <= len({check.attempt or str(check.id) for check in mirrored}):
+ return max(mirrored, key=lambda check: check.id)
+ return max(native, key=lambda check: check.id, default=None)
+
+
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)
+ current = [check for workflow in {run.depot_workflow for run in runs} if (check := current_check(runs, workflow))]
+ live = [run for run in current if run.state != "cancelled"]
+ return max(live or current, key=lambda run: run.id, default=None)
def progress(wait: CheckRun | None, checks: Iterable[CheckRun]) -> Progress:
@@ -149,13 +180,7 @@ def progress(wait: CheckRun | None, checks: Iterable[CheckRun]) -> Progress:
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,
- )
+ check = current_check(checks, wait.depot_workflow)
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":
@@ -168,7 +193,7 @@ class CheckReader(Protocol):
class CheckRunReader:
- """Reads one commit's Depot check runs by name, with conditional requests.
+ """Reads one commit's Depot check runs by name from each app that posts them, with conditional requests.
A 304 answer is free against the rate limit, so polling stays cheap.
"""
@@ -180,18 +205,20 @@ class CheckRunReader:
token: str,
opener: Callable[..., Any] = urllib.request.urlopen,
pr_number: int | None = None,
+ app_ids: Sequence[int] = (MIRROR_APP_ID, DEPOT_APP_ID),
) -> None:
self._repo = repo
self._sha = sha
self._token = token
self._pr_number = pr_number
self._opener = opener
- self._cache: dict[str, tuple[str, list[CheckRun]]] = {}
+ self._app_ids = app_ids
+ self._cache: dict[tuple[str, int], tuple[str, list[CheckRun]]] = {}
self._refusals = 0
- def _url(self, name: str, page: int) -> str:
+ def _url(self, name: str, app_id: int, page: int) -> str:
query = urllib.parse.urlencode(
- {"check_name": name, "app_id": DEPOT_APP_ID, "filter": "all", "per_page": PAGE_SIZE, "page": page}
+ {"check_name": name, "app_id": app_id, "filter": "all", "per_page": PAGE_SIZE, "page": page}
)
return f"{API_ROOT}/repos/{self._repo}/commits/{self._sha}/check-runs?{query}"
@@ -213,14 +240,27 @@ class CheckRunReader:
return error.code, "", {}
def read(self, name: str) -> list[CheckRun]:
+ """Every app's checks of `name`. `current_check` picks the current one per workflow.
+
+ A failed read of any app raises, because the other app's checks alone can hold a stale attempt.
+ """
+ runs: list[CheckRun] = []
+ for app_id in self._app_ids:
+ app_runs = self._read_app(name, app_id)
+ if app_runs is None:
+ raise ReadFailedError(f"Cannot read {name}")
+ runs.extend(app_runs)
+ return runs
+
+ def _read_app(self, name: str, app_id: int) -> list[CheckRun] | None:
"""Read every page, reusing a cached answer only when the API confirms it with 304."""
- etag, cached = self._cache.get(name, ("", []))
+ etag, cached = self._cache.get((name, app_id), ("", []))
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 "")
+ code, page_etag, body = self._get(self._url(name, app_id, page), etag if page == 1 else "")
if page == 1 and code == 304:
self._refusals = 0
return cached
@@ -230,7 +270,7 @@ class CheckRunReader:
raise ReadRefusedError(f"Cannot read checks for {self._sha}")
if code != 200:
sys.stdout.write(f"::warning::check-runs API returned {code}\n")
- return []
+ return None
self._refusals = 0
if page == 1:
new_etag = page_etag
@@ -246,7 +286,7 @@ class CheckRunReader:
for run in raw
# One malformed record is skipped rather than discarding the whole answer.
if isinstance(run, dict)
- and (run.get("app") or {}).get("id") == DEPOT_APP_ID
+ and (run.get("app") or {}).get("id") == app_id
and run.get("name") == name
and run.get("head_sha") == self._sha
and (
@@ -258,9 +298,9 @@ class CheckRunReader:
runs = [run for run in runs if run.depot_workflow is not None]
except (OSError, http.client.HTTPException, KeyError, TypeError, ValueError, AttributeError):
sys.stdout.write("::warning::check-runs API read failed\n")
- return []
+ return None
# One page's ETag cannot validate the other pages of a paginated response.
- self._cache[name] = (new_etag if page == 1 else "", runs)
+ self._cache[(name, app_id)] = (new_etag if page == 1 else "", runs)
return runs
@@ -288,15 +328,7 @@ def racing_wait(reader: CheckReader, event: Event, followed: set[str]) -> str |
def prerequisite_failure(reader: CheckReader, wait: CheckRun, current: Progress) -> Progress:
for name in PREREQUISITES:
- latest = max(
- (
- check
- for check in reader.read(f"{DEPOT_WORKFLOW} / {name}")
- if check.depot_workflow == wait.depot_workflow
- ),
- key=lambda check: check.id,
- default=None,
- )
+ latest = current_check(reader.read(f"{DEPOT_WORKFLOW} / {name}"), wait.depot_workflow)
if latest and latest.state == "failure":
return Progress(Phase.FINISHED, "failure", current.details_url, name, latest.id)
return current
@@ -321,26 +353,32 @@ def poll(
start = clock()
event_name = wait_check_name(event.pr_number, event.event_at)
followed = {event_name}
+ current = Progress(Phase.ABSENT)
while True:
- wait = newest_live(reader.read(event_name))
- checks = reader.read(check_name) if wait and wait.state == "success" else []
- current = progress(wait, checks)
- # Depot cancels its own run only after a deterministic prerequisite failure. A gate that
- # failed without the cancel can follow a retryable one, so it keeps the retry options.
- if current.phase == Phase.CANCELLED and wait and wait.state == "success":
- current = prerequisite_failure(reader, wait, current)
- 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:
- racing = racing_wait(reader, event, followed)
- if racing is None:
+ try:
+ wait = newest_live(reader.read(event_name))
+ checks = reader.read(check_name) if wait and wait.state == "success" else []
+ current = progress(wait, checks)
+ # Depot cancels its own run only after a deterministic prerequisite failure. A gate that
+ # failed without the cancel can follow a retryable one, so it keeps the retry options.
+ if current.phase == Phase.CANCELLED and wait and wait.state == "success":
+ current = prerequisite_failure(reader, wait, current)
+ 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
- sys.stdout.write(f"Depot kept a racing event of this commit instead. Following: {racing}\n")
- followed.add(racing)
- event_name = racing
- continue
+ if current.phase in (Phase.ABSENT, Phase.CANCELLED) and elapsed >= absent_minutes * 60:
+ racing = racing_wait(reader, event, followed)
+ if racing is None:
+ return current
+ sys.stdout.write(f"Depot kept a racing event of this commit instead. Following: {racing}\n")
+ followed.add(racing)
+ event_name = racing
+ continue
+ except ReadFailedError as error:
+ # A failed read says nothing about the run, so it must not end the wait as absent.
+ sys.stdout.write(f"::warning::{error}. Reading again.\n")
+ elapsed = clock() - start
if elapsed >= deadline_minutes * 60:
return current
# The checked job only posts its check when the matrix is done, so once Depot has
diff --git a/.github/scripts/test_ci_backend_relay.py b/.github/scripts/test_ci_backend_relay.py
index 20ebf476874e..201f5768a54e 100644
--- a/.github/scripts/test_ci_backend_relay.py
+++ b/.github/scripts/test_ci_backend_relay.py
@@ -2,6 +2,7 @@ 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
@@ -9,6 +10,8 @@ from typing import Any
import pytest
+import yaml
+
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
@@ -26,17 +29,20 @@ OLDER_RACING_WAIT = relay.wait_check_name(PR, "2026-09-24T09:54:19Z")
NEWER_RACING_WAIT = relay.wait_check_name(PR, "2026-09-24T09:54:22Z")
-def run(id: int, state: str, workflow: str = "live", started_at: str = "2026-09-24T09:56:00Z") -> Any:
+def api_run(id: int, state: str, workflow: str = "live", attempt: str = "") -> dict[str, 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,
- "details_url": f"https://depot.dev/orgs/ntsdt08fpt/workflows/{workflow}?job=j1&repo=PostHog%2Fposthog",
- }
- )
+ query = f"job=j1&attempt={attempt}" if attempt else "job=j1&repo=PostHog%2Fposthog"
+ return {
+ "id": id,
+ "status": "completed" if completed else state,
+ "conclusion": state if completed else None,
+ "app": {"id": relay.MIRROR_APP_ID if attempt else relay.DEPOT_APP_ID},
+ "details_url": f"https://depot.dev/orgs/ntsdt08fpt/workflows/{workflow}?{query}",
+ }
+
+
+def run(id: int, state: str, workflow: str = "live", started_at: str = "2026-09-24T09:56:00Z") -> Any:
+ return relay.CheckRun.from_api({**api_run(id, state, workflow), "started_at": started_at})
def test_wait_job_name_matches_the_depot_workflow() -> None:
@@ -53,6 +59,20 @@ def test_wait_job_name_matches_the_depot_workflow() -> None:
assert name.group(1) == expected
+def test_mirrored_checks_carry_the_names_the_relay_reads() -> None:
+ jobs = yaml.safe_load(DEPOT_WORKFLOW_FILE.read_text())["jobs"]
+ steps = [step for job in jobs.values() for step in job.get("steps", [])]
+ handoff = next(step for step in steps if step.get("name") == "Post the hand-off checks for the relay")
+ gate = next(step for step in steps if step.get("name") == "Post the gate check for the relay")
+ wait_check = (
+ handoff["env"]["WAIT_CHECK"]
+ .replace("${{ github.event.pull_request.number }}", str(PR))
+ .replace("${{ github.event.pull_request.updated_at }}", EVENT_AT)
+ )
+ assert wait_check == EVENT_WAIT
+ assert handoff["env"]["GATE_CHECK"] == gate["env"]["GATE_CHECK"] == relay.GATE_CHECK
+
+
@pytest.mark.parametrize(
"event_waits,gates,expected",
[
@@ -109,7 +129,10 @@ class FakeReader:
self.reads.append(name)
if name == self._advance_on:
self.poll += 1
- return self._polls[min(self.poll, len(self._polls)) - 1].get(name, [])
+ answer = self._polls[min(self.poll, len(self._polls)) - 1].get(name, [])
+ if isinstance(answer, Exception):
+ raise answer
+ return answer
class FakeClock:
@@ -146,6 +169,14 @@ class FakeClock:
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")]}] * 16
+ + [{EVENT_WAIT: relay.ReadFailedError("Cannot read")}]
+ + [{EVENT_WAIT: [run(1, "success")], relay.GATE_CHECK: [run(10, "success")]}],
+ (relay.Phase.FINISHED, "success"),
+ 16,
+ id="a failed read after the grace window keeps waiting",
+ ),
pytest.param(
[
{
@@ -327,12 +358,13 @@ def test_reader_reuses_its_answer_on_304_and_stops_on_repeated_refusals() -> Non
raise answer
return answer
- reader = relay.CheckRunReader("PostHog/posthog", "abc", "token", opener=opener)
+ reader = relay.CheckRunReader("PostHog/posthog", "abc", "token", opener=opener, app_ids=(relay.DEPOT_APP_ID,))
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.ReadFailedError):
+ reader.read(relay.GATE_CHECK)
with pytest.raises(relay.ReadRefusedError):
reader.read(relay.GATE_CHECK)
@@ -355,9 +387,10 @@ def test_reader_retries_interrupted_pages_without_reusing_a_stale_verdict(page:
raise answer
return answer
- reader = relay.CheckRunReader("PostHog/posthog", "abc", "token", opener=opener)
+ reader = relay.CheckRunReader("PostHog/posthog", "abc", "token", opener=opener, app_ids=(relay.DEPOT_APP_ID,))
assert reader.read(relay.GATE_CHECK)[0].state == "success"
- assert reader.read(relay.GATE_CHECK) == []
+ with pytest.raises(relay.ReadFailedError):
+ reader.read(relay.GATE_CHECK)
assert reader.read(relay.GATE_CHECK) == []
assert not answers
@@ -467,3 +500,99 @@ def test_reader_keeps_valid_checks_beside_a_malformed_one() -> None:
"PostHog/posthog", "abc", "token", pr_number=PR, opener=lambda *a, **kw: FakeResponse(answer, "")
)
assert len(reader.read(relay.GATE_CHECK)) == 1
+
+
+ "mirror_gate,depot_gate,expected",
+ [
+ pytest.param(
+ [(2, "failure", "w1", "a1"), (5, "success", "w1", "a2")],
+ [],
+ (relay.Phase.FINISHED, "success"),
+ id="Depot's copies lag",
+ ),
+ pytest.param(
+ [(2, "failure", "w1", "a1"), (5, "success", "w1", "a2")],
+ [(9, "failure", "w1")],
+ (relay.Phase.FINISHED, "success"),
+ id="a late copy of an older attempt",
+ ),
+ pytest.param(
+ [(2, "failure", "w1", "a1"), (5, "success", "w1", "a2")],
+ [(8, "success", "w1"), (9, "failure", "w1")],
+ (relay.Phase.FINISHED, "success"),
+ id="late copies of both attempts",
+ ),
+ pytest.param(
+ [(2, "failure", "w1", "a1"), (5, "failure", "w1", "a2")],
+ [(4, "failure", "w1"), (9, "failure", "w1")],
+ (relay.Phase.FINISHED, "failure"),
+ id="a retry that failed again",
+ ),
+ pytest.param(
+ [(2, "success", "w1", "a1")],
+ [(4, "success", "w1"), (9, "failure", "w1")],
+ (relay.Phase.FINISHED, "failure"),
+ id="a newer attempt the mirror missed",
+ ),
+ pytest.param(
+ [(2, "failure", "w1", "a1")],
+ [(4, "failure", "w1"), (9, "in_progress", "w1")],
+ (relay.Phase.RUNNING, "in_progress"),
+ id="a running retry the mirror has not posted",
+ ),
+ pytest.param(
+ [(5, "success", "w1", "a2")],
+ [(4, "cancelled", "w1")],
+ (relay.Phase.FINISHED, "success"),
+ id="a replacement for a job cancelled before it started",
+ ),
+ pytest.param(
+ [(5, "success", "w1", "a2")],
+ [(4, "cancelled", "w1"), (9, "in_progress", "w1")],
+ (relay.Phase.RUNNING, "in_progress"),
+ id="a replacement Depot has not finished after a cancelled job",
+ ),
+ pytest.param(
+ [(5, "success", "other", "a1")],
+ [(9, "failure", "w1")],
+ (relay.Phase.FINISHED, "failure"),
+ id="another workflow's mirrored gate",
+ ),
+ pytest.param(
+ [(5, "success", "other", "a1")],
+ [],
+ (relay.Phase.RUNNING, ""),
+ id="only another workflow's mirrored gate",
+ ),
+ pytest.param([(5, "success", "w1", "a1")], None, None, id="Depot's app read fails"),
+ ],
+)
+def test_relay_reads_the_current_attempt_across_apps(
+ mirror_gate: list[tuple[int, str, str, str]],
+ depot_gate: list[tuple[int, str, str]] | None,
+ expected: tuple[Any, str] | None,
+) -> None:
+ mirror = {EVENT_WAIT: [api_run(1, "success", "w1", "w")], relay.GATE_CHECK: [api_run(*c) for c in mirror_gate]}
+ depot = {
+ EVENT_WAIT: [api_run(3, "success", "w1")],
+ relay.GATE_CHECK: None if depot_gate is None else [api_run(*c) for c in depot_gate],
+ }
+
+ def opener(request: Any, timeout: int) -> FakeResponse:
+ query = urllib.parse.parse_qs(urllib.parse.urlparse(request.full_url).query)
+ name, app_id = query["check_name"][0], int(query["app_id"][0])
+ runs = (mirror if app_id == relay.MIRROR_APP_ID else depot)[name]
+ if runs is None:
+ raise urllib.error.HTTPError(request.full_url, 502, "Bad Gateway", {}, None) # type: ignore[arg-type]
+ body = [{**check, "name": name, "head_sha": EVENT.sha} for check in runs]
+ return FakeResponse(json.dumps({"check_runs": body}).encode(), "")
+
+ reader = relay.CheckRunReader(EVENT.repo, EVENT.sha, "token", opener=opener)
+ wait = relay.newest_live(reader.read(EVENT_WAIT))
+ if expected is None:
+ with pytest.raises(relay.ReadFailedError):
+ reader.read(relay.GATE_CHECK)
+ return
+ current = relay.progress(wait, reader.read(relay.GATE_CHECK))
+ assert (current.phase, current.state) == expected