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): retry pytest failures and preserve retry diagnostics (#101428)

Julian Bezc053da3e63b4
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index dd36ab9a4411..397f9813195f 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -1203,6 +1203,10 @@ jobs:
shell: bash
run: |
set +e
+ # Open PR heads must have retry diagnostics before blanket retries are enabled.
+ if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
+ export PYTEST_ADDOPTS="$PYTEST_ADDOPTS --force-reruns 1 --reruns-delay 1 -r fEsxXR"
+ fi
overall=0
# The job checks out the PR head while this workflow runs merged with
# master. A head that predates the person-on-events default lacks the
@@ -2468,6 +2472,11 @@ jobs:
run: |
unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)
set +e
+ # Open PR heads must have retry diagnostics before blanket retries are enabled.
+ RETRY_ARGS=()
+ if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
+ RETRY_ARGS=(--force-reruns 1 --reruns-delay 1)
+ fi
# Unrebased branches predate .github/coverage-core.cfg; an explicit --cov-config
# pointing at a missing file is a hard error, so drop coverage rather than fail.
if [[ -n "$COV_ARGS" && ! -f .github/coverage-core.cfg ]]; then
@@ -2500,9 +2509,7 @@ jobs:
if [[ "$MODE" == "selected" ]]; then
# Selected mode: run only the test files chosen by the snob shadow selector.
# Sharded only when build_django_matrix sized the segment above one
- # shard, and no --reruns anywhere, mirroring
- # canonical: retries mask the raw flake signal Trunk needs (the shadow
- # strips the quarantine gate itself).
+ # shard. One pytest retry mirrors canonical's budget.
if [[ "${{ matrix.compat }}" == "true" ]]; then
targets="$COMPAT_FILES"
elif [[ "${{ matrix.person-on-events }}" == "true" ]]; then
@@ -2522,7 +2529,7 @@ jobs:
# shellcheck disable=SC2086
pytest -v --tb=short --reuse-db -o junit_duration_report=call $targets -m "not async_migrations" \
"${SELECTED_SPLIT[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-core.xml \
$COV_ARGS \
$PYTEST_ARGS
@@ -2547,7 +2554,7 @@ jobs:
--pytest-durations=100 \
--splitting-algorithm="$SPLITTING_ALGORITHM" \
"${SPLIT_GRANULARITY[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-core.xml \
$COV_ARGS \
$PYTEST_ARGS
@@ -2596,6 +2603,11 @@ jobs:
run: |
unset GITHUB_TOKEN # reserved var injected by Depot CI; can't override via env: (see workflow env note)
set +e
+ # Open PR heads must have retry diagnostics before blanket retries are enabled.
+ RETRY_ARGS=()
+ if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
+ RETRY_ARGS=(--force-reruns 1 --reruns-delay 1)
+ fi
# Pick the split algorithm and granularity at runtime (see Run Core tests).
SPLITTING_ALGORITHM=duration_based_chunks
SPLIT_GRANULARITY=()
@@ -2613,8 +2625,7 @@ jobs:
# two timeout tests fail downstream (hogql_table never reached). Canonical GHA still runs them.
# The --deselect guards stay on both branches so a selected run can't re-enable them.
if [[ "$MODE" == "selected" ]]; then
- # Selected mode: no --reruns — see the core selected branch;
- # the full run also skips --reruns, mirroring canonical.
+ # Selected mode uses the same single-retry budget as the full run.
# A selection wide enough to need more than one shard is split like a
# full run. Item granularity on purpose: the target list is already
# narrow, so pre-import file skipping saves nothing, and the per-segment
@@ -2627,7 +2638,7 @@ jobs:
# shellcheck disable=SC2086
pytest -v --tb=short --reuse-db -o junit_duration_report=call $TEMPORAL_FILES -m "not async_migrations" \
"${SELECTED_SPLIT[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-temporal.xml \
$PYTEST_ARGS
else
@@ -2640,7 +2651,7 @@ jobs:
--pytest-durations=100 \
--splitting-algorithm="$SPLITTING_ALGORITHM" \
"${SPLIT_GRANULARITY[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-temporal.xml \
$PYTEST_ARGS
fi
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.py
index 5be9a263712b..315cd2eaf69b 100644
--- a/.github/scripts/report_test_timings.py
+++ b/.github/scripts/report_test_timings.py
@@ -106,6 +106,7 @@ class TestCase:
file: str # normalized repo-relative test file; '' when no checked-in file can be found
file_source: Literal["junit", "inferred", "missing"]
selector: str # runnable runner-specific selector; '' when the file cannot be found
+ runner_name: str = "" # GitHub runner that executed the test, not the trace-export job's runner
@dataclass(frozen=True)
@@ -571,6 +572,7 @@ def parse_shard(
end=datetime.min,
outcome=outcome,
attempts=attempts,
+ runner_name=parse_testsuite_properties(tc).get("posthog.runner_name", ""),
)
)
file_durations.append(file_testcase_seconds)
@@ -902,6 +904,8 @@ def _emit_shard_span(
test_span.set_attribute("test.job_key", job_trace_key(info))
test_span.set_attribute("test.outcome", test.outcome)
test_span.set_attribute("test.attempts", test.attempts)
+ if test.runner_name:
+ test_span.set_attribute("test.runner_name", test.runner_name)
test_span.set_attribute("test.classname", test.classname)
test_span.set_attribute("test.name", test.name)
if test.file:
diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.py
index 89429be8f69b..887b9af26794 100644
--- a/.github/scripts/test_report_test_timings.py
+++ b/.github/scripts/test_report_test_timings.py
@@ -70,6 +70,7 @@ def _testcase(
start: datetime | None = None,
name: str = "t",
file: str = "m.py",
+ runner_name: str = "",
) -> 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(
@@ -84,6 +85,7 @@ def _testcase(
end=test_start + timedelta(seconds=duration),
outcome=outcome,
attempts=attempts,
+ runner_name=runner_name,
)
@@ -278,6 +280,7 @@ def test_collect_shards_builds_test_windows_and_overhead(tmp_path: Path) -> None
<testcase classname="pkg.test_a.TestA" name="test_fast" time="0.1"/>
<testcase classname="pkg.test_a.TestA" name="test_slow" time="2.0"/>
<testcase classname="pkg.test_a.TestA" name="test_rerun" time="0.2">
+ <properties><property name="posthog.runner_name" value="runner-example"/></properties>
<flakyFailure message="x" time="0.3"/>
</testcase>
<testcase classname="pkg.test_a.TestA" name="test_fail" time="0.1"><failure message="x"/></testcase>
@@ -306,6 +309,8 @@ def test_collect_shards_builds_test_windows_and_overhead(tmp_path: Path) -> None
assert shard.tests[2].duration_seconds == pytest.approx(0.5)
assert shard.tests[2].outcome == "rerun_passed"
assert shard.tests[2].attempts == 2
+ assert shard.tests[2].runner_name == "runner-example"
+ assert shard.tests[0].runner_name == ""
assert shard.tests[3].outcome == "failed"
@@ -717,7 +722,7 @@ def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatc
testcase_seconds=2.1,
overhead_seconds=7.9,
tests=[
- _testcase(name="slow", duration=2.0, start=start + timedelta(seconds=0.1)),
+ _testcase(name="slow", duration=2.0, start=start + timedelta(seconds=0.1), runner_name="runner-example"),
_testcase(
name="fail",
outcome="failed",
@@ -742,6 +747,8 @@ def test_emit_shard_span_uses_stored_test_windows(monkeypatch: pytest.MonkeyPatc
assert tracer.spans[0].attributes["shard.overhead_seconds"] == pytest.approx(7.9)
assert tracer.spans[1].attributes["test.runner"] == "pytest"
assert tracer.spans[1].attributes["test.job_key"] == "backend:core:1"
+ assert tracer.spans[1].attributes["test.runner_name"] == "runner-example"
+ assert "test.runner_name" not in tracer.spans[2].attributes
def test_emit_shard_span_emits_setup_span_when_setup_seconds_positive(monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index d333fead377b..a3355ab0e31a 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -1075,6 +1075,10 @@ jobs:
shell: bash
run: |
set +e
+ # Open PR heads must have retry diagnostics before blanket retries are enabled.
+ if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
+ export PYTEST_ADDOPTS="$PYTEST_ADDOPTS --force-reruns 1 --reruns-delay 1 -r fEsxXR"
+ fi
overall=0
# The job checks out the PR head while this workflow runs merged with
# master. A head that predates the person-on-events default lacks the
@@ -3341,6 +3345,11 @@ jobs:
shell: 'signal-fanout bash --noprofile --norc -eo pipefail {0}'
run: |
set +e
+ # Open PR heads must have retry diagnostics before blanket retries are enabled.
+ RETRY_ARGS=()
+ if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
+ RETRY_ARGS=(--force-reruns 1 --reruns-delay 1)
+ fi
# Unrebased branches predate .github/coverage-core.cfg; an explicit --cov-config
# pointing at a missing file is a hard error, so drop coverage rather than fail.
if [[ -n "$COV_ARGS" && ! -f .github/coverage-core.cfg ]]; then
@@ -3378,10 +3387,9 @@ jobs:
if [[ "$MODE" == "selected" ]]; then
# Selected mode: run only the test files chosen by the snob shadow selector.
# Sharded only when build_django_matrix sized the segment above one shard,
- # no --store-durations (don't pollute timing data with a partial run), and
- # no --reruns (fail loud on the narrow subset).
- # The full run below also runs without --reruns: retries mask the raw flake
- # signal Trunk needs, and the quarantine gate is the flake net instead.
+ # no --store-durations (don't pollute timing data with a partial run).
+ # One pytest retry overrides product/marker budgets; Engineering analytics
+ # retains the retry count and failed-attempt diagnostics even when it passes.
if [[ "${{ matrix.compat }}" == "true" ]]; then
targets="$COMPAT_FILES"
elif [[ "${{ matrix.person-on-events }}" == "true" ]]; then
@@ -3401,7 +3409,7 @@ jobs:
# shellcheck disable=SC2086
pytest -v --tb=short --reuse-db -o junit_duration_report=call $targets -m "not async_migrations" \
"${SELECTED_SPLIT[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-core.xml \
$COV_ARGS \
$PYTEST_ARGS
@@ -3426,7 +3434,7 @@ jobs:
--pytest-durations=100 \
--splitting-algorithm="$SPLITTING_ALGORITHM" \
"${SPLIT_GRANULARITY[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-core.xml \
$COV_ARGS \
$PYTEST_ARGS
@@ -3496,6 +3504,11 @@ jobs:
TEMPORAL_FILES: ${{ fromJSON(needs.turbo-discover.outputs.selection || '{}').temporal_files }}
run: |
set +e
+ # Open PR heads must have retry diagnostics before blanket retries are enabled.
+ RETRY_ARGS=()
+ if grep -qF '"posthog.runner_name"' posthog/conftest.py; then
+ RETRY_ARGS=(--force-reruns 1 --reruns-delay 1)
+ fi
# Pick the split algorithm and granularity at runtime: optimal_chunks +
# file granularity only when the installed pytest-split offers them, else
# duration_based_chunks / item. A workflow edit runs merged with master, so
@@ -3518,8 +3531,7 @@ jobs:
fi
if [[ "$MODE" == "selected" ]]; then
# Selected mode: no --store-durations (don't pollute timing data with a
- # partial run), no --reruns. See the core selected branch; the full run
- # also skips --reruns so raw flake signal reaches Trunk.
+ # partial run). The same single-retry budget applies to selected and full runs.
# A selection wide enough to need more than one shard is split like a
# full run. Item granularity on purpose: the target list is already
# narrow, so pre-import file skipping saves nothing, and the per-segment
@@ -3532,7 +3544,7 @@ jobs:
# shellcheck disable=SC2086
pytest -v --tb=short --reuse-db -o junit_duration_report=call $TEMPORAL_FILES -m "not async_migrations" \
"${SELECTED_SPLIT[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-temporal.xml \
$PYTEST_ARGS
else
@@ -3548,7 +3560,7 @@ jobs:
--pytest-durations=100 \
--splitting-algorithm="$SPLITTING_ALGORITHM" \
"${SPLIT_GRANULARITY[@]}" \
- -r fEsxX \
+ "${RETRY_ARGS[@]}" -r fEsxXR \
--junitxml=junit-temporal.xml \
$PYTEST_ARGS
fi
diff --git a/docs/internal/backend-test-retries.md b/docs/internal/backend-test-retries.md
new file mode 100644
index 000000000000..a115d5ab3ae1
--- /dev/null
+++ b/docs/internal/backend-test-retries.md
@@ -0,0 +1,29 @@
+# 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 74787aa96bce..7c858b8e3637 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 typing import Any
+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
+if TYPE_CHECKING:
+ from _pytest.terminal import TerminalReporter
+
try:
from hogli_commands.quarantine.pytest_support import apply_quarantine_markers
except ImportError: # fail-open: runs without tools/hogli-commands on pythonpath
@@ -582,6 +585,18 @@ class _JUnitTimingsPlugin:
# 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)))
+ if runner_name := os.environ.get("RUNNER_NAME"):
+ report.user_properties.append(("posthog.runner_name", runner_name))
+
+ def pytest_terminal_summary(self, terminalreporter: "TerminalReporter") -> None:
+ if not terminalreporter.hasopt("R"):
+ return
+ # pytest-rerunfailures 16.1's summary lists nodeids but omits the failed attempt's traceback.
+ for report in terminalreporter.stats.get("rerun", []):
+ terminalreporter.write_sep("_", f"RERUN {report.nodeid} ({report.when})")
+ report.toterminal(terminalreporter._tw)
+ # Anchor the final exception within the log-thinning context window.
+ terminalreporter.write_sep("_", f"RERUN END {report.nodeid} ({report.when})")
@staticmethod
def _find_junit_xml_plugin(config: pytest.Config) -> Any:
diff --git a/posthog/test/test_junit_report_location.py b/posthog/test/test_junit_report_location.py
index e13970387cfd..a328b021eca0 100644
--- a/posthog/test/test_junit_report_location.py
+++ b/posthog/test/test_junit_report_location.py
@@ -1,9 +1,14 @@
+from io import StringIO
from pathlib import Path
from types import SimpleNamespace
-from typing import cast
+from typing import Literal, cast
import pytest
+from _pytest._io import TerminalWriter
+from _pytest.terminal import TerminalReporter
+
+from posthog.conftest import _JUnitTimingsPlugin
from posthog.test.junit import set_junit_report_location
@@ -24,3 +29,39 @@ def test_junit_report_uses_the_collected_test_file() -> None:
set_junit_report_location(cast(pytest.Item, item), report)
assert report.location == ("posthog/api/test/test_project.py", 1426, "test_delete_project")
+
+
[email protected]("when", ["setup", "call", "teardown"])
+def test_retry_diagnostics_survive_a_passing_final_attempt(
+ monkeypatch: pytest.MonkeyPatch, when: Literal["setup", "call", "teardown"]
+) -> None:
+ monkeypatch.setenv("RUNNER_NAME", "runner-example")
+ plugin = _JUnitTimingsPlugin()
+ recovered = pytest.TestReport(
+ nodeid="test_example.py::test_retry",
+ location=("test_example.py", 1, "test_retry"),
+ keywords={},
+ outcome="passed",
+ longrepr=None,
+ when="teardown",
+ rerun=1,
+ )
+ plugin.pytest_runtest_logreport(recovered)
+ assert dict(recovered.user_properties) == {"posthog.reruns": "1", "posthog.runner_name": "runner-example"}
+
+ failed_attempt = pytest.TestReport(
+ nodeid=recovered.nodeid,
+ location=recovered.location,
+ keywords={},
+ outcome="failed",
+ longrepr="ConnectionError: example connection dropped",
+ when=when,
+ )
+ output = StringIO()
+ writer = TerminalWriter(output)
+ reporter = SimpleNamespace(
+ stats={"rerun": [failed_attempt]}, hasopt=lambda _: True, write_sep=writer.sep, _tw=writer
+ )
+ 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()
diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.md
index 56f9fa80c68d..797fd78f6275 100644
--- a/products/engineering_analytics/README.md
+++ b/products/engineering_analytics/README.md
@@ -87,6 +87,10 @@ graph LR
## The goal: CI Signals for PostHog Desktop
+Backend pytest retries retain their failed-attempt diagnostics even when the job passes.
+The job-log collector uses recovered-test spans to include those successful jobs, and keeps their original conclusion.
+See [Backend test retries](../../docs/internal/backend-test-retries.md) for the retry budget and reporting path.
+
Valuable CI conditions ("this check is flaky", "master went red at SHA X", "this PR is wedged on a failing required check") become [Signals](../signals): grouped, researched against the repository, and handed to PostHog Desktop for autonomous remediation.
Detection is defined once in `logic/` over the read layer, so the emitter and the MCP tools share one definition.
Shortening ready-for-review-to-merge is the headline metric this serves.
diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.py
index 9a2725f5d2d4..d9309d7c81ce 100644
--- a/products/engineering_analytics/backend/logic/job_logs/activity.py
+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py
@@ -98,7 +98,6 @@ async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[str
# (visible to any logs:read holder) by design and intentionally do NOT inherit the GitHub
# source's resource-level access control. Don't emit anything a logs:read holder shouldn't see.
def _thin_and_emit() -> int:
- # Failures-only today; pass a different ThinningConfig once all-jobs ingestion lands.
thinned = thin_log_lines(archive)
with JobLogsEmitter(endpoint=settings.OTLP_LOGS_INGEST_ENDPOINT, token=log_ingest_token) as emitter:
# run_id→trace, job_id→span so the Logs UI can group a whole run and isolate one job.
diff --git a/products/engineering_analytics/backend/logic/job_logs/coordinator.py b/products/engineering_analytics/backend/logic/job_logs/coordinator.py
index 2f5d86ffdaa2..fd12a132121a 100644
--- a/products/engineering_analytics/backend/logic/job_logs/coordinator.py
+++ b/products/engineering_analytics/backend/logic/job_logs/coordinator.py
@@ -1,4 +1,4 @@
-"""Find recently-failed CI jobs and fan out one idempotent log-fetch workflow per job.
+"""Find failed CI jobs and jobs recovered by pytest retries, then fetch their diagnostic logs.
Per-job workflow id (``gh-logs-{team}-{job}``, reuse ``ALLOW_DUPLICATE_FAILED_ONLY``) means each
job's log is fetched and emitted at most once, re-running only after a failed attempt.
@@ -52,7 +52,7 @@ _PREFIX = re.compile(r"^[A-Za-z0-9_]*$") # warehouse source prefixes; guards th
MAX_DISCOVERED_JOBS = 2000
-def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: str) -> list[dict[str, Any]]:
+def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: str, repo: str) -> list[dict[str, Any]]:
# Window on completed_at (when the job finished), not created_at: a queued or long-running job
# can be created well before it fails, and a created_at window would miss it. completed_at is an
# ISO-8601 string and is always set for a failed (completed) job, so a lexical comparison against
@@ -64,17 +64,39 @@ def _query_failed_jobs(team: Team, prefix: str, cutoff_iso: str) -> list[dict[st
# ranks every tick (dedup happens later, at child-workflow start), so a job pushed below the
# limit can never rise back into view and would be silently dropped. Matches
# MAX_DISCOVERED_JOBS; the high-water-mark cursor (deferred) removes the cap concern entirely.
+ # Run, attempt, and runner restrict successful-job downloads to runners with retry evidence.
sql = f"""
SELECT id AS job_id, run_id, head_branch AS branch, conclusion,
name AS job_name, workflow_name, run_attempt, head_sha
FROM {table}
- WHERE conclusion = 'failure' AND completed_at > {{cutoff}}
+ WHERE completed_at > {{cutoff}} AND (
+ conclusion = 'failure'
+ OR (
+ conclusion = 'success'
+ AND (toString(run_id), toString(run_attempt), runner_name) IN (
+ SELECT resource_attributes['ci.run_id'], resource_attributes['ci.run_attempt'],
+ attributes['test.runner_name']
+ FROM posthog.trace_spans
+ WHERE service_name = 'ci-backend'
+ AND lower(resource_attributes['ci.repository']) = lower({{repo}})
+ AND timestamp >= (
+ SELECT min(parseDateTimeBestEffort(started_at))
+ FROM {table}
+ WHERE completed_at > {{cutoff}} AND conclusion = 'success'
+ )
+ AND attributes['test.outcome'] = 'rerun_passed'
+ AND notEmpty(coalesce(attributes['test.runner_name'], ''))
+ )
+ )
+ )
ORDER BY completed_at DESC
LIMIT {MAX_DISCOVERED_JOBS}
"""
with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=team.pk):
response = execute_hogql_query(
- query=parse_select(sql, placeholders={"cutoff": ast.Constant(value=cutoff_iso)}),
+ query=parse_select(
+ sql, placeholders={"cutoff": ast.Constant(value=cutoff_iso), "repo": ast.Constant(value=repo)}
+ ),
team=team,
query_type="GithubJobLogsDiscovery",
# Trusted internal sweep with no request user: without this, HogQL's access-control build
@@ -137,7 +159,7 @@ def _discover_failed_jobs(cutoff_iso: str) -> list[dict[str, Any]]:
try:
# Row handling stays inside the try so a single bad row (e.g. a null job_id) skips this
# source rather than failing discovery for every team.
- for row in _query_failed_jobs(source.team, prefix, cutoff_iso):
+ for row in _query_failed_jobs(source.team, prefix, cutoff_iso, repo):
job_id = row.get("job_id")
if job_id is None:
continue
@@ -187,7 +209,7 @@ def _discover_failed_jobs(cutoff_iso: str) -> list[dict[str, Any]]:
@activity.defn
async def discover_failed_jobs_activity(cutoff_iso: str) -> list[dict[str, Any]]:
- """Failed CI jobs across teams with a connected GitHub source, as FetchJobLogInputs dicts."""
+ """Failed or retry-recovered CI jobs with a connected GitHub source, as FetchJobLogInputs dicts."""
return await database_sync_to_async(_discover_failed_jobs, thread_sensitive=False)(cutoff_iso)
diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py b/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py
index 1d78f9906b16..ddf5fb9c8ca8 100644
--- a/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py
+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_coordinator.py
@@ -58,6 +58,6 @@ class TestQueryFailedJobs:
# workflow_jobs warehouse table denied and the query raises "You don't have access to table" —
# the worker then silently emits nothing. Locks in the bypass that makes the trusted query work.
mock_execute.return_value = SimpleNamespace(columns=["job_id"], results=[])
- _query_failed_jobs(Team(pk=1), "devex_", "2026-06-30T00:00:00+00:00")
+ _query_failed_jobs(Team(pk=1), "devex_", "2026-06-30T00:00:00+00:00", "PostHog/posthog")
mock_execute.assert_called_once()
assert mock_execute.call_args.kwargs["bypass_warehouse_access_control"] is True
diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py b/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py
index 077c06d705d9..468380e8ff4a 100644
--- a/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py
+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_thinning.py
@@ -1,5 +1,15 @@
+from io import StringIO
+from types import SimpleNamespace
+from typing import cast
+
+import pytest
+
+from _pytest._io import TerminalWriter
+from _pytest.terminal import TerminalReporter
from parameterized import parameterized
+from posthog.conftest import _JUnitTimingsPlugin
+
from products.engineering_analytics.backend.logic.job_logs.thinning import ThinningConfig, thin_log, thin_log_lines
_CAP = ThinningConfig().max_lines
@@ -10,15 +20,44 @@ class TestThinLog:
text = "\n".join(f"step {i}" for i in range(_CAP))
assert thin_log(text) == text
- def test_keeps_failure_region_warning_and_summary(self):
+ def test_keeps_exception_at_end_of_long_recovered_traceback(self) -> None:
+ failure = "ValueError: example fixture is unavailable"
+ report = pytest.TestReport(
+ nodeid="test_example.py::test_retry",
+ location=("test_example.py", 1, "test_retry"),
+ keywords={},
+ outcome="failed",
+ longrepr="\n".join([f"fixture frame {i}" for i in range(100)] + [failure]),
+ when="setup",
+ )
+ output = StringIO()
+ writer = TerminalWriter(output)
+ reporter = SimpleNamespace(stats={"rerun": [report]}, hasopt=lambda _: True, write_sep=writer.sep, _tw=writer)
+ _JUnitTimingsPlugin().pytest_terminal_summary(cast(TerminalReporter, reporter))
+ noise = "\n".join(f"job output {i}" for i in range(1000))
+
+ thinned = thin_log(f"{noise}\n{output.getvalue()}\n{noise}")
+
+ assert failure in thinned
+ assert "RERUN test_example.py::test_retry (setup)" in thinned
+ assert "job output 500" not in thinned
+
+ @parameterized.expand(
+ [
+ ("failure", "FAILED tests/test_widget.py::test_render - ConnectionError: disconnected"),
+ ("retry", "RERUN tests/test_widget.py::test_render (call)"),
+ ("warning", "##[warning]GeoIP database not found, continuing without it"),
+ ("summary", "test result: FAILED. 412 passed; 1 failed"),
+ ("exit", "##[error]Process completed with exit code 1."),
+ ]
+ )
+ def test_keeps_failure_region_warning_and_summary(self, _name: str, marker: str) -> None:
noise = [f"downloading package {i}" for i in range(2000)]
failure = [
- "##[warning]GeoIP database not found, continuing without it",
- "FAILED tests/test_widget.py::test_render - AssertionError: 1 != 2",
- "test result: FAILED. 412 passed; 1 failed",
- "##[error]Process completed with exit code 1.",
+ marker,
+ "example_client.py:42: ConnectionError: disconnected",
]
- out = thin_log("\n".join(noise + failure))
+ out = thin_log("\n".join(noise + failure + noise))
content = [line for line in out.splitlines() if "lines omitted" not in line]
assert len(content) <= _CAP
diff --git a/products/engineering_analytics/backend/logic/job_logs/thinning.py b/products/engineering_analytics/backend/logic/job_logs/thinning.py
index a77b1dc0eefe..4acb852f9022 100644
--- a/products/engineering_analytics/backend/logic/job_logs/thinning.py
+++ b/products/engineering_analytics/backend/logic/job_logs/thinning.py
@@ -24,6 +24,7 @@ DEFAULT_FAILURE_MARKERS: tuple[str, ...] = (
"Traceback (most recent call last)", # Python
"AssertionError", # Python / JS
"FAILED ", # pytest per-test failure line
+ "RERUN ", # pytest failed-attempt diagnostics, including jobs that recovered
"test result: FAILED", # cargo test summary
"panic:", # Go / Rust panic
"--- FAIL", # go test
diff --git a/products/engineering_analytics/backend/logic/queries/_test_spans.py b/products/engineering_analytics/backend/logic/queries/_test_spans.py
index 8821cac25ade..bc410213d746 100644
--- a/products/engineering_analytics/backend/logic/queries/_test_spans.py
+++ b/products/engineering_analytics/backend/logic/queries/_test_spans.py
@@ -16,10 +16,8 @@ The grain is the CI run, not the span and not the run attempt:
- Every attempt of a run tests the same commit, so attempts are repeated trials: a run that both
failed and passed a test has proven it nondeterministic, whichever attempt failed first. That is
what ``recovered_in_run`` means. Recovery must happen in the same stable matrix job as the failure;
- a pass under a different configuration proves nothing. Backend CI runs pytest without ``--reruns``
- deliberately (failures stay visible instead of being retried away), so a "re-run failed jobs"
- recovery is where that proof comes from; ``rerun_passed`` is the same proof from the handful of
- tests hand-marked ``@pytest.mark.flaky(reruns=N)``.
+ a pass under a different configuration proves nothing. ``rerun_passed`` is the same proof from
+ pytest's in-process retry, whose count survives in JUnit even when the final outcome is a pass.
Failures with no recovery prove nothing about determinism. This surface answers how much a failing
test costs us, so unproven failures are ranked by blast radius and never called flaky.
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index 2f8584f64cbd..f0e5f1e5e408 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -9,7 +9,7 @@ from contextlib import contextmanager
from pathlib import Path
from typing import Any
-from posthog.test.base import BaseTest
+from posthog.test.base import PostHogTestCase
import pandas as pd
@@ -34,7 +34,7 @@ GITHUB_SOURCE_PREFIX = "myprefix"
@contextmanager
-def seeding_object_storage(test: BaseTest) -> Iterator[None]:
+def seeding_object_storage(test: PostHogTestCase) -> Iterator[None]:
# Skipping locally keeps the suite usable without the dev stack; skipping in CI would drop every
# warehouse-backed assertion behind a green job, so there it raises.
try:
@@ -318,7 +318,9 @@ def _status_row(status_id: int, deployment_id: int, state: str, environment: str
}
-def create_github_warehouse_table(test: BaseTest, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
+def create_github_warehouse_table(
+ test: PostHogTestCase, base_name: str, columns: dict, rows: list[dict[str, Any]]
+) -> str:
# Returns the real table name (prefixed), which the builder is then told to read,
# proving build_query honors the resolved name instead of a hardcoded one.
df = pd.DataFrame(rows, columns=list(columns.keys()))
diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.py
index a2f532adad2c..3158fc8c81f3 100644
--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py
+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py
@@ -9,8 +9,14 @@ from rest_framework import status
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
+from products.engineering_analytics.backend.logic.job_logs.coordinator import _query_failed_jobs
from products.engineering_analytics.backend.logic.queries._test_spans import selector_from_nodeid
-from products.engineering_analytics.backend.tests._github_fixtures import connect_github_source_without_data
+from products.engineering_analytics.backend.logic.views.source_schema import WORKFLOW_JOBS_COLUMNS
+from products.engineering_analytics.backend.tests._github_fixtures import (
+ GITHUB_SOURCE_PREFIX,
+ connect_github_source_without_data,
+ create_github_warehouse_table,
+)
from products.warehouse_sources.backend.facade.models import ExternalDataSource
T_RERUN_RECOVERY = "posthog/api/test/test_rerun/TestRerun::test_green_on_attempt_2"
@@ -93,6 +99,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
pr="401",
branch="f1",
selector=T_IN_JOB_SELECTOR,
+ runner_name="runner-example",
),
# Failures across 3 distinct PRs, no recovery: qualifies on blast radius alone.
cls._span(11, T_THREE_PRS, "failed", ts=earlier, run="500", pr="501", branch="f1"),
@@ -115,9 +122,27 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
cls._span(19, T_TIE_B, "rerun_passed", ts=recent, run="1000", pr="1001", branch="tie"),
cls._span(20, T_TIE_A, "rerun_passed", ts=recent, run="1001", pr="1002", branch="tie"),
# Would qualify on signal alone, but a non-CI service must never reach the queue.
- cls._span(21, T_FOREIGN, "rerun_passed", ts=recent, run="1100", pr="1101", service="other-service"),
+ cls._span(
+ 21,
+ T_FOREIGN,
+ "rerun_passed",
+ ts=recent,
+ run="1100",
+ pr="1101",
+ service="other-service",
+ runner_name="runner-example",
+ ),
# Would qualify on signal alone, but belongs to another connected repository.
- cls._span(22, T_OTHER_REPO, "rerun_passed", ts=recent, run="1200", pr="1201", repo="PostHog/posthog.com"),
+ cls._span(
+ 22,
+ T_OTHER_REPO,
+ "rerun_passed",
+ ts=recent,
+ run="1200",
+ pr="1201",
+ repo="PostHog/posthog.com",
+ runner_name="runner-example",
+ ),
# A job-root span carries no test.outcome and must never become a row.
cls._span(23, "Backend CI / core (1)", None, ts=recent, run="1300", branch="master"),
# Main Jest spans share the same evidence model. Recovery only counts within the
@@ -183,6 +208,41 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
super().tearDownClass()
+ def test_job_log_discovery_includes_recovered_jobs_without_collecting_unrelated_passes(self) -> None:
+ now = datetime.now(UTC).replace(microsecond=0)
+ jobs = [
+ (1, 400, 1, "runner-example", "success"),
+ (2, 400, 1, "another-runner", "success"),
+ (3, 400, 2, "runner-example", "success"),
+ (4, 999, 1, "runner-example", "success"),
+ (5, 999, 1, "another-runner", "failure"),
+ (6, 1100, 1, "runner-example", "success"),
+ (7, 1200, 1, "runner-example", "success"),
+ (8, 1000, 1, "", "success"),
+ ]
+ create_github_warehouse_table(
+ self,
+ "github_workflow_jobs",
+ WORKFLOW_JOBS_COLUMNS,
+ [
+ dict.fromkeys(WORKFLOW_JOBS_COLUMNS)
+ | {
+ "id": job_id,
+ "run_id": run_id,
+ "run_attempt": attempt,
+ "runner_name": runner,
+ "conclusion": conclusion,
+ "started_at": (now - timedelta(days=2)).isoformat(),
+ "completed_at": now.isoformat(),
+ }
+ for job_id, run_id, attempt, runner, conclusion in jobs
+ ],
+ )
+ rows = _query_failed_jobs(
+ self.team, GITHUB_SOURCE_PREFIX, (now - timedelta(hours=12)).isoformat(), "posthog/POSTHOG"
+ )
+ assert {row["job_id"] for row in rows} == {1, 5}
+
@classmethod
def _span(
cls,
@@ -199,6 +259,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
service: str = "ci-backend",
repo: str = "PostHog/posthog",
job: str = "",
+ runner_name: str = "",
) -> str:
# Physical attributes carry a type suffix ('test.outcome__str'); the `attributes` ALIAS
# column strips it. Resource attributes are stored as-is; attempt="" drops the
@@ -208,6 +269,8 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
)
if job:
attr_pairs.append(f"'test.job_key__str', '{job}'")
+ if runner_name:
+ attr_pairs.append(f"'test.runner_name__str', '{runner_name}'")
attrs = f"map({', '.join(attr_pairs)})" if attr_pairs else "map()"
resource_pairs = [
f"'{key}', '{value}'"
diff --git a/turbo.json b/turbo.json
index 17e4185710c8..38c352fc6b31 100644
--- a/turbo.json
+++ b/turbo.json
@@ -34,6 +34,7 @@
// unless listed here. Pass-through, not env: they must not become cache keys.
"passThroughEnv": [
"PYTEST_ADDOPTS",
+ "RUNNER_NAME",
"RUNS_ON_INTERNAL_PR",
"SANDBOX_JWT_PRIVATE_KEY",
"MODAL_TOKEN_ID",