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(quarantine): record jest tolerated failures (#73527)

Raúl Negrón-Otero256d8ee6e19c
diff --git a/frontend/jest.quarantine.ts b/frontend/jest.quarantine.ts
index 41d377b52497..e41acf5db650 100644
--- a/frontend/jest.quarantine.ts
+++ b/frontend/jest.quarantine.ts
@@ -19,8 +19,9 @@
* 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.
+ * resolved by jest after collection. Exact row selectors support `mode: "run"`
+ * through the runtime test name; `mode: "skip"` still requires file, directory,
+ * or `product:` scope because jest decides skips during collection.
*/
import * as fs from 'fs'
@@ -170,6 +171,7 @@ const describeStack: string[] = []
interface Decision {
mode: 'run' | 'skip'
label: string
+ testId: string
}
function todayIso(): string {
@@ -222,6 +224,7 @@ function toDecision(entry: QuarantineEntry, testId: string): Decision {
return {
mode: entry.mode,
label: `${testId}: quarantined until ${entry.expires}: ${entry.reason} (${attribution})`,
+ testId,
}
}
@@ -295,9 +298,29 @@ function warnSkip(decision: Decision): void {
}
function warnTolerated(decision: Decision, error: unknown): void {
+ recordToleratedFailure(decision.testId)
warn(`[quarantine] tolerated failure in ${decision.label}\n${errorText(error)}`)
}
+const recordedToleratedFailures = new Set<string>()
+
+function recordToleratedFailure(testId: string): void {
+ const outputDirectory = process.env.JEST_JUNIT_OUTPUT_DIR
+ if (!outputDirectory || recordedToleratedFailures.has(testId)) {
+ return
+ }
+ try {
+ fs.mkdirSync(outputDirectory, { recursive: true })
+ fs.appendFileSync(
+ path.join(outputDirectory, `posthog-jest-quarantine-${process.pid}.jsonl`),
+ `${JSON.stringify({ test_id: testId })}\n`
+ )
+ recordedToleratedFailures.add(testId)
+ } catch {
+ // Telemetry is best-effort; quarantine enforcement must still work without it.
+ }
+}
+
function isThenable(value: unknown): value is PromiseLike<unknown> {
return isRecord(value) && typeof (value as { then?: unknown }).then === 'function'
}
@@ -322,22 +345,35 @@ function tolerate(fn: (...args: unknown[]) => unknown, decision: Decision): (...
}
function runDoneStyle(
- fn: (done: jest.DoneCallback) => void,
+ fn: jest.ProvidesCallback | ((...args: unknown[]) => unknown),
+ args: unknown[],
decision: Decision,
done: jest.DoneCallback,
thisArg: unknown
): void {
- const tolerantDone = function (): void {
- done()
+ let finished = false
+ const finish = (): void => {
+ if (!finished) {
+ finished = true
+ done()
+ }
+ }
+ const tolerantDone = function (reason?: string | Error): void {
+ if (reason !== undefined) {
+ warnTolerated(decision, reason)
+ }
+ finish()
} as jest.DoneCallback
- tolerantDone.fail = function (): void {
- done()
+ tolerantDone.fail = function (reason?: string | Error): void {
+ warnTolerated(decision, reason ?? new Error('done.fail() called'))
+ finish()
}
try {
- fn.call(thisArg, tolerantDone)
+ const doneStyle = fn as (...callbackArgs: unknown[]) => unknown
+ doneStyle.call(thisArg, ...args, tolerantDone)
} catch (error) {
warnTolerated(decision, error)
- done()
+ finish()
}
}
@@ -360,7 +396,7 @@ function tolerateProvidesWhen(
doneStyle.call(this, done)
return
}
- runDoneStyle(doneStyle, decision, done, this)
+ runDoneStyle(doneStyle, [], decision, done, this)
}
}
return function (this: unknown): unknown {
@@ -372,13 +408,6 @@ function tolerateProvidesWhen(
} 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)) {
@@ -395,21 +424,54 @@ function copyMembers(target: object, source: object): void {
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 eachArgumentCount(eachArgs: unknown[]): number | null {
+ const [table, ...templateValues] = eachArgs
+ if (templateValues.length > 0) {
+ return 1
+ }
+ if (!Array.isArray(table) || table.length === 0) {
+ return null
+ }
+ const counts = table.map((row) => (Array.isArray(row) ? row.length : 1))
+ return counts.every((count) => count === counts[0]) ? counts[0] : null
+}
+
+function tolerateEachWhen(
+ fn: (...args: unknown[]) => unknown,
+ getDecision: () => Decision | null,
+ argumentCount: number | null
+): (...args: unknown[]) => unknown {
+ const wrapped = function (this: unknown, ...args: unknown[]): unknown {
+ const decision = getDecision()
+ if (decision === null || decision.mode !== 'run') {
+ return fn.apply(this, args)
+ }
+ if (argumentCount !== null && fn.length > argumentCount && args.length === argumentCount + 1) {
+ const done = args[argumentCount]
+ if (typeof done === 'function') {
+ runDoneStyle(fn, args.slice(0, argumentCount), decision, done as jest.DoneCallback, this)
+ return undefined
+ }
+ }
+ return tolerate(fn, decision).apply(this, args)
+ }
+ // jest-each compares callback arity with row width to decide whether to inject `done`.
+ Object.defineProperty(wrapped, 'length', { value: fn.length })
+ return wrapped
+}
+
+/** `.each`: collection-time file scopes can skip; runtime row identities can tolerate failures. */
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') {
+ 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)
- }
+ const argumentCount = eachArgumentCount(eachArgs)
+ return (name: string, fn: (...args: unknown[]) => unknown, timeout?: number): void =>
+ factory(name, tolerateEachWhen(fn, decideForRunningTest, argumentCount), timeout)
}
return wrapped as unknown as jest.Each
}
@@ -417,16 +479,12 @@ function wrapEach(base: jest.It, skipBase: jest.It): 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') {
+ if (decision?.mode === 'skip') {
warnSkip(decision)
original.skip(name, fn, timeout)
return
}
- source(name, tolerateProvides(fn, decision), timeout)
+ source(name, tolerateProvidesWhen(fn, decideForRunningTest), timeout)
}
const wrapped = ((name: string, fn?: jest.ProvidesCallback, timeout?: number): void => {
diff --git a/frontend/src/test/jest.quarantine.runtime.fixture.ts b/frontend/src/test/jest.quarantine.runtime.fixture.ts
index 01a1bcddcf53..445df12ffa63 100644
--- a/frontend/src/test/jest.quarantine.runtime.fixture.ts
+++ b/frontend/src/test/jest.quarantine.runtime.fixture.ts
@@ -30,6 +30,25 @@ describe('jest quarantine runtime fixture', () => {
throw new Error('quarantined async failure')
})
+ test.each([1])('tolerates each row %s', () => {
+ throw new Error('quarantined each row failure')
+ })
+
+ test.each([2])('keeps unrelated done row %s', (value, done) => {
+ expect(value).toBe(2)
+ done()
+ })
+
+ test.each([3])('tolerates each done row %s', (_value, done) => {
+ done(new Error('quarantined each done row failure'))
+ })
+
+ describe.each(['A'])('parameterized describe %s', () => {
+ test('tolerates nested failure', () => {
+ throw new Error('quarantined parameterized describe failure')
+ })
+ })
+
test('tolerates beforeEach failure', () => {
expect(true).toBe(true)
})
diff --git a/frontend/src/test/jest.quarantine.test.ts b/frontend/src/test/jest.quarantine.test.ts
index 9dcce5875346..b12346438d5d 100644
--- a/frontend/src/test/jest.quarantine.test.ts
+++ b/frontend/src/test/jest.quarantine.test.ts
@@ -131,6 +131,9 @@ describe('jest.quarantine', () => {
runtimeEntry(fixtureSuiteId),
runtimeEntry(`${fixtureSuiteId} tolerates body failure`),
runtimeEntry(`${fixtureSuiteId} tolerates async rejection`),
+ runtimeEntry(`${fixtureSuiteId} tolerates each row 1`),
+ runtimeEntry(`${fixtureSuiteId} tolerates each done row 3`),
+ runtimeEntry(`${fixtureSuiteId} parameterized describe A tolerates nested failure`),
runtimeEntry(`${fixtureSuiteId} tolerates beforeEach failure`),
runtimeEntry(`${fixtureSuiteId} tolerates afterEach failure`),
runtimeEntry(`${fixtureSuiteId} skips body`, 'skip'),
@@ -156,7 +159,20 @@ describe('jest.quarantine', () => {
{
cwd: FRONTEND_DIR,
encoding: 'utf-8',
- env: { ...process.env, CI: '1', POSTHOG_TEST_QUARANTINE_PATH: quarantinePath },
+ env: {
+ ...process.env,
+ CI: '1',
+ JEST_JUNIT_OUTPUT_DIR: tmpDir,
+ // Mirror ci-frontend.yml: the CI reporter reads the `file` attribute to
+ // rebuild each test's identity, so the junit shape must match CI's here.
+ // Every JEST_JUNIT_* var is pinned rather than inherited — under CI this
+ // process already has them set, and an inherited output name would land
+ // the report somewhere this test doesn't look.
+ JEST_JUNIT_ADD_FILE_ATTRIBUTE: 'true',
+ JEST_JUNIT_SUITE_NAME: '{filepath}',
+ JEST_JUNIT_OUTPUT_NAME: 'junit.xml',
+ POSTHOG_TEST_QUARANTINE_PATH: quarantinePath,
+ },
}
)
const output = `${result.stdout}\n${result.stderr}`
@@ -167,8 +183,51 @@ describe('jest.quarantine', () => {
expect(output).toContain('quarantined body failure')
expect(output).toContain('quarantined beforeEach failure')
expect(output).toContain('quarantined afterEach failure')
+ expect(output).toContain('quarantined each row failure')
+ expect(output).toContain('quarantined each done row failure')
+ expect(output).toContain('quarantined parameterized describe failure')
expect(output).toContain('[quarantine] skipping')
expect(output).not.toContain('skipped body should not run')
+ const toleratedIds = fs
+ .readdirSync(tmpDir)
+ .filter((filename) => filename.startsWith('posthog-jest-quarantine-'))
+ .flatMap((filename) =>
+ fs
+ .readFileSync(path.join(tmpDir, filename), 'utf-8')
+ .trim()
+ .split('\n')
+ .map((line) => (JSON.parse(line) as { test_id: string }).test_id)
+ )
+ expect(toleratedIds).toEqual(
+ expect.arrayContaining([
+ `${fixtureSuiteId} tolerates each done row 3`,
+ `${fixtureSuiteId} parameterized describe A tolerates nested failure`,
+ ])
+ )
+
+ // The CI reporter (.github/scripts/report_test_timings.py) rebuilds each test's
+ // identity from junit as `<repo-relative file>::<name>` and matches it against the
+ // sidecar's `test_id` to restore failures quarantine masked as passes. This is the
+ // only place both sides run together, so drift in jest-junit's name/file templates
+ // or in the sidecar id would otherwise silently turn those back into clean passes.
+ const junitIds = [
+ ...fs.readFileSync(path.join(tmpDir, 'junit.xml'), 'utf-8').matchAll(/<testcase\b[^>]*>/g),
+ ].flatMap(([element]) => {
+ const file = /\bfile="([^"]*)"/.exec(element)?.[1]
+ const name = /\bname="([^"]*)"/.exec(element)?.[1]
+ if (file === undefined || name === undefined) {
+ return []
+ }
+ const repoRelative = path.posix.normalize(path.posix.join('frontend', file))
+ return [`${repoRelative}::${name.replace(/&quot;/g, '"').replace(/&amp;/g, '&')}`]
+ })
+ // beforeAll/afterAll tolerate at describe scope, so their id names no single test
+ // and has no testcase to attach to; every per-test id must still resolve to one.
+ const perTestToleratedIds = toleratedIds.filter(
+ (id) => id !== fixtureSuiteId && id !== RUNTIME_FIXTURE_ID
+ )
+ expect(perTestToleratedIds.length).toBeGreaterThan(0)
+ expect(junitIds).toEqual(expect.arrayContaining(perTestToleratedIds))
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}