: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
feat(engineering-analytics): broken-tests triage panel (#70990)
Julian Bez65d5131862b6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e1ab5c186af5..abdc4328faad 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5659,9 +5659,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.8e887d3516448ca8544b66f54ec2b15c348c795f5eeb38121d8822614ab6895a.FSJv5vBtsNGzICpMzsq58FRQDj-CMLwqFPl9IVKY4A4+ hash: v1.k794b7964.06f9bbebe50864d9faa44b12087f126cb4e7bbd6c3edc32d97b8831ff052a64c.3KiiGIL_OptbOha2UJHd1duUyx3sSLXVxpxGMFeFkBAscenes-app-engineering-analytics-test-health--flaky-test-leaderboard--light:- hash: v1.k794b7964.10a6793cc79056bee67f5785d2bf58cc936de9db6ccc526f85b44f051d658f94.EgZzEPDMHkx6x4Jw2IlGMf1wP1CBqkfy0jWdAsdSqAI+ hash: v1.k794b7964.abe059fd4b4e8533cd630f97ebd8ed24f749de71386e5534c4d1eb6f75f613a1.YLsUVjfhXWCEY0RGJObH9x02_41emp85WSyK7Va8Db0scenes-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/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 0dc200247393..3718a5af7a0f 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -25,6 +25,7 @@ from posthog.models.team import Teamfrom products.engineering_analytics.backend import logicfrom products.engineering_analytics.backend.facade.contracts import (BranchPRMatch,+ BrokenTestsResult,CICardSummary,CIFailureLogs,CurrentBranchHealth,@@ -311,6 +312,15 @@ def list_flaky_tests()+def get_broken_tests(+ *,+ team: Team,+ source_id: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> BrokenTestsResult:+ return logic.build_broken_tests(curated=_authorized_source(team, source_id, user_access_control))++def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:return logic.build_github_sources(team=team, user_access_control=user_access_control)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex c07befcda2ca..adc23de265a9 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -92,6 +92,30 @@ class WorkflowHealthRunScope(StrEnum):PULL_REQUEST = "pull_request"+class BrokenTestState(StrEnum):+ """How a live CI-failure fingerprint is behaving right now — the broken-tests classifier's+ verdict, ordered by triage urgency (``breaking_master`` on top, ``pr_only`` last). Inferred+ from the failure fingerprints and the latest default-branch job status; see+ ``logic/queries/broken_tests.py`` for the thresholds.++ - ``breaking_master``: has failed on the default branch and that job's latest completed run+ is still red — trunk is broken by this right now.+ - ``novel_burst``: first seen within the last day and already spreading across several PR+ branches, not on the default branch yet — a new failure catching on.+ - ``potentially_resolved``: hit the default branch but that job's latest run is green again —+ probably already fixed.+ - ``flaky``: sporadic across two or more branches over more than a day, never on the default+ branch — a recurring flake, not a trunk break.+ - ``pr_only``: confined to a single branch — one PR's own problem, the lowest signal.+ """++ BREAKING_MASTER = "breaking_master"+ NOVEL_BURST = "novel_burst"+ POTENTIALLY_RESOLVED = "potentially_resolved"+ FLAKY = "flaky"+ PR_ONLY = "pr_only"++class PRLifecycleEventKind(StrEnum):OPENED = "opened"CI_STARTED = "ci_started"@@ -497,6 +521,9 @@ class FlakyTestItem:failed_count: int# Distinct PRs among the failed/error spans; master/branch failures carry no PR and don't count.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.@@ -901,6 +928,62 @@ class MasterFailureGroup:latest_run_id: int+# The sparkline is a fixed-width hourly histogram; the width is the contract so a caller can render+# it without inspecting the array length. 24 slots = the last 24 hours, oldest first.+BROKEN_TEST_SPARKLINE_HOURS = 24+++@dataclass(frozen=True)+class BrokenTestRow:+ """One classified CI-failure fingerprint — a distinct failing test/error, with its recent+ behavior and the classifier's verdict. Aggregated from the fingerprinted failure lines+ (``engineering_analytics_ci_failures``) over the analysis window, joined to the latest+ default-branch job status for the ``state``.++ ``trend_24h`` is a ``BROKEN_TEST_SPARKLINE_HOURS``-slot hourly failure count (oldest first)+ for the row sparkline — all zeros when nothing failed in the last day. ``latest_run_id`` is the+ most recent failing run, the anchor a drill-down passes to ``run_failure_logs`` for the log lines.+ """++ fingerprint: str+ # The pytest node id from the FAILED line (the failing test's identity).+ test_id: str+ # The normalized trailing failure detail shared across runs of the same failure; '' when none.+ error_signature: str+ # The CI job the failure most recently came from — the key joined to default-branch job status.+ job_name: str+ # 'owner/name' the failure belongs to.+ repo: str+ state: BrokenTestState+ first_seen: datetime+ last_seen: datetime+ # Total failure lines for this fingerprint in the window (absolute count, never a rate).+ occurrences: int+ # Distinct branches the failure appeared on.+ branches: int+ # Failure lines on the default branch (master/main) — 0 means it never hit trunk.+ master_hits: int+ latest_run_id: int+ latest_branch: str+ trend_24h: list[int] = field(default_factory=list)+++@dataclass(frozen=True)+class BrokenTestsResult:+ """The broken-tests panel payload: classified failure fingerprints ranked by triage urgency+ (breaking trunk first), plus the default-branch jobs whose latest completed run is red — the+ "what's on fire right now" summary. ``rows`` is capped at ``limit`` with a ``truncated`` flag,+ same shape as ``FlakyTestList``. ``window_days`` is the analysis window the counts cover.+ """++ rows: list[BrokenTestRow]+ # Default-branch job names whose latest completed run is failing — drives the summary banner.+ breaking_master_jobs: list[str]+ window_days: int+ truncated: bool+ limit: int++@dataclass(frozen=True)class RunFailureLogs:"""Thinned CI failure logs for a single workflow run, grouped by failed job. Same log substratediff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex d5287f9cebad..d09d64170b9c 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -17,7 +17,9 @@ from posthog.models.team import Teamfrom posthog.utils import relative_date_parsefrom products.engineering_analytics.backend.facade.contracts import (+ BROKEN_TEST_SPARKLINE_HOURS,BranchPRMatch,+ BrokenTestsResult,CICardSummary,CIFailureLogs,CurrentBranchHealth,@@ -43,6 +45,7 @@ from products.engineering_analytics.backend.logic.quarantine import (request_quarantine as request_quarantine,)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries.broken_tests import query_broken_testsfrom products.engineering_analytics.backend.logic.queries.ci_cards import query_ci_cardsfrom products.engineering_analytics.backend.logic.queries.ci_failure_logs import (query_ci_failure_logs,@@ -102,6 +105,12 @@ _DEFAULT_FLAKY_MIN_FAILED_PRS = 3_DEFAULT_FLAKY_LIMIT = 50_MAX_FLAKY_LIMIT = 200+# Broken-tests panel: a fixed short window (not caller-tunable in v1, like current_branch_health).+# Two days keeps the logs-cluster scan light while still spanning the classifier's boundaries — a+# flaky failure needs a >24h span and a novel one needs first-seen <24h, both fitting inside 48h.+_BROKEN_TESTS_WINDOW_DAYS = 2+_BROKEN_TESTS_LIMIT = 200+# Each builder operates on an already-resolved CuratedGitHubSource: source selection and per-source# warehouse access control happen once at the facade, which hands these builders the authorized@@ -321,6 +330,19 @@ def build_flaky_tests()+def build_broken_tests(*, curated: CuratedGitHubSource) -> BrokenTestsResult:+ # Fixed windows resolved through the module's relative-date entry point (like current_branch_health):+ # the 2-day analysis window and the 24h sparkline window. The SQL uses now() for the age/span/offset+ # math, so these bounds only floor the scans.+ return query_broken_tests(+ curated=curated,+ date_from=_parse_date(curated.team, f"-{_BROKEN_TESTS_WINDOW_DAYS}d"),+ hourly_from=_parse_date(curated.team, f"-{BROKEN_TEST_SPARKLINE_HOURS}h"),+ window_days=_BROKEN_TESTS_WINDOW_DAYS,+ limit=_BROKEN_TESTS_LIMIT,+ )++def _parse_date(team: Team, value: str) -> datetime:return relative_date_parse(value, team.timezone_info)diff --git a/products/engineering_analytics/backend/logic/queries/broken_tests.py b/products/engineering_analytics/backend/logic/queries/broken_tests.pynew file mode 100644index 000000000000..2c0ac3596ebf--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/broken_tests.py@@ -0,0 +1,324 @@+"""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+sharper, 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 fingerprinted+failure lines (``engineering_analytics_ci_failures`` — the Logs-backed view) over a short window,+groups them into distinct failures, and classifies each against the latest default-branch job+status. The classifier lives here (not in the UI) so the same verdict backs both the panel and,+later, the Signals emitter — detection defined once over the read layer (SPEC §3).++Three reads, merged in Python because they span two ClickHouse clusters:++- fingerprints + the 24h sparkline histogram — both over the failure-lines view on the LOGS+ cluster (scoped by ``repo`` since that view is team-global, not source-scoped);+- latest default-branch job status — over the curated ``workflow_jobs`` source on the warehouse+ cluster, keyed by job name.++Age, span, and sparkline offsets are computed in SQL as integer ``dateDiff``s against ``now()`` so+the Python classifier never does timezone-sensitive datetime math on the returned values.++``breaking_master`` / ``potentially_resolved`` need the failure's job to match a default-branch job+by name (the log record's ``job_name`` vs the warehouse job ``name``). When the job-level source+isn't synced there is no job status at all, so those fingerprints fall through to ``flaky`` /+``pr_only`` — the panel degrades rather than misreports.+"""++from datetime import datetime, timedelta++from posthog.hogql import ast++from posthog.clickhouse.workload import Workload++from products.engineering_analytics.backend.facade.contracts import (+ BROKEN_TEST_SPARKLINE_HOURS,+ BrokenTestRow,+ BrokenTestsResult,+ BrokenTestState,+)+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.views import ci_failures++# Branch names treated as trunk — the failure "hit master" and job-status filters key on these.+_DEFAULT_BRANCHES = ["master", "main"]++# Job conclusions that mean trunk is red right now.+_RED_MASTER_SET = frozenset({"failure", "timed_out"})++# Classifier thresholds (heuristics over the failure fingerprints).+_NOVEL_BURST_MAX_AGE_HOURS = 24 # "new today" — first seen within the last day+_NOVEL_BURST_MIN_BRANCHES = 3 # ...and already spreading across at least this many branches+_FLAKY_MIN_BRANCHES = 2 # sporadic on at least two branches+_FLAKY_MIN_SPAN_HOURS = 24 # ...and recurring over more than a day++# Sort rank: lowest surfaces first (breaking master on top, PR-only last).+_SEVERITY: dict[BrokenTestState, int] = {+ BrokenTestState.BREAKING_MASTER: 0,+ BrokenTestState.NOVEL_BURST: 1,+ BrokenTestState.POTENTIALLY_RESOLVED: 2,+ BrokenTestState.FLAKY: 3,+ BrokenTestState.PR_ONLY: 4,+}++# Fingerprint aggregation over the failure-lines view. ``age_hours`` / ``span_hours`` /+# ``last_master_hit_age`` are computed here (integer dateDiffs against now()) so the Python classifier+# stays timezone-agnostic. No signal-floor HAVING: single-branch failures are kept too (they classify+# as pr_only, which the UI hides by default and the toggle reveals), so the "show PR-only" affordance+# has real rows to show. The cap does the bounding, ordered by urgency proxy first (reached trunk, then+# wider spread, then recency) so it can't evict a trunk-breaking fingerprint in favor of newer+# low-signal ones before the Python classifier runs; +1 reveals truncation, and the final severity+# ranking still happens after classification.+_FINGERPRINTS_SELECT = """+ SELECT+ fingerprint,+ any(test_id) AS test_id,+ any(error_signature) AS error_signature,+ argMax(job_name, timestamp) AS job_name,+ min(timestamp) AS first_seen,+ max(timestamp) AS last_seen,+ dateDiff('hour', min(timestamp), now()) AS age_hours,+ dateDiff('hour', min(timestamp), max(timestamp)) AS span_hours,+ count() AS occurrences,+ uniqExactIf(branch, branch != '') AS branches,+ countIf(branch IN {default_branches}) AS master_hits,+ any(repo) AS repo,+ argMax(run_id, timestamp) AS latest_run_id,+ argMax(branch, timestamp) AS latest_branch,+ argMax(workflow_name, timestamp) AS workflow_name,+ dateDiff('second', maxIf(timestamp, branch IN {default_branches}), now()) AS last_master_hit_age+ FROM __FAILURES_SOURCE__+ WHERE timestamp >= {date_from} AND lower(repo) = lower({repository})+ GROUP BY fingerprint+ ORDER BY master_hits DESC, branches DESC, last_seen DESC+ LIMIT {limit_plus_one}+"""++# Per-fingerprint hourly failure counts over the last day, bucketed by how many whole hours ago the+# hour was (0 = current hour). Bounded to the fingerprints we actually kept ({fingerprints}) so a repo+# with thousands of distinct 24h failures doesn't scan+group them all just to fill ~200 sparklines;+# folded into a fixed array per fingerprint below.+_HOURLY_SELECT = """+ SELECT+ fingerprint,+ dateDiff('hour', toStartOfHour(timestamp), toStartOfHour(now())) AS hours_ago,+ count() AS c+ FROM __FAILURES_SOURCE__+ WHERE timestamp >= {hourly_from} AND lower(repo) = lower({repository}) AND fingerprint IN {fingerprints}+ GROUP BY fingerprint, hours_ago+"""++# Latest default-branch status per (workflow, job), from the curated workflow-jobs source. Keyed by+# workflow too, not job name alone: unrelated workflows can reuse a job name like ``test`` / ``build``,+# and collapsing them would let one workflow's green job mask another's red one. ``created_at_raw`` is+# the raw ISO string the scan can prune on (a parsed-column predicate forces a full scan); it floors a+# day below the precise ``created_at`` window. Recency keys on ``completed_at`` (when the run actually+# finished), not ``created_at`` — a run that started before a failure but finished green after it is a+# real recovery. ``latest_conclusion`` is that newest-finishing completed run's conclusion (red =+# broken now); ``latest_completed_age`` is how long ago it finished, so the classifier can tell a+# genuine recovery from a stale-green row the logs have already overtaken.+_MASTER_JOBS_SELECT = """+ SELECT+ workflow_name,+ name AS job_name,+ argMaxIf(conclusion, completed_at, status = 'completed') AS latest_conclusion,+ dateDiff('second', maxIf(completed_at, status = 'completed'), now()) AS latest_completed_age+ FROM __JOBS_SOURCE__+ WHERE head_branch IN {default_branches}+ AND created_at_raw >= {created_floor}+ AND created_at >= {date_from}+ GROUP BY workflow_name, name+"""+++def _classify(+ *,+ master_hits: int,+ age_hours: int,+ span_hours: int,+ branches: int,+ latest_conclusion: str | None,+ last_master_hit_age: int,+ latest_completed_age: int | None,+) -> BrokenTestState:+ """The broken-test verdict for one fingerprint. ``latest_conclusion`` / ``latest_completed_age`` are+ the matched default-branch job's newest completed conclusion and how long ago it finished, or None+ when the job has no default-branch status (job source unsynced, or the failure's job never ran on+ trunk). ``last_master_hit_age`` is how long ago this fingerprint last failed on trunk (only+ meaningful when ``master_hits > 0``). All ages are seconds-ago-from-now, so smaller = more recent."""+ master_red = latest_conclusion in _RED_MASTER_SET+ # Only a green run that finished *after* the fingerprint's most recent trunk failure counts as a+ # recovery. If the green predates the failure, the warehouse job status is just lagging the fresher+ # logs and the trunk break is still live — don't call it resolved.+ master_green_and_fresh = (+ latest_conclusion == "success"+ and latest_completed_age is not None+ and latest_completed_age < last_master_hit_age+ )+ # Breaking trunk right now: hit the default branch and that job's latest run is still red.+ if master_hits > 0 and master_red:+ return BrokenTestState.BREAKING_MASTER+ # New today and already spreading across branches, but not on trunk yet.+ if age_hours < _NOVEL_BURST_MAX_AGE_HOURS and branches >= _NOVEL_BURST_MIN_BRANCHES and master_hits == 0:+ return BrokenTestState.NOVEL_BURST+ # Hit the default branch but that job has since gone green again — probably already fixed.+ if master_hits > 0 and master_green_and_fresh:+ return BrokenTestState.POTENTIALLY_RESOLVED+ # Sporadic across branches and recurring over more than a day.+ if branches >= _FLAKY_MIN_BRANCHES and span_hours > _FLAKY_MIN_SPAN_HOURS:+ return BrokenTestState.FLAKY+ return BrokenTestState.PR_ONLY+++def _sparklines_by_fingerprint(hourly_rows: list) -> dict[str, list[int]]:+ """Fold the (fingerprint, hours_ago, count) rows into a fixed hourly array per fingerprint,+ oldest slot first. Buckets outside the window are ignored; a fingerprint with no recent failures+ simply gets no entry (the caller renders all-zeros)."""+ series_by_fp: dict[str, list[int]] = {}+ for fingerprint, hours_ago, count in hourly_rows:+ if hours_ago < 0 or hours_ago >= BROKEN_TEST_SPARKLINE_HOURS:+ continue+ series = series_by_fp.setdefault(fingerprint, [0] * BROKEN_TEST_SPARKLINE_HOURS)+ series[BROKEN_TEST_SPARKLINE_HOURS - 1 - hours_ago] += count+ return series_by_fp+++def query_broken_tests(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ hourly_from: datetime,+ window_days: int,+ limit: int,+) -> BrokenTestsResult:+ repository = curated.repository+ # The failure-lines view is team-global; without a source repository we cannot scope it to the+ # selected source, so return nothing rather than mix another repo's failures in.+ if not repository:+ return BrokenTestsResult(+ rows=[], breaking_master_jobs=[], window_days=window_days, truncated=False, limit=limit+ )++ failures_source = f"({ci_failures.build_query()})"+ logs_placeholders: dict[str, ast.Expr] = {+ "default_branches": ast.Constant(value=_DEFAULT_BRANCHES),+ "repository": ast.Constant(value=repository),+ "date_from": ast.Constant(value=date_from),+ # +1 so a full page reveals that more fingerprints qualified than returned.+ "limit_plus_one": ast.Constant(value=limit + 1),+ }+ fingerprint_rows = (+ curated.run(+ _FINGERPRINTS_SELECT.replace("__FAILURES_SOURCE__", failures_source),+ query_type="engineering_analytics.broken_tests_fingerprints",+ placeholders=logs_placeholders,+ workload=Workload.LOGS,+ ).results+ or []+ )+ # Only the fingerprints we kept need a sparkline; bound the 24h scan to them (skip it entirely when+ # the first scan found nothing) so a busy repo doesn't group every recent failure just to fill ~200.+ selected_fingerprints = [row[0] for row in fingerprint_rows]+ hourly_rows = (+ (+ curated.run(+ _HOURLY_SELECT.replace("__FAILURES_SOURCE__", failures_source),+ query_type="engineering_analytics.broken_tests_hourly",+ placeholders={+ "repository": ast.Constant(value=repository),+ "hourly_from": ast.Constant(value=hourly_from),+ "fingerprints": ast.Constant(value=selected_fingerprints),+ },+ workload=Workload.LOGS,+ ).results+ or []+ )+ if selected_fingerprints+ else []+ )++ # Latest default-branch status per (workflow, job) — empty when the job-level source isn't synced,+ # in which case breaking_master / potentially_resolved can't be distinguished and those rows fall+ # through. Keyed on (workflow_name, job_name) so a job name shared across workflows doesn't collapse.+ master_by_key: dict[tuple[str, str], tuple[str | None, int | None]] = {}+ breaking_master_jobs: set[str] = set()+ jobs_source = curated.jobs_source()+ if jobs_source is not None:+ master_rows = (+ curated.run(+ _MASTER_JOBS_SELECT.replace("__JOBS_SOURCE__", jobs_source),+ query_type="engineering_analytics.broken_tests_master_jobs",+ placeholders={+ "default_branches": ast.Constant(value=_DEFAULT_BRANCHES),+ "created_floor": ast.Constant(value=(date_from - timedelta(days=1)).strftime("%Y-%m-%d")),+ "date_from": ast.Constant(value=date_from),+ },+ ).results+ or []+ )+ for workflow_name, job_name, latest_conclusion, latest_completed_age in master_rows:+ master_by_key[(workflow_name, job_name)] = (latest_conclusion, latest_completed_age)+ if latest_conclusion in _RED_MASTER_SET:+ breaking_master_jobs.add(job_name)++ sparklines = _sparklines_by_fingerprint(hourly_rows)++ rows: list[BrokenTestRow] = []+ for (+ fingerprint,+ test_id,+ error_signature,+ job_name,+ first_seen,+ last_seen,+ age_hours,+ span_hours,+ occurrences,+ branches,+ master_hits,+ repo,+ latest_run_id,+ latest_branch,+ workflow_name,+ last_master_hit_age,+ ) in fingerprint_rows:+ latest_conclusion, latest_completed_age = master_by_key.get((workflow_name, job_name), (None, None))+ state = _classify(+ master_hits=master_hits,+ age_hours=age_hours,+ span_hours=span_hours,+ branches=branches,+ latest_conclusion=latest_conclusion,+ last_master_hit_age=last_master_hit_age,+ latest_completed_age=latest_completed_age,+ )+ rows.append(+ BrokenTestRow(+ fingerprint=fingerprint,+ test_id=test_id or "",+ error_signature=error_signature or "",+ job_name=job_name or "",+ repo=repo or "",+ state=state,+ first_seen=first_seen,+ last_seen=last_seen,+ occurrences=occurrences,+ branches=branches,+ master_hits=master_hits,+ latest_run_id=latest_run_id or 0,+ latest_branch=latest_branch or "",+ trend_24h=sparklines.get(fingerprint, [0] * BROKEN_TEST_SPARKLINE_HOURS),+ )+ )++ # Severity first, then most-recent failure — the top of the list is what's on fire right now.+ # Two stable passes (Python's sort is stable): newest last_seen within each state, states in+ # rank order. All last_seen values come from one query, so they're uniformly comparable.+ rows.sort(key=lambda r: r.last_seen, reverse=True)+ rows.sort(key=lambda r: _SEVERITY[r.state])+ return BrokenTestsResult(+ rows=rows[:limit],+ breaking_master_jobs=sorted(breaking_master_jobs),+ window_days=window_days,+ truncated=len(rows) > limit,+ limit=limit,+ )diff --git a/products/engineering_analytics/backend/logic/queries/flaky_tests.py b/products/engineering_analytics/backend/logic/queries/flaky_tests.pyindex f8e3482958be..b7a590125922 100644--- a/products/engineering_analytics/backend/logic/queries/flaky_tests.py+++ b/products/engineering_analytics/backend/logic/queries/flaky_tests.py@@ -46,6 +46,7 @@ _SELECT = """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@@ -137,11 +138,12 @@ def query_flaky_tests(rerun_passed_count=rerun_passed_count,failed_count=failed_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,)- for nodeid, selector, rerun_passed_count, failed_count, failed_pr_count, branch_count, xfailed_count, last_seen_at in rows[+ for nodeid, selector, rerun_passed_count, failed_count, failed_pr_count, master_failed_count, branch_count, xfailed_count, last_seen_at in rows[:limit]],diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.pyindex b71ad3275449..54b48ee4d0cf 100644--- a/products/engineering_analytics/backend/presentation/serializers.py+++ b/products/engineering_analytics/backend/presentation/serializers.py@@ -12,6 +12,8 @@ from rest_framework_dataclasses.serializers import DataclassSerializerfrom products.engineering_analytics.backend.facade.contracts import (Author,BranchPRMatch,+ BrokenTestRow,+ BrokenTestsResult,CICardSummary,CIFailureLogLine,CIFailureLogs,@@ -423,6 +425,10 @@ class FlakyTestItemSerializer(DataclassSerializer):"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).",},+ "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.",+ },"branch_count": {"help_text": "Distinct git branches across all of the test's flaky-signal spans in the window.",},@@ -449,6 +455,74 @@ class FlakyTestListSerializer(DataclassSerializer):}+class BrokenTestRowSerializer(DataclassSerializer):+ class Meta:+ dataclass = BrokenTestRow+ extra_kwargs = {+ "fingerprint": {+ "help_text": "Stable identity of this distinct failure: the failing test's node id plus a "+ "normalized error signature, so the same failure across runs groups into one row.",+ },+ "test_id": {"help_text": "The pytest node id from the CI 'FAILED <id>' line — the failing test."},+ "error_signature": {+ "help_text": "The trailing failure detail with volatile bits (numbers, hashes) normalized, shared "+ "across runs of the same failure. Empty when the FAILED line carried no detail.",+ },+ "job_name": {+ "help_text": "The CI job the failure most recently came from. Matched against default-branch job "+ "status to decide whether trunk is currently broken by it.",+ },+ "repo": {"help_text": "'owner/name' repository the failure belongs to."},+ "state": {+ "help_text": "The classifier's verdict on how this failure is behaving right now: "+ "'breaking_master' (failing on trunk, latest trunk run still red), 'novel_burst' (new within a "+ "day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but "+ "trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' "+ "(confined to one branch — one PR's own problem).",+ },+ "first_seen": {"help_text": "Earliest failure line for this fingerprint in the analysis window."},+ "last_seen": {"help_text": "Most recent failure line for this fingerprint in the analysis window."},+ "occurrences": {+ "help_text": "Total failure lines for this fingerprint in the window. An absolute count, never a "+ "rate — passing runs aren't in this data.",+ },+ "branches": {"help_text": "Distinct branches the failure appeared on in the window."},+ "master_hits": {+ "help_text": "Failure lines on the default branch (master/main). 0 means it never reached trunk.",+ },+ "latest_run_id": {+ "help_text": "The most recent failing workflow run for this fingerprint — pass it to "+ "run_failure_logs to fetch the actual failing log lines.",+ },+ "latest_branch": {"help_text": "The branch of the most recent failing run."},+ "trend_24h": {+ "help_text": "Hourly failure counts over the last 24 hours, oldest first (fixed 24-slot array), "+ "for the row sparkline. All zeros when nothing failed in the last day.",+ },+ }+++class BrokenTestsResultSerializer(DataclassSerializer):+ rows = BrokenTestRowSerializer(+ many=True,+ help_text="Classified failures ranked by triage urgency — breaking trunk first, single-PR failures last.",+ )++ class Meta:+ dataclass = BrokenTestsResult+ extra_kwargs = {+ "breaking_master_jobs": {+ "help_text": "Default-branch job names whose latest completed run is failing — the 'what's on fire "+ "right now' summary. Empty when the job-level source isn't synced or trunk is green.",+ },+ "window_days": {"help_text": "Length in days of the analysis window the counts cover."},+ "truncated": {+ "help_text": "True when more failures qualified than the cap; `rows` is the top `limit` by urgency.",+ },+ "limit": {"help_text": "Maximum number of rows returned."},+ }++class CIStatusRollupSerializer(DataclassSerializer):class Meta:dataclass = CIStatusRollupdiff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.pyindex 0d9dccb793f9..412c33277b69 100644--- a/products/engineering_analytics/backend/presentation/views.py+++ b/products/engineering_analytics/backend/presentation/views.py@@ -35,6 +35,7 @@ from products.engineering_analytics.backend.facade.contracts import ()from products.engineering_analytics.backend.presentation.serializers import (BranchPRMatchSerializer,+ BrokenTestsResultSerializer,CICardSummarySerializer,CIFailureLogsSerializer,CurrentBranchHealthSerializer,@@ -192,6 +193,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe"author_workflow_costs","workflow_jobs","flaky_tests",+ "broken_tests","repo_overview","repo_run_activity","current_branch_health",@@ -929,6 +931,37 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSereturn _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")return Response(FlakyTestListSerializer(instance=result).data)+ @extend_schema(+ operation_id="engineering_analytics_broken_tests",+ parameters=[_SOURCE_ID],+ responses={+ 200: BrokenTestsResultSerializer,+ 400: OpenApiResponse(description="Invalid source_id."),+ },+ description=(+ "The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct "+ "failures (by test id + normalized error signature) and classified by how each is behaving right "+ "now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one "+ "PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the "+ "default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I "+ "care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. "+ "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."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def broken_tests(self, request: Request, **kwargs) -> Response:+ try:+ result = api.get_broken_tests(+ team=self.team,+ source_id=request.query_params.get("source_id") or None,+ user_access_control=self.user_access_control,+ )+ except ValueError as exc:+ return _bad_request(exc, fallback="Invalid source_id")+ return Response(BrokenTestsResultSerializer(instance=result).data)+@extend_schema(operation_id="engineering_analytics_repo_overview",parameters=[diff --git a/products/engineering_analytics/backend/tests/test_broken_tests.py b/products/engineering_analytics/backend/tests/test_broken_tests.pynew file mode 100644index 000000000000..5e0025fd877d--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_broken_tests.py@@ -0,0 +1,240 @@+from datetime import UTC, datetime+from types import SimpleNamespace++import pytest+from unittest import mock++from products.engineering_analytics.backend.facade.contracts import BROKEN_TEST_SPARKLINE_HOURS, BrokenTestState+from products.engineering_analytics.backend.logic.queries import broken_tests as module+from products.engineering_analytics.backend.logic.queries.broken_tests import (+ _classify,+ _sparklines_by_fingerprint,+ query_broken_tests,+)+++# Ages are seconds-ago-from-now (smaller = more recent). last_master_hit_age is the fingerprint's most+# recent trunk failure; latest_completed_age is the matched job's newest completed run.+ "master_hits,age_hours,span_hours,branches,latest_conclusion,last_master_hit_age,latest_completed_age,expected",+ [+ # Breaking trunk: hit master and that job's latest run is still red — highest priority.+ (3, 5, 48, 5, "failure", 100, 50, BrokenTestState.BREAKING_MASTER),+ (1, 40, 100, 2, "timed_out", 100, 50, BrokenTestState.BREAKING_MASTER),+ # Breaking wins even when the row also looks novel (fresh + spreading).+ (3, 5, 5, 4, "failure", 100, 50, BrokenTestState.BREAKING_MASTER),+ # Novel burst: fresh (<24h), spread across >=3 branches, never on trunk.+ (0, 5, 5, 4, None, 0, None, BrokenTestState.NOVEL_BURST),+ # Hit trunk but the green run finished AFTER the last failure (100 < 1000) — a real recovery.+ (2, 40, 100, 3, "success", 1000, 100, BrokenTestState.POTENTIALLY_RESOLVED),+ # Green but STALE: the green predates the last trunk failure (1000 > 100), so the warehouse is+ # just lagging the fresher logs — not resolved, falls through to flaky.+ (2, 40, 100, 3, "success", 100, 1000, BrokenTestState.FLAKY),+ # Flaky: sporadic across >=2 branches over more than a day, not on trunk.+ (0, 100, 48, 3, None, 0, None, BrokenTestState.FLAKY),+ # Degradation: hit trunk but no job status (source unsynced) — falls through, not misreported.+ (3, 100, 48, 3, None, 100, None, BrokenTestState.FLAKY),+ # PR-only: one branch, recent, short span — the lowest signal.+ (0, 5, 2, 1, None, 0, None, BrokenTestState.PR_ONLY),+ # Not novel (only 2 branches) and not flaky (span within a day) → PR-only.+ (0, 5, 10, 2, None, 0, None, BrokenTestState.PR_ONLY),+ ],+)+def test_classify_states(+ master_hits, age_hours, span_hours, branches, latest_conclusion, last_master_hit_age, latest_completed_age, expected+):+ assert (+ _classify(+ master_hits=master_hits,+ age_hours=age_hours,+ span_hours=span_hours,+ branches=branches,+ latest_conclusion=latest_conclusion,+ last_master_hit_age=last_master_hit_age,+ latest_completed_age=latest_completed_age,+ )+ == expected+ )+++def test_sparkline_fold_places_hours_oldest_first_and_skips_out_of_window():+ # hours_ago=0 is the newest slot (last), 23 the oldest (first); anything >=24 is dropped.+ rows = [+ ("fp", 0, 8),+ ("fp", 1, 6),+ ("fp", 23, 1),+ ("fp", 24, 99), # out of window — must be ignored+ ("other", 0, 3),+ ]+ series = _sparklines_by_fingerprint(rows)++ assert len(series["fp"]) == BROKEN_TEST_SPARKLINE_HOURS+ assert series["fp"][BROKEN_TEST_SPARKLINE_HOURS - 1] == 8 # hours_ago 0 → last slot+ assert series["fp"][BROKEN_TEST_SPARKLINE_HOURS - 2] == 6 # hours_ago 1+ assert series["fp"][0] == 1 # hours_ago 23 → first slot+ assert sum(series["fp"]) == 15 # the 24-hours-ago bucket did not count+ assert "other" in series+++def _fp_row(+ fingerprint,+ job_name,+ *,+ master_hits,+ branches,+ last_seen,+ workflow_name="wf",+ latest_run_id=1,+ age=100,+ span=48,+ last_master_hit_age=500,+):+ # Column order mirrors _FINGERPRINTS_SELECT (workflow_name + last_master_hit_age appended last).+ return (+ fingerprint,+ f"test_{fingerprint}",+ "AssertionError",+ job_name,+ datetime(2026, 7, 13, tzinfo=UTC),+ last_seen,+ age,+ span,+ 10,+ branches,+ master_hits,+ "PostHog/posthog",+ latest_run_id,+ "some-branch",+ workflow_name,+ last_master_hit_age,+ )+++def _run_query(*, fingerprint_rows, hourly_rows, master_rows, jobs_synced=True, limit=200):+ curated = mock.Mock()+ curated.repository = "PostHog/posthog"+ curated.jobs_source.return_value = "(jobs)" if jobs_synced else None++ def run_side_effect(_sql, *, query_type, **_kwargs):+ if "fingerprints" in query_type:+ return SimpleNamespace(results=fingerprint_rows)+ if "hourly" in query_type:+ return SimpleNamespace(results=hourly_rows)+ return SimpleNamespace(results=master_rows)++ curated.run.side_effect = run_side_effect+ return query_broken_tests(+ curated=curated,+ date_from=datetime(2026, 7, 13, tzinfo=UTC),+ hourly_from=datetime(2026, 7, 14, tzinfo=UTC),+ window_days=2,+ limit=limit,+ )+++def test_query_joins_master_status_ranks_by_severity_and_attaches_trend():+ # A breaking-master row (its job is red) must outrank a flaky row regardless of recency, carry+ # its folded 24h trend, and the red job must surface in breaking_master_jobs. This is the whole+ # merge: fingerprints × job status → classified, ranked, sparkline-attached rows.+ result = _run_query(+ fingerprint_rows=[+ _fp_row("flaky-fp", "job-b", master_hits=0, branches=3, last_seen=datetime(2026, 7, 15, tzinfo=UTC)),+ _fp_row("break-fp", "job-a", master_hits=3, branches=4, last_seen=datetime(2026, 7, 14, tzinfo=UTC)),+ ],+ hourly_rows=[("break-fp", 0, 5), ("break-fp", 1, 2)],+ # (workflow_name, job_name, latest_conclusion, latest_completed_age)+ master_rows=[("wf", "job-a", "failure", 50), ("wf", "job-b", "success", 50)],+ )++ assert [row.fingerprint for row in result.rows] == ["break-fp", "flaky-fp"]+ assert result.rows[0].state == BrokenTestState.BREAKING_MASTER+ assert result.rows[1].state == BrokenTestState.FLAKY+ assert result.breaking_master_jobs == ["job-a"]+ # trend_24h is the fixed-width fold: newest hour last.+ assert result.rows[0].trend_24h[-1] == 5+ assert result.rows[0].trend_24h[-2] == 2+ # The flaky row had no hourly rows → all-zero trend of the contract width.+ assert result.rows[1].trend_24h == [0] * BROKEN_TEST_SPARKLINE_HOURS+++def test_query_keys_master_status_by_workflow_not_just_job_name():+ # Two workflows reuse the job name "test": one is red on trunk, one green. Keying master status by+ # job name alone would let the green mask the red. Both fingerprints hit trunk, so the right verdicts+ # are breaking_master (red workflow) and potentially_resolved (green workflow, fresh green).+ result = _run_query(+ fingerprint_rows=[+ _fp_row(+ "red-wf-fp",+ "test",+ workflow_name="backend",+ master_hits=3,+ branches=3,+ last_seen=datetime(2026, 7, 15, tzinfo=UTC),+ ),+ _fp_row(+ "green-wf-fp",+ "test",+ workflow_name="frontend",+ master_hits=3,+ branches=3,+ last_seen=datetime(2026, 7, 15, tzinfo=UTC),+ ),+ ],+ hourly_rows=[],+ master_rows=[("backend", "test", "failure", 50), ("frontend", "test", "success", 50)],+ )++ by_fp = {row.fingerprint: row.state for row in result.rows}+ assert by_fp["red-wf-fp"] == BrokenTestState.BREAKING_MASTER+ assert by_fp["green-wf-fp"] == BrokenTestState.POTENTIALLY_RESOLVED+++def test_query_degrades_without_job_source():+ # No jobs source → no master status query runs, breaking/resolved can't be decided, and a+ # trunk-hitting failure falls through to flaky rather than being called breaking_master.+ result = _run_query(+ fingerprint_rows=[+ _fp_row("fp", "job-a", master_hits=3, branches=3, last_seen=datetime(2026, 7, 15, tzinfo=UTC)),+ ],+ hourly_rows=[],+ master_rows=[],+ jobs_synced=False,+ )++ assert result.breaking_master_jobs == []+ assert result.rows[0].state == BrokenTestState.FLAKY+++def test_query_truncates_by_limit():+ rows = [+ _fp_row(f"fp{i}", "job", master_hits=0, branches=3, last_seen=datetime(2026, 7, 15, tzinfo=UTC))+ for i in range(3)+ ]+ result = _run_query(fingerprint_rows=rows, hourly_rows=[], master_rows=[], limit=2)++ assert len(result.rows) == 2+ assert result.truncated is True+++def test_query_returns_empty_without_repository_and_skips_reads():+ curated = mock.Mock()+ curated.repository = ""+ result = query_broken_tests(+ curated=curated,+ date_from=datetime(2026, 7, 13, tzinfo=UTC),+ hourly_from=datetime(2026, 7, 14, tzinfo=UTC),+ window_days=2,+ limit=200,+ )++ assert result.rows == []+ assert result.breaking_master_jobs == []+ # A team-global logs view with no source repository must not be scanned at all.+ curated.run.assert_not_called()+++def test_build_query_embeds_the_failures_view():+ # Guards the private read path: the fingerprint scan reads the ci_failures builder as a subquery,+ # not the registered warehouse view by name (keeps the product off the global catalog).+ assert "engineering_analytics_ci_failures" not in module._FINGERPRINTS_SELECT+ assert "FAILED" in module.ci_failures.build_query()diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.pyindex c8c5e800ed41..2eca1806eb69 100644--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py@@ -50,13 +50,15 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):old = now - timedelta(days=10)rows = [- # Qualifies via distinct PRs (3): 4 failed + 1 error spans, one PR hit twice (dedup),- # one master error with no PR (counts as a failure, not a PR), plus one xfail.+ # 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.@@ -147,13 +149,18 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):# reconstruction (folded '/' → '.py' boundary).assert by_rerun["selector"] == T_RERUN_SELECTORassert by_prs["selector"] == "posthog/api/test/test_prs.py::TestPRs::test_flaky_on_prs"- assert (by_prs["rerun_passed_count"], by_prs["failed_count"], by_prs["failed_pr_count"]) == (0, 5, 3)- assert (by_prs["branch_count"], by_prs["xfailed_count"]) == (4, 1)+ 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([diff --git a/products/engineering_analytics/frontend/components/BrokenTestStateTag.tsx b/products/engineering_analytics/frontend/components/BrokenTestStateTag.tsxnew file mode 100644index 000000000000..e33a512c9af3--- /dev/null+++ b/products/engineering_analytics/frontend/components/BrokenTestStateTag.tsx@@ -0,0 +1,27 @@+import { IconCheckCircle, IconInfo, IconWarning, IconWrench } from '@posthog/icons'+import { LemonTag, LemonTagType } from '@posthog/lemon-ui'++import { BrokenTestState } from '../scenes/engineeringAnalyticsLogic'++// PROTOTYPE: mirrors PullRequestStateTag's shape — a state→config map rendered as a LemonTag.+const STATE_CONFIG: Record<BrokenTestState, { label: string; type: LemonTagType; icon: JSX.Element }> = {+ breaking_master: { label: 'Breaking master', type: 'danger', icon: <IconWarning /> },+ novel_burst: { label: 'Novel burst', type: 'warning', icon: <IconWarning /> },+ potentially_resolved: { label: 'Maybe resolved', type: 'success', icon: <IconCheckCircle /> },+ flaky: { label: 'Flaky', type: 'muted', icon: <IconWrench /> },+ pr_only: { label: 'PR-only', type: 'default', icon: <IconInfo /> },+}++export function BrokenTestStateTag({ state }: { state: BrokenTestState }): JSX.Element {+ // Fall back to a muted tag of the raw value if a state ever lands outside the enum.+ const { label, type, icon } = STATE_CONFIG[state] ?? {+ label: state,+ type: 'muted' as LemonTagType,+ icon: <IconInfo />,+ }+ return (+ <LemonTag type={type} icon={icon}>+ {label}+ </LemonTag>+ )+}diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 69dce82a4852..a219e37a4246 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -25,6 +25,73 @@ export interface WorkflowCostApi {excluded_jobs: number}+/**+ * * `breaking_master` - BREAKING_MASTER+ * * `novel_burst` - NOVEL_BURST+ * * `potentially_resolved` - POTENTIALLY_RESOLVED+ * * `flaky` - FLAKY+ * * `pr_only` - PR_ONLY+ */+export type BrokenTestRowStateEnumApi = (typeof BrokenTestRowStateEnumApi)[keyof typeof BrokenTestRowStateEnumApi]++export const BrokenTestRowStateEnumApi = {+ BreakingMaster: 'breaking_master',+ NovelBurst: 'novel_burst',+ PotentiallyResolved: 'potentially_resolved',+ Flaky: 'flaky',+ PrOnly: 'pr_only',+} as const++export interface BrokenTestRowApi {+ /** Stable identity of this distinct failure: the failing test's node id plus a normalized error signature, so the same failure across runs groups into one row. */+ fingerprint: string+ /** The pytest node id from the CI 'FAILED <id>' line — the failing test. */+ test_id: string+ /** The trailing failure detail with volatile bits (numbers, hashes) normalized, shared across runs of the same failure. Empty when the FAILED line carried no detail. */+ error_signature: string+ /** The CI job the failure most recently came from. Matched against default-branch job status to decide whether trunk is currently broken by it. */+ job_name: string+ /** 'owner/name' repository the failure belongs to. */+ repo: string+ /** The classifier's verdict on how this failure is behaving right now: 'breaking_master' (failing on trunk, latest trunk run still red), 'novel_burst' (new within a day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' (confined to one branch — one PR's own problem).+ *+ * * `breaking_master` - BREAKING_MASTER+ * * `novel_burst` - NOVEL_BURST+ * * `potentially_resolved` - POTENTIALLY_RESOLVED+ * * `flaky` - FLAKY+ * * `pr_only` - PR_ONLY */+ state: BrokenTestRowStateEnumApi+ /** Earliest failure line for this fingerprint in the analysis window. */+ first_seen: string+ /** Most recent failure line for this fingerprint in the analysis window. */+ last_seen: string+ /** Total failure lines for this fingerprint in the window. An absolute count, never a rate — passing runs aren't in this data. */+ occurrences: number+ /** Distinct branches the failure appeared on in the window. */+ branches: number+ /** Failure lines on the default branch (master/main). 0 means it never reached trunk. */+ master_hits: number+ /** The most recent failing workflow run for this fingerprint — pass it to run_failure_logs to fetch the actual failing log lines. */+ latest_run_id: number+ /** The branch of the most recent failing run. */+ latest_branch: string+ /** Hourly failure counts over the last 24 hours, oldest first (fixed 24-slot array), for the row sparkline. All zeros when nothing failed in the last day. */+ trend_24h?: number[]+}++export interface BrokenTestsResultApi {+ /** Classified failures ranked by triage urgency — breaking trunk first, single-PR failures last. */+ rows: BrokenTestRowApi[]+ /** Default-branch job names whose latest completed run is failing — the 'what's on fire right now' summary. Empty when the job-level source isn't synced or trunk is green. */+ breaking_master_jobs: string[]+ /** Length in days of the analysis window the counts cover. */+ window_days: number+ /** True when more failures qualified than the cap; `rows` is the top `limit` by urgency. */+ truncated: boolean+ /** Maximum number of rows returned. */+ limit: number+}+export interface CICardSummaryApi {/** Count of open pull requests. */open_prs: number@@ -111,6 +178,8 @@ export interface FlakyTestItemApi {failed_count: number/** Distinct pull requests among the failed/error spans. Failures on master or unattributed branches carry no PR number and are excluded here (still in failed_count). */failed_pr_count: number+ /** 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. */@@ -983,6 +1052,13 @@ export type EngineeringAnalyticsAuthorWorkflowCostsParams = {source_id?: string}+export type EngineeringAnalyticsBrokenTestsParams = {+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.+ */+ source_id?: string+}+export type EngineeringAnalyticsCiCardsParams = {/*** 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 80a3f978c313..d8cf55fdcf0e 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -10,10 +10,12 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'*/import type {BranchPRMatchApi,+ BrokenTestsResultApi,CICardSummaryApi,CIFailureLogsApi,CurrentBranchHealthApi,EngineeringAnalyticsAuthorWorkflowCostsParams,+ EngineeringAnalyticsBrokenTestsParams,EngineeringAnalyticsCiCardsParams,EngineeringAnalyticsCiFailureLogsParams,EngineeringAnalyticsCurrentBranchHealthParams,@@ -88,6 +90,39 @@ export const engineeringAnalyticsAuthorWorkflowCosts = async (})}+export const getEngineeringAnalyticsBrokenTestsUrl = (+ projectId: string,+ params?: EngineeringAnalyticsBrokenTestsParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/broken_tests/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/broken_tests/`+}++/**+ * The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct failures (by test id + normalized error signature) and classified by how each is behaving right now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. 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.+ */+export const engineeringAnalyticsBrokenTests = async (+ projectId: string,+ params?: EngineeringAnalyticsBrokenTestsParams,+ options?: RequestInit+): Promise<BrokenTestsResultApi> => {+ return apiMutator<BrokenTestsResultApi>(getEngineeringAnalyticsBrokenTestsUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsCiCardsUrl = (projectId: string, params?: EngineeringAnalyticsCiCardsParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsxindex a8688f373803..111e5bc024a0 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx@@ -6,7 +6,15 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'-import type { FlakyTestListApi, GitHubSourceApi, QuarantineFileApi } from '../generated/api.schemas'+import type {+ BrokenTestsResultApi,+ FlakyTestListApi,+ GitHubSourceApi,+ QuarantineFileApi,+} from '../generated/api.schemas'++// A fixed 24-slot hourly sparkline (oldest first) with the given recent tail — mirrors the endpoint's trend_24h.+const spark = (tail: number[]): number[] => [...new Array(24 - tail.length).fill(0), ...tail]const FLAKY_TESTS: FlakyTestListApi = {items: [@@ -16,6 +24,7 @@ const FLAKY_TESTS: FlakyTestListApi = {rerun_passed_count: 6,failed_count: 4,failed_pr_count: 3,+ master_failed_count: 2,branch_count: 5,xfailed_count: 0,last_seen_at: '2026-07-01T18:30:00Z',@@ -26,6 +35,7 @@ const FLAKY_TESTS: FlakyTestListApi = {rerun_passed_count: 0,failed_count: 9,failed_pr_count: 4,+ master_failed_count: 5,branch_count: 4,xfailed_count: 0,last_seen_at: '2026-07-01T09:12:00Z',@@ -36,6 +46,7 @@ const FLAKY_TESTS: FlakyTestListApi = {rerun_passed_count: 2,failed_count: 1,failed_pr_count: 1,+ master_failed_count: 0,branch_count: 3,xfailed_count: 3,last_seen_at: '2026-06-30T22:45:00Z',@@ -46,6 +57,7 @@ const FLAKY_TESTS: FlakyTestListApi = {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',@@ -79,6 +91,79 @@ const QUARANTINE: QuarantineFileApi = {generated_at: '2026-07-02T12:00:00Z',}+const BROKEN_TESTS: BrokenTestsResultApi = {+ rows: [+ {+ fingerprint: 'products/checkout/test_flow.py::test_checkout | assert N == N',+ test_id: 'products/checkout/test_flow.py::test_checkout',+ error_signature: 'AssertionError: expected 200, got 500',+ job_name: 'Django tests – Core (12/22)',+ repo: 'PostHog/posthog',+ state: 'breaking_master',+ first_seen: '2026-06-30T08:00:00Z',+ last_seen: '2026-07-02T11:40:00Z',+ occurrences: 41,+ branches: 5,+ master_hits: 6,+ latest_run_id: 9001,+ latest_branch: 'master',+ trend_24h: spark([1, 3, 6, 8]),+ },+ {+ fingerprint: 'posthog/api/test_serializer.py::test_contract | KeyError: N',+ test_id: 'posthog/api/test_serializer.py::test_contract',+ error_signature: 'KeyError: managed_viewset',+ job_name: 'Django tests – Core (4/22)',+ repo: 'PostHog/posthog',+ state: 'novel_burst',+ first_seen: '2026-07-02T05:00:00Z',+ last_seen: '2026-07-02T11:50:00Z',+ occurrences: 9,+ branches: 4,+ master_hits: 0,+ latest_run_id: 9002,+ latest_branch: 'feat/data-catalog',+ trend_24h: spark([2, 7]),+ },+ {+ fingerprint: 'posthog/temporal/test_async.py::test_race | ConnectionResetError',+ test_id: 'posthog/temporal/test_async.py::test_race',+ error_signature: 'ConnectionResetError',+ job_name: 'Playwright (2/8)',+ repo: 'PostHog/posthog',+ state: 'flaky',+ first_seen: '2026-06-28T14:00:00Z',+ last_seen: '2026-07-02T10:00:00Z',+ occurrences: 7,+ branches: 3,+ master_hits: 0,+ latest_run_id: 9004,+ latest_branch: 'fix/async-teardown',+ trend_24h: spark([1, 0, 1, 0, 0, 1]),+ },+ {+ fingerprint: 'posthog/flags/test_rollout.py::test_flag | Timeout',+ test_id: 'posthog/flags/test_rollout.py::test_flag',+ error_signature: 'Timeout waiting for flag',+ job_name: 'Frontend CI (3/6)',+ repo: 'PostHog/posthog',+ state: 'potentially_resolved',+ first_seen: '2026-06-29T09:00:00Z',+ last_seen: '2026-07-02T04:00:00Z',+ occurrences: 12,+ branches: 3,+ master_hits: 2,+ latest_run_id: 9003,+ latest_branch: 'master',+ trend_24h: spark([]),+ },+ ],+ breaking_master_jobs: ['Django tests – Core (12/22)'],+ window_days: 2,+ truncated: false,+ limit: 200,+}+const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]const meta: Meta = {@@ -98,6 +183,7 @@ const meta: Meta = {mswDecorator({get: {'api/projects/:team_id/engineering_analytics/flaky_tests/': FLAKY_TESTS,+ 'api/projects/:team_id/engineering_analytics/broken_tests/': BROKEN_TESTS,'api/projects/:team_id/engineering_analytics/quarantine/': QUARANTINE,'api/projects/:team_id/engineering_analytics/sources/': SOURCES,'api/projects/:team_id/engineering_analytics/ci_cards/': {diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsxindex 9c6ee79a015e..d3abadc76d10 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx@@ -10,6 +10,8 @@ import {LemonMenu,LemonSegmentedButton,LemonSelect,+ LemonSkeleton,+ LemonSwitch,LemonTable,LemonTableColumns,LemonTag,@@ -17,16 +19,19 @@ import {Tooltip,} from '@posthog/lemon-ui'+import { Sparkline } from 'lib/components/Sparkline'import { dayjs } from 'lib/dayjs'import { cn } from 'lib/utils/css-classes'import { humanFriendlyNumber } from 'lib/utils/numbers'import { pluralize } from 'lib/utils/strings'+import { BrokenTestStateTag } from '../components/BrokenTestStateTag'import { ConnectGitHubSource } from '../components/ConnectGitHubSource'import { QuarantineTestModal } from '../components/QuarantineTestModal'import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'import { StatCard } from '../components/StatCard'import {+ BrokenTestRow,FlakyTestRow,FlakyTestWindow,QuarantineEntryRow,@@ -80,6 +85,257 @@ function ModeTag({ mode }: { mode: QuarantineEntryRow['mode'] }): JSX.Element {)}+function RelativeTime({ iso }: { iso: string }): JSX.Element {+ return (+ <Tooltip title={dayjs(iso).format('YYYY-MM-DD HH:mm:ss')}>+ <span className="text-xs whitespace-nowrap text-secondary">{dayjs(iso).fromNow()}</span>+ </Tooltip>+ )+}++// Reads the `broken_tests` product endpoint: the failure fingerprints, the classifier that ranks+// them, and the two cluster reads it merges all run server-side. The row expansion lazy-loads the+// failing log lines for the row's latest run via run_failure_logs.+function BrokenTestDrilldown({ row }: { row: BrokenTestRow }): JSX.Element {+ const { runFailureLogsByRun, runFailureLogsByRunLoading, brokenTestsWindowDays } =+ useValues(engineeringAnalyticsLogic)+ const logs = row.latestRunId ? runFailureLogsByRun[row.latestRunId] : undefined+ const runUrl = row.repo && row.latestRunId ? `https://github.com/${row.repo}/actions/runs/${row.latestRunId}` : null++ return (+ <div className="flex flex-col gap-2 p-2">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-secondary">+ <span>+ Latest failing run on <span className="font-mono">{row.latestBranch || 'unknown branch'}</span>+ </span>+ <span>·</span>+ <span>+ {pluralize(row.occurrences, 'failure')} across {pluralize(row.branches, 'branch', 'branches')} in+ the last {brokenTestsWindowDays} days+ </span>+ {runUrl && (+ <Link to={runUrl} target="_blank" className="inline-flex items-center gap-1">+ View run on GitHub <IconExternal />+ </Link>+ )}+ </div>+ {!row.latestRunId ? (+ <span className="text-xs text-tertiary">No run id recorded for this failure — can't fetch logs.</span>+ ) : runFailureLogsByRunLoading && !logs ? (+ <LemonSkeleton className="h-24 w-full" />+ ) : !logs || !logs.logs_available || logs.jobs.length === 0 ? (+ <span className="text-xs text-tertiary">+ No failure logs for this run — it didn't fail, or the logs aged out of the short Logs retention.+ </span>+ ) : (+ <div className="flex flex-col gap-3">+ {logs.jobs.map((job) => (+ <div key={job.job_id} className="flex flex-col gap-1">+ <div className="font-mono text-xs font-semibold text-secondary">+ {job.branch || 'unknown'} · job {job.job_id} · {job.conclusion}+ {job.truncated && ' · truncated'}+ </div>+ <pre className="m-0 overflow-x-auto rounded border bg-bg-3000 p-2 font-mono text-xs leading-snug">+ {job.lines.map((line, idx) => (+ <div+ key={idx}+ className={cn(line.original_line === null && 'italic text-tertiary')}+ >+ <span className="mr-3 inline-block w-12 select-none text-right text-tertiary">+ {line.original_line ?? ''}+ </span>+ {line.text}+ </div>+ ))}+ </pre>+ </div>+ ))}+ </div>+ )}+ </div>+ )+}++function BrokenTestsPanel(): JSX.Element {+ const {+ visibleBrokenTests,+ brokenTestsData,+ brokenTestsDataLoading,+ brokenTestsError,+ brokenTestsWindowDays,+ breakingMasterJobs,+ hiddenBrokenTestCount,+ showPrOnlyBrokenTests,+ } = useValues(engineeringAnalyticsLogic)+ const { setShowPrOnlyBrokenTests, loadRunFailureLogs } = useActions(engineeringAnalyticsLogic)++ const columns: LemonTableColumns<BrokenTestRow> = [+ {+ title: 'State',+ key: 'state',+ width: 160,+ render: (_, row) => <BrokenTestStateTag state={row.state} />,+ },+ {+ title: 'Test',+ key: 'testId',+ width: 320,+ render: (_, row) => (+ <Tooltip title={row.testId}>+ <span className="block max-w-[20rem] truncate font-mono text-xs">{row.testId}</span>+ </Tooltip>+ ),+ },+ {+ title: 'Error',+ key: 'errorSignature',+ render: (_, row) =>+ row.errorSignature ? (+ <Tooltip title={row.errorSignature}>+ <span className="line-clamp-2 max-w-[22rem] text-xs text-secondary">{row.errorSignature}</span>+ </Tooltip>+ ) : (+ <span className="text-tertiary">—</span>+ ),+ },+ {+ title: 'Occurrences',+ key: 'occurrences',+ width: 110,+ align: 'right',+ sorter: (a, b) => a.occurrences - b.occurrences,+ render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.occurrences)}</span>,+ },+ {+ title: 'Branches',+ key: 'branches',+ width: 100,+ align: 'right',+ sorter: (a, b) => a.branches - b.branches,+ render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.branches)}</span>,+ },+ {+ title: 'Master hits',+ key: 'masterHits',+ width: 110,+ align: 'right',+ sorter: (a, b) => a.masterHits - b.masterHits,+ render: (_, row) =>+ row.masterHits > 0 ? (+ <span className="tabular-nums font-semibold text-danger">+ {humanFriendlyNumber(row.masterHits)}+ </span>+ ) : (+ <span className="tabular-nums text-tertiary">0</span>+ ),+ },+ {+ title: 'First seen',+ key: 'firstSeen',+ width: 110,+ align: 'right',+ sorter: (a, b) => a.firstSeen.localeCompare(b.firstSeen),+ render: (_, row) => <RelativeTime iso={row.firstSeen} />,+ },+ {+ title: 'Last seen',+ key: 'lastSeen',+ width: 110,+ align: 'right',+ sorter: (a, b) => a.lastSeen.localeCompare(b.lastSeen),+ render: (_, row) => <RelativeTime iso={row.lastSeen} />,+ },+ {+ title: 'Trend (24h)',+ key: 'trend',+ width: 140,+ tooltip: 'Failures per hour over the last 24 hours — a climbing bar means it is escalating right now.',+ render: (_, row) => {+ const series = row.trend+ return series && series.some((n) => n > 0) ? (+ <Sparkline data={series} type="bar" color="danger" maximumIndicator={false} className="h-8 w-28" />+ ) : (+ <span className="text-tertiary">—</span>+ )+ },+ },+ ]++ return (+ <div className="flex flex-col gap-4">+ <div className="flex items-start justify-between gap-2">+ <div className="flex flex-col gap-0.5">+ <h3 className="m-0 text-base font-semibold">Currently broken tests</h3>+ <p className="m-0 max-w-2xl text-xs text-tertiary">+ Failures over the last {brokenTestsWindowDays} days, grouped by whether they're breaking trunk+ right now, resolving, or just flaky — inferred from CI logs + master job history. Expand a row+ for the latest failing run's logs.+ </p>+ </div>+ <LemonSwitch+ label="Show PR-only failures"+ checked={showPrOnlyBrokenTests}+ onChange={setShowPrOnlyBrokenTests}+ size="small"+ bordered+ />+ </div>+ {brokenTestsError ? (+ <LemonBanner type="error">Couldn't load broken tests: {brokenTestsError}</LemonBanner>+ ) : brokenTestsDataLoading && !brokenTestsData ? (+ <LemonSkeleton className="h-48 w-full" />+ ) : (+ <>+ {breakingMasterJobs.length > 0 ? (+ <LemonBanner type="error">+ Breaking master: {pluralize(breakingMasterJobs.length, 'job group')} —{' '}+ {breakingMasterJobs.join(', ')}+ </LemonBanner>+ ) : (+ <LemonBanner type="success">+ Nothing is flagged as breaking master right now. Failures that hit trunk only show here once+ their job's latest master run is known to be red, so this needs the job-level source synced.+ </LemonBanner>+ )}+ <LemonTable+ data-attr="engineering-analytics-broken-tests-table"+ size="small"+ columns={columns}+ dataSource={visibleBrokenTests}+ rowKey={(row) => row.fingerprint}+ loading={brokenTestsDataLoading}+ pagination={{ pageSize: 10 }}+ useURLForSorting={false}+ emptyState="No broken tests to show. Nothing is breaking trunk right now."+ nouns={['broken test', 'broken tests']}+ expandable={{+ noIndent: true,+ onRowExpand: (row) => {+ if (row.latestRunId) {+ loadRunFailureLogs({ runId: row.latestRunId })+ }+ },+ expandedRowRender: (row) => <BrokenTestDrilldown row={row} />,+ }}+ />+ {brokenTestsData?.truncated && (+ <div className="text-xs text-tertiary">+ Showing the top {brokenTestsData.limit} by urgency — more distinct failures matched than+ fit.+ </div>+ )}+ {hiddenBrokenTestCount > 0 && !showPrOnlyBrokenTests && (+ <div className="text-xs text-tertiary">+ {pluralize(hiddenBrokenTestCount, 'PR-only failure')} hidden — toggle "Show PR-only+ failures" to include them.+ </div>+ )}+ </>+ )}+ </div>+ )+}+function FlakyTestLeaderboard(): JSX.Element {const { flakyTests, flakyTestsLoading, flakyTestsStatus, flakyTestWindow } = useValues(engineeringAnalyticsLogic)const { setFlakyTestWindow, openQuarantineModal } = useActions(engineeringAnalyticsLogic)@@ -138,6 +394,23 @@ function FlakyTestLeaderboard(): JSX.Element {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',@@ -244,6 +517,7 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {<div className="flex flex-col gap-8">{/* Tab-level: both sections read the same source, so the picker scopes them together. */}<ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />+ <BrokenTestsPanel /><FlakyTestLeaderboard /><QuarantineRegister />{/* Rendered once for the whole tab: the leaderboard rows, the register rows, and thediff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex a7468ba70889..6e4d7ef39233 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -11,20 +11,24 @@ import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'import {+ engineeringAnalyticsBrokenTests,engineeringAnalyticsCiCards,engineeringAnalyticsFlakyTests,engineeringAnalyticsPullRequests,engineeringAnalyticsQuarantine,engineeringAnalyticsQuarantineRequest,+ engineeringAnalyticsRunFailureLogs,engineeringAnalyticsSources,engineeringAnalyticsWorkflowHealth,} from '../generated/api'import type {+ BrokenTestRowApi,GitHubSourceApi,PullRequestListItemApi,PushCISampleApi,QuarantineRequestApi,QuarantineRequestResultApi,+ RunFailureLogsApi,} from '../generated/api.schemas'import { CIStatus, ciStatusOf } from '../lib/ci'import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'@@ -442,6 +446,8 @@ export interface FlakyTestRow {failedCount: number/** Distinct PRs among the failures; master/branch failures carry no PR and don't count here. */failedPrCount: 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: numberlastSeenAt: string@@ -454,6 +460,62 @@ export interface FlakyTestsData {limit: number}+// ── Broken-tests panel ─────────────────────────────────────────────────────────────+// Live CI failures classified by how each is behaving right now — breaking trunk, novel, resolving,+// flaky, or one PR's problem — ranked most-urgent first. The classifier and the two cluster reads it+// merges run server-side in the `broken_tests` product endpoint (logic/queries/broken_tests.py); the+// UI just renders the typed rows, so there is no client-side HogQL or classifier here any more.++export type BrokenTestState = BrokenTestRowApi['state']++/** A classified CI-failure fingerprint, camelCased from the endpoint row. `trend` is the fixed+ * 24-slot hourly failure count (oldest first) the row sparkline renders. */+export interface BrokenTestRow {+ fingerprint: string+ testId: string+ errorSignature: string+ jobName: string+ repo: string+ state: BrokenTestState+ firstSeen: string+ lastSeen: string+ occurrences: number+ branches: number+ masterHits: number+ // Most recent failing run for this fingerprint — the anchor the row expansion fetches logs for.+ latestRunId: number+ latestBranch: string+ trend: number[]+}++export interface BrokenTestsData {+ rows: BrokenTestRow[]+ // Default-branch jobs whose latest run is red — drives the panel's summary banner.+ breakingMasterJobs: string[]+ windowDays: number+ truncated: boolean+ limit: number+}++function toBrokenTestRow(it: BrokenTestRowApi): BrokenTestRow {+ return {+ fingerprint: it.fingerprint,+ testId: it.test_id,+ errorSignature: it.error_signature,+ jobName: it.job_name,+ repo: it.repo,+ state: it.state,+ firstSeen: it.first_seen,+ lastSeen: it.last_seen,+ occurrences: it.occurrences,+ branches: it.branches,+ masterHits: it.master_hits,+ latestRunId: it.latest_run_id,+ latestBranch: it.latest_branch,+ trend: it.trend_24h ?? [],+ }+}+export type QuarantineRequestAction = 'quarantine' | 'extend' | 'remove'/** What the tab submits to the write endpoint; the backend opens the issue + PR. */@@ -573,6 +635,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyopenQuarantineModal: (state: QuarantineModalState) => ({ state }),closeQuarantineModal: true,setFlakyTestWindow: (window: FlakyTestWindow) => ({ window }),+ setShowPrOnlyBrokenTests: (show: boolean) => ({ show }),refresh: true,}),@@ -693,6 +756,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyrerunPassedCount: it.rerun_passed_count,failedCount: it.failed_count,failedPrCount: it.failed_pr_count,+ masterFailedCount: it.master_failed_count,xfailedCount: it.xfailed_count,lastSeenAt: it.last_seen_at,})@@ -703,6 +767,45 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy},},],+ brokenTestsData: [+ null as BrokenTestsData | null,+ {+ loadBrokenTests: async (): Promise<BrokenTestsData> => {+ const data = await engineeringAnalyticsBrokenTests(projectId(), {+ source_id: values.sourceId ?? undefined,+ })+ return {+ rows: data.rows.map(toBrokenTestRow),+ breakingMasterJobs: data.breaking_master_jobs,+ windowDays: data.window_days,+ truncated: data.truncated,+ limit: data.limit,+ }+ },+ },+ ],+ runFailureLogsByRun: [+ {} as Record<number, RunFailureLogsApi>,+ {+ loadRunFailureLogs: async ({+ runId,+ }: {+ runId: number+ }): Promise<Record<number, RunFailureLogsApi>> => {+ // Lazy: fetched when a broken-test row is expanded, cached per run so re-expanding+ // is free. Rides the product's own engineering_analytics endpoint (not raw /query/),+ // so it authorizes under the same scope the rest of the panel uses.+ if (!runId || values.runFailureLogsByRun[runId]) {+ return values.runFailureLogsByRun+ }+ const result = await engineeringAnalyticsRunFailureLogs(projectId(), {+ run_id: runId,+ source_id: values.sourceId ?? undefined,+ })+ return { ...values.runFailureLogsByRun, [runId]: result }+ },+ },+ ],quarantineSubmit: [null as QuarantineRequestResultApi | null,{@@ -836,6 +939,8 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyDEFAULT_FLAKY_TEST_WINDOW as FlakyTestWindow,{ setFlakyTestWindow: (_, { window }) => window },],+ // 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.flakyTestsStatus: [@@ -846,6 +951,16 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyloadFlakyTestsFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),},],+ // Prototype panel reads two views directly; if either isn't provisioned the query errors,+ // which the panel surfaces in-place instead of crashing the tab.+ brokenTestsError: [+ null as string | null,+ {+ loadBrokenTests: () => null,+ loadBrokenTestsSuccess: () => null,+ loadBrokenTestsFailure: (_, { error }) => error ?? 'Could not load broken tests.',+ },+ ],quarantineModal: [null as QuarantineModalState | null,{@@ -1026,6 +1141,28 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy(filters): boolean =>!objectsEqual({ ...filters, search: filters.search.trim() }, DEFAULT_QUARANTINE_FILTERS),],+ // Classified rows come pre-ranked from the endpoint (severity, then last_seen desc).+ brokenTests: [+ (s) => [s.brokenTestsData],+ (brokenTestsData): BrokenTestRow[] => brokenTestsData?.rows ?? [],+ ],+ breakingMasterJobs: [+ (s) => [s.brokenTestsData],+ (brokenTestsData): string[] => brokenTestsData?.breakingMasterJobs ?? [],+ ],+ brokenTestsWindowDays: [+ (s) => [s.brokenTestsData],+ (brokenTestsData): number => brokenTestsData?.windowDays ?? 2,+ ],+ hiddenBrokenTestCount: [+ (s) => [s.brokenTests],+ (brokenTests: BrokenTestRow[]): number => brokenTests.filter((row) => row.state === 'pr_only').length,+ ],+ visibleBrokenTests: [+ (s) => [s.brokenTests, s.showPrOnlyBrokenTests],+ (brokenTests: BrokenTestRow[], showPrOnly): BrokenTestRow[] =>+ showPrOnly ? brokenTests : brokenTests.filter((row) => row.state !== 'pr_only'),+ ],hasMultipleSources: [(s) => [s.githubSources], (githubSources): boolean => githubSources.length > 1],// The source reads resolve to: the picked one, else the backend default (oldest connected = first).activeSource: [@@ -1050,6 +1187,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyactions.loadWorkflowHealth()actions.loadQuarantine()actions.loadFlakyTests()+ actions.loadBrokenTests()},setFlakyTestWindow: () => actions.loadFlakyTests(),setSourceId: () => actions.refresh(),diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex eb2cebb55970..fab9b9e6b7ce 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -12,6 +12,31 @@ tools:engineering-analytics-author-workflow-costs:operation: engineering_analytics_author_workflow_costsenabled: false+ engineering-analytics-broken-tests:+ operation: engineering_analytics_broken_tests+ enabled: true+ scopes:+ - engineering_analytics:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Broken tests triage+ 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).+ feature_flag: engineering-analyticsengineering-analytics-ci-cards:operation: engineering_analytics_ci_cardsenabled: false@@ -105,7 +130,23 @@ tools:enabled: falseengineering-analytics-run-failure-logs:operation: engineering_analytics_run_failure_logs- enabled: false+ enabled: true+ scopes:+ - engineering_analytics:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: CI failure logs for a run+ description: >+ The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of+ ci-failure-logs, for when you have a run id rather than a PR (default-branch failures, the broken-tests+ panel's latest_run_id, the run page). Each failed job returns its failure region (error lines plus+ surrounding context, with "... N lines omitted ..." markers) as ordered lines, every line carrying its+ original 1-based line number in the full pre-thinning log. logs_available is false when the run didn't fail+ or its logs aged out of the short Logs retention. Use ci-failure-logs instead when you have a PR number and+ want all its runs' failures.+ feature_flag: engineering-analyticsengineering-analytics-sources:operation: engineering_analytics_sourcesenabled: truediff --git a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.mdindex eabfff6eb39f..3aa512e1e29c 100644--- a/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md+++ b/products/engineering_analytics/skills/investigating-ci-failures/SKILL.md@@ -30,6 +30,17 @@ Two warehouse views are the substrate (both non-materialized — always current,Copy-ready SQL for every step is in [references/investigation-queries.md](./references/investigation-queries.md).+## Start wide: what's broken right now++For "what CI failures should I care about right now" (before you have a specific test in hand), the+`engineering-analytics-broken-tests` MCP tool does the shape classification below across _all_ live+failures at once: it groups the last 2 days of failures by fingerprint and labels each+`breaking_master` / `novel_burst` / `potentially_resolved` / `flaky` / `pr_only`, most urgent first,+plus `breaking_master_jobs` (default-branch jobs whose latest run is red). Use it as the triage entry+point, then drop into the per-failure workflow below to reach a culprit. It is the automated+counterpart to fingerprinting by hand; the manual queries stay the way to pin a specific failure to a+boundary and author.+## The three failure shapesFingerprint the failure first (query 1 in the references), then read its shape — the classification@@ -102,6 +113,7 @@ threshold aren't recorded, so there is no honest denominator.| Question | Use || -------------------------------------- | ---------------------------------------------------------------------- |+| "What's broken across CI right now?" | `engineering-analytics-broken-tests` MCP tool (triaged, classified) || "Why did MY PR's CI fail?" | `engineering-analytics-ci-failure-logs` MCP tool (PR-scoped, grouped) || "Who broke master / when did X start?" | The two views, workflow above || "Is X flaky?" | Shape from `ci_failures` + the flaky-tests tool |diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 225c5a8585dc..7bd2a4ec2f32 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2606,6 +2606,21 @@"readOnlyHint": true}},+ "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).",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "Broken tests triage",+ "title": "Broken tests triage",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "engineering-analytics"+ },"engineering-analytics-ci-failure-logs": {"description": "The thinned CI failure logs for a pull request, grouped by failed job — reach for this to answer \"why did this PR's CI fail\". Each failed job returns its failure region (the error lines plus surrounding context, with \"... N lines omitted ...\" markers) as ordered lines, and every line carries its original 1-based line number in the full pre-thinning log so you can locate it in the raw GitHub log. The PR is resolved to ALL its workflow runs across every push (via the pull_requests association, not the latest commit), so earlier pushes' failures are included too. logs_available is false when CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR has no run association to resolve. Use pr-runs or workflow-jobs for the run/job metadata behind these logs.","category": "Engineering analytics",@@ -2651,6 +2666,21 @@},"feature_flag": "engineering-analytics"},+ "engineering-analytics-run-failure-logs": {+ "description": "The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of ci-failure-logs, for when you have a run id rather than a PR (default-branch failures, the broken-tests panel's latest_run_id, the run page). Each failed job returns its failure region (error lines plus surrounding context, with \"... N lines omitted ...\" markers) as ordered lines, every line carrying its original 1-based line number in the full pre-thinning log. logs_available is false when the run didn't fail or its logs aged out of the short Logs retention. Use ci-failure-logs instead when you have a PR number and want all its runs' failures.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "CI failure logs for a run",+ "title": "CI failure logs for a run",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "engineering-analytics"+ },"engineering-analytics-sources": {"description": "The team's connected GitHub data warehouse sources, oldest first, each with its id, repo (owner/name), and table prefix. Call this first when a team may have more than one GitHub source, then pass a chosen id as source_id to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific source. With a single source you can skip it — the other tools default to the oldest connected source. The prefix also names the underlying warehouse tables (prefix + github_pull_requests / github_workflow_runs / github_workflow_jobs), which you can query directly with SQL or save as SQL insights and subscriptions when the named tools don't fit (timestamps land as strings; parse with parseDateTimeBestEffort).","category": "Engineering analytics",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 20a68534221e..7c1d0ae6a1ed 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2649,6 +2649,21 @@"readOnlyHint": true}},+ "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).",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "Broken tests triage",+ "title": "Broken tests triage",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "engineering-analytics"+ },"engineering-analytics-ci-failure-logs": {"description": "The thinned CI failure logs for a pull request, grouped by failed job — reach for this to answer \"why did this PR's CI fail\". Each failed job returns its failure region (the error lines plus surrounding context, with \"... N lines omitted ...\" markers) as ordered lines, and every line carries its original 1-based line number in the full pre-thinning log so you can locate it in the raw GitHub log. The PR is resolved to ALL its workflow runs across every push (via the pull_requests association, not the latest commit), so earlier pushes' failures are included too. logs_available is false when CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR has no run association to resolve. Use pr-runs or workflow-jobs for the run/job metadata behind these logs.","category": "Engineering analytics",@@ -2694,6 +2709,21 @@},"feature_flag": "engineering-analytics"},+ "engineering-analytics-run-failure-logs": {+ "description": "The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of ci-failure-logs, for when you have a run id rather than a PR (default-branch failures, the broken-tests panel's latest_run_id, the run page). Each failed job returns its failure region (error lines plus surrounding context, with \"... N lines omitted ...\" markers) as ordered lines, every line carrying its original 1-based line number in the full pre-thinning log. logs_available is false when the run didn't fail or its logs aged out of the short Logs retention. Use ci-failure-logs instead when you have a PR number and want all its runs' failures.",+ "category": "Engineering analytics",+ "feature": "engineering_analytics",+ "summary": "CI failure logs for a run",+ "title": "CI failure logs for a run",+ "required_scopes": ["engineering_analytics:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "engineering-analytics"+ },"engineering-analytics-sources": {"description": "The team's connected GitHub data warehouse sources, oldest first, each with its id, repo (owner/name), and table prefix. Call this first when a team may have more than one GitHub source, then pass a chosen id as source_id to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific source. With a single source you can skip it — the other tools default to the oldest connected source. The prefix also names the underlying warehouse tables (prefix + github_pull_requests / github_workflow_runs / github_workflow_jobs), which you can query directly with SQL or save as SQL insights and subscriptions when the named tools don't fit (timestamps land as strings; parse with parseDateTimeBestEffort).","category": "Engineering analytics",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 39f524540fe9..268861864ea8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12294,6 +12294,74 @@ export namespace Schemas {has_more: boolean;}+ /**+ * * `breaking_master` - BREAKING_MASTER+ * * `novel_burst` - NOVEL_BURST+ * * `potentially_resolved` - POTENTIALLY_RESOLVED+ * * `flaky` - FLAKY+ * * `pr_only` - PR_ONLY+ */+ export type BrokenTestRowStateEnum = typeof BrokenTestRowStateEnum[keyof typeof BrokenTestRowStateEnum];+++ export const BrokenTestRowStateEnum = {+ BreakingMaster: 'breaking_master',+ NovelBurst: 'novel_burst',+ PotentiallyResolved: 'potentially_resolved',+ Flaky: 'flaky',+ PrOnly: 'pr_only',+ } as const;++ export interface BrokenTestRow {+ /** Stable identity of this distinct failure: the failing test's node id plus a normalized error signature, so the same failure across runs groups into one row. */+ fingerprint: string;+ /** The pytest node id from the CI 'FAILED <id>' line — the failing test. */+ test_id: string;+ /** The trailing failure detail with volatile bits (numbers, hashes) normalized, shared across runs of the same failure. Empty when the FAILED line carried no detail. */+ error_signature: string;+ /** The CI job the failure most recently came from. Matched against default-branch job status to decide whether trunk is currently broken by it. */+ job_name: string;+ /** 'owner/name' repository the failure belongs to. */+ repo: string;+ /** The classifier's verdict on how this failure is behaving right now: 'breaking_master' (failing on trunk, latest trunk run still red), 'novel_burst' (new within a day and spreading across branches, not on trunk yet), 'potentially_resolved' (hit trunk but trunk is green again), 'flaky' (sporadic across branches over more than a day), or 'pr_only' (confined to one branch — one PR's own problem).+ *+ * * `breaking_master` - BREAKING_MASTER+ * * `novel_burst` - NOVEL_BURST+ * * `potentially_resolved` - POTENTIALLY_RESOLVED+ * * `flaky` - FLAKY+ * * `pr_only` - PR_ONLY */+ state: BrokenTestRowStateEnum;+ /** Earliest failure line for this fingerprint in the analysis window. */+ first_seen: string;+ /** Most recent failure line for this fingerprint in the analysis window. */+ last_seen: string;+ /** Total failure lines for this fingerprint in the window. An absolute count, never a rate — passing runs aren't in this data. */+ occurrences: number;+ /** Distinct branches the failure appeared on in the window. */+ branches: number;+ /** Failure lines on the default branch (master/main). 0 means it never reached trunk. */+ master_hits: number;+ /** The most recent failing workflow run for this fingerprint — pass it to run_failure_logs to fetch the actual failing log lines. */+ latest_run_id: number;+ /** The branch of the most recent failing run. */+ latest_branch: string;+ /** Hourly failure counts over the last 24 hours, oldest first (fixed 24-slot array), for the row sparkline. All zeros when nothing failed in the last day. */+ trend_24h?: number[];+ }++ export interface BrokenTestsResult {+ /** Classified failures ranked by triage urgency — breaking trunk first, single-PR failures last. */+ rows: BrokenTestRow[];+ /** Default-branch job names whose latest completed run is failing — the 'what's on fire right now' summary. Empty when the job-level source isn't synced or trunk is green. */+ breaking_master_jobs: string[];+ /** Length in days of the analysis window the counts cover. */+ window_days: number;+ /** True when more failures qualified than the cap; `rows` is the top `limit` by urgency. */+ truncated: boolean;+ /** Maximum number of rows returned. */+ limit: number;+ }+/*** * `distinct_id` - User ID (default)* * `device_id` - Device ID@@ -27290,6 +27358,8 @@ export namespace Schemas {failed_count: number;/** Distinct pull requests among the failed/error spans. Failures on master or unattributed branches carry no PR number and are excluded here (still in failed_count). */failed_pr_count: number;+ /** 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. */@@ -69963,6 +70033,13 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsBrokenTestsParams = {+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.+ */+ source_id?: string;+ };+export type EngineeringAnalyticsCiCardsParams = {/*** 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 497e7b412200..058ddcece493 100644--- a/services/mcp/src/generated/engineering_analytics/api.ts+++ b/services/mcp/src/generated/engineering_analytics/api.ts@@ -3,11 +3,31 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 9 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'+/**+ * The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct failures (by test id + normalized error signature) and classified by how each is behaving right now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. 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.+ */+export const EngineeringAnalyticsBrokenTestsParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const EngineeringAnalyticsBrokenTestsQueryParams = /* @__PURE__ */ zod.object({+ source_id: zod+ .string()+ .optional()+ .describe(+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'+ ),+})+/*** The thinned CI failure logs for a pull request, grouped by failed job. Resolves the PR to its workflow runs via the pull_requests association (all of the PR's pushes, not just the latest commit), then reads the Logs product joined on run_id. Returns failed jobs only (the worker fetches logs for failures); logs_available is false when CI hasn't failed, the logs aged out of the short Logs retention, or a fork PR has no run association. Each line carries its original 1-based line number in the full pre-thinning log; lines are the failure region (errors plus surrounding context, with omission markers), capped per job and overall.*/@@ -136,6 +156,27 @@ export const EngineeringAnalyticsPullRequestsQueryParams = /* @__PURE__ */ zod.o),})+/**+ * The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of ci_failure_logs for surfaces that aren't PR-scoped (default-branch failures, the run page). logs_available is false when the run didn't fail or its logs aged out of the short Logs retention.+ */+export const EngineeringAnalyticsRunFailureLogsParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const EngineeringAnalyticsRunFailureLogsQueryParams = /* @__PURE__ */ zod.object({+ run_id: zod.number().describe('Workflow run id whose failure logs to fetch.'),+ source_id: zod+ .string()+ .optional()+ .describe(+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'+ ),+})+/*** The team's connected GitHub data warehouse sources, oldest first. Populate a source picker from this and pass a chosen `id` back as `source_id` to the other endpoints. A team can connect GitHub more than once (e.g. one source per repository); this lists them all, including any whose tables aren't fully synced yet.*/diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.tsindex 9cecccec56f5..e4753a83ebb2 100644--- a/services/mcp/src/tools/generated/engineering_analytics.ts+++ b/services/mcp/src/tools/generated/engineering_analytics.ts@@ -3,11 +3,13 @@ import { z } from 'zod'import type { Schemas } from '@/api/generated'import {+ EngineeringAnalyticsBrokenTestsQueryParams,EngineeringAnalyticsCiFailureLogsQueryParams,EngineeringAnalyticsFlakyTestsQueryParams,EngineeringAnalyticsPrCostQueryParams,EngineeringAnalyticsPrLifecycleQueryParams,EngineeringAnalyticsPullRequestsQueryParams,+ EngineeringAnalyticsRunFailureLogsQueryParams,EngineeringAnalyticsWorkflowHealthQueryParams,EngineeringAnalyticsWorkflowJobsQueryParams,EngineeringAnalyticsWorkflowRunnerCostsQueryParams,@@ -15,6 +17,27 @@ import {import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'+const EngineeringAnalyticsBrokenTestsSchema = EngineeringAnalyticsBrokenTestsQueryParams++const engineeringAnalyticsBrokenTests = (): ToolBase<+ typeof EngineeringAnalyticsBrokenTestsSchema,+ Schemas.BrokenTestsResult+> => ({+ name: 'engineering-analytics-broken-tests',+ schema: EngineeringAnalyticsBrokenTestsSchema,+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsBrokenTestsSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.BrokenTestsResult>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/broken_tests/`,+ query: {+ source_id: params.source_id,+ },+ })+ return result+ },+})+const EngineeringAnalyticsCiFailureLogsSchema = EngineeringAnalyticsCiFailureLogsQueryParamsconst engineeringAnalyticsCiFailureLogs = (): ToolBase<@@ -84,6 +107,28 @@ const engineeringAnalyticsPrCost = (): ToolBase<typeof EngineeringAnalyticsPrCos},})+const EngineeringAnalyticsRunFailureLogsSchema = EngineeringAnalyticsRunFailureLogsQueryParams++const engineeringAnalyticsRunFailureLogs = (): ToolBase<+ typeof EngineeringAnalyticsRunFailureLogsSchema,+ Schemas.RunFailureLogs+> => ({+ name: 'engineering-analytics-run-failure-logs',+ schema: EngineeringAnalyticsRunFailureLogsSchema,+ handler: async (context: Context, params: z.infer<typeof EngineeringAnalyticsRunFailureLogsSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.RunFailureLogs>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/run_failure_logs/`,+ query: {+ run_id: params.run_id,+ source_id: params.source_id,+ },+ })+ return result+ },+})+const EngineeringAnalyticsSourcesSchema = z.object({})const engineeringAnalyticsSources = (): ToolBase<@@ -229,9 +274,11 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<})export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'engineering-analytics-broken-tests': engineeringAnalyticsBrokenTests,'engineering-analytics-ci-failure-logs': engineeringAnalyticsCiFailureLogs,'engineering-analytics-flaky-tests': engineeringAnalyticsFlakyTests,'engineering-analytics-pr-cost': engineeringAnalyticsPrCost,+ 'engineering-analytics-run-failure-logs': engineeringAnalyticsRunFailureLogs,'engineering-analytics-sources': engineeringAnalyticsSources,'engineering-analytics-workflow-jobs': engineeringAnalyticsWorkflowJobs,'engineering-analytics-workflow-runner-costs': engineeringAnalyticsWorkflowRunnerCosts,