An open-source, faster Devin alternative
TypeScript
computer: remember each computer's size, fall back on quota, placement in its own module
Igor Zalutski via Computerae014b57ee41
diff --git a/services/managed-agents/README.md b/services/managed-agents/README.mdindex abb4b956..d9348e07 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_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 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` || 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`,@@ -154,6 +154,16 @@ already set on the Worker. The vars live in `wrangler.production.jsonc` and`wrangler.platform.jsonc` (`COMPUTER_POOL_SIZE` stays `"0"` and the Azure idsempty until the production infrastructure exists).+Capacity (work 106, `src/computer/placement.ts`): when the cloud has no+capacity 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.+Size (2026-10-13): only the $200 usage plan ("max", the billingadmission's `usagePlan`) gets `COMPUTER_MAX_SIZE`; Pro and free get thedefault. Every organization claims the warm pool's default-size computer; adiff --git a/services/managed-agents/src/computer/config.ts b/services/managed-agents/src/computer/config.tsindex b71f9f07..d44e64bd 100644--- a/services/managed-agents/src/computer/config.ts+++ b/services/managed-agents/src/computer/config.ts@@ -4,6 +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 type { PreviewsEnv } from "./previews.js";/** Preview URLs (work 074, previews.ts): off unless all of PreviewsEnv is set. */@@ -41,9 +42,10 @@ export interface ComputerEdgeEnv extends PreviewsEnv {*/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.+ * Work 106: more sizes a computer may be built on, in order, once no zone+ * has capacity for the one asked for (e.g. "Standard_D16s_v7,Standard_D16as_v6").+ * Each is used for the sizes it matches in vCPUs, memory and disk+ * controller (placement.ts); unset: none.*/COMPUTER_FALLBACK_SIZES?: string;COMPUTER_DEFAULT_DISK_GIB?: string;@@ -105,8 +107,6 @@ 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; 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 +131,9 @@ export function missingEdgeConfig(env: ComputerEdgeEnv): string[] {if (!selfManagedVms(env)) {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 (!env.COMPUTER_HOST_TOKEN_KEY) missing.push("COMPUTER_HOST_TOKEN_KEY");return missing;@@ -142,41 +145,27 @@ 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;+function list(value: string | undefined): string[] {+ return (value ?? "")+ .split(",")+ .map((item) => item.trim())+ .filter(Boolean);}-/** COMPUTER_ZONES in order, without repeats or anything that is not a zone; none left: the default order. */+/** 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 = (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;+ const listed = [...new Set(list(env.COMPUTER_ZONES).filter((zone) => ZONES.includes(zone)))];+ return listed.length ? listed : 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).+ * Work 106: every size this deployment builds computers on, in the order+ * tried when one has no capacity: the plans' sizes, then+ * COMPUTER_FALLBACK_SIZES. A create or wake uses those of its own shape+ * (placement.ts `candidates`).*/-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 sizes(env: ComputerEdgeEnv): string[] {+ return [...new Set([sizeFor(env, "default"), sizeFor(env, "max"), ...list(env.COMPUTER_FALLBACK_SIZES)])].filter(validSize);}export function defaultDiskGiB(env: ComputerEdgeEnv): number {@@ -204,18 +193,6 @@ export function slackRedirectUri(env: ComputerEdgeEnv): string {return `${publicOrigin(env)}/api/managed-agents/computer/slack/callback`;}-/**- * vCPUs and memory of a size, without naming it: `Standard_D2as_v7` → 2- * vCPUs, 8 GiB. D sizes have 4 GiB per vCPU, E 8, F 2.- */-export function sizeShape(size: string): { vcpus: number; memoryGiB: number } {- const match = size.match(/^Standard_([A-Z]+)(\d+)/i);- const family = match?.[1]?.toUpperCase() ?? "D";- const vcpus = Number(match?.[2] ?? 2);- const perVcpu = family.startsWith("E") ? 8 : family.startsWith("F") ? 2 : 4;- return { vcpus, memoryGiB: vcpus * perVcpu };-}-export type PublicComputerState = "provisioning" | "ready" | "parked" | "waking" | "failed" | "deleting";/** The dashboard's `Computer` (work 052, API contract): no cloud, region, size or host names. */diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.tsindex b9e50a98..6f9d7185 100644--- a/services/managed-agents/src/computer/durable-object.ts+++ b/services/managed-agents/src/computer/durable-object.ts@@ -84,13 +84,13 @@ import {gatewayUrl,maxDiskGiB,missingEdgeConfig,- placements,selfManagedVms,publicOrigin,sizeFor,- sizeShape,+ sizes,zones,} from "./config.js";+import { sizeShape } from "./placement.js";import { DEFAULT_HARNESS, computerHarnesses, harnessOnProfile, helloProfiles, profileHarnesses, takeHarnessPrefix } from "./harnesses.js";import { type SealPurpose, seal, sha256Hex, unseal } from "./crypto.js";import { type DiskReport, diskDecision } from "./disk-growth.js";@@ -528,7 +528,8 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {},setAlarm: (at) => this.schedule("lifecycle", at),hostConnected: () => this.socket() !== undefined,- placements: (size) => placements(env, size),+ zones: () => zones(env),+ sizes: () => sizes(env),selfManaged: () => selfManagedVms(env),onReady: () => {this.noteActivity();@@ -1367,7 +1368,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {}const reply =(await this.claimFromPool(accountId)) ??- (await this.lifecycle.create(accountId, { size, diskGiB: defaultDiskGiB(this.env), zone: zones(this.env)[0]! }));+ (await this.lifecycle.create(accountId, { size, diskGiB: defaultDiskGiB(this.env) }));if (reply.status === 202) this.noteActivity();return reply;}@@ -1531,7 +1532,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: zones(this.env)[0]! });+ return this.lifecycle.create(poolId, { size: sizeFor(this.env, "default"), diskGiB: defaultDiskGiB(this.env) });}poolComputerStatus(poolId: string): PoolSlotStatus {@@ -3150,7 +3151,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: zones(this.env)[0]! });+ await this.lifecycle.create(accountId, { size: sizeFor(this.env, "default"), diskGiB: defaultDiskGiB(this.env) });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.tsindex d76c8731..615a3c13 100644--- a/services/managed-agents/src/computer/lifecycle.ts+++ b/services/managed-agents/src/computer/lifecycle.ts@@ -22,12 +22,15 @@// 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.+// Capacity (work 106, placement.ts): a create or wake works out, once, every+// placement it may try (`attempt`): the size the computer last ran on+// (`preferred_size`), the size asked for, then the deployment's other sizes+// of that shape, each in every zone. When the cloud has no capacity or quota+// for the row's size in its zone, the row moves to the next one 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@@ -43,16 +46,9 @@import type { CloudResource, CloudResourceKind, CloudTarget } from "./cloud-contract.js";import { CloudError, type ComputerCloud } from "./cloud.js";-import {- ComputersNotConfigured,- type Placement,- type PublicComputer,- type PublicComputerState,- nvmeSize,- publicError,- sizeShape,-} from "./config.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";export type ComputerState =| "provisioning"@@ -78,11 +74,10 @@ 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[];+ /** 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[];/** 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. */@@ -92,9 +87,9 @@ export interface LifecycleDeps {}export interface CreateOptions {+ /** The size asked for (the plan's); with no capacity for it, another of its shape (placement.ts). */size: string;diskGiB: number;- zone: string;/** Resource name prefix; default the one derived from the organization id. */prefix?: string;}@@ -141,12 +136,25 @@ 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;+ /** The size the computer last became ready on: tried first when it is built again. Null: never ready. */+ preferredSize: string | null;+ /** JSON `Attempt`: the placements of the create or wake under way (or last run). Null on rows from before work 106. */+ attempt: string | null;createdAt: number;updatedAt: number;};+/**+ * 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). */+ asked: string;+ candidates: Placement[];+ index: number;+}+/** Not worth retrying: the request itself is wrong, or a resource is not ours. */class Fatal extends Error {}@@ -165,7 +173,7 @@ const SELECT = `SELECT organization_id AS organizationId, state, size, disk_gibssh_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,- placements_tried AS placementsTried, created_at AS createdAt,+ preferred_size AS preferredSize, attempt, created_at AS createdAt,updated_at AS updatedAt FROM computer WHERE id = 1`;const PUBLIC_STATE: Record<Exclude<ComputerState, "deleted" | "transferred">, PublicComputerState> = {@@ -180,23 +188,6 @@ const PUBLIC_STATE: Record<Exclude<ComputerState, "deleted" | "transferred">, Pudeleting: "deleting",};-/** 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 {- return /^Standard_[A-Za-z0-9_]+$/.test(size);-}-export class ComputerLifecycle {constructor(private readonly deps: LifecycleDeps) {deps.sql.exec(`@@ -218,15 +209,18 @@ export class ComputerLifecycle {resource_prefix TEXT,pool_slot TEXT,tags_pending INTEGER NOT NULL DEFAULT 0,- placements_tried TEXT,+ preferred_size TEXT,+ attempt 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", "placements_tried TEXT"]) {+ for (const column of ["resource_prefix TEXT", "pool_slot TEXT", "tags_pending INTEGER NOT NULL DEFAULT 0", "preferred_size TEXT", "attempt TEXT"]) {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.}@@ -306,28 +300,34 @@ export class ComputerLifecycle {if (row && row.state !== "failed" && row.state !== "deleted") return { status: 200 };if (row) {// Again after a failure or a delete: same names, so kept disks are reused.- // The size is the configured one again (a failure may be the size's- // capacity); the disk stays what it was unless the computer was deleted.+ // The size asked for is the configured one again and every placement is+ // tried anew (a failure may be capacity); the disk stays what it was+ // unless the computer was deleted.+ const first = this.begin(row, options.size);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, placements_tried = NULL, updated_at = ?,- size = ?,+ delete_disk = 0, replace_failed_vm = 1, updated_at = ?,+ size = ?, zone = ?, attempt = ?,disk_gib = CASE WHEN state = 'deleted' THEN ? ELSE disk_gib ENDWHERE id = 1`,now,- options.size,+ first.size,+ first.zone,+ first.attempt,options.diskGiB,);} else {+ const first = this.begin(null, options.size);this.deps.sql.exec(- `INSERT INTO computer (id, organization_id, state, size, disk_gib, zone, ssh_public_key, resource_prefix, created_at, updated_at)- VALUES (1, ?, 'provisioning', ?, ?, ?, ?, ?, ?, ?)`,+ `INSERT INTO computer (id, organization_id, state, size, disk_gib, zone, ssh_public_key, resource_prefix, attempt, created_at, updated_at)+ VALUES (1, ?, 'provisioning', ?, ?, ?, ?, ?, ?, ?, ?)`,organizationId,- options.size,+ first.size,options.diskGiB,- options.zone,+ first.zone,sshPublicKey,options.prefix ?? computerName(organizationId),+ first.attempt,now,now,);@@ -361,7 +361,7 @@ export class ComputerLifecycle {organizationId,options.size,options.diskGiB,- options.zone,+ this.zones()[0]!,options.prefix ?? computerName(organizationId),now,now,@@ -375,11 +375,36 @@ 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+ * (null: none): its last size goes first, and a data disk a host has used+ * keeps its zone.+ */+ private begin(row: ComputerRow | null, asked: string): Placement & { attempt: string } {+ const all = candidates({+ asked,+ sizes: this.deps.sizes?.() ?? [],+ zones: this.zones(),+ preferred: row?.preferredSize,+ pinnedZone: row?.osInitialized ? row.zone : null,+ });+ const attempt: Attempt = { asked, candidates: all, index: 0 };+ return { ...all[0]!, attempt: JSON.stringify(attempt) };+ }+/*** Wakes a parked computer (or one being parked, once it is). True if it is- * now waking or will be. With `size`, the VM comes back on that size (the+ * now waking or will be. With `size`, that is the size asked for (the* organization's plan's: a downsize happens here, never on a running- * computer); a size on another disk controller is ignored.+ * computer); a size on another disk controller is ignored. Without, the+ * size it had. The VM comes back on the size it last ran on when that has+ * the shape asked for, else on the size asked for (`begin`).*/async wake(size?: string): Promise<boolean> {const row = this.row();@@ -396,10 +421,16 @@ 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);this.deps.sql.exec(`UPDATE computer SET state = 'waking', attempts = 0, last_error = NULL, wakes = wakes + 1,- placements_tried = NULL, updated_at = ?+ size = ?, zone = ?, attempt = ?, updated_at = ?WHERE id = 1 AND state = 'parked'`,+ first.size,+ first.zone,+ first.attempt,this.now(),);await this.deps.setAlarm(this.now());@@ -446,11 +477,12 @@ export class ComputerLifecycle {if (this.row()) return false;const now = this.now();this.deps.sql.exec(- `INSERT INTO computer (id, organization_id, state, 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,resource_prefix, pool_slot, tags_pending, created_at, updated_at)- VALUES (1, ?, 'ready', ?, ?, ?, ?, 1, ?, ?, 1, ?, ?)`,+ VALUES (1, ?, 'ready', ?, ?, ?, ?, ?, 1, ?, ?, 1, ?, ?)`,organizationId,computer.size,+ computer.size,computer.diskGiB,computer.zone,computer.sshPublicKey,@@ -554,7 +586,9 @@ export class ComputerLifecycle {error instanceof Fatal ||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 }));+ console.error(+ JSON.stringify({ level: "error", event: "computer.lifecycle_error", accountId: row.organizationId, state: row.state, attempts, fatal, message: text }),+ );// 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);@@ -643,8 +677,8 @@ export class ComputerLifecycle {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;+ // 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;}}@@ -663,7 +697,19 @@ export class ComputerLifecycle {} catch (error) {console.warn(JSON.stringify({ level: "warn", event: "computer.os_disk_tag_failed", message: message(error) }));}- this.transition(row.state, "ready", null);+ this.ready(row);+ const attempt = this.attempt(row);+ console.log(+ JSON.stringify({+ level: "info",+ event: "computer.placed",+ accountId: org,+ state: row.state,+ size: row.size,+ zone: row.zone,+ ...(attempt ? { asked: attempt.asked, index: attempt.index, of: attempt.candidates.length } : {}),+ }),+ );this.deps.onReady?.();return null;}@@ -673,7 +719,7 @@ export class ComputerLifecycle {if (!vm) throw new Fatal("the VM no longer exists");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);+ this.ready(row);// Messages queued during the restart go now.this.deps.onReady?.();return null;@@ -711,37 +757,44 @@ 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 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.+ * 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.*/private fallBack(row: ComputerRow, reason: string): boolean {+ const attempt = this.attempt(row);+ const to = attempt?.candidates[attempt.index + 1];+ if (!attempt || !to) return false;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;+ const index = attempt.index + 1;this.deps.sql.exec(- `UPDATE computer SET size = ?, zone = ?, placements_tried = ?, replace_failed_vm = 1, attempts = 0, last_error = ?, updated_at = ?+ `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(tried),+ JSON.stringify({ ...attempt, index }),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 }),+ JSON.stringify({+ level: "warn",+ event: "computer.capacity_fallback",+ accountId: row.organizationId,+ state: row.state,+ from,+ to,+ index,+ of: attempt.candidates.length,+ message: reason,+ }),);return true;}@@ -770,7 +823,7 @@ export class ComputerLifecycle {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: CAPACITY_CODES.has(vm.failureCode ?? "") };+ return { text: `VM provisioning failed: ${code}${vm.failure}`, capacity: isCapacity(vm.failureCode, vm.failure) };}} catch {// The plain message below is enough.@@ -778,6 +831,15 @@ export class ComputerLifecycle {return { text: "VM provisioning failed", capacity: false };}+ /** Built, woken or resized: ready, and its size is the one to try first next time. */+ private ready(row: ComputerRow): void {+ this.deps.sql.exec(+ "UPDATE computer SET state = 'ready', last_error = NULL, preferred_size = size, updated_at = ? WHERE id = 1 AND state = ?",+ this.now(),+ row.state,+ );+ }+private transition(from: ComputerState, to: ComputerState, error: string | null): void {this.deps.sql.exec("UPDATE computer SET state = ?, last_error = ?, updated_at = ? WHERE id = 1 AND state = ?",diff --git a/services/managed-agents/src/computer/placement.ts b/services/managed-agents/src/computer/placement.tsnew file mode 100644index 00000000..8747ff05--- /dev/null+++ b/services/managed-agents/src/computer/placement.ts@@ -0,0 +1,90 @@+// Where a computer's VM is built (work 106): the sizes and zones a create or+// 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.++/** Where a computer's VM and its zonal data disk are. */+export interface Placement {+ size: string;+ zone: string;+}++/** Premium SSD v2 needs a zone; the numbers are the subscription's own (logical) zones. */+export const ZONES = ["1", "2", "3"];++export function validSize(size: string): boolean {+ return /^Standard_[A-Za-z0-9_]+$/.test(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);+}++/**+ * vCPUs and memory of a size, without naming it: `Standard_D2as_v7` → 2+ * vCPUs, 8 GiB. D sizes have 4 GiB per vCPU (2 for the low-memory `l`+ * 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 perVcpu = family.startsWith("E") ? 8 : family.startsWith("F") || lowMemory ? 2 : 4;+ return { vcpus, memoryGiB: vcpus * perVcpu };+}++export function sameShape(a: string, b: string): boolean {+ const [one, other] = [sizeShape(a), sizeShape(b)];+ return one.vcpus === other.vcpus && one.memoryGiB === other.memoryGiB;+}++/**+ * 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`.+ */+export function candidates(input: {+ asked: string;+ sizes: string[];+ zones: 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 zones = input.pinnedZone ? [input.pinnedZone] : input.zones;+ return order.flatMap((size) => zones.map((zone) => ({ size, zone })));+}++/** ARM's codes for "no capacity for this size here". */+const CAPACITY_CODES = new Set([+ "ZonalAllocationFailed",+ "AllocationFailed",+ "OverconstrainedZonalAllocationRequest",+ "OverconstrainedAllocationRequest",+ "SkuNotAvailable",+ "QuotaExceeded",+]);++/**+ * The cloud has no room for this VM here, by its error code: no capacity+ * for the size in the zone, or the size family's quota is used up (ARM+ * says that as `OperationNotAllowed`, which has other meanings too, so the+ * message must name the quota). Another placement may have room.+ */+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 ?? ""));+}diff --git a/services/managed-agents/test/computer-lifecycle.test.ts b/services/managed-agents/test/computer-lifecycle.test.tsindex 5cba0aa8..8c069133 100644--- a/services/managed-agents/test/computer-lifecycle.test.ts+++ b/services/managed-agents/test/computer-lifecycle.test.ts@@ -2,8 +2,9 @@ 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 { 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 { sqlStorage } from "./fixtures/computer-sql.js";const ORG = "org_test";@@ -144,14 +145,15 @@ 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 }))),+ zones: () => ["1", "2", "3"],+ sizes: () => fallbackSizes,onReady: () => void (readyCalls += 1),now: () => now,sshPublicKey: async () => "ssh-rsa AAAA test",});});-const OPTIONS = { size: "Standard_D2as_v7", diskGiB: 128, zone: "1" };+const OPTIONS = { size: "Standard_D2as_v7", diskGiB: 128 };/** Runs alarms until the state settles (or `limit` ticks). */async function settle(limit = 20) {@@ -283,6 +285,112 @@ describe("computer lifecycle", () => {expect(other.row()).toMatchObject({ state: "ready", size: "Standard_D2as_v7", zone: "2" });});+ it("a size family out of quota falls back like one out of capacity; another refusal of the same code does not", async () => {+ fallbackSizes = ["Standard_D2s_v7"];+ const put = cloud.putVm.bind(cloud);+ cloud.putVm = async (target, spec) => {+ if (spec.size === "Standard_D2as_v7") {+ throw new CloudError(409, "OperationNotAllowed", "Operation could not be completed as it results in exceeding approved standardDASv7Family Cores quota.");+ }+ return put(target, spec);+ };+ await lifecycle.create(ORG, OPTIONS);+ await settle(80);+ // The quota is the region's: every zone refuses, then the next size is tried.+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2s_v7", zone: "1" });++ const other = new ComputerLifecycle({ ...(lifecycle as any).deps, sql: sqlStorage() });+ cloud = new FakeCloud();+ cloud.putVm = async () => {+ throw new CloudError(409, "OperationNotAllowed", "the disk is being attached");+ };+ await other.create(ORG, OPTIONS);+ for (let i = 0; i < 6; i += 1) await other.tick();+ expect(other.row()).toMatchObject({ state: "provisioning", size: "Standard_D2as_v7", zone: "1", lastError: "the disk is being attached" });+ });++ it("remembers the size it last ran on and tries it first, so a computer that fell back does not fail first on every wake", async () => {+ fallbackSizes = ["Standard_D2s_v7"];+ await lifecycle.create(ORG, OPTIONS);+ await settle();+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2as_v7", preferredSize: "Standard_D2as_v7" });+ lifecycle.noteHostSeen();+ await lifecycle.park();+ await settle();++ cloud.noCapacity = new Set(["Standard_D2as_v7@1"]);+ 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({+ asked: "Standard_D2as_v7",+ candidates: [+ { size: "Standard_D2as_v7", zone: "1" },+ { size: "Standard_D2s_v7", zone: "1" },+ ],+ index: 1,+ });++ // The plan still asks for the first size; the computer goes straight to the one that worked.+ await lifecycle.park();+ await settle();+ cloud.vmPlacements = [];+ await lifecycle.wake("Standard_D2as_v7");+ await settle(40);+ expect(cloud.vmPlacements).toEqual(["Standard_D2s_v7@1"]);+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2s_v7" });++ // That size gone too: back to the one asked for.+ await lifecycle.park();+ await settle();+ cloud.noCapacity = new Set(["Standard_D2s_v7@1"]);+ cloud.vmPlacements = [];+ await lifecycle.wake("Standard_D2as_v7");+ await settle(40);+ expect(cloud.vmPlacements).toEqual(["Standard_D2s_v7@1", "Standard_D2as_v7@1"]);+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2as_v7", preferredSize: "Standard_D2as_v7" });+ expect(cloud.calls).not.toContain("DELETE dataDisk");+ });++ it("a plan of another shape overrides the remembered size, on waking and while parking", async () => {+ await lifecycle.create(ORG, { ...OPTIONS, size: "Standard_D8as_v7" });+ await settle();+ lifecycle.noteHostSeen();+ await lifecycle.park();+ await settle();+ await lifecycle.wake("Standard_D2as_v7");+ await settle();+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D2as_v7", preferredSize: "Standard_D2as_v7" });++ await lifecycle.park();+ await lifecycle.tick();+ expect(lifecycle.row()?.state).toBe("parking");+ await lifecycle.wake("Standard_D8as_v7");+ await settle();+ expect(lifecycle.row()).toMatchObject({ state: "ready", size: "Standard_D8as_v7", preferredSize: "Standard_D8as_v7" });+ });++ it("a computer from before placements were stored keeps its size first, and one under way then fails on capacity as before", async () => {+ const sql = sqlStorage();+ sql.exec(`CREATE TABLE computer (id INTEGER PRIMARY KEY, organization_id TEXT NOT NULL, state TEXT NOT NULL, size TEXT NOT NULL,+ disk_gib INTEGER NOT NULL, zone TEXT NOT NULL, ssh_public_key TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT,+ 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, resource_prefix TEXT, pool_slot TEXT,+ 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 });+ 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();++ cloud.noCapacity = new Set(["Standard_D2s_v7@1"]);+ for (let i = 0; i < 20 && old.row()?.state === "provisioning"; i += 1) await old.tick();+ expect(old.row()).toMatchObject({ state: "failed", size: "Standard_D2s_v7", zone: "1" });+ expect(cloud.vmPlacements).toEqual(["Standard_D2s_v7@1"]);+ });+it("a capacity refusal of the VM PUT itself falls back too", async () => {await lifecycle.create(ORG, OPTIONS);await lifecycle.tick();@@ -318,6 +426,7 @@ describe("computer lifecycle", () => {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(cloud.calls).not.toContain("DELETE dataDisk");expect(cloud.calls.filter((call) => call === "PUT dataDisk")).toHaveLength(1);@@ -526,25 +635,73 @@ 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("tries every zone in the configured order; unset or nonsense is 1, 2, 3", () => {+ 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,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" },+ 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("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",+ 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(placements(env(vars), "Standard_D8as_v7").map((placement) => placement.size)).toEqual(["Standard_D8as_v7"]);+ 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);});});diff --git a/services/managed-agents/test/computer-units.test.ts b/services/managed-agents/test/computer-units.test.tsindex 4466e84e..eede04d4 100644--- a/services/managed-agents/test/computer-units.test.ts+++ b/services/managed-agents/test/computer-units.test.ts@@ -1,7 +1,8 @@import { describe, expect, it, vi } from "vitest";import { verifySlackSignature } from "../src/channels/slack-events.js";-import { gatewayUrl, publicError, sizeFor, sizeShape } from "../src/computer/config.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";