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(eng-analytics): add flaky test leaderboard (#67996)

Raúl Negrón-Otero45afba5e2b64
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.py
index 1f4f3192bb32..920c2358f0c1 100644
--- a/.github/scripts/report_test_timings.py
+++ b/.github/scripts/report_test_timings.py
@@ -69,6 +69,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
+ selector: str # runnable 'path/test.py::Class::test' from JUnit's `file`; '' when file is absent
@dataclass(frozen=True)
@@ -188,6 +189,24 @@ def to_nodeid(classname: str, name: str) -> str:
return f"{classname.replace('.', '/')}::{name}" if classname else name
+def to_selector(file: str, classname: str, name: str) -> str:
+ """Runnable pytest selector 'path/to/test_x.py::TestClass::test_y' from JUnit's `file` + `classname`.
+
+ Unlike `to_nodeid`, JUnit's `file` gives the exact module boundary, so nothing is guessed: the
+ class portion is `classname` with the file's module prefix stripped. Returns '' when JUnit omits
+ `file` (external shards) or the shape is unexpected — consumers fall back to the nodeid.
+ """
+ if not file or not name:
+ return ""
+ module = file[:-3].replace("/", ".") if file.endswith(".py") else ""
+ if not classname:
+ return f"{file}::{name}"
+ if module and classname.startswith(module):
+ class_part = classname[len(module) :].lstrip(".")
+ return f"{file}::{class_part}::{name}" if class_part else f"{file}::{name}"
+ return ""
+
+
def parse_iso_utc(value: str) -> datetime | None:
"""Parse an ISO 8601 timestamp (pytest emits naive); treat as UTC."""
if not value:
@@ -251,6 +270,7 @@ def parse_shard(xml_path: Path, info: ArtifactInfo) -> Shard | None:
for tc in suite_elem.iter("testcase"):
classname = tc.get("classname", "")
name = tc.get("name", "")
+ file = tc.get("file", "")
outcome, attempts = classify_testcase(tc)
try:
duration = float(tc.get("time", "0"))
@@ -264,6 +284,7 @@ def parse_shard(xml_path: Path, info: ArtifactInfo) -> Shard | None:
nodeid=to_nodeid(classname, name),
classname=classname,
name=name,
+ selector=to_selector(file, classname, name),
duration_seconds=duration,
start=test_start,
end=test_end,
@@ -474,6 +495,8 @@ def _emit_shard_span(tracer: trace.Tracer, shard: Shard, root_name: str) -> bool
test_span.set_attribute("test.attempts", test.attempts)
test_span.set_attribute("test.classname", test.classname)
test_span.set_attribute("test.name", test.name)
+ if test.selector:
+ test_span.set_attribute("test.selector", test.selector)
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 1ca6586b23d7..4c117bedd9f9 100644
--- a/.github/scripts/test_report_test_timings.py
+++ b/.github/scripts/test_report_test_timings.py
@@ -35,6 +35,7 @@ def _testcase(
nodeid=f"m::{name}",
classname="m",
name=name,
+ selector=f"m.py::{name}",
duration_seconds=duration,
start=test_start,
end=test_start + timedelta(seconds=duration),
@@ -43,6 +44,29 @@ def _testcase(
)
+ "file,classname,name,expected",
+ [
+ # Class-based: the file's module prefix is stripped from classname, leaving the class.
+ (
+ "posthog/hogql/test/test_resolver.py",
+ "posthog.hogql.test.test_resolver.TestResolver",
+ "test_x",
+ "posthog/hogql/test/test_resolver.py::TestResolver::test_x",
+ ),
+ # Module-level test: classname equals the module, so no class segment.
+ ("pkg/test_a.py", "pkg.test_a", "test_y", "pkg/test_a.py::test_y"),
+ # No classname at all also collapses to file::name.
+ ("pkg/test_a.py", "", "test_y", "pkg/test_a.py::test_y"),
+ # No file (external shard) or an unexpected classname shape yields '' — caller uses the nodeid.
+ ("", "pkg.test_a.TestA", "test_y", ""),
+ ("pkg/test_a.py", "totally.unrelated.Thing", "test_y", ""),
+ ],
+)
+def test_to_selector(file: str, classname: str, name: str, expected: str) -> None:
+ assert report_test_timings.to_selector(file, classname, name) == expected
+
+
# ---------- artifact name parsing ----------
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f588426b8bd9..4fb16d3384a0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5420,6 +5420,10 @@ snapshots:
hash: v1.k794b7964.c5aa3840807ca349309a893b884ebc767c8fab70a82127532c1dae27d13f9f3d.51y_th6-WoFAlLgiWfsu6KUr3rxWjZzAbV84FIikvXQ
scenes-app-data-warehouse-sql-editor--top-tools-per-server--light:
hash: v1.k794b7964.e6420f44b86930d43085b575192d3c26ac0401919a4af6f8d7bd1c799e964836.pZmiZ4w-9QbQ60TFc6Sx94NT0YmU4EULydWdqDqxDmY
+ scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--dark:
+ hash: v1.k794b7964.11b690fa6779c138fc78a905c08701fa1c0d14ca740712bc737cb704be689518.p4XIRGrjbbNPexcT586n6Anw8Hvzjcjmd0FS1NOVQ5I
+ scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--light:
+ hash: v1.k794b7964.0c9580ba54e5d865a26157ce07d53efb14f3e6bb1039d22fc7d46a5b01217346.JWsdPaiMJDKrEjpDZ1wKeTH9bHP_8iWFRTOynGQi3FA
scenes-app-error-project-unavailable--access-revoked--dark:
hash: v1.k794b7964.30ace8f015100159e1dedbed07ff9f0b0b770535870d5c98ea764b10ff1f7621.dTVw9qLa7D_e7ZNme4tVuPZov-0Gg1o84aiDl5zihF0
scenes-app-error-project-unavailable--access-revoked--light:
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d4b32462b661..9f5b3e6513b0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3124,6 +3124,9 @@ importers:
'@posthog/icons':
specifier: 'catalog:'
+ '@storybook/react':
+ specifier: 'catalog:'
'@types/react':
specifier: 18.3.27
version: 18.3.27
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 133459302bb2..8b36cc69963d 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -144,6 +144,7 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` C
- `workflow_health` — per-workflow run count, success rate, p50/p95 duration, last failure over a `date_from`/`date_to` window, optionally scoped to a single git `branch` (`head_branch`).
- `pr_lifecycle` — PR header + ordered CI-run timeline (a genuine assembly; `metric_quality = "partial"` until reviews/deploys land).
- `ci_failure_logs` — the thinned failure log lines for a PR's CI, grouped by job. Resolves the PR to its run_ids via the same `pull_requests` attribution as `pr_runs`, then reads the Logs product (`service.name = github-ci-logs`) joined on `run_id`. Reads from Logs, not the warehouse.
+- `flaky_tests` — the flaky-test leaderboard: per-test CI spans from the Traces product (`trace_spans`, emitted by Backend CI's report-test-timings job) grouped by pytest nodeid over a window (default `-7d`, max 30 days), ranked by flakiness signal. A test qualifies by passing on retry (`rerun_passed`) at least `min_rerun_passes` times (default 1) OR failing on at least `min_failed_prs` distinct PRs (default 3). Absolute counts only, never rates — sub-threshold passing runs aren't emitted, so denominators are biased. Reads from Traces, not the warehouse.
**UI:** a read-only scene on the same endpoints via the generated API client — a PR list (CI status, CI duration, age), the count cards (open / stuck >7d / failing CI), and a workflow-health view. Read-only; **no saved views or stateful filters in this phase** (persisted/stateful surfaces are a later, separate decision). Columns that need deferred data — time-in-review, reviewers/approvals, per-check counts, DORA — are out until the event substrate lands (§9).
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 17d9054968ba..d2406263f9c9 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -25,6 +25,7 @@ from products.engineering_analytics.backend import logic
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
CIFailureLogs,
+ FlakyTestList,
GitHubSource,
MasterFailureGroup,
PRCostSummary,
@@ -252,6 +253,27 @@ def list_workflow_health(
)
+def list_flaky_tests(
+ *,
+ team: Team,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ min_rerun_passes: int | None = None,
+ min_failed_prs: int | None = None,
+ limit: int | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> FlakyTestList:
+ return logic.build_flaky_tests(
+ curated=_authorized_source(team, source_id, user_access_control),
+ date_from=date_from,
+ date_to=date_to,
+ min_rerun_passes=min_rerun_passes,
+ min_failed_prs=min_failed_prs,
+ limit=limit,
+ )
+
+
def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:
return logic.build_github_sources(team=team, user_access_control=user_access_control)
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 9ebfb9ddab08..113adf1c589b 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -423,6 +423,55 @@ class CIFailureLogs:
truncated: bool
+# The one caveat that governs every flaky figure — defined once here (the canonical-types home)
+# so the API/MCP description and any other consumer-facing copy read from it instead of drifting.
+FLAKY_TEST_SIGNAL_CAVEAT = (
+ "All figures are absolute counts, never rates: fast passing runs are not emitted, so denominators "
+ "are biased. Pass-on-retry counts only flow from CI lanes running with reruns enabled; in other "
+ "lanes a flake surfaces as a plain failure, which the distinct-PR count catches."
+)
+
+
+@dataclass(frozen=True)
+class FlakyTestItem:
+ """One flaky-test leaderboard row, aggregated from the per-test CI spans in the Traces store.
+
+ See ``FLAKY_TEST_SIGNAL_CAVEAT`` for why these are absolute counts and how the two signals
+ (pass-on-retry vs distinct-PR failures) divide the rerun-enabled and no-rerun lanes.
+ """
+
+ # Reconstructed pytest nodeid (the span name), e.g. 'posthog/api/test/test_x/TestX::test_y'.
+ nodeid: str
+ # Runnable pytest selector ('posthog/api/test/test_x.py::TestX::test_y'). Exact when the CI
+ # reporter stamped it; reconstructed from the nodeid (file/class boundary guessed) for older spans.
+ selector: str
+ # Spans where the test failed first, then passed on an automatic retry.
+ rerun_passed_count: int
+ # Spans with outcome 'failed' or 'error' (the final outcome after any retries).
+ failed_count: int
+ # Distinct PRs among the failed/error spans; master/branch failures carry no PR and don't count.
+ failed_pr_count: int
+ # Distinct git branches across all of the test's signal spans in the window.
+ branch_count: int
+ # Spans where the test failed while quarantined (xfail) — already masked, still flaky.
+ xfailed_count: int
+ # Most recent signal span for this test in the window.
+ last_seen_at: datetime
+
+
+@dataclass(frozen=True)
+class FlakyTestList:
+ """The flaky-test leaderboard for a window: qualifying tests ranked by flakiness signal,
+ capped at ``limit`` with an explicit truncation flag (same shape as ``PullRequestList``).
+ A test qualifies when it passed on retry at least ``min_rerun_passes`` times OR failed on
+ at least ``min_failed_prs`` distinct PRs in the window.
+ """
+
+ items: list[FlakyTestItem]
+ truncated: bool
+ limit: int
+
+
@dataclass(frozen=True)
class CIStatusRollup:
"""A PR's CI, collapsed from the latest workflow run per workflow on its head
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 6df101e82a36..fadb88aaece6 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -16,6 +16,7 @@ from posthog.utils import relative_date_parse
from products.engineering_analytics.backend.facade.contracts import (
CICardSummary,
CIFailureLogs,
+ FlakyTestList,
GitHubSource,
MasterFailureGroup,
PRCostSummary,
@@ -41,6 +42,7 @@ from products.engineering_analytics.backend.logic.queries.ci_failure_logs import
query_ci_failure_logs,
query_run_failure_logs,
)
+from products.engineering_analytics.backend.logic.queries.flaky_tests import query_flaky_tests
from products.engineering_analytics.backend.logic.queries.job_aggregates import query_job_aggregates
from products.engineering_analytics.backend.logic.queries.master_failures import query_master_failures
from products.engineering_analytics.backend.logic.queries.pr_cost import (
@@ -75,6 +77,15 @@ _DEFAULT_WORKFLOW_WINDOW = "-24h"
# unbounded range would materialize an enormous response. A year is plenty for trends.
_MAX_WINDOW_DAYS = 366
+# Flaky-test leaderboard defaults: a week of signal is the triage window, a month the ceiling
+# (per-test spans are high-volume and the short Traces retention makes older data spotty anyway).
+_DEFAULT_FLAKY_WINDOW = "-7d"
+_MAX_FLAKY_WINDOW_DAYS = 30
+_DEFAULT_FLAKY_MIN_RERUN_PASSES = 1
+_DEFAULT_FLAKY_MIN_FAILED_PRS = 3
+_DEFAULT_FLAKY_LIMIT = 50
+_MAX_FLAKY_LIMIT = 200
+
# Each builder operates on an already-resolved CuratedGitHubSource: source selection and per-source
# warehouse access control happen once at the facade, which hands these builders the authorized
@@ -230,19 +241,52 @@ def build_workflow_health(
return query_workflow_health(curated=curated, date_from=parsed_from, date_to=parsed_to, branch=branch)
+def build_flaky_tests(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ min_rerun_passes: int | None = None,
+ min_failed_prs: int | None = None,
+ limit: int | None = None,
+) -> FlakyTestList:
+ parsed_from, parsed_to = _parse_window(
+ curated.team, date_from, date_to, default=_DEFAULT_FLAKY_WINDOW, max_days=_MAX_FLAKY_WINDOW_DAYS
+ )
+ min_rerun_passes = min_rerun_passes if min_rerun_passes is not None else _DEFAULT_FLAKY_MIN_RERUN_PASSES
+ min_failed_prs = min_failed_prs if min_failed_prs is not None else _DEFAULT_FLAKY_MIN_FAILED_PRS
+ # A zero threshold would make its HAVING arm trivially true and silently qualify every
+ # test with any signal span — require an explicit positive bar instead.
+ if min_rerun_passes < 1 or min_failed_prs < 1:
+ raise ValueError("min_rerun_passes and min_failed_prs must be at least 1")
+ limit = limit if limit is not None else _DEFAULT_FLAKY_LIMIT
+ if not 1 <= limit <= _MAX_FLAKY_LIMIT:
+ raise ValueError(f"limit must be between 1 and {_MAX_FLAKY_LIMIT}")
+ return query_flaky_tests(
+ curated=curated,
+ date_from=parsed_from,
+ date_to=parsed_to,
+ min_rerun_passes=min_rerun_passes,
+ min_failed_prs=min_failed_prs,
+ limit=limit,
+ )
+
+
def _parse_date(team: Team, value: str) -> datetime:
return relative_date_parse(value, team.timezone_info)
def _parse_window(
- team: Team, date_from: str | None, date_to: str | None, *, default: str
+ team: Team, date_from: str | None, date_to: str | None, *, default: str, max_days: int = _MAX_WINDOW_DAYS
) -> tuple[datetime, datetime | None]:
- """Resolve a caller's date window against the team timezone, capping the span at _MAX_WINDOW_DAYS."""
+ """Resolve a caller's date window against the team timezone, capping the span at max_days."""
parsed_from = _parse_date(team, date_from or default)
parsed_to = _parse_date(team, date_to) if date_to else None
span_days = ((parsed_to or datetime.now(tz=parsed_from.tzinfo)) - parsed_from).days
- if span_days > _MAX_WINDOW_DAYS:
- raise ValueError(f"date window spans {span_days} days; the maximum is {_MAX_WINDOW_DAYS}")
+ if span_days < 0:
+ raise ValueError("date_to must be on or after date_from")
+ if span_days > max_days:
+ raise ValueError(f"date window spans {span_days} days; the maximum is {max_days}")
return parsed_from, parsed_to
diff --git a/products/engineering_analytics/backend/logic/queries/flaky_tests.py b/products/engineering_analytics/backend/logic/queries/flaky_tests.py
new file mode 100644
index 000000000000..7fef39d5d335
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/flaky_tests.py
@@ -0,0 +1,140 @@
+"""HogQL aggregation of per-test CI spans into a flaky-test leaderboard.
+
+Backend CI emits one OTel span per test into the Traces store (span name = reconstructed
+pytest nodeid, ``test.outcome`` / ``test.attempts`` span attributes, ``ci.*`` resource
+attributes — see ``.github/scripts/report_test_timings.py``). This groups the signal spans
+by nodeid over a window and ranks tests by flakiness signal.
+
+Two data caveats shape the query:
+
+- Passing tests under the emitter's duration threshold are dropped, while failures, errors,
+ xfails, and reruns are always emitted — denominators are biased, so everything here is an
+ absolute count, never a rate.
+- ``rerun_passed`` (pass-on-retry, the strongest flaky signal) only flows from lanes running
+ pytest with reruns enabled. Lanes without reruns surface a flake as a plain ``failed`` /
+ ``error`` span, so the cross-PR failure count is the qualifying signal for those.
+
+Ranking is ``rerun_passed_count + failed_pr_count``: reruns catch the rerun-enabled lanes,
+distinct-PRs-hit catches the rest, and neither is inflated by one broken PR failing the same
+test on every push (that raises only ``failed_count``, the tiebreaker).
+
+Reads the ``posthog.trace_spans`` table on the LOGS ClickHouse cluster, not the warehouse.
+"""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from posthog.clickhouse.workload import Workload
+
+from products.engineering_analytics.backend.facade.contracts import FlakyTestItem, FlakyTestList
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+
+# Only test spans carry test.outcome (job-root and setup spans don't), and only these
+# outcomes are flaky signal — plain 'passed'/'skipped' spans never reach the aggregation.
+_SIGNAL_OUTCOMES = ["failed", "error", "rerun_passed", "xfailed"]
+
+# Scope the aggregation to the CI test-timing emitter (report_test_timings.py sets this as
+# service.name); without it any team span carrying a test.outcome attribute would pollute.
+_CI_SERVICE_NAME = "ci-backend"
+
+_SELECT = """
+ SELECT
+ nodeid,
+ anyIf(selector, selector != '') AS selector,
+ countIf(outcome = 'rerun_passed') AS rerun_passed_count,
+ countIf(outcome IN ('failed', 'error')) AS failed_count,
+ uniqIf(pr_number, outcome IN ('failed', 'error') AND pr_number != '') AS failed_pr_count,
+ uniqIf(branch, branch != '') AS branch_count,
+ countIf(outcome = 'xfailed') AS xfailed_count,
+ max(span_timestamp) AS last_seen_at
+ FROM (
+ SELECT
+ name AS nodeid,
+ attributes['test.selector'] AS selector,
+ attributes['test.outcome'] AS outcome,
+ resource_attributes['ci.pr_number'] AS pr_number,
+ resource_attributes['ci.branch'] AS branch,
+ timestamp AS span_timestamp
+ FROM posthog.trace_spans
+ WHERE service_name = {service_name}
+ AND attributes['test.outcome'] IN {signal_outcomes}
+ AND timestamp >= {date_from} __DATE_TO__
+ )
+ GROUP BY nodeid
+ HAVING rerun_passed_count >= {min_rerun_passes} OR failed_pr_count >= {min_failed_prs}
+ ORDER BY (rerun_passed_count + failed_pr_count) DESC, failed_count DESC, last_seen_at DESC
+ LIMIT {limit_plus_one}
+"""
+
+
+def _selector_from_nodeid(nodeid: str) -> str:
+ """Best-effort runnable pytest selector for a span the CI reporter emitted before it stamped
+ ``test.selector``. The nodeid folds the file/class boundary into '/' and drops '.py'
+ ('posthog/api/test/test_x/TestX::test_y'); re-split on the convention that class segments are
+ CamelCase and everything before them is the module file. Newer spans skip this — they carry the
+ exact selector, built from JUnit's ``file`` where the boundary isn't guessed. Removable once every
+ in-retention span carries ``test.selector`` (i.e. the emitter has been live longer than Traces
+ retention).
+ """
+ class_path, sep, test_part = nodeid.partition("::")
+ if not sep or "/" not in class_path:
+ return nodeid
+ segments = class_path.split("/")
+ module_end = len(segments)
+ while module_end > 1 and segments[module_end - 1][:1].isupper():
+ module_end -= 1
+ module = "/".join(segments[:module_end]) + ".py"
+ return "::".join([module, *segments[module_end:], test_part])
+
+
+def query_flaky_tests(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ min_rerun_passes: int,
+ min_failed_prs: int,
+ limit: int,
+) -> FlakyTestList:
+ date_to_clause = "AND timestamp <= {date_to}" if date_to is not None else ""
+ placeholders: dict[str, ast.Expr] = {
+ "service_name": ast.Constant(value=_CI_SERVICE_NAME),
+ "signal_outcomes": ast.Constant(value=_SIGNAL_OUTCOMES),
+ "date_from": ast.Constant(value=date_from),
+ "min_rerun_passes": ast.Constant(value=min_rerun_passes),
+ "min_failed_prs": ast.Constant(value=min_failed_prs),
+ # +1 so a full page tells us more tests qualified than returned.
+ "limit_plus_one": ast.Constant(value=limit + 1),
+ }
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+
+ response = curated.run(
+ _SELECT.replace("__DATE_TO__", date_to_clause),
+ query_type="engineering_analytics.flaky_tests",
+ placeholders=placeholders,
+ # trace_spans lives on the LOGS ClickHouse cluster, not the warehouse default.
+ workload=Workload.LOGS,
+ )
+ rows = response.results or []
+ return FlakyTestList(
+ items=[
+ FlakyTestItem(
+ nodeid=nodeid,
+ # Prefer the emitter's exact selector; reconstruct from the nodeid for older spans.
+ selector=selector or _selector_from_nodeid(nodeid),
+ rerun_passed_count=rerun_passed_count,
+ failed_count=failed_count,
+ failed_pr_count=failed_pr_count,
+ branch_count=branch_count,
+ xfailed_count=xfailed_count,
+ last_seen_at=last_seen_at,
+ )
+ for nodeid, selector, rerun_passed_count, failed_count, failed_pr_count, branch_count, xfailed_count, last_seen_at in rows[
+ :limit
+ ]
+ ],
+ truncated=len(rows) > limit,
+ limit=limit,
+ )
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index cc358f1be1ea..f5aab00183ae 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -17,6 +17,8 @@ from products.engineering_analytics.backend.facade.contracts import (
CIJobFailureLog,
CIStatusRollup,
CostPerMergeBucket,
+ FlakyTestItem,
+ FlakyTestList,
GitHubSource,
MasterFailureGroup,
PRCostSummary,
@@ -363,6 +365,59 @@ class PRCostSummarySerializer(DataclassSerializer):
}
+class FlakyTestItemSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = FlakyTestItem
+ extra_kwargs = {
+ "nodeid": {
+ "help_text": "Reconstructed pytest nodeid (the CI span name), e.g. "
+ "'posthog/api/test/test_event/TestEvents::test_x'. A stable grouping key, not a runnable "
+ "selector — use `selector` to run or quarantine the test.",
+ },
+ "selector": {
+ "help_text": "Runnable pytest selector, e.g. "
+ "'posthog/api/test/test_event.py::TestEvents::test_x'. Exact when the CI reporter emitted it; "
+ "otherwise reconstructed from the nodeid, where the file/class boundary is a best-effort guess.",
+ },
+ "rerun_passed_count": {
+ "help_text": "Times the test failed, then passed on an automatic retry — the strongest flaky "
+ "signal. Only CI lanes running with reruns enabled emit it; a flake in a no-rerun lane "
+ "shows up in failed_count instead.",
+ },
+ "failed_count": {
+ "help_text": "Spans whose final outcome was 'failed' or 'error' in the window. An absolute "
+ "count, not a rate — fast passing runs are not emitted, so denominators are biased.",
+ },
+ "failed_pr_count": {
+ "help_text": "Distinct pull requests among the failed/error spans. Failures on master or "
+ "unattributed branches carry no PR number and are excluded here (still in failed_count).",
+ },
+ "branch_count": {
+ "help_text": "Distinct git branches across all of the test's flaky-signal spans in the window.",
+ },
+ "xfailed_count": {
+ "help_text": "Runs where the test failed while quarantined (xfail) — already masked in CI "
+ "but still flaky.",
+ },
+ "last_seen_at": {"help_text": "Most recent flaky-signal span for this test in the window."},
+ }
+
+
+class FlakyTestListSerializer(DataclassSerializer):
+ items = FlakyTestItemSerializer(
+ many=True, help_text="Qualifying tests ranked by flakiness signal, strongest first, capped at `limit`."
+ )
+
+ class Meta:
+ dataclass = FlakyTestList
+ extra_kwargs = {
+ "truncated": {
+ "help_text": "True when more tests qualified than the cap; `items` is the strongest `limit` rows.",
+ },
+ "limit": {"help_text": "Maximum number of tests returned in `items`."},
+ }
+
+
class CIStatusRollupSerializer(DataclassSerializer):
class Meta:
dataclass = CIStatusRollup
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 0796cb33e161..5c528b473e29 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -23,6 +23,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.facade.contracts import (
+ FLAKY_TEST_SIGNAL_CAVEAT,
GitHubSourceNotConnectedError,
QuarantineRequest,
QuarantineWriteError,
@@ -30,6 +31,7 @@ from products.engineering_analytics.backend.facade.contracts import (
from products.engineering_analytics.backend.presentation.serializers import (
CICardSummarySerializer,
CIFailureLogsSerializer,
+ FlakyTestListSerializer,
GitHubSourceSerializer,
MasterFailureGroupSerializer,
PRCostSummarySerializer,
@@ -143,6 +145,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"workflow_runner_costs",
"author_workflow_costs",
"workflow_jobs",
+ "flaky_tests",
"repo_overview",
"repo_run_activity",
"master_failures",
@@ -752,6 +755,72 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
return _bad_request(exc, fallback="Invalid source_id")
return Response(WorkflowJobSerializer(instance=jobs, many=True).data)
+ @extend_schema(
+ operation_id="engineering_analytics_flaky_tests",
+ parameters=[
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window "
+ "may span at most 30 days.",
+ ),
+ _DATE_TO,
+ OpenApiParameter(
+ name="min_rerun_passes",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test qualifies once it passed on retry at least this many times in the window "
+ "(OR-ed with min_failed_prs). Minimum 1. Defaults to 1.",
+ ),
+ OpenApiParameter(
+ name="min_failed_prs",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test qualifies once it failed on at least this many distinct pull requests in "
+ "the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.",
+ ),
+ OpenApiParameter(
+ name="limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Maximum number of tests to return (1-200). Defaults to 50.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: FlakyTestListSerializer,
+ 400: OpenApiResponse(
+ description="Invalid date, threshold, limit, or source_id, or a window longer than 30 days."
+ ),
+ },
+ description=(
+ "The flaky-test leaderboard: backend tests ranked by flakiness signal from the per-test CI spans, "
+ "over a window (default -7d, maximum 30 days). A test qualifies by passing on retry at least "
+ "min_rerun_passes times OR failing on at least min_failed_prs distinct PRs. " + FLAKY_TEST_SIGNAL_CAVEAT
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def flaky_tests(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_flaky_tests(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ min_rerun_passes=_optional_int_param(request, "min_rerun_passes"),
+ min_failed_prs=_optional_int_param(request, "min_failed_prs"),
+ limit=_optional_int_param(request, "limit"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")
+ return Response(FlakyTestListSerializer(instance=result).data)
+
@extend_schema(
operation_id="engineering_analytics_repo_overview",
parameters=[_DATE_FROM, _DATE_TO, _SOURCE_ID],
diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.py
new file mode 100644
index 000000000000..5f9dfb36551c
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py
@@ -0,0 +1,197 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+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.queries.flaky_tests import _selector_from_nodeid
+from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
+
+T_PRS = "posthog/api/test/test_prs/TestPRs::test_flaky_on_prs"
+T_RERUN = "posthog/api/test/test_rerun/TestRerun::test_pass_on_retry"
+T_RERUN_SELECTOR = "posthog/api/test/test_rerun.py::TestRerun::test_pass_on_retry"
+T_TWO_PRS = "posthog/api/test/test_two/TestTwo::test_two_prs"
+T_XFAIL_ONLY = "posthog/api/test/test_xf/TestXF::test_xfail_only"
+T_OLD = "posthog/api/test/test_old/TestOld::test_old_flake"
+T_FOREIGN = "posthog/api/test/test_foreign/TestForeign::test_other_service"
+
+
+class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):
+ # The aggregation, qualification (HAVING), and ranking all live in the HogQL query, so the
+ # regressions worth catching only surface against real seeded trace_spans rows — same setup
+ # pattern as the tracing product's query tests.
+
+ # ClickhouseTestMixin flips this off (per-test teams); back on so one class-level team can
+ # key the class-level span seed.
+ CLASS_DATA_LEVEL_SETUP = True
+
+ recent: datetime
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ connect_github_source_without_data(cls.team, prefix="flaky")
+ sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
+ sync_execute("DROP TABLE IF EXISTS trace_spans")
+ sync_execute(TRACE_SPANS_TABLE_SQL())
+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+
+ now = datetime.now(UTC).replace(microsecond=0)
+ cls.recent = now - timedelta(days=1)
+ earlier = now - timedelta(days=2)
+ # Inside a -30d window but outside the -7d default.
+ old = now - timedelta(days=10)
+
+ rows = [
+ # Qualifies via distinct PRs (3): 4 failed + 1 error spans, one PR hit twice (dedup),
+ # one master error with no PR (counts as a failure, not a PR), plus one xfail.
+ cls._span(1, T_PRS, "failed", ts=earlier, pr="101", branch="f1"),
+ cls._span(2, T_PRS, "failed", ts=earlier, pr="101", branch="f1"),
+ cls._span(3, T_PRS, "failed", ts=earlier, pr="102", branch="f2"),
+ cls._span(4, T_PRS, "error", ts=earlier, pr="103", branch="f3"),
+ cls._span(5, T_PRS, "error", ts=earlier, branch="master"),
+ cls._span(6, T_PRS, "xfailed", ts=cls.recent, branch="master"),
+ # Qualifies via pass-on-retry; the passing span must not leak into any count. The
+ # emitter stamped test.selector here, so it wins over the nodeid reconstruction.
+ cls._span(7, T_RERUN, "rerun_passed", ts=cls.recent, pr="201", branch="r1", selector=T_RERUN_SELECTOR),
+ cls._span(8, T_RERUN, "rerun_passed", ts=cls.recent, branch="master", selector=T_RERUN_SELECTOR),
+ cls._span(9, T_RERUN, "passed", ts=cls.recent, branch="pass-branch"),
+ # Fails on only 2 distinct PRs — below the default bar, reachable via min_failed_prs=2.
+ cls._span(10, T_TWO_PRS, "failed", ts=cls.recent, pr="301", branch="x1"),
+ cls._span(11, T_TWO_PRS, "failed", ts=cls.recent, pr="302", branch="x2"),
+ cls._span(12, T_TWO_PRS, "failed", ts=cls.recent, pr="302", branch="x2"),
+ # xfail alone is already-quarantined noise, never a qualifier.
+ cls._span(13, T_XFAIL_ONLY, "xfailed", ts=cls.recent, branch="master"),
+ cls._span(14, T_XFAIL_ONLY, "xfailed", ts=cls.recent, branch="master"),
+ # Signal outside the default window.
+ cls._span(15, T_OLD, "rerun_passed", ts=old, pr="401", branch="old1"),
+ # Would qualify on signal alone, but a non-CI service must never reach the leaderboard.
+ cls._span(17, T_FOREIGN, "rerun_passed", ts=cls.recent, pr="501", branch="s1", service="other-service"),
+ # A job-root span carries no test.outcome and must never become a leaderboard row.
+ cls._span(16, "Backend CI / core (1)", None, ts=cls.recent, branch="master"),
+ ]
+ sync_execute(
+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
+ "timestamp, end_time, observed_timestamp, status_code, service_name, attributes_map_str, "
+ "resource_attributes) VALUES " + ",".join(rows)
+ )
+
+ @classmethod
+ def tearDownClass(cls):
+ sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")
+ sync_execute("DROP TABLE IF EXISTS trace_spans")
+ sync_execute(TRACE_SPANS_TABLE_SQL())
+ sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())
+ super().tearDownClass()
+
+ @classmethod
+ def _span(
+ cls,
+ i: int,
+ name: str,
+ outcome: str | None,
+ *,
+ ts: datetime,
+ pr: str = "",
+ branch: str = "",
+ selector: str = "",
+ service: str = "ci-backend",
+ ) -> str:
+ # Physical attributes carry a type suffix ('test.outcome__str'); the `attributes` ALIAS
+ # column strips it. Resource attributes are stored as-is.
+ attr_pairs = ([f"'test.outcome__str', '{outcome}'"] if outcome else []) + (
+ [f"'test.selector__str', '{selector}'"] if selector else []
+ )
+ attrs = f"map({', '.join(attr_pairs)})" if attr_pairs else "map()"
+ resource_pairs = ([f"'ci.pr_number', '{pr}'"] if pr else []) + ([f"'ci.branch', '{branch}'"] if branch else [])
+ resource = f"map({', '.join(resource_pairs)})" if resource_pairs else "map()"
+ stamp = ts.strftime("%Y-%m-%d %H:%M:%S")
+ return (
+ f"('uuid-{i}', {cls.team.id}, 'trace-{i}', 'span-{i}', 'parent', '{name}', 1, "
+ f"'{stamp}', '{stamp}', '{stamp}', 0, '{service}', {attrs}, {resource})"
+ )
+
+ def _get(self, **params: str) -> dict:
+ response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/flaky_tests/", params)
+ assert response.status_code == status.HTTP_200_OK, response.content
+ return response.json()
+
+ def test_default_window_qualifies_aggregates_and_ranks(self):
+ data = self._get()
+
+ # Only the qualifying tests, strongest signal first (T_PRS scores 3 distinct PRs vs
+ # T_RERUN's 2 retries); the 2-PR test, the xfail-only test, the out-of-window test, the
+ # outcome-less job-root span, and the foreign-service row are all excluded.
+ assert [item["nodeid"] for item in data["items"]] == [T_PRS, T_RERUN]
+ assert data["truncated"] is False
+ assert data["limit"] == 50
+
+ by_prs, by_rerun = data["items"]
+ # T_RERUN carried an emitted test.selector; T_PRS didn't, so it falls back to the nodeid
+ # reconstruction (folded '/' → '.py' boundary).
+ assert by_rerun["selector"] == T_RERUN_SELECTOR
+ assert by_prs["selector"] == "posthog/api/test/test_prs.py::TestPRs::test_flaky_on_prs"
+ assert (by_prs["rerun_passed_count"], by_prs["failed_count"], by_prs["failed_pr_count"]) == (0, 5, 3)
+ assert (by_prs["branch_count"], by_prs["xfailed_count"]) == (4, 1)
+ # max() over the signal spans — the xfail at `recent` is newer than the failures.
+ assert by_prs["last_seen_at"].startswith(self.recent.strftime("%Y-%m-%dT%H:%M:%S"))
+ assert (by_rerun["rerun_passed_count"], by_rerun["failed_count"], by_rerun["failed_pr_count"]) == (2, 0, 0)
+ # 2, not 3: the plain 'passed' span (branch 'pass-branch') is outside the signal set.
+ assert (by_rerun["branch_count"], by_rerun["xfailed_count"]) == (2, 0)
+
+ @parameterized.expand(
+ [
+ # Lowering the PR bar pulls in the 2-PR test; ties on score (2) break on failed_count.
+ ("lower_min_failed_prs", {"min_failed_prs": "2"}, [T_PRS, T_TWO_PRS, T_RERUN]),
+ # Raising the rerun bar drops the retry-qualified test; T_PRS still qualifies via PRs.
+ ("raise_min_rerun_passes", {"min_rerun_passes": "3"}, [T_PRS]),
+ ]
+ )
+ def test_thresholds_are_query_params(self, _name: str, params: dict, expected: list[str]):
+ data = self._get(**params)
+ assert [item["nodeid"] for item in data["items"]] == expected
+
+ def test_wider_window_includes_older_signal(self):
+ data = self._get(date_from="-30d")
+ assert T_OLD in [item["nodeid"] for item in data["items"]]
+
+ def test_limit_caps_and_flags_truncation(self):
+ data = self._get(limit="1")
+ assert [item["nodeid"] for item in data["items"]] == [T_PRS]
+ assert data["truncated"] is True
+ assert data["limit"] == 1
+
+ @parameterized.expand(
+ [
+ ("window_over_30_days", {"date_from": "-45d"}),
+ ("reversed_window", {"date_from": "-1d", "date_to": "-5d"}),
+ ("zero_min_rerun_passes", {"min_rerun_passes": "0"}),
+ ("zero_min_failed_prs", {"min_failed_prs": "0"}),
+ ("zero_limit", {"limit": "0"}),
+ ("oversized_limit", {"limit": "201"}),
+ ("non_integer_threshold", {"min_failed_prs": "lots"}),
+ ]
+ )
+ def test_invalid_params_return_400(self, _name: str, params: dict):
+ response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/flaky_tests/", params)
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
+
+# A wrong split yields a selector CI's quarantine matching would silently never hit — the fallback
+# reconstruction for spans emitted before the CI reporter stamped test.selector.
+ "nodeid,expected",
+ [
+ ("posthog/api/test/test_event/TestEvents::test_x", "posthog/api/test/test_event.py::TestEvents::test_x"),
+ ("posthog/tasks/test/test_calc::test_sum", "posthog/tasks/test/test_calc.py::test_sum"),
+ ("posthog/test/test_a/TestOuter/TestInner::test_x", "posthog/test/test_a.py::TestOuter::TestInner::test_x"),
+ ("test_bare", "test_bare"),
+ ],
+)
+def test_selector_from_nodeid(nodeid: str, expected: str) -> None:
+ assert _selector_from_nodeid(nodeid) == expected
diff --git a/products/engineering_analytics/backend/tests/test_mcp.py b/products/engineering_analytics/backend/tests/test_mcp.py
index 001cd472e909..a3f992dc7355 100644
--- a/products/engineering_analytics/backend/tests/test_mcp.py
+++ b/products/engineering_analytics/backend/tests/test_mcp.py
@@ -7,7 +7,9 @@ _DEFINITIONS = Path(__file__).parents[4] / "services/mcp/schema/generated-tool-d
class TestEngineeringAnalyticsMCPTools:
- @pytest.mark.parametrize("tool", ["pull-requests", "workflow-health", "pr-lifecycle"])
+ @pytest.mark.parametrize(
+ "tool", ["pull-requests", "workflow-health", "pr-lifecycle", "engineering-analytics-flaky-tests"]
+ )
def test_tool_is_generated_read_only_and_scoped(self, tool: str) -> None:
definitions = json.loads(_DEFINITIONS.read_text())
diff --git a/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx b/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx
index 62f0697d84cf..488e4b3fbc88 100644
--- a/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx
+++ b/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx
@@ -52,6 +52,8 @@ export function QuarantineTestModal({
const [customReason, setCustomReason] = useState('')
const [owner, setOwner] = useState('')
const [expires, setExpires] = useState<dayjs.Dayjs | null>(dayjs().add(DEFAULT_QUARANTINE_DAYS, 'day'))
+ // 'Edit details' flips a confirm-presentation modal into the full form.
+ const [editing, setEditing] = useState(false)
// Reseed when a new modal opens; keyed on identity so background refreshes don't trample edits.
useEffect(() => {
@@ -66,8 +68,11 @@ export function QuarantineTestModal({
// New quarantines suggest the owning team from a product selector; extend keeps the entry's owner.
setOwner(modal.owner || (modal.action === 'extend' ? '' : inferOwnerFromSelector(modal.selector)))
setExpires(dayjs().add(DEFAULT_QUARANTINE_DAYS, 'day'))
+ setEditing(false)
}, [modal])
+ const isConfirm = !!modal?.confirm && !editing && !isExtend
+
const reason = reasonChoice === OTHER_REASON ? customReason.trim() : reasonChoice
// Backend requires a future expiry within the cap; mirror that so submit can't 400.
const expiresValid = !!expires && expires.isAfter(dayjs(), 'day')
@@ -99,6 +104,22 @@ export function QuarantineTestModal({
})
}
+ // Owner is the one field editable in both presentations (a leaderboard row can't always infer it).
+ const ownerField = (
+ <div>
+ <label className="mb-1 block text-sm font-medium">Owner</label>
+ <LemonInputSelect
+ mode="single"
+ allowCustomValues
+ value={owner ? [owner] : []}
+ onChange={(values) => setOwner(values[0] ?? '')}
+ options={ownerOptions.map((option) => ({ key: option, label: option }))}
+ placeholder="Select the owning team"
+ data-attr="eng-analytics-quarantine-owner"
+ />
+ </div>
+ )
+
return (
<LemonModal
isOpen={!!modal}
@@ -111,6 +132,15 @@ export function QuarantineTestModal({
}
footer={
<>
+ {isConfirm && (
+ <LemonButton
+ type="tertiary"
+ onClick={() => setEditing(true)}
+ data-attr="eng-analytics-quarantine-edit"
+ >
+ Edit details
+ </LemonButton>
+ )}
<LemonButton type="secondary" onClick={onClose} data-attr="eng-analytics-quarantine-cancel">
Cancel
</LemonButton>
@@ -126,74 +156,89 @@ export function QuarantineTestModal({
</>
}
>
- <div className="flex flex-col gap-4">
- <div>
- <label className="mb-1 block text-sm font-medium">Test selector</label>
- {isExtend ? (
- <div className="rounded bg-surface-secondary px-2 py-1.5 font-mono text-xs text-secondary">
+ {isConfirm ? (
+ // Glanceable confirmation for prefilled openers: selector/reason/expiry are review-only.
+ <div className="flex flex-col gap-4">
+ <div>
+ <div className="mb-1 text-sm font-medium">Test selector</div>
+ <div className="rounded bg-surface-secondary px-2 py-1.5 font-mono text-xs break-all">
{selector}
</div>
- ) : (
- <LemonInput
- value={selector}
- onChange={setSelector}
- placeholder="posthog/path/test.py::TestClass::test_method or product:my-product"
- autoFocus
- />
- )}
+ </div>
+ <div>
+ <div className="mb-1 text-sm font-medium">Reason</div>
+ <div className="text-sm text-secondary">{reason}</div>
+ </div>
+ <div>
+ <div className="mb-1 text-sm font-medium">Expires</div>
+ <div className="text-sm">
+ {expires?.format('MMMM D, YYYY')}
+ <span className="ml-1 text-tertiary">
+ (in {DEFAULT_QUARANTINE_DAYS} days — the test gates CI again after this unless extended)
+ </span>
+ </div>
+ </div>
+ {ownerField}
</div>
+ ) : (
+ <div className="flex flex-col gap-4">
+ <div>
+ <label className="mb-1 block text-sm font-medium">Test selector</label>
+ {isExtend ? (
+ <div className="rounded bg-surface-secondary px-2 py-1.5 font-mono text-xs text-secondary">
+ {selector}
+ </div>
+ ) : (
+ <LemonInput
+ value={selector}
+ onChange={setSelector}
+ placeholder="posthog/path/test.py::TestClass::test_method or product:my-product"
+ autoFocus
+ />
+ )}
+ </div>
- <div>
- <label className="mb-1 block text-sm font-medium">Reason</label>
- <LemonSelect
- value={reasonChoice || null}
- onChange={(value) => setReasonChoice(value ?? '')}
- options={[
- ...REASON_OPTIONS.map((option) => ({ value: option, label: option })),
- { value: OTHER_REASON, label: 'Other…' },
- ]}
- placeholder="Select a reason"
- fullWidth
- data-attr="eng-analytics-quarantine-reason"
- />
- {reasonChoice === OTHER_REASON && (
- <LemonInput
- className="mt-2"
- value={customReason}
- onChange={setCustomReason}
- placeholder="Describe the reason"
- autoFocus
+ <div>
+ <label className="mb-1 block text-sm font-medium">Reason</label>
+ <LemonSelect
+ value={reasonChoice || null}
+ onChange={(value) => setReasonChoice(value ?? '')}
+ options={[
+ ...REASON_OPTIONS.map((option) => ({ value: option, label: option })),
+ { value: OTHER_REASON, label: 'Other…' },
+ ]}
+ placeholder="Select a reason"
+ fullWidth
+ data-attr="eng-analytics-quarantine-reason"
/>
- )}
- </div>
+ {reasonChoice === OTHER_REASON && (
+ <LemonInput
+ className="mt-2"
+ value={customReason}
+ onChange={setCustomReason}
+ placeholder="Describe the reason"
+ autoFocus
+ />
+ )}
+ </div>
- <div>
- <label className="mb-1 block text-sm font-medium">Owner</label>
- <LemonInputSelect
- mode="single"
- allowCustomValues
- value={owner ? [owner] : []}
- onChange={(values) => setOwner(values[0] ?? '')}
- options={ownerOptions.map((option) => ({ key: option, label: option }))}
- placeholder="Select a team"
- data-attr="eng-analytics-quarantine-owner"
- />
- </div>
+ {ownerField}
- <div>
- <label className="mb-1 block text-sm font-medium">Expires</label>
- <LemonCalendarSelectInput
- value={expires}
- onChange={setExpires}
- placeholder="Pick an expiry"
- clearable={false}
- selectionPeriod="upcoming"
- />
- <div className="mt-1 text-xs text-tertiary">
- At most {MAX_QUARANTINE_DAYS} days out. After this the test gates CI again unless extended.
+ <div>
+ <label className="mb-1 block text-sm font-medium">Expires</label>
+ <LemonCalendarSelectInput
+ value={expires}
+ onChange={setExpires}
+ placeholder="Pick an expiry"
+ clearable={false}
+ selectionPeriod="upcoming"
+ />
+ <div className="mt-1 text-xs text-tertiary">
+ At most {MAX_QUARANTINE_DAYS} days out. After this the test gates CI again unless extended.
+ </div>
</div>
</div>
- </div>
+ )}
</LemonModal>
)
}
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index f7b111733dc0..452c18aa9722 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -89,6 +89,34 @@ export interface CIFailureLogsApi {
truncated: boolean
}
+export interface FlakyTestItemApi {
+ /** Reconstructed pytest nodeid (the CI span name), e.g. 'posthog/api/test/test_event/TestEvents::test_x'. A stable grouping key, not a runnable selector — use `selector` to run or quarantine the test. */
+ nodeid: string
+ /** Runnable pytest selector, e.g. 'posthog/api/test/test_event.py::TestEvents::test_x'. Exact when the CI reporter emitted it; otherwise reconstructed from the nodeid, where the file/class boundary is a best-effort guess. */
+ selector: string
+ /** Times the test failed, then passed on an automatic retry — the strongest flaky signal. Only CI lanes running with reruns enabled emit it; a flake in a no-rerun lane shows up in failed_count instead. */
+ rerun_passed_count: number
+ /** Spans whose final outcome was 'failed' or 'error' in the window. An absolute count, not a rate — fast passing runs are not emitted, so denominators are biased. */
+ failed_count: number
+ /** Distinct pull requests among the failed/error spans. Failures on master or unattributed branches carry no PR number and are excluded here (still in failed_count). */
+ failed_pr_count: number
+ /** Distinct git branches across all of the test's flaky-signal spans in the window. */
+ branch_count: number
+ /** Runs where the test failed while quarantined (xfail) — already masked in CI but still flaky. */
+ xfailed_count: number
+ /** Most recent flaky-signal span for this test in the window. */
+ last_seen_at: string
+}
+
+export interface FlakyTestListApi {
+ /** Qualifying tests ranked by flakiness signal, strongest first, capped at `limit`. */
+ items: FlakyTestItemApi[]
+ /** True when more tests qualified than the cap; `items` is the strongest `limit` rows. */
+ truncated: boolean
+ /** Maximum number of tests returned in `items`. */
+ limit: number
+}
+
export interface WorkflowJobAggregateApi {
/** De-sharded job name: the matrix '(G/N)' suffix is stripped and unexpanded '${{ matrix.* }}' templates are collapsed, so shards of one matrix aggregate together. */
job_name: string
@@ -870,6 +898,33 @@ export type EngineeringAnalyticsCiFailureLogsParams = {
source_id?: string
}
+export type EngineeringAnalyticsFlakyTestsParams = {
+ /**
+ * Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * Maximum number of tests to return (1-200). Defaults to 50.
+ */
+ limit?: number
+ /**
+ * A test qualifies once it failed on at least this many distinct pull requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.
+ */
+ min_failed_prs?: number
+ /**
+ * A test qualifies once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.
+ */
+ min_rerun_passes?: number
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+}
+
export type EngineeringAnalyticsJobAggregatesParams = {
/**
* Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 59219318b067..65d8b97f5cdf 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -14,6 +14,7 @@ import type {
EngineeringAnalyticsAuthorWorkflowCostsParams,
EngineeringAnalyticsCiCardsParams,
EngineeringAnalyticsCiFailureLogsParams,
+ EngineeringAnalyticsFlakyTestsParams,
EngineeringAnalyticsJobAggregatesParams,
EngineeringAnalyticsMasterFailuresParams,
EngineeringAnalyticsPrCostParams,
@@ -30,6 +31,7 @@ import type {
EngineeringAnalyticsWorkflowRunParams,
EngineeringAnalyticsWorkflowRunnerCostsParams,
EngineeringAnalyticsWorkflowRunsParams,
+ FlakyTestListApi,
GitHubSourceApi,
MasterFailureGroupApi,
PRCostSummaryApi,
@@ -145,6 +147,39 @@ export const engineeringAnalyticsCiFailureLogs = async (
})
}
+export const getEngineeringAnalyticsFlakyTestsUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsFlakyTestsParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/flaky_tests/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/flaky_tests/`
+}
+
+/**
+ * The flaky-test leaderboard: backend tests ranked by flakiness signal from the per-test CI spans, over a window (default -7d, maximum 30 days). A test qualifies by passing on retry at least min_rerun_passes times OR failing on at least min_failed_prs distinct PRs. All figures are absolute counts, never rates: fast passing runs are not emitted, so denominators are biased. Pass-on-retry counts only flow from CI lanes running with reruns enabled; in other lanes a flake surfaces as a plain failure, which the distinct-PR count catches.
+ */
+export const engineeringAnalyticsFlakyTests = async (
+ projectId: string,
+ params?: EngineeringAnalyticsFlakyTestsParams,
+ options?: RequestInit
+): Promise<FlakyTestListApi> => {
+ return apiMutator<FlakyTestListApi>(getEngineeringAnalyticsFlakyTestsUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsJobAggregatesUrl = (
projectId: string,
params: EngineeringAnalyticsJobAggregatesParams
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx
new file mode 100644
index 000000000000..a8688f373803
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx
@@ -0,0 +1,126 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import type { FlakyTestListApi, GitHubSourceApi, QuarantineFileApi } from '../generated/api.schemas'
+
+const FLAKY_TESTS: FlakyTestListApi = {
+ items: [
+ {
+ nodeid: 'posthog/api/test/test_decide/TestDecide::test_flag_rollout_consistency',
+ selector: 'posthog/api/test/test_decide.py::TestDecide::test_flag_rollout_consistency',
+ rerun_passed_count: 6,
+ failed_count: 4,
+ failed_pr_count: 3,
+ branch_count: 5,
+ xfailed_count: 0,
+ last_seen_at: '2026-07-01T18:30:00Z',
+ },
+ {
+ nodeid: 'posthog/tasks/test/test_usage_report/TestUsageReport::test_full_report',
+ selector: 'posthog/tasks/test/test_usage_report.py::TestUsageReport::test_full_report',
+ rerun_passed_count: 0,
+ failed_count: 9,
+ failed_pr_count: 4,
+ branch_count: 4,
+ xfailed_count: 0,
+ last_seen_at: '2026-07-01T09:12:00Z',
+ },
+ {
+ nodeid: 'posthog/hogql/test/test_resolver/TestResolver::test_asterisk_expander',
+ selector: 'posthog/hogql/test/test_resolver.py::TestResolver::test_asterisk_expander',
+ rerun_passed_count: 2,
+ failed_count: 1,
+ failed_pr_count: 1,
+ branch_count: 3,
+ xfailed_count: 3,
+ last_seen_at: '2026-06-30T22:45:00Z',
+ },
+ {
+ nodeid: 'posthog/temporal/tests/batch_exports/test_backfill::test_workflow_timeout',
+ selector: 'posthog/temporal/tests/batch_exports/test_backfill.py::test_workflow_timeout',
+ rerun_passed_count: 1,
+ failed_count: 2,
+ failed_pr_count: 2,
+ branch_count: 2,
+ xfailed_count: 0,
+ last_seen_at: '2026-06-29T14:00:00Z',
+ },
+ ],
+ truncated: false,
+ limit: 50,
+}
+
+const QUARANTINE: QuarantineFileApi = {
+ available: true,
+ entries: [
+ {
+ id: 'posthog/hogql/test/test_resolver.py::TestResolver::test_asterisk_expander',
+ runner: 'pytest',
+ reason: 'Nondeterministic ordering or data',
+ owner: '@PostHog/team-hogql',
+ issue: 'https://github.com/PostHog/posthog/issues/1',
+ added: '2026-06-24',
+ expires: '2026-07-08',
+ mode: 'run',
+ lifecycle: 'active',
+ days_until_expiry: 6,
+ selector_kind: 'test',
+ },
+ ],
+ parse_errors: [],
+ parse_warnings: [],
+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
+ source_url: 'https://github.com/PostHog/posthog/blob/HEAD/.test_quarantine.json',
+ generated_at: '2026-07-02T12:00:00Z',
+}
+
+const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Engineering Analytics/Test Health',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-07-02',
+ featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],
+ testOptions: {
+ // A per-row quarantine button only renders once the leaderboard has data rows.
+ waitForSelector: '[data-attr="eng-analytics-flaky-quarantine"]',
+ },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ 'api/projects/:team_id/engineering_analytics/flaky_tests/': FLAKY_TESTS,
+ 'api/projects/:team_id/engineering_analytics/quarantine/': QUARANTINE,
+ 'api/projects/:team_id/engineering_analytics/sources/': SOURCES,
+ 'api/projects/:team_id/engineering_analytics/ci_cards/': {
+ open_prs: 18,
+ repos: 1,
+ stuck: 3,
+ failing_ci: 4,
+ },
+ 'api/projects/:team_id/engineering_analytics/pull_requests/': {
+ items: [],
+ truncated: false,
+ limit: 1000,
+ },
+ 'api/projects/:team_id/engineering_analytics/workflow_health/': [],
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const FlakyTestLeaderboard: Story = {
+ render: () => <App />,
+ parameters: { pageUrl: urls.engineeringAnalyticsTestHealth() },
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
index 59f549dd69a9..30db695f05e3 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
@@ -17,6 +17,7 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
+import { dayjs } from 'lib/dayjs'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { pluralize } from 'lib/utils/strings'
@@ -26,11 +27,14 @@ import { QuarantineTestModal } from '../components/QuarantineTestModal'
import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'
import { StatCard } from '../components/StatCard'
import {
+ FlakyTestRow,
+ FlakyTestWindow,
QuarantineEntryRow,
QuarantineLifecycle,
QuarantineLifecycleFilter,
QuarantineModeFilter,
engineeringAnalyticsLogic,
+ flakyEvidenceReason,
} from './engineeringAnalyticsLogic'
function relativeExpiry(daysUntilExpiry: number): string {
@@ -76,11 +80,193 @@ function ModeTag({ mode }: { mode: QuarantineEntryRow['mode'] }): JSX.Element {
)
}
+function FlakyTestLeaderboard(): JSX.Element {
+ const { flakyTests, flakyTestsLoading, flakyTestsStatus, flakyTestWindow } = useValues(engineeringAnalyticsLogic)
+ const { setFlakyTestWindow, openQuarantineModal } = useActions(engineeringAnalyticsLogic)
+
+ const columns: LemonTableColumns<FlakyTestRow> = [
+ {
+ title: 'Test',
+ key: 'nodeid',
+ render: (_, row) => (
+ <div className="flex max-w-[32rem] flex-col gap-0.5">
+ <Tooltip title={row.nodeid}>
+ <span className="truncate font-mono text-xs">{row.nodeid}</span>
+ </Tooltip>
+ {row.xfailedCount > 0 && (
+ <div>
+ <Tooltip
+ title={`Failed ${pluralize(row.xfailedCount, 'time')} while quarantined (runs as xfail) — already masked in CI, still flaky.`}
+ >
+ <LemonTag type="warning" size="small">
+ Quarantined, still failing
+ </LemonTag>
+ </Tooltip>
+ </div>
+ )}
+ </div>
+ ),
+ },
+ {
+ title: 'Pass on retry',
+ key: 'rerunPassedCount',
+ width: 120,
+ align: 'right',
+ tooltip:
+ 'Failed, then passed on an automatic retry — the strongest flaky signal. Only CI lanes running with retries emit it.',
+ sorter: (a, b) => a.rerunPassedCount - b.rerunPassedCount,
+ render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.rerunPassedCount)}</span>,
+ },
+ {
+ title: 'Failures',
+ key: 'failedCount',
+ width: 100,
+ align: 'right',
+ tooltip:
+ 'Runs whose final outcome was failed or error. An absolute count, not a rate — passing runs are mostly not recorded.',
+ sorter: (a, b) => a.failedCount - b.failedCount,
+ render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.failedCount)}</span>,
+ },
+ {
+ title: 'PRs hit',
+ key: 'failedPrCount',
+ width: 100,
+ align: 'right',
+ tooltip:
+ 'Distinct pull requests the failures landed on. Failures on master carry no PR and are not counted here.',
+ sorter: (a, b) => a.failedPrCount - b.failedPrCount,
+ render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.failedPrCount)}</span>,
+ },
+ {
+ title: 'Branches',
+ key: 'branchCount',
+ width: 100,
+ align: 'right',
+ tooltip: 'Distinct git branches across the test’s flaky-signal runs in the window.',
+ sorter: (a, b) => a.branchCount - b.branchCount,
+ render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.branchCount)}</span>,
+ },
+ {
+ title: 'Last seen',
+ key: 'lastSeenAt',
+ width: 120,
+ align: 'right',
+ sorter: (a, b) => a.lastSeenAt.localeCompare(b.lastSeenAt),
+ render: (_, row) => (
+ <Tooltip title={dayjs(row.lastSeenAt).format('YYYY-MM-DD HH:mm:ss')}>
+ <span className="text-xs whitespace-nowrap text-secondary">{dayjs(row.lastSeenAt).fromNow()}</span>
+ </Tooltip>
+ ),
+ },
+ {
+ title: '',
+ key: 'actions',
+ width: 120,
+ render: (_, row) => (
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={() =>
+ openQuarantineModal({
+ action: 'quarantine',
+ selector: row.selector,
+ // The evidence is the reason; the cause is the tracking issue's job to find.
+ reason: flakyEvidenceReason(row, flakyTestWindow),
+ owner: '',
+ issue: '',
+ mode: 'run',
+ confirm: true,
+ })
+ }
+ data-attr="eng-analytics-flaky-quarantine"
+ >
+ Quarantine…
+ </LemonButton>
+ ),
+ },
+ ]
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex flex-col gap-0.5">
+ <h3 className="m-0 text-base font-semibold">Flaky test leaderboard</h3>
+ <p className="m-0 text-xs text-tertiary">
+ Backend tests that passed on retry or failed across several PRs — quarantine candidates, ranked
+ by flakiness signal.
+ </p>
+ </div>
+ <LemonSegmentedButton
+ size="small"
+ value={flakyTestWindow}
+ onChange={(value) => setFlakyTestWindow(value as FlakyTestWindow)}
+ options={[
+ { value: '-7d', label: '7d' },
+ { value: '-14d', label: '14d' },
+ { value: '-30d', label: '30d' },
+ ]}
+ />
+ </div>
+ {flakyTestsStatus === 'error' ? (
+ <LemonBanner type="warning">Couldn't load flaky test data. Try refreshing.</LemonBanner>
+ ) : (
+ <>
+ <LemonTable
+ data-attr="engineering-analytics-flaky-tests-table"
+ size="small"
+ columns={columns}
+ dataSource={flakyTests?.rows ?? []}
+ rowKey={(row) => row.nodeid}
+ loading={flakyTestsLoading}
+ pagination={{ pageSize: 50 }}
+ useURLForSorting={false}
+ emptyState="No flaky tests detected in this window."
+ nouns={['flaky test', 'flaky tests']}
+ />
+ {flakyTests?.truncated && (
+ <div className="text-xs text-tertiary">
+ Showing the {flakyTests.limit} strongest signals — more tests qualified in this window.
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ )
+}
+
export function EngineeringAnalyticsTestHealth(): JSX.Element {
+ const { quarantineLoadFailed, quarantineModal, quarantineOwnerOptions, quarantineSubmitLoading } =
+ useValues(engineeringAnalyticsLogic)
+ const { closeQuarantineModal, submitQuarantine } = useActions(engineeringAnalyticsLogic)
+
+ // Production with no GitHub source and no local checkout: the endpoint 400s, same as the other tabs.
+ if (quarantineLoadFailed) {
+ return <ConnectGitHubSource />
+ }
+
+ return (
+ <div className="flex flex-col gap-8">
+ {/* Tab-level: both sections read the same source, so the picker scopes them together. */}
+ <ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />
+ <FlakyTestLeaderboard />
+ <QuarantineRegister />
+ {/* Rendered once for the whole tab: the leaderboard rows, the register rows, and the
+ register's no-file empty state all open it. */}
+ <QuarantineTestModal
+ modal={quarantineModal}
+ ownerOptions={quarantineOwnerOptions}
+ submitting={quarantineSubmitLoading}
+ onClose={closeQuarantineModal}
+ onSubmit={(input) => submitQuarantine({ input })}
+ />
+ </div>
+ )
+}
+
+function QuarantineRegister(): JSX.Element {
const {
quarantine,
quarantineLoading,
- quarantineLoadFailed,
filteredQuarantineEntries,
quarantineCounts,
quarantineOwnerOptions,
@@ -90,8 +276,6 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
quarantineOwner,
activeQuarantineCard,
hasActiveQuarantineFilters,
- quarantineModal,
- quarantineSubmitLoading,
} = useValues(engineeringAnalyticsLogic)
const {
setQuarantineSearch,
@@ -101,7 +285,6 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
applyQuarantineCard,
resetQuarantineFilters,
openQuarantineModal,
- closeQuarantineModal,
submitQuarantine,
} = useActions(engineeringAnalyticsLogic)
@@ -142,52 +325,29 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
})
}
- // Rendered alongside every branch that can open it, so the modal survives the no-file empty state.
- const modalElement = (
- <QuarantineTestModal
- modal={quarantineModal}
- ownerOptions={quarantineOwnerOptions}
- submitting={quarantineSubmitLoading}
- onClose={closeQuarantineModal}
- onSubmit={(input) => submitQuarantine({ input })}
- />
- )
-
- // Rendered on every data-bearing branch: the quarantine file is per-repo, so multi-source teams
- // need the source picker here too — including on the wrong-repo empty states.
- const scopeBar = <ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />
-
- // Production with no GitHub source and no local checkout: the endpoint 400s, same as the other tabs.
- if (quarantineLoadFailed) {
- return <ConnectGitHubSource />
- }
-
// A fetch failure (timeout, 5xx, unsafe repo) also comes back as available:false, but with
// parse_errors set — surface those instead of the "no file" explainer, which only fits a true 404.
if (quarantine && !quarantine.available && quarantine.parseErrors.length > 0) {
return (
- <div className="flex flex-col gap-4">
- {scopeBar}
- <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
- <IconShieldLock className="size-8 text-tertiary" />
- <div className="text-lg font-semibold">Couldn't read the quarantine file</div>
- <div className="w-full max-w-xl">
- <LemonBanner type="warning">
- <ul className="ml-4 list-disc text-left">
- {quarantine.parseErrors.map((error, index) => (
- <li key={index} className="font-mono text-xs">
- {error}
- </li>
- ))}
- </ul>
- </LemonBanner>
- </div>
- {quarantine.repoFullName && (
- <p className="text-sm text-secondary">
- Repository: <span className="font-mono">{quarantine.repoFullName}</span>
- </p>
- )}
+ <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
+ <IconShieldLock className="size-8 text-tertiary" />
+ <div className="text-lg font-semibold">Couldn't read the quarantine file</div>
+ <div className="w-full max-w-xl">
+ <LemonBanner type="warning">
+ <ul className="ml-4 list-disc text-left">
+ {quarantine.parseErrors.map((error, index) => (
+ <li key={index} className="font-mono text-xs">
+ {error}
+ </li>
+ ))}
+ </ul>
+ </LemonBanner>
</div>
+ {quarantine.repoFullName && (
+ <p className="text-sm text-secondary">
+ Repository: <span className="font-mono">{quarantine.repoFullName}</span>
+ </p>
+ )}
</div>
)
}
@@ -195,23 +355,19 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
// A file that does not exist is a normal state, not an error — offer to start one.
if (quarantine && !quarantine.available) {
return (
- <div className="flex flex-col gap-4">
- {scopeBar}
- <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
- <IconShieldLock className="size-8 text-tertiary" />
- <div className="text-lg font-semibold">No test quarantine yet</div>
- <p className="max-w-xl text-sm text-secondary">
- {quarantine.repoFullName
- ? `${quarantine.repoFullName} has no .test_quarantine.json. `
- : 'This repo has no .test_quarantine.json. '}
- Quarantine masks a flaky test in CI with a hard expiry, so it stops blocking merges while its
- owner fixes it. The first quarantine opens a PR that creates the file.
- </p>
- <LemonButton type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">
- Quarantine a test
- </LemonButton>
- {modalElement}
- </div>
+ <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">
+ <IconShieldLock className="size-8 text-tertiary" />
+ <div className="text-lg font-semibold">No test quarantine yet</div>
+ <p className="max-w-xl text-sm text-secondary">
+ {quarantine.repoFullName
+ ? `${quarantine.repoFullName} has no .test_quarantine.json. `
+ : 'This repo has no .test_quarantine.json. '}
+ Quarantine masks a flaky test in CI with a hard expiry, so it stops blocking merges while its owner
+ fixes it. The first quarantine opens a PR that creates the file.
+ </p>
+ <LemonButton type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">
+ Quarantine a test
+ </LemonButton>
</div>
)
}
@@ -331,7 +487,6 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
return (
<div className="flex flex-col gap-4">
- {scopeBar}
<div className="flex items-start justify-between gap-2">
<div className="flex flex-col gap-0.5">
<h3 className="m-0 text-base font-semibold">Quarantine register</h3>
@@ -487,7 +642,6 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {
Quarantining, extending, or removing opens a pull request, so the file stays the source of truth. A
merged edit only affects CI runs that start after it lands.
</div>
- {modalElement}
</div>
)
}
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index f0ee2732bffd..0256ad74d735 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -7,10 +7,12 @@ import { lemonToast } from '@posthog/lemon-ui'
import { ApiConfig, ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { objectsEqual } from 'lib/utils/objects'
+import { pluralize } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import {
engineeringAnalyticsCiCards,
+ engineeringAnalyticsFlakyTests,
engineeringAnalyticsPullRequests,
engineeringAnalyticsQuarantine,
engineeringAnalyticsQuarantineRequest,
@@ -398,6 +400,35 @@ export function quarantineCountsOf(rows: QuarantineEntryRow[]): QuarantineCounts
return { ...counts, pastExpiry: counts.inGrace + counts.overdue }
}
+/** Leaderboard windows the UI offers; the endpoint accepts any window up to 30 days. */
+export type FlakyTestWindow = '-7d' | '-14d' | '-30d'
+export const DEFAULT_FLAKY_TEST_WINDOW: FlakyTestWindow = '-7d'
+
+export interface FlakyTestRow {
+ /** Reconstructed pytest nodeid (the CI span name) — a stable grouping/display key. */
+ nodeid: string
+ /** Runnable pytest selector for the quarantine action; exact when the CI reporter emitted it. */
+ selector: string
+ /** Failed, then passed on an automatic retry — the strongest flaky signal (rerun-enabled lanes only). */
+ rerunPassedCount: number
+ /** Spans whose final outcome was failed/error. Absolute count, never a rate (denominators are biased). */
+ failedCount: number
+ /** Distinct PRs among the failures; master/branch failures carry no PR and don't count here. */
+ failedPrCount: number
+ /** Distinct branches across the test's flaky-signal spans. */
+ branchCount: number
+ /** Failed while quarantined (xfail) — already masked in CI, still flaky. */
+ xfailedCount: number
+ lastSeenAt: string
+}
+
+export interface FlakyTestsData {
+ rows: FlakyTestRow[]
+ /** True when more tests qualified than the cap; rows are the strongest `limit`. */
+ truncated: boolean
+ limit: number
+}
+
export type QuarantineRequestAction = 'quarantine' | 'extend' | 'remove'
/** What the tab submits to the write endpoint; the backend opens the issue + PR. */
@@ -421,6 +452,29 @@ export interface QuarantineModalState {
owner: string
issue: string
mode: QuarantineMode
+ /** Glanceable confirm presentation for prefilled openers (leaderboard rows); 'Edit details' switches to the form. */
+ confirm?: boolean
+}
+
+/** Data-backed quarantine reason from a leaderboard row — the evidence is the reason; the
+ * cause is unknown until someone investigates, which is the tracking issue's job. */
+export function flakyEvidenceReason(row: FlakyTestRow, window: FlakyTestWindow): string {
+ const windowLabel = { '-7d': '7 days', '-14d': '14 days', '-30d': '30 days' }[window]
+ const parts: string[] = []
+ if (row.rerunPassedCount > 0) {
+ parts.push(`passed on retry ${row.rerunPassedCount}x`)
+ }
+ if (row.failedCount > 0) {
+ parts.push(
+ row.failedPrCount > 0
+ ? `failed ${row.failedCount}x across ${pluralize(row.failedPrCount, 'PR')}`
+ : `failed ${row.failedCount}x`
+ )
+ }
+ if (row.xfailedCount > 0) {
+ parts.push(`failed while quarantined ${row.xfailedCount}x`)
+ }
+ return `Flaky in CI: ${parts.join(', ')} in the last ${windowLabel}`
}
/** Suggest an owning team from a product-scoped selector; '' when the selector isn't product-scoped. */
@@ -492,6 +546,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
resetQuarantineFilters: true,
openQuarantineModal: (state: QuarantineModalState) => ({ state }),
closeQuarantineModal: true,
+ setFlakyTestWindow: (window: FlakyTestWindow) => ({ window }),
refresh: true,
}),
@@ -595,6 +650,33 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
},
],
+ flakyTests: [
+ null as FlakyTestsData | null,
+ {
+ loadFlakyTests: async (): Promise<FlakyTestsData> => {
+ const data = await engineeringAnalyticsFlakyTests(projectId(), {
+ date_from: values.flakyTestWindow,
+ source_id: values.sourceId ?? undefined,
+ })
+ return {
+ rows: data.items.map(
+ (it): FlakyTestRow => ({
+ nodeid: it.nodeid,
+ selector: it.selector,
+ rerunPassedCount: it.rerun_passed_count,
+ failedCount: it.failed_count,
+ failedPrCount: it.failed_pr_count,
+ branchCount: it.branch_count,
+ xfailedCount: it.xfailed_count,
+ lastSeenAt: it.last_seen_at,
+ })
+ ),
+ truncated: data.truncated,
+ limit: data.limit,
+ }
+ },
+ },
+ ],
quarantineSubmit: [
null as QuarantineRequestResultApi | null,
{
@@ -707,6 +789,21 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadQuarantineFailure: () => true,
},
],
+ // Leaderboard window; transient like the other lenses (no persisted UI in this phase).
+ flakyTestWindow: [
+ DEFAULT_FLAKY_TEST_WINDOW as FlakyTestWindow,
+ { setFlakyTestWindow: (_, { window }) => window },
+ ],
+ // Same tri-state as the other loaders: 'notConnected' (no source) defers to the tab-level
+ // "connect a source" gate; only a real 'error' surfaces the leaderboard's own banner.
+ flakyTestsStatus: [
+ 'ok' as LoaderStatus,
+ {
+ loadFlakyTests: () => 'ok',
+ loadFlakyTestsSuccess: () => 'ok',
+ loadFlakyTestsFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),
+ },
+ ],
quarantineModal: [
null as QuarantineModalState | null,
{
@@ -891,7 +988,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
actions.loadPullRequests()
actions.loadWorkflowHealth()
actions.loadQuarantine()
+ actions.loadFlakyTests()
},
+ setFlakyTestWindow: () => actions.loadFlakyTests(),
setSourceId: () => actions.refresh(),
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadWorkflowHealth()
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 8d7e6d83f7d7..085e50f2a398 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -34,6 +34,27 @@ tools:
pushes' failures are included too. logs_available is false when CI hasn't failed, the logs aged out of the
short Logs retention, or a fork PR has no run association to resolve. Use pr-runs or workflow-jobs for the
run/job metadata behind these logs.
+ engineering-analytics-flaky-tests:
+ operation: engineering_analytics_flaky_tests
+ enabled: true
+ scopes:
+ - engineering_analytics:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: Flaky test leaderboard
+ description: >
+ Backend tests ranked by flakiness signal over a window (date_from default -7d, maximum 30 days), from the
+ per-test CI spans. A test qualifies by passing on an automatic retry at least min_rerun_passes times
+ (default 1) OR failing on at least min_failed_prs distinct pull requests (default 3). Use this for "which
+ tests are flaky right now" and to pick quarantine candidates. Read the counts as absolute signal, never
+ rates — fast passing runs are not emitted, so there is no honest denominator. rerun_passed_count only flows
+ from CI lanes running with retries enabled; in other lanes a flake surfaces as a plain failure, which
+ failed_pr_count catches. xfailed_count > 0 means the test is already quarantined but still failing. nodeid
+ is a best-effort reconstruction (no '.py' suffix, the file/class boundary folded into '/'), so convert
+ before using it as a pytest selector.
engineering-analytics-job-aggregates:
operation: engineering_analytics_job_aggregates
enabled: false
diff --git a/products/engineering_analytics/package.json b/products/engineering_analytics/package.json
index 28537069ba01..f5f22bb52f1d 100644
--- a/products/engineering_analytics/package.json
+++ b/products/engineering_analytics/package.json
@@ -15,6 +15,7 @@
},
"peerDependencies": {
"@posthog/icons": "catalog:",
+ "@storybook/react": "catalog:",
"@types/react": "*",
"react": "*"
}
diff --git a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md
index dcd941d429ea..f73fcd6f5fd1 100644
--- a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md
+++ b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md
@@ -13,8 +13,8 @@ description: >
# Diagnosing CI and merge bottlenecks
Engineering analytics treats a pull request like product analytics treats a user: a PR moves through a pipeline
-(`opened → CI → review → merged → deployed`) and the job is to find where it slows down. The surface is **three
-named MCP tools** — you call them, you don't write SQL. Dogfooded on `PostHog/posthog`; the same tools serve
+(`opened → CI → review → merged → deployed`) and the job is to find where it slows down. The surface is **named
+MCP tools** — you call them, you don't write SQL. Dogfooded on `PostHog/posthog`; the same tools serve
autonomous agents (e.g. PostHog Code) reasoning about their own PRs.
## The tools
@@ -35,6 +35,13 @@ autonomous agents (e.g. PostHog Code) reasoning about their own PRs.
- **`pr-lifecycle`** — a single PR's timeline: a header plus ordered events — opened, then a CI started/finished
pair **per workflow run** (many on a multi-workflow repo, interleaved by time), then merged/closed. Answers
"where is PR N stuck". `metric_quality` is `partial`.
+- **`engineering-analytics-flaky-tests`** — per-test flakiness leaderboard from the per-test CI spans, over a
+ window (`date_from` default `-7d`, max 30 days). A test qualifies by passing on an automatic retry
+ (`rerun_passed_count`, the strongest signal — only rerun-enabled CI lanes emit it) or failing on ≥
+ `min_failed_prs` distinct PRs (`failed_pr_count`, the signal for no-rerun lanes). Answers "which tests are
+ flaky right now" and picks quarantine candidates; `xfailed_count > 0` means already quarantined but still
+ failing. Counts are absolute signal, never rates — passing runs are mostly not emitted, so there is no honest
+ denominator.
There is no aggregate time-to-merge tool and no "counts" tool — derive those from `pull-requests` (the stuck/failing
counts, the merge-time percentiles).
@@ -62,13 +69,14 @@ These are structural limits of today's snapshot data — state them, don't paper
## Choosing a tool
-| The question | Tool | How |
-| ------------------------------------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Is CI getting slower? Which workflow is the long pole? | `workflow-health` | Call over two adjacent windows (e.g. `date_from=-14d`, then `date_from=-28d` `date_to=-14d`); compare `p50_seconds` and `p95_seconds` per workflow. Lead with the median but always check p95 separately — they move independently. |
-| Which open PRs have failing or pending CI? | `pull-requests` | Keep rows where `ci.failing > 0` or `ci.pending > 0`. `pending` means unsettled (or stale) — not a settled failure. |
-| Which PRs are stuck open longest? | `pull-requests` | Keep `state = open`, not `is_draft`, not `author.is_bot`; sort by `created_at` ascending (oldest first). |
-| How long are PRs taking to merge? Per author? | `pull-requests` | Over merged rows (`merged_at` set, not bot, not draft), aggregate `open_to_merge_seconds` — median and p95. Group by `author.handle` for **cohort context, not a ranking** (per-developer surveillance is an explicit non-goal). Trend it by calling with two `date_from` windows. |
-| Where is PR N stuck? | `pr-lifecycle` | Walk the sorted events: `opened → first CI started`, the CI span (first start → last finish; one pair per workflow), `last CI finished → merged`. The largest gap is the bottleneck. A long open→merge with quick CI points at review/idle time the `partial` data can't itemize yet — say so. |
+| The question | Tool | How |
+| ------------------------------------------------------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Is CI getting slower? Which workflow is the long pole? | `workflow-health` | Call over two adjacent windows (e.g. `date_from=-14d`, then `date_from=-28d` `date_to=-14d`); compare `p50_seconds` and `p95_seconds` per workflow. Lead with the median but always check p95 separately — they move independently. |
+| Which open PRs have failing or pending CI? | `pull-requests` | Keep rows where `ci.failing > 0` or `ci.pending > 0`. `pending` means unsettled (or stale) — not a settled failure. |
+| Which PRs are stuck open longest? | `pull-requests` | Keep `state = open`, not `is_draft`, not `author.is_bot`; sort by `created_at` ascending (oldest first). |
+| How long are PRs taking to merge? Per author? | `pull-requests` | Over merged rows (`merged_at` set, not bot, not draft), aggregate `open_to_merge_seconds` — median and p95. Group by `author.handle` for **cohort context, not a ranking** (per-developer surveillance is an explicit non-goal). Trend it by calling with two `date_from` windows. |
+| Where is PR N stuck? | `pr-lifecycle` | Walk the sorted events: `opened → first CI started`, the CI span (first start → last finish; one pair per workflow), `last CI finished → merged`. The largest gap is the bottleneck. A long open→merge with quick CI points at review/idle time the `partial` data can't itemize yet — say so. |
+| Which tests are flaky? What should be quarantined? | `engineering-analytics-flaky-tests` | Default window is `-7d`; rows are already ranked by `rerun_passed_count` + `failed_pr_count`. Report counts, never rates. A no-rerun lane surfaces flakes as plain failures — that's what `failed_pr_count` catches. |
## The high-value chain
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a54969f8ea37..491795ca2e6a 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2512,6 +2512,20 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-flaky-tests": {
+ "description": "Backend tests ranked by flakiness signal over a window (date_from default -7d, maximum 30 days), from the per-test CI spans. A test qualifies by passing on an automatic retry at least min_rerun_passes times (default 1) OR failing on at least min_failed_prs distinct pull requests (default 3). Use this for \"which tests are flaky right now\" and to pick quarantine candidates. Read the counts as absolute signal, never rates — fast passing runs are not emitted, so there is no honest denominator. rerun_passed_count only flows from CI lanes running with retries enabled; in other lanes a flake surfaces as a plain failure, which failed_pr_count catches. xfailed_count > 0 means the test is already quarantined but still failing. nodeid is a best-effort reconstruction (no '.py' suffix, the file/class boundary folded into '/'), so convert before using it as a pytest selector.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Flaky test leaderboard",
+ "title": "Flaky test leaderboard",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"engineering-analytics-pr-cost": {
"description": "Estimated CI dollar cost of one pull request, summed over the jobs of all its workflow runs, with breakdowns per workflow (by_workflow) and per run (by_run). Reach for this instead of summing runner minutes by hand: the estimate already classifies runners (billable self-hosted Linux vs free GitHub-hosted), applies the per-vCPU price ladder, and excludes non-Linux and provider-hosted jobs. jobs_available is false when the job-level source isn't synced yet — every figure is then zero/null, so check it before trusting a $0.00. estimated_cost_usd is null (not zero) when nothing was costable, and unsettled_jobs counts billable jobs still running that are left out of the estimate.",
"category": "Engineering analytics",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 90407797b809..360a175f05e4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2556,6 +2556,20 @@
"readOnlyHint": true
}
},
+ "engineering-analytics-flaky-tests": {
+ "description": "Backend tests ranked by flakiness signal over a window (date_from default -7d, maximum 30 days), from the per-test CI spans. A test qualifies by passing on an automatic retry at least min_rerun_passes times (default 1) OR failing on at least min_failed_prs distinct pull requests (default 3). Use this for \"which tests are flaky right now\" and to pick quarantine candidates. Read the counts as absolute signal, never rates — fast passing runs are not emitted, so there is no honest denominator. rerun_passed_count only flows from CI lanes running with retries enabled; in other lanes a flake surfaces as a plain failure, which failed_pr_count catches. xfailed_count > 0 means the test is already quarantined but still failing. nodeid is a best-effort reconstruction (no '.py' suffix, the file/class boundary folded into '/'), so convert before using it as a pytest selector.",
+ "category": "Engineering analytics",
+ "feature": "engineering_analytics",
+ "summary": "Flaky test leaderboard",
+ "title": "Flaky test leaderboard",
+ "required_scopes": ["engineering_analytics:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"engineering-analytics-pr-cost": {
"description": "Estimated CI dollar cost of one pull request, summed over the jobs of all its workflow runs, with breakdowns per workflow (by_workflow) and per run (by_run). Reach for this instead of summing runner minutes by hand: the estimate already classifies runners (billable self-hosted Linux vs free GitHub-hosted), applies the per-vCPU price ladder, and excludes non-Linux and provider-hosted jobs. jobs_available is false when the job-level source isn't synced yet — every figure is then zero/null, so check it before trusting a $0.00. estimated_cost_usd is null (not zero) when nothing was costable, and unsettled_jobs counts billable jobs still running that are left out of the estimate.",
"category": "Engineering analytics",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 95872fd0a45d..c4b206407543 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24564,6 +24564,34 @@ export namespace Schemas {
refreshing: boolean;
}
+ export interface FlakyTestItem {
+ /** Reconstructed pytest nodeid (the CI span name), e.g. 'posthog/api/test/test_event/TestEvents::test_x'. A stable grouping key, not a runnable selector — use `selector` to run or quarantine the test. */
+ nodeid: string;
+ /** Runnable pytest selector, e.g. 'posthog/api/test/test_event.py::TestEvents::test_x'. Exact when the CI reporter emitted it; otherwise reconstructed from the nodeid, where the file/class boundary is a best-effort guess. */
+ selector: string;
+ /** Times the test failed, then passed on an automatic retry — the strongest flaky signal. Only CI lanes running with reruns enabled emit it; a flake in a no-rerun lane shows up in failed_count instead. */
+ rerun_passed_count: number;
+ /** Spans whose final outcome was 'failed' or 'error' in the window. An absolute count, not a rate — fast passing runs are not emitted, so denominators are biased. */
+ failed_count: number;
+ /** Distinct pull requests among the failed/error spans. Failures on master or unattributed branches carry no PR number and are excluded here (still in failed_count). */
+ failed_pr_count: number;
+ /** Distinct git branches across all of the test's flaky-signal spans in the window. */
+ branch_count: number;
+ /** Runs where the test failed while quarantined (xfail) — already masked in CI but still flaky. */
+ xfailed_count: number;
+ /** Most recent flaky-signal span for this test in the window. */
+ last_seen_at: string;
+ }
+
+ export interface FlakyTestList {
+ /** Qualifying tests ranked by flakiness signal, strongest first, capped at `limit`. */
+ items: FlakyTestItem[];
+ /** True when more tests qualified than the cap; `items` is the strongest `limit` rows. */
+ truncated: boolean;
+ /** Maximum number of tests returned in `items`. */
+ limit: number;
+ }
+
/**
* Fleet-wide tally of recently emitted findings — backs the "Scout findings" callout so it
* renders from one cheap query instead of the client walking the whole paginated runs window.
@@ -64027,6 +64055,33 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsFlakyTestsParams = {
+ /**
+ * Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * Maximum number of tests to return (1-200). Defaults to 50.
+ */
+ limit?: number;
+ /**
+ * A test qualifies once it failed on at least this many distinct pull requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.
+ */
+ min_failed_prs?: number;
+ /**
+ * A test qualifies once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.
+ */
+ min_rerun_passes?: number;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ };
+
export type EngineeringAnalyticsJobAggregatesParams = {
/**
* Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 80a3e983ea0c..e4fee7de52ab 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 8 enabled ops
+ * PostHog API - MCP 9 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -30,6 +30,46 @@ export const EngineeringAnalyticsCiFailureLogsQueryParams = /* @__PURE__ */ zod.
),
})
+/**
+ * The flaky-test leaderboard: backend tests ranked by flakiness signal from the per-test CI spans, over a window (default -7d, maximum 30 days). A test qualifies by passing on retry at least min_rerun_passes times OR failing on at least min_failed_prs distinct PRs. All figures are absolute counts, never rates: fast passing runs are not emitted, so denominators are biased. Pass-on-retry counts only flow from CI lanes running with reruns enabled; in other lanes a flake surfaces as a plain failure, which the distinct-PR count catches.
+ */
+export const EngineeringAnalyticsFlakyTestsParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const EngineeringAnalyticsFlakyTestsQueryParams = /* @__PURE__ */ zod.object({
+ date_from: zod
+ .string()
+ .optional()
+ .describe(
+ "Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days."
+ ),
+ date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),
+ limit: zod.number().optional().describe('Maximum number of tests to return (1-200). Defaults to 50.'),
+ min_failed_prs: zod
+ .number()
+ .optional()
+ .describe(
+ 'A test qualifies once it failed on at least this many distinct pull requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.'
+ ),
+ min_rerun_passes: zod
+ .number()
+ .optional()
+ .describe(
+ 'A test qualifies once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.'
+ ),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
+})
+
/**
* Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level source isn't synced yet.
*/
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index d2f64548cc5f..ead0a8c5f7b4 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -4,6 +4,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import {
EngineeringAnalyticsCiFailureLogsQueryParams,
+ EngineeringAnalyticsFlakyTestsQueryParams,
EngineeringAnalyticsPrCostQueryParams,
EngineeringAnalyticsPrLifecycleQueryParams,
EngineeringAnalyticsPullRequestsQueryParams,
@@ -37,6 +38,32 @@ const engineeringAnalyticsCiFailureLogs = (): ToolBase<
},
})
+const EngineeringAnalyticsFlakyTestsSchema = EngineeringAnalyticsFlakyTestsQueryParams
+
+const engineeringAnalyticsFlakyTests = (): ToolBase<
+ typeof EngineeringAnalyticsFlakyTestsSchema,
+ WithPostHogUrl<Schemas.FlakyTestList>
+> => ({
+ name: 'engineering-analytics-flaky-tests',
+ schema: EngineeringAnalyticsFlakyTestsSchema,
+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsFlakyTestsSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.FlakyTestList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/flaky_tests/`,
+ query: {
+ date_from: params.date_from,
+ date_to: params.date_to,
+ limit: params.limit,
+ min_failed_prs: params.min_failed_prs,
+ min_rerun_passes: params.min_rerun_passes,
+ source_id: params.source_id,
+ },
+ })
+ return await withPostHogUrl(context, result, '/engineering-analytics')
+ },
+})
+
const EngineeringAnalyticsPrCostSchema = EngineeringAnalyticsPrCostQueryParams
const engineeringAnalyticsPrCost = (): ToolBase<typeof EngineeringAnalyticsPrCostSchema, Schemas.PRCostSummary> => ({
@@ -199,6 +226,7 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'engineering-analytics-ci-failure-logs': engineeringAnalyticsCiFailureLogs,
+ 'engineering-analytics-flaky-tests': engineeringAnalyticsFlakyTests,
'engineering-analytics-pr-cost': engineeringAnalyticsPrCost,
'engineering-analytics-sources': engineeringAnalyticsSources,
'engineering-analytics-workflow-jobs': engineeringAnalyticsWorkflowJobs,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-flaky-tests.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-flaky-tests.json
new file mode 100644
index 000000000000..1aa034ffcab2
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/engineering-analytics-flaky-tests.json
@@ -0,0 +1,30 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "date_from": {
+ "description": "Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days.",
+ "type": "string"
+ },
+ "date_to": {
+ "description": "Window end: relative or ISO8601. Defaults to now.",
+ "type": "string"
+ },
+ "limit": {
+ "description": "Maximum number of tests to return (1-200). Defaults to 50.",
+ "type": "number"
+ },
+ "min_failed_prs": {
+ "description": "A test qualifies once it failed on at least this many distinct pull requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.",
+ "type": "number"
+ },
+ "min_rerun_passes": {
+ "description": "A test qualifies once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.",
+ "type": "number"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
+ }
+ },
+ "type": "object"
+}