import { dropStaleWorkerDatabases, resolveTestDatabaseUri, truncateAllData } from "./test-db";
import { failureMarkerPresent } from "./vitest-marker";
/**
* 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`.
* `KEEP_TEST_DBS=0` forces dropping even after failures. 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 vitestTeardown(): Promise {
try {
if (process.env.TEST_DATABASE_URI) {
await truncateAllData(resolveTestDatabaseUri());
return;
}
const forceKeep = process.env.KEEP_TEST_DBS === "1";
const forceDrop = process.env.KEEP_TEST_DBS === "0";
if (!forceDrop && (forceKeep || 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 cleanup failed:", error);
}
}