: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): print depot failure steps in the relay (#107829)
Raúl Negrón-Oteroc88565edc3f3
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 3097cea1e0af..1207adb25d71 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -13,7 +13,8 @@# `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.+# 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.# 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.pynew file mode 100644index 000000000000..c87fe7c81aec--- /dev/null+++ b/.github/scripts/ci_backend_depot_failures.py@@ -0,0 +1,45 @@+"""Explain why a Depot backend workflow failed: each failed job's step and its log lines.++Depot's own checks carry no output, and its run pages need a Depot login. The GitHub+check a PR author opens prints these lines instead.+"""++import re+import json+import subprocess+from typing import Any++RUNNER_MARKER = re.compile(r"^##\[\w+\]")+# Depot keeps up to 8,000 characters per log line. A shorter cut keeps one long line+# from filling the annotation.+MAX_LINE = 500+++def message(attempt: dict[str, Any]) -> str:+ step = " ".join(f"{attempt['job_display_name']}: {attempt['error_message']}".split())+ lines = (RUNNER_MARKER.sub("", line["content"])[:MAX_LINE] for line in attempt["relevant_lines"])+ return "\n".join((step, *lines))+++def escape_annotation(text: str) -> str:+ return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")+++def explain(org: str, workflow: str) -> list[str]:+ """Workflow commands: one error annotation per failed step, with its log lines as the message.++ The log lines come from pull request code. Escaped as annotation data, the way+ @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"]]+ 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 adc410de9eea..602bd918a8d9 100644--- a/.github/scripts/ci_backend_relay.py+++ b/.github/scripts/ci_backend_relay.py@@ -41,6 +41,8 @@ from datetime import datetime, timedeltafrom enum import Enumfrom typing import Any, Protocol+from ci_backend_depot_failures import explain+DEPOT_APP_ID = 219785DEPOT_ORG = "ntsdt08fpt"# The PostHog tests GitHub App. Depot's wait and gate jobs post the same checks with it, because@@ -453,6 +455,8 @@ def main(argv: Sequence[str]) -> int:sys.stdout.write(f"::error::{error}\n")return 1code, lines = relay_gate(result, event, env.get("GITHUB_RUN_ID", ""))+ if code and result.phase == Phase.FINISHED and (match := DEPOT_RUN_URL.match(result.details_url)):+ lines += explain(*match.groups())sys.stdout.writelines(f"{line}\n" for line in lines)return codediff --git a/.github/scripts/test_ci_backend_depot_failures.py b/.github/scripts/test_ci_backend_depot_failures.pynew file mode 100644index 000000000000..36b4c12d1595--- /dev/null+++ b/.github/scripts/test_ci_backend_depot_failures.py@@ -0,0 +1,49 @@+import json+import subprocess+from typing import Any++import pytest++import ci_backend_depot_failures as depot_failures+++def stub_diagnose(monkeypatch: pytest.MonkeyPatch, outcome: str | BaseException) -> None:+ def run(*args: Any, **kwargs: Any) -> subprocess.CompletedProcess[str]:+ if isinstance(outcome, BaseException):+ raise outcome+ return subprocess.CompletedProcess(args, 0, stdout=outcome)++ monkeypatch.setattr(depot_failures.subprocess, "run", run)+++def test_log_lines_stay_inside_one_escaped_annotation(monkeypatch: pytest.MonkeyPatch) -> None:+ lines = ["##[error]FAILED test_widget - 100% broken", "::add-mask::ghp_example", "tail\r\n::set-output name=x::y"]+ attempt = {+ "job_display_name": "Repo checks",+ "error_message": "Step 3 (Validate widgets): exit 1",+ "relevant_lines": [{"content": line} for line in lines],+ }+ stub_diagnose(monkeypatch, json.dumps({"representative_attempts": [attempt]}))++ assert depot_failures.explain("org", "workflow") == [+ "::error title=Failed on Depot::Repo checks: Step 3 (Validate widgets): exit 1"+ "%0AFAILED test_widget - 100%25 broken"+ "%0A::add-mask::ghp_example"+ "%0Atail%0D%0A::set-output name=x::y"+ ]+++ "outcome, error",+ [+ (FileNotFoundError("depot"), "FileNotFoundError"),+ (subprocess.CalledProcessError(1, "depot"), "CalledProcessError"),+ ("not json", "JSONDecodeError"),+ ],+)+def test_unreadable_diagnosis_leaves_one_warning(+ monkeypatch: pytest.MonkeyPatch, outcome: str | BaseException, error: str+) -> None:+ stub_diagnose(monkeypatch, outcome)++ assert depot_failures.explain("org", "workflow") == [f"::warning::Cannot read the Depot failure details: {error}"]diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex c3c210d76149..0979ded67df0 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -4227,15 +4227,23 @@ jobs:if: needs.changes.outputs.engine == 'depot'uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:- sparse-checkout: .github/scripts/ci_backend_relay.py+ sparse-checkout: |+ .github/scripts/ci_backend_relay.py+ .github/scripts/ci_backend_depot_failures.pysparse-checkout-cone-mode: falsepersist-credentials: false+ # The relay reads a failed run's steps and log lines with the Depot CLI. Without+ # the CLI, the relay prints a warning and still reports the verdict.+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1+ if: needs.changes.outputs.engine == 'depot'+ continue-on-error: true# The script finds this event's Depot run by the event in its wait job's check# name, then waits for that run's gate. Its docstring explains why check times# and pull request lists cannot identify the run.- name: Relay the Depot verdictif: needs.changes.outputs.engine == 'depot'env:+ DEPOT_TOKEN: ${{ secrets.DEPOT_TOKEN }}GH_TOKEN: ${{ github.token }}REPO: ${{ github.repository }}SHA: ${{ github.event.pull_request.head.sha }}