Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ubicloud: expiring VM names and an operator reaper (P6)

garrytand40791ef1ce9
diff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.ts
index 990628ff8b..a42a8f99c8 100755
--- a/scripts/ci-ubicloud.ts
+++ b/scripts/ci-ubicloud.ts
@@ -19,6 +19,10 @@
* --diff doc-only diffs run only the doc checks and gitleaks (ci:local --diff)
* --record-weights write measured durations to scripts/ubicloud/weights.json
* --keep leave the VMs running (destroy with ubi-runner.sh down NAME)
+ * --ttl-hours N VM expiry written into each name (default 2; 0 = no
+ * expiry). The operator reaper destroys VMs past their
+ * expiry, so a VM a sleeping machine never tore down
+ * dies within hours (scripts/ubicloud/reap-expired.ts)
*
* Needs UBICLOUD_API_KEY (or UBICLOUD_API_TOKEN) plus bash, curl, python3,
* ssh, ssh-keygen and tar locally. The checkout (tracked + untracked-unignored
@@ -39,8 +43,9 @@
* and slow lanes it does the same for test.yml's unit shards. Durations of every run are
* merged into .context/ci-ubicloud/weights.json, which weights the next run.
*
- * VMs are named ubirun-<owner>-<epoch>-ciNN<hex> (owner: UBI_OWNER or the
- * runner's per-machine id). Each name is appended to <run>/vms.txt before its
+ * VMs are named ubirun-<owner>-<epoch>-x<expiry epoch>-ciNN<hex> (owner:
+ * UBI_OWNER or the runner's per-machine id; ubirun-<owner>-<epoch>-ciNN<hex>
+ * with --ttl-hours 0). Each name is appended to <run>/vms.txt before its
* create request is sent. On exit, including SIGINT, SIGTERM, SIGHUP (a
* dropped terminal, a cancelled background operation) and SIGQUIT, in-flight
* `up` calls are allowed to finish (they destroy their own VM), then every
@@ -66,6 +71,7 @@ import {
type WeightTable,
} from "./ubicloud/schedule.ts";
import { runScript, type RunScriptOpts } from "./ubicloud/run-script.ts";
+import { expiringVmName } from "./ubicloud/reap-expired.ts";
import { buildTypecheckState, portableBuildInfo, typecheckBuildInfo } from "./ubicloud/typecheck-state.ts";
import { ARM_SHARDS, ARM_STEP_TIMEOUT_MS, ARM_WEIGHTS, armShards, readArmsList } from "./postgres-unit-arms.ts";
import { UNIT_JOB_TIMEOUT_MS, UNIT_SETUP_ALLOWANCE_MS, UNIT_SHARDS, unitShards } from "./sharding.ts";
@@ -108,6 +114,7 @@ interface Opts {
diff: boolean;
recordWeights: boolean;
keep: boolean;
+ ttlHours: number;
}
function parseArgs(argv: string[]): Opts {
@@ -121,6 +128,7 @@ function parseArgs(argv: string[]): Opts {
diff: false,
recordWeights: false,
keep: false,
+ ttlHours: 2,
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]!;
@@ -138,9 +146,11 @@ function parseArgs(argv: string[]): Opts {
else if (arg === "--diff") opts.diff = true;
else if (arg === "--record-weights") opts.recordWeights = true;
else if (arg === "--keep") opts.keep = true;
+ else if (arg === "--ttl-hours") opts.ttlHours = Number(value());
else usage(`unknown argument ${arg}`);
}
for (const lane of opts.lanes) if (!(ALL_LANES as readonly string[]).includes(lane)) usage(`unknown lane ${lane}`);
+ if (!Number.isInteger(opts.ttlHours) || opts.ttlHours < 0 || opts.ttlHours > 8760) usage("--ttl-hours must be a whole number of hours from 0 (no expiry) to 8760");
if (!Number.isInteger(opts.vms) || opts.vms < 0 || (opts.vms === 0 && argv.includes("--vms"))) usage("--vms must be a positive integer");
// One slot per two vCPUs: the whole corpus still fits inside the longest
// single file's runtime at the default fleet size, and the headroom keeps
@@ -152,7 +162,7 @@ function parseArgs(argv: string[]): Opts {
function usage(message: string): never {
console.error(`ci-ubicloud: ${message}`);
- console.error("usage: bun run scripts/ci-ubicloud.ts [--vms N] [--size SIZE] [--slots N] [--location LOC] [--image IMAGE] [--lanes a,b] [--diff] [--record-weights] [--keep]");
+ console.error("usage: bun run scripts/ci-ubicloud.ts [--vms N] [--size SIZE] [--slots N] [--location LOC] [--image IMAGE] [--lanes a,b] [--diff] [--record-weights] [--keep] [--ttl-hours N]");
process.exit(2);
}
@@ -264,7 +274,7 @@ async function main() {
opts.vms = decision.vms;
log(`fleet: ${decision.reason} (pass --vms N to override)`);
}
- log(`provisioning ${opts.vms} × ${opts.size} in ${opts.location} (${opts.image === "stock" ? "stock Ubuntu 24.04" : `image ${opts.image}`}), ${opts.slots} slots each; logs in ${runDir}`);
+ log(`provisioning ${opts.vms} × ${opts.size} in ${opts.location} (${opts.image === "stock" ? "stock Ubuntu 24.04" : `image ${opts.image}`}), ${opts.slots} slots each, ${opts.ttlHours ? `names expiring ${opts.ttlHours}h after creation` : "no expiry"}; logs in ${runDir}`);
// ── Checkout tarball, packed once while the VMs boot ─────────────────────
const tarball = join(tmpdir(), `gbrain-ci-ubicloud-${process.pid}.tgz`);
@@ -287,8 +297,9 @@ async function main() {
// ── Teardown on every exit path ──────────────────────────────────────────
const owner = sh("bash", [RUNNER, "owner"]).trim();
const ledger = join(runDir, "vms.txt");
+ const createdAt = Math.floor(Date.now() / 1000);
const vms: Vm[] = Array.from({ length: opts.vms }, (_, i) => ({
- name: `ubirun-${owner}-${Math.floor(Date.now() / 1000)}-ci${String(i + 1).padStart(2, "0")}${Math.random().toString(16).slice(2, 6)}`,
+ name: expiringVmName({ owner, createdAt, ttlHours: opts.ttlHours, suffix: `ci${String(i + 1).padStart(2, "0")}${Math.random().toString(16).slice(2, 6).padEnd(4, "0")}` }),
state: "provisioning",
requested: false,
infraErrors: 0,
@@ -309,7 +320,7 @@ async function main() {
rmSync(tarball, { force: true });
const live = vms.filter((vm) => vm.requested && vm.state !== "destroyed");
if (opts.keep) {
- log(`--keep: leaving ${live.map((vm) => vm.name).join(" ")} running; destroy with: scripts/ubicloud/ubi-runner.sh down NAME`);
+ log(`--keep: leaving ${live.map((vm) => vm.name).join(" ")} running; destroy with: scripts/ubicloud/ubi-runner.sh down NAME${opts.ttlHours ? ` (the operator reaper destroys them ${opts.ttlHours}h after creation; --ttl-hours 0 for no expiry)` : ""}`);
return;
}
log(`destroying ${live.length} VM(s): ${live.map((vm) => vm.name).join(" ")}`);
diff --git a/scripts/ubicloud/README.md b/scripts/ubicloud/README.md
index f5e7bb92be..f37898b67e 100644
--- a/scripts/ubicloud/README.md
+++ b/scripts/ubicloud/README.md
@@ -6,14 +6,46 @@ untracked files that are not ignored, and `.git`) and streams it to every VM, so
uncommitted edits are tested. `scripts/ubicloud/ubi-runner.sh` creates and
destroys the VMs.
+## How many full gates
+
+Run one full gate (`bun run ci:ubicloud`) per PR, at handoff, on the tree you
+hand off (the tree rule in the project's shipping rules: a head whose tree
+matches an already-gated tree apart from the release stamp files needs no new
+gate). During development use `bun run ci:ubicloud:diff`, `--lanes` and
+targeted suites (`bun test <files>`). The gstack pregate remote stage
+(`scripts/pregate-remote-gate.sh`, `.gstack/pregate.json`'s `remote_gate`)
+runs the `:diff` form for the same reason. `:diff` narrows only doc-only
+trees today (doc checks plus gitleaks); any other tree still runs every lane,
+so pick `--lanes` or targeted suites when the change is narrow. In a
+multi-lane wave, lanes run `ci:ubicloud:diff` or targeted suites, and only
+the integrator runs the full gate.
+
## Ownership and teardown
-Every VM is named `ubirun-<owner>-<epoch>-<suffix>`. The owner is `UBI_OWNER`
-(lowercased, letters and digits only, at most 12 characters, starting with a
-letter) or a random per-machine id kept in the runner's state directory. Set
-`UBI_OWNER` to your thread code (`UBI_OWNER=gbra41 bun run ci:ubicloud`) so
-everyone can see whose VMs hold the quota. Ubicloud names allow 63 characters
-of `[a-z0-9-]`, so a full name stays under 40.
+Every VM is named `ubirun-<owner>-<epoch>-<suffix>`, or
+`ubirun-<owner>-<epoch>-x<expiry epoch>-<suffix>` when it carries an expiry.
+The owner is `UBI_OWNER` (lowercased, letters and digits only, at most 12
+characters, starting with a letter) or a random per-machine id kept in the
+runner's state directory. Set `UBI_OWNER` to your thread code
+(`UBI_OWNER=gbra41 bun run ci:ubicloud`) so everyone can see whose VMs hold
+the quota. Ubicloud names allow 63 characters of `[a-z0-9-]`, so a full name
+stays under 52.
+
+Ubicloud has no VM tags, so the expiry lives in the name. `ci:ubicloud` names
+every gate VM to expire two hours after creation (`--ttl-hours N` changes it,
+`--ttl-hours 0` means no expiry). `ubi-runner.sh up` and `run` take the same
+`--ttl-hours H`; without it their VMs never expire, which suits long dev,
+benchmark and eval VMs. `scripts/ubicloud/reap-expired.ts` is the operator
+side of the leak guard: run from the operator's Capy automation, where the
+Ubicloud token already lives (never from GitHub Actions), it lists the project's
+VMs, selects only names in the expiring format whose expiry plus a 15-minute
+grace has passed, and prints each `ubirun-*` VM's owner, age, expiry and action
+plus an owner-notice block (expired VMs grouped by owner and the thread code
+the owner tag names). It is a dry run unless given `--apply`, which destroys
+each expired VM through `ubi-runner.sh down`, and it refuses the whole run when
+more than `--max` (40) VMs are expired. It never selects an owner-tagged name
+without an expiry, a legacy untagged `ubirun-<epoch>-*` name or a VM the
+runner did not name, whoever owns it.
Each name is recorded before its create request is sent: the runner writes
the VM's state directory first, and `ci-ubicloud.ts` appends the name to
@@ -37,7 +69,8 @@ A machine that goes to sleep kills the run outright, with no signal, so
teardown can't run: on Capy, run `ci:ubicloud` as a watched background
operation so the machine stays awake. After any interrupted run, check
`list --mine` and reap leftovers with `down NAME` (or `gc HOURS`, which only
-destroys your own VMs older than HOURS).
+destroys your own VMs older than HOURS). A gate VM nobody reaps still dies
+once its expiry passes and the operator reaper next runs with `--apply`.
`ubi-runner.sh list --mine` lists your VMs. `ubi-runner.sh usage` prints VMs
and vCPUs per owner across the project, which shows who holds the shared quota.
@@ -140,9 +173,7 @@ VM). The decision is logged (`fleet: project VMs hold 192 vCPUs, ceiling 448:
10 VM(s) × 16 vCPUs (burst maximum 10)`). The 64 vCPUs above the ceiling are
headroom for the managed GitHub runners `usage` can't see. When usage can't
be read, or the project is busy, the run takes the default. Slots default to
-one per two vCPUs (`--slots`); `--size` and `--location` pick the VM shape. In
-a multi-lane wave, each lane runs `ci:ubicloud:diff` or its targeted suites,
-and only the integrator runs the full gate. A VM that the quota refuses fails
+one per two vCPUs (`--slots`); `--size` and `--location` pick the VM shape. A VM that the quota refuses fails
to provision and the run continues on the VMs that did start, so a busy
project shrinks the fleet instead of failing. The runner prints the refusal
(needed, used and maximum vCPUs) with the project's VMs and vCPUs per owner;
diff --git a/scripts/ubicloud/reap-expired.ts b/scripts/ubicloud/reap-expired.ts
new file mode 100644
index 0000000000..d7efbe5985
--- /dev/null
+++ b/scripts/ubicloud/reap-expired.ts
@@ -0,0 +1,233 @@
+#!/usr/bin/env bun
+/**
+ * scripts/ubicloud/reap-expired.ts — destroy expired ci:ubicloud VMs, whoever
+ * owns them. Operator side: it runs where the Ubicloud token already lives
+ * (the operator's Capy automation), never in GitHub Actions.
+ *
+ * bun scripts/ubicloud/reap-expired.ts # dry run: plan + owner notices
+ * bun scripts/ubicloud/reap-expired.ts --apply # destroy the expired VMs
+ *
+ * Options:
+ * --apply destroy (default: dry run, nothing is destroyed)
+ * --grace-minutes N keep a VM this long past its expiry (default 15)
+ * --max N refuse the whole run (exit 3) when more than N VMs
+ * are expired: a burst that large needs a human look (default 40)
+ * --now EPOCH evaluate at this time (default now; for tests and replays)
+ *
+ * Only names in the expiring format are ever selected:
+ *
+ * ubirun-<owner>-<created epoch>-x<expiry epoch>-<suffix>
+ *
+ * which `ci:ubicloud` writes for its gate VMs (`--ttl-hours`, default 2) and
+ * `ubi-runner.sh up|run --ttl-hours H` writes on request. Owner-tagged names
+ * without an expiry (`ubirun-<owner>-<epoch>-<suffix>`: long dev, benchmark
+ * and eval VMs), legacy untagged `ubirun-<epoch>-*` names and VMs the runner
+ * did not name are never selected. Ubicloud has no VM tags, so the expiry
+ * lives in the name and the list's location and name columns are all the
+ * reaper reads.
+ *
+ * It lists the project's VMs through the same Ubicloud CLI endpoint
+ * ubi-runner.sh uses (POST $UBICLOUD_API_URL/cli with UBICLOUD_API_KEY or
+ * UBICLOUD_API_TOKEN), prints one row per ubi-runner VM (owner, action, age,
+ * expiry, location/name) and an owner-notice block grouping expired VMs by
+ * owner with the thread code the owner tag names (gbra135 -> GBRA-135). With
+ * --apply each expired VM goes through `ubi-runner.sh down NAME -l LOC`,
+ * which destroys it and polls until it is confirmed gone.
+ *
+ * Exit codes: 0 done (dry run, or every destroy confirmed), 1 the list or a
+ * destroy failed, 2 usage, 3 more expired VMs than --max (nothing destroyed).
+ * Tests: test/scripts/ubicloud-reap-expired.test.ts.
+ */
+
+import { spawn } from "node:child_process";
+import { join } from "node:path";
+
+const RUNNER = join(import.meta.dir, "ubi-runner.sh");
+const MAX_NAME = 63;
+const OWNER = "[a-z][a-z0-9]{0,11}";
+const EXPIRING = new RegExp(`^ubirun-(${OWNER})-(\\d{10})-x(\\d{10})-([a-z0-9]{1,24})$`);
+const NO_EXPIRY = new RegExp(`^ubirun-(${OWNER})-(\\d{10})-([a-z0-9]{1,24})$`);
+const LEGACY = /^ubirun-(\d{10})-[a-z0-9]{1,24}$/;
+
+export type ParsedName =
+ | { kind: "expiring"; owner: string; createdAt: number; expiresAt: number }
+ | { kind: "no-expiry"; owner: string; createdAt: number }
+ | { kind: "legacy"; createdAt: number }
+ | { kind: "foreign" };
+
+export function parseVmName(name: string): ParsedName {
+ let m = EXPIRING.exec(name);
+ if (m) return { kind: "expiring", owner: m[1]!, createdAt: Number(m[2]), expiresAt: Number(m[3]) };
+ m = NO_EXPIRY.exec(name);
+ if (m) return { kind: "no-expiry", owner: m[1]!, createdAt: Number(m[2]) };
+ m = LEGACY.exec(name);
+ if (m) return { kind: "legacy", createdAt: Number(m[1]) };
+ return { kind: "foreign" };
+}
+
+/** A gate VM name: expiring `ttlHours` after `createdAt`, or no expiry when ttlHours is 0. */
+export function expiringVmName(o: { owner: string; createdAt: number; ttlHours: number; suffix: string }): string {
+ if (!Number.isInteger(o.ttlHours) || o.ttlHours < 0 || o.ttlHours > 8760) throw new Error(`ttl must be a whole number of hours from 0 to 8760, got ${o.ttlHours}`);
+ const name = o.ttlHours
+ ? `ubirun-${o.owner}-${o.createdAt}-x${o.createdAt + o.ttlHours * 3600}-${o.suffix}`
+ : `ubirun-${o.owner}-${o.createdAt}-${o.suffix}`;
+ if (name.length > MAX_NAME || parseVmName(name).kind !== (o.ttlHours ? "expiring" : "no-expiry")) throw new Error(`not a valid ubi-runner VM name: ${name}`);
+ return name;
+}
+
+export interface VmRow { location: string; name: string }
+export interface PlanRow extends VmRow {
+ parsed: ParsedName;
+ action: "destroy" | "keep" | "skip";
+ reason?: string;
+ result?: "destroyed" | "failed";
+}
+
+export function planReap(rows: VmRow[], o: { now: number; graceSeconds: number }): PlanRow[] {
+ return rows.map((row) => {
+ const parsed = parseVmName(row.name);
+ if (parsed.kind === "foreign") return { ...row, parsed, action: "skip", reason: "not named by ubi-runner" };
+ if (parsed.kind === "legacy") return { ...row, parsed, action: "skip", reason: "legacy name" };
+ if (parsed.kind === "no-expiry") return { ...row, parsed, action: "skip", reason: "no expiry" };
+ if (parsed.expiresAt <= parsed.createdAt) return { ...row, parsed, action: "skip", reason: "expiry before creation" };
+ return { ...row, parsed, action: o.now >= parsed.expiresAt + o.graceSeconds ? "destroy" : "keep" };
+ });
+}
+
+const span = (seconds: number) => {
+ const m = Math.max(0, Math.floor(seconds / 60));
+ return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}m`;
+};
+const ownerOf = (p: ParsedName) => ("owner" in p ? p.owner : p.kind === "legacy" ? "(untagged)" : "(other)");
+const threadOf = (owner: string) => {
+ const m = /^([a-z]+)(\d+)$/.exec(owner);
+ return m ? `${m[1]!.toUpperCase()}-${m[2]}` : null;
+};
+
+function actionLabel(row: PlanRow, apply: boolean): string {
+ if (row.action === "skip") return `skip: ${row.reason}`;
+ if (row.action === "keep") return "keep";
+ if (row.result) return row.result === "destroyed" ? "destroyed" : "destroy FAILED";
+ return apply ? "destroy" : "would destroy";
+}
+
+export function renderPlan(plan: PlanRow[], o: { now: number; apply: boolean; graceSeconds: number }): string {
+ const mine = plan.filter((row) => row.parsed.kind !== "foreign");
+ const foreign = plan.length - mine.length;
+ const lines = [
+ `reap-expired: ${o.apply ? "apply" : "dry run (pass --apply to destroy)"}, now ${new Date(o.now * 1000).toISOString()}, grace ${o.graceSeconds / 60}m`,
+ `${"OWNER".padEnd(13)} ${"ACTION".padEnd(26)} ${"AGE".padEnd(8)} ${"EXPIRY".padEnd(22)} VM`,
+ ];
+ for (const row of mine) {
+ const p = row.parsed;
+ const age = "createdAt" in p ? span(o.now - p.createdAt) : "-";
+ const expiry = p.kind === "expiring" ? (p.expiresAt <= o.now ? `expired ${span(o.now - p.expiresAt)} ago` : `expires in ${span(p.expiresAt - o.now)}`) : "-";
+ lines.push(`${ownerOf(p).padEnd(13)} ${actionLabel(row, o.apply).padEnd(26)} ${age.padEnd(8)} ${expiry.padEnd(22)} ${row.location}/${row.name}`);
+ }
+ if (foreign) lines.push(`${foreign} VM(s) not named by ubi-runner: skipped`);
+ const count = (action: PlanRow["action"]) => plan.filter((row) => row.action === action).length;
+ lines.push(`summary: ${count("destroy")} expired (${o.apply ? "destroy" : "would destroy"}), ${count("keep")} not yet expired, ${mine.length - count("destroy") - count("keep")} without a usable expiry (never reaped), ${foreign} not ubi-runner's`);
+ return lines.join("\n");
+}
+
+export function ownerNotices(plan: PlanRow[], o: { now: number; apply: boolean }): string {
+ const byOwner = new Map<string, PlanRow[]>();
+ for (const row of plan) if (row.action === "destroy") byOwner.set(ownerOf(row.parsed), [...(byOwner.get(ownerOf(row.parsed)) ?? []), row]);
+ const lines = ["=== owner notices ==="];
+ if (!byOwner.size) return [...lines, "no expired VMs"].join("\n");
+ for (const [owner, rows] of byOwner) {
+ const thread = threadOf(owner);
+ lines.push(`owner ${owner}${thread ? ` (thread ${thread})` : ""}: ${rows.length} expired VM(s)`);
+ for (const row of rows) {
+ const p = row.parsed as Extract<ParsedName, { kind: "expiring" }>;
+ lines.push(` - ${row.location}/${row.name} expired ${span(o.now - p.expiresAt)} ago (created ${span(o.now - p.createdAt)} ago)${row.result === "failed" ? ": destroy FAILED, still running" : ""}`);
+ }
+ lines.push(o.apply
+ ? ` Destroyed by the operator reaper at ${new Date(o.now * 1000).toISOString()}. Nothing to do unless a run still needed one: start long runs with ubi-runner.sh up/run --ttl-hours H, or without --ttl-hours for a VM that never expires.`
+ : ` Dry run: nothing was destroyed. The operator reaper destroys these once it runs with --apply. Destroy them now with UBI_OWNER=${owner} scripts/ubicloud/ubi-runner.sh down <name> -l <location>. An expiry can't be extended; start long runs with ubi-runner.sh up/run --ttl-hours H, or without --ttl-hours for a VM that never expires.`);
+ }
+ return lines.join("\n");
+}
+
+async function listVms(): Promise<VmRow[]> {
+ const token = process.env.UBICLOUD_API_KEY || process.env.UBICLOUD_API_TOKEN;
+ if (!token) throw new Error("UBICLOUD_API_KEY (or UBICLOUD_API_TOKEN) is not set");
+ const api = process.env.UBICLOUD_API_URL || "https://api.ubicloud.com";
+ const res = await fetch(`${api}/cli`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, accept: "text/plain", "content-type": "application/json", "x-ubi-version": "1.0.0" },
+ body: JSON.stringify({ argv: ["vm", "list", "-N", "-f", "location,name"] }),
+ signal: AbortSignal.timeout(120_000),
+ });
+ const body = await res.text();
+ if (!res.ok) throw new Error(`ubi vm list -> HTTP ${res.status}: ${body.slice(0, 300)}`);
+ return body.split("\n").map((line) => line.trim().split(/\s+/)).filter((cols) => cols.length === 2 && cols[0] && cols[1]).map(([location, name]) => ({ location: location!, name: name! }));
+}
+
+function down(row: PlanRow): Promise<{ ok: boolean; log: string }> {
+ return new Promise((done) => {
+ const child = spawn("bash", [RUNNER, "down", row.name, "-l", row.location], { stdio: ["ignore", "pipe", "pipe"] });
+ let log = "";
+ child.stdout.on("data", (d) => (log += d));
+ child.stderr.on("data", (d) => (log += d));
+ child.on("close", (code) => done({ ok: code === 0, log: log.trim() }));
+ });
+}
+
+function usage(message: string): never {
+ console.error(`reap-expired: ${message}`);
+ console.error("usage: bun scripts/ubicloud/reap-expired.ts [--apply] [--grace-minutes N] [--max N] [--now EPOCH]");
+ process.exit(2);
+}
+
+async function main(argv: string[]) {
+ let apply = false;
+ let graceMinutes = 15;
+ let max = 40;
+ let now = Math.floor(Date.now() / 1000);
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i]!;
+ const num = () => {
+ const v = Number(argv[++i]);
+ if (!Number.isInteger(v) || v < 0) usage(`${arg} needs a whole number`);
+ return v;
+ };
+ if (arg === "--apply") apply = true;
+ else if (arg === "--grace-minutes") graceMinutes = num();
+ else if (arg === "--max") max = num();
+ else if (arg === "--now") now = num();
+ else usage(`unknown argument ${arg}`);
+ }
+ const graceSeconds = graceMinutes * 60;
+ const plan = planReap(await listVms(), { now, graceSeconds });
+ const expired = plan.filter((row) => row.action === "destroy");
+ if (apply && expired.length > max) {
+ console.log(renderPlan(plan, { now, apply: false, graceSeconds }));
+ console.error(`reap-expired: ${expired.length} expired VMs exceed --max ${max}; nothing was destroyed. A burst this large means something else is wrong: check the plan above, then rerun with a higher --max.`);
+ process.exit(3);
+ }
+ let failed = 0;
+ if (apply) {
+ for (let i = 0; i < expired.length; i += 4) {
+ await Promise.all(expired.slice(i, i + 4).map(async (row) => {
+ const r = await down(row);
+ row.result = r.ok ? "destroyed" : "failed";
+ if (!r.ok) {
+ failed++;
+ console.error(`reap-expired: destroy FAILED for ${row.location}/${row.name}:\n${r.log}`);
+ }
+ }));
+ }
+ }
+ console.log(renderPlan(plan, { now, apply, graceSeconds }));
+ console.log("");
+ console.log(ownerNotices(plan, { now, apply }));
+ process.exit(failed ? 1 : 0);
+}
+
+if (import.meta.main) {
+ main(process.argv.slice(2)).catch((error) => {
+ console.error(`reap-expired: ${error instanceof Error ? error.message : String(error)}`);
+ process.exit(1);
+ });
+}
diff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.sh
index ebae7c13b7..1195f6ea79 100755
--- a/scripts/ubicloud/ubi-runner.sh
+++ b/scripts/ubicloud/ubi-runner.sh
@@ -20,6 +20,15 @@
# letter) or a random per-machine id kept in $STATE_ROOT/owner-id. Ubicloud names
# allow 63 characters of [a-z0-9-], so a full name stays under 40.
#
+# Expiry: `up` and `run` with --ttl-hours H name the VM
+# ubirun-<owner>-<epoch>-x<expiry epoch>-<suffix>, expiring H hours after
+# creation (ci:ubicloud names its own VMs this way, 2 hours by default). The
+# operator reaper (scripts/ubicloud/reap-expired.ts) destroys VMs in that
+# format once the expiry has passed, whoever owns them. Without --ttl-hours a
+# VM never expires and is never reaped; use that, or a long TTL, for dev,
+# benchmark and eval VMs. Every parser here reads both formats, and the
+# expiring form stays under 52 characters.
+#
# Teardown: `up` records each VM's state (location, create status) before it
# sends the create request, and `down` destroys and polls until the VM is
# confirmed gone or provably never existed, waiting out a create that may still
@@ -210,14 +219,26 @@ write_state() {
"$1" "$2" "$3" "$4" "$5" "$6" "$$" >"$(state_dir "$1")/env"
}
-new_name() { echo "$PREFIX-$OWNER-$(date +%s)-$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')"; }
+# new_name [TTL_HOURS]: a fresh name for this owner, carrying an expiry
+# TTL_HOURS after now when given.
+new_name() {
+ local now suffix
+ now=$(date +%s)
+ suffix=$(head -c4 /dev/urandom | od -An -tx1 | tr -d ' \n')
+ if [ -n "${1:-}" ]; then echo "$PREFIX-$OWNER-$now-x$(( now + $1 * 3600 ))-$suffix"; else echo "$PREFIX-$OWNER-$now-$suffix"; fi
+}
+
+check_ttl() {
+ [[ "$1" =~ ^[1-9][0-9]{0,3}$ ]] && [ "$1" -le 8760 ] \
+ || die "--ttl-hours must be a whole number of hours from 1 to 8760 (omit it for a VM that never expires)"
+}
valid_name() { [[ "$1" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; }
UP_NAME=""
UP_READY=""
cmd_up() {
- local size=$DEFAULT_SIZE location=$DEFAULT_LOCATION name="" storage="" image=ubuntu-noble
+ local size=$DEFAULT_SIZE location=$DEFAULT_LOCATION name="" storage="" image=ubuntu-noble ttl=""
while [ $# -gt 0 ]; do
case $1 in
-s|--size) size=$2; shift 2 ;;
@@ -225,10 +246,12 @@ cmd_up() {
-n|--name) name=$2; shift 2 ;;
-S|--storage) storage=$2; shift 2 ;;
-b|--image) image=$2; shift 2 ;;
+ --ttl-hours) check_ttl "$2"; ttl=$2; shift 2 ;;
*) die "up: unknown option $1" ;;
esac
done
- [ -n "$name" ] || name=$(new_name)
+ [ -z "$name" ] || [ -z "$ttl" ] || die "up: --ttl-hours writes the expiry into the generated name, so it cannot be combined with -n"
+ [ -n "$name" ] || name=$(new_name "$ttl")
valid_name "$name" || die "invalid VM name '$name' (Ubicloud allows 1-63 of a-z, 0-9 and '-', starting and ending with a letter or digit)"
if [ "$GC_HOURS" -gt 0 ]; then
cmd_gc "$GC_HOURS" || log "stale-VM cleanup failed; continuing"
@@ -423,10 +446,11 @@ cmd_pull() {
}
cmd_run() {
- local up_args=() src=. dest="" setup="" keep=0 pulls=() envs=()
+ local up_args=() src=. dest="" setup="" keep=0 pulls=() envs=() ttl=""
while [ $# -gt 0 ]; do
case $1 in
-s|--size|-l|--location|-n|--name|-S|--storage|-b|--image) up_args+=("$1" "$2"); shift 2 ;;
+ --ttl-hours) check_ttl "$2"; ttl=$2; shift 2 ;;
--src) src=$2; shift 2 ;;
--dest) dest=$2; shift 2 ;;
--setup) setup=$2; shift 2 ;;
@@ -447,7 +471,8 @@ cmd_run() {
for (( i = 0; i < ${#up_args[@]}; i += 2 )); do
case ${up_args[i]} in -n|--name) name=${up_args[i+1]} ;; esac
done
- [ -n "$name" ] || { name=$(new_name); up_args+=(-n "$name"); }
+ [ -z "$name" ] || [ -z "$ttl" ] || die "run: --ttl-hours writes the expiry into the generated name, so it cannot be combined with -n"
+ [ -n "$name" ] || { name=$(new_name "$ttl"); up_args+=(-n "$name"); }
RUN_VM=$name
# Armed before the create request: an interrupted `up` still destroys its VM.
# A second signal must not cut teardown short, so the EXIT handler ignores them.
@@ -489,11 +514,13 @@ usage() {
cat <<EOF
usage: ubi-runner.sh <command> [args]
- run [up opts] [--src DIR] [--dest PATH] [--setup FILE] [--env K=V]...
+ run [up opts] [--ttl-hours H] [--src DIR] [--dest PATH] [--setup FILE] [--env K=V]...
[--pass NAME]... [--pull REMOTE_GLOB:LOCAL_DIR]... [--keep] -- COMMAND
up + sync + setup + command + pull + destroy; exits with COMMAND's status
- up [-s SIZE] [-l LOCATION] [-n NAME] [-S STORAGE_GIB] [-b IMAGE]
- create a VM and wait for SSH; prints its name
+ up [-s SIZE] [-l LOCATION] [-n NAME | --ttl-hours H] [-S STORAGE_GIB] [-b IMAGE]
+ create a VM and wait for SSH; prints its name. --ttl-hours H
+ names it to expire H hours from now (the operator reaper
+ destroys it after that); without it the VM never expires
ssh NAME [COMMAND] shell or login-shell command on the VM (user ubi, passwordless sudo)
sync NAME [SRC] [DEST] stream a checkout (tracked + untracked-unignored + .git)
pack [SRC] write that checkout tarball to stdout (with a slim .git: HEAD + origin/master)
@@ -507,8 +534,9 @@ usage: ubi-runner.sh <command> [args]
gc HOURS destroy this owner's VMs older than HOURS (never other owners')
cli ARGS... raw Ubicloud CLI passthrough (e.g. cli vm list)
-VMs are named $PREFIX-<owner>-<epoch>-<suffix>; set UBI_OWNER (e.g. your thread
-code) to tag them, otherwise a per-machine id is used.
+VMs are named $PREFIX-<owner>-<epoch>-<suffix>, or $PREFIX-<owner>-<epoch>-x<expiry>-<suffix>
+with --ttl-hours; set UBI_OWNER (e.g. your thread code) to tag them, otherwise a
+per-machine id is used.
defaults: size=$DEFAULT_SIZE location=$DEFAULT_LOCATION (env UBI_SIZE, UBI_LOCATION)
env: UBI_GC_HOURS (unset/0: no sweep on up), UBI_CREATE_GRACE (${CREATE_GRACE}s),
UBI_DOWN_TIMEOUT (${DOWN_TIMEOUT}s), UBI_API_TIMEOUT (${API_TIMEOUT}s)
diff --git a/test/scripts/ci-ubicloud-teardown.slow.test.ts b/test/scripts/ci-ubicloud-teardown.slow.test.ts
index 8d7f19e9da..6745a7dbde 100644
--- a/test/scripts/ci-ubicloud-teardown.slow.test.ts
+++ b/test/scripts/ci-ubicloud-teardown.slow.test.ts
@@ -2,7 +2,9 @@
// a cancelled background operation) to scripts/ci-ubicloud.ts while
// its VMs are still provisioning (one created, two creates in flight) against
// a mock Ubicloud API. Every name is recorded before its create, and teardown
-// returns only after each VM that came to exist is destroyed and gone.
+// returns only after each VM that came to exist is destroyed and gone. Every
+// gate VM name carries its expiry, two hours after creation by default
+// (scripts/ubicloud/reap-expired.ts reaps a VM teardown never reached).
//
// The orchestrator packs its whole checkout (.git and untracked files
// included) before it provisions anything, so it runs from a fixture repo
@@ -71,7 +73,9 @@ describe("ci:ubicloud teardown", () => {
const requested = readFileSync(join(runDir, "vms.txt"), "utf8").trim().split("\n").map((l) => l.split(" ")[0]!);
expect(requested).toHaveLength(3);
for (const name of requested) {
- expect(name).toMatch(/^ubirun-probe-\d{10}-ci0[123][0-9a-f]{4}$/);
+ const tagged = /^ubirun-probe-(\d{10})-x(\d{10})-ci0[123][0-9a-f]{4}$/.exec(name);
+ expect(tagged).not.toBeNull();
+ expect(Number(tagged![2]) - Number(tagged![1])).toBe(2 * 3600);
expect(api.events).toContain(`created ${name}`);
expect(api.events).toContain(`removed ${name}`);
}
diff --git a/test/scripts/ci-ubicloud-vm-names.test.ts b/test/scripts/ci-ubicloud-vm-names.test.ts
new file mode 100644
index 0000000000..1f3592ca1a
--- /dev/null
+++ b/test/scripts/ci-ubicloud-vm-names.test.ts
@@ -0,0 +1,139 @@
+// ci-ubicloud-vm-names.test.ts — VM names that carry an expiry
+// (ubirun-<owner>-<epoch>-x<expiry>-<suffix>) next to the older names, for
+// scripts/ubicloud/ubi-runner.sh and scripts/ci-ubicloud.ts.
+//
+// Protects: `up`/`run --ttl-hours H` name their VM with an expiry H hours
+// after creation (no --ttl-hours: no expiry, never reaped), the flag is
+// validated and cannot be combined with -n, and every existing parser
+// (list --mine, usage, gc, down) reads old and new names alike: gc ages a VM
+// by its creation epoch, never its expiry.
+// Fails when: a new-format name is not owner-tagged for list --mine or usage,
+// gc sweeps by the expiry or another owner's VM, or the flag is ignored.
+// Network: none (in-process mock Ubicloud API).
+
+import { afterEach, describe, expect, it } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { startMockUbicloud, waitForEvent, type MockUbicloud, type MockUbicloudOptions } from "../helpers/mock-ubicloud-api.ts";
+
+const RUNNER = resolve(import.meta.dir, "..", "..", "scripts/ubicloud/ubi-runner.sh");
+const NOW = Math.floor(Date.now() / 1000);
+const OLD = NOW - 5 * 3600;
+
+let dir = "";
+let mock: MockUbicloud | null = null;
+afterEach(() => {
+ mock?.stop();
+ mock = null;
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ dir = "";
+});
+
+function serve(opts: MockUbicloudOptions = {}): MockUbicloud {
+ mock = startMockUbicloud(opts);
+ return mock;
+}
+
+function spawnRunner(args: string[], extra: Record<string, string> = {}) {
+ dir ||= mkdtempSync(join(tmpdir(), "ubi-vm-names-"));
+ return Bun.spawn(["bash", RUNNER, ...args], {
+ env: {
+ PATH: process.env.PATH ?? "/usr/bin:/bin",
+ HOME: dir,
+ UBICLOUD_API_KEY: "test-token",
+ UBICLOUD_API_URL: mock?.url ?? "http://127.0.0.1:9",
+ UBI_RUNNER_STATE: join(dir, "state"),
+ UBI_POLL_SECONDS: "0.2",
+ ...extra,
+ },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+}
+
+async function run(args: string[], extra: Record<string, string> = {}) {
+ const proc = spawnRunner(args, extra);
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, code };
+}
+
+describe("--ttl-hours", () => {
+ for (const verb of ["up", "run"] as const) {
+ it(`${verb} --ttl-hours 3 names the VM with an expiry three hours after creation`, async () => {
+ const api = serve();
+ const proc = spawnRunner(verb === "up" ? ["up", "--ttl-hours", "3"] : ["run", "--ttl-hours", "3", "--", "true"], { UBI_OWNER: "gbra135" });
+ const name = (await waitForEvent(api, /^create-start /)).split(" ")[1]!;
+ proc.kill("SIGTERM");
+ await proc.exited;
+ const m = /^ubirun-gbra135-(\d{10})-x(\d{10})-[0-9a-f]{8}$/.exec(name);
+ expect(m).not.toBeNull();
+ expect(Number(m![2]) - Number(m![1])).toBe(3 * 3600);
+ expect(Math.abs(Number(m![1]) - NOW)).toBeLessThan(120);
+ expect(name.length).toBeLessThanOrEqual(63);
+ expect(api.vms.size).toBe(0);
+ });
+ }
+
+ it("without --ttl-hours the name carries no expiry", async () => {
+ const api = serve();
+ const proc = spawnRunner(["up"], { UBI_OWNER: "gbra135" });
+ const name = (await waitForEvent(api, /^create-start /)).split(" ")[1]!;
+ proc.kill("SIGTERM");
+ await proc.exited;
+ expect(name).toMatch(/^ubirun-gbra135-\d{10}-[0-9a-f]{8}$/);
+ });
+
+ it("refuses a bad value and the combination with -n before any create", async () => {
+ const api = serve();
+ for (const bad of ["0", "1.5", "abc", "9000"]) {
+ const r = await run(["up", "--ttl-hours", bad], { UBI_OWNER: "t1" });
+ expect(r.code).toBe(1);
+ expect(r.stderr).toContain("--ttl-hours must be a whole number of hours from 1 to 8760");
+ }
+ const both = await run(["up", "-n", "ubirun-t1-1790000000-aaaaaaaa", "--ttl-hours", "2"], { UBI_OWNER: "t1" });
+ expect(both.code).toBe(1);
+ expect(both.stderr).toContain("cannot be combined with -n");
+ const runBoth = await run(["run", "--ttl-hours", "2", "-n", "ubirun-t1-1790000000-aaaaaaaa", "--", "true"], { UBI_OWNER: "t1" });
+ expect(runBoth.code).toBe(1);
+ expect(runBoth.stderr).toContain("cannot be combined with -n");
+ expect(api.events).toEqual([]);
+ });
+});
+
+describe("parsers read old and new names", () => {
+ const seed = [
+ { name: `ubirun-t1-${OLD}-x${NOW + 3600}-ci01abcd`, size: "standard-16" },
+ { name: `ubirun-t1-${NOW}-x${OLD}-ci02abcd`, size: "standard-8" },
+ { name: `ubirun-t1-${OLD}-aaaaaaaa`, size: "standard-4" },
+ { name: `ubirun-other-${OLD}-x${OLD + 3600}-ci01ffff`, size: "standard-16" },
+ { name: `ubirun-${OLD}-dddddddd`, size: "standard-2" },
+ { name: "prod-db", size: "standard-2" },
+ ];
+
+ it("list --mine and usage tag new-format names with their owner", async () => {
+ serve({ seed });
+ const mine = await run(["list", "--mine"], { UBI_OWNER: "t1" });
+ expect(mine.stdout.trim().split("\n").map((l) => l.split(/\s+/)[1])).toEqual(seed.slice(0, 3).map((s) => s.name));
+ const usage = (await run(["usage"], { UBI_OWNER: "t1" })).stdout;
+ expect(usage).toMatch(/^t1\s+3\s+28\s+\(you\)$/m);
+ expect(usage).toMatch(/^other\s+1\s+16$/m);
+ expect(usage).toMatch(/^\(untagged\)\s+1\s+2$/m);
+ expect(usage).toMatch(/^\(other\)\s+1\s+2$/m);
+ });
+
+ it("gc ages by creation epoch: it sweeps the caller's old VMs of both formats, not a young VM whose expiry passed", async () => {
+ const api = serve({ seed });
+ const gc = await run(["gc", "1"], { UBI_OWNER: "t1" });
+ expect(gc.code).toBe(0);
+ expect(api.events.filter((e) => e.startsWith("destroy ")).sort()).toEqual([`destroy ${seed[0]!.name}`, `destroy ${seed[2]!.name}`].sort());
+ expect([...api.vms.keys()].sort()).toEqual([seed[1]!.name, seed[3]!.name, seed[4]!.name, seed[5]!.name].sort());
+ });
+
+ it("down destroys a new-format name", async () => {
+ const api = serve({ seed });
+ const down = await run(["down", seed[3]!.name], { UBI_OWNER: "t1" });
+ expect(down.code).toBe(0);
+ expect(api.events).toEqual([`destroy ${seed[3]!.name}`, `removed ${seed[3]!.name}`]);
+ });
+});
diff --git a/test/scripts/ubicloud-reap-expired.test.ts b/test/scripts/ubicloud-reap-expired.test.ts
new file mode 100644
index 0000000000..c2ad86e88e
--- /dev/null
+++ b/test/scripts/ubicloud-reap-expired.test.ts
@@ -0,0 +1,141 @@
+// ubicloud-reap-expired.test.ts — scripts/ubicloud/reap-expired.ts, the
+// operator-side leak guard for ci:ubicloud VMs.
+//
+// Protects: only VMs in the expiring name format
+// (ubirun-<owner>-<epoch>-x<expiry>-<suffix>) whose expiry plus the grace has
+// passed are ever selected; legacy untagged names, owner-tagged names without
+// an expiry and names ubi-runner did not make are never selected, whoever
+// owns them. Dry run is the default and destroys nothing; --apply destroys
+// through ubi-runner.sh down; more expired VMs than --max refuse the whole run.
+// Fails when: a selection rule loosens, the dry run sends a destroy, the plan
+// or owner notice stops naming owner, age, expiry and action, or the gate's
+// name helper makes a name the reaper cannot read back.
+// Network: none. The end-to-end cases use the in-process mock Ubicloud API.
+
+import { afterEach, describe, expect, it } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { expiringVmName, ownerNotices, parseVmName, planReap, renderPlan } from "../../scripts/ubicloud/reap-expired.ts";
+import { startMockUbicloud, type MockUbicloud } from "../helpers/mock-ubicloud-api.ts";
+
+const SCRIPT = resolve(import.meta.dir, "..", "..", "scripts/ubicloud/reap-expired.ts");
+const NOW = 1_792_000_000;
+const H = 3600;
+const LOC = "eu-central-h1";
+
+const expired = `ubirun-gbra135-${NOW - 5 * H}-x${NOW - 3 * H}-ci01a1b2`;
+const inGrace = `ubirun-gbra130-${NOW - 3 * H}-x${NOW - 5 * 60}-ci02c3d4`;
+const live = `ubirun-gbra130-${NOW - 600}-x${NOW + 2 * H}-9f8e7d6c`;
+const noExpiry = `ubirun-gbra9-${NOW - 50 * H}-aaaaaaaa`;
+const legacy = `ubirun-${NOW - 300 * H}-e9af21ce`;
+const backwards = `ubirun-gbra7-${NOW - 2 * H}-x${NOW - 3 * H}-bbbbbbbb`;
+const FIXTURE = [expired, inGrace, live, noExpiry, legacy, backwards, "prod-db", `ubirun-x${NOW - 9 * H}-x${NOW - 8 * H}`].map((name) => ({ location: LOC, name }));
+
+describe("parseVmName", () => {
+ it("reads the expiring format, owner-tagged names without expiry, legacy names and foreign names", () => {
+ expect(parseVmName(expired)).toEqual({ kind: "expiring", owner: "gbra135", createdAt: NOW - 5 * H, expiresAt: NOW - 3 * H });
+ expect(parseVmName(noExpiry)).toEqual({ kind: "no-expiry", owner: "gbra9", createdAt: NOW - 50 * H });
+ expect(parseVmName(legacy)).toEqual({ kind: "legacy", createdAt: NOW - 300 * H });
+ expect(parseVmName("prod-db")).toEqual({ kind: "foreign" });
+ expect(parseVmName(`ubirun-x${NOW - 9 * H}-x${NOW - 8 * H}`)).toEqual({ kind: "foreign" });
+ expect(parseVmName(`${expired}-extra!`)).toEqual({ kind: "foreign" });
+ });
+
+ it("the gate's name helper writes names of at most 63 characters that read back with their expiry", () => {
+ const name = expiringVmName({ owner: "abcdefghijkl", createdAt: NOW, ttlHours: 2, suffix: "ci10ffff" });
+ expect(name).toBe(`ubirun-abcdefghijkl-${NOW}-x${NOW + 2 * H}-ci10ffff`);
+ expect(name.length).toBeLessThanOrEqual(63);
+ expect(parseVmName(name)).toEqual({ kind: "expiring", owner: "abcdefghijkl", createdAt: NOW, expiresAt: NOW + 2 * H });
+ expect(expiringVmName({ owner: "t1", createdAt: NOW, ttlHours: 0, suffix: "ci01abcd" })).toBe(`ubirun-t1-${NOW}-ci01abcd`);
+ expect(() => expiringVmName({ owner: "t1", createdAt: NOW, ttlHours: 1.5, suffix: "ci01abcd" })).toThrow();
+ expect(() => expiringVmName({ owner: "T-1", createdAt: NOW, ttlHours: 1, suffix: "ci01abcd" })).toThrow();
+ });
+});
+
+describe("planReap", () => {
+ it("selects only expiring names past expiry plus grace, and never legacy, untagged-expiry or foreign names", () => {
+ const plan = planReap(FIXTURE, { now: NOW, graceSeconds: 15 * 60 });
+ const action = Object.fromEntries(plan.map((row) => [row.name, row.action]));
+ expect(action).toEqual({
+ [expired]: "destroy",
+ [inGrace]: "keep",
+ [live]: "keep",
+ [noExpiry]: "skip",
+ [legacy]: "skip",
+ [backwards]: "skip",
+ "prod-db": "skip",
+ [`ubirun-x${NOW - 9 * H}-x${NOW - 8 * H}`]: "skip",
+ });
+ expect(plan.find((row) => row.name === backwards)?.reason).toContain("expiry before creation");
+ expect(plan.filter((row) => row.action === "destroy").map((row) => row.name)).toEqual([expired]);
+ expect(planReap(FIXTURE, { now: NOW, graceSeconds: 0 }).filter((row) => row.action === "destroy").map((row) => row.name).sort()).toEqual([expired, inGrace].sort());
+ });
+
+ it("the plan names owner, age, expiry and action per VM; the notice groups expired VMs by owner with the thread code", () => {
+ const plan = planReap(FIXTURE, { now: NOW, graceSeconds: 15 * 60 });
+ const text = renderPlan(plan, { now: NOW, apply: false, graceSeconds: 15 * 60 });
+ expect(text).toContain("dry run");
+ expect(text).toMatch(new RegExp(`gbra135\\s+would destroy\\s+5h00m\\s+expired 3h00m ago\\s+${LOC}/${expired}`));
+ expect(text).toMatch(new RegExp(`gbra130\\s+keep\\s+0h10m\\s+expires in 2h00m\\s+${LOC}/${live}`));
+ expect(text).toMatch(new RegExp(`gbra9\\s+skip: no expiry\\s+50h00m\\s+-\\s+${LOC}/${noExpiry}`));
+ expect(text).toMatch(new RegExp(`\\(untagged\\)\\s+skip: legacy name\\s+300h00m`));
+ expect(text).toContain("2 VM(s) not named by ubi-runner: skipped");
+ expect(text).not.toContain("prod-db");
+ const notice = ownerNotices(plan, { now: NOW, apply: false });
+ expect(notice).toContain("owner gbra135 (thread GBRA-135): 1 expired VM(s)");
+ expect(notice).toContain(`${LOC}/${expired} expired 3h00m ago`);
+ expect(notice).toContain("Dry run: nothing was destroyed");
+ expect(notice).not.toContain("gbra130");
+ expect(ownerNotices(planReap([{ location: LOC, name: live }], { now: NOW, graceSeconds: 0 }), { now: NOW, apply: false })).toContain("no expired VMs");
+ });
+});
+
+describe("reap-expired CLI against the mock Ubicloud API", () => {
+ let mock: MockUbicloud | null = null;
+ let dir = "";
+ afterEach(() => {
+ mock?.stop();
+ mock = null;
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ async function cli(args: string[]) {
+ dir ||= mkdtempSync(join(tmpdir(), "reap-expired-"));
+ const proc = Bun.spawn(["bun", SCRIPT, ...args, "--now", String(NOW)], {
+ env: { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: dir, UBICLOUD_API_TOKEN: "test-token", UBICLOUD_API_URL: mock!.url, UBI_RUNNER_STATE: join(dir, "state"), UBI_POLL_SECONDS: "0.2" },
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, code };
+ }
+
+ it("dry run by default: prints the plan and notice and sends no destroy", async () => {
+ mock = startMockUbicloud({ seed: FIXTURE });
+ const r = await cli([]);
+ expect(r.code).toBe(0);
+ expect(r.stdout).toContain(`would destroy`);
+ expect(r.stdout).toContain("=== owner notices ===");
+ expect(mock.events.filter((e) => e.startsWith("destroy "))).toEqual([]);
+ expect(mock.vms.size).toBe(FIXTURE.length);
+ });
+
+ it("--apply destroys only the expired VM through ubi-runner.sh down", async () => {
+ mock = startMockUbicloud({ seed: FIXTURE });
+ const r = await cli(["--apply"]);
+ expect({ code: r.code, stderr: r.stderr.includes("FAILED") }).toEqual({ code: 0, stderr: false });
+ expect(mock.events).toEqual([`destroy ${expired}`, `removed ${expired}`]);
+ expect(r.stdout).toMatch(new RegExp(`gbra135\\s+destroyed\\s+5h00m`));
+ expect(r.stdout).toContain("Destroyed by the operator reaper");
+ expect([...mock.vms.keys()].sort()).toEqual(FIXTURE.map((v) => v.name).filter((n) => n !== expired).sort());
+ });
+
+ it("more expired VMs than --max refuses the whole run with exit 3 and destroys nothing", async () => {
+ mock = startMockUbicloud({ seed: FIXTURE });
+ const r = await cli(["--apply", "--grace-minutes", "0", "--max", "1"]);
+ expect(r.code).toBe(3);
+ expect(r.stderr).toContain("2 expired VMs exceed --max 1");
+ expect(mock.events.filter((e) => e.startsWith("destroy "))).toEqual([]);
+ });
+});