Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 80ee64bd70befb4f5598a8c5750f79c01fae36c3
parent ce861473ce3eba270365d2329e4559240b70910b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 17 Oct 2026 16:27:12 -0400

Merge r33/heavy-cap: queue-lock --heavy caps what it admits by default (8G/2G user scope; skipped under an existing cap)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MAGENTS.md | 5++++-
MENVIRONMENT.md | 4++++
MWORKTREES.md | 20++++++++++++++++++++
Mcommon/lib/envVars.ts | 4++++
Meditor/CHANGELOG.md | 1+
Mscripts/queue-lock.mjs | 110++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mscripts/queue-lock.test.mjs | 72+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
7 files changed, 213 insertions(+), 3 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -66,7 +66,10 @@ job that declares nothing (a render, a hand `pnpm heavy -- <cmd>`, an uncapped p build) runs ALONE above the 6000 MB floor, as before. e2e and the builds take it on their own; a render or any other heavy command runs as `pnpm heavy -- <cmd>`. `queue-lock: waiting for the heavy slot — held by …`, `heavy: waiting for memory …` or `heavy: waiting for the -build slot …` is the gate working, not a hang. Bypasses: `HEAVY=0`, +build slot …` is the gate working, not a hang. **An admitted `--heavy` command runs in a +capped scope of its own by default** (`systemd-run --user --scope`, MemoryMax 8G, +MemorySwapMax 2G) unless it carries its own cap or its caller already sits under one (the live +units, a capped scope); `HEAVY_CAP=0` turns that off. Bypasses: `HEAVY=0`, `HEAVY_MIN_FREE_MB=<MB>`, `HEAVY_TIMEOUT=<seconds>`. See [WORKTREES.md](WORKTREES.md) for the port scheme, the queue, the heavy slot, and the diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -121,6 +121,9 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `PARAKEET_DEVICE` | parakeet-cli's | Compute device (`cpu`, `CUDA0`, `Vulkan1`, …), exported to parakeet-cli. | scripts/parakeet-stitch.mjs | | `HEAVY` | on | `0` skips the heavy slot AND the memory floor: the machine-wide one-at-a-time gate that `pnpm heavy -- <cmd>`, every e2e entry point and the publish stages' `next build` go through. | scripts/queue-lock.mjs | | `HEAVY_MIN_FREE_MB` | `6000` | The memory floor: a heavy job, once it holds the slot, waits until /proc/meminfo's MemAvailable is at least this many MB. `0` turns the floor off; a machine whose MemTotal is under it runs without waiting. | scripts/queue-lock.mjs | +| `HEAVY_CAP` | on | An admitted `pnpm heavy` / `queue-lock --heavy` command runs in a memory-capped systemd user scope of its own (`systemd-run --user --scope`, MemoryMax + MemorySwapMax, never MemoryHigh), so a runaway dies in its scope instead of taking the session down. Not wrapped when the command carries its own `MemoryMax=`, when the caller already sits under a finite memory.max (the live units, a capped scope, a container), or with no `systemd-run`. `0` turns it off. | scripts/queue-lock.mjs | +| `HEAVY_CAP_MB` | `8192` | The heavy cap's MemoryMax in MB; a larger `--estimate` raises it to the estimate. The cap never changes admission: an undeclared job still runs alone. | scripts/queue-lock.mjs | +| `HEAVY_CAP_SWAP_MB` | `2048` | The heavy cap's MemorySwapMax in MB. | scripts/queue-lock.mjs | | `HEAVY_TIMEOUT` | wait forever | Seconds a `pnpm heavy` run waits for the slot, and then for the floor, before giving up (exit 3). An e2e run uses `E2E_QUEUE_TIMEOUT` for both. | scripts/queue-lock.mjs | ## Ports @@ -212,6 +215,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `HEAVY_HELD` | — | Set by the heavy slot for the command it runs (`build` inside a build), so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through — except a build inside a non-build, which still waits for the build slot. | scripts/queue-lock.mjs | | `HEAVY_LOCK_FILE` | one per machine | The heavy slot's lock file (its line, build slot and job tickets sit beside it: `.admit`, `.build`, `.jobs/`); the gate's own tests point it elsewhere. | scripts/queue-lock.mjs | | `HEAVY_MEMINFO_FILE` | `/proc/meminfo` | Where the memory floor reads MemAvailable; the gate's tests hand it a fake. | scripts/queue-lock.mjs | +| `HEAVY_PROC_CGROUP` | `/proc/self/cgroup` | Where the heavy cap reads this process's cgroup, to tell whether it is already capped; the gate's tests hand it a fake. | scripts/queue-lock.mjs | | `HEAVY_POLL_MS` | `5000` | How often a run waiting for the memory floor re-reads it. | scripts/queue-lock.mjs | | `PLAYWRIGHT_BASE_URL` | `http://localhost:<PORT>` | The editor test server's URL; the worktree injector sets it. | editor/playwright.config.ts, editor/e2e/baseUrl.ts | | `E2E_AUDIO_CHECK_INTERVAL_MS` | the real cadence | Shrinks the mid-download audio check so the e2e suite sees it fire. | common/ytdlp/audioCheckedDownload.ts | diff --git a/WORKTREES.md b/WORKTREES.md @@ -216,6 +216,24 @@ node scripts/queue-lock.mjs --heavy --estimate 2000 -- <cmd…> # declare an e pnpm heavy -- node umtool/report-to-video/build-video.mjs <manifest> … # a render (alone) ``` +**An admitted `pnpm heavy` / `queue-lock --heavy` command is capped by default.** It runs in +a systemd user scope of its own — `systemd-run --user --scope -q -p MemoryMax=8192M -p +MemorySwapMax=2048M -- <cmd…>`, started as a child of the gate (a scope is named for its pid, +so the gate never execs into one), and never MemoryHigh (a throttled job crawls and holds the +slot). A runaway then dies in its scope instead of taking the desktop session with it. The +gate says `heavy: capped at 8192 MB (swap 2048 MB) in a scope of its own`. It does not wrap: + +- a command that carries its own cap (`systemd-run … -p MemoryMax=…`, as the e2e build does); +- a caller already under a finite `memory.max` — the live editor and umtool units (a publish + stage's build stays inside the editor's 8 GB, with its jobs), a capped scope of the + caller's own, a container's limit, or a heavy run inside a heavy run; +- with no `systemd-run` (a container — quietly), or no user manager to talk to (it says so + and runs uncapped). + +The cap sizes nothing in admission: an undeclared job still runs alone. A larger +`--estimate` raises the cap to the estimate. The e2e suites' own admissions (`pnpm e2e`) +are not wrapped — the cap is `--heavy`'s. + Who takes it, and in what order: - **Every e2e entry point**: its suite's queue first, then its build (if any), then its own @@ -255,6 +273,8 @@ alone — it is a safety net, not a correctness lock. | `HEAVY=0` | Skip the heavy slot AND the memory floor | | `HEAVY_MIN_FREE_MB=<MB>` | Move the floor (`0` turns it off; the build rule still holds) | | `HEAVY_TIMEOUT=<seconds>` | Give up waiting (line, slot, memory) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` | +| `HEAVY_CAP=0` | Run a `--heavy` command without the default memory cap | +| `HEAVY_CAP_MB=<MB>` / `HEAVY_CAP_SWAP_MB=<MB>` | Size the cap (8192 / 2048) | ### A render and the transcription lane diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -157,6 +157,9 @@ const DECLARED: EnvVarDecl[] = [ { name: "PARAKEET_DEVICE", audience: "runtime", default: "parakeet-cli's", readBy: "scripts/parakeet-stitch.mjs", doc: "Compute device (`cpu`, `CUDA0`, `Vulkan1`, …), exported to parakeet-cli." }, { name: "HEAVY", audience: "runtime", default: "on", readBy: "scripts/queue-lock.mjs", doc: "`0` skips the heavy slot AND the memory floor: the machine-wide one-at-a-time gate that `pnpm heavy -- <cmd>`, every e2e entry point and the publish stages' `next build` go through." }, { name: "HEAVY_MIN_FREE_MB", audience: "runtime", default: "`6000`", readBy: "scripts/queue-lock.mjs", doc: "The memory floor: a heavy job, once it holds the slot, waits until /proc/meminfo's MemAvailable is at least this many MB. `0` turns the floor off; a machine whose MemTotal is under it runs without waiting." }, + { name: "HEAVY_CAP", audience: "runtime", default: "on", readBy: "scripts/queue-lock.mjs", doc: "An admitted `pnpm heavy` / `queue-lock --heavy` command runs in a memory-capped systemd user scope of its own (`systemd-run --user --scope`, MemoryMax + MemorySwapMax, never MemoryHigh), so a runaway dies in its scope instead of taking the session down. Not wrapped when the command carries its own `MemoryMax=`, when the caller already sits under a finite memory.max (the live units, a capped scope, a container), or with no `systemd-run`. `0` turns it off." }, + { name: "HEAVY_CAP_MB", audience: "runtime", default: "`8192`", readBy: "scripts/queue-lock.mjs", doc: "The heavy cap's MemoryMax in MB; a larger `--estimate` raises it to the estimate. The cap never changes admission: an undeclared job still runs alone." }, + { name: "HEAVY_CAP_SWAP_MB", audience: "runtime", default: "`2048`", readBy: "scripts/queue-lock.mjs", doc: "The heavy cap's MemorySwapMax in MB." }, { name: "HEAVY_TIMEOUT", audience: "runtime", default: "wait forever", readBy: "scripts/queue-lock.mjs", doc: "Seconds a `pnpm heavy` run waits for the slot, and then for the floor, before giving up (exit 3). An e2e run uses `E2E_QUEUE_TIMEOUT` for both." }, // ── internal: the pipeline sets these for a process it spawns ────────── @@ -209,6 +212,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "HEAVY_HELD", audience: "test", default: "—", readBy: "scripts/queue-lock.mjs", doc: "Set by the heavy slot for the command it runs (`build` inside a build), so a heavy command inside it (a `pnpm heavy -- pnpm e2e`, a build stage under an e2e suite's editor) passes through — except a build inside a non-build, which still waits for the build slot." }, { name: "HEAVY_LOCK_FILE", audience: "test", default: "one per machine", readBy: "scripts/queue-lock.mjs", doc: "The heavy slot's lock file (its line, build slot and job tickets sit beside it: `.admit`, `.build`, `.jobs/`); the gate's own tests point it elsewhere." }, { name: "HEAVY_MEMINFO_FILE", audience: "test", default: "`/proc/meminfo`", readBy: "scripts/queue-lock.mjs", doc: "Where the memory floor reads MemAvailable; the gate's tests hand it a fake." }, + { name: "HEAVY_PROC_CGROUP", audience: "test", default: "`/proc/self/cgroup`", readBy: "scripts/queue-lock.mjs", doc: "Where the heavy cap reads this process's cgroup, to tell whether it is already capped; the gate's tests hand it a fake." }, { name: "HEAVY_POLL_MS", audience: "test", default: "`5000`", readBy: "scripts/queue-lock.mjs", doc: "How often a run waiting for the memory floor re-reads it." }, { name: "PLAYWRIGHT_BASE_URL", audience: "test", default: "`http://localhost:<PORT>`", readBy: "editor/playwright.config.ts, editor/e2e/baseUrl.ts", doc: "The editor test server's URL; the worktree injector sets it." }, { name: "E2E_AUDIO_CHECK_INTERVAL_MS", audience: "test", default: "the real cadence", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Shrinks the mid-download audio check so the e2e suite sees it fire." }, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **`pnpm heavy` caps what it runs.** A command admitted to the heavy slot through `pnpm heavy -- <cmd>` (or `scripts/queue-lock.mjs --heavy`) now runs in a memory-capped systemd user scope of its own — 8 GB, 2 GB of swap — so a runaway render or build is stopped in its scope instead of taking the desktop session down. A command that sets its own `MemoryMax=`, or one started from inside a capped unit or scope (the live editor and umtool, a publish stage's build), is run as before. `HEAVY_CAP=0` turns it off; `HEAVY_CAP_MB` and `HEAVY_CAP_SWAP_MB` size it. - **A media move says how far its copy got again with the newer rsync.** rsync 3.5.1 as packaged since mid-October writes its progress with a unit on the byte count and an unscaled rate, which the move did not read: the job showed no progress bar and no "Copying… · N % ·" lines, and the log filled with rsync's raw redraws. Both forms are read now, and the rate reads as before (for example 1.16GB/s). Needs a restart of the editor. - **A full download from Odysee's stored media URL survives a dropped connection.** When the connection to the file's server drops mid-file (`fetch failed`, a reset, a timeout, a body cut short), the same download now checks what came down, pauses 45 seconds, opens the video's page again and goes on from the last clean byte — it no longer ends the job. Each one is in the job log as "Connection dropped at <bytes> — reopening the page and resuming (k of 6)". After six drops in a row with no progress the download stops and keeps what it has for the next run, as before. A refusal that follows bytes the server served is handled the same way; a refusal straight after the page was opened still stops at once. A continuation is not a new file: it does not wait the 20-minute rest between files, and the whole run is still one attempt on the video's record (one of the two full-audio attempts before a salvage). The attempt records how many continuations it took. Needs a restart of the editor. - **Partial transcripts wait for the full audio first.** A video whose download completed with malformed audio (a corrupt full source) used to get a salvage transcript, with gaps, as soon as anyone pressed Transcribe. When the video's record stores an Odysee media URL, Transcribe and the corrupt full sources' Retry now download from that URL first, up to two times and 20 minutes apart. The salvage transcript is made only if neither download comes back clean. A clean download is transcribed in full. **Salvage** (`transcribe-one {"salvage": true}`) still makes the partial transcript at once. The channel's line shows **awaiting full audio** for the videos still waiting, and the salvaged transcripts read **salvaged — full audio attempts: n**. The video page's salvaged notice gives the same count, the video list marks a salvaged transcript amber, and the MCP's `get_transcripts` marks it partial as `get_transcript` already did. diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs @@ -41,6 +41,18 @@ // and a cap is an estimate — a build beside suites, never beside a build. // - a render: `pnpm heavy -- node umtool/report-to-video/build-video.mjs …`: // alone. +// THE CAP (`--heavy` only). An admitted `--heavy` command runs in a memory-capped +// systemd user scope of its own (`systemd-run --user --scope -p MemoryMax=8G +// -p MemorySwapMax=2G`, never MemoryHigh — a throttled job holds the slot), so +// a runaway is killed in its scope instead of taking the desktop session with +// it. It is the CHILD, never an exec of this process (a scope is named for its +// pid). No wrap when the command is already capped (a `systemd-run … MemoryMax=` +// of its own), when this process already sits under a finite memory.max (the +// live editor/umtool units, a caller's capped scope, a container's limit), or +// with no `systemd-run`. The cap sizes nothing in admission: an undeclared job +// still runs alone. HEAVY_CAP=0 turns it off; HEAVY_CAP_MB / HEAVY_CAP_SWAP_MB +// size it (a larger --estimate raises it to the estimate). +// // Bypasses: HEAVY=0 (no slot, no floor), HEAVY_MIN_FREE_MB=0 (no floor), // HEAVY_TIMEOUT=<seconds>. E2E_QUEUE=0 skips the slot as it skips the queue; // the floor still applies. A machine whose MemTotal is under the floor is not @@ -845,6 +857,102 @@ export function memoryCapMb(cmd = []) { return null; } +// ---------------------------------------------------------------- the cap + +export const DEFAULT_HEAVY_CAP_MB = 8192; +export const DEFAULT_HEAVY_CAP_SWAP_MB = 2048; + +/** + * The cgroup (v2) path that already caps this process, or null: the leaf named + * by /proc/self/cgroup's `0::` line or any ancestor with a finite memory.max. + * `readMax(path)` returns that cgroup's memory.max text, or null (no file — the + * host's root cgroup has none). + */ +export function cappingCgroup(cgroupText, readMax) { + const line = String(cgroupText ?? "") + .split("\n") + .find((l) => l.startsWith("0::")); + if (!line) return null; + let p = line.slice(3).trim() || "/"; + for (;;) { + const max = readMax(p); + if (max != null && max.trim() !== "" && max.trim() !== "max") return p; + if (p === "/") return null; + p = path.posix.dirname(p); + } +} + +function realCappingCgroup() { + let text; + try { + text = fs.readFileSync(process.env.HEAVY_PROC_CGROUP || "/proc/self/cgroup", "utf8"); + } catch { + return null; + } + return cappingCgroup(text, (p) => { + try { + return fs.readFileSync(path.posix.join("/sys/fs/cgroup", p, "memory.max"), "utf8"); + } catch { + return null; + } + }); +} + +function sizeMb(raw, fallback) { + if (raw == null || raw === "") return fallback; + const n = Number(raw); + return n > 0 ? Math.round(n) : fallback; +} + +/** + * Whether and how to cap a `--heavy` command, pure. `cappedBy` is the cgroup + * that already caps us (or null); `scopeOk` whether `systemd-run --user + * --scope` works here. Returns `{wrap: false, why}` or `{wrap: true, memMb, + * swapMb}`. + */ +export function heavyCapPlan({ env = {}, cmd = [], job = {}, cappedBy = null, scopeOk = true }) { + if (env.HEAVY_CAP === "0") return { wrap: false, why: "off" }; + if (memoryCapMb(cmd) != null) return { wrap: false, why: "command" }; + if (cappedBy) return { wrap: false, why: "cgroup", cgroup: cappedBy }; + if (!scopeOk) return { wrap: false, why: "no-scope" }; + const memMb = Math.max(sizeMb(env.HEAVY_CAP_MB, DEFAULT_HEAVY_CAP_MB), Number(job.estimateMb) || 0); + return { wrap: true, memMb, swapMb: sizeMb(env.HEAVY_CAP_SWAP_MB, DEFAULT_HEAVY_CAP_SWAP_MB) }; +} + +export function cappedCommand(cmd, { memMb, swapMb }) { + return [ + "systemd-run", "--user", "--scope", "-q", + "-p", `MemoryMax=${memMb}M`, "-p", `MemorySwapMax=${swapMb}M`, + "--", ...cmd, + ]; +} + +// Does `systemd-run --user --scope` work here (a binary, a user manager on a +// bus)? "missing" (no binary — a container: quiet), true, or false (say so). +function probeScope() { + try { + execFileSync("systemd-run", ["--user", "--scope", "-q", "true"], { stdio: "ignore", timeout: 10_000 }); + return true; + } catch (err) { + return err?.code === "ENOENT" ? "missing" : false; + } +} + +// The command an admitted `--heavy` run starts: capped unless the plan says not. +function capHeavy(cmd, job) { + const env = process.env; + const cappedBy = env.HEAVY_CAP === "0" || memoryCapMb(cmd) != null ? null : realCappingCgroup(); + const needsProbe = env.HEAVY_CAP !== "0" && memoryCapMb(cmd) == null && !cappedBy; + const probe = needsProbe ? probeScope() : true; + const plan = heavyCapPlan({ env, cmd, job, cappedBy, scopeOk: probe === true }); + if (plan.why === "no-scope" && probe === false) { + process.stderr.write("heavy: no systemd user scope here — running uncapped (HEAVY_CAP=0 silences this)\n"); + } + if (!plan.wrap) return cmd; + process.stderr.write(`heavy: capped at ${plan.memMb} MB (swap ${plan.swapMb} MB) in a scope of its own\n`); + return cappedCommand(cmd, plan); +} + // `… next build …`, by the words (pnpm exec next build, node_modules/.bin/next build). export function isNextBuild(cmd = []) { return cmd.some( @@ -1323,7 +1431,7 @@ async function main() { } const code = opts.heavy ? await withHeavy({ timeoutMs: opts.timeoutMs, cmd, estimateMb: opts.estimateMb, build: opts.build }, () => - runCommand(cmd, null, { forwardTerm: true }), + runCommand(capHeavy(cmd, resolveJob(opts, cmd)), null, { forwardTerm: true }), ) : await withQueue({ ...opts, cmd }, () => runCommand(cmd, opts.name)); process.exit(code); diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs @@ -15,6 +15,9 @@ import test from "node:test"; import { fileURLToPath } from "node:url"; import { admissionDecision, + cappedCommand, + cappingCgroup, + heavyCapPlan, isNextBuild, memoryCapMb, parseMeminfo, @@ -37,7 +40,7 @@ function tmpDir() { // pass-through marker inherited from whatever runs this suite (a // `pnpm heavy -- pnpm test:scripts`) is dropped unless the test sets it. function lockEnv(env) { - const out = { E2E_PORT_CHECK: "0", HEAVY: "0", ...process.env, ...env }; + const out = { E2E_PORT_CHECK: "0", HEAVY: "0", HEAVY_CAP: "0", ...process.env, ...env }; for (const k of ["HEAVY_HELD", "QUEUE_LOCK_HELD", "E2E_QUEUE"]) { if (!(k in env)) delete out[k]; } @@ -874,3 +877,70 @@ test("--with: a suite that shares a tree holds the other suite's queue too", asy assert.ok(order.indexOf("Su") < order.indexOf("Ee"), `umtool waited for the editor: ${order}`); assert.equal(fs.existsSync(path.join(dir, "q.lock.e2e-export.holder.json")), false); }); + +test("cappingCgroup: the leaf or an ancestor with a finite memory.max caps; `max` and no file do not", () => { + const maxes = { + "/user.slice/user-1000.slice/session-5.scope": "max\n", + "/user.slice/user-1000.slice": "max\n", + "/user.slice/user-1000.slice/user@1000.service/app.slice/archilyzer-editor.service": "8589934592\n", + "/user.slice/user-1000.slice/user@1000.service/app.slice/run-p9-i9.scope": "6442450944\n", + }; + const read = (p) => maxes[p] ?? null; + assert.equal(cappingCgroup("0::/user.slice/user-1000.slice/session-5.scope\n", read), null); + const svc = "/user.slice/user-1000.slice/user@1000.service/app.slice/archilyzer-editor.service"; + assert.equal(cappingCgroup(`0::${svc}\n`, read), svc, "a job inside the editor's unit is capped by it"); + assert.equal(cappingCgroup(`0::${svc}/child\n`, read), svc, "an ancestor's cap counts"); + assert.equal(cappingCgroup("0::/\n", (p) => (p === "/" ? "2147483648" : null)), "/", "a container's limit"); + assert.equal(cappingCgroup("12:memory:/foo\n", read), null, "cgroup v1 only: unknown, not capped"); +}); + +test("heavyCapPlan: capped by default; off, already-capped, under a cap or no scope do not wrap", () => { + assert.deepEqual(heavyCapPlan({ cmd: ["x"] }), { wrap: true, memMb: 8192, swapMb: 2048 }); + assert.deepEqual(heavyCapPlan({ env: { HEAVY_CAP_MB: "4096", HEAVY_CAP_SWAP_MB: "0" }, cmd: ["x"] }), { + wrap: true, + memMb: 4096, + swapMb: 2048, + }); + assert.equal(heavyCapPlan({ cmd: ["x"], job: { estimateMb: 12000 } }).memMb, 12000, "an estimate over the cap raises it"); + assert.equal(heavyCapPlan({ env: { HEAVY_CAP: "0" }, cmd: ["x"] }).why, "off"); + assert.equal(heavyCapPlan({ cmd: ["systemd-run", "-p", "MemoryMax=5G", "x"] }).why, "command"); + assert.equal(heavyCapPlan({ cmd: ["x"], cappedBy: "/a.scope" }).why, "cgroup"); + assert.equal(heavyCapPlan({ cmd: ["x"], scopeOk: false }).why, "no-scope"); + assert.deepEqual(cappedCommand(["node", "r.mjs"], { memMb: 8192, swapMb: 2048 }), [ + "systemd-run", "--user", "--scope", "-q", "-p", "MemoryMax=8192M", "-p", "MemorySwapMax=2048M", "--", "node", "r.mjs", + ]); +}); + +test("an admitted --heavy command runs under systemd-run's cap by default; HEAVY_CAP=0 runs it bare", async () => { + const dir = tmpDir(); + const bin = path.join(dir, "bin"); + fs.mkdirSync(bin); + const log = path.join(dir, "systemd-run.log"); + // A fake systemd-run: logs its arguments, then runs what follows `--`. + fs.writeFileSync( + path.join(bin, "systemd-run"), + `#!/bin/sh\nprintf '%s\\n' "$*" >> '${log}'\nwhile [ "$1" != "--" ] && [ $# -gt 0 ]; do shift; done\n[ "$1" = "--" ] && shift\n[ $# -gt 0 ] && exec "$@"\nexit 0\n`, + { mode: 0o755 }, + ); + const cgroup = path.join(dir, "cgroup"); + fs.writeFileSync(cgroup, "0::/queue-lock-test-not-a-cgroup.scope\n"); + const env = { + HEAVY: "1", + HEAVY_CAP: undefined, + HEAVY_LOCK_FILE: path.join(dir, "heavy.lock"), + HEAVY_MIN_FREE_MB: "0", + HEAVY_PROC_CGROUP: cgroup, + PATH: `${bin}:${process.env.PATH}`, + }; + const capped = await startLock(["--heavy", "--", "sh", "-c", "echo ran"], env).done; + assert.equal(capped.code, 0, capped.stderr); + assert.match(capped.stdout, /ran/); + assert.match(capped.stderr, /capped at 8192 MB/); + const calls = fs.readFileSync(log, "utf8"); + assert.match(calls, /--user --scope -q -p MemoryMax=8192M -p MemorySwapMax=2048M -- sh -c echo ran/); + fs.rmSync(log); + const bare = await startLock(["--heavy", "--", "sh", "-c", "echo ran"], { ...env, HEAVY_CAP: "0" }).done; + assert.equal(bare.code, 0, bare.stderr); + assert.match(bare.stdout, /ran/); + assert.equal(fs.existsSync(log), false, "no systemd-run at all with the cap off"); +});