diff --git a/tests/e2e/global-setup.ts b/tests/e2e/global-setup.ts index af1405b0..3293edf8 100644 --- a/tests/e2e/global-setup.ts +++ b/tests/e2e/global-setup.ts @@ -2,10 +2,11 @@ import { bootstrapTestDatabase } from "../test-db"; import { resolveTestDatabaseUri } from "../test-db"; /** - * Playwright global setup: ensure the dedicated test database exists, is - * migrated, seeded and emptied before the dev server (started by webServer - * with DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared - * e2e login ("dev" / "Test123"): every authed spec logs in with it, and the + * Playwright global setup: ensure the dedicated test database exists and is + * freshly built from the cached schema template (push runs only when the + * schema hash changed) before the dev server (started by webServer with + * DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared e2e + * login ("dev" / "Test123"): every authed spec logs in with it, and the * dashboard smoke expects the "Welcome back, J. Fraley." heading. */ export default async function globalSetup(): Promise { diff --git a/tests/test-db.ts b/tests/test-db.ts index 65ab14f0..bfc89410 100644 --- a/tests/test-db.ts +++ b/tests/test-db.ts @@ -1,4 +1,7 @@ import { execSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; import { Client } from "pg"; import { applyAnalyticsDdl, ANALYTICS_TABLE_NAMES } from "../src/lib/analytics/schema"; @@ -10,21 +13,52 @@ import "dotenv/config"; /** * Dedicated test database machinery for the vitest and Playwright suites. * - * Tests never touch the development database: they run against a sibling - * `_test` database that is ensured, migrated, seeded and truncated per - * run. All operations are idempotent, so a crashed run's leftovers are wiped - * by the next run no matter what leaked. + * Tests never touch the development database. The topology: + * + * - `ptf_app_test_template` is built once per schema change by globalSetup: + * ensure db, drop analytics tables, drizzle push (auto-accepting warnings), + * analytics DDL, seedRoles + baseline seed, sequence repair. A hash of all + * schema-relevant inputs is cached in `.cache/testdb-template.json`; warm + * runs skip the push entirely. + * - Vitest workers each clone it into `ptf_app_test_w` at startup + * (`CREATE DATABASE ... TEMPLATE`, milliseconds because it holds only the + * empty baseline schema) and drop the clones at teardown unless the run + * failed. Two workers therefore never share tables. + * - `ptf_app_test` (the serial database, used by Playwright and by legacy + * serial vitest when no override is set) is recreated fresh from the + * template on every bootstrap instead of being truncated in place. + * + * >>> CLONING INVARIANT - DO NOT BREAK <<< + * `CREATE DATABASE ... TEMPLATE` fails while anything is connected to the + * template. Every clone happens after globalSetup finished building it and + * before any worker's tests import the Payload config, and no test code ever + * connects to the template database. If future tooling wants to "just peek" + * at `ptf_app_test_template` during a run, it must go through a snapshot + * clone instead - peeks re-break parallel worker startup. * * Override points: - * - `TEST_DATABASE_URI` — use this exact connection string instead of the - * derived one. - * - `TEST_DB_HARD_RESET=1` — drop and recreate the test database (fresh - * schema from migrations) instead of the default truncate flow. + * - `TEST_DATABASE_URI`: use this exact connection string instead of the + * derived one. This also forces LEGACY SERIAL behavior (single shared db, + * truncate per run, no templates or clones) for bisecting flakes. + * - `TEST_DB_HARD_RESET=1`: ignore the template cache and rebuild the + * template from scratch. + * - `KEEP_TEST_DBS=1`: teardown keeps worker clones even after green runs + * (postmortem hatch). */ /** Tables that must survive truncation: PostGIS internals and migration journals. */ const SKIP_TRUNCATE = new Set(["spatial_ref_sys", "__drizzle_migrations", "payload_migrations"]); +/** Template build cache; gitignored, disposable, rebuilt on hash mismatch. */ +const TEMPLATE_CACHE_FILE = path.join(".cache", "testdb-template.json"); + +interface TemplateCache { + hash: string; + builtAt: string; + pgVersion: string; + dbName: string; +} + /** True when truncation should be skipped in favor of a full drop/recreate. */ export function hardResetRequested(): boolean { return process.env.TEST_DB_HARD_RESET === "1"; @@ -59,6 +93,28 @@ function testDatabaseName(testUri: string): string { return name; } +/** Same connection string with its database name replaced. */ +function withDatabaseName(testUri: string, dbName: string): string { + const url = new URL(testUri); + const segments = url.pathname.split("/").filter(Boolean); + if (segments.length === 0) throw new Error("Database URI has no database name"); + segments[segments.length - 1] = dbName; + url.pathname = segments.join("/"); + return url.toString(); +} + +/** Template database URI (`ptf_app_test` -> `ptf_app_test_template`). */ +export function templateDatabaseUri(): string { + const base = 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(); + return withDatabaseName(base, `${testDatabaseName(base)}_w${workerId}`); +} + function quotedIdentifier(identifier: string): string { return `"${identifier.replace(/"/g, '""')}"`; } @@ -76,6 +132,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], + ); +} + /** * Create the test database when missing. With `hardReset`, terminate * connections, drop it and recreate from scratch instead. @@ -85,10 +149,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 admin.query( - "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()", - [dbName], - ); + await terminateBackends(admin, dbName); await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`); existing.rows.length = 0; } @@ -98,10 +159,25 @@ export async function ensureTestDatabase(testUri: string, hardReset: boolean): P }); } +/** Drop the database when present, terminating any lingering backends. */ +export async function dropDatabaseIfPresent(uri: string): Promise { + const dbName = testDatabaseName(uri); + let dropped = false; + 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)}`); + dropped = true; + }); + return dropped; +} + /** * Create or diff the full schema via drizzle push. The migration chain * assumes a schema that push originally created (its first migration alters * existing tables), so a fresh database is built by pushing, not migrating. + * Warning/data-loss prompts are auto-accepted (see tests/push-schema.ts). */ export function pushSchema(testUri: string): void { execSync("bun run tests/push-schema.ts", { @@ -149,8 +225,9 @@ export async function ensureAnalyticsTables(testUri: string): Promise { /** * Truncate every table in the public schema except migration journals and - * PostGIS internals. Idempotent by construction: the result is the same empty - * database no matter how many rows leaked from earlier runs. + * PostGIS internals. Only used by the legacy serial path (`TEST_DATABASE_URI` + * override) for bootstrap and teardown hygiene; template clones replace + * truncation everywhere else. Idempotent by construction. */ export async function truncateAllData(testUri: string): Promise { const client = new Client({ connectionString: testUri }); @@ -213,13 +290,190 @@ export function runSeedScripts(testUri: string): void { } } +// --------------------------------------------------------------------------- +// Template database + schema-hash cache +// --------------------------------------------------------------------------- + /** - * Full bootstrap, safe to call repeatedly: ensure the database (drop/recreate - * on hard reset), apply migrations, truncate leftover data, reseed baselines - * and repair sequences. + * Deliberately broad input set for the template cache key. False positives + * (rebuild with no real change) cost one cold build; misses produce loud but + * confusing "column does not exist" failures, recoverable via + * TEST_DB_HARD_RESET=1. When in doubt, add to the list. */ -export async function bootstrapTestDatabase(): Promise { - const testUri = resolveTestDatabaseUri(); +const SCHEMA_HASH_FILES = [ + "src/payload.config.ts", + "src/payload-generated-schema.ts", + "drizzle.config.ts", + "package.json", +]; +const SCHEMA_HASH_DIRS = ["src/collections", "src/globals", "src/utils", "src/migrations", "patches"]; +const SCHEMA_HASH_PACKAGES = ["payload", "@payloadcms/drizzle", "drizzle-orm", "@payloadcms/plugin-mcp"]; + +function walkFiles(dir: string): string[] { + if (!existsSync(dir)) return []; + const out: string[] = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) out.push(...walkFiles(full)); + else if (entry.isFile()) out.push(full); + } + return out; +} + +async function pgServerVersion(): Promise { + let version = "unknown"; + await withAdminClient(resolveTestDatabaseUri(), async (admin) => { + const { rows } = await admin.query("SHOW server_version"); + version = String(rows[0]?.server_version ?? "unknown"); + }); + return version; +} + +/** sha256 over every schema-relevant input (see SCHEMA_HASH_* for the set). */ +export async function schemaHash(): Promise { + const pkg = JSON.parse(readFileSync(path.resolve("package.json"), "utf8")) as { + dependencies?: Record; + devDependencies?: Record; + }; + const cwd = process.cwd(); + const files = [ + ...SCHEMA_HASH_FILES.map((file) => path.resolve(cwd, file)), + ...SCHEMA_HASH_DIRS.flatMap((dir) => walkFiles(path.resolve(cwd, dir))), + ] + .filter((file) => existsSync(file)) + .map((file) => path.relative(cwd, file)) + .sort(); + + const hash = createHash("sha256"); + for (const rel of files) { + hash.update(rel); + hash.update("\0"); + hash.update(readFileSync(path.resolve(cwd, rel))); + hash.update("\0"); + } + for (const dep of SCHEMA_HASH_PACKAGES) { + hash.update(`${dep}@${pkg.dependencies?.[dep] ?? pkg.devDependencies?.[dep] ?? "missing"}\n`); + } + hash.update(`pg:${await pgServerVersion()}\n`); + return hash.digest("hex"); +} + +function readTemplateCache(): TemplateCache | null { + try { + return JSON.parse(readFileSync(path.resolve(TEMPLATE_CACHE_FILE), "utf8")) as TemplateCache; + } catch { + return null; + } +} + +function writeTemplateCache(cache: TemplateCache): void { + const file = path.resolve(TEMPLATE_CACHE_FILE); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(cache, null, 2)); +} + +/** Cheap liveness probe: does the template still exist and carry a schema? */ +async function templateIsLive(templateUri: string): Promise { + try { + const client = new Client({ connectionString: templateUri }); + await client.connect(); + try { + const { rows } = await client.query( + "SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'payload_migrations'", + ); + return rows.length > 0; + } finally { + await client.end(); + } + } catch { + return false; + } +} + +/** + * Ensure `ptf_app_test_template` exists and matches the current schema hash. + * On cache miss (or `TEST_DB_HARD_RESET=1`, or a broken/missing template): + * drop/recreate it and run the full build (push, analytics DDL, seeds, + * sequence repair). On hit: return immediately after a liveness check. + * Never truncates - a template is a point-in-time image that clones inherit. + */ +export async function ensureTemplateDatabase(): Promise { + const templateUri = templateDatabaseUri(); + const templateName = testDatabaseName(templateUri); + const pgVersion = await pgServerVersion(); + const hash = await schemaHash(); + + if (!hardResetRequested()) { + const cached = readTemplateCache(); + if (cached && cached.hash === hash && cached.dbName === templateName && (await templateIsLive(templateUri))) { + console.log(`[test-db] template cache hit: ${templateName}`); + return templateUri; + } + } + + const started = Date.now(); + console.log( + `[test-db] building template ${templateName}${hardResetRequested() ? " (hard reset)" : ""}...`, + ); + await ensureTestDatabase(templateUri, true); + await dropAnalyticsTables(templateUri); + pushSchema(templateUri); + await ensureAnalyticsTables(templateUri); + runSeedScripts(templateUri); + await repairSequences(templateUri); + writeTemplateCache({ hash, builtAt: new Date().toISOString(), pgVersion, dbName: templateName }); + console.log(`[test-db] template ready: ${templateName} in ${((Date.now() - started) / 1000).toFixed(1)}s`); + return templateUri; +} + +/** + * 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. + */ +export async function cloneTemplateInto(targetUri: string): Promise { + const target = testDatabaseName(targetUri); + const template = testDatabaseName(templateDatabaseUri()); + await withAdminClient(targetUri, async (admin) => { + await terminateBackends(admin, target); + await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(target)}`); + await admin.query(`CREATE DATABASE ${quotedIdentifier(target)} TEMPLATE ${quotedIdentifier(template)}`); + }); +} + +/** Enumerate + drop `_w` clones left behind by crashed runs. */ +export async function dropStaleWorkerDatabases(): Promise { + const base = testDatabaseName(resolveTestDatabaseUri()); + let dropped = 0; + await withAdminClient(resolveTestDatabaseUri(), async (admin) => { + // Postgres database names are [a-z0-9_]; none of those are regex + // specials, so the derived base can be interpolated directly. + const { rows } = await admin.query( + "SELECT datname FROM pg_database WHERE datname ~ $1", + [`^${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)}`); + dropped += 1; + } + }); + if (dropped > 0) console.log(`[test-db] dropped ${dropped} stale worker database(s)`); + return dropped; +} + +// --------------------------------------------------------------------------- +// Bootstrap entry points +// --------------------------------------------------------------------------- + +/** + * Legacy serial bootstrap against one shared database, safe to call + * repeatedly: ensure (drop/recreate on hard reset), push, truncate leftover + * data, reseed baselines, repair sequences. Used when `TEST_DATABASE_URI` + * explicitly points the suite at a single db (bisect mode). + */ +export async function bootstrapSerialDatabase(testUri: string): Promise { const hardReset = hardResetRequested(); await ensureTestDatabase(testUri, hardReset); @@ -230,7 +484,23 @@ export async function bootstrapTestDatabase(): Promise { runSeedScripts(testUri); await repairSequences(testUri); - const dbName = testDatabaseName(testUri); - console.log(`[test-db] ready: ${dbName}${hardReset ? " (hard reset)" : ""}`); + console.log(`[test-db] ready: ${testDatabaseName(testUri)}${hardReset ? " (hard reset)" : ""}`); + return testUri; +} + +/** + * Full bootstrap for the serial databases (Playwright; legacy vitest bisect + * mode). Without an explicit override it guarantees the template and hands + * back a FRESH clone of it - no truncate, no push in the steady state. + */ +export async function bootstrapTestDatabase(): Promise { + const testUri = resolveTestDatabaseUri(); + if (process.env.TEST_DATABASE_URI) { + return bootstrapSerialDatabase(testUri); + } + + await ensureTemplateDatabase(); + await cloneTemplateInto(testUri); + console.log(`[test-db] ready: ${testDatabaseName(testUri)} (cloned from template)`); return testUri; } diff --git a/tests/vitest-global.ts b/tests/vitest-global.ts index 5b7a412d..23ec85e1 100644 --- a/tests/vitest-global.ts +++ b/tests/vitest-global.ts @@ -3,7 +3,9 @@ import { bootstrapTestDatabase } from "./test-db"; /** * 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. + * 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. */ export default async function globalSetup(): Promise { await bootstrapTestDatabase();