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): playwright quarantine adapter + selector validation (#67974)

Raúl Negrón-Oteroe87cdc582342
diff --git a/frontend/src/test/playwright.quarantine.reporter.test.ts b/frontend/src/test/playwright.quarantine.reporter.test.ts
new file mode 100644
index 000000000000..4a8a12389a15
--- /dev/null
+++ b/frontend/src/test/playwright.quarantine.reporter.test.ts
@@ -0,0 +1,105 @@
+import type { FullResult, Suite, TestCase } from '@playwright/test/reporter'
+import * as path from 'path'
+
+import { QuarantineEntry, REPO_ROOT } from '../../../playwright/playwright.quarantine'
+import QuarantineReporter, { nameParts } from '../../../playwright/playwright.quarantine.reporter'
+
+// The reporter's onEnd can flip a red run to passed, so it is the highest-risk
+// code here and needs its own lock: these cover when it tolerates, when it must
+// keep the run red, and that the run-half id agrees with the skip fixture.
+
+type FakeSuite = { type: string; title: string; parent?: FakeSuite }
+type Outcome = ReturnType<TestCase['outcome']>
+
+function fakeTest(relFile: string, describes: string[], title: string, outcome: Outcome): TestCase {
+ const fileSuite: FakeSuite = { type: 'file', title: relFile }
+ let parent: FakeSuite = fileSuite
+ for (const describe of describes) {
+ parent = { type: 'describe', title: describe, parent }
+ }
+ return {
+ title,
+ outcome: () => outcome,
+ location: { file: path.join(REPO_ROOT, relFile) },
+ parent,
+ } as unknown as TestCase
+}
+
+function runEntry(id: string): QuarantineEntry {
+ return { id, mode: 'run', reason: 'flaky', owner: '@web', issue: '', expires: '2026-12-31' }
+}
+
+function reporterFor(entries: QuarantineEntry[], tests: TestCase[]): QuarantineReporter {
+ const reporter = new QuarantineReporter(entries)
+ reporter.onBegin({}, { allTests: () => tests } as unknown as Suite)
+ return reporter
+}
+
+const failedRun = { status: 'failed' } as unknown as FullResult
+
+describe('playwright.quarantine.reporter', () => {
+ let warn: jest.SpyInstance
+
+ beforeEach(() => {
+ warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
+ })
+ afterEach(() => {
+ warn.mockRestore()
+ })
+
+ test('overrides a failed run to passed when every unexpected failure is a mode:run quarantined test', async () => {
+ const tests = [
+ fakeTest('playwright/e2e/x.spec.ts', ['Auth'], 'logs in', 'unexpected'),
+ fakeTest('playwright/e2e/y.spec.ts', [], 'passes', 'expected'),
+ ]
+ const reporter = reporterFor([runEntry('playwright/e2e/x.spec.ts::Auth logs in')], tests)
+ expect(await reporter.onEnd(failedRun)).toEqual({ status: 'passed' })
+ })
+
+ test('keeps the run red when a non-quarantined test also failed', async () => {
+ const tests = [
+ fakeTest('playwright/e2e/x.spec.ts', ['Auth'], 'logs in', 'unexpected'),
+ fakeTest('playwright/e2e/z.spec.ts', [], 'real regression', 'unexpected'),
+ ]
+ const reporter = reporterFor([runEntry('playwright/e2e/x.spec.ts::Auth logs in')], tests)
+ expect(await reporter.onEnd(failedRun)).toBeUndefined()
+ })
+
+ test('never overrides once a run-level error fired (onError)', async () => {
+ const tests = [fakeTest('playwright/e2e/x.spec.ts', ['Auth'], 'logs in', 'unexpected')]
+ const reporter = reporterFor([runEntry('playwright/e2e/x.spec.ts::Auth logs in')], tests)
+ reporter.onError()
+ expect(await reporter.onEnd(failedRun)).toBeUndefined()
+ })
+
+ test('only a failed final status is a candidate — interrupted stays red', async () => {
+ const tests = [fakeTest('playwright/e2e/x.spec.ts', ['Auth'], 'logs in', 'unexpected')]
+ const reporter = reporterFor([runEntry('playwright/e2e/x.spec.ts::Auth logs in')], tests)
+ expect(await reporter.onEnd({ status: 'interrupted' } as unknown as FullResult)).toBeUndefined()
+ })
+
+ test('a mode:run entry matches a test in an anonymous describe (reporter id omits the empty title)', async () => {
+ // The skip fixture derives ids from Playwright titlePath, which drops anonymous
+ // describes; nameParts must agree or the run half silently fails to match.
+ const anon = fakeTest('playwright/e2e/x.spec.ts', [''], 'loads', 'unexpected')
+ expect(nameParts(anon)).toEqual(['loads'])
+ const reporter = reporterFor([runEntry('playwright/e2e/x.spec.ts::loads')], [anon])
+ expect(await reporter.onEnd(failedRun)).toEqual({ status: 'passed' })
+ })
+
+ test('no active entries makes the reporter a no-op', async () => {
+ const tests = [fakeTest('playwright/e2e/x.spec.ts', ['Auth'], 'logs in', 'unexpected')]
+ const reporter = reporterFor([], tests)
+ expect(await reporter.onEnd(failedRun)).toBeUndefined()
+ })
+
+ test('constructed the way Playwright does (reporter-options object) it loads entries instead of crashing', async () => {
+ // Playwright passes `{}` for `['./reporter.ts']` with no options; treating
+ // that object as the entries array made onEnd throw "entries is not iterable".
+ const reporter = new QuarantineReporter({})
+ reporter.onBegin({}, {
+ allTests: () => [fakeTest('playwright/e2e/x.spec.ts', ['Auth'], 'logs in', 'unexpected')],
+ } as unknown as Suite)
+ await expect(reporter.onEnd(failedRun)).resolves.toBeUndefined()
+ })
+})
diff --git a/frontend/src/test/playwright.quarantine.test.ts b/frontend/src/test/playwright.quarantine.test.ts
new file mode 100644
index 000000000000..bd67b3869dcb
--- /dev/null
+++ b/frontend/src/test/playwright.quarantine.test.ts
@@ -0,0 +1,119 @@
+import {
+ QuarantineEntry,
+ activePlaywrightEntries,
+ decideForTest,
+ parseQuarantine,
+ selectorMatches,
+} from '../../../playwright/playwright.quarantine'
+
+const TODAY = '2026-06-10'
+const REPO = '/repo'
+
+function entry(overrides: Partial<QuarantineEntry> = {}): QuarantineEntry {
+ return {
+ id: 'playwright/e2e/login.spec.ts',
+ mode: 'run',
+ reason: 'flaky',
+ owner: '@web',
+ issue: '',
+ expires: '2026-06-20',
+ ...overrides,
+ }
+}
+
+// This is a JS reimplementation of core.py's contract for runner: "playwright",
+// so it can drift from the Python source independently and needs its own lock.
+describe('playwright.quarantine', () => {
+ describe('selectorMatches', () => {
+ // The space boundary is the playwright-specific rule: a ::-qualified selector
+ // whose name carries spaces must still cover a nested describe/test.
+ test.each<[string, string, string, boolean]>([
+ ['file covers a test', 'playwright/e2e/login.spec.ts', 'playwright/e2e/login.spec.ts::A works', true],
+ ['directory prefix', 'playwright/e2e', 'playwright/e2e/login.spec.ts::A works', true],
+ ['describe via space', 'playwright/e2e/x.spec.ts::Auth', 'playwright/e2e/x.spec.ts::Auth logs in', true],
+ [
+ 'exact full name',
+ 'playwright/e2e/x.spec.ts::Auth logs in',
+ 'playwright/e2e/x.spec.ts::Auth logs in',
+ true,
+ ],
+ ['partial word', 'playwright/e2e/x.spec.ts::Au', 'playwright/e2e/x.spec.ts::Auth logs in', false],
+ ['product selector', 'product:batch-exports', 'products/batch_exports/frontend/e2e/x.spec.ts::A', true],
+ ['product mismatch', 'product:batch-exports', 'playwright/e2e/x.spec.ts::A', false],
+ ])('%s', (_label, selector, testId, expected) => {
+ expect(selectorMatches(selector, testId)).toBe(expected)
+ })
+ })
+
+ describe('activePlaywrightEntries', () => {
+ test('keeps only unexpired playwright entries', () => {
+ const raw = [
+ { id: 'a', runner: 'playwright', expires: '2026-06-20' },
+ { id: 'b', runner: 'playwright', expires: '2026-06-01' }, // expired
+ { id: 'c', expires: '2026-06-20' }, // defaults to pytest
+ { id: 'd', runner: 'jest', expires: '2026-06-20' },
+ { id: 'e', runner: 'playwright', mode: 'pause', expires: '2026-06-20' }, // invalid mode dropped
+ { id: 'f', runner: 'playwright', mode: 'skip', expires: '2026-06-20' },
+ ]
+ expect(activePlaywrightEntries(raw, TODAY).map((e) => e.id)).toEqual(['a', 'f'])
+ })
+
+ // A malformed expires must drop the entry (fail-safe), mirroring core.py's
+ // date.fromisoformat rejection. Without the ISO guard, the raw string compare
+ // sorts these after TODAY and would mask the test past its expiry forever.
+ test.each<[string, string]>([
+ ['non-zero-padded', '2026-9-05'],
+ ['non-date text', 'soon'],
+ ['impossible month', '2026-13-05'],
+ ])('drops an entry whose expires is %s', (_label, expires) => {
+ expect(activePlaywrightEntries([{ id: 'x', runner: 'playwright', expires }], TODAY)).toEqual([])
+ })
+ })
+
+ describe('decideForTest', () => {
+ // The genuinely new logic: assemble the repo-relative id from an absolute file +
+ // name parts, then pick the most specific match. Both the fixture and reporter call this.
+ const entries = [
+ entry({ id: 'playwright/e2e', mode: 'run' }),
+ entry({ id: 'playwright/e2e/login.spec.ts::Login', mode: 'skip', expires: '2026-06-25' }),
+ ]
+
+ test('the most specific selector wins so a narrow skip overrides a broad run', () => {
+ const decision = decideForTest(
+ entries,
+ '/repo/playwright/e2e/login.spec.ts',
+ ['Login', 'redirects home'],
+ REPO
+ )
+ expect(decision?.mode).toBe('skip')
+ expect(decision?.label).toContain('quarantined until 2026-06-25')
+ expect(decision?.label).toContain('flaky')
+ })
+
+ test('a test only covered by the broad entry runs', () => {
+ const decision = decideForTest(entries, '/repo/playwright/e2e/signup.spec.ts', ['Signup', 'works'], REPO)
+ expect(decision?.mode).toBe('run')
+ })
+
+ test('returns null when nothing matches', () => {
+ expect(decideForTest(entries, '/repo/products/x/frontend/e2e/x.spec.ts', ['A'], REPO)).toBeNull()
+ })
+ })
+
+ describe('parseQuarantine', () => {
+ test('reads v1 entries and drops ones without an id', () => {
+ const text = JSON.stringify({
+ version: 1,
+ entries: [{ id: 'playwright/e2e/x.spec.ts', runner: 'playwright' }, { runner: 'playwright' }],
+ })
+ expect(parseQuarantine(text).map((e) => e.id)).toEqual(['playwright/e2e/x.spec.ts'])
+ })
+
+ test.each<[string, string]>([
+ ['unsupported version', JSON.stringify({ version: 2, entries: [{ id: 'a' }] })],
+ ['entries not a list', JSON.stringify({ version: 1, entries: {} })],
+ ])('returns [] for %s', (_label, text) => {
+ expect(parseQuarantine(text)).toEqual([])
+ })
+ })
+})
diff --git a/playwright/playwright.config.ts b/playwright/playwright.config.ts
index b26b9a72c677..c98edc31e523 100644
--- a/playwright/playwright.config.ts
+++ b/playwright/playwright.config.ts
@@ -52,6 +52,9 @@ export default defineConfig({
workers: process.env.CI ? 3 : 6,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: [
+ // Enforces `mode: "run"` quarantine entries — tolerates their failures so
+ // flaky tests can't block CI (schema: .test_quarantine.json). No-op when empty.
+ ['./playwright.quarantine.reporter.ts'],
['html', { open: 'never' }],
...(process.env.CI ? [['junit', { outputFile: 'junit-results.xml' }] as const] : []),
...(process.env.CI ? [['json', { outputFile: 'results.json' }] as const] : []),
diff --git a/playwright/playwright.quarantine.reporter.ts b/playwright/playwright.quarantine.reporter.ts
new file mode 100644
index 000000000000..9116619a185d
--- /dev/null
+++ b/playwright/playwright.quarantine.reporter.ts
@@ -0,0 +1,133 @@
+/**
+ * Playwright reporter half of the test quarantine — enforces `mode: "run"`.
+ *
+ * Playwright has no native non-strict xfail, so a `mode: "run"` quarantined
+ * test still executes (keeping its timing/outcome in the html/junit/json
+ * reports) and this reporter tolerates a genuine failure: if the ONLY
+ * unexpected failures in the run are `mode: "run"` quarantined tests, it
+ * overrides the final run status to `passed` so they don't block CI. A single
+ * non-quarantined failure keeps the run red.
+ *
+ * Scope: this only flips the run-level status the CI exit code reads. The
+ * per-test outcome in junit-results.xml is written by the separate junit
+ * reporter and still records the failure, so a per-test consumer of that file
+ * (e.g. test-health ingestion) sees it as failed. Unlike pytest's xfail, the
+ * quarantine does not rewrite the per-test result, only the merge gate.
+ *
+ * The override is deliberately conservative: it fires ONLY when the run's final
+ * status is a plain `failed`, no `onError` fired, and every `unexpected` test
+ * outcome is covered by a `mode: "run"` entry. Anything surfaced through
+ * `onError` (global setup/teardown throw, uncaught error) or a non-`failed`
+ * final status (`timedout`, `interrupted`) keeps the run red, because masking a
+ * run-level problem would be far worse than a flaky test blocking a merge.
+ *
+ * Two accepted limitations follow from that conservatism:
+ * - Reaching `--max-failures` both fires `onError` ("Testing stopped early")
+ * and finalizes the run as `interrupted`, so once the cap is hit quarantine
+ * no longer suppresses those failures. That is the safe direction (stay
+ * red) and the alternative (overriding an `onError` run) is not worth it.
+ * - A mid-test worker crash (OOM/segfault) is attributed by Playwright to
+ * that test as `unexpected` rather than through `onError`, so a crash in a
+ * `mode: "run"` test is tolerated as that test's own failure. Playwright
+ * restarts the worker and re-runs the rest, so the blast radius is the
+ * quarantined test itself.
+ *
+ * `mode: "skip"` is handled earlier by the auto fixture in
+ * `utils/playwright-test-core.ts`; skipped tests never reach here as failures.
+ *
+ * Fail-open: if the quarantine file is missing or unreadable there are no
+ * active entries and this reporter is a no-op.
+ *
+ * Schema contract + matching: `playwright.quarantine.ts` (and core.py behind it).
+ */
+
+import type { FullResult, Reporter, Suite, TestCase } from '@playwright/test/reporter'
+
+import { QuarantineDecision, QuarantineEntry, decideForTest, loadActiveEntries } from './playwright.quarantine'
+
+/**
+ * Describe titles from the root down, then the test title — the playwright name
+ * parts. Anonymous `describe(() => {…})` blocks (empty title) are skipped, so
+ * this matches Playwright's own `titlePath()` that the skip fixture consumes via
+ * `info.titlePath` — otherwise the two enforcement halves derive different ids.
+ */
+export function nameParts(test: TestCase): string[] {
+ const describes: string[] = []
+ for (let suite: Suite | undefined = test.parent; suite && suite.type === 'describe'; suite = suite.parent) {
+ if (suite.title) {
+ describes.unshift(suite.title)
+ }
+ }
+ return [...describes, test.title]
+}
+
+export default class QuarantineReporter implements Reporter {
+ private readonly entries: QuarantineEntry[]
+ private rootSuite: Suite | undefined
+ private sawRunError = false
+
+ // entries is injectable so the onEnd override can be unit-tested without a
+ // file. Playwright itself constructs config-registered reporters with a
+ // reporter-options OBJECT (`{}` when none are configured), so anything that
+ // is not an array means "load from the quarantine file".
+ constructor(entries?: QuarantineEntry[] | object) {
+ this.entries = Array.isArray(entries) ? (entries as QuarantineEntry[]) : loadActiveEntries()
+ }
+
+ // We only emit occasional warnings, so let Playwright keep its default terminal reporter.
+ printsToStdio(): boolean {
+ return false
+ }
+
+ onBegin(_config: unknown, suite: Suite): void {
+ this.rootSuite = suite
+ }
+
+ // Errors outside test execution (worker crash, global setup/teardown, uncaught) land here,
+ // not as an `unexpected` test — record them so the override below never masks one.
+ onError(): void {
+ this.sawRunError = true
+ }
+
+ async onEnd(result: FullResult): Promise<{ status?: FullResult['status'] } | void> {
+ if (this.entries.length === 0 || !this.rootSuite) {
+ return
+ }
+ // Only a plain 'failed' run is a candidate. 'timedout' (global timeout), 'interrupted',
+ // and any run-level error are not per-test failures — never override them.
+ if (result.status !== 'failed' || this.sawRunError) {
+ return
+ }
+
+ const tolerated: QuarantineDecision[] = []
+ let realFailures = 0
+ for (const test of this.rootSuite.allTests()) {
+ if (test.outcome() !== 'unexpected') {
+ continue // Passed, skipped, or recovered-on-retry (flaky) — not a blocking failure.
+ }
+ const decision = decideForTest(this.entries, test.location.file, nameParts(test))
+ if (decision?.mode === 'run') {
+ tolerated.push(decision)
+ } else {
+ realFailures += 1
+ }
+ }
+
+ if (tolerated.length === 0) {
+ return // Nothing quarantined failed; the run stays red on its own merits.
+ }
+ for (const decision of tolerated) {
+ // eslint-disable-next-line no-console
+ console.warn(`[quarantine] tolerated failure in ${decision.label}`)
+ }
+ if (realFailures > 0) {
+ return // Real failures remain — keep the run red.
+ }
+ // eslint-disable-next-line no-console
+ console.warn(
+ `[quarantine] overriding run status to passed — the only ${tolerated.length} unexpected ` +
+ `failure(s) are quarantined (mode: run)`
+ )
+ return { status: 'passed' }
+ }
+}
diff --git a/playwright/playwright.quarantine.ts b/playwright/playwright.quarantine.ts
new file mode 100644
index 000000000000..7190450df7ca
--- /dev/null
+++ b/playwright/playwright.quarantine.ts
@@ -0,0 +1,212 @@
+/**
+ * Playwright adapter for the test quarantine — pure contract logic + loader.
+ *
+ * Schema contract: tools/hogli-commands/hogli_commands/quarantine/core.py — this
+ * file consumes that contract for `runner: "playwright"` entries and must not
+ * reimplement parsing, date handling, or matching beyond what it documents.
+ * It is the Playwright sibling of `quarantine/pytest_support.py`.
+ *
+ * A playwright id is `<repo-relative-spec>::<full test name>`, where the name is
+ * the space-joined ancestor `describe` titles plus the `test`/`it` title.
+ *
+ * The two halves of enforcement live next to this pure core:
+ * - `mode: "skip"` — an auto fixture in `utils/playwright-test-core.ts` calls
+ * `test.skip()` before the body runs (for hangs / state-polluters).
+ * - `mode: "run"` — Playwright has no native non-strict xfail, so the test
+ * still executes and `playwright.quarantine.reporter.ts` tolerates a
+ * failure by overriding the run status, keeping timing/outcome flowing.
+ *
+ * Fail-open: any problem reading or applying the file yields no active entries
+ * and the run proceeds normally. This module imports only Node stdlib so the
+ * pure logic can be unit-tested without pulling in `@playwright/test`.
+ */
+
+import * as fs from 'fs'
+import * as path from 'path'
+
+const SCHEMA_VERSION = 1
+// Mirrors PYTEST_RUNNER/PLAYWRIGHT_RUNNER in core.py; pytest is also the schema default when an entry omits `runner`.
+const PYTEST_RUNNER = 'pytest'
+const PLAYWRIGHT_RUNNER = 'playwright'
+const PRODUCT_PREFIX = 'product:'
+
+// __dirname is <repo>/playwright, so the repo root is one directory up.
+export const REPO_ROOT = path.resolve(__dirname, '..')
+const QUARANTINE_PATH = path.join(REPO_ROOT, '.test_quarantine.json')
+
+interface RawEntry {
+ id: string
+ runner?: string
+ mode?: string
+ reason?: string
+ owner?: string
+ issue?: string
+ added?: string
+ expires?: string
+}
+
+export interface QuarantineEntry {
+ id: string
+ mode: 'run' | 'skip'
+ reason: string
+ owner: string
+ issue: string
+ expires: string
+}
+
+export interface QuarantineDecision {
+ mode: 'run' | 'skip'
+ /** Human-readable line for skip warnings / tolerated-failure logs. */
+ label: string
+}
+
+// --- Pure contract logic (mirrors core.py; unit-tested in playwright.quarantine.test.ts) ---
+
+export function productPathPrefix(selector: string): string {
+ const name = selector.slice(PRODUCT_PREFIX.length)
+ return `products/${name.replace(/-/g, '_')}/`
+}
+
+/** Does `selector` cover `testId`? See the playwright grammar in core.py's docstring. */
+export function selectorMatches(selector: string, testId: string): boolean {
+ if (selector.startsWith(PRODUCT_PREFIX)) {
+ return testId.startsWith(productPathPrefix(selector))
+ }
+ const trimmed = selector.replace(/\/+$/, '')
+ return (
+ testId === trimmed ||
+ testId.startsWith(`${trimmed}/`) ||
+ testId.startsWith(`${trimmed}::`) ||
+ testId.startsWith(`${trimmed}[`) ||
+ testId.startsWith(`${trimmed} `)
+ )
+}
+
+function expandedSelector(selector: string): string {
+ return selector.startsWith(PRODUCT_PREFIX) ? productPathPrefix(selector) : selector
+}
+
+/** The most specific (longest) matching selector wins, so a narrow skip overrides a broad run. */
+export function findMatch(entries: QuarantineEntry[], testId: string): QuarantineEntry | null {
+ let best: QuarantineEntry | null = null
+ let bestLength = -1
+ for (const entry of entries) {
+ if (!selectorMatches(entry.id, testId)) {
+ continue
+ }
+ const length = expandedSelector(entry.id).length
+ if (length > bestLength) {
+ best = entry
+ bestLength = length
+ }
+ }
+ return best
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null
+}
+
+function isRawEntry(value: unknown): value is RawEntry {
+ return isRecord(value) && typeof value.id === 'string' && value.id.length > 0
+}
+
+/** Parse v1 quarantine JSON into raw entries. Throws only on invalid JSON (caller fails open). */
+export function parseQuarantine(text: string): RawEntry[] {
+ const data: unknown = JSON.parse(text)
+ if (!isRecord(data) || data.version !== SCHEMA_VERSION || !Array.isArray(data.entries)) {
+ return []
+ }
+ return data.entries.filter(isRawEntry)
+}
+
+/**
+ * True only for a real `YYYY-MM-DD` calendar date. `expires` is compared
+ * lexicographically below, so a non-zero-padded ('2026-9-05') or non-date
+ * ('soon') string would sort wrong and mask a test forever — core.py's
+ * `date.fromisoformat` rejects those, and this guard keeps the reader in step
+ * (fail-safe: an unparseable expiry drops the entry rather than activating it).
+ */
+export function isIsoDate(value: string): boolean {
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
+ return false
+ }
+ const parsed = new Date(`${value}T00:00:00Z`)
+ return !isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value
+}
+
+/** Unexpired `runner: "playwright"` entries only — other runners and expired entries are excluded. */
+export function activePlaywrightEntries(entries: RawEntry[], todayIso: string): QuarantineEntry[] {
+ const active: QuarantineEntry[] = []
+ for (const entry of entries) {
+ if ((entry.runner ?? PYTEST_RUNNER) !== PLAYWRIGHT_RUNNER) {
+ continue
+ }
+ if (typeof entry.expires !== 'string' || !isIsoDate(entry.expires) || entry.expires < todayIso) {
+ continue
+ }
+ if (entry.mode !== undefined && entry.mode !== 'run' && entry.mode !== 'skip') {
+ continue
+ }
+ active.push({
+ id: entry.id,
+ mode: entry.mode === 'skip' ? 'skip' : 'run',
+ reason: entry.reason ?? '',
+ owner: entry.owner ?? '',
+ issue: entry.issue ?? '',
+ expires: entry.expires,
+ })
+ }
+ return active
+}
+
+/** Repo-root-relative, forward-slash path for an absolute spec file path. */
+export function repoRelativePath(absolutePath: string, repoRoot: string = REPO_ROOT): string {
+ return path.relative(repoRoot, absolutePath).split(path.sep).join('/')
+}
+
+/** `<repo-relative-spec>::<describe… test>` — the canonical playwright id. */
+export function testId(fileRelPath: string, nameParts: string[]): string {
+ return `${fileRelPath}::${nameParts.join(' ')}`
+}
+
+function toDecision(entry: QuarantineEntry, id: string): QuarantineDecision {
+ const attribution = entry.issue || entry.owner || 'no owner'
+ return {
+ mode: entry.mode,
+ label: `${id} — quarantined until ${entry.expires}: ${entry.reason} (${attribution})`,
+ }
+}
+
+/** The active entry (as a decision) covering a test, or null. Shared by the fixture and reporter. */
+export function decideForTest(
+ entries: QuarantineEntry[],
+ absoluteFile: string,
+ nameParts: string[],
+ repoRoot: string = REPO_ROOT
+): QuarantineDecision | null {
+ const id = testId(repoRelativePath(absoluteFile, repoRoot), nameParts)
+ const entry = findMatch(entries, id)
+ return entry ? toDecision(entry, id) : null
+}
+
+// --- Loader (runtime side; fail-open) ---
+
+function todayIso(): string {
+ return new Date().toISOString().slice(0, 10)
+}
+
+/** Read the active playwright entries, or [] on any problem (missing/malformed file). */
+export function loadActiveEntries(quarantinePath: string = QUARANTINE_PATH): QuarantineEntry[] {
+ let text: string
+ try {
+ text = fs.readFileSync(quarantinePath, 'utf-8')
+ } catch {
+ return [] // A missing file means quarantine is simply off.
+ }
+ try {
+ return activePlaywrightEntries(parseQuarantine(text), todayIso())
+ } catch {
+ return [] // Malformed file: fail open rather than break the run.
+ }
+}
diff --git a/playwright/utils/playwright-test-core.ts b/playwright/utils/playwright-test-core.ts
index 2bf6a4a9d110..d9fa0c90cebb 100644
--- a/playwright/utils/playwright-test-core.ts
+++ b/playwright/utils/playwright-test-core.ts
@@ -1,7 +1,12 @@
import { Page, test as base } from '@playwright/test'
+import { decideForTest, loadActiveEntries } from '../playwright.quarantine'
import { Identifier, Navigation } from './navigation'
+// Read once per worker; a `mode: "skip"` match short-circuits the test below.
+// `mode: "run"` is enforced separately by playwright.quarantine.reporter.ts.
+const quarantineEntries = loadActiveEntries()
+
export const LOGIN_USERNAME = process.env.LOGIN_USERNAME || '[email protected]'
export const LOGIN_PASSWORD = process.env.LOGIN_PASSWORD || '12345678'
@@ -15,7 +20,7 @@ declare module '@playwright/test' {
* Core Playwright test base with page extensions but NO automatic login
* Use this as the foundation for workspace-based tests
*/
-export const test = base.extend<{ page: Page }>({
+export const test = base.extend<{ page: Page; _quarantine: void }>({
page: async ({ page }, use) => {
// Add custom methods to the page object
page.goToMenuItem = async function (name: Identifier): Promise<void> {
@@ -26,6 +31,29 @@ export const test = base.extend<{ page: Page }>({
// eslint-disable-next-line react-hooks/rules-of-hooks
await use(page)
},
+
+ // Auto fixture: skip a `mode: "skip"` quarantined test before its body runs.
+ // titlePath starts with the file name, so slice(1) is the describe/test name.
+ // Skip enforcement rides this base, so a spec must import `test` from here (or
+ // a base that extends it), not straight from `@playwright/test`, or its skip
+ // entries silently no-op. `mode: "run"` needs no base (the reporter sees all).
+ _quarantine: [
+ // eslint-disable-next-line no-empty-pattern -- Playwright fixtures require the deps arg; we use none.
+ async ({}, use) => {
+ if (quarantineEntries.length > 0) {
+ const info = test.info()
+ const decision = decideForTest(quarantineEntries, info.file, info.titlePath.slice(1))
+ if (decision?.mode === 'skip') {
+ // eslint-disable-next-line no-console
+ console.warn(`[quarantine] skipping ${decision.label}`)
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ test.skip(true, decision.label)
+ }
+ }
+ await use(undefined)
+ },
+ { auto: true },
+ ],
})
export { expect } from '@playwright/test'
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
index 1e743e94a602..2d033e502b73 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx
@@ -44,7 +44,7 @@ import {
// Runners with an enforcement adapter; mirrors ADAPTED_RUNNERS in the quarantine
// contract (tools/hogli-commands/hogli_commands/quarantine/core.py), which the frontend can't import.
-const ENFORCED_RUNNERS = ['pytest', 'jest']
+const ENFORCED_RUNNERS = ['pytest', 'jest', 'playwright']
function relativeExpiry(daysUntilExpiry: number): string {
if (daysUntilExpiry === 0) {
@@ -665,7 +665,7 @@ function QuarantineRegister(): JSX.Element {
<Tooltip
title={
isEnforced
- ? 'Enforced by the Jest adapter.'
+ ? `Enforced by the ${row.runner} adapter.`
: 'No enforcement adapter yet. This entry is informational.'
}
>
diff --git a/tools/hogli-commands/hogli_commands/quarantine/cli.py b/tools/hogli-commands/hogli_commands/quarantine/cli.py
index d1d4f9846f2f..0b244ee92108 100644
--- a/tools/hogli-commands/hogli_commands/quarantine/cli.py
+++ b/tools/hogli-commands/hogli_commands/quarantine/cli.py
@@ -86,7 +86,7 @@ def add(path: Path, selector_id: str, reason: str, owner: str, issue: str, days:
)
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()}.")
+ click.echo(f"Quarantined '{selector_id}' ({runner}/{mode}) until {entry.expires.isoformat()}.")
@quarantine.command(name="remove", help="Remove a quarantine entry for every runner (succeeds even if absent).")
diff --git a/tools/hogli-commands/hogli_commands/quarantine/core.py b/tools/hogli-commands/hogli_commands/quarantine/core.py
index ebb210030b7d..107c06b9c27d 100644
--- a/tools/hogli-commands/hogli_commands/quarantine/core.py
+++ b/tools/hogli-commands/hogli_commands/quarantine/core.py
@@ -2,7 +2,8 @@
This module is stdlib-only and runner-agnostic: it knows nothing about pytest
markers or CI. Runner adapters (``pytest_support``, ``jest.quarantine.ts``,
-``.github/scripts/turbo-discover.js``) consume the contract below and
+``playwright/playwright.quarantine.ts``, ``.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.
@@ -51,6 +52,18 @@ name after it may contain spaces. ``test.each`` row titles are resolved after
the adapter sees the declaration, so quarantine those at file, directory, or
``product:`` scope.
+Selector grammar (``id``, playwright): the same shape as jest. A playwright id
+is ``<repo-relative-spec>::<full test name>``, where the name is the
+space-joined ancestor ``describe`` titles plus the ``test``/``it`` title, with
+the same prefix and ``::`` rules.
+
+Caveat (jest and playwright): because names are space-joined and flat, the
+space boundary that lets a selector cover a nested ``describe`` cannot tell a
+leaf test name from a describe prefix. So a full-name selector also matches a
+sibling whose name begins with it plus a space (``::checkout pays`` covers
+``::checkout pays with coupon``). Prefer the narrowest describe title, or the
+spec path, when a sibling shares a word-prefix.
+
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.
@@ -83,10 +96,12 @@ MAX_QUARANTINE_DAYS = 30
DEFAULT_GRACE_DAYS = 7
PYTEST_RUNNER = "pytest" # also the schema default when an entry omits `runner`
JEST_RUNNER = "jest"
+PLAYWRIGHT_RUNNER = "playwright"
# Runners with an enforcement adapter that consumes this contract (pytest via
-# ``pytest_support``, jest via ``frontend/jest.quarantine.ts``). Entries for any
-# other runner are kept but only informational; ``check`` warns, never errors.
-ADAPTED_RUNNERS = (PYTEST_RUNNER, JEST_RUNNER)
+# ``pytest_support``, jest via ``frontend/jest.quarantine.ts``, playwright via
+# ``playwright/playwright.quarantine.ts``). Entries for any other runner are
+# kept but only informational; ``check`` warns, never errors.
+ADAPTED_RUNNERS = (PYTEST_RUNNER, JEST_RUNNER, PLAYWRIGHT_RUNNER)
MODES = ("run", "skip")
REPO_ROOT = Path(__file__).resolve().parents[4]
@@ -221,6 +236,8 @@ def selector_matches(selector: str, test_id: str) -> bool:
if selector.startswith(_PRODUCT_SELECTOR_PREFIX):
return test_id.startswith(product_path_prefix(selector))
selector = selector.rstrip("/")
+ # The trailing-space boundary lets a ``::``-qualified selector (whose name
+ # carries spaces, e.g. jest/playwright) cover a nested describe/test.
return test_id == selector or test_id.startswith((f"{selector}/", f"{selector}::", f"{selector}[", f"{selector} "))
@@ -268,17 +285,17 @@ def _entry_to_dict(entry: Entry) -> dict[str, Any]:
def validate_selector(selector: str, runner: str) -> str | None:
"""Selector validity for runners with an adapter; returns a violation message or None.
- Only pytest and jest selectors have rules; runners without an enforcement
- adapter are not validated here. ``product:`` selectors share one rule across
- runners; path selectors differ (jest ids carry a space-bearing test name
- after ``::``).
+ Only adapted runners (``ADAPTED_RUNNERS``) have rules; runners without an
+ enforcement adapter are not validated here. ``product:`` selectors share
+ one rule across runners; path selectors differ (jest and playwright ids
+ carry a space-bearing test name after ``::``).
"""
if runner not in ADAPTED_RUNNERS:
return None
if selector.startswith(_PRODUCT_SELECTOR_PREFIX):
return _validate_product_selector(selector)
- if runner == JEST_RUNNER:
- return _validate_jest_selector(selector)
+ if runner in (JEST_RUNNER, PLAYWRIGHT_RUNNER):
+ return _validate_name_qualified_selector(selector)
return _validate_pytest_selector(selector)
@@ -302,9 +319,9 @@ def _validate_pytest_selector(selector: str) -> str | None:
return None
-def _validate_jest_selector(selector: str) -> str | None:
- # A jest id is '<repo-relative-file>::<full test name>'; the name may hold
- # spaces, so only the path before '::' is constrained.
+def _validate_name_qualified_selector(selector: str) -> str | None:
+ # A jest or playwright id is '<repo-relative-file>::<full test name>'; the
+ # name may hold spaces, so only the path before '::' is constrained.
path_part = selector.split("::", 1)[0]
if not path_part:
return "missing a file path before '::'"
@@ -319,10 +336,12 @@ def check(result: LoadResult, today: date, grace_days: int = DEFAULT_GRACE_DAYS)
"""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.
+ more than ``MAX_QUARANTINE_DAYS`` after it, a future ``added`` (which
+ would un-anchor that window from today and let a hand-edited entry stay
+ active indefinitely), 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)
@@ -339,6 +358,12 @@ def check(result: LoadResult, today: date, grace_days: int = DEFAULT_GRACE_DAYS)
elif entry.expires - entry.added > timedelta(days=MAX_QUARANTINE_DAYS):
violations.append(f"{label}: quarantine window exceeds {MAX_QUARANTINE_DAYS} days")
+ # A future added would un-anchor the window from today: a hand-edited
+ # entry dated 2099 passes the window check yet stays active for decades.
+ # With added capped at today, the window check bounds expires too.
+ if entry.added > today:
+ violations.append(f"{label}: added {entry.added} is in the future")
+
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")
diff --git a/tools/hogli-commands/hogli_commands/tests/test_quarantine.py b/tools/hogli-commands/hogli_commands/tests/test_quarantine.py
index 5359e1bfbec3..c1758fa82bd3 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_quarantine.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_quarantine.py
@@ -100,6 +100,8 @@ def test_selector_matches(selector: str, test_id: str, expected: bool) -> None:
("frontend/src/x test.ts::name", "jest", False), # whitespace in the path part
("::name-only", "jest", False), # missing file path before ::
("product:batch_exports", "jest", False), # underscored product form
+ ("playwright/e2e/login.spec.ts::Login redirects home", "playwright", True), # spaces allowed after ::
+ ("playwright/e2e/login file.spec.ts::Login", "playwright", False), # whitespace in the path part
("anything at all", "some-future-runner", True), # unadapted runner: not validated
],
)
@@ -408,8 +410,22 @@ def test_list_shows_status(runner: CliRunner, tmp_path: Path) -> None:
),
# forward compat: a runner without an adapter (and an unknown field) warn but pass
([raw_entry(runner="some-future-runner", future_field="x")], 0, "no enforcement adapter"),
- # jest now has an enforcement adapter; a valid jest entry passes clean
+ # a hand-edited future-dated entry must fail check, not sit active for years
+ (
+ [
+ raw_entry(
+ runner="playwright",
+ id="playwright/e2e/x.spec.ts",
+ added=(core.today_utc() + timedelta(days=365)).isoformat(),
+ expires=(core.today_utc() + timedelta(days=395)).isoformat(),
+ )
+ ],
+ 1,
+ "is in the future",
+ ),
+ # jest and playwright have enforcement adapters; valid entries pass clean
([raw_entry(runner="jest", id="frontend/src/x.test.ts")], 0, "OK"),
+ ([raw_entry(runner="playwright", id="playwright/e2e/login.spec.ts::Login redirects home")], 0, "OK"),
# 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"),