:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(engineering_analytics): open issue + PR to quarantine a test (#63826)
Raúl Negrón-Oteroa1cad68c89d9
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 2ba3c10003de..c2c1cfee3a3e 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -2860,6 +2860,37 @@ class GitHubIntegration(GitHubIntegrationBase):"status_code": response.status_code,}+ def get_file_contents(self, repository: str, file_path: str, ref: str | None = None) -> dict[str, Any] | None:+ """Read a file's decoded text and blob SHA at ``ref`` (default branch when omitted).++ Returns ``{"content": str, "sha": str}``, or ``None`` when the file does not+ exist — a missing file is a normal state, not an error. The SHA lets a caller+ pass it straight to ``update_file`` for a conflict-safe write. Counterpart to+ ``update_file``, kept here so URL and token handling stay inside the client.+ """+ org = self.organization()+ access_token = self.integration.sensitive_config["access_token"]++ response = self._github_api_get(+ f"https://api.github.com/repos/{org}/{repository}/contents/{file_path}",+ endpoint="/repos/{owner}/{repo}/contents/{path}",+ params={"ref": ref} if ref else None,+ headers={+ "Accept": "application/vnd.github+json",+ "Authorization": f"Bearer {access_token}",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,+ },+ )+ if response.status_code == 404:+ return None+ if response.status_code != 200:+ raise GitHubIntegrationError(+ f"Failed to read {file_path} from {repository}: {response.text}",+ status_code=response.status_code,+ )+ payload = response.json()+ return {"content": base64.b64decode(payload["content"]).decode("utf-8"), "sha": payload["sha"]}+def create_pull_request(self, repository: str, title: str, body: str, head_branch: str, base_branch: str | None = None) -> dict[str, Any]:diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 34cf1a900856..99ee5681f9b1 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -28,6 +28,8 @@ from products.engineering_analytics.backend.facade.contracts import (PRLifecycle,PullRequestList,QuarantineFile,+ QuarantineRequest,+ QuarantineRequestResult,WorkflowHealthItem,WorkflowJob,WorkflowRunDetail,@@ -202,3 +204,12 @@ def get_quarantine(# 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)+++def request_quarantine(+ *,+ team: Team,+ request: QuarantineRequest,+ user_access_control: "UserAccessControl | None" = None,+) -> QuarantineRequestResult:+ return logic.request_quarantine(team=team, request=request, user_access_control=user_access_control)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 82ac2ec1b06c..dd9cdf6fa787 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -41,6 +41,17 @@ class GitHubSourceNotConnectedError(Exception):super().__init__(message)+class QuarantineWriteError(Exception):+ """A quarantine write could not be completed — no GitHub App installed on the+ target repo, the App lives on a different org, a malformed quarantine file, or a+ failed GitHub call. Carries a message safe to show the user verbatim. Framework-free;+ the presentation layer maps it to a 400 so the UI explains what to fix.+ """++ def __init__(self, message: str) -> None:+ super().__init__(message)++class PRState(StrEnum):OPEN = "open"CLOSED = "closed"@@ -107,6 +118,17 @@ class QuarantineSelectorKind(StrEnum):TEST = "test"+class QuarantineRequestAction(StrEnum):+ """What a write to the quarantine file does. ``quarantine`` adds (or replaces) an+ entry and files a fresh tracking issue; ``extend`` re-stamps an existing entry's+ expiry, reusing its issue; ``remove`` deletes the entry. All three open a PR.+ """++ QUARANTINE = "quarantine"+ EXTEND = "extend"+ REMOVE = "remove"++@dataclass(frozen=True)class GitHubSource:"""A connected GitHub warehouse source the team can analyze. ``id`` is what a@@ -435,6 +457,39 @@ class QuarantineFile:generated_at: datetime+@dataclass(frozen=True)+class QuarantineRequest:+ """A request to mutate a repo's ``.test_quarantine.json`` via a PR. ``selector`` is+ required for every action. ``reason``/``owner``/``expires``/``mode`` drive+ ``quarantine`` and ``extend`` and are ignored by ``remove``; ``issue`` carries the+ existing tracking issue forward on ``extend`` (``quarantine`` files a new one and+ overrides it). ``repo`` is an optional ``owner/name`` override; it defaults to the+ team's most active repo, matching the read endpoint.+ """++ # Named 'operation', not 'action': a bare 'action' enum field collides with other+ # serializers' 'action' enums in the OpenAPI spec and churns their generated types.+ operation: QuarantineRequestAction+ selector: str+ repo: str | None = None+ reason: str = ""+ owner: str = ""+ issue: str = ""+ expires: date | None = None+ mode: QuarantineMode = QuarantineMode.RUN+++@dataclass(frozen=True)+class QuarantineRequestResult:+ """Outcome of a quarantine write: the opened PR, the tracking issue (empty for+ ``extend``/``remove``), and the branch the PR was opened from.+ """++ pr_url: str+ issue_url: str+ branch: str++@dataclass(frozen=True)class WorkflowHealthItem:"""Per-workflow CI health over a window. Rates and percentiles are overdiff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex f0f2975729c3..5ba1078afe09 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -24,7 +24,10 @@ from products.engineering_analytics.backend.facade.contracts import (WorkflowRunDetail,WorkflowRunnerCost,)-from products.engineering_analytics.backend.logic.quarantine import build_quarantine as build_quarantine+from products.engineering_analytics.backend.logic.quarantine import (+ build_quarantine as build_quarantine,+ request_quarantine as request_quarantine,+)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries.ci_cards import query_ci_cardsfrom products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_cost, query_workflow_runner_costsdiff --git a/products/engineering_analytics/backend/logic/quarantine.py b/products/engineering_analytics/backend/logic/quarantine.pyindex 4f475572e8d1..dbac8a3acf7a 100644--- a/products/engineering_analytics/backend/logic/quarantine.py+++ b/products/engineering_analytics/backend/logic/quarantine.py@@ -1,19 +1,25 @@-"""Read side of a repo's checked-in ``.test_quarantine.json``.+"""Read and write sides 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+forbids importing tools code, so the minimal 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 GitHubsource's most active repo over the last 30 days (``source_id`` selects whichconnected source; ``user_access_control`` filters out sources the caller can'tread). Staying fail-open, a team with no connected source returns``available=false`` rather than the 4xx the curated read endpoints raise.++Writing is the opposite of fail-open: it refuses to edit a malformed file rather+than silently drop entries, opens a tracking issue plus a PR through the team's+GitHub App, and re-renders the file byte-for-byte the way ``core.render`` (and+therefore ``hogli test:quarantine add``) would — locked by a golden test — so the+bot's diff is indistinguishable from a human's. The file stays the single source+of truth; CI enforcement never reads anything but the committed bytes."""import re@@ -26,9 +32,11 @@ from django.conf import settingsfrom django.core.cache import cacheimport requests+import structlogfrom posthog.hogql import ast+from posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.team import Teamfrom products.engineering_analytics.backend.facade.contracts import (@@ -37,14 +45,21 @@ from products.engineering_analytics.backend.facade.contracts import (QuarantineFile,QuarantineLifecycle,QuarantineMode,+ QuarantineRequest,+ QuarantineRequestAction,+ QuarantineRequestResult,QuarantineSelectorKind,+ QuarantineWriteError,RepoRef,)from products.engineering_analytics.backend.logic.queries import _curated+from products.engineering_analytics.backend.logic.sources import list_github_sourcesif TYPE_CHECKING:from posthog.rbac.user_access_control import UserAccessControl+logger = structlog.get_logger(__name__)+QUARANTINE_FILENAME = ".test_quarantine.json"_SCHEMA_VERSION = 1@@ -262,6 +277,24 @@ def _most_active_repo(return str(owner), str(name)+def _repo_is_connected(+ team: Team,+ owner: str,+ name: str,+ *,+ user_access_control: "UserAccessControl | None" = None,+) -> bool:+ """True when ``owner/name`` is one of the team's connected GitHub sources — the authorization+ set for a client-supplied write repo override. Reads the same connected-source list the read+ endpoint surfaces, so a connected-but-quiet repo still qualifies and a deleted source's repo+ does not. A team with no connected source has none, so this is False."""+ target = f"{owner}/{name}".lower()+ return any(+ source.repo.lower() == target+ for source in list_github_sources(team=team, user_access_control=user_access_control)+ )++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@@ -310,3 +343,346 @@ def _unavailable(generated_at: datetime, *, repo: RepoRef | None = None, error:source_url="",generated_at=generated_at,)+++# ----------------------------------------------------------------------------+# Write side: edit `.test_quarantine.json` via a GitHub PR + tracking issue.+#+# Mirrors the CLI's limits so a UI-opened PR passes the same `quarantine check`:+# at most 30 days of quarantine, defaulting to 14 (see core.MAX_QUARANTINE_DAYS /+# the `add --days` default). Everything below is one deep operation behind+# `request_quarantine` — the facade, view, and UI never see a SHA or a branch.+# ----------------------------------------------------------------------------++_MAX_QUARANTINE_DAYS = 30+_DEFAULT_QUARANTINE_DAYS = 14+++def request_quarantine(+ *,+ team: Team,+ request: QuarantineRequest,+ user_access_control: "UserAccessControl | None" = None,+) -> QuarantineRequestResult:+ """Open a PR (and, for a new quarantine, a tracking issue) that edits the repo's+ ``.test_quarantine.json``. Raises ``QuarantineWriteError`` with a user-safe message+ for anything the caller can fix (App not installed, malformed file, GitHub failure).+ """+ selector = request.selector.strip()+ if not selector:+ raise QuarantineWriteError("A test selector is required.")++ try:+ return _open_quarantine_pr(+ team=team,+ selector=selector,+ request=request,+ user_access_control=user_access_control,+ )+ except QuarantineWriteError:+ # Already a user-safe message — let it through to the 400 the view renders.+ raise+ except Exception as exc:+ # Everything that can throw past this point is a GitHub integration call (the pure+ # render/parse helpers only ever raise QuarantineWriteError, caught above). Those+ # raise a grab-bag of plain Exception/ValueError/KeyError/GitHubIntegrationError that+ # would otherwise escape handle_exception as a 500. Collapse them into a user-safe 400+ # and keep the real cause in the logs.+ logger.warning("quarantine_write_failed", team_id=team.pk, exc_info=exc)+ raise QuarantineWriteError(+ "Couldn't open the quarantine pull request — GitHub returned an unexpected error. "+ "The App may have lost access to the repository; check its installation and try again."+ ) from exc+++def _open_quarantine_pr(+ *,+ team: Team,+ selector: str,+ request: QuarantineRequest,+ user_access_control: "UserAccessControl | None" = None,+) -> QuarantineRequestResult:+ github, owner, name = _resolve_write_target(team, request.repo, user_access_control=user_access_control)+ default_branch = github.get_default_branch(name)+ current = github.get_file_contents(name, QUARANTINE_FILENAME, ref=default_branch)+ entries, extras = _load_writable(current["content"] if current else None)++ if request.operation == QuarantineRequestAction.REMOVE:+ remaining = _remove_entry(entries, selector)+ if len(remaining) == len(entries):+ raise QuarantineWriteError(f"'{selector}' is not quarantined — nothing to remove.")+ new_entries, issue_url = remaining, ""+ commit_message = f"chore(ci): unquarantine {selector}"+ pr_body = _remove_pr_body(selector, request)+ else:+ today = datetime.now(UTC).date()+ expires = request.expires or today + timedelta(days=_DEFAULT_QUARANTINE_DAYS)+ _validate_quarantine_inputs(request, today=today, expires=expires)++ # A new quarantine files its own issue; an extend carries the existing one forward.+ if request.operation == QuarantineRequestAction.QUARANTINE:+ issue_url = _open_tracking_issue(github, name, owner, selector, request, expires)+ else:+ issue_url = request.issue++ new_entry = _canonical_entry(+ {+ "id": selector,+ "runner": _DEFAULT_RUNNER,+ "reason": request.reason.strip(),+ "owner": request.owner.strip(),+ "issue": issue_url,+ "added": today.isoformat(),+ "expires": expires.isoformat(),+ "mode": request.mode.value,+ }+ )+ new_entries = _upsert_entry(entries, new_entry)+ verb = "quarantine" if request.operation == QuarantineRequestAction.QUARANTINE else "extend quarantine for"+ commit_message = f"chore(ci): {verb} {selector}"+ pr_body = _quarantine_pr_body(selector, request, expires, issue_url)++ content = render_quarantine_file(new_entries, extras)+ branch = _branch_for(request.operation, selector)+ pr_url = _commit_and_open_pr(+ github,+ name,+ default_branch=default_branch,+ branch=branch,+ content=content,+ commit_message=commit_message,+ pr_title=commit_message,+ pr_body=pr_body,+ )+ # Only a new quarantine files an issue; extend reuses the entry's existing one and+ # remove files none, so the result surfaces a fresh issue only for `quarantine`.+ filed_issue_url = issue_url if request.operation == QuarantineRequestAction.QUARANTINE else ""+ return QuarantineRequestResult(pr_url=pr_url, issue_url=filed_issue_url, branch=branch)+++def _validate_quarantine_inputs(request: QuarantineRequest, *, today: date, expires: date) -> None:+ if expires <= today:+ raise QuarantineWriteError("The expiry date must be in the future.")+ max_expiry = today + timedelta(days=_MAX_QUARANTINE_DAYS)+ if expires > max_expiry:+ raise QuarantineWriteError(+ f"A quarantine can last at most {_MAX_QUARANTINE_DAYS} days (until {max_expiry.isoformat()})."+ )+ if not request.reason.strip():+ raise QuarantineWriteError("A reason is required to quarantine a test.")+ if not request.owner.strip():+ raise QuarantineWriteError("An owning team or person is required.")+++def _resolve_write_target(+ team: Team,+ repo: str | None,+ *,+ user_access_control: "UserAccessControl | None" = None,+) -> tuple[GitHubIntegration, str, str]:+ """Resolve the target ``(integration, owner, name)`` or raise a user-safe error.+ Writing needs the App installed on the repo's org, so a mismatch fails loudly+ instead of silently opening a PR on the wrong repo."""+ if repo is not None:+ owner, _, name = repo.partition("/")+ else:+ resolved = _most_active_repo(team, user_access_control=user_access_control)+ if resolved is None:+ raise QuarantineWriteError(+ "Couldn't tell which repository to quarantine in — no workflow runs in the last 30 days. "+ "Pass an explicit owner/name."+ )+ owner, name = resolved+ if not (_REPO_PART_RE.fullmatch(owner) and _REPO_PART_RE.fullmatch(name)):+ raise QuarantineWriteError(+ f"Invalid repository {(repo or f'{owner}/{name}')!r}: expected an 'owner/name' slug."+ )+ # An explicit repo is client-controlled. The org check below only proves the App lives on+ # that org — without this gate a caller could aim the App's write token at any repo in the+ # install's org. Constrain it to a repo the team has connected as a GitHub source; the default+ # path is already constrained because _most_active_repo only returns the team's own repos.+ if repo is not None and not _repo_is_connected(team, owner, name, user_access_control=user_access_control):+ raise QuarantineWriteError(+ f"'{owner}/{name}' isn't one of this team's connected GitHub repositories — "+ "connect it as a GitHub source to quarantine there."+ )++ integration_row = Integration.objects.filter(team=team, kind="github").first()+ if integration_row is None:+ raise QuarantineWriteError("Connect a GitHub integration with write access to quarantine tests from here.")+ github = GitHubIntegration(integration_row)+ installed_org = github.organization()+ if installed_org.lower() != owner.lower():+ raise QuarantineWriteError(+ f"The connected GitHub App is installed on '{installed_org}', not '{owner}'. "+ f"Install it on {owner}/{name} to quarantine there."+ )+ return github, owner, name+++def _open_tracking_issue(+ github: GitHubIntegration, repository: str, owner: str, selector: str, request: QuarantineRequest, expires: date+) -> str:+ result = github.create_issue(+ {+ "title": f"Flaky test quarantined: {selector}",+ "body": _issue_body(selector, request, expires),+ "repository": repository,+ }+ )+ # create_issue returns only number + repository; the org is the App's install account.+ return f"https://github.com/{owner}/{repository}/issues/{result['number']}"+++def _commit_and_open_pr(+ github: GitHubIntegration,+ repository: str,+ *,+ default_branch: str,+ branch: str,+ content: str,+ commit_message: str,+ pr_title: str,+ pr_body: str,+) -> str:+ branch_result = github.create_branch(repository, branch, default_branch)+ if not branch_result.get("success"):+ raise QuarantineWriteError(f"Couldn't create the quarantine branch: {branch_result.get('error', 'unknown')}")+ # The branch was just cut from the default tip, so update_file's auto-fetched SHA is+ # current — committing to a unique branch sidesteps any stale-SHA race by construction.+ update_result = github.update_file(repository, QUARANTINE_FILENAME, content, commit_message, branch)+ if not update_result.get("success"):+ raise QuarantineWriteError(f"Couldn't commit the quarantine change: {update_result.get('error', 'unknown')}")+ pr_result = github.create_pull_request(repository, pr_title, pr_body, branch, default_branch)+ if not pr_result.get("success"):+ raise QuarantineWriteError(f"Couldn't open the quarantine PR: {pr_result.get('error', 'unknown')}")+ return pr_result["pr_url"]+++def _branch_for(action: QuarantineRequestAction, selector: str) -> str:+ slug = re.sub(r"[^A-Za-z0-9._-]+", "-", selector).strip("-")[:60] or "test"+ stamp = datetime.now(UTC).strftime("%Y%m%d%H%M%S")+ prefix = "unquarantine" if action == QuarantineRequestAction.REMOVE else "quarantine"+ return f"{prefix}/{slug}-{stamp}"+++# --- File model: edit raw entry dicts, render byte-identical to core.render ---+++def _load_writable(text: str | None) -> tuple[list[dict], dict]:+ """Parse the file into canonical entry dicts plus any top-level extras. Unlike the+ read path this is fail-closed: a malformed file aborts the write so we never produce+ a bad diff or drop a sibling entry."""+ if text is None:+ return [], {}+ try:+ data = json.loads(text)+ except json.JSONDecodeError as exc:+ raise QuarantineWriteError(f"The quarantine file isn't valid JSON ({exc}); fix it before editing here.")+ if not isinstance(data, dict) or data.get("version") != _SCHEMA_VERSION:+ raise QuarantineWriteError("The quarantine file is malformed or an unsupported version; fix it before editing.")+ raw_entries = data.get("entries")+ if not isinstance(raw_entries, list):+ raise QuarantineWriteError("The quarantine file's 'entries' must be a list; fix it before editing.")+ extras = {k: v for k, v in data.items() if k not in ("version", "entries")}+ return [_canonical_entry(raw) for raw in raw_entries], extras+++def _canonical_entry(raw: object) -> dict:+ """Re-key one entry into the on-disk order ``core._entry_to_dict`` uses: required+ fields, then ``issue`` only when set, then any unknown fields sorted. Normalizes+ dates through ``date.fromisoformat`` so output matches the CLI byte-for-byte."""+ if not isinstance(raw, dict):+ raise QuarantineWriteError("The quarantine file has a non-object entry; fix it before editing.")+ try:+ out = {+ "id": raw["id"],+ "runner": raw.get("runner", _DEFAULT_RUNNER),+ "reason": raw.get("reason", ""),+ "owner": raw.get("owner", ""),+ **({"issue": raw["issue"]} if raw.get("issue") else {}),+ "added": date.fromisoformat(raw["added"]).isoformat(),+ "expires": date.fromisoformat(raw["expires"]).isoformat(),+ "mode": raw.get("mode", QuarantineMode.RUN.value),+ }+ except (KeyError, TypeError, ValueError) as exc:+ raise QuarantineWriteError(+ f"The quarantine file has a malformed entry ({raw.get('id', '?')}); fix it before editing."+ ) from exc+ out.update(sorted((k, v) for k, v in raw.items() if k not in _ENTRY_FIELDS))+ return out+++def _upsert_entry(entries: list[dict], new_entry: dict) -> list[dict]:+ """Replace any entry with the same (id, runner) — matching the CLI's `add` — then append."""+ key = (new_entry["id"], new_entry["runner"])+ return [e for e in entries if (e["id"], e["runner"]) != key] + [new_entry]+++def _remove_entry(entries: list[dict], selector: str) -> list[dict]:+ """Drop the selector for every runner, matching the CLI's `remove`."""+ return [e for e in entries if e["id"] != selector]+++def render_quarantine_file(entries: list[dict], extras: dict) -> str:+ """Serialize to the canonical on-disk form (``version`` then extras then ``entries``+ sorted by id+runner, 4-space indent, trailing newline). Byte-identical to+ ``core.render``; the golden test in ``test_quarantine.py`` keeps it that way."""+ payload: dict = {"version": _SCHEMA_VERSION, **extras}+ payload["entries"] = sorted(entries, key=lambda e: (e["id"], e["runner"]))+ return json.dumps(payload, indent=4) + "\n"+++# --- Issue / PR copy ---++# Surfaced on every quarantine so reviewers know it isn't a fix and doesn't take+# effect on in-flight runs.+_GATE_FRESHNESS_NOTE = (+ "Note: a quarantine only affects CI runs that start after this PR merges; runs already in flight are unaffected."+)+++def _issue_body(selector: str, request: QuarantineRequest, expires: date) -> str:+ mode_line = (+ "runs but cannot fail the suite (xfail)"+ if request.mode == QuarantineMode.RUN+ else "is skipped entirely (not collected)"+ )+ return "\n".join(+ [+ f"`{selector}` was quarantined because it is flaky.",+ "",+ f"- **Owner:** {request.owner.strip() or '_unassigned_'}",+ f"- **Reason:** {request.reason.strip() or '_none given_'}",+ f"- **Mode:** the test {mode_line}.",+ f"- **Expires:** {expires.isoformat()} — after which it blocks CI again unless the quarantine is extended.",+ "",+ "Keep this issue open until the test is fixed and its quarantine entry removed; "+ "this is the durable record of the flake, not the quarantine PR.",+ "",+ _GATE_FRESHNESS_NOTE,+ ]+ )+++def _quarantine_pr_body(selector: str, request: QuarantineRequest, expires: date, issue_url: str) -> str:+ verb = "Quarantines" if request.operation == QuarantineRequestAction.QUARANTINE else "Extends the quarantine for"+ lines = [+ f"{verb} the flaky test `{selector}` in `{QUARANTINE_FILENAME}` until {expires.isoformat()}.",+ "",+ f"- **Reason:** {request.reason.strip()}",+ f"- **Owner:** {request.owner.strip()}",+ ]+ if issue_url:+ # Tracked, not Closed: the issue must outlive this PR and close only when the test is fixed.+ lines.append(f"- **Tracked in:** {issue_url}")+ lines += ["", _GATE_FRESHNESS_NOTE]+ return "\n".join(lines)+++def _remove_pr_body(selector: str, request: QuarantineRequest) -> str:+ lines = [f"Removes `{selector}` from `{QUARANTINE_FILENAME}` so it gates CI normally again."]+ if request.issue:+ lines += ["", f"- **Tracking issue:** {request.issue}"]+ lines += ["", _GATE_FRESHNESS_NOTE]+ return "\n".join(lines)diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.pyindex 739ae8e338c5..187b34b806d2 100644--- a/products/engineering_analytics/backend/presentation/serializers.py+++ b/products/engineering_analytics/backend/presentation/serializers.py@@ -22,6 +22,8 @@ from products.engineering_analytics.backend.facade.contracts import (PullRequestListItem,QuarantineEntry,QuarantineFile,+ QuarantineRequest,+ QuarantineRequestResult,RepoRef,RunCost,WorkflowCost,@@ -392,6 +394,69 @@ class QuarantineFileSerializer(DataclassSerializer):}+class QuarantineRequestSerializer(DataclassSerializer):+ class Meta:+ dataclass = QuarantineRequest+ extra_kwargs = {+ "operation": {+ "help_text": "What to do: 'quarantine' (add or replace an entry and file a tracking issue), 'extend' "+ "(re-stamp an existing entry's expiry, reusing its issue), or 'remove' (delete the entry). All three "+ "open a pull request.",+ },+ "selector": {+ "help_text": "Test selector to act on: an exact test id, a file, a directory, a class prefix, or "+ "'product:<dashed-name>'.",+ },+ "repo": {+ "help_text": "Optional 'owner/name' repository override; defaults to the team's most active repo.",+ "allow_null": True,+ "required": False,+ },+ # Blank is meaningful: remove sends no reason/owner, and quarantine sends no issue+ # (the server files one). Per-action required checks live in the logic layer.+ "reason": {+ "help_text": "Why the test is quarantined. Required for quarantine and extend; ignored by remove.",+ "required": False,+ "allow_blank": True,+ },+ "owner": {+ "help_text": "GitHub team or user handle responsible for the fix, e.g. '@PostHog/team-x'. Required "+ "for quarantine and extend.",+ "required": False,+ "allow_blank": True,+ },+ "issue": {+ "help_text": "Existing tracking issue URL, carried forward on extend and remove. Ignored by "+ "quarantine, which files a fresh issue.",+ "required": False,+ "allow_blank": True,+ },+ "expires": {+ "help_text": "ISO date the quarantine expires (at most 30 days out). Defaults to 14 days from today. "+ "Ignored by remove.",+ "allow_null": True,+ "required": False,+ },+ "mode": {+ "help_text": "'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all). "+ "Defaults to 'run'.",+ "required": False,+ },+ }+++class QuarantineRequestResultSerializer(DataclassSerializer):+ class Meta:+ dataclass = QuarantineRequestResult+ extra_kwargs = {+ "pr_url": {"help_text": "URL of the opened pull request that edits the quarantine file."},+ "issue_url": {+ "help_text": "URL of the tracking issue filed for a new quarantine; empty for extend and remove.",+ },+ "branch": {"help_text": "Branch the pull request was opened from."},+ }++class WorkflowHealthBucketSerializer(DataclassSerializer):class Meta:dataclass = WorkflowHealthBucketdiff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.pyindex 92a9fa41a697..abdbd70d06d4 100644--- a/products/engineering_analytics/backend/presentation/views.py+++ b/products/engineering_analytics/backend/presentation/views.py@@ -18,10 +18,15 @@ from rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.mixins import TypedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom products.engineering_analytics.backend.facade import api-from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError+from products.engineering_analytics.backend.facade.contracts import (+ GitHubSourceNotConnectedError,+ QuarantineRequest,+ QuarantineWriteError,+)from products.engineering_analytics.backend.presentation.serializers import (CICardSummarySerializer,GitHubSourceSerializer,@@ -29,6 +34,8 @@ from products.engineering_analytics.backend.presentation.serializers import (PRLifecycleSerializer,PullRequestListSerializer,QuarantineFileSerializer,+ QuarantineRequestResultSerializer,+ QuarantineRequestSerializer,WorkflowHealthItemSerializer,WorkflowJobSerializer,WorkflowRunDetailSerializer,@@ -127,12 +134,16 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe"workflow_runner_costs","workflow_jobs",]- scope_object_write_actions: list[str] = []+ scope_object_write_actions: list[str] = ["quarantine_request"]def handle_exception(self, exc: Exception) -> Response:- # No GitHub warehouse source connected — every action degrades the same way.+ # No GitHub warehouse source connected — every read action degrades the same way.if isinstance(exc, GitHubSourceNotConnectedError):return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)+ # A quarantine write that can't proceed (App not installed, malformed file, GitHub+ # failure) — the message is user-safe and explains what to fix.+ if isinstance(exc, QuarantineWriteError):+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)return super().handle_exception(exc)@extend_schema(@@ -609,3 +620,32 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSeexcept ValueError as exc:return _bad_request(exc, fallback="Invalid repo or source_id")return Response(QuarantineFileSerializer(instance=result).data)++ @validated_request(+ request_serializer=QuarantineRequestSerializer,+ operation_id="engineering_analytics_quarantine_request",+ responses={+ 201: OpenApiResponse(+ response=QuarantineRequestResultSerializer,+ description="The opened pull request, plus the tracking issue for a new quarantine.",+ ),+ 400: OpenApiResponse(+ description="Invalid input, or the write could not be completed (no GitHub App installed on the "+ "repo's org, a malformed quarantine file, or a GitHub failure). The detail message is safe to show."+ ),+ },+ summary="Quarantine, extend, or unquarantine a flaky test",+ description=(+ "Opens a pull request that edits the repository's checked-in .test_quarantine.json — and, for a new "+ "quarantine, a tracking issue the PR links but does not close. The file stays the source of truth that "+ "CI enforces; this never bypasses it. A quarantine only affects CI runs that start after the PR merges."+ ),+ )+ @action(detail=False, methods=["post"], url_path="quarantine/request", pagination_class=None)+ def quarantine_request(self, request: TypedRequest[QuarantineRequest], **kwargs) -> Response:+ result = api.request_quarantine(+ team=self.team,+ request=request.validated_data,+ user_access_control=self.user_access_control,+ )+ return Response(QuarantineRequestResultSerializer(instance=result).data, status=status.HTTP_201_CREATED)diff --git a/products/engineering_analytics/backend/tests/test_access_control.py b/products/engineering_analytics/backend/tests/test_access_control.pyindex 9bae17292a94..55d182bab89b 100644--- a/products/engineering_analytics/backend/tests/test_access_control.py+++ b/products/engineering_analytics/backend/tests/test_access_control.py@@ -119,6 +119,45 @@ class TestEngineeringAnalyticsAccessControl(WarehouseAccessControlTestMixin):assert response.status_code == status.HTTP_200_OKassert str(self.source_b.id) in {source["id"] for source in response.json()}+ def test_denied_user_cannot_write_quarantine_to_source_b(self) -> None:+ ExternalDataSource.objects.filter(pk=self.source_b.pk).update(job_inputs={"repository": "PostHog/secret"})+ github = mock.Mock()+ github.organization.return_value = "PostHog"+ github.get_default_branch.return_value = "master"+ github.get_file_contents.return_value = None+ github.create_issue.return_value = {"number": 4242, "repository": "secret"}+ github.create_branch.return_value = {"success": True, "sha": "branchsha"}+ github.update_file.return_value = {"success": True, "commit_sha": "commitsha"}+ github.create_pull_request.return_value = {+ "success": True,+ "pr_url": "https://github.com/PostHog/secret/pull/99",+ }++ self.client.force_login(self.no_access_user)+ with (+ mock.patch(+ "products.engineering_analytics.backend.logic.quarantine.GitHubIntegration", return_value=github+ ),+ mock.patch("products.engineering_analytics.backend.logic.quarantine.Integration") as integration_cls,+ ):+ integration_cls.objects.filter.return_value.first.return_value = object()+ response = self.client.post(+ self._url("quarantine/request"),+ {+ "operation": "quarantine",+ "selector": "posthog/api/test/test_foo.py::TestFoo::test_bar",+ "repo": "PostHog/secret",+ "reason": "flaky",+ "owner": "@PostHog/team-foo",+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "connected GitHub repositories" in response.json()["detail"]+ github.create_issue.assert_not_called()+ github.create_branch.assert_not_called()+@pytest.mark.eeclass TestEngineeringAnalyticsWarehouseAcl(WarehouseAccessControlTestMixin):diff --git a/products/engineering_analytics/backend/tests/test_quarantine.py b/products/engineering_analytics/backend/tests/test_quarantine.pyindex 8291ae22b5e6..f547477b07f2 100644--- a/products/engineering_analytics/backend/tests/test_quarantine.py+++ b/products/engineering_analytics/backend/tests/test_quarantine.py@@ -19,10 +19,15 @@ from rest_framework import statusfrom products.engineering_analytics.backend.facade import contractsfrom products.engineering_analytics.backend.logic.quarantine import (QUARANTINE_FILENAME,+ _canonical_entry,_lifecycle_for,+ _remove_entry,_selector_kind,+ _upsert_entry,build_quarantine,parse_quarantine_text,+ render_quarantine_file,+ request_quarantine,)_TODAY = date(2026, 6, 12)@@ -30,6 +35,28 @@ _REQUESTS_GET = "products.engineering_analytics.backend.logic.quarantine.request_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"+_Q = "products.engineering_analytics.backend.logic.quarantine"++# The exact bytes core.render (and therefore `hogli test:quarantine add`) writes for one+# full entry: version, then entries sorted by id, 4-space indent, trailing newline. If this+# breaks, the bot's PR diff would diverge from a human's and `quarantine check` could flag it.+_GOLDEN_ONE = (+ "{\n"+ ' "version": 1,\n'+ ' "entries": [\n'+ " {\n"+ ' "id": "a/b.py::T::t",\n'+ ' "runner": "pytest",\n'+ ' "reason": "flaky",\n'+ ' "owner": "@PostHog/team-foo",\n'+ ' "issue": "https://github.com/PostHog/posthog/issues/1",\n'+ ' "added": "2026-06-01",\n'+ ' "expires": "2026-06-20",\n'+ ' "mode": "run"\n'+ " }\n"+ " ]\n"+ "}\n"+)def _curated_source(results: list[tuple[str, str]]) -> mock.Mock:@@ -71,6 +98,38 @@ def _response(status_code: int = 200, text: str = "", headers: dict[str, str] |return response+def _github_mock(**overrides: Any) -> mock.Mock:+ github = mock.Mock()+ github.organization.return_value = "PostHog"+ github.get_default_branch.return_value = "master"+ github.get_file_contents.return_value = None+ github.create_issue.return_value = {"number": 4242, "repository": "posthog"}+ github.create_branch.return_value = {"success": True, "sha": "branchsha"}+ github.update_file.return_value = {"success": True, "commit_sha": "commitsha"}+ github.create_pull_request.return_value = {+ "success": True,+ "pr_url": "https://github.com/PostHog/posthog/pull/99",+ }+ for name, value in overrides.items():+ getattr(github, name).return_value = value+ return github+++def _request(**overrides: Any) -> contracts.QuarantineRequest:+ fields: dict[str, Any] = {+ "operation": contracts.QuarantineRequestAction.QUARANTINE,+ "selector": "posthog/api/test/test_foo.py::TestFoo::test_bar",+ "repo": "PostHog/posthog",+ "reason": "flaky under shards",+ "owner": "@PostHog/team-foo",+ "issue": "",+ "expires": None,+ "mode": contracts.QuarantineMode.RUN,+ }+ fields.update(overrides)+ return contracts.QuarantineRequest(**fields)++class TestQuarantineParse(TestCase):def test_parses_valid_file_and_applies_defaults(self) -> None:full = _entry()@@ -344,3 +403,290 @@ class TestQuarantineAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert get.call_args.kwargs["repo"] == "PostHog/posthog.com"assert get.call_args.kwargs["team"] == self.team+++class TestQuarantineRender(TestCase):+ def test_render_matches_core_byte_for_byte(self) -> None:+ entry = _canonical_entry(+ {+ "id": "a/b.py::T::t",+ "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",+ }+ )+ assert render_quarantine_file([entry], {}) == _GOLDEN_ONE++ def test_render_round_trips_through_the_read_parser(self) -> None:+ entry = _canonical_entry(_entry())+ text = render_quarantine_file([entry], {})+ parsed, errors, warnings = parse_quarantine_text(text, _TODAY)+ assert errors == [] and warnings == []+ assert parsed[0].id == _entry()["id"]++ def test_empty_issue_is_omitted(self) -> None:+ entry = _canonical_entry(_entry(issue=""))+ assert "issue" not in entry+ assert '"issue"' not in render_quarantine_file([entry], {})++ def test_unknown_fields_and_top_level_extras_are_preserved_sorted(self) -> None:+ entry = _canonical_entry(_entry(zeta="z", alpha="a"))+ keys = list(entry.keys())+ assert keys[-2:] == ["alpha", "zeta"]+ rendered = render_quarantine_file([entry], {"generated_by": "test"})+ assert json.loads(rendered)["generated_by"] == "test"++ def test_render_sorts_entries_by_id_then_runner(self) -> None:+ first = _canonical_entry(_entry(id="a/z.py"))+ second = _canonical_entry(_entry(id="a/a.py"))+ rendered = render_quarantine_file([first, second], {})+ ids = [e["id"] for e in json.loads(rendered)["entries"]]+ assert ids == ["a/a.py", "a/z.py"]++ @parameterized.expand(+ [+ ("missing_id", {"added": "2026-06-01", "expires": "2026-06-20"}),+ ("bad_date", {"id": "x", "added": "nope", "expires": "2026-06-20"}),+ ("not_an_object", "just a string"),+ ]+ )+ def test_canonical_entry_rejects_malformed(self, _name: str, raw: Any) -> None:+ with self.assertRaises(contracts.QuarantineWriteError):+ _canonical_entry(raw)++ def test_upsert_replaces_same_id_and_runner(self) -> None:+ existing = _canonical_entry(_entry(reason="old"))+ replacement = _canonical_entry(_entry(reason="new"))+ result = _upsert_entry([existing], replacement)+ assert len(result) == 1 and result[0]["reason"] == "new"++ def test_remove_drops_selector_across_runners(self) -> None:+ keep = _canonical_entry(_entry(id="other"))+ drop = _canonical_entry(_entry())+ result = _remove_entry([keep, drop], _entry()["id"])+ assert [e["id"] for e in result] == ["other"]+++class TestQuarantineRequest(BaseTest):+ def _install(self, github: mock.Mock, *, has_integration: bool = True, connected: bool = True) -> mock.Mock:+ gh_patch = mock.patch(f"{_Q}.GitHubIntegration", return_value=github)+ integration_patch = mock.patch(f"{_Q}.Integration")+ # The explicit repo override is authorized against the team's connected GitHub sources;+ # mock that list so the real _repo_is_connected runs against a matching source (or none).+ sources = [SimpleNamespace(repo="PostHog/posthog")] if connected else []+ sources_patch = mock.patch(f"{_Q}.list_github_sources", return_value=sources)+ gh_patch.start()+ integration_cls = integration_patch.start()+ sources_patch.start()+ self.addCleanup(gh_patch.stop)+ self.addCleanup(integration_patch.stop)+ self.addCleanup(sources_patch.stop)+ integration_cls.objects.filter.return_value.first.return_value = object() if has_integration else None+ return github++ @freeze_time("2026-06-12")+ def test_quarantine_opens_issue_then_pr_and_writes_canonical_entry(self) -> None:+ github = self._install(_github_mock())+ result = request_quarantine(team=self.team, request=_request())++ assert result.issue_url == "https://github.com/PostHog/posthog/issues/4242"+ assert result.pr_url == "https://github.com/PostHog/posthog/pull/99"+ assert result.branch.startswith("quarantine/")++ github.create_issue.assert_called_once()+ issue_config = github.create_issue.call_args.args[0]+ assert _request().selector in issue_config["title"] and issue_config["repository"] == "posthog"++ committed = github.update_file.call_args.args[2]+ entry = json.loads(committed)["entries"][0]+ assert entry["id"] == _request().selector+ assert entry["mode"] == "run"+ assert entry["expires"] == "2026-06-26"+ assert entry["issue"] == "https://github.com/PostHog/posthog/issues/4242"+ assert github.create_pull_request.call_args.args[3] == result.branch # head branch+ assert github.create_pull_request.call_args.args[4] == "master" # base branch++ @freeze_time("2026-06-12")+ def test_skip_mode_is_persisted(self) -> None:+ github = self._install(_github_mock())+ request_quarantine(team=self.team, request=_request(mode=contracts.QuarantineMode.SKIP))+ entry = json.loads(github.update_file.call_args.args[2])["entries"][0]+ assert entry["mode"] == "skip"++ @freeze_time("2026-06-12")+ def test_extend_reuses_existing_issue_and_files_no_new_one(self) -> None:+ existing = _text(_entry(expires="2026-06-15", issue="https://github.com/PostHog/posthog/issues/7"))+ github = self._install(_github_mock(get_file_contents={"content": existing, "sha": "s"}))+ result = request_quarantine(+ team=self.team,+ request=_request(+ operation=contracts.QuarantineRequestAction.EXTEND,+ selector=_entry()["id"],+ issue="https://github.com/PostHog/posthog/issues/7",+ expires=date(2026, 6, 25),+ ),+ )+ github.create_issue.assert_not_called()+ assert result.issue_url == ""+ entry = json.loads(github.update_file.call_args.args[2])["entries"][0]+ assert entry["expires"] == "2026-06-25"+ assert entry["issue"] == "https://github.com/PostHog/posthog/issues/7"++ def test_remove_drops_the_entry_without_an_issue(self) -> None:+ github = self._install(_github_mock(get_file_contents={"content": _text(_entry()), "sha": "s"}))+ result = request_quarantine(+ team=self.team,+ request=_request(operation=contracts.QuarantineRequestAction.REMOVE, selector=_entry()["id"]),+ )+ github.create_issue.assert_not_called()+ assert result.issue_url == "" and result.branch.startswith("unquarantine/")+ assert json.loads(github.update_file.call_args.args[2])["entries"] == []++ def test_remove_of_absent_entry_is_a_clear_error(self) -> None:+ github = self._install(_github_mock(get_file_contents={"content": _text(), "sha": "s"}))+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(+ team=self.team,+ request=_request(operation=contracts.QuarantineRequestAction.REMOVE, selector="not/there"),+ )+ github.create_branch.assert_not_called()++ def test_no_github_integration_is_a_clear_error(self) -> None:+ self._install(_github_mock(), has_integration=False)+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(team=self.team, request=_request())++ def test_app_installed_on_wrong_org_is_rejected(self) -> None:+ self._install(_github_mock(organization="SomeoneElse"))+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(team=self.team, request=_request())++ def test_explicit_repo_outside_the_team_is_rejected_before_any_write(self) -> None:+ # A client-supplied repo the team hasn't connected as a GitHub source must not get the+ # App's write token, even when it sits in the install's org.+ github = self._install(_github_mock(), connected=False)+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(team=self.team, request=_request(repo="PostHog/not-ours"))+ github.create_branch.assert_not_called()+ github.create_issue.assert_not_called()++ @parameterized.expand(+ [+ ("missing_token", ValueError("GitHub access token not configured")),+ ("api_failure", Exception("Failed to get default branch: HTTP 404")),+ ]+ )+ def test_github_failure_becomes_a_user_safe_error_not_a_500(self, _name: str, failure: Exception) -> None:+ # get_default_branch raises plain ValueError/Exception, not QuarantineWriteError; without+ # translation those escape as a 500 instead of the user-safe 400 the rest of the path gives.+ github = self._install(_github_mock())+ github.get_default_branch.side_effect = failure+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(team=self.team, request=_request())+ github.create_branch.assert_not_called()++ def test_malformed_existing_file_aborts_without_writing(self) -> None:+ github = self._install(_github_mock(get_file_contents={"content": "{ not json", "sha": "s"}))+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(team=self.team, request=_request())+ github.create_branch.assert_not_called()++ @parameterized.expand(+ [+ ("past", date(2026, 6, 1)),+ ("too_far", date(2026, 8, 1)),+ ]+ )+ @freeze_time("2026-06-12")+ def test_expiry_bounds_are_enforced(self, _name: str, expires: date) -> None:+ self._install(_github_mock())+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(team=self.team, request=_request(expires=expires))++ @parameterized.expand([("reason", {"reason": ""}), ("owner", {"owner": ""})])+ @freeze_time("2026-06-12")+ def test_quarantine_requires_reason_and_owner(self, _name: str, overrides: dict[str, Any]) -> None:+ self._install(_github_mock())+ with self.assertRaises(contracts.QuarantineWriteError):+ request_quarantine(team=self.team, request=_request(**overrides))+++class TestQuarantineRequestAPI(APIBaseTest):+ def _url(self) -> str:+ return f"/api/projects/{self.team.id}/engineering_analytics/quarantine/request/"++ def _body(self, **overrides: Any) -> dict[str, Any]:+ body: dict[str, Any] = {+ "operation": "quarantine",+ "selector": "posthog/api/test/test_foo.py::TestFoo::test_bar",+ "repo": "PostHog/posthog",+ "reason": "flaky",+ "owner": "@PostHog/team-foo",+ }+ body.update(overrides)+ return body++ def test_returns_201_with_pr_and_issue_links(self) -> None:+ result = contracts.QuarantineRequestResult(+ pr_url="https://github.com/PostHog/posthog/pull/99",+ issue_url="https://github.com/PostHog/posthog/issues/4242",+ branch="quarantine/foo-20260612",+ )+ with mock.patch(f"{_VIEWS}.request_quarantine", return_value=result) as called:+ response = self.client.post(self._url(), self._body(), format="json")++ assert response.status_code == status.HTTP_201_CREATED+ body = response.json()+ assert body["pr_url"].endswith("/pull/99")+ assert body["issue_url"].endswith("/issues/4242")+ assert called.call_args.kwargs["team"] == self.team+ assert called.call_args.kwargs["request"].selector == self._body()["selector"]++ @parameterized.expand(+ [+ # quarantine sends a blank issue (the server files one); remove sends no reason/owner.+ ("blank_issue_on_quarantine", {"issue": ""}),+ ("blank_reason_owner_on_remove", {"operation": "remove", "reason": "", "owner": "", "issue": ""}),+ ]+ )+ def test_blank_optional_strings_reach_the_facade(self, _name: str, overrides: dict[str, Any]) -> None:+ result = contracts.QuarantineRequestResult(pr_url="https://x/pull/1", issue_url="", branch="b")+ with mock.patch(f"{_VIEWS}.request_quarantine", return_value=result) as called:+ response = self.client.post(self._url(), self._body(**overrides), format="json")++ assert response.status_code == status.HTTP_201_CREATED+ called.assert_called_once()++ def test_write_error_becomes_400_with_detail(self) -> None:+ with mock.patch(+ f"{_VIEWS}.request_quarantine",+ side_effect=contracts.QuarantineWriteError("The connected GitHub App is installed on 'X', not 'PostHog'."),+ ):+ response = self.client.post(self._url(), self._body(), format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "not 'PostHog'" in response.json()["detail"]++ @parameterized.expand(+ [+ ("missing_selector", {"selector": None}),+ ("missing_action", {"operation": None}),+ ("bad_action", {"operation": "nuke"}),+ ]+ )+ def test_invalid_body_is_rejected(self, _name: str, overrides: dict[str, Any]) -> None:+ body = self._body()+ for key, value in overrides.items():+ if value is None:+ body.pop(key, None)+ else:+ body[key] = value+ with mock.patch(f"{_VIEWS}.request_quarantine") as called:+ response = self.client.post(self._url(), body, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ called.assert_not_called()diff --git a/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx b/products/engineering_analytics/frontend/components/QuarantineTestModal.tsxnew file mode 100644index 000000000000..62f0697d84cf--- /dev/null+++ b/products/engineering_analytics/frontend/components/QuarantineTestModal.tsx@@ -0,0 +1,199 @@+import { useEffect, useState } from 'react'++import { LemonButton, LemonInput, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'++import {+ QuarantineModalState,+ QuarantineSubmitInput,+ inferOwnerFromSelector,+} from '../scenes/engineeringAnalyticsLogic'++// Common flake categories (industry-standard buckets). 'Other' reveals a free-text field.+const REASON_OPTIONS = [+ 'Concurrency / race condition',+ 'Timing / timeout',+ 'Nondeterministic ordering or data',+ 'Test isolation / shared state',+ 'Eventual consistency / async wait',+ 'External dependency or network',+ 'Resource / environment',+]+const OTHER_REASON = 'Other'++// Mirrors the backend cap (core.MAX_QUARANTINE_DAYS); the server rejects anything further out.+const MAX_QUARANTINE_DAYS = 30+const DEFAULT_QUARANTINE_DAYS = 14++interface QuarantineTestModalProps {+ /** Null closes the modal; non-null seeds it for a quarantine or an extend. */+ modal: QuarantineModalState | null+ /** Owning teams already present in the quarantine file; the dropdown also accepts a custom value. */+ ownerOptions: string[]+ submitting: boolean+ onClose: () => void+ onSubmit: (input: QuarantineSubmitInput) => void+}++export function QuarantineTestModal({+ modal,+ ownerOptions,+ submitting,+ onClose,+ onSubmit,+}: QuarantineTestModalProps): JSX.Element {+ const isExtend = modal?.action === 'extend'++ const [selector, setSelector] = useState('')+ // A picked category, or OTHER_REASON when the reason is free-text (held in customReason).+ const [reasonChoice, setReasonChoice] = useState('')+ const [customReason, setCustomReason] = useState('')+ const [owner, setOwner] = useState('')+ const [expires, setExpires] = useState<dayjs.Dayjs | null>(dayjs().add(DEFAULT_QUARANTINE_DAYS, 'day'))++ // Reseed when a new modal opens; keyed on identity so background refreshes don't trample edits.+ useEffect(() => {+ if (!modal) {+ return+ }+ setSelector(modal.selector)+ // An existing reason that isn't one of the buckets falls into the 'Other' free-text path.+ const isKnown = REASON_OPTIONS.includes(modal.reason)+ setReasonChoice(modal.reason ? (isKnown ? modal.reason : OTHER_REASON) : '')+ setCustomReason(isKnown ? '' : modal.reason)+ // New quarantines suggest the owning team from a product selector; extend keeps the entry's owner.+ setOwner(modal.owner || (modal.action === 'extend' ? '' : inferOwnerFromSelector(modal.selector)))+ setExpires(dayjs().add(DEFAULT_QUARANTINE_DAYS, 'day'))+ }, [modal])++ const reason = reasonChoice === OTHER_REASON ? customReason.trim() : reasonChoice+ // Backend requires a future expiry within the cap; mirror that so submit can't 400.+ const expiresValid = !!expires && expires.isAfter(dayjs(), 'day')++ const canSubmit = !!selector.trim() && !!reason && !!owner.trim() && expiresValid+ const disabledReason = !selector.trim()+ ? 'A test selector is required'+ : !reason+ ? 'A reason is required'+ : !owner.trim()+ ? 'An owning team is required'+ : !expiresValid+ ? 'Pick an expiry date in the future'+ : undefined++ const handleSubmit = (): void => {+ if (!canSubmit || !modal || !expires) {+ return+ }+ onSubmit({+ action: modal.action,+ selector: selector.trim(),+ reason,+ owner: owner.trim(),+ issue: modal.issue,+ expires: expires.format('YYYY-MM-DD'),+ // Mode isn't editable here: new quarantines run as xfail; extend keeps the entry's mode.+ mode: modal.mode,+ })+ }++ return (+ <LemonModal+ isOpen={!!modal}+ onClose={onClose}+ title={isExtend ? 'Extend quarantine' : 'Quarantine a flaky test'}+ description={+ isExtend+ ? 'Re-stamps the expiry on an existing entry and opens a PR. It takes effect once the PR merges.'+ : 'Opens a tracking issue and a PR that masks this test in CI until its expiry. It takes effect once the PR merges.'+ }+ footer={+ <>+ <LemonButton type="secondary" onClick={onClose} data-attr="eng-analytics-quarantine-cancel">+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ loading={submitting}+ disabledReason={submitting ? 'Opening PR…' : disabledReason}+ onClick={handleSubmit}+ data-attr="eng-analytics-quarantine-confirm"+ >+ {isExtend ? 'Extend and open PR' : 'Quarantine and open PR'}+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ <div>+ <label className="mb-1 block text-sm font-medium">Test selector</label>+ {isExtend ? (+ <div className="rounded bg-surface-secondary px-2 py-1.5 font-mono text-xs text-secondary">+ {selector}+ </div>+ ) : (+ <LemonInput+ value={selector}+ onChange={setSelector}+ placeholder="posthog/path/test.py::TestClass::test_method or product:my-product"+ autoFocus+ />+ )}+ </div>++ <div>+ <label className="mb-1 block text-sm font-medium">Reason</label>+ <LemonSelect+ value={reasonChoice || null}+ onChange={(value) => setReasonChoice(value ?? '')}+ options={[+ ...REASON_OPTIONS.map((option) => ({ value: option, label: option })),+ { value: OTHER_REASON, label: 'Other…' },+ ]}+ placeholder="Select a reason"+ fullWidth+ data-attr="eng-analytics-quarantine-reason"+ />+ {reasonChoice === OTHER_REASON && (+ <LemonInput+ className="mt-2"+ value={customReason}+ onChange={setCustomReason}+ placeholder="Describe the reason"+ autoFocus+ />+ )}+ </div>++ <div>+ <label className="mb-1 block text-sm font-medium">Owner</label>+ <LemonInputSelect+ mode="single"+ allowCustomValues+ value={owner ? [owner] : []}+ onChange={(values) => setOwner(values[0] ?? '')}+ options={ownerOptions.map((option) => ({ key: option, label: option }))}+ placeholder="Select a team"+ data-attr="eng-analytics-quarantine-owner"+ />+ </div>++ <div>+ <label className="mb-1 block text-sm font-medium">Expires</label>+ <LemonCalendarSelectInput+ value={expires}+ onChange={setExpires}+ placeholder="Pick an expiry"+ clearable={false}+ selectionPeriod="upcoming"+ />+ <div className="mt-1 text-xs text-tertiary">+ At most {MAX_QUARANTINE_DAYS} days out. After this the test gates CI again unless extended.+ </div>+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 2ee5610b8705..b60d7691f644 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -409,6 +409,60 @@ export interface QuarantineFileApi {generated_at: string}+/**+ * * `quarantine` - QUARANTINE+ * * `extend` - EXTEND+ * * `remove` - REMOVE+ */+export type OperationEnumApi = (typeof OperationEnumApi)[keyof typeof OperationEnumApi]++export const OperationEnumApi = {+ Quarantine: 'quarantine',+ Extend: 'extend',+ Remove: 'remove',+} as const++export interface QuarantineRequestApi {+ /** What to do: 'quarantine' (add or replace an entry and file a tracking issue), 'extend' (re-stamp an existing entry's expiry, reusing its issue), or 'remove' (delete the entry). All three open a pull request.+ *+ * * `quarantine` - QUARANTINE+ * * `extend` - EXTEND+ * * `remove` - REMOVE */+ operation: OperationEnumApi+ /** Test selector to act on: an exact test id, a file, a directory, a class prefix, or 'product:<dashed-name>'. */+ selector: string+ /**+ * Optional 'owner/name' repository override; defaults to the team's most active repo.+ * @nullable+ */+ repo?: string | null+ /** Why the test is quarantined. Required for quarantine and extend; ignored by remove. */+ reason?: string+ /** GitHub team or user handle responsible for the fix, e.g. '@PostHog/team-x'. Required for quarantine and extend. */+ owner?: string+ /** Existing tracking issue URL, carried forward on extend and remove. Ignored by quarantine, which files a fresh issue. */+ issue?: string+ /**+ * ISO date the quarantine expires (at most 30 days out). Defaults to 14 days from today. Ignored by remove.+ * @nullable+ */+ expires?: string | null+ /** 'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all). Defaults to 'run'.+ *+ * * `run` - RUN+ * * `skip` - SKIP */+ mode?: QuarantineModeEnumApi+}++export interface QuarantineRequestResultApi {+ /** URL of the opened pull request that edits the quarantine file. */+ pr_url: string+ /** URL of the tracking issue filed for a new quarantine; empty for extend and remove. */+ issue_url: string+ /** Branch the pull request was opened from. */+ branch: string+}+export interface GitHubSourceApi {/** Source id — pass as `source_id` to the other endpoints to read this source. */id: stringdiff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex de40d784541c..99b5f5f6cc84 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -26,6 +26,8 @@ import type {PRLifecycleApi,PullRequestListApi,QuarantineFileApi,+ QuarantineRequestApi,+ QuarantineRequestResultApi,WorkflowHealthItemApi,WorkflowJobApi,WorkflowRunDetailApi,@@ -222,6 +224,27 @@ export const engineeringAnalyticsQuarantine = async (})}+export const getEngineeringAnalyticsQuarantineRequestUrl = (projectId: string) => {+ return `/api/projects/${projectId}/engineering_analytics/quarantine/request/`+}++/**+ * Opens a pull request that edits the repository's checked-in .test_quarantine.json — and, for a new quarantine, a tracking issue the PR links but does not close. The file stays the source of truth that CI enforces; this never bypasses it. A quarantine only affects CI runs that start after the PR merges.+ * @summary Quarantine, extend, or unquarantine a flaky test+ */+export const engineeringAnalyticsQuarantineRequest = async (+ projectId: string,+ quarantineRequestApi: QuarantineRequestApi,+ options?: RequestInit+): Promise<QuarantineRequestResultApi> => {+ return apiMutator<QuarantineRequestResultApi>(getEngineeringAnalyticsQuarantineRequestUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(quarantineRequestApi),+ })+}+export const getEngineeringAnalyticsSourcesUrl = (projectId: string) => {return `/api/projects/${projectId}/engineering_analytics/sources/`}diff --git a/products/engineering_analytics/frontend/generated/api.zod.ts b/products/engineering_analytics/frontend/generated/api.zod.tsindex e8a15d4e1b52..d6008206b204 100644--- a/products/engineering_analytics/frontend/generated/api.zod.ts+++ b/products/engineering_analytics/frontend/generated/api.zod.ts@@ -7,3 +7,55 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+import * as zod from 'zod'++/**+ * Opens a pull request that edits the repository's checked-in .test_quarantine.json — and, for a new quarantine, a tracking issue the PR links but does not close. The file stays the source of truth that CI enforces; this never bypasses it. A quarantine only affects CI runs that start after the PR merges.+ * @summary Quarantine, extend, or unquarantine a flaky test+ */+export const EngineeringAnalyticsQuarantineRequestBody = /* @__PURE__ */ zod.object({+ operation: zod+ .enum(['quarantine', 'extend', 'remove'])+ .describe('\* `quarantine` - QUARANTINE\n\* `extend` - EXTEND\n\* `remove` - REMOVE')+ .describe(+ "What to do: 'quarantine' (add or replace an entry and file a tracking issue), 'extend' (re-stamp an existing entry's expiry, reusing its issue), or 'remove' (delete the entry). All three open a pull request.\n\n\* `quarantine` - QUARANTINE\n\* `extend` - EXTEND\n\* `remove` - REMOVE"+ ),+ selector: zod+ .string()+ .describe(+ "Test selector to act on: an exact test id, a file, a directory, a class prefix, or 'product:<dashed-name>'."+ ),+ repo: zod+ .string()+ .nullish()+ .describe("Optional 'owner\/name' repository override; defaults to the team's most active repo."),+ reason: zod+ .string()+ .optional()+ .describe('Why the test is quarantined. Required for quarantine and extend; ignored by remove.'),+ owner: zod+ .string()+ .optional()+ .describe(+ "GitHub team or user handle responsible for the fix, e.g. '@PostHog\/team-x'. Required for quarantine and extend."+ ),+ issue: zod+ .string()+ .optional()+ .describe(+ 'Existing tracking issue URL, carried forward on extend and remove. Ignored by quarantine, which files a fresh issue.'+ ),+ expires: zod.iso+ .date()+ .nullish()+ .describe(+ 'ISO date the quarantine expires (at most 30 days out). Defaults to 14 days from today. Ignored by remove.'+ ),+ mode: zod+ .enum(['run', 'skip'])+ .describe('\* `run` - RUN\n\* `skip` - SKIP')+ .optional()+ .describe(+ "'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all). Defaults to 'run'.\n\n\* `run` - RUN\n\* `skip` - SKIP"+ ),+})diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsxindex e07004f82b93..d5c9082515ec 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx@@ -4,6 +4,7 @@ import { IconEllipsis, IconExternal, IconShieldLock } from '@posthog/icons'import {LemonBanner,LemonButton,+ LemonDialog,LemonInput,LemonInputSelect,LemonMenu,@@ -16,13 +17,12 @@ import {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 { QuarantineTestModal } from '../components/QuarantineTestModal'import { StatCard } from '../components/StatCard'import {QuarantineEntryRow,@@ -32,33 +32,6 @@ import {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'@@ -69,27 +42,19 @@ function relativeExpiry(daysUntilExpiry: number): string {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>- )+ return <LemonTag type="success">Active</LemonTag>case 'expiring_soon':- return (- <Tooltip title="Still masked in CI, but expires within 7 days.">- <LemonTag type="warning">Expiring</LemonTag>- </Tooltip>- )+ return <LemonTag type="warning">Expiring soon</LemonTag>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 title="Expired, but inside the 7-day grace — the quarantine check only warns for now.">+ <LemonTag type="warning">In 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 title="Expired beyond the grace period — the quarantine check workflow fails until it is removed or re-triaged.">+ <LemonTag type="danger">Overdue — blocks CI</LemonTag></Tooltip>)}@@ -98,14 +63,14 @@ function LifecycleTag({ lifecycle }: { lifecycle: QuarantineLifecycle }): JSX.Elfunction 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 title="Skipped: the test is not collected at all (for hangs, import-time flakes, and state-polluters).">+ <LemonTag type="danger">Skipped</LemonTag></Tooltip>)}return (- <Tooltip title="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 title="Runs as xfail: the test still executes but cannot fail the suite.">+ <LemonTag type="muted">Runs, can't fail</LemonTag></Tooltip>)}@@ -124,6 +89,8 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {quarantineOwner,activeQuarantineCard,hasActiveQuarantineFilters,+ quarantineModal,+ quarantineSubmitLoading,} = useValues(engineeringAnalyticsLogic)const {setQuarantineSearch,@@ -132,15 +99,66 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {setQuarantineOwner,applyQuarantineCard,resetQuarantineFilters,+ openQuarantineModal,+ closeQuarantineModal,+ submitQuarantine,} = useActions(engineeringAnalyticsLogic)+ const openNewQuarantine = (): void =>+ openQuarantineModal({ action: 'quarantine', selector: '', reason: '', owner: '', issue: '', mode: 'run' })++ const openExtend = (row: QuarantineEntryRow): void =>+ openQuarantineModal({+ action: 'extend',+ selector: row.id,+ reason: row.reason,+ owner: row.owner,+ issue: row.issue,+ mode: row.mode,+ })++ const confirmRemove = (row: QuarantineEntryRow): void => {+ LemonDialog.open({+ title: 'Remove from quarantine?',+ description: `Opens a PR that removes ${row.id} from .test_quarantine.json so it gates CI normally again. It takes effect once the PR merges.`,+ primaryButton: {+ children: 'Open removal PR',+ status: 'danger',+ onClick: () =>+ submitQuarantine({+ input: {+ action: 'remove',+ selector: row.id,+ reason: '',+ owner: '',+ issue: row.issue,+ expires: null,+ mode: row.mode,+ },+ }),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ // Rendered alongside every branch that can open it, so the modal survives the no-file empty state.+ const modalElement = (+ <QuarantineTestModal+ modal={quarantineModal}+ ownerOptions={quarantineOwnerOptions}+ submitting={quarantineSubmitLoading}+ onClose={closeQuarantineModal}+ onSubmit={(input) => submitQuarantine({ input })}+ />+ )+// 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.+ // 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">@@ -166,7 +184,7 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {)}- // A file that does not exist is a normal state, not an error, so explain how to start one.+ // A file that does not exist is a normal state, not an error — offer to start one.if (quarantine && !quarantine.available) {return (<div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-primary p-10 text-center">@@ -177,14 +195,12 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {? `${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:+ fixes it. The first quarantine opens a PR that creates the file.</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 type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">+ Quarantine a test</LemonButton>+ {modalElement}</div>)}@@ -203,7 +219,7 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {{row.selectorKind}</LemonTag>{row.runner !== 'pytest' && (- <Tooltip title="No enforcement adapter yet, so this entry is informational.">+ <Tooltip title="No enforcement adapter yet — entry is informational."><LemonTag type="muted" size="small">{row.runner}</LemonTag>@@ -291,14 +307,8 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {render: (_, row) => (<LemonMenuitems={[- {- label: 'Copy remove command',- onClick: () => void copyToClipboard(removeCommand(row), 'remove command'),- },- {- label: 'Copy extend command',- onClick: () => void copyToClipboard(extendCommand(row), 'extend command'),- },+ { label: 'Extend…', onClick: () => openExtend(row) },+ { label: 'Remove…', status: 'danger', onClick: () => confirmRemove(row) },...(row.issue ? [{ label: 'Open issue', to: row.issue, targetBlank: true }] : []),]}>@@ -310,12 +320,16 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {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 className="flex items-start justify-between gap-2">+ <div className="flex flex-col gap-0.5">+ <h3 className="m-0 text-base font-semibold">Quarantine register</h3>+ <p className="m-0 text-xs text-tertiary">+ Flaky tests currently masked in CI via the checked-in quarantine file.+ </p>+ </div>+ <LemonButton type="primary" onClick={openNewQuarantine} data-attr="eng-analytics-quarantine-open">+ Quarantine a test+ </LemonButton></div><div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4"><StatCard@@ -405,8 +419,8 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {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' },+ { value: 'run', label: 'Mode: runs', labelInMenu: "Runs, can't fail" },+ { value: 'skip', label: 'Mode: skipped', labelInMenu: 'Skipped' },]}/><div className="w-56">@@ -450,7 +464,7 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {</LemonButton></div>) : (- 'No quarantined tests. Nothing is masked right now.'+ 'No quarantined tests — nothing is masked right now.')}nouns={['quarantined test', 'quarantined tests']}@@ -458,10 +472,10 @@ export function EngineeringAnalyticsTestHealth(): JSX.Element {<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.+ Quarantining, extending, or removing opens a pull request — the file stays the source of truth. A merged+ edit only affects CI runs that start after it lands.</div>+ {modalElement}</div>)}diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.tsindex 54eee93ab2eb..afa6d35c345a 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts@@ -9,6 +9,7 @@ import {engineeringAnalyticsCiCards,engineeringAnalyticsPullRequests,engineeringAnalyticsQuarantine,+ engineeringAnalyticsQuarantineRequest,engineeringAnalyticsSources,engineeringAnalyticsWorkflowHealth,} from '../generated/api'@@ -33,7 +34,9 @@ import {filterPullRequests,workflowFailureSeries,filterQuarantineEntries,+ inferOwnerFromSelector,quarantineCountsOf,+ quarantineRequestErrorMessage,workflowFailureTrend,} from './engineeringAnalyticsLogic'import { engineeringAnalyticsSceneLogic } from './engineeringAnalyticsSceneLogic'@@ -44,6 +47,7 @@ jest.mock('../generated/api', () => ({engineeringAnalyticsPrLifecycle: jest.fn(),engineeringAnalyticsPullRequests: jest.fn(),engineeringAnalyticsQuarantine: jest.fn(),+ engineeringAnalyticsQuarantineRequest: jest.fn(),engineeringAnalyticsSources: jest.fn(),engineeringAnalyticsWorkflowHealth: jest.fn(),}))@@ -56,6 +60,9 @@ const mockWorkflowHealth = engineeringAnalyticsWorkflowHealth as jest.MockedFunctypeof engineeringAnalyticsWorkflowHealth>const mockQuarantine = engineeringAnalyticsQuarantine as jest.MockedFunction<typeof engineeringAnalyticsQuarantine>+const mockQuarantineRequest = engineeringAnalyticsQuarantineRequest as jest.MockedFunction<+ typeof engineeringAnalyticsQuarantineRequest+>const mockSources = engineeringAnalyticsSources as jest.MockedFunction<typeof engineeringAnalyticsSources>function apiQuarantineEntry(overrides: Partial<QuarantineEntryApi> = {}): QuarantineEntryApi {@@ -209,6 +216,11 @@ describe('engineeringAnalyticsLogic', () => {mockPullRequests.mockResolvedValue({ items: PRS, truncated: false, limit: PRS.length })mockWorkflowHealth.mockResolvedValue(WORKFLOWS)mockQuarantine.mockResolvedValue(QUARANTINE)+ mockQuarantineRequest.mockResolvedValue({+ pr_url: 'https://github.com/PostHog/posthog/pull/99',+ issue_url: 'https://github.com/PostHog/posthog/issues/4242',+ branch: 'quarantine/foo-20260612',+ })// Most tests are single- or no-source; the picker tests override with SOURCES.mockSources.mockResolvedValue([])})@@ -762,4 +774,107 @@ describe('engineeringAnalyticsLogic', () => {expect(logic.values.quarantineLoadFailed).toBe(true)})++ it.each([+ ['product: selector', 'product:batch-exports', '@PostHog/team-batch-exports'],+ ['products/ path', 'products/web_analytics/backend/test_foo.py::T::t', '@PostHog/team-web-analytics'],+ ['plain nodeid', 'posthog/api/test/test_foo.py::T::t', ''],+ ['bare file', 'frontend/src/foo.test.ts', ''],+ ])('inferOwnerFromSelector: %s', (_label, selector, expected) => {+ expect(inferOwnerFromSelector(selector)).toBe(expected)+ })++ it.each([+ ['DRF detail', { detail: 'App not installed' }, 'App not installed'],+ ['nested data.detail', { data: { detail: 'Malformed file' } }, 'Malformed file'],+ ['error message', new Error('Network down'), 'Network down'],+ ['unknown shape', {}, 'Could not complete the quarantine request.'],+ ])('quarantineRequestErrorMessage: %s', (_label, error, expected) => {+ expect(quarantineRequestErrorMessage(error)).toBe(expected)+ })++ it('opens the quarantine modal with the given config', async () => {+ logic = engineeringAnalyticsLogic()+ logic.mount()++ logic.actions.openQuarantineModal({+ action: 'extend',+ selector: 'a/b.py::T::t',+ reason: 'flaky',+ owner: '@team/x',+ issue: 'https://github.com/PostHog/posthog/issues/7',+ mode: 'run',+ })+ expect(logic.values.quarantineModal?.action).toBe('extend')+ expect(logic.values.quarantineModal?.selector).toBe('a/b.py::T::t')++ logic.actions.closeQuarantineModal()+ expect(logic.values.quarantineModal).toBeNull()+ })++ it('a successful submit closes the modal and reloads the register', async () => {+ logic = engineeringAnalyticsLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadQuarantineSuccess'])++ logic.actions.openQuarantineModal({+ action: 'quarantine',+ selector: 'a/b.py::T::t',+ reason: 'flaky',+ owner: '@team/x',+ issue: '',+ mode: 'run',+ })+ logic.actions.submitQuarantine({+ input: {+ action: 'quarantine',+ selector: 'a/b.py::T::t',+ reason: 'flaky',+ owner: '@team/x',+ issue: '',+ expires: '2026-06-26',+ mode: 'run',+ },+ })+ // The success listener reloads the register so the merged change shows up.+ await expectLogic(logic).toDispatchActions(['submitQuarantineSuccess', 'loadQuarantine'])++ // The viewed repo is threaded into the write so the PR targets it.+ expect(mockQuarantineRequest).toHaveBeenCalledWith(+ '1',+ expect.objectContaining({ operation: 'quarantine', repo: 'PostHog/posthog' })+ )+ expect(logic.values.quarantineModal).toBeNull()+ expect(logic.values.quarantineSubmitLoading).toBe(false)+ })++ it('a failed submit keeps the modal open so the user can retry', async () => {+ mockQuarantineRequest.mockRejectedValue({ detail: "The App isn't installed on PostHog." })+ logic = engineeringAnalyticsLogic()+ logic.mount()++ logic.actions.openQuarantineModal({+ action: 'quarantine',+ selector: 'a/b.py::T::t',+ reason: 'flaky',+ owner: '@team/x',+ issue: '',+ mode: 'run',+ })+ logic.actions.submitQuarantine({+ input: {+ action: 'quarantine',+ selector: 'a/b.py::T::t',+ reason: 'flaky',+ owner: '@team/x',+ issue: '',+ expires: null,+ mode: 'run',+ },+ })+ await expectLogic(logic).toDispatchActions(['submitQuarantineFailure'])++ expect(logic.values.quarantineModal).not.toBeNull()+ expect(logic.values.quarantineSubmitLoading).toBe(false)+ })})diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex 815451174f8c..0e4e8e30b6db 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -2,6 +2,8 @@ import { LogicWrapper, actions, afterMount, connect, kea, listeners, path, reducimport { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'+import { lemonToast } from '@posthog/lemon-ui'+import { ApiConfig, ApiError } from 'lib/api'import { dayjs } from 'lib/dayjs'import { objectsEqual } from 'lib/utils/objects'@@ -11,10 +13,16 @@ import {engineeringAnalyticsCiCards,engineeringAnalyticsPullRequests,engineeringAnalyticsQuarantine,+ engineeringAnalyticsQuarantineRequest,engineeringAnalyticsSources,engineeringAnalyticsWorkflowHealth,} from '../generated/api'-import type { GitHubSourceApi, PullRequestListItemApi } from '../generated/api.schemas'+import type {+ GitHubSourceApi,+ PullRequestListItemApi,+ QuarantineRequestApi,+ QuarantineRequestResultApi,+} from '../generated/api.schemas'import { CIStatus, ciStatusOf } from '../lib/ci'import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'@@ -401,6 +409,65 @@ export function quarantineCountsOf(rows: QuarantineEntryRow[]): QuarantineCountsreturn { ...counts, pastExpiry: counts.inGrace + counts.overdue }}+export type QuarantineRequestAction = 'quarantine' | 'extend' | 'remove'++/** What the tab submits to the write endpoint; the backend opens the issue + PR. */+export interface QuarantineSubmitInput {+ action: QuarantineRequestAction+ selector: string+ reason: string+ owner: string+ /** Existing tracking issue, carried forward on extend/remove. */+ issue: string+ /** ISO 'YYYY-MM-DD', or null to let the server default to +14 days. */+ expires: string | null+ mode: QuarantineMode+}++/** Open-modal state for quarantine/extend; null when closed. Remove uses a confirm dialog. */+export interface QuarantineModalState {+ action: 'quarantine' | 'extend'+ selector: string+ reason: string+ owner: string+ issue: string+ mode: QuarantineMode+}++/**+ * Suggest an owning team from a product-scoped selector — a confirm-then-edit starting+ * point, since CODEOWNERS here is intentionally sparse. Returns '' when the selector is+ * not product-scoped, so the user just types the owner.+ */+export function inferOwnerFromSelector(selector: string): string {+ const trimmed = selector.trim()+ const product = trimmed.startsWith('product:')+ ? trimmed.slice('product:'.length)+ : (trimmed.match(/^products\/([^/]+)\//)?.[1] ?? '').replace(/_/g, '-')+ return product ? `@PostHog/team-${product}` : ''+}++function toRequestBody(input: QuarantineSubmitInput, repo: string | null): QuarantineRequestApi {+ return {+ // Wire field is 'operation' (a bare 'action' enum collides in the OpenAPI spec).+ operation: input.action,+ selector: input.selector,+ // Write to the repo currently being viewed so the PR lands where the user expects —+ // and the backend skips the most-active-repo warehouse lookup. Null in local dev.+ repo,+ reason: input.reason,+ owner: input.owner,+ issue: input.issue,+ expires: input.expires,+ mode: input.mode,+ }+}++export function quarantineRequestErrorMessage(error: unknown): string {+ const detail = error as { detail?: string; data?: { detail?: string }; message?: string }+ return detail?.detail ?? detail?.data?.detail ?? detail?.message ?? 'Could not complete the quarantine request.'+}+/*** Per-loader outcome. The endpoints all resolve the same GitHub source, so a 400* (GitHubSourceNotConnectedError) means "connect a source" for every scene; any other@@ -445,6 +512,8 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTysetQuarantineOwner: (owner: string | null) => ({ owner }),applyQuarantineCard: (card: QuarantineCard) => ({ card }),resetQuarantineFilters: true,+ openQuarantineModal: (state: QuarantineModalState) => ({ state }),+ closeQuarantineModal: true,refresh: true,}),@@ -552,6 +621,21 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy},},],+ quarantineSubmit: [+ null as QuarantineRequestResultApi | null,+ {+ submitQuarantine: async ({+ input,+ }: {+ input: QuarantineSubmitInput+ }): Promise<QuarantineRequestResultApi> => {+ return await engineeringAnalyticsQuarantineRequest(+ projectId(),+ toRequestBody(input, values.quarantine?.repoFullName ?? null)+ )+ },+ },+ ],githubSources: [[] as GitHubSourceApi[],{@@ -646,6 +730,16 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyloadQuarantineFailure: () => true,},],+ // Drives the quarantine/extend modal; remove uses a confirm dialog instead.+ quarantineModal: [+ null as QuarantineModalState | null,+ {+ openQuarantineModal: (_, { state }) => state,+ closeQuarantineModal: () => null,+ // A successful write closes the modal; a failure keeps it open so the user can retry.+ submitQuarantineSuccess: () => null,+ },+ ],pullRequestsStatus: ['ok' as LoaderStatus,{@@ -853,6 +947,22 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyactions.setQuarantineLifecycleFilter(target)}},+ submitQuarantineSuccess: ({ quarantineSubmit }) => {+ if (!quarantineSubmit) {+ return+ }+ lemonToast.success(+ quarantineSubmit.issue_url+ ? 'Opened a quarantine PR and a tracking issue. It takes effect once the PR merges.'+ : 'Opened a PR. It takes effect once it merges.',+ { button: { label: 'View PR', action: () => window.open(quarantineSubmit.pr_url, '_blank') } }+ )+ // Reflect the pending change once it lands; the file is still the source of truth.+ actions.loadQuarantine()+ },+ submitQuarantineFailure: ({ error }) => {+ lemonToast.error(quarantineRequestErrorMessage(error))+ },})),actionToUrl(() => ({diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 6e659bcbdd76..e4901263f631 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -36,6 +36,9 @@ tools:engineering-analytics-quarantine:operation: engineering_analytics_quarantineenabled: false+ engineering-analytics-quarantine-request:+ operation: engineering_analytics_quarantine_request+ enabled: falseengineering-analytics-sources:operation: engineering_analytics_sourcesenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 261bd97647b6..7336553f4138 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -30057,6 +30057,20 @@ export namespace Schemas {NotRegex: 'not_regex',} as const;+ /**+ * * `quarantine` - QUARANTINE+ * * `extend` - EXTEND+ * * `remove` - REMOVE+ */+ export type OperationEnum = typeof OperationEnum[keyof typeof OperationEnum];+++ export const OperationEnum = {+ Quarantine: 'quarantine',+ Extend: 'extend',+ Remove: 'remove',+ } as const;+/*** * `latest` - latest* * `earliest` - earliest@@ -44025,6 +44039,47 @@ export namespace Schemas {expires_at?: string | null;}+ export interface QuarantineRequest {+ /** What to do: 'quarantine' (add or replace an entry and file a tracking issue), 'extend' (re-stamp an existing entry's expiry, reusing its issue), or 'remove' (delete the entry). All three open a pull request.+ *+ * * `quarantine` - QUARANTINE+ * * `extend` - EXTEND+ * * `remove` - REMOVE */+ operation: OperationEnum;+ /** Test selector to act on: an exact test id, a file, a directory, a class prefix, or 'product:<dashed-name>'. */+ selector: string;+ /**+ * Optional 'owner/name' repository override; defaults to the team's most active repo.+ * @nullable+ */+ repo?: string | null;+ /** Why the test is quarantined. Required for quarantine and extend; ignored by remove. */+ reason?: string;+ /** GitHub team or user handle responsible for the fix, e.g. '@PostHog/team-x'. Required for quarantine and extend. */+ owner?: string;+ /** Existing tracking issue URL, carried forward on extend and remove. Ignored by quarantine, which files a fresh issue. */+ issue?: string;+ /**+ * ISO date the quarantine expires (at most 30 days out). Defaults to 14 days from today. Ignored by remove.+ * @nullable+ */+ expires?: string | null;+ /** 'run' (the test still executes but cannot fail the suite) or 'skip' (not run at all). Defaults to 'run'.+ *+ * * `run` - RUN+ * * `skip` - SKIP */+ mode?: QuarantineModeEnum;+ }++ export interface QuarantineRequestResult {+ /** URL of the opened pull request that edits the quarantine file. */+ pr_url: string;+ /** URL of the tracking issue filed for a new quarantine; empty for extend and remove. */+ issue_url: string;+ /** Branch the pull request was opened from. */+ branch: string;+ }+export type QueryRequestVariablesOverride = {[key: string]: { [key: string]: unknown }} | null;export interface SavedInsightNode {