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.

fix(ci): capture pytest reruns in CI test telemetry (#67904)

Raúl Negrón-Otero554f2f8ca8f8
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.py
index 457f085dd7a1..1f4f3192bb32 100644
--- a/.github/scripts/report_test_timings.py
+++ b/.github/scripts/report_test_timings.py
@@ -148,14 +148,24 @@ def collect_artifact_infos(artifacts_root: Path) -> list[ArtifactInfo]:
def classify_testcase(testcase: Any) -> tuple[str, int]:
"""Return (outcome, attempts) from a single `<testcase>` element.
- pytest-rerunfailures emits prior attempts as `<rerunFailure>` /
- `<rerunError>` siblings before the final outcome child. Walk children once.
+ pytest's junitxml records nothing for pytest-rerunfailures attempts (a
+ rerun report is neither passed, failed, nor skipped), so the root
+ conftest's `posthog-junit-timings` plugin surfaces the retry count as a
+ `posthog.reruns` testcase property. `<rerunFailure>`/`<rerunError>`
+ children from other junit producers are honored too. Walk children once.
"""
rerun_count = 0
final_outcome: str | None = None
for child in testcase:
tag = child.tag
- if tag.startswith("rerun"):
+ if tag == "properties":
+ for prop in child.findall("property"):
+ if prop.get("name") == "posthog.reruns":
+ try:
+ rerun_count += max(0, int(prop.get("value", "0")))
+ except ValueError:
+ pass
+ elif tag.startswith("rerun"):
rerun_count += 1
elif tag in ("failure", "error", "skipped") and final_outcome is None:
if tag == "skipped" and child.get("type") == "pytest.xfail":
diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.py
index b0dc4159095d..334b1e96826f 100644
--- a/.github/scripts/test_report_test_timings.py
+++ b/.github/scripts/test_report_test_timings.py
@@ -11,6 +11,8 @@ from pathlib import Path
import pytest
+from defusedxml import ElementTree
+
SCRIPT_PATH = Path(__file__).with_name("report_test_timings.py")
SPEC = importlib.util.spec_from_file_location("report_test_timings", SCRIPT_PATH)
assert SPEC is not None and SPEC.loader is not None
@@ -131,6 +133,35 @@ def test_collect_shards_builds_test_windows_and_overhead(tmp_path: Path) -> None
assert shard.tests[3].outcome == "failed"
+# ---------- rerun classification (posthog.reruns testcase property) ----------
+
+
+ "testcase_xml,expected",
+ [
+ # pytest 8's junitxml drops rerun attempts entirely; the posthog-junit-timings
+ # plugin records them as a testcase property — the only rerun signal we get.
+ (
+ '<testcase name="t"><properties><property name="posthog.reruns" value="2"/></properties></testcase>',
+ ("rerun_passed", 3),
+ ),
+ # A rerun count must not mask a test that exhausted its retries and failed.
+ (
+ '<testcase name="t"><properties><property name="posthog.reruns" value="2"/></properties>'
+ '<failure message="x"/></testcase>',
+ ("failed", 3),
+ ),
+ # Malformed value must never crash the exporter.
+ (
+ '<testcase name="t"><properties><property name="posthog.reruns" value="garbage"/></properties></testcase>',
+ ("passed", 1),
+ ),
+ ],
+)
+def test_classify_testcase_reads_rerun_property(testcase_xml: str, expected: tuple[str, int]) -> None:
+ assert report_test_timings.classify_testcase(ElementTree.fromstring(testcase_xml)) == expected
+
+
# ---------- setup_seconds (posthog-junit-timings plugin) ----------
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index 025ea0ff4e1a..39ae54f558e6 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -35,17 +35,21 @@ jobs:
with:
python-version-file: pyproject.toml
+ # defusedxml + opentelemetry are report_test_timings.py's script deps.
- name: Install pytest
- run: python -m pip install --quiet 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
# `-c /dev/null` skips the repo pytest.ini (its --reuse-db addopt needs
# pytest-django, which we don't install here). `--noconftest` skips the
# root conftest.py, whose autouse fixtures import the posthog package
- # (and thus Django) — not installed in this lightweight job. The test
- # is standalone and needs no conftest fixtures beyond pytest's tmp_path.
+ # (and thus Django) — not installed in this lightweight job. These tests
+ # are standalone and need no conftest fixtures beyond pytest's tmp_path.
- name: Schema-usage scanner tests (Python)
run: python -m pytest .github/scripts/test_schema_usage_scan.py -v -c /dev/null -p no:cacheprovider --noconftest
+ - name: Test-timings reporter tests (Python)
+ run: python -m pytest .github/scripts/test_report_test_timings.py -v -c /dev/null -p no:cacheprovider --noconftest
+
# Shells out to schema_usage_scan.py via python3 (preinstalled on ubuntu).
- name: Schema-impact tests (Node)
run: node --test .github/scripts/schema-impact.test.js
diff --git a/posthog/conftest.py b/posthog/conftest.py
index cd1b16db9187..70d07f24aff8 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -472,10 +472,16 @@ class _JUnitTimingsPlugin:
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.
+
+ Also records pytest-rerunfailures retries as a `<testcase>` property: pytest's
+ junitxml appends children only for passed/failed/skipped reports, so a rerun
+ report leaves no trace and a flaky fail-then-pass serializes as a clean
+ `<testcase/>` — invisible to flaky-test telemetry.
"""
_PROPERTY_SETUP = "posthog.setup_seconds"
_PROPERTY_COLLECTION = "posthog.collection_seconds"
+ _PROPERTY_RERUNS = "posthog.reruns"
def __init__(self) -> None:
self._session_start: float | None = None
@@ -497,6 +503,18 @@ class _JUnitTimingsPlugin:
if self._first_test_call_start is None:
self._first_test_call_start = time.monotonic()
+ # `tryfirst` so the property is on the report before junitxml's own
+ # logreport consumes `user_properties` into the `<testcase>` element.
+ @pytest.hookimpl(tryfirst=True)
+ def pytest_runtest_logreport(self, report: pytest.TestReport) -> None:
+ reruns = getattr(report, "rerun", 0) or 0 # attempt index, set by pytest-rerunfailures
+ # str() widens TestReport.outcome's Literal: "rerun" is assigned by pytest-rerunfailures.
+ if not reruns or report.when != "teardown" or str(report.outcome) == "rerun":
+ return
+ # Appended exactly once: intermediate attempts never log a non-rerun teardown,
+ # and each report owns its own copy of `user_properties`.
+ report.user_properties.append((self._PROPERTY_RERUNS, str(reruns)))
+
@staticmethod
def _find_junit_xml_plugin(config: pytest.Config) -> Any:
# pytest's junit XML plugin (`_pytest.junitxml.LogXML`) registers itself