The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add ci-conductor (dry run) quarantine gate for e2e tests (#76014)
Nemanja Glumacac0c1c3d3ed3
diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.ymlindex cad7b7c2fc5..52b3a9b39cb 100644--- a/.github/workflows/e2e-test.yml+++ b/.github/workflows/e2e-test.yml@@ -59,6 +59,11 @@ jobs:name: e2e-tests-${{ inputs.name }}-${{ inputs.edition }}env:MB_EDITION: ${{ inputs.edition }}+ # Absolute path for the quarantine failures file (DEV-2082). The after:spec+ # recorder runs in Cypress' plugins process, whose cwd differs from the+ # workspace where the gate step runs; an absolute path anchored to the+ # workspace makes both agree regardless of cwd.+ QUARANTINE_FAILURES_FILE: ${{ github.workspace }}/target/quarantine-failures.jsonl# Sensitive env vars (tokens, secrets) starting with `CYPRESS_` are accessed via async `cy.env()`# Example: `cy.env(["FOO"]).then(({ FOO }) => ...)`# For non-sensitive config, use `Cypress.expose()` in cypress config instead (synchronous)@@ -209,6 +214,21 @@ jobs:trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}previous-step-outcome: ${{ inputs.specs && steps.tagged-e2e.outcome || steps.split-e2e.outcome }}+ # Quarantine gate (DEV-2082). Compare this job's ultimate test failures+ # (recorded by after:spec into ./target/quarantine-failures.jsonl) against+ # ci-conductor's quarantine list and decide whether the job should pass:+ # pass if every failure is quarantined, fail if any isn't. This mirrors+ # what Trunk's analytics-uploader does for us today. Runs in dry-run mode+ # for now (QUARANTINE_DRY_RUN defaults to true) — it only prints the+ # verdict and never fails the job. `continue-on-error` is belt-and-braces+ # while it's observational; drop both it and the dry run to enforce.+ - name: Quarantine gate (dry run)+ if: always()+ continue-on-error: true+ timeout-minutes: 2+ shell: bash+ run: bun e2e/support/check-quarantine.ts+- name: Upload Cypress Artifacts upon failureuses: actions/upload-artifact@v7if: |diff --git a/e2e/support/check-quarantine.ts b/e2e/support/check-quarantine.tsnew file mode 100644index 00000000000..256d482a10e--- /dev/null+++ b/e2e/support/check-quarantine.ts@@ -0,0 +1,167 @@+#!/usr/bin/env bun++// Quarantine gate (DEV-2082). After an e2e job runs, compare the tests that+// *ultimately failed* against the quarantine list served by ci-conductor and+// decide whether the job should pass or fail:+//+// - No failures -> pass (nothing to gate)+// - Every failure is quarantined -> pass (exit cleanly)+// - Any failure is NOT quarantined -> fail+//+// This mirrors what Trunk's analytics-uploader currently does for us; the goal+// is to eventually replace that. For now the gate runs in DRY-RUN mode: it+// computes and prints the verdict but always exits 0, so it can be observed in+// CI without affecting job outcomes. Flip QUARANTINE_DRY_RUN=false to enforce.+//+// The failures come from the file written by after:spec+// (`recordFailedTestsForQuarantine` in ci_conductor.ts). Both that file and+// ci-conductor's quarantine list derive {test_name, test_path, file_path} from+// the same Cypress title array, so the comparison here is exact.++import { readFileSync } from "node:fs";++import {+ type FailedTest,+ type QuarantineEntry,+ compareFailedToQuarantine,+} from "./quarantine-compare";++const {+ CI_CONDUCTOR_BASE_URL,+ CI_CONDUCTOR_WEBHOOK_SECRET,+ // Default to a dry run: compute and print the verdict, but never fail the+ // job. Set to "false" to actually gate the build on the verdict.+ QUARANTINE_DRY_RUN,+ QUARANTINE_FAILURES_FILE,+} = process.env;++const isDryRun = QUARANTINE_DRY_RUN !== "false";++// The test suite to gate. ci-conductor keys its quarantine list by suite.+const TEST_SUITE = "e2e";++const failuresFile =+ QUARANTINE_FAILURES_FILE ?? "./target/quarantine-failures.jsonl";++/** Read the run's failed tests from the JSONL file. */+function readFailedTests(file: string): FailedTest[] {+ let raw: string;+ try {+ raw = readFileSync(file, "utf8");+ } catch {+ console.log(`[quarantine] no failures file at ${file}; nothing to gate.`);+ return [];+ }++ return raw+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line !== "")+ .map((line): FailedTest | null => {+ try {+ return JSON.parse(line) as FailedTest;+ } catch {+ console.error(`[quarantine] skipping unparseable line: ${line}`);+ return null;+ }+ })+ .filter((test): test is FailedTest => test !== null);+}++/**+ * Build the quarantine list URL from the ci-conductor base origin secret. The+ * reporter posts to ".../webhooks/failed-tests"; the quarantine list lives at+ * ".../api/quarantine" on the same host.+ */+function quarantineUrl(): string | null {+ if (!CI_CONDUCTOR_BASE_URL) {+ return null;+ }+ const base = CI_CONDUCTOR_BASE_URL.replace(/\/+$/, "");+ return `${base}/api/quarantine?suite=${TEST_SUITE}`;+}++/** Fetch the quarantine list, or null if it can't be retrieved. */+async function fetchQuarantine(): Promise<QuarantineEntry[] | null> {+ const url = quarantineUrl();+ if (!url) {+ console.log(+ "[quarantine] CI_CONDUCTOR_BASE_URL is unset; cannot fetch the quarantine list.",+ );+ return null;+ }+ try {+ const headers: Record<string, string> = {};+ if (CI_CONDUCTOR_WEBHOOK_SECRET) {+ headers["x-internal-secret"] = CI_CONDUCTOR_WEBHOOK_SECRET;+ }+ const response = await fetch(url, { headers });+ if (!response.ok) {+ console.error(+ `[quarantine] GET ${url} returned ${response.status} ${response.statusText}`,+ );+ return null;+ }+ const body = (await response.json()) as { tests?: QuarantineEntry[] };+ return body.tests ?? [];+ } catch (error) {+ console.error(`[quarantine] failed to fetch ${url}`, error);+ return null;+ }+}++/** Print the verdict and, outside dry run, set the exit code accordingly. */+function finish(shouldFail: boolean, reason: string): void {+ const verdict = shouldFail ? "FAIL" : "PASS";+ const mode = isDryRun ? " (dry run — not enforced)" : "";+ console.log(`[quarantine] verdict: ${verdict}${mode} — ${reason}.`);+ if (shouldFail && !isDryRun) {+ process.exitCode = 1;+ }+}++async function main(): Promise<void> {+ const failed = readFailedTests(failuresFile);++ if (failed.length === 0) {+ console.log("[quarantine] no failed tests; passing.");+ return;+ }++ const quarantine = await fetchQuarantine();+ if (quarantine === null) {+ // We couldn't read the list, so we can't confirm everything is+ // quarantined — that's a failing verdict (enforced only outside dry run).+ finish(true, "could not fetch the quarantine list");+ return;+ }++ const { quarantined, unquarantined } = compareFailedToQuarantine(+ failed,+ quarantine,+ );++ console.log(+ `[quarantine] ${failed.length} failed test(s); ${quarantine.length} test(s) in the ${TEST_SUITE} quarantine list.`,+ );+ const describe = (test: FailedTest) =>+ `${test.test_name} (${test.file_path ?? "unknown file"})`;+ quarantined.forEach((test) =>+ console.log(` 🔒 quarantined: ${describe(test)}`),+ );+ unquarantined.forEach((test) =>+ console.log(` 🚨 NOT quarantined: ${describe(test)}`),+ );++ finish(+ unquarantined.length > 0,+ unquarantined.length > 0+ ? `${unquarantined.length} failed test(s) are not quarantined`+ : "every failed test is quarantined",+ );+}++// Only run when invoked directly (`bun check-quarantine.ts`), not on import.+if (import.meta.main) {+ await main();+}diff --git a/e2e/support/ci_conductor.ts b/e2e/support/ci_conductor.tsindex b6dd654a2a5..819bdff80d7 100644--- a/e2e/support/ci_conductor.ts+++ b/e2e/support/ci_conductor.ts@@ -1,4 +1,5 @@-import { readFileSync, statSync } from "node:fs";+import { appendFileSync, mkdirSync, readFileSync, statSync } from "node:fs";+import { dirname } from "node:path";import fetch from "node-fetch"; // must be node-fetch v2 because it's non-esm@@ -272,6 +273,47 @@ export function extractFailedTests(return tests;}+/**+ * Where after:spec records this run's ultimate test failures for the post-run+ * quarantine gate (DEV-2082). One JSON object per line+ * (`{test_name, test_path, file_path}`), appended per spec, so the gate step+ * can read the whole job's failures from a single file. Override with+ * QUARANTINE_FAILURES_FILE. Note these are the SAME fields ci-conductor stores+ * in its quarantine list (both derived from the same Cypress title array), so+ * the gate can compare them exactly. See `check-quarantine.ts`.+ */+const QUARANTINE_FAILURES_FILE =+ process.env.QUARANTINE_FAILURES_FILE ?? "./target/quarantine-failures.jsonl";++/**+ * Persist the tests that ultimately failed (status "failure") so the post-run+ * quarantine gate can decide whether the job passes. Flaky tests that recovered+ * on retry and passing tests don't gate the build, so they're filtered out.+ * Best-effort and never throws — recording must not break the test run.+ */+export function recordFailedTestsForQuarantine(tests: ConductorTest[]): void {+ try {+ const broken = tests.filter((test) => test.status === "failure");+ if (broken.length === 0) {+ return;+ }+ const lines =+ broken+ .map((test) =>+ JSON.stringify({+ test_name: test.name,+ test_path: test.path ?? null,+ file_path: test.file ?? null,+ }),+ )+ .join("\n") + "\n";+ mkdirSync(dirname(QUARANTINE_FAILURES_FILE), { recursive: true });+ appendFileSync(QUARANTINE_FAILURES_FILE, lines);+ } catch (error) {+ console.error("[quarantine] failed to record failures", error);+ }+}+/*** Report the given failures to ci-conductor. In dry-run mode the payload is* logged and nothing is sent. Otherwise it's POSTed, no-opping when the webhookdiff --git a/e2e/support/ci_conductor.unit.spec.ts b/e2e/support/ci_conductor.unit.spec.tsindex 0544d3adafa..82c73fd7763 100644--- a/e2e/support/ci_conductor.unit.spec.ts+++ b/e2e/support/ci_conductor.unit.spec.ts@@ -1,3 +1,7 @@+import { existsSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { extractFailedTests, resolveScreenshotPath } from "./ci_conductor";// jest.mock is hoisted; the mocked default must be referenced via a `mock`-@@ -643,3 +647,104 @@ describe("reportFailedTestsToConductor", () => {(console.error as jest.Mock).mockRestore();});});++describe("recordFailedTestsForQuarantine", () => {+ const failuresFile = join(tmpdir(), `q-failures-${process.pid}.jsonl`);++ afterEach(() => {+ if (existsSync(failuresFile)) {+ rmSync(failuresFile);+ }+ });++ // The recorder reads QUARANTINE_FAILURES_FILE at import time, so point it at+ // a temp file by re-importing the module with that env applied.+ const load = () => loadConductor({ QUARANTINE_FAILURES_FILE: failuresFile });++ const readLines = () =>+ readFileSync(failuresFile, "utf8")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));++ it("records only ultimate failures (not flakes or passes), one per line", async () => {+ const { recordFailedTestsForQuarantine } = await load();++ const results = makeResults({+ tests: [+ test(["scenarios > foo", "passes"], ["passed"]),+ test(["scenarios > foo", "flakes then passes"], ["failed", "passed"]),+ test(["scenarios > foo", "stays broken"], ["failed", "failed"], "boom"),+ ],+ });++ recordFailedTestsForQuarantine(extractFailedTests(spec, results));++ expect(readLines()).toEqual([+ {+ test_name: "stays broken",+ test_path: "scenarios > foo",+ file_path: "e2e/test/scenarios/foo/foo.cy.spec.ts",+ },+ ]);+ });++ it("appends across calls so the whole job's failures accumulate", async () => {+ const { recordFailedTestsForQuarantine } = await load();++ recordFailedTestsForQuarantine(+ extractFailedTests(+ spec,+ makeResults({ tests: [test(["A", "one"], ["failed", "failed"], "x")] }),+ ),+ );+ recordFailedTestsForQuarantine(+ extractFailedTests(+ spec,+ makeResults({ tests: [test(["B", "two"], ["failed", "failed"], "y")] }),+ ),+ );++ expect(readLines().map((t) => t.test_name)).toEqual(["one", "two"]);+ });++ it("writes nothing when there are no ultimate failures", async () => {+ const { recordFailedTestsForQuarantine } = await load();++ recordFailedTestsForQuarantine(+ extractFailedTests(+ spec,+ makeResults({+ tests: [+ test(["A", "ok"], ["passed"]),+ test(["A", "flaky"], ["failed", "passed"]),+ ],+ }),+ ),+ );++ expect(existsSync(failuresFile)).toBe(false);+ });++ it("never throws when the file can't be written", async () => {+ // A NUL byte in the path makes the fs calls throw; the recorder must swallow it.+ const { recordFailedTestsForQuarantine } = await loadConductor({+ QUARANTINE_FAILURES_FILE: "/tmp/\0/nope.jsonl",+ });+ jest.spyOn(console, "error").mockImplementation(() => {});++ expect(() =>+ recordFailedTestsForQuarantine([+ {+ name: "n",+ path: "p",+ file: "f",+ status: "failure",+ attempts: [{ state: "failed" }],+ },+ ] as Parameters<typeof recordFailedTestsForQuarantine>[0]),+ ).not.toThrow();++ (console.error as jest.Mock).mockRestore();+ });+});diff --git a/e2e/support/config.js b/e2e/support/config.jsindex 0cebabf6b35..8682e256abf 100644--- a/e2e/support/config.js+++ b/e2e/support/config.js@@ -10,6 +10,7 @@ import { BACKEND_HOST, BACKEND_PORT } from "../runner/constants/backend-port";import {extractFailedTests,+ recordFailedTestsForQuarantine,reportFailedTestsToConductor,} from "./ci_conductor";import * as ciTasks from "./ci_tasks";@@ -200,7 +201,10 @@ const defaultConfig = {// a hard backstop around everything — extraction, payload build, and// the request. The reporter also handles its own errors internally.try {- await reportFailedTestsToConductor(extractFailedTests(spec, results));+ const failedTests = extractFailedTests(spec, results);+ // Persist ultimate failures for the post-run quarantine gate (DEV-2082).+ recordFailedTestsForQuarantine(failedTests);+ await reportFailedTestsToConductor(failedTests);} catch (error) {console.error("[ci-conductor] reporting failed (ignored)", error);}diff --git a/e2e/support/quarantine-compare.ts b/e2e/support/quarantine-compare.tsnew file mode 100644index 00000000000..13e227a10b5--- /dev/null+++ b/e2e/support/quarantine-compare.ts@@ -0,0 +1,59 @@+// Pure comparison logic for the quarantine gate (DEV-2082), split out from the+// `check-quarantine.ts` executable so it can be unit tested without the script's+// CLI side effects (`import.meta.main`, env reads, `fetch`).++import _ from "underscore";++/** One quarantined test as served by ci-conductor's `/api/quarantine`. */+export type QuarantineEntry = {+ test_name: string;+ test_suite: string;+ test_path: string;+ file_path: string;+};++/** A test that ultimately failed in this run, as recorded by after:spec. */+export type FailedTest = {+ test_name: string;+ test_path: string | null;+ file_path: string | null;+};++/**+ * Identity key for a test: the spec file path, describe path, and leaf test+ * name as a JSON tuple. ci-conductor's quarantine list and our after:spec+ * recorder both derive these three fields from the same Cypress title array+ * (file_path = `spec.relative`, test_path = the joined `describe` titles), so+ * they match exactly. JSON-encoding keeps the parts distinct, so tuples that+ * differ only in where a boundary falls can't collide.+ */+export function matchKey(+ filePath: string | null | undefined,+ testPath: string | null | undefined,+ testName: string,+): string {+ return JSON.stringify([filePath ?? "", testPath ?? "", testName]);+}++/**+ * Partition the run's failed tests into those that are quarantined and those+ * that are not, matching on exact {file_path, test_path, test_name} identity.+ * A single pass over the failures, so the gate doesn't repeat the (potentially+ * large) comparison when it later logs or counts each bucket.+ */+export function compareFailedToQuarantine(+ failedTests: FailedTest[],+ quarantineEntries: QuarantineEntry[],+): { quarantined: FailedTest[]; unquarantined: FailedTest[] } {+ const quarantinedKeys = new Set(+ quarantineEntries.map((q) =>+ matchKey(q.file_path, q.test_path, q.test_name),+ ),+ );+ const [quarantined, unquarantined] = _.partition(failedTests, (test) =>+ quarantinedKeys.has(+ matchKey(test.file_path, test.test_path, test.test_name),+ ),+ );+ return { quarantined, unquarantined };+}diff --git a/e2e/support/quarantine-compare.unit.spec.ts b/e2e/support/quarantine-compare.unit.spec.tsnew file mode 100644index 00000000000..a5ec8406923--- /dev/null+++ b/e2e/support/quarantine-compare.unit.spec.ts@@ -0,0 +1,114 @@+import {+ type FailedTest,+ type QuarantineEntry,+ compareFailedToQuarantine,+ matchKey,+} from "./quarantine-compare";++const failed = (+ test_name: string,+ test_path: string | null = "Suite",+ file_path: string | null = "e2e/test/foo.cy.spec.ts",+): FailedTest => ({ test_name, test_path, file_path });++const quarantined = (+ test_name: string,+ test_path = "Suite",+ file_path = "e2e/test/foo.cy.spec.ts",+): QuarantineEntry => ({+ test_name,+ test_path,+ file_path,+ test_suite: "e2e",+});++describe("compareFailedToQuarantine", () => {+ it("puts every failure in `unquarantined` when nothing is quarantined", () => {+ const failures = [failed("a"), failed("b")];++ const { quarantined: q, unquarantined } = compareFailedToQuarantine(+ failures,+ [],+ );++ expect(q).toEqual([]);+ expect(unquarantined).toEqual(failures);+ });++ it("puts every failure in `quarantined` when all are listed", () => {+ const failures = [failed("a"), failed("b")];++ const { quarantined: q, unquarantined } = compareFailedToQuarantine(+ failures,+ [quarantined("a"), quarantined("b")],+ );++ expect(q).toEqual(failures);+ expect(unquarantined).toEqual([]);+ });++ it("partitions a mixed set", () => {+ const a = failed("a");+ const b = failed("b");+ const c = failed("c");++ const { quarantined: q, unquarantined } = compareFailedToQuarantine(+ [a, b, c],+ [quarantined("a"), quarantined("c")],+ );++ expect(q).toEqual([a, c]);+ expect(unquarantined).toEqual([b]);+ });++ it("returns two empty buckets for no failures", () => {+ expect(compareFailedToQuarantine([], [quarantined("a")])).toEqual({+ quarantined: [],+ unquarantined: [],+ });+ });++ it("matches on all three fields — same name, different file is not a match", () => {+ const failure = failed("a", "Suite", "e2e/test/foo.cy.spec.ts");++ const { unquarantined } = compareFailedToQuarantine(+ [failure],+ [quarantined("a", "Suite", "e2e/test/bar.cy.spec.ts")],+ );++ expect(unquarantined).toEqual([failure]);+ });++ it("matches on all three fields — same name/file, different describe path is not a match", () => {+ const failure = failed("a", "Suite > inner");++ const { unquarantined } = compareFailedToQuarantine(+ [failure],+ [quarantined("a", "Suite > other")],+ );++ expect(unquarantined).toEqual([failure]);+ });++ it("treats a null path on the failure as an empty string for matching", () => {+ const failure = failed("a", null, null);++ const { quarantined: q } = compareFailedToQuarantine(+ [failure],+ [quarantined("a", "", "")],+ );++ expect(q).toEqual([failure]);+ });+});++describe("matchKey", () => {+ it("normalizes null/undefined paths to empty strings", () => {+ expect(matchKey(null, undefined, "a")).toBe(matchKey("", "", "a"));+ });++ it("does not collide when a boundary between fields shifts", () => {+ // ["a", "b", "c"] vs ["ab", "", "c"] must stay distinct.+ expect(matchKey("a", "b", "c")).not.toBe(matchKey("ab", "", "c"));+ });+});