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): report pytest retry attempts to trunk (#101493)

Julian Bez2d6c6bd79d48
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 397f9813195f..eb3a1c398009 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -42,7 +42,8 @@
# shadow strips both the gate and the verdict step entirely, both variables are
# no-ops here and there is nothing to mirror. Canonical's turbo-tests gate now calls
# ./.github/actions/trunk-quarantine-gate to retry once. The shadow has no gate, so it
-# does not need a mirrored action)
+# does not need a mirrored action. Canonical pins Trunk CLI 0.15.4 for JUnit retry
+# elements; the shadow has no uploader CLI to pin)
# - Per-test failure rollup: canonical's django_tests gate uploads product JUnit and, when a
# 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
diff --git a/.github/actions/trunk-quarantine-gate/action.yml b/.github/actions/trunk-quarantine-gate/action.yml
index 2ae8b83793f2..cbe1d4da0d44 100644
--- a/.github/actions/trunk-quarantine-gate/action.yml
+++ b/.github/actions/trunk-quarantine-gate/action.yml
@@ -28,7 +28,7 @@ runs:
org-slug: posthog-inc
variant: ${{ inputs.variant }}
# Pinned rather than 'latest', which costs an extra github.com request to follow the release redirect.
- cli-version: '0.13.7'
+ cli-version: '0.15.4'
quarantine: true
previous-step-outcome: ${{ inputs.previous-step-outcome }}
token: ${{ inputs.token }}
@@ -52,7 +52,7 @@ runs:
junit-paths: ${{ inputs.junit-paths }}
org-slug: posthog-inc
variant: ${{ inputs.variant }}
- cli-version: '0.13.7'
+ cli-version: '0.15.4'
quarantine: true
previous-step-outcome: ${{ inputs.previous-step-outcome }}
token: ${{ inputs.token }}
diff --git a/.github/scripts/prepare-product-junit-for-trunk.sh b/.github/scripts/prepare-product-junit-for-trunk.sh
index 8607345d2bd4..b73d485a07e7 100644
--- a/.github/scripts/prepare-product-junit-for-trunk.sh
+++ b/.github/scripts/prepare-product-junit-for-trunk.sh
@@ -40,6 +40,10 @@ for report in products/*/junit-product.xml; do
if ! is_excluded "$report"; then
product="$(basename "$(dirname "$report")")"
cp "$report" "$output_dir/junit-product-$product.xml"
+ retry_report="${report%.xml}-retry-failures.xml"
+ if [ -f "$retry_report" ]; then
+ cp "$retry_report" "$output_dir/junit-product-$product-retry-failures.xml"
+ fi
fi
done
diff --git a/.github/scripts/prepare-product-junit-for-trunk.test.sh b/.github/scripts/prepare-product-junit-for-trunk.test.sh
index 3ce3e0e01cbb..abb5dab2ba03 100644
--- a/.github/scripts/prepare-product-junit-for-trunk.test.sh
+++ b/.github/scripts/prepare-product-junit-for-trunk.test.sh
@@ -21,6 +21,7 @@ run_case() {
read -r -a exclusions <<<"$excluded_paths"
mkdir -p "$root"
create_product "$root" warehouse_sources @posthog/products-warehouse-sources "$warehouse_report"
+ printf '%s\n' '<testsuite tests="1" failures="1" />' >"$root/products/warehouse_sources/junit-product-retry-failures.xml"
create_product "$root" warehouse_sources_queue @posthog/products-warehouse-sources-queue '<testsuite tests="1" failures="0" />'
create_product "$root" other @posthog/products-other "$other_report"
@@ -40,6 +41,10 @@ run_case() {
echo "FAIL: $name staged excluded report $excluded_path"
exit 1
fi
+ if [ -e "$root/trunk-junit/junit-product-$product-retry-failures.xml" ]; then
+ echo "FAIL: $name staged retries for excluded report $excluded_path"
+ exit 1
+ fi
done
if [ "${#exclusions[@]}" -eq 0 ] && [ ! -e "$root/trunk-junit/junit-product-warehouse_sources.xml" ]; then
echo "FAIL: $name did not stage a report that nothing excludes"
@@ -59,4 +64,12 @@ run_case selected-report-fails '--filter=@posthog/products-warehouse-sources' 1
run_case multiple-exclusions '--filter=@posthog/products-other' 0 '<testsuite tests="1" failures="0" />' '<testsuite tests="1" failures="0" />' 'products/warehouse_sources/junit-product.xml products/other/junit-product.xml'
run_case no-exclusions-stages-a-failed-report '--filter=@posthog/products-warehouse-sources' 0 '<testsuite tests="1" failures="1"><testcase><failure /></testcase></testsuite>' '<testsuite tests="1" failures="0" />' ''
+retry_root="$workdir/retry-failures"
+mkdir -p "$retry_root"
+create_product "$retry_root" other @posthog/products-other '<testsuite tests="1" failures="0" />'
+printf '%s\n' '<testsuite tests="1" failures="1"><testcase><failure /></testcase></testsuite>' >"$retry_root/products/other/junit-product-retry-failures.xml"
+(cd "$retry_root" && bash "$script" trunk-junit '--filter=@posthog/products-other')
+test -f "$retry_root/trunk-junit/junit-product-other-retry-failures.xml"
+echo 'ok: stages retry failures with the product report'
+
echo "Product JUnit preparation regression cases passed."
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index a3355ab0e31a..8106625dca5f 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -3670,7 +3670,9 @@ jobs:
# artifact, and the timing reporter needs both to pair a re-run recovery
# (attempt-N pass) with the attempt-1 failure it proves flaky.
name: junit-results-backend-${{ matrix.artifact_key }}${{ github.run_attempt != '1' && format('-attempt{0}', github.run_attempt) || '' }}
- path: junit-*.xml
+ path: |
+ junit-*.xml
+ !junit-*-retry-failures.xml
# Best-effort Trunk upload (continue-on-error); the "Fail on test failure" step below is
# the verdict, so a Trunk outage can't red a passing shard. Internal PRs only (needs the
@@ -3688,9 +3690,9 @@ jobs:
if: ${{ !cancelled() && matrix.segment == 'Core' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}
uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2
with:
- junit-paths: junit-core.xml
+ junit-paths: junit-core.xml,junit-core-retry-failures.xml
org-slug: posthog-inc
- cli-version: '0.13.7'
+ cli-version: '0.15.4'
quarantine: true
previous-step-outcome: ${{ steps.run-core-tests.outcome }}
token: ${{ secrets.TRUNK_API_TOKEN }}
@@ -3700,9 +3702,9 @@ jobs:
if: ${{ !cancelled() && matrix.segment == 'Temporal' && needs.changes.outputs.backend == 'true' && env.RUNS_ON_INTERNAL_PR == 'true' && github.repository == 'PostHog/posthog' && github.actor != 'dependabot[bot]' && vars.TRUNK_UPLOAD_ENABLED == 'true' }}
uses: trunk-io/analytics-uploader@385f1ccdf345b4532dc4b6c665dd432b702b8e28 # v2.1.2
with:
- junit-paths: junit-temporal.xml
+ junit-paths: junit-temporal.xml,junit-temporal-retry-failures.xml
org-slug: posthog-inc
- cli-version: '0.13.7'
+ cli-version: '0.15.4'
quarantine: true
previous-step-outcome: ${{ steps.run-temporal-tests.outcome }}
token: ${{ secrets.TRUNK_API_TOKEN }}
diff --git a/docs/internal/backend-test-retries.md b/docs/internal/backend-test-retries.md
deleted file mode 100644
index a115d5ab3ae1..000000000000
--- a/docs/internal/backend-test-retries.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# Backend test retries
-
-Backend CI retries each failed pytest test once, in the same pytest process, with a one-second delay.
-The Django core and Temporal jobs and the Turbo product jobs use `--force-reruns 1 --reruns-delay 1`.
-The Depot workflow uses the same budget.
-This overrides per-test retry markers, including markers that request more retries.
-Local test commands retain their existing retry settings.
-
-Pytest keeps control of the result: a passing retry passes, and a second failure fails.
-Collection errors and a killed test process are not rescued by this mechanism.
-CI does not rerun the step or job automatically.
-
-## Keeping the failure evidence
-
-The existing JUnit hook records `posthog.reruns` on the final test report.
-For retried tests it also records the executing GitHub `RUNNER_NAME` as `posthog.runner_name`.
-The timing reporter exports these as `test.attempts`, `test.outcome` (`rerun_passed` for a recovered test), and `test.runner_name`.
-Recovered tests are retained even if they are below the normal duration threshold.
-Engineering analytics already treats `rerun_passed` as evidence of flakiness.
-
-CI enables `-rR` and the JUnit plugin prints failed-attempt tracebacks in the terminal summary.
-The pinned pytest-rerunfailures 16.1 otherwise prints only rerun node IDs.
-The job-log collector includes successful jobs with a matching recovered-test span, using the repository, workflow run, run attempt, and runner name.
-If a runner is reused for several jobs in one run attempt, those successful jobs can also be collected.
-The normal log retention limits still apply, and `RERUN` lines preserve the surrounding diagnostics during thinning.
-These logs retain the job's `success` conclusion; recovery is not a persistent job failure.
-
-Trunk still receives the final JUnit result.
-This preserves retry evidence in Engineering analytics, but does not restore Trunk's visibility into each failed attempt.
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 7c858b8e3637..46c6c890c14a 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -4,12 +4,15 @@ import warnings
import subprocess
from collections.abc import Callable
from functools import partial
+from pathlib import Path
from typing import TYPE_CHECKING, Any
from urllib.parse import quote_plus
import pytest
from posthog.test.base import PostHogTestCase, run_clickhouse_statement_in_parallel
+from _pytest.junitxml import ET, bin_xml_escape, mangle_test_address
+
if TYPE_CHECKING:
from _pytest.terminal import TerminalReporter
@@ -544,10 +547,9 @@ class _JUnitTimingsPlugin:
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.
+ Also records pytest-rerunfailures retries as a `<testcase>` property.
+ Pytest's JUnit output omits intermediate rerun reports, so a separate
+ JUnit file preserves their failures for Trunk.
"""
_PROPERTY_SETUP = "posthog.setup_seconds"
@@ -558,6 +560,7 @@ class _JUnitTimingsPlugin:
self._session_start: float | None = None
self._collection_finish: float | None = None
self._first_test_call_start: float | None = None
+ self._retry_reports: list[pytest.TestReport] = []
def pytest_sessionstart(self, session: pytest.Session) -> None:
self._session_start = time.monotonic()
@@ -579,6 +582,8 @@ class _JUnitTimingsPlugin:
@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
+ if str(report.outcome) == "rerun":
+ self._retry_reports.append(report)
# 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
@@ -621,6 +626,50 @@ class _JUnitTimingsPlugin:
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}")
+ self._write_retry_junit(xml)
+
+ def _write_retry_junit(self, xml: Any) -> None:
+ source_path = Path(xml.logfile)
+ retry_path = source_path.with_name(f"{source_path.stem}-retry-failures.xml")
+ if not self._retry_reports:
+ retry_path.unlink(missing_ok=True)
+ return
+
+ failures = sum(report.when == "call" for report in self._retry_reports)
+ suite = ET.Element(
+ "testsuite",
+ name=xml.suite_name,
+ tests=str(len(self._retry_reports)),
+ failures=str(failures),
+ errors=str(len(self._retry_reports) - failures),
+ skipped="0",
+ time=f"{sum(report.duration for report in self._retry_reports):.3f}",
+ timestamp=xml.suite_start.as_utc().astimezone().isoformat(),
+ )
+ for report in self._retry_reports:
+ names = mangle_test_address(report.nodeid)
+ classnames = names[:-1]
+ if xml.prefix:
+ classnames.insert(0, xml.prefix)
+ attrs = {
+ "classname": ".".join(classnames),
+ "name": bin_xml_escape(names[-1]),
+ "file": report.location[0],
+ "time": f"{report.duration:.3f}",
+ "attempt_number": str(getattr(report, "rerun", 0) + 1),
+ }
+ if report.location[1] is not None:
+ attrs["line"] = str(report.location[1])
+ testcase = ET.SubElement(suite, "testcase", attrs)
+ reprcrash = getattr(report.longrepr, "reprcrash", None)
+ message = getattr(reprcrash, "message", None) or report.longreprtext or "pytest retry failed"
+ tag = "failure" if report.when == "call" else "error"
+ ET.SubElement(testcase, tag, message=bin_xml_escape(message)).text = bin_xml_escape(report.longreprtext)
+
+ root = ET.Element("testsuites")
+ root.append(suite)
+ retry_path.parent.mkdir(parents=True, exist_ok=True)
+ ET.ElementTree(root).write(retry_path, encoding="utf-8", xml_declaration=True)
def pytest_configure(config):
diff --git a/posthog/test/test_junit_report_location.py b/posthog/test/test_junit_report_location.py
index a328b021eca0..af6e14c5d476 100644
--- a/posthog/test/test_junit_report_location.py
+++ b/posthog/test/test_junit_report_location.py
@@ -2,10 +2,12 @@ from io import StringIO
from pathlib import Path
from types import SimpleNamespace
from typing import Literal, cast
+from xml.etree import ElementTree
import pytest
from _pytest._io import TerminalWriter
+from _pytest.junitxml import LogXML
from _pytest.terminal import TerminalReporter
from posthog.conftest import _JUnitTimingsPlugin
@@ -65,3 +67,92 @@ def test_retry_diagnostics_survive_a_passing_final_attempt(
plugin.pytest_terminal_summary(cast(TerminalReporter, reporter))
assert f"RERUN test_example.py::test_retry ({when})" in output.getvalue()
assert "ConnectionError: example connection dropped" in output.getvalue()
+
+
[email protected]("when", ["setup", "call", "teardown"])
+def test_retry_failure_uses_separate_junit_file(tmp_path: Path, when: Literal["setup", "call", "teardown"]) -> None:
+ junit_path = tmp_path / "reports" / "junit.xml"
+ xml = LogXML(junit_path, prefix=None, report_duration="call")
+ xml.pytest_sessionstart()
+ plugin = _JUnitTimingsPlugin()
+ session = cast(
+ pytest.Session,
+ SimpleNamespace(config=SimpleNamespace(pluginmanager=SimpleNamespace(list_name_plugin=lambda: [("xml", xml)]))),
+ )
+ plugin.pytest_sessionstart(session)
+
+ retry = pytest.TestReport(
+ nodeid="test_example.py::test_retry",
+ location=("test_example.py", 1, "test_retry"),
+ keywords={},
+ outcome=cast(Literal["passed", "failed", "skipped"], "rerun"),
+ longrepr="first failure",
+ when=when,
+ duration=0.1,
+ rerun=0,
+ )
+ plugin.pytest_runtest_logreport(retry)
+ xml.pytest_runtest_logreport(retry)
+
+ final_call = pytest.TestReport(
+ nodeid=retry.nodeid,
+ location=retry.location,
+ keywords={},
+ outcome="skipped",
+ longrepr=("test_example.py", 1, "Skipped: final attempt skipped"),
+ when="call",
+ duration=0.1,
+ )
+ plugin.pytest_runtest_logreport(final_call)
+ xml.pytest_runtest_logreport(final_call)
+ teardown = pytest.TestReport(
+ nodeid=retry.nodeid,
+ location=retry.location,
+ keywords={},
+ outcome="passed",
+ longrepr=None,
+ when="teardown",
+ rerun=1,
+ )
+ plugin.pytest_runtest_logreport(teardown)
+ xml.pytest_runtest_logreport(teardown)
+ plugin.pytest_sessionfinish(session, 0)
+ xml.pytest_sessionfinish()
+
+ main_suite = ElementTree.parse(junit_path).getroot().find("testsuite")
+ assert main_suite is not None
+ assert main_suite.find(".//skipped") is not None
+ assert main_suite.find(".//failure") is None
+ assert main_suite.find(".//error") is None
+
+ retry_suite = ElementTree.parse(junit_path.with_name("junit-retry-failures.xml")).getroot().find("testsuite")
+ assert retry_suite is not None
+ assert retry_suite.get("tests") == "1"
+ assert retry_suite.get("failures") == ("1" if when == "call" else "0")
+ assert retry_suite.get("errors") == ("0" if when == "call" else "1")
+ testcase = retry_suite.find("testcase")
+ assert testcase is not None
+ assert testcase.get("classname") == "test_example"
+ assert testcase.get("name") == "test_retry"
+ assert testcase.get("file") == "test_example.py"
+ assert testcase.get("attempt_number") == "1"
+ failure = testcase.find("failure" if when == "call" else "error")
+ assert failure is not None
+ assert failure.get("message") == "first failure"
+
+
+def test_retry_junit_removes_stale_file_without_reruns(tmp_path: Path) -> None:
+ junit_path = tmp_path / "junit.xml"
+ retry_path = tmp_path / "junit-retry-failures.xml"
+ retry_path.write_text("stale")
+ xml = LogXML(junit_path, prefix=None)
+ xml.pytest_sessionstart()
+ plugin = _JUnitTimingsPlugin()
+ session = cast(
+ pytest.Session,
+ SimpleNamespace(config=SimpleNamespace(pluginmanager=SimpleNamespace(list_name_plugin=lambda: [("xml", xml)]))),
+ )
+ plugin.pytest_sessionstart(session)
+ plugin.pytest_sessionfinish(session, 0)
+
+ assert not retry_path.exists()