Skip to content

An open-source, faster Devin alternative

TypeScript

perf: restore the shard pin + placement probe, and stop the warm path failing in silence

Brian Reardona02f888d4893
diff --git a/benchmarks/tti/bench.mjs b/benchmarks/tti/bench.mjs
index f8a501cf..6962c7b7 100644
--- a/benchmarks/tti/bench.mjs
+++ b/benchmarks/tti/bench.mjs
@@ -75,15 +75,83 @@ function withTimeout(promise, ms, label) {
return Promise.race([promise, timeout]).finally(() => clearTimeout(t));
}
+// ---- teardown ledger ------------------------------------------------------
+//
+// Every sandbox this process has ever been handed, minus the ones confirmed
+// destroyed. It exists because a benchmark that leaks boxes silently corrupts
+// every measurement taken after it, including its own later modes.
+//
+// The leak this closes is specifically the timed-out create. withTimeout only
+// abandons OUR promise — the create it raced is still running server-side, and
+// the sandbox it eventually returns lands in a resolved promise nobody is
+// holding. Those boxes were never destroyed and never even counted. A burst of
+// 100 could pin the cell at its box budget, at which point creates stop being
+// served from warm stock and fall through to rate-limited cold launches, and
+// the run measures that instead of what it meant to. Registering off the
+// ORIGINAL promise (not the raced one) is what makes a late arrival reachable.
+const outstanding = new Map(); // sandboxId -> sandbox handle
+
+function register(sandbox) {
+ const id = sandbox?.sandboxId ?? sandbox?.id;
+ if (id) outstanding.set(id, sandbox);
+ return sandbox;
+}
+
+/** Destroy with retries. Resolves true only when the box is confirmed gone. */
+async function destroySandbox(sandbox, attempts = 3) {
+ const id = sandbox?.sandboxId ?? sandbox?.id;
+ for (let i = 0; i < attempts; i++) {
+ try {
+ await withTimeout(sandbox.destroy(), DESTROY_TIMEOUT_MS, 'destroy timed out');
+ if (id) outstanding.delete(id);
+ return true;
+ } catch {
+ if (i < attempts - 1) await sleep(250 * (i + 1));
+ }
+ }
+ return false;
+}
+
+/**
+ * Destroy anything still outstanding. Called after every mode and once more on
+ * exit, so a leak has to survive both to escape — and if it does, it is printed
+ * with its ids rather than swallowed, because the next run needs to know the
+ * pool it is measuring against is short.
+ */
+async function sweepOutstanding(where) {
+ if (outstanding.size === 0) return;
+ const handles = [...outstanding.values()];
+ process.stdout.write(`\n sweeping ${handles.length} undestroyed sandbox(es) after ${where}...\n`);
+ const q = [...handles];
+ await Promise.all(
+ Array.from({ length: 16 }, async () => {
+ for (;;) {
+ const sb = q.pop();
+ if (!sb) return;
+ await destroySandbox(sb);
+ }
+ }),
+ );
+ if (outstanding.size > 0) {
+ process.stdout.write(
+ ` LEAKED ${outstanding.size} sandbox(es) — these boxes are still running and hold pool budget:\n` +
+ ` ${[...outstanding.keys()].join(' ')}\n` +
+ ` Reclaim them with: go run ./cmd/mvmwipe -state RUNNING -apply\n`,
+ );
+ }
+}
+
/** One TTI iteration: create -> node -v (exit 0) -> destroy (untimed). */
async function ttiTask() {
const compute = opencomputer({ apiKey: API_KEY, apiUrl: API_URL });
const start = performance.now();
- const sandbox = await withTimeout(
- compute.sandbox.create({ timeout: KEEP_ALIVE_MS }),
- CREATE_TIMEOUT_MS,
- 'create timed out',
- );
+ // Register off the underlying promise so a create that outruns our timeout is
+ // still swept. Attaching to the raced promise instead would lose exactly the
+ // sandboxes most likely to leak.
+ const creating = compute.sandbox.create({ timeout: KEEP_ALIVE_MS });
+ creating.then(register).catch(() => {});
+ const sandbox = await withTimeout(creating, CREATE_TIMEOUT_MS, 'create timed out');
+ register(sandbox);
try {
const res = await withTimeout(sandbox.runCommand('node -v'), COMMAND_TIMEOUT_MS, 'command timed out');
if (res.exitCode !== 0) {
@@ -91,7 +159,7 @@ async function ttiTask() {
}
return performance.now() - start;
} finally {
- await withTimeout(sandbox.destroy(), DESTROY_TIMEOUT_MS, 'destroy timed out').catch(() => {});
+ await destroySandbox(sandbox);
}
}
@@ -131,6 +199,9 @@ async function runMode(label, { iterations, concurrency, staggerDelayMs }) {
if (staggerDelayMs > 0 && i < iterations - 1) await sleep(staggerDelayMs);
}
await Promise.all(queue);
+ // Between modes, not just at exit: a mode that leaks must not hand the next
+ // mode a depleted pool and have its result read as a regression.
+ await sweepOutstanding(label);
return summarize(label, { iterations, oks, fails });
}
@@ -230,11 +301,115 @@ for (const m of toRun) {
}
}
+// ---- preflight ------------------------------------------------------------
+//
+// Every precondition below is load-bearing for the number this prints, and each
+// one has already produced a wrong answer at least once by failing quietly. The
+// rule here is: a run that cannot be compared to the reference must ABORT, not
+// print a number that looks comparable.
+//
+// The reference is TTI p50=308 p90=457 p95=521 p99=564, burst-100 from IAD
+// against a pool confirmed at >=144 reserved, with the agent channel live on
+// 100/100 execs. Anything that silently breaks one of those makes this bench a
+// measurement of the breakage instead.
+const REQUIRE_POOL = Number(flag('require-pool', 'REQUIRE_POOL', '0'));
+
+async function preflight() {
+ const problems = [];
+
+ // 1. The adapter must actually be the leaderboard's. A local shim or a stale
+ // node_modules measures something nobody else will ever run.
+ let adapterVersion = 'unknown';
+ try {
+ const { createRequire } = await import('node:module');
+ const req = createRequire(import.meta.url);
+ adapterVersion = req('@computesdk/opencomputer/package.json').version;
+ } catch {
+ problems.push('cannot resolve @computesdk/opencomputer — is node_modules installed?');
+ }
+
+ // 2. Connection prewarm. Without it the first create in a burst pays TLS +
+ // HTTP/2 setup and the whole distribution shifts; with it the cost is paid
+ // at import. Which of the two we are measuring must never be a surprise —
+ // a silently-absent prewarm was worth hundreds of ms and went unnoticed
+ // for a month.
+ let prewarm = 'absent';
+ try {
+ const { createRequire } = await import('node:module');
+ const req = createRequire(import.meta.url);
+ const fs = await import('node:fs');
+ const path = await import('node:path');
+ const sdkPkg = req.resolve('@opencomputer/sdk/package.json');
+ const dist = path.join(path.dirname(sdkPkg), 'dist');
+ const hit = ['sandbox.js', 'http2.js'].every(
+ (f) => fs.existsSync(path.join(dist, f)) && fs.readFileSync(path.join(dist, f), 'utf8').includes('prewarmConnections'),
+ );
+ prewarm = hit ? 'present' : 'absent';
+ } catch {
+ prewarm = 'unknown';
+ }
+
+ // 3. Pool depth. This is the one that invalidated an entire measurement
+ // session: a burst against a depleted pool does not measure create latency
+ // at all, it measures the cold-launch rate limit behind it, and the result
+ // is a plausible-looking number that is simply about something else.
+ // Opt-in because it needs an admin endpoint the public bench has no
+ // business calling.
+ let poolDepth = null;
+ if (REQUIRE_POOL > 0) {
+ try {
+ const r = await fetch(`${API_URL}/api/internal/pool/depth`, { headers: { 'X-API-Key': API_KEY } });
+ const j = await r.json();
+ poolDepth = Number(j.reserved ?? j.depth ?? NaN);
+ if (!Number.isFinite(poolDepth)) problems.push(`pool depth endpoint returned no usable count: ${JSON.stringify(j)}`);
+ else if (poolDepth < REQUIRE_POOL) problems.push(`pool depth ${poolDepth} < required ${REQUIRE_POOL} — burst would measure cold launches, not create`);
+ } catch (e) {
+ problems.push(`pool depth check failed: ${e?.message || e} (unset REQUIRE_POOL to skip)`);
+ }
+ }
+
+ console.log(
+ `preflight: adapter=${adapterVersion} sdk-prewarm=${prewarm}` +
+ (poolDepth !== null ? ` pool-reserved=${poolDepth}` : ' pool-check=skipped'),
+ );
+ if (prewarm !== 'present') {
+ console.log(` NOTE: SDK connection prewarm is ${prewarm} — create p50 will include per-connection setup.`);
+ }
+ if (REQUIRE_POOL <= 0) {
+ console.log(' NOTE: pool-depth check skipped. Set REQUIRE_POOL=144 to refuse to run against a depleted pool.');
+ }
+ if (problems.length > 0) {
+ console.error('\nABORT — preconditions for a comparable run are not met:');
+ for (const p of problems) console.error(` - ${p}`);
+ console.error('\nRefusing to print a score that cannot be compared to the reference run.');
+ process.exit(3);
+ }
+}
+
+await preflight();
+
console.log(`OpenComputer TTI bench → ${API_URL} (key ${API_KEY.slice(0, 6)}…) modes=[${toRun.join(', ')}]`);
+// Ctrl-C is the most likely way this run ends with boxes outstanding, and it was
+// previously the way they were guaranteed to leak. One pass only — a second
+// signal exits immediately rather than trapping someone in a sweep.
+let interrupted = false;
+process.on('SIGINT', async () => {
+ if (interrupted) process.exit(130);
+ interrupted = true;
+ process.stdout.write('\ninterrupted — destroying outstanding sandboxes (Ctrl-C again to abandon them)\n');
+ await sweepOutstanding('interrupt');
+ process.exit(130);
+});
+
const results = [];
-for (const m of toRun) {
- results.push(await runMode(m, MODES[m]));
+try {
+ for (const m of toRun) {
+ results.push(await runMode(m, MODES[m]));
+ }
+} finally {
+ // A crash mid-run must not leave the pool short for whatever runs next.
+ await sweepOutstanding('exit');
}
printSummary(results);
@@ -243,3 +418,12 @@ if (JSON_OUT) {
fs.writeFileSync(JSON_OUT, JSON.stringify({ apiUrl: API_URL, results }, null, 2));
console.log(`\nwrote raw results → ${JSON_OUT}`);
}
+
+// A leak is a failed run even when the numbers look fine, because the damage is
+// to whatever measures next: those boxes hold pool budget until something
+// reclaims them. Exiting non-zero is what stops a scripted sequence of runs from
+// stacking leak on leak, which is exactly how a 308ms baseline became a 3.1s one.
+if (outstanding.size > 0) {
+ console.error(`\nFAIL: ${outstanding.size} sandbox(es) leaked — the pool is now short by that many.`);
+ process.exit(1);
+}
diff --git a/cloudflare-workers/api-edge/src/pool_stock.test.ts b/cloudflare-workers/api-edge/src/pool_stock.test.ts
index 5619a382..cc55d22c 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.test.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.test.ts
@@ -45,6 +45,31 @@ const ORG_A = "11111111-1111-4111-8111-111111111111";
interface ReserveBox {
sandboxID: string;
workerID: string;
+ endpoint?: string;
+ token?: string;
+ port?: number;
+}
+
+/**
+ * Stands in for the MICROVM_SESSIONS namespace, recording every attach.
+ *
+ * The attach count per box is the thing under test: it used to be exactly one
+ * for a box's entire life, which made the warm path depend on that single call
+ * landing at a moment when the box happened to be ready.
+ */
+class FakeSessions {
+ attaches: string[] = [];
+ idFromName(name: string): string {
+ return name;
+ }
+ get(id: string): { fetch: (url: string, init?: RequestInit) => Promise<Response> } {
+ return {
+ fetch: async (url: string) => {
+ if (url.includes("/attach")) this.attaches.push(id);
+ return Response.json({ ok: true });
+ },
+ };
+ }
}
/** Records every origin call the DO makes, and controls what edge-reserve returns. */
@@ -74,12 +99,13 @@ class FakeOrigin {
};
}
-function makeDO(origin: FakeOrigin, target = "4", lowWater = "1") {
+function makeDO(origin: FakeOrigin, target = "4", lowWater = "1", sessions?: FakeSessions) {
const state = new FakeState();
const env = {
SESSION_JWT_SECRET: "test-secret",
POOL_STOCK_TARGET: target,
POOL_STOCK_LOW_WATER: lowWater,
+ MICROVM_SESSIONS: sessions,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const doInstance = new PoolStock(state as any, env as any);
@@ -126,6 +152,52 @@ describe("PoolStock", () => {
vi.unstubAllGlobals();
});
+ it("keeps re-attaching sitting stock instead of warming it exactly once", async () => {
+ // The regression this pins: with a single attach per box, the whole warm
+ // path hung on that one call landing while the box happened to be ready.
+ // For freshly-manufactured stock it usually is not, and the box then sits
+ // cold for its entire life because nothing ever tries again. Measured on
+ // prod: 76 of 78 execs served on a dead channel.
+ const sessions = new FakeSessions();
+ origin.supply = [
+ { sandboxID: "sb-1", workerID: "w-1", endpoint: "e1", token: "t1", port: 8080 },
+ { sandboxID: "sb-2", workerID: "w-2", endpoint: "e2", token: "t2", port: 8080 },
+ ];
+ const { doInstance, state } = makeDO(origin, "2", "1", sessions);
+ await claimBatch(doInstance, state, ORG_A, 0); // prime the stock
+
+ const afterRestock = sessions.attaches.length;
+ expect(afterRestock).toBe(2); // one attach each at reserve
+
+ // Ticks with the stock full and nothing claimed: restock has nothing to do,
+ // so any further attach can only come from the rotating re-warm.
+ for (let i = 0; i < 3; i++) {
+ await doInstance.alarm();
+ await state.settle();
+ }
+ expect(sessions.attaches.length).toBeGreaterThan(afterRestock);
+ // And it must cover the whole shard, not just re-poke the first entry.
+ expect(new Set(sessions.attaches.slice(afterRestock))).toEqual(new Set(["sb-1", "sb-2"]));
+ });
+
+ it("reports a pre-warm it cannot perform rather than skipping in silence", async () => {
+ // A cell that supplies no reach-info means every exec pays a cold dial. That
+ // is a config problem with a large latency cost and no other symptom, so it
+ // has to appear in the log; silently returning here is what let it hide.
+ const err = vi.spyOn(console, "error").mockImplementation(() => {});
+ const sessions = new FakeSessions();
+ origin.supply = [
+ { sandboxID: "sb-1", workerID: "w-1" }, // no endpoint/token/port
+ { sandboxID: "sb-2", workerID: "w-2" },
+ ];
+ const { doInstance, state } = makeDO(origin, "2", "1", sessions);
+ await claimBatch(doInstance, state, ORG_A, 0);
+
+ expect(sessions.attaches).toEqual([]);
+ expect(err).toHaveBeenCalledWith(expect.stringContaining("agent pre-warm SKIPPED"));
+ err.mockRestore();
+ });
+
it("hands a box out exactly once", async () => {
origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];
const { doInstance, state } = makeDO(origin);
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 854715a5..f4bf4bd3 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -111,6 +111,10 @@ const IDLE_DECOMMISSION_MS = 30 * 60_000;
// than ALARM_INTERVAL_MS because nothing is being restocked, but still inside
// the shortest window it refreshes (count/cells, 30s) so an entry never lapses.
const IDLE_WARM_INTERVAL_MS = 20_000;
+// Stock entries re-attached per alarm tick by rewarmSlice. Deliberately a count,
+// not a fraction: it makes background load independent of TARGET_STOCK. At the
+// default 18 this cycles the whole shard about every 45s.
+const REWARM_PER_TICK = 4;
// Hard stop for warm-only ticking. A shard idle this long is not between bursts,
// it is out of service, and warming it is pure cost.
const WARM_MAX_IDLE_MS = 6 * 3600_000;
@@ -211,6 +215,15 @@ export class PoolStock {
private stock: StockEntry[] = [];
private restockInFlight = false;
private lastClaimMs = 0;
+ // Rotating position for rewarmSlice. In-memory only: a shard that is evicted
+ // and reloaded simply restarts the rotation, which costs nothing.
+ private rewarmCursor = 0;
+ // Pre-warm health. Counted and reported rather than swallowed — see
+ // warmMicrovmBox for why a silent skip here is the expensive kind of quiet.
+ private warmSkips = 0;
+ private warmFails = 0;
+ private warmSkipLoggedAt = 0;
+ private warmFailLoggedAt = 0;
// One-shot colo self-identification (diagnostics): placement is sticky at
// first-touch; a stock DO cross-colo from the claiming edge adds per-claim RTT.
private coloLogged = false;
@@ -566,17 +579,46 @@ export class PoolStock {
// lands, and the shard is placed in-metro with the traffic it serves, so
// the colo it warms is the colo that will read it.
await this.warmColo();
- // NOTE: deliberately NO periodic re-prewake of sitting stock here. Warming
- // every entry each tick costs 8 shards × TARGET_STOCK DO pokes every
- // ALARM_INTERVAL — sustained background load on the vm-do worker plus
- // waitUntil work competing with this DO's own claim serving — and prod
- // measurement showed the burst gate is edge-isolate admission, not DO
- // coldness (exec held ~48ms with 100% VM-DO). Fresh boxes are warmed once in
- // reserveOnce; a box that re-hibernates while it sits wakes on the host dial
- // or first exec, as it always did.
+ this.rewarmSlice();
await this.state.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
}
+ // rewarmSlice re-attaches a bounded, rotating slice of the sitting stock.
+ //
+ // This used to be nothing at all, and the comment where it used to be argued
+ // that warming every entry on every tick was too expensive — 8 shards ×
+ // TARGET_STOCK DO pokes per ALARM_INTERVAL of sustained load on the vm-do
+ // worker, competing with this object's own claim serving. That argument is
+ // still right, and this does not do that.
+ //
+ // What it replaces is the part that was wrong: with no re-warm at all, the
+ // single attach in reserveOnce was the ONLY one a box ever got. Its whole
+ // warm life then hung on one call landing at one moment — and for a freshly
+ // manufactured box that moment is the worst possible one, because the agent
+ // may not be answering yet. The MicrovmSession keepalive would fail its five
+ // pings, drop to its slow cadence (before that fix: stop forever), and nothing
+ // would ever re-attach. Measured on prod against a just-manufactured pool: 76
+ // of 78 execs served on a dead channel, each paying the full re-dial, versus
+ // 100 of 100 live on a pool old enough to have been attached while healthy.
+ //
+ // A rotating cursor makes the cost independent of stock depth: REWARM_PER_TICK
+ // pokes per shard per tick regardless of TARGET_STOCK, so at the default 18
+ // every box is re-attached about every 45s for roughly a fifth of the load the
+ // rejected every-entry version would have cost. Re-attach is idempotent — an
+ // already-live channel just refreshes warmUntil.
+ private rewarmSlice(): void {
+ if (this.stock.length === 0) return;
+ const n = Math.min(REWARM_PER_TICK, this.stock.length);
+ for (let i = 0; i < n; i++) {
+ const e = this.stock[this.rewarmCursor % this.stock.length];
+ this.rewarmCursor++;
+ if (!e.endpoint) continue; // cell routes through a worker; nothing to attach
+ this.warmMicrovmBox({ sandboxID: e.id, endpoint: e.endpoint, token: e.token, port: e.port });
+ }
+ // Keep the cursor from growing without bound over a long-lived shard.
+ if (this.rewarmCursor > 1e9) this.rewarmCursor = 0;
+ }
+
// prewakeBox wakes one box's VmSession DO isolate (best-effort, off any hot
// path). Called from reserveOnce when a box enters the stock.
private prewakeBox(sandboxID: string): void {
@@ -598,7 +640,27 @@ export class PoolStock {
// exec IS the race. Here there is no race: the box sits in stock for minutes.
private warmMicrovmBox(b: { sandboxID: string; endpoint?: string; token?: string; port?: number }): void {
const ns = this.env.MICROVM_SESSIONS;
- if (!ns || !b.endpoint || !b.token || !b.port) return;
+ // A silent skip here is indistinguishable from a warm that worked, and this
+ // is the single most load-bearing call on the fast path: without it every
+ // exec in the next burst pays a full re-dial. Every reason it can be skipped
+ // is a misconfiguration or a cell that changed shape, so say so — rate
+ // limited to one line per minute per shard, because under a restock storm
+ // this would otherwise be the noisiest line in the log.
+ if (!ns || !b.endpoint || !b.token || !b.port) {
+ this.warmSkips++;
+ const now = Date.now();
+ if (now - this.warmSkipLoggedAt > 60_000) {
+ this.warmSkipLoggedAt = now;
+ const missing = !ns
+ ? "MICROVM_SESSIONS binding"
+ : [!b.endpoint && "endpoint", !b.token && "token", !b.port && "port"].filter(Boolean).join("+");
+ console.error(
+ `pool-stock ${this.cell?.cellID ?? "?"}: agent pre-warm SKIPPED (${this.warmSkips} total) — missing ${missing}. ` +
+ `Every exec on these boxes will pay a cold dial.`,
+ );
+ }
+ return;
+ }
this.state.waitUntil(
ns
.get(ns.idFromName(b.sandboxID), { locationHint: "enam" })
@@ -607,8 +669,25 @@ export class PoolStock {
headers: { "content-type": "application/json" },
body: JSON.stringify({ endpoint: b.endpoint, token: b.token, port: b.port, dial: true }),
})
- .then(() => {})
- .catch(() => {}),
+ .then(async (r) => {
+ if (r.ok) return;
+ this.warmFails++;
+ const now = Date.now();
+ if (now - this.warmFailLoggedAt > 60_000) {
+ this.warmFailLoggedAt = now;
+ console.error(
+ `pool-stock ${this.cell?.cellID ?? "?"}: agent pre-warm attach failed ${r.status} (${this.warmFails} total)`,
+ );
+ }
+ })
+ .catch((e) => {
+ this.warmFails++;
+ const now = Date.now();
+ if (now - this.warmFailLoggedAt > 60_000) {
+ this.warmFailLoggedAt = now;
+ console.error(`pool-stock ${this.cell?.cellID ?? "?"}: agent pre-warm attach error (${this.warmFails} total): ${e}`);
+ }
+ }),
);
}
diff --git a/cloudflare-workers/vm-do/src/microvm_session.ts b/cloudflare-workers/vm-do/src/microvm_session.ts
index be33a504..0a61fb18 100644
--- a/cloudflare-workers/vm-do/src/microvm_session.ts
+++ b/cloudflare-workers/vm-do/src/microvm_session.ts
@@ -47,10 +47,32 @@ const KEEPALIVE_MS = 5_000;
// stock can sit for a while and the whole point is that the customer never waits
// for a dial. Refreshed by every attach and every exec.
const KEEPALIVE_TTL_MS = 60 * 60 * 1000;
-// Consecutive failed keepalives before we stop. A box that has been destroyed
-// or whose credential expired will never answer, and pinging it forever would
-// leave one alarm loop running per dead sandbox.
+// Consecutive failed keepalives before we back the loop off to its slow cadence.
+// A box that has been destroyed or whose credential expired will never answer,
+// and pinging one of those every 5s forever is a per-dead-sandbox alarm loop.
+//
+// Backing OFF is not the same as giving up, and conflating the two was a real
+// outage of the warm path. This used to return without re-arming the alarm, so
+// five failures ended the loop permanently — and because PoolStock warms each
+// box exactly once, at restock (see the NOTE in its alarm()), nothing ever
+// re-attached it. The give-up was written for "destroyed box / expired
+// credential", but it also caught the far more common case it was never meant
+// to: a box attached in the seconds after manufacture, before its agent is
+// answering. Those five pings burn in 25s and the box then sits in stock cold
+// for its whole life. Measured on prod: a burst against a freshly-manufactured
+// pool served 76 of 78 execs on a dead channel (dlive=0), each paying the full
+// re-dial, against dlive=1 on 100/100 for a pool that had been stocked long
+// enough to be attached while healthy.
+//
+// So failures slow the loop down instead of ending it. warmUntil is what ends
+// it — one hour, refreshed by every attach and every exec — which bounds a truly
+// dead box to KEEPALIVE_TTL_MS of slow pings rather than forever, while leaving
+// a not-yet-ready box able to recover on its own.
const MAX_KEEPALIVE_FAILURES = 5;
+// Cadence once a box has failed MAX_KEEPALIVE_FAILURES in a row. Long enough
+// that a dead sandbox costs ~60 pings/hour instead of 720, short enough that a
+// box which comes good is back on the fast cadence within a minute.
+const KEEPALIVE_BACKOFF_MS = 60_000;
const PING_TIMEOUT_MS = 3_000;
interface Creds {
@@ -168,6 +190,12 @@ export class MicrovmSession {
}
private async armKeepalive(): Promise<void> {
+ // Called from attach and from exec — either way someone just proved they
+ // care about this box, so clear the failure count. A box that failed its way
+ // into the slow cadence and is then re-attached (a PoolStock re-warm) or
+ // used gets the fast cadence back immediately rather than staying on the
+ // 60s tick until its next success.
+ this.failures = 0;
// setAlarm overwrites, so this is also the re-arm. Only skip when one is
// already due sooner than we would set it — a burst of attaches must not
// push the next tick further out.
@@ -201,23 +229,22 @@ export class MicrovmSession {
console.log("mvm-do: keepalive expired, going cold");
return;
}
+ let next = KEEPALIVE_MS;
try {
const conn = await this.channel();
await conn.ping(PING_TIMEOUT_MS);
+ if (this.failures > 0) console.log(`mvm-do: keepalive recovered after ${this.failures}`);
this.failures = 0;
} catch (e) {
this.conn = null;
this.failures++;
console.log(`mvm-do: keepalive failed (${this.failures}/${MAX_KEEPALIVE_FAILURES}): ${e}`);
- if (this.failures >= MAX_KEEPALIVE_FAILURES) {
- // Destroyed box, or a credential that has aged out. Either way nothing
- // here can fix it, and a permanent retry loop per dead sandbox is worse
- // than a cold first exec.
- console.log("mvm-do: keepalive giving up");
- return;
- }
+ // Slow down, but keep trying — a box that is merely not ready yet must be
+ // able to recover, and nothing else will ever re-attach it. warmUntil is
+ // the thing that ends this loop.
+ if (this.failures >= MAX_KEEPALIVE_FAILURES) next = KEEPALIVE_BACKOFF_MS;
}
- await this.state.storage.setAlarm(Date.now() + KEEPALIVE_MS);
+ await this.state.storage.setAlarm(Date.now() + next);
}
private async loadCreds(): Promise<Creds | null> {
diff --git a/cmd/mvmwipe/main.go b/cmd/mvmwipe/main.go
new file mode 100644
index 00000000..e908da95
--- /dev/null
+++ b/cmd/mvmwipe/main.go
@@ -0,0 +1,193 @@
+// mvmwipe — list and (with -apply) terminate MicroVMs in the account/region.
+//
+// Uses the same client the control plane uses, so ownership and throttling
+// behave identically. Dry-run by default: it prints the inventory grouped by
+// image ARN and state, and terminates nothing unless -apply is passed.
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "os"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+)
+
+func main() {
+ apply := flag.Bool("apply", false, "actually terminate (default: dry run)")
+ image := flag.String("image", "", "only touch boxes with this image ARN (default: all)")
+ conc := flag.Int("c", 8, "terminate concurrency")
+ out := flag.String("out", "", "write target IDs here and exit (one List pass, then reusable)")
+ from := flag.String("from", "", "read target IDs from this file instead of calling List")
+ state := flag.String("state", "RUNNING", "only touch boxes in this state (empty = all). Terminating an already-TERMINATED box is a wasted call straight into the throttler.")
+ ids := flag.String("ids", "", "terminate exactly these box or sandbox IDs (comma/space separated). Skips List entirely — the targeted intervention.")
+ allImages := flag.Bool("all-images", false, "permit -apply without -image. Required, because the image ARN is the only ownership test this account has.")
+ flag.Parse()
+
+ region := os.Getenv("AWS_REGION")
+ if region == "" {
+ region = os.Getenv("OPENSANDBOX_MICROVM_REGION")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
+ defer cancel()
+
+ awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region))
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "aws config:", err)
+ os.Exit(1)
+ }
+ c := awsvm.NewClient(awsCfg, awsvm.Config{Region: region})
+
+ // -ids is the intervention path: something told you exactly which boxes are
+ // stranded (a bench run printing its leaks, a budget log naming them) and you
+ // want those gone and nothing else. No List, no filters to get wrong, no way
+ // to widen the blast radius by fat-fingering a flag.
+ if *ids != "" {
+ targets := strings.FieldsFunc(*ids, func(r rune) bool { return r == ',' || r == ' ' || r == '\n' || r == '\t' })
+ fmt.Printf("targets: %d (explicit)\n", len(targets))
+ for _, id := range targets {
+ fmt.Printf(" %s\n", id)
+ }
+ if !*apply {
+ fmt.Println("\nDRY RUN — nothing terminated. Re-run with -apply.")
+ return
+ }
+ terminate(ctx, c, targets, *conc)
+ return
+ }
+
+ // The image ARN is the only thing distinguishing our boxes from anything else
+ // running in this account, so a bulk -apply without it is a wipe with no
+ // ownership test at all. Making that an explicit opt-in rather than a default
+ // is the difference between a tool and an accident.
+ if *apply && *image == "" && !*allImages {
+ fmt.Fprintln(os.Stderr, "refusing to -apply across every image: pass -image <arn> to scope it, or -all-images if you truly mean the whole account.")
+ os.Exit(2)
+ }
+
+ // -from skips List entirely. List pages through every record the API has
+ // ever returned (5k+ here) under heavy throttling with a 6-attempt backoff
+ // ladder, so it can outlive a short-lived credential all on its own — which
+ // is exactly how the first wipe attempt died before terminating anything.
+ // One List, cached to a file, then terminate as many times as it takes.
+ if *from != "" {
+ raw, err := os.ReadFile(*from)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "read -from:", err)
+ os.Exit(1)
+ }
+ var targets []string
+ for _, line := range strings.Split(string(raw), "\n") {
+ if id := strings.TrimSpace(line); id != "" {
+ targets = append(targets, id)
+ }
+ }
+ fmt.Printf("loaded %d target(s) from %s\n", len(targets), *from)
+ if !*apply {
+ fmt.Println("DRY RUN — nothing terminated. Re-run with -apply.")
+ return
+ }
+ terminate(ctx, c, targets, *conc)
+ return
+ }
+
+ boxes, err := c.List(ctx)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "list:", err)
+ os.Exit(1)
+ }
+
+ byImage := map[string]int{}
+ byState := map[string]int{}
+ var targets []string
+ for _, b := range boxes {
+ byImage[b.ImageArn]++
+ byState[fmt.Sprint(b.State)]++
+ if *image != "" && b.ImageArn != *image {
+ continue
+ }
+ if *state != "" && !strings.EqualFold(fmt.Sprint(b.State), *state) {
+ continue
+ }
+ targets = append(targets, b.ID)
+ }
+ fmt.Printf("total microvms: %d\n", len(boxes))
+ fmt.Println("by image:")
+ keys := make([]string, 0, len(byImage))
+ for k := range byImage {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ fmt.Printf(" %-70s %d\n", k, byImage[k])
+ }
+ fmt.Println("by state:")
+ for k, v := range byState {
+ fmt.Printf(" %-20s %d\n", k, v)
+ }
+ fmt.Printf("targets: %d\n", len(targets))
+
+ if *out != "" {
+ if err := os.WriteFile(*out, []byte(strings.Join(targets, "\n")+"\n"), 0o600); err != nil {
+ fmt.Fprintln(os.Stderr, "write -out:", err)
+ os.Exit(1)
+ }
+ fmt.Printf("wrote %d target(s) -> %s (re-run with -from %s -apply)\n", len(targets), *out, *out)
+ return
+ }
+
+ if !*apply {
+ fmt.Println("\nDRY RUN — nothing terminated. Re-run with -apply to wipe.")
+ return
+ }
+ terminate(ctx, c, targets, *conc)
+}
+
+func terminate(ctx context.Context, c *awsvm.Client, targets []string, conc int) {
+
+ var (
+ mu sync.Mutex
+ ok, fail int
+ )
+ sem := make(chan struct{}, conc)
+ var wg sync.WaitGroup
+ for _, id := range targets {
+ wg.Add(1)
+ go func(id string) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ // Terminate is throttled like the rest of the API; retry a few times
+ // so a throttled call does not leak the box's quota until the 8h cap.
+ var err error
+ for attempt := 0; attempt < 5; attempt++ {
+ if err = c.Terminate(ctx, id); err == nil {
+ break
+ }
+ time.Sleep(time.Duration(200*(1<<attempt)) * time.Millisecond)
+ }
+ mu.Lock()
+ if err == nil {
+ ok++
+ } else {
+ fail++
+ if fail <= 5 {
+ fmt.Fprintf(os.Stderr, "terminate %s: %v\n", id, err)
+ }
+ }
+ n := ok + fail
+ if n%25 == 0 {
+ fmt.Printf(" %d/%d terminated (%d failed)\n", n, len(targets), fail)
+ }
+ mu.Unlock()
+ }(id)
+ }
+ wg.Wait()
+ fmt.Printf("\nterminated %d, failed %d, of %d\n", ok, fail, len(targets))
+}
diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.go
index 791030b2..9e4b94bc 100644
--- a/internal/api/microvm_backend.go
+++ b/internal/api/microvm_backend.go
@@ -10,6 +10,7 @@ import (
"os"
"strconv"
"strings"
+ "sync/atomic"
"time"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
@@ -73,6 +74,11 @@ type microvmBackend struct {
// never reports is not routed to at all.
capacity *controlplane.CapacityReporter
+ // aliveRowless carries the last binding sweep's count of live boxes bound to
+ // a sandbox with no row, so the pool's budget log can report it without
+ // re-probing AWS. See boxesInUseDetail.
+ aliveRowless atomic.Int64
+
// coldSlots caps concurrent cold launches (see maxColdCreates).
coldSlots chan struct{}
@@ -199,9 +205,10 @@ func newMicrovmBackend(ctx context.Context, checkpointStore *storage.CheckpointS
// use" against 130 boxes alive in total, which pinned the pool at a
// permanent budget hold and would have starved refill through exactly
// the burst the budget exists to survive.
- InUse: b.boxesInUse,
- OnExpire: b.forgetExpiredReservation,
- OnMaintain: b.warmReservedTunnels,
+ InUse: b.boxesInUse,
+ InUseDetail: b.boxesInUseDetail,
+ OnExpire: b.forgetExpiredReservation,
+ OnMaintain: b.warmReservedTunnels,
// How long refill stands down once the budget is reached. Tunable
// because the right value is a property of the workload, not the code:
// it wants to outlast the burst that drained the pool, so that the
@@ -501,12 +508,31 @@ func (b *microvmBackend) forgetDeadBindings(ctx context.Context, hasRow map[stri
if forgotten > 0 {
log.Printf("microvm: binding sweep forgot %d dead binding(s) holding pool budget", forgotten)
}
+ b.aliveRowless.Store(int64(aliveRowless))
if aliveRowless > 0 {
log.Printf("microvm: binding sweep — %d live box(es) bound to a sandbox with no row; left alone for the orphan sweep to age out",
aliveRowless)
}
}
+// boxesInUseDetail decomposes boxesInUse for the pool's budget log. Wired to
+// PoolConfig.InUseDetail.
+//
+// boxesInUse is a subtraction of two independently-maintained counts, and when
+// the pool freezes at its budget the only question that matters is which of them
+// is wrong. Reporting just the difference makes that unanswerable from the logs:
+// a freeze looks identical whether the manager is holding bindings for sandboxes
+// that are long gone or the edge genuinely has that many boxes reserved.
+// alive-rowless is included because it is the leading indicator of the first
+// case — bindings the sweep can see but deliberately will not act on.
+func (b *microvmBackend) boxesInUseDetail() string {
+ if b == nil || b.manager == nil {
+ return ""
+ }
+ return fmt.Sprintf("tracked=%d edge-reserved=%d alive-rowless=%d",
+ len(b.manager.TrackedMicrovmIDs()), b.edgeReserved.depth(), b.aliveRowless.Load())
+}
+
// orphanMinAge is how old a MicroVM must be before the sweep will consider it
// abandoned. A box is invisible to us for a real window during its own creation
// — launched but not yet stocked, or claimed but not yet tracked — and reaping
diff --git a/internal/awsvm/pool.go b/internal/awsvm/pool.go
index b24cace3..cc3cd365 100644
--- a/internal/awsvm/pool.go
+++ b/internal/awsvm/pool.go
@@ -88,6 +88,12 @@ type PoolConfig struct {
// Nil means "nothing else exists", which is only true in tests.
InUse func() int
+ // InUseDetail explains the InUse number for the budget log — the terms it is
+ // computed from, so a refill freeze names its own cause instead of needing a
+ // live investigation to decompose. Optional; must be cheap and must not
+ // block, since it runs inside the pool's own tick.
+ InUseDetail func() string
+
// RefillDelay is how long the filler stands down after finding itself at
// MaxTotalBoxes.
//
@@ -579,8 +585,23 @@ func (p *Pool) overBudget() bool {
}
p.mu.Unlock()
if !quiet {
- log.Printf("awsvm: pool at box budget (%d in use + %d committed >= %d) — refill paused %s to leave regional quota for creates",
- inUse, p.committed(), p.cfg.MaxTotalBoxes, p.cfg.RefillDelay)
+ // Decomposed on purpose. "N in use + M committed" says the budget is
+ // full but not which term is holding it, and the two have opposite
+ // fixes: a stuck committed() means the pool is hoarding stock or has
+ // launches wedged in flight, while a stuck in-use means bindings the
+ // manager still counts for sandboxes that are gone. Diagnosing a refill
+ // freeze from the undecomposed line took a full benchmark session and
+ // several wrong answers, because every latency number measured during it
+ // was taken against a capped pool without that being visible.
+ p.mu.Lock()
+ stock, inflight, reserved := len(p.stock), p.inflight, len(p.reserved)
+ p.mu.Unlock()
+ detail := ""
+ if p.cfg.InUseDetail != nil {
+ detail = " " + p.cfg.InUseDetail()
+ }
+ log.Printf("awsvm: pool at box budget (%d in use + %d committed >= %d) — refill paused %s to leave regional quota for creates [stock=%d inflight=%d reserved=%d%s]",
+ inUse, p.committed(), p.cfg.MaxTotalBoxes, p.cfg.RefillDelay, stock, inflight, reserved, detail)
}
return true
}
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index f18a844c..4d3cba23 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "0.15.1",
+ "version": "0.15.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "0.15.1",
+ "version": "0.15.6",
"license": "MIT",
"dependencies": {
"undici": "^6.0.0 || ^7.0.0"
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index b056674a..036743b3 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.15.5",
+ "version": "0.15.6",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",