:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(eng-analytics): require proof before calling a test flaky (#71339)
Raúl Negrón-Otero6ac98c2e8925
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d2e0d3456e77..eb248242681d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5835,9 +5835,9 @@ snapshots:scenes-app-engineering-analytics-run-activity-chart--default--light:hash: v1.k794b7964.f63752ff3ebf3bbee3be4ddc83d1ff657d9cdd11ee71e7283c30ce5a1aefde72.yTb8kpRqcG51TbM2CqgRmC5YvgE7-6pV1Trc7y5wutoscenes-app-engineering-analytics-test-health--flaky-test-leaderboard--dark:- hash: v1.k794b7964.06f9bbebe50864d9faa44b12087f126cb4e7bbd6c3edc32d97b8831ff052a64c.3KiiGIL_OptbOha2UJHd1duUyx3sSLXVxpxGMFeFkBA+ hash: v1.k794b7964.c8a8c1d5961339dd76602d92f48e05ea11d10b19b8ca611dce24a4e71eed8a3b.BayfjT4SJzeM7T1GCHDLs1Pi1ZF6vTwvR87EbTGr34Ascenes-app-engineering-analytics-test-health--flaky-test-leaderboard--light:- hash: v1.k794b7964.abe059fd4b4e8533cd630f97ebd8ed24f749de71386e5534c4d1eb6f75f613a1.YLsUVjfhXWCEY0RGJObH9x02_41emp85WSyK7Va8Db0+ hash: v1.k794b7964.5804098730db9c4faeb0bc5c4b43298e4e7fd3f77e5e1f43b65a4e03352c3132.b558b-H8LxsRoTNzDqhfKG4kbNprgpdaFRgoh6vB8_Mscenes-app-error-project-unavailable--access-revoked--dark:hash: v1.k794b7964.30ace8f015100159e1dedbed07ff9f0b0b770535870d5c98ea764b10ff1f7621.dTVw9qLa7D_e7ZNme4tVuPZov-0Gg1o84aiDl5zihF0scenes-app-error-project-unavailable--access-revoked--light:diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex 45eca86b07ab..b45bee10b747 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -82,6 +82,7 @@ graph LR- Job-level CI: per-job duration, queue time, runner tier, and dollar cost ride `workflow_jobs` (webhook stream plus bounded backfill).- One write surface: test quarantine. The UI files a tracking issue plus a PR against the repo's checked-in `.test_quarantine.json` through the team's GitHub App. Everything else is read-only.+- The test-health view is an active work queue, not a failure-rate leaderboard: evidence is counted per CI run, a test is called flaky only where the evidence proves it (an in-job retry recovered it), and every other failure ranks as an honest suspected regression by blast radius.- Access control: per-user warehouse RBAC at the source resolver, `engineering_analytics:read` scopes on tools, feature-flag gated.## The goal: CI Signals for PostHog Codediff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex a2dd372f7290..eda8612d0270 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -89,6 +89,7 @@ The endpoint catalog is `presentation/views.py`; the agent-facing descriptions l- Time windows are `date_from` / `date_to`, relative (`-30d`) or ISO8601.- Capped list contracts that include a sibling aggregate return `{items, truncated, limit}` so they never silently undercount against it.- Span-derived reads (flaky tests, team CI health) report absolute counts, never rates: sub-threshold runs aren't emitted, so denominators are biased.+- Test evidence is counted per CI run, never per span (one run fans a test across matrix legs), and both span-derived reads group the same `run_evidence()` so the grain and the meaning of flaky cannot drift. A test is `confirmed_flake` only on in-run recovery proof; unproven failures rank as `suspected_regression` by blast radius.- Reads over optional data (e.g. `team_members`) degrade honestly (`has_membership_data: false`), never 500.### Exposed warehouse viewsdiff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex a68bf86bf224..cfbc39eae993 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -312,7 +312,6 @@ 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,@@ -323,7 +322,6 @@ def list_flaky_tests(curated=_authorized_source(team, source_id, user_access_control, repo=repo),date_from=date_from,date_to=date_to,- min_rerun_passes=min_rerun_passes,min_failed_prs=min_failed_prs,limit=limit,)@@ -334,7 +332,6 @@ def list_team_ci_health(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,@@ -344,7 +341,6 @@ def list_team_ci_health(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,)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 573fbc29e63f..ba578e907766 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -498,21 +498,43 @@ class CIFailureLogs:truncated: bool-# The one caveat that governs every flaky figure — defined once here (the canonical-types home)+# 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."+ "Counts are absolute, never rates: CI emits a span for every failure but only for passes slow "+ "enough to clear the emitter's duration threshold, so there is no execution denominator. "+ "'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.")+class FlakyTestClassification(StrEnum):+ # An in-job retry recovered the test in the same run.+ CONFIRMED_FLAKE = "confirmed_flake"+ # Only failures recorded, which is absence of proof, not proof of a regression.+ SUSPECTED_REGRESSION = "suspected_regression"+ # Failing while masked as xfail.+ QUARANTINED = "quarantined"++ @classmethod+ def from_run_evidence(+ cls, *, quarantined_failed_run_count: int, rerun_passed_run_count: int+ ) -> "FlakyTestClassification":+ # Quarantine wins over a recovery proof: an xfail is already masked, so surface that first.+ if quarantined_failed_run_count > 0:+ return cls.QUARANTINED+ if rerun_passed_run_count > 0:+ return cls.CONFIRMED_FLAKE+ return cls.SUSPECTED_REGRESSION++@dataclass(frozen=True)class FlakyTestItem:- """One flaky-test leaderboard row, aggregated from the per-test CI spans in the Traces store.+ """One test in the active test-health queue, 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.+ Ranked by blast radius: what a failing test costs, not how often it flakes. This queue only sees+ Backend CI. Evidence is counted per CI run, never per span: one run fans a test across matrix+ legs, so only the run grain counts one failure once. See ``FLAKY_TEST_SIGNAL_CAVEAT`` for why+ every figure is an absolute count."""# Reconstructed pytest nodeid (the span name), e.g. 'posthog/api/test/test_x/TestX::test_y'.@@ -520,29 +542,26 @@ class FlakyTestItem:# 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.+ classification: FlakyTestClassification+ # Runs where an in-job pytest retry recovered the test after it failed. Only tests hand-marked+ # @pytest.mark.flaky(reruns=N) can reach this: Backend CI runs without --reruns so failures+ # stay visible instead of being retried away.+ rerun_passed_run_count: int+ failed_run_count: int+ # Master/branch failures carry no PR number and don't count here.failed_pr_count: int- # Failed/error spans on the default branch (master/main approximation — the source doesn't record- # the default branch); the "matters right now" signal.- master_failed_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+ # master/main approximation: the source doesn't record the default branch.+ master_failed_run_count: int+ quarantined_failed_run_count: int+ last_signal_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.+ """The active test-health queue for a window: tests with a live failure signal, ranked by blast+ radius (trunk first, then PRs, then runs), capped at ``limit`` with an explicit truncation flag+ (same shape as ``PullRequestList``). A test qualifies on any in-run recovery, any+ default-branch failure, failures on at least ``min_failed_prs`` distinct PRs, or an xfail."""items: list[FlakyTestItem]@@ -563,19 +582,22 @@ class TeamCIHealthItem:# Owning team slug (CODEOWNERS handle minus '@PostHog/'), or 'unowned' for unstamped spans.owner_team: str- # Owned tests meeting the flaky-leaderboard bar in the window (rerun passes OR distinct failed PRs).+ # Owned tests an in-job retry recovered in the window: the same proof, and the same word,+ # the test-health queue's `confirmed_flake` uses.flaky_test_count: intflaky_test_count_prior: int- # Signal spans on owned tests with outcome 'failed' or 'error' in the window.- failed_count: int- failed_count_prior: int- # Spans on owned tests that failed first, then passed on an automatic retry.- rerun_passed_count: int- rerun_passed_count_prior: int- # Spans on owned tests that failed while quarantined (xfail): already masked, still flaky.- xfailed_count: int- xfailed_count_prior: int- # Most recent signal span across the team's owned tests, either window.+ # Owned tests that failed with no such proof and still hit the blast-radius bar. Not flakes.+ regression_test_count: int+ regression_test_count_prior: int+ # Runs (not spans) where an owned test's recorded outcome was failed or error.+ failed_run_count: int+ failed_run_count_prior: int+ rerun_passed_run_count: int+ rerun_passed_run_count_prior: int+ # Runs where an owned test failed while quarantined (xfail): already masked, still failing.+ quarantined_failed_run_count: int+ quarantined_failed_run_count_prior: int+ # Most recent failure, recovery, or xfail run across the team's owned tests, either window.last_seen_at: datetime@@ -594,8 +616,8 @@ class TeamCIHealthList:@dataclass(frozen=True)class TeamTestSignal:"""One owned test's flaky signal across the current window and its equal-length prior- window, the pair behind a before-vs-after slope reading. Signal = failed + error +- pass-on-retry spans (xfail excluded: already-quarantined noise).+ window, the pair behind a before-vs-after slope reading. Signal = runs where the test+ failed, errored, or a retry recovered it (xfail excluded: already-quarantined noise)."""nodeid: strdiff --git a/products/engineering_analytics/backend/logic/queries/_test_spans.py b/products/engineering_analytics/backend/logic/queries/_test_spans.pyindex f0671c4d3236..119b7e0e4f96 100644--- a/products/engineering_analytics/backend/logic/queries/_test_spans.py+++ b/products/engineering_analytics/backend/logic/queries/_test_spans.py@@ -1,10 +1,24 @@-"""The one definition of the per-test CI span scan (domain rules defined once, APOSD).+"""The one definition of the per-test CI span scan and what it proves (domain rules defined once, APOSD).Backend CI emits one OTel span per test into the Traces store (span name = reconstructedpytest nodeid, ``test.*`` attributes, ``ci.*`` resource attributes; see-``.github/scripts/report_test_timings.py``). Every query over that signal (the flaky-test-leaderboard and the per-team rollups) embeds this scan, so the service fence, the signal-outcomes, the repository scoping, and the ownership fallback cannot drift apart.+``.github/scripts/report_test_timings.py``). Every query over that signal (the test-health+queue and the per-team rollups) embeds ``run_evidence()``, so the service fence, the signal+outcomes, the repository scoping, the ownership fallback, and above all the **grain** cannot+drift apart. Sharing a predicate string was not enough: each caller still counted its own way,+and they disagreed.++The grain is the CI run, not the span. One run fans a test out across matrix legs (person-on-events,+compat, and friends), so span-grain counting multiplies a single failure by the number of legs that+ran it. At run grain a failure in any leg counts once, and outweighs a pass in another.++What this signal can and cannot prove:++- ``rerun_passed`` is proof of nondeterminism: the test failed and passed within one run. It reaches+ only the handful of tests hand-marked ``@pytest.mark.flaky(reruns=N)``, because Backend CI runs+ pytest without ``--reruns`` deliberately, so failures stay visible instead of being retried away.+- Everything else proves nothing about determinism. This surface answers how much a failing test+ costs us, so unproven failures are ranked by blast radius and never called flaky."""from datetime import datetime@@ -23,9 +37,36 @@ CI_SERVICE_NAME = "ci-backend"UNOWNED_TEAM = "unowned"-def flaky_bar(rerun_count: str, failed_pr_count: str) -> str:- """The one flaky-test qualification bar (SPEC §5): enough rerun passes OR enough distinct failed PRs."""- return f"{rerun_count} >= {{min_rerun_passes}} OR {failed_pr_count} >= {{min_failed_prs}}"+_RUN_EVIDENCE = """+ SELECT+ nodeid,+ run_id,+ argMax(owner_team, span_timestamp) AS owner_team,+ anyIf(selector, selector != '') AS selector,+ anyIf(pr_number, pr_number != '') AS pr_number,+ anyIf(branch, branch != '') AS branch,+ max(is_current) AS is_current,+ max(outcome IN ('failed', 'error')) AS failed_in_run,+ max(outcome = 'xfailed') AS quarantined_in_run,+ max(outcome = 'rerun_passed') AS recovered_in_run,+ -- Every scanned span is a signal span (the fence admits no plain passes), so the run's last+ -- span is its last signal.+ max(span_timestamp) AS run_signal_at+ FROM (__SPAN_SCAN__)+ GROUP BY nodeid, run_id+"""+++def run_evidence(*, bounded: bool) -> str:+ """One row per (test, CI run): what that run proves about that test.++ Every consumer groups this, never the raw spans, so all of them count at the same grain and+ agree on what the signal means. See the module docstring for why the run is the grain.++ ``bounded`` adds the upper time bound; some callers scan to now.+ """+ scan = _SCAN.replace("__DATE_TO__", " AND timestamp <= {date_to}" if bounded else "")+ return _RUN_EVIDENCE.replace("__SPAN_SCAN__", scan)# Scans [scan_from, date_to?]; `is_current` splits rows at {date_from} so a caller scanning@@ -39,6 +80,9 @@ _SCAN = """coalesce(nullIf(attributes['test.owner_team'], ''), {unowned_team}) AS owner_team,resource_attributes['ci.pr_number'] AS pr_number,resource_attributes['ci.branch'] AS branch,+ -- The emitter always stamps ci.run_id; the trace_id fallback (one trace per job) keeps an+ -- unstamped span from merging every execution of its test into one phantom run.+ coalesce(nullIf(resource_attributes['ci.run_id'], ''), trace_id) AS run_id,timestamp AS span_timestamp,timestamp >= {date_from} AS is_currentFROM posthog.trace_spans@@ -49,11 +93,6 @@ _SCAN = """"""-def span_scan(*, bounded: bool) -> str:- """The scan SELECT, with or without the upper time bound (some callers scan to now)."""- return _SCAN.replace("__DATE_TO__", " AND timestamp <= {date_to}" if bounded else "")--def scan_placeholders(*,repository: str,diff --git a/products/engineering_analytics/backend/logic/queries/broken_tests.py b/products/engineering_analytics/backend/logic/queries/broken_tests.pyindex 9e4321f7505d..27a94e1aa14d 100644--- a/products/engineering_analytics/backend/logic/queries/broken_tests.py+++ b/products/engineering_analytics/backend/logic/queries/broken_tests.py@@ -1,6 +1,6 @@"""Broken-tests classifier: rank live CI failures by how they're behaving right now.-The flaky-test leaderboard answers "which tests are unreliable over a week". This answers a+The test-health queue answers "which tests are unreliable over a week". This answers asharper, more urgent question: of the failures happening *right now*, which are breaking trunk,which are a new failure catching on, which are just one PR's problem. It reads the fingerprintedfailure lines (``engineering_analytics_ci_failures`` — the Logs-backed view) over a short window,diff --git a/products/engineering_analytics/backend/logic/queries/flaky_tests.py b/products/engineering_analytics/backend/logic/queries/flaky_tests.pyindex 47ec58cef398..19df8d350890 100644--- a/products/engineering_analytics/backend/logic/queries/flaky_tests.py+++ b/products/engineering_analytics/backend/logic/queries/flaky_tests.py@@ -1,21 +1,15 @@-"""HogQL aggregation of per-test CI spans into a flaky-test leaderboard.+"""HogQL aggregation of per-test CI run evidence into the active test-health queue.-Embeds the shared per-test span scan (``_test_spans``, the one definition of the service-fence, signal outcomes, and repository scoping) and groups the signal spans by nodeid over-a window, ranking tests by flakiness signal.+Groups ``_test_spans.run_evidence()`` (the one definition of the grain and of what a run proves)+by nodeid, and ranks by blast radius: how many PRs a test broke and how often it broke master.-Two data caveats shape the query:+A test is a ``confirmed_flake`` only where the evidence already carries proof (an in-job retry+recovered it), and every other failure is an honest ``suspected_regression`` rather than a guess+dressed up as one. Failing on many distinct PRs proves only that a failure is not one PR's+fault, never that the test is flaky: real regressions fail across PRs too.-- Passing tests under the emitter's duration threshold are dropped, while failures, errors,- xfails, and reruns are always emitted, so denominators are biased and 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).+Every figure is an absolute count: the emitter drops sub-threshold passes, so there is no+denominator to divide by.Reads the ``posthog.trace_spans`` table on the LOGS ClickHouse cluster, not the warehouse."""@@ -26,31 +20,41 @@ from posthog.hogql import astfrom posthog.clickhouse.workload import Workload-from products.engineering_analytics.backend.facade.contracts import FlakyTestItem, FlakyTestList+from products.engineering_analytics.backend.facade.contracts import (+ FlakyTestClassification,+ FlakyTestItem,+ FlakyTestList,+)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._test_spans import (- flaky_bar,+ run_evidence,scan_placeholders,selector_from_nodeid,- span_scan,)-_SELECT = f"""+_SELECT = """SELECTnodeid,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,- countIf(outcome IN ('failed', 'error') AND branch IN ('master', 'main')) AS master_failed_count,- uniqIf(branch, branch != '') AS branch_count,- countIf(outcome = 'xfailed') AS xfailed_count,- max(span_timestamp) AS last_seen_at- FROM (__SPAN_SCAN__)+ countIf(recovered_in_run) AS rerun_passed_run_count,+ countIf(failed_in_run) AS failed_run_count,+ uniqIf(pr_number, failed_in_run AND pr_number != '') AS failed_pr_count,+ countIf(failed_in_run AND branch IN ('master', 'main')) AS master_failed_run_count,+ countIf(quarantined_in_run) AS quarantined_failed_run_count,+ max(run_signal_at) AS last_signal_at+ FROM (__RUN_EVIDENCE__)GROUP BY nodeid- HAVING {flaky_bar("rerun_passed_count", "failed_pr_count")}- ORDER BY (rerun_passed_count + failed_pr_count) DESC, failed_count DESC, last_seen_at DESC- LIMIT {{limit_plus_one}}+ HAVING rerun_passed_run_count > 0+ OR quarantined_failed_run_count > 0+ OR master_failed_run_count > 0+ OR failed_pr_count >= {min_failed_prs}+ ORDER BY+ master_failed_run_count DESC,+ failed_pr_count DESC,+ failed_run_count DESC,+ last_signal_at DESC,+ nodeid ASC+ LIMIT {limit_plus_one}"""@@ -59,25 +63,23 @@ def query_flaky_tests(curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,- min_rerun_passes: int,min_failed_prs: int,limit: int,) -> FlakyTestList:repository = curated.repository# Fail closed: the spans are scoped to the source's repository. Without a repository identity we# cannot tell one connected repo's spans from another, so return nothing rather than leak every- # repository's flaky signals into the selected source's leaderboard.+ # repository's flaky signals into the selected source's queue.if not repository:return FlakyTestList(items=[], truncated=False, limit=limit)placeholders = scan_placeholders(repository=repository, date_from=date_from, date_to=date_to)- placeholders["min_rerun_passes"] = ast.Constant(value=min_rerun_passes)placeholders["min_failed_prs"] = ast.Constant(value=min_failed_prs)# +1 so a full page tells us more tests qualified than returned.placeholders["limit_plus_one"] = ast.Constant(value=limit + 1)response = curated.run(- _SELECT.replace("__SPAN_SCAN__", span_scan(bounded=date_to is not None)),+ _SELECT.replace("__RUN_EVIDENCE__", run_evidence(bounded=date_to is not None)),query_type="engineering_analytics.flaky_tests",placeholders=placeholders,# trace_spans lives on the LOGS ClickHouse cluster, not the warehouse default.@@ -90,17 +92,27 @@ def query_flaky_tests(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,+ classification=FlakyTestClassification.from_run_evidence(+ quarantined_failed_run_count=quarantined_failed_run_count,+ rerun_passed_run_count=rerun_passed_run_count,+ ),+ rerun_passed_run_count=rerun_passed_run_count,+ failed_run_count=failed_run_count,failed_pr_count=failed_pr_count,- master_failed_count=master_failed_count,- branch_count=branch_count,- xfailed_count=xfailed_count,- last_seen_at=last_seen_at,+ master_failed_run_count=master_failed_run_count,+ quarantined_failed_run_count=quarantined_failed_run_count,+ last_signal_at=last_signal_at,)- for nodeid, selector, rerun_passed_count, failed_count, failed_pr_count, master_failed_count, branch_count, xfailed_count, last_seen_at in rows[- :limit- ]+ for (+ nodeid,+ selector,+ rerun_passed_run_count,+ failed_run_count,+ failed_pr_count,+ master_failed_run_count,+ quarantined_failed_run_count,+ last_signal_at,+ ) in rows[:limit]],truncated=len(rows) > limit,limit=limit,diff --git a/products/engineering_analytics/backend/logic/queries/team_ci_health.py b/products/engineering_analytics/backend/logic/queries/team_ci_health.pyindex b87840077ef1..58f5859c78cf 100644--- a/products/engineering_analytics/backend/logic/queries/team_ci_health.py+++ b/products/engineering_analytics/backend/logic/queries/team_ci_health.py@@ -7,8 +7,12 @@ aggregate under the literal team ``'unowned'``, an honest first-class bucket thaownership gaps instead of dropping them.Teams are organizational owners of code surfaces; nothing here aggregates by author-(SPEC §2). Both queries share the flaky-tests caveats: sub-threshold passing runs are not-emitted, so every figure is an absolute count over signal spans, never a rate.+(SPEC §2). Both queries group ``_test_spans.run_evidence()``, so they carry its caveats and its+grain: sub-threshold passing runs are not emitted, so every figure is an absolute count over+signal spans, never a rate.++This is the ownership dimension of the test-health data: only these spans know which team owns a+test and what its failures cost the fleet.Reads the ``posthog.trace_spans`` table on the LOGS ClickHouse cluster, not the warehouse."""@@ -27,46 +31,56 @@ from products.engineering_analytics.backend.facade.contracts import ()from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._test_spans import (- flaky_bar,+ run_evidence,scan_placeholders,selector_from_nodeid,- span_scan,)-# The shared span scan, bounded and scanning [scan_from, date_to] in one pass; `is_current`+# The shared run evidence, bounded and scanning [scan_from, date_to] in one pass; `is_current`# splits the current window from its equal-length prior twin.-_SPAN_SCAN = span_scan(bounded=True)+_RUN_EVIDENCE = run_evidence(bounded=True)+# A test lands under one team, resolved by its latest ownership stamp, so a re-stamped test is+# never counted for two teams at once._ROSTER_SELECT = f"""SELECTowner_team,- countIf({flaky_bar("rerun_current", "failed_prs_current")}) AS flaky_test_count,- countIf({flaky_bar("rerun_prior", "failed_prs_prior")}) AS flaky_test_count_prior,- sum(failed_current) AS failed_count,- sum(failed_prior) AS failed_count_prior,- sum(rerun_current) AS rerun_passed_count,- sum(rerun_prior) AS rerun_passed_count_prior,- sum(xfail_current) AS xfailed_count,- sum(xfail_prior) AS xfailed_count_prior,- max(last_seen) AS last_seen_at+ countIf(recovery_runs_current > 0) AS flaky_test_count,+ countIf(recovery_runs_prior > 0) AS flaky_test_count_prior,+ countIf(recovery_runs_current = 0 AND blast_radius_current) AS regression_test_count,+ countIf(recovery_runs_prior = 0 AND blast_radius_prior) AS regression_test_count_prior,+ sum(failed_runs_current) AS failed_run_count,+ sum(failed_runs_prior) AS failed_run_count_prior,+ sum(recovery_runs_current) AS rerun_passed_run_count,+ sum(recovery_runs_prior) AS rerun_passed_run_count_prior,+ sum(xfail_runs_current) AS quarantined_failed_run_count,+ sum(xfail_runs_prior) AS quarantined_failed_run_count_prior,+ max(last_signal) AS last_seen_atFROM (SELECT- owner_team,nodeid,- countIf(outcome = 'rerun_passed' AND is_current) AS rerun_current,- countIf(outcome = 'rerun_passed' AND NOT is_current) AS rerun_prior,- countIf(outcome IN ('failed', 'error') AND is_current) AS failed_current,- countIf(outcome IN ('failed', 'error') AND NOT is_current) AS failed_prior,- countIf(outcome = 'xfailed' AND is_current) AS xfail_current,- countIf(outcome = 'xfailed' AND NOT is_current) AS xfail_prior,- uniqIf(pr_number, outcome IN ('failed', 'error') AND pr_number != '' AND is_current) AS failed_prs_current,- uniqIf(pr_number, outcome IN ('failed', 'error') AND pr_number != '' AND NOT is_current) AS failed_prs_prior,- max(span_timestamp) AS last_seen- FROM ({_SPAN_SCAN})- GROUP BY owner_team, nodeid+ argMax(owner_team, run_signal_at) AS owner_team,+ countIf(recovered_in_run AND is_current) AS recovery_runs_current,+ countIf(recovered_in_run AND NOT is_current) AS recovery_runs_prior,+ countIf(failed_in_run AND is_current) AS failed_runs_current,+ countIf(failed_in_run AND NOT is_current) AS failed_runs_prior,+ countIf(quarantined_in_run AND is_current) AS xfail_runs_current,+ countIf(quarantined_in_run AND NOT is_current) AS xfail_runs_prior,+ countIf(failed_in_run AND branch IN ('master', 'main') AND is_current) > 0+ OR uniqIf(pr_number, failed_in_run AND pr_number != '' AND is_current) >= {{min_failed_prs}}+ AS blast_radius_current,+ countIf(failed_in_run AND branch IN ('master', 'main') AND NOT is_current) > 0+ OR uniqIf(pr_number, failed_in_run AND pr_number != '' AND NOT is_current) >= {{min_failed_prs}}+ AS blast_radius_prior,+ max(run_signal_at) AS last_signal+ FROM ({_RUN_EVIDENCE})+ GROUP BY nodeid)GROUP BY owner_team- ORDER BY (flaky_test_count + failed_count) DESC, (flaky_test_count_prior + failed_count_prior) DESC, owner_team ASC+ ORDER BY+ (flaky_test_count + regression_test_count) DESC,+ (flaky_test_count_prior + regression_test_count_prior) DESC,+ owner_team ASCLIMIT {{limit_plus_one}}"""@@ -74,13 +88,15 @@ _TEST_SIGNAL_SELECT = f"""SELECTnodeid,anyIf(selector, selector != '') AS selector,- countIf(is_current AND outcome != 'xfailed') AS signal_count,- countIf(NOT is_current AND outcome != 'xfailed') AS signal_count_prior,- max(span_timestamp) AS last_seen_at- FROM ({_SPAN_SCAN})- WHERE owner_team = {{owner_team}}+ countIf(is_current AND (failed_in_run OR recovered_in_run)) AS signal_count,+ countIf(NOT is_current AND (failed_in_run OR recovered_in_run)) AS signal_count_prior,+ max(run_signal_at) AS last_seen_at+ FROM ({_RUN_EVIDENCE})GROUP BY nodeid- HAVING signal_count > 0 OR signal_count_prior > 0+ -- Latest stamp owns the whole test, exactly as the roster counts it, so this drill-in never+ -- shows different rows than the summary that opened it.+ HAVING argMax(owner_team, run_signal_at) = {{owner_team}}+ AND (signal_count > 0 OR signal_count_prior > 0)ORDER BY greatest(signal_count, signal_count_prior) DESC, signal_count DESC, nodeid ASCLIMIT {{test_limit_plus_one}}"""@@ -102,7 +118,6 @@ def query_team_ci_health(curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,- min_rerun_passes: int,min_failed_prs: int,limit: int,) -> TeamCIHealthList:@@ -112,7 +127,6 @@ def query_team_ci_health(return TeamCIHealthList(items=[], truncated=False, limit=limit)placeholders = _window_placeholders(curated=curated, date_from=date_from, date_to=date_to)- placeholders["min_rerun_passes"] = ast.Constant(value=min_rerun_passes)placeholders["min_failed_prs"] = ast.Constant(value=min_failed_prs)placeholders["limit_plus_one"] = ast.Constant(value=limit + 1)@@ -129,24 +143,28 @@ def query_team_ci_health(owner_team=owner_team,flaky_test_count=flaky_test_count,flaky_test_count_prior=flaky_test_count_prior,- failed_count=failed_count,- failed_count_prior=failed_count_prior,- rerun_passed_count=rerun_passed_count,- rerun_passed_count_prior=rerun_passed_count_prior,- xfailed_count=xfailed_count,- xfailed_count_prior=xfailed_count_prior,+ regression_test_count=regression_test_count,+ regression_test_count_prior=regression_test_count_prior,+ failed_run_count=failed_run_count,+ failed_run_count_prior=failed_run_count_prior,+ rerun_passed_run_count=rerun_passed_run_count,+ rerun_passed_run_count_prior=rerun_passed_run_count_prior,+ quarantined_failed_run_count=quarantined_failed_run_count,+ quarantined_failed_run_count_prior=quarantined_failed_run_count_prior,last_seen_at=last_seen_at,)for (owner_team,flaky_test_count,flaky_test_count_prior,- failed_count,- failed_count_prior,- rerun_passed_count,- rerun_passed_count_prior,- xfailed_count,- xfailed_count_prior,+ regression_test_count,+ regression_test_count_prior,+ failed_run_count,+ failed_run_count_prior,+ rerun_passed_run_count,+ rerun_passed_run_count_prior,+ quarantined_failed_run_count,+ quarantined_failed_run_count_prior,last_seen_at,) in rows[:limit]],diff --git a/products/engineering_analytics/backend/logic/suite_health.py b/products/engineering_analytics/backend/logic/suite_health.pyindex 77a9a28ce097..c037661a13c8 100644--- a/products/engineering_analytics/backend/logic/suite_health.py+++ b/products/engineering_analytics/backend/logic/suite_health.py@@ -1,4 +1,4 @@-"""Test-health orchestration: the flaky-test leaderboard and the broken-tests panel."""+"""Test-health orchestration: the active test-health queue and the broken-tests panel."""from products.engineering_analytics.backend.facade.contracts import (BROKEN_TEST_SPARKLINE_HOURS,@@ -10,12 +10,11 @@ from products.engineering_analytics.backend.logic.queries._curated import Curatefrom products.engineering_analytics.backend.logic.queries.broken_tests import query_broken_testsfrom products.engineering_analytics.backend.logic.queries.flaky_tests import query_flaky_tests-# Flaky-test leaderboard defaults: a week of signal is the triage window, a month the ceiling+# Test-health queue 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).-# The signal thresholds double as the bar for the team CI health rollups.+# The signal threshold doubles as the bar for the team CI health rollups._DEFAULT_FLAKY_WINDOW = "-7d"MAX_FLAKY_WINDOW_DAYS = 30-DEFAULT_FLAKY_MIN_RERUN_PASSES = 1DEFAULT_FLAKY_MIN_FAILED_PRS = 3_DEFAULT_FLAKY_LIMIT = 50_MAX_FLAKY_LIMIT = 200@@ -32,19 +31,17 @@ 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_PASSESmin_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")+ # test with any signal span, so require an explicit positive bar instead.+ if min_failed_prs < 1:+ raise ValueError("min_failed_prs must be at least 1")limit = limit if limit is not None else _DEFAULT_FLAKY_LIMITif not 1 <= limit <= _MAX_FLAKY_LIMIT:raise ValueError(f"limit must be between 1 and {_MAX_FLAKY_LIMIT}")@@ -52,7 +49,6 @@ def build_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,)diff --git a/products/engineering_analytics/backend/logic/teams.py b/products/engineering_analytics/backend/logic/teams.pyindex bae7aa3b4629..bc2d525f51bd 100644--- a/products/engineering_analytics/backend/logic/teams.py+++ b/products/engineering_analytics/backend/logic/teams.py@@ -10,7 +10,6 @@ from products.engineering_analytics.backend.logic.queries.team_ci_health importfrom products.engineering_analytics.backend.logic.queries.team_merge_trend import query_team_merge_trendfrom products.engineering_analytics.backend.logic.suite_health import (DEFAULT_FLAKY_MIN_FAILED_PRS,- DEFAULT_FLAKY_MIN_RERUN_PASSES,MAX_FLAKY_WINDOW_DAYS,)@@ -29,19 +28,17 @@ def build_team_ci_health(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,) -> TeamCIHealthList:parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_TEAM_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_PASSESmin_failed_prs = min_failed_prs if min_failed_prs is not None else DEFAULT_FLAKY_MIN_FAILED_PRS- # Same explicit-positive-bar rule as the flaky leaderboard: a zero threshold would- # silently qualify every test with any signal span.- if min_rerun_passes < 1 or min_failed_prs < 1:- raise ValueError("min_rerun_passes and min_failed_prs must be at least 1")+ # Same explicit-positive-bar rule as the test-health queue: a zero threshold would+ # silently qualify every test with any failure.+ if min_failed_prs < 1:+ raise ValueError("min_failed_prs must be at least 1")limit = limit if limit is not None else _DEFAULT_TEAM_LIMITif not 1 <= limit <= _MAX_TEAM_LIMIT:raise ValueError(f"limit must be between 1 and {_MAX_TEAM_LIMIT}")@@ -49,7 +46,6 @@ def build_team_ci_health(curated=curated,date_from=parsed_from,date_to=parsed_to,- min_rerun_passes=min_rerun_passes,min_failed_prs=min_failed_prs,limit=limit,)diff --git a/products/engineering_analytics/backend/presentation/serializers/suite_health.py b/products/engineering_analytics/backend/presentation/serializers/suite_health.pyindex 3aa8cf73fe2a..339d747bf010 100644--- a/products/engineering_analytics/backend/presentation/serializers/suite_health.py+++ b/products/engineering_analytics/backend/presentation/serializers/suite_health.py@@ -29,44 +29,49 @@ class FlakyTestItemSerializer(DataclassSerializer):"'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.",+ "classification": {+ "help_text": "confirmed_flake: an in-job retry recovered the test in the same run, so it is "+ "provably nondeterministic. quarantined: it fails while masked as xfail. suspected_regression: "+ "only failures were recorded, which is absence of proof, not proof that it is a real break.",},- "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.",+ "rerun_passed_run_count": {+ "help_text": "Runs where an in-job pytest retry recovered the test after it failed. Above zero is "+ "the only proof of flakiness this data carries, and it reaches only tests hand-marked "+ "@pytest.mark.flaky(reruns=N), since Backend CI runs without --reruns so failures stay visible.",+ },+ "failed_run_count": {+ "help_text": "Distinct CI runs whose recorded outcome was failed or error. A run counts once "+ "however many matrix legs it failed in.",},"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).",+ "help_text": "Distinct pull requests among the failed runs. Failures on master or unattributed "+ "branches carry no PR number and are excluded here (still in failed_run_count).",},- "master_failed_count": {- "help_text": "Failed/error spans on the default branch (master/main approximation) — the "- "'matters right now' signal that a flake is breaking the trunk, not just PR branches.",+ "master_failed_run_count": {+ "help_text": "Failed runs on the default branch (master/main approximation): the 'matters right "+ "now' signal that a test is breaking the trunk, not just PR branches.",},- "branch_count": {- "help_text": "Distinct git branches across all of the test's flaky-signal spans in the window.",+ "quarantined_failed_run_count": {+ "help_text": "Runs where the test failed while quarantined (xfail): already masked in CI, still "+ "failing.",},- "xfailed_count": {- "help_text": "Runs where the test failed while quarantined (xfail) — already masked in CI "- "but still flaky.",+ "last_signal_at": {+ "help_text": "Most recent failure, recovery, or xfail run for this test in the window.",},- "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`."+ many=True,+ help_text="Tests worth acting on now, ranked by blast radius: master failures, then PRs hit, then runs.",)class Meta:dataclass = FlakyTestListextra_kwargs = {"truncated": {- "help_text": "True when more tests qualified than the cap; `items` is the strongest `limit` rows.",+ "help_text": "True when more tests qualified than the cap; `items` is the highest-ranked `limit` rows.",},"limit": {"help_text": "Maximum number of tests returned in `items`."},}diff --git a/products/engineering_analytics/backend/presentation/serializers/teams.py b/products/engineering_analytics/backend/presentation/serializers/teams.pyindex bad8985a0c97..0ed0c3d4a478 100644--- a/products/engineering_analytics/backend/presentation/serializers/teams.py+++ b/products/engineering_analytics/backend/presentation/serializers/teams.py@@ -21,28 +21,35 @@ class TeamCIHealthItemSerializer(DataclassSerializer):"or the literal 'unowned' for tests whose spans carry no ownership stamp.",},"flaky_test_count": {- "help_text": "Owned tests meeting the flaky-leaderboard bar in the window (passed on retry "- "or failed on enough distinct PRs). Compare with flaky_test_count_prior for the delta.",+ "help_text": "Owned tests an in-job retry recovered in the window: the same proof, and the same "+ "word, that flaky_tests calls a confirmed_flake. Compare with flaky_test_count_prior for the "+ "delta.",},"flaky_test_count_prior": {"help_text": "Same count over the equal-length window immediately before date_from.",},- "failed_count": {- "help_text": "Signal spans on owned tests with final outcome 'failed' or 'error' in the "- "window. An absolute count, not a rate: fast passing runs are not emitted.",+ "regression_test_count": {+ "help_text": "Owned tests that failed with no recorded in-run recovery and still hit the "+ "blast-radius bar (a master/main failure, or min_failed_prs distinct PRs). Not flakes: absence "+ "of proof, not proof.",},- "failed_count_prior": {"help_text": "Same count over the prior window."},- "rerun_passed_count": {- "help_text": "Spans on owned tests that failed, then passed on an automatic retry, the "- "strongest flaky signal. Only rerun-enabled CI lanes emit it.",+ "regression_test_count_prior": {"help_text": "Same count over the prior window."},+ "failed_run_count": {+ "help_text": "CI runs (not spans) where an owned test's recorded outcome was failed or error. "+ "An absolute count, not a rate: fast passing runs are not emitted.",},- "rerun_passed_count_prior": {"help_text": "Same count over the prior window."},- "xfailed_count": {- "help_text": "Spans on owned tests that failed while quarantined (xfail): masked in CI "- "but still flaky.",+ "failed_run_count_prior": {"help_text": "Same count over the prior window."},+ "rerun_passed_run_count": {+ "help_text": "Runs where an in-job pytest retry recovered an owned test after it failed.",+ },+ "rerun_passed_run_count_prior": {"help_text": "Same count over the prior window."},+ "quarantined_failed_run_count": {+ "help_text": "Runs where an owned test failed while quarantined (xfail): masked in CI, still failing.",+ },+ "quarantined_failed_run_count_prior": {"help_text": "Same count over the prior window."},+ "last_seen_at": {+ "help_text": "Most recent failure, recovery, or xfail run across the team's owned tests, either window."},- "xfailed_count_prior": {"help_text": "Same count over the prior window."},- "last_seen_at": {"help_text": "Most recent signal span across the team's owned tests, either window."},}@@ -68,10 +75,11 @@ class TeamTestSignalSerializer(DataclassSerializer):"nodeid": {"help_text": "Reconstructed pytest nodeid (the CI span name), a stable grouping key."},"selector": {"help_text": "Runnable pytest selector; exact when the CI reporter emitted it."},"signal_count": {- "help_text": "Failed + error + pass-on-retry spans in the current window (xfail excluded).",+ "help_text": "Runs in the current window where the test failed, errored, or a retry "+ "recovered it (xfail excluded).",},"signal_count_prior": {"help_text": "Same count over the equal-length window before date_from."},- "last_seen_at": {"help_text": "Most recent signal span for this test, either window."},+ "last_seen_at": {"help_text": "Most recent failure, recovery, or xfail run for this test, either window."},}diff --git a/products/engineering_analytics/backend/presentation/views/suite_health.py b/products/engineering_analytics/backend/presentation/views/suite_health.pyindex 416490554073..cd60e0ca1e4c 100644--- a/products/engineering_analytics/backend/presentation/views/suite_health.py+++ b/products/engineering_analytics/backend/presentation/views/suite_health.py@@ -44,21 +44,13 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):"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.",+ description="A test with no recorded recovery qualifies once it failed on at least this many "+ "distinct pull requests in the window. Minimum 1. Defaults to 3.",),OpenApiParameter(name="limit",@@ -77,9 +69,12 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):),},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+ "The active test-health queue: backend tests worth acting on now, from the per-test CI spans, over a "+ "window (default -7d, maximum 30 days). Evidence is counted per CI run, never per span. "+ "A test is a 'confirmed_flake' when an in-job retry recovered it in the same run; 'quarantined' when "+ "it fails while masked as xfail; otherwise "+ "'suspected_regression'. It qualifies on any recovery, any master/main failure, an xfail, or failures "+ "on at least min_failed_prs distinct PRs. " + FLAKY_TEST_SIGNAL_CAVEAT),)@action(detail=False, methods=["get"], pagination_class=None)@@ -89,7 +84,6 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):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,diff --git a/products/engineering_analytics/backend/presentation/views/teams.py b/products/engineering_analytics/backend/presentation/views/teams.pyindex db354d689bba..f4d4a0a4bb48 100644--- a/products/engineering_analytics/backend/presentation/views/teams.py+++ b/products/engineering_analytics/backend/presentation/views/teams.py@@ -39,21 +39,14 @@ class TeamActionsMixin(EngineeringAnalyticsViewSetBase):"*_prior counts and overstating deltas.",),_DATE_TO,- OpenApiParameter(- name="min_rerun_passes",- type=OpenApiTypes.INT,- location=OpenApiParameter.QUERY,- required=False,- description="A test counts as flaky 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 counts as flaky 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.",+ description="An unrecovered test counts toward regression_test_count once it failed on at least "+ "this many distinct pull requests in the window. Minimum 1. Defaults to 3. Does not affect "+ "flaky_test_count, which needs proof, not a threshold.",),OpenApiParameter(name="limit",@@ -71,11 +64,14 @@ class TeamActionsMixin(EngineeringAnalyticsViewSetBase):),},description=(- "Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and "- "pass-on-retry span counts, each with an equal-length previous-window twin for honest deltas. "- "Ownership is stamped on the spans at CI emission time from the repo's ownership map "- "(products/*/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team "- "'unowned'. Teams are organizational owners of code surfaces, never authors. " + FLAKY_TEST_SIGNAL_CAVEAT+ "Per-owning-team rollup of the CI test surfaces each team owns, over the same run evidence as "+ "flaky_tests and with the same meaning of flaky: flaky_test_count is owned tests an in-job retry "+ "recovered in the window, regression_test_count is owned tests that failed with no such proof and "+ "still hit the blast-radius bar, plus failed/recovery/quarantined run counts. Each has an "+ "equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI "+ "emission time from the repo's ownership map (products/*/product.yaml + CODEOWNERS); unstamped "+ "spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest "+ "owner only. Teams are organizational owners of code surfaces, never authors. " + FLAKY_TEST_SIGNAL_CAVEAT),)@action(detail=False, methods=["get"], pagination_class=None)@@ -85,7 +81,6 @@ class TeamActionsMixin(EngineeringAnalyticsViewSetBase):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,@@ -134,8 +129,8 @@ class TeamActionsMixin(EngineeringAnalyticsViewSetBase):},description=("One owning team's CI test activity: per-test current-vs-prior signal pairs (the before/after "- "comparison) over the window and its equal-length prior twin. Signal = failed + error + "- "pass-on-retry spans on the team's owned tests. " + FLAKY_TEST_SIGNAL_CAVEAT+ "comparison) over the window and its equal-length prior twin. Signal = runs where an owned "+ "test failed, errored, or a retry recovered it. " + FLAKY_TEST_SIGNAL_CAVEAT),)@action(detail=False, methods=["get"], pagination_class=None)diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.pyindex 74b0f6f7653c..67954708af26 100644--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py@@ -13,29 +13,31 @@ from products.engineering_analytics.backend.logic.queries._test_spans import selfrom products.engineering_analytics.backend.tests._github_fixtures import connect_github_source_without_datafrom products.warehouse_sources.backend.facade.models import ExternalDataSource-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_MATRIX_LEGS = "posthog/api/test/test_legs/TestLegs::test_fails_in_two_legs"+T_IN_JOB_RETRY = "posthog/api/test/test_injob/TestInJob::test_pytest_retry"+T_IN_JOB_SELECTOR = "posthog/api/test/test_injob.py::TestInJob::test_pytest_retry"+T_THREE_PRS = "posthog/api/test/test_three/TestThree::test_fails_on_three_prs"+T_TWO_PRS = "posthog/api/test/test_two/TestTwo::test_fails_on_two_prs"+T_MASTER = "posthog/api/test/test_master/TestMaster::test_breaks_trunk"+T_QUARANTINED = "posthog/api/test/test_quarantined/TestQuarantined::test_still_fails"T_OLD = "posthog/api/test/test_old/TestOld::test_old_flake"+T_NO_RUN_ID = "posthog/api/test/test_norun/TestNoRun::test_unstamped_spans"+T_TIE_A = "posthog/api/test/test_tie_a/TestTie::test_retry"+T_TIE_B = "posthog/api/test/test_tie_b/TestTie::test_retry"T_FOREIGN = "posthog/api/test/test_foreign/TestForeign::test_other_service"T_OTHER_REPO = "posthog/api/test/test_other_repo/TestOtherRepo::test_flaky"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.+ # regressions worth catching only surface against real seeded trace_spans rows.# 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):+ def setUpTestData(cls) -> None:super().setUpTestData()connect_github_source_without_data(cls.team, prefix="flaky", repository="PostHog/posthog")sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")@@ -44,44 +46,57 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):sync_execute(TRACE_SPANS_DISTRIBUTED_TABLE_SQL())now = datetime.now(UTC).replace(microsecond=0)- cls.recent = now - timedelta(days=1)+ 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): failed/error spans, one PR hit twice (dedup), two- # master failures with no PR (count as failures, not PRs, and drive master_failed_count),- # plus one xfail on master that must NOT count as a master failure.- 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(19, T_PRS, "failed", ts=earlier, branch="main"),- 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"),- # Would qualify on signal alone, but belongs to another connected repository.+ # One run fans a test across matrix legs, and two of them fail. One run, one failure.+ cls._span(5, T_MATRIX_LEGS, "failed", ts=earlier, run="250", branch="master"),+ cls._span(6, T_MATRIX_LEGS, "failed", ts=recent, run="250", branch="master"),+ # A third leg passed. Plain passes sit outside the scan fence, so a passing leg can never+ # be mistaken for the test recovering.+ cls._span(7, T_MATRIX_LEGS, "passed", ts=recent, run="250", branch="master"),+ # In-job pytest retry: the only proof of nondeterminism this telemetry carries, and it+ # reaches only tests hand-marked @pytest.mark.flaky(reruns=N). The emitter stamped+ # test.selector here, so it wins over the nodeid reconstruction.cls._span(- 18, T_OTHER_REPO, "rerun_passed", ts=cls.recent, pr="601", branch="r1", repo="PostHog/posthog.com"+ 10,+ T_IN_JOB_RETRY,+ "rerun_passed",+ ts=recent,+ run="400",+ pr="401",+ branch="f1",+ selector=T_IN_JOB_SELECTOR,),- # 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"),+ # Failures across 3 distinct PRs, no recovery: qualifies on blast radius alone.+ cls._span(11, T_THREE_PRS, "failed", ts=earlier, run="500", pr="501", branch="f1"),+ cls._span(12, T_THREE_PRS, "failed", ts=earlier, run="501", pr="502", branch="f2"),+ cls._span(13, T_THREE_PRS, "error", ts=recent, run="502", pr="503", branch="f3"),+ # Only 2 distinct PRs: below the default bar, reachable via min_failed_prs=2.+ cls._span(14, T_TWO_PRS, "failed", ts=recent, run="600", pr="601", branch="x1"),+ cls._span(15, T_TWO_PRS, "failed", ts=recent, run="601", pr="602", branch="x2"),+ # A master failure is actionable with no PR and no recovery.+ cls._span(16, T_MASTER, "failed", ts=recent, run="700", branch="master"),+ # xfail on master: quarantined, and never counted as a master failure.+ cls._span(17, T_QUARANTINED, "xfailed", ts=recent, run="800", branch="master"),+ # Signal outside the default window.+ cls._span(18, T_OLD, "rerun_passed", ts=old, run="900", pr="901", branch="old1"),+ # Two master failures whose spans carry no ci.run_id: the trace_id fallback keeps them+ # two distinct runs instead of merging every unstamped execution into one phantom run.+ cls._span(24, T_NO_RUN_ID, "failed", ts=recent, run="", branch="master"),+ cls._span(25, T_NO_RUN_ID, "failed", ts=recent, run="", branch="master"),+ # Identical evidence: nodeid is the deterministic final tiebreaker.+ cls._span(19, T_TIE_B, "rerun_passed", ts=recent, run="1000", pr="1001", branch="tie"),+ cls._span(20, T_TIE_A, "rerun_passed", ts=recent, run="1001", pr="1002", branch="tie"),+ # Would qualify on signal alone, but a non-CI service must never reach the queue.+ cls._span(21, T_FOREIGN, "rerun_passed", ts=recent, run="1100", pr="1101", service="other-service"),+ # Would qualify on signal alone, but belongs to another connected repository.+ cls._span(22, T_OTHER_REPO, "rerun_passed", ts=recent, run="1200", pr="1201", repo="PostHog/posthog.com"),+ # A job-root span carries no test.outcome and must never become a row.+ cls._span(23, "Backend CI / core (1)", None, ts=recent, run="1300", branch="master"),]sync_execute("INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "@@ -90,7 +105,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):)@classmethod- def tearDownClass(cls):+ def tearDownClass(cls) -> None:sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")sync_execute("DROP TABLE IF EXISTS trace_spans")sync_execute(TRACE_SPANS_TABLE_SQL())@@ -100,11 +115,12 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):@classmethoddef _span(cls,- i: int,+ index: int,name: str,outcome: str | None,*,ts: datetime,+ run: str = "",pr: str = "",branch: str = "",selector: str = "",@@ -119,13 +135,18 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):attrs = f"map({', '.join(attr_pairs)})" if attr_pairs else "map()"resource_pairs = [f"'{key}', '{value}'"- for key, value in (("ci.pr_number", pr), ("ci.branch", branch), ("ci.repository", repo))+ for key, value in (+ ("ci.run_id", run),+ ("ci.pr_number", pr),+ ("ci.branch", branch),+ ("ci.repository", repo),+ )if value]- resource = f"map({', '.join(resource_pairs)})" if resource_pairs else "map()"+ resource = f"map({', '.join(resource_pairs)})"stamp = ts.strftime("%Y-%m-%d %H:%M:%S")return (- f"('uuid-{i}', {cls.team.id}, 'trace-{i}', 'span-{i}', 'parent', '{name}', 1, "+ f"('uuid-{index}', {cls.team.id}, 'trace-{index}', 'span-{index}', 'parent', '{name}', 1, "f"'{stamp}', '{stamp}', '{stamp}', 0, '{service}', {attrs}, {resource})")@@ -134,62 +155,99 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.contentreturn response.json()- def test_default_window_qualifies_aggregates_and_ranks(self):+ def _rows(self, **params: str) -> dict[str, dict]:+ return {item["nodeid"]: item for item in self._get(**params)["items"]}++ def test_default_window_qualifies_only_actionable_tests(self) -> None: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, foreign-service row, and other-repo row are all excluded.- assert [item["nodeid"] for item in data["items"]] == [T_PRS, T_RERUN]+ # The 2-PR test is below the bar; the out-of-window, foreign-service, other-repo, and+ # outcome-less job-root spans must never qualify.+ assert {row["nodeid"] for row in data["items"]} == {+ T_MATRIX_LEGS,+ T_IN_JOB_RETRY,+ T_THREE_PRS,+ T_MASTER,+ T_QUARANTINED,+ T_TIE_A,+ T_TIE_B,+ T_NO_RUN_ID,+ }assert data["truncated"] is Falseassert 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, 6, 3)- assert (by_prs["branch_count"], by_prs["xfailed_count"]) == (5, 1)- # Only failed/error spans on master/main: the master error (5) and the main failure (19).- # The master xfail (6) is not a failure and doesn't count.- assert by_prs["master_failed_count"] == 2- # 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)- # T_RERUN's only master span (8) is a rerun_passed, not a failure — so no master failures.- assert by_rerun["master_failed_count"] == 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]),+ ("recovered_via_in_job_retry", T_IN_JOB_RETRY, "confirmed_flake"),+ # A passing leg alongside a failing one is not proof of anything.+ ("pass_in_another_matrix_leg", T_MATRIX_LEGS, "suspected_regression"),+ ("no_recovery_recorded", T_THREE_PRS, "suspected_regression"),+ ("failing_while_xfailed", T_QUARANTINED, "quarantined"),])- 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_source_without_repository_fails_closed(self):- # A source with no repository identity can't be scoped, so the leaderboard must be empty- # rather than leak every connected repository's flaky spans (the qualifying rows are still- # seeded, so a fail-open regression would return them).+ def test_classification_needs_proof_to_call_a_test_flaky(self, _name: str, nodeid: str, expected: str) -> None:+ assert self._rows()[nodeid]["classification"] == expected++ def test_evidence_is_counted_once_per_run(self) -> None:+ rows = self._rows()++ # Two failing matrix legs of one run: one run, one failure. Span-grain counting would say 2.+ legs = rows[T_MATRIX_LEGS]+ assert legs["failed_run_count"] == 1+ assert legs["master_failed_run_count"] == 1+ # The passing leg must not read as a recovery.+ assert legs["rerun_passed_run_count"] == 0++ recovered = rows[T_IN_JOB_RETRY]+ assert recovered["rerun_passed_run_count"] == 1+ assert recovered["selector"] == T_IN_JOB_SELECTOR++ three_prs = rows[T_THREE_PRS]+ assert (three_prs["failed_run_count"], three_prs["failed_pr_count"]) == (3, 3)+ # Falls back to the nodeid reconstruction: no emitted test.selector.+ assert three_prs["selector"] == "posthog/api/test/test_three.py::TestThree::test_fails_on_three_prs"++ master = rows[T_MASTER]+ assert (master["master_failed_run_count"], master["failed_pr_count"]) == (1, 0)++ # An xfail is not a failure, so it drives neither count.+ quarantined = rows[T_QUARANTINED]+ assert quarantined["quarantined_failed_run_count"] == 1+ assert (quarantined["failed_run_count"], quarantined["master_failed_run_count"]) == (0, 0)++ def test_ranking_leads_with_trunk_breakage_and_breaks_ties_on_nodeid(self) -> None:+ nodeids = [item["nodeid"] for item in self._get()["items"]]++ # Master failures outrank PR-only evidence however many PRs it hit.+ assert nodeids.index(T_MASTER) < nodeids.index(T_THREE_PRS)+ assert nodeids.index(T_TIE_A) < nodeids.index(T_TIE_B)++ def test_spans_without_run_id_stay_distinct_runs(self) -> None:+ no_run = self._rows()[T_NO_RUN_ID]+ # Without the trace_id fallback these two unstamped failures would merge into one+ # phantom run and halve the blast radius.+ assert (no_run["failed_run_count"], no_run["master_failed_run_count"]) == (2, 2)+ assert no_run["classification"] == "suspected_regression"++ def test_min_failed_prs_controls_the_no_recovery_threshold(self) -> None:+ assert T_TWO_PRS not in self._rows()+ assert T_TWO_PRS in self._rows(min_failed_prs="2")++ def test_wider_window_includes_older_signal(self) -> None:+ assert T_OLD in self._rows(date_from="-30d")++ def test_source_without_repository_fails_closed(self) -> None:+ # A source with no repository identity can't be scoped, so the queue must be empty rather+ # than leak every connected repository's spans (the qualifying rows are still seeded, so a+ # fail-open regression would return them).ExternalDataSource.objects.filter(team_id=self.team.id).update(job_inputs={})data = self._get()assert data["items"] == []assert data["truncated"] is False- def test_limit_caps_and_flags_truncation(self):+ def test_limit_caps_and_flags_truncation(self) -> None:data = self._get(limit="1")- assert [item["nodeid"] for item in data["items"]] == [T_PRS]+ assert len(data["items"]) == 1assert data["truncated"] is Trueassert data["limit"] == 1@@ -197,20 +255,19 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):[("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):+ def test_invalid_params_return_400(self, _name: str, params: dict) -> None: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.+# A wrong split yields a selector CI's quarantine matching would silently never hit. This is the+# fallback reconstruction for spans emitted before the CI reporter stamped test.selector.@pytest.mark.parametrize("nodeid,expected",[diff --git a/products/engineering_analytics/backend/tests/test_team_ci_health.py b/products/engineering_analytics/backend/tests/test_team_ci_health.pyindex f6bc435537b6..c108dc8c8f8d 100644--- a/products/engineering_analytics/backend/tests/test_team_ci_health.py+++ b/products/engineering_analytics/backend/tests/test_team_ci_health.py@@ -14,6 +14,7 @@ T_REPLAY_RERUN = "products/replay/backend/tests/test_playlist/TestPlaylist::testT_EXPORTS_RECOVERED = "products/batch_exports/backend/tests/test_snowflake/TestSnowflake::test_recovered"T_UNOWNED = "posthog/api/test/test_shared/TestShared::test_unowned"T_FOREIGN = "posthog/api/test/test_foreign/TestForeign::test_other_service"+T_RESTAMPED = "products/moved/backend/tests/test_moved/TestMoved::test_restamped"class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):@@ -43,25 +44,43 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):prior = now - timedelta(days=20)rows = [- # team-replay test 1 qualifies current via 3 distinct failed PRs (prior has only 1 PR,- # below the bar); one current xfail must count separately and stay out of slope signal.- cls._span(1, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", pr="101"),- cls._span(2, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", pr="102"),- cls._span(3, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", pr="103"),- cls._span(4, T_REPLAY_PRS, "xfailed", ts=cls.current_b, owner="team-replay"),- cls._span(5, T_REPLAY_PRS, "failed", ts=prior, owner="team-replay", pr="101"),- # team-replay test 2 qualifies in both windows via pass-on-retry.- cls._span(6, T_REPLAY_RERUN, "rerun_passed", ts=cls.current_b, owner="team-replay", pr="201"),- cls._span(7, T_REPLAY_RERUN, "rerun_passed", ts=prior, owner="team-replay", pr="202"),- cls._span(8, T_REPLAY_RERUN, "rerun_passed", ts=prior, owner="team-replay", pr="203"),- # batch-exports recovered: qualifies prior only (3 distinct PRs), zero current signal.- cls._span(9, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", pr="301"),- cls._span(10, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", pr="302"),- cls._span(11, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", pr="303"),+ # team-replay test 1: 3 distinct failed PRs current, no recovery, so a regression, not a+ # flake. Prior has 1 PR, below the bar. One current xfail counts separately and stays out+ # of the slope signal.+ cls._span(1, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", run="101", pr="101"),+ cls._span(2, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", run="102", pr="102"),+ cls._span(3, T_REPLAY_PRS, "failed", ts=cls.current_a, owner="team-replay", run="103", pr="103"),+ cls._span(4, T_REPLAY_PRS, "xfailed", ts=cls.current_b, owner="team-replay", run="104"),+ cls._span(5, T_REPLAY_PRS, "failed", ts=prior, owner="team-replay", run="105", pr="101"),+ # team-replay test 2 is a proven flake in both windows via in-job pass-on-retry.+ cls._span(6, T_REPLAY_RERUN, "rerun_passed", ts=cls.current_b, owner="team-replay", run="201", pr="201"),+ cls._span(7, T_REPLAY_RERUN, "rerun_passed", ts=prior, owner="team-replay", run="202", pr="202"),+ cls._span(8, T_REPLAY_RERUN, "rerun_passed", ts=prior, owner="team-replay", run="203", pr="203"),+ # batch-exports: unrecovered PR failures in the prior window, then an in-job retry recovers+ # it in the current one. The same test moves from regression to proven flake.+ cls._span(9, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", run="301", pr="301"),+ cls._span(10, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", run="302", pr="302"),+ cls._span(11, T_EXPORTS_RECOVERED, "failed", ts=prior, owner="batch-exports", run="303", pr="303"),+ cls._span(+ 14, T_EXPORTS_RECOVERED, "rerun_passed", ts=cls.current_a, owner="batch-exports", run="304", pr="304"+ ),+ # Ownership re-stamp: prior-window failure stamped team-old, current stamped team-new.+ # The latest stamp owns the whole test, in the roster and the drill-in alike.+ cls._span(15, T_RESTAMPED, "failed", ts=prior, owner="team-old", run="601", pr="601"),+ cls._span(16, T_RESTAMPED, "failed", ts=cls.current_b, owner="team-new", run="602", pr="602"),# No owner stamp: buckets under the literal 'unowned'.- cls._span(12, T_UNOWNED, "rerun_passed", ts=cls.current_b, owner="", pr="401"),+ cls._span(12, T_UNOWNED, "rerun_passed", ts=cls.current_b, owner="", run="401", pr="401"),# A non-CI service must never reach the roster (the scan is fenced by service_name).- cls._span(13, T_FOREIGN, "rerun_passed", ts=cls.current_b, owner="ghost-team", pr="501", service="other"),+ cls._span(+ 13,+ T_FOREIGN,+ "rerun_passed",+ ts=cls.current_b,+ owner="ghost-team",+ run="501",+ pr="501",+ service="other",+ ),]sync_execute("INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "@@ -86,13 +105,17 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):*,ts: datetime,owner: str,+ run: str,pr: str = "",service: str = "ci-backend",) -> str:attr_pairs = [f"'test.outcome__str', '{outcome}'"]if owner:attr_pairs.append(f"'test.owner_team__str', '{owner}'")- resource_pairs = [f"'ci.repository', 'PostHog/posthog'"]+ resource_pairs = [+ "'ci.repository', 'PostHog/posthog'",+ f"'ci.run_id', '{run}'",+ ]if pr:resource_pairs.append(f"'ci.pr_number', '{pr}'")stamp = ts.strftime("%Y-%m-%d %H:%M:%S")@@ -107,33 +130,47 @@ class TestTeamCIHealthAPI(ClickhouseTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OK, response.contentreturn response.json()- def test_roster_splits_windows_qualifies_and_buckets_unowned(self):- data = self._get("team_ci_health")+ def _roster(self) -> dict[str, dict]:+ return {item["owner_team"]: item for item in self._get("team_ci_health")["items"]}- assert [item["owner_team"] for item in data["items"]] == ["team-replay", "unowned", "batch-exports"]- replay, unowned, exports = data["items"]+ def test_roster_uses_the_same_flake_proof_as_the_queue(self):+ rows = self._roster()- # Current window: both replay tests qualify; prior: only the rerun test does.- assert replay["flaky_test_count"] == 2- assert replay["flaky_test_count_prior"] == 1- assert replay["failed_count"] == 3- assert replay["failed_count_prior"] == 1- assert replay["rerun_passed_count"] == 1- assert replay["rerun_passed_count_prior"] == 2- assert replay["xfailed_count"] == 1- assert replay["xfailed_count_prior"] == 0+ # Only the pass-on-retry test is proven flaky. The 3-PR test failed with no recovery, so it+ # is a regression here exactly as it is in the queue.+ replay = rows["team-replay"]+ assert (replay["flaky_test_count"], replay["regression_test_count"]) == (1, 1)+ assert (replay["flaky_test_count_prior"], replay["regression_test_count_prior"]) == (1, 0)+ assert (replay["failed_run_count"], replay["failed_run_count_prior"]) == (3, 1)+ assert (replay["rerun_passed_run_count"], replay["rerun_passed_run_count_prior"]) == (1, 2)+ assert (replay["quarantined_failed_run_count"], replay["quarantined_failed_run_count_prior"]) == (1, 0)- assert unowned["flaky_test_count"] == 1- assert unowned["rerun_passed_count"] == 1+ assert (rows["unowned"]["flaky_test_count"], rows["unowned"]["rerun_passed_run_count"]) == (1, 1)- # Recovered team: all signal in the prior window, none current.- assert exports["flaky_test_count"] == 0- assert exports["flaky_test_count_prior"] == 1- assert exports["failed_count"] == 0- assert exports["failed_count_prior"] == 3+ # An in-job retry recovered it, so it is current-window flaky; the prior window's 3+ # unrecovered PR failures are a regression, not a flake.+ exports = rows["batch-exports"]+ assert (exports["flaky_test_count"], exports["regression_test_count"]) == (1, 0)+ assert (exports["flaky_test_count_prior"], exports["regression_test_count_prior"]) == (0, 1)+ assert (exports["failed_run_count"], exports["failed_run_count_prior"]) == (0, 3)# The foreign-service span's team must not appear at all.- assert not data["truncated"]+ assert "ghost-team" not in rows++ def test_restamped_test_lands_under_its_latest_owner_in_roster_and_drill_in(self):+ rows = self._roster()++ # All evidence, prior window included, follows the latest stamp; the old team keeps nothing.+ assert "team-old" not in rows+ new = rows["team-new"]+ assert (new["failed_run_count"], new["failed_run_count_prior"]) == (1, 1)++ # The drill-in agrees with the summary that opened it.+ assert [+ (t["nodeid"], t["signal_count"], t["signal_count_prior"])+ for t in self._get("team_ci_activity", owner_team="team-new")["tests"]+ ] == [(T_RESTAMPED, 1, 1)]+ assert self._get("team_ci_activity", owner_team="team-old")["tests"] == []def test_activity_scopes_to_team_and_pairs_windows(self):data = self._get("team_ci_activity", owner_team="team-replay")diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 0dbb0463fa49..851edacb2b3b 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -167,31 +167,49 @@ export interface CurrentBranchHealthApi {failing_workflow_names: string[]}+/**+ * * `confirmed_flake` - CONFIRMED_FLAKE+ * * `suspected_regression` - SUSPECTED_REGRESSION+ * * `quarantined` - QUARANTINED+ */+export type FlakyTestItemClassificationEnumApi =+ (typeof FlakyTestItemClassificationEnumApi)[keyof typeof FlakyTestItemClassificationEnumApi]++export const FlakyTestItemClassificationEnumApi = {+ ConfirmedFlake: 'confirmed_flake',+ SuspectedRegression: 'suspected_regression',+ Quarantined: 'quarantined',+} as const+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). */+ /** confirmed_flake: an in-job retry recovered the test in the same run, so it is provably nondeterministic. quarantined: it fails while masked as xfail. suspected_regression: only failures were recorded, which is absence of proof, not proof that it is a real break.+ *+ * * `confirmed_flake` - CONFIRMED_FLAKE+ * * `suspected_regression` - SUSPECTED_REGRESSION+ * * `quarantined` - QUARANTINED */+ classification: FlakyTestItemClassificationEnumApi+ /** Runs where an in-job pytest retry recovered the test after it failed. Above zero is the only proof of flakiness this data carries, and it reaches only tests hand-marked @pytest.mark.flaky(reruns=N), since Backend CI runs without --reruns so failures stay visible. */+ rerun_passed_run_count: number+ /** Distinct CI runs whose recorded outcome was failed or error. A run counts once however many matrix legs it failed in. */+ failed_run_count: number+ /** Distinct pull requests among the failed runs. Failures on master or unattributed branches carry no PR number and are excluded here (still in failed_run_count). */failed_pr_count: number- /** Failed/error spans on the default branch (master/main approximation) — the 'matters right now' signal that a flake is breaking the trunk, not just PR branches. */- master_failed_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+ /** Failed runs on the default branch (master/main approximation): the 'matters right now' signal that a test is breaking the trunk, not just PR branches. */+ master_failed_run_count: number+ /** Runs where the test failed while quarantined (xfail): already masked in CI, still failing. */+ quarantined_failed_run_count: number+ /** Most recent failure, recovery, or xfail run for this test in the window. */+ last_signal_at: string}export interface FlakyTestListApi {- /** Qualifying tests ranked by flakiness signal, strongest first, capped at `limit`. */+ /** Tests worth acting on now, ranked by blast radius: master failures, then PRs hit, then runs. */items: FlakyTestItemApi[]- /** True when more tests qualified than the cap; `items` is the strongest `limit` rows. */+ /** True when more tests qualified than the cap; `items` is the highest-ranked `limit` rows. */truncated: boolean/** Maximum number of tests returned in `items`. */limit: number@@ -911,11 +929,11 @@ export interface TeamTestSignalApi {nodeid: string/** Runnable pytest selector; exact when the CI reporter emitted it. */selector: string- /** Failed + error + pass-on-retry spans in the current window (xfail excluded). */+ /** Runs in the current window where the test failed, errored, or a retry recovered it (xfail excluded). */signal_count: number/** Same count over the equal-length window before date_from. */signal_count_prior: number- /** Most recent signal span for this test, either window. */+ /** Most recent failure, recovery, or xfail run for this test, either window. */last_seen_at: string}@@ -931,23 +949,27 @@ export interface TeamCIActivityApi {export interface TeamCIHealthItemApi {/** Owning team slug (the CODEOWNERS handle minus '@PostHog/', e.g. 'team-replay'), or the literal 'unowned' for tests whose spans carry no ownership stamp. */owner_team: string- /** Owned tests meeting the flaky-leaderboard bar in the window (passed on retry or failed on enough distinct PRs). Compare with flaky_test_count_prior for the delta. */+ /** Owned tests an in-job retry recovered in the window: the same proof, and the same word, that flaky_tests calls a confirmed_flake. Compare with flaky_test_count_prior for the delta. */flaky_test_count: number/** Same count over the equal-length window immediately before date_from. */flaky_test_count_prior: number- /** Signal spans on owned tests with final outcome 'failed' or 'error' in the window. An absolute count, not a rate: fast passing runs are not emitted. */- failed_count: number+ /** Owned tests that failed with no recorded in-run recovery and still hit the blast-radius bar (a master/main failure, or min_failed_prs distinct PRs). Not flakes: absence of proof, not proof. */+ regression_test_count: number+ /** Same count over the prior window. */+ regression_test_count_prior: number+ /** CI runs (not spans) where an owned test's recorded outcome was failed or error. An absolute count, not a rate: fast passing runs are not emitted. */+ failed_run_count: number/** Same count over the prior window. */- failed_count_prior: number- /** Spans on owned tests that failed, then passed on an automatic retry, the strongest flaky signal. Only rerun-enabled CI lanes emit it. */- rerun_passed_count: number+ failed_run_count_prior: number+ /** Runs where an in-job pytest retry recovered an owned test after it failed. */+ rerun_passed_run_count: number/** Same count over the prior window. */- rerun_passed_count_prior: number- /** Spans on owned tests that failed while quarantined (xfail): masked in CI but still flaky. */- xfailed_count: number+ rerun_passed_run_count_prior: number+ /** Runs where an owned test failed while quarantined (xfail): masked in CI, still failing. */+ quarantined_failed_run_count: number/** Same count over the prior window. */- xfailed_count_prior: number- /** Most recent signal span across the team's owned tests, either window. */+ quarantined_failed_run_count_prior: number+ /** Most recent failure, recovery, or xfail run across the team's owned tests, either window. */last_seen_at: string}@@ -1200,13 +1222,9 @@ export type EngineeringAnalyticsFlakyTestsParams = {*/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.+ * A test with no recorded recovery qualifies once it failed on at least this many distinct pull requests in the window. 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/*** 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/@@ -1459,13 +1477,9 @@ export type EngineeringAnalyticsTeamCiHealthParams = {*/limit?: number/**- * A test counts as flaky 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.+ * An unrecovered test counts toward regression_test_count once it failed on at least this many distinct pull requests in the window. Minimum 1. Defaults to 3. Does not affect flaky_test_count, which needs proof, not a threshold.*/min_failed_prs?: number- /**- * A test counts as flaky 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.*/diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex eab456742c89..2edf7ae5ddcc 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -245,7 +245,7 @@ export const getEngineeringAnalyticsFlakyTestsUrl = (}/**- * 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.+ * The active test-health queue: backend tests worth acting on now, from the per-test CI spans, over a window (default -7d, maximum 30 days). Evidence is counted per CI run, never per span. A test is a 'confirmed_flake' when an in-job retry recovered it in the same run; 'quarantined' when it fails while masked as xfail; otherwise 'suspected_regression'. It qualifies on any recovery, any master/main failure, an xfail, or failures on at least min_failed_prs distinct PRs. Counts are absolute, never rates: CI emits a span for every failure but only for passes slow enough to clear the emitter's duration threshold, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.*/export const engineeringAnalyticsFlakyTests = async (projectId: string,@@ -674,7 +674,7 @@ export const getEngineeringAnalyticsTeamCiActivityUrl = (}/**- * One owning team's CI test activity: per-test current-vs-prior signal pairs (the before/after comparison) over the window and its equal-length prior twin. Signal = failed + error + pass-on-retry spans on the team's owned tests. 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.+ * One owning team's CI test activity: per-test current-vs-prior signal pairs (the before/after comparison) over the window and its equal-length prior twin. Signal = runs where an owned test failed, errored, or a retry recovered it. Counts are absolute, never rates: CI emits a span for every failure but only for passes slow enough to clear the emitter's duration threshold, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.*/export const engineeringAnalyticsTeamCiActivity = async (projectId: string,@@ -707,7 +707,7 @@ export const getEngineeringAnalyticsTeamCiHealthUrl = (}/**- * Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and pass-on-retry span counts, each with an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*\/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team 'unowned'. Teams are organizational owners of code surfaces, never authors. 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.+ * Per-owning-team rollup of the CI test surfaces each team owns, over the same run evidence as flaky_tests and with the same meaning of flaky: flaky_test_count is owned tests an in-job retry recovered in the window, regression_test_count is owned tests that failed with no such proof and still hit the blast-radius bar, plus failed/recovery/quarantined run counts. Each has an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*\/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Counts are absolute, never rates: CI emits a span for every failure but only for passes slow enough to clear the emitter's duration threshold, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.*/export const engineeringAnalyticsTeamCiHealth = async (projectId: string,diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsxindex 19a401c89e72..3c96628cee59 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTeams.tsx@@ -67,28 +67,42 @@ export function EngineeringAnalyticsTeams(): JSX.Element {width: 140,align: 'right',tooltip:- 'Owned tests meeting the flaky-leaderboard bar in this window (passed on retry, or failed across several distinct PRs), vs the previous window.',+ 'Owned tests an in-job retry recovered in this window, vs the previous one. Only tests with that recovery proof count as flaky.',sorter: (a, b) => a.flakyTestCount - b.flakyTestCount,render: (_, row) => <CountWithDelta current={row.flakyTestCount} prior={row.flakyTestCountPrior} />,},{- title: 'Failures',- key: 'failedCount',+ title: 'Regressions',+ key: 'regressionTestCount',+ width: 140,+ align: 'right',+ tooltip:+ 'Owned tests that failed with no recorded recovery and still hit several PRs or master. Treat as real breaks until a recovery proves otherwise.',+ sorter: (a, b) => a.regressionTestCount - b.regressionTestCount,+ render: (_, row) => (+ <CountWithDelta current={row.regressionTestCount} prior={row.regressionTestCountPrior} />+ ),+ },+ {+ title: 'Failed runs',+ key: 'failedRunCount',width: 130,align: 'right',tooltip:- 'Failed or errored runs on owned tests. Absolute counts, not rates: passing runs are mostly not recorded.',- sorter: (a, b) => a.failedCount - b.failedCount,- render: (_, row) => <CountWithDelta current={row.failedCount} prior={row.failedCountPrior} />,+ 'CI runs where an owned test failed or errored. Absolute counts, not rates: passing runs are mostly not recorded.',+ sorter: (a, b) => a.failedRunCount - b.failedRunCount,+ render: (_, row) => <CountWithDelta current={row.failedRunCount} prior={row.failedRunCountPrior} />,},{- title: 'Pass on retry',- key: 'rerunPassedCount',+ title: 'Recoveries',+ key: 'rerunPassedRunCount',width: 130,align: 'right',- tooltip: 'Failed, then passed on an automatic retry. The strongest flaky signal.',- sorter: (a, b) => a.rerunPassedCount - b.rerunPassedCount,- render: (_, row) => <CountWithDelta current={row.rerunPassedCount} prior={row.rerunPassedCountPrior} />,+ tooltip: 'Runs where an in-job retry recovered an owned test after it failed. This is what proves a flake.',+ sorter: (a, b) => a.rerunPassedRunCount - b.rerunPassedRunCount,+ render: (_, row) => (+ <CountWithDelta current={row.rerunPassedRunCount} prior={row.rerunPassedRunCountPrior} />+ ),},]diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsxindex 111e5bc024a0..fccd466d65f5 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx@@ -21,46 +21,46 @@ const FLAKY_TESTS: FlakyTestListApi = {{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,+ classification: 'confirmed_flake',+ rerun_passed_run_count: 6,+ failed_run_count: 8,failed_pr_count: 3,- master_failed_count: 2,- branch_count: 5,- xfailed_count: 0,- last_seen_at: '2026-07-01T18:30:00Z',+ master_failed_run_count: 2,+ quarantined_failed_run_count: 0,+ last_signal_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,+ classification: 'suspected_regression',+ rerun_passed_run_count: 0,+ failed_run_count: 9,failed_pr_count: 4,- master_failed_count: 5,- branch_count: 4,- xfailed_count: 0,- last_seen_at: '2026-07-01T09:12:00Z',+ master_failed_run_count: 5,+ quarantined_failed_run_count: 0,+ last_signal_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,+ classification: 'quarantined',+ rerun_passed_run_count: 0,+ failed_run_count: 1,failed_pr_count: 1,- master_failed_count: 0,- branch_count: 3,- xfailed_count: 3,- last_seen_at: '2026-06-30T22:45:00Z',+ master_failed_run_count: 0,+ quarantined_failed_run_count: 3,+ last_signal_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,- master_failed_count: 1,- branch_count: 2,- xfailed_count: 0,- last_seen_at: '2026-06-29T14:00:00Z',+ classification: 'confirmed_flake',+ rerun_passed_run_count: 1,+ failed_run_count: 1,+ failed_pr_count: 1,+ master_failed_run_count: 0,+ quarantined_failed_run_count: 0,+ last_signal_at: '2026-06-29T14:00:00Z',},],truncated: false,@@ -175,7 +175,7 @@ const meta: Meta = {mockDate: '2026-07-02',featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],testOptions: {- // A per-row quarantine button only renders once the leaderboard has data rows.+ // A per-row quarantine button only renders once the queue has data rows.waitForSelector: '[data-attr="eng-analytics-flaky-quarantine"]',},},diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsxindex 2d033e502b73..c5c37622dc84 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx@@ -15,6 +15,7 @@ import {LemonTable,LemonTableColumns,LemonTag,+ LemonTagType,Link,Tooltip,} from '@posthog/lemon-ui'@@ -32,6 +33,7 @@ import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'import { StatCard } from '../components/StatCard'import {BrokenTestRow,+ FlakyTestClassification,FlakyTestRow,FlakyTestWindow,QuarantineEntryRow,@@ -340,7 +342,27 @@ function BrokenTestsPanel(): JSX.Element {)}-function FlakyTestLeaderboard(): JSX.Element {+const FLAKY_CLASSIFICATION: Record<FlakyTestClassification, { label: string; type: LemonTagType; tooltip: string }> = {+ confirmed_flake: {+ label: 'Confirmed flake',+ type: 'warning',+ tooltip:+ 'A retry recovered this test in the same run, so the failure is nondeterministic. Fix it, or quarantine it while you do.',+ },+ suspected_regression: {+ label: 'Suspected regression',+ type: 'danger',+ tooltip:+ 'Only failures recorded, so nothing here proves the test is flaky. Treat it as a real break until a recovery proves otherwise.',+ },+ quarantined: {+ label: 'Quarantined, still failing',+ type: 'muted',+ tooltip: 'Already masked as xfail in CI and still failing. Fix it, then remove the quarantine.',+ },+}++function ActiveTestHealthQueue(): JSX.Element {const { flakyTests, flakyTestsLoading, flakyTestsStatus, flakyTestWindow } = useValues(engineeringAnalyticsLogic)const { setFlakyTestWindow, openQuarantineModal } = useActions(engineeringAnalyticsLogic)@@ -349,113 +371,93 @@ function FlakyTestLeaderboard(): JSX.Element {title: 'Test',key: 'nodeid',width: 360,- render: (_, row) => (- <div className="flex max-w-[22rem] flex-col gap-0.5">- <Tooltip title={row.nodeid}>- <span className="truncate font-mono text-xs">{row.nodeid}</span>- </Tooltip>- {row.xfailedCount > 0 && (+ render: (_, row) => {+ const { label, type, tooltip } = FLAKY_CLASSIFICATION[row.classification]+ return (+ <div className="flex max-w-[22rem] flex-col gap-0.5">+ <Tooltip title={row.nodeid}>+ <span className="truncate font-mono text-xs">{row.nodeid}</span>+ </Tooltip><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+ <Tooltip title={tooltip}>+ <LemonTag type={type} size="small">+ {label}</LemonTag></Tooltip></div>+ </div>+ )+ },+ },+ {+ title: 'Evidence',+ key: 'failedRunCount',+ tooltip: 'Absolute counts, never a rate: fast passing runs are not recorded, so there is no denominator.',+ sorter: (a, b) => a.failedRunCount - b.failedRunCount,+ render: (_, row) => (+ <div className="flex flex-col gap-0.5 text-xs">+ {row.failedRunCount > 0 && (+ <span>+ {pluralize(row.failedRunCount, 'failed run')} · {pluralize(row.failedPrCount, 'PR')}+ </span>+ )}+ {row.quarantinedFailedRunCount > 0 && (+ <span>Failed in {pluralize(row.quarantinedFailedRunCount, 'quarantined run')} (xfail)</span>+ )}+ {/* An xfail row has no recovery question to answer: it is masked, not racing. */}+ {row.classification !== 'quarantined' && (+ <span className="text-secondary">+ {row.rerunPassedRunCount > 0+ ? `A retry recovered it in ${pluralize(row.rerunPassedRunCount, 'run')}`+ : 'No recovery recorded'}+ </span>+ )}+ {row.masterFailedRunCount > 0 && (+ <span className="font-semibold text-danger">+ {pluralize(row.masterFailedRunCount, 'master failure')}+ </span>)}</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: 'Master failures',- key: 'masterFailedCount',- width: 130,- align: 'right',- tooltip:- 'Failed or errored on the default branch (master/main) — the flake is breaking the trunk, not just PR branches.',- sorter: (a, b) => a.masterFailedCount - b.masterFailedCount,- render: (_, row) =>- row.masterFailedCount > 0 ? (- <span className="tabular-nums font-semibold text-danger">- {humanFriendlyNumber(row.masterFailedCount)}- </span>- ) : (- <span className="tabular-nums text-tertiary">0</span>- ),- },- {- title: 'Last seen',- key: 'lastSeenAt',+ title: 'Last signal',+ key: 'lastSignalAt',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>- ),+ sorter: (a, b) => a.lastSignalAt.localeCompare(b.lastSignalAt),+ render: (_, row) => <RelativeTime iso={row.lastSignalAt} />,},{title: '',key: 'actions',width: 130,align: 'right',- render: (_, row) => (- <LemonButton- size="small"- type="tertiary"- icon={<IconShieldLock />}- tooltip="Review the evidence and owner before opening a tracking issue and quarantine PR."- aria-label={`Quarantine ${row.nodeid}`}- 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>- ),+ render: (_, row) =>+ row.classification === 'confirmed_flake' ? (+ <LemonButton+ size="small"+ type="tertiary"+ icon={<IconShieldLock />}+ tooltip="Review the evidence and owner before opening a tracking issue and quarantine PR."+ aria-label={`Quarantine ${row.nodeid}`}+ 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>+ ) : null,},]@@ -463,10 +465,10 @@ function FlakyTestLeaderboard(): JSX.Element {<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>+ <h3 className="m-0 text-base font-semibold">Active test health queue</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.+ Backend tests worth acting on now, ranked by blast radius: how many PRs they broke and how often+ they broke master.</p></div><LemonSegmentedButton@@ -493,12 +495,12 @@ function FlakyTestLeaderboard(): JSX.Element {loading={flakyTestsLoading}pagination={{ pageSize: 10 }}useURLForSorting={false}- emptyState="No flaky tests detected in this window."- nouns={['flaky test', 'flaky tests']}+ emptyState="No tests need attention in this window."+ nouns={['test', 'tests']}/>{flakyTests?.truncated && (<div className="text-xs text-tertiary">- Showing the {flakyTests.limit} strongest signals — more tests qualified in this window.+ Showing the top {flakyTests.limit} by blast radius. More tests qualified in this window.</div>)}</>@@ -522,9 +524,9 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {{/* Tab-level: both sections read the same source, so the picker scopes them together. */}<ScopeBar repoSlot={<SourceScopeChip />} showDate={false} /><BrokenTestsPanel />- <FlakyTestLeaderboard />+ <ActiveTestHealthQueue /><QuarantineRegister />- {/* Rendered once for the whole tab: the leaderboard rows, the register rows, and the+ {/* Rendered once for the whole tab: the queue rows, the register rows, and theregister's no-file empty state all open it. */}<QuarantineTestModalmodal={quarantineModal}diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex 5be45d3ae537..dde1624e0611 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -34,6 +34,7 @@ import {} from '../generated/api'import type {BrokenTestRowApi,+ FlakyTestItemClassificationEnumApi,GitHubSourceApi,PullRequestListItemApi,PushCISampleApi,@@ -53,7 +54,7 @@ export const PR_TABLE_LIMIT = 1000// Mirrors `workflow_health.py` `_LIMIT` (top workflows by run count).export const WORKFLOW_HEALTH_LIMIT = 100-// Mirrors the endpoint's maximum so the UI can paginate every returned leaderboard row.+// Mirrors the endpoint's maximum so the UI can paginate every returned queue row.export const FLAKY_TEST_LIMIT = 200const projectId = (): string => String(ApiConfig.getCurrentProjectId())@@ -443,31 +444,29 @@ export function quarantineCountsOf(rows: QuarantineEntryRow[]): QuarantineCountsreturn { ...counts, pastExpiry: counts.inGrace + counts.overdue }}-/** Leaderboard windows the UI offers; the endpoint accepts any window up to 30 days. */+/** Test-health 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 type FlakyTestClassification = FlakyTestItemClassificationEnumApiexport interface FlakyTestRow {- /** Reconstructed pytest nodeid (the CI span name) — a stable grouping/display key. */+ /** 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. */+ classification: FlakyTestClassification+ /** Runs where an in-job retry recovered the test after failing: the only proof of flakiness here. */+ rerunPassedRunCount: number+ failedRunCount: numberfailedPrCount: number- /** Failed/error spans on the default branch (master/main) — the "matters right now" signal. */- masterFailedCount: number- /** Failed while quarantined (xfail) — already masked in CI, still flaky. */- xfailedCount: number- lastSeenAt: string+ masterFailedRunCount: number+ quarantinedFailedRunCount: number+ lastSignalAt: string}export interface FlakyTestsData {rows: FlakyTestRow[]- /** True when more tests qualified than the cap; rows are the strongest `limit`. */+ /** True when more tests qualified than the cap; rows are the highest-ranked `limit`. */truncated: booleanlimit: number}@@ -551,29 +550,28 @@ export interface QuarantineModalState {owner: stringissue: stringmode: QuarantineMode- /** Glanceable confirm presentation for prefilled openers (leaderboard rows); 'Edit details' switches to the form. */+ /** Glanceable confirm presentation for prefilled openers (queue rows); 'Edit details' switches to the form. */confirm?: boolean}-/** Data-backed quarantine reason from a leaderboard row — the evidence is the reason; the+/** Data-backed quarantine reason from a queue 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.rerunPassedRunCount > 0) {+ parts.push(`recovered on retry in ${pluralize(row.rerunPassedRunCount, 'run')}`)}- if (row.failedCount > 0) {- parts.push(- row.failedPrCount > 0- ? `failed ${row.failedCount}x across ${pluralize(row.failedPrCount, 'PR')}`- : `failed ${row.failedCount}x`- )+ if (row.failedRunCount > 0) {+ parts.push(`failed in ${pluralize(row.failedRunCount, 'run')}`)}- if (row.xfailedCount > 0) {- parts.push(`failed while quarantined ${row.xfailedCount}x`)+ if (row.failedPrCount > 0) {+ parts.push(`hit ${pluralize(row.failedPrCount, 'PR')}`)}- return `Flaky in CI: ${parts.join(', ')} in the last ${windowLabel}`+ if (row.masterFailedRunCount > 0) {+ parts.push(`broke master in ${pluralize(row.masterFailedRunCount, 'run')}`)+ }+ return `CI evidence: ${parts.join(', ')} in the last ${windowLabel}`}/** Suggest an owning team from a product-scoped selector; '' when the selector isn't product-scoped. */@@ -1184,12 +1182,13 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy(it): FlakyTestRow => ({nodeid: it.nodeid,selector: it.selector,- rerunPassedCount: it.rerun_passed_count,- failedCount: it.failed_count,+ classification: it.classification,+ rerunPassedRunCount: it.rerun_passed_run_count,+ failedRunCount: it.failed_run_count,failedPrCount: it.failed_pr_count,- masterFailedCount: it.master_failed_count,- xfailedCount: it.xfailed_count,- lastSeenAt: it.last_seen_at,+ masterFailedRunCount: it.master_failed_run_count,+ quarantinedFailedRunCount: it.quarantined_failed_run_count,+ lastSignalAt: it.last_signal_at,})),truncated: data.truncated,@@ -1373,7 +1372,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyloadQuarantineFailure: () => true,},],- // Leaderboard window; transient like the other lenses (no persisted UI in this phase).+ // Test-health window; transient like the other lenses (no persisted UI in this phase).flakyTestWindow: [DEFAULT_FLAKY_TEST_WINDOW as FlakyTestWindow,{ setFlakyTestWindow: (_, { window }) => window },@@ -1381,7 +1380,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy// Prototype panel hides the low-signal PR-only failures by default.showPrOnlyBrokenTests: [false, { setShowPrOnlyBrokenTests: (_, { show }) => show }],// 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.+ // "connect a source" gate; only a real 'error' surfaces the queue's own banner.flakyTestsStatus: ['ok' as LoaderStatus,{diff --git a/products/engineering_analytics/frontend/scenes/teamsLogic.ts b/products/engineering_analytics/frontend/scenes/teamsLogic.tsindex a4bba8474ce6..edfabf13dc98 100644--- a/products/engineering_analytics/frontend/scenes/teamsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/teamsLogic.ts@@ -31,12 +31,16 @@ export const UNOWNED_TEAM = 'unowned'export interface TeamCIHealthRow {ownerTeam: string+ /** Owned tests an in-job retry recovered in the window: the queue's `confirmed_flake`. */flakyTestCount: numberflakyTestCountPrior: number- failedCount: number- failedCountPrior: number- rerunPassedCount: number- rerunPassedCountPrior: number+ /** Owned tests that failed with no such proof and still hit the blast-radius bar. */+ regressionTestCount: number+ regressionTestCountPrior: number+ failedRunCount: number+ failedRunCountPrior: number+ rerunPassedRunCount: number+ rerunPassedRunCountPrior: number}export interface TeamsData {@@ -107,10 +111,12 @@ export const teamsLogic = kea<teamsLogicType>([ownerTeam: it.owner_team,flakyTestCount: it.flaky_test_count,flakyTestCountPrior: it.flaky_test_count_prior,- failedCount: it.failed_count,- failedCountPrior: it.failed_count_prior,- rerunPassedCount: it.rerun_passed_count,- rerunPassedCountPrior: it.rerun_passed_count_prior,+ regressionTestCount: it.regression_test_count,+ regressionTestCountPrior: it.regression_test_count_prior,+ failedRunCount: it.failed_run_count,+ failedRunCountPrior: it.failed_run_count_prior,+ rerunPassedRunCount: it.rerun_passed_run_count,+ rerunPassedRunCountPrior: it.rerun_passed_run_count_prior,})),truncated: data.truncated,diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex e5cfa48fa621..acdf3e4f42d1 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -25,9 +25,9 @@ tools:description: >Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalizederror signature) and classified by how each is behaving right now, most urgent first. Reach for this to- answer "what CI failures should I care about right now" — it is the triage counterpart to the flaky-test- leaderboard (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing- on the default branch and that job's latest run is still red — trunk is broken now), novel_burst (first seen+ answer "what CI failures should I care about right now": it is the triage counterpart to the test-health+ queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on+ the default branch and that job's latest run is still red, so trunk is broken now), novel_burst (first seenwithin a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk butthat job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only(confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs@@ -73,17 +73,20 @@ tools:destructive: falseidempotent: truelist: true- title: Flaky test leaderboard+ title: Active test health queuedescription: >- 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.+ Backend tests worth acting on now, from the per-test CI spans over a window (date_from default -7d, maximum+ 30 days), ranked by blast radius: master failures first, then how many distinct PRs the test broke. Use this+ for "what is this failing test costing us" and to pick quarantine candidates. It does not measure flake+ rates, and this data only sees Backend CI. Evidence is counted per CI run, never per span, because one run+ fans a test across matrix legs. classification is confirmed_flake only when an in-job pytest retry recovered+ the test in the same run (rerun_passed_run_count > 0), which is the only proof of flakiness here and reaches+ only tests hand-marked @pytest.mark.flaky(reruns=N). quarantined means the test fails while masked as xfail.+ suspected_regression means only failures were recorded, which is absence of proof, not proof of a real+ break: treat it as real until a recovery proves otherwise. A test qualifies on any recovery, any master/main+ failure, an xfail, or failures on at least min_failed_prs distinct PRs (default 3). Counts are absolute,+ never rates, because fast passing runs are not emitted. Use selector to run or quarantine the test; nodeid+ is only the stable grouping key.feature_flag: engineering-analyticsengineering-analytics-job-aggregates:operation: engineering_analytics_job_aggregates@@ -190,14 +193,18 @@ tools:title: Team CI health rosterdescription: >Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d,- maximum 30 days): flaky-test count (same qualification bar as the flaky-test leaderboard), failed/error span- count, and pass-on-retry count, each with an equal-length previous-window twin (*_prior) for honest deltas.- Use this for "which team owns the flakiest surfaces right now" and to route a flaky-test or CI Signal to its- owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map- (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a- nonempty 'unowned' row means ownership gaps, not a real team). Teams are organizational owners of code- surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted,- so there is no honest denominator.+ maximum 30 days). It reads the same per-run evidence as engineering-analytics-flaky-tests and means the same+ thing by flaky: flaky_test_count is owned tests an in-job retry recovered in the window (the only flake+ proof this data carries), regression_test_count is owned tests that failed with no such proof and still hit+ min_failed_prs distinct PRs or master, and failed_run_count / rerun_passed_run_count /+ quarantined_failed_run_count are run counts. Each has an equal-length previous-window twin (*_prior) for+ honest deltas. Use this for "which team owns the flakiest surfaces right now" and to route a flaky-test or+ CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's+ ownership map (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team+ 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team), and a re-stamped test lands+ under its latest owner only. Teams are organizational owners of code surfaces, never authors. Read all+ counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest+ denominator.feature_flag: engineering-analyticsengineering-analytics-team-merge-trend:operation: engineering_analytics_team_merge_trenddiff --git a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.mdindex 9f07c41b58e1..44ac8ad468b0 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@@ -37,13 +37,16 @@ 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/finishedpair **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.+- **`engineering-analytics-flaky-tests`** — the active test-health queue from the per-test CI spans, over a+ window (`date_from` default `-7d`, max 30 days). Evidence is counted per CI run, never per span. `classification`+ is `confirmed_flake` only where the evidence proves nondeterminism (`rerun_passed_run_count > 0`, an+ in-job retry recovered it); `quarantined` means failing while masked as xfail; `suspected_regression` means only+ failures were recorded, which is absence of proof, not proof of a real break. A test qualifies on any recovery,+ an xfail, any master/main failure, or failures on ≥ `min_failed_prs` distinct PRs (`failed_pr_count`). Answers+ "what is this failing test costing us" and picks quarantine candidates. **It does not answer "which tests are+ flaky"**: this queue only sees Backend CI and only proves a flake for tests hand-marked+ `@pytest.mark.flaky(reruns=N)`. 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/failingcounts, the merge-time percentiles).@@ -78,7 +81,7 @@ These are structural limits of today's snapshot data — state them, don't paper| 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. |+| What is a failing test costing us? What to quarantine? | `engineering-analytics-flaky-tests` | Default window is `-7d`; rows are already ranked by blast radius (master failures, then distinct PRs hit). Report counts, never rates. For "is it flaky": only `confirmed_flake` rows are proven, and only for tests hand-marked with reruns. |## The high-value chaindiff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex eaa40a97ff98..6e8ba9b5d2af 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1365,9 +1365,10 @@ export interface _LogsPatternsDiffRequestApi {* * `gone` - gone* * `unchanged` - unchanged*/-export type ClassificationEnumApi = (typeof ClassificationEnumApi)[keyof typeof ClassificationEnumApi]+export type _LogPatternDiffEntryClassificationEnumApi =+ (typeof _LogPatternDiffEntryClassificationEnumApi)[keyof typeof _LogPatternDiffEntryClassificationEnumApi]-export const ClassificationEnumApi = {+export const _LogPatternDiffEntryClassificationEnumApi = {New: 'new',RateShift: 'rate_shift',Gone: 'gone',@@ -1381,7 +1382,7 @@ export interface _LogPatternDiffEntryApi {* * `rate_shift` - rate_shift* * `gone` - gone* * `unchanged` - unchanged */- classification: ClassificationEnumApi+ classification: _LogPatternDiffEntryClassificationEnumApi/*** Current-window rate divided by baseline rate, both normalized per second so windows of different lengths compare fairly. 4.0 means 4x faster now; 0.25 means quartered. Null when the pattern is missing from either window.* @nullablediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f93383518fbf..18dc624e2072 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3116,7 +3116,7 @@}},"engineering-analytics-broken-tests": {- "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\" — it is the triage counterpart to the flaky-test leaderboard (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red — trunk is broken now), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).",+ "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\": it is the triage counterpart to the test-health queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red, so trunk is broken now), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).","category": "Engineering analytics","feature": "engineering_analytics","summary": "Broken tests triage",@@ -3146,11 +3146,11 @@"feature_flag": "engineering-analytics"},"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.",+ "description": "Backend tests worth acting on now, from the per-test CI spans over a window (date_from default -7d, maximum 30 days), ranked by blast radius: master failures first, then how many distinct PRs the test broke. Use this for \"what is this failing test costing us\" and to pick quarantine candidates. It does not measure flake rates, and this data only sees Backend CI. Evidence is counted per CI run, never per span, because one run fans a test across matrix legs. classification is confirmed_flake only when an in-job pytest retry recovered the test in the same run (rerun_passed_run_count > 0), which is the only proof of flakiness here and reaches only tests hand-marked @pytest.mark.flaky(reruns=N). quarantined means the test fails while masked as xfail. suspected_regression means only failures were recorded, which is absence of proof, not proof of a real break: treat it as real until a recovery proves otherwise. A test qualifies on any recovery, any master/main failure, an xfail, or failures on at least min_failed_prs distinct PRs (default 3). Counts are absolute, never rates, because fast passing runs are not emitted. Use selector to run or quarantine the test; nodeid is only the stable grouping key.","category": "Engineering analytics","feature": "engineering_analytics",- "summary": "Flaky test leaderboard",- "title": "Flaky test leaderboard",+ "summary": "Active test health queue",+ "title": "Active test health queue","required_scopes": ["engineering_analytics:read"],"annotations": {"destructiveHint": false,@@ -3206,7 +3206,7 @@"feature_flag": "engineering-analytics"},"engineering-analytics-team-ci-health": {- "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days): flaky-test count (same qualification bar as the flaky-test leaderboard), failed/error span count, and pass-on-retry count, each with an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team). Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.",+ "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days). It reads the same per-run evidence as engineering-analytics-flaky-tests and means the same thing by flaky: flaky_test_count is owned tests an in-job retry recovered in the window (the only flake proof this data carries), regression_test_count is owned tests that failed with no such proof and still hit min_failed_prs distinct PRs or master, and failed_run_count / rerun_passed_run_count / quarantined_failed_run_count are run counts. Each has an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team), and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.","category": "Engineering analytics","feature": "engineering_analytics","summary": "Team CI health roster",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex cc496bfff22c..217faeaa0487 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3159,7 +3159,7 @@}},"engineering-analytics-broken-tests": {- "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\" — it is the triage counterpart to the flaky-test leaderboard (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red — trunk is broken now), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).",+ "description": "Live CI failures over the last 2 days, grouped into distinct failures (by failing test id + a normalized error signature) and classified by how each is behaving right now, most urgent first. Reach for this to answer \"what CI failures should I care about right now\": it is the triage counterpart to the test-health queue (which ranks week-long unreliability). Each row's state is the verdict: breaking_master (failing on the default branch and that job's latest run is still red, so trunk is broken now), novel_burst (first seen within a day and already spreading across branches, not on trunk yet), potentially_resolved (hit trunk but that job is green again), flaky (sporadic across two or more branches over more than a day), or pr_only (confined to one branch — one PR's own problem). Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Pass a row's latest_run_id to run-failure-logs to read the actual failing lines. Caveats: fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and the breaking/resolved distinction needs the job-level source synced — without it those failures fall through to flaky/pr_only rather than being misreported. Counts are absolute, never rates (passing runs aren't in this data).","category": "Engineering analytics","feature": "engineering_analytics","summary": "Broken tests triage",@@ -3189,11 +3189,11 @@"feature_flag": "engineering-analytics"},"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.",+ "description": "Backend tests worth acting on now, from the per-test CI spans over a window (date_from default -7d, maximum 30 days), ranked by blast radius: master failures first, then how many distinct PRs the test broke. Use this for \"what is this failing test costing us\" and to pick quarantine candidates. It does not measure flake rates, and this data only sees Backend CI. Evidence is counted per CI run, never per span, because one run fans a test across matrix legs. classification is confirmed_flake only when an in-job pytest retry recovered the test in the same run (rerun_passed_run_count > 0), which is the only proof of flakiness here and reaches only tests hand-marked @pytest.mark.flaky(reruns=N). quarantined means the test fails while masked as xfail. suspected_regression means only failures were recorded, which is absence of proof, not proof of a real break: treat it as real until a recovery proves otherwise. A test qualifies on any recovery, any master/main failure, an xfail, or failures on at least min_failed_prs distinct PRs (default 3). Counts are absolute, never rates, because fast passing runs are not emitted. Use selector to run or quarantine the test; nodeid is only the stable grouping key.","category": "Engineering analytics","feature": "engineering_analytics",- "summary": "Flaky test leaderboard",- "title": "Flaky test leaderboard",+ "summary": "Active test health queue",+ "title": "Active test health queue","required_scopes": ["engineering_analytics:read"],"annotations": {"destructiveHint": false,@@ -3249,7 +3249,7 @@"feature_flag": "engineering-analytics"},"engineering-analytics-team-ci-health": {- "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days): flaky-test count (same qualification bar as the flaky-test leaderboard), failed/error span count, and pass-on-retry count, each with an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team). Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.",+ "description": "Per-owning-team rollup of the CI test surfaces each team owns, over a window (date_from default -14d, maximum 30 days). It reads the same per-run evidence as engineering-analytics-flaky-tests and means the same thing by flaky: flaky_test_count is owned tests an in-job retry recovered in the window (the only flake proof this data carries), regression_test_count is owned tests that failed with no such proof and still hit min_failed_prs distinct PRs or master, and failed_run_count / rerun_passed_run_count / quarantined_failed_run_count are run counts. Each has an equal-length previous-window twin (*_prior) for honest deltas. Use this for \"which team owns the flakiest surfaces right now\" and to route a flaky-test or CI Signal to its owning team. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*/product.yaml + CODEOWNERS); spans without a stamp aggregate under the literal team 'unowned' (a nonempty 'unowned' row means ownership gaps, not a real team), and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Read all counts as absolute signal, never rates: fast passing runs are not emitted, so there is no honest denominator.","category": "Engineering analytics","feature": "engineering_analytics","summary": "Team CI health roster",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a183f05a5290..837d5fc980c6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -14373,22 +14373,6 @@ export namespace Schemas {available: boolean;}- /**- * * `new` - new- * * `rate_shift` - rate_shift- * * `gone` - gone- * * `unchanged` - unchanged- */- export type ClassificationEnum = typeof ClassificationEnum[keyof typeof ClassificationEnum];--- export const ClassificationEnum = {- New: 'new',- RateShift: 'rate_shift',- Gone: 'gone',- Unchanged: 'unchanged',- } as const;-/*** * `abandoned` - Abandoned* * `off-topic` - Off-topic@@ -31524,31 +31508,49 @@ export namespace Schemas {Cancelled: 'cancelled',} as const;+ /**+ * * `confirmed_flake` - CONFIRMED_FLAKE+ * * `suspected_regression` - SUSPECTED_REGRESSION+ * * `quarantined` - QUARANTINED+ */+ export type FlakyTestItemClassificationEnum = typeof FlakyTestItemClassificationEnum[keyof typeof FlakyTestItemClassificationEnum];+++ export const FlakyTestItemClassificationEnum = {+ ConfirmedFlake: 'confirmed_flake',+ SuspectedRegression: 'suspected_regression',+ Quarantined: 'quarantined',+ } as const;+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). */+ /** confirmed_flake: an in-job retry recovered the test in the same run, so it is provably nondeterministic. quarantined: it fails while masked as xfail. suspected_regression: only failures were recorded, which is absence of proof, not proof that it is a real break.+ *+ * * `confirmed_flake` - CONFIRMED_FLAKE+ * * `suspected_regression` - SUSPECTED_REGRESSION+ * * `quarantined` - QUARANTINED */+ classification: FlakyTestItemClassificationEnum;+ /** Runs where an in-job pytest retry recovered the test after it failed. Above zero is the only proof of flakiness this data carries, and it reaches only tests hand-marked @pytest.mark.flaky(reruns=N), since Backend CI runs without --reruns so failures stay visible. */+ rerun_passed_run_count: number;+ /** Distinct CI runs whose recorded outcome was failed or error. A run counts once however many matrix legs it failed in. */+ failed_run_count: number;+ /** Distinct pull requests among the failed runs. Failures on master or unattributed branches carry no PR number and are excluded here (still in failed_run_count). */failed_pr_count: number;- /** Failed/error spans on the default branch (master/main approximation) — the 'matters right now' signal that a flake is breaking the trunk, not just PR branches. */- master_failed_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;+ /** Failed runs on the default branch (master/main approximation): the 'matters right now' signal that a test is breaking the trunk, not just PR branches. */+ master_failed_run_count: number;+ /** Runs where the test failed while quarantined (xfail): already masked in CI, still failing. */+ quarantined_failed_run_count: number;+ /** Most recent failure, recovery, or xfail run for this test in the window. */+ last_signal_at: string;}export interface FlakyTestList {- /** Qualifying tests ranked by flakiness signal, strongest first, capped at `limit`. */+ /** Tests worth acting on now, ranked by blast radius: master failures, then PRs hit, then runs. */items: FlakyTestItem[];- /** True when more tests qualified than the cap; `items` is the strongest `limit` rows. */+ /** True when more tests qualified than the cap; `items` is the highest-ranked `limit` rows. */truncated: boolean;/** Maximum number of tests returned in `items`. */limit: number;@@ -68321,11 +68323,11 @@ export namespace Schemas {nodeid: string;/** Runnable pytest selector; exact when the CI reporter emitted it. */selector: string;- /** Failed + error + pass-on-retry spans in the current window (xfail excluded). */+ /** Runs in the current window where the test failed, errored, or a retry recovered it (xfail excluded). */signal_count: number;/** Same count over the equal-length window before date_from. */signal_count_prior: number;- /** Most recent signal span for this test, either window. */+ /** Most recent failure, recovery, or xfail run for this test, either window. */last_seen_at: string;}@@ -68341,23 +68343,27 @@ export namespace Schemas {export interface TeamCIHealthItem {/** Owning team slug (the CODEOWNERS handle minus '@PostHog/', e.g. 'team-replay'), or the literal 'unowned' for tests whose spans carry no ownership stamp. */owner_team: string;- /** Owned tests meeting the flaky-leaderboard bar in the window (passed on retry or failed on enough distinct PRs). Compare with flaky_test_count_prior for the delta. */+ /** Owned tests an in-job retry recovered in the window: the same proof, and the same word, that flaky_tests calls a confirmed_flake. Compare with flaky_test_count_prior for the delta. */flaky_test_count: number;/** Same count over the equal-length window immediately before date_from. */flaky_test_count_prior: number;- /** Signal spans on owned tests with final outcome 'failed' or 'error' in the window. An absolute count, not a rate: fast passing runs are not emitted. */- failed_count: number;+ /** Owned tests that failed with no recorded in-run recovery and still hit the blast-radius bar (a master/main failure, or min_failed_prs distinct PRs). Not flakes: absence of proof, not proof. */+ regression_test_count: number;+ /** Same count over the prior window. */+ regression_test_count_prior: number;+ /** CI runs (not spans) where an owned test's recorded outcome was failed or error. An absolute count, not a rate: fast passing runs are not emitted. */+ failed_run_count: number;/** Same count over the prior window. */- failed_count_prior: number;- /** Spans on owned tests that failed, then passed on an automatic retry, the strongest flaky signal. Only rerun-enabled CI lanes emit it. */- rerun_passed_count: number;+ failed_run_count_prior: number;+ /** Runs where an in-job pytest retry recovered an owned test after it failed. */+ rerun_passed_run_count: number;/** Same count over the prior window. */- rerun_passed_count_prior: number;- /** Spans on owned tests that failed while quarantined (xfail): masked in CI but still flaky. */- xfailed_count: number;+ rerun_passed_run_count_prior: number;+ /** Runs where an owned test failed while quarantined (xfail): masked in CI, still failing. */+ quarantined_failed_run_count: number;/** Same count over the prior window. */- xfailed_count_prior: number;- /** Most recent signal span across the team's owned tests, either window. */+ quarantined_failed_run_count_prior: number;+ /** Most recent failure, recovery, or xfail run across the team's owned tests, either window. */last_seen_at: string;}@@ -70009,6 +70015,22 @@ export namespace Schemas {match_literal: string | null;}+ /**+ * * `new` - new+ * * `rate_shift` - rate_shift+ * * `gone` - gone+ * * `unchanged` - unchanged+ */+ export type _LogPatternDiffEntryClassificationEnum = typeof _LogPatternDiffEntryClassificationEnum[keyof typeof _LogPatternDiffEntryClassificationEnum];+++ export const _LogPatternDiffEntryClassificationEnum = {+ New: 'new',+ RateShift: 'rate_shift',+ Gone: 'gone',+ Unchanged: 'unchanged',+ } as const;+export interface _LogPatternDiffEntry {/** "new": appears only in the current window and clears the novelty floor (at least ~1% volume share, or any error/fatal occurrences). "rate_shift": present in both windows with the per-second rate changed by at least 2x either way, backed by enough samples on both sides to trust the estimates. "gone": cleared the floor in the baseline but absent from the current window. "unchanged" means "no confident claim", not "provably identical" — sampled mining cannot prove a below-floor template is genuinely new or gone.*@@ -70016,7 +70038,7 @@ export namespace Schemas {* * `rate_shift` - rate_shift* * `gone` - gone* * `unchanged` - unchanged */- classification: ClassificationEnum;+ classification: _LogPatternDiffEntryClassificationEnum;/*** Current-window rate divided by baseline rate, both normalized per second so windows of different lengths compare fairly. 4.0 means 4x faster now; 0.25 means quartered. Null when the pattern is missing from either window.* @nullable@@ -74262,13 +74284,9 @@ export namespace Schemas {*/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.+ * A test with no recorded recovery qualifies once it failed on at least this many distinct pull requests in the window. 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;/*** 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.*/@@ -74521,13 +74539,9 @@ export namespace Schemas {*/limit?: number;/**- * A test counts as flaky 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.+ * An unrecovered test counts toward regression_test_count once it failed on at least this many distinct pull requests in the window. Minimum 1. Defaults to 3. Does not affect flaky_test_count, which needs proof, not a threshold.*/min_failed_prs?: number;- /**- * A test counts as flaky 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.*/diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.tsindex 415dfd85edfe..d5d31e2cc7ee 100644--- a/services/mcp/src/generated/engineering_analytics/api.ts+++ b/services/mcp/src/generated/engineering_analytics/api.ts@@ -57,7 +57,7 @@ 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.+ * The active test-health queue: backend tests worth acting on now, from the per-test CI spans, over a window (default -7d, maximum 30 days). Evidence is counted per CI run, never per span. A test is a 'confirmed_flake' when an in-job retry recovered it in the same run; 'quarantined' when it fails while masked as xfail; otherwise 'suspected_regression'. It qualifies on any recovery, any master/main failure, an xfail, or failures on at least min_failed_prs distinct PRs. Counts are absolute, never rates: CI emits a span for every failure but only for passes slow enough to clear the emitter's duration threshold, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.*/export const EngineeringAnalyticsFlakyTestsParams = /* @__PURE__ */ zod.object({project_id: zod@@ -80,13 +80,7 @@ export const EngineeringAnalyticsFlakyTestsQueryParams = /* @__PURE__ */ zod.obj.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.'+ 'A test with no recorded recovery qualifies once it failed on at least this many distinct pull requests in the window. Minimum 1. Defaults to 3.'),repo: zod.string()@@ -213,7 +207,7 @@ export const EngineeringAnalyticsSourcesParams = /* @__PURE__ */ zod.object({})/**- * Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and pass-on-retry span counts, each with an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*\/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team 'unowned'. Teams are organizational owners of code surfaces, never authors. 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.+ * Per-owning-team rollup of the CI test surfaces each team owns, over the same run evidence as flaky_tests and with the same meaning of flaky: flaky_test_count is owned tests an in-job retry recovered in the window, regression_test_count is owned tests that failed with no such proof and still hit the blast-radius bar, plus failed/recovery/quarantined run counts. Each has an equal-length previous-window twin for honest deltas. Ownership is stamped on the spans at CI emission time from the repo's ownership map (products/*\/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team 'unowned', and a re-stamped test lands under its latest owner only. Teams are organizational owners of code surfaces, never authors. Counts are absolute, never rates: CI emits a span for every failure but only for passes slow enough to clear the emitter's duration threshold, so there is no execution denominator. 'suspected_regression' means no recovery was recorded in this data, not that the test never flakes.*/export const EngineeringAnalyticsTeamCiHealthParams = /* @__PURE__ */ zod.object({project_id: zod@@ -236,13 +230,7 @@ export const EngineeringAnalyticsTeamCiHealthQueryParams = /* @__PURE__ */ zod.o.number().optional().describe(- 'A test counts as flaky 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 counts as flaky once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.'+ 'An unrecovered test counts toward regression_test_count once it failed on at least this many distinct pull requests in the window. Minimum 1. Defaults to 3. Does not affect flaky_test_count, which needs proof, not a threshold.'),source_id: zod.string()diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.tsindex adedb5d29078..2297d23d9694 100644--- a/services/mcp/src/tools/generated/engineering_analytics.ts+++ b/services/mcp/src/tools/generated/engineering_analytics.ts@@ -81,7 +81,6 @@ const engineeringAnalyticsFlakyTests = (): ToolBase<date_to: params.date_to,limit: params.limit,min_failed_prs: params.min_failed_prs,- min_rerun_passes: params.min_rerun_passes,repo: params.repo,source_id: params.source_id,},@@ -170,7 +169,6 @@ const engineeringAnalyticsTeamCiHealth = (): ToolBase<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,},})