: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): emit dedicated setup span in test timing traces (#62310)
Frank Hamand93b35e18edce
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.pyindex 2bf1332874e1..125d0de6a3f5 100644--- a/.github/scripts/report_test_timings.py+++ b/.github/scripts/report_test_timings.py@@ -89,6 +89,12 @@ class Shard:testcase_seconds: floatoverhead_seconds: floattests: list[TestCase]+ # Wall-clock seconds from `<testsuite timestamp>` to the first test's logstart, as+ # reported by the `posthog-junit-timings` pytest plugin. Captures the shared+ # pre-first-test overhead (imports, collection, session/package fixture setup) so+ # the trace exporter can emit it as its own span instead of letting it visually+ # collapse into the first test. Zero when the plugin didn't run (external shards).+ setup_seconds: float = 0.0# ---------- artifact directory parsing ----------@@ -178,6 +184,25 @@ def parse_iso_utc(value: str) -> datetime | None:return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+def parse_testsuite_properties(suite_elem: Any) -> dict[str, str]:+ """Extract `<properties><property name=.. value=../></properties>` from `<testsuite>`.++ Pytest writes these via `record_testsuite_property` /+ `xml.add_global_property`. Returns an empty dict when no `<properties>` block+ exists (e.g., external shards without the `posthog-junit-timings` plugin).+ """+ properties_elem = suite_elem.find("properties")+ if properties_elem is None:+ return {}+ result: dict[str, str] = {}+ for prop in properties_elem.findall("property"):+ name = prop.get("name")+ value = prop.get("value")+ if name and value is not None:+ result[name] = value+ return result++def parse_shard(xml_path: Path, info: ArtifactInfo) -> Shard | None:"""One Shard per junit XML file. Tolerant of malformed input."""try:@@ -198,8 +223,16 @@ def parse_shard(xml_path: Path, info: ArtifactInfo) -> Shard | None:except ValueError:wall_seconds = 0.0+ properties = parse_testsuite_properties(suite_elem)+ try:+ setup_seconds = max(0.0, float(properties.get("posthog.setup_seconds", "0")))+ except ValueError:+ setup_seconds = 0.0+ # Clamp to wall time so a clock skew or malformed property can't push tests past `end`.+ setup_seconds = min(setup_seconds, wall_seconds)+tests: list[TestCase] = []- cursor = start+ cursor = start + timedelta(seconds=setup_seconds)for tc in suite_elem.iter("testcase"):classname = tc.get("classname", "")name = tc.get("name", "")@@ -234,6 +267,7 @@ def parse_shard(xml_path: Path, info: ArtifactInfo) -> Shard | None:testcase_seconds=testcase_seconds,overhead_seconds=max(0.0, wall_seconds - testcase_seconds),tests=tests,+ setup_seconds=setup_seconds,)@@ -270,6 +304,7 @@ def filter_shards(shards: list[Shard], min_duration_seconds: float) -> list[Shartestcase_seconds=s.testcase_seconds,overhead_seconds=s.overhead_seconds,tests=[t for t in s.tests if should_emit(t, min_duration_seconds)],+ setup_seconds=s.setup_seconds,)for s in shards]@@ -391,9 +426,18 @@ def _emit_shard_span(tracer: trace.Tracer, shard: Shard) -> bool:shard_span.set_attribute("shard.junit_filename", shard.junit_filename)shard_span.set_attribute("shard.testcase_seconds", shard.testcase_seconds)shard_span.set_attribute("shard.overhead_seconds", shard.overhead_seconds)+ shard_span.set_attribute("shard.setup_seconds", shard.setup_seconds)has_error = Falsewith trace.use_span(shard_span, end_on_exit=False):+ # Surface the pre-first-test gap (imports, collection, session/package fixtures)+ # as its own span — without it, the cursor-based reconstruction would visually+ # collapse this overhead into the first test's window.+ if shard.setup_seconds > 0:+ setup_span = tracer.start_span("setup", start_time=_to_ns(shard.start))+ setup_span.set_attribute("shard.setup_seconds", shard.setup_seconds)+ setup_span.end(end_time=_to_ns(shard.start + timedelta(seconds=shard.setup_seconds)))+# Pytest runs serially within a shard (no `-n` flag — confirmed in pytest.ini),# so parse-time cumulative durations give non-overlapping per-test windows# that stay stable even after threshold filtering.diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.pyindex 85481c19aa4e..c4fa7272051d 100644--- a/.github/scripts/test_report_test_timings.py+++ b/.github/scripts/test_report_test_timings.py@@ -59,14 +59,28 @@ def test_derive_suite_segment_and_group(dir_name: str, expected: tuple[str, str,# ---------- shard parsing end-to-end -----------def _write_shard_xml(artifact_dir: Path, *, filename: str, timestamp: str, time: str, body: str) -> None:+def _write_shard_xml(+ artifact_dir: Path,+ *,+ filename: str,+ timestamp: str,+ time: str,+ body: str,+ properties: dict[str, str] | None = None,+) -> None:artifact_dir.mkdir(parents=True, exist_ok=True)+ properties_block = ""+ if properties:+ # Single line keeps `textwrap.dedent` below honest — an unindented inner line would zero the common prefix.+ property_elements = "".join(f'<property name="{n}" value="{v}"/>' for n, v in properties.items())+ properties_block = f"<properties>{property_elements}</properties>"(artifact_dir / filename).write_text(textwrap.dedent(f"""\<?xml version="1.0"?><testsuites><testsuite name="pytest" timestamp="{timestamp}" time="{time}">+ {properties_block}{body}</testsuite></testsuites>@@ -117,6 +131,87 @@ def test_collect_shards_builds_test_windows_and_overhead(tmp_path: Path) -> Noneassert shard.tests[3].outcome == "failed"+# ---------- setup_seconds (posthog-junit-timings plugin) ----------+++def test_parse_shard_shifts_tests_past_setup_seconds(tmp_path: Path) -> None:+ _write_shard_xml(+ tmp_path / "junit-results-backend-core-1",+ filename="junit-core.xml",+ timestamp="2026-05-04T10:00:00",+ time="10.0",+ properties={"posthog.setup_seconds": "3.5", "posthog.collection_seconds": "0.4"},+ body="""\+ <testcase classname="pkg.t.T" name="test_a" time="1.0"/>+ <testcase classname="pkg.t.T" name="test_b" time="2.0"/>+ """,+ )++ shard = report_test_timings.collect_shards(tmp_path)[0]++ assert shard.setup_seconds == pytest.approx(3.5)+ # First test no longer starts at shard.start — it starts after the setup gap.+ assert shard.tests[0].start == datetime(2026, 5, 4, 10, 0, 3, 500000, tzinfo=UTC)+ assert shard.tests[0].end == datetime(2026, 5, 4, 10, 0, 4, 500000, tzinfo=UTC)+ assert shard.tests[1].start == shard.tests[0].end+ # Shard wall-clock bounds are unaffected by the property.+ assert (shard.end - shard.start).total_seconds() == pytest.approx(10.0)+++def test_parse_shard_defaults_setup_to_zero_when_property_missing(tmp_path: Path) -> None:+ _write_shard_xml(+ tmp_path / "junit-results-backend-core-1",+ filename="junit-core.xml",+ timestamp="2026-05-04T10:00:00",+ time="5.0",+ body='<testcase classname="pkg.t.T" name="test_a" time="1.0"/>',+ )++ shard = report_test_timings.collect_shards(tmp_path)[0]++ assert shard.setup_seconds == 0.0+ assert shard.tests[0].start == shard.start+++ "raw_value,expected",+ [+ ("not-a-float", 0.0), # malformed → fall back to zero, don't crash+ ("-1.5", 0.0), # negative → clamp to zero+ ("999.0", 5.0), # exceeds wall time → clamp to wall_seconds to avoid pushing tests past shard.end+ ],+)+def test_parse_shard_handles_malformed_or_out_of_range_setup_seconds(+ tmp_path: Path, raw_value: str, expected: float+) -> None:+ _write_shard_xml(+ tmp_path / "junit-results-backend-core-1",+ filename="junit-core.xml",+ timestamp="2026-05-04T10:00:00",+ time="5.0",+ properties={"posthog.setup_seconds": raw_value},+ body='<testcase classname="pkg.t.T" name="test_a" time="1.0"/>',+ )++ shard = report_test_timings.collect_shards(tmp_path)[0]++ assert shard.setup_seconds == pytest.approx(expected)+++def test_parse_testsuite_properties_returns_empty_when_block_missing(tmp_path: Path) -> None:+ _write_shard_xml(+ tmp_path / "junit-results-backend-core-1",+ filename="junit-core.xml",+ timestamp="2026-05-04T10:00:00",+ time="1.0",+ body='<testcase classname="pkg.t.T" name="t" time="0.5"/>',+ )+ import defusedxml.ElementTree as ET++ suite = ET.parse(tmp_path / "junit-results-backend-core-1" / "junit-core.xml").getroot().find("testsuite")+ assert report_test_timings.parse_testsuite_properties(suite) == {}++# ---------- threshold filter ----------@@ -161,36 +256,39 @@ def test_filter_shards_preserves_parse_time_test_windows(tmp_path: Path) -> Noneassert filtered[0].tests[2].start == datetime(2026, 5, 4, 10, 0, 2, 300000, tzinfo=UTC)-def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatch) -> None:- class FakeSpan:- def __init__(self, name: str, start_time: int) -> None:- self.name = name- self.start_time = start_time- self.end_time: int | None = None- self.attributes: dict[str, str | int | float] = {}+class _FakeSpan:+ def __init__(self, name: str, start_time: int) -> None:+ self.name = name+ self.start_time = start_time+ self.end_time: int | None = None+ self.attributes: dict[str, str | int | float] = {}++ def set_attribute(self, key: str, value: str | int | float) -> None:+ self.attributes[key] = value++ def set_status(self, status: object) -> None:+ pass++ def end(self, end_time: int) -> None:+ self.end_time = end_time- def set_attribute(self, key: str, value: str | int | float) -> None:- self.attributes[key] = value- def set_status(self, status: object) -> None:- pass+class _FakeTracer:+ def __init__(self) -> None:+ self.spans: list[_FakeSpan] = []- def end(self, end_time: int) -> None:- self.end_time = end_time+ def start_span(self, name: str, start_time: int) -> _FakeSpan:+ span = _FakeSpan(name, start_time)+ self.spans.append(span)+ return span- class FakeTracer:- def __init__(self) -> None:- self.spans: list[FakeSpan] = []- def start_span(self, name: str, start_time: int) -> FakeSpan:- span = FakeSpan(name, start_time)- self.spans.append(span)- return span+@contextmanager+def _noop_use_span(span: _FakeSpan, end_on_exit: bool = False) -> Iterator[None]:+ yield- @contextmanager- def use_span(span: FakeSpan, end_on_exit: bool = False) -> Iterator[None]:- yield+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(info=report_test_timings.ArtifactInfo(@@ -215,13 +313,14 @@ def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatc),],)- tracer = FakeTracer()- monkeypatch.setattr(report_test_timings.trace, "use_span", use_span)+ tracer = _FakeTracer()+ monkeypatch.setattr(report_test_timings.trace, "use_span", _noop_use_span)has_error = report_test_timings._emit_shard_span(tracer, shard)assert has_error is Trueassert [span.name for span in tracer.spans] == ["core-1", "m::slow", "m::fail"]+ assert tracer.spans[0].attributes["shard.setup_seconds"] == 0.0assert tracer.spans[1].start_time == report_test_timings._to_ns(start + timedelta(seconds=0.1))assert tracer.spans[1].end_time == report_test_timings._to_ns(start + timedelta(seconds=2.1))assert tracer.spans[2].start_time == report_test_timings._to_ns(start + timedelta(seconds=2.3))@@ -230,6 +329,40 @@ def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatcassert tracer.spans[0].attributes["shard.overhead_seconds"] == pytest.approx(7.9)+def test_emit_shard_span_emits_setup_span_when_setup_seconds_positive(monkeypatch: pytest.MonkeyPatch) -> None:+ """When the posthog-junit-timings plugin reported setup_seconds, a sibling `setup`+ span covers the pre-first-test gap. Without this, the cursor-based reconstruction+ would visually attribute that gap to the first test."""+ 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="slow", duration=2.0, start=start + timedelta(seconds=3.5))],+ setup_seconds=3.5,+ )+ tracer = _FakeTracer()+ monkeypatch.setattr(report_test_timings.trace, "use_span", _noop_use_span)++ report_test_timings._emit_shard_span(tracer, shard)++ assert [span.name for span in tracer.spans] == ["core-1", "setup", "m::slow"]+ setup_span = tracer.spans[1]+ assert setup_span.start_time == report_test_timings._to_ns(start)+ assert setup_span.end_time == report_test_timings._to_ns(start + timedelta(seconds=3.5))+ assert setup_span.attributes["shard.setup_seconds"] == pytest.approx(3.5)+ assert tracer.spans[0].attributes["shard.setup_seconds"] == pytest.approx(3.5)++# ---------- workflow context ----------diff --git a/posthog/conftest.py b/posthog/conftest.pyindex a8428c3b5281..0a6924ebb9d3 100644--- a/posthog/conftest.py+++ b/posthog/conftest.py@@ -1,4 +1,5 @@import os+import timeimport subprocessfrom collections.abc import Callablefrom functools import partial@@ -458,6 +459,70 @@ def mock_email_mfa_verifier(request, mocker):)+class _JUnitTimingsPlugin:+ """Capture wall-clock offsets and surface them as JUnit `<testsuite>` properties.++ Pytest's junit XML emits one `time` per `<testcase>` but no per-test start. The+ CI trace exporter (`.github/scripts/report_test_timings.py`) reconstructs windows+ by stacking durations from `<testsuite timestamp>`, so the shared pre-first-test+ overhead (interpreter import, plugin init, collection, session/package fixture+ setup) gets visually attributed to the first test span. We record the offset+ explicitly so the exporter can split it into its own span.++ Important: this measures up to the first test's *call* phase, not its setup+ phase. The backend CI uses `-o junit_duration_report=call`, so session and+ module-scoped fixture setup time is excluded from `<testcase time>` and+ instead lives in this pre-first-call gap.+ """++ _PROPERTY_SETUP = "posthog.setup_seconds"+ _PROPERTY_COLLECTION = "posthog.collection_seconds"++ def __init__(self) -> None:+ self._session_start: float | None = None+ self._collection_finish: float | None = None+ self._first_test_call_start: float | None = None++ def pytest_sessionstart(self, session: pytest.Session) -> None:+ self._session_start = time.monotonic()++ def pytest_collection_finish(self, session: pytest.Session) -> None:+ if self._collection_finish is None:+ self._collection_finish = time.monotonic()++ # `tryfirst` so our timestamp lands just before pytest's default call impl+ # actually runs the test body — capturing the moment the first call begins,+ # after session/module fixture setup has completed.+ @pytest.hookimpl(tryfirst=True)+ def pytest_runtest_call(self, item: pytest.Item) -> None:+ if self._first_test_call_start is None:+ self._first_test_call_start = time.monotonic()++ @staticmethod+ def _find_junit_xml_plugin(config: pytest.Config) -> Any:+ # pytest's junit XML plugin (`_pytest.junitxml.LogXML`) registers itself+ # without a stable name — `get_plugin("junitxml")` returns the module, not+ # the instance — so we identify it by its `add_global_property` interface.+ for _, plugin in config.pluginmanager.list_name_plugin():+ if hasattr(plugin, "add_global_property"):+ return plugin+ return None++ # Must run before pytest_junitxml's own sessionfinish, which serializes the XML+ # and stops consuming new `add_global_property` calls after that point.+ @pytest.hookimpl(tryfirst=True)+ def pytest_sessionfinish(self, session: pytest.Session, exitstatus: int) -> None:+ if self._session_start is None:+ return+ xml = self._find_junit_xml_plugin(session.config)+ if xml is None:+ return+ if self._first_test_call_start is not None:+ xml.add_global_property(self._PROPERTY_SETUP, f"{self._first_test_call_start - self._session_start:.6f}")+ if self._collection_finish is not None:+ xml.add_global_property(self._PROPERTY_COLLECTION, f"{self._collection_finish - self._session_start:.6f}")++def pytest_configure(config):"""Configure pytest-django to allow access to persons databases by default.@@ -471,6 +536,9 @@ def pytest_configure(config):TestCase.databases = {"default", "persons_db_writer", "persons_db_reader"}TransactionTestCase.databases = {"default", "persons_db_writer", "persons_db_reader"}+ if not config.pluginmanager.hasplugin("posthog-junit-timings"):+ config.pluginmanager.register(_JUnitTimingsPlugin(), "posthog-junit-timings")+def _runs_on_internal_pr() -> bool:"""