An open-source, faster Devin alternative
TypeScript
fix(microvm): stop the pool stranding quota on drain, reclaim orphans, and skip the dead VM-DO hop on every exec
Brian Reardonc79c7e7dd6e5
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex a06b589d..d1a4eeaf 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -930,6 +930,10 @@ async function handlePreviewURL(// ── route handlers ───────────────────────────────────────────────────────// OrgPolicy is the subset of the D1 `orgs` row the create/fork paths gate on.+// Mirrors runtimeMicrovm in internal/api/backend.go — the value stored in+// orgs.runtime that routes an org's creates to the AWS MicroVM backend.+const RUNTIME_MICROVM = "microvm";+interface OrgPolicy {home_cell: string;plan: string;@@ -1822,6 +1826,16 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>// path can't be used to exec on another org's sandbox. See vm_session.ts.async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, authMs = 0): Promise<Response | null> {if (!env.VM_SESSIONS) return null; // binding absent mid-cutover → tunnel+ // MicroVM-backed orgs never have a live VmSession: the host dialer that opens+ // the channel is a QEMU-worker component (internal/worker/dodialer.go), and a+ // MicroVM box has no worker behind it. So the DO can only ever answer "not+ // connected" — but it answers that only AFTER its 400ms entry grace+ // (vm_session.ts), which exists to absorb a hibernated-DO wake race that this+ // backend cannot have. Measured on prod: that grace was ~437ms of every+ // MicroVM exec — 79% of benchmark TTI, against a control plane that served+ // the exec itself in 10ms. Skip straight to the tunnel.+ const orgPolicy = await loadOrgPolicy(env, caller.orgID);+ if (orgPolicy?.runtime === RUNTIME_MICROVM) return null;const tRoute = Date.now();const route = await resolveSandboxRoute(env, id);const routeMs = Date.now() - tRoute;diff --git a/cmd/microvmreap/main.go b/cmd/microvmreap/main.gonew file mode 100644index 00000000..34d87157--- /dev/null+++ b/cmd/microvmreap/main.go@@ -0,0 +1,165 @@+// microvmreap terminates a specific, explicitly-listed set of MicroVMs.+//+// It exists because a drain that fires every TerminateMicrovm at once against a+// 10/s quota gets most of them throttled, and a throttled terminate used to be+// logged and dropped — stranding the box for the full 8h service cap while it+// kept billing and kept holding the regional memory quota that caps pool depth.+// On 2026-08-18 a single 255-box drain stranded 114 boxes that way.+//+// Deliberately NOT a discovery tool. It reads ids from a file and can act on+// nothing else. This account is shared, so a reaper that decided for itself+// what looked abandoned could terminate another environment's fleet, and a+// terminate is irreversible. Building the id list is a human's job — the safest+// source being ids the control plane already logged a failed terminate for,+// which are provably ours because we tried to kill them ourselves.+//+// Reports by default; --confirm is required to terminate.+//+// microvmreap --ids /tmp/leaked.txt --region us-east-1+// microvmreap --ids /tmp/leaked.txt --region us-east-1 --confirm+package main++import (+ "bufio"+ "context"+ "flag"+ "fmt"+ "os"+ "strings"+ "time"++ awscfg "github.com/aws/aws-sdk-go-v2/config"++ "github.com/opensandbox/opensandbox/internal/awsvm"+)++// terminateInterval paces terminate calls under the 10/s quota, leaving room+// for the control plane's own destroys — the whole point is to not recreate the+// throttling storm that caused the leak.+const terminateInterval = 125 * time.Millisecond++func main() {+ idsPath := flag.String("ids", "", "file of MicroVM ids, one per line (required)")+ region := flag.String("region", "", "AWS region (default: AWS_REGION)")+ confirm := flag.Bool("confirm", false, "actually terminate; without it, report only")+ flag.Parse()++ if *idsPath == "" {+ fmt.Fprintln(os.Stderr, "--ids is required")+ os.Exit(2)+ }+ ids, err := readIDs(*idsPath)+ if err != nil {+ fmt.Fprintf(os.Stderr, "read ids: %v\n", err)+ os.Exit(1)+ }+ if len(ids) == 0 {+ fmt.Fprintln(os.Stderr, "id list is empty — nothing to do")+ os.Exit(1)+ }++ ctx := context.Background()+ opts := []func(*awscfg.LoadOptions) error{}+ if *region != "" {+ opts = append(opts, awscfg.WithRegion(*region))+ }+ acfg, err := awscfg.LoadDefaultConfig(ctx, opts...)+ if err != nil {+ fmt.Fprintf(os.Stderr, "aws config: %v\n", err)+ os.Exit(1)+ }+ client := awsvm.NewClient(acfg, awsvm.Config{Region: acfg.Region})++ fmt.Printf("microvmreap: %d id(s) from %s, region=%s, confirm=%v\n\n", len(ids), *idsPath, acfg.Region, *confirm)++ // Pass 1 — establish what is actually still out there. A box that already+ // aged out costs nothing and must not be counted as reclaimed.+ var alive []string+ var gone, unknown int+ for _, id := range ids {+ box, err := client.Get(ctx, id)+ switch {+ case err != nil:+ unknown+++ fmt.Printf(" %s UNREADABLE (%v)\n", id, err)+ case !box.Alive():+ gone+++ default:+ alive = append(alive, id)+ fmt.Printf(" %s %s started=%s age=%s\n",+ id, box.State, box.StartedAt.Format(time.RFC3339), time.Since(box.StartedAt).Round(time.Minute))+ }+ }++ fmt.Printf("\nalive=%d already-gone=%d unreadable=%d\n", len(alive), gone, unknown)+ if len(alive) == 0 {+ fmt.Println("nothing to reclaim.")+ return+ }+ if !*confirm {+ fmt.Printf("\nREPORT ONLY — re-run with --confirm to terminate these %d box(es).\n", len(alive))+ return+ }++ // Pass 2 — terminate, paced, with retries. Client.Terminate classifies+ // throttling, so a throttled call is retried rather than dropped.+ fmt.Printf("\nterminating %d box(es) at %v intervals...\n", len(alive), terminateInterval)+ var ok, failed int+ for i, id := range alive {+ if i > 0 {+ time.Sleep(terminateInterval)+ }+ if err := terminateWithRetry(ctx, client, id); err != nil {+ failed+++ fmt.Printf(" FAIL %s: %v\n", id, err)+ continue+ }+ ok+++ }+ fmt.Printf("\nreclaimed %d, failed %d, of %d alive\n", ok, failed, len(alive))+ if failed > 0 {+ os.Exit(1)+ }+}++func terminateWithRetry(ctx context.Context, c *awsvm.Client, id string) error {+ backoff := 250 * time.Millisecond+ var err error+ for attempt := 1; attempt <= 6; attempt++ {+ if err = c.Terminate(ctx, id); err == nil {+ return nil+ }+ if !isThrottle(err) {+ return err+ }+ time.Sleep(backoff)+ backoff *= 2+ }+ return err+}++func isThrottle(err error) bool {+ return err != nil && strings.Contains(err.Error(), "Throttl")+}++func readIDs(path string) ([]string, error) {+ f, err := os.Open(path)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ seen := map[string]bool{}+ var ids []string+ s := bufio.NewScanner(f)+ for s.Scan() {+ line := strings.TrimSpace(s.Text())+ // Only accept the id shape, so a stray log line in the file can never+ // be interpreted as something to terminate.+ if !strings.HasPrefix(line, "microvm-") || seen[line] {+ continue+ }+ seen[line] = true+ ids = append(ids, line)+ }+ return ids, s.Err()+}diff --git a/internal/api/create_flow.go b/internal/api/create_flow.goindex 2a8a7187..4e267d0f 100644--- a/internal/api/create_flow.go+++ b/internal/api/create_flow.go@@ -6,12 +6,18 @@ import ("fmt""log""net/http"+ "time""github.com/labstack/echo/v4""github.com/opensandbox/opensandbox/internal/awsvm")+// createTimingLogThreshold is the total above which runCreate logs its per-step+// breakdown. A warm pooled claim lands well under this, so steady state stays+// silent and only creates worth explaining show up.+const createTimingLogThreshold = 50 * time.Millisecond+// create_flow.go — the order a sandbox comes into existence, independent of the// runtime that hosts it.//@@ -62,13 +68,33 @@ type createSteps struct {// persist, and one that could not activate must not promote. Both mistakes// produce a row the system believes in and no host behind it.func runCreate(ctx context.Context, sandboxID string, steps createSteps) (workerID string, err error) {+ // Per-step timings. The four steps have wildly different costs depending on+ // backend — a pooled MicroVM claim is an in-memory pop while persist is two+ // Postgres writes — and the request log only reports the total, which left+ // a 200ms create unattributable. Logged above a threshold so the normal+ // path stays quiet.+ start := time.Now()+ var claimMs, persistMs, activateMs, promoteMs int64+ defer func() {+ total := time.Since(start)+ if total >= createTimingLogThreshold {+ log.Printf("create: %s timings total=%dms claim=%dms persist=%dms activate=%dms promote=%dms",+ sandboxID, total.Milliseconds(), claimMs, persistMs, activateMs, promoteMs)+ }+ }()++ t := time.Now()workerID, err = steps.claim(ctx)+ claimMs = time.Since(t).Milliseconds()if err != nil {return "", err}if steps.persist != nil {- if err := steps.persist(ctx, workerID); err != nil {+ t = time.Now()+ err := steps.persist(ctx, workerID)+ persistMs = time.Since(t).Milliseconds()+ if err != nil {if steps.persistRequired {// Nothing else knows this host exists, so continuing would hand// out a sandbox no sweep can ever reclaim.@@ -87,7 +113,10 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker}if steps.activate != nil {- if err := steps.activate(ctx, workerID); err != nil {+ t = time.Now()+ err := steps.activate(ctx, workerID)+ activateMs = time.Since(t).Milliseconds()+ if err != nil {if steps.cleanup != nil {steps.cleanup(ctx, workerID, err)}@@ -96,7 +125,10 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker}if steps.promote != nil {- if err := steps.promote(ctx, workerID); err != nil {+ t = time.Now()+ err := steps.promote(ctx, workerID)+ promoteMs = time.Since(t).Milliseconds()+ if err != nil {// The sandbox is up; only the row lags. Same reasoning as persist.log.Printf("create: promote failed for %s on %s: %v", sandboxID, workerID, err)}diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.goindex a8910528..e002bf25 100644--- a/internal/api/microvm_backend.go+++ b/internal/api/microvm_backend.go@@ -305,6 +305,7 @@ func (b *microvmBackend) StartReconciler(ctx context.Context, store *db.Store) {returncase <-t.C:b.reconcileOnce(ctx, store)+ b.sweepOrphans(ctx)}}}()@@ -373,6 +374,114 @@ func (b *microvmBackend) reconcileOnce(ctx context.Context, store *db.Store) {}}+// orphanMinAge is how old a MicroVM must be before the sweep will consider it+// abandoned. A box is invisible to us for a real window during its own creation+// — launched but not yet stocked, or claimed but not yet tracked — and reaping+// one mid-flight would kill a sandbox a customer is actively waiting on. Well+// above the worst-case launch (~1.5s) plus a claim.+const orphanMinAge = 20 * time.Minute++// orphanReapCap bounds one sweep. A sweep that suddenly wants to terminate+// hundreds of boxes is far more likely to be wrong about ownership than to have+// found hundreds of real orphans, so it stops and says so instead. Mirrors+// foreignReapCap on the QEMU side.+const orphanReapCap = 25++// sweepOrphans terminates MicroVMs that exist in AWS but that nothing here owns.+//+// This is the leak reconcileOnce structurally cannot see: that pass walks+// persisted rows and asks AWS about each one, so it only ever finds boxes we+// still have a record of. A box whose row was deleted — or that was launched+// into stock and abandoned when a terminate came back throttled, or when the+// process died before Drain ran — is referenced by nothing and is therefore+// invisible to every existing sweep. It keeps billing, and keeps holding the+// regional memory quota that caps pool depth, until the 8h service cap.+//+// SAFETY: this account is shared with dev, and a terminate is irreversible. The+// sweep therefore refuses to act on anything it cannot positively attribute:+// it only considers boxes built from the exact image this cell launches, and+// only those old enough that no in-flight create could still be adopting them.+// Even then it defaults to REPORT-ONLY — set OPENSANDBOX_MICROVM_ORPHAN_REAP=1+// to let it terminate. Run it in report mode first and read the log: if it+// names boxes that belong to another environment, the image guard is not+// enough discrimination for this account and the boxes need real tagging+// before this is armed.+func (b *microvmBackend) sweepOrphans(ctx context.Context) {+ if b == nil || b.client == nil {+ return+ }+ boxes, err := b.client.List(ctx)+ if err != nil {+ log.Printf("microvm: orphan sweep list failed: %v", err)+ return+ }++ known := b.pool.StockIDs()+ for id := range b.manager.TrackedMicrovmIDs() {+ known[id] = struct{}{}+ }++ ourImage := b.client.Config().ImageIdentifier+ armed := envInt("OPENSANDBOX_MICROVM_ORPHAN_REAP", 0) == 1++ var orphans []string+ var skippedYoung, skippedForeign int+ for _, box := range boxes {+ if !box.Alive() {+ continue // already terminating; nothing to reclaim+ }+ if _, ok := known[box.ID]; ok {+ continue+ }+ // Never reap a box we did not build. Without this the sweep would+ // happily terminate another environment's pool out from under it.+ if ourImage != "" && box.ImageArn != "" && box.ImageArn != ourImage {+ skippedForeign+++ continue+ }+ // An unset StartedAt must protect the box, not expose it. The API does+ // not always populate it (observed empty on real Get responses), and+ // time.Since(zero) is enormous — so a naive age comparison reads+ // "ancient" for exactly the boxes whose age we failed to learn, turning+ // the guard inside out and making unknown boxes the most eligible.+ if box.StartedAt.IsZero() || time.Since(box.StartedAt) < orphanMinAge {+ skippedYoung+++ continue+ }+ orphans = append(orphans, box.ID)+ }++ if len(orphans) == 0 {+ if skippedYoung > 0 || skippedForeign > 0 {+ log.Printf("microvm: orphan sweep clean (skipped %d too-young, %d foreign-image)", skippedYoung, skippedForeign)+ }+ return+ }++ capped := orphans+ if len(capped) > orphanReapCap {+ capped = capped[:orphanReapCap]+ log.Printf("microvm: orphan sweep found %d orphan(s) — capped at %d this pass; if that count is real it will drain over subsequent passes, and if it is not, the cap just prevented a mass mistake",+ len(orphans), orphanReapCap)+ }++ if !armed {+ log.Printf("microvm: orphan sweep REPORT-ONLY — %d unowned box(es) holding quota: %v (set OPENSANDBOX_MICROVM_ORPHAN_REAP=1 to reclaim)",+ len(orphans), capped)+ return+ }++ var reaped int+ for _, id := range capped {+ if err := b.client.Terminate(ctx, id); err != nil {+ log.Printf("microvm: orphan sweep terminate %s: %v", id, err)+ continue+ }+ reaped+++ }+ log.Printf("microvm: orphan sweep reclaimed %d of %d unowned box(es)", reaped, len(orphans))+}+// Kill terminates a MicroVM-backed sandbox. Reports whether this backend owned// it, so the caller can fall through to the worker path when it did not.func (b *microvmBackend) Kill(ctx context.Context, sandboxID string) (bool, error) {diff --git a/internal/awsvm/client.go b/internal/awsvm/client.goindex 9d16af2f..e3608c59 100644--- a/internal/awsvm/client.go+++ b/internal/awsvm/client.go@@ -308,7 +308,10 @@ func (c *Client) Terminate(ctx context.Context, id string) error {if _, err := c.api.TerminateMicrovm(ctx, &lambdamicrovms.TerminateMicrovmInput{MicrovmIdentifier: aws.String(id),}); err != nil {- return fmt.Errorf("awsvm: terminate microvm %s: %w", id, err)+ // Classified so callers can distinguish throttling — which is worth+ // retrying, because an abandoned terminate leaks the box's quota until+ // the 8h cap — from a terminal failure, which is not.+ return fmt.Errorf("awsvm: terminate microvm %s: %w", id, classifyLaunchError(err))}c.forgetToken(id)return nildiff --git a/internal/awsvm/manager.go b/internal/awsvm/manager.goindex 8097eabf..07475b97 100644--- a/internal/awsvm/manager.go+++ b/internal/awsvm/manager.go@@ -92,29 +92,44 @@ func (m *Manager) TrackClaimed(sandboxID string, e *StockEntry, cfg types.Sandbo}}-// Default sizing for a MicroVM whose SandboxConfig does not state one.+// What a MicroVM actually gets, regardless of what the create asked for.//-// These are NOT cosmetic: the usage ticker reads memoryMB/cpuCount off List()-// and puts them in every usage_tick, which is what pro-tier metering prices on.-// Left at zero — which is what a create without an explicit size, or a Restore-// after a control-plane restart, would otherwise produce — every sandbox meters-// as if it consumed nothing.+// These are NOT cosmetic and they are NOT defaults: the usage ticker reads+// memoryMB/cpuCount off List() and puts them in every usage_tick, which is what+// pro-tier metering prices on. Whatever is recorded here is what the customer+// is billed for.//// 2048 MiB matches the image's minimumMemoryInMiB, and Lambda gives a full vCPU// at that baseline (peak scales to 4x).const (- defaultMicrovmMemoryMB = 2048- defaultMicrovmCPUCount = 1+ deliveredMicrovmMemoryMB = 2048+ deliveredMicrovmCPUCount = 1)-func (m *Manager) Track(sandboxID string, box *Box, cfg types.SandboxConfig) {- memoryMB, cpuCount := cfg.MemoryMB, cfg.CpuCount- if memoryMB <= 0 {- memoryMB = defaultMicrovmMemoryMB- }- if cpuCount <= 0 {- cpuCount = defaultMicrovmCPUCount+// deliveredSize reports what the platform actually provides, which on this+// backend has nothing to do with what was requested.+//+// RunMicrovmInput has no memory or vCPU field — sizing is a property of the+// IMAGE, and the seven-operation API has no way to change it before or after+// launch. So a create asking for 8 GB gets the image baseline either way.+//+// This used to record the REQUESTED size, which was never sent to AWS but was+// still what the meter charged for: ask for 8 GB, receive the baseline, pay for+// 8 GB. A silent overcharge that scaled with the size of the ask. Metering the+// delivered size is the only honest reading, and the mismatch is logged rather+// than swallowed so an operator can see demand the image cannot satisfy.+func deliveredSize(sandboxID string, requestedMemoryMB, requestedCPUCount int) (memoryMB, cpuCount int) {+ if requestedMemoryMB > deliveredMicrovmMemoryMB || requestedCPUCount > deliveredMicrovmCPUCount {+ log.Printf("awsvm: %s requested %dMB/%dcpu but this backend delivers %dMB/%dcpu — "++ "metering the delivered size (the platform has no sizing knob)",+ sandboxID, requestedMemoryMB, requestedCPUCount,+ deliveredMicrovmMemoryMB, deliveredMicrovmCPUCount)}+ return deliveredMicrovmMemoryMB, deliveredMicrovmCPUCount+}++func (m *Manager) Track(sandboxID string, box *Box, cfg types.SandboxConfig) {+ memoryMB, cpuCount := deliveredSize(sandboxID, cfg.MemoryMB, cfg.CpuCount)m.mu.Lock()m.byID[sandboxID] = &entry{sandboxID: sandboxID,@@ -187,6 +202,19 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S}, nil}+// TrackedMicrovmIDs returns every MicroVM this manager is routing a sandbox to.+// The orphan sweep subtracts these (plus warm stock) from what AWS reports, so+// whatever is left over is genuinely owned by nobody.+func (m *Manager) TrackedMicrovmIDs() map[string]struct{} {+ m.mu.RLock()+ defer m.mu.RUnlock()+ ids := make(map[string]struct{}, len(m.byID))+ for _, e := range m.byID {+ ids[e.microvmID] = struct{}{}+ }+ return ids+}+func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {e, err := m.lookup(id)if err != nil {@@ -598,8 +626,30 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPireturn nil}+// UpdateSandboxSecret injects or replaces a secret in a running sandbox.+//+// The QEMU backend routes this through its in-guest secrets proxy, which does+// not exist here — there is no worker host to run one. The agent's SetEnvs+// reaches the same place over the tunnel every exec already uses, so the value+// lands in the environment new processes inherit.+//+// Note the narrower promise than QEMU's proxy: processes ALREADY running keep+// the old environment, because a process's environment cannot be rewritten from+// outside. Anything that needs the new value must be restarted.func (m *Manager) UpdateSandboxSecret(ctx context.Context, sandboxID, secretName, value string) (bool, error) {- return false, unsupported("UpdateSandboxSecret")+ if secretName == "" {+ return false, fmt.Errorf("awsvm: %s: empty secret name", sandboxID)+ }+ a, err := m.agent(sandboxID)+ if err != nil {+ return false, err+ }+ if _, err := a.client.SetEnvs(ctx, &pb.SetEnvsRequest{+ Envs: map[string]string{secretName: value},+ }); err != nil {+ return false, fmt.Errorf("awsvm: %s: set secret %s: %w", sandboxID, secretName, err)+ }+ return true, nil}// ReadFileStream streams a file out of the guest.@@ -701,12 +751,89 @@ func (m *Manager) WriteFileStream(ctx context.Context, sandboxID, path string, mreturn resp.BytesWritten, nil}+// RebootSandbox restarts a sandbox on a clean host, preserving its workspace.+//+// There is no reboot API — the seven MicroVM operations are Run, Get, Suspend,+// Resume, Terminate, List and CreateAuthToken. So a reboot is assembled from+// the pieces hibernate already uses: capture the workspace, throw the host+// away, launch a replacement from the image, and unpack into it.+//+// That is a stronger guarantee than a soft reboot, not a weaker one. The+// replacement boots from the image snapshot, so the kernel, the process table+// and anything a runaway process dirtied outside the workspace are all genuinely+// new — where a soft reboot leaves the same disk in place.+//+// The cost is real and worth stating: this is a full export/import round trip+// (~3.3s floor plus workspace size), not the sub-second restart a QEMU reboot+// gives. And what survives is /home/sandbox — anything installed elsewhere came+// from the image and comes back from the image, but anything installed+// elsewhere AT RUNTIME does not.func (m *Manager) RebootSandbox(ctx context.Context, sandboxID string) error {- return unsupported("RebootSandbox")+ e, err := m.lookup(sandboxID)+ if err != nil {+ return err+ }++ rc, _, err := m.ExportWorkspace(ctx, sandboxID)+ if err != nil {+ return fmt.Errorf("awsvm: reboot %s: capture workspace: %w", sandboxID, err)+ }+ defer rc.Close()++ // Launch the replacement BEFORE terminating the old host. If Run fails —+ // quota, throttling, a bad image — the sandbox is still alive and the reboot+ // simply did not happen, which is far better than a customer left with+ // neither host nor a way back.+ box, err := m.client.Run(ctx, "")+ if err != nil {+ return fmt.Errorf("awsvm: reboot %s: launch replacement: %w", sandboxID, err)+ }+ ready, err := m.client.WaitRunning(ctx, box.ID, 60*time.Second)+ if err != nil {+ go func() { _ = m.client.Terminate(context.WithoutCancel(ctx), box.ID) }()+ return fmt.Errorf("awsvm: reboot %s: replacement never became ready: %w", sandboxID, err)+ }++ oldID := e.microvmID+ // Drop before tracking: the pooled gRPC connection is keyed by sandbox id+ // and the sandbox now lives on a different host entirely.+ m.agents.drop(sandboxID)+ m.Track(sandboxID, ready, types.SandboxConfig{+ SandboxID: sandboxID, Template: e.template,+ MemoryMB: e.memoryMB, CpuCount: e.cpuCount,+ })++ if err := m.ImportWorkspace(ctx, sandboxID, rc); err != nil {+ // The replacement is unusable. Terminate it and put the tracking back on+ // the original, which is still running — the customer keeps the sandbox+ // they had rather than losing it to a failed reboot.+ go func() { _ = m.client.Terminate(context.WithoutCancel(ctx), ready.ID) }()+ m.agents.drop(sandboxID)+ m.Track(sandboxID, &Box{ID: oldID, Endpoint: e.endpoint, StartedAt: e.startedAt}, types.SandboxConfig{+ SandboxID: sandboxID, Template: e.template,+ MemoryMB: e.memoryMB, CpuCount: e.cpuCount,+ })+ return fmt.Errorf("awsvm: reboot %s: restore workspace: %w", sandboxID, err)+ }++ // Only now is the old host redundant.+ go func() { _ = m.client.Terminate(context.WithoutCancel(ctx), oldID) }()+ log.Printf("awsvm: reboot %s: %s -> %s (workspace preserved)", sandboxID, oldID, ready.ID)+ return nil}+// PowerCycleSandbox is a reboot on this backend.+//+// On QEMU the two differ: reboot asks the guest to restart, power-cycle kills+// QEMU and starts it again. Here even the gentler path already replaces the+// host, so there is no harsher one to escalate to — and pretending otherwise by+// leaving this unsupported would make callers implement a fallback that does+// exactly what this does.+//+// Returns 0 for the pid the QEMU implementation reports; there is no host+// process here to name.func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (int, error) {- return 0, unsupported("PowerCycleSandbox")+ return 0, m.RebootSandbox(ctx, sandboxID)}func (m *Manager) TemplateCachePath(templateID, filename string) string { return "" }diff --git a/internal/awsvm/pool.go b/internal/awsvm/pool.goindex 9a9f379b..87ae884d 100644--- a/internal/awsvm/pool.go+++ b/internal/awsvm/pool.go@@ -2,6 +2,7 @@ package awsvmimport ("context"+ "errors""log""sync""time"@@ -125,6 +126,13 @@ type Pool struct {mu sync.Mutexstock []*StockEntry+ // backoffUntil suppresses launches after the account hits its regional+ // memory quota. Without it the ticker keeps firing doomed RunMicrovm calls+ // — a 402 fails instantly, so inflight drops straight back and the next+ // tick launches again, producing a permanent LaunchInterval-rate storm of+ // failures (measured on prod: ~4/s indefinitely, each with SDK retries+ // behind it, on a 2-vCPU control plane that also serves creates).+ backoffUntil time.Time// inflight counts launches that have called RunMicrovm but are still// waiting to reach RUNNING. Without it the ticker sees a low Depth() and// keeps launching, overshooting the target by however many boxes fit in one@@ -192,9 +200,21 @@ func (p *Pool) Run(ctx context.Context) {// for the box to reach RUNNING. Doing that inline would pace the// pool at boot time rather than at the quota, turning a parallel// fill into a serial one.+ if p.launchSuppressed() {+ continue+ }if p.committed() < p.cfg.TargetStock {go func() {if err := p.launchOne(ctx); err != nil {+ // Quota exhaustion is a standing condition, not a+ // transient one: capacity frees up when boxes age out+ // or are terminated, on a scale of minutes. Retrying at+ // tick rate cannot fix it and merely burns CPU and API+ // budget, so stand down and re-probe once per cooldown.+ if errors.Is(err, ErrQuotaExceeded) {+ p.suppressLaunches(quotaCooldown, err)+ return+ }log.Printf("awsvm: pool launch failed: %v", err)}}()@@ -206,6 +226,35 @@ func (p *Pool) Run(ctx context.Context) {}}+// quotaCooldown is how long the pool stops launching after the account reports+// its regional memory quota exhausted. Long enough that a full pool's worth of+// failures collapses into one probe per minute; short enough that capacity+// freed by retirement is picked up promptly.+const quotaCooldown = time.Minute++// launchSuppressed reports whether launches are standing down after a quota+// rejection. One probe per cooldown still gets through, so the pool refills on+// its own once capacity returns — no operator action, no restart.+func (p *Pool) launchSuppressed() bool {+ p.mu.Lock()+ defer p.mu.Unlock()+ return time.Now().Before(p.backoffUntil)+}++// suppressLaunches stands the launch loop down for d. Logged once per cooldown+// rather than once per attempt: the old behaviour buried every other log line+// on the cell under identical quota errors.+func (p *Pool) suppressLaunches(d time.Duration, cause error) {+ p.mu.Lock()+ already := time.Now().Before(p.backoffUntil)+ p.backoffUntil = time.Now().Add(d)+ depth := len(p.stock)+ p.mu.Unlock()+ if !already {+ log.Printf("awsvm: pool launches paused for %s — %v (depth=%d/%d)", d, cause, depth, p.cfg.TargetStock)+ }+}+// launchOne adds a single box to stock: run it, mint its token, park it.// committed is stock plus launches still in flight — what the pool will have// once everything settles, and therefore the right number to compare against@@ -357,12 +406,53 @@ func (p *Pool) terminate(e *StockEntry) {p.terminateID(e.MicrovmID)}+// terminateInterval paces TerminateMicrovm starts. The quota is 10/s; 8/s+// leaves room for the reconciler and customer destroys, which draw on the same+// bucket. Without pacing, draining a full pool fires every terminate at once+// and most of them come back throttled.+const terminateInterval = 125 * time.Millisecond++// terminateAttempts bounds retries of a throttled terminate. Giving up leaks+// the box for up to the 8h service cap — it keeps billing and, worse, keeps+// holding the regional memory quota that caps pool depth. So a terminate is+// worth retrying properly rather than logging and walking away.+const terminateAttempts = 6+func (p *Pool) terminateID(id string) {- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)defer cancel()- if err := p.client.Terminate(ctx, id); err != nil {- log.Printf("awsvm: pool terminate %s: %v", id, err)+ backoff := 250 * time.Millisecond+ for attempt := 1; ; attempt++ {+ err := p.client.Terminate(ctx, id)+ if err == nil {+ return+ }+ // Only throttling is worth retrying: a box that is already gone, or an+ // id we are not allowed to touch, will fail identically every time.+ if !errors.Is(err, ErrThrottled) || attempt >= terminateAttempts {+ log.Printf("awsvm: pool terminate %s (attempt %d): %v", id, attempt, err)+ return+ }+ select {+ case <-time.After(backoff):+ case <-ctx.Done():+ log.Printf("awsvm: pool terminate %s abandoned after %d attempt(s) — box will hold quota until the age cap", id, attempt)+ return+ }+ backoff *= 2+ }+}++// StockIDs returns the MicrovmIDs currently parked in stock. Used by the orphan+// sweep to tell a box we are deliberately holding from one nothing owns.+func (p *Pool) StockIDs() map[string]struct{} {+ p.mu.Lock()+ defer p.mu.Unlock()+ ids := make(map[string]struct{}, len(p.stock))+ for _, e := range p.stock {+ ids[e.MicrovmID] = struct{}{}}+ return ids}// Drain terminates all stock. Called on shutdown so a restarting filler does not@@ -374,8 +464,16 @@ func (p *Pool) Drain() {p.stock = nilp.mu.Unlock()+ // Paced, not a fan-out. Firing every terminate at once against a 10/s quota+ // means most come back throttled, and a throttled terminate used to be+ // logged and dropped — which is how a restart stranded most of a pool.+ // Starts are paced; each terminate then runs concurrently so its retries+ // don't serialize behind the next box.+ tick := time.NewTicker(terminateInterval)+ defer tick.Stop()var wg sync.WaitGroupfor _, e := range stock {+ <-tick.Cwg.Add(1)go func(e *StockEntry) {defer wg.Done()diff --git a/internal/awsvm/pool_test.go b/internal/awsvm/pool_test.goindex 3f3f39ea..732e90da 100644--- a/internal/awsvm/pool_test.go+++ b/internal/awsvm/pool_test.go@@ -21,13 +21,23 @@ type poolAPI struct {gets inttokens intterminates []string+ // runErr, when set, makes every RunMicrovm fail with it — for exercising+ // the launch loop's reaction to a standing AWS-side rejection.+ runErr error+ // terminateFailures throttles that many TerminateMicrovm calls before+ // letting one through, reproducing a quota-pressed account.+ terminateFailures int}func (f *poolAPI) RunMicrovm(_ context.Context, _ *lambdamicrovms.RunMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {f.mu.Lock()f.runs++id := fmt.Sprintf("mvm-%d", f.runs)+ runErr := f.runErrf.mu.Unlock()+ if runErr != nil {+ return nil, runErr+ }return &lambdamicrovms.RunMicrovmOutput{MicrovmId: aws.String(id),Endpoint: aws.String(id + ".microvm.aws.dev"),@@ -64,6 +74,14 @@ func (f *poolAPI) CreateMicrovmAuthToken(_ context.Context, in *lambdamicrovms.Cfunc (f *poolAPI) TerminateMicrovm(_ context.Context, in *lambdamicrovms.TerminateMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error) {f.mu.Lock()+ // Throttle the first terminateFailures calls, as a quota-pressed account+ // does. Only successes are recorded, so a test asserting on terminates is+ // asserting the box actually went away.+ if f.terminateFailures > 0 {+ f.terminateFailures--+ f.mu.Unlock()+ return nil, &types.ThrottlingException{}+ }f.terminates = append(f.terminates, aws.ToString(in.MicrovmIdentifier))f.mu.Unlock()return &lambdamicrovms.TerminateMicrovmOutput{}, nil@@ -242,3 +260,82 @@ func TestZeroTargetStockKeepsPoolEmpty(t *testing.T) {t.Fatal("claimed a box from a pool configured to hold none")}}++// A quota-exhausted account must not be retried at tick rate. RunMicrovm fails+// instantly with 402, so inflight drops straight back and the next tick launches+// again — an unbounded failure storm that cannot possibly succeed, since quota+// only frees on the scale of minutes. Observed on prod as ~4 failed launches per+// second, indefinitely, on the same 2-vCPU host that serves customer creates.+func TestQuotaExhaustionPausesLaunches(t *testing.T) {+ p, f := testPool(t, PoolConfig{TargetStock: 5, LaunchInterval: 5 * time.Millisecond})+ f.mu.Lock()+ f.runErr = &types.ServiceQuotaExceededException{}+ f.mu.Unlock()++ ctx, cancel := context.WithCancel(context.Background())+ go p.Run(ctx)+ // Long enough for ~60 ticks. Pre-fix this produced ~60 RunMicrovm calls.+ time.Sleep(300 * time.Millisecond)+ cancel()++ runs, _, _ := f.counts()+ if runs > 5 {+ t.Fatalf("quota-exhausted pool kept launching: %d RunMicrovm calls in 300ms (want it to stand down after the first)", runs)+ }+ if runs == 0 {+ t.Fatal("pool never attempted a launch, so the test proves nothing")+ }+ if !p.launchSuppressed() {+ t.Fatal("launches not suppressed after a quota rejection")+ }+}++// A throttled terminate must not be dropped. TerminateMicrovm is quota'd at+// 10/s, so draining a full pool reliably trips it — and the old code logged the+// throttle and moved on, abandoning the box. An abandoned box keeps billing and+// keeps holding regional memory quota until the 8h cap, which is precisely what+// starved the pool at 129/200 while the launch loop failed 4x/s on 402s.+func TestDrainRetriesThrottledTerminates(t *testing.T) {+ p, f := testPool(t, PoolConfig{TargetStock: 2})+ for i := 0; i < 2; i++ {+ if err := p.launchOne(context.Background()); err != nil {+ t.Fatalf("launchOne: %v", err)+ }+ }+ // Every box gets throttled twice before AWS accepts the terminate.+ f.mu.Lock()+ f.terminateFailures = 4+ f.mu.Unlock()++ p.Drain()++ if _, _, terms := f.counts(); terms != 2 {+ t.Fatalf("drain confirmed %d terminate(s) through throttling, want 2 — the rest leaked", terms)+ }+ if got := p.Depth(); got != 0 {+ t.Fatalf("depth after drain = %d, want 0", got)+ }+}++// Stock and tracked sandboxes are the pool's "owned" set; the orphan sweep+// subtracts them from what AWS reports. If StockIDs under-reports, the sweep+// would consider live warm stock unowned and terminate it.+func TestStockIDsReportsEveryParkedBox(t *testing.T) {+ p, _ := testPool(t, PoolConfig{TargetStock: 3})+ for i := 0; i < 3; i++ {+ if err := p.launchOne(context.Background()); err != nil {+ t.Fatalf("launchOne: %v", err)+ }+ }+ ids := p.StockIDs()+ if len(ids) != 3 {+ t.Fatalf("StockIDs returned %d id(s), want 3 — a missing id would let the sweep reap live stock", len(ids))+ }+ p.mu.Lock()+ defer p.mu.Unlock()+ for _, e := range p.stock {+ if _, ok := ids[e.MicrovmID]; !ok {+ t.Fatalf("stocked box %s missing from StockIDs", e.MicrovmID)+ }+ }+}