An open-source, faster Devin alternative
TypeScript
Computer placement: fixes from four reviews of work 106
Igor Zalutski via Computer5cedb7c422fb
diff --git a/services/managed-agents/README.md b/services/managed-agents/README.mdindex d9348e07..202439b9 100644--- a/services/managed-agents/README.md+++ b/services/managed-agents/README.md@@ -141,7 +141,7 @@ Configuration (empty values make computer creation answer| Worker | Secrets | Vars ||---|---|---|-| edge | `COMPUTER_HOST_TOKEN_KEY`, `SLACK_COMPUTER_CLIENT_ID`, `SLACK_COMPUTER_CLIENT_SECRET`, `SLACK_COMPUTER_SIGNING_SECRET`, `COMPUTER_ANTHROPIC_API_KEY` (fallback model credentials), `BLUE_USAGE_HMAC_SECRET` and `OC_MANAGED_CRED_HMAC_SECRET` (shared with serverless agents) | `COMPUTER_HOST_GATEWAY_URL` (wss origin the VM dials), `COMPUTER_DEFAULT_SIZE`, `COMPUTER_MAX_SIZE` (the $200 "max" usage plan's size; `COMPUTER_PAID_SIZE` is read when it is unset), `COMPUTER_ZONES` (zones a new computer may be placed in, most preferred first; default `1,2,3`), `COMPUTER_FALLBACK_SIZES` (more sizes to build a computer on when its own has no capacity or quota, in order; each serves the sizes it matches in vCPUs, memory and disk controller), `COMPUTER_DEFAULT_DISK_GIB`, `COMPUTER_MAX_DISK_GIB` (the data disk grows on its own at 80% used up to this, default 1024), `COMPUTER_POOL_SIZE`, `COMPUTER_VMS` (`self-managed`: the operator creates and runs each organization's VM, the gateway only accepts its host's connection and needs no platform Worker), `COMPUTER_API_ORGS`, `COMPUTER_PUBLIC_ORIGIN`, `SLACK_COMPUTER_SCOPES` |+| edge | `COMPUTER_HOST_TOKEN_KEY`, `SLACK_COMPUTER_CLIENT_ID`, `SLACK_COMPUTER_CLIENT_SECRET`, `SLACK_COMPUTER_SIGNING_SECRET`, `COMPUTER_ANTHROPIC_API_KEY` (fallback model credentials), `BLUE_USAGE_HMAC_SECRET` and `OC_MANAGED_CRED_HMAC_SECRET` (shared with serverless agents) | `COMPUTER_HOST_GATEWAY_URL` (wss origin the VM dials), `COMPUTER_DEFAULT_SIZE`, `COMPUTER_MAX_SIZE` (the $200 "max" usage plan's size; `COMPUTER_PAID_SIZE` is read when it is unset), `COMPUTER_ZONES` (zones a new computer may be placed in, most preferred first; default `1,2,3`), `COMPUTER_FALLBACK_SIZES` (more sizes to build a computer on when its own has no capacity or quota, in order; each serves the plan sizes it can stand in for: same vCPUs, memory and disk controller, x86 D or E family with premium storage and no local disk), `COMPUTER_DEFAULT_DISK_GIB`, `COMPUTER_MAX_DISK_GIB` (the data disk grows on its own at 80% used up to this, default 1024), `COMPUTER_POOL_SIZE`, `COMPUTER_VMS` (`self-managed`: the operator creates and runs each organization's VM, the gateway only accepts its host's connection and needs no platform Worker), `COMPUTER_API_ORGS`, `COMPUTER_PUBLIC_ORIGIN`, `SLACK_COMPUTER_SCOPES` || platform | `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET` | `AZURE_SUBSCRIPTION_ID`, `AZURE_COMPUTER_RESOURCE_GROUP`, `AZURE_COMPUTER_REGION`, `AZURE_COMPUTER_SUBNET_ID`, `AZURE_COMPUTER_IDENTITY_ID`, `AZURE_COMPUTER_IDENTITY_CLIENT_ID`, `COMPUTER_BOOTSTRAP_URL` |A production deploy sets these Worker secrets, under the same names: edge `COMPUTER_HOST_TOKEN_KEY`,@@ -156,13 +156,22 @@ empty until the production infrastructure exists).Capacity (work 106, `src/computer/placement.ts`): when the cloud has nocapacity or quota for a computer's size in its zone, the create or wake moves-on by itself: the size in each of `COMPUTER_ZONES`, then each matching size of-`COMPUTER_FALLBACK_SIZES` in each zone. A computer whose disk holds data keeps-its zone and only changes size. Each computer remembers the size it last ran-on and tries that first, so one that fell back stays on its new size until-that runs out too; `computer.capacity_fallback` and `computer.placed` log-every move and where it ended. A value in either var that is not a zone or a-size stops creates (`computers are not configured`) rather than being skipped.+on by itself: the size in each of `COMPUTER_ZONES`, then each size of the+deployment (the plans' sizes, then `COMPUTER_FALLBACK_SIZES`) that can stand+in for it, in each zone. A size stands in for another when a computer cannot+tell them apart (`standsIn`): same vCPUs, memory and disk controller, x86, D+or E family, premium storage, no local disk. Out of quota skips the size's+other zones, since quota is the region's. A computer whose data disk has been+used (`data_used`) keeps its zone and only changes size. Each computer+remembers the size it last ran on and tries that first while the deployment+still lists it, so one that fell back stays on its new size until that runs+out too, or until the size is taken out of `COMPUTER_FALLBACK_SIZES`.+`computer.capacity_fallback` and `computer.placed` log every move and where+it ended; `computer.capacity_exhausted` (error) says a computer failed with+nowhere left to try, which is the one to alert on. Nothing retries a failed+computer: its owner (or `operatorWake`) does. A value in either var that is+not a zone or a size, or a fallback size that can stand in for no plan's size,+stops creates (`computers are not configured`) rather than being skipped.Size (2026-10-13): only the $200 usage plan ("max", the billingadmission's `usagePlan`) gets `COMPUTER_MAX_SIZE`; Pro and free get thediff --git a/services/managed-agents/src/computer/config.ts b/services/managed-agents/src/computer/config.tsindex d44e64bd..e1cfc031 100644--- a/services/managed-agents/src/computer/config.ts+++ b/services/managed-agents/src/computer/config.ts@@ -4,7 +4,7 @@// the host token key, where hosts dial, and the organization Slack app.import type { ManagedAgentBillingService } from "../edge/billing-admission.js";-import { ZONES, validSize } from "./placement.js";+import { ZONES, standsIn, validSize, validZone } from "./placement.js";import type { PreviewsEnv } from "./previews.js";/** Preview URLs (work 074, previews.ts): off unless all of PreviewsEnv is set. */@@ -132,8 +132,15 @@ export function missingEdgeConfig(env: ComputerEdgeEnv): string[] {if (!env.RUNTIMES) missing.push("RUNTIMES");if (!env.COMPUTER_HOST_GATEWAY_URL) missing.push("COMPUTER_HOST_GATEWAY_URL");// A misspelt zone or size is a fallback that is not there when capacity runs out: say so now.- if (!list(env.COMPUTER_ZONES).every((zone) => ZONES.includes(zone))) missing.push("COMPUTER_ZONES (not a list of zones 1 to 3)");- if (!list(env.COMPUTER_FALLBACK_SIZES).every(validSize)) missing.push("COMPUTER_FALLBACK_SIZES (not a list of sizes)");+ if (!list(env.COMPUTER_ZONES).every(validZone)) missing.push("COMPUTER_ZONES (not a list of zones 1 to 3)");+ const fallbacks = list(env.COMPUTER_FALLBACK_SIZES);+ if (!fallbacks.every(validSize)) missing.push("COMPUTER_FALLBACK_SIZES (not a list of sizes)");+ else {+ // One that can stand in for neither plan's size would never be tried (placement.ts `standsIn`).+ const plans = [sizeFor(env, "default"), sizeFor(env, "max")];+ const unused = fallbacks.filter((size) => !plans.some((plan) => standsIn(size, plan)));+ if (unused.length) missing.push(`COMPUTER_FALLBACK_SIZES (${unused.join(", ")} cannot stand in for ${[...new Set(plans)].join(" or ")})`);+ }}if (!env.COMPUTER_HOST_TOKEN_KEY) missing.push("COMPUTER_HOST_TOKEN_KEY");return missing;@@ -153,8 +160,8 @@ function list(value: string | undefined): string[] {}/** COMPUTER_ZONES in order; unset: 1, 2, 3. (A value that is not zones stops creates: missingEdgeConfig.) */-export function zones(env: ComputerEdgeEnv): string[] {- const listed = [...new Set(list(env.COMPUTER_ZONES).filter((zone) => ZONES.includes(zone)))];+export function zones(env: ComputerEdgeEnv): readonly string[] {+ const listed = [...new Set(list(env.COMPUTER_ZONES).filter(validZone))];return listed.length ? listed : ZONES;}@@ -212,11 +219,15 @@ export interface PublicComputer {* cloud and name it, its resources and regions; the page gets a plain* sentence and the full text stays in the logs.*/+/** Says whose side it is on: a customer read the terser sentence as an unpaid bill (work 106). */+export const CAPACITY_ERROR =+ "Our cloud provider has no machine free for your computer right now. This is on our side, not your plan or billing, and your files are safe. Try again later.";+export function publicError(error: string | null): string | null {if (!error) return null;if (/not configured/i.test(error)) return "Computers are not available yet.";if (/quota|capacity|allocation|SkuNotAvailable|NotAvailableForSubscription/i.test(error)) {- return "No capacity was available for your computer; try again in a few minutes.";+ return CAPACITY_ERROR;}if (/tagged for/i.test(error)) return "Your computer's resources are in an unexpected state; support has been notified.";return "Your computer could not be started.";diff --git a/services/managed-agents/src/computer/lifecycle.ts b/services/managed-agents/src/computer/lifecycle.tsindex 615a3c13..232de623 100644--- a/services/managed-agents/src/computer/lifecycle.ts+++ b/services/managed-agents/src/computer/lifecycle.ts@@ -48,7 +48,7 @@ import type { CloudResource, CloudResourceKind, CloudTarget } from "./cloud-contimport { CloudError, type ComputerCloud } from "./cloud.js";import { ComputersNotConfigured, type PublicComputer, type PublicComputerState, publicError } from "./config.js";import { POOL_TAG, computerName, ownerTag } from "./names.js";-import { type Placement, ZONES, candidates, isCapacity, nvmeSize, sizeShape, validSize } from "./placement.js";+import { type Placement, candidates, isCapacity, isQuota, nvmeSize, sizeShape, validSize } from "./placement.js";export type ComputerState =| "provisioning"@@ -74,10 +74,10 @@ export interface LifecycleDeps {gatewayUrl(organizationId: string): string;setAlarm(at: number): Promise<void>;hostConnected(): boolean;- /** Work 106: the zones a new computer may be placed in, most preferred first (config.ts `zones`). Absent: 1, 2, 3. */- zones?(): string[];- /** Work 106: the sizes the deployment builds computers on, in the order tried (config.ts `sizes`). Absent: no other size. */- sizes?(): string[];+ /** Work 106: the zones a new computer may be placed in, most preferred first (config.ts `zones`: never empty). */+ zones(): readonly string[];+ /** Work 106: the sizes the deployment builds computers on, in the order tried (config.ts `sizes`). */+ sizes(): readonly string[];/** 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. */@@ -126,6 +126,8 @@ export type ComputerRow = {deleteDisk: number;/** A host has said hello from this computer: its OS disk is provisioned and may be attached on wake. */osInitialized: number;+ /** A host has used the data disk: it is never deleted to change zone, so the computer keeps its zone. */+ dataUsed: number;/** Created again after `failed`: a VM left in Failed is deleted and built again, not PUT over. */replaceFailedVm: number;/** Times woken; a notice is posted once per thread per wake. */@@ -148,13 +150,27 @@ export type ComputerRow = {* A create or wake's placements, worked out when it began: `size` and `zone`* of the row are `candidates[index]`, and a capacity failure moves to the next.*/-interface Attempt {- /** The size asked for (the plan's). */+export interface Attempt {+ /** The size the create or wake asked for. */asked: string;candidates: Placement[];index: number;}+/** Null on rows from before work 106, and for a value that is not an attempt (the row then fails on capacity as before). */+export function readAttempt(row: Pick<ComputerRow, "attempt">): Attempt | null {+ try {+ const attempt = row.attempt ? (JSON.parse(row.attempt) as Attempt) : null;+ return attempt && Array.isArray(attempt.candidates) && Number.isInteger(attempt.index) ? attempt : null;+ } catch {+ return null;+ }+}++function writeAttempt(attempt: Attempt): string {+ return JSON.stringify(attempt);+}+/** Not worth retrying: the request itself is wrong, or a resource is not ours. */class Fatal extends Error {}@@ -171,7 +187,7 @@ 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,+ delete_disk AS deleteDisk, os_initialized AS osInitialized, data_used AS dataUsed, replace_failed_vm AS replaceFailedVm, wakes,resource_prefix AS resourcePrefix, pool_slot AS poolSlot, tags_pending AS tagsPending,preferred_size AS preferredSize, attempt, created_at AS createdAt,updated_at AS updatedAt FROM computer WHERE id = 1`;@@ -204,6 +220,7 @@ export class ComputerLifecycle {wake_after_park INTEGER NOT NULL DEFAULT 0,delete_disk INTEGER NOT NULL DEFAULT 0,os_initialized INTEGER NOT NULL DEFAULT 0,+ data_used INTEGER NOT NULL DEFAULT 0,replace_failed_vm INTEGER NOT NULL DEFAULT 0,wakes INTEGER NOT NULL DEFAULT 0,resource_prefix TEXT,@@ -216,14 +233,25 @@ export class ComputerLifecycle {);`);// 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", "preferred_size TEXT", "attempt TEXT"]) {+ // `backfill` runs once, when the column is new.+ const added: Array<[column: string, backfill?: string]> = [+ ["resource_prefix TEXT"],+ ["pool_slot TEXT"],+ ["tags_pending INTEGER NOT NULL DEFAULT 0"],+ // A computer from before work 106 keeps trying the size it has first.+ ["preferred_size TEXT", "UPDATE computer SET preferred_size = size"],+ ["attempt TEXT"],+ // Until now one flag said both "the OS disk booted" and "the data disk is in use".+ ["data_used INTEGER NOT NULL DEFAULT 0", "UPDATE computer SET data_used = os_initialized"],+ ];+ for (const [column, backfill] of added) {try {deps.sql.exec(`ALTER TABLE computer ADD COLUMN ${column}`);- // Once, when the column is new: a computer from before it keeps trying the size it has first.- if (column === "preferred_size TEXT") deps.sql.exec("UPDATE computer SET preferred_size = size");} catch {// Already there.+ continue;}+ if (backfill) deps.sql.exec(backfill);}}@@ -361,7 +389,7 @@ export class ComputerLifecycle {organizationId,options.size,options.diskGiB,- this.zones()[0]!,+ this.deps.zones()[0]!,options.prefix ?? computerName(organizationId),now,now,@@ -375,11 +403,6 @@ export class ComputerLifecycle {return this.deps.selfManaged?.() ?? false;}- private zones(): string[] {- const zones = this.deps.zones?.() ?? [];- return zones.length ? zones : ZONES;- }-/*** The placements of a create or wake that starts now and asks for `asked`,* as the row's next size, zone and attempt. `row` is the computer so far@@ -389,13 +412,12 @@ export class ComputerLifecycle {private begin(row: ComputerRow | null, asked: string): Placement & { attempt: string } {const all = candidates({asked,- sizes: this.deps.sizes?.() ?? [],- zones: this.zones(),+ sizes: this.deps.sizes(),+ zones: this.deps.zones(),preferred: row?.preferredSize,- pinnedZone: row?.osInitialized ? row.zone : null,+ pinnedZone: row?.dataUsed ? row.zone : null,});- const attempt: Attempt = { asked, candidates: all, index: 0 };- return { ...all[0]!, attempt: JSON.stringify(attempt) };+ return { ...all[0]!, attempt: writeAttempt({ asked, candidates: all, index: 0 }) };}/**@@ -409,11 +431,13 @@ export class ComputerLifecycle {async wake(size?: string): Promise<boolean> {const row = this.row();if (!row) return false;+ let asked = row.size;if (size && size !== row.size && (row.state === "parked" || row.state === "parking")) {if (validSize(size) && nvmeSize(size) === nvmeSize(row.size)) {this.deps.sql.exec("UPDATE computer SET size = ?, updated_at = ? WHERE id = 1", size, this.now());+ asked = size;} else {- console.warn(JSON.stringify({ level: "warn", event: "computer.wake_size_ignored", from: row.size, to: size }));+ console.warn(JSON.stringify({ level: "warn", event: "computer.wake_size_ignored", accountId: row.organizationId, from: row.size, to: size }));}}if (row.state === "parking") {@@ -421,9 +445,7 @@ export class ComputerLifecycle {return true;}if (row.state !== "parked") return false;- // Read again: the size asked for may have just been written.- const parked = this.row()!;- const first = this.begin(parked, parked.size);+ const first = this.begin(row, asked);this.deps.sql.exec(`UPDATE computer SET state = 'waking', attempts = 0, last_error = NULL, wakes = wakes + 1,size = ?, zone = ?, attempt = ?, updated_at = ?@@ -477,9 +499,9 @@ export class ComputerLifecycle {if (this.row()) return false;const now = this.now();this.deps.sql.exec(- `INSERT INTO computer (id, organization_id, state, size, preferred_size, disk_gib, zone, ssh_public_key, os_initialized,+ `INSERT INTO computer (id, organization_id, state, size, preferred_size, disk_gib, zone, ssh_public_key, os_initialized, data_used,resource_prefix, pool_slot, tags_pending, created_at, updated_at)- VALUES (1, ?, 'ready', ?, ?, ?, ?, ?, 1, ?, ?, 1, ?, ?)`,+ VALUES (1, ?, 'ready', ?, ?, ?, ?, ?, 1, 1, ?, ?, 1, ?, ?)`,organizationId,computer.size,computer.size,@@ -498,7 +520,7 @@ export class ComputerLifecycle {/** A host said hello: its OS disk has been through first boot, so a wake may attach it. */noteHostSeen(): void {- this.deps.sql.exec("UPDATE computer SET os_initialized = 1 WHERE id = 1 AND os_initialized = 0");+ this.deps.sql.exec("UPDATE computer SET os_initialized = 1, data_used = 1 WHERE id = 1 AND (os_initialized = 0 OR data_used = 0)");}/** CPU and memory: the VM restarts on the new size, disks stay. A parked computer takes it on waking. */@@ -665,6 +687,8 @@ export class ComputerLifecycle {if (osDisk.provisioningState !== "Deleting") await cloud.delete(target, "osDisk");return POLL_MS;}+ // No OS disk: the one the PUT creates has booted no host yet, whatever the one before it had (a computer deleted and created again).+ if (!osDisk && row.osInitialized) this.deps.sql.exec("UPDATE computer SET os_initialized = 0 WHERE id = 1");try {vm = osDisk? await cloud.putVm(target, { size: row.size, zone: row.zone, mode: "attach", sshPublicKey: row.sshPublicKey })@@ -678,14 +702,16 @@ export class ComputerLifecycle {});} catch (error) {// Refused outright for capacity or quota (a zone's capacity is more often a VM that ends up Failed, below).- if (error instanceof CloudError && isCapacity(error.code, error.message) && this.fallBack(row, error.message)) return POLL_MS;- throw error;+ if (!(error instanceof CloudError) || !isCapacity(error.code, error.message)) throw error;+ if (this.fallBack(row, error.message, { nextSize: isQuota(error.code, error.message) })) return POLL_MS;+ // Nowhere left: fail now, as a VM that ends Failed does, rather than retry a refusal that will not change.+ throw new Fatal(`${error.code}: ${error.message}`);}}const state = vm.provisioningState;if (state === "Failed") {const failure = await this.vmFailure(target);- if (failure.capacity && this.fallBack(row, failure.text)) return POLL_MS;+ if (failure.capacity && this.fallBack(row, failure.text, { nextSize: failure.quota })) return POLL_MS;throw new Fatal(failure.text);}if (state !== "Succeeded") return POLL_MS;@@ -695,10 +721,10 @@ export class ComputerLifecycle {const osDisk = await cloud.get(target, "osDisk");if (osDisk && !osDisk.organization) await cloud.tagOsDisk(target);} catch (error) {- console.warn(JSON.stringify({ level: "warn", event: "computer.os_disk_tag_failed", message: message(error) }));+ console.warn(JSON.stringify({ level: "warn", event: "computer.os_disk_tag_failed", accountId: org, message: message(error) }));}this.ready(row);- const attempt = this.attempt(row);+ const attempt = readAttempt(row);console.log(JSON.stringify({level: "info",@@ -735,6 +761,8 @@ export class ComputerLifecycle {return POLL_MS;}this.transition(row.state, to, null);+ // With its data disk gone, a computer created again may be placed in any zone.+ if (to === "deleted" && row.deleteDisk) this.deps.sql.exec("UPDATE computer SET data_used = 0 WHERE id = 1 AND state = 'deleted'");if (to === "parked" && row.wakeAfterPark) {this.deps.sql.exec("UPDATE computer SET wake_after_park = 0 WHERE id = 1");await this.wake();@@ -757,28 +785,41 @@ export class ComputerLifecycle {throw new Fatal(`${what} is tagged for ${owner ?? "no organization"}, not ${ownerTag(row.organizationId)}`);}- private attempt(row: ComputerRow): Attempt | null {- return row.attempt ? (JSON.parse(row.attempt) as Attempt) : null;- }-/*** The row's placement has no capacity: move the row to the attempt's next* one, 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.+ * replaced; `clearZone` when the zone changed). With `nextSize` (a quota,+ * which is the region's) the size's other zones are passed over. False+ * when there is none left, and the capacity error stands.*/- private fallBack(row: ComputerRow, reason: string): boolean {- const attempt = this.attempt(row);- const to = attempt?.candidates[attempt.index + 1];- if (!attempt || !to) return false;+ private fallBack(row: ComputerRow, reason: string, options: { nextSize?: boolean } = {}): boolean {+ // The row as it is now: a delete may have come in while the cloud answered.+ const current = this.row();+ if (!current || current.state !== row.state || current.attempt !== row.attempt) return false;+ const attempt = readAttempt(row);const from = { size: row.size, zone: row.zone };- const index = attempt.index + 1;+ const index = attempt ? attempt.candidates.findIndex((each, at) => at > attempt.index && !(options.nextSize && each.size === row.size)) : -1;+ const to = attempt?.candidates[index];+ if (!attempt || !to) {+ console.error(+ JSON.stringify({+ level: "error",+ event: "computer.capacity_exhausted",+ accountId: row.organizationId,+ state: row.state,+ ...from,+ tried: attempt ? attempt.candidates.length : 1,+ message: reason,+ }),+ );+ return false;+ }this.deps.sql.exec(`UPDATE computer SET size = ?, zone = ?, attempt = ?, replace_failed_vm = 1, attempts = 0, last_error = ?, updated_at = ?WHERE id = 1 AND state = ?`,to.size,to.zone,- JSON.stringify({ ...attempt, index }),+ writeAttempt({ ...attempt, index }),reason,this.now(),row.state,@@ -805,7 +846,7 @@ export class ComputerLifecycle {* 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}`);+ if (row.dataUsed) 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) {@@ -818,17 +859,24 @@ export class ComputerLifecycle {return POLL_MS;}- private async vmFailure(target: CloudTarget): Promise<{ text: string; capacity: boolean }> {+ /** Why the VM ended Failed. The code leads the text: `publicError` tells capacity by it. */+ private async vmFailure(target: CloudTarget): Promise<{ text: string; capacity: boolean; quota: boolean }> {try {const vm = await this.deps.cloud().get(target, "vm", { instanceView: true });if (vm?.failure) {const code = vm.failureCode && !vm.failure.includes(vm.failureCode) ? `${vm.failureCode}: ` : "";- return { text: `VM provisioning failed: ${code}${vm.failure}`, capacity: isCapacity(vm.failureCode, vm.failure) };+ return {+ text: `VM provisioning failed: ${code}${vm.failure}`,+ capacity: isCapacity(vm.failureCode, vm.failure),+ quota: isQuota(vm.failureCode, vm.failure),+ };}- } catch {- // The plain message below is enough.+ } catch (error) {+ // Throttled or unreachable: ask again, since the reason decides whether another placement is tried.+ if (error instanceof CloudError && error.retryable) throw error;+ // Otherwise the plain message below is enough.}- return { text: "VM provisioning failed", capacity: false };+ return { text: "VM provisioning failed", capacity: false, quota: false };}/** Built, woken or resized: ready, and its size is the one to try first next time. */diff --git a/services/managed-agents/src/computer/placement.ts b/services/managed-agents/src/computer/placement.tsindex 8747ff05..954478c8 100644--- a/services/managed-agents/src/computer/placement.ts+++ b/services/managed-agents/src/computer/placement.ts@@ -2,13 +2,14 @@// wake may try, in order, and which cloud failures mean "try the next one".// Pure: the settings come from config.ts, the state machine is lifecycle.ts.//-// A create or wake asks for one size (its plan's). It may get any size of-// the same shape (vCPUs and memory) on the same disk controller: the size-// the computer last ran on first, so a computer that fell back does not pay-// a failed attempt on every wake while the shortage lasts; then the size-// asked for; then the deployment's other sizes. Each size is tried in every-// zone before the next size. The data disk is zonal, so once a host has-// used it the computer keeps its zone and only the size may change.+// A create or wake asks for one size (its plan's). It may get any of the+// deployment's sizes that can stand in for it (`standsIn`: same vCPUs,+// memory, disk controller, architecture and disks): the size the computer+// last ran on first, so a computer that fell back does not pay a failed+// attempt on every wake while the shortage lasts; then the size asked for;+// then the others. Each size is tried in every zone before the next size.+// The data disk is zonal, so once a host has used it the computer keeps its+// zone and only the size may change./** Where a computer's VM and its zonal data disk are. */export interface Placement {@@ -17,7 +18,11 @@ export interface Placement {}/** Premium SSD v2 needs a zone; the numbers are the subscription's own (logical) zones. */-export const ZONES = ["1", "2", "3"];+export const ZONES: readonly string[] = ["1", "2", "3"];++export function validZone(zone: string): boolean {+ return ZONES.includes(zone);+}export function validSize(size: string): boolean {return /^Standard_[A-Za-z0-9_]+$/.test(size);@@ -34,36 +39,56 @@ export function nvmeSize(size: string): boolean {* ones, e.g. `Standard_D16als_v7`), E 8, F 2.*/export function sizeShape(size: string): { vcpus: number; memoryGiB: number } {- const match = size.match(/^Standard_([A-Z]+)(\d+)([a-z]*)/i);- const family = match?.[1]?.toUpperCase() ?? "D";- const vcpus = Number(match?.[2] ?? 2);- const lowMemory = family.startsWith("D") && (match?.[3] ?? "").includes("l");+ const { family, vcpus, features } = parts(size);+ const lowMemory = family.startsWith("D") && features.includes("l");const perVcpu = family.startsWith("E") ? 8 : family.startsWith("F") || lowMemory ? 2 : 4;return { vcpus, memoryGiB: vcpus * perVcpu };}+/** `Standard_D16as_v7` → family D, 16 vCPUs, features `as` (a constrained-core `-8` is skipped). Unparseable: D, 2, none. */+function parts(size: string): { family: string; vcpus: number; features: string } {+ const match = size.match(/^Standard_([A-Z]+)(\d+)(?:-\d+)?([a-z]*)/i);+ return { family: match?.[1]?.toUpperCase() ?? "D", vcpus: Number(match?.[2] ?? 2), features: match?.[3] ?? "" };+}+export function sameShape(a: string, b: string): boolean {const [one, other] = [sizeShape(a), sizeShape(b)];return one.vcpus === other.vcpus && one.memoryGiB === other.memoryGiB;}+/**+ * Whether a computer asked for on `asked` may be built on `size` instead,+ * disks and all: same shape and disk controller, same architecture (`p` is+ * arm64), the same local disk or none (`d`), premium storage for the data+ * disk (`s`), and a family whose memory the name tells (D and E; the+ * others' ratios vary by generation, so they are never a stand-in).+ */+export function standsIn(size: string, asked: string): boolean {+ if (size === asked) return true;+ if (!validSize(size) || !sameShape(size, asked) || nvmeSize(size) !== nvmeSize(asked)) return false;+ const [one, other] = [parts(size), parts(asked)];+ if (![one, other].every((each) => each.family === "D" || each.family === "E")) return false;+ return one.features.includes("s") && ["p", "d"].every((feature) => one.features.includes(feature) === other.features.includes(feature));+}+/*** Every placement a create or wake asking for `asked` may get, in the order* tried. `sizes` are the deployment's (config.ts `sizes`), `preferred` the* size the computer last ran on, `pinnedZone` the zone of a data disk a- * host has used. Never empty: the first is `asked` or `preferred`.+ * host has used. Never empty: `asked` is always one.*/export function candidates(input: {asked: string;- sizes: string[];- zones: string[];+ sizes: readonly string[];+ zones: readonly string[];preferred?: string | null;pinnedZone?: string | null;}): Placement[] {const { asked } = input;- const fits = (size: string) => validSize(size) && sameShape(size, asked) && nvmeSize(size) === nvmeSize(asked);- const preferred = input.preferred && fits(input.preferred) ? [input.preferred] : [];- const order = [...new Set([...preferred, asked, ...input.sizes.filter(fits)])];+ const sizes = input.sizes.filter((size) => standsIn(size, asked));+ // Only while the deployment still lists it: taking a size out of the settings takes computers off it.+ const preferred = input.preferred && sizes.includes(input.preferred) ? [input.preferred] : [];+ const order = [...new Set([...preferred, asked, ...sizes])];const zones = input.pinnedZone ? [input.pinnedZone] : input.zones;return order.flatMap((size) => zones.map((zone) => ({ size, zone })));}@@ -86,5 +111,10 @@ const CAPACITY_CODES = new Set([*/export function isCapacity(code: string | null | undefined, text: string | null | undefined): boolean {if (!code) return false;- return CAPACITY_CODES.has(code) || (code === "OperationNotAllowed" && /quota/i.test(text ?? ""));+ return CAPACITY_CODES.has(code) || isQuota(code, text);+}++/** The capacity failure is a quota: the region's, so no other zone has room for this size either. */+export function isQuota(code: string | null | undefined, text: string | null | undefined): boolean {+ return code === "QuotaExceeded" || (code === "OperationNotAllowed" && /quota/i.test(text ?? ""));}diff --git a/services/managed-agents/src/computer/pool.ts b/services/managed-agents/src/computer/pool.tsindex 967d4482..6660384e 100644--- a/services/managed-agents/src/computer/pool.ts+++ b/services/managed-agents/src/computer/pool.ts@@ -311,8 +311,10 @@ export class ComputerPool {await this.gauge(live.filter((slot) => slot.state === "warm"));const provisioning = live.filter((slot) => slot.state === "provisioning").length;- const health = this.health();const warm = live.length - provisioning;+ // Full again without a start coming up (the target was lowered, or a slot came back from a claim): no longer degraded.+ if (warm >= target) this.deps.sql.exec("DELETE FROM pool_health");+ const health = this.health();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() }),diff --git a/services/managed-agents/src/platform/computers/arm.ts b/services/managed-agents/src/platform/computers/arm.tsindex 30752a6d..c670a15c 100644--- a/services/managed-agents/src/platform/computers/arm.ts+++ b/services/managed-agents/src/platform/computers/arm.ts@@ -9,6 +9,8 @@// Errors carry the HTTP status and ARM's own error code and message, never a// token or the client secret.+import { isCapacity } from "../../computer/placement.js";+export const ARM_ORIGIN = "https://management.azure.com";export const LOGIN_ORIGIN = "https://login.microsoftonline.com";@@ -89,7 +91,7 @@ export async function armError(response: Response, what: string): Promise<ArmErrlet message = "";try {const body = (await response.json()) as {- error?: string | { code?: string; message?: string };+ error?: string | { code?: string; message?: string; details?: Array<{ code?: string; message?: string }> };error_description?: string;};if (typeof body.error === "string") {@@ -99,6 +101,12 @@ export async function armError(response: Response, what: string): Promise<ArmErr} else if (body.error) {code = body.error.code ?? code;message = body.error.message ?? "";+ // A capacity or quota refusal may be wrapped (`Conflict` with the cause in `details`): the cause is what callers act on.+ const cause = isCapacity(code, message) ? undefined : body.error.details?.find((detail) => isCapacity(detail.code, detail.message));+ if (cause?.code) {+ code = cause.code;+ message = cause.message ?? message;+ }}} catch {// Not JSON: the status says enough.diff --git a/services/managed-agents/src/platform/computers/resources.ts b/services/managed-agents/src/platform/computers/resources.tsindex 269214f5..f7f1eb1c 100644--- a/services/managed-agents/src/platform/computers/resources.ts+++ b/services/managed-agents/src/platform/computers/resources.ts@@ -9,6 +9,7 @@// kept OS disk (createOption Attach: no image, no osProfile, no customData).import { computerName, isPoolId, ownerTag, validResourcePrefix } from "../../computer/names.js";+import { nvmeSize, validSize } from "../../computer/placement.js";import { API_VERSIONS, type AzureCredentials } from "./arm.js";export { computerName, validOrganizationId, validResourcePrefix } from "../../computer/names.js";@@ -106,14 +107,7 @@ const DATA_DISK_MBPS = 600;const ADMIN_USER = "azureuser";const MAX_DISK_GIB = 65_536;-/** v6 and v7 sizes (e.g. `Standard_D2as_v7`) expose disks only over NVMe. */-export function nvmeSize(size: string): boolean {- return /_v[67]$/i.test(size);-}--export function validSize(size: string): boolean {- return /^Standard_[A-Za-z0-9_]+$/.test(size);-}+export { nvmeSize, validSize };export function validDiskGiB(diskGiB: number): boolean {return Number.isInteger(diskGiB) && diskGiB >= 1 && diskGiB <= MAX_DISK_GIB;diff --git a/services/managed-agents/test/computer-azure.test.ts b/services/managed-agents/test/computer-azure.test.tsindex 774d23ad..aaa567dd 100644--- a/services/managed-agents/test/computer-azure.test.ts+++ b/services/managed-agents/test/computer-azure.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { ArmError, AzureClient, armRequest, tokenRequest } from "../src/platform/computers/arm.js";+import { ArmError, AzureClient, armError, armRequest, tokenRequest } from "../src/platform/computers/arm.js";import {type ComputerPlacement,cloudInit,@@ -306,6 +306,17 @@ describe("platform computer route", () => {expect(JSON.stringify(failed.body)).not.toContain(ENV.AZURE_CLIENT_SECRET);});+ it("reads a capacity or quota refusal out of a wrapped ARM error, and leaves any other error as it is", async () => {+ const error = async (body: unknown) => {+ const { code, message } = await armError(Response.json({ error: body }, { status: 409 }), "PUT vm");+ return `${code}|${message}`;+ };+ const quota = { code: "QuotaExceeded", message: "over the quota" };+ expect(await error({ code: "Conflict", message: "failed", details: [{ code: "Other" }, quota] })).toBe("QuotaExceeded|PUT vm: 409 QuotaExceeded: over the quota");+ expect(await error({ code: "Conflict", message: "busy", details: [{ code: "Other", message: "x" }] })).toBe("Conflict|PUT vm: 409 Conflict: busy");+ expect(await error({ code: "SkuNotAvailable", message: "none", details: [quota] })).toBe("SkuNotAvailable|PUT vm: 409 SkuNotAvailable: none");+ });+it("retries sign-in after a 401 and reports network failures as status 0", async () => {let fail = true;const client = new AzureClient({ tenantId: "t", clientId: "c401", clientSecret: "s" }, async (request) => {diff --git a/services/managed-agents/test/computer-lifecycle.test.ts b/services/managed-agents/test/computer-lifecycle.test.tsindex 8c069133..d8359e11 100644--- a/services/managed-agents/test/computer-lifecycle.test.ts+++ b/services/managed-agents/test/computer-lifecycle.test.ts@@ -2,9 +2,8 @@ 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 { missingEdgeConfig, sizes, zones } from "../src/computer/config.js";-import { ComputerLifecycle, POLL_MS, backoffMs } from "../src/computer/lifecycle.js";-import { candidates, isCapacity, sameShape, sizeShape } from "../src/computer/placement.js";+import { CAPACITY_ERROR } from "../src/computer/config.js";+import { ComputerLifecycle, type LifecycleDeps, POLL_MS, backoffMs, readAttempt } from "../src/computer/lifecycle.js";import { sqlStorage } from "./fixtures/computer-sql.js";const ORG = "org_test";@@ -124,6 +123,7 @@ let connected: boolean;let readyCalls: number;let missingEdge: string[];let lifecycle: ComputerLifecycle;+let deps: LifecycleDeps;let selfManaged: boolean;let fallbackSizes: string[];@@ -136,7 +136,7 @@ beforeEach(() => {readyCalls = 0;missingEdge = [];selfManaged = false;- lifecycle = new ComputerLifecycle({+ deps = {selfManaged: () => selfManaged,sql: sqlStorage(),cloud: () => cloud,@@ -150,9 +150,13 @@ beforeEach(() => {onReady: () => void (readyCalls += 1),now: () => now,sshPublicKey: async () => "ssh-rsa AAAA test",- });+ };+ lifecycle = new ComputerLifecycle(deps);});+/** Another computer, or (with `sql`) the same one after a restart. */+const another = (sql = sqlStorage()) => new ComputerLifecycle({ ...deps, sql });+const OPTIONS = { size: "Standard_D2as_v7", diskGiB: 128 };/** Runs alarms until the state settles (or `limit` ticks). */@@ -191,7 +195,7 @@ describe("computer lifecycle", () => {expect(await lifecycle.create(ORG, OPTIONS)).toEqual({ status: 200 });// Provisioning again over existing resources only looks: no PUT.cloud.calls = [];- (lifecycle as any).deps.sql.exec("UPDATE computer SET state = 'provisioning'");+ deps.sql.exec("UPDATE computer SET state = 'provisioning'");await settle();expect(lifecycle.row()?.state).toBe("ready");expect(cloud.calls.filter((c) => c.startsWith("PUT"))).toEqual([]);@@ -217,7 +221,7 @@ describe("computer lifecycle", () => {await settle();expect(lifecycle.row()?.state).toBe("ready");- const other = new ComputerLifecycle({ ...(lifecycle as any).deps, sql: sqlStorage() });+ const other = another();await other.create(ORG, OPTIONS);cloud.resources.clear();cloud.failNext = new CloudError(400, "InvalidParameter", "bad request");@@ -231,7 +235,7 @@ describe("computer lifecycle", () => {await lifecycle.create(ORG, OPTIONS);await settle();expect(lifecycle.row()).toMatchObject({ state: "failed", lastError: "VM provisioning failed: Allocation failed" });- expect(lifecycle.view()).toMatchObject({ state: "failed", lastError: "No capacity was available for your computer; try again in a few minutes." });+ expect(lifecycle.view()).toMatchObject({ state: "failed", lastError: CAPACITY_ERROR });cloud.vmOutcome = "Succeeded";expect(await lifecycle.create(ORG, OPTIONS)).toEqual({ status: 202 });await settle();@@ -264,20 +268,20 @@ describe("computer lifecycle", () => {});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"];+ fallbackSizes = ["Standard_D2s_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" });+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2s_v7", zone: "1" });- const other = new ComputerLifecycle({ ...(lifecycle as any).deps, sql: sqlStorage() });+ const other = another();cloud = new FakeCloud();- cloud.noCapacity = new Set(["Standard_D2as_v7", "Standard_D2ads_v7"].flatMap((size) => ["1", "2", "3"].map((zone) => `${size}@${zone}`)));+ cloud.noCapacity = new Set(["Standard_D2as_v7", "Standard_D2s_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.");+ expect(other.view()?.lastError).toBe(CAPACITY_ERROR);// Asked again, it starts over from every placement.cloud.noCapacity.delete("Standard_D2as_v7@2");await other.create(ORG, OPTIONS);@@ -296,10 +300,12 @@ describe("computer lifecycle", () => {};await lifecycle.create(ORG, OPTIONS);await settle(80);- // The quota is the region's: every zone refuses, then the next size is tried.+ // The quota is the region's: the size's other zones are not tried, and the data disk stays.expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2s_v7", zone: "1" });+ expect(cloud.vmPlacements).toEqual(["Standard_D2s_v7@1"]);+ expect(cloud.calls).not.toContain("DELETE dataDisk");- const other = new ComputerLifecycle({ ...(lifecycle as any).deps, sql: sqlStorage() });+ const other = another();cloud = new FakeCloud();cloud.putVm = async () => {throw new CloudError(409, "OperationNotAllowed", "the disk is being attached");@@ -322,7 +328,7 @@ describe("computer lifecycle", () => {await lifecycle.wake("Standard_D2as_v7");await settle(40);expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2s_v7", zone: "1", preferredSize: "Standard_D2s_v7" });- expect(JSON.parse(lifecycle.row()!.attempt!)).toEqual({+ expect(readAttempt(lifecycle.row()!)).toEqual({asked: "Standard_D2as_v7",candidates: [{ size: "Standard_D2as_v7", zone: "1" },@@ -379,11 +385,11 @@ describe("computer lifecycle", () => {tags_pending INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`);sql.exec("INSERT INTO computer (id, organization_id, state, size, disk_gib, zone, ssh_public_key, created_at, updated_at) VALUES (1, ?, 'provisioning', 'Standard_D2s_v7', 128, '1', 'k', 0, 0)", ORG);fallbackSizes = ["Standard_D2s_v7"];- const old = new ComputerLifecycle({ ...(lifecycle as any).deps, sql });+ const old = another(sql);expect(old.row()).toMatchObject({ preferredSize: "Standard_D2s_v7", attempt: null });// The backfill runs once: a later start leaves the column alone.sql.exec("UPDATE computer SET preferred_size = NULL");- expect(new ComputerLifecycle({ ...(lifecycle as any).deps, sql }).row()?.preferredSize).toBeNull();+ expect(another(sql).row()?.preferredSize).toBeNull();cloud.noCapacity = new Set(["Standard_D2s_v7@1"]);for (let i = 0; i < 20 && old.row()?.state === "provisioning"; i += 1) await old.tick();@@ -393,10 +399,6 @@ describe("computer lifecycle", () => {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) => {@@ -410,6 +412,84 @@ describe("computer lifecycle", () => {expect(lifecycle.row()).toMatchObject({ state: "ready", zone: "2" });});+ it("a refusal for capacity with nowhere left fails at once instead of retrying", async () => {+ let puts = 0;+ cloud.putVm = async () => {+ puts += 1;+ throw new CloudError(409, "SkuNotAvailable", "the requested size is currently not available");+ };+ await lifecycle.create(ORG, OPTIONS);+ await settle(60);+ // One PUT per zone, then failed: not ten attempts on the last.+ expect(puts).toBe(3);+ expect(lifecycle.row()).toMatchObject({ state: "failed", attempts: 0 });+ expect(lifecycle.view()?.lastError).toBe(CAPACITY_ERROR);+ });++ it("an instance view that cannot be read is asked for again: the reason decides the fallback", async () => {+ cloud.noCapacity = new Set(["Standard_D2as_v7@1"]);+ const get = cloud.get.bind(cloud);+ let throttled = 0;+ cloud.get = async (target, kind, options = {}) => {+ if (options.instanceView && throttled < 2) {+ throttled += 1;+ throw new CloudError(429, "TooManyRequests", "throttled");+ }+ return get(target, kind, options);+ };+ await lifecycle.create(ORG, OPTIONS);+ await settle(60);+ expect(throttled).toBe(2);+ expect(lifecycle.row()).toMatchObject({ state: "ready", zone: "2" });+ });++ it("a computer deleted and created again boots a new OS disk, and keeps its zone only while its data disk is kept", async () => {+ fallbackSizes = ["Standard_D2as_v7", "Standard_D2s_v7"];+ await lifecycle.create(ORG, OPTIONS);+ await settle();+ lifecycle.noteHostSeen();+ await lifecycle.delete();+ await settle();+ expect(lifecycle.row()).toMatchObject({ state: "deleted", dataUsed: 1 });++ // The data disk was kept: no other zone, and the OS disk a failed first try leaves is not attached.+ cloud.noCapacity = new Set(["Standard_D2as_v7@1"]);+ cloud.vmPuts = [];+ await lifecycle.create(ORG, OPTIONS);+ await settle(60);+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2s_v7", zone: "1" });+ expect(cloud.vmPuts.map((put) => put.mode)).toEqual(["create", "create"]);+ expect(cloud.vmPuts.at(-1)?.hostToken).toBe(`sph_token_for_${ORG}`);+ expect(cloud.calls).not.toContain("DELETE dataDisk");++ // Deleted with its data: created again, it may go to another zone.+ lifecycle.noteHostSeen();+ await lifecycle.delete({ deleteDisk: true });+ await settle();+ expect(lifecycle.row()).toMatchObject({ state: "deleted", dataUsed: 0 });+ cloud.noCapacity = new Set(["Standard_D2as_v7@1", "Standard_D2s_v7@1"]);+ await lifecycle.create(ORG, OPTIONS);+ await settle(60);+ expect(lifecycle.row()).toMatchObject({ state: "ready", zone: "2" });+ });++ it("a size taken out of the settings is no longer tried first", async () => {+ fallbackSizes = ["Standard_D2as_v7", "Standard_D2s_v7"];+ cloud.noCapacity = new Set(["1", "2", "3"].map((zone) => `Standard_D2as_v7@${zone}`));+ await lifecycle.create(ORG, OPTIONS);+ await settle(80);+ lifecycle.noteHostSeen();+ expect(lifecycle.row()).toMatchObject({ state: "ready", preferredSize: "Standard_D2s_v7" });+ await lifecycle.park();+ await settle();+ fallbackSizes = ["Standard_D2as_v7"];+ cloud.noCapacity = new Set();+ cloud.vmPlacements = [];+ await lifecycle.wake("Standard_D2as_v7");+ await settle();+ expect(cloud.vmPlacements).toEqual(["Standard_D2as_v7@1"]);+ });+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();@@ -420,14 +500,14 @@ describe("computer lifecycle", () => {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.");+ expect(lifecycle.view()?.lastError).toBe(CAPACITY_ERROR);- fallbackSizes = ["Standard_D2ads_v7"];+ fallbackSizes = ["Standard_D2s_v7"];await lifecycle.create(ORG, OPTIONS);await settle(40);- expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2ads_v7", zone: "1" });- expect(cloud.vmPlacements.slice(-2)).toEqual(["Standard_D2as_v7@1", "Standard_D2ads_v7@1"]);- expect(cloud.vmPuts.at(-1)).toMatchObject({ mode: "attach", size: "Standard_D2ads_v7" });+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2s_v7", zone: "1" });+ expect(cloud.vmPlacements.slice(-2)).toEqual(["Standard_D2as_v7@1", "Standard_D2s_v7@1"]);+ expect(cloud.vmPuts.at(-1)).toMatchObject({ mode: "attach", size: "Standard_D2s_v7" });expect(cloud.calls).not.toContain("DELETE dataDisk");expect(cloud.calls.filter((call) => call === "PUT dataDisk")).toHaveLength(1);});@@ -512,7 +592,7 @@ describe("computer lifecycle", () => {await lifecycle.create(ORG, OPTIONS);expect(lifecycle.row()?.resourcePrefix).toBe("oc-org-test");// A computer that changed hands keeps the name it was built under.- (lifecycle as any).deps.sql.exec("UPDATE computer SET resource_prefix = 'oc-pool-abc123'");+ deps.sql.exec("UPDATE computer SET resource_prefix = 'oc-pool-abc123'");await settle();lifecycle.noteHostSeen();await lifecycle.park();@@ -528,7 +608,7 @@ describe("computer lifecycle", () => {it("falls back to the name derived from the organization on rows from before the prefix was stored", async () => {await lifecycle.create(ORG, OPTIONS);- (lifecycle as any).deps.sql.exec("UPDATE computer SET resource_prefix = NULL");+ deps.sql.exec("UPDATE computer SET resource_prefix = NULL");await settle();expect(lifecycle.row()).toMatchObject({ state: "ready", resourcePrefix: null });expect(new Set(cloud.prefixes)).toEqual(new Set(["oc-org-test"]));@@ -541,7 +621,7 @@ describe("computer lifecycle", () => {wake_after_park INTEGER NOT NULL DEFAULT 0, delete_disk INTEGER NOT NULL DEFAULT 0, os_initialized INTEGER NOT NULL DEFAULT 0,replace_failed_vm INTEGER NOT NULL DEFAULT 0, wakes INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`);sql.exec("INSERT INTO computer (id, organization_id, state, size, disk_gib, zone, ssh_public_key, created_at, updated_at) VALUES (1, ?, 'ready', 'Standard_D2as_v7', 128, '1', 'k', 0, 0)", ORG);- const old = new ComputerLifecycle({ ...(lifecycle as any).deps, sql });+ const old = another(sql);expect(old.target(old.row()!)).toEqual({ organizationId: ORG, prefix: "oc-org-test" });});@@ -557,7 +637,7 @@ describe("computer lifecycle", () => {});it("hands a ready pool computer over once, and leaves it alone afterwards", async () => {- const pool = new ComputerLifecycle({ ...(lifecycle as any).deps, sql: sqlStorage() });+ const pool = another();expect(pool.transfer()).toBeNull();await pool.create("pool-abc123", OPTIONS);expect(pool.row()?.resourcePrefix).toBe("oc-pool-abc123");@@ -633,78 +713,6 @@ 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;- const D16 = "Standard_D16as_v7";-- it("reads the zones in the configured order; unset is 1, 2, 3", () => {- expect(zones(env({}))).toEqual(["1", "2", "3"]);- expect(zones(env({ COMPUTER_ZONES: "2, 3,2" }))).toEqual(["2", "3"]);- });-- it("the deployment's sizes are the plans' sizes, then the fallback sizes", () => {- expect(sizes(env({}))).toEqual(["Standard_D2as_v7"]);- expect(sizes(env({ COMPUTER_DEFAULT_SIZE: D16, COMPUTER_MAX_SIZE: "Standard_D32as_v7", COMPUTER_FALLBACK_SIZES: "Standard_D16s_v7, Standard_D16as_v7" }))).toEqual([- D16,- "Standard_D32as_v7",- "Standard_D16s_v7",- ]);- });-- it("a zone or size list that is not one stops creates, by name, instead of being ignored", () => {- const configured = { COMPUTERS: {}, RUNTIMES: {}, COMPUTER_HOST_GATEWAY_URL: "wss://edge.example", COMPUTER_HOST_TOKEN_KEY: "k" };- const missing = (vars: Record<string, string>) => missingEdgeConfig({ ...configured, ...vars } as never);- expect(missing({ COMPUTER_ZONES: "2,1", COMPUTER_FALLBACK_SIZES: "Standard_D16s_v7" })).toEqual([]);- expect(missing({ COMPUTER_ZONES: "east" })).toEqual(["COMPUTER_ZONES (not a list of zones 1 to 3)"]);- expect(missing({ COMPUTER_FALLBACK_SIZES: "Standard_D16s_v7;D16as_v6" })).toEqual(["COMPUTER_FALLBACK_SIZES (not a list of sizes)"]);- expect(missing({ COMPUTER_VMS: "self-managed", COMPUTER_ZONES: "east" })).toEqual([]);- });-- it("knows a size's shape, low-memory sizes included", () => {- expect(sizeShape("Standard_D16as_v7")).toEqual({ vcpus: 16, memoryGiB: 64 });- expect(sizeShape("Standard_D16als_v7")).toEqual({ vcpus: 16, memoryGiB: 32 });- expect(sizeShape("Standard_D16ls_v6")).toEqual({ vcpus: 16, memoryGiB: 32 });- expect(sizeShape("Standard_E8as_v7")).toEqual({ vcpus: 8, memoryGiB: 64 });- expect(sizeShape("Standard_F4s_v2")).toEqual({ vcpus: 4, memoryGiB: 8 });- expect(sameShape("Standard_D16as_v7", "Standard_D16s_v7")).toBe(true);- expect(sameShape("Standard_D16as_v7", "Standard_D16als_v7")).toBe(false);- });-- it("tries the size asked for in every zone, then each other size of its shape and disk controller", () => {- const all = ["Standard_D16ads_v7", "Standard_D8as_v7", "Standard_D16as_v5", "Standard_E16as_v7", "Standard_D16als_v7", "bogus", D16, "Standard_D16as_v6"];- expect(candidates({ asked: D16, sizes: all, zones: ["3", "1"] })).toEqual([- { size: D16, zone: "3" },- { size: D16, zone: "1" },- { size: "Standard_D16ads_v7", zone: "3" },- { size: "Standard_D16ads_v7", zone: "1" },- { size: "Standard_D16as_v6", zone: "3" },- { size: "Standard_D16as_v6", zone: "1" },- ]);- expect(candidates({ asked: "Standard_D8as_v7", sizes: all, zones: ["1"] })).toEqual([{ size: "Standard_D8as_v7", zone: "1" }]);- });-- it("puts the size last run on first when it has the shape asked for, and keeps a used disk's zone", () => {- const input = { asked: D16, sizes: [D16, "Standard_D16s_v7"], zones: ["1", "2"] };- const order = (extra: object) => candidates({ ...input, ...extra }).map((placement) => `${placement.size}@${placement.zone}`);- expect(order({ preferred: "Standard_D16s_v7" })).toEqual(["Standard_D16s_v7@1", "Standard_D16s_v7@2", `${D16}@1`, `${D16}@2`]);- // A size no longer configured is still the computer's own.- expect(order({ preferred: "Standard_D16as_v6", pinnedZone: "2" })).toEqual(["Standard_D16as_v6@2", `${D16}@2`, "Standard_D16s_v7@2"]);- // Another shape (the plan changed) or disk controller: not tried.- expect(order({ preferred: "Standard_D2as_v7", pinnedZone: "2" })).toEqual([`${D16}@2`, "Standard_D16s_v7@2"]);- expect(order({ preferred: "Standard_D16as_v5", pinnedZone: "2" })).toEqual([`${D16}@2`, "Standard_D16s_v7@2"]);- });-- it("tells capacity and quota from other failures by ARM's code", () => {- for (const code of ["ZonalAllocationFailed", "AllocationFailed", "OverconstrainedZonalAllocationRequest", "OverconstrainedAllocationRequest", "SkuNotAvailable", "QuotaExceeded"]) {- expect(isCapacity(code, null)).toBe(true);- }- expect(isCapacity("OperationNotAllowed", "exceeding approved standardDSv7Family Cores quota")).toBe(true);- expect(isCapacity("OperationNotAllowed", "the disk is being attached")).toBe(false);- expect(isCapacity("Conflict", "Allocation failed")).toBe(false);- expect(isCapacity(undefined, "quota")).toBe(false);- });-});-describe("self-managed VMs", () => {beforeEach(() => {selfManaged = true;diff --git a/services/managed-agents/test/computer-placement.test.ts b/services/managed-agents/test/computer-placement.test.tsnew file mode 100644index 00000000..8b733cc0--- /dev/null+++ b/services/managed-agents/test/computer-placement.test.ts@@ -0,0 +1,128 @@+import { readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { describe, expect, it } from "vitest";++import { missingEdgeConfig, sizes, zones } from "../src/computer/config.js";+import { candidates, isCapacity, isQuota, sameShape, sizeShape, standsIn } from "../src/computer/placement.js";++// Work 106: where a computer may be built (placement.ts) and the settings that say so (config.ts).+const env = (vars: Record<string, string>) => vars as never;+const D16 = "Standard_D16as_v7";++describe("placement settings", () => {+ const configured = { COMPUTERS: {}, RUNTIMES: {}, COMPUTER_HOST_GATEWAY_URL: "wss://edge.example", COMPUTER_HOST_TOKEN_KEY: "k", COMPUTER_DEFAULT_SIZE: D16 };+ const missing = (vars: Record<string, string>) => missingEdgeConfig({ ...configured, ...vars } as never);++ it("reads the zones in the configured order; unset is 1, 2, 3", () => {+ expect(zones(env({}))).toEqual(["1", "2", "3"]);+ expect(zones(env({ COMPUTER_ZONES: "2, 3,2" }))).toEqual(["2", "3"]);+ });++ it("the deployment's sizes are the plans' sizes, then the fallback sizes", () => {+ expect(sizes(env({}))).toEqual(["Standard_D2as_v7"]);+ expect(sizes(env({ COMPUTER_DEFAULT_SIZE: D16, COMPUTER_MAX_SIZE: "Standard_D32as_v7", COMPUTER_FALLBACK_SIZES: "Standard_D16s_v7, Standard_D16as_v7" }))).toEqual([+ D16,+ "Standard_D32as_v7",+ "Standard_D16s_v7",+ ]);+ });++ it("a zone or size list that is not one stops creates, by name, instead of being ignored", () => {+ expect(missing({ COMPUTER_ZONES: "2,1", COMPUTER_FALLBACK_SIZES: "Standard_D16s_v7" })).toEqual([]);+ expect(missing({ COMPUTER_ZONES: "east" })).toEqual(["COMPUTER_ZONES (not a list of zones 1 to 3)"]);+ expect(missing({ COMPUTER_FALLBACK_SIZES: "Standard_D16s_v7;D16as_v6" })).toEqual(["COMPUTER_FALLBACK_SIZES (not a list of sizes)"]);+ expect(missing({ COMPUTER_VMS: "self-managed", COMPUTER_ZONES: "east" })).toEqual([]);+ });++ it("a fallback size no plan's size could use stops creates too: a typo, another shape, arm64", () => {+ expect(missing({ COMPUTER_FALLBACK_SIZES: "Standard_D16s_v7,Standard_D8s_v7,Standard_D16ps_v6" })).toEqual([+ "COMPUTER_FALLBACK_SIZES (Standard_D8s_v7, Standard_D16ps_v6 cannot stand in for Standard_D16as_v7)",+ ]);+ expect(missing({ COMPUTER_MAX_SIZE: "Standard_D32as_v7", COMPUTER_FALLBACK_SIZES: "Standard_D32s_v7" })).toEqual([]);+ });++ it("the committed production settings are valid", () => {+ // Comments in the file are whole lines.+ const text = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../wrangler.production.jsonc"), "utf8").replace(/^\s*\/\/.*$/gm, "");+ const vars = (JSON.parse(text) as { vars: Record<string, string> }).vars;+ expect(missingEdgeConfig({ ...configured, ...vars } as never)).toEqual([]);+ });+});++describe("placements", () => {+ it.each([+ ["Standard_D2as_v7", 2, 8],+ [D16, 16, 64],+ ["Standard_D16als_v7", 16, 32],+ ["Standard_D16ls_v6", 16, 32],+ ["Standard_E8as_v7", 8, 64],+ ["Standard_E16-8as_v5", 16, 128],+ ["Standard_F4s_v2", 4, 8],+ ["garbage", 2, 8],+ ])("%s is %i vCPUs and %i GiB", (size, vcpus, memoryGiB) => {+ expect(sizeShape(size)).toEqual({ vcpus, memoryGiB });+ });++ it.each([+ ["Standard_D16s_v7", true],+ ["Standard_D16as_v6", true],+ [D16, true],+ // Half the memory, another controller, arm64, a local disk, no premium storage, a family whose memory the name does not tell.+ ["Standard_D16als_v7", false],+ ["Standard_D16as_v5", false],+ ["Standard_D16ps_v6", false],+ ["Standard_D16ads_v7", false],+ ["Standard_D16a_v7", false],+ ["Standard_F32as_v7", false],+ ["Standard_DC16as_v6", false],+ ["Standard_D8as_v7", false],+ ["bogus", false],+ ])("%s stands in for Standard_D16as_v7: %s", (size, expected) => {+ expect(standsIn(size, D16)).toBe(expected);+ expect(sameShape(D16, "Standard_D16s_v7")).toBe(true);+ });++ it("tries the size asked for in every zone, then each other size that can stand in for it", () => {+ const all = ["Standard_D16s_v7", "Standard_D8as_v7", "Standard_D16as_v5", "Standard_E16as_v7", "Standard_D16als_v7", "bogus", D16, "Standard_D16as_v6"];+ expect(candidates({ asked: D16, sizes: all, zones: ["3", "1"] })).toEqual([+ { size: D16, zone: "3" },+ { size: D16, zone: "1" },+ { size: "Standard_D16s_v7", zone: "3" },+ { size: "Standard_D16s_v7", zone: "1" },+ { size: "Standard_D16as_v6", zone: "3" },+ { size: "Standard_D16as_v6", zone: "1" },+ ]);+ expect(candidates({ asked: "Standard_D8as_v7", sizes: all, zones: ["1"] })).toEqual([{ size: "Standard_D8as_v7", zone: "1" }]);+ // A size the deployment does not list is still built when asked for.+ expect(candidates({ asked: "Standard_F4s_v2", sizes: [], zones: ["2"] })).toEqual([{ size: "Standard_F4s_v2", zone: "2" }]);+ });++ it("puts the size last run on first while the deployment lists it, and keeps a used disk's zone", () => {+ const input = { asked: D16, sizes: [D16, "Standard_D16s_v7"], zones: ["1", "2"] };+ const order = (extra: object) => candidates({ ...input, ...extra }).map((placement) => `${placement.size}@${placement.zone}`);+ expect(order({ preferred: "Standard_D16s_v7" })).toEqual(["Standard_D16s_v7@1", "Standard_D16s_v7@2", `${D16}@1`, `${D16}@2`]);+ expect(order({ preferred: "Standard_D16s_v7", pinnedZone: "2" })).toEqual(["Standard_D16s_v7@2", `${D16}@2`]);+ // No longer listed, another shape (the plan changed) or another disk controller: not tried.+ for (const preferred of ["Standard_D16as_v6", "Standard_D2as_v7", "Standard_D16as_v5"]) {+ expect(order({ preferred, pinnedZone: "2" })).toEqual([`${D16}@2`, "Standard_D16s_v7@2"]);+ }+ });++ it.each([+ ["ZonalAllocationFailed", null, true, false],+ ["AllocationFailed", null, true, false],+ ["OverconstrainedZonalAllocationRequest", null, true, false],+ ["OverconstrainedAllocationRequest", null, true, false],+ ["SkuNotAvailable", null, true, false],+ ["QuotaExceeded", null, true, true],+ ["OperationNotAllowed", "exceeding approved standardDSv7Family Cores quota", true, true],+ ["OperationNotAllowed", "the disk is being attached", false, false],+ ["Conflict", "Allocation failed", false, false],+ [undefined, "quota", false, false],+ ])("code %s (%s): capacity %s, quota %s", (code, text, capacity, quota) => {+ expect(isCapacity(code, text)).toBe(capacity);+ expect(isQuota(code, text)).toBe(quota);+ });+});diff --git a/services/managed-agents/test/computer-units.test.ts b/services/managed-agents/test/computer-units.test.tsindex eede04d4..2042a32f 100644--- a/services/managed-agents/test/computer-units.test.ts+++ b/services/managed-agents/test/computer-units.test.ts@@ -2,7 +2,6 @@ import { describe, expect, it, vi } from "vitest";import { verifySlackSignature } from "../src/channels/slack-events.js";import { gatewayUrl, publicError, sizeFor } from "../src/computer/config.js";-import { sizeShape } from "../src/computer/placement.js";import { bytesToBase64Url, seal, unseal } from "../src/computer/crypto.js";import { DEFINITION_REPO_LIMIT, EAGER_REPO_COUNT, selectTokenTarget, workspaceDefinition } from "../src/computer/github.js";import { constantTimeEqual, hostAuthorized, hostToken } from "../src/computer/host-token.js";@@ -68,7 +67,7 @@ describe("host tokens", () => {});describe("computer config and vocabulary", () => {- it("sizes by plan and describes sizes without naming them", () => {+ it("sizes by plan", () => {const env = { ACCOUNTS: {} as DurableObjectNamespace };expect(sizeFor(env, "default")).toBe("Standard_D2as_v7");expect(sizeFor({ ...env, COMPUTER_MAX_SIZE: "Standard_D8as_v7" }, "max")).toBe("Standard_D8as_v7");@@ -77,9 +76,6 @@ describe("computer config and vocabulary", () => {expect(sizeFor({ ...env, COMPUTER_PAID_SIZE: "Standard_D4as_v7" }, "max")).toBe("Standard_D4as_v7");expect(sizeFor({ ...env, COMPUTER_PAID_SIZE: "Standard_D4as_v7", COMPUTER_MAX_SIZE: "Standard_D8as_v7" }, "max")).toBe("Standard_D8as_v7");expect(sizeFor({ ...env, COMPUTER_MAX_SIZE: "" }, "max")).toBe("Standard_D2as_v7");- expect(sizeShape("Standard_D2as_v7")).toEqual({ vcpus: 2, memoryGiB: 8 });- expect(sizeShape("Standard_E4as_v7")).toEqual({ vcpus: 4, memoryGiB: 32 });- expect(sizeShape("Standard_D16as_v7")).toEqual({ vcpus: 16, memoryGiB: 64 });});it("builds the gateway URL the host dials", () => {diff --git a/services/managed-agents/vitest.config.ts b/services/managed-agents/vitest.config.tsindex b1889d2d..3f96aeb4 100644--- a/services/managed-agents/vitest.config.ts+++ b/services/managed-agents/vitest.config.ts@@ -489,6 +489,7 @@ export default defineConfig({"test/computer-azure.test.ts","test/computer-billing.test.ts","test/computer-lifecycle.test.ts",+ "test/computer-placement.test.ts","test/computer-pool.test.ts","test/computer-pool-probe.test.ts","test/computer-token-check.test.ts",