Skip to content

An open-source, faster Devin alternative

TypeScript

computer: fall back across zones and sizes on capacity, back off the pool refill

Mohamed Habib via Computer7584db872092
diff --git a/services/managed-agents/src/computer/cloud-contract.ts b/services/managed-agents/src/computer/cloud-contract.ts
index 126232ab..30f92140 100644
--- a/services/managed-agents/src/computer/cloud-contract.ts
+++ b/services/managed-agents/src/computer/cloud-contract.ts
@@ -24,8 +24,12 @@ export interface CloudResource {
organization: string | null;
vmSize?: string | null;
diskSizeGB?: number | null;
+ /** The zone of a zonal resource (the data disk, the VM). */
+ zone?: string | null;
/** VM instance view: why provisioning failed, when it did. */
failure?: string | null;
+ /** That failure's code, e.g. `ZonalAllocationFailed` (work 106: capacity failures fall back). */
+ failureCode?: string | null;
}
/** Which computer an operation is about. */
diff --git a/services/managed-agents/src/computer/config.ts b/services/managed-agents/src/computer/config.ts
index fb43a493..b71f9f07 100644
--- a/services/managed-agents/src/computer/config.ts
+++ b/services/managed-agents/src/computer/config.ts
@@ -35,6 +35,17 @@ export interface ComputerEdgeEnv extends PreviewsEnv {
COMPUTER_MAX_SIZE?: string;
/** Former name of COMPUTER_MAX_SIZE, still read when it is unset. */
COMPUTER_PAID_SIZE?: string;
+ /**
+ * Work 106: zones a new computer may be placed in, most preferred first
+ * (e.g. "2,1,3"); unset: 1, 2, 3. A zone without capacity falls to the next.
+ */
+ COMPUTER_ZONES?: string;
+ /**
+ * Work 106: sizes tried, in order, once no zone has capacity for the size
+ * asked for (e.g. "Standard_D16ads_v7,Standard_D16as_v6"). Only those with
+ * its vCPUs, memory and disk controller are used; unset: none.
+ */
+ COMPUTER_FALLBACK_SIZES?: string;
COMPUTER_DEFAULT_DISK_GIB?: string;
/** The most a computer's data disk grows to on its own (work 071; default 1024). */
COMPUTER_MAX_DISK_GIB?: string;
@@ -94,8 +105,8 @@ export const DEFAULT_WIRE_TUNNEL_DOMAIN = "w.opencomputer.dev";
export const DEFAULT_SIZE = "Standard_D2as_v7";
export const DEFAULT_DISK_GIB = 128;
export const DEFAULT_MAX_DISK_GIB = 1024;
-/** Premium SSD v2 needs a zone; every eastus v7 size is offered in zone 1. */
-export const DEFAULT_ZONE = "1";
+/** Premium SSD v2 needs a zone; the numbers are the subscription's own (logical) zones. */
+export const DEFAULT_ZONES = ["1", "2", "3"];
export class ComputersNotConfigured extends Error {
constructor(readonly missing: string[]) {
@@ -131,6 +142,43 @@ export function sizeFor(env: ComputerEdgeEnv, tier: "max" | "default"): string {
return (tier === "max" ? max : undefined) || env.COMPUTER_DEFAULT_SIZE || DEFAULT_SIZE;
}
+/** v6 and v7 sizes expose disks only over NVMe; the OS finds its disks by controller, so the two kinds do not mix. */
+export function nvmeSize(size: string): boolean {
+ return /_v[67]$/i.test(size);
+}
+
+/** Where a computer's VM and its zonal data disk are. */
+export interface Placement {
+ size: string;
+ zone: string;
+}
+
+/** COMPUTER_ZONES in order, without repeats or anything that is not a zone; none left: the default order. */
+export function zones(env: ComputerEdgeEnv): string[] {
+ const listed = (env.COMPUTER_ZONES ?? "").split(",").map((zone) => zone.trim());
+ const valid = [...new Set(listed.filter((zone) => DEFAULT_ZONES.includes(zone)))];
+ return valid.length ? valid : DEFAULT_ZONES;
+}
+
+/**
+ * Work 106: every placement a computer asked for at `size` may get, in the
+ * order tried: each zone at that size, then each zone at every fallback size
+ * of the same shape. The first is where it is created; the rest are for when
+ * the cloud has no capacity there (lifecycle.ts).
+ */
+export function placements(env: ComputerEdgeEnv, size: string): Placement[] {
+ const shape = sizeShape(size);
+ const fallbacks = (env.COMPUTER_FALLBACK_SIZES ?? "")
+ .split(",")
+ .map((other) => other.trim())
+ .filter((other) => {
+ if (!/^Standard_[A-Za-z0-9_]+$/.test(other) || other === size || nvmeSize(other) !== nvmeSize(size)) return false;
+ const { vcpus, memoryGiB } = sizeShape(other);
+ return vcpus === shape.vcpus && memoryGiB === shape.memoryGiB;
+ });
+ return [...new Set([size, ...fallbacks])].flatMap((each) => zones(env).map((zone) => ({ size: each, zone })));
+}
+
export function defaultDiskGiB(env: ComputerEdgeEnv): number {
const disk = Number(env.COMPUTER_DEFAULT_DISK_GIB || DEFAULT_DISK_GIB);
return Number.isInteger(disk) && disk > 0 ? disk : DEFAULT_DISK_GIB;
diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.ts
index 92056af3..b9e50a98 100644
--- a/services/managed-agents/src/computer/durable-object.ts
+++ b/services/managed-agents/src/computer/durable-object.ts
@@ -79,16 +79,17 @@ import { PlatformComputerCloud } from "./cloud.js";
import {
type ComputerEdgeEnv,
ComputersNotConfigured,
- DEFAULT_ZONE,
type PublicComputer,
defaultDiskGiB,
gatewayUrl,
maxDiskGiB,
missingEdgeConfig,
+ placements,
selfManagedVms,
publicOrigin,
sizeFor,
sizeShape,
+ zones,
} from "./config.js";
import { DEFAULT_HARNESS, computerHarnesses, harnessOnProfile, helloProfiles, profileHarnesses, takeHarnessPrefix } from "./harnesses.js";
import { type SealPurpose, seal, sha256Hex, unseal } from "./crypto.js";
@@ -527,6 +528,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
},
setAlarm: (at) => this.schedule("lifecycle", at),
hostConnected: () => this.socket() !== undefined,
+ placements: (size) => placements(env, size),
selfManaged: () => selfManagedVms(env),
onReady: () => {
this.noteActivity();
@@ -1365,7 +1367,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
}
const reply =
(await this.claimFromPool(accountId)) ??
- (await this.lifecycle.create(accountId, { size, diskGiB: defaultDiskGiB(this.env), zone: DEFAULT_ZONE }));
+ (await this.lifecycle.create(accountId, { size, diskGiB: defaultDiskGiB(this.env), zone: zones(this.env)[0]! }));
if (reply.status === 202) this.noteActivity();
return reply;
}
@@ -1529,7 +1531,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
/** Creates the pool computer: the free size and the default disk, like a new free organization's. */
startPoolComputer(poolId: string): Promise<LifecycleReply> {
this.bindPool(poolId);
- return this.lifecycle.create(poolId, { size: sizeFor(this.env, "default"), diskGiB: defaultDiskGiB(this.env), zone: DEFAULT_ZONE });
+ return this.lifecycle.create(poolId, { size: sizeFor(this.env, "default"), diskGiB: defaultDiskGiB(this.env), zone: zones(this.env)[0]! });
}
poolComputerStatus(poolId: string): PoolSlotStatus {
@@ -3148,7 +3150,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {
if (selfManagedVms(this.env)) {
// Work 105: the operator's VM connecting is what makes the computer: its row is `ready` from here,
// whether or not Slack was installed first, and threads told it was offline may be told again next time.
- await this.lifecycle.create(accountId, { size: sizeFor(this.env, "default"), diskGiB: defaultDiskGiB(this.env), zone: DEFAULT_ZONE });
+ await this.lifecycle.create(accountId, { size: sizeFor(this.env, "default"), diskGiB: defaultDiskGiB(this.env), zone: zones(this.env)[0]! });
this.ctx.storage.sql.exec("DELETE FROM notices WHERE kind = 'offline'");
}
this.lifecycle.noteHostSeen();
diff --git a/services/managed-agents/src/computer/lifecycle.ts b/services/managed-agents/src/computer/lifecycle.ts
index ed429a2e..d76c8731 100644
--- a/services/managed-agents/src/computer/lifecycle.ts
+++ b/services/managed-agents/src/computer/lifecycle.ts
@@ -19,7 +19,15 @@
// is created from the image the first time, and attached to its kept OS disk
// after a park. Transient cloud errors back off and retry; a refusal (4xx), a
// failed VM or too many attempts leave the row `failed` with its error.
-// Parking deletes the VM and NIC and keeps both disks.
+// Parking deletes the VM and NIC and keeps both disks. Deleting never gives
+// up on a transient error: a row left `failed` mid-delete leaks what is left.
+//
+// Capacity (work 106): when the cloud has no capacity for the VM's size in
+// its zone, the row moves to the next placement (`placements`: the other
+// zones, then the fallback sizes) and the same step builds it there. The
+// data disk is zonal, so a zone change deletes and recreates it; that only
+// happens while it is still empty (no host has ever said hello). A computer
+// whose disk holds data keeps its zone and can only change size.
//
// Every cloud call names the computer by its stored resource name prefix
// (`resource_prefix`), not by a name derived from the organization id at
@@ -35,7 +43,15 @@
import type { CloudResource, CloudResourceKind, CloudTarget } from "./cloud-contract.js";
import { CloudError, type ComputerCloud } from "./cloud.js";
-import { ComputersNotConfigured, type PublicComputer, type PublicComputerState, publicError, sizeShape } from "./config.js";
+import {
+ ComputersNotConfigured,
+ type Placement,
+ type PublicComputer,
+ type PublicComputerState,
+ nvmeSize,
+ publicError,
+ sizeShape,
+} from "./config.js";
import { POOL_TAG, computerName, ownerTag } from "./names.js";
export type ComputerState =
@@ -62,6 +78,11 @@ export interface LifecycleDeps {
gatewayUrl(organizationId: string): string;
setAlarm(at: number): Promise<void>;
hostConnected(): boolean;
+ /**
+ * Work 106: every placement a computer asked for at `size` may get, in
+ * the order tried (config.ts `placements`). Absent: no fallback.
+ */
+ placements?(size: string): Placement[];
/** The operator runs the VMs (COMPUTER_VMS=self-managed): the cloud is never called. */
selfManaged?(): boolean;
/** The computer became ready (created or woken): counts as activity, so it is not parked at once. */
@@ -120,6 +141,8 @@ export type ComputerRow = {
poolSlot: string | null;
/** Claimed from the pool and its resources still tagged `pool`: the alarm moves them. */
tagsPending: number;
+ /** JSON list of the placements (`size@zone`) this create or wake found without capacity; null: none. */
+ placementsTried: string | null;
createdAt: number;
updatedAt: number;
};
@@ -141,7 +164,8 @@ export function backoffMs(attempts: number): number {
const SELECT = `SELECT organization_id AS organizationId, state, size, disk_gib AS diskGiB, zone,
ssh_public_key AS sshPublicKey, attempts, last_error AS lastError, wake_after_park AS wakeAfterPark,
delete_disk AS deleteDisk, os_initialized AS osInitialized, replace_failed_vm AS replaceFailedVm, wakes,
- resource_prefix AS resourcePrefix, pool_slot AS poolSlot, tags_pending AS tagsPending, created_at AS createdAt,
+ resource_prefix AS resourcePrefix, pool_slot AS poolSlot, tags_pending AS tagsPending,
+ placements_tried AS placementsTried, created_at AS createdAt,
updated_at AS updatedAt FROM computer WHERE id = 1`;
const PUBLIC_STATE: Record<Exclude<ComputerState, "deleted" | "transferred">, PublicComputerState> = {
@@ -156,8 +180,17 @@ const PUBLIC_STATE: Record<Exclude<ComputerState, "deleted" | "transferred">, Pu
deleting: "deleting",
};
-function nvmeSize(size: string): boolean {
- return /_v[67]$/i.test(size);
+/** ARM's codes for "no capacity for this size here"; another zone or size may have it. */
+const CAPACITY_CODES = new Set([
+ "ZonalAllocationFailed",
+ "AllocationFailed",
+ "OverconstrainedZonalAllocationRequest",
+ "OverconstrainedAllocationRequest",
+ "SkuNotAvailable",
+]);
+
+function placementKey(placement: Placement): string {
+ return `${placement.size}@${placement.zone}`;
}
function validSize(size: string): boolean {
@@ -185,12 +218,13 @@ export class ComputerLifecycle {
resource_prefix TEXT,
pool_slot TEXT,
tags_pending INTEGER NOT NULL DEFAULT 0,
+ placements_tried TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// Columns added after the table first shipped (no migration step: NULL means "derive").
- for (const column of ["resource_prefix TEXT", "pool_slot TEXT", "tags_pending INTEGER NOT NULL DEFAULT 0"]) {
+ for (const column of ["resource_prefix TEXT", "pool_slot TEXT", "tags_pending INTEGER NOT NULL DEFAULT 0", "placements_tried TEXT"]) {
try {
deps.sql.exec(`ALTER TABLE computer ADD COLUMN ${column}`);
} catch {
@@ -276,7 +310,7 @@ export class ComputerLifecycle {
// capacity); the disk stays what it was unless the computer was deleted.
this.deps.sql.exec(
`UPDATE computer SET state = 'provisioning', attempts = 0, last_error = NULL, wake_after_park = 0,
- delete_disk = 0, replace_failed_vm = 1, updated_at = ?,
+ delete_disk = 0, replace_failed_vm = 1, placements_tried = NULL, updated_at = ?,
size = ?,
disk_gib = CASE WHEN state = 'deleted' THEN ? ELSE disk_gib END
WHERE id = 1`,
@@ -363,7 +397,8 @@ export class ComputerLifecycle {
}
if (row.state !== "parked") return false;
this.deps.sql.exec(
- `UPDATE computer SET state = 'waking', attempts = 0, last_error = NULL, wakes = wakes + 1, updated_at = ?
+ `UPDATE computer SET state = 'waking', attempts = 0, last_error = NULL, wakes = wakes + 1,
+ placements_tried = NULL, updated_at = ?
WHERE id = 1 AND state = 'parked'`,
this.now(),
);
@@ -520,7 +555,8 @@ export class ComputerLifecycle {
error instanceof ComputersNotConfigured ||
(error instanceof CloudError && !error.retryable);
console.error(JSON.stringify({ level: "error", event: "computer.lifecycle_error", state: row.state, attempts, fatal, message: text }));
- if (fatal || attempts >= MAX_ATTEMPTS) {
+ // A delete that stops half way leaks what is left, and nothing comes back for it: keep trying.
+ if (fatal || (attempts >= MAX_ATTEMPTS && row.state !== "deleting")) {
this.transition(row.state, "failed", text);
return;
}
@@ -568,6 +604,7 @@ export class ComputerLifecycle {
const target = this.target(row);
let disk = this.ours(row, await cloud.get(target, "dataDisk"), "data disk");
+ if (disk?.zone && disk.zone !== row.zone) return this.clearZone(row, disk);
disk ??= await cloud.putDataDisk(target, { diskGiB: row.diskGiB, zone: row.zone });
if (!succeeded(disk)) return POLL_MS;
@@ -594,19 +631,29 @@ export class ComputerLifecycle {
if (osDisk.provisioningState !== "Deleting") await cloud.delete(target, "osDisk");
return POLL_MS;
}
- vm = osDisk
- ? await cloud.putVm(target, { size: row.size, zone: row.zone, mode: "attach", sshPublicKey: row.sshPublicKey })
- : await cloud.putVm(target, {
- size: row.size,
- zone: row.zone,
- mode: "create",
- sshPublicKey: row.sshPublicKey,
- gatewayUrl: this.deps.gatewayUrl(org),
- hostToken: await this.deps.hostToken(org),
- });
+ try {
+ vm = osDisk
+ ? await cloud.putVm(target, { size: row.size, zone: row.zone, mode: "attach", sshPublicKey: row.sshPublicKey })
+ : await cloud.putVm(target, {
+ size: row.size,
+ zone: row.zone,
+ mode: "create",
+ sshPublicKey: row.sshPublicKey,
+ gatewayUrl: this.deps.gatewayUrl(org),
+ hostToken: await this.deps.hostToken(org),
+ });
+ } catch (error) {
+ // Refused outright for capacity (the usual way is a VM that ends up Failed, below).
+ if (error instanceof CloudError && CAPACITY_CODES.has(error.code) && this.fallBack(row, error.message)) return POLL_MS;
+ throw error;
+ }
}
const state = vm.provisioningState;
- if (state === "Failed") throw new Fatal(await this.vmFailure(target));
+ if (state === "Failed") {
+ const failure = await this.vmFailure(target);
+ if (failure.capacity && this.fallBack(row, failure.text)) return POLL_MS;
+ throw new Fatal(failure.text);
+ }
if (state !== "Succeeded") return POLL_MS;
// The OS disk a VM PUT created carries no tags: tag it, so it is
// recognisably this organization's while the computer is parked.
@@ -624,7 +671,7 @@ export class ComputerLifecycle {
private async awaitResize(row: ComputerRow): Promise<number | null> {
const vm = this.ours(row, await this.deps.cloud().get(this.target(row), "vm"), "VM");
if (!vm) throw new Fatal("the VM no longer exists");
- if (vm.provisioningState === "Failed") throw new Fatal(await this.vmFailure(this.target(row)));
+ if (vm.provisioningState === "Failed") throw new Fatal((await this.vmFailure(this.target(row))).text);
if (vm.provisioningState !== "Succeeded" || vm.vmSize !== row.size) return POLL_MS;
this.transition("resizing", "ready", null);
// Messages queued during the restart go now.
@@ -664,14 +711,71 @@ export class ComputerLifecycle {
throw new Fatal(`${what} is tagged for ${owner ?? "no organization"}, not ${ownerTag(row.organizationId)}`);
}
- private async vmFailure(target: CloudTarget): Promise<string> {
+ /**
+ * The row's placement has no capacity: move the row to the next one this
+ * create or wake has not tried, and let the next steps rebuild the VM
+ * there (the failed VM is replaced; `clearZone` when the zone changed).
+ * False when there is none left, and the capacity error stands. A data
+ * disk a host has used stays in its zone: only the size may change.
+ */
+ private fallBack(row: ComputerRow, reason: string): boolean {
+ const from = { size: row.size, zone: row.zone };
+ const tried = [...(JSON.parse(row.placementsTried ?? "[]") as string[]), placementKey(from)];
+ // The first one tried is at the size that was asked for.
+ const asked = tried[0]!.split("@")[0]!;
+ const to = (this.deps.placements?.(asked) ?? []).find(
+ (placement) =>
+ !tried.includes(placementKey(placement)) &&
+ nvmeSize(placement.size) === nvmeSize(row.size) &&
+ (placement.zone === row.zone || !row.osInitialized),
+ );
+ if (!to) return false;
+ this.deps.sql.exec(
+ `UPDATE computer SET size = ?, zone = ?, placements_tried = ?, replace_failed_vm = 1, attempts = 0, last_error = ?, updated_at = ?
+ WHERE id = 1 AND state = ?`,
+ to.size,
+ to.zone,
+ JSON.stringify(tried),
+ reason,
+ this.now(),
+ row.state,
+ );
+ console.warn(
+ JSON.stringify({ level: "warn", event: "computer.capacity_fallback", accountId: row.organizationId, state: row.state, from, to, message: reason }),
+ );
+ return true;
+ }
+
+ /**
+ * The data disk is in another zone than the row's (the row fell back):
+ * the VM and OS disk built on it go, then the disk itself, so the next
+ * steps create all three in the row's zone. Never a disk a host has used.
+ */
+ private async clearZone(row: ComputerRow, disk: CloudResource): Promise<number> {
+ if (row.osInitialized) throw new Fatal(`the data disk is in zone ${disk.zone}, the computer in zone ${row.zone}`);
+ const cloud = this.deps.cloud();
+ const target = this.target(row);
+ for (const kind of ["vm", "osDisk"] as const) {
+ const resource = this.ours(row, await cloud.get(target, kind), kind, { allowUntagged: kind === "osDisk" });
+ if (!resource) continue;
+ if (resource.provisioningState !== "Deleting") await cloud.delete(target, kind);
+ return POLL_MS;
+ }
+ if (disk.provisioningState !== "Deleting") await cloud.delete(target, "dataDisk");
+ return POLL_MS;
+ }
+
+ private async vmFailure(target: CloudTarget): Promise<{ text: string; capacity: boolean }> {
try {
const vm = await this.deps.cloud().get(target, "vm", { instanceView: true });
- if (vm?.failure) return `VM provisioning failed: ${vm.failure}`;
+ if (vm?.failure) {
+ const code = vm.failureCode && !vm.failure.includes(vm.failureCode) ? `${vm.failureCode}: ` : "";
+ return { text: `VM provisioning failed: ${code}${vm.failure}`, capacity: CAPACITY_CODES.has(vm.failureCode ?? "") };
+ }
} catch {
// The plain message below is enough.
}
- return "VM provisioning failed";
+ return { text: "VM provisioning failed", capacity: false };
}
private transition(from: ComputerState, to: ComputerState, error: string | null): void {
diff --git a/services/managed-agents/src/computer/pool.ts b/services/managed-agents/src/computer/pool.ts
index 876677d0..967d4482 100644
--- a/services/managed-agents/src/computer/pool.ts
+++ b/services/managed-agents/src/computer/pool.ts
@@ -14,6 +14,7 @@
// provisioning → warm → claiming → claimed
// ↑ │ │
// └───────────┴────────┘ (host gone, or the slot's object refused)
+// provisioning | warm → retiring → (row dropped once its computer is deleted)
//
// A slot is `warm` once its object reports the host connected (it tells the
// pool on hello; the alarm also asks). The alarm refills to
@@ -23,6 +24,15 @@
// this single-threaded object, before any await: two concurrent claims
// never get the same slot.
//
+// Work 106. A retired slot stays in the table as `retiring` until its
+// computer is deleted, and is asked to delete again if that stopped: a slot
+// dropped at once left its VM and disks behind whenever the delete failed.
+// And the refill backs off: every computer that fails to start or never
+// connects doubles the wait before the next start (REFILL_BACKOFF_MAX_MS at
+// most), one start at a time, until one comes up warm. Each failed start
+// creates and deletes a VM and two disks, so retrying every alarm through an
+// outage is churn; `computer.pool_degraded` says so on every alarm meanwhile.
+//
// Work 081: a warm slot also checks Claude setup tokens for the dashboard,
// before the person has a computer (`probe`). Stateless by design: it reads
// the slot table and writes nothing to it, makes one try on one warm slot
@@ -34,7 +44,10 @@ import { type ProbeOutcome, tokenFingerprint } from "./model-access.js";
import { computerName, newPoolId } from "./names.js";
import { ProbeLimits } from "./pool-probe-limits.js";
-export type PoolSlotState = "provisioning" | "warm" | "claiming" | "claimed";
+export type PoolSlotState = "provisioning" | "warm" | "claiming" | "claimed" | "retiring";
+
+/** Consecutive pool computers that did not come up, and when the next may start. */
+export type PoolHealth = { failures: number; retryAt: number };
export type PoolSlot = {
poolId: string;
@@ -89,6 +102,13 @@ export interface PoolClaim extends AdoptedComputer {
/** Pool computers created at once; the rest follow on later alarms. */
export const MAX_PROVISIONING = 3;
export const REFILL_INTERVAL_MS = 60_000;
+/** The longest wait between starts while pool computers keep failing. */
+export const REFILL_BACKOFF_MAX_MS = 30 * 60_000;
+
+/** The wait before the next start after `failures` consecutive failures: 2, 4, 8, 16, then 30 minutes. */
+export function refillBackoffMs(failures: number): number {
+ return Math.min(REFILL_INTERVAL_MS * 2 ** Math.min(failures, 10), REFILL_BACKOFF_MAX_MS);
+}
/** A slot not connected by then is retired (a first boot takes about two minutes). */
export const PROVISION_TIMEOUT_MS = 30 * 60_000;
/** A claim whose hand-over never finished (the object was evicted mid-claim). */
@@ -124,6 +144,11 @@ export class ComputerPool {
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
+ CREATE TABLE IF NOT EXISTS pool_health (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ failures INTEGER NOT NULL,
+ retry_at INTEGER NOT NULL
+ );
`);
this.limits = new ProbeLimits(deps.sql, () => this.now());
}
@@ -146,6 +171,27 @@ export class ComputerPool {
);
}
+ /** Zero failures when every recent start came up. */
+ health(): PoolHealth {
+ return [...this.deps.sql.exec<PoolHealth>("SELECT failures, retry_at AS retryAt FROM pool_health WHERE id = 1")][0] ?? { failures: 0, retryAt: 0 };
+ }
+
+ /** A pool computer did not come up: the next start waits longer. */
+ private startFailed(): void {
+ const failures = this.health().failures + 1;
+ this.deps.sql.exec(
+ "INSERT INTO pool_health (id, failures, retry_at) VALUES (1, ?, ?) ON CONFLICT (id) DO UPDATE SET failures = excluded.failures, retry_at = excluded.retry_at",
+ failures,
+ this.now() + refillBackoffMs(failures),
+ );
+ }
+
+ /** provisioning → warm: a pool computer came up, so starts are working. */
+ private warmed(poolId: string): void {
+ this.setState(poolId, "provisioning", "warm");
+ this.deps.sql.exec("DELETE FROM pool_health");
+ }
+
private drop(poolId: string): void {
this.deps.sql.exec("DELETE FROM pool_slots WHERE pool_id = ?", poolId);
}
@@ -157,7 +203,7 @@ export class ComputerPool {
/** A slot's host said hello. */
async connected(poolId: string): Promise<void> {
- this.setState(poolId, "provisioning", "warm");
+ if (this.slots().some((slot) => slot.poolId === poolId && slot.state === "provisioning")) this.warmed(poolId);
}
/**
@@ -249,6 +295,7 @@ export class ComputerPool {
for (const slot of this.slots()) {
if (slot.state === "provisioning") await this.reconcile(slot, now);
+ else if (slot.state === "retiring") await this.reconcileRetiring(slot);
else if (slot.state === "claiming" && now - slot.updatedAt > CLAIM_TIMEOUT_MS) await this.reconcileClaim(slot);
}
@@ -264,7 +311,16 @@ export class ComputerPool {
await this.gauge(live.filter((slot) => slot.state === "warm"));
const provisioning = live.filter((slot) => slot.state === "provisioning").length;
- const create = Math.min(target - live.length, MAX_PROVISIONING - provisioning);
+ const health = this.health();
+ const warm = live.length - provisioning;
+ if (health.failures > 0 && target > 0) {
+ console.error(
+ JSON.stringify({ level: "error", event: "computer.pool_degraded", failures: health.failures, warm, target, retryAt: new Date(health.retryAt).toISOString() }),
+ );
+ }
+ // While starts are failing: one at a time, and not before the backoff is over.
+ const atOnce = health.failures === 0 ? MAX_PROVISIONING : now >= health.retryAt ? 1 : 0;
+ const create = Math.min(target - live.length, atOnce - provisioning);
for (let index = 0; index < create; index += 1) {
const poolId = newPoolId();
this.deps.sql.exec(
@@ -282,8 +338,11 @@ export class ComputerPool {
}
if (reply.status >= 400) {
console.error(JSON.stringify({ level: "error", event: "computer.pool_start_failed", poolId, status: reply.status, message: reply.error }));
- await this.deps.slot(poolId).retire().catch(() => {});
- this.drop(poolId);
+ this.startFailed();
+ const slot = this.slots().find((each) => each.poolId === poolId)!;
+ await this.retire(slot, "start failed");
+ // Usually nothing was created, and the slot can go at once.
+ await this.reconcileRetiring(slot);
break;
}
console.log(JSON.stringify({ level: "info", event: "computer.pool_started", poolId }));
@@ -320,17 +379,28 @@ export class ComputerPool {
console.warn(JSON.stringify({ level: "warn", event: "computer.pool_status_failed", poolId: slot.poolId, message: errorText(error) }));
return;
}
- if (status.state === "ready" && status.connected) return this.setState(slot.poolId, "provisioning", "warm");
+ if (status.state === "ready" && status.connected) return this.warmed(slot.poolId);
if (status.state === null || status.state === "deleted" || status.state === "transferred") {
this.drop(slot.poolId);
return;
}
// From the last state change: a warm slot whose host dropped during a claim gets a fresh wait.
if (status.state === "failed" || now - slot.updatedAt > PROVISION_TIMEOUT_MS) {
+ this.startFailed();
await this.retire(slot, status.state === "failed" ? "failed" : "never connected");
}
}
+ /** A retiring slot goes once its computer is deleted; a delete that stopped (the row `failed`) is asked for again. */
+ private async reconcileRetiring(slot: PoolSlot): Promise<void> {
+ const status = await this.deps.slot(slot.poolId).status().catch(() => null);
+ if (!status) return;
+ if (status.state === null || status.state === "deleted" || status.state === "transferred") return this.drop(slot.poolId);
+ if (status.state === "deleting") return;
+ console.error(JSON.stringify({ level: "error", event: "computer.pool_retire_stalled", poolId: slot.poolId, state: status.state }));
+ await this.deps.slot(slot.poolId).retire().catch(() => {});
+ }
+
/** A claim that never finished: the slot's object says whether it was handed over. */
private async reconcileClaim(slot: PoolSlot): Promise<void> {
const status = await this.deps.slot(slot.poolId).status().catch(() => null);
@@ -353,10 +423,11 @@ export class ComputerPool {
console.log(JSON.stringify({ level: "info", event: "computer.pool_retired", poolId: slot.poolId, reason }));
try {
await this.deps.slot(slot.poolId).retire();
- this.drop(slot.poolId);
} catch (error) {
+ // Still retiring: the alarm asks again.
console.error(JSON.stringify({ level: "error", event: "computer.pool_retire_failed", poolId: slot.poolId, message: errorText(error) }));
}
+ this.deps.sql.exec("UPDATE pool_slots SET state = 'retiring', claimed_by = NULL, updated_at = ? WHERE pool_id = ?", this.now(), slot.poolId);
}
}
diff --git a/services/managed-agents/src/platform/computers/arm.ts b/services/managed-agents/src/platform/computers/arm.ts
index 8ffa63a7..30752a6d 100644
--- a/services/managed-agents/src/platform/computers/arm.ts
+++ b/services/managed-agents/src/platform/computers/arm.ts
@@ -197,6 +197,7 @@ export interface ArmResource {
id?: string;
name?: string;
tags?: Record<string, string>;
+ zones?: string[];
properties?: {
provisioningState?: string;
diskSizeGB?: number;
diff --git a/services/managed-agents/src/platform/computers/routes.ts b/services/managed-agents/src/platform/computers/routes.ts
index eaeafd93..50e82c7e 100644
--- a/services/managed-agents/src/platform/computers/routes.ts
+++ b/services/managed-agents/src/platform/computers/routes.ts
@@ -47,7 +47,9 @@ function summary(resource: ArmResource | null): CloudResource | null {
? { vmSize: resource.properties.hardwareProfile.vmSize }
: {}),
...(resource.properties?.diskSizeGB !== undefined ? { diskSizeGB: resource.properties.diskSizeGB } : {}),
- ...(failure ? { failure: failure.message ?? failure.code ?? null } : {}),
+ ...(resource.zones?.[0] ? { zone: resource.zones[0] } : {}),
+ // `ProvisioningState/failed/ZonalAllocationFailed`: the last part is ARM's error code.
+ ...(failure ? { failure: failure.message ?? failure.code ?? null, failureCode: failure.code?.split("/")[2] ?? null } : {}),
};
}
diff --git a/services/managed-agents/test/computer-azure.test.ts b/services/managed-agents/test/computer-azure.test.ts
index 609c8d9b..774d23ad 100644
--- a/services/managed-agents/test/computer-azure.test.ts
+++ b/services/managed-agents/test/computer-azure.test.ts
@@ -211,7 +211,7 @@ describe("platform computer route", () => {
it("derives every resource id itself and answers with the summary the lifecycle reads", async () => {
const azure = fakeAzure();
const put = await call(ENV, { op: "putDataDisk", organizationId: ORG, diskGiB: 128, zone: "1" }, azure.fetcher);
- expect(put.body).toEqual({ ok: true, resource: { provisioningState: "Creating", organization: ORG, diskSizeGB: 128 } });
+ expect(put.body).toEqual({ ok: true, resource: { provisioningState: "Creating", organization: ORG, diskSizeGB: 128, zone: "1" } });
expect(azure.requests[0]).toMatchObject({ method: "PUT", path: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/disks/oc-org-01hxyz-data" });
const got = await call(ENV, { op: "get", organizationId: ORG, kind: "dataDisk" }, azure.fetcher);
expect(got.body.resource.organization).toBe(ORG);
@@ -222,6 +222,25 @@ describe("platform computer route", () => {
expect(azure.tokens()).toBeGreaterThanOrEqual(1);
});
+ it("summarises a failed VM with ARM's error code and its zone, so the lifecycle can tell capacity from the rest", async () => {
+ const azure = fakeAzure();
+ azure.resources.set("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/oc-org-01hxyz", {
+ zones: ["2"],
+ tags: { organization: ORG },
+ properties: {
+ provisioningState: "Failed",
+ instanceView: {
+ statuses: [{ code: "ProvisioningState/failed/ZonalAllocationFailed", message: "Allocation failed. We do not have sufficient capacity." }],
+ },
+ },
+ });
+ const got = await call(ENV, { op: "get", organizationId: ORG, kind: "vm", instanceView: true }, azure.fetcher);
+ expect(got.body).toMatchObject({
+ ok: true,
+ resource: { provisioningState: "Failed", zone: "2", failureCode: "ZonalAllocationFailed", failure: "Allocation failed. We do not have sufficient capacity." },
+ });
+ });
+
it("names resources by the prefix the edge stores, validated at the boundary", async () => {
const azure = fakeAzure();
const put = await call(ENV, { op: "putNic", organizationId: ORG, prefix: "oc-pool-k3x9ab" }, azure.fetcher);
diff --git a/services/managed-agents/test/computer-lifecycle.test.ts b/services/managed-agents/test/computer-lifecycle.test.ts
index 98c09b70..5cba0aa8 100644
--- a/services/managed-agents/test/computer-lifecycle.test.ts
+++ b/services/managed-agents/test/computer-lifecycle.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from "vitest";
import type { CloudResource, CloudResourceKind, CloudTarget } from "../src/computer/cloud-contract.js";
import { CloudError, type ComputerCloud } from "../src/computer/cloud.js";
+import { placements, zones } from "../src/computer/config.js";
import { ComputerLifecycle, POLL_MS, backoffMs } from "../src/computer/lifecycle.js";
import { sqlStorage } from "./fixtures/computer-sql.js";
@@ -19,6 +20,10 @@ class FakeCloud implements ComputerCloud {
prefixes: string[] = [];
vmPuts: Array<{ mode: string; size: string; hostToken?: string; gatewayUrl?: string }> = [];
vmOutcome: "Succeeded" | "Failed" = "Succeeded";
+ /** Placements (`size@zone`) whose VM ends Failed with ZonalAllocationFailed. */
+ noCapacity = new Set<string>();
+ /** Where every VM PUT asked to be. */
+ vmPlacements: string[] = [];
failNext?: CloudError;
missingNames: string[] = [];
@@ -45,6 +50,9 @@ class FakeCloud implements ComputerCloud {
if (resource.provisioningState === "Creating" || resource.provisioningState === "Updating") {
resource.provisioningState = kind === "vm" ? this.vmOutcome : "Succeeded";
if (kind === "vm" && this.vmOutcome === "Failed") resource.failure = "Allocation failed";
+ if (kind === "vm" && this.noCapacity.has(`${resource.vmSize}@${resource.zone}`)) {
+ Object.assign(resource, { provisioningState: "Failed", failure: "We do not have sufficient capacity", failureCode: "ZonalAllocationFailed" });
+ }
}
return { ...resource };
}
@@ -55,9 +63,9 @@ class FakeCloud implements ComputerCloud {
return { ...resource };
}
- async putDataDisk(target: CloudTarget, spec: { diskGiB: number }) {
+ async putDataDisk(target: CloudTarget, spec: { diskGiB: number; zone: string }) {
this.check("PUT dataDisk", target);
- return this.create("dataDisk", { diskSizeGB: spec.diskGiB });
+ return this.create("dataDisk", { diskSizeGB: spec.diskGiB, zone: spec.zone });
}
async putNic(target: CloudTarget) {
@@ -65,11 +73,14 @@ class FakeCloud implements ComputerCloud {
return this.create("nic");
}
- async putVm(target: CloudTarget, spec: { size: string; mode: "create" | "attach"; hostToken?: string; gatewayUrl?: string }) {
+ async putVm(target: CloudTarget, spec: { size: string; zone: string; mode: "create" | "attach"; hostToken?: string; gatewayUrl?: string }) {
this.check(`PUT vm ${spec.mode}`, target);
this.vmPuts.push(spec);
+ this.vmPlacements.push(`${spec.size}@${spec.zone}`);
+ const diskZone = this.resources.get("dataDisk")?.zone;
+ if (diskZone && diskZone !== spec.zone) throw new CloudError(400, "BadRequest", "the disk and the VM are in different zones");
if (spec.mode === "create") this.resources.set("osDisk", { provisioningState: "Succeeded", organization: null });
- return this.create("vm", { vmSize: spec.size });
+ return this.create("vm", { vmSize: spec.size, zone: spec.zone });
}
async resizeVm(target: CloudTarget, size: string) {
@@ -113,8 +124,10 @@ let readyCalls: number;
let missingEdge: string[];
let lifecycle: ComputerLifecycle;
let selfManaged: boolean;
+let fallbackSizes: string[];
beforeEach(() => {
+ fallbackSizes = [];
cloud = new FakeCloud();
alarms = [];
now = 1_000_000;
@@ -131,6 +144,7 @@ beforeEach(() => {
gatewayUrl: (org) => `wss://edge.example/v1/computer/host?organizationId=${org}`,
setAlarm: async (at) => void alarms.push(at),
hostConnected: () => connected,
+ placements: (size) => [size, ...fallbackSizes].flatMap((each) => ["1", "2", "3"].map((zone) => ({ size: each, zone }))),
onReady: () => void (readyCalls += 1),
now: () => now,
sshPublicKey: async () => "ssh-rsa AAAA test",
@@ -226,6 +240,104 @@ describe("computer lifecycle", () => {
expect(cloud.vmPuts.map((p) => p.mode)).toEqual(["create", "create"]);
});
+ it("a zone without capacity falls to the next: the empty data disk moves with the VM, and the row keeps the zone", async () => {
+ cloud.noCapacity = new Set(["Standard_D2as_v7@1", "Standard_D2as_v7@2"]);
+ await lifecycle.create(ORG, OPTIONS);
+ await settle(60);
+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2as_v7", zone: "3", lastError: null });
+ expect(cloud.vmPlacements).toEqual(["Standard_D2as_v7@1", "Standard_D2as_v7@2", "Standard_D2as_v7@3"]);
+ expect(cloud.resources.get("dataDisk")).toMatchObject({ zone: "3", provisioningState: "Succeeded" });
+ // The NIC is regional: it is kept.
+ expect(cloud.calls.filter((call) => call === "PUT nic")).toHaveLength(1);
+ expect(cloud.calls.filter((call) => call === "DELETE dataDisk")).toHaveLength(2);
+
+ // Parked and woken, it stays where its disk is.
+ lifecycle.noteHostSeen();
+ await lifecycle.park();
+ await settle();
+ await lifecycle.wake();
+ await settle();
+ expect(lifecycle.row()).toMatchObject({ state: "ready", zone: "3" });
+ expect(cloud.vmPlacements.at(-1)).toBe("Standard_D2as_v7@3");
+ });
+
+ it("falls to the next size once no zone has capacity, and fails with the capacity error when nothing is left", async () => {
+ fallbackSizes = ["Standard_D2ads_v7"];
+ cloud.noCapacity = new Set(["1", "2", "3"].map((zone) => `Standard_D2as_v7@${zone}`));
+ await lifecycle.create(ORG, OPTIONS);
+ await settle(80);
+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2ads_v7", zone: "1" });
+
+ const other = new ComputerLifecycle({ ...(lifecycle as any).deps, sql: sqlStorage() });
+ cloud = new FakeCloud();
+ cloud.noCapacity = new Set(["Standard_D2as_v7", "Standard_D2ads_v7"].flatMap((size) => ["1", "2", "3"].map((zone) => `${size}@${zone}`)));
+ await other.create(ORG, OPTIONS);
+ for (let i = 0; i < 120 && other.row()?.state === "provisioning"; i += 1) await other.tick();
+ expect(cloud.vmPlacements).toHaveLength(6);
+ expect(other.row()).toMatchObject({ state: "failed", lastError: "VM provisioning failed: ZonalAllocationFailed: We do not have sufficient capacity" });
+ expect(other.view()?.lastError).toBe("No capacity was available for your computer; try again in a few minutes.");
+ // Asked again, it starts over from every placement.
+ cloud.noCapacity.delete("Standard_D2as_v7@2");
+ await other.create(ORG, OPTIONS);
+ for (let i = 0; i < 120 && other.row()?.state === "provisioning"; i += 1) await other.tick();
+ expect(other.row()).toMatchObject({ state: "ready", size: "Standard_D2as_v7", zone: "2" });
+ });
+
+ it("a capacity refusal of the VM PUT itself falls back too", async () => {
+ await lifecycle.create(ORG, OPTIONS);
+ await lifecycle.tick();
+ await lifecycle.tick();
+ cloud.calls = [];
+ // Third call of the next tick is the PUT: GET dataDisk, GET nic, GET vm, GET osDisk, PUT vm.
+ const put = cloud.putVm.bind(cloud);
+ let refused = false;
+ cloud.putVm = async (target, spec) => {
+ if (!refused) {
+ refused = true;
+ throw new CloudError(409, "SkuNotAvailable", "the requested size is currently not available in zone 1");
+ }
+ return put(target, spec);
+ };
+ await settle(40);
+ expect(lifecycle.row()).toMatchObject({ state: "ready", zone: "2" });
+ });
+
+ it("a wake keeps its zone: with no capacity there it changes size, or fails saying so, and never touches the data disk", async () => {
+ await lifecycle.create(ORG, OPTIONS);
+ await settle();
+ lifecycle.noteHostSeen();
+ await lifecycle.park();
+ await settle();
+ cloud.noCapacity = new Set(["Standard_D2as_v7@1"]);
+ await lifecycle.wake();
+ await settle(40);
+ expect(lifecycle.row()).toMatchObject({ state: "failed", zone: "1" });
+ expect(lifecycle.view()?.lastError).toBe("No capacity was available for your computer; try again in a few minutes.");
+
+ fallbackSizes = ["Standard_D2ads_v7"];
+ await lifecycle.create(ORG, OPTIONS);
+ await settle(40);
+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2ads_v7", zone: "1" });
+ expect(cloud.vmPuts.at(-1)).toMatchObject({ mode: "attach", size: "Standard_D2ads_v7" });
+ expect(cloud.calls).not.toContain("DELETE dataDisk");
+ expect(cloud.calls.filter((call) => call === "PUT dataDisk")).toHaveLength(1);
+ });
+
+ it("a delete keeps retrying transient errors instead of stopping half way", async () => {
+ await lifecycle.create(ORG, OPTIONS);
+ await settle();
+ await lifecycle.delete({ deleteDisk: true });
+ for (let i = 0; i < 15; i += 1) {
+ cloud.failNext = new CloudError(409, "OperationNotAllowed", "the disk is being attached");
+ await lifecycle.tick();
+ }
+ expect(lifecycle.row()).toMatchObject({ state: "deleting", attempts: 15 });
+ expect(alarms.at(-1)).toBe(now + backoffMs(15));
+ await settle();
+ expect(lifecycle.row()?.state).toBe("deleted");
+ expect(cloud.resources.size).toBe(0);
+ });
+
it("refuses resources tagged for another organization", async () => {
cloud.resources.set("dataDisk", { provisioningState: "Succeeded", organization: "org_other" });
await lifecycle.create(ORG, OPTIONS);
@@ -412,6 +524,30 @@ describe("computer lifecycle", () => {
});
// Work 105: the operator runs the VM; the lifecycle never calls the cloud.
+describe("placements", () => {
+ const env = (vars: Record<string, string>) => vars as never;
+
+ it("tries every zone in the configured order; unset or nonsense is 1, 2, 3", () => {
+ expect(zones(env({}))).toEqual(["1", "2", "3"]);
+ expect(zones(env({ COMPUTER_ZONES: "2, 3,2,9" }))).toEqual(["2", "3"]);
+ expect(zones(env({ COMPUTER_ZONES: "east" }))).toEqual(["1", "2", "3"]);
+ expect(placements(env({ COMPUTER_ZONES: "3,1" }), "Standard_D16as_v7")).toEqual([
+ { size: "Standard_D16as_v7", zone: "3" },
+ { size: "Standard_D16as_v7", zone: "1" },
+ ]);
+ });
+
+ it("then the fallback sizes of the same shape and disk controller, each in every zone", () => {
+ const vars = { COMPUTER_ZONES: "1", COMPUTER_FALLBACK_SIZES: "Standard_D16ads_v7, Standard_D8as_v7,Standard_D16as_v5,Standard_E16as_v7,bogus,Standard_D16as_v6" };
+ expect(placements(env(vars), "Standard_D16as_v7").map((placement) => placement.size)).toEqual([
+ "Standard_D16as_v7",
+ "Standard_D16ads_v7",
+ "Standard_D16as_v6",
+ ]);
+ expect(placements(env(vars), "Standard_D8as_v7").map((placement) => placement.size)).toEqual(["Standard_D8as_v7"]);
+ });
+});
+
describe("self-managed VMs", () => {
beforeEach(() => {
selfManaged = true;
diff --git a/services/managed-agents/test/computer-pool.test.ts b/services/managed-agents/test/computer-pool.test.ts
index 4c18ec86..b78b98a6 100644
--- a/services/managed-agents/test/computer-pool.test.ts
+++ b/services/managed-agents/test/computer-pool.test.ts
@@ -2,7 +2,15 @@ import { beforeEach, describe, expect, it } from "vitest";
import type { AdoptedComputer, LifecycleReply } from "../src/computer/lifecycle.js";
import { isPoolId, newPoolId, ownerTag } from "../src/computer/names.js";
-import { ComputerPool, MAX_PROVISIONING, PROVISION_TIMEOUT_MS, REFILL_INTERVAL_MS, poolSize } from "../src/computer/pool.js";
+import {
+ ComputerPool,
+ MAX_PROVISIONING,
+ PROVISION_TIMEOUT_MS,
+ REFILL_BACKOFF_MAX_MS,
+ REFILL_INTERVAL_MS,
+ poolSize,
+ refillBackoffMs,
+} from "../src/computer/pool.js";
import { sqlStorage } from "./fixtures/computer-sql.js";
/** A slot's ComputerDurableObject, in memory: started computers become ready when the test says so. */
@@ -126,26 +134,99 @@ describe("warm pool", () => {
slots.get(failed!)!.state = "failed";
await pool.refill();
expect(slots.get(failed!)!.retired).toBe(true);
- expect(pool.slots().map((slot) => slot.poolId)).not.toContain(failed);
+ // It stays in the table, retiring, until its computer is deleted.
+ expect(pool.slots().find((slot) => slot.poolId === failed)?.state).toBe("retiring");
+ slots.get(failed!)!.state = "deleted";
now += PROVISION_TIMEOUT_MS + 1;
slots.get(slow!)!.state = "ready";
await pool.refill();
expect(slots.get(slow!)!.retired).toBe(true);
+ expect(pool.slots().map((slot) => slot.poolId)).not.toContain(failed);
+ slots.get(slow!)!.state = "deleted";
+ now += REFILL_BACKOFF_MAX_MS;
+ await pool.refill();
await bootAll();
await pool.refill();
await bootAll();
expect(states()).toEqual(["warm", "warm"]);
target = 0;
+ expect(await pool.refill()).toBe(now + REFILL_INTERVAL_MS);
+ expect(states()).toEqual(["retiring", "retiring"]);
+ expect([...slots.values()].filter((slot) => !slot.retired)).toEqual([]);
+ for (const slot of slots.values()) slot.state = "deleted";
expect(await pool.refill()).toBeNull();
expect(pool.slots()).toEqual([]);
- expect([...slots.values()].filter((slot) => !slot.retired)).toEqual([]);
+ });
+
+ it("asks a retiring slot to delete again when its delete stopped, and keeps it until it is gone", async () => {
+ target = 1;
+ await pool.refill();
+ const [poolId] = [...slots.keys()];
+ const slot = slots.get(poolId!)!;
+ slot.state = "failed";
+ await pool.refill();
+ expect(slot).toMatchObject({ retired: true, state: "deleting" });
+ // The delete gave up (the lifecycle row is failed again): nothing else would come back for its VM and disks.
+ Object.assign(slot, { retired: false, state: "failed" });
+ await pool.refill();
+ expect(slot).toMatchObject({ retired: true, state: "deleting" });
+ expect(pool.slots().find((each) => each.poolId === poolId)?.state).toBe("retiring");
+ slot.state = "deleted";
+ await pool.refill();
+ expect(pool.slots().map((each) => each.poolId)).not.toContain(poolId);
+ });
+
+ it("backs off while pool computers fail to start: one at a time, doubling to a cap, until one comes up", async () => {
+ target = 5;
+ const started = () => slots.size;
+ /** Runs the alarm every minute for `minutes`, failing whatever is provisioning. */
+ const failFor = async (minutes: number) => {
+ for (let minute = 0; minute < minutes; minute += 1) {
+ for (const slot of slots.values()) if (slot.state === "provisioning") slot.state = "failed";
+ await pool.refill();
+ for (const slot of slots.values()) if (slot.state === "deleting") slot.state = "deleted";
+ now += REFILL_INTERVAL_MS;
+ }
+ };
+ await pool.refill();
+ expect(started()).toBe(MAX_PROVISIONING);
+ // Three failures at once: the next start waits 8 minutes, then 16, then 30 each time.
+ await failFor(1);
+ expect(pool.health()).toMatchObject({ failures: 3 });
+ expect(refillBackoffMs(3)).toBe(8 * 60_000);
+ await failFor(7);
+ expect(started()).toBe(MAX_PROVISIONING);
+ await failFor(1);
+ expect(started()).toBe(MAX_PROVISIONING + 1);
+ const before = started();
+ await failFor(4 * 60);
+ // Without backoff this would be 240 starts (720 VMs and disks created and deleted).
+ expect(started() - before).toBeLessThanOrEqual(4 * 60 / 30 + 1);
+ expect(pool.health().failures).toBeGreaterThan(5);
+ expect(refillBackoffMs(pool.health().failures)).toBe(REFILL_BACKOFF_MAX_MS);
+
+ // The next one comes up: the pool is healthy again and refills at full speed.
+ now = pool.health().retryAt;
+ await pool.refill();
+ await bootAll();
+ expect(pool.health()).toEqual({ failures: 0, retryAt: 0 });
+ await pool.refill();
+ expect(states()).toEqual(["provisioning", "provisioning", "provisioning", "warm"]);
});
it("starts nothing while computers are not configured", async () => {
startReply = { status: 503, error: "computers are not configured: missing AZURE_CLIENT_ID" };
expect(await pool.refill()).toBe(now + REFILL_INTERVAL_MS);
expect(pool.slots()).toEqual([]);
+ // And does not ask again every minute.
+ now += REFILL_INTERVAL_MS;
+ startReply = { status: 202 };
+ await pool.refill();
+ expect(pool.slots()).toEqual([]);
+ now += REFILL_INTERVAL_MS;
+ await pool.refill();
+ expect(states()).toEqual(["provisioning"]);
});
it("claims a warm slot atomically: two concurrent claims get different computers", async () => {