: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
feat(ci): report backend ci running time from depot (#106890)
Raúl Negrón-Otero5286fbe2b641
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex da7b756e2494..9ce80c0ef8c1 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -54,6 +54,11 @@# cache. This job and the mig_schema_key output that feeds it remain depot-exempt.# - 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+# Actions API by run id, and GitHub has no run for a Depot run id. Here+# .github/scripts/capture_depot_running_time.py reads the workflow with `depot ci workflow show`+# and DEPOT_CI_CANCEL_TOKEN, then sends the same events with the same property keys and+# runner `depot-ci`. Its attempt guard sits on the steps, as canonical's does.# - Workflow-name expressions remain literal, so the role cannot switch names through a# variable; the cutover renames the workflow in a plain edit. The gate's hand-off `&&`# is safe only while its status remains optional.@@ -4619,4 +4624,38 @@ jobs:retention-days: 2overwrite: true- # calculate-running-time is omitted so Depot runs are not recorded as canonical CI data.+ calculate-running-time:+ name: Calculate running time+ needs: [changes, django_tests]+ runs-on: depot-ubuntu-24.04+ timeout-minutes: 5+ # Run on pull requests to PostHog/posthog + on PostHog/posthog outside of PRs - but never on forks or Dependabot (no secrets access)+ if: >-+ !cancelled() && github.actor != 'dependabot[bot]' && (+ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'PostHog/posthog') ||+ (github.event_name != 'pull_request' && github.repository == 'PostHog/posthog'))+ && needs.changes.result == 'success'+ permissions:+ contents: read+ steps:+ # Depot evaluates github.run_attempt as empty in a job-level `if`, so the attempt guard sits on the steps.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ id: checkout+ if: github.run_attempt == '1'+ continue-on-error: true+ with:+ sparse-checkout: .github/scripts/capture_depot_running_time.py+ sparse-checkout-cone-mode: false+ - uses: depot/setup-action@15c09a5f77a0840ad4bce955686522a257853461 # v1.7.1+ id: setup-depot+ if: github.run_attempt == '1' && steps.checkout.outcome == 'success'+ continue-on-error: true+ - name: Capture running time to PostHog and DevEx PostHog+ if: github.run_attempt == '1' && steps.setup-depot.outcome == 'success'+ continue-on-error: true+ env:+ DEPOT_TOKEN: ${{ secrets.DEPOT_CI_CANCEL_TOKEN }}+ POSTHOG_API_TOKEN: ${{ secrets.POSTHOG_API_TOKEN }}+ POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}+ STATUS_JOB: django_tests+ run: python3 .github/scripts/capture_depot_running_time.pydiff --git a/.github/scripts/capture_depot_running_time.py b/.github/scripts/capture_depot_running_time.pynew file mode 100644index 000000000000..ebabb9938f99--- /dev/null+++ b/.github/scripts/capture_depot_running_time.py@@ -0,0 +1,199 @@+#!/usr/bin/env python3+"""Send the Backend CI running-time events for a Depot CI run.++On GitHub Actions, PostHog/posthog-github-action sends `posthog-ci-running-time` and one+`posthog-ci-running-time-job` event per job. It reads the run from the Actions API by run id,+and GitHub has no run for a Depot run id. This script reads the workflow with+`depot ci workflow show` instead and sends the same events with the same property keys.+`workflow` and `runner` tell the two engines apart.+"""++import os+import re+import sys+import json+import math+import datetime as dt+import subprocess+import urllib.request+from collections.abc import Mapping+from typing import Any++JSONObject = dict[str, Any]++POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"+EVENT = "posthog-ci-running-time"+DISTINCT_ID = "posthog-github-action"+RUNNER = "depot-ci"+REQUEST_TIMEOUT_SECONDS = 30+DEPOT_JOB_URL = re.compile(r"^(https://depot\.dev/orgs/([^/?]+)/workflows/([a-z0-9]+))")+# Depot's terminal job statuses in GitHub's conclusion vocabulary. `cancelled` and `skipped` already match.+CONCLUSION_BY_STATUS = {"finished": "success", "failed": "failure"}+# Depot posts one placeholder job per matrix that it expands from `fromJSON`. The placeholder runs nothing.+MATRIX_PLACEHOLDER_SUFFIX = ":_dynamicMatrix"+KNOWN_BOT_ACTORS = frozenset({"Copilot"})+HANDOFF_JOB = "wait-for-handoff"+++def conclusion(status: str) -> str:+ return CONCLUSION_BY_STATUS.get(status, status)+++def actor_type(actor: str) -> str:+ if not actor:+ return "unknown"+ if actor.endswith("[bot]") or actor in KNOWN_BOT_ACTORS:+ return "bot"+ return "human"+++def seconds_between(started_at: str, finished_at: str) -> int:+ elapsed = dt.datetime.fromisoformat(finished_at) - dt.datetime.fromisoformat(started_at)+ return math.floor(elapsed.total_seconds())+++def github_context(env: Mapping[str, str]) -> JSONObject:+ owner, _, repository = env["GITHUB_REPOSITORY"].partition("/")+ actor = env.get("GITHUB_ACTOR", "")+ run_number = env.get("GITHUB_RUN_NUMBER", "")+ return {+ "sha": env["GITHUB_SHA"],+ "ref": env["GITHUB_REF"],+ "workflow": env["GITHUB_WORKFLOW"],+ "runNumber": int(run_number) if run_number.isdigit() else None,+ "runId": int(env["GITHUB_RUN_ID"]),+ "repository": repository,+ "repositoryOwner": owner,+ "actor": actor,+ "actor_type": actor_type(actor),+ "eventName": env["GITHUB_EVENT_NAME"],+ }+++def job_id(job: JSONObject) -> str:+ # A job key is `<workflow file>:<job id>`, with a `:matrix-NN` suffix on matrix cells.+ return job["job_key"].partition(":")[2]+++def latest_attempt(job: JSONObject) -> JSONObject:+ # A retried job keeps its earlier attempts. The Actions API reports the latest attempt only.+ return max(job.get("attempts") or [job], key=lambda attempt: attempt.get("attempt", 0))+++def job_events(jobs: list[JSONObject], context: JSONObject, groups: JSONObject) -> list[JSONObject]:+ events: list[JSONObject] = []+ for job in jobs:+ if job["job_key"].endswith(MATRIX_PLACEHOLDER_SUFFIX):+ continue+ latest = latest_attempt(job)+ finished_at = latest.get("finished_at")+ if not finished_at:+ continue+ # A skipped job never starts, and the Actions API reports it with a zero duration.+ started_at = latest.get("started_at") or finished_at+ events.append(+ {+ "event": f"{EVENT}-job",+ "properties": {+ "name": job.get("job_display_name") or job["job_key"],+ "duration_seconds": seconds_between(started_at, finished_at),+ "conclusion": conclusion(job["status"]),+ "started_at": started_at,+ "completed_at": finished_at,+ "runner": RUNNER,+ **context,+ "$groups": groups,+ },+ }+ )+ return events+++def build_events(+ shown: JSONObject, workflow_url: str, status_job: str, env: Mapping[str, str], now: dt.datetime+) -> list[JSONObject]:+ context = github_context(env)+ group_key = f"{context['repositoryOwner']}/{context['repository']}/{context['runId']}"+ groups = {"workflow_run": group_key}+ jobs = shown.get("jobs") or []+ # The workflow starts on every pull request event and idles in wait-for-handoff until GitHub+ # routes the event here. The run starts after that wait, so the duration compares with GitHub's.+ handoff = next((job for job in jobs if job_id(job) == HANDOFF_JOB), None)+ started_at = (handoff and latest_attempt(handoff).get("finished_at")) or shown["workflow"]["started_at"]+ properties: JSONObject = {+ "duration_seconds": seconds_between(started_at, now.isoformat()),+ "url": workflow_url,+ "attempt": int(env["GITHUB_RUN_ATTEMPT"]),+ "started_at": started_at,+ "runner": RUNNER,+ }+ gate = next((job for job in jobs if job_id(job) == status_job), None)+ if gate is None:+ sys.stdout.write(f"::warning::Job '{status_job}' not found in the Depot workflow\n")+ else:+ properties["conclusion"] = conclusion(gate["status"])++ events = [{"event": EVENT, "properties": {**properties, **context, "$groups": groups}}]+ if "conclusion" in properties:+ events.append(+ {+ "event": "$groupidentify",+ "properties": {+ "$group_type": "workflow_run",+ "$group_key": group_key,+ "$group_set": {"conclusion": properties["conclusion"]},+ },+ "distinct_id": f"$workflow_run_{group_key}",+ }+ )+ events.extend(job_events(jobs, context, groups))+ timestamp = now.isoformat()+ return [{"distinct_id": DISTINCT_ID, "timestamp": timestamp, **event} for event in events]+++def send_batch(token: str, events: list[JSONObject]) -> None:+ request = urllib.request.Request(+ POSTHOG_BATCH_URL,+ data=json.dumps({"api_key": token, "batch": events}).encode(),+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected -- the URL is the module constant above, not input+ with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS):+ pass+++def main() -> int:+ env = os.environ+ match = DEPOT_JOB_URL.match(env.get("DEPOT_JOB_URL", ""))+ if not match:+ sys.stdout.write("::error::DEPOT_JOB_URL does not name a Depot workflow\n")+ return 1+ workflow_url, org, workflow_id = match.groups()+ shown = json.loads(+ subprocess.run(+ ["depot", "ci", "workflow", "show", workflow_id, "--org", org, "-o", "json"],+ check=True,+ capture_output=True,+ text=True,+ ).stdout+ )+ events = build_events(shown, workflow_url, env["STATUS_JOB"], env, dt.datetime.now(dt.UTC))+ failed = False+ for token_name in ("POSTHOG_API_TOKEN", "POSTHOG_DEVEX_PROJECT_API_TOKEN"):+ token = env.get(token_name)+ if not token:+ sys.stdout.write(f"::warning::{token_name} is not set, so its project gets no events\n")+ continue+ try:+ send_batch(token, events)+ except OSError as error:+ sys.stdout.write(f"::warning::Sending events with {token_name} failed: {error}\n")+ failed = True+ continue+ sys.stdout.write(f"Sent {len(events)} events with {token_name}\n")+ return 1 if failed else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/scripts/test_capture_depot_running_time.py b/.github/scripts/test_capture_depot_running_time.pynew file mode 100644index 000000000000..a40dfc110956--- /dev/null+++ b/.github/scripts/test_capture_depot_running_time.py@@ -0,0 +1,108 @@+import datetime as dt+import importlib.util+from pathlib import Path++SCRIPT_PATH = Path(__file__).with_name("capture_depot_running_time.py")+SPEC = importlib.util.spec_from_file_location("capture_depot_running_time", SCRIPT_PATH)+assert SPEC is not None+assert SPEC.loader is not None+capture = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(capture)++ENV = {+ "GITHUB_REPOSITORY": "PostHog/posthog",+ "GITHUB_SHA": "0123456789abcdef0123456789abcdef01234567",+ "GITHUB_REF": "refs/pull/1/merge",+ "GITHUB_WORKFLOW": "Backend CI on Depot",+ "GITHUB_RUN_NUMBER": "",+ "GITHUB_RUN_ID": "42",+ "GITHUB_RUN_ATTEMPT": "1",+ "GITHUB_ACTOR": "octocat",+ "GITHUB_EVENT_NAME": "pull_request",+}+SHOWN = {+ "workflow": {"started_at": "2026-01-01T00:00:00Z"},+ "jobs": [+ {+ "job_key": "ci-backend.yml:wait-for-handoff",+ "job_display_name": "Wait for GitHub Actions to hand off backend tests",+ "status": "finished",+ "attempts": [{"attempt": 1, "started_at": "2026-01-01T00:00:05Z", "finished_at": "2026-01-01T00:00:30Z"}],+ },+ {+ "job_key": "ci-backend.yml:django_tests",+ "job_display_name": "Django Tests Pass on Depot",+ "status": "failed",+ "attempts": [{"attempt": 1, "started_at": "2026-01-01T00:20:00Z", "finished_at": "2026-01-01T00:20:05Z"}],+ },+ {+ "job_key": "ci-backend.yml:django:matrix-01",+ "job_display_name": "Django tests - Core (1/2)",+ "status": "finished",+ "attempts": [+ {"attempt": 1, "started_at": "2026-01-01T00:01:00Z", "finished_at": "2026-01-01T00:11:00Z"},+ {"attempt": 2, "started_at": "2026-01-01T00:12:00Z", "finished_at": "2026-01-01T00:19:30Z"},+ ],+ },+ {+ "job_key": "ci-backend.yml:validate-product-yamls",+ "job_display_name": "Validate product.yaml owners",+ "status": "skipped",+ "started_at": "",+ "finished_at": "2026-01-01T00:00:40Z",+ "attempts": [],+ },+ {"job_key": "ci-backend.yml:django:_dynamicMatrix", "status": "skipped", "finished_at": "2026-01-01T00:00:50Z"},+ {+ "job_key": "ci-backend.yml:calculate-running-time",+ "job_display_name": "Calculate running time",+ "status": "running",+ "attempts": [{"attempt": 1, "started_at": "2026-01-01T00:20:10Z", "finished_at": ""}],+ },+ ],+}+++def test_build_events_matches_the_action_event_shape() -> None:+ now = dt.datetime(2026, 1, 1, 0, 21, 30, tzinfo=dt.UTC)++ events = capture.build_events(SHOWN, "https://depot.dev/orgs/org/workflows/wf", "django_tests", ENV, now)++ group = {"workflow_run": "PostHog/posthog/42"}+ assert events[0] == {+ "distinct_id": "posthog-github-action",+ "timestamp": now.isoformat(),+ "event": "posthog-ci-running-time",+ "properties": {+ "duration_seconds": 1260,+ "url": "https://depot.dev/orgs/org/workflows/wf",+ "attempt": 1,+ "started_at": "2026-01-01T00:00:30Z",+ "conclusion": "failure",+ "runner": "depot-ci",+ "sha": ENV["GITHUB_SHA"],+ "ref": "refs/pull/1/merge",+ "workflow": "Backend CI on Depot",+ "runNumber": None,+ "runId": 42,+ "repository": "posthog",+ "repositoryOwner": "PostHog",+ "actor": "octocat",+ "actor_type": "human",+ "eventName": "pull_request",+ "$groups": group,+ },+ }+ assert events[1]["event"] == "$groupidentify"+ assert events[1]["distinct_id"] == "$workflow_run_PostHog/posthog/42"+ assert events[1]["properties"]["$group_set"] == {"conclusion": "failure"}+ assert [+ (e["properties"]["name"], e["properties"]["duration_seconds"], e["properties"]["conclusion"])+ for e in events[2:]+ ] == [+ ("Wait for GitHub Actions to hand off backend tests", 25, "success"),+ ("Django Tests Pass on Depot", 5, "failure"),+ ("Django tests - Core (1/2)", 450, "success"),+ ("Validate product.yaml owners", 0, "skipped"),+ ]+ assert all(e["event"] == "posthog-ci-running-time-job" and e["properties"]["$groups"] == group for e in events[2:])