Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ci(ubicloud): burst-size the fleet from usage, overlap VM setup with the upload, slim .git tarball, opt-in machine image, control VM no longer caps heavy items

garrytan7039d6332078
diff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.ts
index d6a3106ae1..9303010be0 100755
--- a/scripts/ci-ubicloud.ts
+++ b/scripts/ci-ubicloud.ts
@@ -7,11 +7,14 @@
* bun run ci:ubicloud:diff # doc-only diff: doc checks + gitleaks; any other diff: the full gate
*
* Options:
- * --vms N VMs to provision in parallel (default 4: 64 vCPUs of the
- * project quota that pull-request CI shares)
+ * --vms N VMs to provision in parallel (default: burst-sized from
+ * `ubi-runner.sh usage`; 4 when the quota is busy)
* --size SIZE Ubicloud size (default standard-16)
* --slots N concurrent work slots per VM (default: half of --size's vCPUs)
* --location LOC Ubicloud location (default eu-central-h1)
+ * --image IMAGE boot image (default: UBI_CI_IMAGE, else stock Ubuntu 24.04);
+ * gbrain-ci@latest is the prebaked machine image
+ * scripts/ubicloud/build-ci-image.sh builds
* --lanes a,b subset of gitleaks,verify,serial,slow,unit,e2e (default all)
* --diff doc-only diffs run only the doc checks and gitleaks (ci:local --diff)
* --record-weights write measured durations to scripts/ubicloud/weights.json
@@ -23,7 +26,8 @@
* are tested.
*
* Each VM runs scripts/ubicloud/setup-ci-vm.sh (bun, test prerequisites, one
- * pgvector server + PgBouncer per slot, PGLite snapshots). The first VM to
+ * pgvector server + PgBouncer per slot, PGLite snapshots), streamed over SSH
+ * while the checkout uploads. The first VM to
* finish setup runs the machine-level items in order (gitleaks, verify, the
* serial lane's machine-exclusive files) and then joins the pool. Every other
* test file is an item in one global heaviest-first queue that idle slots pull
@@ -45,7 +49,9 @@ import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import {
buildItems,
+ burstVms,
parseItemLog,
+ parseUsageTotal,
readWeightTable,
sortQueue,
takeBatch,
@@ -59,6 +65,9 @@ import {
const ROOT = resolve(import.meta.dir, "..");
const RUNNER = join(ROOT, "scripts/ubicloud/ubi-runner.sh");
const REMOTE_DIR = "work/gbrain";
+// Written once the checkout is unpacked; setup-ci-vm.sh waits for it before the steps that need the checkout.
+const UNPACKED_MARKER = "work/gbrain.unpacked";
+const SETUP_SCRIPT = join(ROOT, "scripts/ubicloud/setup-ci-vm.sh");
const COMMITTED_WEIGHTS = join(ROOT, "scripts/ubicloud/weights.json");
const LOCAL_WEIGHTS = join(ROOT, ".context/ci-ubicloud/weights.json");
const ALL_LANES = ["gitleaks", "verify", "serial", "slow", "unit", "e2e"] as const;
@@ -69,12 +78,24 @@ const HEAVY_MS = 60_000;
// VMs still in setup count toward heavy spreading for this long after the
// first VM is ready, so the first VM does not claim every long pole.
const HEAVY_SETUP_GRACE_MS = 45_000;
+// Fleet size without --vms: the default when the shared quota is busy, up to
+// BURST_MAX_VMS when it is free, never past BURST_CEILING_VCPUS of the
+// project's 512 (the rest is headroom for pull-request runners `usage` can't see).
+const DEFAULT_VMS = 4;
+const BURST_MAX_VMS = 10;
+const BURST_CEILING_VCPUS = 448;
+// A VM whose slots would each get less than this much weighted work is not worth its setup.
+const MIN_SLOT_WORK_S = 120;
+const vcpusOf = (size: string) => Number(/(\d+)$/.exec(size)?.[1] ?? 16);
interface Opts {
+ /** 0 until sized: --vms N, or the burst decision from `ubi-runner.sh usage`. */
vms: number;
size: string;
slots: number;
location: string;
+ /** A machine image (NAME@VERSION) or "stock". */
+ image: string;
lanes: Set<string>;
diff: boolean;
recordWeights: boolean;
@@ -83,10 +104,11 @@ interface Opts {
function parseArgs(argv: string[]): Opts {
const opts: Opts = {
- vms: 4,
+ vms: 0,
size: "standard-16",
slots: 0,
location: "eu-central-h1",
+ image: process.env.UBI_CI_IMAGE || "stock",
lanes: new Set(ALL_LANES),
diff: false,
recordWeights: false,
@@ -103,6 +125,7 @@ function parseArgs(argv: string[]): Opts {
else if (arg === "--size") opts.size = value();
else if (arg === "--slots") opts.slots = Number(value());
else if (arg === "--location") opts.location = value();
+ else if (arg === "--image") opts.image = value();
else if (arg === "--lanes") opts.lanes = new Set(value().split(","));
else if (arg === "--diff") opts.diff = true;
else if (arg === "--record-weights") opts.recordWeights = true;
@@ -110,18 +133,18 @@ function parseArgs(argv: string[]): Opts {
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.vms) || opts.vms < 1) usage("--vms must be a positive integer");
+ 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
// timing-sensitive files (and that longest file) from starving for CPU.
- if (!opts.slots) opts.slots = Math.max(1, Math.round(Number(/(\d+)$/.exec(opts.size)?.[1] ?? 16) / 2));
+ if (!opts.slots) opts.slots = Math.max(1, Math.round(vcpusOf(opts.size) / 2));
if (!Number.isInteger(opts.slots) || opts.slots < 1) usage("--slots must be a positive integer");
return 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] [--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]");
process.exit(2);
}
@@ -177,6 +200,8 @@ interface Vm {
setupMs?: number;
busySlots: number;
heavy: number;
+ /** Running the machine-level control items; takes no queue items meanwhile. */
+ control: boolean;
}
async function main() {
@@ -233,12 +258,26 @@ async function main() {
const totalItems = queue.length + control.reduce((n, c) => n + Math.max(c.files.length, 1), 0);
const estimate = queue.reduce((s, i) => s + i.weight, 0) / 1000;
log(`${totalItems} items (${Object.entries(inventory).filter(([l]) => opts.lanes.has(l)).map(([l, f]) => `${l} ${f.length}`).join(", ")}, control ${control.map((c) => c.lane).join("+") || "none"}); ~${Math.round(estimate)}s of weighted work`);
- log(`provisioning ${opts.vms} × ${opts.size} in ${opts.location}, ${opts.slots} slots each; logs in ${runDir}`);
+ if (!opts.vms) {
+ const usageReport = await runner(["usage"], { timeoutMs: 120_000 });
+ const decision = burstVms({
+ usedVcpus: usageReport.code === 0 ? parseUsageTotal(usageReport.stdout) : null,
+ vmVcpus: vcpusOf(opts.size),
+ defaultVms: DEFAULT_VMS,
+ maxVms: BURST_MAX_VMS,
+ ceilingVcpus: BURST_CEILING_VCPUS,
+ workVms: Math.max(1, Math.ceil(estimate / (opts.slots * MIN_SLOT_WORK_S))),
+ });
+ 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}`);
- // ── Checkout tarball, packed once ────────────────────────────────────────
+ // ── Checkout tarball, packed once while the VMs boot ─────────────────────
const tarball = join(tmpdir(), `gbrain-ci-ubicloud-${process.pid}.tgz`);
- const packed = await runner(["pack", ROOT], { out: tarball });
- if (packed.code !== 0) throw new Error("packing the checkout failed");
+ const packed = runner(["pack", ROOT], { out: tarball });
+ // Faster create and SSH polling than the runner's interactive default.
+ process.env.UBI_POLL_SECONDS ??= "2";
const bunVersion = process.env.GBRAIN_CI_BUN_TAG
?? /oven\/bun:\$\{GBRAIN_CI_BUN_TAG:-([^}]+)\}/.exec(readFileSync(join(ROOT, "docker-compose.ci.yml"), "utf8"))?.[1]
@@ -254,6 +293,7 @@ async function main() {
infraErrors: 0,
busySlots: 0,
heavy: 0,
+ control: false,
}));
// Memoized: the signal handler and main's finally must await the same
// teardown, or main exits while its `down` calls are still running.
@@ -302,12 +342,13 @@ async function main() {
let controlDone = control.length === 0;
let controlClaimed = false;
let batchSeq = 0;
- const totalSlots = () => vms.filter((vm) => vm.state === "ready").length * opts.slots;
+ const totalSlots = () => vms.filter((vm) => vm.state === "ready" && !vm.control).length * opts.slots;
let firstReadyAt = 0;
const skipHeavy = (vm: Vm) => (item: Item) => {
if (item.weight < HEAVY_MS) return false;
const inGrace = Date.now() - firstReadyAt < HEAVY_SETUP_GRACE_MS;
- const peers = vms.filter((v) => v.state === "ready" || (inGrace && (v.state === "setup" || v.state === "provisioning")));
+ // The control VM holds no heavy items until it joins the pool; counting it would cap every other VM at one.
+ const peers = vms.filter((v) => !v.control && (v.state === "ready" || (inGrace && (v.state === "setup" || v.state === "provisioning"))));
return vm.heavy > Math.min(...peers.map((v) => v.heavy));
};
@@ -365,6 +406,7 @@ async function main() {
};
const runControl = async (vm: Vm) => {
+ vm.control = true;
for (const step of control) {
log(`control on ${vm.name}: ${step.lane}${step.files.length ? ` (${step.files.length} exclusive files, sequential)` : ""}`);
const { parsed, logPath } = await runBatch(vm, 1, step.lane, step.files);
@@ -375,6 +417,7 @@ async function main() {
}
}
controlDone = true;
+ vm.control = false;
};
const vmLifecycle = async (vm: Vm, index: number) => {
@@ -383,7 +426,7 @@ async function main() {
if (tornDown) return;
vm.requested = true;
appendFileSync(ledger, `${vm.name} ${opts.location}\n`);
- const up = await runner(["up", "-n", vm.name, "-s", opts.size, "-l", opts.location], { out: setupLog });
+ const up = await runner(["up", "-n", vm.name, "-s", opts.size, "-l", opts.location, ...(opts.image === "stock" ? [] : ["-b", opts.image])], { out: setupLog });
if (tornDown) return;
if (up.code !== 0) {
vm.state = "failed";
@@ -394,11 +437,19 @@ async function main() {
return;
}
vm.state = "setup";
+ // System packages, Bun and image pulls need no checkout: setup starts now
+ // and waits for the marker the upload writes when it lands.
+ const env = `SLOTS=${opts.slots} BUN_VERSION=${quote(bunVersion)} GITLEAKS=${opts.lanes.has("gitleaks") ? 1 : 0} CHECKOUT=${REMOTE_DIR} CHECKOUT_MARKER=${UNPACKED_MARKER}`;
+ const setupRun = runner(["ssh", vm.name, `${env} bash -s`], { input: SETUP_SCRIPT, out: `${setupLog}.bootstrap`, timeoutMs: 15 * 60 * 1000 });
+ if ((await packed).code !== 0) throw new Error("packing the checkout failed");
const unpack = await runner(["unpack", vm.name, REMOTE_DIR], { input: tarball });
- const env = `SLOTS=${opts.slots} BUN_VERSION=${quote(bunVersion)} GITLEAKS=${opts.lanes.has("gitleaks") ? 1 : 0}`;
- const setup = unpack.code === 0
- ? await runner(["ssh", vm.name, `cd ${REMOTE_DIR} && ${env} bash scripts/ubicloud/setup-ci-vm.sh`], { out: `${setupLog}.bootstrap`, timeoutMs: 15 * 60 * 1000 })
- : unpack;
+ const marked = unpack.code === 0 ? await runner(["ssh", vm.name, `touch ${UNPACKED_MARKER}`]) : unpack;
+ if (marked.code !== 0) {
+ vm.state = "failed";
+ log(`VM ${vm.name} checkout upload failed: ${marked.stdout.trim().split("\n").slice(-2).join(" | ")}`);
+ return;
+ }
+ const setup = await setupRun;
if (setup.code !== 0) {
vm.state = "failed";
log(`VM ${vm.name} setup failed (see ${setupLog}.bootstrap)`);
diff --git a/scripts/ubicloud/build-ci-image.sh b/scripts/ubicloud/build-ci-image.sh
new file mode 100755
index 0000000000..3c7eaec7a2
--- /dev/null
+++ b/scripts/ubicloud/build-ci-image.sh
@@ -0,0 +1,55 @@
+#!/usr/bin/env bash
+# scripts/ubicloud/build-ci-image.sh — build or refresh the `gbrain-ci`
+# Ubicloud machine image, which `ci:ubicloud --image gbrain-ci@latest` (or
+# UBI_CI_IMAGE) boots instead of stock Ubuntu so setup skips apt.
+#
+# UBI_OWNER=gbra40 bash scripts/ubicloud/build-ci-image.sh [-l LOCATION] [-n IMAGE]
+#
+# Boots a stock Ubuntu 24.04 VM (standard-2 with 40 GiB, the largest disk a
+# machine image accepts), runs `PREPARE_IMAGE=1 setup-ci-vm.sh` (the apt
+# packages and both database images, nothing from the checkout), stops it and
+# captures it as a new version of IMAGE, which becomes IMAGE@latest. The
+# source VM is destroyed after capture. Rerun it when setup-ci-vm.sh's package
+# list or images change; setup still pulls the floating image tags on every
+# VM, so a stale image costs time, not correctness. To delete the image,
+# destroy each version (`ubi-runner.sh cli mi LOCATION/IMAGE destroy-version
+# -f VERSION`), then the image (`... destroy -f`).
+set -euo pipefail
+
+cd "$(dirname "$0")/../.."
+RUNNER=scripts/ubicloud/ubi-runner.sh
+location=${UBI_LOCATION:-eu-central-h1}
+image=gbrain-ci
+while [ $# -gt 0 ]; do
+ case $1 in
+ -l|--location) location=$2; shift 2 ;;
+ -n|--name) image=$2; shift 2 ;;
+ *) echo "build-ci-image: unknown option $1" >&2; exit 2 ;;
+ esac
+done
+
+name=$(bash "$RUNNER" up -s standard-2 -S 40 -l "$location" | tail -1)
+# Capture destroys the source VM; down confirms it is gone either way.
+trap '[ -z "${name:-}" ] || bash "$RUNNER" down "$name" -l "$location"' EXIT
+bash "$RUNNER" ssh "$name" 'PREPARE_IMAGE=1 bash -s' <scripts/ubicloud/setup-ci-vm.sh
+bash "$RUNNER" cli vm "$location/$name" stop >/dev/null
+for _ in $(seq 1 120); do
+ [ "$(bash "$RUNNER" cli vm "$location/$name" show | sed -n 's/^state: //p')" = stopped ] && break
+ sleep 3
+done
+if bash "$RUNNER" cli mi list | awk -v l="$location" -v n="$image" '$1 == l && $2 == n { found = 1 } END { exit !found }'; then
+ bash "$RUNNER" cli mi "$location/$image" create-version -d "$name"
+else
+ bash "$RUNNER" cli mi "$location/$image" create -d "$name"
+fi
+for _ in $(seq 1 200); do
+ versions=$(bash "$RUNNER" cli mi "$location/$image" list-versions)
+ if awk '$NF == "true" && $3 == "ready" { found = 1 } END { exit !found }' <<<"$versions"; then
+ echo "$versions"
+ echo "build-ci-image: $location/$image@latest is ready"
+ exit 0
+ fi
+ sleep 6
+done
+echo "build-ci-image: $location/$image did not become ready; check: $RUNNER cli mi $location/$image list-versions" >&2
+exit 1
diff --git a/scripts/ubicloud/schedule.ts b/scripts/ubicloud/schedule.ts
index a7ce4373aa..8f6af07b2d 100644
--- a/scripts/ubicloud/schedule.ts
+++ b/scripts/ubicloud/schedule.ts
@@ -122,3 +122,41 @@ export function parseItemLog(log: string): ItemResult[] {
}
return results;
}
+
+/** The project's total vCPUs from `ubi-runner.sh usage` (its `total VMS VCPUS` row), or null. */
+export function parseUsageTotal(report: string): number | null {
+ const total = /^total\s+\d+\s+(\d+)\s*$/m.exec(report);
+ return total ? Number(total[1]) : null;
+}
+
+export interface FleetOpts {
+ /** vCPUs the project's VMs hold now; null when usage could not be read. */
+ usedVcpus: number | null;
+ vmVcpus: number;
+ defaultVms: number;
+ maxVms: number;
+ /** Never push the project's VM vCPUs past this. */
+ ceilingVcpus: number;
+ /** VMs the run's work can keep busy. */
+ workVms: number;
+}
+
+/**
+ * Burst sizing: as many VMs as fit under the ceiling, between the default and
+ * the burst maximum, and no more than the work can use. A busy project gets the
+ * default; a VM the quota then refuses just shrinks the fleet.
+ */
+export function burstVms(o: FleetOpts): { vms: number; reason: string } {
+ if (o.usedVcpus === null) {
+ const vms = Math.min(o.defaultVms, o.workVms);
+ return { vms, reason: `project usage unreadable, using ${vms} VM(s)` };
+ }
+ const fit = Math.floor((o.ceilingVcpus - o.usedVcpus) / o.vmVcpus);
+ const target = Math.max(o.defaultVms, Math.min(o.maxVms, fit));
+ const vms = Math.max(1, Math.min(o.workVms, target));
+ const why = vms < target ? "all the work can use"
+ : fit >= o.maxVms ? `burst maximum ${o.maxVms}`
+ : fit > o.defaultVms ? `room for ${fit} under the ceiling`
+ : `quota busy, default ${o.defaultVms}`;
+ return { vms, reason: `project VMs hold ${o.usedVcpus} vCPUs, ceiling ${o.ceilingVcpus}: ${vms} VM(s) × ${o.vmVcpus} vCPUs (${why})` };
+}
diff --git a/scripts/ubicloud/setup-ci-vm.sh b/scripts/ubicloud/setup-ci-vm.sh
index 42c5dedc5c..ad2be68a6b 100755
--- a/scripts/ubicloud/setup-ci-vm.sh
+++ b/scripts/ubicloud/setup-ci-vm.sh
@@ -1,11 +1,11 @@
#!/usr/bin/env bash
# scripts/ubicloud/setup-ci-vm.sh — bootstrap one Ubicloud VM for
-# scripts/ci-ubicloud.ts. Runs as user `ubi` (passwordless sudo) inside the
-# synced checkout on a stock Ubuntu 24.04 image.
+# scripts/ci-ubicloud.ts. Runs as user `ubi` (passwordless sudo) on a stock
+# Ubuntu 24.04 image.
#
# Provides what the ci:local runner container provides, per VM:
# - bun (pinned; BUN_VERSION, matching docker-compose.ci.yml's runner tag)
-# - git, python3, procps, psql, jq, node, timeout (test prerequisites)
+# - git, python3, procps, psql, jq, node, cc, timeout (test prerequisites)
# - SLOTS isolated pgvector/pgvector:pg16 servers, each fronted by a
# transaction-mode PgBouncer, so every E2E slot owns its whole server just
# as each ci:local shard owns postgres-N (slot i: postgres on
@@ -14,13 +14,29 @@
# - frozen dependencies and both PGLite snapshot fixtures, built once
# - gitleaks (GITLEAKS=1; pinned + checksum-verified like test.yml)
#
-# Knobs: SLOTS (default nproc), BUN_VERSION (default 1.4.2), GITLEAKS=0|1.
+# Every step starts as soon as its inputs exist: apt, the Bun and gitleaks
+# downloads and the image pulls need no checkout, so scripts/ci-ubicloud.ts
+# streams this script over SSH (`bash -s`) while the checkout is still
+# uploading, with CHECKOUT_MARKER naming the file it writes once the checkout
+# is unpacked. Run from inside a checkout with no marker, it starts at once.
+#
+# On a VM booted from the gbrain-ci machine image (scripts/ubicloud/build-ci-image.sh)
+# the packages are already installed, so apt is skipped and the image pulls
+# only confirm the baked images are current.
+#
+# Knobs: SLOTS (default nproc), BUN_VERSION (default 1.4.2), GITLEAKS=0|1,
+# CHECKOUT (default .), CHECKOUT_MARKER (default: none, checkout present),
+# PREPARE_IMAGE=1 (install packages and pull images only, then reset
+# cloud-init so the stopped VM can be captured as a machine image).
set -euo pipefail
SLOTS="${SLOTS:-$(nproc)}"
BUN_VERSION="${BUN_VERSION:-1.4.2}"
GITLEAKS="${GITLEAKS:-0}"
+CHECKOUT="${CHECKOUT:-.}"
+CHECKOUT_MARKER="${CHECKOUT_MARKER:-}"
GITLEAKS_VERSION=8.30.1
+APT_PACKAGES=(git ca-certificates python3 procps postgresql-client jq nodejs gcc libc6-dev)
PG_IMAGE=pgvector/pgvector:pg16
PGBOUNCER_IMAGE=edoburu/pgbouncer:latest
# Throwaway password of the loopback-only test servers (docker-compose.ci.yml uses the same).
@@ -28,26 +44,84 @@ PG_PASSWORD=postgres
t0=$(date +%s)
step() { echo "[setup-ci-vm +$(( $(date +%s) - t0 ))s] $*"; }
+fail() { echo "[setup-ci-vm] $*" >&2; exit 1; }
# scripts/ci-ubicloud.ts multiplexes every slot's commands over one SSH
# connection; sshd's default MaxSessions (10) would refuse slots 11+.
echo "MaxSessions 256" | sudo tee /etc/ssh/sshd_config.d/99-gbrain-ci.conf >/dev/null
sudo systemctl reload ssh
-export DEBIAN_FRONTEND=noninteractive
+# apt on a throwaway VM: no fsync per package, no man-db rebuild, no
+# needrestart scan, and no translation, AppStream or command-not-found indexes.
+echo force-unsafe-io | sudo tee /etc/dpkg/dpkg.cfg.d/99-gbrain-ci >/dev/null
+sudo rm -f /var/lib/man-db/auto-update
+apt_get() {
+ sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_SUSPEND=1 apt-get -qq \
+ -o Acquire::Languages=none -o APT::Update::Post-Invoke-Success= \
+ -o Acquire::IndexTargets::deb::DEP-11::DefaultEnabled=false \
+ -o Acquire::IndexTargets::deb::DEP-11-icons::DefaultEnabled=false \
+ -o Acquire::IndexTargets::deb::DEP-11-icons-small::DefaultEnabled=false \
+ -o Acquire::IndexTargets::deb::CNF::DefaultEnabled=false "$@" >/dev/null
+}
+
+# Docker first so the image pulls overlap the rest of apt. Containers start
+# only once apt is done: a package's systemd reload while Docker creates a
+# container's scope unit fails the `docker run` ("Message recipient
+# disconnected from message bus").
+install_system() {
+ local pg_pull pgb_pull bin baked=1
+ for bin in docker psql node cc jq git; do command -v "$bin" >/dev/null || baked=0; done
+ if [ "$baked" = 1 ]; then
+ sudo docker pull -q "$PG_IMAGE" >/dev/null
+ sudo docker pull -q "$PGBOUNCER_IMAGE" >/dev/null
+ return
+ fi
+ apt_get update
+ apt_get install -y --no-install-recommends docker.io
+ sudo docker pull -q "$PG_IMAGE" >/dev/null &
+ pg_pull=$!
+ sudo docker pull -q "$PGBOUNCER_IMAGE" >/dev/null &
+ pgb_pull=$!
+ apt_get install -y --no-install-recommends "${APT_PACKAGES[@]}"
+ wait "$pg_pull"
+ wait "$pgb_pull"
+}
+
+if [ "${PREPARE_IMAGE:-0}" = "1" ]; then
+ install_system
+ sudo apt-get clean
+ sudo cloud-init clean --logs
+ step "image prepared"
+ exit 0
+fi
+
(
- sudo apt-get update -qq >/dev/null
- sudo apt-get install -y -qq --no-install-recommends \
- docker.io git ca-certificates python3 procps postgresql-client jq nodejs build-essential >/dev/null
-) &
-apt_pid=$!
+ install_system
+ sudo docker network create gbrain-ci >/dev/null 2>&1 || true
+ for i in $(seq 1 "$SLOTS"); do
+ sudo docker run -d --name "pg-$i" --network gbrain-ci \
+ -p "127.0.0.1:$((15432 + i)):5432" \
+ -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD="$PG_PASSWORD" -e POSTGRES_DB=gbrain_test \
+ "$PG_IMAGE" -c fsync=off -c synchronous_commit=off -c full_page_writes=off >/dev/null
+ done
+ for i in $(seq 1 "$SLOTS"); do
+ # Same pooler settings as docker-compose.ci.yml's pgbouncer service.
+ sudo docker run -d --name "pgb-$i" --network gbrain-ci \
+ -p "127.0.0.1:$((16432 + i)):5432" \
+ -e DB_HOST="pg-$i" -e DB_PORT=5432 -e DB_USER=postgres -e DB_PASSWORD="$PG_PASSWORD" \
+ -e POOL_MODE=transaction -e AUTH_TYPE=plain -e MAX_CLIENT_CONN=200 -e DEFAULT_POOL_SIZE=10 \
+ -e IGNORE_STARTUP_PARAMETERS=extra_float_digits,statement_timeout,idle_in_transaction_session_timeout,search_path \
+ "$PGBOUNCER_IMAGE" >/dev/null
+ done
+) >/tmp/gbrain-system.log 2>&1 &
+system_pid=$!
# bun ships as a zip; python3's zipfile avoids waiting on apt for unzip.
(
arch=x64
[ "$(uname -m)" = aarch64 ] && arch=aarch64
tmp=$(mktemp -d)
- curl -fsSL -o "$tmp/bun.zip" "https://github.com/oven-sh/bun/releases/download/bun-v${BUN_VERSION}/bun-linux-${arch}.zip"
+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 1 -o "$tmp/bun.zip" "https://github.com/oven-sh/bun/releases/download/bun-v${BUN_VERSION}/bun-linux-${arch}.zip"
python3 -m zipfile -e "$tmp/bun.zip" "$tmp"
mkdir -p "$HOME/.bun/bin"
install -m 755 "$tmp/bun-linux-${arch}/bun" "$HOME/.bun/bin/bun"
@@ -61,8 +135,8 @@ if [ "$GITLEAKS" = "1" ]; then
base="gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz"
url="https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}"
tmp=$(mktemp -d)
- curl -fsSL -o "$tmp/$base" "$url/$base"
- curl -fsSL -o "$tmp/checksums.txt" "$url/gitleaks_${GITLEAKS_VERSION}_checksums.txt"
+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 1 -o "$tmp/$base" "$url/$base"
+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 1 -o "$tmp/checksums.txt" "$url/gitleaks_${GITLEAKS_VERSION}_checksums.txt"
( cd "$tmp" && grep " ${base}\$" checksums.txt | sha256sum -c - >/dev/null )
tar -xzf "$tmp/$base" -C "$tmp" gitleaks
sudo install "$tmp/gitleaks" /usr/local/bin/gitleaks
@@ -74,40 +148,24 @@ fi
wait "$bun_pid"
export PATH="$HOME/.bun/bin:$PATH"
step "bun $(bun --version)"
+
+if [ -n "$CHECKOUT_MARKER" ]; then
+ for _ in $(seq 1 1200); do [ -e "$CHECKOUT_MARKER" ] && break; sleep 0.25; done
+ [ -e "$CHECKOUT_MARKER" ] || fail "checkout never arrived ($CHECKOUT_MARKER)"
+ step "checkout unpacked"
+fi
+cd "$CHECKOUT"
bun install --frozen-lockfile >/tmp/gbrain-bun-install.log 2>&1 || { tail -40 /tmp/gbrain-bun-install.log; exit 1; }
step "dependencies installed"
-wait "$apt_pid"
-step "apt packages installed"
-git config --global --add safe.directory '*'
-
-sudo docker pull -q "$PG_IMAGE" >/dev/null &
-pg_pull=$!
-sudo docker pull -q "$PGBOUNCER_IMAGE" >/dev/null &
-pgb_pull=$!
-
-# Snapshot builds overlap the image pulls. Both are idempotent and hash-keyed.
+# Snapshot builds overlap the system packages and image pulls. Both are idempotent and hash-keyed.
bun run build:pglite-snapshot >/tmp/gbrain-snapshot.log 2>&1 || { tail -40 /tmp/gbrain-snapshot.log; exit 1; }
bun run build:pglite-snapshot --profile default >>/tmp/gbrain-snapshot.log 2>&1 || { tail -40 /tmp/gbrain-snapshot.log; exit 1; }
step "PGLite snapshots built"
-wait "$pg_pull" "$pgb_pull"
-sudo docker network create gbrain-ci >/dev/null 2>&1 || true
-for i in $(seq 1 "$SLOTS"); do
- sudo docker run -d --name "pg-$i" --network gbrain-ci \
- -p "127.0.0.1:$((15432 + i)):5432" \
- -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD="$PG_PASSWORD" -e POSTGRES_DB=gbrain_test \
- "$PG_IMAGE" -c fsync=off -c synchronous_commit=off -c full_page_writes=off >/dev/null
-done
-for i in $(seq 1 "$SLOTS"); do
- # Same pooler settings as docker-compose.ci.yml's pgbouncer service.
- sudo docker run -d --name "pgb-$i" --network gbrain-ci \
- -p "127.0.0.1:$((16432 + i)):5432" \
- -e DB_HOST="pg-$i" -e DB_PORT=5432 -e DB_USER=postgres -e DB_PASSWORD="$PG_PASSWORD" \
- -e POOL_MODE=transaction -e AUTH_TYPE=plain -e MAX_CLIENT_CONN=200 -e DEFAULT_POOL_SIZE=10 \
- -e IGNORE_STARTUP_PARAMETERS=extra_float_digits,statement_timeout,idle_in_transaction_session_timeout,search_path \
- "$PGBOUNCER_IMAGE" >/dev/null
-done
+wait "$system_pid" || { tail -40 /tmp/gbrain-system.log >&2; fail "system packages or database containers failed"; }
+step "apt packages installed, database containers started"
+git config --global --add safe.directory '*'
for i in $(seq 1 "$SLOTS"); do
for _ in $(seq 1 120); do
PGPASSWORD="$PG_PASSWORD" psql -h 127.0.0.1 -p "$((15432 + i))" -U postgres -d gbrain_test -Atc 'select 1' >/dev/null 2>&1 && break
diff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.sh
index ea4447fd95..fc054ad515 100755
--- a/scripts/ubicloud/ubi-runner.sh
+++ b/scripts/ubicloud/ubi-runner.sh
@@ -355,20 +355,43 @@ cmd_down() {
done
}
+# slim_git SRC DIR: build DIR/.git holding only the objects HEAD and
+# origin/master reach, with SRC's branch, index and config, so a checkout that
+# fetched many branches does not upload all of them to every VM. Fails (and
+# the caller ships SRC's own .git) on anything unexpected.
+slim_git() {
+ local src=$1 dir=$2 git_dir common branch specs
+ git_dir=$(git -C "$src" rev-parse --absolute-git-dir) || return 1
+ common=$(cd "$src" && cd "$(git rev-parse --git-common-dir)" && pwd) || return 1
+ branch=$(git -C "$src" symbolic-ref -q HEAD) || branch=""
+ specs=("+HEAD:${branch:-refs/heads/ubi-pack-head}")
+ if git -C "$src" rev-parse -q --verify refs/remotes/origin/master >/dev/null; then
+ specs+=("+refs/remotes/origin/master:refs/remotes/origin/master")
+ fi
+ git init -q "$dir" &&
+ git -C "$dir" fetch -q --update-shallow --no-tags --no-write-fetch-head "$src" "${specs[@]}" &&
+ cp "$common/config" "$dir/.git/config" &&
+ { [ ! -f "$git_dir/index" ] || cp "$git_dir/index" "$dir/.git/index"; } &&
+ if [ -n "$branch" ]; then git -C "$dir" symbolic-ref HEAD "$branch"; else git -C "$dir" update-ref --no-deref HEAD "$(git -C "$src" rev-parse HEAD)"; fi
+}
+
# pack SRC: write a gzipped checkout tarball to stdout (tracked + untracked
-# files that are not ignored, plus .git; a non-git directory is taken whole).
+# files that are not ignored, plus a slim .git; a non-git directory is taken whole).
cmd_pack() {
- local src
+ local src tmp
src=$(cd "${1:-.}" && pwd)
if git -C "$src" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
+ tmp=$(mktemp -d)
(
cd "$src"
- { git ls-files -z -co --exclude-standard; printf '.git\0'; } \
+ if slim_git "$src" "$tmp/repo" >&2; then git_from=(-C "$tmp/repo" .git); else git_from=(.git); fi
+ git ls-files -z -co --exclude-standard \
| while IFS= read -r -d '' f; do
- if [ -e "$f" ] || [ -L "$f" ]; then printf '%s\0' "$f"; fi
+ if { [ -e "$f" ] || [ -L "$f" ]; } && [ "$f" != .git ]; then printf '%s\0' "$f"; fi
done \
- | tar --null -T - -czf -
+ | tar --null -T - "${git_from[@]}" -czf -
)
+ rm -rf "$tmp"
else
tar -C "$src" -czf - .
fi
@@ -471,7 +494,7 @@ usage: ubi-runner.sh <command> [args]
create a VM and wait for SSH; prints its name
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
+ pack [SRC] write that checkout tarball to stdout (with a slim .git: HEAD + origin/master)
unpack NAME DEST extract a tarball from stdin into DEST on the VM
pull NAME REMOTE_GLOB LOCAL_DIR
copy matching remote entries into LOCAL_DIR
diff --git a/test/scripts/ci-ubicloud-schedule.test.ts b/test/scripts/ci-ubicloud-schedule.test.ts
index 9ebbdda08f..8f2a1f6fb8 100644
--- a/test/scripts/ci-ubicloud-schedule.test.ts
+++ b/test/scripts/ci-ubicloud-schedule.test.ts
@@ -1,7 +1,8 @@
// ci-ubicloud-schedule.test.ts — the Ubicloud fan-out's work queue:
// weighting (trusted tables first, lane p75 fallback), heaviest-first
-// same-lane batching with a draining batch target, marker-log parsing, and
-// the explicit-file seams the ci:local wrappers expose for it.
+// same-lane batching with a draining batch target, marker-log parsing, burst
+// fleet sizing from `ubi-runner.sh usage`, and the explicit-file seams the
+// ci:local wrappers expose for it.
import { describe, expect, it } from "bun:test";
import { execFileSync } from "node:child_process";
@@ -10,7 +11,9 @@ import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import {
buildItems,
+ burstVms,
parseItemLog,
+ parseUsageTotal,
readWeightTable,
sortQueue,
takeBatch,
@@ -103,6 +106,34 @@ describe("parseItemLog", () => {
});
});
+describe("burst fleet sizing", () => {
+ const fleet = { vmVcpus: 16, defaultVms: 4, maxVms: 8, ceilingVcpus: 448, workVms: 100 };
+
+ it("reads the project total from the usage report", () => {
+ const report = "OWNER VMS VCPUS\ngbra40 4 64\ngbra49 1 16\ntotal 5 80\n";
+ expect(parseUsageTotal(report)).toBe(80);
+ expect(parseUsageTotal("ubi-runner: request failed")).toBeNull();
+ });
+
+ it("bursts to the maximum when the quota is free", () => {
+ expect(burstVms({ ...fleet, usedVcpus: 80 }).vms).toBe(8);
+ expect(burstVms({ ...fleet, usedVcpus: 0 }).reason).toContain("burst maximum 8");
+ });
+
+ it("never pushes the project past the ceiling, and falls back to the default when busy", () => {
+ expect(burstVms({ ...fleet, usedVcpus: 320 }).vms).toBe(8);
+ expect(burstVms({ ...fleet, usedVcpus: 352 }).vms).toBe(6);
+ expect(burstVms({ ...fleet, usedVcpus: 400 }).vms).toBe(4);
+ expect(burstVms({ ...fleet, usedVcpus: 500 }).reason).toContain("quota busy, default 4");
+ });
+
+ it("uses the default when usage cannot be read, and never more VMs than the work fills", () => {
+ expect(burstVms({ ...fleet, usedVcpus: null }).vms).toBe(4);
+ expect(burstVms({ ...fleet, usedVcpus: 0, workVms: 1 })).toMatchObject({ vms: 1 });
+ expect(burstVms({ ...fleet, usedVcpus: null, workVms: 2 }).vms).toBe(2);
+ });
+});
+
describe("readWeightTable", () => {
it("scales and prefixes lane weight files, and treats a missing file as empty", () => {
const dir = mkdtempSync(join(tmpdir(), "ubi-weights-"));