diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a3d6191cc..b3ad934e2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -106,6 +106,10 @@ The Stryker mutation gate (`bun run conformance:mutation` in `server/typescript/packages/metadata`, via `scripts/run-stryker.sh`) builds its sandbox under `$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. +`scripts/ci-local.sh` gives each run its own `mo-ci-scratch..*` directory under `$DEV_SCRATCH` +and deletes it at the end. A process that exits without running its exit handler (a `bun test` +process, or one killed by a signal) leaves its per-process scratch behind; the next run of the same +user removes it once the process is gone and the directory is 15 minutes old. 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 })`: diff --git a/changelog.d/codegen-ts-scratch-gen-state-sweep.md b/changelog.d/codegen-ts-scratch-gen-state-sweep.md new file mode 100644 index 000000000..31aa77c7e --- /dev/null +++ b/changelog.d/codegen-ts-scratch-gen-state-sweep.md @@ -0,0 +1,10 @@ +- **codegen-ts: a run with no project no longer fills the scratch directory.** `runGen` without a + `projectRoot` keeps its gen-state in `$DEV_SCRATCH` (else the system temp directory) as + `meta-gen-state-`, and removed it only on the process's `exit` event. A `bun test` process + never fires `exit`, and neither does a killed one, so every test process that generated with no + project left up to ~120 MiB behind; on a shared RAM-backed scratch area they ran it out of space. + The first such run in a process now also removes leftover `meta-gen-state-` directories, + and the first `runGen` of any kind in a process removes leftover `meta-gen-untracked--…` + ones: those that the current user owns, whose processes no longer exist and that have not + changed for 15 minutes. `scripts/ci-local.sh` also gives each run its own `$DEV_SCRATCH` + subdirectory and deletes it at the end, removing those of earlier runs that were killed. diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index d77e0e480..72a526341 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -247,6 +247,26 @@ have() { command -v "$1" >/dev/null 2>&1; } CI_T0=$SECONDS CI_TMP="$(mktemp -d "${TMPDIR:-/tmp}/mo-ci-local.XXXXXX")" CI_RESULTS="$CI_TMP/main.tsv"; : > "$CI_RESULTS" +# Everything this run's tools write under $DEV_SCRATCH (a RAM tmpfs shared by every checkout, +# agent and CI job on the machine) goes in a directory of this run's own, which ci_cleanup +# deletes. Tools clean up after themselves only when they exit normally, and they do not +# always: a `bun test` process never fires `exit`, and a cancelled CI job is killed. Before +# this, those leftovers filled the 16 GiB scratch area and the CI runners failed on ENOSPC. +# The directory is named for this script's PID, so the directory of a run that was itself +# killed (a cancelled job past its grace period) is removed by a later run of the same user, +# once its process is gone and it has not changed for 15 minutes. +CI_SCRATCH="" +if [ -n "${DEV_SCRATCH:-}" ] && [ -d "$DEV_SCRATCH" ]; then + for ci_d in "${DEV_SCRATCH%/}"/mo-ci-scratch.*; do + ci_p="${ci_d##*/mo-ci-scratch.}"; ci_p="${ci_p%%.*}" + case "$ci_p" in ''|*[!0-9]*) continue ;; esac + ps -p "$ci_p" >/dev/null 2>&1 && continue + [ -n "$(find "$ci_d" -maxdepth 0 -type d -user "$(id -u)" -mmin +15 2>/dev/null)" ] && rm -rf "$ci_d" 2>/dev/null + done + CI_SCRATCH="$(mktemp -d "${DEV_SCRATCH%/}/mo-ci-scratch.$$.XXXXXX")" || { + echo "cannot create a scratch directory under DEV_SCRATCH ($DEV_SCRATCH)" >&2; rm -rf "$CI_TMP"; exit 1; } + export DEV_SCRATCH="$CI_SCRATCH" +fi record() { printf '%s\t%s\t%s\n' "$1" "$2" "$3" >> "$CI_RESULTS"; } # record fmt_dur() { if [ "$1" -ge 60 ]; then printf '%dm%02ds' $(($1 / 60)) $(($1 % 60)); else printf '%ds' "$1"; fi; } step_passed() { # step_passed "" — true when a step of that name has PASSED in this run @@ -271,7 +291,7 @@ step_passed() { # step_passed "" — true when a step of that name has PAS . "$(dirname "${BASH_SOURCE[0]}")/lib/maven-private-repo.sh" mo_maven_private_repo CI_M2_OWNED="$MO_M2_OWNED" -trap 'rm -rf "$CI_TMP" ${CI_M2_OWNED:+"$CI_M2_OWNED"}' EXIT # replaced by ci_cleanup below +trap 'rm -rf "$CI_TMP" ${CI_M2_OWNED:+"$CI_M2_OWNED"} ${CI_SCRATCH:+"$CI_SCRATCH"}' EXIT # replaced by ci_cleanup below # bun exits 1 when an OPTIONAL native dep fails its install script (the # ssh2/cpu-features chain needs node-gyp on the machine — `npm i -g node-gyp` @@ -1518,7 +1538,7 @@ kill_tree() { local c; for c in $(pgrep -P "$1" 2>/dev/null); do kill_tree "$c"; ci_cleanup() { local p; for p in "${LANE_PID[@]:-}"; do [ -n "$p" ] && kill -0 "$p" 2>/dev/null && kill_tree "$p"; done stop_pg_sidecar - rm -rf "$CI_TMP" ${CI_M2_OWNED:+"$CI_M2_OWNED"} + rm -rf "$CI_TMP" ${CI_M2_OWNED:+"$CI_M2_OWNED"} ${CI_SCRATCH:+"$CI_SCRATCH"} } trap ci_cleanup EXIT trap 'exit 130' INT TERM diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index d1a723a00..7b33ccb4d 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -3,7 +3,7 @@ import { join, relative, resolve, isAbsolute, dirname, sep } from "node:path"; import { warnMissingPromptGenerators } from "./prompt-generator-gate.js"; import { runEmitsEntityModule, runEmitsHonoRoutes, runEmitsQueries, runEmitsRestRoutes, runEmitsUiTier, runRoutesExpose } from "./ui-tier-gate.js"; import { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; -import { removeTree, removeTreeAtExit, scratchRoot } from "./scratch-dir.js"; +import { removeTree, removeTreeAtExit, scratchRoot, sweepDeadProcessDirs } from "./scratch-dir.js"; import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; import { existsSync, readFileSync } from "node:fs"; @@ -387,6 +387,10 @@ export function shouldNoteNamesArtifactAbsent( * generator needed a db module path; the runner then fails naming that generator. */ const DB_IMPORT_UNSET = "__METAOBJECTS_DB_IMPORT_UNSET__"; +/** Scratch-root directory names a run owns, each followed by the owning process's PID. */ +const GEN_STATE_PREFIX = "meta-gen-state-"; +const UNTRACKED_PREFIX = "meta-gen-untracked-"; + export async function runGen(opts: RunGenOpts): Promise { const warnings: string[] = []; const strategy = opts.mergeStrategy ?? "overwrite"; @@ -411,9 +415,14 @@ export async function runGen(opts: RunGenOpts): Promise { : resolve(projectRoot ?? process.cwd(), opts.genStateDir)) : (projectRoot !== undefined ? join(projectRoot, ".metaobjects", ".gen-state") - : join(scratchRoot(), `meta-gen-state-${process.pid}`)); - // A run with no project keeps its state for this process's later runs only. - if (opts.genStateDir === undefined && projectRoot === undefined) removeTreeAtExit(genStateDir); + : join(scratchRoot(), `${GEN_STATE_PREFIX}${process.pid}`)); + // A run with no project keeps its state for this process's later runs only. The exit handler + // never fires in a `bun test` process or one killed by a signal, so the first such run in a + // process also removes what dead processes left behind. + if (opts.genStateDir === undefined && projectRoot === undefined) { + removeTreeAtExit(genStateDir); + sweepDeadProcessDirs(GEN_STATE_PREFIX); + } // 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 @@ -422,7 +431,9 @@ 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(scratchRoot(), `meta-gen-untracked-${process.pid}-${randomUUID()}`); + // Removed when the run ends; a run killed mid-way leaves it for the sweep. + sweepDeadProcessDirs(UNTRACKED_PREFIX); + const untrackedGenStateDir = join(scratchRoot(), `${UNTRACKED_PREFIX}${process.pid}-${randomUUID()}`); const untrackedOutDirs = opts.untrackedOutDirs ?? []; const outsideProject = (fullPath: string): boolean => { if (projectRoot === undefined) return false; diff --git a/server/typescript/packages/codegen-ts/src/scratch-dir.ts b/server/typescript/packages/codegen-ts/src/scratch-dir.ts index 9f313028e..3629b3d24 100644 --- a/server/typescript/packages/codegen-ts/src/scratch-dir.ts +++ b/server/typescript/packages/codegen-ts/src/scratch-dir.ts @@ -51,10 +51,14 @@ export function removeTree(path: string): void { const removedAtExit = new Set(); /** - * Remove `path` when this process exits normally (the `exit` event; a process killed by a signal - * leaves it behind). For state a process shares across its own runs and no - * later process reads (runGen's gen-state for a run with no project): without it, every process - * that ever ran one left a directory in the scratch root. + * Remove `path` when this process exits normally (the `exit` event). For state a process shares + * across its own runs and no later process reads (runGen's gen-state for a run with no project). + * + * This alone does NOT keep the scratch root clean. A process killed by a signal never emits + * `exit`, and neither does a `bun test` process, serial or `--parallel` worker (Bun 1.3.14): the + * test runner ends without firing `exit` or `beforeExit`. Every test process that generated with + * no project therefore left its directory behind, ~120 MiB for a codegen-ts worker, and they + * filled a 16 GiB RAM-backed scratch root. {@link sweepDeadProcessDirs} removes those. */ export function removeTreeAtExit(path: string): void { if (removedAtExit.has(path)) return; @@ -71,3 +75,59 @@ export function removeTreeAtExit(path: string): void { } removedAtExit.add(path); } + +/** How long a dead-looking process's directory is left alone before a sweep removes it, measured + * from the directory's own mtime, which moves only when a direct entry is created, removed or + * renamed. A partial guard for a process in another PID namespace (a container sharing the + * scratch root), whose live PID this process cannot see: writes deeper in its tree do not + * refresh that mtime. */ +const SWEEP_MIN_AGE_MS = 15 * 60 * 1000; + +const swept = new Set(); + +/** True when no process with this PID exists. A PID owned by another user answers EPERM: alive. */ +function processIsGone(pid: number): boolean { + try { + process.kill(pid, 0); + return false; + } catch (e) { + return (e as NodeJS.ErrnoException).code === "ESRCH"; + } +} + +/** + * Remove this user's directories `` (optionally followed by `-`) under + * {@link scratchRoot} whose process no longer exists and that have not changed for + * {@link SWEEP_MIN_AGE_MS}. Runs once per prefix per process; never throws. The cleanup for + * per-process state whose owner never ran its exit handler (see {@link removeTreeAtExit}). + */ +export function sweepDeadProcessDirs(prefix: string): void { + const root = scratchRoot(); + const key = `${root}\0${prefix}`; + if (swept.has(key)) return; + swept.add(key); + let names: string[]; + try { + names = readdirSync(root); + } catch { + return; + } + const now = Date.now(); + const uid = process.getuid?.(); + for (const name of names) { + if (!name.startsWith(prefix)) continue; + const m = /^(\d+)(?:-|$)/.exec(name.slice(prefix.length)); + if (m === null) continue; + const pid = Number(m[1]); + if (pid === process.pid || !processIsGone(pid)) continue; + const path = join(root, name); + try { + const st = lstatSync(path); + if (!st.isDirectory() || now - st.mtimeMs < SWEEP_MIN_AGE_MS) continue; + if (uid !== undefined && st.uid !== uid) continue; + removeTree(path); + } catch { + // Another sweeper got there first, or the entry belongs to someone we cannot remove. + } + } +} diff --git a/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts index 316295ce6..6ee43f72b 100644 --- a/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts +++ b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts @@ -1,7 +1,7 @@ -import { describe, test, expect } from "bun:test"; -import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs"; +import { describe, test, expect, spyOn } from "bun:test"; +import { existsSync, mkdirSync, readdirSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; -import { makeScratchDir, removeTree, scratchRoot } from "../src/scratch-dir.js"; +import { makeScratchDir, removeTree, scratchRoot, sweepDeadProcessDirs } from "../src/scratch-dir.js"; describe("scratch-dir", () => { test("makeScratchDir is unique, under the scratch root, and removeTree clears a populated tree", () => { @@ -51,4 +51,63 @@ describe("scratch-dir", () => { removeTree(root); } }); + + // `bun test` never fires `exit` (serial or --parallel worker, Bun 1.3.14), and a killed process + // never does either, so the exit handler above cannot be the only cleanup: on the self-hosted + // CI runners ~900 such directories (8.6 GiB) filled the 16 GiB RAM scratch root. The next run + // with no project removes the directories of processes that no longer exist. + test("a run with no project removes the gen-state that dead processes left behind", () => { + const root = makeScratchDir("scratch-dir-sweep-"); + try { + const dead = Bun.spawnSync(["true"]).pid; // exited: its PID names no process now + const old = new Date(Date.now() - 60 * 60 * 1000); + const make = (name: string, aged: boolean): string => { + const dir = join(root, name); + mkdirSync(join(dir, "nested"), { recursive: true }); + writeFileSync(join(dir, "nested", "snapshot"), "x"); + if (aged) utimesSync(dir, old, old); + return name; + }; + const deadState = make(`meta-gen-state-${dead}`, true); + const deadUntracked = make(`meta-gen-untracked-${dead}-0b0e`, true); + const recentDead = make(`meta-gen-untracked-${dead}-fresh`, false); // may belong to another PID namespace + const live = make(`meta-gen-state-${process.pid}`, true); // this test's own process is alive + const foreign = make("meta-gen-state-fallback", true); // not a PID: not ours to judge + const runner = resolve(import.meta.dir, "../src/runner.ts"); + writeFileSync(join(root, "meta.t.json"), JSON.stringify({ "metadata.root": { package: "t", children: [{ "object.entity": { name: "Thing", children: [{ "field.string": { name: "label" } }] } }] } })); + const script = ` + import { runGen } from ${JSON.stringify(runner)}; + import { loadUris } from ${JSON.stringify(import.meta.resolve("@metaobjectsdev/metadata"))}; + import { pathToFileURL } from "node:url"; + const { root: metadata } = await loadUris([pathToFileURL(${JSON.stringify(join(root, "meta.t.json"))}).href]); + await runGen({ metadata, config: { outDir: ${JSON.stringify(join(root, "out"))}, generators: [{ name: "one", generate: () => [{ path: "one.txt", content: "1" }] }] } }); + `; + const child = Bun.spawnSync(["bun", "-e", script], { env: { ...process.env, DEV_SCRATCH: root }, stderr: "pipe" }); + expect({ exit: child.exitCode, stderr: child.stderr.toString() }).toEqual({ exit: 0, stderr: "" }); + const left = readdirSync(root); + expect(left).not.toContain(deadState); + expect(left).not.toContain(deadUntracked); + expect(left).toEqual(expect.arrayContaining([recentDead, live, foreign])); + } finally { + removeTree(root); + } + }); + + // The scratch root can be the shared system temp directory, where another user controls what + // is inside their own directories while a remover walks them. + test.skipIf(process.getuid === undefined)("a sweep leaves another user's directory alone", () => { + const prefix = `scratch-dir-owner-${process.pid}-`; + const dir = join(scratchRoot(), `${prefix}${Bun.spawnSync(["true"]).pid}`); + mkdirSync(dir); + const old = new Date(Date.now() - 60 * 60 * 1000); + utimesSync(dir, old, old); + const getuid = spyOn(process, "getuid").mockReturnValue(statSync(dir).uid + 1); + try { + sweepDeadProcessDirs(prefix); + expect(existsSync(dir)).toBe(true); + } finally { + getuid.mockRestore(); + removeTree(dir); + } + }); });