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(ci): checked-in test quarantine with hard expiry (#62737)

Raúl Negrón-Otero0e45a6a1fe1b
diff --git a/.github/CODEOWNERS-soft b/.github/CODEOWNERS-soft
index ab25416104c9..9b9c7da73d7a 100644
--- a/.github/CODEOWNERS-soft
+++ b/.github/CODEOWNERS-soft
@@ -232,6 +232,7 @@ Dockerfile @PostHog/team-devex
docker-compose\*.yml @PostHog/team-devex
.prettierrc @PostHog/team-devex
mypy.ini @PostHog/team-devex
+.test_quarantine.json @PostHog/team-devex
posthog/management/migration_analysis/ @PostHog/team-devex
tools/hogli/ @PostHog/team-devex
tools/hogli-commands/ @PostHog/team-devex
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.py
index 125d0de6a3f5..852bc778ff02 100644
--- a/.github/scripts/report_test_timings.py
+++ b/.github/scripts/report_test_timings.py
@@ -67,7 +67,7 @@ class TestCase:
duration_seconds: float
start: datetime
end: datetime
- outcome: str # passed | failed | error | skipped | rerun_passed
+ outcome: str # passed | failed | error | skipped | xfailed | rerun_passed
attempts: int # 1 + number of pytest-rerunfailures retries before final outcome
@@ -158,7 +158,12 @@ def classify_testcase(testcase: Any) -> tuple[str, int]:
if tag.startswith("rerun"):
rerun_count += 1
elif tag in ("failure", "error", "skipped") and final_outcome is None:
- final_outcome = "failed" if tag == "failure" else tag
+ if tag == "skipped" and child.get("type") == "pytest.xfail":
+ # Quarantined-but-still-failing tests (xfail strict=False) must stay
+ # distinguishable from plain skips in the analytics data.
+ final_outcome = "xfailed"
+ else:
+ final_outcome = "failed" if tag == "failure" else tag
if final_outcome is None:
final_outcome = "rerun_passed" if rerun_count else "passed"
return final_outcome, 1 + rerun_count
@@ -285,8 +290,8 @@ def collect_shards(artifacts_root: Path) -> list[Shard]:
def should_emit(test: TestCase, min_duration_seconds: float) -> bool:
- """Emit signal-bearing testcases: failures, errors, reruns, or above the duration threshold."""
- if test.outcome in ("failed", "error"):
+ """Emit signal-bearing testcases: failures, errors, xfails, reruns, or above the duration threshold."""
+ if test.outcome in ("failed", "error", "xfailed"):
return True
if test.attempts > 1:
return True
diff --git a/.github/scripts/schema-impact.js b/.github/scripts/schema-impact.js
index 304319d0fcf6..1fbc4f7b4ac9 100644
--- a/.github/scripts/schema-impact.js
+++ b/.github/scripts/schema-impact.js
@@ -156,4 +156,5 @@ module.exports = {
diffDefinitions,
buildImportMap,
affectedProductsFor,
+ readBaseSchema,
}
diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.js
index cef82874b677..bde94aece082 100644
--- a/.github/scripts/turbo-discover.js
+++ b/.github/scripts/turbo-discover.js
@@ -23,7 +23,7 @@
const { execFileSync } = require('child_process')
const fs = require('fs')
-const { analyzeSchemaImpact } = require('./schema-impact')
+const { analyzeSchemaImpact, readBaseSchema } = require('./schema-impact')
// --- Product shard sizing (same Amdahl shape as Django below) ---
// Each product is atomic for packing, but unlike Django the test pool isn't
@@ -135,6 +135,67 @@ function logAffectedReasons(label, tasks) {
console.error(`${label} affected reasons: ${JSON.stringify(reasons)}`)
}
+// --- Test quarantine (.test_quarantine.json) ---
+// Schema contract: tools/hogli-commands/hogli_commands/quarantine/core.py.
+// This script consumes a deliberately trivial subset of it: pytest entries
+// with an explicit `product:<dashed-name>` selector and `mode: "skip"` drop
+// the whole product from the matrix (mode "run" entries need no matrix change
+// — their tests xfail in-shard). ISO date strings compare lexicographically;
+// an entry is active while today <= expires.
+const QUARANTINE_FILE = '.test_quarantine.json'
+
+function quarantinedSkipProducts(jsonText, todayISO) {
+ const parsed = JSON.parse(jsonText)
+ if (parsed?.version !== 1 || !Array.isArray(parsed.entries)) {
+ return new Set()
+ }
+ const products = new Set()
+ for (const entry of parsed.entries) {
+ if (typeof entry?.id !== 'string' || !entry.id.startsWith('product:')) continue
+ if ((entry.runner ?? 'pytest') !== 'pytest' || entry.mode !== 'skip') continue
+ if (typeof entry.expires !== 'string' || entry.expires < todayISO) continue
+ products.add(entry.id.slice('product:'.length))
+ }
+ return products
+}
+
+function loadQuarantinedSkipProducts(todayISO) {
+ try {
+ return quarantinedSkipProducts(fs.readFileSync(QUARANTINE_FILE, 'utf-8'), todayISO)
+ } catch (e) {
+ // Fail-open: a missing or malformed file means no quarantine, never a blocked matrix.
+ console.error(`Warning: could not read ${QUARANTINE_FILE} (${e.message}) — quarantine ignored`)
+ return new Set()
+ }
+}
+
+function loadBaseQuarantinedSkipProducts(base, todayISO) {
+ // Fail-open: file absent at base (or unreadable ref) means nothing was quarantined there.
+ try {
+ const raw = readBaseSchema(base, QUARANTINE_FILE)
+ return raw === null ? new Set() : quarantinedSkipProducts(raw, todayISO)
+ } catch {
+ return new Set()
+ }
+}
+
+// Warn on names matching no real product (catches the dash/underscore mixup:
+// the dir is batch_exports but the product is batch-exports), then drop the
+// rest from the matrix.
+function dropProducts(products, allProducts, names, label) {
+ const allProductSet = new Set(allProducts)
+ for (const name of names) {
+ if (!allProductSet.has(name)) {
+ console.error(
+ `::warning::${label}: unknown product '${name}' — use the dashed name (e.g. 'batch-exports'), not the directory form`
+ )
+ }
+ }
+ const remaining = products.filter((p) => !names.has(p))
+ console.error(`${label}: ${[...names].join(',')} — dropped ${products.length - remaining.length} product(s)`)
+ return remaining
+}
+
function loadTestDurations() {
let parsed
try {
@@ -424,19 +485,31 @@ if (legacyChanged) {
// running, and blocking on, a product whose tests are temporarily too flaky.
const skipProducts = new Set((process.env.SKIP_PRODUCT_TESTS || '').split(',').map((p) => p.trim()).filter(Boolean))
if (skipProducts.size > 0) {
- // Warn loudly on a name that matches no real product (checked against the
- // full product list, not just the affected ones) — catches the dash/
- // underscore mixup where the dir is batch_exports but the product is
- // batch-exports, which would otherwise silently skip nothing.
+ products = dropProducts(products, allProducts, skipProducts, 'SKIP_PRODUCT_TESTS')
+}
+
+const todayISO = new Date().toISOString().slice(0, 10)
+const quarantinedProducts = loadQuarantinedSkipProducts(todayISO)
+if (quarantinedProducts.size > 0) {
+ products = dropProducts(products, allProducts, quarantinedProducts, 'Quarantined products (mode: skip)')
+}
+
+// Un-quarantining must re-run the suite. Today the ci-backend `legacy` paths-
+// filter already forces a full run on any PR touching the quarantine file, so
+// this diff against the merge base rarely changes the outcome — it is the
+// backstop that keeps product re-runs correct if that coarse trigger is ever
+// narrowed (Turbo itself never sees .test_quarantine.json as a product input).
+if (process.env.TURBO_SCM_BASE) {
+ const baseQuarantined = loadBaseQuarantinedSkipProducts(process.env.TURBO_SCM_BASE, todayISO)
const allProductSet = new Set(allProducts)
- for (const name of skipProducts) {
- if (!allProductSet.has(name)) {
- console.error(`::warning::SKIP_PRODUCT_TESTS: unknown product '${name}' — use the dashed name (e.g. 'batch-exports'), not the directory form`)
- }
+ const productSet = new Set(products)
+ for (const name of baseQuarantined) {
+ if (quarantinedProducts.has(name) || skipProducts.has(name)) continue
+ if (!allProductSet.has(name) || productSet.has(name)) continue
+ console.error(`Quarantine lifted for '${name}' since ${process.env.TURBO_SCM_BASE} — forced into matrix`)
+ products.push(name)
}
- const before = products.length
- products = products.filter((p) => !skipProducts.has(p))
- console.error(`SKIP_PRODUCT_TESTS=${[...skipProducts].join(',')} — dropped ${before - products.length} product(s)`)
+ products.sort()
}
console.error(`Products to test: ${JSON.stringify(products)}`)
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 3b78453a7913..01a026886dd6 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -159,6 +159,7 @@ jobs:
- pytest.ini
- conftest.py # Root conftest loads for every pytest run
- .test_durations # Used for pytest-split sharding
+ - .test_quarantine.json # Un-quarantining must re-run the affected tests
# generates posthog/schema.py
- frontend/src/queries/schema.json
# Operator parity check
@@ -218,6 +219,7 @@ jobs:
- pytest.ini
- conftest.py # Root conftest loads for every pytest run
- .test_durations
+ - .test_quarantine.json
- frontend/src/products.json
- 'products/*/manifest.tsx'
- rust/feature-flags/src/properties/property_models.rs
diff --git a/.github/workflows/test-quarantine.yml b/.github/workflows/test-quarantine.yml
new file mode 100644
index 000000000000..ccc22d9152d7
--- /dev/null
+++ b/.github/workflows/test-quarantine.yml
@@ -0,0 +1,38 @@
+name: Test quarantine
+
+on:
+ pull_request:
+ paths:
+ - .test_quarantine.json
+ - tools/hogli-commands/hogli_commands/quarantine/**
+ - .github/workflows/test-quarantine.yml
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ check-quarantine:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - name: Set up Python
+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version-file: 'pyproject.toml'
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0
+ with:
+ version: '0.11.14' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit
+
+ - name: Check quarantine file
+ # Same as `hogli test:quarantine check`, without installing the dev
+ # environment: the quarantine core is stdlib-only and the CLI needs
+ # only click, so quarantine PRs stay decoupled from lockfile health.
+ run: PYTHONPATH=tools/hogli-commands uv run --no-project --with click python -m hogli_commands.quarantine.cli check
diff --git a/.test_quarantine.json b/.test_quarantine.json
new file mode 100644
index 000000000000..925fc770cd68
--- /dev/null
+++ b/.test_quarantine.json
@@ -0,0 +1,4 @@
+{
+ "version": 1,
+ "entries": []
+}
diff --git a/hogli.yaml b/hogli.yaml
index 0c43d57938be..dcffe750dbae 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -743,6 +743,9 @@ tests:
test:e2e:
bin_script: e2e-test-runner
description: Set up test databases and run Playwright E2E tests
+ test:quarantine:
+ click: hogli_commands.quarantine.cli:quarantine
+ description: Manage .test_quarantine.json — quarantine flaky tests so they stop blocking CI
quality:
lint:
cmd: ./bin/ruff.sh check . && pnpm --filter=@posthog/frontend run lint
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 0a6924ebb9d3..57d4c4e8cb38 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -9,6 +9,11 @@ from urllib.parse import quote_plus
import pytest
from posthog.test.base import PostHogTestCase, run_clickhouse_statement_in_parallel
+try:
+ from hogli_commands.quarantine.pytest_support import apply_quarantine_markers
+except ImportError: # fail-open: runs without tools/hogli-commands on pythonpath (e.g. ee/pytest.ini)
+ apply_quarantine_markers = None
+
from django.conf import settings
from django.core.management.commands.flush import Command as FlushCommand
from django.db import connections
@@ -555,3 +560,8 @@ def _runs_on_internal_pr() -> bool:
def pytest_runtest_setup(item: pytest.Item) -> None:
if "requires_secrets" in item.keywords and not _runs_on_internal_pr():
pytest.skip("Skipping test that requires internal secrets on external PRs")
+
+
+def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
+ if apply_quarantine_markers is not None:
+ apply_quarantine_markers(items)
diff --git a/pytest.ini b/pytest.ini
index ffb88b85f552..0b80cacbcab2 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -15,6 +15,7 @@ markers =
skip_on_multitenancy
async_migrations
requires_secrets: test needs internal secrets or infra and is skipped on external PRs
+ quarantine: applied automatically to tests quarantined via .test_quarantine.json (hogli test:quarantine)
asyncio_mode = auto
asyncio_default_fixture_loop_scope = module
diff --git a/tools/hogli-commands/hogli_commands/quarantine/__init__.py b/tools/hogli-commands/hogli_commands/quarantine/__init__.py
new file mode 100644
index 000000000000..dbe857bcde01
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/quarantine/__init__.py
@@ -0,0 +1,7 @@
+"""Test quarantine: keep flaky tests from blocking CI, with a hard expiry.
+
+``core`` owns the schema and rules for ``.test_quarantine.json`` (the schema
+contract is documented in its module docstring). ``pytest_support`` is the
+pytest adapter used by ``posthog/conftest.py``; ``cli`` is the
+``hogli test:quarantine`` entrypoint wired via ``hogli.yaml``.
+"""
diff --git a/tools/hogli-commands/hogli_commands/quarantine/cli.py b/tools/hogli-commands/hogli_commands/quarantine/cli.py
new file mode 100644
index 000000000000..1559425f8d27
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/quarantine/cli.py
@@ -0,0 +1,141 @@
+"""Click entrypoint for ``hogli test:quarantine``.
+
+Wired into the hogli CLI via the ``click:`` manifest entry in ``hogli.yaml``.
+Schema contract and selector grammar: ``hogli_commands.quarantine.core``.
+
+ hogli test:quarantine add <id> --reason ... --owner ... [--issue ...] [--days 14] [--mode run|skip]
+ hogli test:quarantine list [--json]
+ hogli test:quarantine remove <id>
+ hogli test:quarantine check [--grace-days 7]
+"""
+
+from __future__ import annotations
+
+from datetime import timedelta
+from pathlib import Path
+
+import click
+
+from hogli_commands.quarantine import core
+
+
[email protected](name="test:quarantine", help="Manage .test_quarantine.json — flaky tests that must not block CI.")
+ "--file",
+ "file_path",
+ type=click.Path(path_type=Path),
+ default=None,
+ hidden=True,
+ help="Override the quarantine file location (testing only).",
+)
+def quarantine(ctx: click.Context, file_path: Path | None) -> None:
+ ctx.obj = file_path or core.QUARANTINE_PATH
+
+
+def _load_for_writing(path: Path) -> core.LoadResult:
+ result = core.load(path)
+ if result.errors:
+ details = "\n".join(f" {e}" for e in result.errors)
+ raise click.ClickException(f"{path} has problems — fix it before rewriting:\n{details}")
+ return result
+
+
[email protected](name="add", help="Quarantine a test (replaces an existing entry with the same id).")
[email protected]("selector_id", metavar="ID")
[email protected]("--reason", required=True, help="Why the test is quarantined.")
[email protected]("--owner", required=True, help="Team or person responsible, e.g. @team-product-analytics.")
[email protected]("--issue", default="", help="Tracking issue URL.")
+ "--days",
+ type=click.IntRange(1, core.MAX_QUARANTINE_DAYS),
+ default=14,
+ show_default=True,
+ help="Days until the entry expires and the test blocks CI again.",
+)
+ "--mode",
+ type=click.Choice(core.MODES),
+ default="run",
+ show_default=True,
+ help="run = still executes but cannot fail CI (xfail); skip = not executed (hangs, state-polluters).",
+)
+def add(path: Path, selector_id: str, reason: str, owner: str, issue: str, days: int, mode: str) -> None:
+ selector_problem = core.validate_selector(selector_id, core.DEFAULT_RUNNER)
+ if selector_problem is not None:
+ raise click.ClickException(f"invalid selector '{selector_id}': {selector_problem}")
+ result = _load_for_writing(path)
+ today = core.today_utc()
+ entry = core.Entry(
+ id=selector_id,
+ added=today,
+ expires=today + timedelta(days=days),
+ reason=reason,
+ owner=owner,
+ issue=issue,
+ mode=mode,
+ )
+ entries = [e for e in result.entries if (e.id, e.runner) != (entry.id, entry.runner)] + [entry]
+ path.write_text(core.render(entries, result.extras))
+ click.echo(f"Quarantined '{selector_id}' (mode: {mode}) until {entry.expires.isoformat()}.")
+
+
[email protected](name="remove", help="Remove a quarantine entry for every runner (succeeds even if absent).")
[email protected]("selector_id", metavar="ID")
+def remove(path: Path, selector_id: str) -> None:
+ result = _load_for_writing(path)
+ remaining = [e for e in result.entries if e.id != selector_id]
+ if len(remaining) == len(result.entries):
+ click.echo(f"No entry for '{selector_id}' — nothing to do.")
+ return
+ path.write_text(core.render(remaining, result.extras))
+ click.echo(f"Removed '{selector_id}'.")
+
+
[email protected](name="list", help="List quarantine entries and their status.")
[email protected]("--json", "as_json", is_flag=True, help="Emit raw JSON instead of a table.")
+def list_entries(path: Path, as_json: bool) -> None:
+ result = core.load(path)
+ for message in (*result.errors, *result.warnings):
+ click.secho(message, fg="yellow", err=True)
+ today = core.today_utc()
+ if as_json:
+ click.echo(core.render(result.entries, result.extras), nl=False)
+ return
+ if not result.entries:
+ click.echo("No quarantined tests.")
+ return
+ for entry in sorted(result.entries, key=lambda e: e.id):
+ days_left = (entry.expires - today).days
+ status = f"expires in {days_left}d" if days_left >= 0 else f"EXPIRED {-days_left}d ago"
+ click.echo(f"[{entry.runner}/{entry.mode}] {entry.id} ({status}, {entry.owner}) {entry.reason}")
+
+
[email protected](name="check", help="Lint the quarantine file; exits 1 on violations (used by CI).")
+ "--grace-days",
+ type=click.IntRange(min=0),
+ default=core.DEFAULT_GRACE_DAYS,
+ show_default=True,
+ help="Days an expired entry may linger before this check fails.",
+)
+def check(path: Path, grace_days: int) -> None:
+ result = core.load(path)
+ violations, warnings = core.check(result, today=core.today_utc(), grace_days=grace_days)
+ for message in warnings:
+ click.secho(f"warning: {message}", fg="yellow", err=True)
+ for message in violations:
+ click.secho(f"error: {message}", fg="red", err=True)
+ if violations:
+ raise SystemExit(1)
+ click.echo(f"{path.name} OK ({len(result.entries)} entries).")
+
+
+# Direct invocation needs only click + stdlib (used by test-quarantine.yml to
+# avoid installing the full dev environment): python -m hogli_commands.quarantine.cli
+if __name__ == "__main__":
+ quarantine()
diff --git a/tools/hogli-commands/hogli_commands/quarantine/core.py b/tools/hogli-commands/hogli_commands/quarantine/core.py
new file mode 100644
index 000000000000..9be69189d0a0
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/quarantine/core.py
@@ -0,0 +1,316 @@
+"""Schema and rules for ``.test_quarantine.json`` — THE quarantine contract.
+
+This module is stdlib-only and runner-agnostic: it knows nothing about pytest
+markers or CI. Runner adapters (``pytest_support``, a future jest adapter,
+``.github/scripts/turbo-discover.js``) consume the contract below and
+interpret selectors for their runner; they must not reimplement parsing,
+date handling, or matching beyond what is documented here.
+
+File format (repo root, sorted by ``id``, 4-space indent, trailing newline)::
+
+ {
+ "version": 1,
+ "entries": [
+ {
+ "id": "posthog/api/test/test_foo.py::TestFoo::test_bar",
+ "runner": "pytest",
+ "reason": "Flaky ClickHouse ordering assertion",
+ "owner": "@team-product-analytics",
+ "issue": "https://github.com/PostHog/posthog/issues/12345",
+ "added": "2026-06-10",
+ "expires": "2026-06-24",
+ "mode": "run"
+ }
+ ]
+ }
+
+Fields: ``runner`` defaults to ``"pytest"``; ``mode`` is ``"run"`` (default,
+the test still executes but cannot fail the suite) or ``"skip"`` (for hangs,
+import-time flakes, and state-polluters — the test is not executed at all);
+``issue`` is optional; everything else is required. ``added``/``expires`` are
+ISO dates, so they also compare correctly as plain strings (which is how the
+JS reader compares them).
+
+Selector grammar (``id``, pytest):
+
+- exact nodeid: ``posthog/api/test/test_foo.py::TestFoo::test_bar``
+- prefix: a directory (``posthog/api/test``), file (``.../test_foo.py``),
+ class (``...::TestFoo``), or test function (``...::test_bar``) — matches
+ everything underneath it, where "underneath" means the next character in
+ the nodeid is a ``/``, ``::``, or ``[`` boundary (so a function selector
+ covers its parameterized variants, and partial names never match)
+- ``product:<dashed-name>``: everything under ``products/<name_with_underscores>/``
+
+When several entries match the same test, the most specific (longest)
+selector wins — so a narrow ``mode: skip`` entry overrides a broad
+``mode: run`` one.
+
+Nodeids are repo-root-relative in every PostHog pytest invocation (product
+suites pass ``--rootdir ../..``), so one id format works everywhere.
+
+Expiry: an entry is ACTIVE while ``today (UTC) <= expires``; past that it is
+inert — not an error — and the test blocks CI normally again. ``check`` is
+where staleness becomes a failure: entries expired for more than the grace
+period must be removed, and ``expires - added`` may not exceed
+``MAX_QUARANTINE_DAYS``.
+
+Forward compatibility: readers warn on (and preserve) unknown entry fields,
+tolerate entries for unknown runners (filtered out by ``active_entries``,
+never an error), and treat an unrecognized top-level ``version`` as
+"quarantine disabled". Breaking schema changes bump ``version``.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from datetime import UTC, date, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+SCHEMA_VERSION = 1
+MAX_QUARANTINE_DAYS = 30
+DEFAULT_GRACE_DAYS = 7
+DEFAULT_RUNNER = "pytest"
+MODES = ("run", "skip")
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+QUARANTINE_PATH = REPO_ROOT / ".test_quarantine.json"
+
+_PRODUCT_SELECTOR_PREFIX = "product:"
+_ENTRY_FIELDS = ("id", "runner", "reason", "owner", "issue", "added", "expires", "mode")
+
+
+@dataclass(frozen=True)
+class Entry:
+ id: str
+ added: date
+ expires: date
+ runner: str = DEFAULT_RUNNER
+ reason: str = ""
+ owner: str = ""
+ issue: str = ""
+ mode: str = "run"
+ extras: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class LoadResult:
+ """Outcome of reading a quarantine file.
+
+ ``errors`` are contract violations (malformed JSON, bad entry) — entries
+ that could not be parsed are dropped, the rest are kept, so enforcement
+ stays fail-open while ``check`` can still fail. ``warnings`` are
+ forward-compatibility notices and are never fatal.
+ """
+
+ entries: list[Entry] = field(default_factory=list)
+ errors: list[str] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+ extras: dict[str, Any] = field(default_factory=dict)
+
+
+def today_utc() -> date:
+ return datetime.now(UTC).date()
+
+
+def load(path: Path = QUARANTINE_PATH) -> LoadResult:
+ """Read a quarantine file. A missing file means quarantine is simply off."""
+ try:
+ text = path.read_text()
+ except FileNotFoundError:
+ return LoadResult()
+ except OSError as exc:
+ return LoadResult(errors=[f"could not read {path}: {exc}"])
+ return parse(text)
+
+
+def parse(text: str) -> LoadResult:
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError as exc:
+ return LoadResult(errors=[f"invalid JSON: {exc}"])
+ if not isinstance(data, dict):
+ return LoadResult(errors=["top level must be an object"])
+ if data.get("version") != SCHEMA_VERSION:
+ return LoadResult(errors=[f"unsupported version {data.get('version')!r} (expected {SCHEMA_VERSION})"])
+ raw_entries = data.get("entries")
+ if not isinstance(raw_entries, list):
+ return LoadResult(errors=["'entries' must be a list"])
+
+ result = LoadResult(extras={k: v for k, v in data.items() if k not in ("version", "entries")})
+ for index, raw in enumerate(raw_entries):
+ entry = _parse_entry(raw, index, result)
+ if entry is not None:
+ result.entries.append(entry)
+ return result
+
+
+def _parse_entry(raw: Any, index: int, result: LoadResult) -> Entry | None:
+ label = f"entries[{index}]"
+ if not isinstance(raw, dict):
+ result.errors.append(f"{label}: must be an object")
+ return None
+ if isinstance(raw.get("id"), str) and raw["id"]:
+ label = f"entries[{index}] ({raw['id']})"
+ else:
+ result.errors.append(f"{label}: 'id' must be a non-empty string")
+ return None
+
+ for key in ("reason", "owner", "issue", "runner", "mode"):
+ if key in raw and not isinstance(raw[key], str):
+ result.errors.append(f"{label}: '{key}' must be a string")
+ return None
+ mode = raw.get("mode", "run")
+ if mode not in MODES:
+ result.errors.append(f"{label}: 'mode' must be one of {MODES}, 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):
+ result.errors.append(f"{label}: '{key}' must be an ISO date (YYYY-MM-DD)")
+ return None
+
+ extras = {k: v for k, v in raw.items() if k not in _ENTRY_FIELDS}
+ if extras:
+ result.warnings.append(f"{label}: unknown fields {sorted(extras)} (kept for forward compatibility)")
+
+ return Entry(
+ id=raw["id"],
+ added=dates["added"],
+ expires=dates["expires"],
+ runner=raw.get("runner", DEFAULT_RUNNER),
+ reason=raw.get("reason", ""),
+ owner=raw.get("owner", ""),
+ issue=raw.get("issue", ""),
+ mode=mode,
+ extras=extras,
+ )
+
+
+def is_active(entry: Entry, today: date) -> bool:
+ return today <= entry.expires
+
+
+def active_entries(entries: list[Entry], runner: str, today: date) -> list[Entry]:
+ """Unexpired entries for one runner — entries for other (or future,
+ unknown) runners are silently excluded, never an error."""
+ return [e for e in entries if e.runner == runner and is_active(e, today)]
+
+
+def selector_matches(selector: str, test_id: str) -> bool:
+ """Does ``selector`` cover ``test_id``? See the grammar in the module docstring."""
+ if selector.startswith(_PRODUCT_SELECTOR_PREFIX):
+ return test_id.startswith(product_path_prefix(selector))
+ selector = selector.rstrip("/")
+ return test_id == selector or test_id.startswith((f"{selector}/", f"{selector}::", f"{selector}["))
+
+
+def product_path_prefix(selector: str) -> str:
+ """``product:batch-exports`` → ``products/batch_exports/``."""
+ name = selector[len(_PRODUCT_SELECTOR_PREFIX) :]
+ return f"products/{name.replace('-', '_')}/"
+
+
+def find_match(entries: list[Entry], test_id: str) -> Entry | None:
+ """The most specific (longest) matching selector wins, so a narrow
+ ``mode: skip`` entry can override a broad ``mode: run`` one. Ties keep
+ file order (sorted by id)."""
+ matches = [e for e in entries if selector_matches(e.id, test_id)]
+ return max(matches, key=lambda e: len(_expanded_selector(e.id)), default=None)
+
+
+def _expanded_selector(selector: str) -> str:
+ return product_path_prefix(selector) if selector.startswith(_PRODUCT_SELECTOR_PREFIX) else selector
+
+
+def render(entries: list[Entry], extras: dict[str, Any] | None = None) -> str:
+ """Serialize to the canonical on-disk form: sorted by id, 4-space indent,
+ trailing newline. Unknown fields captured at parse time are written back."""
+ payload: dict[str, Any] = {"version": SCHEMA_VERSION, **(extras or {})}
+ payload["entries"] = [_entry_to_dict(e) for e in sorted(entries, key=lambda e: (e.id, e.runner))]
+ return json.dumps(payload, indent=4) + "\n"
+
+
+def _entry_to_dict(entry: Entry) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "id": entry.id,
+ "runner": entry.runner,
+ "reason": entry.reason,
+ "owner": entry.owner,
+ **({"issue": entry.issue} if entry.issue else {}),
+ "added": entry.added.isoformat(),
+ "expires": entry.expires.isoformat(),
+ "mode": entry.mode,
+ }
+ out.update(sorted(entry.extras.items()))
+ return out
+
+
+def validate_selector(selector: str, runner: str) -> str | None:
+ """Selector validity for known runners; returns a violation message or None.
+
+ Only pytest selectors have rules today; other runners' grammars belong to
+ their future adapters and are not validated here.
+ """
+ if runner != DEFAULT_RUNNER:
+ return None
+ if selector.startswith(_PRODUCT_SELECTOR_PREFIX):
+ name = selector[len(_PRODUCT_SELECTOR_PREFIX) :]
+ if "_" in name:
+ # turbo-discover compares dashed product names; the underscored
+ # directory form would silently skip nothing there.
+ return "use the dashed product name (e.g. 'batch-exports'), not the directory form"
+ product_dir = REPO_ROOT / product_path_prefix(selector)
+ if not product_dir.is_dir():
+ return f"no directory {product_dir.relative_to(REPO_ROOT)} — is the product name right?"
+ return None
+ if selector.startswith("/") or selector.startswith("\\"):
+ return "must be repo-root-relative, not absolute"
+ if any(c.isspace() for c in selector):
+ return "must not contain whitespace"
+ return None
+
+
+def check(result: LoadResult, today: date, grace_days: int = DEFAULT_GRACE_DAYS) -> tuple[list[str], list[str]]:
+ """Lint a loaded quarantine file; returns (violations, warnings).
+
+ Violations: load errors, duplicate ids, ``expires`` before ``added`` or
+ more than ``MAX_QUARANTINE_DAYS`` after it, entries expired beyond the
+ grace period, invalid selectors for known runners. Warnings: load
+ warnings, entries for runners without an enforcement adapter, entries
+ inside the expiry grace period.
+ """
+ violations = list(result.errors)
+ warnings = list(result.warnings)
+
+ seen: set[tuple[str, str]] = set()
+ for entry in result.entries:
+ label = f"entry '{entry.id}'"
+ if (entry.id, entry.runner) in seen:
+ violations.append(f"{label}: duplicate id for runner '{entry.runner}'")
+ seen.add((entry.id, entry.runner))
+
+ if entry.expires < entry.added:
+ violations.append(f"{label}: expires {entry.expires} is before added {entry.added}")
+ elif entry.expires - entry.added > timedelta(days=MAX_QUARANTINE_DAYS):
+ violations.append(f"{label}: quarantine window exceeds {MAX_QUARANTINE_DAYS} days")
+
+ expired_for = (today - entry.expires).days
+ if expired_for > grace_days:
+ violations.append(f"{label}: expired {expired_for} days ago (grace is {grace_days}) — remove or re-triage")
+ elif expired_for > 0:
+ days_left = grace_days - expired_for
+ deadline = f"within {days_left} days" if days_left else "today — grace period ends"
+ warnings.append(f"{label}: expired {expired_for} days ago — remove {deadline}")
+
+ if entry.runner != DEFAULT_RUNNER:
+ warnings.append(f"{label}: runner '{entry.runner}' has no enforcement adapter yet")
+ selector_problem = validate_selector(entry.id, entry.runner)
+ if selector_problem is not None:
+ violations.append(f"{label}: {selector_problem}")
+
+ return violations, warnings
diff --git a/tools/hogli-commands/hogli_commands/quarantine/pytest_support.py b/tools/hogli-commands/hogli_commands/quarantine/pytest_support.py
new file mode 100644
index 000000000000..69474a0985de
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/quarantine/pytest_support.py
@@ -0,0 +1,47 @@
+"""Pytest adapter for the test quarantine (schema contract: ``core``).
+
+Applies markers to collected items that match an active pytest entry:
+``mode: run`` → ``xfail(strict=False)`` so the test still executes and its
+duration/outcome keep flowing to the JUnit→OTLP pipeline; ``mode: skip`` →
+``skip`` for hangs, import-time flakes, and state-polluters.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+from hogli_commands.quarantine import core
+
+
+def apply_quarantine_markers(items: list[pytest.Item], path: Path | None = None) -> None:
+ """Mark quarantined items. Fail-open: any problem with the quarantine file
+ is reported on stderr and quarantine is disabled — collection never breaks.
+
+ Idempotent via the ``quarantine`` guard marker: the conftest hook registers
+ twice in runs where ``products/conftest.py`` or ``ee/conftest.py``
+ star-import ``posthog/conftest.py`` alongside it.
+ """
+ try:
+ result = core.load(path or core.QUARANTINE_PATH)
+ for message in result.errors:
+ sys.stderr.write(f"[quarantine] disabled entry: {message}\n")
+ entries = core.active_entries(result.entries, runner="pytest", today=core.today_utc())
+ if not entries:
+ return
+ for item in items:
+ if item.get_closest_marker("quarantine") is not None:
+ continue
+ entry = core.find_match(entries, item.nodeid)
+ if entry is None:
+ continue
+ reason = f"quarantined until {entry.expires.isoformat()}: {entry.reason} ({entry.issue or entry.owner})"
+ item.add_marker(pytest.mark.quarantine)
+ if entry.mode == "skip":
+ item.add_marker(pytest.mark.skip(reason=reason))
+ else:
+ item.add_marker(pytest.mark.xfail(reason=reason, strict=False))
+ except Exception as exc:
+ sys.stderr.write(f"[quarantine] disabled: {exc}\n")
diff --git a/tools/hogli-commands/hogli_commands/tests/test_quarantine.py b/tools/hogli-commands/hogli_commands/tests/test_quarantine.py
new file mode 100644
index 000000000000..f3c52113ec7a
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_quarantine.py
@@ -0,0 +1,405 @@
+from __future__ import annotations
+
+import json
+from datetime import date, timedelta
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from click.testing import CliRunner
+from hogli_commands.quarantine import core
+from hogli_commands.quarantine.cli import quarantine
+from hogli_commands.quarantine.pytest_support import apply_quarantine_markers
+
+TODAY = date(2026, 6, 10)
+
+
+def make_entry(**overrides: Any) -> core.Entry:
+ defaults: dict[str, Any] = {
+ "id": "posthog/api/test/test_foo.py::TestFoo::test_bar",
+ "added": TODAY,
+ "expires": TODAY + timedelta(days=14),
+ "reason": "flaky",
+ "owner": "@team-devex",
+ }
+ return core.Entry(**{**defaults, **overrides})
+
+
+def write_file(path: Path, entries: list[dict[str, Any]], version: int = 1) -> Path:
+ path.write_text(json.dumps({"version": version, "entries": entries}, indent=4) + "\n")
+ return path
+
+
+def raw_entry(**overrides: Any) -> dict[str, Any]:
+ defaults: dict[str, Any] = {
+ "id": "posthog/api/test/test_foo.py::TestFoo::test_bar",
+ "runner": "pytest",
+ "reason": "flaky",
+ "owner": "@team-devex",
+ "added": core.today_utc().isoformat(),
+ "expires": (core.today_utc() + timedelta(days=14)).isoformat(),
+ "mode": "run",
+ }
+ return {**defaults, **overrides}
+
+
+ "selector, test_id, expected",
+ [
+ # exact nodeid
+ ("posthog/api/test/test_foo.py::TestFoo::test_bar", "posthog/api/test/test_foo.py::TestFoo::test_bar", True),
+ # function selector covers parameterized variants
+ (
+ "posthog/api/test/test_foo.py::TestFoo::test_bar",
+ "posthog/api/test/test_foo.py::TestFoo::test_bar[a-1]",
+ True,
+ ),
+ # class prefix
+ ("posthog/api/test/test_foo.py::TestFoo", "posthog/api/test/test_foo.py::TestFoo::test_other", True),
+ # file prefix
+ ("posthog/api/test/test_foo.py", "posthog/api/test/test_foo.py::TestBar::test_x", True),
+ # directory prefix, with and without trailing slash
+ ("posthog/api/test", "posthog/api/test/test_foo.py::TestFoo::test_bar", True),
+ ("posthog/api/test/", "posthog/api/test/test_foo.py::TestFoo::test_bar", True),
+ # partial names never match
+ ("posthog/api/test", "posthog/api/test_organization.py::test_x", False),
+ (
+ "posthog/api/test/test_foo.py::TestFoo::test_bar",
+ "posthog/api/test/test_foo.py::TestFoo::test_barbell",
+ False,
+ ),
+ # product selector translates dashes to the underscored directory
+ ("product:batch-exports", "products/batch_exports/backend/tests/test_runs.py::test_x", True),
+ ("product:batch-exports", "products/batch_exports_v2/backend/tests/test_runs.py::test_x", False),
+ ("product:batch-exports", "posthog/api/test/test_foo.py::test_x", False),
+ # unrelated paths
+ ("posthog/api/test/test_foo.py", "posthog/api/test/test_food.py::test_x", False),
+ ],
+)
+def test_selector_matches(selector: str, test_id: str, expected: bool) -> None:
+ assert core.selector_matches(selector, test_id) is expected
+
+
+ "expires_offset_days, expected_active",
+ [(-1, False), (0, True), (1, True)],
+)
+def test_expiry_boundary(expires_offset_days: int, expected_active: bool) -> None:
+ entry = make_entry(expires=TODAY + timedelta(days=expires_offset_days))
+ assert core.is_active(entry, TODAY) is expected_active
+
+
+def test_active_entries_filters_runner_and_expiry() -> None:
+ entries = [
+ make_entry(id="a"),
+ make_entry(id="b", expires=TODAY - timedelta(days=1)),
+ make_entry(id="c", runner="jest"),
+ make_entry(id="d", runner="some-future-runner"),
+ ]
+ assert [e.id for e in core.active_entries(entries, "pytest", TODAY)] == ["a"]
+
+
+def test_load_missing_file_is_empty_and_clean(tmp_path: Path) -> None:
+ result = core.load(tmp_path / "nope.json")
+ assert result.entries == []
+ assert result.errors == []
+
+
+ "text, error_fragment",
+ [
+ ("not json{", "invalid JSON"),
+ ("[]", "top level"),
+ ('{"version": 2, "entries": []}', "unsupported version"),
+ ('{"version": 1, "entries": {}}', "must be a list"),
+ ],
+)
+def test_parse_malformed_file_reports_error_without_entries(text: str, error_fragment: str) -> None:
+ result = core.parse(text)
+ assert result.entries == []
+ assert any(error_fragment in e for e in result.errors)
+
+
+ "broken",
+ [
+ {"id": "", "added": "2026-06-10", "expires": "2026-06-20"},
+ {"id": "x", "added": "not-a-date", "expires": "2026-06-20"},
+ {"id": "x", "added": "2026-06-10", "expires": "2026-06-20", "mode": "pause"},
+ {"id": "x", "added": "2026-06-10", "expires": "2026-06-20", "reason": 42},
+ "not-an-object",
+ ],
+)
+def test_parse_skips_broken_entry_but_keeps_good_ones(broken: Any) -> None:
+ good = {"id": "posthog/a.py", "added": "2026-06-10", "expires": "2026-06-20"}
+ result = core.parse(json.dumps({"version": 1, "entries": [broken, good]}))
+ assert [e.id for e in result.entries] == ["posthog/a.py"]
+ assert len(result.errors) == 1
+
+
+def test_parse_warns_on_unknown_field_and_preserves_it_on_render() -> None:
+ entry = {"id": "posthog/a.py", "added": "2026-06-10", "expires": "2026-06-20", "future_field": "x"}
+ result = core.parse(json.dumps({"version": 1, "entries": [entry], "future_top_level": True}))
+ assert result.errors == []
+ assert any("future_field" in w for w in result.warnings)
+ rendered = json.loads(core.render(result.entries, result.extras))
+ assert rendered["future_top_level"] is True
+ assert rendered["entries"][0]["future_field"] == "x"
+
+
+def test_render_is_sorted_indented_and_newline_terminated() -> None:
+ text = core.render([make_entry(id="z/b.py"), make_entry(id="a/a.py")])
+ assert text.endswith("}\n")
+ assert ' "version": 1' in text
+ ids = [e["id"] for e in json.loads(text)["entries"]]
+ assert ids == sorted(ids)
+
+
+# ---------- pytest adapter ----------
+
+
+class FakeItem:
+ def __init__(self, nodeid: str) -> None:
+ self.nodeid = nodeid
+ self.markers: list[Any] = []
+
+ def add_marker(self, marker: Any) -> None:
+ self.markers.append(marker)
+
+ def get_closest_marker(self, name: str) -> Any:
+ return next((m for m in self.markers if m.name == name), None)
+
+ def marker_names(self) -> list[str]:
+ return [m.name for m in self.markers]
+
+
+def test_adapter_marks_matching_item_xfail(tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry()])
+ item = FakeItem("posthog/api/test/test_foo.py::TestFoo::test_bar")
+ other = FakeItem("posthog/api/test/test_other.py::test_x")
+ apply_quarantine_markers([item, other], path=path) # type: ignore[arg-type]
+ assert item.marker_names() == ["quarantine", "xfail"]
+ assert "quarantined until" in item.markers[1].kwargs["reason"]
+ assert other.markers == []
+
+
+def test_adapter_skip_mode_applies_skip_marker(tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry(mode="skip")])
+ item = FakeItem("posthog/api/test/test_foo.py::TestFoo::test_bar")
+ apply_quarantine_markers([item], path=path) # type: ignore[arg-type]
+ assert item.marker_names() == ["quarantine", "skip"]
+
+
+def test_adapter_most_specific_selector_wins(tmp_path: Path) -> None:
+ entries = [
+ raw_entry(id="posthog/api/test/test_foo.py", mode="run"),
+ raw_entry(id="posthog/api/test/test_foo.py::TestFoo::test_bar", mode="skip"),
+ ]
+ path = write_file(tmp_path / "q.json", entries)
+ narrow = FakeItem("posthog/api/test/test_foo.py::TestFoo::test_bar")
+ broad = FakeItem("posthog/api/test/test_foo.py::TestFoo::test_other")
+ apply_quarantine_markers([narrow, broad], path=path) # type: ignore[arg-type]
+ assert narrow.marker_names() == ["quarantine", "skip"]
+ assert broad.marker_names() == ["quarantine", "xfail"]
+
+
+def test_adapter_is_idempotent_across_double_registration(tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry()])
+ item = FakeItem("posthog/api/test/test_foo.py::TestFoo::test_bar")
+ apply_quarantine_markers([item], path=path) # type: ignore[arg-type]
+ apply_quarantine_markers([item], path=path) # type: ignore[arg-type]
+ assert item.marker_names() == ["quarantine", "xfail"]
+
+
+ "entry",
+ [
+ raw_entry(expires="2020-01-01"), # expired → inert
+ raw_entry(runner="jest"), # other runner → not pytest's business
+ raw_entry(runner="never-heard-of-it"), # unknown runner → ignored, not an error
+ ],
+)
+def test_adapter_leaves_item_unmarked(tmp_path: Path, entry: dict[str, Any]) -> None:
+ path = write_file(tmp_path / "q.json", [entry])
+ item = FakeItem("posthog/api/test/test_foo.py::TestFoo::test_bar")
+ apply_quarantine_markers([item], path=path) # type: ignore[arg-type]
+ assert item.markers == []
+
+
+def test_adapter_fails_open_on_malformed_file(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
+ path = tmp_path / "q.json"
+ path.write_text("not json{")
+ item = FakeItem("posthog/api/test/test_foo.py::TestFoo::test_bar")
+ apply_quarantine_markers([item], path=path) # type: ignore[arg-type]
+ assert item.markers == []
+ assert "[quarantine]" in capsys.readouterr().err
+
+
+# ---------- CLI ----------
+
+
+def runner() -> CliRunner:
+ return CliRunner()
+
+
+def cli(runner: CliRunner, path: Path, *args: str) -> Any:
+ return runner.invoke(quarantine, ["--file", str(path), *args])
+
+
+def test_add_creates_canonical_file(runner: CliRunner, tmp_path: Path) -> None:
+ path = tmp_path / "q.json"
+ result = cli(runner, path, "add", "posthog/api/test/test_foo.py", "--reason", "flaky", "--owner", "@team-devex")
+ assert result.exit_code == 0, result.output
+ text = path.read_text()
+ assert text.endswith("\n")
+ data = json.loads(text)
+ entry = data["entries"][0]
+ assert entry["id"] == "posthog/api/test/test_foo.py"
+ assert entry["mode"] == "run"
+ assert date.fromisoformat(entry["expires"]) - date.fromisoformat(entry["added"]) == timedelta(days=14)
+
+
+def test_add_replaces_existing_entry_with_same_id(runner: CliRunner, tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry(reason="old")])
+ result = cli(runner, path, "add", raw_entry()["id"], "--reason", "new", "--owner", "@x", "--mode", "skip")
+ assert result.exit_code == 0, result.output
+ entries = json.loads(path.read_text())["entries"]
+ assert len(entries) == 1
+ assert entries[0]["reason"] == "new"
+ assert entries[0]["mode"] == "skip"
+
+
+ "argv",
+ [
+ ("add", "x.py", "--reason", "r", "--owner", "@o", "--days", "31"), # over the cap
+ ("add", "x.py", "--reason", "r", "--owner", "@o", "--days", "0"),
+ ("add", "/abs/path.py", "--reason", "r", "--owner", "@o"), # absolute selector
+ ("add", "product:no_such_product", "--reason", "r", "--owner", "@o"), # underscored / unknown product
+ ("add", "x.py", "--owner", "@o"), # missing --reason
+ ],
+)
+def test_add_rejects_invalid_input(runner: CliRunner, tmp_path: Path, argv: tuple[str, ...]) -> None:
+ path = tmp_path / "q.json"
+ result = cli(runner, path, *argv)
+ assert result.exit_code != 0
+ assert not path.exists()
+
+
+def test_add_refuses_to_rewrite_malformed_file(runner: CliRunner, tmp_path: Path) -> None:
+ path = tmp_path / "q.json"
+ path.write_text("not json{")
+ result = cli(runner, path, "add", "x.py", "--reason", "r", "--owner", "@o")
+ assert result.exit_code != 0
+ assert path.read_text() == "not json{"
+
+
+def test_remove_absent_id_succeeds(runner: CliRunner, tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry()])
+ result = cli(runner, path, "remove", "posthog/never/was/quarantined.py")
+ assert result.exit_code == 0
+ assert "nothing to do" in result.output
+ assert len(json.loads(path.read_text())["entries"]) == 1
+
+
+def test_remove_deletes_entry(runner: CliRunner, tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry()])
+ result = cli(runner, path, "remove", raw_entry()["id"])
+ assert result.exit_code == 0
+ assert json.loads(path.read_text())["entries"] == []
+
+
+def test_list_json_emits_canonical_document(runner: CliRunner, tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry()])
+ result = cli(runner, path, "list", "--json")
+ assert result.exit_code == 0
+ assert json.loads(result.output)["version"] == 1
+
+
+def test_list_shows_status(runner: CliRunner, tmp_path: Path) -> None:
+ path = write_file(tmp_path / "q.json", [raw_entry()])
+ result = cli(runner, path, "list")
+ assert result.exit_code == 0
+ assert "expires in" in result.output
+ assert "@team-devex" in result.output
+
+
+ "entries, expected_exit, expected_fragment",
+ [
+ # healthy file
+ ([raw_entry()], 0, "OK"),
+ # duplicate ids
+ ([raw_entry(), raw_entry(reason="again")], 1, "duplicate id"),
+ # cap exceeded
+ ([raw_entry(expires=(core.today_utc() + timedelta(days=40)).isoformat())], 1, "exceeds 30 days"),
+ # expires before added
+ ([raw_entry(expires=(core.today_utc() - timedelta(days=1)).isoformat())], 1, "before added"),
+ # expired beyond the grace period
+ (
+ [
+ raw_entry(
+ added=(core.today_utc() - timedelta(days=30)).isoformat(),
+ expires=(core.today_utc() - timedelta(days=10)).isoformat(),
+ )
+ ],
+ 1,
+ "remove or re-triage",
+ ),
+ # expired but within grace → warn, pass
+ (
+ [
+ raw_entry(
+ added=(core.today_utc() - timedelta(days=20)).isoformat(),
+ expires=(core.today_utc() - timedelta(days=3)).isoformat(),
+ )
+ ],
+ 0,
+ "remove within",
+ ),
+ # expired exactly grace days ago → last day of grace, warn without "within 0 days"
+ (
+ [
+ raw_entry(
+ added=(core.today_utc() - timedelta(days=27)).isoformat(),
+ expires=(core.today_utc() - timedelta(days=7)).isoformat(),
+ )
+ ],
+ 0,
+ "remove today — grace period ends",
+ ),
+ # forward compat: unknown runner and unknown field warn but pass
+ ([raw_entry(runner="jest", future_field="x")], 0, "no enforcement adapter"),
+ # known-product selector passes; unknown product fails
+ ([raw_entry(id="product:batch-exports")], 0, "OK"),
+ ([raw_entry(id="product:batch_exports")], 1, "dashed product name"),
+ ],
+)
+def test_check(
+ runner: CliRunner, tmp_path: Path, entries: list[dict[str, Any]], expected_exit: int, expected_fragment: str
+) -> None:
+ path = write_file(tmp_path / "q.json", entries)
+ result = cli(runner, path, "check")
+ assert result.exit_code == expected_exit, result.output
+ assert expected_fragment in result.output
+
+
+def test_check_fails_on_malformed_file(runner: CliRunner, tmp_path: Path) -> None:
+ path = tmp_path / "q.json"
+ path.write_text('{"version": 99}')
+ result = cli(runner, path, "check")
+ assert result.exit_code == 1
+ assert "unsupported version" in result.output
+
+
+def test_check_passes_on_missing_file(runner: CliRunner, tmp_path: Path) -> None:
+ result = cli(runner, tmp_path / "missing.json", "check")
+ assert result.exit_code == 0
+
+
+def test_repo_quarantine_file_is_valid(runner: CliRunner) -> None:
+ assert core.QUARANTINE_PATH.name == ".test_quarantine.json"
+ result = runner.invoke(quarantine, ["check"])
+ assert result.exit_code == 0, result.output