From cc8a91150293bb78e16b39c996c46c32e0fd6748 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Wed, 21 Oct 2026 10:41:57 -0400 Subject: [PATCH] test(vitest): parallel forks with per-worker database clones Stage 2 of the int-suite speedup: pool=forks with fileParallelism and a default cap of 8 (VITEST_MAX_FORKS), each fork cloning the template into ptf_*_test_w via tests/vitest-worker-setup.ts; environment defaults to node with jsdom opt-in docblocks on the six DOM-consuming specs; a tiny reporter writes a failure marker so post-run cleanup keeps clones after red runs (KEEP_TEST_DBS=1 forces keeping); pg pools cap at TEST_PG_POOL_MAX=3 per boot in workers mode. Legacy serial mode stays reachable by setting TEST_DATABASE_URI. Notes from the gate G2 runs (Vitest 4.0.16): globalTeardown config was removed in Vitest 4 entirely - cleanup now returns from globalSetup. The pool scheduler only reuses worker processes when isolate:false, so this per-file-fork stage lands short of the wall-time target and is expected to be superseded by the gated isolate:false stage. Gate G2 warm serial equivalent stays green via TEST_DATABASE_URI bisect mode. --- .gitignore | 2 + src/payload.config.ts | 3 + tests/int/announcements.int.spec.ts | 1 + tests/int/arena-server.int.spec.ts | 2 +- .../game-structures-labor-route.int.spec.ts | 2 +- tests/int/mission-card.int.spec.ts | 1 + tests/int/mission-reminder-toasts.int.spec.ts | 1 + tests/int/mission-reminder.int.spec.ts | 2 +- .../int/notification-inbox-scope.int.spec.ts | 2 +- tests/int/operation-ui-primitives.int.spec.ts | 1 + tests/int/preferences-form.int.spec.ts | 1 + tests/int/tours.int.spec.ts | 1 + tests/test-db.ts | 55 +++++++++++-------- tests/vitest-global.ts | 33 ++++++++--- tests/vitest-marker.ts | 25 +++++++++ tests/vitest-reporter.ts | 16 ++++++ tests/vitest-teardown.ts | 30 +++++++--- tests/vitest-worker-setup.ts | 44 +++++++++++++++ vitest.config.mts | 27 +++++++-- 19 files changed, 200 insertions(+), 49 deletions(-) create mode 100644 tests/vitest-marker.ts create mode 100644 tests/vitest-reporter.ts create mode 100644 tests/vitest-worker-setup.ts diff --git a/.gitignore b/.gitignore index 480e1d6c..ef25dc9f 100644 --- a/.gitignore +++ b/.gitignore @@ -48,6 +48,8 @@ npm-debug.log* /src/generated/ # testing /test-results/ +# test-db template cache + int failure marker (see tests/test-db.ts, tests/vitest-marker.ts) +/.cache/ *.tsbuildinfo # typescript # vercel diff --git a/src/payload.config.ts b/src/payload.config.ts index 7fac4efd..73fad43a 100644 --- a/src/payload.config.ts +++ b/src/payload.config.ts @@ -595,6 +595,9 @@ export default buildConfig({ db: postgresAdapter({ pool: { connectionString: process.env.DATABASE_URI || "", + // Test workers cap the pg pool per boot (tests/vitest-worker-setup.ts + // sets TEST_PG_POOL_MAX); unset in dev/prod, zero behavior change there. + ...(process.env.TEST_PG_POOL_MAX ? { max: Number(process.env.TEST_PG_POOL_MAX) } : {}), }, // push: process.env.NODE_ENV === "development", // Env-gated drizzle push: only the test-database bootstrap (DB_PUSH=1) uses diff --git a/tests/int/announcements.int.spec.ts b/tests/int/announcements.int.spec.ts index bfd548d2..b6cdc910 100644 --- a/tests/int/announcements.int.spec.ts +++ b/tests/int/announcements.int.spec.ts @@ -1,3 +1,4 @@ +// @vitest-environment jsdom (specs clear window.localStorage via the Shims evaluator) import { getPayload, Payload } from "payload"; import config from "@/payload.config"; diff --git a/tests/int/arena-server.int.spec.ts b/tests/int/arena-server.int.spec.ts index cc9b11e9..064acde8 100644 --- a/tests/int/arena-server.int.spec.ts +++ b/tests/int/arena-server.int.spec.ts @@ -1,4 +1,4 @@ -// @vitest-environment node + // Node realm on purpose: this drives the real http/ws server, and jose's // key-type checks are realm-sensitive (a jsdom realm's Uint8Array intrinsics // differ from the externalized jose module's). diff --git a/tests/int/game-structures-labor-route.int.spec.ts b/tests/int/game-structures-labor-route.int.spec.ts index 67c45a05..e6667255 100644 --- a/tests/int/game-structures-labor-route.int.spec.ts +++ b/tests/int/game-structures-labor-route.int.spec.ts @@ -1,4 +1,4 @@ -// @vitest-environment node + // jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and // the global Uint8Array come from different realms, so signing throws a TypeError. diff --git a/tests/int/mission-card.int.spec.ts b/tests/int/mission-card.int.spec.ts index 8a8154b7..223d492f 100644 --- a/tests/int/mission-card.int.spec.ts +++ b/tests/int/mission-card.int.spec.ts @@ -1,3 +1,4 @@ +// @vitest-environment jsdom import { createElement } from "react"; import { cleanup, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it } from "vitest"; diff --git a/tests/int/mission-reminder-toasts.int.spec.ts b/tests/int/mission-reminder-toasts.int.spec.ts index a0592ce7..830f1aa6 100644 --- a/tests/int/mission-reminder-toasts.int.spec.ts +++ b/tests/int/mission-reminder-toasts.int.spec.ts @@ -1,3 +1,4 @@ +// @vitest-environment jsdom import { createElement } from "react"; import { act, cleanup, render, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; diff --git a/tests/int/mission-reminder.int.spec.ts b/tests/int/mission-reminder.int.spec.ts index b7a037fd..22256d87 100644 --- a/tests/int/mission-reminder.int.spec.ts +++ b/tests/int/mission-reminder.int.spec.ts @@ -1,4 +1,4 @@ -// @vitest-environment node + // jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and // the global Uint8Array come from different realms, so signing throws a TypeError. diff --git a/tests/int/notification-inbox-scope.int.spec.ts b/tests/int/notification-inbox-scope.int.spec.ts index 67ebc8d0..601367b3 100644 --- a/tests/int/notification-inbox-scope.int.spec.ts +++ b/tests/int/notification-inbox-scope.int.spec.ts @@ -1,4 +1,4 @@ -// @vitest-environment node + // jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and // the global Uint8Array come from different realms, so signing throws a TypeError. diff --git a/tests/int/operation-ui-primitives.int.spec.ts b/tests/int/operation-ui-primitives.int.spec.ts index 899d6d1c..faea79b4 100644 --- a/tests/int/operation-ui-primitives.int.spec.ts +++ b/tests/int/operation-ui-primitives.int.spec.ts @@ -1,3 +1,4 @@ +// @vitest-environment jsdom import { createElement as h } from "react"; import { afterEach, describe, expect, it } from "vitest"; import { cleanup, render, screen, within } from "@testing-library/react"; diff --git a/tests/int/preferences-form.int.spec.ts b/tests/int/preferences-form.int.spec.ts index 643ceacf..089d8ee6 100644 --- a/tests/int/preferences-form.int.spec.ts +++ b/tests/int/preferences-form.int.spec.ts @@ -1,3 +1,4 @@ +// @vitest-environment jsdom import { createElement } from "react"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; diff --git a/tests/int/tours.int.spec.ts b/tests/int/tours.int.spec.ts index e89f09e9..8c41c00c 100644 --- a/tests/int/tours.int.spec.ts +++ b/tests/int/tours.int.spec.ts @@ -1,3 +1,4 @@ +// @vitest-environment jsdom (specs stub window.localStorage accessors) import { beforeEach, describe, expect, it } from "vitest"; import { DEFAULT_GATES, diff --git a/tests/test-db.ts b/tests/test-db.ts index bfc89410..22452b60 100644 --- a/tests/test-db.ts +++ b/tests/test-db.ts @@ -103,15 +103,21 @@ function withDatabaseName(testUri: string, dbName: string): string { return url.toString(); } -/** Template database URI (`ptf_app_test` -> `ptf_app_test_template`). */ -export function templateDatabaseUri(): string { - const base = resolveTestDatabaseUri(); +/** + * Template database URI for a given serial test URI (`ptf_app_test` -> + * `ptf_app_test_template`). Defaults to resolving from the environment; pass + * an explicit URI when the caller's `process.env.DATABASE_URI` has already + * been repointed at the serial test db (worker setup files do exactly that, + * so re-resolving there would append `_test` twice). + */ +export function templateDatabaseUri(serialTestUri?: string): string { + const base = serialTestUri ?? resolveTestDatabaseUri(); return withDatabaseName(base, `${testDatabaseName(base)}_template`); } /** Per-vitest-worker clone URI (`ptf_app_test` -> `ptf_app_test_w`). */ -export function workerDatabaseUri(workerId: string | number): string { - const base = resolveTestDatabaseUri(); +export function workerDatabaseUri(workerId: string | number, serialTestUri?: string): string { + const base = serialTestUri ?? resolveTestDatabaseUri(); return withDatabaseName(base, `${testDatabaseName(base)}_w${workerId}`); } @@ -132,12 +138,14 @@ async function withAdminClient(testUri: string, fn: (client: Client) => Promise< } } -/** Terminate every backend connected to `dbName` so it can be dropped/cloned. */ -async function terminateBackends(admin: Client, dbName: string): Promise { - await admin.query( - "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()", - [dbName], - ); +/** + * Drop a database even while client pools keep reconnecting to it. Postgres + * >= 13 (`WITH (FORCE)`) terminates conflicting sessions itself and waits for + * the lock, removing the terminate-then-drop race against vitest forks that + * are still shutting down when post-run cleanup runs. + */ +async function forceDropDatabase(admin: Client, dbName: string): Promise { + await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(dbName)} WITH (FORCE)`); } /** @@ -149,8 +157,7 @@ export async function ensureTestDatabase(testUri: string, hardReset: boolean): P await withAdminClient(testUri, async (admin) => { const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]); if (hardReset && existing.rows.length > 0) { - await terminateBackends(admin, dbName); - await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`); + await forceDropDatabase(admin, dbName); existing.rows.length = 0; } if (existing.rows.length === 0) { @@ -166,8 +173,7 @@ export async function dropDatabaseIfPresent(uri: string): Promise { await withAdminClient(uri, async (admin) => { const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]); if (existing.rows.length === 0) return; - await terminateBackends(admin, dbName); - await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`); + await forceDropDatabase(admin, dbName); dropped = true; }); return dropped; @@ -427,17 +433,19 @@ export async function ensureTemplateDatabase(): Promise { } /** - * Replace the target database with an exact copy of the template. Terminate - * leftover backends and drop first so a crashed run's state can never leak - * into a fresh clone. Subject to the CLONING INVARIANT at the top of this - * file: nothing may be connected to the template while this runs. + * Replace the target database with an exact copy of the template. The + * template is addressed by name derived from the target (clone `_w` suffix + * stripped, `_template` appended), so this never re-resolves the environment + * and works after DATABASE_URI mutations. Terminate leftover backends and + * drop first so a crashed run's state can never leak into a fresh clone. + * Subject to the CLONING INVARIANT at the top of this file: nothing may be + * connected to the template while this runs. */ export async function cloneTemplateInto(targetUri: string): Promise { const target = testDatabaseName(targetUri); - const template = testDatabaseName(templateDatabaseUri()); + const template = `${target.replace(/_w[0-9]+$/, "")}_template`; await withAdminClient(targetUri, async (admin) => { - await terminateBackends(admin, target); - await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(target)}`); + await forceDropDatabase(admin, target); await admin.query(`CREATE DATABASE ${quotedIdentifier(target)} TEMPLATE ${quotedIdentifier(template)}`); }); } @@ -454,8 +462,7 @@ export async function dropStaleWorkerDatabases(): Promise { [`^${base}_w[0-9]+$`], ); for (const row of rows as { datname: string }[]) { - await terminateBackends(admin, row.datname); - await admin.query(`DROP DATABASE ${quotedIdentifier(row.datname)}`); + await forceDropDatabase(admin, row.datname); dropped += 1; } }); diff --git a/tests/vitest-global.ts b/tests/vitest-global.ts index 23ec85e1..529c45d7 100644 --- a/tests/vitest-global.ts +++ b/tests/vitest-global.ts @@ -1,12 +1,29 @@ -import { bootstrapTestDatabase } from "./test-db"; +import { bootstrapTestDatabase, dropStaleWorkerDatabases, ensureTemplateDatabase } from "./test-db"; +import { clearFailureMarker } from "./vitest-marker"; +import vitestTeardown from "./vitest-teardown"; /** - * Vitest global setup: point the suite at the dedicated test database and - * leave it in a known state (ensured, migrated, truncated, seeded, sequences - * repaired) before any test file loads. Stage 2 rewires this entry point to - * the template + per-fork clone lifecycle; until then it bootstraps the one - * serial test database exactly as before. + * Vitest global setup. Two modes: + * + * - Workers mode (default): guarantee the template database, then drop any + * `_w` clones left behind by crashed runs. Per-fork cloning lives + * in tests/vitest-worker-setup.ts; nothing here truncates. After this + * function returns no further connections touch the template until the next + * build (CLONING INVARIANT in tests/test-db.ts). + * - Legacy serial mode (`TEST_DATABASE_URI` set): today's single-database + * truncate bootstrap, for bisecting flakes. + * + * The returned function is executed after the run: Vitest 4 removed the + * `globalTeardown` config option, returning a teardown from globalSetup is + * the supported contract (see tests/vitest-teardown.ts). */ -export default async function globalSetup(): Promise { - await bootstrapTestDatabase(); +export default async function globalSetup(): Promise<() => Promise> { + clearFailureMarker(); + if (process.env.TEST_DATABASE_URI) { + await bootstrapTestDatabase(); + } else { + await ensureTemplateDatabase(); + await dropStaleWorkerDatabases(); + } + return vitestTeardown; } diff --git a/tests/vitest-marker.ts b/tests/vitest-marker.ts new file mode 100644 index 00000000..b17cbf53 --- /dev/null +++ b/tests/vitest-marker.ts @@ -0,0 +1,25 @@ +import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +/** + * Failure marker shared by the custom vitest reporter (writer) and global + * teardown (reader). Vitest's globalTeardown cannot portably see pass/fail + * state, so the reporter leaves this file behind on failure and clears it on + * success; teardown keeps worker clones while it exists. globalSetup deletes + * a stale marker at startup so a run killed before reporting cannot keep + * clones alive forever. + */ +export const FAILURE_MARKER_FILE = path.resolve(".cache", "test-int-failed"); + +export function clearFailureMarker(): void { + rmSync(FAILURE_MARKER_FILE, { force: true }); +} + +export function writeFailureMarker(reason: string): void { + mkdirSync(path.dirname(FAILURE_MARKER_FILE), { recursive: true }); + writeFileSync(FAILURE_MARKER_FILE, `${new Date().toISOString()} ${reason}\n`); +} + +export function failureMarkerPresent(): boolean { + return existsSync(FAILURE_MARKER_FILE); +} diff --git a/tests/vitest-reporter.ts b/tests/vitest-reporter.ts new file mode 100644 index 00000000..db90c48e --- /dev/null +++ b/tests/vitest-reporter.ts @@ -0,0 +1,16 @@ +import { clearFailureMarker, writeFailureMarker } from "./vitest-marker"; + +/** + * Minimal custom reporter: records run outcome in the failure marker file so + * globalTeardown can keep worker database clones after a failed run (and drop + * them after a green one). See tests/vitest-marker.ts for why the reporter is + * the reliable channel. Vitest 4 calls onTestRunEnd(modules, errors, state) + * with state "passed" | "failed" | "interrupted". + */ +export default class FailureMarkerReporter { + onTestRunEnd(_modules: unknown[], errors: unknown[], state?: string): void { + const passed = (state ?? "passed") === "passed" && (!errors || errors.length === 0); + if (passed) clearFailureMarker(); + else writeFailureMarker(state ?? "failed"); + } +} diff --git a/tests/vitest-teardown.ts b/tests/vitest-teardown.ts index 7643d566..68fde72c 100644 --- a/tests/vitest-teardown.ts +++ b/tests/vitest-teardown.ts @@ -1,14 +1,30 @@ -import { resolveTestDatabaseUri, truncateAllData } from "./test-db"; +import { dropStaleWorkerDatabases, resolveTestDatabaseUri, truncateAllData } from "./test-db"; +import { failureMarkerPresent } from "./vitest-marker"; /** - * Vitest global teardown: leave the test database empty after the run. The - * next run truncates again anyway, so this is hygiene, not correctness: - * failures here must never fail the suite. + * Post-run cleanup returned by tests/vitest-global.ts (Vitest 4 removed the + * `globalTeardown` config option entirely; the supported contract is that + * globalSetup returns this function). Failures here must never fail the run; + * leftovers are dropped by the next run's globalSetup sweep regardless. + * + * - Workers mode: drop every `_w` clone after a green run; keep them + * when the failure marker exists (postmortem) or `KEEP_TEST_DBS=1`. The + * template itself survives across runs and is only rebuilt on hash mismatch + * or `TEST_DB_HARD_RESET=1`. + * - Legacy serial mode (`TEST_DATABASE_URI` set): truncate for hygiene. */ -export default async function globalTeardown(): Promise { +export default async function vitestTeardown(): Promise { try { - await truncateAllData(resolveTestDatabaseUri()); + if (process.env.TEST_DATABASE_URI) { + await truncateAllData(resolveTestDatabaseUri()); + return; + } + if (process.env.KEEP_TEST_DBS === "1" || failureMarkerPresent()) { + console.log("[test-db] keeping worker clones (failed run or KEEP_TEST_DBS=1)"); + return; + } + await dropStaleWorkerDatabases(); } catch (error) { - console.warn("[test-db] teardown truncate failed:", error); + console.warn("[test-db] teardown cleanup failed:", error); } } diff --git a/tests/vitest-worker-setup.ts b/tests/vitest-worker-setup.ts new file mode 100644 index 00000000..a22f124e --- /dev/null +++ b/tests/vitest-worker-setup.ts @@ -0,0 +1,44 @@ +import { cloneTemplateInto, workerDatabaseUri } from "./test-db"; + +/** + * Per-fork vitest setup, appended AFTER vitest.setup.ts in setupFiles. Gives + * every fork its own clone of the template database (`_w`), + * repoints DATABASE_URI at it, and caps the pg pool per Payload boot so N + * forks stay far below Postgres' max_connections. + * + * No-ops outside workers mode: with `TEST_DATABASE_URI` set the suite runs in + * legacy serial mode against the single override db (bisect hatch), and a + * missing VITEST_WORKER_ID means this is not a vitest worker process. + * + * NOTE: vitest imports setupFiles but never calls their default export, so + * the work happens in a top-level IIFE below. The vite-node SSR transform + * hoists top-level await into an async wrapper, so side effects MUST live + * inside the awaited function, not before it. + * + * The clone happens ONCE PER FORK, not per test file: setup files re-run + * before every file under isolate:true, but process.env survives those module + * resets, so the marker env var short-circuits repeats. Within a fork, files + * keep running sequentially against one database that started empty plus the + * seeded baseline, exactly mirroring the old cross-file semantics while two + * forks never share tables. + */ +const CLONED_MARKER_ENV = "PTF_WORKER_DB_CLONED"; + +async function attachWorkerDatabase(): Promise { + if (process.env.TEST_DATABASE_URI || !process.env.VITEST_WORKER_ID) return; + + // vitest.setup.ts already repointed DATABASE_URI at the serial test db, so + // derive names from THAT (re-resolving would append `_test` twice). + const uri = workerDatabaseUri(process.env.VITEST_WORKER_ID, process.env.DATABASE_URI); + if (process.env[CLONED_MARKER_ENV] === uri) return; + + await cloneTemplateInto(uri); + process.env[CLONED_MARKER_ENV] = uri; + process.env.DATABASE_URI = uri; + if (!process.env.TEST_PG_POOL_MAX) { + // Reads as pg PoolConfig.max in src/payload.config.ts (unset elsewhere). + process.env.TEST_PG_POOL_MAX = "3"; + } +} + +await attachWorkerDatabase(); diff --git a/vitest.config.mts b/vitest.config.mts index ce3389f6..d8bf42d8 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -2,16 +2,31 @@ import { defineConfig } from "vitest/config"; import react from "@vitejs/plugin-react"; import tsconfigPaths from "vite-tsconfig-paths"; +// Setting TEST_DATABASE_URI forces the legacy single-database serial mode +// (bisect hatch): shared db, truncate per run, no forks and no clones. +const serialMode = Boolean(process.env.TEST_DATABASE_URI); +const maxForks = Number(process.env.VITEST_MAX_FORKS ?? 8); + export default defineConfig({ plugins: [tsconfigPaths(), react()], test: { - environment: "jsdom", - setupFiles: ["./vitest.setup.ts"], + // Node by default; component specs opt into jsdom with a + // `// @vitest-environment jsdom` docblock. + environment: "node", + setupFiles: ["./vitest.setup.ts", "./tests/vitest-worker-setup.ts"], include: ["tests/int/**/*.int.spec.ts"], - // Serial test files: every spec shares one test database, and parallel - // workers against it produced flaky cross-file interference. - fileParallelism: false, globalSetup: ["./tests/vitest-global.ts"], - globalTeardown: ["./tests/vitest-teardown.ts"], + reporters: ["default", "./tests/vitest-reporter.ts"], + ...(serialMode + ? { fileParallelism: false } + : { + // Per-fork worker databases (tests/vitest-worker-setup.ts) replace + // the old serial execution: cross-file data interference is gone by + // construction because two forks never share tables. Fork cap stays + // conservative: Postgres max_connections=100 on this box plus IO. + fileParallelism: true, + pool: "forks" as const, + maxWorkers: maxForks, + }), }, });