diff --git a/.github/workflows/local-ci.yml b/.github/workflows/local-ci.yml index 21553778ce..63a147b6a9 100644 --- a/.github/workflows/local-ci.yml +++ b/.github/workflows/local-ci.yml @@ -347,6 +347,6 @@ jobs: RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus" - notify-send -u critical "local-ci FAILED: metaobjects" \ + notify-send -u normal "local-ci FAILED: metaobjects" \ "$(printf '%s' "$HEAD_MSG" | head -n1) $RUN_URL" || echo "notify-send unavailable; GitHub email still fires" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8c35a9e1f6..8e3bf9fd00 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -90,6 +90,10 @@ The Stryker mutation gate (`bun run conformance:mutation` in `$DEV_SCRATCH` when that is set, else the system temp directory, and removes it on exit. Point `DEV_SCRATCH` at a RAM-backed directory to keep that scratch off disk. +In `server/typescript/packages/codegen-ts`, a new test that needs a temp directory uses `makeScratchDir` +and `removeTree` (`src/scratch-dir.ts`), not `mkdtempSync` and `rmSync(..., { recursive: true })`: +Bun's recursive `rmSync` can fail with `EFAULT` under parallel test load and fail the test. + ### Local CI (the checks GitHub runs — run it before opening a PR) GitHub Actions is enabled on this repository. The check workflows in diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index bbdbf5cb1a..adbdb6f1af 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -3,10 +3,10 @@ import { join, relative, resolve, isAbsolute, dirname, sep } from "node:path"; import { warnMissingPromptGenerators } from "./prompt-generator-gate.js"; import { runEmitsEntityModule, runEmitsHonoRoutes, runEmitsQueries, runEmitsRestRoutes, runEmitsUiTier, runRoutesExpose, warnUnmarkedRoutesGenerators, warnUnmarkedUiGenerators } from "./ui-tier-gate.js"; import { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; -import { tmpdir } from "node:os"; +import { removeTree, scratchRoot } from "./scratch-dir.js"; import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; -import { existsSync, readFileSync, rmSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import type { MetaData, MetaObject } from "@metaobjectsdev/metadata"; import { isMetaRoot, FIELD_SUBTYPE_TIMESTAMP, FIELD_ATTR_FILTERABLE, @@ -382,7 +382,7 @@ export async function runGen(opts: RunGenOpts): Promise { : resolve(projectRoot ?? process.cwd(), opts.genStateDir)) : (projectRoot !== undefined ? join(projectRoot, ".metaobjects", ".gen-state") - : join(tmpdir(), `meta-gen-state-${process.pid}`)); + : join(scratchRoot(), `meta-gen-state-${process.pid}`)); // A file written OUTSIDE the project has no place in the project's gen-state: its // manifest key would be `../..`-relative, committed into the hash manifest, and its snapshot // body — stored at `/` — would walk out of `.gen-state/` and land a second @@ -391,7 +391,7 @@ export async function runGen(opts: RunGenOpts): Promise { // Unique to THIS run, not just this process: a second runGen in one process (an embedder, // a watch loop, a test) would otherwise find the first run's snapshot and three-way merge, // which is exactly the record-keeping an untracked file does not have. - const untrackedGenStateDir = join(tmpdir(), `meta-gen-untracked-${process.pid}-${randomUUID()}`); + const untrackedGenStateDir = join(scratchRoot(), `meta-gen-untracked-${process.pid}-${randomUUID()}`); const untrackedOutDirs = opts.untrackedOutDirs ?? []; const outsideProject = (fullPath: string): boolean => { if (projectRoot === undefined) return false; @@ -418,7 +418,7 @@ export async function runGen(opts: RunGenOpts): Promise { }; const noteUntracked = (): void => { // The per-run state held nothing anyone reads again; do not leave it in the tmpdir. - rmSync(untrackedGenStateDir, { recursive: true, force: true }); + removeTree(untrackedGenStateDir); if (untrackedCount === 0) return; warnings.push( `${untrackedCount} generated file(s) were written outside the project root and are not ` + diff --git a/server/typescript/packages/codegen-ts/src/scratch-dir.ts b/server/typescript/packages/codegen-ts/src/scratch-dir.ts new file mode 100644 index 0000000000..b3402c0c56 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/scratch-dir.ts @@ -0,0 +1,49 @@ +// Throwaway directories: where they live and how they are removed. +// +// Bun's `rmSync(dir, { recursive: true })` has been seen failing with +// `EFAULT: bad address in system call argument` while other tests in the same process +// were also touching the filesystem (observed on Bun 1.3.x; local Bun 1.3.14). The failure +// is in the remover, not in the directory, so removal never calls it: it always walks the +// tree with readdir/unlink/rmdir. A path that is already gone is success, never an error: +// another remover may have beaten us to it. +import { mkdtempSync, readdirSync, rmdirSync, unlinkSync, lstatSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +/** `$DEV_SCRATCH` (RAM-backed) when set and non-empty, else the OS temp directory. */ +export function scratchRoot(): string { + const scratch = process.env.DEV_SCRATCH; + return scratch !== undefined && scratch !== "" ? scratch : tmpdir(); +} + +/** A fresh, uniquely named directory under {@link scratchRoot}. */ +export function makeScratchDir(prefix: string): string { + return mkdtempSync(join(scratchRoot(), prefix)); +} + +const isGone = (e: unknown): boolean => (e as NodeJS.ErrnoException).code === "ENOENT"; + +function walkRemove(path: string): void { + let isDir: boolean; + try { + isDir = lstatSync(path).isDirectory(); + } catch (e) { + if (isGone(e)) return; + throw e; + } + try { + if (!isDir) { + unlinkSync(path); + return; + } + for (const name of readdirSync(path)) walkRemove(join(path, name)); + rmdirSync(path); + } catch (e) { + if (!isGone(e)) throw e; + } +} + +/** Remove a directory tree, tolerating it being absent. Never uses Bun's recursive `rmSync`. */ +export function removeTree(path: string): void { + walkRemove(path); +} diff --git a/server/typescript/packages/codegen-ts/test/package-layout-root-declared.test.ts b/server/typescript/packages/codegen-ts/test/package-layout-root-declared.test.ts index 02fe64a673..a029be87bb 100644 --- a/server/typescript/packages/codegen-ts/test/package-layout-root-declared.test.ts +++ b/server/typescript/packages/codegen-ts/test/package-layout-root-declared.test.ts @@ -36,7 +36,8 @@ // barrel exports to name a file the run actually wrote. import { describe, expect, test } from "bun:test"; -import { mkdtempSync, rmSync, readdirSync, statSync, readFileSync } from "node:fs"; +import { readdirSync, statSync, readFileSync } from "node:fs"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; import { join, relative } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; @@ -78,7 +79,7 @@ async function emit(model: unknown, outputLayout: "flat" | "package"): Promise e.message)).toEqual([]); - const dir = mkdtempSync(join(import.meta.dir, "tmp-pkg-layout-")); + const dir = makeScratchDir("tmp-pkg-layout-"); try { await runGen({ config: defineConfig({ @@ -102,7 +103,7 @@ async function emit(model: unknown, outputLayout: "flat" | "package"): Promise e.message)).toEqual([]); - const dir = mkdtempSync(join(import.meta.dir, "tmp-pkg-barrel-")); + const dir = makeScratchDir("tmp-pkg-barrel-"); try { await runGen({ config: defineConfig({ @@ -145,7 +146,7 @@ async function emitWithBarrel( const specifiers = [...index.matchAll(/from\s+"([^"]+)"/g)].map((m) => m[1]!); return { specifiers, files: files.sort() }; } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } } @@ -237,7 +238,7 @@ describe("every relative import resolves in package layout, shared enums include new InMemoryStringSource(JSON.stringify(ENUM_MODEL), { id: "meta.json" }), ]); expect(errors.map((e) => e.message)).toEqual([]); - const dir = mkdtempSync(join(import.meta.dir, "tmp-pkg-enum-")); + const dir = makeScratchDir("tmp-pkg-enum-"); try { await runGen({ config: defineConfig({ @@ -277,7 +278,7 @@ describe("every relative import resolves in package layout, shared enums include expect(enumImports).toBeGreaterThan(0); expect(unresolved).toEqual([]); } finally { - rmSync(dir, { recursive: true, force: true }); + removeTree(dir); } }); }); diff --git a/server/typescript/packages/codegen-ts/test/run-gen.test.ts b/server/typescript/packages/codegen-ts/test/run-gen.test.ts index 31bf582e45..dfe1915cfb 100644 --- a/server/typescript/packages/codegen-ts/test/run-gen.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-gen.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync, readFileSync, existsSync, readdirSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { readFileSync, existsSync, readdirSync, writeFileSync } from "node:fs"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; import { join, resolve } from "node:path"; import type { MetaRoot, MetaObject } from "@metaobjectsdev/metadata"; import { @@ -24,8 +24,8 @@ import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-run-gen-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-run-gen-"); }); +afterEach(() => { removeTree(tmp); }); const FIXTURE_DIR = resolve(import.meta.dir, "fixtures"); @@ -305,7 +305,7 @@ describe("runGen — entityFilter", () => { const fullBarrel = readFileSync(join(tmp, "index.ts"), "utf-8"); expect(fullBarrel).toContain('export * from "./Post"'); expect(fullBarrel).toContain('export * from "./User"'); - for (const f of readdirSync(tmp)) rmSync(join(tmp, f), { recursive: true, force: true }); + for (const f of readdirSync(tmp)) removeTree(join(tmp, f)); const out = await runGen({ config, metadata: result.root, entityFilter: ["Post"] }); expect(out.warnings).toEqual([]); diff --git a/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts new file mode 100644 index 0000000000..875ed7d8f8 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts @@ -0,0 +1,25 @@ +import { describe, test, expect } from "bun:test"; +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { makeScratchDir, removeTree, scratchRoot } from "../src/scratch-dir.js"; + +describe("scratch-dir", () => { + test("makeScratchDir is unique, under the scratch root, and removeTree clears a populated tree", () => { + const a = makeScratchDir("scratch-dir-test-"); + const b = makeScratchDir("scratch-dir-test-"); + expect(a).not.toBe(b); + expect(a.startsWith(scratchRoot())).toBe(true); + mkdirSync(join(a, "x", "y"), { recursive: true }); + writeFileSync(join(a, "x", "y", "f.txt"), "1"); + removeTree(a); + removeTree(b); + expect(existsSync(a)).toBe(false); + expect(existsSync(b)).toBe(false); + }); + + test("removeTree of an absent path is not an error", () => { + const a = makeScratchDir("scratch-dir-test-"); + removeTree(a); + expect(() => removeTree(a)).not.toThrow(); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/vo-only-config-optional.test.ts b/server/typescript/packages/codegen-ts/test/vo-only-config-optional.test.ts index 79babebf5b..3ddf0c6188 100644 --- a/server/typescript/packages/codegen-ts/test/vo-only-config-optional.test.ts +++ b/server/typescript/packages/codegen-ts/test/vo-only-config-optional.test.ts @@ -11,8 +11,7 @@ // could not use it. It is now demanded at the point of USE, by the generator that // needs it, naming that generator. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { runGen } from "../src/runner.js"; @@ -22,8 +21,8 @@ import { entityFile as referenceEntityFile } from "../src/reference/entity.js"; import type { MetaobjectsGenConfig } from "../src/metaobjects-config.js"; let tmp: string; -beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-vo-only-")); }); -afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); +beforeEach(() => { tmp = makeScratchDir("codegen-vo-only-"); }); +afterEach(() => { removeTree(tmp); }); async function load(children: unknown[]) { const json = JSON.stringify({ "metadata.root": { package: "app", children } }); diff --git a/server/typescript/packages/integration-tests/test/report-views-sqlite.test.ts b/server/typescript/packages/integration-tests/test/report-views-sqlite.test.ts index ddfd31999f..d843adfd65 100644 --- a/server/typescript/packages/integration-tests/test/report-views-sqlite.test.ts +++ b/server/typescript/packages/integration-tests/test/report-views-sqlite.test.ts @@ -23,7 +23,7 @@ */ import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; +import { lstatSync, mkdtempSync, readdirSync, rmdirSync, unlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { Kysely, sql } from "kysely"; @@ -44,17 +44,34 @@ function literalColumns(root: T): T { return root; } +/** Walks the tree instead of Bun's recursive rmSync, which intermittently throws EFAULT under load. */ +function removeTree(path: string): void { + try { + if (!lstatSync(path).isDirectory()) { unlinkSync(path); return; } + for (const n of readdirSync(path)) removeTree(join(path, n)); + rmdirSync(path); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e; + } +} + let tmpDir: string; let k: Kysely>; -beforeEach(() => { - tmpDir = mkdtempSync(join(tmpdir(), "report-views-sqlite-")); +beforeEach(async () => { + // The database file lives in RAM ($DEV_SCRATCH when set): libsql commits every DDL statement + // with an fsync, and the canonical model applies dozens of them per test, so on a disk that is + // ~1.3 s per test setup (14 tests, ~20 s) and past the default timeout when the disk is busy. + tmpDir = mkdtempSync(join(process.env.DEV_SCRATCH || tmpdir(), "report-views-sqlite-")); k = new Kysely({ dialect: new LibsqlDialect({ url: `file:${join(tmpDir, "test.db")}` }) }); + // A throwaway database needs no crash safety, so skip the per-statement fsync even when + // $DEV_SCRATCH is unset and the file lands on a real disk. + await sql.raw("PRAGMA synchronous = OFF").execute(k); }); afterEach(async () => { await k.destroy(); - rmSync(tmpDir, { recursive: true, force: true }); + removeTree(tmpDir); }); // libsql execute() is single-statement: split on ";" (no view body or seed carries an inner ";").