Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(engineering_analytics): quarantined-tests management tab (#63293)

Raúl Negrón-Otero051a102d529c
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index a2871074849a..bdf208e0ef0a 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -238,6 +238,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/endpoints/:name': ['EndpointScene', 'endpoint'],
'/engineering-analytics': ['EngineeringAnalytics', 'engineeringAnalytics'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
+ '/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
'/engineering-analytics/pr/:repoOwner/:repoName/:number': [
'EngineeringAnalyticsPullRequest',
'engineeringAnalyticsPullRequest',
@@ -1032,6 +1033,7 @@ export const productUrls = {
},
engineeringAnalytics: (): string => '/engineering-analytics',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
+ engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
`/engineering-analytics/pr/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/${number}`,
errorTracking: (params = {}): string => combineUrl('/error_tracking', params).url,
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 6fd1f74ff230..f51b2000336b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -476,6 +476,7 @@ SPECTACULAR_SETTINGS = {
# path (drf-spectacular generates the x-spec-enum-id from the same tuples).
# --- Model class paths (ChoiceField x-spec-enum-id hashes) ---
"EngineeringAnalyticsPRStateEnum": "products.engineering_analytics.backend.facade.contracts.PRState",
+ "QuarantineModeEnum": "products.engineering_analytics.backend.facade.contracts.QuarantineMode",
"RestrictionLevelEnum": "products.dashboards.backend.models.dashboard.Dashboard.RestrictionLevel",
"OrganizationMembershipLevelEnum": "posthog.models.organization.OrganizationMembership.Level",
"SetupTaskId": "posthog.models.team.setup_tasks.SetupTaskId",
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index f02516f8cc8c..a2a4016fed35 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -26,6 +26,7 @@ from products.engineering_analytics.backend.facade.contracts import (
GitHubSource,
PRLifecycle,
PullRequestList,
+ QuarantineFile,
WorkflowHealthItem,
)
@@ -96,3 +97,16 @@ def list_workflow_health(
def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:
return logic.build_github_sources(team=team, user_access_control=user_access_control)
+
+
+def get_quarantine(
+ *,
+ team: Team,
+ repo: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> QuarantineFile:
+ # Quarantine resolves its source lazily (DEBUG reads the local checkout, an explicit ``repo`` needs
+ # no source) so it stays fail-open where the curated reads above don't — ``source_id`` /
+ # ``user_access_control`` only matter when it falls back to the connected source's most-active repo.
+ return logic.build_quarantine(team=team, repo=repo, source_id=source_id, user_access_control=user_access_control)
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 6b8cb121cf0a..1212076b28c7 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -81,6 +81,32 @@ class PRLifecycleEventKind(StrEnum):
CLOSED = "closed"
+class QuarantineMode(StrEnum):
+ # "run": the test still executes but cannot fail the suite. "skip": not run at all.
+ RUN = "run"
+ SKIP = "skip"
+
+
+class QuarantineLifecycle(StrEnum):
+ """Where an entry sits relative to its expiry: ``active`` (more than 7 days
+ left), ``expiring_soon`` (7 days or fewer left), ``in_grace`` (expired up to
+ 7 days ago — inert, but its removal is not yet mandatory), ``overdue``
+ (expired beyond the 7-day grace period).
+ """
+
+ ACTIVE = "active"
+ EXPIRING_SOON = "expiring_soon"
+ IN_GRACE = "in_grace"
+ OVERDUE = "overdue"
+
+
+class QuarantineSelectorKind(StrEnum):
+ PRODUCT = "product"
+ FILE = "file"
+ DIRECTORY = "directory"
+ TEST = "test"
+
+
@dataclass(frozen=True)
class GitHubSource:
"""A connected GitHub warehouse source the team can analyze. ``id`` is what a
@@ -239,6 +265,44 @@ class WorkflowHealthDay:
failures: int
+@dataclass(frozen=True)
+class QuarantineEntry:
+ """One selector from a repo's checked-in ``.test_quarantine.json``, enriched
+ with read-side expiry classification."""
+
+ id: str
+ runner: str
+ reason: str
+ owner: str
+ issue: str
+ added: date
+ expires: date
+ mode: QuarantineMode
+ lifecycle: QuarantineLifecycle
+ # Negative once past expiry.
+ days_until_expiry: int
+ selector_kind: QuarantineSelectorKind
+
+
+@dataclass(frozen=True)
+class QuarantineFile:
+ """A repo's parsed quarantine file. ``available`` is False when no file
+ exists — that is not an error. Parsing is fail-open to match the enforcement
+ readers: malformed entries land in ``parse_errors`` while well-formed ones
+ are kept, and unknown entry fields only warn.
+ """
+
+ available: bool
+ # Most urgent first (overdue, in_grace, expiring_soon, active), then by expiry.
+ entries: list[QuarantineEntry]
+ parse_errors: list[str]
+ parse_warnings: list[str]
+ # None in local-dev mode, where the server's own checkout is read.
+ repo: RepoRef | None
+ source_url: str
+ generated_at: datetime
+
+
@dataclass(frozen=True)
class WorkflowHealthItem:
"""Per-workflow CI health over a window. Rates and percentiles are over
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index c9bf5d84d479..aa9eca8110b5 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -20,6 +20,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PullRequestList,
WorkflowHealthItem,
)
+from products.engineering_analytics.backend.logic.quarantine import build_quarantine as build_quarantine
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries.ci_cards import query_ci_cards
from products.engineering_analytics.backend.logic.queries.pr_lifecycle import query_pr_lifecycle
diff --git a/products/engineering_analytics/backend/logic/quarantine.py b/products/engineering_analytics/backend/logic/quarantine.py
new file mode 100644
index 000000000000..4f475572e8d1
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/quarantine.py
@@ -0,0 +1,312 @@
+"""Read side of a repo's checked-in ``.test_quarantine.json``.
+
+The v1 schema contract lives with the hogli quarantine tooling
+(``tools/hogli-commands/hogli_commands/quarantine/core.py``); product isolation
+forbids importing tools code, so the minimal read-side parsing is reimplemented
+here. Reading is fail-open to match the enforcement readers: malformed entries
+are dropped into ``parse_errors`` and the rest kept; unknown entry fields only
+warn; entries for runners without an enforcement adapter are kept (the UI shows
+the runner).
+
+Acquisition order: the server's own checkout in DEBUG (so the tab is live in
+local dev), then the caller-supplied ``repo``, then the connected GitHub
+source's most active repo over the last 30 days (``source_id`` selects which
+connected source; ``user_access_control`` filters out sources the caller can't
+read). Staying fail-open, a team with no connected source returns
+``available=false`` rather than the 4xx the curated read endpoints raise.
+"""
+
+import re
+import json
+from datetime import UTC, date, datetime, timedelta
+from pathlib import Path, PurePosixPath
+from typing import TYPE_CHECKING
+
+from django.conf import settings
+from django.core.cache import cache
+
+import requests
+
+from posthog.hogql import ast
+
+from posthog.models.team import Team
+
+from products.engineering_analytics.backend.facade.contracts import (
+ GitHubSourceNotConnectedError,
+ QuarantineEntry,
+ QuarantineFile,
+ QuarantineLifecycle,
+ QuarantineMode,
+ QuarantineSelectorKind,
+ RepoRef,
+)
+from products.engineering_analytics.backend.logic.queries import _curated
+
+if TYPE_CHECKING:
+ from posthog.rbac.user_access_control import UserAccessControl
+
+QUARANTINE_FILENAME = ".test_quarantine.json"
+
+_SCHEMA_VERSION = 1
+_DEFAULT_RUNNER = "pytest"
+# Matches DEFAULT_GRACE_DAYS in the quarantine contract: an expired entry stays
+# inert for this long before `quarantine check` makes its removal mandatory.
+_GRACE_DAYS = 7
+_EXPIRING_SOON_DAYS = 7
+_ENTRY_FIELDS = ("id", "runner", "reason", "owner", "issue", "added", "expires", "mode")
+
+# SSRF hardening: both halves of `owner/name` must look like a GitHub slug
+# before they are interpolated into the fetch URL.
+_REPO_PART_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$")
+_FETCH_TIMEOUT_SECONDS = 3
+_CACHE_TTL_SECONDS = 60
+# A real quarantine file is tens of KB; this is generous headroom while bounding how
+# much a hostile public repo can make us buffer, cache, and parse from one request.
+_MAX_QUARANTINE_BYTES = 5 * 1024 * 1024
+
+# Most urgent first; ties broken by soonest expiry, then id.
+_LIFECYCLE_URGENCY = {
+ QuarantineLifecycle.OVERDUE: 0,
+ QuarantineLifecycle.IN_GRACE: 1,
+ QuarantineLifecycle.EXPIRING_SOON: 2,
+ QuarantineLifecycle.ACTIVE: 3,
+}
+
+_REPO_SELECT = """
+ SELECT repo_owner, repo_name
+ FROM __RUNS_SOURCE__ AS r
+ WHERE run_started_at >= {date_from}
+ GROUP BY repo_owner, repo_name
+ ORDER BY count() DESC
+ LIMIT 1
+"""
+
+
+def build_quarantine(
+ *,
+ team: Team,
+ repo: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> QuarantineFile:
+ generated_at = datetime.now(UTC)
+ today = generated_at.date()
+
+ local_text = _read_local_text()
+ if local_text is not None:
+ entries, errors, warnings = parse_quarantine_text(local_text, today)
+ return QuarantineFile(
+ available=True,
+ entries=entries,
+ parse_errors=errors,
+ parse_warnings=warnings,
+ repo=None,
+ source_url="",
+ generated_at=generated_at,
+ )
+
+ if repo is not None:
+ owner, _, name = repo.partition("/")
+ else:
+ try:
+ resolved = _most_active_repo(team, source_id=source_id, user_access_control=user_access_control)
+ except GitHubSourceNotConnectedError as exc:
+ # Fail open: no connected source isn't an error here, just nothing to read.
+ return _unavailable(generated_at, error=f"{exc} — pass ?repo=owner/name to read a specific repository")
+ if resolved is None:
+ return _unavailable(
+ generated_at,
+ error="could not determine a repository: no workflow runs in the last 30 days — pass ?repo=owner/name",
+ )
+ owner, name = resolved
+ if not (_REPO_PART_RE.fullmatch(owner) and _REPO_PART_RE.fullmatch(name)):
+ slug = repo if repo is not None else f"{owner}/{name}"
+ return _unavailable(generated_at, error=f"invalid repo {slug!r}: expected 'owner/name' GitHub slugs")
+
+ repo_ref = RepoRef(provider="github", owner=owner, name=name)
+ text, fetch_error = _fetch_quarantine_text(owner, name)
+ if text is None:
+ return _unavailable(generated_at, repo=repo_ref, error=fetch_error)
+
+ entries, errors, warnings = parse_quarantine_text(text, today)
+ return QuarantineFile(
+ available=True,
+ entries=entries,
+ parse_errors=errors,
+ parse_warnings=warnings,
+ repo=repo_ref,
+ source_url=f"https://github.com/{owner}/{name}/blob/HEAD/{QUARANTINE_FILENAME}",
+ generated_at=generated_at,
+ )
+
+
+def parse_quarantine_text(text: str, today: date) -> tuple[list[QuarantineEntry], list[str], list[str]]:
+ """Parse v1 quarantine JSON into sorted entries plus parse errors/warnings."""
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError as exc:
+ return [], [f"invalid JSON: {exc}"], []
+ if not isinstance(data, dict):
+ return [], ["top level must be an object"], []
+ if data.get("version") != _SCHEMA_VERSION:
+ return [], [f"unsupported version {data.get('version')!r} (expected {_SCHEMA_VERSION})"], []
+ raw_entries = data.get("entries")
+ if not isinstance(raw_entries, list):
+ return [], ["'entries' must be a list"], []
+
+ entries: list[QuarantineEntry] = []
+ errors: list[str] = []
+ warnings: list[str] = []
+ for index, raw in enumerate(raw_entries):
+ entry = _parse_entry(raw, index, today, errors, warnings)
+ if entry is not None:
+ entries.append(entry)
+ entries.sort(key=lambda entry: (_LIFECYCLE_URGENCY[entry.lifecycle], entry.expires, entry.id))
+ return entries, errors, warnings
+
+
+def _parse_entry(
+ raw: object, index: int, today: date, errors: list[str], warnings: list[str]
+) -> QuarantineEntry | None:
+ label = f"entries[{index}]"
+ if not isinstance(raw, dict):
+ errors.append(f"{label}: must be an object")
+ return None
+ raw_id = raw.get("id")
+ if not (isinstance(raw_id, str) and raw_id):
+ errors.append(f"{label}: 'id' must be a non-empty string")
+ return None
+ label = f"entries[{index}] ({raw_id})"
+
+ for key in ("reason", "owner", "issue", "runner", "mode"):
+ if key in raw and not isinstance(raw[key], str):
+ errors.append(f"{label}: '{key}' must be a string")
+ return None
+ mode = raw.get("mode", QuarantineMode.RUN.value)
+ if mode not in (QuarantineMode.RUN.value, QuarantineMode.SKIP.value):
+ errors.append(f"{label}: 'mode' must be one of ('run', 'skip'), got {mode!r}")
+ return None
+
+ dates: dict[str, date] = {}
+ for key in ("added", "expires"):
+ try:
+ dates[key] = date.fromisoformat(raw.get(key, ""))
+ except (TypeError, ValueError):
+ errors.append(f"{label}: '{key}' must be an ISO date (YYYY-MM-DD)")
+ return None
+
+ unknown = sorted(key for key in raw if key not in _ENTRY_FIELDS)
+ if unknown:
+ warnings.append(f"{label}: unknown fields {unknown} (kept for forward compatibility)")
+
+ days_until_expiry = (dates["expires"] - today).days
+ return QuarantineEntry(
+ id=raw_id,
+ runner=raw.get("runner", _DEFAULT_RUNNER),
+ reason=raw.get("reason", ""),
+ owner=raw.get("owner", ""),
+ issue=raw.get("issue", ""),
+ added=dates["added"],
+ expires=dates["expires"],
+ mode=QuarantineMode(mode),
+ lifecycle=_lifecycle_for(days_until_expiry),
+ days_until_expiry=days_until_expiry,
+ selector_kind=_selector_kind(raw_id),
+ )
+
+
+def _lifecycle_for(days_until_expiry: int) -> QuarantineLifecycle:
+ if days_until_expiry > _EXPIRING_SOON_DAYS:
+ return QuarantineLifecycle.ACTIVE
+ if days_until_expiry >= 0:
+ return QuarantineLifecycle.EXPIRING_SOON
+ if days_until_expiry >= -_GRACE_DAYS:
+ return QuarantineLifecycle.IN_GRACE
+ return QuarantineLifecycle.OVERDUE
+
+
+def _selector_kind(selector: str) -> QuarantineSelectorKind:
+ if selector.startswith("product:"):
+ return QuarantineSelectorKind.PRODUCT
+ if "::" in selector:
+ return QuarantineSelectorKind.TEST
+ if PurePosixPath(selector).suffix:
+ return QuarantineSelectorKind.FILE
+ return QuarantineSelectorKind.DIRECTORY
+
+
+def _read_local_text() -> str | None:
+ if not settings.DEBUG:
+ return None
+ path = Path(settings.BASE_DIR) / QUARANTINE_FILENAME
+ if not path.is_file():
+ return None
+ return path.read_text()
+
+
+def _most_active_repo(
+ team: Team, *, source_id: str | None = None, user_access_control: "UserAccessControl | None" = None
+) -> tuple[str, str] | None:
+ # Raises GitHubSourceNotConnectedError when the team has no source (caught upstream and turned
+ # into available=false) or ValueError for a bad source_id (propagated to a 4xx by the view).
+ curated = _curated.CuratedGitHubSource.for_team(team, source_id=source_id, user_access_control=user_access_control)
+ sql = _REPO_SELECT.replace("__RUNS_SOURCE__", curated.run_source())
+ response = curated.run(
+ sql,
+ query_type="engineering_analytics.quarantine_repo",
+ placeholders={"date_from": ast.Constant(value=datetime.now(UTC) - timedelta(days=30))},
+ )
+ if not response.results:
+ return None
+ owner, name = response.results[0]
+ return str(owner), str(name)
+
+
+def _fetch_quarantine_text(owner: str, name: str) -> tuple[str | None, str | None]:
+ """Returns ``(text, error)``: the file text on 200, ``(None, None)`` on 404
+ (no quarantine file is not an error), ``(None, message)`` on any other
+ failure — including a body over ``_MAX_QUARANTINE_BYTES``."""
+ cache_key = f"engineering_analytics_quarantine:{owner}/{name}"
+ cached = cache.get(cache_key)
+ if isinstance(cached, str):
+ return cached, None
+
+ url = f"https://raw.githubusercontent.com/{owner}/{name}/HEAD/{QUARANTINE_FILENAME}"
+ too_large = f"{QUARANTINE_FILENAME} for {owner}/{name} exceeds the {_MAX_QUARANTINE_BYTES}-byte limit"
+ try:
+ with requests.get(url, timeout=_FETCH_TIMEOUT_SECONDS, stream=True) as response:
+ if response.status_code == 404:
+ return None, None
+ if response.status_code != 200:
+ return None, f"could not fetch {QUARANTINE_FILENAME} for {owner}/{name}: HTTP {response.status_code}"
+ # Reject an advertised oversize body before reading it. Content-Length can be
+ # absent or wrong, so the streamed read below is the actual ceiling.
+ declared = response.headers.get("Content-Length")
+ if declared is not None and declared.isdigit() and int(declared) > _MAX_QUARANTINE_BYTES:
+ return None, too_large
+ body = bytearray()
+ for chunk in response.iter_content(chunk_size=8192):
+ body.extend(chunk)
+ if len(body) > _MAX_QUARANTINE_BYTES:
+ return None, too_large
+ except requests.RequestException as err:
+ return None, f"could not fetch {QUARANTINE_FILENAME} for {owner}/{name}: {err}"
+
+ try:
+ text = body.decode("utf-8")
+ except UnicodeDecodeError:
+ return None, f"could not fetch {QUARANTINE_FILENAME} for {owner}/{name}: not valid UTF-8"
+ cache.set(cache_key, text, _CACHE_TTL_SECONDS)
+ return text, None
+
+
+def _unavailable(generated_at: datetime, *, repo: RepoRef | None = None, error: str | None = None) -> QuarantineFile:
+ return QuarantineFile(
+ available=False,
+ entries=[],
+ parse_errors=[error] if error else [],
+ parse_warnings=[],
+ repo=repo,
+ source_url="",
+ generated_at=generated_at,
+ )
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 8d84d13639a6..3b51929839c1 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -19,6 +19,8 @@ from products.engineering_analytics.backend.facade.contracts import (
PullRequest,
PullRequestList,
PullRequestListItem,
+ QuarantineEntry,
+ QuarantineFile,
RepoRef,
WorkflowHealthDay,
WorkflowHealthItem,
@@ -178,6 +180,64 @@ class CICardSummarySerializer(DataclassSerializer):
}
+class QuarantineEntrySerializer(DataclassSerializer):
+ class Meta:
+ dataclass = QuarantineEntry
+ extra_kwargs = {
+ "id": {
+ "help_text": "Test selector: an exact test id, a file, a directory, a class prefix, or "
+ "'product:<dashed-name>'.",
+ },
+ "runner": {"help_text": "Test runner the selector targets, e.g. 'pytest' or 'jest'."},
+ "reason": {"help_text": "Why the test was quarantined."},
+ "owner": {"help_text": "GitHub team or user handle responsible for the fix."},
+ "issue": {"help_text": "Tracking issue URL, or empty when none was filed."},
+ "added": {"help_text": "ISO date the entry was added."},
+ "expires": {"help_text": "ISO date the quarantine expires; past it the test blocks CI normally again."},
+ "mode": {
+ "help_text": "'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all).",
+ },
+ "lifecycle": {
+ "help_text": "Expiry classification: 'active' (>7 days left), 'expiring_soon' (0-7 days left), "
+ "'in_grace' (expired up to 7 days ago), 'overdue' (expired beyond the grace period).",
+ },
+ "days_until_expiry": {"help_text": "Days until the entry expires; negative once past expiry."},
+ "selector_kind": {
+ "help_text": "What the selector covers: 'test' (contains '::'), 'file', 'directory', or 'product'.",
+ },
+ }
+
+
+class QuarantineFileSerializer(DataclassSerializer):
+ entries = QuarantineEntrySerializer(
+ many=True,
+ help_text="Quarantined selectors, most urgent first (overdue, in_grace, expiring_soon, active), "
+ "then by soonest expiry.",
+ )
+ repo = RepoRefSerializer(
+ help_text="Repository the file was read from. Null in local-dev mode, where the server's own checkout is read.",
+ allow_null=True,
+ )
+
+ class Meta:
+ dataclass = QuarantineFile
+ extra_kwargs = {
+ "available": {
+ "help_text": "False when the repository has no quarantine file (not an error) or it could not "
+ "be fetched.",
+ },
+ "parse_errors": {
+ "help_text": "Contract violations (malformed JSON, bad entries) or fetch failures. Malformed "
+ "entries are dropped; well-formed ones are kept.",
+ },
+ "parse_warnings": {"help_text": "Forward-compatibility notices, e.g. unknown entry fields."},
+ "source_url": {
+ "help_text": "GitHub blob URL of the quarantine file, or empty when read locally or unavailable.",
+ },
+ "generated_at": {"help_text": "When this snapshot was computed (UTC); expiry math uses this clock."},
+ }
+
+
class WorkflowHealthDaySerializer(DataclassSerializer):
class Meta:
dataclass = WorkflowHealthDay
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 461f911537a5..12b540997324 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -8,6 +8,7 @@ contract. These same endpoints back both the MCP tools and the UI:
- ``pull_requests`` — PR list with head-SHA CI rollup.
- ``workflow_health`` — per-workflow CI health over a window.
- ``pr_lifecycle`` — a single PR's header plus its ordered CI timeline.
+- ``quarantine`` — the repo's checked-in flaky-test quarantine file.
"""
from drf_spectacular.types import OpenApiTypes
@@ -26,6 +27,7 @@ from products.engineering_analytics.backend.presentation.serializers import (
GitHubSourceSerializer,
PRLifecycleSerializer,
PullRequestListSerializer,
+ QuarantineFileSerializer,
WorkflowHealthItemSerializer,
)
@@ -84,7 +86,14 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"""PR and CI lifecycle analytics over the GitHub warehouse data."""
scope_object = "engineering_analytics"
- scope_object_read_actions = ["sources", "ci_cards", "pull_requests", "workflow_health", "pr_lifecycle"]
+ scope_object_read_actions = [
+ "sources",
+ "ci_cards",
+ "pull_requests",
+ "workflow_health",
+ "pr_lifecycle",
+ "quarantine",
+ ]
scope_object_write_actions: list[str] = []
def handle_exception(self, exc: Exception) -> Response:
@@ -238,3 +247,41 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
if result is None:
return Response({"detail": "Pull request not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(PRLifecycleSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_quarantine",
+ summary="Flaky-test quarantine file",
+ parameters=[
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional 'owner/name' repository to read the quarantine file from. Defaults to the "
+ "connected GitHub source's most active repo over the last 30 days.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: QuarantineFileSerializer,
+ 400: OpenApiResponse(description="Invalid repo or source_id."),
+ },
+ description=(
+ "The repository's checked-in .test_quarantine.json: flaky tests temporarily quarantined with a hard "
+ "expiry, classified by urgency (overdue, in grace, expiring soon, active). `available` is false when "
+ "the repo has no quarantine file — that is not an error. Parsing is fail-open: malformed entries are "
+ "reported in parse_errors while well-formed ones are kept."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def quarantine(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_quarantine(
+ team=self.team,
+ repo=request.query_params.get("repo") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
+ return Response(QuarantineFileSerializer(instance=result).data)
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 6f298340899e..c15d9b9da1f9 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -193,7 +193,7 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "the maximum is 366" in response.json()["detail"]
- @parameterized.expand(["sources", "ci_cards", "pull_requests", "workflow_health", "pr_lifecycle"])
+ @parameterized.expand(["sources", "ci_cards", "pull_requests", "workflow_health", "pr_lifecycle", "quarantine"])
def test_requires_authentication(self, action: str) -> None:
self.client.logout()
response = self.client.get(self._url(action))
diff --git a/products/engineering_analytics/backend/tests/test_quarantine.py b/products/engineering_analytics/backend/tests/test_quarantine.py
new file mode 100644
index 000000000000..8291ae22b5e6
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_quarantine.py
@@ -0,0 +1,346 @@
+import json
+import tempfile
+from datetime import UTC, date, datetime
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, BaseTest
+from unittest import TestCase, mock
+
+from django.core.cache import cache
+from django.test import override_settings
+
+import requests
+from parameterized import parameterized
+from rest_framework import status
+
+from products.engineering_analytics.backend.facade import contracts
+from products.engineering_analytics.backend.logic.quarantine import (
+ QUARANTINE_FILENAME,
+ _lifecycle_for,
+ _selector_kind,
+ build_quarantine,
+ parse_quarantine_text,
+)
+
+_TODAY = date(2026, 6, 12)
+_REQUESTS_GET = "products.engineering_analytics.backend.logic.quarantine.requests.get"
+_MAX_BYTES = "products.engineering_analytics.backend.logic.quarantine._MAX_QUARANTINE_BYTES"
+_FOR_TEAM = "products.engineering_analytics.backend.logic.queries._curated.CuratedGitHubSource.for_team"
+_VIEWS = "products.engineering_analytics.backend.presentation.views.api"
+
+
+def _curated_source(results: list[tuple[str, str]]) -> mock.Mock:
+ """A stand-in CuratedGitHubSource: run_source() feeds the repo SQL, run() returns the rows."""
+ source = mock.Mock()
+ source.run_source.return_value = "(runs)"
+ source.run.return_value = SimpleNamespace(results=results)
+ return source
+
+
+def _entry(**overrides: Any) -> dict[str, Any]:
+ raw: dict[str, Any] = {
+ "id": "posthog/api/test/test_foo.py::TestFoo::test_bar",
+ "runner": "pytest",
+ "reason": "flaky",
+ "owner": "@PostHog/team-foo",
+ "issue": "https://github.com/PostHog/posthog/issues/1",
+ "added": "2026-06-01",
+ "expires": "2026-06-20",
+ "mode": "run",
+ }
+ raw.update(overrides)
+ return {key: value for key, value in raw.items() if value is not None}
+
+
+def _text(*entries: dict[str, Any]) -> str:
+ return json.dumps({"version": 1, "entries": list(entries)})
+
+
+def _response(status_code: int = 200, text: str = "", headers: dict[str, str] | None = None) -> mock.MagicMock:
+ """A streamed requests response: usable as a context manager, body delivered via iter_content."""
+ body = text.encode("utf-8")
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.headers = headers or {}
+ response.iter_content.side_effect = lambda *args, **kwargs: iter([body])
+ response.__enter__.return_value = response
+ response.__exit__.return_value = False
+ return response
+
+
+class TestQuarantineParse(TestCase):
+ def test_parses_valid_file_and_applies_defaults(self) -> None:
+ full = _entry()
+ minimal = {"id": "posthog/api/test", "added": "2026-06-01", "expires": "2026-06-09"}
+ entries, errors, warnings = parse_quarantine_text(_text(full, minimal), _TODAY)
+
+ assert errors == [] and warnings == []
+ by_id = {entry.id: entry for entry in entries}
+ assert by_id[full["id"]].mode == contracts.QuarantineMode.RUN
+ assert by_id[full["id"]].issue == "https://github.com/PostHog/posthog/issues/1"
+ assert by_id[full["id"]].days_until_expiry == 8
+ defaulted = by_id["posthog/api/test"]
+ assert (defaulted.runner, defaulted.reason, defaulted.owner, defaulted.issue) == ("pytest", "", "", "")
+ assert defaulted.mode == contracts.QuarantineMode.RUN
+ assert defaulted.days_until_expiry == -3
+
+ @parameterized.expand(
+ [
+ ("malformed_json", "{not json", "invalid JSON"),
+ ("not_an_object", "[]", "top level must be an object"),
+ ("wrong_version", '{"version": 2, "entries": []}', "unsupported version"),
+ ("entries_not_a_list", '{"version": 1, "entries": {}}', "'entries' must be a list"),
+ ]
+ )
+ def test_top_level_problems_yield_one_error_and_no_entries(self, _name: str, text: str, message: str) -> None:
+ entries, errors, warnings = parse_quarantine_text(text, _TODAY)
+
+ assert entries == [] and warnings == []
+ assert len(errors) == 1 and message in errors[0]
+
+ @parameterized.expand(
+ [
+ ("not_an_object", "just-a-string", "must be an object"),
+ ("missing_id", _entry(id=None), "'id' must be a non-empty string"),
+ ("bad_mode", _entry(mode="pause"), "'mode' must be one of"),
+ ("bad_date", _entry(expires="next week"), "must be an ISO date"),
+ ("non_string_reason", _entry(reason=42), "'reason' must be a string"),
+ ]
+ )
+ def test_malformed_entry_dropped_while_good_ones_kept(self, _name: str, bad: Any, message: str) -> None:
+ good = _entry(id="posthog/api/test/test_ok.py")
+ entries, errors, warnings = parse_quarantine_text(_text(bad, good), _TODAY)
+
+ assert [entry.id for entry in entries] == ["posthog/api/test/test_ok.py"]
+ assert len(errors) == 1 and message in errors[0]
+ assert warnings == []
+
+ def test_unknown_entry_fields_warn_and_entry_is_kept(self) -> None:
+ entries, errors, warnings = parse_quarantine_text(_text(_entry(snooze_until="2027-01-01")), _TODAY)
+
+ assert len(entries) == 1
+ assert errors == []
+ assert len(warnings) == 1 and "snooze_until" in warnings[0]
+
+ @parameterized.expand(
+ [
+ (8, contracts.QuarantineLifecycle.ACTIVE),
+ (7, contracts.QuarantineLifecycle.EXPIRING_SOON),
+ (0, contracts.QuarantineLifecycle.EXPIRING_SOON),
+ (-1, contracts.QuarantineLifecycle.IN_GRACE),
+ (-7, contracts.QuarantineLifecycle.IN_GRACE),
+ (-8, contracts.QuarantineLifecycle.OVERDUE),
+ ]
+ )
+ def test_lifecycle_boundaries(self, days: int, expected: contracts.QuarantineLifecycle) -> None:
+ assert _lifecycle_for(days) == expected
+
+ @parameterized.expand(
+ [
+ ("product:batch-exports", contracts.QuarantineSelectorKind.PRODUCT),
+ ("posthog/api/test/test_foo.py::TestFoo::test_bar", contracts.QuarantineSelectorKind.TEST),
+ ("posthog/api/test/test_foo.py::TestFoo", contracts.QuarantineSelectorKind.TEST),
+ ("posthog/api/test/test_foo.py", contracts.QuarantineSelectorKind.FILE),
+ ("frontend/src/scenes/dashboard/dashboardLogic.test.ts", contracts.QuarantineSelectorKind.FILE),
+ ("posthog/api/test", contracts.QuarantineSelectorKind.DIRECTORY),
+ ]
+ )
+ def test_selector_kind(self, selector: str, expected: contracts.QuarantineSelectorKind) -> None:
+ assert _selector_kind(selector) == expected
+
+ def test_sorts_most_urgent_first_then_expiry_then_id(self) -> None:
+ text = _text(
+ _entry(id="zz", added="2026-06-01", expires="2026-07-02"),
+ _entry(id="aa", added="2026-06-01", expires="2026-07-02"),
+ _entry(id="grace", added="2026-05-12", expires="2026-06-09"),
+ _entry(id="active-late", added="2026-06-08", expires="2026-07-07"),
+ _entry(id="soon", added="2026-05-20", expires="2026-06-15"),
+ _entry(id="overdue", added="2026-05-05", expires="2026-06-02"),
+ )
+ entries, errors, _warnings = parse_quarantine_text(text, _TODAY)
+
+ assert errors == []
+ assert [entry.id for entry in entries] == ["overdue", "grace", "soon", "aa", "zz", "active-late"]
+
+
+class TestQuarantineBuild(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ @freeze_time("2026-06-12")
+ def test_fetches_and_parses_remote_file(self) -> None:
+ with mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))) as get:
+ result = build_quarantine(team=self.team, repo="PostHog/posthog")
+
+ assert result.available is True
+ assert result.repo == contracts.RepoRef(provider="github", owner="PostHog", name="posthog")
+ assert result.source_url == "https://github.com/PostHog/posthog/blob/HEAD/.test_quarantine.json"
+ assert len(result.entries) == 1
+ assert result.entries[0].days_until_expiry == 8
+ assert result.entries[0].lifecycle == contracts.QuarantineLifecycle.ACTIVE
+ get.assert_called_once_with(
+ "https://raw.githubusercontent.com/PostHog/posthog/HEAD/.test_quarantine.json", timeout=3, stream=True
+ )
+
+ def test_404_means_unavailable_without_errors(self) -> None:
+ with mock.patch(_REQUESTS_GET, return_value=_response(404)):
+ result = build_quarantine(team=self.team, repo="PostHog/posthog")
+
+ assert result.available is False
+ assert result.entries == [] and result.parse_errors == []
+ assert result.repo == contracts.RepoRef(provider="github", owner="PostHog", name="posthog")
+ assert result.source_url == ""
+
+ @parameterized.expand(
+ [
+ ("timeout", requests.Timeout("boom")),
+ ("server_error", 500),
+ ]
+ )
+ def test_fetch_failure_reported_as_single_parse_error(self, _name: str, failure: Exception | int) -> None:
+ kwargs: dict[str, Any] = (
+ {"side_effect": failure} if isinstance(failure, Exception) else {"return_value": _response(failure)}
+ )
+ with mock.patch(_REQUESTS_GET, **kwargs):
+ result = build_quarantine(team=self.team, repo="PostHog/posthog")
+
+ assert result.available is False
+ assert len(result.parse_errors) == 1 and "could not fetch" in result.parse_errors[0]
+
+ @parameterized.expand(["PostHog", "Post Hog/repo", "PostHog/po$thog", "-bad/repo", "a/b/c", "PostHog/"])
+ def test_invalid_repo_rejected_before_fetch(self, repo: str) -> None:
+ with mock.patch(_REQUESTS_GET) as get:
+ result = build_quarantine(team=self.team, repo=repo)
+
+ assert result.available is False
+ assert len(result.parse_errors) == 1 and "invalid repo" in result.parse_errors[0]
+ get.assert_not_called()
+
+ def test_caches_fetched_text(self) -> None:
+ with mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))) as get:
+ build_quarantine(team=self.team, repo="PostHog/posthog")
+ result = build_quarantine(team=self.team, repo="PostHog/posthog")
+
+ assert get.call_count == 1
+ assert result.available is True and len(result.entries) == 1
+
+ def test_oversized_streamed_body_rejected_and_not_cached(self) -> None:
+ # No Content-Length header: the cap must hold on the streamed bytes, and a
+ # hostile oversize response must not poison the cache for the next caller.
+ with mock.patch(_MAX_BYTES, 16), mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))) as get:
+ first = build_quarantine(team=self.team, repo="PostHog/posthog")
+ second = build_quarantine(team=self.team, repo="PostHog/posthog")
+
+ assert first.available is False
+ assert len(first.parse_errors) == 1 and "exceeds" in first.parse_errors[0]
+ assert second.available is False
+ assert get.call_count == 2
+
+ def test_oversized_content_length_rejected_before_reading_body(self) -> None:
+ response = _response(200, _text(_entry()), headers={"Content-Length": str(10 * 1024 * 1024)})
+ with mock.patch(_REQUESTS_GET, return_value=response):
+ result = build_quarantine(team=self.team, repo="PostHog/posthog")
+
+ assert result.available is False and "exceeds" in result.parse_errors[0]
+ response.iter_content.assert_not_called()
+
+ def test_resolves_most_active_repo_from_workflow_runs(self) -> None:
+ source = _curated_source([("PostHog", "posthog.com")])
+ with (
+ mock.patch(_FOR_TEAM, return_value=source),
+ mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))),
+ ):
+ result = build_quarantine(team=self.team)
+
+ assert result.repo == contracts.RepoRef(provider="github", owner="PostHog", name="posthog.com")
+ assert source.run.call_args.kwargs["query_type"] == "engineering_analytics.quarantine_repo"
+
+ def test_no_recent_runs_means_unavailable(self) -> None:
+ with (
+ mock.patch(_FOR_TEAM, return_value=_curated_source([])),
+ mock.patch(_REQUESTS_GET) as get,
+ ):
+ result = build_quarantine(team=self.team)
+
+ assert result.available is False
+ assert len(result.parse_errors) == 1 and "could not determine a repository" in result.parse_errors[0]
+ get.assert_not_called()
+
+ def test_no_connected_source_is_fail_open(self) -> None:
+ with (
+ mock.patch(_FOR_TEAM, side_effect=contracts.GitHubSourceNotConnectedError("no GitHub source connected")),
+ mock.patch(_REQUESTS_GET) as get,
+ ):
+ result = build_quarantine(team=self.team)
+
+ assert result.available is False
+ assert "pass ?repo=owner/name" in result.parse_errors[0]
+ get.assert_not_called()
+
+ def test_debug_reads_local_checkout(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ (Path(tmp) / QUARANTINE_FILENAME).write_text(_text(_entry()))
+ with override_settings(DEBUG=True, BASE_DIR=tmp), mock.patch(_REQUESTS_GET) as get:
+ result = build_quarantine(team=self.team)
+
+ assert result.available is True
+ assert result.repo is None and result.source_url == ""
+ assert len(result.entries) == 1
+ get.assert_not_called()
+
+
+class TestQuarantineAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ def _url(self) -> str:
+ return f"/api/projects/{self.team.id}/engineering_analytics/quarantine/"
+
+ @freeze_time("2026-06-12")
+ def test_quarantine_serializes(self) -> None:
+ with mock.patch(_REQUESTS_GET, return_value=_response(200, _text(_entry()))):
+ response = self.client.get(self._url(), {"repo": "PostHog/posthog"})
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["available"] is True
+ assert body["repo"] == {"provider": "github", "owner": "PostHog", "name": "posthog"}
+ assert body["source_url"] == "https://github.com/PostHog/posthog/blob/HEAD/.test_quarantine.json"
+ entry = body["entries"][0]
+ assert entry["id"] == "posthog/api/test/test_foo.py::TestFoo::test_bar"
+ assert entry["mode"] == "run"
+ assert entry["lifecycle"] == "active"
+ assert entry["selector_kind"] == "test"
+ assert entry["days_until_expiry"] == 8
+ assert entry["expires"] == "2026-06-20"
+
+ def test_quarantine_available_false_when_repo_has_no_file(self) -> None:
+ with mock.patch(_REQUESTS_GET, return_value=_response(404)):
+ response = self.client.get(self._url(), {"repo": "PostHog/no-quarantine"})
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["available"] is False
+ assert body["entries"] == [] and body["parse_errors"] == []
+
+ def test_repo_param_passes_through_to_facade(self) -> None:
+ empty = contracts.QuarantineFile(
+ available=False,
+ entries=[],
+ parse_errors=[],
+ parse_warnings=[],
+ repo=None,
+ source_url="",
+ generated_at=datetime(2026, 6, 12, tzinfo=UTC),
+ )
+ with mock.patch(f"{_VIEWS}.get_quarantine", return_value=empty) as get:
+ response = self.client.get(self._url(), {"repo": "PostHog/posthog.com"})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert get.call_args.kwargs["repo"] == "PostHog/posthog.com"
+ assert get.call_args.kwargs["team"] == self.team
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 763e67dbec76..dbefac98dc29 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -215,6 +215,102 @@ export interface PullRequestListApi {
limit: number
}
+/**
+ * * `run` - RUN
+ * * `skip` - SKIP
+ */
+export type QuarantineModeEnumApi = (typeof QuarantineModeEnumApi)[keyof typeof QuarantineModeEnumApi]
+
+export const QuarantineModeEnumApi = {
+ Run: 'run',
+ Skip: 'skip',
+} as const
+
+/**
+ * * `active` - ACTIVE
+ * * `expiring_soon` - EXPIRING_SOON
+ * * `in_grace` - IN_GRACE
+ * * `overdue` - OVERDUE
+ */
+export type LifecycleEnumApi = (typeof LifecycleEnumApi)[keyof typeof LifecycleEnumApi]
+
+export const LifecycleEnumApi = {
+ Active: 'active',
+ ExpiringSoon: 'expiring_soon',
+ InGrace: 'in_grace',
+ Overdue: 'overdue',
+} as const
+
+/**
+ * * `product` - PRODUCT
+ * * `file` - FILE
+ * * `directory` - DIRECTORY
+ * * `test` - TEST
+ */
+export type SelectorKindEnumApi = (typeof SelectorKindEnumApi)[keyof typeof SelectorKindEnumApi]
+
+export const SelectorKindEnumApi = {
+ Product: 'product',
+ File: 'file',
+ Directory: 'directory',
+ Test: 'test',
+} as const
+
+export interface QuarantineEntryApi {
+ /** Test selector: an exact test id, a file, a directory, a class prefix, or 'product:<dashed-name>'. */
+ id: string
+ /** Test runner the selector targets, e.g. 'pytest' or 'jest'. */
+ runner: string
+ /** Why the test was quarantined. */
+ reason: string
+ /** GitHub team or user handle responsible for the fix. */
+ owner: string
+ /** Tracking issue URL, or empty when none was filed. */
+ issue: string
+ /** ISO date the entry was added. */
+ added: string
+ /** ISO date the quarantine expires; past it the test blocks CI normally again. */
+ expires: string
+ /** 'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all).
+ *
+ * * `run` - RUN
+ * * `skip` - SKIP */
+ mode: QuarantineModeEnumApi
+ /** Expiry classification: 'active' (>7 days left), 'expiring_soon' (0-7 days left), 'in_grace' (expired up to 7 days ago), 'overdue' (expired beyond the grace period).
+ *
+ * * `active` - ACTIVE
+ * * `expiring_soon` - EXPIRING_SOON
+ * * `in_grace` - IN_GRACE
+ * * `overdue` - OVERDUE */
+ lifecycle: LifecycleEnumApi
+ /** Days until the entry expires; negative once past expiry. */
+ days_until_expiry: number
+ /** What the selector covers: 'test' (contains '::'), 'file', 'directory', or 'product'.
+ *
+ * * `product` - PRODUCT
+ * * `file` - FILE
+ * * `directory` - DIRECTORY
+ * * `test` - TEST */
+ selector_kind: SelectorKindEnumApi
+}
+
+export interface QuarantineFileApi {
+ /** Quarantined selectors, most urgent first (overdue, in_grace, expiring_soon, active), then by soonest expiry. */
+ entries: QuarantineEntryApi[]
+ /** Repository the file was read from. Null in local-dev mode, where the server's own checkout is read. */
+ repo: RepoRefApi | null
+ /** False when the repository has no quarantine file (not an error) or it could not be fetched. */
+ available: boolean
+ /** Contract violations (malformed JSON, bad entries) or fetch failures. Malformed entries are dropped; well-formed ones are kept. */
+ parse_errors: string[]
+ /** Forward-compatibility notices, e.g. unknown entry fields. */
+ parse_warnings: string[]
+ /** GitHub blob URL of the quarantine file, or empty when read locally or unavailable. */
+ source_url: string
+ /** When this snapshot was computed (UTC); expiry math uses this clock. */
+ generated_at: string
+}
+
export interface GitHubSourceApi {
/** Source id — pass as `source_id` to the other endpoints to read this source. */
id: string
@@ -301,6 +397,17 @@ export type EngineeringAnalyticsPullRequestsParams = {
source_id?: string
}
+export type EngineeringAnalyticsQuarantineParams = {
+ /**
+ * Optional 'owner/name' repository to read the quarantine file from. Defaults to the connected GitHub source's most active repo over the last 30 days.
+ */
+ 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 workflow health to, e.g. 'main'. Omit or leave blank to aggregate across all branches.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index f2230ff7bfe4..600b843445b0 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -13,10 +13,12 @@ import type {
EngineeringAnalyticsCiCardsParams,
EngineeringAnalyticsPrLifecycleParams,
EngineeringAnalyticsPullRequestsParams,
+ EngineeringAnalyticsQuarantineParams,
EngineeringAnalyticsWorkflowHealthParams,
GitHubSourceApi,
PRLifecycleApi,
PullRequestListApi,
+ QuarantineFileApi,
WorkflowHealthItemApi,
} from './api.schemas'
@@ -116,6 +118,40 @@ export const engineeringAnalyticsPullRequests = async (
})
}
+export const getEngineeringAnalyticsQuarantineUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsQuarantineParams
+) => {
+ 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/quarantine/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/quarantine/`
+}
+
+/**
+ * The repository's checked-in .test_quarantine.json: flaky tests temporarily quarantined with a hard expiry, classified by urgency (overdue, in grace, expiring soon, active). `available` is false when the repo has no quarantine file — that is not an error. Parsing is fail-open: malformed entries are reported in parse_errors while well-formed ones are kept.
+ * @summary Flaky-test quarantine file
+ */
+export const engineeringAnalyticsQuarantine = async (
+ projectId: string,
+ params?: EngineeringAnalyticsQuarantineParams,
+ options?: RequestInit
+): Promise<QuarantineFileApi> => {
+ return apiMutator<QuarantineFileApi>(getEngineeringAnalyticsQuarantineUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsSourcesUrl = (projectId: string) => {
return `/api/projects/${projectId}/engineering_analytics/sources/`
}
diff --git a/products/engineering_analytics/frontend/generated/api.zod.schemas.ts b/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
index 907defe5f00f..b89857ea0fbd 100644
--- a/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.zod.schemas.ts
@@ -344,6 +344,138 @@ export const PullRequestListApi = zod.object({
export type PullRequestListApi = zod.input<typeof PullRequestListApi>
export type PullRequestListApiOutput = zod.output<typeof PullRequestListApi>
+export const QuarantineModeEnumApi = zod.enum(['run', 'skip']).describe('\* `run` - RUN\n\* `skip` - SKIP')
+
+export type QuarantineModeEnumApi = zod.input<typeof QuarantineModeEnumApi>
+export type QuarantineModeEnumApiOutput = zod.output<typeof QuarantineModeEnumApi>
+
+export const LifecycleEnumApi = zod
+ .enum(['active', 'expiring_soon', 'in_grace', 'overdue'])
+ .describe(
+ '\* `active` - ACTIVE\n\* `expiring_soon` - EXPIRING_SOON\n\* `in_grace` - IN_GRACE\n\* `overdue` - OVERDUE'
+ )
+
+export type LifecycleEnumApi = zod.input<typeof LifecycleEnumApi>
+export type LifecycleEnumApiOutput = zod.output<typeof LifecycleEnumApi>
+
+export const SelectorKindEnumApi = zod
+ .enum(['product', 'file', 'directory', 'test'])
+ .describe('\* `product` - PRODUCT\n\* `file` - FILE\n\* `directory` - DIRECTORY\n\* `test` - TEST')
+
+export type SelectorKindEnumApi = zod.input<typeof SelectorKindEnumApi>
+export type SelectorKindEnumApiOutput = zod.output<typeof SelectorKindEnumApi>
+
+export const QuarantineEntryApi = zod.object({
+ id: zod
+ .string()
+ .describe("Test selector: an exact test id, a file, a directory, a class prefix, or 'product:<dashed-name>'."),
+ runner: zod.string().describe("Test runner the selector targets, e.g. 'pytest' or 'jest'."),
+ reason: zod.string().describe('Why the test was quarantined.'),
+ owner: zod.string().describe('GitHub team or user handle responsible for the fix.'),
+ issue: zod.string().describe('Tracking issue URL, or empty when none was filed.'),
+ added: zod.iso.date().describe('ISO date the entry was added.'),
+ expires: zod.iso.date().describe('ISO date the quarantine expires; past it the test blocks CI normally again.'),
+ mode: zod
+ .enum(['run', 'skip'])
+ .describe('\* `run` - RUN\n\* `skip` - SKIP')
+ .describe(
+ "'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all).\n\n\* `run` - RUN\n\* `skip` - SKIP"
+ ),
+ lifecycle: zod
+ .enum(['active', 'expiring_soon', 'in_grace', 'overdue'])
+ .describe(
+ '\* `active` - ACTIVE\n\* `expiring_soon` - EXPIRING_SOON\n\* `in_grace` - IN_GRACE\n\* `overdue` - OVERDUE'
+ )
+ .describe(
+ "Expiry classification: 'active' (>7 days left), 'expiring_soon' (0-7 days left), 'in_grace' (expired up to 7 days ago), 'overdue' (expired beyond the grace period).\n\n\* `active` - ACTIVE\n\* `expiring_soon` - EXPIRING_SOON\n\* `in_grace` - IN_GRACE\n\* `overdue` - OVERDUE"
+ ),
+ days_until_expiry: zod.number().describe('Days until the entry expires; negative once past expiry.'),
+ selector_kind: zod
+ .enum(['product', 'file', 'directory', 'test'])
+ .describe('\* `product` - PRODUCT\n\* `file` - FILE\n\* `directory` - DIRECTORY\n\* `test` - TEST')
+ .describe(
+ "What the selector covers: 'test' (contains '::'), 'file', 'directory', or 'product'.\n\n\* `product` - PRODUCT\n\* `file` - FILE\n\* `directory` - DIRECTORY\n\* `test` - TEST"
+ ),
+})
+
+export type QuarantineEntryApi = zod.input<typeof QuarantineEntryApi>
+export type QuarantineEntryApiOutput = zod.output<typeof QuarantineEntryApi>
+
+export const QuarantineFileApi = zod.object({
+ entries: zod
+ .array(
+ zod.object({
+ id: zod
+ .string()
+ .describe(
+ "Test selector: an exact test id, a file, a directory, a class prefix, or 'product:<dashed-name>'."
+ ),
+ runner: zod.string().describe("Test runner the selector targets, e.g. 'pytest' or 'jest'."),
+ reason: zod.string().describe('Why the test was quarantined.'),
+ owner: zod.string().describe('GitHub team or user handle responsible for the fix.'),
+ issue: zod.string().describe('Tracking issue URL, or empty when none was filed.'),
+ added: zod.iso.date().describe('ISO date the entry was added.'),
+ expires: zod.iso
+ .date()
+ .describe('ISO date the quarantine expires; past it the test blocks CI normally again.'),
+ mode: zod
+ .enum(['run', 'skip'])
+ .describe('\* `run` - RUN\n\* `skip` - SKIP')
+ .describe(
+ "'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all).\n\n\* `run` - RUN\n\* `skip` - SKIP"
+ ),
+ lifecycle: zod
+ .enum(['active', 'expiring_soon', 'in_grace', 'overdue'])
+ .describe(
+ '\* `active` - ACTIVE\n\* `expiring_soon` - EXPIRING_SOON\n\* `in_grace` - IN_GRACE\n\* `overdue` - OVERDUE'
+ )
+ .describe(
+ "Expiry classification: 'active' (>7 days left), 'expiring_soon' (0-7 days left), 'in_grace' (expired up to 7 days ago), 'overdue' (expired beyond the grace period).\n\n\* `active` - ACTIVE\n\* `expiring_soon` - EXPIRING_SOON\n\* `in_grace` - IN_GRACE\n\* `overdue` - OVERDUE"
+ ),
+ days_until_expiry: zod.number().describe('Days until the entry expires; negative once past expiry.'),
+ selector_kind: zod
+ .enum(['product', 'file', 'directory', 'test'])
+ .describe('\* `product` - PRODUCT\n\* `file` - FILE\n\* `directory` - DIRECTORY\n\* `test` - TEST')
+ .describe(
+ "What the selector covers: 'test' (contains '::'), 'file', 'directory', or 'product'.\n\n\* `product` - PRODUCT\n\* `file` - FILE\n\* `directory` - DIRECTORY\n\* `test` - TEST"
+ ),
+ })
+ )
+ .describe(
+ 'Quarantined selectors, most urgent first (overdue, in_grace, expiring_soon, active), then by soonest expiry.'
+ ),
+ repo: zod
+ .union([
+ zod.object({
+ provider: zod.string().describe("Code host provider, e.g. 'github'."),
+ owner: zod.string().describe('Repository owner or organization.'),
+ name: zod.string().describe('Repository name.'),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ "Repository the file was read from. Null in local-dev mode, where the server's own checkout is read."
+ ),
+ available: zod
+ .boolean()
+ .describe('False when the repository has no quarantine file (not an error) or it could not be fetched.'),
+ parse_errors: zod
+ .array(zod.string())
+ .describe(
+ 'Contract violations (malformed JSON, bad entries) or fetch failures. Malformed entries are dropped; well-formed ones are kept.'
+ ),
+ parse_warnings: zod.array(zod.string()).describe('Forward-compatibility notices, e.g. unknown entry fields.'),
+ source_url: zod
+ .string()
+ .describe('GitHub blob URL of the quarantine file, or empty when read locally or unavailable.'),
+ generated_at: zod.iso
+ .datetime({ offset: true })
+ .describe('When this snapshot was computed (UTC); expiry math uses this clock.'),
+})
+
+export type QuarantineFileApi = zod.input<typeof QuarantineFileApi>
+export type QuarantineFileApiOutput = zod.output<typeof QuarantineFileApi>
+
export const GitHubSourceApi = zod.object({
id: zod.string().describe('Source id — pass as `source_id` to the other endpoints to read this source.'),
repo: zod.string().describe("Connected repository as 'owner\/name', or '' if unknown."),
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
index f3beb67a1e6a..e37eaa9b82b4 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx
@@ -16,6 +16,7 @@ import {
TAB_DESCRIPTIONS,
engineeringAnalyticsSceneLogic,
} from './engineeringAnalyticsSceneLogic'
+import { EngineeringAnalyticsTestHealth } from './EngineeringAnalyticsTestHealth'
import { EngineeringAnalyticsWorkflows } from './EngineeringAnalyticsWorkflows'
export const scene: SceneExport = {
@@ -45,6 +46,13 @@ export function EngineeringAnalyticsScene(): JSX.Element {
link: combineUrl(urls.engineeringAnalyticsWorkflows(), searchParams).url,
'data-attr': 'engineering-analytics-workflows-tab',
},
+ {
+ key: 'test-health',
+ label: 'Test health',
+ content: <EngineeringAnalyticsTestHealth />,
+ link: combineUrl(urls.engineeringAnalyticsTestHealth(), searchParams).url,
+ 'data-attr': 'engineering-analytics-test-health-tab',
+ },
]
return (
@@ -81,7 +89,7 @@ export function EngineeringAnalyticsScene(): JSX.Element {
}
/>
<LemonBanner type="info" dismissKey="engineering-analytics-alpha">
- CI analytics is in alpha — metrics are limited to CI events, and details may change.
+ CI analytics is in alpha. Metrics are limited to CI events, and details may change.
</LemonBanner>
<LemonTabs activeKey={activeTab} data-attr="engineering-analytics-tabs" tabs={tabs} sceneInset />
</SceneContent>
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
new file mode 100644
index 000000000000..e07004f82b93
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
@@ -0,0 +1,467 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEllipsis, IconExternal, IconShieldLock } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonInput,
+ LemonInputSelect,
+ LemonMenu,
+ LemonSegmentedButton,
+ LemonSelect,
+ LemonTable,
+ LemonTableColumns,
+ LemonTag,
+ Link,
+ Tooltip,
+} from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+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 { StatCard } from '../components/StatCard'
+import {
+ QuarantineEntryRow,
+ QuarantineLifecycle,
+ QuarantineLifecycleFilter,
+ QuarantineModeFilter,
+ engineeringAnalyticsLogic,
+} from './engineeringAnalyticsLogic'
+
+/** Default runway granted by an extend, mirroring how teams re-triage before re-quarantining. */
+const EXTEND_DAYS = 14
+
+function nextExpiry(): string {
+ return dayjs().add(EXTEND_DAYS, 'day').format('YYYY-MM-DD')
+}
+
+/** Single-quote a value for a POSIX shell, escaping embedded single quotes so a
+ * selector, reason, or owner containing a `'` still copies as a runnable command. */
+function shellQuote(value: string): string {
+ return `'${value.replace(/'/g, "'\\''")}'`
+}
+
+function removeCommand(row: QuarantineEntryRow): string {
+ return `hogli test:quarantine remove ${shellQuote(row.id)}`
+}
+
+function extendCommand(row: QuarantineEntryRow): string {
+ return `hogli test:quarantine add ${shellQuote(row.id)} --expires ${nextExpiry()} --reason ${shellQuote(
+ row.reason
+ )} --owner ${shellQuote(row.owner)}`
+}
+
+const ADD_EXAMPLE =
+ "hogli test:quarantine add 'posthog/path/to/test.py::TestClass::test_method' " +
+ '--reason "Flaky under parallel shards" --owner "@PostHog/your-team" --expires <YYYY-MM-DD>'
+
+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 (
+ <Tooltip title="Masked in CI, with more than 7 days before it expires.">
+ <LemonTag type="success">Active</LemonTag>
+ </Tooltip>
+ )
+ case 'expiring_soon':
+ return (
+ <Tooltip title="Still masked in CI, but expires within 7 days.">
+ <LemonTag type="warning">Expiring</LemonTag>
+ </Tooltip>
+ )
+ case 'in_grace':
+ return (
+ <Tooltip title="Expired, so the test runs (and can fail) again. hogli test:quarantine check only warns until the 7-day grace period ends.">
+ <LemonTag type="warning">Grace</LemonTag>
+ </Tooltip>
+ )
+ default:
+ return (
+ <Tooltip title="Expired past the 7-day grace. hogli test:quarantine check fails and blocks merges until the entry is removed or re-triaged.">
+ <LemonTag type="danger">Blocking</LemonTag>
+ </Tooltip>
+ )
+ }
+}
+
+function ModeTag({ mode }: { mode: QuarantineEntryRow['mode'] }): JSX.Element {
+ if (mode === 'skip') {
+ return (
+ <Tooltip title="mode: skip. Applied as pytest.mark.skip, so the test is not collected at all (for hangs, import-time flakes, and state-polluters).">
+ <LemonTag type="danger">skip</LemonTag>
+ </Tooltip>
+ )
+ }
+ return (
+ <Tooltip title="mode: run. Applied as pytest.mark.xfail(strict=False), so the test still runs but can't fail the suite.">
+ <LemonTag type="muted">xfail</LemonTag>
+ </Tooltip>
+ )
+}
+
+export function EngineeringAnalyticsTestHealth(): JSX.Element {
+ const {
+ quarantine,
+ quarantineLoading,
+ quarantineLoadFailed,
+ filteredQuarantineEntries,
+ quarantineCounts,
+ quarantineOwnerOptions,
+ quarantineSearch,
+ quarantineLifecycleFilter,
+ quarantineModeFilter,
+ quarantineOwner,
+ activeQuarantineCard,
+ hasActiveQuarantineFilters,
+ } = useValues(engineeringAnalyticsLogic)
+ const {
+ setQuarantineSearch,
+ setQuarantineLifecycleFilter,
+ setQuarantineModeFilter,
+ setQuarantineOwner,
+ applyQuarantineCard,
+ resetQuarantineFilters,
+ } = useActions(engineeringAnalyticsLogic)
+
+ // Production with no GitHub source and no local checkout: the endpoint 400s, same as the other tabs.
+ if (quarantineLoadFailed) {
+ return <ConnectGitHubSource />
+ }
+
+ // A fetch failure (timeout, 5xx, unsafe repo) also comes back as available:false, but with
+ // parse_errors set: surface those instead of the "no file" explainer, which only fits a true 404.
+ if (quarantine && !quarantine.available && quarantine.parseErrors.length > 0) {
+ return (
+ <div className="flex flex-col 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>
+ )
+ }
+
+ // A file that does not exist is a normal state, not an error, so explain how to start one.
+ if (quarantine && !quarantine.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. Add the first entry from the repo root:
+ </p>
+ <code className="max-w-xl overflow-x-auto rounded bg-surface-secondary px-3 py-2 text-left font-mono text-xs">
+ {ADD_EXAMPLE}
+ </code>
+ <LemonButton type="secondary" size="small" onClick={() => void copyToClipboard(ADD_EXAMPLE, 'command')}>
+ Copy add command
+ </LemonButton>
+ </div>
+ )
+ }
+
+ const columns: LemonTableColumns<QuarantineEntryRow> = [
+ {
+ title: 'Selector',
+ key: 'id',
+ render: (_, row) => (
+ <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="No enforcement adapter yet, so this entry is informational.">
+ <LemonTag type="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: 'Copy remove command',
+ onClick: () => void copyToClipboard(removeCommand(row), 'remove command'),
+ },
+ {
+ label: 'Copy extend command',
+ onClick: () => void copyToClipboard(extendCommand(row), 'extend command'),
+ },
+ ...(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 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 in the checked-in quarantine file. Active entries are masked in CI; once expired the
+ test runs again and the entry needs removing.
+ </p>
+ </div>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl: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"
+ />
+ <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"
+ />
+ <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)"
+ />
+ <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)"
+ />
+ </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: xfail', labelInMenu: 'xfail' },
+ { value: 'skip', label: 'Mode: skip', labelInMenu: 'skip' },
+ ]}
+ />
+ <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"
+ size="small"
+ columns={columns}
+ dataSource={filteredQuarantineEntries}
+ rowKey={(row) => `${row.runner}:${row.id}`}
+ loading={quarantineLoading}
+ pagination={{ pageSize: 50 }}
+ 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']}
+ />
+
+ <div className="text-xs text-tertiary">
+ Quarantine is checked into <span className="font-mono">.test_quarantine.json</span> and enforced by CI.
+ Edits land through a pull request, not this page. Use the per-row menu to copy the matching{' '}
+ <span className="font-mono">hogli test:quarantine</span> command. A merged edit only affects CI runs
+ that start after it lands.
+ </div>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index e2bdaf493b53..db0f80e6367c 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -8,6 +8,7 @@ import { initKeaTests } from '~/test/init'
import {
engineeringAnalyticsCiCards,
engineeringAnalyticsPullRequests,
+ engineeringAnalyticsQuarantine,
engineeringAnalyticsSources,
engineeringAnalyticsWorkflowHealth,
} from '../generated/api'
@@ -15,15 +16,21 @@ import type {
CICardSummaryApi,
GitHubSourceApi,
PullRequestListItemApi,
+ QuarantineEntryApi,
+ QuarantineFileApi,
WorkflowHealthItemApi,
} from '../generated/api.schemas'
import { ciStatusOf } from '../lib/ci'
import { summarizeLifecycle, workflowRuns } from '../lib/lifecycle'
import {
DEFAULT_FILTERS,
+ DEFAULT_QUARANTINE_FILTERS,
PullRequestRow,
+ QuarantineEntryRow,
engineeringAnalyticsLogic,
filterPullRequests,
+ filterQuarantineEntries,
+ quarantineCountsOf,
workflowTrendSeries,
} from './engineeringAnalyticsLogic'
import { engineeringAnalyticsSceneLogic } from './engineeringAnalyticsSceneLogic'
@@ -33,6 +40,7 @@ jest.mock('../generated/api', () => ({
engineeringAnalyticsCiCards: jest.fn(),
engineeringAnalyticsPrLifecycle: jest.fn(),
engineeringAnalyticsPullRequests: jest.fn(),
+ engineeringAnalyticsQuarantine: jest.fn(),
engineeringAnalyticsSources: jest.fn(),
engineeringAnalyticsWorkflowHealth: jest.fn(),
}))
@@ -44,8 +52,66 @@ const mockPullRequests = engineeringAnalyticsPullRequests as jest.MockedFunction
const mockWorkflowHealth = engineeringAnalyticsWorkflowHealth as jest.MockedFunction<
typeof engineeringAnalyticsWorkflowHealth
>
+const mockQuarantine = engineeringAnalyticsQuarantine as jest.MockedFunction<typeof engineeringAnalyticsQuarantine>
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 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',
+ }),
+ ],
+ parse_errors: [],
+ parse_warnings: [],
+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
+ source_url: 'https://github.com/PostHog/posthog/blob/HEAD/.test_quarantine.json',
+ generated_at: '2026-06-12T00:00:00Z',
+}
+
function makePr(overrides: Partial<PullRequestRow> = {}): PullRequestRow {
return {
number: 1,
@@ -135,6 +201,7 @@ describe('engineeringAnalyticsLogic', () => {
mockCiCards.mockResolvedValue(CARDS)
mockPullRequests.mockResolvedValue({ items: PRS, truncated: false, limit: PRS.length })
mockWorkflowHealth.mockResolvedValue(WORKFLOWS)
+ mockQuarantine.mockResolvedValue(QUARANTINE)
// Most tests are single- or no-source; the picker tests override with SOURCES.
mockSources.mockResolvedValue([])
})
@@ -516,4 +583,115 @@ describe('engineeringAnalyticsLogic', () => {
expect(logic.values.pullRequestsLoadError).toBe(false)
expect(logic.values.notConnected).toBe(false)
})
+
+ 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 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)
+ })
+
+ 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')
+ })
+
+ it('resetQuarantineFilters returns filters to defaults and clears hasActiveQuarantineFilters', async () => {
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ expect(logic.values.hasActiveQuarantineFilters).toBe(false)
+
+ logic.actions.setQuarantineSearch('flake')
+ logic.actions.setQuarantineLifecycleFilter('active')
+ logic.actions.setQuarantineModeFilter('skip')
+ logic.actions.setQuarantineOwner('@team/x')
+ expect(logic.values.hasActiveQuarantineFilters).toBe(true)
+
+ logic.actions.resetQuarantineFilters()
+ expect(logic.values.quarantineFilters).toEqual(DEFAULT_QUARANTINE_FILTERS)
+ expect(logic.values.hasActiveQuarantineFilters).toBe(false)
+ })
+
+ it('flags quarantineLoadFailed when the quarantine endpoint 400s', async () => {
+ mockQuarantine.mockRejectedValue(
+ new Error('Connect a GitHub data warehouse source to use engineering analytics.')
+ )
+
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadQuarantineFailure'])
+
+ expect(logic.values.quarantineLoadFailed).toBe(true)
+ })
})
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index 6e3d8842d6e4..b7b8edbc2ad7 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -10,6 +10,7 @@ import { urls } from 'scenes/urls'
import {
engineeringAnalyticsCiCards,
engineeringAnalyticsPullRequests,
+ engineeringAnalyticsQuarantine,
engineeringAnalyticsSources,
engineeringAnalyticsWorkflowHealth,
} from '../generated/api'
@@ -182,6 +183,128 @@ export function filterPullRequests(
})
}
+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'
+/** The stat cards double as quick filters over the entries, like the PR tab. */
+export type QuarantineCard = 'active' | 'expiring_soon' | 'past_expiry' | 'skipped'
+
+export interface QuarantineEntryRow {
+ id: string
+ runner: string
+ reason: string
+ owner: string
+ /** Tracking issue URL, or '' when none was filed. */
+ issue: string
+ /** ISO date. */
+ added: string
+ /** ISO date. */
+ expires: string
+ mode: QuarantineMode
+ lifecycle: QuarantineLifecycle
+ /** Negative once past expiry. */
+ daysUntilExpiry: number
+ selectorKind: QuarantineSelectorKind
+}
+
+export interface QuarantineData {
+ available: boolean
+ entries: QuarantineEntryRow[]
+ parseErrors: string[]
+ parseWarnings: string[]
+ sourceUrl: string
+ /** owner/name, or null when read from the local checkout in dev. */
+ 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 }
+}
+
/**
* Per-loader outcome. The endpoints all resolve the same GitHub source, so a 400
* (GitHubSourceNotConnectedError) means "connect a source" for every scene; any other
@@ -216,6 +339,12 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
setSourceId: (sourceId: string | null) => ({ sourceId }),
setCostLensEnabled: (enabled: boolean) => ({ enabled }),
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,
refresh: true,
}),
@@ -306,6 +435,38 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
},
],
+ quarantine: [
+ null as QuarantineData | null,
+ {
+ loadQuarantine: async (): Promise<QuarantineData> => {
+ const data = await engineeringAnalyticsQuarantine(projectId(), {
+ source_id: values.sourceId ?? undefined,
+ })
+ return {
+ available: data.available,
+ entries: data.entries.map(
+ (it): QuarantineEntryRow => ({
+ id: it.id,
+ runner: it.runner,
+ reason: it.reason,
+ owner: it.owner,
+ issue: it.issue,
+ added: it.added,
+ expires: it.expires,
+ mode: it.mode as QuarantineMode,
+ lifecycle: it.lifecycle as QuarantineLifecycle,
+ daysUntilExpiry: it.days_until_expiry,
+ selectorKind: it.selector_kind as QuarantineSelectorKind,
+ })
+ ),
+ parseErrors: data.parse_errors,
+ parseWarnings: data.parse_warnings,
+ sourceUrl: data.source_url,
+ repoFullName: data.repo ? `${data.repo.owner}/${data.repo.name}` : null,
+ }
+ },
+ },
+ ],
githubSources: [
[] as GitHubSourceApi[],
{
@@ -367,6 +528,44 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadCardsFailure: (_, { 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 is no GitHub source AND no local
+ // checkout (production without a source); a failed load is that canary.
+ quarantineLoadFailed: [
+ false,
+ {
+ loadQuarantine: () => false,
+ loadQuarantineSuccess: () => false,
+ loadQuarantineFailure: () => true,
+ },
+ ],
pullRequestsStatus: [
'ok' as LoaderStatus,
{
@@ -434,9 +633,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
Array.from(new Set(pullRequests.map((pr) => `${pr.repoOwner}/${pr.repoName}`))).sort(),
],
anyLoading: [
- (s) => [s.cardsLoading, s.pullRequestsLoading, s.workflowHealthLoading],
- (cardsLoading, pullRequestsLoading, workflowHealthLoading): boolean =>
- cardsLoading || pullRequestsLoading || workflowHealthLoading,
+ (s) => [s.cardsLoading, s.pullRequestsLoading, s.workflowHealthLoading, s.quarantineLoading],
+ (cardsLoading, pullRequestsLoading, workflowHealthLoading, quarantineLoading): boolean =>
+ cardsLoading || pullRequestsLoading || workflowHealthLoading || quarantineLoading,
],
// No GitHub source connected: a 400 from any endpoint (they share source resolution).
// Drives the "connect a source" state on every scene, regardless of which loaders it renders.
@@ -460,6 +659,44 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
(workflowHealthStatus): boolean => workflowHealthStatus === 'error',
],
tableTruncated: [(s) => [s.pullRequests], (pullRequests): boolean => pullRequests.length >= PR_TABLE_LIMIT],
+ quarantineFilters: [
+ (s) => [s.quarantineSearch, s.quarantineLifecycleFilter, s.quarantineModeFilter, s.quarantineOwner],
+ (search, lifecycle, mode, owner): QuarantineFilters => ({ search, lifecycle, mode, owner }),
+ ],
+ filteredQuarantineEntries: [
+ (s) => [s.quarantine, s.quarantineFilters],
+ (quarantine, filters): QuarantineEntryRow[] =>
+ quarantine ? filterQuarantineEntries(quarantine.entries, filters) : [],
+ ],
+ quarantineCounts: [
+ (s) => [s.quarantine],
+ (quarantine): QuarantineCounts => quarantineCountsOf(quarantine?.entries ?? []),
+ ],
+ quarantineOwnerOptions: [
+ (s) => [s.quarantine],
+ (quarantine): string[] =>
+ Array.from(new Set((quarantine?.entries ?? []).map((entry) => entry.owner).filter(Boolean))).sort(),
+ ],
+ activeQuarantineCard: [
+ (s) => [s.quarantineLifecycleFilter, s.quarantineModeFilter],
+ (lifecycle, mode): 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): boolean =>
+ !objectsEqual({ ...filters, search: filters.search.trim() }, DEFAULT_QUARANTINE_FILTERS),
+ ],
// Only worth a picker when the team has more than one GitHub source connected.
hasMultipleSources: [(s) => [s.githubSources], (githubSources): boolean => githubSources.length > 1],
sourceOptions: [
@@ -477,8 +714,9 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
actions.loadCards()
actions.loadPullRequests()
actions.loadWorkflowHealth()
+ actions.loadQuarantine()
},
- // Cards, the PR list, and workflow health are all per-source — reload them all.
+ // Cards, the PR list, workflow health, and the quarantine repo are all per-source — reload them all.
setSourceId: () => actions.refresh(),
setWorkflowDateRange: () => {
actions.loadWorkflowHealth()
@@ -509,6 +747,20 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
actions.setCiStatusFilter(target === 'failing' ? 'failing' : 'all')
actions.setStuckOnly(target === 'stuck')
},
+ 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)
+ }
+ },
})),
actionToUrl(() => ({
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
index d76c9f252605..df352a34ed36 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts
@@ -4,16 +4,18 @@ import { sceneLogic } from '~/scenes/sceneLogic'
import type { engineeringAnalyticsSceneLogicType } from './engineeringAnalyticsSceneLogicType'
-export type EngineeringAnalyticsTab = 'pull-requests' | 'workflows'
+export type EngineeringAnalyticsTab = 'pull-requests' | 'workflows' | 'test-health'
export const TAB_DESCRIPTIONS: Record<EngineeringAnalyticsTab, string> = {
'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.',
}
const SCENE_KEY_TO_TAB: Record<string, EngineeringAnalyticsTab> = {
engineeringAnalytics: 'pull-requests',
engineeringAnalyticsWorkflows: 'workflows',
+ engineeringAnalyticsTestHealth: 'test-health',
}
export const engineeringAnalyticsSceneLogic = kea<engineeringAnalyticsSceneLogicType>([
diff --git a/products/engineering_analytics/manifest.tsx b/products/engineering_analytics/manifest.tsx
index 0b4cdbbf2bcc..c6ba7ec2439f 100644
--- a/products/engineering_analytics/manifest.tsx
+++ b/products/engineering_analytics/manifest.tsx
@@ -33,6 +33,7 @@ export const manifest: ProductManifest = {
routes: {
'/engineering-analytics': ['EngineeringAnalytics', 'engineeringAnalytics'],
'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],
+ '/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],
'/engineering-analytics/pr/:repoOwner/:repoName/:number': [
'EngineeringAnalyticsPullRequest',
'engineeringAnalyticsPullRequest',
@@ -42,6 +43,7 @@ export const manifest: ProductManifest = {
urls: {
engineeringAnalytics: (): string => '/engineering-analytics',
engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',
+ engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',
engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>
`/engineering-analytics/pr/${encodeURIComponent(repoOwner)}/${encodeURIComponent(repoName)}/${number}`,
},
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index f227c8885ec1..924256a8cd1c 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -12,6 +12,9 @@ tools:
engineering-analytics-ci-cards:
operation: engineering_analytics_ci_cards
enabled: false
+ engineering-analytics-quarantine:
+ operation: engineering_analytics_quarantine
+ enabled: false
engineering-analytics-sources:
operation: engineering_analytics_sources
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a6a1402f2919..9d64b8e702c2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27803,6 +27803,22 @@ export namespace Schemas {
created_at: string;
}
+ /**
+ * * `active` - ACTIVE
+ * * `expiring_soon` - EXPIRING_SOON
+ * * `in_grace` - IN_GRACE
+ * * `overdue` - OVERDUE
+ */
+ export type LifecycleEnum = typeof LifecycleEnum[keyof typeof LifecycleEnum];
+
+
+ export const LifecycleEnum = {
+ Active: 'active',
+ ExpiringSoon: 'expiring_soon',
+ InGrace: 'in_grace',
+ Overdue: 'overdue',
+ } as const;
+
export type LimitContext = typeof LimitContext[keyof typeof LimitContext];
@@ -43630,6 +43646,89 @@ export namespace Schemas {
Web: 'web',
} as const;
+ /**
+ * * `run` - RUN
+ * * `skip` - SKIP
+ */
+ export type QuarantineModeEnum = typeof QuarantineModeEnum[keyof typeof QuarantineModeEnum];
+
+
+ export const QuarantineModeEnum = {
+ Run: 'run',
+ Skip: 'skip',
+ } as const;
+
+ /**
+ * * `product` - PRODUCT
+ * * `file` - FILE
+ * * `directory` - DIRECTORY
+ * * `test` - TEST
+ */
+ export type SelectorKindEnum = typeof SelectorKindEnum[keyof typeof SelectorKindEnum];
+
+
+ export const SelectorKindEnum = {
+ Product: 'product',
+ File: 'file',
+ Directory: 'directory',
+ Test: 'test',
+ } as const;
+
+ export interface QuarantineEntry {
+ /** Test selector: an exact test id, a file, a directory, a class prefix, or 'product:<dashed-name>'. */
+ id: string;
+ /** Test runner the selector targets, e.g. 'pytest' or 'jest'. */
+ runner: string;
+ /** Why the test was quarantined. */
+ reason: string;
+ /** GitHub team or user handle responsible for the fix. */
+ owner: string;
+ /** Tracking issue URL, or empty when none was filed. */
+ issue: string;
+ /** ISO date the entry was added. */
+ added: string;
+ /** ISO date the quarantine expires; past it the test blocks CI normally again. */
+ expires: string;
+ /** 'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all).
+ *
+ * * `run` - RUN
+ * * `skip` - SKIP */
+ mode: QuarantineModeEnum;
+ /** Expiry classification: 'active' (>7 days left), 'expiring_soon' (0-7 days left), 'in_grace' (expired up to 7 days ago), 'overdue' (expired beyond the grace period).
+ *
+ * * `active` - ACTIVE
+ * * `expiring_soon` - EXPIRING_SOON
+ * * `in_grace` - IN_GRACE
+ * * `overdue` - OVERDUE */
+ lifecycle: LifecycleEnum;
+ /** Days until the entry expires; negative once past expiry. */
+ days_until_expiry: number;
+ /** What the selector covers: 'test' (contains '::'), 'file', 'directory', or 'product'.
+ *
+ * * `product` - PRODUCT
+ * * `file` - FILE
+ * * `directory` - DIRECTORY
+ * * `test` - TEST */
+ selector_kind: SelectorKindEnum;
+ }
+
+ export interface QuarantineFile {
+ /** Quarantined selectors, most urgent first (overdue, in_grace, expiring_soon, active), then by soonest expiry. */
+ entries: QuarantineEntry[];
+ /** Repository the file was read from. Null in local-dev mode, where the server's own checkout is read. */
+ repo: RepoRef | null;
+ /** False when the repository has no quarantine file (not an error) or it could not be fetched. */
+ available: boolean;
+ /** Contract violations (malformed JSON, bad entries) or fetch failures. Malformed entries are dropped; well-formed ones are kept. */
+ parse_errors: string[];
+ /** Forward-compatibility notices, e.g. unknown entry fields. */
+ parse_warnings: string[];
+ /** GitHub blob URL of the quarantine file, or empty when read locally or unavailable. */
+ source_url: string;
+ /** When this snapshot was computed (UTC); expiry math uses this clock. */
+ generated_at: string;
+ }
+
export interface QuarantineInput {
/**
* Snapshot identifier to quarantine.
@@ -60058,6 +60157,17 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsQuarantineParams = {
+ /**
+ * Optional 'owner/name' repository to read the quarantine file from. Defaults to the connected GitHub source's most active repo over the last 30 days.
+ */
+ 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 workflow health to, e.g. 'main'. Omit or leave blank to aggregate across all branches.