: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(ci): jest quarantine adapter + selector validation (#67960)
Raúl Negrón-Otero76ddb4524f60
diff --git a/common/replay-shared/jest.config.js b/common/replay-shared/jest.config.jsindex 8c6814e0a2c0..8a8a02feb4e6 100644--- a/common/replay-shared/jest.config.js+++ b/common/replay-shared/jest.config.js@@ -5,6 +5,8 @@ module.exports = {// posthog-js's rrweb subpath entries are shipped as ESM; let them through to the transform.transformIgnorePatterns: ['node_modules/(?!.*posthog-js/dist/rrweb)'],testEnvironment: 'node',+ // Wraps the describe/it/test globals to enforce .test_quarantine.json jest entries.+ setupFilesAfterEnv: ['../../frontend/jest.quarantine.ts'],clearMocks: true,testMatch: ['<rootDir>/src/**/*.test.ts'],// CI sets JEST_JUNIT_OUTPUT_DIR to collect junit for the Trunk quarantine gate.diff --git a/frontend/jest.config.ts b/frontend/jest.config.tsindex 925be69c3053..fc3b18bd6a7e 100644--- a/frontend/jest.config.ts+++ b/frontend/jest.config.ts@@ -269,7 +269,12 @@ const config: Config = {setupFiles: ['<rootDir>/jest.polyfills.js', '<rootDir>/jest.setup.ts', 'fake-indexeddb/auto'],// A list of paths to modules that run some code to configure or set up the testing framework before each test- setupFilesAfterEnv: ['<rootDir>/jest.setupAfterEnv.ts', '<rootDir>/src/mocks/jest.ts'],+ // jest.quarantine.ts first so it wraps the describe/it/test globals before any test file declares tests.+ setupFilesAfterEnv: [+ '<rootDir>/jest.quarantine.ts',+ '<rootDir>/jest.setupAfterEnv.ts',+ '<rootDir>/src/mocks/jest.ts',+ ],// The number of seconds after which a test is considered as slow and reported as such in the results.// slowTestThreshold: 5,diff --git a/frontend/jest.quarantine.ts b/frontend/jest.quarantine.tsnew file mode 100644index 000000000000..41d377b52497--- /dev/null+++ b/frontend/jest.quarantine.ts@@ -0,0 +1,535 @@+/**+ * Jest adapter for the test quarantine.+ *+ * Schema contract: tools/hogli-commands/hogli_commands/quarantine/core.py; this+ * file consumes that contract for `runner: "jest"` entries and must not+ * reimplement parsing, date handling, or matching beyond what it documents.+ * It is the jest sibling of `quarantine/pytest_support.py`.+ *+ * A jest id is `<repo-relative-file>::<full test name>`, where the name is the+ * space-joined ancestor `describe` titles plus the `it`/`test` title (jest's+ * `currentTestName`). Installed as a `setupFilesAfterEnv` module, it wraps the+ * `describe`/`it`/`test` globals and lifecycle hooks so a matching active entry+ * either skips the test (`mode: "skip"`, for hangs/state-polluters) or+ * tolerates its body and matching hook failures (`mode: "run"`, since jest has+ * no native non-strict xfail, so failures are swallowed instead of failing the+ * suite).+ *+ * Fail-open: any problem reading or applying the file leaves the globals+ * untouched and the run proceeds normally.+ *+ * Granularity note: `describe.each` block titles and `it.each` row titles are+ * resolved by jest after this wrapper runs, so those are matched at file /+ * directory / `product:` scope only, not by exact test name.+ */++import * as fs from 'fs'+import * as path from 'path'++const SCHEMA_VERSION = 1+// Mirrors PYTEST_RUNNER/JEST_RUNNER in core.py; pytest is also the schema default when an entry omits `runner`.+const PYTEST_RUNNER = 'pytest'+const JEST_RUNNER = 'jest'+const PRODUCT_PREFIX = 'product:'++// __dirname is <repo>/frontend, so the repo root is one directory up.+const REPO_ROOT = path.resolve(__dirname, '..')+// Overridable so the adapter's own runtime test can point a spawned jest worker+// at an isolated fixture file instead of the committed repo-root one.+const QUARANTINE_PATH = process.env.POSTHOG_TEST_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+}++// --- Pure contract logic (mirrors core.py; unit-tested in jest.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 jest grammar in core.py's module 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)+}++/**+ * Expiry compares lexicographically, so a malformed date (e.g. `2026-9-05` or free+ * text) would sort after today and quarantine a test forever. The contract'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: "jest"` entries only; other runners and expired entries are excluded. */+export function activeJestEntries(entries: RawEntry[], todayIso: string): QuarantineEntry[] {+ const active: QuarantineEntry[] = []+ for (const entry of entries) {+ if ((entry.runner ?? PYTEST_RUNNER) !== JEST_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 a jest `testPath` (absolute). */+export function repoRelativePath(absolutePath: string, repoRoot: string = REPO_ROOT): string {+ return path.relative(repoRoot, absolutePath).split(path.sep).join('/')+}++// --- Runtime wiring: read the file, then wrap the jest globals ---++let activeEntries: QuarantineEntry[] = []+const describeStack: string[] = []++interface Decision {+ mode: 'run' | 'skip'+ label: string+}++function todayIso(): string {+ return new Date().toISOString().slice(0, 10)+}++function loadActiveEntries(): QuarantineEntry[] {+ let text: string+ try {+ text = fs.readFileSync(QUARANTINE_PATH, 'utf-8')+ } catch {+ return [] // A missing file means quarantine is simply off.+ }+ let raw: RawEntry[]+ try {+ raw = parseQuarantine(text)+ } catch {+ return [] // Malformed file: fail open rather than break collection.+ }+ return activeJestEntries(raw, todayIso())+}++function stringifyName(name: unknown): string {+ if (typeof name === 'function') {+ return (name as { name?: string }).name ?? ''+ }+ return String(name)+}++// `expect` may not be initialized yet while setup files run, so read defensively.+function jestState(): ReturnType<typeof expect.getState> | undefined {+ try {+ return expect.getState()+ } catch {+ return undefined+ }+}++function currentTestPath(): string | undefined {+ return jestState()?.testPath ?? undefined+}++function currentTestName(): string | undefined {+ const name = jestState()?.currentTestName+ return typeof name === 'string' && name.length > 0 ? name : undefined+}++function toDecision(entry: QuarantineEntry, testId: string): Decision {+ const attribution = entry.issue || entry.owner || 'no owner'+ return {+ mode: entry.mode,+ label: `${testId}: quarantined until ${entry.expires}: ${entry.reason} (${attribution})`,+ }+}++// testPath is constant for a whole file run, so cache its repo-relative form+// rather than recomputing path.relative on every test declaration.+let cachedTestPath: string | undefined+let cachedRelativePath = ''++function relativeTestPath(): string | null {+ const testPath = currentTestPath()+ if (testPath === undefined) {+ return null+ }+ if (testPath !== cachedTestPath) {+ cachedTestPath = testPath+ cachedRelativePath = repoRelativePath(testPath)+ }+ return cachedRelativePath+}++function decideFor(testId: string): Decision | null {+ const entry = findMatch(activeEntries, testId)+ return entry ? toDecision(entry, testId) : null+}++function decideForTest(name: unknown): Decision | null {+ const relativePath = relativeTestPath()+ if (relativePath === null) {+ return null+ }+ return decideFor(`${relativePath}::${[...describeStack, stringifyName(name)].join(' ')}`)+}++function decideForRunningTest(): Decision | null {+ const relativePath = relativeTestPath()+ const name = currentTestName()+ if (relativePath === null || name === undefined) {+ return null+ }+ return decideFor(`${relativePath}::${name}`)+}++function decideForFile(): Decision | null {+ const relativePath = relativeTestPath()+ return relativePath === null ? null : decideFor(relativePath)+}++function decideForScope(): Decision | null {+ const relativePath = relativeTestPath()+ if (relativePath === null) {+ return null+ }+ const scopeId = describeStack.length > 0 ? `${relativePath}::${describeStack.join(' ')}` : relativePath+ return decideFor(scopeId)+}++function errorText(error: unknown): string {+ if (error instanceof Error) {+ return error.stack ?? error.message+ }+ return String(error)+}++function warn(message: string): void {+ // eslint-disable-next-line no-console+ console.warn(message)+}++function warnSkip(decision: Decision): void {+ warn(`[quarantine] skipping ${decision.label}`)+}++function warnTolerated(decision: Decision, error: unknown): void {+ warn(`[quarantine] tolerated failure in ${decision.label}\n${errorText(error)}`)+}++function isThenable(value: unknown): value is PromiseLike<unknown> {+ return isRecord(value) && typeof (value as { then?: unknown }).then === 'function'+}++/** Run a callback swallowing any thrown error or rejected promise (jest's non-strict xfail analog). */+function tolerate(fn: (...args: unknown[]) => unknown, decision: Decision): (...args: unknown[]) => unknown {+ return function (this: unknown, ...args: unknown[]): unknown {+ try {+ const result = fn.apply(this, args)+ if (isThenable(result)) {+ return result.then(undefined, (error: unknown) => {+ warnTolerated(decision, error)+ return undefined+ })+ }+ return result+ } catch (error) {+ warnTolerated(decision, error)+ return undefined+ }+ }+}++function runDoneStyle(+ fn: (done: jest.DoneCallback) => void,+ decision: Decision,+ done: jest.DoneCallback,+ thisArg: unknown+): void {+ const tolerantDone = function (): void {+ done()+ } as jest.DoneCallback+ tolerantDone.fail = function (): void {+ done()+ }+ try {+ fn.call(thisArg, tolerantDone)+ } catch (error) {+ warnTolerated(decision, error)+ done()+ }+}++/**+ * Tolerate an `it`/`test` body or hook, handling the done-callback style that+ * `tolerate` can't (it swallows via the promise/throw path).+ */+function tolerateProvidesWhen(+ fn: jest.ProvidesCallback | undefined,+ getDecision: () => Decision | null+): jest.ProvidesCallback | undefined {+ if (typeof fn !== 'function') {+ return fn+ }+ if (fn.length >= 1) {+ const doneStyle = fn as (done: jest.DoneCallback) => void+ return function (this: unknown, done: jest.DoneCallback): void {+ const decision = getDecision()+ if (decision === null || decision.mode !== 'run') {+ doneStyle.call(this, done)+ return+ }+ runDoneStyle(doneStyle, decision, done, this)+ }+ }+ return function (this: unknown): unknown {+ const decision = getDecision()+ if (decision === null || decision.mode !== 'run') {+ return (fn as () => unknown).call(this)+ }+ return tolerate(fn as () => unknown, decision).call(this)+ } as jest.ProvidesCallback+}++function tolerateProvides(+ fn: jest.ProvidesCallback | undefined,+ decision: Decision+): jest.ProvidesCallback | undefined {+ return tolerateProvidesWhen(fn, () => decision)+}++/** Copy every own member (skip/only/todo/each/…) from a jest global onto its wrapper. */+function copyMembers(target: object, source: object): void {+ for (const key of Object.getOwnPropertyNames(source)) {+ if (key === 'length' || key === 'name' || key === 'prototype') {+ continue+ }+ const descriptor = Object.getOwnPropertyDescriptor(source, key)+ if (descriptor) {+ Object.defineProperty(target, key, descriptor)+ }+ }+}++type EachFactory = (name: string, fn: (...args: unknown[]) => unknown, timeout?: number) => void+type EachEntry = (...args: unknown[]) => EachFactory++/** File-scope `.each`: skip or tolerate the whole table (row titles aren't known here). */+function wrapEach(base: jest.It, skipBase: jest.It): jest.Each {+ const wrapped = (...eachArgs: unknown[]): EachFactory => {+ const factory = (base.each as unknown as EachEntry)(...eachArgs)+ const decision = decideForFile()+ if (decision === null) {+ return factory+ }+ if (decision.mode === 'skip') {+ warnSkip(decision)+ return (skipBase.each as unknown as EachEntry)(...eachArgs)+ }+ return (name: string, fn: (...args: unknown[]) => unknown, timeout?: number): void => {+ factory(name, tolerate(fn, decision), timeout)+ }+ }+ return wrapped as unknown as jest.Each+}++function wrapIt(original: jest.It, wrapConcurrent = true): jest.It {+ const run = (source: jest.It, name: string, fn?: jest.ProvidesCallback, timeout?: number): void => {+ const decision = decideForTest(name)+ if (decision === null) {+ source(name, fn, timeout)+ return+ }+ if (decision.mode === 'skip') {+ warnSkip(decision)+ original.skip(name, fn, timeout)+ return+ }+ source(name, tolerateProvides(fn, decision), timeout)+ }++ const wrapped = ((name: string, fn?: jest.ProvidesCallback, timeout?: number): void => {+ run(original, name, fn, timeout)+ }) as jest.It+ copyMembers(wrapped, original)++ const wrappedOnly = ((name: string, fn?: jest.ProvidesCallback, timeout?: number): void => {+ run(original.only, name, fn, timeout)+ }) as jest.It+ copyMembers(wrappedOnly, original.only)+ wrappedOnly.each = wrapEach(original.only, original.skip)+ wrapped.only = wrappedOnly++ if (wrapConcurrent && typeof original.concurrent === 'function') {+ wrapped.concurrent = wrapIt(original.concurrent, false)+ }+ wrapped.each = wrapEach(original, original.skip)+ return wrapped+}++type DescribeName = Parameters<jest.Describe>[0]+type DescribeBody = Parameters<jest.Describe>[1]++function wrapDescribeVariant(variant: jest.Describe): jest.Describe {+ const wrapped = ((name: DescribeName, fn: DescribeBody): void => {+ variant(name, function (this: unknown): void {+ describeStack.push(stringifyName(name))+ try {+ fn.call(this)+ } finally {+ describeStack.pop()+ }+ })+ }) as jest.Describe+ copyMembers(wrapped, variant)+ return wrapped+}++function wrapDescribe(original: jest.Describe): jest.Describe {+ const wrapped = wrapDescribeVariant(original)+ // `.only`/`.skip` also nest, so keep the stack correct through them.+ wrapped.only = wrapDescribeVariant(original.only)+ wrapped.skip = wrapDescribeVariant(original.skip)+ return wrapped+}++function wrapLifecycle(+ original: jest.Lifecycle,+ getDecision: () => Decision | null,+ useDeclarationDecision = false+): jest.Lifecycle {+ return ((fn: jest.ProvidesHookCallback, timeout?: number): void => {+ const declarationDecision = useDeclarationDecision ? getDecision() : null+ original(+ tolerateProvidesWhen(+ fn as jest.ProvidesCallback,+ () => declarationDecision ?? getDecision()+ ) as jest.ProvidesHookCallback,+ timeout+ )+ }) as jest.Lifecycle+}++function install(entries: QuarantineEntry[]): void {+ if (entries.length === 0) {+ return+ }+ const globals = globalThis as typeof globalThis & {+ describe: jest.Describe+ it: jest.It+ test: jest.It+ beforeEach: jest.Lifecycle+ afterEach: jest.Lifecycle+ beforeAll: jest.Lifecycle+ afterAll: jest.Lifecycle+ }+ if (typeof globals.describe === 'function') {+ globals.describe = wrapDescribe(globals.describe)+ }+ if (typeof globals.it === 'function') {+ globals.it = wrapIt(globals.it)+ }+ if (typeof globals.test === 'function') {+ globals.test = wrapIt(globals.test)+ }+ if (typeof globals.beforeEach === 'function') {+ globals.beforeEach = wrapLifecycle(globals.beforeEach, decideForRunningTest)+ }+ if (typeof globals.afterEach === 'function') {+ globals.afterEach = wrapLifecycle(globals.afterEach, decideForRunningTest)+ }+ if (typeof globals.beforeAll === 'function') {+ globals.beforeAll = wrapLifecycle(globals.beforeAll, decideForScope, true)+ }+ if (typeof globals.afterAll === 'function') {+ globals.afterAll = wrapLifecycle(globals.afterAll, decideForScope, true)+ }+}++try {+ activeEntries = loadActiveEntries()+ install(activeEntries)+} catch (error) {+ warn(`[quarantine] disabled: ${errorText(error)}`)+}diff --git a/frontend/src/test/jest.quarantine.runtime.fixture.ts b/frontend/src/test/jest.quarantine.runtime.fixture.tsnew file mode 100644index 000000000000..01a1bcddcf53--- /dev/null+++ b/frontend/src/test/jest.quarantine.runtime.fixture.ts@@ -0,0 +1,44 @@+function currentFixtureTestName(): string | undefined {+ const state = (globalThis as typeof globalThis & { expect: jest.Expect }).expect.getState()+ return typeof state.currentTestName === 'string' ? state.currentTestName : undefined+}++describe('jest quarantine runtime fixture', () => {+ beforeAll(() => {+ if (currentFixtureTestName() === undefined) {+ throw new Error('quarantined beforeAll failure')+ }+ })++ beforeEach(() => {+ if (currentFixtureTestName()?.includes('tolerates beforeEach failure')) {+ throw new Error('quarantined beforeEach failure')+ }+ })++ afterEach(() => {+ if (currentFixtureTestName()?.includes('tolerates afterEach failure')) {+ throw new Error('quarantined afterEach failure')+ }+ })++ test('tolerates body failure', () => {+ throw new Error('quarantined body failure')+ })++ test('tolerates async rejection', async () => {+ throw new Error('quarantined async failure')+ })++ test('tolerates beforeEach failure', () => {+ expect(true).toBe(true)+ })++ test('tolerates afterEach failure', () => {+ expect(true).toBe(true)+ })++ test('skips body', () => {+ throw new Error('skipped body should not run')+ })+})diff --git a/frontend/src/test/jest.quarantine.test.ts b/frontend/src/test/jest.quarantine.test.tsnew file mode 100644index 000000000000..9dcce5875346--- /dev/null+++ b/frontend/src/test/jest.quarantine.test.ts@@ -0,0 +1,177 @@+import { spawnSync } from 'child_process'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'++import {+ activeJestEntries,+ findMatch,+ parseQuarantine,+ productPathPrefix,+ QuarantineEntry,+ repoRelativePath,+ selectorMatches,+} from '../../jest.quarantine'++const TODAY = '2026-06-10'+const REPO_ROOT = path.resolve(__dirname, '../../..')+const FRONTEND_DIR = path.join(REPO_ROOT, 'frontend')+const RUNTIME_FIXTURE_ID = 'frontend/src/test/jest.quarantine.runtime.fixture.ts'+const RUNTIME_FIXTURE_MATCH = '**/jest.quarantine.runtime.fixture.ts'++function entry(overrides: Partial<QuarantineEntry> = {}): QuarantineEntry {+ return {+ id: 'frontend/src/x.test.ts',+ mode: 'run',+ reason: 'flaky',+ owner: '@web',+ issue: '',+ expires: '2026-06-20',+ ...overrides,+ }+}++function runtimeEntry(id: string, mode: 'run' | 'skip' = 'run'): Record<string, string> {+ return {+ id,+ runner: 'jest',+ reason: 'runtime quarantine adapter test',+ owner: '@team-devex',+ added: TODAY,+ expires: '2099-12-31',+ mode,+ }+}++describe('jest.quarantine', () => {+ describe('selectorMatches', () => {+ // The JS reimplements core.py's grammar, so it can drift independently; these lock it.+ test.each<[string, string, string, boolean]>([+ ['file covers a test in it', 'frontend/src/x.test.ts', 'frontend/src/x.test.ts::A loads', true],+ ['directory prefix', 'frontend/src', 'frontend/src/x.test.ts::A loads', true],+ ['directory trailing slash', 'frontend/src/', 'frontend/src/x.test.ts::A loads', true],+ ['describe prefix via space', 'frontend/src/x.test.ts::A', 'frontend/src/x.test.ts::A loads data', true],+ ['exact full name', 'frontend/src/x.test.ts::A loads', 'frontend/src/x.test.ts::A loads', true],+ ['partial describe word', 'frontend/src/x.test.ts::A lo', 'frontend/src/x.test.ts::A loads', false],+ ['product selector', 'product:batch-exports', 'products/batch_exports/frontend/x.test.ts::A', true],+ ['product mismatch', 'product:batch-exports', 'frontend/src/x.test.ts::A', false],+ ['unrelated sibling file', 'frontend/src/x.test.ts', 'frontend/src/xy.test.ts::A', false],+ ])('%s', (_label, selector, testId, expected) => {+ expect(selectorMatches(selector, testId)).toBe(expected)+ })+ })++ describe('activeJestEntries', () => {+ test('keeps only unexpired jest entries', () => {+ const raw = [+ { id: 'a', runner: 'jest', expires: '2026-06-20' },+ { id: 'b', runner: 'jest', expires: '2026-06-01' }, // expired+ { id: 'c', expires: '2026-06-20' }, // defaults to pytest+ { id: 'd', runner: 'pytest', expires: '2026-06-20' },+ { id: 'e', runner: 'jest', mode: 'pause', expires: '2026-06-20' }, // invalid mode dropped+ { id: 'f', runner: 'jest', mode: 'skip', expires: '2026-06-20' },+ { id: 'g', runner: 'jest', expires: 'not-a-date' }, // malformed expiry would sort after today and mask forever+ { id: 'h', runner: 'jest', expires: '2026-9-05' }, // non-canonical ISO, same trap+ ]+ expect(activeJestEntries(raw, TODAY).map((e) => e.id)).toEqual(['a', 'f'])+ })+ })++ describe('findMatch', () => {+ test('the most specific selector wins so a narrow skip overrides a broad run', () => {+ const entries = [+ entry({ id: 'frontend/src/x.test.ts', mode: 'run' }),+ entry({ id: 'frontend/src/x.test.ts::A loads', mode: 'skip' }),+ ]+ expect(findMatch(entries, 'frontend/src/x.test.ts::A loads')?.mode).toBe('skip')+ expect(findMatch(entries, 'frontend/src/x.test.ts::B other')?.mode).toBe('run')+ })++ test('returns null when nothing matches', () => {+ expect(findMatch([entry()], 'frontend/src/other.test.ts::A')).toBeNull()+ })+ })++ describe('parseQuarantine', () => {+ test('reads v1 entries and drops ones without an id', () => {+ const text = JSON.stringify({+ version: 1,+ entries: [{ id: 'frontend/src/x.test.ts', runner: 'jest' }, { runner: 'jest' }],+ })+ expect(parseQuarantine(text).map((e) => e.id)).toEqual(['frontend/src/x.test.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([])+ })+ })++ describe('repoRelativePath', () => {+ test('makes an absolute test path repo-root-relative with forward slashes', () => {+ expect(repoRelativePath('/repo/frontend/src/x.test.ts', '/repo')).toBe('frontend/src/x.test.ts')+ })+ })++ describe('productPathPrefix', () => {+ test('maps a dashed product name to the underscored directory', () => {+ expect(productPathPrefix('product:batch-exports')).toBe('products/batch_exports/')+ })+ })++ describe('runtime adapter', () => {+ test('enforces skip and tolerated failures in a real jest worker', () => {+ expect.hasAssertions()+ const fixtureSuiteId = `${RUNTIME_FIXTURE_ID}::jest quarantine runtime fixture`+ const payload = {+ version: 1,+ entries: [+ runtimeEntry(fixtureSuiteId),+ runtimeEntry(`${fixtureSuiteId} tolerates body failure`),+ runtimeEntry(`${fixtureSuiteId} tolerates async rejection`),+ runtimeEntry(`${fixtureSuiteId} tolerates beforeEach failure`),+ runtimeEntry(`${fixtureSuiteId} tolerates afterEach failure`),+ runtimeEntry(`${fixtureSuiteId} skips body`, 'skip'),+ ],+ }++ // Write to an isolated temp file, never the committed repo-root one, so parallel+ // workers and a killed run can't read or leave behind fixture-only entries.+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jest-quarantine-'))+ const quarantinePath = path.join(tmpDir, '.test_quarantine.json')+ try {+ fs.writeFileSync(quarantinePath, `${JSON.stringify(payload, null, 4)}\n`)+ const result = spawnSync(+ path.join(FRONTEND_DIR, 'node_modules/.bin/jest'),+ [+ '--config',+ path.join(FRONTEND_DIR, 'jest.config.ts'),+ '--runInBand',+ '--no-cache',+ '--testMatch',+ RUNTIME_FIXTURE_MATCH,+ ],+ {+ cwd: FRONTEND_DIR,+ encoding: 'utf-8',+ env: { ...process.env, CI: '1', POSTHOG_TEST_QUARANTINE_PATH: quarantinePath },+ }+ )+ const output = `${result.stdout}\n${result.stderr}`+ if (result.status !== 0) {+ throw new Error(`fixture jest run failed with status ${result.status}\n${output}`)+ }+ expect(output).toContain('[quarantine] tolerated failure')+ expect(output).toContain('quarantined body failure')+ expect(output).toContain('quarantined beforeEach failure')+ expect(output).toContain('quarantined afterEach failure')+ expect(output).toContain('[quarantine] skipping')+ expect(output).not.toContain('skipped body should not run')+ } finally {+ fs.rmSync(tmpDir, { recursive: true, force: true })+ }+ }, 30000)+ })+})diff --git a/nodejs/jest.config.js b/nodejs/jest.config.jsindex ef14b3fbedf5..1f5f0f59d19a 100644--- a/nodejs/jest.config.js+++ b/nodejs/jest.config.js@@ -13,7 +13,8 @@ module.exports = {clearMocks: true,coverageProvider: 'v8',setupFiles: ['./jest.setup-env.ts'],- setupFilesAfterEnv: ['./jest.setup.ts'],+ // jest.quarantine.ts first so it wraps the describe/it/test globals before any test file declares tests.+ setupFilesAfterEnv: ['../frontend/jest.quarantine.ts', './jest.setup.ts'],testMatch: ['<rootDir>/tests/**/*.test.ts', '<rootDir>/src/**/*.test.ts'],testTimeout: 60000,// The image-scrub sidecar is a standalone package with its own jest run; keep the plugin-server suite out of it.diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsxindex d3abadc76d10..1e743e94a602 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx@@ -42,6 +42,10 @@ import {flakyEvidenceReason,} from './engineeringAnalyticsLogic'+// 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']+function relativeExpiry(daysUntilExpiry: number): string {if (daysUntilExpiry === 0) {return 'today'@@ -646,25 +650,34 @@ function QuarantineRegister(): JSX.Element {{title: 'Selector',key: 'id',- render: (_, row) => (- <div className="flex max-w-[28rem] flex-col gap-0.5">- <Tooltip title={row.id}>- <span className="truncate font-mono text-xs">{row.id}</span>- </Tooltip>- <div className="flex items-center gap-1.5">- <LemonTag type="option" size="small">- {row.selectorKind}- </LemonTag>- {row.runner !== 'pytest' && (- <Tooltip title="No enforcement adapter yet. This entry is informational.">- <LemonTag type="muted" size="small">- {row.runner}- </LemonTag>- </Tooltip>- )}+ render: (_, row) => {+ const isEnforced = ENFORCED_RUNNERS.includes(row.runner)+ return (+ <div className="flex max-w-[28rem] flex-col gap-0.5">+ <Tooltip title={row.id}>+ <span className="truncate font-mono text-xs">{row.id}</span>+ </Tooltip>+ <div className="flex items-center gap-1.5">+ <LemonTag type="option" size="small">+ {row.selectorKind}+ </LemonTag>+ {row.runner !== 'pytest' && (+ <Tooltip+ title={+ isEnforced+ ? 'Enforced by the Jest adapter.'+ : 'No enforcement adapter yet. This entry is informational.'+ }+ >+ <LemonTag type={isEnforced ? 'option' : 'muted'} size="small">+ {row.runner}+ </LemonTag>+ </Tooltip>+ )}+ </div></div>- </div>- ),+ )+ },},{title: 'Mode',diff --git a/tools/hogli-commands/hogli_commands/quarantine/cli.py b/tools/hogli-commands/hogli_commands/quarantine/cli.pyindex 1559425f8d27..d1d4f9846f2f 100644--- a/tools/hogli-commands/hogli_commands/quarantine/cli.py+++ b/tools/hogli-commands/hogli_commands/quarantine/cli.py@@ -58,11 +58,18 @@ def _load_for_writing(path: Path) -> core.LoadResult: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).",+ help="run = still executes with tolerated failures; skip = not executed (hangs, state-polluters).",+)+ "--runner",+ type=click.Choice(core.ADAPTED_RUNNERS),+ default=core.PYTEST_RUNNER,+ show_default=True,+ help="Which enforcement adapter interprets the selector.",)@click.pass_obj-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)+def add(path: Path, selector_id: str, reason: str, owner: str, issue: str, days: int, mode: str, runner: str) -> None:+ selector_problem = core.validate_selector(selector_id, runner)if selector_problem is not None:raise click.ClickException(f"invalid selector '{selector_id}': {selector_problem}")result = _load_for_writing(path)@@ -71,6 +78,7 @@ def add(path: Path, selector_id: str, reason: str, owner: str, issue: str, days:id=selector_id,added=today,expires=today + timedelta(days=days),+ runner=runner,reason=reason,owner=owner,issue=issue,diff --git a/tools/hogli-commands/hogli_commands/quarantine/core.py b/tools/hogli-commands/hogli_commands/quarantine/core.pyindex 9be69189d0a0..ebb210030b7d 100644--- a/tools/hogli-commands/hogli_commands/quarantine/core.py+++ b/tools/hogli-commands/hogli_commands/quarantine/core.py@@ -1,7 +1,7 @@"""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,+markers or CI. Runner adapters (``pytest_support``, ``jest.quarantine.ts``,``.github/scripts/turbo-discover.js``) consume the contract below andinterpret selectors for their runner; they must not reimplement parsing,date handling, or matching beyond what is documented here.@@ -25,11 +25,11 @@ File format (repo root, sorted by ``id``, 4-space indent, trailing newline)::}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).+the matching test still executes but tolerated failures do not 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):@@ -37,10 +37,20 @@ Selector grammar (``id``, pytest):- prefix: a directory (``posthog/api/test``), file (``.../test_foo.py``),class (``...::TestFoo``), or test function (``...::test_bar``) — matcheseverything 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)+ the nodeid is a ``/``, ``::``, ``[``, or space boundary (so a function+ selector covers its parameterized variants, and partial names never match)- ``product:<dashed-name>``: everything under ``products/<name_with_underscores>/``+Selector grammar (``id``, jest): a jest id is ``<repo-relative-file>::<full+test name>``, where the name is the space-joined ancestor ``describe`` titles+plus the ``it``/``test`` title (jest's ``currentTestName``). The same prefix+rules apply: a file, directory, or ``product:`` selector covers every test+under it, and a ``::``-qualified selector covers a describe block (space+boundary) or an exact test. Only the path before ``::`` is constrained; the+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.+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.@@ -71,7 +81,12 @@ from typing import AnySCHEMA_VERSION = 1MAX_QUARANTINE_DAYS = 30DEFAULT_GRACE_DAYS = 7-DEFAULT_RUNNER = "pytest"+PYTEST_RUNNER = "pytest" # also the schema default when an entry omits `runner`+JEST_RUNNER = "jest"+# 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)MODES = ("run", "skip")REPO_ROOT = Path(__file__).resolve().parents[4]@@ -86,7 +101,7 @@ class Entry:id: stradded: dateexpires: date- runner: str = DEFAULT_RUNNER+ runner: str = PYTEST_RUNNERreason: str = ""owner: str = ""issue: str = ""@@ -182,7 +197,7 @@ def _parse_entry(raw: Any, index: int, result: LoadResult) -> Entry | None:id=raw["id"],added=dates["added"],expires=dates["expires"],- runner=raw.get("runner", DEFAULT_RUNNER),+ runner=raw.get("runner", PYTEST_RUNNER),reason=raw.get("reason", ""),owner=raw.get("owner", ""),issue=raw.get("issue", ""),@@ -206,7 +221,7 @@ 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("/")- return test_id == selector or test_id.startswith((f"{selector}/", f"{selector}::", f"{selector}["))+ return test_id == selector or test_id.startswith((f"{selector}/", f"{selector}::", f"{selector}[", f"{selector} "))def product_path_prefix(selector: str) -> str:@@ -251,23 +266,35 @@ def _entry_to_dict(entry: Entry) -> dict[str, Any]:def validate_selector(selector: str, runner: str) -> str | None:- """Selector validity for known runners; returns a violation message or None.+ """Selector validity for runners with an adapter; 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.+ 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 ``::``)."""- if runner != DEFAULT_RUNNER:+ if runner not in ADAPTED_RUNNERS:return Noneif 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+ return _validate_product_selector(selector)+ if runner == JEST_RUNNER:+ return _validate_jest_selector(selector)+ return _validate_pytest_selector(selector)+++def _validate_product_selector(selector: str) -> str | None:+ 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+++def _validate_pytest_selector(selector: str) -> str | None:if selector.startswith("/") or selector.startswith("\\"):return "must be repo-root-relative, not absolute"if any(c.isspace() for c in selector):@@ -275,6 +302,19 @@ def validate_selector(selector: str, runner: 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.+ path_part = selector.split("::", 1)[0]+ if not path_part:+ return "missing a file path before '::'"+ if path_part.startswith("/") or path_part.startswith("\\"):+ return "must be repo-root-relative, not absolute"+ if any(c.isspace() for c in path_part):+ return "the file path must not contain whitespace (the test name goes after '::')"+ 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).@@ -307,7 +347,7 @@ def check(result: LoadResult, today: date, grace_days: int = DEFAULT_GRACE_DAYS)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:+ if entry.runner not in ADAPTED_RUNNERS: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:diff --git a/tools/hogli-commands/hogli_commands/tests/test_quarantine.py b/tools/hogli-commands/hogli_commands/tests/test_quarantine.pyindex f3c52113ec7a..5359e1bfbec3 100644--- a/tools/hogli-commands/hogli_commands/tests/test_quarantine.py+++ b/tools/hogli-commands/hogli_commands/tests/test_quarantine.py@@ -75,12 +75,38 @@ def raw_entry(**overrides: Any) -> dict[str, Any]:("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),+ # jest ids: file::<space-joined test name>; a file selector covers every test in it+ ("frontend/src/x.test.ts", "frontend/src/x.test.ts::MyLogic loads data", True),+ # describe-block prefix matches via the space boundary+ ("frontend/src/x.test.ts::MyLogic", "frontend/src/x.test.ts::MyLogic loads data", True),+ # exact full test name+ ("frontend/src/x.test.ts::MyLogic loads data", "frontend/src/x.test.ts::MyLogic loads data", True),+ # a partial describe word never matches (space, not substring)+ ("frontend/src/x.test.ts::MyLog", "frontend/src/x.test.ts::MyLogic loads data", False),],)def test_selector_matches(selector: str, test_id: str, expected: bool) -> None:assert core.selector_matches(selector, test_id) is expected+ "selector, runner, valid",+ [+ ("frontend/src/x.test.ts", "jest", True),+ ("frontend/src/x.test.ts::MyLogic loads data", "jest", True), # spaces allowed after ::+ ("frontend/src", "jest", True),+ ("product:batch-exports", "jest", True), # product rule shared with pytest+ ("/abs/x.test.ts", "jest", False), # absolute path+ ("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+ ("anything at all", "some-future-runner", True), # unadapted runner: not validated+ ],+)+def test_validate_selector_by_runner(selector: str, runner: str, valid: bool) -> None:+ assert (core.validate_selector(selector, runner) is None) is valid++@pytest.mark.parametrize("expires_offset_days, expected_active",[(-1, False), (0, True), (1, True)],@@ -261,6 +287,16 @@ def test_add_creates_canonical_file(runner: CliRunner, tmp_path: Path) -> None:assert date.fromisoformat(entry["expires"]) - date.fromisoformat(entry["added"]) == timedelta(days=14)+def test_add_records_jest_runner(runner: CliRunner, tmp_path: Path) -> None:+ path = tmp_path / "q.json"+ result = cli(+ runner, path, "add", "frontend/src/x.test.ts", "--runner", "jest", "--reason", "flaky", "--owner", "@web"+ )+ assert result.exit_code == 0, result.output+ entry = json.loads(path.read_text())["entries"][0]+ assert (entry["runner"], entry["id"]) == ("jest", "frontend/src/x.test.ts")++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")@@ -370,8 +406,10 @@ def test_list_shows_status(runner: CliRunner, tmp_path: Path) -> None: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"),+ # 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+ ([raw_entry(runner="jest", id="frontend/src/x.test.ts")], 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"),