: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(eng-analytics): trunk quarantine debt scoreboard (#90952)
Raúl Negrón-Oteroacdb1f6ea103
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d31b63e7eebc..f52f7d2a613b 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6424,10 +6424,10 @@ snapshots:hash: v1.k794b7964.7f17c5ac7c6862493f7c4d59e6e3c3146c42e3d7b08908ee1716d387c129ba64.lPsE9KrOSZee9wJq8zjqYnvk09numvEFWOn4mdCOgJEscenes-app-engineering-analytics-run-activity-chart--default--light:hash: v1.k794b7964.f63752ff3ebf3bbee3be4ddc83d1ff657d9cdd11ee71e7283c30ce5a1aefde72.yTb8kpRqcG51TbM2CqgRmC5YvgE7-6pV1Trc7y5wuto- scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--dark:- hash: v1.k794b7964.08e498898aa4436459dfa3b9afcb743d9ef5bddef4b887544a7dd5ada869a319.SuwJaPoLme6T0CusTJ4qMfeL8ieOiczYKySe06STXhQ- scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--light:- hash: v1.k794b7964.b241a075f9538da83fab55dfb1af54896ec9c6f43cfc3db4d374fcedef606777.0UlzoD6n70FR5PA_Lj8S8L4xtah1AqdGsy9VrKZQ5is+ scenes-app-engineering-analytics-test-health--trunk-quarantine-debt--dark:+ hash: v1.k794b7964.1bf2a96d4a8f8875fc554a67e7e7b28adc98b144607babe0ae8342de5a0f3edc.JM5CCK4syW_o4_XReB3Nn6NUpB0I643u2a05XZmoeck+ scenes-app-engineering-analytics-test-health--trunk-quarantine-debt--light:+ hash: v1.k794b7964.1f330c8921d0151e1a846cf3cdccd6cd8196fd012630780b3a20491cc5ff293f.oEUS4LgdANupAGuZ7t8vmArgxuzi4IBEIJIlWHFXOAwscenes-app-error-project-unavailable--access-revoked--dark:hash: v1.k794b7964.30ace8f015100159e1dedbed07ff9f0b0b770535870d5c98ea764b10ff1f7621.dTVw9qLa7D_e7ZNme4tVuPZov-0Gg1o84aiDl5zihF0scenes-app-error-project-unavailable--access-revoked--light:diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex 02ec46ec95f6..142eafcf6c18 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -81,8 +81,8 @@ graph LR```- Job-level CI: per-job duration, queue time, runner tier, and dollar cost ride `workflow_jobs` (webhook stream plus bounded backfill).-- One write surface: test quarantine. The UI files a tracking issue plus a PR against the repo's checked-in `.test_quarantine.json` through the team's GitHub App. Everything else is read-only.-- The test-health view is an active work queue, not a failure-rate leaderboard: the main pytest and Jest suites emit failures and same-job re-run recovery evidence. Jest writes a small marker beside JUnit when quarantine tolerates a failure, so masking it does not erase the signal. Evidence is counted per CI run, a test is called flaky only where one commit was seen both failing and passing it, and every other failure ranks as an honest suspected regression by blast radius. Callers can filter by `runner` before ranking and limiting when they need a runner-specific queue. The weekly Slack report requests each runner separately and shows up to 10 pytest tests followed by up to 10 Jest tests; it is informational, so suppressed tests stay listed with their quarantine state. Logs-based rescue counts and links remain pytest-only.+- One write surface: test quarantine. The `quarantine/request` endpoint files a tracking issue plus a PR against the repo's checked-in `.test_quarantine.json` through the team's GitHub App; it is reachable via the API and MCP only, with no in-app UI. Everything else is read-only.+- The test-health view is the Trunk quarantine debt scoreboard: every test Trunk currently quarantines, attributed to its owning team from the span-stamped ownership, aged against a TTL, and rolled up per team. A quarantine masks a failure without fixing it, so the board is the standing work queue of masked tests. The flaky-test queue itself (failures plus same-commit recovery evidence from the pytest and Jest suites, counted per CI run, ranked by blast radius) remains an endpoint and MCP tool; the weekly Slack report requests each runner separately and shows up to 10 pytest tests followed by up to 10 Jest tests; it is informational, so suppressed tests stay listed with their quarantine state. Logs-based rescue counts and links remain pytest-only.- Access control: per-user warehouse RBAC at the source resolver, `engineering_analytics:read` scopes on tools, feature-flag gated.## The goal: CI Signals for PostHog Desktop@@ -114,7 +114,7 @@ Change one only in a separate PR with a written reason. Engineering-level decisi- Unit of value = the open PR. Phase model: draft (low rigor) vs ready-for-review (high stakes).- North star: actionable CI Signals for PostHog Desktop. Ready-for-review-to-merge time is the headline metric, not the end in itself.- Two first-class surfaces, one endpoint set: the in-app UI and MCP tools. Named typed endpoints run the curated read layer privately (no global HogQL views, core imports only the viewset); keep `mcp/tools.yaml` current whenever endpoints change.-- One sanctioned write: the test-health sidecar (quarantine, as an issue plus PR through the team's GitHub App), carved out because this UI is the fastest surface to iterate on it. No saved views or stateful filters; persisted surfaces are a separate decision.+- One sanctioned write: the test-health sidecar (quarantine, as an issue plus PR through the team's GitHub App). The write now lives behind the API and MCP tool only; the test-health UI became the Trunk quarantine debt scoreboard because Trunk's auto-quarantine outran the file-based flow as the thing teams need to see. No saved views or stateful filters; persisted surfaces are a separate decision.- Data path: HogQL over the warehouse, plus reads from Logs and Traces. PR lifecycle event ingestion deferred. Product Postgres DB stays empty.- No author leaderboards or per-developer performance rankings, ever. The author page (own PRs plus own CI cost, reached only from PR-row author links) is allowed; ranking people against each other is not.- Bots and drafts excluded by default in throughput / cycle-time reads; bot detection = `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`.diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 12f22a7e7b60..3645a3384db6 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -7,7 +7,7 @@ Sibling doc: [README.md](./README.md), read that first for the product picture aThe product surfaces PR + CI data through **named, typed endpoints** that run curated HogQL privately over the warehouse (`github_*` tables), Logs, and Traces. Two first-class surfaces consume the same endpoints: the in-app UI and **MCP tools**. Nothing is registered as a global HogQL view, so the product stays isolated and off the per-query catalog hot path; core imports only the viewset, exactly like `visual_review`.-Reads are the product. The one write is the test-health sidecar (quarantine: issue plus PR through the team's GitHub App), carved out here because this UI is the fastest surface to iterate on it.+Reads are the product. The one write is the test-health sidecar (quarantine: issue plus PR through the team's GitHub App), reachable via the API and MCP tool; the test-health UI itself is the Trunk quarantine debt scoreboard.The goal is Signals for PostHog Desktop (README → "The goal"): Signal detection is defined once in `logic/` over the read layer, shared by the surfaces and the Signal emitter. Emission rides the curated builders; it does not wait on lifecycle events.diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex e8bbc887f1e4..7c23b3d4222f 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -47,6 +47,7 @@ from products.engineering_analytics.backend.facade.contracts import (TeamCIActivity,TeamCIHealthList,TeamMergeTrend,+ TrunkQuarantineDebt,WorkflowCost,WorkflowHealthItem,WorkflowJob,@@ -444,6 +445,16 @@ def list_github_sources(*, team: Team, user_access_control: "UserAccessControl |return logic.build_github_sources(team=team, user_access_control=user_access_control)+def get_trunk_quarantine(+ *,+ team: Team,+ source_id: str | None = None,+ repo: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> TrunkQuarantineDebt:+ return logic.build_trunk_quarantine(curated=_authorized_source(team, source_id, user_access_control, repo=repo))++def get_quarantine(*,team: Team,diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex c3da69a76c4f..501e4157bf1f 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -624,6 +624,65 @@ class FlakyTestList:limit: int+# How long a Trunk quarantine may stand before the scoreboard calls it overdue. Trunk itself never+# expires a quarantine, so this deadline is the product's own accountability bar.+TRUNK_QUARANTINE_TTL_DAYS = 15+++@dataclass(frozen=True)+class TrunkQuarantinedTest:+ """One test Trunk currently quarantines, aged against ``TRUNK_QUARANTINE_TTL_DAYS``.++ Rows come from the synced TrunkIo ``QuarantinedTests`` warehouse table. Ownership rides the+ per-test CI spans (the emitter stamps ``test.owner_team``); a quarantined test with no+ in-retention span aggregates under ``'unowned'``.+ """++ # Runner label derived from Trunk's uploader-specific 'parent' field: 'pytest', 'jest',+ # 'playwright', 'rust', or 'storybook'. Free-form on purpose; Trunk ingests suites the+ # CITestRunner enum does not model.+ runner: str+ # Runner-native test id reconstructed from Trunk's (file, classname, name) key.+ nodeid: str+ file: str+ owner_team: str+ # Trunk's health verdict on the test, e.g. 'FLAKY' or 'BROKEN'.+ status: str+ # How the quarantine was applied, e.g. 'AUTO_QUARANTINE'.+ quarantine_setting: str+ quarantined_at: datetime+ age_days: int+ overdue: bool+ # The Trunk app's page for this test; None when the source has no org slug or the row no id.+ trunk_url: str | None+++@dataclass(frozen=True)+class TrunkQuarantineTeamDebt:+ """One owning team's share of the standing Trunk quarantine debt."""++ owner_team: str+ test_count: int+ overdue_count: int+ oldest_age_days: int+++@dataclass(frozen=True)+class TrunkQuarantineDebt:+ """The standing Trunk quarantine debt: every currently quarantined test with its owning team,+ age, and whether it has outlived the TTL, plus the per-team rollup. ``available`` is false when+ no TrunkIo source has the QuarantinedTests endpoint synced — that is not an error."""++ available: bool+ ttl_days: int+ # The 'owner/name' repository the debt was read for; test file paths are relative to it.+ repository: str+ # The Trunk app's flaky-tests page for this repository; None when the source has no org slug.+ trunk_url: str | None+ teams: list[TrunkQuarantineTeamDebt]+ tests: list[TrunkQuarantinedTest]++@dataclass(frozen=True)class TeamCIHealthItem:"""One owning team's rollup of the CI test surfaces it owns, with equal-lengthdiff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 371b67b154a1..0772839cbfe6 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -39,6 +39,7 @@ from products.engineering_analytics.backend.logic.sources import build_github_sofrom products.engineering_analytics.backend.logic.suite_health import (build_broken_tests as build_broken_tests,build_flaky_tests as build_flaky_tests,+ build_trunk_quarantine as build_trunk_quarantine,)from products.engineering_analytics.backend.logic.teams import (build_team_ci_activity as build_team_ci_activity,diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 1b606b74db63..7169abb15dd1 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -30,8 +30,10 @@ from posthog.models.team import Teamfrom products.engineering_analytics.backend.logic.sources import (GitHubTables,+ TrunkQuarantineSource,resolve_github_tables,resolve_trunk_merge_queue_table,+ resolve_trunk_quarantined_tests_source,)from products.engineering_analytics.backend.logic.views import (deployments,@@ -40,6 +42,7 @@ from products.engineering_analytics.backend.logic.views import (pull_requests,team_members,trunk_merge_queue,+ trunk_quarantined_tests,workflow_jobs,workflow_runs,)@@ -141,6 +144,8 @@ class CuratedGitHubSource:self._user_access_control = user_access_controlself._trunk_table: str | None = Noneself._trunk_table_resolved = False+ self._trunk_quarantine_source: TrunkQuarantineSource | None = None+ self._trunk_quarantine_resolved = False@propertydef team(self) -> Team:@@ -206,6 +211,28 @@ class CuratedGitHubSource:return Nonereturn f"({trunk_merge_queue.build_query(self._trunk_table)})"+ def _trunk_quarantine(self) -> "TrunkQuarantineSource | None":+ if not self._trunk_quarantine_resolved:+ self._trunk_quarantine_source = resolve_trunk_quarantined_tests_source(+ self._team, self.repository, self._user_access_control+ )+ self._trunk_quarantine_resolved = True+ return self._trunk_quarantine_source++ def trunk_quarantined_tests_source(self) -> str | None:+ """Curated Trunk quarantined-tests ``SELECT`` subquery, or None when no TrunkIo source has+ the QuarantinedTests endpoint synced or the requesting user can't access one; consumers+ degrade to ``available: false``. Lazily resolved and cached like the merge-queue sibling."""+ source = self._trunk_quarantine()+ if source is None:+ return None+ return f"({trunk_quarantined_tests.build_query(source.table)})"++ def trunk_org_url_slug(self) -> str | None:+ """The TrunkIo source's org slug, for links into the Trunk app; None when unsynced or unset."""+ source = self._trunk_quarantine()+ return source.org_url_slug if source else None+def members_source(self) -> str | None:"""Curated team-membership ``SELECT`` subquery, or None when the optional table isn't synced."""if not self._tables.team_members:diff --git a/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.pynew file mode 100644index 000000000000..b5b7ada8cd0c--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py@@ -0,0 +1,156 @@+"""The standing Trunk quarantine debt, attributed to owning teams.++Two substrates, joined in Python because they live on different clusters: the quarantined set from+the synced TrunkIo ``QuarantinedTests`` warehouse table, and ownership from the per-test CI spans+on the LOGS cluster (the emitter stamps ``test.owner_team``; SPEC locks ownership to that stamp,+never a server-side map). A quarantined test with no in-retention span lands under ``'unowned'``.++Trunk keys a test by (file, classname, name); the curated builder reconstructs the runner-native+nodeid from that key, and the span side reports the same id as the span name — but each side can+carry a longer path prefix (product suites run from their product dir), so the join matches on+path suffixes rather than exact equality.+"""++from datetime import UTC, datetime, timedelta++from posthog.clickhouse.workload import Workload++from products.engineering_analytics.backend.facade.contracts import (+ TrunkQuarantineDebt,+ TrunkQuarantinedTest,+ TrunkQuarantineTeamDebt,+)+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries._test_spans import (+ UNOWNED_TEAM,+ run_evidence,+ scan_placeholders,+)++# One owner per test, resolved by its latest ownership stamp (same rule as the team rollups). The+# selector rides along because it is the runner-native id Trunk's key reconstructs to; the span+# nodeid folds the pytest file/class boundary and never matches a Trunk key directly.+_OWNER_ROSTER_SELECT = f"""+ SELECT runner, nodeid, anyIf(selector, selector != '') AS selector, argMax(owner_team, run_signal_at) AS owner_team+ FROM ({run_evidence(bounded=False)})+ GROUP BY runner, nodeid+"""++_QUARANTINED_SELECT = """+ SELECT runner, nodeid, file, status, quarantine_setting, test_case_id, quarantined_at+ FROM __TRUNK_SOURCE__+"""+++def _nodeid_variants(nodeid: str) -> list[str]:+ """Every path-suffix variant of a nodeid, so either join side can hold the longer prefix.+ Stops above the bare filename, where two packages' same-named files would collide."""+ path, sep, tail = nodeid.partition("::")+ suffix = f"{sep}{tail}" if sep else ""+ segments = path.split("/")+ variants = [f"{'/'.join(segments[start:])}{suffix}" for start in range(max(len(segments) - 1, 1))]+ return variants or [nodeid]+++def _trunk_url(org_url_slug: str | None, repository: str) -> str | None:+ if not org_url_slug:+ return None+ return f"https://app.trunk.io/{org_url_slug}/flaky-tests?repo={repository}"+++def _trunk_test_url(org_url_slug: str | None, repository: str, test_case_id: str) -> str | None:+ """The Trunk app's per-test page. The ``?repo`` form is what Trunk itself redirects to the+ canonical repo-uuid URL (verified against the live app); the uuid is not in the synced data."""+ if not org_url_slug or not test_case_id:+ return None+ return f"https://app.trunk.io/{org_url_slug}/flaky-tests/test/{test_case_id}?repo={repository}"+++def query_trunk_quarantine_debt(+ *,+ curated: CuratedGitHubSource,+ owner_window_from: datetime,+ ttl_days: int,+ now: datetime,+) -> TrunkQuarantineDebt:+ """Every currently quarantined test with its owning team and age, plus the per-team rollup;+ the unavailable shape when no TrunkIo QuarantinedTests table is synced."""+ source = curated.trunk_quarantined_tests_source()+ if source is None:+ return TrunkQuarantineDebt(+ available=False, ttl_days=ttl_days, repository=curated.repository, trunk_url=None, teams=[], tests=[]+ )+ org_url_slug = curated.trunk_org_url_slug()+ trunk_url = _trunk_url(org_url_slug, curated.repository)++ quarantined = curated.run(+ _QUARANTINED_SELECT.replace("__TRUNK_SOURCE__", source),+ query_type="engineering_analytics.trunk_quarantine_debt",+ placeholders={},+ )+ rows = quarantined.results or []+ if not rows:+ return TrunkQuarantineDebt(+ available=True, ttl_days=ttl_days, repository=curated.repository, trunk_url=trunk_url, teams=[], tests=[]+ )++ owners = curated.run(+ _OWNER_ROSTER_SELECT,+ query_type="engineering_analytics.trunk_quarantine_owners",+ placeholders=scan_placeholders(repository=curated.repository, date_from=owner_window_from),+ workload=Workload.LOGS,+ )+ owner_by_variant: dict[tuple[str, str], str] = {}+ for runner, nodeid, selector, owner_team in owners.results or []:+ for key in (nodeid, selector):+ if not key:+ continue+ for variant in _nodeid_variants(key):+ owner_by_variant[(runner, variant)] = owner_team++ tests: list[TrunkQuarantinedTest] = []+ for runner, nodeid, file, status, quarantine_setting, test_case_id, quarantined_at in rows:+ owner = next(+ (+ owner_by_variant[(runner, variant)]+ for variant in _nodeid_variants(nodeid)+ if (runner, variant) in owner_by_variant+ ),+ UNOWNED_TEAM,+ )+ if quarantined_at.tzinfo is None:+ quarantined_at = quarantined_at.replace(tzinfo=UTC)+ age_days = max((now - quarantined_at) // timedelta(days=1), 0)+ tests.append(+ TrunkQuarantinedTest(+ runner=runner,+ nodeid=nodeid,+ file=file,+ owner_team=owner,+ status=status,+ quarantine_setting=quarantine_setting,+ quarantined_at=quarantined_at,+ age_days=age_days,+ overdue=age_days > ttl_days,+ trunk_url=_trunk_test_url(org_url_slug, curated.repository, test_case_id),+ )+ )+ tests.sort(key=lambda test: (-test.age_days, test.nodeid))++ rollup: dict[str, list[TrunkQuarantinedTest]] = {}+ for test in tests:+ rollup.setdefault(test.owner_team, []).append(test)+ teams = [+ TrunkQuarantineTeamDebt(+ owner_team=owner_team,+ test_count=len(owned),+ overdue_count=sum(1 for test in owned if test.overdue),+ # tests is sorted oldest first above, so each owner's first entry carries the max age+ oldest_age_days=owned[0].age_days,+ )+ for owner_team, owned in rollup.items()+ ]+ teams.sort(key=lambda team: (-team.overdue_count, -team.test_count, -team.oldest_age_days, team.owner_team))+ return TrunkQuarantineDebt(+ available=True, ttl_days=ttl_days, repository=curated.repository, trunk_url=trunk_url, teams=teams, tests=tests+ )diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex 6965beed8d8a..e788a81a9143 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -27,6 +27,7 @@ from uuid import UUIDfrom django.db.models import QuerySet+from posthog.dataclasses import frozenfrom posthog.models.team import Teamfrom products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedError@@ -236,6 +237,45 @@ def resolve_trunk_merge_queue_table(team: Team, user_access_control: "UserAccessreturn None+TRUNK_QUARANTINED_TESTS_SCHEMA = "QuarantinedTests"+++@frozen+class TrunkQuarantineSource:+ """The synced Trunk quarantined-tests table plus the source's Trunk org slug (for app links)."""++ table: str+ org_url_slug: str | None+++def resolve_trunk_quarantined_tests_source(+ team: Team, repository: str, user_access_control: "UserAccessControl | None" = None+) -> TrunkQuarantineSource | None:+ """The synced Trunk quarantined-tests table's warehouse name and org slug, or None.++ A TrunkIo source is configured for one repository (``repo_owner``/``repo_name``), so prefer+ the source matching ``repository`` and fall back to the oldest synced source only when none+ declares a match (legacy sources without those keys). Per-user warehouse RBAC applies, and+ None degrades the consumer to an honest ``available: false`` rather than an error.+ """+ fallback: TrunkQuarantineSource | None = None+ for source in _accessible_sources(team, ExternalDataSourceType.TRUNKIO, user_access_control):+ for schema in _synced_schemas(team=team, source=source):+ if schema.name != TRUNK_QUARANTINED_TESTS_SCHEMA:+ continue+ table = schema.table+ if table is None or table.deleted or not _IDENTIFIER.match(table.name):+ continue+ # job_inputs is an EncryptedJSONField and can hold any JSON shape.+ inputs = source.job_inputs if isinstance(source.job_inputs, dict) else {}+ resolved = TrunkQuarantineSource(table=table.name, org_url_slug=inputs.get("org_url_slug") or None)+ source_repo = f"{inputs.get('repo_owner', '')}/{inputs.get('repo_name', '')}"+ if source_repo.lower() == repository.lower():+ return resolved+ fallback = fallback or resolved+ return fallback++# Listing the team's connected sources is its own concern (no curated read handle): it threads the# requesting user's access control so the picker can't enumerate sources the user can't access.def build_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:diff --git a/products/engineering_analytics/backend/logic/suite_health.py b/products/engineering_analytics/backend/logic/suite_health.pyindex 506a0ad1ed00..c6d6d80084fa 100644--- a/products/engineering_analytics/backend/logic/suite_health.py+++ b/products/engineering_analytics/backend/logic/suite_health.py@@ -1,15 +1,21 @@-"""Test-health orchestration: the active test-health queue and the broken-tests panel."""+"""Test-health orchestration: the flaky-test queue, the broken-tests panel, and the Trunk+quarantine debt scoreboard."""++from datetime import UTC, datetimefrom products.engineering_analytics.backend.facade.contracts import (BROKEN_TEST_SPARKLINE_HOURS,+ TRUNK_QUARANTINE_TTL_DAYS,BrokenTestsResult,CITestRunner,FlakyTestList,+ TrunkQuarantineDebt,)from products.engineering_analytics.backend.logic._shared import _parse_date, _parse_windowfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries.broken_tests import query_broken_testsfrom products.engineering_analytics.backend.logic.queries.flaky_tests import query_flaky_tests+from products.engineering_analytics.backend.logic.queries.trunk_quarantine import query_trunk_quarantine_debt# Test-health queue defaults: a week of signal is the triage window, a month the ceiling# (per-test spans are high-volume and the short Traces retention makes older data spotty anyway).@@ -57,6 +63,17 @@ def build_flaky_tests()+def build_trunk_quarantine(*, curated: CuratedGitHubSource) -> TrunkQuarantineDebt:+ # Owners come from the span roster over the widest window the flaky queue allows: older stamps+ # have aged out of Traces retention anyway, and a stale owner beats 'unowned'.+ return query_trunk_quarantine_debt(+ curated=curated,+ owner_window_from=_parse_date(curated.team, f"-{MAX_FLAKY_WINDOW_DAYS}d"),+ ttl_days=TRUNK_QUARANTINE_TTL_DAYS,+ now=datetime.now(UTC),+ )++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/offsetdiff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.pyindex 9d74e8ca97ac..0e13f52fa293 100644--- a/products/engineering_analytics/backend/logic/views/source_schema.py+++ b/products/engineering_analytics/backend/logic/views/source_schema.py@@ -159,3 +159,22 @@ TRUNK_MERGE_QUEUE_COLUMNS: dict[str, dict[str, str]] = {"skip_the_line": {"clickhouse": "Nullable(Bool)", "hogql": "BooleanDatabaseField"},"state_changed_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},}++# The Trunk quarantined-tests snapshot (TrunkIo source, QuarantinedTests endpoint): one row per+# currently quarantined test case, keyed by the (name, parent, file, classname, variant) tuple+# because Trunk documents ``test_case_id`` as unstable. Verified against a real connected source;+# every column lands Nullable(String), timestamps included.+TRUNK_QUARANTINED_TESTS_COLUMNS: dict[str, dict[str, str]] = {+ "file": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "labels": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "parent": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "status": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "variant": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "classname": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "codeowners": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "test_case_id": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "quarantined_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "quarantine_setting": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "status_last_updated_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+}diff --git a/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py b/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.pynew file mode 100644index 000000000000..a5c7ac60fff6--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/trunk_quarantined_tests.py@@ -0,0 +1,54 @@+"""Curated view over the Trunk quarantined-tests snapshot (``TRUNK_QUARANTINED_TESTS_COLUMNS``)."""+++def build_query(table: str) -> str:+ """Curated SELECT over a synced Trunk quarantined-tests table: the reconstructed runner-native+ nodeid, a runner label, and the parsed quarantine timestamp.++ Trunk keys a test by (file, classname, name) and overloads ``parent`` per uploader (verified+ against a real connected source): 'pytest' for pytest, the test file path for jest and+ Playwright, and the nextest 'suite::test' id for Rust. Trimming the module prefix recovers the+ pytest class; jest and Playwright need no reassembly; Rust and Storybook rows carry no file, so+ the nodeid falls back to classname::name. Rows without a name or quarantine time carry nothing+ a consumer can attribute or age, so they drop here.+ """+ return f"""+ SELECT+ runner,+ multiIf(+ file != '', concat(file, '::', if(cls = '', '', concat(cls, '::')), name),+ classname != '' AND classname != name, concat(classname, '::', name),+ name+ ) AS nodeid,+ file,+ any(status) AS status,+ any(quarantine_setting) AS quarantine_setting,+ any(test_case_id) AS test_case_id,+ -- Trunk keys a test per variant (e.g. one row per browser), so collapse to one row per+ -- test; the oldest quarantine carries the honest age.+ min(quarantined_at_parsed) AS quarantined_at+ FROM (+ SELECT+ multiIf(+ parent = 'pytest', 'pytest',+ parent LIKE '%::%', 'rust',+ parent LIKE 'playwright/%' OR parent LIKE '%.spec.ts', 'playwright',+ parent LIKE '%.stories.tsx', 'storybook',+ 'jest'+ ) AS runner,+ ifNull(file, '') AS file,+ ifNull(name, '') AS name,+ ifNull(classname, '') AS classname,+ ifNull(status, '') AS status,+ ifNull(quarantine_setting, '') AS quarantine_setting,+ ifNull(test_case_id, '') AS test_case_id,+ parseDateTimeBestEffort(quarantined_at) AS quarantined_at_parsed,+ replaceAll(substring(ifNull(file, ''), 1, length(ifNull(file, '')) - 3), '/', '.') AS module,+ if(parent = 'pytest' AND startsWith(ifNull(classname, ''), concat(module, '.')),+ replaceAll(substring(ifNull(classname, ''), length(module) + 2, length(ifNull(classname, ''))), '.', '::'),+ '') AS cls+ FROM {table}+ )+ WHERE name != '' AND quarantined_at_parsed IS NOT NULL+ GROUP BY runner, nodeid, file+"""diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.pyindex a7e797ecd035..8a793055161b 100644--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py@@ -52,6 +52,7 @@ from products.engineering_analytics.backend.logic.sources import (ISSUE_EVENTS_SCHEMA,PULL_REQUESTS_SCHEMA,TEAM_MEMBERS_SCHEMA,+ TRUNK_QUARANTINED_TESTS_SCHEMA,WORKFLOW_JOBS_SCHEMA,WORKFLOW_RUNS_SCHEMA,)@@ -60,6 +61,7 @@ from products.engineering_analytics.backend.logic.views.source_schema import (ISSUE_EVENTS_COLUMNS,PULL_REQUESTS_COLUMNS,TEAM_MEMBERS_COLUMNS,+ TRUNK_QUARANTINED_TESTS_COLUMNS,WORKFLOW_JOBS_COLUMNS,WORKFLOW_RUNS_COLUMNS,)@@ -83,6 +85,8 @@ RUN_DATE_FIELDS = ("created_at", "run_started_at", "updated_at")# Marks the GitHub source this command owns, so re-seeding never clobbers a real source.SEED_SOURCE_ID = "engineering_analytics_seed"+# The TrunkIo sibling backing the Trunk quarantine debt scoreboard.+TRUNK_SEED_SOURCE_ID = "engineering_analytics_seed_trunkio"# Matches the fixtures' repository.full_name; without it the UI's repo header/picker fall back to# placeholders (a real source stores the repo in job_inputs at connect time).SEED_REPOSITORY = "PostHog/posthog"@@ -776,6 +780,63 @@ def _selector(module_dir: str, test_class: str, test_name: str) -> str:return f"{module_dir}/{test_name}.py::{test_class}::{test_name}"+def _trunk_quarantined_rows() -> list[dict[str, Any]]:+ """Trunk-quarantined rows for the debt scoreboard, reusing the span roster so owner attribution+ resolves through the seeded spans. Ages are staggered on both sides of the TTL, and two rows+ (one of them jest) name tests outside the roster so the 'unowned' bucket renders."""+ anchor = timezone.now().replace(microsecond=0)+ rows: list[dict[str, Any]] = []++ def add(*, file: str, name: str, classname: str, parent: str, age_days: int) -> None:+ quarantined_at = (anchor - timedelta(days=age_days, hours=len(rows))).strftime("%Y-%m-%dT%H:%M:%S.000Z")+ rows.append(+ {+ "file": file,+ "name": name,+ "labels": "[]",+ "parent": parent,+ "status": "FLAKY",+ "variant": "",+ "classname": classname,+ "codeowners": "[]",+ "test_case_id": f"engseed-trunk-{len(rows):03d}",+ "quarantined_at": quarantined_at,+ "quarantine_setting": "AUTO_QUARANTINE",+ "status_last_updated_at": quarantined_at,+ }+ )++ age = 2+ for _owner_team, module_dir, tests in _SPAN_TEAMS:+ # Quarantine the first two roster tests per team; module = test_name (the span seed's rule).+ for test_class, test_name, _prior, _current in tests[:2]:+ module_path = f"{module_dir}/{test_name}.py"+ add(+ file=module_path,+ name=test_name,+ classname=f"{module_path[:-3].replace('/', '.')}.{test_class}",+ parent="pytest",+ age_days=age,+ )+ # Walks 2..44 in 7-day steps across the roster, landing rows on both sides of the TTL.+ age = (age + 7) % 45+ add(+ file="posthog/api/test/test_signup.py",+ name="test_social_signup_ratelimit",+ classname="posthog.api.test.test_signup.TestSignup",+ parent="pytest",+ age_days=41,+ )+ add(+ file="frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx",+ name="the activity log logic humanizes flag changes",+ classname="",+ parent="frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx",+ age_days=9,+ )+ return rows++def _seed_trace_spans(team: Team) -> int:anchor = timezone.now().replace(microsecond=0)rows: list[str] = []@@ -1015,7 +1076,13 @@ class Command(BaseCommand):access_key=settings.OBJECT_STORAGE_ACCESS_KEY_ID,access_secret=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,)- source = self._get_or_create_seed_source(team, prefix)+ source = self._get_or_create_seed_source(+ team,+ prefix,+ source_id=SEED_SOURCE_ID,+ source_type=ExternalDataSourceType.GITHUB,+ job_inputs={"repository": SEED_REPOSITORY},+ )self._upsert_schema_table(team, source, credential, prefix, PULL_REQUESTS_SCHEMA, PULL_REQUESTS_COLUMNS, map(_flatten_pr, prs))@@ -1034,6 +1101,24 @@ class Command(BaseCommand):self._upsert_schema_table(team, source, credential, prefix, ISSUE_EVENTS_SCHEMA, ISSUE_EVENTS_COLUMNS, issue_events)+ # A TrunkIo sibling source backs the Trunk quarantine debt scoreboard.+ trunk_source = self._get_or_create_seed_source(+ team,+ prefix,+ source_id=TRUNK_SEED_SOURCE_ID,+ source_type=ExternalDataSourceType.TRUNKIO,+ job_inputs={"org_url_slug": "posthog-inc", "repo_owner": "PostHog", "repo_name": "posthog"},+ )+ self._upsert_schema_table(+ team,+ trunk_source,+ credential,+ prefix,+ TRUNK_QUARANTINED_TESTS_SCHEMA,+ TRUNK_QUARANTINED_TESTS_COLUMNS,+ _trunk_quarantined_rows(),+ source_kind="trunkio",+ )# Per-test CI spans back the flaky-test leaderboard and the team CI health surfaces.# Best-effort: a dev stack without the traces table still gets the warehouse seed.@@ -1086,26 +1171,32 @@ class Command(BaseCommand):shifted[field] = moved.strftime("%Y-%m-%d %H:%M:%S")return shifted- def _get_or_create_seed_source(self, team: Team, prefix: str) -> ExternalDataSource:- source = ExternalDataSource.objects.filter(- team=team, source_id=SEED_SOURCE_ID, source_type=ExternalDataSourceType.GITHUB- ).first()+ def _get_or_create_seed_source(+ self,+ team: Team,+ prefix: str,+ *,+ source_id: str,+ source_type: ExternalDataSourceType,+ job_inputs: dict[str, str],+ ) -> ExternalDataSource:+ source = ExternalDataSource.objects.filter(team=team, source_id=source_id, source_type=source_type).first()if source is None:return ExternalDataSource.objects.create(team=team,- source_id=SEED_SOURCE_ID,- connection_id=SEED_SOURCE_ID,+ source_id=source_id,+ connection_id=source_id,status=ExternalDataSourceStatus.COMPLETED,- source_type=ExternalDataSourceType.GITHUB,+ source_type=source_type,prefix=prefix,- job_inputs={"repository": SEED_REPOSITORY},+ job_inputs=dict(job_inputs),)update_fields = []if source.prefix != prefix:source.prefix = prefixupdate_fields.append("prefix")- if (source.job_inputs or {}).get("repository") != SEED_REPOSITORY:- source.job_inputs = {**(source.job_inputs or {}), "repository": SEED_REPOSITORY}+ if any((source.job_inputs or {}).get(key) != value for key, value in job_inputs.items()):+ source.job_inputs = {**(source.job_inputs or {}), **job_inputs}update_fields.append("job_inputs")if update_fields:source.save(update_fields=[*update_fields, "updated_at"])@@ -1120,10 +1211,11 @@ class Command(BaseCommand):schema_name: str,columns: dict[str, dict[str, str]],rows: Any,+ source_kind: str = "github",) -> None:records = list(rows)- # The materialized table name is exactly what a real sync produces: <prefix>github_<endpoint>.- table_name = f"{prefix}github_{schema_name}"+ # The materialized table name is exactly what a real sync produces: <prefix><kind>_<endpoint>.+ table_name = f"{prefix}{source_kind}_{schema_name.lower() if source_kind != 'github' else schema_name}"headers = list(columns.keys())output = StringIO()writer = csv.writer(output)diff --git a/products/engineering_analytics/backend/presentation/serializers/suite_health.py b/products/engineering_analytics/backend/presentation/serializers/suite_health.pyindex 5af4bfcba341..09e9583a7a34 100644--- a/products/engineering_analytics/backend/presentation/serializers/suite_health.py+++ b/products/engineering_analytics/backend/presentation/serializers/suite_health.py@@ -11,6 +11,9 @@ from products.engineering_analytics.backend.facade.contracts import (QuarantineFile,QuarantineRequest,QuarantineRequestResult,+ TrunkQuarantineDebt,+ TrunkQuarantinedTest,+ TrunkQuarantineTeamDebt,)from products.engineering_analytics.backend.presentation.serializers._shared import RepoRefSerializer@@ -62,6 +65,71 @@ class FlakyTestItemSerializer(DataclassSerializer):}+class TrunkQuarantinedTestSerializer(DataclassSerializer):+ class Meta:+ dataclass = TrunkQuarantinedTest+ extra_kwargs = {+ "runner": {"help_text": "Test runner: 'pytest' or 'jest'."},+ "nodeid": {+ "help_text": "Runner-native test id reconstructed from Trunk's (file, classname, name) key.",+ },+ "file": {"help_text": "Repo-relative path of the test file, as Trunk reports it."},+ "owner_team": {+ "help_text": "Owning team slug from the per-test CI spans' emission-time stamp, or 'unowned' "+ "when no in-retention span carries one.",+ },+ "status": {"help_text": "Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'."},+ "quarantine_setting": {+ "help_text": "How the quarantine was applied in Trunk, e.g. 'AUTO_QUARANTINE'.",+ },+ "quarantined_at": {"help_text": "When Trunk quarantined the test."},+ "age_days": {"help_text": "Whole days since the quarantine started."},+ "overdue": {"help_text": "True once age_days exceeds ttl_days: the quarantine has outlived the TTL."},+ "trunk_url": {+ "help_text": "The Trunk app's page for this test; null when the connected source has no "+ "organization slug or the row carries no test case id.",+ },+ }+++class TrunkQuarantineTeamDebtSerializer(DataclassSerializer):+ class Meta:+ dataclass = TrunkQuarantineTeamDebt+ extra_kwargs = {+ "owner_team": {"help_text": "Owning team slug, or 'unowned'."},+ "test_count": {"help_text": "Tests this team owns that Trunk currently quarantines."},+ "overdue_count": {"help_text": "Of those, tests quarantined longer than ttl_days."},+ "oldest_age_days": {"help_text": "Age in days of the team's oldest standing quarantine."},+ }+++class TrunkQuarantineDebtSerializer(DataclassSerializer):+ teams = TrunkQuarantineTeamDebtSerializer(+ many=True,+ help_text="Per-team rollup, most indebted first: overdue count, then test count, then oldest age.",+ )+ tests = TrunkQuarantinedTestSerializer(+ many=True,+ help_text="Every currently quarantined test, oldest first.",+ )++ class Meta:+ dataclass = TrunkQuarantineDebt+ extra_kwargs = {+ "available": {+ "help_text": "False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error.",+ },+ "ttl_days": {"help_text": "Days a quarantine may stand before it counts as overdue."},+ "repository": {+ "help_text": "The 'owner/name' repository the debt was read for; test file paths are relative to it.",+ },+ "trunk_url": {+ "help_text": "The Trunk app's flaky-tests page for this repository; null when the connected "+ "source has no organization slug.",+ },+ }++class FlakyTestListSerializer(DataclassSerializer):items = FlakyTestItemSerializer(many=True,diff --git a/products/engineering_analytics/backend/presentation/views/suite_health.py b/products/engineering_analytics/backend/presentation/views/suite_health.pyindex 29d590574c48..84c07a16e262 100644--- a/products/engineering_analytics/backend/presentation/views/suite_health.py+++ b/products/engineering_analytics/backend/presentation/views/suite_health.py@@ -21,6 +21,7 @@ from products.engineering_analytics.backend.presentation.serializers.suite_healtQuarantineFileSerializer,QuarantineRequestResultSerializer,QuarantineRequestSerializer,+ TrunkQuarantineDebtSerializer,)from products.engineering_analytics.backend.presentation.views._base import (_DATE_TO,@@ -34,7 +35,7 @@ from products.engineering_analytics.backend.presentation.views._base import (class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):- READ_ACTIONS = ["flaky_tests", "broken_tests", "quarantine"]+ READ_ACTIONS = ["flaky_tests", "broken_tests", "quarantine", "trunk_quarantine"]WRITE_ACTIONS = ["quarantine_request"]@extend_schema(@@ -183,6 +184,36 @@ class SuiteHealthActionsMixin(EngineeringAnalyticsViewSetBase):return _bad_request(exc, fallback="Invalid repo or source_id")return Response(QuarantineFileSerializer(instance=result).data)+ @extend_schema(+ operation_id="engineering_analytics_trunk_quarantine",+ summary="Trunk quarantine debt by owning team",+ parameters=[_SOURCE_ID, _REPO],+ responses={+ 200: TrunkQuarantineDebtSerializer,+ 400: OpenApiResponse(description="Invalid repo or source_id."),+ },+ description=(+ "The standing Trunk quarantine debt: every test Trunk currently quarantines (failures "+ "suppressed in CI), attributed to its owning team from the per-test CI spans, aged against a "+ "TTL, and rolled up per team with the most indebted first. A quarantine only masks a test; it "+ "never fixes it, so this is the work queue of tests someone still has to repair or delete. "+ "`available` is false when no TrunkIo source has the QuarantinedTests endpoint synced — that "+ "is not an error."+ ),+ )+ @action(detail=False, methods=["get"], url_path="trunk_quarantine", pagination_class=None)+ def trunk_quarantine(self, request: Request, **kwargs) -> Response:+ try:+ result = api.get_trunk_quarantine(+ team=self.team,+ source_id=request.query_params.get("source_id") or None,+ repo=request.query_params.get("repo") or None,+ user_access_control=self.user_access_control,+ )+ except ValueError as exc:+ return _bad_request(exc, fallback="Invalid repo or source_id")+ return Response(TrunkQuarantineDebtSerializer(instance=result).data)+@validated_request(request_serializer=QuarantineRequestSerializer,operation_id="engineering_analytics_quarantine_request",diff --git a/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx b/products/engineering_analytics/frontend/components/QuarantineTestModal.tsxdeleted file mode 100644index e8b0052bd708..000000000000--- a/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx+++ /dev/null@@ -1,268 +0,0 @@-import { useEffect, useState } from 'react'--import { LemonButton, LemonInput, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'--import { dayjs } from 'lib/dayjs'-import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'--import {- QuarantineModalState,- QuarantineSubmitInput,- TestRunner,- inferOwnerFromSelector,-} from '../scenes/engineeringAnalyticsLogic'--// Common flake categories (industry-standard buckets). 'Other' reveals a free-text field.-const REASON_OPTIONS = [- 'Concurrency / race condition',- 'Timing / timeout',- 'Nondeterministic ordering or data',- 'Test isolation / shared state',- 'Eventual consistency / async wait',- 'External dependency or network',- 'Resource / environment',-]-const OTHER_REASON = 'Other'--// Mirrors the backend cap (core.MAX_QUARANTINE_DAYS); the server rejects anything further out.-const MAX_QUARANTINE_DAYS = 30-const DEFAULT_QUARANTINE_DAYS = 14--interface QuarantineTestModalProps {- /** Null closes the modal; non-null seeds it for a quarantine or an extend. */- modal: QuarantineModalState | null- /** Owning teams already present in the quarantine file; the dropdown also accepts a custom value. */- ownerOptions: string[]- submitting: boolean- onClose: () => void- onSubmit: (input: QuarantineSubmitInput) => void-}--export function QuarantineTestModal({- modal,- ownerOptions,- submitting,- onClose,- onSubmit,-}: QuarantineTestModalProps): JSX.Element {- const isExtend = modal?.action === 'extend'-- const [selector, setSelector] = useState('')- const [runner, setRunner] = useState<TestRunner>('pytest')- // A picked category, or OTHER_REASON when the reason is free-text (held in customReason).- const [reasonChoice, setReasonChoice] = useState('')- const [customReason, setCustomReason] = useState('')- const [owner, setOwner] = useState('')- const [expires, setExpires] = useState<dayjs.Dayjs | null>(dayjs().add(DEFAULT_QUARANTINE_DAYS, 'day'))- // 'Edit details' flips a confirm-presentation modal into the full form.- const [editing, setEditing] = useState(false)-- // Reseed when a new modal opens; keyed on identity so background refreshes don't trample edits.- useEffect(() => {- if (!modal) {- return- }- setSelector(modal.selector)- setRunner(modal.runner)- // An existing reason that isn't one of the buckets falls into the 'Other' free-text path.- const isKnown = REASON_OPTIONS.includes(modal.reason)- setReasonChoice(modal.reason ? (isKnown ? modal.reason : OTHER_REASON) : '')- setCustomReason(isKnown ? '' : modal.reason)- // New quarantines suggest the owning team from a product selector; extend keeps the entry's owner.- setOwner(modal.owner || (modal.action === 'extend' ? '' : inferOwnerFromSelector(modal.selector)))- setExpires(dayjs().add(DEFAULT_QUARANTINE_DAYS, 'day'))- setEditing(false)- }, [modal])-- const isConfirm = !!modal?.confirm && !editing && !isExtend-- const reason = reasonChoice === OTHER_REASON ? customReason.trim() : reasonChoice- // Backend requires a future expiry within the cap; mirror that so submit can't 400.- const expiresValid = !!expires && expires.isAfter(dayjs(), 'day')-- const canSubmit = !!selector.trim() && !!reason && !!owner.trim() && expiresValid- const disabledReason = !selector.trim()- ? 'A test selector is required'- : !reason- ? 'A reason is required'- : !owner.trim()- ? 'An owning team is required'- : !expiresValid- ? 'Pick an expiry date in the future'- : undefined-- const handleSubmit = (): void => {- if (!canSubmit || !modal || !expires) {- return- }- onSubmit({- action: modal.action,- selector: selector.trim(),- runner,- reason,- owner: owner.trim(),- issue: modal.issue,- expires: expires.format('YYYY-MM-DD'),- // Mode isn't editable here: new quarantines tolerate failures; extend keeps the entry's mode.- mode: modal.mode,- })- }-- // Owner is the one field editable in both presentations (a leaderboard row can't always infer it).- const ownerField = (- <div>- <label className="mb-1 block text-sm font-medium">Owner</label>- <LemonInputSelect- mode="single"- allowCustomValues- value={owner ? [owner] : []}- onChange={(values) => setOwner(values[0] ?? '')}- options={ownerOptions.map((option) => ({ key: option, label: option }))}- placeholder="Select the owning team"- data-attr="eng-analytics-quarantine-owner"- />- </div>- )-- return (- <LemonModal- isOpen={!!modal}- onClose={onClose}- title={isExtend ? 'Extend quarantine' : 'Quarantine a flaky test'}- description={- isExtend- ? 'Re-stamps the expiry on an existing entry and opens a PR. It takes effect once the PR merges.'- : 'Opens a tracking issue and a PR that masks this test in CI until its expiry. It takes effect once the PR merges.'- }- footer={- <>- {isConfirm && (- <LemonButton- type="tertiary"- onClick={() => setEditing(true)}- data-attr="eng-analytics-quarantine-edit"- >- Edit details- </LemonButton>- )}- <LemonButton type="secondary" onClick={onClose} data-attr="eng-analytics-quarantine-cancel">- Cancel- </LemonButton>- <LemonButton- type="primary"- loading={submitting}- disabledReason={submitting ? 'Opening PR…' : disabledReason}- onClick={handleSubmit}- data-attr="eng-analytics-quarantine-confirm"- >- {isExtend ? 'Extend and open PR' : 'Quarantine and open PR'}- </LemonButton>- </>- }- >- {isConfirm ? (- // Glanceable confirmation for prefilled openers: selector/reason/expiry are review-only.- <div className="flex flex-col gap-4">- <div>- <div className="mb-1 text-sm font-medium">Test selector</div>- <div className="rounded bg-surface-secondary px-2 py-1.5 font-mono text-xs break-all">- {selector}- </div>- </div>- <div>- <div className="mb-1 text-sm font-medium">Test runner</div>- <div className="text-sm">{runner}</div>- </div>- <div>- <div className="mb-1 text-sm font-medium">Reason</div>- <div className="text-sm text-secondary">{reason}</div>- </div>- <div>- <div className="mb-1 text-sm font-medium">Expires</div>- <div className="text-sm">- {expires?.format('MMMM D, YYYY')}- <span className="ml-1 text-tertiary">- (in {DEFAULT_QUARANTINE_DAYS} days — the test gates CI again after this unless extended)- </span>- </div>- </div>- {ownerField}- </div>- ) : (- <div className="flex flex-col gap-4">- {!isExtend && (- <div>- <label className="mb-1 block text-sm font-medium">Test runner</label>- <LemonSelect<TestRunner>- value={runner}- onChange={(value) => value && setRunner(value)}- options={[- { value: 'pytest', label: 'pytest' },- { value: 'jest', label: 'Jest' },- { value: 'playwright', label: 'Playwright' },- ]}- fullWidth- data-attr="eng-analytics-quarantine-runner"- />- </div>- )}- <div>- <label className="mb-1 block text-sm font-medium">Test selector</label>- {isExtend ? (- <div className="rounded bg-surface-secondary px-2 py-1.5 font-mono text-xs text-secondary">- {selector}- </div>- ) : (- <LemonInput- value={selector}- onChange={setSelector}- placeholder="posthog/path/test.py::TestClass::test_method or product:my-product"- autoFocus- />- )}- </div>-- <div>- <label className="mb-1 block text-sm font-medium">Reason</label>- <LemonSelect- value={reasonChoice || null}- onChange={(value) => setReasonChoice(value ?? '')}- options={[- ...REASON_OPTIONS.map((option) => ({ value: option, label: option })),- { value: OTHER_REASON, label: 'Other…' },- ]}- placeholder="Select a reason"- fullWidth- data-attr="eng-analytics-quarantine-reason"- />- {reasonChoice === OTHER_REASON && (- <LemonInput- className="mt-2"- value={customReason}- onChange={setCustomReason}- placeholder="Describe the reason"- autoFocus- />- )}- </div>-- {ownerField}-- <div>- <label className="mb-1 block text-sm font-medium">Expires</label>- <LemonCalendarSelectInput- value={expires}- onChange={setExpires}- placeholder="Pick an expiry"- clearable={false}- selectionPeriod="upcoming"- />- <div className="mt-1 text-xs text-tertiary">- At most {MAX_QUARANTINE_DAYS} days out. After this the test gates CI again unless extended.- </div>- </div>- </div>- )}- </LemonModal>- )-}diff --git a/products/engineering_analytics/frontend/components/StatCard.tsx b/products/engineering_analytics/frontend/components/StatCard.tsxindex b19355e02a6a..2868aef0c3a1 100644--- a/products/engineering_analytics/frontend/components/StatCard.tsx+++ b/products/engineering_analytics/frontend/components/StatCard.tsx@@ -91,11 +91,34 @@ export function StatCard({/** Visible definition — only when the label alone doesn't explain the count. */caption?: stringloading: boolean- onClick: () => void+ /** Like HeroStat: without it the card is a plain stat, not a filter toggle. */+ onClick?: () => voidactive?: boolean/** What clicking filters the list to — surfaces in the tooltip and hover icon. */- filterHint: string+ filterHint?: string}): JSX.Element {+ const body = loading ? (+ <>+ <div className={cn('text-sm font-medium', active ? 'text-accent' : 'text-secondary')}>{label}</div>+ <LemonSkeleton className="h-9 w-20" />+ </>+ ) : (+ <MetricCard+ title={<span className={active ? 'text-accent' : undefined}>{label}</span>}+ // Pre-formatted display string ('—' when no data yet) rides through the formatter.+ value={0}+ formatValue={() => value}+ change={null}+ subtitle={caption}+ />+ )+ if (!onClick) {+ return (+ <div className="relative flex flex-col gap-1 rounded-lg border border-primary bg-surface-primary p-4 text-left">+ {body}+ </div>+ )+ }return (<Tooltip title={active ? 'Showing this view' : filterHint} placement="bottom"><button@@ -115,23 +138,7 @@ export function StatCard({active ? 'text-accent opacity-100' : 'text-tertiary opacity-0 group-hover:opacity-100')}/>- {loading ? (- <>- <div className={cn('text-sm font-medium', active ? 'text-accent' : 'text-secondary')}>- {label}- </div>- <LemonSkeleton className="h-9 w-20" />- </>- ) : (- <MetricCard- title={<span className={active ? 'text-accent' : undefined}>{label}</span>}- // Pre-formatted display string ('—' when no data yet) rides through the formatter.- value={0}- formatValue={() => value}- change={null}- subtitle={caption}- />- )}+ {body}</button></Tooltip>)diff --git a/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx b/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsxnew file mode 100644index 000000000000..7aeb6bd2b264--- /dev/null+++ b/products/engineering_analytics/frontend/components/TeamQuarantinedTestsTable.tsx@@ -0,0 +1,99 @@+import { IconExternal } from '@posthog/icons'+import { LemonTable, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { pluralize } from 'lib/utils/strings'++import { TrunkQuarantinedTestRow } from '../scenes/engineeringAnalyticsLogic'++/** One team's quarantined tests, rendered inside the debt table's expanded row. */+export function TeamQuarantinedTestsTable({+ tests,+ ttlDays,+ repository,+}: {+ tests: TrunkQuarantinedTestRow[]+ ttlDays: number+ /** 'owner/name' the test file paths are relative to, for the GitHub links. */+ repository: string+}): JSX.Element {+ const columns: LemonTableColumns<TrunkQuarantinedTestRow> = [+ {+ title: 'Test',+ key: 'nodeid',+ // max-w-0 lets the auto-layout cell shrink to the distributed width, so a long+ // nodeid truncates instead of pushing the table wider than the scene.+ className: 'w-full max-w-0',+ render: (_, row) => {+ // Rust and Storybook rows carry no file path in Trunk's data.+ const url =+ row.trunkUrl ?? (row.file ? `https://github.com/${repository}/blob/master/${row.file}` : null)+ if (!url) {+ return (+ <Tooltip title={row.nodeid}>+ <span className="block max-w-full truncate font-mono text-xs">{row.nodeid}</span>+ </Tooltip>+ )+ }+ return (+ <Tooltip title={row.trunkUrl ? `${row.nodeid} - open in Trunk` : row.nodeid}>+ <Link+ to={url}+ target="_blank"+ targetBlankIcon={false}+ className="flex max-w-full items-center gap-1 font-mono text-xs"+ >+ {/* Icon leads so truncating a long nodeid never clips it away. */}+ <IconExternal className="shrink-0" />+ <span className="truncate">{row.nodeid}</span>+ </Link>+ </Tooltip>+ )+ },+ },+ {+ title: 'Runner',+ key: 'runner',+ width: 90,+ render: (_, row) => row.runner,+ },+ {+ title: 'Quarantined',+ key: 'quarantinedAt',+ width: 130,+ render: (_, row) => <TZLabel time={row.quarantinedAt} />,+ },+ {+ title: 'Age',+ key: 'ageDays',+ width: 140,+ align: 'right',+ render: (_, row) => (+ <div className="flex items-center justify-end gap-2">+ <span>{pluralize(row.ageDays, 'day')}</span>+ {row.overdue && (+ <Tooltip+ title={`Quarantined longer than ${pluralize(ttlDays, 'day')}. Fix the test or delete it.`}+ >+ <LemonTag type="danger" size="small">+ Overdue+ </LemonTag>+ </Tooltip>+ )}+ </div>+ ),+ },+ ]+ return (+ <LemonTable+ data-attr="engineering-analytics-trunk-debt-tests-table"+ size="small"+ embedded+ columns={columns}+ dataSource={tests}+ rowKey={(row) => `${row.runner}:${row.nodeid}`}+ useURLForSorting={false}+ nouns={['test', 'tests']}+ />+ )+}diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex f76a1118eafd..7261830fa2e7 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -1376,6 +1376,61 @@ export interface TeamMergeTrendApi {has_membership_data: boolean}+export interface TrunkQuarantineTeamDebtApi {+ /** Owning team slug, or 'unowned'. */+ owner_team: string+ /** Tests this team owns that Trunk currently quarantines. */+ test_count: number+ /** Of those, tests quarantined longer than ttl_days. */+ overdue_count: number+ /** Age in days of the team's oldest standing quarantine. */+ oldest_age_days: number+}++export interface TrunkQuarantinedTestApi {+ /** Test runner: 'pytest' or 'jest'. */+ runner: string+ /** Runner-native test id reconstructed from Trunk's (file, classname, name) key. */+ nodeid: string+ /** Repo-relative path of the test file, as Trunk reports it. */+ file: string+ /** Owning team slug from the per-test CI spans' emission-time stamp, or 'unowned' when no in-retention span carries one. */+ owner_team: string+ /** Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'. */+ status: string+ /** How the quarantine was applied in Trunk, e.g. 'AUTO_QUARANTINE'. */+ quarantine_setting: string+ /** When Trunk quarantined the test. */+ quarantined_at: string+ /** Whole days since the quarantine started. */+ age_days: number+ /** True once age_days exceeds ttl_days: the quarantine has outlived the TTL. */+ overdue: boolean+ /**+ * The Trunk app's page for this test; null when the connected source has no organization slug or the row carries no test case id.+ * @nullable+ */+ trunk_url: string | null+}++export interface TrunkQuarantineDebtApi {+ /** Per-team rollup, most indebted first: overdue count, then test count, then oldest age. */+ teams: TrunkQuarantineTeamDebtApi[]+ /** Every currently quarantined test, oldest first. */+ tests: TrunkQuarantinedTestApi[]+ /** False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error. */+ available: boolean+ /** Days a quarantine may stand before it counts as overdue. */+ ttl_days: number+ /** The 'owner/name' repository the debt was read for; test file paths are relative to it. */+ repository: string+ /**+ * The Trunk app's flaky-tests page for this repository; null when the connected source has no organization slug.+ * @nullable+ */+ trunk_url: string | null+}+export interface WorkflowHealthBucketApi {/** Bucket start, aligned to the item's granularity (top of hour, midnight, or Monday). */bucket_start: string@@ -1919,6 +1974,17 @@ export type EngineeringAnalyticsTeamMergeTrendParams = {source_id?: string}+export type EngineeringAnalyticsTrunkQuarantineParams = {+ /**+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.+ */+ repo?: string+ /**+ * 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 EngineeringAnalyticsWorkflowHealthParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex 503c0c7b6dd9..e7577212a5b6 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -38,6 +38,7 @@ import type {EngineeringAnalyticsTeamCiActivityParams,EngineeringAnalyticsTeamCiHealthParams,EngineeringAnalyticsTeamMergeTrendParams,+ EngineeringAnalyticsTrunkQuarantineParams,EngineeringAnalyticsWorkflowHealthParams,EngineeringAnalyticsWorkflowJobsParams,EngineeringAnalyticsWorkflowRunActivityParams,@@ -58,6 +59,7 @@ import type {TeamCIActivityApi,TeamCIHealthListApi,TeamMergeTrendApi,+ TrunkQuarantineDebtApi,WorkflowCostApi,WorkflowHealthItemApi,WorkflowJobAggregateApi,@@ -824,6 +826,40 @@ export const engineeringAnalyticsTeamMergeTrend = async (})}+export const getEngineeringAnalyticsTrunkQuarantineUrl = (+ projectId: string,+ params?: EngineeringAnalyticsTrunkQuarantineParams+) => {+ 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/trunk_quarantine/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/trunk_quarantine/`+}++/**+ * The standing Trunk quarantine debt: every test Trunk currently quarantines (failures suppressed in CI), attributed to its owning team from the per-test CI spans, aged against a TTL, and rolled up per team with the most indebted first. A quarantine only masks a test; it never fixes it, so this is the work queue of tests someone still has to repair or delete. `available` is false when no TrunkIo source has the QuarantinedTests endpoint synced — that is not an error.+ * @summary Trunk quarantine debt by owning team+ */+export const engineeringAnalyticsTrunkQuarantine = async (+ projectId: string,+ params?: EngineeringAnalyticsTrunkQuarantineParams,+ options?: RequestInit+): Promise<TrunkQuarantineDebtApi> => {+ return apiMutator<TrunkQuarantineDebtApi>(getEngineeringAnalyticsTrunkQuarantineUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsWorkflowHealthUrl = (projectId: string,params?: EngineeringAnalyticsWorkflowHealthParamsdiff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsxindex 717813379e9b..4bb31d46c1c9 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.stories.tsx@@ -6,80 +6,11 @@ import { urls } from 'scenes/urls'import { mswDecorator } from '~/mocks/browser'-import type { FlakyTestListApi, GitHubSourceApi, QuarantineFileApi } from '../generated/api.schemas'--const FLAKY_TESTS: FlakyTestListApi = {- items: [- {- runner: 'pytest',- nodeid: 'posthog/api/test/test_decide/TestDecide::test_flag_rollout_consistency',- selector: 'posthog/api/test/test_decide.py::TestDecide::test_flag_rollout_consistency',- classification: 'confirmed_flake',- same_commit_recovery_run_count: 6,- failed_run_count: 8,- failed_pr_count: 3,- master_failed_run_count: 2,- quarantined_failed_run_count: 0,- last_signal_at: '2026-07-01T18:30:00Z',- },- {- runner: 'pytest',- nodeid: 'posthog/tasks/test/test_usage_report/TestUsageReport::test_full_report',- selector: 'posthog/tasks/test/test_usage_report.py::TestUsageReport::test_full_report',- classification: 'suspected_regression',- same_commit_recovery_run_count: 0,- failed_run_count: 9,- failed_pr_count: 4,- master_failed_run_count: 5,- quarantined_failed_run_count: 0,- last_signal_at: '2026-07-01T09:12:00Z',- },- {- runner: 'pytest',- nodeid: 'posthog/hogql/test/test_resolver/TestResolver::test_asterisk_expander',- selector: 'posthog/hogql/test/test_resolver.py::TestResolver::test_asterisk_expander',- classification: 'quarantined',- same_commit_recovery_run_count: 0,- failed_run_count: 1,- failed_pr_count: 1,- master_failed_run_count: 0,- quarantined_failed_run_count: 3,- last_signal_at: '2026-06-30T22:45:00Z',- },- {- runner: 'pytest',- nodeid: 'posthog/temporal/tests/batch_exports/test_backfill::test_workflow_timeout',- selector: 'posthog/temporal/tests/batch_exports/test_backfill.py::test_workflow_timeout',- classification: 'confirmed_flake',- same_commit_recovery_run_count: 1,- failed_run_count: 1,- failed_pr_count: 1,- master_failed_run_count: 0,- quarantined_failed_run_count: 0,- last_signal_at: '2026-06-29T14:00:00Z',- },- ],- truncated: false,- limit: 50,-}+import type { GitHubSourceApi, QuarantineFileApi, TrunkQuarantineDebtApi } from '../generated/api.schemas'const QUARANTINE: QuarantineFileApi = {available: true,- entries: [- {- id: 'posthog/hogql/test/test_resolver.py::TestResolver::test_asterisk_expander',- runner: 'pytest',- reason: 'Nondeterministic ordering or data',- owner: '@PostHog/team-hogql',- issue: 'https://github.com/PostHog/posthog/issues/1',- added: '2026-06-24',- expires: '2026-07-08',- mode: 'run',- lifecycle: 'active',- days_until_expiry: 6,- selector_kind: 'test',- },- ],+ entries: [],parse_errors: [],parse_warnings: [],repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },@@ -89,6 +20,56 @@ const QUARANTINE: QuarantineFileApi = {const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '' }]+const TRUNK_QUARANTINE: TrunkQuarantineDebtApi = {+ available: true,+ ttl_days: 15,+ repository: 'PostHog/posthog',+ trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog',+ teams: [+ { owner_team: 'batch-exports', test_count: 1, overdue_count: 1, oldest_age_days: 44 },+ { owner_team: 'team-replay', test_count: 1, overdue_count: 1, oldest_age_days: 38 },+ { owner_team: 'unowned', test_count: 1, overdue_count: 0, oldest_age_days: 9 },+ ],+ tests: [+ {+ runner: 'pytest',+ nodeid: 'products/batch_exports/backend/tests/test_snowflake.py::TestSnowflakeExport::test_resume',+ file: 'products/batch_exports/backend/tests/test_snowflake.py',+ owner_team: 'batch-exports',+ status: 'FLAKY',+ quarantine_setting: 'AUTO_QUARANTINE',+ quarantined_at: '2026-05-19T08:00:00Z',+ age_days: 44,+ overdue: true,+ trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests/test/t-1?repo=PostHog/posthog',+ },+ {+ runner: 'pytest',+ nodeid: 'posthog/session_recordings/test/test_snapshots.py::TestSnapshots::test_batching',+ file: 'posthog/session_recordings/test/test_snapshots.py',+ owner_team: 'team-replay',+ status: 'FLAKY',+ quarantine_setting: 'AUTO_QUARANTINE',+ quarantined_at: '2026-05-25T08:00:00Z',+ age_days: 38,+ overdue: true,+ trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests/test/t-2?repo=PostHog/posthog',+ },+ {+ runner: 'jest',+ nodeid: 'frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx::humanizes flag changes',+ file: 'frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx',+ owner_team: 'unowned',+ status: 'FLAKY',+ quarantine_setting: 'AUTO_QUARANTINE',+ quarantined_at: '2026-06-23T08:00:00Z',+ age_days: 9,+ overdue: false,+ trunk_url: null,+ },+ ],+}+const meta: Meta = {component: App,title: 'Scenes-App/Engineering Analytics/Test Health',@@ -98,15 +79,15 @@ const meta: Meta = {mockDate: '2026-07-02',featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],testOptions: {- // A per-row quarantine button only renders once the queue has data rows.- waitForSelector: '[data-attr="eng-analytics-flaky-quarantine"]',+ // The debt board's team table only renders once the trunk quarantine data loaded.+ waitForSelector: '[data-attr="engineering-analytics-trunk-debt-teams-table"]',},},decorators: [mswDecorator({get: {- 'api/projects/:team_id/engineering_analytics/flaky_tests/': FLAKY_TESTS,'api/projects/:team_id/engineering_analytics/quarantine/': QUARANTINE,+ 'api/projects/:team_id/engineering_analytics/trunk_quarantine/': TRUNK_QUARANTINE,'api/projects/:team_id/engineering_analytics/sources/': SOURCES,'api/projects/:team_id/engineering_analytics/ci_cards/': {open_prs: 18,@@ -128,7 +109,7 @@ export default metatype Story = StoryObj<typeof meta>-export const FlakyTestLeaderboard: Story = {+export const TrunkQuarantineDebt: Story = {render: () => <App />,parameters: { pageUrl: urls.engineeringAnalyticsTestHealth() },}diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsxindex 5bbdc7503cca..f54c157bcc63 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx@@ -1,700 +1,167 @@import { useActions, useValues } from 'kea'-import { IconEllipsis, IconExternal, IconShieldLock } from '@posthog/icons'-import {- LemonBanner,- LemonButton,- LemonDialog,- LemonInput,- LemonInputSelect,- LemonMenu,- LemonSegmentedButton,- LemonSelect,- LemonTable,- LemonTableColumns,- LemonTag,- LemonTagType,- Link,- Tooltip,-} from '@posthog/lemon-ui'+import { IconExternal } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonTable, LemonTableColumns } from '@posthog/lemon-ui'-import { dayjs } from 'lib/dayjs'-import { cn } from 'lib/utils/css-classes'import { humanFriendlyNumber } from 'lib/utils/numbers'import { pluralize } from 'lib/utils/strings'import { ConnectGitHubSource } from '../components/ConnectGitHubSource'-import { QuarantineTestModal } from '../components/QuarantineTestModal'import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'import { StatCard } from '../components/StatCard'-import {- FlakyTestClassification,- FlakyTestRow,- FlakyTestWindow,- QuarantineEntryRow,- QuarantineLifecycle,- QuarantineLifecycleFilter,- QuarantineModeFilter,- engineeringAnalyticsLogic,- flakyEvidenceReason,- isTestRunner,-} from './engineeringAnalyticsLogic'+import { TeamQuarantinedTestsTable } from '../components/TeamQuarantinedTestsTable'+import { TrunkQuarantineTeamRow, engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'-function relativeExpiry(daysUntilExpiry: number): string {- if (daysUntilExpiry === 0) {- return 'today'- }- return daysUntilExpiry > 0 ? `in ${pluralize(daysUntilExpiry, 'day')}` : `${pluralize(-daysUntilExpiry, 'day')} ago`-}--function LifecycleTag({ lifecycle }: { lifecycle: QuarantineLifecycle }): JSX.Element {- switch (lifecycle) {- case 'active':- return <LemonTag type="success">Active</LemonTag>- case 'expiring_soon':- return <LemonTag type="warning">Expiring soon</LemonTag>- case 'in_grace':- return (- <Tooltip title="Expired, but inside the 7-day grace period. The quarantine check only warns for now.">- <LemonTag type="warning">In grace</LemonTag>- </Tooltip>- )- default:- return (- <Tooltip title="Expired beyond the grace period. The quarantine check workflow fails until the entry is removed or re-triaged.">- <LemonTag type="danger">Overdue · blocks CI</LemonTag>- </Tooltip>- )- }-}--function ModeTag({ mode }: { mode: QuarantineEntryRow['mode'] }): JSX.Element {- if (mode === 'skip') {- return (- <Tooltip title="Skipped: the test is not collected at all (for hangs, import-time flakes, and state-polluters).">- <LemonTag type="danger">Skipped</LemonTag>- </Tooltip>- )- }- return (- <Tooltip title="Runs: the test still executes but cannot fail the suite.">- <LemonTag type="muted">Runs, can't fail</LemonTag>- </Tooltip>- )-}--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>- )+function teamLabel(ownerTeam: string): string {+ return ownerTeam.replace(/^team-/, '')}-const FLAKY_CLASSIFICATION: Record<FlakyTestClassification, { label: string; type: LemonTagType; tooltip: string }> = {- confirmed_flake: {- label: 'Confirmed flake',- type: 'warning',- tooltip:- 'One commit both failed and passed this test, so the failure is nondeterministic. Fix it, or quarantine it while you do.',- },- suspected_regression: {- label: 'Suspected regression',- type: 'danger',- tooltip:- 'Only failures recorded, so nothing here proves the test is flaky. Treat it as a real break until a recovery proves otherwise.',- },- quarantined: {- label: 'Quarantined, still failing',- type: 'muted',- tooltip: 'Already masked in CI with a tolerated failure recorded. Fix it, then remove the quarantine.',- },-}+function TrunkQuarantineDebtBoard(): JSX.Element {+ const {+ trunkQuarantine,+ trunkQuarantineLoading,+ trunkQuarantineStatus,+ trunkQuarantineTestsByTeam,+ expandedTrunkQuarantineTeams,+ } = useValues(engineeringAnalyticsLogic)+ const { toggleTrunkQuarantineTeam } = useActions(engineeringAnalyticsLogic)-function ActiveTestHealthQueue(): JSX.Element {- const { flakyTests, flakyTestsLoading, flakyTestsStatus, flakyTestWindow } = useValues(engineeringAnalyticsLogic)- const { setFlakyTestWindow, openQuarantineModal } = useActions(engineeringAnalyticsLogic)+ const ttlDays = trunkQuarantine?.ttlDays ?? 15+ const overdueCount = trunkQuarantine ? trunkQuarantine.teams.reduce((n, t) => n + t.overdueCount, 0) : null+ const oldestAgeDays = trunkQuarantine?.tests.length ? trunkQuarantine.tests[0].ageDays : null- const columns: LemonTableColumns<FlakyTestRow> = [+ const teamColumns: LemonTableColumns<TrunkQuarantineTeamRow> = [{- title: 'Test',- key: 'nodeid',- width: 360,- render: (_, row) => {- const { label, type, tooltip } = FLAKY_CLASSIFICATION[row.classification]- return (- <div className="flex max-w-[22rem] flex-col gap-0.5">- <Tooltip title={row.nodeid}>- <span className="truncate font-mono text-xs">{row.nodeid}</span>- </Tooltip>- <div>- <Tooltip title={tooltip}>- <LemonTag type={type} size="small">- {label}- </LemonTag>- </Tooltip>- </div>- </div>- )- },+ title: 'Team',+ key: 'ownerTeam',+ render: (_, row) => <span className="font-semibold">{teamLabel(row.ownerTeam)}</span>,},{- title: 'Evidence',- key: 'failedRunCount',- tooltip: 'Absolute counts, never a rate: fast passing runs are not recorded, so there is no denominator.',- sorter: (a, b) => a.failedRunCount - b.failedRunCount,- render: (_, row) => (- <div className="flex flex-col gap-0.5 text-xs">- {row.failedRunCount > 0 && (- <span>- {pluralize(row.failedRunCount, 'failed run')} · {pluralize(row.failedPrCount, 'PR')}- </span>- )}- {row.quarantinedFailedRunCount > 0 && (- <span>Failed in {pluralize(row.quarantinedFailedRunCount, 'quarantined run')}</span>- )}- {/* A quarantined row has no recovery question to answer: it is masked, not racing. */}- {row.classification !== 'quarantined' && (- <span className="text-secondary">- {row.sameCommitRecoveryRunCount > 0- ? `Recovered on the same commit in ${pluralize(row.sameCommitRecoveryRunCount, 'run')}`- : 'No recovery recorded'}- </span>- )}- {row.masterFailedRunCount > 0 && (- <span className="font-semibold text-danger">- {pluralize(row.masterFailedRunCount, 'master failure')}- </span>- )}- </div>- ),+ title: 'Quarantined',+ key: 'testCount',+ align: 'right',+ sorter: (a, b) => a.testCount - b.testCount,+ render: (_, row) => humanFriendlyNumber(row.testCount),},{- title: 'Last signal',- key: 'lastSignalAt',- width: 120,+ title: 'Overdue',+ key: 'overdueCount',align: 'right',- sorter: (a, b) => a.lastSignalAt.localeCompare(b.lastSignalAt),- render: (_, row) => <RelativeTime iso={row.lastSignalAt} />,+ tooltip: `Quarantined longer than ${pluralize(ttlDays, 'day')}.`,+ sorter: (a, b) => a.overdueCount - b.overdueCount,+ render: (_, row) =>+ row.overdueCount > 0 ? (+ <span className="font-semibold text-danger">{humanFriendlyNumber(row.overdueCount)}</span>+ ) : (+ '0'+ ),},{- title: '',- key: 'actions',- width: 130,+ title: 'Oldest',+ key: 'oldestAgeDays',align: 'right',- render: (_, row) =>- row.classification === 'confirmed_flake' ? (- <LemonButton- size="small"- type="tertiary"- icon={<IconShieldLock />}- tooltip="Review the evidence and owner before opening a tracking issue and quarantine PR."- aria-label={`Quarantine ${row.nodeid}`}- onClick={() =>- openQuarantineModal({- action: 'quarantine',- selector: row.selector,- runner: row.runner,- // The evidence is the reason; the cause is the tracking issue's job to find.- reason: flakyEvidenceReason(row, flakyTestWindow),- owner: '',- issue: '',- mode: 'run',- confirm: true,- })- }- data-attr="eng-analytics-flaky-quarantine"- >- Quarantine…- </LemonButton>- ) : null,+ sorter: (a, b) => a.oldestAgeDays - b.oldestAgeDays,+ render: (_, row) => `${row.oldestAgeDays}d`,},]- 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">Active test health queue</h3>- <p className="m-0 text-xs text-tertiary">- CI tests worth acting on now, ranked by blast radius: how many PRs they broke and how often they- broke master.- </p>- </div>- <LemonSegmentedButton- size="small"- value={flakyTestWindow}- onChange={(value) => setFlakyTestWindow(value as FlakyTestWindow)}- options={[- { value: '-7d', label: '7d' },- { value: '-14d', label: '14d' },- { value: '-30d', label: '30d' },- ]}- />- </div>- {flakyTestsStatus === 'error' ? (- <LemonBanner type="warning">Couldn't load flaky test data. Try refreshing.</LemonBanner>- ) : (- <>- <LemonTable- data-attr="engineering-analytics-flaky-tests-table"- size="small"- columns={columns}- dataSource={flakyTests?.rows ?? []}- rowKey={(row) => `${row.runner}:${row.nodeid}`}- loading={flakyTestsLoading}- pagination={{ pageSize: 10 }}- useURLForSorting={false}- emptyState="No tests need attention in this window."- nouns={['test', 'tests']}- />- {flakyTests?.truncated && (- <div className="text-xs text-tertiary">- Showing the top {flakyTests.limit} by blast radius. More tests qualified in this window.- </div>- )}- </>- )}- </div>- )-}--export function EngineeringAnalyticsTestHealth(): JSX.Element {- const { quarantineLoadFailed, quarantineModal, quarantineOwnerOptions, quarantineSubmitLoading } =- useValues(engineeringAnalyticsLogic)- const { closeQuarantineModal, submitQuarantine } = useActions(engineeringAnalyticsLogic)-- // Production with no GitHub source and no local checkout: the endpoint 400s, same as the other tabs.- if (quarantineLoadFailed) {- return <ConnectGitHubSource />- }-- return (- <div className="flex flex-col gap-8">- {/* Tab-level: both sections read the same source, so the picker scopes them together. */}- <ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />- <ActiveTestHealthQueue />- <QuarantineRegister />- {/* Rendered once for the whole tab: the queue rows, the register rows, and the- register's no-file empty state all open it. */}- <QuarantineTestModal- modal={quarantineModal}- ownerOptions={quarantineOwnerOptions}- submitting={quarantineSubmitLoading}- onClose={closeQuarantineModal}- onSubmit={(input) => submitQuarantine({ input })}- />- </div>- )-}--function QuarantineRegister(): JSX.Element {- const {- quarantine,- quarantineLoading,- filteredQuarantineEntries,- quarantineCounts,- quarantineOwnerOptions,- quarantineSearch,- quarantineLifecycleFilter,- quarantineModeFilter,- quarantineOwner,- activeQuarantineCard,- hasActiveQuarantineFilters,- } = useValues(engineeringAnalyticsLogic)- const {- setQuarantineSearch,- setQuarantineLifecycleFilter,- setQuarantineModeFilter,- setQuarantineOwner,- applyQuarantineCard,- resetQuarantineFilters,- openQuarantineModal,- submitQuarantine,- } = useActions(engineeringAnalyticsLogic)-- const openNewQuarantine = (): void =>- openQuarantineModal({- action: 'quarantine',- selector: '',- runner: 'pytest',- reason: '',- owner: '',- issue: '',- mode: 'run',- })-- const openExtend = (row: QuarantineEntryRow): void => {- if (!isTestRunner(row.runner)) {- return- }- openQuarantineModal({- action: 'extend',- selector: row.id,- runner: row.runner,- reason: row.reason,- owner: row.owner,- issue: row.issue,- mode: row.mode,- })- }-- const confirmRemove = (row: QuarantineEntryRow): void => {- LemonDialog.open({- title: 'Remove from quarantine?',- description: `Opens a PR that removes ${row.id} from .test_quarantine.json so it gates CI normally again. It takes effect once the PR merges.`,- primaryButton: {- children: 'Open removal PR',- status: 'danger',- onClick: () =>- submitQuarantine({- input: {- action: 'remove',- selector: row.id,- reason: '',- owner: '',- issue: row.issue,- expires: null,- mode: row.mode,- },- }),- },- secondaryButton: { children: 'Cancel' },- })- }-- // A fetch failure (timeout, 5xx, unsafe repo) also comes back as available:false, but with- // parse_errors set — surface those instead of the "no file" explainer, which only fits a true 404.- if (quarantine && !quarantine.available && quarantine.parseErrors.length > 0) {- return (- <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">- <IconShieldLock className="size-8 text-tertiary" />- <div className="text-lg font-semibold">Couldn't read the quarantine file</div>- <div className="w-full max-w-xl">- <LemonBanner type="warning">- <ul className="ml-4 list-disc text-left">- {quarantine.parseErrors.map((error, index) => (- <li key={index} className="font-mono text-xs">- {error}- </li>- ))}- </ul>- </LemonBanner>- </div>- {quarantine.repoFullName && (- <p className="text-sm text-secondary">- Repository: <span className="font-mono">{quarantine.repoFullName}</span>- </p>- )}- </div>- )+ if (trunkQuarantineStatus === 'error') {+ return <LemonBanner type="warning">Couldn't load Trunk quarantine data. Try refreshing.</LemonBanner>}-- // A file that does not exist is a normal state, not an error — offer to start one.- if (quarantine && !quarantine.available) {+ if (trunkQuarantineStatus === 'notConnected' || (trunkQuarantine && !trunkQuarantine.available)) {return (- <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">- <IconShieldLock className="size-8 text-tertiary" />- <div className="text-lg font-semibold">No test quarantine yet</div>- <p className="max-w-xl text-sm text-secondary">- {quarantine.repoFullName- ? `${quarantine.repoFullName} has no .test_quarantine.json. `- : 'This repo has no .test_quarantine.json. '}- Quarantine masks a flaky test in CI with a hard expiry, so it stops blocking merges while its owner- fixes it. The first quarantine opens a PR that creates the file.- </p>- <LemonButton type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">- Quarantine a test- </LemonButton>- </div>+ <LemonBanner type="info">+ No Trunk source is connected. Connect the Trunk.io data warehouse source with its quarantined tests+ endpoint to see which quarantined tests each team owns.+ </LemonBanner>)}- const columns: LemonTableColumns<QuarantineEntryRow> = [- {- title: 'Selector',- key: 'id',- render: (_, row) => {- const isEnforced = isTestRunner(row.runner)- return (- <div className="flex max-w-[28rem] flex-col gap-0.5">- <Tooltip title={row.id}>- <span className="truncate font-mono text-xs">{row.id}</span>- </Tooltip>- <div className="flex items-center gap-1.5">- <LemonTag type="option" size="small">- {row.selectorKind}- </LemonTag>- {row.runner !== 'pytest' && (- <Tooltip- title={- isEnforced- ? `Enforced by the ${row.runner} adapter.`- : 'No enforcement adapter yet. This entry is informational.'- }- >- <LemonTag type={isEnforced ? 'option' : 'muted'} size="small">- {row.runner}- </LemonTag>- </Tooltip>- )}- </div>- </div>- )- },- },- {- title: 'Mode',- key: 'mode',- width: 130,- render: (_, row) => <ModeTag mode={row.mode} />,- },- {- title: 'Status',- key: 'lifecycle',- width: 150,- render: (_, row) => <LifecycleTag lifecycle={row.lifecycle} />,- },- {- title: 'Owner',- key: 'owner',- width: 200,- render: (_, row) => <span className="font-mono text-xs">{row.owner || '—'}</span>,- },- {- title: 'Reason',- key: 'reason',- render: (_, row) => (- <Tooltip title={row.reason}>- <span className="line-clamp-2 max-w-[20rem] text-xs text-secondary">{row.reason || '—'}</span>- </Tooltip>- ),- },- {- title: 'Issue',- key: 'issue',- width: 70,- align: 'center',- render: (_, row) =>- row.issue ? (- <Link to={row.issue} target="_blank">- <IconExternal className="text-base" />- </Link>- ) : (- <span className="text-tertiary">—</span>- ),- },- {- title: 'Added',- key: 'added',- width: 110,- align: 'right',- sorter: (a, b) => a.added.localeCompare(b.added),- render: (_, row) => (- <span className="text-xs whitespace-nowrap tabular-nums text-secondary">{row.added}</span>- ),- },- {- title: 'Expires',- key: 'expires',- width: 150,- align: 'right',- sorter: (a, b) => a.daysUntilExpiry - b.daysUntilExpiry,- render: (_, row) => (- <div className="flex flex-col items-end gap-0.5">- <span className="text-xs whitespace-nowrap tabular-nums">{row.expires}</span>- <span- className={cn(- 'text-xs whitespace-nowrap tabular-nums',- row.daysUntilExpiry < 0 ? 'text-danger' : 'text-tertiary'- )}- >- {relativeExpiry(row.daysUntilExpiry)}- </span>- </div>- ),- },- {- title: '',- key: 'actions',- width: 40,- render: (_, row) => (- <LemonMenu- items={[- {- label: 'Extend…',- onClick: () => openExtend(row),- disabledReason: isTestRunner(row.runner)- ? undefined- : `Runner '${row.runner}' is not supported here`,- },- { label: 'Remove…', status: 'danger', onClick: () => confirmRemove(row) },- ...(row.issue ? [{ label: 'Open issue', to: row.issue, targetBlank: true }] : []),- ]}- >- <LemonButton size="small" icon={<IconEllipsis />} aria-label="More actions" />- </LemonMenu>- ),- },- ]-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">Quarantine register</h3>- <p className="m-0 text-xs text-tertiary">- Flaky tests currently masked in CI via the checked-in quarantine file.- </p>- </div>- <LemonButton type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">- Quarantine a test- </LemonButton>+ <div className="flex items-center justify-between gap-2">+ <h3 className="m-0 text-base font-semibold">Quarantine debt by team</h3>+ {trunkQuarantine?.trunkUrl && (+ <LemonButton+ size="small"+ type="secondary"+ to={trunkQuarantine.trunkUrl}+ targetBlank+ sideIcon={<IconExternal />}+ data-attr="engineering-analytics-trunk-debt-open-trunk"+ >+ Open in Trunk+ </LemonButton>+ )}</div>- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <div className="grid grid-cols-1 gap-3 @2xl/main-content:grid-cols-2 @5xl/main-content:grid-cols-4"><StatCard- label="Active"- value={quarantine ? humanFriendlyNumber(quarantineCounts.active) : '—'}- caption="more than 7 days of runway"- loading={quarantineLoading}- onClick={() => applyQuarantineCard('active')}- active={activeQuarantineCard === 'active'}- filterHint="Filter to entries with runway left"+ label="Quarantined tests"+ value={trunkQuarantine ? humanFriendlyNumber(trunkQuarantine.tests.length) : '—'}+ caption="currently masked in CI"+ loading={trunkQuarantineLoading}/><StatCard- label="Expiring soon"- value={quarantine ? humanFriendlyNumber(quarantineCounts.expiringSoon) : '—'}- caption="7 days or fewer left"- loading={quarantineLoading}- onClick={() => applyQuarantineCard('expiring_soon')}- active={activeQuarantineCard === 'expiring_soon'}- filterHint="Filter to entries expiring within 7 days"+ label="Overdue"+ value={overdueCount !== null ? humanFriendlyNumber(overdueCount) : '—'}+ caption={`quarantined over ${ttlDays} days`}+ loading={trunkQuarantineLoading}/><StatCard- label="Past expiry"- value={quarantine ? humanFriendlyNumber(quarantineCounts.pastExpiry) : '—'}- caption="fails the quarantine check after 7 days"- loading={quarantineLoading}- onClick={() => applyQuarantineCard('past_expiry')}- active={activeQuarantineCard === 'past_expiry'}- filterHint="Filter to expired entries (in grace or overdue)"+ label="Teams affected"+ value={trunkQuarantine ? humanFriendlyNumber(trunkQuarantine.teams.length) : '—'}+ caption="own at least one quarantined test"+ loading={trunkQuarantineLoading}/><StatCard- label="Skipped entirely"- value={quarantine ? humanFriendlyNumber(quarantineCounts.skipped) : '—'}- caption="dropped from CI, not just masked"- loading={quarantineLoading}- onClick={() => applyQuarantineCard('skipped')}- active={activeQuarantineCard === 'skipped'}- filterHint="Filter to entries skipped entirely (mode: skip)"+ label="Oldest quarantine"+ value={oldestAgeDays !== null ? `${oldestAgeDays}d` : '—'}+ caption="longest-standing masked test"+ loading={trunkQuarantineLoading}/></div>-- {quarantine && quarantine.parseErrors.length > 0 && (- <LemonBanner type="warning">- <div className="font-semibold">The quarantine file has problems</div>- <ul className="ml-4 list-disc">- {quarantine.parseErrors.map((error, index) => (- <li key={index} className="font-mono text-xs">- {error}- </li>- ))}- </ul>- </LemonBanner>- )}- {quarantine && quarantine.parseWarnings.length > 0 && (- <LemonBanner type="info">- <ul className="ml-4 list-disc">- {quarantine.parseWarnings.map((warning, index) => (- <li key={index} className="font-mono text-xs">- {warning}- </li>- ))}- </ul>- </LemonBanner>- )}-- <div className="flex flex-wrap items-center gap-2">- <LemonInput- type="search"- placeholder="Search selector, reason, owner…"- value={quarantineSearch}- onChange={setQuarantineSearch}- className="w-64"- />- <LemonSegmentedButton- size="small"- value={quarantineLifecycleFilter}- onChange={(value) => setQuarantineLifecycleFilter(value as QuarantineLifecycleFilter)}- options={[- { value: 'all', label: 'All' },- { value: 'active', label: 'Active' },- { value: 'expiring_soon', label: 'Expiring' },- { value: 'past_expiry', label: 'Past expiry' },- ]}- />- <LemonSelect- size="small"- value={quarantineModeFilter}- onChange={(value) => setQuarantineModeFilter(value as QuarantineModeFilter)}- options={[- { value: 'all', label: 'Mode: any', labelInMenu: 'Any' },- { value: 'run', label: 'Mode: runs', labelInMenu: "Runs, can't fail" },- { value: 'skip', label: 'Mode: skipped', labelInMenu: 'Skipped' },- ]}- />- <div className="w-56">- <LemonInputSelect- mode="single"- size="small"- placeholder="Owner: anyone"- value={quarantineOwner ? [quarantineOwner] : []}- onChange={(values) => setQuarantineOwner(values[0] ?? null)}- options={quarantineOwnerOptions.map((owner) => ({ key: owner, label: owner }))}- data-attr="engineering-analytics-quarantine-owner-filter"- />- </div>- {hasActiveQuarantineFilters && (- <LemonButton type="secondary" size="small" onClick={resetQuarantineFilters}>- Reset- </LemonButton>- )}- {quarantine?.sourceUrl && (- <Link to={quarantine.sourceUrl} target="_blank" className="ml-auto text-xs">- View .test_quarantine.json- </Link>- )}- </div>-<LemonTable- data-attr="engineering-analytics-quarantine-table"+ data-attr="engineering-analytics-trunk-debt-teams-table"size="small"- columns={columns}- dataSource={filteredQuarantineEntries}- rowKey={(row) => `${row.runner}:${row.id}`}- loading={quarantineLoading}- pagination={{ pageSize: 25 }}+ columns={teamColumns}+ dataSource={trunkQuarantine?.teams ?? []}+ rowKey={(row) => row.ownerTeam}+ loading={trunkQuarantineLoading}useURLForSorting={false}- emptyState={- hasActiveQuarantineFilters ? (- <div className="flex flex-col items-center gap-2">- <span>No entries match these filters.</span>- <LemonButton type="secondary" size="small" onClick={resetQuarantineFilters}>- Clear filters- </LemonButton>- </div>- ) : (- 'No quarantined tests. Nothing is masked right now.'- )- }- nouns={['quarantined test', 'quarantined tests']}+ emptyState="No tests are quarantined right now."+ nouns={['team', 'teams']}+ onRow={(row) => ({+ className: 'cursor-pointer',+ onClick: () => toggleTrunkQuarantineTeam(row.ownerTeam),+ })}+ expandable={{+ noIndent: true,+ isRowExpanded: (row) => expandedTrunkQuarantineTeams.includes(row.ownerTeam),+ expandedRowRender: (row) => (+ <TeamQuarantinedTestsTable+ tests={trunkQuarantineTestsByTeam[row.ownerTeam] ?? []}+ ttlDays={ttlDays}+ repository={trunkQuarantine?.repository ?? ''}+ />+ ),+ }}/>+ </div>+ )+}- <div className="text-xs text-tertiary">- Quarantine is checked into <span className="font-mono">.test_quarantine.json</span> and enforced by CI.- Quarantining, extending, or removing opens a pull request, so the file stays the source of truth. A- merged edit only affects CI runs that start after it lands.- </div>+export function EngineeringAnalyticsTestHealth(): JSX.Element {+ const { quarantineLoadFailed } = useValues(engineeringAnalyticsLogic)++ // Production with no GitHub source and no local checkout: the endpoint 400s, same as the other tabs.+ if (quarantineLoadFailed) {+ return <ConnectGitHubSource />+ }++ return (+ <div className="flex flex-col gap-8">+ <ScopeBar repoSlot={<SourceScopeChip />} showDate={false} />+ <TrunkQuarantineDebtBoard /></div>)}diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.tsindex ab933559e55f..2e2a71a94a39 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts@@ -12,15 +12,14 @@ import {engineeringAnalyticsCiCards,engineeringAnalyticsPullRequests,engineeringAnalyticsQuarantine,- engineeringAnalyticsQuarantineRequest,engineeringAnalyticsSources,+ engineeringAnalyticsTrunkQuarantine,engineeringAnalyticsWorkflowHealth,} from '../generated/api'import type {CICardSummaryApi,GitHubSourceApi,PullRequestListItemApi,- QuarantineEntryApi,QuarantineFileApi,WorkflowHealthItemApi,WorkflowRunDetailApi,@@ -30,19 +29,13 @@ import { summarizeLifecycle, workflowRuns } from '../lib/lifecycle'import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'import {DEFAULT_FILTERS,- DEFAULT_QUARANTINE_FILTERS,DEFAULT_WORKFLOW_FILTERS,PullRequestRow,- QuarantineEntryRow,WorkflowHealthRow,engineeringAnalyticsLogic,filterPullRequests,filterWorkflowHealth,workflowFailureSeries,- filterQuarantineEntries,- inferOwnerFromSelector,- quarantineCountsOf,- quarantineRequestErrorMessage,} from './engineeringAnalyticsLogic'import { engineeringAnalyticsSceneLogic } from './engineeringAnalyticsSceneLogic'import { groupRunsByCommit, sortRunsForTriage } from './pullRequestDetailLogic'@@ -52,8 +45,8 @@ jest.mock('../generated/api', () => ({engineeringAnalyticsPrLifecycle: jest.fn(),engineeringAnalyticsPullRequests: jest.fn(),engineeringAnalyticsQuarantine: jest.fn(),- engineeringAnalyticsQuarantineRequest: jest.fn(),engineeringAnalyticsSources: jest.fn(),+ engineeringAnalyticsTrunkQuarantine: jest.fn(),engineeringAnalyticsWorkflowHealth: jest.fn(),}))@@ -65,61 +58,14 @@ const mockWorkflowHealth = engineeringAnalyticsWorkflowHealth as jest.MockedFunctypeof engineeringAnalyticsWorkflowHealth>const mockQuarantine = engineeringAnalyticsQuarantine as jest.MockedFunction<typeof engineeringAnalyticsQuarantine>-const mockQuarantineRequest = engineeringAnalyticsQuarantineRequest as jest.MockedFunction<- typeof engineeringAnalyticsQuarantineRequest->const mockSources = engineeringAnalyticsSources as jest.MockedFunction<typeof engineeringAnalyticsSources>--function apiQuarantineEntry(overrides: Partial<QuarantineEntryApi> = {}): QuarantineEntryApi {- return {- id: 'posthog/api/test/test_foo.py::TestFoo::test_bar',- runner: 'pytest',- reason: 'flaky ordering assertion',- owner: '@PostHog/team-foo',- issue: '',- added: '2026-06-01',- expires: '2026-06-20',- mode: 'run',- lifecycle: 'active',- days_until_expiry: 8,- selector_kind: 'test',- ...overrides,- }-}--function qRow(overrides: Partial<QuarantineEntryRow> = {}): QuarantineEntryRow {- return {- id: 'posthog/api/test/test_foo.py::TestFoo::test_bar',- runner: 'pytest',- reason: 'flaky',- owner: '@PostHog/team-foo',- issue: '',- added: '2026-06-01',- expires: '2026-06-20',- mode: 'run',- lifecycle: 'active',- daysUntilExpiry: 8,- selectorKind: 'test',- ...overrides,- }-}+const mockTrunkQuarantine = engineeringAnalyticsTrunkQuarantine as jest.MockedFunction<+ typeof engineeringAnalyticsTrunkQuarantine+>const QUARANTINE: QuarantineFileApi = {available: true,- entries: [- apiQuarantineEntry({ id: 'a-overdue', lifecycle: 'overdue', days_until_expiry: -10, owner: '@team/x' }),- apiQuarantineEntry({ id: 'b-grace', lifecycle: 'in_grace', days_until_expiry: -2, owner: '@team/y' }),- apiQuarantineEntry({ id: 'c-soon', lifecycle: 'expiring_soon', days_until_expiry: 3, owner: '@team/x' }),- apiQuarantineEntry({ id: 'd-active', lifecycle: 'active', days_until_expiry: 20, owner: '@team/z' }),- apiQuarantineEntry({- id: 'product:e',- lifecycle: 'active',- mode: 'skip',- selector_kind: 'product',- owner: '@team/z',- reason: 'teardown hang',- }),- ],+ entries: [],parse_errors: [],parse_warnings: [],repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },@@ -248,13 +194,16 @@ describe('engineeringAnalyticsLogic', () => {mockPullRequests.mockResolvedValue({ items: PRS, truncated: false, limit: PRS.length })mockWorkflowHealth.mockResolvedValue(WORKFLOWS)mockQuarantine.mockResolvedValue(QUARANTINE)- mockQuarantineRequest.mockResolvedValue({- pr_url: 'https://github.com/PostHog/posthog/pull/99',- issue_url: 'https://github.com/PostHog/posthog/issues/4242',- branch: 'quarantine/foo-20260612',- })// Most tests are single- or no-source; the picker tests override with SOURCES.mockSources.mockResolvedValue([])+ mockTrunkQuarantine.mockResolvedValue({+ available: true,+ ttl_days: 15,+ repository: 'PostHog/posthog',+ trunk_url: null,+ teams: [],+ tests: [],+ })})afterEach(() => {@@ -569,19 +518,6 @@ describe('engineeringAnalyticsLogic', () => {'workflowFilters',DEFAULT_WORKFLOW_FILTERS,],- [- 'quarantine',- [- ['setQuarantineSearch', 'flake'],- ['setQuarantineLifecycleFilter', 'active'],- ['setQuarantineModeFilter', 'skip'],- ['setQuarantineOwner', '@team/x'],- ],- 'resetQuarantineFilters',- 'hasActiveQuarantineFilters',- 'quarantineFilters',- DEFAULT_QUARANTINE_FILTERS,- ],] as [string, [string, string][], string, string, string, object][])('the %s reset returns filters to defaults and clears the active flag',(_label, dirtyCalls, resetAction, activeKey, filtersKey, defaults) => {@@ -766,87 +702,65 @@ describe('engineeringAnalyticsLogic', () => {}).toEqual(expected)})- it.each([- ['all', { lifecycle: 'all' as const }, ['a-overdue', 'b-grace', 'c-soon', 'd-active', 'e-skip']],- ['active', { lifecycle: 'active' as const }, ['d-active', 'e-skip']],- ['expiring_soon', { lifecycle: 'expiring_soon' as const }, ['c-soon']],- // past_expiry groups in_grace + overdue.- ['past_expiry', { lifecycle: 'past_expiry' as const }, ['a-overdue', 'b-grace']],- ['mode skip', { mode: 'skip' as const }, ['e-skip']],- ['owner', { owner: '@team/x' }, ['a-overdue', 'c-soon']],- ['search matches reason', { search: 'hang' }, ['e-skip']],- ['search matches id', { search: 'b-grace' }, ['b-grace']],- ])('filterQuarantineEntries: %s', (_label, partial, expectedIds) => {- const rows = [- qRow({ id: 'a-overdue', lifecycle: 'overdue', daysUntilExpiry: -10, owner: '@team/x' }),- qRow({ id: 'b-grace', lifecycle: 'in_grace', daysUntilExpiry: -2, owner: '@team/y' }),- qRow({ id: 'c-soon', lifecycle: 'expiring_soon', daysUntilExpiry: 3, owner: '@team/x' }),- qRow({ id: 'd-active', lifecycle: 'active', daysUntilExpiry: 20, owner: '@team/z' }),- qRow({ id: 'e-skip', lifecycle: 'active', mode: 'skip', owner: '@team/z', reason: 'teardown hang' }),- ]- const result = filterQuarantineEntries(rows, { ...DEFAULT_QUARANTINE_FILTERS, ...partial })- expect(result.map((row) => row.id)).toEqual(expectedIds)- })-- it('quarantineCountsOf tallies lifecycle buckets, past expiry, and skips', () => {- const counts = quarantineCountsOf([- qRow({ lifecycle: 'overdue' }),- qRow({ lifecycle: 'in_grace' }),- qRow({ lifecycle: 'expiring_soon' }),- qRow({ lifecycle: 'active' }),- qRow({ lifecycle: 'active', mode: 'skip' }),- ])- expect(counts).toEqual({- active: 2,- expiringSoon: 1,- inGrace: 1,- overdue: 1,- pastExpiry: 2,- skipped: 1,- total: 5,+ it('maps the trunk quarantine endpoint and filters the tests by team', async () => {+ mockTrunkQuarantine.mockResolvedValue({+ available: true,+ ttl_days: 15,+ repository: 'PostHog/posthog',+ trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog',+ teams: [{ owner_team: 'team-replay', test_count: 1, overdue_count: 1, oldest_age_days: 44 }],+ tests: [+ {+ runner: 'pytest',+ nodeid: 'a.py::TestA::test_a',+ file: 'a.py',+ owner_team: 'team-replay',+ status: 'FLAKY',+ quarantine_setting: 'AUTO_QUARANTINE',+ quarantined_at: '2026-05-19T08:00:00Z',+ age_days: 44,+ overdue: true,+ trunk_url: 'https://app.trunk.io/posthog-inc/flaky-tests/test/t-1?repo=PostHog/posthog',+ },+ {+ runner: 'jest',+ nodeid: 'b.test.tsx::renders',+ file: 'b.test.tsx',+ owner_team: 'unowned',+ status: 'FLAKY',+ quarantine_setting: 'AUTO_QUARANTINE',+ quarantined_at: '2026-06-23T08:00:00Z',+ age_days: 9,+ overdue: false,+ trunk_url: null,+ },+ ],})- })-- it('maps the quarantine endpoint into rows with counts and owner options', async () => {logic = engineeringAnalyticsLogic()logic.mount()- await expectLogic(logic).toDispatchActions(['loadQuarantineSuccess'])-- expect(logic.values.quarantine?.available).toBe(true)- expect(logic.values.quarantine?.repoFullName).toBe('PostHog/posthog')- expect(logic.values.quarantine?.entries).toHaveLength(5)- expect(logic.values.quarantineCounts).toEqual({- active: 2,- expiringSoon: 1,- inGrace: 1,- overdue: 1,- pastExpiry: 2,- skipped: 1,- total: 5,- })- expect(logic.values.quarantineOwnerOptions).toEqual(['@team/x', '@team/y', '@team/z'])- expect(logic.values.quarantineLoadFailed).toBe(false)- })+ await expectLogic(logic).toDispatchActions(['loadTrunkQuarantineSuccess'])- it('quarantine cards toggle the lifecycle and mode lens and back', async () => {- logic = engineeringAnalyticsLogic()- logic.mount()- expect(logic.values.activeQuarantineCard).toBeNull()-- logic.actions.applyQuarantineCard('past_expiry')- expect(logic.values.activeQuarantineCard).toBe('past_expiry')- expect(logic.values.quarantineLifecycleFilter).toBe('past_expiry')- expect(logic.values.quarantineModeFilter).toBe('all')-- logic.actions.applyQuarantineCard('skipped')- expect(logic.values.activeQuarantineCard).toBe('skipped')- expect(logic.values.quarantineModeFilter).toBe('skip')- expect(logic.values.quarantineLifecycleFilter).toBe('all')-- // Clicking the active card clears the lens back to the default view.- logic.actions.applyQuarantineCard('skipped')- expect(logic.values.activeQuarantineCard).toBeNull()- expect(logic.values.quarantineModeFilter).toBe('all')+ expect(logic.values.trunkQuarantine?.ttlDays).toBe(15)+ expect(logic.values.trunkQuarantine?.repository).toBe('PostHog/posthog')+ expect(logic.values.trunkQuarantine?.trunkUrl).toBe(+ 'https://app.trunk.io/posthog-inc/flaky-tests?repo=PostHog/posthog'+ )+ expect(logic.values.trunkQuarantine?.tests[0]).toEqual({+ runner: 'pytest',+ nodeid: 'a.py::TestA::test_a',+ file: 'a.py',+ ownerTeam: 'team-replay',+ status: 'FLAKY',+ quarantineSetting: 'AUTO_QUARANTINE',+ quarantinedAt: '2026-05-19T08:00:00Z',+ ageDays: 44,+ overdue: true,+ trunkUrl: 'https://app.trunk.io/posthog-inc/flaky-tests/test/t-1?repo=PostHog/posthog',+ })+ expect(Object.keys(logic.values.trunkQuarantineTestsByTeam)).toEqual(['team-replay', 'unowned'])+ expect(logic.values.trunkQuarantineTestsByTeam['team-replay'].map((test) => test.nodeid)).toEqual([+ 'a.py::TestA::test_a',+ ])})it('flags quarantineLoadFailed when the quarantine endpoint 400s', async () => {@@ -861,120 +775,4 @@ describe('engineeringAnalyticsLogic', () => {expect(logic.values.quarantineLoadFailed).toBe(true)})-- it.each([- ['product: selector', 'product:batch-exports', '@PostHog/team-batch-exports'],- ['products/ path', 'products/web_analytics/backend/test_foo.py::T::t', '@PostHog/team-web-analytics'],- ['plain nodeid', 'posthog/api/test/test_foo.py::T::t', ''],- ['bare file', 'frontend/src/foo.test.ts', ''],- ])('inferOwnerFromSelector: %s', (_label, selector, expected) => {- expect(inferOwnerFromSelector(selector)).toBe(expected)- })-- it.each([- ['DRF detail', { detail: 'App not installed' }, 'App not installed'],- ['nested data.detail', { data: { detail: 'Malformed file' } }, 'Malformed file'],- ['error message', new Error('Network down'), 'Network down'],- ['unknown shape', {}, 'Could not complete the quarantine request.'],- ])('quarantineRequestErrorMessage: %s', (_label, error, expected) => {- expect(quarantineRequestErrorMessage(error)).toBe(expected)- })-- it('a successful submit closes the modal and reloads the register', async () => {- logic = engineeringAnalyticsLogic()- logic.mount()- await expectLogic(logic).toDispatchActions(['loadQuarantineSuccess'])-- logic.actions.openQuarantineModal({- action: 'quarantine',- selector: 'frontend/src/a.test.ts::renders',- runner: 'jest',- reason: 'flaky',- owner: '@team/x',- issue: '',- mode: 'run',- })- expect(logic.values.quarantineModal?.selector).toBe('frontend/src/a.test.ts::renders')- logic.actions.submitQuarantine({- input: {- action: 'quarantine',- selector: 'frontend/src/a.test.ts::renders',- runner: 'jest',- reason: 'flaky',- owner: '@team/x',- issue: '',- expires: '2026-06-26',- mode: 'run',- },- })- // The success listener reloads the register so the merged change shows up.- await expectLogic(logic).toDispatchActions(['submitQuarantineSuccess', 'loadQuarantine'])-- // The viewed repo is threaded into the write so the PR targets it.- expect(mockQuarantineRequest).toHaveBeenCalledWith(- '1',- expect.objectContaining({ operation: 'quarantine', repo: 'PostHog/posthog', runner: 'jest' })- )- expect(logic.values.quarantineModal).toBeNull()- expect(logic.values.quarantineSubmitLoading).toBe(false)- })-- it('omits the runner when removing a forward-compatible quarantine entry', async () => {- logic = engineeringAnalyticsLogic()- logic.mount()-- logic.actions.submitQuarantine({- input: {- action: 'remove',- selector: 'future/runner/test',- reason: '',- owner: '',- issue: '',- expires: null,- mode: 'run',- },- })- await expectLogic(logic).toDispatchActions(['submitQuarantineSuccess'])-- expect(mockQuarantineRequest).toHaveBeenCalledWith(- '1',- expect.not.objectContaining({ runner: expect.anything() })- )- })-- it('a failed submit keeps the modal open so the user can retry', async () => {- silenceKeaLoadersErrors() // the submit failure is the scenario under test- mockQuarantineRequest.mockRejectedValue({ detail: "The App isn't installed on PostHog." })- logic = engineeringAnalyticsLogic()- logic.mount()-- logic.actions.openQuarantineModal({- action: 'quarantine',- selector: 'a/b.py::T::t',- runner: 'pytest',- reason: 'flaky',- owner: '@team/x',- issue: '',- mode: 'run',- })- logic.actions.submitQuarantine({- input: {- action: 'quarantine',- selector: 'a/b.py::T::t',- runner: 'pytest',- reason: 'flaky',- owner: '@team/x',- issue: '',- expires: null,- mode: 'run',- },- })- await expectLogic(logic).toDispatchActions(['submitQuarantineFailure'])-- expect(logic.values.quarantineModal).not.toBeNull()- expect(logic.values.quarantineSubmitLoading).toBe(false)-- logic.actions.closeQuarantineModal()- expect(logic.values.quarantineModal).toBeNull()- })})diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex 7c349a80adf6..18ed599b3fba 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -13,31 +13,21 @@ import {import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'-import { lemonToast } from '@posthog/lemon-ui'-import { ApiConfig, ApiError } from 'lib/api'import { dayjs } from 'lib/dayjs'+import { groupBy } from 'lib/utils/arrays'import { objectsEqual } from 'lib/utils/objects'-import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'import {engineeringAnalyticsCiCards,- engineeringAnalyticsFlakyTests,engineeringAnalyticsPullRequests,engineeringAnalyticsQuarantine,- engineeringAnalyticsQuarantineRequest,engineeringAnalyticsSources,+ engineeringAnalyticsTrunkQuarantine,engineeringAnalyticsWorkflowHealth,} from '../generated/api'-import type {- FlakyTestItemClassificationEnumApi,- GitHubSourceApi,- PullRequestListItemApi,- PushCISampleApi,- QuarantineRequestApi,- QuarantineRequestResultApi,-} from '../generated/api.schemas'+import type { GitHubSourceApi, PullRequestListItemApi, PushCISampleApi } from '../generated/api.schemas'import { CIStatus, ciStatusOf } from '../lib/ci'import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'import { scopeToValue } from '../lib/scope'@@ -50,9 +40,6 @@ export const PR_TABLE_LIMIT = 1000// Mirrors `workflow_health.py` `_LIMIT` (top workflows by run count).export const WORKFLOW_HEALTH_LIMIT = 100-// Mirrors the endpoint's maximum so the UI can paginate every returned queue row.-export const FLAKY_TEST_LIMIT = 200-const projectId = (): string => String(ApiConfig.getCurrentProjectId())export type PRState = 'open' | 'closed' | 'merged'@@ -326,11 +313,6 @@ export type QuarantineMode = 'run' | 'skip'export type QuarantineLifecycle = 'active' | 'expiring_soon' | 'in_grace' | 'overdue'export type QuarantineSelectorKind = 'product' | 'directory' | 'file' | 'test'-/** 'past_expiry' groups in_grace + overdue — the states the quarantine check warns or fails on. */-export type QuarantineLifecycleFilter = 'all' | 'active' | 'expiring_soon' | 'past_expiry'-export type QuarantineModeFilter = QuarantineMode | 'all'-export type QuarantineCard = 'active' | 'expiring_soon' | 'past_expiry' | 'skipped'-export interface QuarantineEntryRow {id: stringrunner: string@@ -359,201 +341,37 @@ export interface QuarantineData {repoFullName: string | null}-export interface QuarantineCounts {- active: number- expiringSoon: number- inGrace: number- overdue: number- /** in_grace + overdue — everything the quarantine check warns or fails on. */- pastExpiry: number- skipped: number- total: number-}--export interface QuarantineFilters {- search: string- lifecycle: QuarantineLifecycleFilter- mode: QuarantineModeFilter- owner: string | null-}--export const DEFAULT_QUARANTINE_FILTERS: QuarantineFilters = {- search: '',- lifecycle: 'all',- mode: 'all',- owner: null,-}--function matchesLifecycleFilter(row: QuarantineEntryRow, lifecycle: QuarantineLifecycleFilter): boolean {- if (lifecycle === 'all') {- return true- }- if (lifecycle === 'past_expiry') {- return row.lifecycle === 'in_grace' || row.lifecycle === 'overdue'- }- return row.lifecycle === lifecycle-}--export function filterQuarantineEntries(rows: QuarantineEntryRow[], filters: QuarantineFilters): QuarantineEntryRow[] {- const search = filters.search.trim().toLowerCase()- return rows.filter((row) => {- if (!matchesLifecycleFilter(row, filters.lifecycle)) {- return false- }- if (filters.mode !== 'all' && row.mode !== filters.mode) {- return false- }- if (filters.owner && row.owner !== filters.owner) {- return false- }- if (search) {- const haystack = `${row.id} ${row.reason} ${row.owner}`.toLowerCase()- if (!haystack.includes(search)) {- return false- }- }- return true- })-}--export function quarantineCountsOf(rows: QuarantineEntryRow[]): QuarantineCounts {- const counts = {- active: 0,- expiringSoon: 0,- inGrace: 0,- overdue: 0,- skipped: 0,- total: rows.length,- }- for (const row of rows) {- if (row.lifecycle === 'active') {- counts.active++- } else if (row.lifecycle === 'expiring_soon') {- counts.expiringSoon++- } else if (row.lifecycle === 'in_grace') {- counts.inGrace++- } else {- counts.overdue++- }- if (row.mode === 'skip') {- counts.skipped++- }- }- // past_expiry is exactly the expired buckets — derive it so the two can't drift.- return { ...counts, pastExpiry: counts.inGrace + counts.overdue }-}--/** Test-health windows the UI offers; the endpoint accepts any window up to 30 days. */-export type FlakyTestWindow = '-7d' | '-14d' | '-30d'-export const DEFAULT_FLAKY_TEST_WINDOW: FlakyTestWindow = '-7d'-export type FlakyTestClassification = FlakyTestItemClassificationEnumApi-export type TestRunner = NonNullable<QuarantineRequestApi['runner']>-export const TEST_RUNNERS: readonly TestRunner[] = ['pytest', 'jest', 'playwright']--export function isTestRunner(runner: string): runner is TestRunner {- return TEST_RUNNERS.some((candidate) => candidate === runner)-}--export interface FlakyTestRow {- runner: TestRunner- /** Runner-specific test identity (the CI span name): a stable grouping/display key. */+export interface TrunkQuarantinedTestRow {+ runner: stringnodeid: string- /** Runnable selector for the quarantine action; exact when the CI reporter emitted it. */- selector: string- classification: FlakyTestClassification- /** Runs where one commit both failed and passed the test (re-run attempt or in-job retry): the flake proof. */- sameCommitRecoveryRunCount: number- failedRunCount: number- failedPrCount: number- masterFailedRunCount: number- quarantinedFailedRunCount: number- lastSignalAt: string-}--export interface FlakyTestsData {- rows: FlakyTestRow[]- /** True when more tests qualified than the cap; rows are the highest-ranked `limit`. */- truncated: boolean- limit: number-}--export type QuarantineRequestAction = 'quarantine' | 'extend' | 'remove'--/** What the tab submits to the write endpoint; the backend opens the issue + PR. */-export interface QuarantineSubmitInput {- action: QuarantineRequestAction- selector: string- runner?: TestRunner- reason: string- owner: string- /** Existing tracking issue, carried forward on extend/remove. */- issue: string- /** ISO 'YYYY-MM-DD', or null to let the server default to +14 days. */- expires: string | null- mode: QuarantineMode+ file: string+ ownerTeam: string+ status: string+ quarantineSetting: string+ quarantinedAt: string+ ageDays: number+ overdue: boolean+ /** The Trunk app's page for this test; null when the source has no org slug or the row no id. */+ trunkUrl: string | null}-/** Open-modal state for quarantine/extend; null when closed. Remove uses a confirm dialog. */-export interface QuarantineModalState {- action: 'quarantine' | 'extend'- selector: string- runner: TestRunner- reason: string- owner: string- issue: string- mode: QuarantineMode- /** Glanceable confirm presentation for prefilled openers (queue rows); 'Edit details' switches to the form. */- confirm?: boolean+export interface TrunkQuarantineTeamRow {+ ownerTeam: string+ testCount: number+ overdueCount: number+ oldestAgeDays: number}-/** Data-backed quarantine reason from a queue row: the evidence is the reason; the- * cause is unknown until someone investigates, which is the tracking issue's job. */-export function flakyEvidenceReason(row: FlakyTestRow, window: FlakyTestWindow): string {- const windowLabel = { '-7d': '7 days', '-14d': '14 days', '-30d': '30 days' }[window]- const parts: string[] = []- if (row.sameCommitRecoveryRunCount > 0) {- parts.push(`recovered on the same commit in ${pluralize(row.sameCommitRecoveryRunCount, 'run')}`)- }- if (row.failedRunCount > 0) {- parts.push(`failed in ${pluralize(row.failedRunCount, 'run')}`)- }- if (row.failedPrCount > 0) {- parts.push(`hit ${pluralize(row.failedPrCount, 'PR')}`)- }- if (row.masterFailedRunCount > 0) {- parts.push(`broke master in ${pluralize(row.masterFailedRunCount, 'run')}`)- }- return `CI evidence: ${parts.join(', ')} in the last ${windowLabel}`-}--/** Suggest an owning team from a product-scoped selector; '' when the selector isn't product-scoped. */-export function inferOwnerFromSelector(selector: string): string {- const trimmed = selector.trim()- const product = trimmed.startsWith('product:')- ? trimmed.slice('product:'.length)- : (trimmed.match(/^products\/([^/]+)\//)?.[1] ?? '').replace(/_/g, '-')- return product ? `@PostHog/team-${product}` : ''-}--function toRequestBody(input: QuarantineSubmitInput, repo: string | null): QuarantineRequestApi {- return {- // Wire field is 'operation' (a bare 'action' enum collides in the OpenAPI spec).- operation: input.action,- selector: input.selector,- ...(input.runner ? { runner: input.runner } : {}),- // The repo being viewed, so the PR lands there. Null in local dev.- repo,- reason: input.reason,- owner: input.owner,- issue: input.issue,- expires: input.expires,- mode: input.mode,- }-}--export function quarantineRequestErrorMessage(error: unknown): string {- const detail = error as { detail?: string; data?: { detail?: string }; message?: string }- return detail?.detail ?? detail?.data?.detail ?? detail?.message ?? 'Could not complete the quarantine request.'+export interface TrunkQuarantineData {+ /** False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error. */+ available: boolean+ ttlDays: number+ /** 'owner/name' the debt was read for; test file paths are relative to it. */+ repository: string+ /** The Trunk app's flaky-tests page for this repository; null when the source has no org slug. */+ trunkUrl: string | null+ teams: TrunkQuarantineTeamRow[]+ tests: TrunkQuarantinedTestRow[]}/**@@ -572,7 +390,6 @@ export interface engineeringAnalyticsLogicValues {dateFrom: string | null // engineeringAnalyticsFiltersLogicdateTo: string | null // engineeringAnalyticsFiltersLogicactiveCard: CardFilter | null- activeQuarantineCard: QuarantineCard | nullactiveSource: GitHubSourceApi | nullanyLoading: booleanauthor: string | null@@ -580,20 +397,15 @@ export interface engineeringAnalyticsLogicValues {cardsLoading: booleancardsStatus: LoaderStatusciStatusFilter: CIStatusFilter+ expandedTrunkQuarantineTeams: string[]filteredPullRequests: PullRequestRow[]- filteredQuarantineEntries: QuarantineEntryRow[]filteredWorkflowHealth: WorkflowHealthRow[]filters: PullRequestFilters- flakyTestWindow: FlakyTestWindow- flakyTests: FlakyTestsData | null- flakyTestsLoading: boolean- flakyTestsStatus: LoaderStatusfleetSummary: FleetSummaryfleetTruncated: booleangithubSources: GitHubSourceApi[]githubSourcesLoading: booleanhasActiveFilters: boolean- hasActiveQuarantineFilters: booleanhasActiveWorkflowFilters: booleanhasMultipleSources: booleannotConnected: boolean@@ -602,18 +414,8 @@ export interface engineeringAnalyticsLogicValues {pullRequestsLoading: booleanpullRequestsStatus: LoaderStatusquarantine: QuarantineData | null- quarantineCounts: QuarantineCounts- quarantineFilters: QuarantineFilters- quarantineLifecycleFilter: QuarantineLifecycleFilterquarantineLoadFailed: booleanquarantineLoading: boolean- quarantineModal: QuarantineModalState | null- quarantineModeFilter: QuarantineModeFilter- quarantineOwner: string | null- quarantineOwnerOptions: string[]- quarantineSearch: string- quarantineSubmit: QuarantineRequestResultApi | null- quarantineSubmitLoading: booleanreadyCount: numberreadyOnly: booleanrepo: string | null@@ -630,6 +432,10 @@ export interface engineeringAnalyticsLogicValues {tableTruncated: booleanthrashCount: numberthrashOnly: boolean+ trunkQuarantine: TrunkQuarantineData | null+ trunkQuarantineLoading: boolean+ trunkQuarantineStatus: LoaderStatus+ trunkQuarantineTestsByTeam: Record<string, TrunkQuarantinedTestRow[]>workflowCostAvailable: booleanworkflowFilters: WorkflowFiltersworkflowHealth: WorkflowHealthRow[]@@ -645,12 +451,6 @@ export interface engineeringAnalyticsLogicActions {applyCardFilter: (card: CardFilter) => {card: CardFilter}- applyQuarantineCard: (card: QuarantineCard) => {- card: QuarantineCard- }- closeQuarantineModal: () => {- value: true- }loadCards: () => anyloadCardsFailure: (error: string,@@ -666,21 +466,6 @@ export interface engineeringAnalyticsLogicActions {cards: CardsDatapayload?: any}- loadFlakyTests: () => any- loadFlakyTestsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadFlakyTestsSuccess: (- flakyTests: FlakyTestsData,- payload?: any- ) => {- flakyTests: FlakyTestsData- payload?: any- }loadGithubSources: () => anyloadGithubSourcesFailure: (error: string,@@ -726,6 +511,21 @@ export interface engineeringAnalyticsLogicActions {quarantine: QuarantineDatapayload?: any}+ loadTrunkQuarantine: () => any+ loadTrunkQuarantineFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTrunkQuarantineSuccess: (+ trunkQuarantine: TrunkQuarantineData,+ payload?: any+ ) => {+ trunkQuarantine: TrunkQuarantineData+ payload?: any+ }loadWorkflowHealth: () => anyloadWorkflowHealthFailure: (error: string,@@ -741,18 +541,12 @@ export interface engineeringAnalyticsLogicActions {workflowHealth: WorkflowHealthRow[]payload?: any}- openQuarantineModal: (state: QuarantineModalState) => {- state: QuarantineModalState- }refresh: () => {value: true}resetFilters: () => {value: true}- resetQuarantineFilters: () => {- value: true- }resetWorkflowFilters: () => {value: true}@@ -762,21 +556,6 @@ export interface engineeringAnalyticsLogicActions {setCiStatusFilter: (ciStatus: CIStatusFilter) => {ciStatus: CIStatusFilter}- setFlakyTestWindow: (window: FlakyTestWindow) => {- window: FlakyTestWindow- }- setQuarantineLifecycleFilter: (lifecycle: QuarantineLifecycleFilter) => {- lifecycle: QuarantineLifecycleFilter- }- setQuarantineModeFilter: (mode: QuarantineModeFilter) => {- mode: QuarantineModeFilter- }- setQuarantineOwner: (owner: string | null) => {- owner: string | null- }- setQuarantineSearch: (search: string) => {- search: string- }setReadyOnly: (ready: boolean) => {ready: boolean}@@ -811,26 +590,8 @@ export interface engineeringAnalyticsLogicActions {setWorkflowStatusFilter: (status: WorkflowStatusFilter) => {status: WorkflowStatusFilter}- submitQuarantine: ({ input }: { input: QuarantineSubmitInput }) => {- input: QuarantineSubmitInput- }- submitQuarantineFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- submitQuarantineSuccess: (- quarantineSubmit: QuarantineRequestResultApi,- payload?: {- input: QuarantineSubmitInput- }- ) => {- quarantineSubmit: QuarantineRequestResultApi- payload?: {- input: QuarantineSubmitInput- }+ toggleTrunkQuarantineTeam: (team: string) => {+ team: string}}@@ -881,23 +642,9 @@ export interface engineeringAnalyticsLogicMeta {pullRequestsLoadError: (cardsStatus: LoaderStatus, pullRequestsStatus: LoaderStatus) => booleanworkflowHealthLoadError: (workflowHealthStatus: LoaderStatus) => booleantableTruncated: (pullRequests: PullRequestRow[]) => boolean- quarantineFilters: (- quarantineSearch: string,- quarantineLifecycleFilter: QuarantineLifecycleFilter,- quarantineModeFilter: QuarantineModeFilter,- quarantineOwner: string | null- ) => QuarantineFilters- filteredQuarantineEntries: (- quarantine: QuarantineData | null,- quarantineFilters: QuarantineFilters- ) => QuarantineEntryRow[]- quarantineCounts: (quarantine: QuarantineData | null) => QuarantineCounts- quarantineOwnerOptions: (quarantine: QuarantineData | null) => string[]- activeQuarantineCard: (- quarantineLifecycleFilter: QuarantineLifecycleFilter,- quarantineModeFilter: QuarantineModeFilter- ) => QuarantineCard | null- hasActiveQuarantineFilters: (quarantineFilters: QuarantineFilters) => boolean+ trunkQuarantineTestsByTeam: (+ trunkQuarantine: TrunkQuarantineData | null+ ) => Record<string, TrunkQuarantinedTestRow[]>hasMultipleSources: (githubSources: GitHubSourceApi[]) => booleanactiveSource: (githubSources: GitHubSourceApi[],@@ -948,15 +695,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy// The picker selects a (source, repo) pair in one action, so both land before a single refresh.setScope: (sourceId: string | null, scopeRepo: string | null) => ({ sourceId, scopeRepo }),resetFilters: true,- setQuarantineSearch: (search: string) => ({ search }),- setQuarantineLifecycleFilter: (lifecycle: QuarantineLifecycleFilter) => ({ lifecycle }),- setQuarantineModeFilter: (mode: QuarantineModeFilter) => ({ mode }),- setQuarantineOwner: (owner: string | null) => ({ owner }),- applyQuarantineCard: (card: QuarantineCard) => ({ card }),- resetQuarantineFilters: true,- openQuarantineModal: (state: QuarantineModalState) => ({ state }),- closeQuarantineModal: true,- setFlakyTestWindow: (window: FlakyTestWindow) => ({ window }),+ toggleTrunkQuarantineTeam: (team: string) => ({ team }),refresh: true,}),@@ -1064,52 +803,45 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy},},],- flakyTests: [- null as FlakyTestsData | null,+ trunkQuarantine: [+ null as TrunkQuarantineData | null,{- loadFlakyTests: async (): Promise<FlakyTestsData> => {- const data = await engineeringAnalyticsFlakyTests(projectId(), {- date_from: values.flakyTestWindow,- limit: FLAKY_TEST_LIMIT,+ loadTrunkQuarantine: async (): Promise<TrunkQuarantineData> => {+ const data = await engineeringAnalyticsTrunkQuarantine(projectId(), {source_id: values.sourceId ?? undefined,repo: values.scopeRepo ?? undefined,})return {- rows: data.items.map(- (it): FlakyTestRow => ({+ available: data.available,+ ttlDays: data.ttl_days,+ repository: data.repository,+ trunkUrl: data.trunk_url ?? null,+ teams: data.teams.map(+ (it): TrunkQuarantineTeamRow => ({+ ownerTeam: it.owner_team,+ testCount: it.test_count,+ overdueCount: it.overdue_count,+ oldestAgeDays: it.oldest_age_days,+ })+ ),+ tests: data.tests.map(+ (it): TrunkQuarantinedTestRow => ({runner: it.runner,nodeid: it.nodeid,- selector: it.selector,- classification: it.classification,- sameCommitRecoveryRunCount: it.same_commit_recovery_run_count,- failedRunCount: it.failed_run_count,- failedPrCount: it.failed_pr_count,- masterFailedRunCount: it.master_failed_run_count,- quarantinedFailedRunCount: it.quarantined_failed_run_count,- lastSignalAt: it.last_signal_at,+ file: it.file,+ ownerTeam: it.owner_team,+ status: it.status,+ quarantineSetting: it.quarantine_setting,+ quarantinedAt: it.quarantined_at,+ ageDays: it.age_days,+ overdue: it.overdue,+ trunkUrl: it.trunk_url ?? null,})),- truncated: data.truncated,- limit: data.limit,}},},],- quarantineSubmit: [- null as QuarantineRequestResultApi | null,- {- submitQuarantine: async ({- input,- }: {- input: QuarantineSubmitInput- }): Promise<QuarantineRequestResultApi> => {- return await engineeringAnalyticsQuarantineRequest(- projectId(),- toRequestBody(input, values.quarantine?.repoFullName ?? null)- )- },- },- ],githubSources: [[] as GitHubSourceApi[],{@@ -1192,34 +924,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyloadCardsFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),},],- quarantineSearch: [- DEFAULT_QUARANTINE_FILTERS.search,- {- setQuarantineSearch: (_, { search }) => search,- resetQuarantineFilters: () => DEFAULT_QUARANTINE_FILTERS.search,- },- ],- quarantineLifecycleFilter: [- DEFAULT_QUARANTINE_FILTERS.lifecycle,- {- setQuarantineLifecycleFilter: (_, { lifecycle }) => lifecycle,- resetQuarantineFilters: () => DEFAULT_QUARANTINE_FILTERS.lifecycle,- },- ],- quarantineModeFilter: [- DEFAULT_QUARANTINE_FILTERS.mode,- {- setQuarantineModeFilter: (_, { mode }) => mode,- resetQuarantineFilters: () => DEFAULT_QUARANTINE_FILTERS.mode,- },- ],- quarantineOwner: [- DEFAULT_QUARANTINE_FILTERS.owner,- {- setQuarantineOwner: (_, { owner }) => owner,- resetQuarantineFilters: () => DEFAULT_QUARANTINE_FILTERS.owner,- },- ],// The quarantine endpoint only 400s when there's no GitHub source and no local checkout.quarantineLoadFailed: [false,@@ -1229,27 +933,25 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyloadQuarantineFailure: () => true,},],- // Test-health window; transient like the other lenses (no persisted UI in this phase).- flakyTestWindow: [- DEFAULT_FLAKY_TEST_WINDOW as FlakyTestWindow,- { setFlakyTestWindow: (_, { window }) => window },- ],- // Same tri-state as the other loaders: 'notConnected' (no source) defers to the tab-level- // "connect a source" gate; only a real 'error' surfaces the queue's own banner.- flakyTestsStatus: [- 'ok' as LoaderStatus,+ // Whole-row click toggles a team's slice open (controlled LemonTable expansion, like the+ // workflow runs table); a scope switch loads different teams, so open rows reset with it.+ expandedTrunkQuarantineTeams: [+ [] as string[],{- loadFlakyTests: () => 'ok',- loadFlakyTestsSuccess: () => 'ok',- loadFlakyTestsFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),+ toggleTrunkQuarantineTeam: (state, { team }) =>+ state.includes(team) ? state.filter((open) => open !== team) : [...state, team],+ setSourceId: () => [],+ setScope: () => [],},],- quarantineModal: [- null as QuarantineModalState | null,+ // 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 board's own banner.+ trunkQuarantineStatus: [+ 'ok' as LoaderStatus,{- openQuarantineModal: (_, { state }) => state,- closeQuarantineModal: () => null,- submitQuarantineSuccess: () => null,+ loadTrunkQuarantine: () => 'ok',+ loadTrunkQuarantineSuccess: () => 'ok',+ loadTrunkQuarantineFailure: (_, { errorObject }) => loaderStatusFromError(errorObject),},],pullRequestsStatus: [@@ -1411,48 +1113,10 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy(s) => [s.pullRequests],(pullRequests: PullRequestRow[]): boolean => pullRequests.length >= PR_TABLE_LIMIT,],- quarantineFilters: [- (s) => [s.quarantineSearch, s.quarantineLifecycleFilter, s.quarantineModeFilter, s.quarantineOwner],- (- search: string,- lifecycle: QuarantineLifecycleFilter,- mode: QuarantineModeFilter,- owner: string | null- ): QuarantineFilters => ({ search, lifecycle, mode, owner }),- ],- filteredQuarantineEntries: [- (s) => [s.quarantine, s.quarantineFilters],- (quarantine: QuarantineData | null, filters: QuarantineFilters): QuarantineEntryRow[] =>- quarantine ? filterQuarantineEntries(quarantine.entries, filters) : [],- ],- quarantineCounts: [- (s) => [s.quarantine],- (quarantine: QuarantineData | null): QuarantineCounts => quarantineCountsOf(quarantine?.entries ?? []),- ],- quarantineOwnerOptions: [- (s) => [s.quarantine],- (quarantine: QuarantineData | null): string[] =>- Array.from(new Set((quarantine?.entries ?? []).map((entry) => entry.owner).filter(Boolean))).sort(),- ],- activeQuarantineCard: [- (s) => [s.quarantineLifecycleFilter, s.quarantineModeFilter],- (lifecycle: QuarantineLifecycleFilter, mode: QuarantineModeFilter): QuarantineCard | null => {- if (mode === 'skip' && lifecycle === 'all') {- return 'skipped'- }- if (mode !== 'all') {- return null- }- if (lifecycle === 'active' || lifecycle === 'expiring_soon' || lifecycle === 'past_expiry') {- return lifecycle- }- return null- },- ],- hasActiveQuarantineFilters: [- (s) => [s.quarantineFilters],- (filters: QuarantineFilters): boolean =>- !objectsEqual({ ...filters, search: filters.search.trim() }, DEFAULT_QUARANTINE_FILTERS),+ trunkQuarantineTestsByTeam: [+ (s) => [s.trunkQuarantine],+ (trunkQuarantine: TrunkQuarantineData | null): Record<string, TrunkQuarantinedTestRow[]> =>+ groupBy(trunkQuarantine?.tests ?? [], (test) => test.ownerTeam),],hasMultipleSources: [(s) => [s.githubSources],@@ -1536,9 +1200,8 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyactions.loadPullRequests()actions.loadWorkflowHealth()actions.loadQuarantine()- actions.loadFlakyTests()+ actions.loadTrunkQuarantine()},- setFlakyTestWindow: () => actions.loadFlakyTests(),setSourceId: () => actions.refresh(),setScope: () => actions.refresh(),[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {@@ -1560,35 +1223,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyactions.setReadyOnly(target === 'ready')actions.setThrashOnly(target === 'thrash')},- applyQuarantineCard: ({ card }) => {- // Toggling a card off clears only the lifecycle/mode lens, leaving search and owner intact.- const target = values.activeQuarantineCard === card ? null : card- if (target === 'skipped') {- actions.setQuarantineLifecycleFilter('all')- actions.setQuarantineModeFilter('skip')- } else if (target === null) {- actions.setQuarantineLifecycleFilter('all')- actions.setQuarantineModeFilter('all')- } else {- actions.setQuarantineModeFilter('all')- actions.setQuarantineLifecycleFilter(target)- }- },- submitQuarantineSuccess: ({ quarantineSubmit }) => {- if (!quarantineSubmit) {- return- }- lemonToast.success(- quarantineSubmit.issue_url- ? 'Opened a quarantine PR and a tracking issue. It takes effect once the PR merges.'- : 'Opened a PR. It takes effect once it merges.',- { button: { label: 'View PR', action: () => window.open(quarantineSubmit.pr_url, '_blank') } }- )- actions.loadQuarantine()- },- submitQuarantineFailure: ({ error }) => {- lemonToast.error(quarantineRequestErrorMessage(error))- },})),actionToUrl(() => {diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.tsindex 724aed02bcd0..960bea29d44b 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts@@ -9,7 +9,7 @@ export const VIEW_DESCRIPTIONS: Record<EngineeringAnalyticsView, string> = {hub: 'CI health, pull requests, workflows, and cost for the connected repo.','pull-requests': 'Pull requests and their CI status across connected repos.',workflows: 'Run volume, success rate, and duration per workflow over the selected window.',- 'test-health': 'Flaky tests under quarantine: what is masked, who owns it, and when it expires.',+ 'test-health': 'Quarantine debt by team: which quarantined tests each team owns, and how long they have stood.',teams: 'CI test surfaces rolled up by owning team: flaky signal and failures, with prior-window deltas.',health: 'DORA-style deploy metrics from the GitHub deployments data: frequency, merge to deploy lead time, and failure proxies.',}diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 1643cd801539..b114045e7ffa 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -244,6 +244,9 @@ tools:engineering-analytics-team-merge-trend:operation: engineering_analytics_team_merge_trendenabled: false+ engineering-analytics-trunk-quarantine:+ operation: engineering_analytics_trunk_quarantine+ enabled: falseengineering-analytics-workflow-jobs:operation: engineering_analytics_workflow_jobsenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 68f281a10549..1f17ddb43d7c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -85151,6 +85151,61 @@ export namespace Schemas {summary: unknown;}+ export interface TrunkQuarantineTeamDebt {+ /** Owning team slug, or 'unowned'. */+ owner_team: string;+ /** Tests this team owns that Trunk currently quarantines. */+ test_count: number;+ /** Of those, tests quarantined longer than ttl_days. */+ overdue_count: number;+ /** Age in days of the team's oldest standing quarantine. */+ oldest_age_days: number;+ }++ export interface TrunkQuarantinedTest {+ /** Test runner: 'pytest' or 'jest'. */+ runner: string;+ /** Runner-native test id reconstructed from Trunk's (file, classname, name) key. */+ nodeid: string;+ /** Repo-relative path of the test file, as Trunk reports it. */+ file: string;+ /** Owning team slug from the per-test CI spans' emission-time stamp, or 'unowned' when no in-retention span carries one. */+ owner_team: string;+ /** Trunk's current health verdict on the test, e.g. 'FLAKY' or 'BROKEN'. */+ status: string;+ /** How the quarantine was applied in Trunk, e.g. 'AUTO_QUARANTINE'. */+ quarantine_setting: string;+ /** When Trunk quarantined the test. */+ quarantined_at: string;+ /** Whole days since the quarantine started. */+ age_days: number;+ /** True once age_days exceeds ttl_days: the quarantine has outlived the TTL. */+ overdue: boolean;+ /**+ * The Trunk app's page for this test; null when the connected source has no organization slug or the row carries no test case id.+ * @nullable+ */+ trunk_url: string | null;+ }++ export interface TrunkQuarantineDebt {+ /** Per-team rollup, most indebted first: overdue count, then test count, then oldest age. */+ teams: TrunkQuarantineTeamDebt[];+ /** Every currently quarantined test, oldest first. */+ tests: TrunkQuarantinedTest[];+ /** False when no TrunkIo source has the QuarantinedTests endpoint synced; not an error. */+ available: boolean;+ /** Days a quarantine may stand before it counts as overdue. */+ ttl_days: number;+ /** The 'owner/name' repository the debt was read for; test file paths are relative to it. */+ repository: string;+ /**+ * The Trunk app's flaky-tests page for this repository; null when the connected source has no organization slug.+ * @nullable+ */+ trunk_url: string | null;+ }+export interface UnquarantineQuery {/*** Snapshot identifier to unquarantine@@ -91962,6 +92017,17 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsTrunkQuarantineParams = {+ /**+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.+ */+ repo?: string;+ /**+ * 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 EngineeringAnalyticsWorkflowHealthParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.