Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ubicloud): SIGHUP/SIGQUIT take the teardown path; quota refusals print usage by owner
garrytan5923b540ed32
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 804039bccf..0545346eac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,9 +16,9 @@ identifiers and attribution are available in the pre-removal Git revisionVMs are named `ubirun-<owner>-<epoch>-<suffix>`, where the owner is `UBI_OWNER` or a per-machine id. Before, nothing showed which thread a VM belonged to, and every `up` destroyed any `ubirun-*` VM older than 12 hours, whoever started it. That sweep is now off unless `UBI_GC_HOURS` is set, and even then it only destroys the caller's own VMs. `ubi-runner.sh gc HOURS` runs the same sweep by hand.-A run stopped with SIGTERM while VMs were still provisioning used to tear down before their create requests finished. Those VMs appeared afterwards and leaked (three `standard-16` VMs sat idle for 84 minutes). Now each name is recorded before its create is sent. An interrupted `up` finishes its create request and destroys its own VM. Teardown then polls every recorded name until it is confirmed gone. A mock-API test reproduces the old leak (two of three VMs left behind) and passes with the fix.+A run stopped with SIGTERM while VMs were still provisioning used to tear down before their create requests finished. Those VMs appeared afterwards and leaked (three `standard-16` VMs sat idle for 84 minutes). SIGHUP, which a dropped terminal or a cancelled background operation sends, was not handled at all, so the run died with every VM still up (14 leaked VMs on 2026-10-04). Now SIGINT, SIGTERM, SIGHUP and SIGQUIT all take the same teardown path, and a second signal can't cut it short. Each name is recorded before its create is sent. An interrupted `up` finishes its create request and destroys its own VM. Teardown then polls every recorded name until it is confirmed gone. Mock-API tests reproduce both old leaks (SIGTERM left two of three VMs behind, SIGHUP all three) and pass with the fix.-`ubi-runner.sh list --mine` lists your VMs, and `ubi-runner.sh usage` shows VMs and vCPUs per owner across the project.+`ubi-runner.sh list --mine` lists your VMs, and `ubi-runner.sh usage` shows VMs and vCPUs per owner across the project. A create refused for vCPU quota now says how many vCPUs it needed, how many the project uses and the maximum, followed by that per-owner table.## To take advantage of v0.60.70.0diff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.tsindex 73eaa78807..d6a3106ae1 100755--- a/scripts/ci-ubicloud.ts+++ b/scripts/ci-ubicloud.ts@@ -33,7 +33,8 @@** 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- * create request is sent. On exit, including SIGINT and SIGTERM, in-flight+ * 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* recorded name is destroyed and polled until it is confirmed gone.*/@@ -284,7 +285,9 @@ async function main() {log(left ? `teardown left ${left} VM(s) unconfirmed (names in ${ledger})` : `teardown confirmed ${live.length} VM(s) gone`);};let interrupted = false;- for (const signal of ["SIGINT", "SIGTERM"] as const) {+ // After SIGHUP the terminal may be gone: a failed log write must not abort teardown.+ for (const stream of [process.stdout, process.stderr]) stream.on("error", () => {});+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"] as const) {process.on(signal, () => {if (interrupted) return;interrupted = true;@@ -384,7 +387,10 @@ async function main() {if (tornDown) return;if (up.code !== 0) {vm.state = "failed";- log(`VM ${index + 1} failed to provision (see ${setupLog}): ${readFileSync(setupLog, "utf8").trim().split("\n").slice(-2).join(" | ")}`);+ const setupText = readFileSync(setupLog, "utf8").trim();+ const quota = setupText.indexOf("ubi-runner: quota refused");+ if (quota >= 0) log(`VM ${index + 1} refused by the Ubicloud vCPU quota; the run continues on the VMs that started:\n${setupText.slice(quota)}`);+ else log(`VM ${index + 1} failed to provision (see ${setupLog}): ${setupText.split("\n").slice(-2).join(" | ")}`);return;}vm.state = "setup";diff --git a/scripts/ubicloud/README.md b/scripts/ubicloud/README.mdindex 6e62ee0eaa..fd4e858670 100644--- a/scripts/ubicloud/README.md+++ b/scripts/ubicloud/README.md@@ -17,9 +17,10 @@ of `[a-z0-9-]`, so a full name stays under 40.Each name is recorded before its create request is sent: the runner writesthe VM's state directory first, and `ci-ubicloud.ts` appends the name to-`.context/ci-ubicloud/<run>/vms.txt`. On every exit, including Ctrl-C and-SIGTERM, an `up` still talking to the API finishes the request and destroys its-own VM. Then every recorded name gets `down`, which destroys the VM and polls+`.context/ci-ubicloud/<run>/vms.txt`. On every exit, including Ctrl-C,+SIGTERM, SIGQUIT and SIGHUP (a dropped terminal or a cancelled background+operation), an `up` still talking to the API finishes the request and destroys+its own VM; further signals are ignored until teardown ends. Then every recorded name gets `down`, which destroys the VM and pollsuntil it is confirmed gone. A create whose answer never arrived is waited outfor `UBI_CREATE_GRACE` seconds (default 180) before the VM counts as nevercreated. `down` gives up after `UBI_DOWN_TIMEOUT` seconds (default 900) and@@ -78,7 +79,10 @@ multi-lane wave, each lane runs `ci:ubicloud:diff` or its targeted suites, andonly the integrator runs the full gate; four lanes each running the full gatetake 256 vCPUs, the whole quota. A VM that thequota refuses fails to provision and the run continues on the VMs that did-start, so a busy project shrinks the fleet instead of failing. Pass `--vms 10`+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; used vCPUs beyond that table are other usage, such as+managed GitHub runners. Pass `--vms 10`only when the quota is idle. Slow-lane items run `test/export-scale.slow.test.ts`at the pull-request scale (`GBRAIN_TEST_EXPORT_SCALE_PAGES=10001`). `--lanes` runs asubset, `--keep` leaves the VMs up for debugging, and `--diff` followsdiff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.shindex 6d1f2d3f02..93e15afe83 100755--- a/scripts/ubicloud/ubi-runner.sh+++ b/scripts/ubicloud/ubi-runner.sh@@ -23,7 +23,9 @@# 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-# be in flight. An interrupted `up` or `run` (EXIT, INT, TERM) runs that `down`.+# be in flight. An interrupted `up` or `run` (EXIT, INT, TERM, HUP, QUIT) runs+# that `down`; further signals are ignored until it finishes. A create refused+# for vCPU quota prints the project's usage per owner.## Stale-VM sweeps are off by default. With UBI_GC_HOURS set to a positive# number, every `up` first destroys this owner's VMs older than that; `gc HOURS`@@ -227,15 +229,26 @@ cmd_up() {write_state "$name" "$location" "$size" "" unknown "$create_at"UP_NAME=$namelog "creating $location/$name ($size)"- # Hold INT/TERM until the create answer is recorded, so teardown knows+ # Hold signals until the create answer is recorded, so teardown knows# whether the VM exists instead of waiting out UBI_CREATE_GRACE.- local interrupted="" created=yes- trap 'interrupted=1' INT TERM- cli "${args[@]}" >/dev/null || created=no+ local interrupted="" created=yes refusal need used max+ trap 'interrupted=1' INT TERM HUP QUIT+ cli "${args[@]}" >/dev/null 2>"$dir/create.err" || created=nowrite_state "$name" "$location" "$size" "" "$created" "$create_at"- trap 'exit 130' INT TERM+ trap 'exit 130' INT TERM HUP QUIT[ -z "$interrupted" ] || exit 130- [ "$created" = yes ] || die "create failed"+ if [ "$created" = no ]; then+ refusal=$(sed -n 's/.*Requested vCPU count: \([0-9]*\), currently used vCPU count: \([0-9]*\), maximum allowed vCPU count: \([0-9]*\).*/\1 \2 \3/p' "$dir/create.err")+ if [ -z "$refusal" ]; then+ cat "$dir/create.err" >&2+ die "create failed"+ fi+ read -r need used max <<<"$refusal"+ log "quota refused $location/$name ($size): it needs $need vCPUs and the project already uses $used of $max"+ log "VMs in the project by owner (the rest of the used count is other usage, such as managed GitHub runners):"+ cmd_usage >&2 || true+ die "create failed: vCPU quota exhausted; wait for running VMs to finish, or use fewer or smaller VMs (ci:ubicloud --vms N)"+ filocal deadline=$(( $(date +%s) + 600 )) show state ipwhile :; do@@ -394,8 +407,9 @@ cmd_run() {[ -n "$name" ] || { name=$(new_name); up_args+=(-n "$name"); }RUN_VM=$name# Armed before the create request: an interrupted `up` still destroys its VM.- trap 'cmd_down "$RUN_VM" || log "WARNING: failed to destroy $RUN_VM; run: $0 down $RUN_VM"' EXIT- trap 'exit 130' INT TERM+ # A second signal must not cut teardown short, so the EXIT handler ignores them.+ trap 'trap "" INT TERM HUP QUIT; cmd_down "$RUN_VM" || log "WARNING: failed to destroy $RUN_VM; run: $0 down $RUN_VM"' EXIT+ trap 'exit 130' INT TERM HUP QUITcmd_up "${up_args[@]}" >/dev/nullif [ "$keep" = 1 ]; thentrap - EXIT@@ -466,8 +480,8 @@ case $cmd inesaccase $cmd inrun) cmd_run "$@" ;;- up) trap '[ -z "$UP_NAME" ] || [ -n "$UP_READY" ] || cmd_down "$UP_NAME" || log "WARNING: failed to destroy $UP_NAME; run: $0 down $UP_NAME"' EXIT- trap 'exit 130' INT TERM+ up) trap 'trap "" INT TERM HUP QUIT; [ -z "$UP_NAME" ] || [ -n "$UP_READY" ] || cmd_down "$UP_NAME" || log "WARNING: failed to destroy $UP_NAME; run: $0 down $UP_NAME"' EXIT+ trap 'exit 130' INT TERM HUP QUITcmd_up "$@" ;;ssh) name=$1; shift; load "$name"# shellcheck disable=SC2046diff --git a/test/helpers/mock-ubicloud-api.ts b/test/helpers/mock-ubicloud-api.tsindex 5fbdd9c47e..12fe4b6919 100644--- a/test/helpers/mock-ubicloud-api.ts+++ b/test/helpers/mock-ubicloud-api.ts@@ -16,7 +16,7 @@ export interface MockUbicloudOptions {createDelayMs?: (name: string) => number;/** Delay between `destroy` and the VM disappearing. Default 200. */destroyDelayMs?: number;- /** Answer every create with a 400, like a quota refusal. */+ /** Refuse every create with Ubicloud's vCPU quota error (400). */rejectCreates?: boolean;seed?: Array<{ location?: string; name: string; size?: string }>;}@@ -52,7 +52,7 @@ export function startMockUbicloud(opts: MockUbicloudOptions = {}): MockUbicloudawait Bun.sleep(opts.createDelayMs?.(name) ?? 0);if (opts.rejectCreates) {events.push(`create-rejected ${name}`);- return text("! Validation failed: quota exceeded", 400);+ return text("! Unexpected response status: 400\nDetails: Validation failed for following fields: size\n size: Insufficient quota for requested size. Requested vCPU count: 16, currently used vCPU count: 252, maximum allowed vCPU count: 256, remaining vCPU count: 4", 400);}const size = argv[argv.indexOf("-s") + 1] ?? "standard-16";vms.set(name, { location, name, size, state: "creating" });diff --git a/test/scripts/ci-ubicloud-teardown.slow.test.ts b/test/scripts/ci-ubicloud-teardown.slow.test.tsindex 2d0a518ec9..4f5b345769 100644--- a/test/scripts/ci-ubicloud-teardown.slow.test.ts+++ b/test/scripts/ci-ubicloud-teardown.slow.test.ts@@ -1,4 +1,5 @@-// ci-ubicloud-teardown.slow.test.ts — SIGTERM to scripts/ci-ubicloud.ts while+// ci-ubicloud-teardown.slow.test.ts — SIGTERM or SIGHUP (a dropped terminal,+// 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. Slow@@ -22,7 +23,7 @@ afterEach(() => {});describe("ci:ubicloud teardown", () => {- it("SIGTERM mid-provision destroys every VM it asked for, including creates still in flight", async () => {+ for (const signal of ["SIGTERM", "SIGHUP"] as const) it(`${signal} mid-provision destroys every VM it asked for, including creates still in flight`, async () => {dir = mkdtempSync(join(tmpdir(), "ci-ubicloud-teardown-"));const api = (mock = startMockUbicloud({ createDelayMs: (name) => (/-ci01/.test(name) ? 0 : 4000) }));const proc = Bun.spawn(["bun", "run", "scripts/ci-ubicloud.ts", "--vms", "3", "--lanes", "gitleaks"], {@@ -44,7 +45,7 @@ describe("ci:ubicloud teardown", () => {await waitForEvent(api, /^created \S+-ci01/, 120_000);await waitForEvent(api, /^create-start \S+-ci03/, 10_000);expect(api.events.some((e) => /^created \S+-ci0[23]/.test(e))).toBe(false);- proc.kill("SIGTERM");+ proc.kill(signal);expect(await proc.exited).toBe(130);const out = await stdout;runDir = /logs in (\S+)/.exec(out)?.[1] ?? "";diff --git a/test/scripts/ubi-runner.test.ts b/test/scripts/ubi-runner.test.tsindex 6e0cc937bc..c52ae65783 100644--- a/test/scripts/ubi-runner.test.ts+++ b/test/scripts/ubi-runner.test.ts@@ -68,15 +68,30 @@ describe("owner tag", () => {});describe("teardown waits for in-flight creates", () => {- it("SIGTERM during the create request: the create finishes, then the VM is destroyed and confirmed gone", async () => {- const api = serve({ createDelayMs: () => 1500 });+ for (const signal of ["SIGTERM", "SIGHUP", "SIGINT", "SIGQUIT"] as const) {+ it(`${signal} during the create request: the create finishes, then the VM is destroyed and confirmed gone`, async () => {+ const api = serve({ createDelayMs: () => 1500 });+ const proc = spawnRunner(["up"], { UBI_OWNER: "t1" });+ const started = await waitForEvent(api, /^create-start /);+ const name = started.split(" ")[1]!;+ expect(name).toMatch(/^ubirun-t1-\d{10}-[0-9a-f]{8}$/);+ proc.kill(signal);+ expect(await proc.exited).toBe(130);+ expect(api.events).toEqual([`create-start ${name}`, `created ${name}`, `destroy ${name}`, `removed ${name}`]);+ expect(api.vms.size).toBe(0);+ });+ }++ it("a second signal during teardown does not cut it short", async () => {+ const api = serve({ destroyDelayMs: 1500 });const proc = spawnRunner(["up"], { UBI_OWNER: "t1" });- const started = await waitForEvent(api, /^create-start /);- const name = started.split(" ")[1]!;- expect(name).toMatch(/^ubirun-t1-\d{10}-[0-9a-f]{8}$/);+ const name = (await waitForEvent(api, /^created /)).split(" ")[1]!;proc.kill("SIGTERM");+ await waitForEvent(api, /^destroy /);+ proc.kill("SIGHUP");+ proc.kill("SIGINT");expect(await proc.exited).toBe(130);- expect(api.events).toEqual([`create-start ${name}`, `created ${name}`, `destroy ${name}`, `removed ${name}`]);+ expect(api.events.slice(-2)).toEqual([`destroy ${name}`, `removed ${name}`]);expect(api.vms.size).toBe(0);});@@ -103,17 +118,20 @@ describe("teardown waits for in-flight creates", () => {expect(api.vms.size).toBe(0);});- it("a refused create needs no grace wait, and down of an unknown name reports it gone", async () => {- const api = serve({ rejectCreates: true });+ it("a quota refusal reports usage by owner and needs no grace wait; down of an unknown name reports it gone", async () => {+ const api = serve({ rejectCreates: true, seed: [{ name: `ubirun-lane2-${NOW}-aaaaaaaa` }, { name: `ubirun-lane2-${NOW}-bbbbbbbb` }] });const t0 = Date.now();const up = await run(["up"], { UBI_OWNER: "t1", UBI_CREATE_GRACE: "60" });expect(up.code).toBe(1);- expect(up.stderr).toContain("create failed");+ expect(up.stderr).toMatch(/quota refused eu-central-h1\/ubirun-t1-\S+ \(standard-16\): it needs 16 vCPUs and the project already uses 252 of 256/);+ expect(up.stderr).toMatch(/^lane2\s+2\s+32$/m);+ expect(up.stderr).toContain("create failed: vCPU quota exhausted");expect(Date.now() - t0).toBeLessThan(15_000);const down = await run(["down", `ubirun-t1-${NOW}-deadbeef`, "-l", "eu-central-h1"]);expect(down.code).toBe(0);expect(down.stderr).toContain("never existed or already destroyed");- expect(api.vms.size).toBe(0);+ expect(api.vms.size).toBe(2);+ expect(api.events.some((e) => e.startsWith("destroy "))).toBe(false);});});