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): stamp owning team on per-test CI spans (#71695)

Raúl Negrón-Otero6c68b845a6fc
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 1c74602f0b27..310ecd76e007 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -27,6 +27,9 @@
# test job fails, downloads that shard's JUnit to list the actual failing tests. The shadow
# strips artifact uploads (above), so it has nothing to download and keeps the plain
# dependency-result table — depot-exempt for the same reason as the other uploads.
+# - report-test-timings: canonical emits per-test OTLP spans from the uploaded JUnit. The shadow
+# strips artifact uploads (above) and posts no telemetry, so the whole job is depot-exempt —
+# changes confined to it (script deps, the reporter's availability guard) need no depot bump.
# - OpenAPI types: the check-openapi-types job is folded into check-migrations as a
# check-only step (drift still fails the run); only its auto-commit side effect is dropped
# - actions/cache reads/writes route to Depot Cache, not GitHub Actions Cache,
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.py
index 920c2358f0c1..4a0d33addb6c 100644
--- a/.github/scripts/report_test_timings.py
+++ b/.github/scripts/report_test_timings.py
@@ -6,7 +6,11 @@
# "opentelemetry-api~=1.27",
# "opentelemetry-sdk~=1.27",
# "opentelemetry-exporter-otlp-proto-http~=1.27",
+# "posthog-owners",
# ]
+#
+# [tool.uv.sources]
+# posthog-owners = { path = "../../tools/owners" }
# ///
"""Emit OTLP traces from Backend CI JUnit XML artifacts.
@@ -35,8 +39,10 @@ import hashlib
import logging
import secrets
import argparse
+from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
+from functools import cache
from pathlib import Path
from typing import Any
@@ -48,6 +54,7 @@ from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.id_generator import IdGenerator
from opentelemetry.trace import Status, StatusCode
+from posthog_owners import OwnersResolver
logger = logging.getLogger("report_test_timings")
@@ -69,6 +76,7 @@ class TestCase:
end: datetime
outcome: str # passed | failed | error | skipped | xfailed | rerun_passed
attempts: int # 1 + number of pytest-rerunfailures retries before final outcome
+ file: str # repo-relative test file from JUnit's `file`; '' when absent (external shards)
selector: str # runnable 'path/test.py::Class::test' from JUnit's `file`; '' when file is absent
@@ -284,6 +292,7 @@ def parse_shard(xml_path: Path, info: ArtifactInfo) -> Shard | None:
nodeid=to_nodeid(classname, name),
classname=classname,
name=name,
+ file=file,
selector=to_selector(file, classname, name),
duration_seconds=duration,
start=test_start,
@@ -435,6 +444,35 @@ def job_trace_name(workflow: str, info: ArtifactInfo) -> str:
return f"{workflow} / {job}"
+def owner_team_lookup() -> Callable[[str], str]:
+ """Repo-relative test file -> primary owning team slug, '' when unowned.
+
+ Resolution is capture-time on purpose: a test is attributed to whoever owned it when it
+ ran. Ownership is best-effort next to the timings themselves, so every failure — a resolver
+ that can't load (a base checkout predating `tools/owners`) or one file that won't resolve —
+ degrades to no stamp, leaving those spans in the reader's `unowned` bucket rather than
+ losing the emit.
+ """
+ try:
+ resolver = OwnersResolver()
+ except Exception:
+ logger.exception("owners resolver unavailable; emitting spans without team attribution")
+ return lambda _file: ""
+
+ @cache
+ def lookup(file: str) -> str:
+ if not file:
+ return ""
+ try:
+ owners = resolver.resolve(file).owners
+ except Exception:
+ logger.exception("owners resolution failed for %s; emitting span without team attribution", file)
+ return ""
+ return owners[0] if owners else ""
+
+ return lookup
+
+
def emit_traces(shards: list[Shard], endpoint: str, token: str) -> None:
"""Emit one trace per job: a `<workflow> / <job>` root span with test children, shipped via OTLP HTTP."""
run_id = os.environ.get("GITHUB_RUN_ID", "0")
@@ -452,16 +490,17 @@ def emit_traces(shards: list[Shard], endpoint: str, token: str) -> None:
provider.shutdown()
return
+ owner_of = owner_team_lookup()
for shard in shards:
# Mutate the shared generator before each job so its root span (and the test
# children that inherit the active parent's trace ID) form a distinct trace.
id_generator.trace_id = deterministic_trace_id(run_id, run_attempt, job_trace_key(shard.info))
- _emit_shard_span(tracer, shard, job_trace_name(workflow, shard.info))
+ _emit_shard_span(tracer, shard, job_trace_name(workflow, shard.info), owner_of)
provider.shutdown()
-def _emit_shard_span(tracer: trace.Tracer, shard: Shard, root_name: str) -> bool:
+def _emit_shard_span(tracer: trace.Tracer, shard: Shard, root_name: str, owner_of: Callable[[str], str]) -> bool:
"""Emit the job's root span and its test children. Returns True iff any child has Error."""
info = shard.info
shard_span = tracer.start_span(root_name, start_time=_to_ns(shard.start))
@@ -497,6 +536,9 @@ def _emit_shard_span(tracer: trace.Tracer, shard: Shard, root_name: str) -> bool
test_span.set_attribute("test.name", test.name)
if test.selector:
test_span.set_attribute("test.selector", test.selector)
+ owner_team = owner_of(test.file)
+ if owner_team:
+ test_span.set_attribute("test.owner_team", owner_team)
if test.outcome in ("failed", "error"):
test_span.set_status(Status(StatusCode.ERROR))
has_error = True
diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.py
index c3061d066f6f..b467b8f4b47a 100644
--- a/.github/scripts/test_report_test_timings.py
+++ b/.github/scripts/test_report_test_timings.py
@@ -29,12 +29,14 @@ def _testcase(
duration: float = 1.0,
start: datetime | None = None,
name: str = "t",
+ file: str = "m.py",
) -> report_test_timings.TestCase: # type: ignore[name-defined]
test_start = start if start is not None else datetime(2026, 5, 4, 10, 0, 0, tzinfo=UTC)
return report_test_timings.TestCase(
nodeid=f"m::{name}",
classname="m",
name=name,
+ file=file,
selector=f"m.py::{name}",
duration_seconds=duration,
start=test_start,
@@ -343,6 +345,10 @@ def _noop_use_span(span: _FakeSpan, end_on_exit: bool = False) -> Iterator[None]
yield
+def _no_owner(file: str) -> str:
+ return ""
+
+
def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatch) -> None:
start = datetime(2026, 5, 4, 10, 0, 0, tzinfo=UTC)
shard = report_test_timings.Shard(
@@ -371,7 +377,7 @@ def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatc
tracer = _FakeTracer()
monkeypatch.setattr(report_test_timings.trace, "use_span", _noop_use_span)
- has_error = report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)")
+ has_error = report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)", _no_owner)
assert has_error is True
assert [span.name for span in tracer.spans] == ["Backend CI / core (1)", "m::slow", "m::fail"]
@@ -408,7 +414,7 @@ def test_emit_shard_span_emits_setup_span_when_setup_seconds_positive(monkeypatc
tracer = _FakeTracer()
monkeypatch.setattr(report_test_timings.trace, "use_span", _noop_use_span)
- report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)")
+ report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)", _no_owner)
assert [span.name for span in tracer.spans] == ["Backend CI / core (1)", "setup", "m::slow"]
setup_span = tracer.spans[1]
@@ -418,6 +424,38 @@ def test_emit_shard_span_emits_setup_span_when_setup_seconds_positive(monkeypatc
assert tracer.spans[0].attributes["shard.setup_seconds"] == pytest.approx(3.5)
+# `test.owner_team` is the contract the team CI health rollup reads: an unstamped span
+# aggregates as `unowned`, so an unowned file must stay unstamped rather than carry an empty one.
+def test_emit_shard_span_stamps_owner_team_only_for_owned_files(monkeypatch: pytest.MonkeyPatch) -> None:
+ start = datetime(2026, 5, 4, 10, 0, 0, tzinfo=UTC)
+ shard = report_test_timings.Shard(
+ info=report_test_timings.ArtifactInfo(
+ path=Path("junit-results-backend-core-1"),
+ suite="backend",
+ segment="core",
+ group=1,
+ total=1,
+ ),
+ junit_filename="junit-core.xml",
+ start=start,
+ end=start + timedelta(seconds=10),
+ testcase_seconds=2.0,
+ overhead_seconds=8.0,
+ tests=[
+ _testcase(name="owned", file="products/x/test_a.py"),
+ _testcase(name="unowned", file="stray/test_b.py", start=start + timedelta(seconds=1)),
+ ],
+ )
+ tracer = _FakeTracer()
+ monkeypatch.setattr(report_test_timings.trace, "use_span", _noop_use_span)
+
+ owners = {"products/x/test_a.py": "team-devex"}
+ report_test_timings._emit_shard_span(tracer, shard, "Backend CI / core (1)", lambda f: owners.get(f, ""))
+
+ assert tracer.spans[1].attributes["test.owner_team"] == "team-devex"
+ assert "test.owner_team" not in tracer.spans[2].attributes
+
+
# ---------- workflow context ----------
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 5b31cf21c0e9..7bd9868faf84 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -3491,7 +3491,8 @@ jobs:
if: github.run_attempt == '1'
shell: bash
run: |
- if [[ -f .github/scripts/report_test_timings.py ]]; then
+ # tools/owners is a path dep of the reporter, so a base ref predating it can't resolve its deps.
+ if [[ -f .github/scripts/report_test_timings.py && -d tools/owners ]]; then
echo "available=true" >> "$GITHUB_OUTPUT"
else
echo "available=false" >> "$GITHUB_OUTPUT"
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index 8a0964a54ba1..c60751270b74 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -35,9 +35,9 @@ jobs:
with:
python-version-file: pyproject.toml
- # defusedxml + opentelemetry are report_test_timings.py's script deps.
+ # defusedxml + opentelemetry + tools/owners are report_test_timings.py's script deps.
- name: Install pytest
- run: python -m pip install --quiet pytest defusedxml==0.7.1 opentelemetry-sdk==1.33.1 opentelemetry-exporter-otlp-proto-http==1.33.1
+ run: python -m pip install --quiet pytest defusedxml==0.7.1 opentelemetry-sdk==1.33.1 opentelemetry-exporter-otlp-proto-http==1.33.1 ./tools/owners
# `-c /dev/null` skips the repo pytest.ini (its --reuse-db addopt needs
# pytest-django, which we don't install here). `--noconftest` skips the