An open-source, faster Devin alternative
TypeScript
refactor(microvm)!: delete the agent-tunnel MicroVM path — the per-box gRPC tunnel, its pool/manager/workspace layer and the backend built on it, keeping only the worker-id encoding and client helpers lite still needs
Brian Reardon8d829fc9c7ff
diff --git a/cmd/microvm-harness/main.go b/cmd/microvm-harness/main.godeleted file mode 100644index ecb0e457..00000000--- a/cmd/microvm-harness/main.go+++ /dev/null@@ -1,698 +0,0 @@-// Command microvm-harness measures the AWS Lambda MicroVM backend end to end:-// fill a warm pool, claim from it, exec through Lambda's auth proxy, tear down.-//-// It exists to answer two questions that no amount of documentation settles,-// and that decide whether this backend is viable:-//-// 1. Does gRPC actually survive Lambda's JWE proxy? The proxy is documented to-// support HTTP/2, and gRPC is HTTP/2 — but "supports HTTP/2" and "forwards-// long-lived bidirectional HTTP/2 streams with custom headers intact" are-// different claims. If this fails, the agent transport has to change.-//-// 2. What does a claim+exec actually cost at burst width? The pool design-// exists because RunMicrovm is 5/s and ResumeMicrovm is 5/s, so a burst-// cannot make AWS calls at all. This measures whether the claim path really-// is free and where the remaining latency sits.-//-// It is a measurement tool, not a service: it creates only MicroVMs from the-// image it is pointed at, and terminates everything it created before exiting.-//-// go run ./cmd/microvm-harness -image <ARN> -stock 5 -burst 5-package main--import (- "context"- "flag"- "fmt"- "io"- "log"- "net/http"- "os"- "os/signal"- "sort"- "strings"- "sync"- "syscall"- "time"-- "github.com/aws/aws-sdk-go-v2/aws"- awsconfig "github.com/aws/aws-sdk-go-v2/config"- awsTypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"- "github.com/gorilla/websocket"- "github.com/opensandbox/opensandbox/internal/awsvm"- "github.com/opensandbox/opensandbox/internal/storage"- "github.com/opensandbox/opensandbox/pkg/types"-)--// Ports the image declares: hooks on 8080 (the one Lambda already reaches-// during the build) and osb-agent's gRPC on 8081.-const (- hookPort int32 = 8080- agentPort int32 = 8081-)--func main() {- var (- image = flag.String("image", os.Getenv("MICROVM_IMAGE_ARN"), "MicroVM image ARN or name (required)")- role = flag.String("role", os.Getenv("MICROVM_EXECUTION_ROLE_ARN"), "execution role ARN assumed by the guest")- region = flag.String("region", envOr("AWS_REGION", "us-east-1"), "AWS region")- stock = flag.Int("stock", 5, "warm pool depth to fill before claiming")- burst = flag.Int("burst", 5, "how many sandboxes to claim+exec simultaneously")- command = flag.String("cmd", "node -v", "command to exec in each sandbox")- fillWait = flag.Duration("fill-timeout", 5*time.Minute, "how long to wait for the pool to fill")- keep = flag.Bool("keep", false, "leave MicroVMs running on exit (for manual poking)")- lifecycle = flag.Int("lifecycle-mb", 0, "run the hibernate/wake lifecycle sim with an N-MB workspace")- resumeB = flag.Bool("resume-bench", false, "measure suspend/resume: how long a hibernated box takes to become usable again")- probe = flag.Bool("probe", false, "instead of exec, probe plain HTTP /healthz on the hook port to isolate proxy reachability from gRPC")- // Defaults to the hook port: Lambda forwards only there, and the hook- // server bridges to the agent. 8081 is kept reachable via this flag- // purely to re-demonstrate that a direct agent port returns 502.- gPort = flag.Int("agent-port", int(hookPort), "guest port to send gRPC to")- // More than one exec per box separates cold-channel cost from steady state.- execsPer = flag.Int("execs", 3, "execs per sandbox; the first is cold, the rest warm")- )- flag.Parse()-- if *image == "" {- log.Fatal("-image is required (the MicroVM image ARN built by deploy/microvm/publish.sh)")- }- if *burst > *stock {- log.Fatalf("-burst %d exceeds -stock %d: the point of the pool is that a burst never waits on AWS", *burst, *stock)- }-- // Ctrl-C must still terminate what we launched: a leaked MicroVM burns- // regional memory quota until it hits the 8h cap, and quota is the ceiling- // on pool depth.- ctx, stopSignals := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)- defer stopSignals()-- awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(*region))- if err != nil {- log.Fatalf("load AWS config: %v", err)- }-- client := awsvm.NewClient(awsCfg, awsvm.Config{- Region: *region,- ImageIdentifier: *image,- ExecutionRoleArn: *role,- AgentPort: int32(*gPort),- // Idle-suspend must be off for pooled stock. A box that suspends itself- // while waiting turns the next claim into a throttled ResumeMicrovm,- // which is the exact cost the pool exists to avoid.- AutoResume: false,- })-- pool := awsvm.NewPool(client, awsvm.PoolConfig{TargetStock: *stock})- mgr := awsvm.NewManager(client, os.TempDir())- defer mgr.Close()-- poolCtx, stopPool := context.WithCancel(ctx)- defer stopPool()- go pool.Run(poolCtx)-- if err := waitForStock(ctx, pool, *stock, *fillWait); err != nil {- log.Printf("pool never filled: %v (depth=%d)", err, pool.Depth())- if !*keep {- pool.Drain()- }- os.Exit(1)- }-- // Stop launching before measuring. Otherwise the launch ticker keeps calling- // RunMicrovm during the burst and we would be measuring the pool topping- // itself up, not the claim path.- stopPool()-- if *probe {- probeProxy(ctx, awsCfg, *region, *image, pool)- pool.Drain()- return- }-- if *lifecycle > 0 {- st, sErr := storage.NewCheckpointStore(storage.S3Config{- Endpoint: os.Getenv("OPENSANDBOX_S3_ENDPOINT"),- Bucket: os.Getenv("OPENSANDBOX_S3_BUCKET"),- Region: envOr("OPENSANDBOX_S3_REGION", "auto"),- AccessKeyID: os.Getenv("OPENSANDBOX_S3_ACCESS_KEY"),- SecretAccessKey: os.Getenv("OPENSANDBOX_S3_SECRET_KEY"),- ForcePathStyle: true,- })- if sErr != nil {- log.Fatalf("checkpoint store: %v", sErr)- }- runLifecycleSim(ctx, client, pool, mgr, st, *lifecycle)- pool.Drain()- return- }-- if *resumeB {- runResumeBench(ctx, client, pool, mgr, *burst, *command)- pool.Drain()- return- }-- results := runBurst(ctx, pool, mgr, *burst, *command, *execsPer)- report(results)-- if *keep {- log.Printf("-keep set: leaving %d pooled + %d claimed MicroVMs running", pool.Depth(), len(results))- return- }- log.Printf("cleaning up…")- for _, r := range results {- if r.sandboxID != "" {- if err := mgr.Kill(context.WithoutCancel(ctx), r.sandboxID); err != nil {- log.Printf(" terminate %s: %v", r.sandboxID, err)- }- }- }- pool.Drain()-}--func envOr(key, def string) string {- if v := os.Getenv(key); v != "" {- return v- }- return def-}--// waitForStock blocks until the pool reaches the target depth, reporting-// progress so a slow fill is visibly a fill and not a hang.-func waitForStock(ctx context.Context, pool *awsvm.Pool, target int, timeout time.Duration) error {- start := time.Now()- deadline := time.Now().Add(timeout)- tick := time.NewTicker(2 * time.Second)- defer tick.Stop()- last := -1- for {- if d := pool.Depth(); d >= target {- log.Printf("pool filled: %d boxes in %s (%.1f boxes/s)",- d, time.Since(start).Round(time.Millisecond), float64(d)/time.Since(start).Seconds())- return nil- } else if d != last {- log.Printf(" filling: %d/%d", d, target)- last = d- }- select {- case <-ctx.Done():- return ctx.Err()- case <-tick.C:- if time.Now().After(deadline) {- return fmt.Errorf("timed out after %s", timeout)- }- }- }-}--// result is one sandbox's timings. claim and exec are separated because they-// answer different questions: claim should be ~0 by construction, while exec is-// the number that actually reaches the customer.-type result struct {- sandboxID string- claim time.Duration- // exec is the FIRST exec on a freshly claimed box, which pays the whole- // cold-channel cost: token mint, WebSocket handshake, HTTP/2 setup.- exec time.Duration- // warm are subsequent execs on the same established channel. This is the- // number that describes steady-state latency, and the two must never be- // conflated — quoting the cold figure as "exec latency" overstates it by- // roughly a second.- warm []time.Duration- stdout string- err error-}--// runBurst claims and execs n sandboxes simultaneously. Simultaneously is the-// point: a staggered run hides exactly the contention a real create burst hits.-func runBurst(ctx context.Context, pool *awsvm.Pool, mgr *awsvm.Manager, n int, command string, execs int) []result {- log.Printf("bursting %d claim+exec…", n)- results := make([]result, n)- var wg sync.WaitGroup- start := time.Now()-- for i := 0; i < n; i++ {- wg.Add(1)- go func(i int) {- defer wg.Done()- sandboxID := fmt.Sprintf("sb-harness-%d-%d", start.UnixNano(), i)-- claimStart := time.Now()- entry, ok := pool.Claim()- results[i].claim = time.Since(claimStart)- if !ok {- results[i].err = fmt.Errorf("pool empty")- return- }- results[i].sandboxID = sandboxID-- // Track is what the edge-claim path does: bind a pre-launched box to- // a sandbox id without any AWS call.- mgr.TrackClaimed(sandboxID, entry, types.SandboxConfig{- SandboxID: sandboxID,- Template: "microvm",- })-- for n := 0; n < execs; n++ {- execStart := time.Now()- res, err := mgr.Exec(ctx, sandboxID, types.ProcessConfig{- Command: command,- Timeout: 30,- })- took := time.Since(execStart)- if n == 0 {- results[i].exec = took- } else {- results[i].warm = append(results[i].warm, took)- }- if err != nil {- results[i].err = err- return- }- if res.ExitCode != 0 {- results[i].err = fmt.Errorf("exit %d: %s", res.ExitCode, res.Stderr)- return- }- results[i].stdout = res.Stdout- }- }(i)- }- wg.Wait()- log.Printf("burst wall-clock: %s", time.Since(start).Round(time.Millisecond))- return results-}--// probeProxy isolates "can the proxy reach the guest at all" from "does gRPC-// work through the proxy".-//-// The hook server serves plain HTTP /healthz on port 8080 — the same port and-// process Lambda already talks to successfully during the image build. If a-// plain GET through the proxy succeeds while gRPC on 8081 returns 502, the-// problem is gRPC or that specific port. If BOTH 502, the guest is not-// admitting proxied traffic at all and the transport is not the issue.-func probeProxy(ctx context.Context, awsCfg aws.Config, region, image string, pool *awsvm.Pool) {- entry, ok := pool.Claim()- if !ok {- log.Fatal("probe: pool empty")- }-- for _, port := range []int32{hookPort, agentPort} {- // Tokens are port-scoped, so each probe needs one minted for its port.- c := awsvm.NewClient(awsCfg, awsvm.Config{- Region: region, ImageIdentifier: image, AgentPort: port,- })- token, err := c.AuthToken(ctx, entry.MicrovmID)- if err != nil {- log.Printf("probe port %d: mint token: %v", port, err)- continue- }-- path := "/healthz"- if port == agentPort {- // Nothing serves plain HTTP here; we only care which error comes- // back — a proxy 502 versus anything originating in the guest.- path = "/"- }- url := awsvm.AgentURL(entry.Endpoint) + path- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)- if err != nil {- log.Printf("probe port %d: %v", port, err)- continue- }- req.Header.Set("X-aws-proxy-auth", token)- req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", port))-- start := time.Now()- resp, err := http.DefaultClient.Do(req)- took := time.Since(start).Round(time.Millisecond)- if err != nil {- log.Printf("probe port %d %s → transport error after %s: %v", port, path, took, err)- continue- }- body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))- resp.Body.Close()- // Print the body verbatim rather than trimmed: on the hook port it is- // the guest's self-report, which is the whole point of the probe.- log.Printf("probe port %d %s → HTTP %d in %s (proto=%s) %s",- port, path, resp.StatusCode, took, resp.Proto, strings.TrimSpace(string(body)))- }- // Does an unannounced HTTP/2 trailer survive the proxy? gRPC carries its- // status that way, so a "no" here means gRPC cannot work through Lambda at- // all and the agent transport has to change; a "yes" means the trailer loss- // is ours to fix inside the guest.- c := awsvm.NewClient(awsCfg, awsvm.Config{Region: region, ImageIdentifier: image, AgentPort: hookPort})- if token, err := c.AuthToken(ctx, entry.MicrovmID); err == nil {- req, _ := http.NewRequestWithContext(ctx, http.MethodGet,- awsvm.AgentURL(entry.Endpoint)+"/trailer-test", nil)- req.Header.Set("X-aws-proxy-auth", token)- req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", hookPort))- if resp, err := http.DefaultClient.Do(req); err != nil {- log.Printf("trailer probe: %v", err)- } else {- // Trailers are only populated after the body is drained.- _, _ = io.Copy(io.Discard, resp.Body)- resp.Body.Close()- got := resp.Trailer.Get("X-Osb-Trailer")- if got == "" {- log.Printf("trailer probe: TRAILER LOST through the proxy (trailers=%v) → gRPC cannot work as-is", resp.Trailer)- } else {- log.Printf("trailer probe: trailer survived (X-Osb-Trailer=%q) → proxy is fine, our bridge drops them", got)- }- }- }-- // Does a WebSocket survive the proxy, and does it stream both ways? If so,- // gRPC can be tunnelled inside one and the agent's entire API keeps working- // unchanged despite trailers being stripped.- if token, err := c.AuthToken(ctx, entry.MicrovmID); err == nil {- wsURL := "wss://" + hostOnly(entry.Endpoint) + "/ws-test"- hdr := http.Header{}- hdr.Set("X-aws-proxy-auth", token)- hdr.Set("X-aws-proxy-port", fmt.Sprintf("%d", hookPort))-- start := time.Now()- conn, resp, err := websocket.DefaultDialer.DialContext(ctx, wsURL, hdr)- if err != nil {- status := 0- if resp != nil {- status = resp.StatusCode- }- log.Printf("ws probe: upgrade FAILED (http=%d): %v → gRPC-over-WebSocket is not available either", status, err)- } else {- defer conn.Close()- payload := []byte("hello-microvm")- _ = conn.WriteMessage(websocket.TextMessage, payload)- _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second))- _, got, rerr := conn.ReadMessage()- rtt := time.Since(start).Round(time.Millisecond)- if rerr != nil {- log.Printf("ws probe: upgraded but echo failed after %s: %v", rtt, rerr)- } else if string(got) == string(payload) {- log.Printf("ws probe: OK — upgrade + round-trip echo in %s → gRPC can be tunnelled over WebSocket", rtt)- } else {- log.Printf("ws probe: echo mismatch (%q)", string(got))- }- }- }-- log.Printf("probe: microvm=%s endpoint=%s", entry.MicrovmID, entry.Endpoint)-}--func report(results []result) {- var claims, cold, warm []time.Duration- ok := 0- fmt.Println()- fmt.Println("── per-sandbox ─────────────────────────────────────────────")- for _, r := range results {- status := "ok"- if r.err != nil {- status = "FAIL: " + r.err.Error()- } else {- ok++- cold = append(cold, r.exec)- warm = append(warm, r.warm...)- }- claims = append(claims, r.claim)- fmt.Printf(" claim=%-9s exec=%-9s %s %s\n",- r.claim.Round(time.Microsecond), r.exec.Round(time.Millisecond), status, trim(r.stdout))- }-- fmt.Println()- fmt.Println("── summary ─────────────────────────────────────────────────")- fmt.Printf(" success: %d/%d\n", ok, len(results))- printStats("claim", claims)- printStats("cold ", cold)- printStats("warm ", warm)- fmt.Println()- if ok == 0 {- // The single most important negative result this harness can produce.- fmt.Println(" NO EXEC SUCCEEDED — if the errors are transport-level, gRPC")- fmt.Println(" does not survive the Lambda proxy and the agent transport")- fmt.Println(" must change. Check whether the failures are gRPC status")- fmt.Println(" codes (reached the agent) or dial/TLS errors (did not).")- }-}--func printStats(label string, ds []time.Duration) {- if len(ds) == 0 {- fmt.Printf(" %s: (none)\n", label)- return- }- sorted := append([]time.Duration(nil), ds...)- sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })- at := func(q float64) time.Duration {- idx := int(q * float64(len(sorted)-1))- return sorted[idx].Round(time.Millisecond)- }- fmt.Printf(" %s: min=%s med=%s p95=%s max=%s\n",- label, sorted[0].Round(time.Millisecond), at(0.5), at(0.95), sorted[len(sorted)-1].Round(time.Millisecond))-}--// hostOnly strips the scheme so the endpoint can be rebuilt as wss://.-func hostOnly(endpoint string) string {- return strings.TrimPrefix(awsvm.AgentURL(endpoint), "https://")-}--// trim renders command output on a single line so the per-sandbox table stays-// readable when a command is chatty.-func trim(s string) string {- s = strings.TrimSpace(s)- if len(s) > 60 {- s = s[:60] + "…"- }- return strings.NewReplacer("\n", " ", "\r", " ").Replace(s)-}--// ── suspend/resume ──────────────────────────────────────────────────────────--// resumeResult is one box's wake timings.-//-// The three are separated because only the last one is what a customer feels.-// ResumeMicrovm returning is not the same as the box being RUNNING, and RUNNING-// is not the same as the agent answering — a wake design that quotes the API-// call latency would understate the real number by whatever the tail costs.-type resumeResult struct {- suspend time.Duration // SuspendMicrovm call- resumeAPI time.Duration // ResumeMicrovm call returns- toRunning time.Duration // ...until GetMicrovm reports RUNNING- toExec time.Duration // ...until an exec actually succeeds- err error-}--// runResumeBench measures the cost of the fast-wake tier: claim boxes, warm-// them, suspend them, then wake them and time how long until each is usable.-//-// This is the number the hibernation design turns on. If resume is close to a-// cold create (~1.5s) there is little reason to hold a suspended box at all —-// it consumes regional memory quota, which is the ceiling on pool depth — and-// the tier should be dropped in favour of always exporting to blob. If resume-// is much faster, the tier earns its quota.-func runResumeBench(ctx context.Context, client *awsvm.Client, pool *awsvm.Pool, mgr *awsvm.Manager, n int, command string) {- log.Printf("resume-bench: claiming %d box(es)", n)- type box struct {- sandboxID string- microvmID string- }- boxes := make([]box, 0, n)- for i := 0; i < n; i++ {- e, ok := pool.Claim()- if !ok {- log.Printf("resume-bench: pool exhausted at %d", i)- break- }- sid := fmt.Sprintf("sb-resume-%d", i)- mgr.TrackClaimed(sid, e, types.SandboxConfig{SandboxID: sid})- boxes = append(boxes, box{sandboxID: sid, microvmID: e.MicrovmID})- }- if len(boxes) == 0 {- log.Printf("resume-bench: nothing claimed")- return- }-- // Warm each channel first. Measuring a resume through a cold agent tunnel- // would fold the tunnel setup into the wake number and overstate it.- for _, b := range boxes {- if _, err := mgr.Exec(ctx, b.sandboxID, types.ProcessConfig{Command: "sh", Args: []string{"-c", command}}); err != nil {- log.Printf("resume-bench: warm exec %s: %v", b.sandboxID, err)- }- }-- results := make([]resumeResult, len(boxes))- for i, b := range boxes {- var r resumeResult-- t := time.Now()- if err := client.Suspend(ctx, b.microvmID); err != nil {- r.err = fmt.Errorf("suspend: %w", err)- results[i] = r- continue- }- r.suspend = time.Since(t)-- // Wait for it to actually reach SUSPENDED, or we would be timing a- // resume against a box that never finished suspending.- for wait := time.Now(); time.Since(wait) < 60*time.Second; {- bx, err := client.Get(ctx, b.microvmID)- if err == nil && bx.State == awsTypes.MicrovmStateSuspended {- break- }- time.Sleep(500 * time.Millisecond)- }-- t = time.Now()- if err := client.Resume(ctx, b.microvmID); err != nil {- r.err = fmt.Errorf("resume: %w", err)- results[i] = r- continue- }- r.resumeAPI = time.Since(t)-- for wait := time.Now(); time.Since(wait) < 60*time.Second; {- bx, err := client.Get(ctx, b.microvmID)- if err == nil && bx.State == awsTypes.MicrovmStateRunning {- break- }- time.Sleep(100 * time.Millisecond)- }- r.toRunning = time.Since(t)-- for wait := time.Now(); time.Since(wait) < 90*time.Second; {- if _, err := mgr.Exec(ctx, b.sandboxID, types.ProcessConfig{Command: "sh", Args: []string{"-c", "echo woke"}}); err == nil {- break- }- time.Sleep(200 * time.Millisecond)- }- r.toExec = time.Since(t)- results[i] = r- log.Printf(" %s suspend=%s resumeAPI=%s toRunning=%s toExec=%s",- b.sandboxID, r.suspend.Round(time.Millisecond), r.resumeAPI.Round(time.Millisecond),- r.toRunning.Round(time.Millisecond), r.toExec.Round(time.Millisecond))- }-- var suspends, apis, runnings, execs []time.Duration- for _, r := range results {- if r.err != nil {- log.Printf("resume-bench: %v", r.err)- continue- }- suspends = append(suspends, r.suspend)- apis = append(apis, r.resumeAPI)- runnings = append(runnings, r.toRunning)- execs = append(execs, r.toExec)- }- log.Printf("── resume-bench (n=%d) ──", len(execs))- printStats("SuspendMicrovm call", suspends)- printStats("ResumeMicrovm call", apis)- printStats("resume -> RUNNING", runnings)- printStats("resume -> exec OK", execs)-- for _, b := range boxes {- _ = mgr.Kill(context.WithoutCancel(ctx), b.sandboxID)- }-}--// ── hibernate/wake lifecycle ────────────────────────────────────────────────--// runLifecycleSim measures the full hibernation cycle against real MicroVMs:-// claim a box, write a workspace of a known size, hibernate it (export+upload+-// suspend), then wake it both ways and check the files actually came back.-//-// It exists to settle the one number the hibernation design still turns on:-// what a blob restore costs. Resume measured ~1.04s and a pooled claim ~0ms, so-// if restore is cheap the suspended tier is buying almost nothing and can be-// dropped; if it is expensive the tier earns the regional memory quota it-// holds. No amount of reasoning settles that — only the archive round trip on-// a realistic workspace does.-func runLifecycleSim(ctx context.Context, client *awsvm.Client, pool *awsvm.Pool, mgr *awsvm.Manager,- store *storage.CheckpointStore, sizeMB int) {-- e, ok := pool.Claim()- if !ok {- log.Printf("lifecycle: pool empty")- return- }- sid := "sb-lifecycle"- mgr.TrackClaimed(sid, e, types.SandboxConfig{SandboxID: sid})- defer func() { _ = mgr.Kill(context.WithoutCancel(ctx), sid) }()-- // A known payload, so the restore can be verified rather than assumed. A- // wake that silently returns an empty workspace is the failure this whole- // design exists to prevent, and it would look identical to success.- log.Printf("lifecycle: seeding %dMB workspace", sizeMB)- seed := time.Now()- if _, err := mgr.Exec(ctx, sid, types.ProcessConfig{Command: "sh", Args: []string{"-c",- fmt.Sprintf("mkdir -p %s/data && head -c %d /dev/urandom > %s/data/blob.bin && "+- "echo canary-12345 > %s/data/canary.txt && sha256sum %s/data/blob.bin | cut -d' ' -f1",- workspaceGuestDir, sizeMB<<20, workspaceGuestDir, workspaceGuestDir, workspaceGuestDir)},- }); err != nil {- log.Printf("lifecycle: seed failed: %v", err)- return- }- log.Printf(" seeded in %s", time.Since(seed).Round(time.Millisecond))-- // Hibernate: tar + upload + suspend.- t := time.Now()- res, err := mgr.Hibernate(ctx, sid, store)- if err != nil {- log.Printf("lifecycle: hibernate failed: %v", err)- return- }- hibDur := time.Since(t)- log.Printf(" hibernate (tar+upload+suspend): %s archive=%dB key=%s",- hibDur.Round(time.Millisecond), res.SizeBytes, res.HibernationKey)-- // Wake A — the box is still suspended, so this is the fast tier.- t = time.Now()- if _, err := mgr.Wake(ctx, sid, res.HibernationKey, store, 0); err != nil {- log.Printf("lifecycle: fast wake failed: %v", err)- return- }- fastWake := time.Since(t)- verify(ctx, mgr, sid, "fast wake")- log.Printf(" WAKE (resume, box alive): %s", fastWake.Round(time.Millisecond))-- // Now retire the box the way the expiry sweep would, and wake from blob- // alone. This is the tier a sandbox lands in after the dwell.- if err := client.Terminate(ctx, e.MicrovmID); err != nil {- log.Printf("lifecycle: terminate for deep-wake test: %v", err)- return- }- mgr.Forget(sid)-- t = time.Now()- if _, err := mgr.Wake(ctx, sid, res.HibernationKey, store, 0); err != nil {- log.Printf("lifecycle: deep wake failed: %v", err)- return- }- deepWake := time.Since(t)- ok2 := verify(ctx, mgr, sid, "deep wake")- log.Printf(" WAKE (restore from blob): %s filesIntact=%v", deepWake.Round(time.Millisecond), ok2)-- log.Printf("── lifecycle (%dMB workspace) ──", sizeMB)- log.Printf(" hibernate %s", hibDur.Round(time.Millisecond))- log.Printf(" wake resume %s", fastWake.Round(time.Millisecond))- log.Printf(" wake restore %s", deepWake.Round(time.Millisecond))- log.Printf(" delta %s (what the suspended tier buys)", (deepWake - fastWake).Round(time.Millisecond))-}--// workspaceGuestDir mirrors awsvm's workspaceDir; the harness cannot import an-// unexported constant, and hardcoding it here means a divergence shows up as a-// failed verification rather than a silent no-op.-const workspaceGuestDir = "/home/sandbox"--// verify checks the canary survived the round trip. Size alone proves nothing:-// an empty archive restores "successfully" and reports a plausible duration.-func verify(ctx context.Context, mgr *awsvm.Manager, sid, label string) bool {- res, err := mgr.Exec(ctx, sid, types.ProcessConfig{Command: "sh", Args: []string{"-c",- fmt.Sprintf("cat %s/data/canary.txt 2>/dev/null; stat -c %%s %s/data/blob.bin 2>/dev/null",- workspaceGuestDir, workspaceGuestDir)}})- if err != nil {- log.Printf(" %s: verify exec failed: %v", label, err)- return false- }- if !strings.Contains(res.Stdout, "canary-12345") {- log.Printf(" %s: CANARY MISSING — workspace did not survive: %q", label, trim(res.Stdout))- return false- }- return true-}diff --git a/cmd/server/main.go b/cmd/server/main.goindex f6682d59..cfaf7c39 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -314,7 +314,7 @@ func main() {// registry would publish available_workers=0 on a cell that is serving// creates fine, and two reporters on one stream would alternate and// flap it in and out of the edge's routing set. The backend that owns- // the sandboxes reports instead (see microvmBackend.Capacity).+ // the sandboxes reports instead (see liteBackend.Capacity).if cfg.CellID != "" && !workersDisabled {cr, err := controlplane.NewCapacityReporter(controlplane.CapacityReporterConfig{Redis: redisRegistry.RedisClient(),diff --git a/internal/api/edge_claim_microvm.go b/internal/api/edge_claim_microvm.godeleted file mode 100644index bfdd67c6..00000000--- a/internal/api/edge_claim_microvm.go+++ /dev/null@@ -1,354 +0,0 @@-package api--import (- "context"- "errors"- "fmt"- "log"- "sync"- "time"-- "github.com/google/uuid"-- "github.com/opensandbox/opensandbox/pkg/types"-)--// edge_claim_microvm.go — the MicroVM half of the edge-claim protocol.-//-// The QEMU implementation next door runs the whole reservation state machine in-// Postgres, because there a pool box is already a row: it was created by a-// worker, it has a sandbox id, and the CP's only job is to flip its status. None-// of that is true here. A MicroVM pool box is an in-memory *awsvm.StockEntry-// holding a live gRPC channel; it has no row, no sandbox id, and it cannot be-// serialized anywhere. So this path implements the same transitions against the-// pool's own reservation map:-//-// pooled → reserved EdgeReserve (pool.Reserve)-// reserved → bound EdgeFinalize (pool.ClaimReserved; the caller writes the row)-// reserved → pooled EdgeRelease (pool.ReleaseReserved — never tokened)-// reserved → gone pool.expireReservations, which TERMINATES (see its-// docstring: a stale reservation may already be in a-// customer's hands, so re-pooling it is cross-tenant access)-//-// The one real design difference from QEMU: the sandbox id is assigned at-// RESERVE, not at finalize, and the box is bound to it immediately. That is what-// makes the edge answer safe. The edge returns a 201 the moment it pops a box-// from DO stock, and the customer's first exec can arrive before finalize has-// run — on the QEMU path that resolves anyway because the cell proxies by-// worker_id, but here routing goes through the manager's sandbox→box map. If-// that map were only written at finalize, every create would have a window where-// its own sandbox id 404s. Binding at reserve closes it: by the time the id-// exists anywhere outside this process, it already routes.-//-// The cost of binding early is that a reservation which dies unclaimed leaves a-// binding behind, which is what PoolConfig.OnExpire is for.--// edgeBox is one reserved box as the PoolStock DO sees it: an identity, nothing-// more. The tunnel and the entry stay in this process.-type edgeBox struct {- SandboxID string- WorkerID string-- // Reach-info: how to talk to this box WITHOUT going through this process.- // The endpoint is a public TLS host and the token is a port-scoped header- // credential, so handing them to the edge lets it hold the agent tunnel- // itself and take the control plane out of the exec data path entirely.- //- // Delivered here, at reserve, rather than fetched later on purpose: the- // sandbox id is already assigned at this point, so the edge can open and- // guest-attach the tunnel while the box is still sitting in stock — before- // any customer exists. Measured, that is the difference between a first exec- // of ~30ms and one of ~1.1s, because the AWS proxy only connects to the- // guest when payload first arrives and somebody has to pay for that.- //- // Empty on the Postgres path: those cells route through a worker, and this- // is a MicroVM-only shortcut.- Endpoint string- Token string- Port int32-}--// edgeClaimer is a backend that serves edge-claim from its own stock instead of-// the shared Postgres pool. A backend that does not implement it falls through-// to the PG path, which is what every QEMU cell does.-//-// Deliberately store-free: the row write is identical for every backend and the-// handler already owns every other store call on this path, so keeping it there-// leaves this interface about stock and bindings only.-type edgeClaimer interface {- EdgeReserve(n int) []edgeBox- EdgeRelease(sandboxIDs []string) int- EdgeFinalize(sandboxID string, cfg types.SandboxConfig) (workerID string, err error)-}--var _ edgeClaimer = (*microvmBackend)(nil)--// edgeReservedMap tracks reservations this backend made for the edge, keyed by-// the AWS host id so an expiry callback — which only knows the host — can find-// the sandbox id it has to forget.-type edgeReservedMap struct {- mu sync.Mutex- m map[string]string // microvmID → sandboxID-}--func (r *edgeReservedMap) put(microvmID, sandboxID string) {- r.mu.Lock()- defer r.mu.Unlock()- if r.m == nil {- r.m = make(map[string]string)- }- r.m[microvmID] = sandboxID-}--func (r *edgeReservedMap) take(microvmID string) (string, bool) {- r.mu.Lock()- defer r.mu.Unlock()- id, ok := r.m[microvmID]- if ok {- delete(r.m, microvmID)- }- return id, ok-}--func (r *edgeReservedMap) depth() int {- r.mu.Lock()- defer r.mu.Unlock()- return len(r.m)-}--// sandboxIDs returns the sandbox ids currently held as edge reservations.-//-// A reservation has a binding in the manager but no running row — it is-// deliberately parked between the two. Anything reconciling bindings against-// rows has to subtract these first, or every reservation reads as a binding-// whose sandbox has vanished.-func (r *edgeReservedMap) sandboxIDs() map[string]struct{} {- r.mu.Lock()- defer r.mu.Unlock()- out := make(map[string]struct{}, len(r.m))- for _, id := range r.m {- out[id] = struct{}{}- }- return out-}--// EdgeReserve promises up to n warm boxes to the edge's PoolStock DO, assigning-// each a sandbox id and binding it now — see the file docstring for why the-// binding cannot wait for finalize.-//-// Returns fewer than n, or none, when stock is short. Not an error: the DO tops-// up again on its next alarm, and a create that finds empty stock falls back to-// the control plane, which is exactly the path this optimization skips.-func (b *microvmBackend) EdgeReserve(n int) []edgeBox {- if b == nil || b.pool == nil {- return nil- }- entries := b.pool.Reserve(n)- if len(entries) == 0 {- return nil- }- out := make([]edgeBox, 0, len(entries))- for _, e := range entries {- sandboxID := "sb-" + uuid.New().String()[:8]- // Empty cfg deliberately: nobody has asked for anything yet. It resolves- // to the delivered size, which is what this runtime hands out regardless- // of the request (see deliveredSize), so the billing shape is already- // correct before the customer arrives. EdgeFinalize re-tracks with the- // real config once there is one.- b.manager.TrackClaimed(sandboxID, e, types.SandboxConfig{})- b.edgeReserved.put(e.MicrovmID, sandboxID)- out = append(out, edgeBox{- SandboxID: sandboxID,- WorkerID: microvmWorkerID(e.MicrovmID),- Endpoint: e.Endpoint,- Token: e.Token,- Port: b.pool.AgentPort(),- })- }- log.Printf("microvm: edge-reserved %d box(es) (asked %d, %d left in stock)", len(out), n, b.pool.Depth())- return out-}--// EdgeRelease takes back stock the DO discarded without ever handing it to a-// customer. Safe to re-pool precisely because of that assertion — which is the-// DO's to make, not ours; see expireReservations for the case where we cannot-// make it and must terminate instead.-func (b *microvmBackend) EdgeRelease(sandboxIDs []string) int {- if b == nil || b.pool == nil {- return 0- }- released := 0- for _, sandboxID := range sandboxIDs {- microvmID, ok := b.manager.MicrovmIDFor(sandboxID)- if !ok {- continue- }- if !b.pool.ReleaseReserved(microvmID) {- // Already claimed, or already expired. Leave the binding alone: if it- // was claimed it belongs to a customer now, and forgetting it here- // would strand a live sandbox.- continue- }- // Hand the tunnel back to the pool before dropping the binding. Forget- // would CLOSE it, and the box then re-enters stock with no tunnel — so- // the next customer to claim it pays a full cold dial on their first- // exec (measured 549ms vs 76ms warm). Safe here and nowhere else: the DO- // is asserting it never handed this box to a customer, which is the same- // assertion that makes re-pooling the box itself legal.- //- // Ordered after ReleaseReserved deliberately — if that failed the box is- // claimed, the customer owns the channel, and we must not take it.- if a := b.manager.DetachAgent(sandboxID); a != nil {- b.pool.AttachAgent(microvmID, a)- }- b.edgeReserved.take(microvmID)- // Back to anonymous stock, so this id must stop resolving — the box will- // be reissued under a different one at the next reserve.- b.manager.Forget(sandboxID)- released++- }- if released > 0 {- log.Printf("microvm: edge released %d reservation(s) back to stock", released)- }- return released-}--// EdgeFinalize redeems the reservation and rebinds the box to the config the-// customer actually sent. The caller writes the durable row; this is the part-// only the backend can do.-//-// Redeeming is what makes finalizing late safe: ClaimReserved fails if the-// reaper got there first, so a finalize racing expiry reports the loss instead-// of confirming a box that no longer exists.-func (b *microvmBackend) EdgeFinalize(sandboxID string, cfg types.SandboxConfig) (string, error) {- if b == nil || b.pool == nil {- return "", fmt.Errorf("microvm: backend disabled")- }- microvmID, ok := b.manager.MicrovmIDFor(sandboxID)- if !ok {- return "", fmt.Errorf("microvm: finalize %s: no box bound to that sandbox", sandboxID)- }- entry, ok := b.pool.ClaimReserved(microvmID)- if !ok {- return "", fmt.Errorf("microvm: finalize %s: reservation lost (box %s)", sandboxID, microvmID)- }- b.edgeReserved.take(microvmID)-- // Re-track with the real config. Track overwrites the byID entry only — the- // agent channel lives in a separate map keyed by sandbox id — so the- // pre-dialled tunnel adopted at reserve survives this.- b.manager.TrackClaimed(sandboxID, entry, cfg)- return microvmWorkerID(microvmID), nil-}--// forgetExpiredReservation is the PoolConfig.OnExpire callback: a reservation-// died unredeemed and its box has been terminated, so the sandbox id bound at-// reserve must stop resolving.-func (b *microvmBackend) forgetExpiredReservation(microvmID string) {- sandboxID, ok := b.edgeReserved.take(microvmID)- if !ok {- return- }- b.manager.Forget(sandboxID)- if b.onReservationLost != nil {- b.onReservationLost(sandboxID, errors.New("edge reservation expired before it was claimed"))- }- log.Printf("microvm: edge reservation %s (box %s) expired unclaimed — binding dropped", sandboxID, microvmID)-}--// edgeClaimBackend returns this cell's backend if it serves edge-claim from its-// own stock. Dispatching on the placing backend rather than on the caller's org-// is deliberate: a reserve request arrives from a Durable Object holding stock-// for THIS cell, so the question is what this cell runs — a fact the cell knows-// without consulting anyone.-func (s *Server) edgeClaimBackend() (edgeClaimer, bool) {- b, ok := s.claimBackend(placement{runtime: runtimeMicrovm})- if !ok {- return nil, false- }- ec, ok := b.(edgeClaimer)- return ec, ok-}--// poolStockRegion is the region stamped on rows and on the reserve response.-// "local" stands in for an unset region so a dev cell still writes a row that-// the reconciler's region-scoped queries can find.-func (s *Server) poolStockRegion() string {- if s.region == "" {- return "local"- }- return s.region-}--// boxesInUse reports the boxes the pool cannot see: ones bound to a live-// sandbox. It is what PoolConfig.InUse asks, and the budget adds it to the-// pool's own committed count to decide whether there is room to refill.-//-// The subtraction is the whole point. EdgeReserve binds a box to its sandbox id-// at RESERVE rather than at finalize (see the file header for why that window-// has to be closed), so a box waiting in a PoolStock shard is tracked by the-// manager AND counted by committed()'s len(p.reserved). Left uncorrected the-// budget sees roughly SHARDS × POOL_STOCK_TARGET boxes that do not exist —-// measured on dev as "130 in use + 124 committed" against a fleet of 130 —-// which holds the pool at a permanent refill freeze.-func (b *microvmBackend) boxesInUse() int {- if b == nil || b.manager == nil {- return 0- }- n := len(b.manager.TrackedMicrovmIDs()) - b.edgeReserved.depth()- if n < 0 {- // The two counts are taken without a shared lock, so a reserve landing- // between them can transiently invert the difference. Reporting a- // negative would credit the budget with headroom it does not have.- return 0- }- return n-}--// warmReservedTunnels keeps the agent channel alive on every box reserved to the-// edge but not yet claimed by a customer. Wired to PoolConfig.OnMaintain.-//-// These boxes are the pool's whole reason for existing and they are the ones-// nothing else warms. EdgeReserve moves the channel to the manager and takes the-// entry out of p.stock, so the pool's own warmTunnels cannot see it — measured-// on dev, that left ~126 of 150 boxes unwarmed while only the 24 free ones were-// being maintained. A reservation then sits in a PoolStock shard for minutes-// with no traffic, its tunnel lapses, and the customer who claims it pays the-// re-handshake on their FIRST exec, which is exactly what TTI measures-// (383ms cold vs 75ms warm).-//-// Safe to ping precisely because no customer owns these yet: the idle-suspend-// policy that forbids keepalive on a live sandbox has nothing to say about warm-// stock, which is supposed to be running and ready.-func (b *microvmBackend) warmReservedTunnels() {- if b == nil || b.manager == nil {- return- }- reserved := b.edgeReserved.sandboxIDs()- if len(reserved) == 0 {- return- }- if n := b.manager.WarmAgents(reserved); n > 0 {- log.Printf("microvm: re-warmed %d idle tunnel(s) across %d edge reservation(s)", n, len(reserved))- }- // Reconnecting the channel is not enough to keep the box awake — only guest- // traffic is. Edge reservations matter most here: they are the boxes a- // customer is about to claim, so a suspended one turns into ~1s on the very- // first exec. See the keepalive block in internal/awsvm/agent.go.- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)- defer cancel()- if ok, failed, retired, sample := b.manager.PingAgents(ctx, reserved); ok+failed > 0 {- // The sampled cause is the point of the line. A bare failure count is what- // let the stock pool decay from 130 live tunnels to 5 without anything in- // the log naming a reason.- msg := fmt.Sprintf("microvm: keepalive pinged %d reserved box(es) (%d failed", ok, failed)- if retired > 0 {- msg += fmt.Sprintf(", %d channel(s) retired for re-dial", retired)- }- msg += ")"- if sample != nil {- msg += fmt.Sprintf("; first failure: %v", sample)- }- log.Print(msg)- }-}diff --git a/internal/api/edge_claim_microvm_test.go b/internal/api/edge_claim_microvm_test.godeleted file mode 100644index 1267c610..00000000--- a/internal/api/edge_claim_microvm_test.go+++ /dev/null@@ -1,184 +0,0 @@-package api--import (- "context"- "errors"- "os"- "testing"-- lambdamicrovms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"- mvtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"-- "github.com/opensandbox/opensandbox/internal/awsvm"- "github.com/opensandbox/opensandbox/pkg/types"-)--// failingGetAPI answers every describe with an error, standing in for the-// transient API failures that must never be mistaken for a terminated box.-type failingGetAPI struct{ sweepAPI }--func (f *failingGetAPI) GetMicrovm(context.Context, *lambdamicrovms.GetMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {- return nil, errors.New("describe unavailable")-}--// A disabled backend is what every QEMU cell has. The edge-claim endpoints are-// reachable on all of them, so each entry point must be inert rather than-// dereferencing a nil pool — the same class of bug the conformance suite exists-// to catch, now on three new methods.-func TestEdgeClaimIsInertWhenDisabled(t *testing.T) {- var b *microvmBackend- if got := b.EdgeReserve(5); got != nil {- t.Errorf("disabled backend reserved %d box(es)", len(got))- }- if n := b.EdgeRelease([]string{"sb-anything"}); n != 0 {- t.Errorf("disabled backend released %d", n)- }- if _, err := b.EdgeFinalize("sb-anything", types.SandboxConfig{}); err == nil {- t.Error("disabled backend finalized a claim without error")- }-}--// The expiry callback is the counterpart to binding a sandbox id at reserve-// time. Its whole job is to make that id stop resolving once the box behind it-// has been terminated; a binding that outlives its box turns a clean 404 into a-// timeout somewhere in the agent tunnel.-func TestForgetExpiredReservationDropsTheBinding(t *testing.T) {- b := µvmBackend{manager: awsvm.NewManager(nil, os.TempDir())}- const microvmID = "microvm-abc123"- const sandboxID = "sb-deadbeef"-- b.manager.TrackClaimed(sandboxID, &awsvm.StockEntry{MicrovmID: microvmID}, types.SandboxConfig{})- b.edgeReserved.put(microvmID, sandboxID)- if _, ok := b.manager.MicrovmIDFor(sandboxID); !ok {- t.Fatal("reserve did not bind the sandbox id — routing would 404 before finalize")- }-- b.forgetExpiredReservation(microvmID)-- if _, ok := b.manager.MicrovmIDFor(sandboxID); ok {- t.Error("sandbox id still resolves after its reservation expired and its box was terminated")- }- if b.edgeReserved.depth() != 0 {- t.Errorf("reservation map still holds %d entry(s)", b.edgeReserved.depth())- }- // Idempotent: the pool fires this from a goroutine per stale entry, and a- // duplicate must not unbind something a later reserve rebound.- b.forgetExpiredReservation(microvmID)-}--// Finalize must refuse a sandbox id it never handed out. Accepting one would-// write a durable row for a box this cell does not hold.-func TestEdgeFinalizeRejectsAnUnboundSandbox(t *testing.T) {- b := µvmBackend{- manager: awsvm.NewManager(nil, os.TempDir()),- pool: awsvm.NewPool(nil, awsvm.PoolConfig{}),- }- if _, err := b.EdgeFinalize("sb-neverseen", types.SandboxConfig{}); err == nil {- t.Fatal("finalized a sandbox that was never reserved")- }-}--// The pool's box budget is only as good as the inventory it is fed. Reserving-// for the edge binds a box in the manager while it is still counted as pool-// stock, so a naive "in use = everything tracked" double-counts the entire-// magazine — on dev that read 130 in use against a fleet of exactly 130 boxes,-// freezing refill for good.-func TestEdgeReservationsAreNotCountedAsBoxesInUse(t *testing.T) {- b := µvmBackend{manager: awsvm.NewManager(nil, os.TempDir())}-- // Two boxes sitting in edge stock, one genuinely claimed by a customer.- for _, id := range []string{"mvm-stock-1", "mvm-stock-2"} {- sb := "sb-" + id- b.manager.TrackClaimed(sb, &awsvm.StockEntry{MicrovmID: id}, types.SandboxConfig{})- b.edgeReserved.put(id, sb)- }- b.manager.TrackClaimed("sb-live", &awsvm.StockEntry{MicrovmID: "mvm-live"}, types.SandboxConfig{})-- if got := b.boxesInUse(); got != 1 {- t.Fatalf("boxesInUse = %d, want 1 — edge stock is already counted by the pool's committed(), so counting it here inflates the budget by the whole magazine", got)- }-- // Finalizing a reservation hands the box to a customer: it leaves the- // reservation map and must start counting.- b.edgeReserved.take("mvm-stock-1")- if got := b.boxesInUse(); got != 2 {- t.Fatalf("boxesInUse = %d after a reservation was claimed, want 2", got)- }-}--// A reserve landing between the two unsynchronized reads must never produce a-// negative, which would hand the budget headroom that does not exist.-func TestBoxesInUseNeverGoesNegative(t *testing.T) {- b := µvmBackend{manager: awsvm.NewManager(nil, os.TempDir())}- b.edgeReserved.put("mvm-racing", "sb-racing") // reserved, not yet tracked- if got := b.boxesInUse(); got != 0 {- t.Fatalf("boxesInUse = %d, want 0", got)- }-}--// The reconciler is driven by the sessions table, so it can only ever repair a-// binding whose sandbox still has a running row. Bindings whose row reached a-// terminal state by some other path are unreachable by it — and because-// TrackedMicrovmIDs feeds boxesInUse, which is the pool budget's "in use" term,-// each one permanently convinces the pool that a box is busy. The pool then-// refuses to manufacture a replacement for a box that no longer exists, so a-// cell's usable depth decays over its uptime and only a restart clears it.-//-// Measured on dev: 80 "in use" against a 230-box budget, with the pool pinned at-// depth 1-3 out of a target of 150 while the edge served creates cold.-func TestDeadBindingsStopHoldingPoolBudget(t *testing.T) {- f := &sweepAPI{- getImage: map[string]string{},- getState: map[string]mvtypes.MicrovmState{- "mvm-dead": mvtypes.MicrovmStateTerminated,- },- }- b := sweepBackend(t, f)-- // Four bindings, one of each shape the sweep has to tell apart.- b.manager.TrackClaimed("sb-live", &awsvm.StockEntry{MicrovmID: "mvm-live"}, types.SandboxConfig{})- b.manager.TrackClaimed("sb-dead", &awsvm.StockEntry{MicrovmID: "mvm-dead"}, types.SandboxConfig{})- b.manager.TrackClaimed("sb-rowless", &awsvm.StockEntry{MicrovmID: "mvm-rowless"}, types.SandboxConfig{})- b.manager.TrackClaimed("sb-reserved", &awsvm.StockEntry{MicrovmID: "mvm-reserved"}, types.SandboxConfig{})- b.edgeReserved.put("mvm-reserved", "sb-reserved")-- // Only sb-live still has a row; everything else is invisible to reconcileOnce.- b.forgetDeadBindings(context.Background(), map[string]struct{}{"sb-live": {}})-- if _, ok := b.manager.MicrovmIDFor("sb-dead"); ok {- t.Error("kept a binding whose box AWS reports terminated — this is the entry that holds budget forever")- }- if _, ok := b.manager.MicrovmIDFor("sb-live"); !ok {- t.Error("dropped a binding that still has a running row")- }- // Rowless but alive is ambiguous — a create mid-flight looks exactly like a- // leak. On an account shared with other products the sweep reports it and- // leaves it to sweepOrphans, which has the age and image guards.- if _, ok := b.manager.MicrovmIDFor("sb-rowless"); !ok {- t.Error("unbound a live box on the strength of a missing row alone")- }- // Reservations are rowless by construction: binding before the row exists is- // the entire point of reserving. Reaping them would break every create the- // edge has in flight.- if _, ok := b.manager.MicrovmIDFor("sb-reserved"); !ok {- t.Error("unbound an in-flight edge reservation")- }- if len(f.terminated) != 0 {- t.Errorf("binding sweep terminated %v — it must only ever drop local state; this AWS account is shared", f.terminated)- }-}--// A describe that fails must not be read as "the box is gone". Unbinding a live-// sandbox on a transient API error would 404 a customer's running box.-func TestBindingSweepKeepsBindingsItCannotProveDead(t *testing.T) {- f := &failingGetAPI{}- b := sweepBackend(t, &sweepAPI{getImage: map[string]string{}})- b.client = awsvm.NewClientWithAPI(f, awsvm.Config{ImageIdentifier: "arn:ours"})- b.manager.TrackClaimed("sb-unprovable", &awsvm.StockEntry{MicrovmID: "mvm-unprovable"}, types.SandboxConfig{})-- b.forgetDeadBindings(context.Background(), nil)-- if _, ok := b.manager.MicrovmIDFor("sb-unprovable"); !ok {- t.Fatal("dropped a binding because the describe failed — an API blip must not unbind a running sandbox")- }-}diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.godeleted file mode 100644index 5ebc3e6e..00000000--- a/internal/api/microvm_backend.go+++ /dev/null@@ -1,1264 +0,0 @@-package api--import (- "context"- "encoding/json"- "errors"- "fmt"- "log"- "net/http"- "os"- "sort"- "strconv"- "strings"- "sync/atomic"- "time"-- awsconfig "github.com/aws/aws-sdk-go-v2/config"- "github.com/google/uuid"- "github.com/labstack/echo/v4"- "github.com/opensandbox/opensandbox/internal/awsvm"- "github.com/opensandbox/opensandbox/internal/controlplane"- "github.com/opensandbox/opensandbox/internal/db"- "github.com/opensandbox/opensandbox/internal/sandbox"- "github.com/opensandbox/opensandbox/internal/storage"- "github.com/opensandbox/opensandbox/internal/worker"- "github.com/opensandbox/opensandbox/pkg/types"- "github.com/redis/go-redis/v9"-)--// microvm_backend.go — the AWS Lambda MicroVM backend, owned by the control-// plane.-//-// It lives here rather than in cmd/worker on purpose. The point of this backend-// is that AWS holds the VM, so there is nothing for a QEMU worker host to own;-// running it from the worker would keep the very hop it exists to remove and-// add an Azure→AWS leg to every exec. The control plane already decides which-// cell serves a create, so backend selection belongs at the same level.-//-// The QEMU path is untouched. When this backend is disabled — the default —-// nothing here runs and no AWS call is ever made.-//-// Measured on us-east-1 (3-box runs, laptop client):-//-// claim 0s (zero AWS calls, by construction)-// first exec ~224ms (pre-dialled tunnel + agent-path warm-up in the image)-// warm exec ~83ms-//-// Two platform constraints shape everything and are documented where they bite-// (internal/awsvm/agent.go): the proxy strips HTTP/2 trailers, so gRPC rides-// inside a WebSocket; and it forwards only to the image's declared hook port.--// microvmBackend holds the CP's MicroVM client and warm pool. nil when the-// backend is disabled, which is the only state the QEMU fleet ever sees.-type microvmBackend struct {- client *awsvm.Client- pool *awsvm.Pool- manager *awsvm.Manager-- // checkpointStore is where a hibernated sandbox's workspace archive lives.- // Required for Hibernate/Wake and nothing else — without it this backend- // still serves sandboxes, it just cannot park them.- checkpointStore *storage.CheckpointStore-- // usageTicker emits the billing ticks these sandboxes would otherwise never- // produce. On the QEMU fleet the worker runs one; there is no worker here,- // so the control plane runs it directly over the same sandbox.Manager- // interface. Without it MicroVM sandboxes run entirely unmetered.- usageTicker *worker.UsageTicker-- // eventPub drains those ticks off local disk to the cell's Redis stream.- // The ticker without the publisher meters into a file nobody reads.- eventPub *worker.RedisEventPublisher-- // capacity tells the edge this cell exists and can take creates. A cell that- // never reports is not routed to at all.- capacity *controlplane.CapacityReporter-- // aliveRowless carries the last binding sweep's count of live boxes bound to- // a sandbox with no row, so the pool's budget log can report it without- // re-probing AWS. See boxesInUseDetail.- aliveRowless atomic.Int64-- // coldSlots caps concurrent cold launches (see maxColdCreates).- coldSlots chan struct{}-- // stopPool ends the maintenance loop on shutdown so a redeploying CP does- // not leave stock running: abandoned boxes bill compute and hold regional- // memory quota until the 8h service cap.- stopPool context.CancelFunc-- // edgeReserved maps a reserved box back to the sandbox id bound to it at- // reserve time, so an expiring reservation can drop that binding. See- // edge_claim_microvm.go for why the binding happens that early.- edgeReserved edgeReservedMap-- // onReservationLost tells the control plane that a reserved sandbox id will- // never finalize, so anything parked waiting for that claim is released- // with the failure instead of waiting the window out. Set by the Server at- // wiring time; nil in tests, where nobody is waiting.- onReservationLost func(sandboxID string, err error)-}--// microvmEnabled reports whether this cell serves MicroVM-backed sandboxes.-// Off unless explicitly turned on: this backend is regional (us-east-1 today)-// and cannot serve a cell whose customers expect QEMU semantics like-// checkpoints or fork, which it does not implement.-func microvmEnabled() bool {- return os.Getenv("OPENSANDBOX_MICROVM_ENABLED") == "1"-}--// newMicrovmBackend builds the backend from environment config, or returns nil-// if disabled. An error here is fatal to startup by design — a cell configured-// for MicroVMs that silently fell back to QEMU would be far more confusing than-// a refusal to boot.-func newMicrovmBackend(ctx context.Context, checkpointStore *storage.CheckpointStore) (*microvmBackend, error) {- if !microvmEnabled() {- return nil, nil- }- // The direct-exec backend replaces this one rather than joining it — see the- // registration order in router.go. Returning nil here is what makes that- // exclusive: otherwise both pools would fill from the same regional quota.- if liteEnabled() {- log.Printf("microvm: agent-tunnel backend stood down — OPENSANDBOX_MICROVM_LITE=1 is serving this cell")- return nil, nil- }-- client, err := newMicrovmClient(ctx)- if err != nil {- return nil, err- }- region := client.Config().Region-- poolCtx, stop := context.WithCancel(context.Background())-- // Built before the pool because the pool's expiry callback reaches back into- // it: an edge reservation that dies unclaimed has to drop the sandbox- // binding this backend made when it handed the box to the edge.- b := µvmBackend{- client: client,- manager: awsvm.NewManager(client, os.TempDir()),- checkpointStore: checkpointStore,- coldSlots: make(chan struct{}, maxColdCreates),- stopPool: stop,- }- // The account-wide ceiling, in boxes. The regional quota is expressed in- // gigabytes (1024 by default, adjustable), and every box costs the image's- // delivered size regardless of what the create asked for — so the box count- // is what actually has to be capped. Default 0 (off) so a cell nobody has- // sized keeps its previous behaviour rather than silently refusing to fill.- maxTotal := envInt("OPENSANDBOX_MICROVM_MAX_TOTAL_BOXES", 0)- b.pool = awsvm.NewPool(client, awsvm.PoolConfig{- TargetStock: envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20),- MaxTotalBoxes: maxTotal,- // Claimed boxes are exactly the ones the manager tracks: a box enters on- // Claim and leaves on Release, which is the population the pool is blind- // to and the reason a target-only filler can overrun the quota.- //- // Minus the edge's reservations, which the pool already counts itself.- // EdgeReserve binds a box to its sandbox id at RESERVE (see- // edge_claim_microvm.go for why that window has to be closed), so every- // box sitting in a PoolStock shard is simultaneously tracked here and- // inside committed()'s len(p.reserved). Double-counting them makes the- // budget hallucinate a fleet roughly SHARDS × POOL_STOCK_TARGET larger- // than the one AWS is actually running — measured on dev at 130 "in- // use" against 130 boxes alive in total, which pinned the pool at a- // permanent budget hold and would have starved refill through exactly- // the burst the budget exists to survive.- InUse: b.boxesInUse,- InUseDetail: b.boxesInUseDetail,- OnExpire: b.forgetExpiredReservation,- OnMaintain: b.warmReservedTunnels,- // How long refill stands down once the budget is reached. Tunable- // because the right value is a property of the workload, not the code:- // it wants to outlast the burst that drained the pool, so that the- // releases behind it accumulate into headroom instead of being spent- // one at a time against the regional quota the burst still needs.- RefillDelay: time.Duration(envInt("OPENSANDBOX_MICROVM_POOL_REFILL_DELAY_SECONDS", 60)) * time.Second,- })- if maxTotal > 0 {- log.Printf("microvm: box budget %d (pool target %d) — refill pauses while claimed boxes fill the rest",- maxTotal, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))- }-- go b.pool.Run(poolCtx)-- log.Printf("microvm: backend enabled (region=%s image=%s poolTarget=%d)",- region, client.Config().ImageIdentifier, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))-- return b, nil-}--// newMicrovmClient builds the AWS client from environment config.-//-// Shared by both MicroVM backends — the agent-tunnel one above and the direct-// exec one in lite_backend.go — because they are two ways of TALKING to a box,-// not two fleets. They launch from the same image, in the same region, under the-// same idle policy and the same regional quota, and letting those drift apart-// would make a measurement taken on one say nothing about the other.-func newMicrovmClient(ctx context.Context) (*awsvm.Client, error) {- image := os.Getenv("OPENSANDBOX_MICROVM_IMAGE_ARN")- if image == "" {- return nil, fmt.Errorf("OPENSANDBOX_MICROVM_ENABLED=1 but OPENSANDBOX_MICROVM_IMAGE_ARN is unset")- }- region := os.Getenv("OPENSANDBOX_MICROVM_REGION")- if region == "" {- region = "us-east-1"- }-- awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region))- if err != nil {- return nil, fmt.Errorf("microvm: load AWS config: %w", err)- }-- // Idle policy. Measured on dev: with idle=60s and suspended=300s, a sandbox- // was TERMINATED — disk and all — roughly six minutes after its last- // request. The old defaults (900/1800) put that at 45 minutes of inactivity,- // which silently destroys any sandbox a customer steps away from.- //- // idle seconds without inbound proxy traffic before AWS suspends.- // A persistent agent tunnel does NOT count as traffic — only- // requests through the proxy do, which is why an open connection- // does not keep a box alive.- // suspended seconds a box may stay suspended before AWS TERMINATES it.- // This, not the 8h ceiling, is what actually bounds a parked- // sandbox, and when it fires the disk goes with it.- // resume whether an inbound request wakes a suspended box. With this- // off, nothing can reach a box during its suspended window, so- // the window always runs out and the sandbox is destroyed.- //- // Default idle deliberately exceeds the pool's MaxBoxAge (7h) so stock never- // drifts into SUSPENDED while waiting — the pool's docstring requires that,- // and the previous 900s default did not deliver it. Auto-resume defaults ON- // so that anything which does suspend is recoverable rather than doomed.- idleSec := envInt("OPENSANDBOX_MICROVM_IDLE_SECONDS", 28_800)- // Default to the hard ceiling rather than 1800: AWS terminates a suspended- // box when this fires, taking its disk with it, so a 30-minute default made- // "hibernate" mean "deleted in half an hour". At the ceiling this timer- // never fires before the 8h total cap does, which leaves the cap as the- // single deadline to reason about — and the one the blob promotion works- // against.- suspendedSec := envInt("OPENSANDBOX_MICROVM_SUSPENDED_SECONDS", 28_800)- autoResume := os.Getenv("OPENSANDBOX_MICROVM_AUTO_RESUME") != "0"- sizeImages := parseSizeImages(os.Getenv("OPENSANDBOX_MICROVM_SIZE_IMAGES"))- defaultMemoryMB := envInt("OPENSANDBOX_MICROVM_DEFAULT_MEMORY_MB", 0)- // Empty pins nothing and takes the image's latest active version, which is- // what production wants. Setting it is for A/B: a republished image changes- // every box in the fleet at once, so without a way to pin an older version- // there is no way to tell "the image regressed" from "something else did".- imageVersion := os.Getenv("OPENSANDBOX_MICROVM_IMAGE_VERSION")- client := awsvm.NewClient(awsCfg, awsvm.Config{- Region: region,- ImageIdentifier: image,- ImageVersion: imageVersion,- DefaultMemoryMB: defaultMemoryMB,- SizeImages: sizeImages,- ExecutionRoleArn: os.Getenv("OPENSANDBOX_MICROVM_EXECUTION_ROLE_ARN"),- MaxIdleDurationSeconds: int32(idleSec),- SuspendedDurationSeconds: int32(suspendedSec),- AutoResume: autoResume,- })- if len(sizeImages) > 0 {- log.Printf("microvm: size tiers — default %dMB pooled, cold-only: %v",- client.Config().DefaultMemoryMB, sortedTiers(sizeImages))- }- log.Printf("microvm: idle policy — suspend after %ds idle, terminate after %ds suspended, auto-resume=%v",- idleSec, suspendedSec, autoResume)- if imageVersion != "" {- log.Printf("microvm: image version PINNED to %s (unset OPENSANDBOX_MICROVM_IMAGE_VERSION for latest)", imageVersion)- }-- return client, nil-}--// claimPooled binds a warm host to a sandbox id and returns whether one was-// available. It makes NO provider calls — that is the property the whole pool-// design exists to preserve, because launch and resume are both rate-limited-// and a burst cannot afford either.-//-// A miss is not an error here; Claim decides what to do about it.-func (b *microvmBackend) claimPooled(sandboxID string, cfg types.SandboxConfig) (string, bool) {- if b == nil {- return "", false- }- // Only the default tier is pooled, so a request for any other size must miss- // the pool on purpose and cold-launch its own image.- //- // Without this the pool would happily hand a 16 GB request a default-size- // box: warm stock is manufactured from one image and carries no record of- // what it was asked for, so nothing downstream can tell the difference. The- // customer gets a box a quarter the size they asked for, metered at what- // they actually got, with no error anywhere.- if !b.client.Config().IsDefaultTier(cfg.MemoryMB) {- log.Printf("microvm: %s asked for %dMB — not the pooled tier, cold create", sandboxID, cfg.MemoryMB)- return "", false- }- entry, ok := b.pool.Claim()- if !ok {- log.Printf("microvm: pool empty on claim for %s — cold create", sandboxID)- return "", false- }- // TrackClaimed adopts the tunnel the pool already established. Losing that- // here would cost ~700ms on the customer's first command, which is most of- // what this backend's latency story is about.- b.manager.TrackClaimed(sandboxID, entry, cfg)- // Encoded, not raw: Claim's contract is "the worker_id to persist", and the- // raw host id is not a worker_id this backend recognizes as its own.- return microvmWorkerID(entry.MicrovmID), true-}--// maxColdCreates bounds concurrent cold launches. RunMicrovm is rate-limited at-// 5/s, so letting an unbounded burst through would convert one empty pool into-// a wall of throttling errors — turning a slow create into a failed one for-// requests that had nothing to do with the burst.-const maxColdCreates = 5--// coldCreateTimeout bounds a single cold launch. Generous relative to the ~1.5s-// a healthy launch takes, because the alternative for the customer is a failed-// create, not a fast one.-const coldCreateTimeout = 45 * time.Second--// Claim serves a sandbox from warm stock, falling back to launching one.-//-// The pool is a latency optimization, not the capacity limit: the real ceiling-// is an AWS regional quota far above normal use. Before this existed a pool miss-// fell through to the worker path and sat in its 30s poll waiting for a worker-// that a MicroVM cell never has — so every create past pool depth failed after-// 30 seconds against a backend that would have launched a box in ~1.5s.-//-// Returns ErrQuotaExceeded only when AWS says the region is genuinely full, so-// the caller can report "out of capacity" and mean it.-func (b *microvmBackend) Claim(ctx context.Context, p placement) (string, error) {- if b == nil {- return "", errors.New("microvm: backend disabled")- }- sandboxID, cfg := p.sandboxID, p.cfg- if id, ok := b.claimPooled(sandboxID, cfg); ok {- return id, nil- }-- // Bound concurrency rather than queueing indefinitely: a caller blocked here- // is a customer waiting on a create, so failing fast beats a long hold.- select {- case b.coldSlots <- struct{}{}:- defer func() { <-b.coldSlots }()- case <-ctx.Done():- return "", ctx.Err()- }-- launchCtx, cancel := context.WithTimeout(ctx, coldCreateTimeout)- defer cancel()-- // Resolve the tier's image. Refused rather than downgraded — see- // awsvm.Config.ImageForMemory.- image, _, ok := b.client.Config().ImageForMemory(cfg.MemoryMB)- if !ok {- return "", fmt.Errorf("microvm: %s: no image configured for %dMB: %w",- sandboxID, cfg.MemoryMB, awsvm.ErrUnsupported)- }-- start := time.Now()- box, err := b.client.RunImage(launchCtx, "", image)- if err != nil {- return "", err // already classified (quota vs throttle) by awsvm- }- ready, err := b.client.WaitRunning(launchCtx, box.ID, coldCreateTimeout)- if err != nil {- // The box may be mid-boot rather than dead, but we cannot hand out one- // we could not confirm — terminate it instead of leaking a box that- // bills and holds quota with nothing tracking it.- go func() { _ = b.client.Terminate(context.Background(), box.ID) }()- return "", fmt.Errorf("microvm: cold create %s never became ready: %w", box.ID, err)- }- // WaitRunning returns the settled box — it carries the endpoint the agent- // tunnel dials, which the pre-ready Run response does not.- box = ready-- // Track, not TrackClaimed: there is no pre-dialled tunnel on this path, so- // the first exec pays the dial. That is the cost of missing the pool.- b.manager.Track(sandboxID, box, cfg)- log.Printf("microvm: COLD CREATE %s -> %s in %s", sandboxID, box.ID, time.Since(start).Round(time.Millisecond))- return microvmWorkerID(box.ID), nil-}--// Restore rebuilds the in-memory sandbox→MicroVM map from the database after a-// control-plane restart, and closes out rows whose box AWS no longer has.-//-// Skipping this does not merely lose routing: an untracked box is one nothing-// will ever terminate, so it keeps billing compute and holding regional memory-// quota — which is the real ceiling on pool depth — until the 8h cap.-func (b *microvmBackend) Restore(ctx context.Context, store *db.Store) {- b.reconcileOnce(ctx, store)-}--// microvmReconcileInterval paces the background sweep. Boxes die on their own-// schedule — the 8h service cap, or AWS terminating one underneath us — so this-// is the only thing that ever notices. Five minutes is far tighter than the-// window in which a stale row could matter, and each pass is one cheap-// GetMicrovm per live sandbox.-const microvmReconcileInterval = 5 * time.Minute--// StartReconciler sweeps for boxes that died without anyone telling us.-//-// Unlike the QEMU fleet, nothing here reports in, so a dead box keeps a running-// row forever unless this sweep notices — inflating concurrency and quota counts-// with sandboxes that no longer exist.-//-// The inverse hazard is real too, and cost a dev cell every sandbox it created:-// MarkOrphanedSandboxes reaps any session whose worker_id is missing from the-// live worker registry, and "microvm:<id>" is missing from it by construction.-// It now skips these rows explicitly (internal/db/store.go). Anything else that-// infers liveness from the worker registry has to do the same — AWS is the only-// authority on whether one of these boxes is alive.-func (b *microvmBackend) StartReconciler(ctx context.Context, store *db.Store) {- if b == nil || store == nil {- return- }- go func() {- t := time.NewTicker(microvmReconcileInterval)- defer t.Stop()- for {- select {- case <-ctx.Done():- return- case <-t.C:- b.reconcileOnce(ctx, store)- b.sweepOrphans(ctx)- }- }- }()-}--// reconcileOnce reconciles persisted MicroVM sandboxes against AWS: adopt the-// ones still alive, close out the ones that are gone. Used both at boot (where-// the adopt half matters, after a restart drops the in-memory map) and on the-// ticker (where the close half matters).-func (b *microvmBackend) reconcileOnce(ctx context.Context, store *db.Store) {- if b == nil || store == nil {- return- }- rows, err := store.ListMicrovmSessions(ctx, b.WorkerIDPrefixes())- if err != nil {- log.Printf("microvm: restore query failed: %v", err)- return- }-- var restored, closed int- hasRow := make(map[string]struct{}, len(rows))- for _, r := range rows {- // Recorded before the parse check: a row we cannot parse is still a row,- // and the binding sweep below must not treat its sandbox as vanished.- hasRow[r.SandboxID] = struct{}{}- microvmID, ok := parseMicrovmWorkerID(r.WorkerID)- if !ok {- continue- }- // Already tracked AND still alive — nothing to do. Skipping avoids a- // GetMicrovm per sandbox per tick once the map is warm.- //- // The status matters, not just the error: Get returns a nil error with- // status stopped for a box AWS has terminated. Reading only the error- // meant this shortcut fired for exactly the sandboxes the sweep exists- // to close, so dead boxes kept their rows at 'running' indefinitely —- // holding concurrency quota and reporting healthy — while the usage- // ticker logged "not alive, reaper should drain it" for a reaper that- // could never see them.- if sb, err := b.manager.Get(ctx, r.SandboxID); err == nil && sb.Status == types.SandboxStatusRunning {- continue- }- box, err := b.client.Get(ctx, microvmID)- if err != nil || !box.Alive() {- // The box is gone (terminated, or aged past the 8h cap) but the row- // still says running. Close it, or wake/exec will 404 forever- // against a sandbox that cannot exist.- msg := "microvm no longer exists"- _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)- // Drop the in-memory binding too. Closing only the row leaves a- // phantom entry in the manager's map that nothing can ever remove:- // ListMicrovmSessions returns running rows, so the next pass does not- // even see this sandbox again. Those phantoms are counted by- // TrackedMicrovmIDs, which is what the pool's box budget treats as- // "in use" — measured on dev at 112 phantoms against 130 boxes- // actually alive, i.e. a budget that would refuse to refill the pool- // during exactly the burst it was sized for.- b.manager.Forget(r.SandboxID)- closed++- continue- }- // Re-derive the config from the persisted row rather than tracking a- // bare id. Track fills zero sizing with the backend default, so a- // restore that skipped this would re-meter a 4096MB sandbox at 2048- // for the rest of its life — under-billing that nothing surfaces,- // since every log line still reports ticks flowing.- cfg := types.SandboxConfig{SandboxID: r.SandboxID}- if len(r.Config) > 0 {- if err := json.Unmarshal(r.Config, &cfg); err != nil {- log.Printf("microvm: restore %s: config unmarshal failed (%v) — tracking with defaults", r.SandboxID, err)- }- cfg.SandboxID = r.SandboxID- }- b.manager.Track(r.SandboxID, box, cfg)- restored++- }- if restored > 0 || closed > 0 {- log.Printf("microvm: reconciled — adopted %d sandbox(es), closed %d dead row(s)", restored, closed)- }- b.forgetDeadBindings(ctx, hasRow)-}--// bindingSweepCap bounds how many rowless bindings one pass probes against AWS.-// Each probe is a GetMicrovm, and a cell that has accumulated a large backlog-// should drain it over successive passes rather than spend its API budget in one-// burst — the same reasoning as orphanReapCap, minus the blast radius, since-// this sweep only ever forgets local state.-const bindingSweepCap = 50--// forgetDeadBindings drops in-memory bindings whose sandbox no longer has a row.-//-// reconcileOnce walks the sessions table and can therefore only ever fix a-// binding whose sandbox still has a running row. That leaves the opposite leak-// structurally invisible: when a row reaches a terminal state by any path that-// does not also call Kill or Forget, its binding stays in the manager's map with-// nothing left that can reach it. Nothing reaps it, and it is counted forever by-// TrackedMicrovmIDs — which is precisely what boxesInUse reports to the pool as-// the budget's "in use" term. Every stranded binding is a box the pool believes-// is working and permanently refuses to replace, so the pool's usable depth-// decays toward zero over a cell's uptime and never recovers without a restart.-//-// Two cases, treated differently on purpose:-//-// - Box dead in AWS. Unambiguous, and forgetting is purely local — no API call,-// nothing destroyed. Dropped.-// - Box alive but rowless. Only reported. It may be a genuine leak, but it may-// equally be a create mid-flight whose row has not landed yet, and this-// account is shared with other products, so acting on "I cannot find the-// paperwork" is exactly the reasoning that must never terminate anything.-// sweepOrphans owns that decision, behind its age and attribution guards.-func (b *microvmBackend) forgetDeadBindings(ctx context.Context, hasRow map[string]struct{}) {- if b == nil || b.manager == nil {- return- }- // Edge reservations are bound before any row exists — that window is the- // whole point of reserving — so they are rowless by design, not by leak.- reserved := b.edgeReserved.sandboxIDs()-- var forgotten, aliveRowless, probed int- for sandboxID, microvmID := range b.manager.TrackedBindings() {- if _, ok := hasRow[sandboxID]; ok {- continue- }- if _, ok := reserved[sandboxID]; ok {- continue- }- if probed >= bindingSweepCap {- break- }- probed++- box, err := b.client.Get(ctx, microvmID)- if err != nil {- // Could not prove it is dead, so leave it. A transient describe- // failure must not be able to unbind a live sandbox.- continue- }- if box.Alive() {- aliveRowless++- continue- }- b.manager.Forget(sandboxID)- forgotten++- }- if forgotten > 0 {- log.Printf("microvm: binding sweep forgot %d dead binding(s) holding pool budget", forgotten)- }- b.aliveRowless.Store(int64(aliveRowless))- if aliveRowless > 0 {- log.Printf("microvm: binding sweep — %d live box(es) bound to a sandbox with no row; left alone for the orphan sweep to age out",- aliveRowless)- }-}--// boxesInUseDetail decomposes boxesInUse for the pool's budget log. Wired to-// PoolConfig.InUseDetail.-//-// boxesInUse is a subtraction of two independently-maintained counts, and when-// the pool freezes at its budget the only question that matters is which of them-// is wrong. Reporting just the difference makes that unanswerable from the logs:-// a freeze looks identical whether the manager is holding bindings for sandboxes-// that are long gone or the edge genuinely has that many boxes reserved.-// alive-rowless is included because it is the leading indicator of the first-// case — bindings the sweep can see but deliberately will not act on.-func (b *microvmBackend) boxesInUseDetail() string {- if b == nil || b.manager == nil {- return ""- }- return fmt.Sprintf("tracked=%d edge-reserved=%d alive-rowless=%d",- len(b.manager.TrackedMicrovmIDs()), b.edgeReserved.depth(), b.aliveRowless.Load())-}--// orphanMinAge is how old a MicroVM must be before the sweep will consider it-// abandoned. A box is invisible to us for a real window during its own creation-// — launched but not yet stocked, or claimed but not yet tracked — and reaping-// 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{}{}- }-- // Every image this cell launches from, not just the default: a box on a size- // tier is equally ours, and testing only the default image would leave every- // tier orphan uncollectable (it reads as another product's host).- ourImages := make(map[string]struct{}, 4)- for _, arn := range b.client.Config().OwnedImages() {- ourImages[arn] = struct{}{}- }- armed := envInt("OPENSANDBOX_MICROVM_ORPHAN_REAP", 0) == 1-- var orphans []string- var skippedYoung, skippedForeign, skippedUnprovable int- for _, box := range boxes {- if !box.Alive() {- continue // already terminating; nothing to reclaim- }- if _, ok := known[box.ID]; ok {- 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.- //- // Checked before the image lookup below so a fleet of young boxes cannot- // cost us a GetMicrovm each — ListMicrovms already throttles on this- // account.- if box.StartedAt.IsZero() || time.Since(box.StartedAt) < orphanMinAge {- skippedYoung++- continue- }- // Never reap a box we did not build: this AWS account is shared with- // other products, and terminating their hosts would be far worse than- // leaking one of ours.- //- // The match must be POSITIVE. An earlier version skipped the comparison- // whenever ImageArn was empty, which inverted the guard exactly like the- // StartedAt bug above: a box whose image we failed to learn became- // eligible instead of protected. ListMicrovms returns a reduced- // projection (it carries no endpoint either), so an empty ImageArn here- // says nothing about ownership — resolve it with a Get, and if it still- // cannot be established, leave the box alone.- arn := box.ImageArn- if arn == "" {- if full, gerr := b.client.Get(ctx, box.ID); gerr == nil {- arn = full.ImageArn- }- }- if _, ours := ourImages[arn]; len(ourImages) == 0 || !ours {- if arn == "" {- skippedUnprovable++- } else {- skippedForeign++- }- continue- }- orphans = append(orphans, box.ID)- }-- if skippedForeign > 0 || skippedUnprovable > 0 {- log.Printf("microvm: orphan sweep left %d foreign-image and %d unprovable box(es) alone",- skippedForeign, skippedUnprovable)- }- if len(orphans) == 0 {- if skippedYoung > 0 || skippedForeign > 0 || skippedUnprovable > 0 {- log.Printf("microvm: orphan sweep clean (skipped %d too-young, %d foreign-image, %d unprovable)",- skippedYoung, skippedForeign, skippedUnprovable)- }- 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) {- if b == nil {- return false, nil- }- if _, err := b.manager.Get(ctx, sandboxID); err != nil {- return false, nil- }- return true, b.manager.Kill(ctx, sandboxID)-}--// Depth reports current stock, for telemetry and for the sizing invariant: if-// the edge shards claims, the shards' aggregate target must not exceed this-// pool or they starve while hoarding — the failure that cost 1045ms vs 174ms on-// the QEMU fleet.-func (b *microvmBackend) Depth() int {- if b == nil {- return 0- }- return b.pool.Depth()-}--// StartUsageTicker begins emitting billing ticks for MicroVM sandboxes.-//-// UsageTicker takes a sandbox.Manager, which awsvm.Manager already satisfies,-// so this is wiring rather than a second implementation. It also relies on-// IsSandboxAlive to drop dead sandboxes — and this backend deliberately asks-// AWS there instead of trusting its local map, which is exactly what stops a-// stale entry billing for a VM that no longer exists.-func (b *microvmBackend) StartUsageTicker(ctx context.Context, sandboxDBs *sandbox.SandboxDBManager) {- if b == nil {- return- }- t := worker.NewUsageTicker(b.manager, sandboxDBs, 20*time.Second, 10)- if t == nil {- // nil sandboxDBs disables it. Say so loudly: silent non-billing is the- // failure mode that does not page anyone.- log.Printf("microvm: WARNING usage ticker disabled — sandboxes will not be metered")- return- }- b.usageTicker = t- t.Start(ctx)- log.Printf("microvm: usage ticker started")-}--// StartEventPublisher drains the ticks the usage ticker writes into per-sandbox-// SQLite out to the cell's Redis stream, where event_forwarder picks them up for-// events-ingest → D1 `usage_samples`.-//-// This is the second half of billing and is easy to miss, because omitting it-// looks fine from inside the control plane: LogEvent succeeds, the ticks are on-// disk, and nothing errors — they simply never leave the box. On the QEMU fleet-// cmd/worker runs this publisher; with no worker in the MicroVM path, the-// control plane has to.-//-// Off unless both Redis and a cell id are configured, matching the worker: with-// no consumer, the stream is a slow leak rather than a billing path.-func (b *microvmBackend) StartEventPublisher(ctx context.Context, sandboxDBs *sandbox.SandboxDBManager, rdb *redis.Client, cellID string, store *db.Store) {- if b == nil {- return- }- if sandboxDBs == nil || rdb == nil || cellID == "" {- log.Printf("microvm: WARNING event publisher disabled (sandboxDBs=%v redis=%v cellID=%q) — usage ticks stay on local disk and are never billed",- sandboxDBs != nil, rdb != nil, cellID)- return- }-- // Each MicroVM sandbox carries its own owner id, so the envelope's worker_id- // has to be resolved per sandbox rather than stamped from the publisher.- // events-ingest drops a tick whose worker_id disagrees with- // sandboxes_index.worker_id, and every one of these disagrees with any- // single fleet-wide id.- workerIDs := func(sandboxID string) (string, bool) {- hostID, ok := b.manager.MicrovmIDFor(sandboxID)- if !ok {- return "", false- }- return microvmWorkerID(hostID), true- }-- // org_id + plan are denormalized onto the envelope so events-ingest can- // route without a D1 lookup per event. Blank plan means "unknown" there,- // which skips the debit — so a missing org row costs metering, not a- // mis-bill.- var meta worker.MetadataResolver- if store != nil {- meta = func(sandboxID string) (string, string, bool) {- lookupCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()- orgIDStr, err := store.GetSandboxOrgID(lookupCtx, sandboxID)- if err != nil || orgIDStr == "" {- return "", "", false- }- orgID, err := uuid.Parse(orgIDStr)- if err != nil {- return "", "", false- }- org, err := store.GetOrg(lookupCtx, orgID)- if err != nil {- return orgIDStr, "", true- }- return orgIDStr, org.Plan, true- }- }-- pub, err := worker.NewRedisEventPublisher(worker.RedisEventPublisherConfig{- Client: rdb,- SandboxDBs: sandboxDBs,- CellID: cellID,- WorkerID: microvmPublisherWorkerID,- Resolver: meta,- WorkerIDResolver: workerIDs,- })- if err != nil {- log.Printf("microvm: WARNING event publisher init failed: %v — usage ticks will not be billed", err)- return- }-- // Flush before the SQLite file is deleted. Without this the terminal events- // of a destroyed sandbox — including its final usage slice — race the 2s- // poll and are lost.- sandboxDBs.SetOnRemove(func(sandboxID string) {- pub.FlushSandbox(context.Background(), sandboxID)- })-- pub.Start(ctx)- b.eventPub = pub- log.Printf("microvm: event publisher started (stream=events:%s)", cellID)-}--// Capacity reports this cell's placement numbers to the edge, in the shape a-// QEMU cell reports worker counts. Implements controlplane.CapacitySource.-//-// `available` is a constant 1: this backend has no cell-level capacity worth-// publishing. Its real ceiling is an AWS regional memory quota that is raised-// on request and sits orders of magnitude above current use, so any number we-// computed would say "yes" until the day it didn't.-//-// It reported pool depth first, which was wrong in the direction that costs-// customers: the pool is warmth, not capacity. Advertising depth 503'd creates-// the backend could serve — every burst past the pool, plus a 30s window after-// each refill where a fully-stocked cell still advertised zero.-//-// What this keeps is the freshness half. The edge also requires-// capacity_updated_at inside 120s, so this doubles as a liveness heartbeat: a-// CP that dies, loses Redis, or stops forwarding drops its cell out of routing-// on its own. That is how a stopped dev CP announced itself rather than-// silently black-holing creates.-//-// Not covered: a live CP whose AWS credentials have expired keeps publishing 1-// while failing every launch. Closing that means gating on a recent-success-// signal rather than a constant — worth doing when this backend carries real-// traffic, and deliberately not built now.-func (b *microvmBackend) Capacity() (healthy, available, running int) {- if b == nil {- return 0, 0, 0- }- n, err := b.manager.Count(context.Background())- if err != nil {- n = 0- }- return 1, 1, n-}--// StartCapacityReporter publishes this cell's capacity so the edge will route-// to it at all.-//-// Without this a MicroVM cell is invisible rather than unhealthy: the edge's-// isHealthy() gate requires available_workers > 0 and a capacity_updated_at-// inside 120s, both of which only ever came from the QEMU worker registry. A-// cell with no workers never wrote either, so every create — including one-// pinned to it by cellId — fell through to "no cells available with capacity".-func (b *microvmBackend) StartCapacityReporter(ctx context.Context, rdb *redis.Client, cellID string) {- if b == nil {- return- }- if rdb == nil || cellID == "" {- log.Printf("microvm: WARNING capacity reporter disabled (redis=%v cellID=%q) — the edge will not route creates to this cell",- rdb != nil, cellID)- return- }- cr, err := controlplane.NewCapacityReporter(controlplane.CapacityReporterConfig{- Redis: rdb,- Source: b,- CellID: cellID,- })- if err != nil {- log.Printf("microvm: WARNING capacity reporter init failed: %v — the edge will not route creates to this cell", err)- return- }- cr.Start(ctx)- b.capacity = cr- log.Printf("microvm: capacity reporter started (cell=%s)", cellID)-}--// Close stops the maintenance loop and terminates remaining stock.-func (b *microvmBackend) Close() {- if b == nil {- return- }- if b.usageTicker != nil {- stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- _ = b.usageTicker.Stop(stopCtx)- cancel()- }- // After the ticker, so its final slices are in SQLite before the publisher- // drains. Stop() does a last flush; skipping it drops the ticks accrued- // since the previous 2s poll on every redeploy.- if b.eventPub != nil {- stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- _ = b.eventPub.Stop(stopCtx)- cancel()- }- if b.capacity != nil {- b.capacity.Stop()- }- b.stopPool()- b.pool.Drain()- b.manager.Close()-}--// microvmWorkerPrefix marks sandbox_sessions.worker_id as backed by this-// runtime and carries the underlying host id after the colon.-//-// There is no worker: the host is managed for us, which is the point of this-// backend. But worker_id is NOT NULL and every existing lookup keys on it, so-// this keeps those queries working. Encoding the host id here rather than-// adding a column is deliberate — it is the only durable link between our-// sandbox id and the host, and without it a control-plane restart loses the-// mapping: the sandboxes become unroutable AND unreapable, billing compute-// until the hard duration cap.-//-// worker_id travels well beyond the database — it is returned in the create-// response, written to D1 sandboxes_index, and rendered in the dashboard — so-// both halves of it are ours to choose, and neither describes the runtime.-const microvmWorkerPrefix = "vmhost:"--// legacyWorkerPrefix is still read so rows predating the current encoding stay-// routable and reapable; dropping it would strand those hosts billing until-// their duration cap with nothing able to parse, reconcile, or terminate them.-// Never written.-const legacyWorkerPrefix = "microvm:"--// hostIDPrefix is the fixed prefix the platform puts on every host id. Trimmed-// on the way into worker_id and restored on the way out, so the id we publish-// is ours end to end while the value we hand back to the platform is unchanged.-// A host id that does not carry it is stored verbatim.-const hostIDPrefix = "microvm-"--// microvmPublisherWorkerID is the event publisher's fallback stamp, used only-// for a sandbox whose host binding is already gone from memory — which in-// practice means its final flush during shutdown or after a reconcile drop.-// The per-sandbox resolver supplies the real owner in every other case.-const microvmPublisherWorkerID = "vmhost-cp"--// microvmWorkerID encodes a host id for storage in worker_id.-func microvmWorkerID(microvmID string) string {- return microvmWorkerPrefix + strings.TrimPrefix(microvmID, hostIDPrefix)-}--// parseMicrovmWorkerID recovers the host id, reporting whether the row is-// backed by this runtime at all.-func parseMicrovmWorkerID(workerID string) (string, bool) {- for _, prefix := range []string{microvmWorkerPrefix, legacyWorkerPrefix} {- if !strings.HasPrefix(workerID, prefix) {- continue- }- id := strings.TrimPrefix(workerID, prefix)- if id == "" {- return "", false- }- // Rows stored before the id was trimmed already carry it.- if !strings.HasPrefix(id, hostIDPrefix) {- id = hostIDPrefix + id- }- return id, true- }- return "", false-}--// execManagerFor returns the sandbox.Manager that owns a sandbox.-//-// This is the routing seam for step 3: MicroVM-backed sandboxes are served by-// the awsvm manager in this process, everything else by the existing-// worker/cell path. Membership is decided by the awsvm manager's own tracking-// rather than a DB read, so the exec hot path stays in memory.-// ── Backend implementation ──────────────────────────────────────────────────--// Compile-time proof this backend satisfies the dispatch seam. Without it a-// method-signature drift would not surface until a call site failed at runtime,-// which for this backend has repeatedly meant a silent failure rather than a-// loud one.-var _ Placer = (*microvmBackend)(nil)--func (b *microvmBackend) Name() string { return "vmhost" }--func (b *microvmBackend) WorkerIDPrefixes() []string {- return []string{microvmWorkerPrefix, legacyWorkerPrefix}-}--func (b *microvmBackend) OwnsWorkerID(workerID string) bool {- _, ok := parseMicrovmWorkerID(workerID)- return ok-}--// Route reports whether this backend holds the sandbox, from its in-memory-// binding only. Deliberately not an availability check: a false here sends the-// caller to another backend, so "mine but sick" must never look like "not-// mine".-func (b *microvmBackend) Route(_ context.Context, sandboxID string) (sandbox.Manager, bool) {- if b == nil {- return nil, false- }- if _, ok := b.manager.MicrovmIDFor(sandboxID); !ok {- return nil, false- }- return b.manager, true-}--// Activate has nothing to do: Claim returns a host that is already running,-// either popped from warm stock or launched and waited for. There is no second-// step, which is the whole reason this backend answers a create in ~350ms.-//-// It reports running rather than an empty status so the caller does not have to-// know which backends boot lazily.-func (b *microvmBackend) Activate(_ context.Context, a activation) (activated, error) {- return activated{sandboxID: a.sandboxID, status: "running"}, nil-}--// RequiresPersistedRow is true: this backend rebuilds its map of what it is-// running *from* these rows, so a host with no row is one nothing will ever-// terminate — it bills compute and holds regional capacity until the service's-// hard lifetime cap.-func (b *microvmBackend) RequiresPersistedRow() bool { return true }--// DefersPersist is true: Claim binds sandbox→MicroVM in the manager and adopts-// the pool's warm tunnel before it returns, so exec, destroy and routing all-// resolve from memory the moment the create is answered. Nothing on the request-// path reads the row, and the two writes it contains measured 230ms of a 450ms-// create. Restart recovery reads it, and tolerates arriving late.-func (b *microvmBackend) DefersPersist() bool { return true }--// Release terminates the host, because here Claim already produced a running-// one — from warm stock or a cold launch. Merely forgetting it would leave a-// box that bills compute and holds regional capacity with nothing tracking it,-// until its hard lifetime cap hours later.-func (b *microvmBackend) Release(ctx context.Context, sandboxID, _ string) {- if b == nil {- return- }- if err := b.manager.Kill(ctx, sandboxID); err != nil {- log.Printf("microvm: release %s: %v", sandboxID, err)- }-}--// Accepts takes creates for orgs assigned to this runtime, and only those.-//-// This is the only moment placement can be decided — a sandbox never moves-// runtimes after Claim (see Placer.Accepts). Two independent reasons to decline:-//-// - the org is not assigned here. Assignment lives in D1 orgs.runtime and-// arrives on the capability token, so an org reaches this backend only by-// an explicit row. Everyone else — including every org that predates this-// field — falls through to the QEMU fleet exactly as before.-// - the request needs something this runtime cannot do. A custom template is-// a QEMU checkpoint; there is no such artifact here, where a template is a-// container image. Accepting one would build the sandbox from the wrong-// image and report success.-//-// Declining is not an error. The create is offered to the next registered-// Placer, which is the fleet.-//-// OPERATIONAL CONSTRAINT: an org pinned to this runtime must only be routed to-// cells that run this backend. Declining assumes something to decline TO, and-// the reverse holds as well — a microvm-pinned org landing on a cell without-// this backend finds no Placer at all and gets a 503 rather than being quietly-// served by QEMU. That is the intended failure: silently serving the other-// runtime is what this design exists to prevent.-//-// Accepts must stay a pure function of the request. Putting mutable runtime-// state here — pool depth, quota, health — would create a decision that is true-// when asked and false when acted on, and Claim is terminal, so there is no-// second chance. Capacity belongs in Claim, where failing may mean failing.-func (b *microvmBackend) Accepts(p placement) bool {- if b == nil {- return false- }- if p.runtime != runtimeMicrovm {- return false- }- // Custom templates resolve to checkpoint artifacts this runtime cannot- // restore. The named default is fine — it maps to the image.- if p.cfg.Template != "" && p.cfg.Template != "default" && p.cfg.Template != poolTemplateName() {- return false- }- return true-}--// Hibernate parks a sandbox: its workspace goes to blob storage and the host is-// suspended. See internal/awsvm/workspace.go for why only /home/sandbox travels-// — AWS exposes no snapshot export, so the archive is ordinary files rather-// than machine state.-func (b *microvmBackend) Hibernate(ctx context.Context, sandboxID string) (*sandbox.HibernateResult, error) {- if b == nil || b.manager == nil {- return nil, fmt.Errorf("microvm: hibernate %s: backend not available", sandboxID)- }- if b.checkpointStore == nil {- // Explicit rather than a nil-pointer panic deeper in: a cell without a- // blob store can run sandboxes perfectly well and simply cannot park- // them, and the operator needs to be told which of the two it is.- return nil, fmt.Errorf("microvm: hibernate %s: no checkpoint store configured", sandboxID)- }- return b.manager.Hibernate(ctx, sandboxID, b.checkpointStore)-}--// Wake revives a sandbox and reports the worker_id now serving it.-//-// The manager decides how: a still-suspended host is resumed in place, and one-// that is gone is rebuilt from the archive. Both land here, and only the second-// changes hosts — which is exactly why the id is returned rather than assumed.-// A restore mints a NEW MicroVM, and a caller that kept the old worker_id would-// leave a live sandbox that nothing can route to.-func (b *microvmBackend) Wake(ctx context.Context, sandboxID, hibernationKey string, timeoutSeconds int) (string, error) {- if b == nil || b.manager == nil {- return "", fmt.Errorf("microvm: wake %s: backend not available", sandboxID)- }- if b.checkpointStore == nil {- return "", fmt.Errorf("microvm: wake %s: no checkpoint store configured", sandboxID)- }- if _, err := b.manager.Wake(ctx, sandboxID, hibernationKey, b.checkpointStore, timeoutSeconds); err != nil {- return "", err- }- microvmID, ok := b.manager.MicrovmIDFor(sandboxID)- if !ok {- // Wake reported success but left nothing tracked, so there is no id to- // persist. Failing here is the honest answer: reporting success would- // write a stale worker_id and strand a running sandbox.- return "", fmt.Errorf("microvm: wake %s: no host tracked after wake", sandboxID)- }- return microvmWorkerID(microvmID), nil-}--func (b *microvmBackend) Reconcile(ctx context.Context, store *db.Store) {- b.reconcileOnce(ctx, store)-}--// respondManagerErr maps a sandbox.Manager error to a response, turning-// "this backend cannot do that" into 501 Not Implemented rather than 500.-//-// The distinction matters to callers: a 500 invites a retry and reads as our-// bug, while 501 says the operation will never succeed on this runtime. The-// MicroVM backend returns ErrUnsupported for checkpoint/fork (no counterpart in-// a service where images are built through an API rather than captured from a-// running VM) and for SetResourceLimits (sizing belongs to the image, so there-// is no per-sandbox knob to turn).-func respondManagerErr(c echo.Context, err error) error {- if errors.Is(err, awsvm.ErrUnsupported) {- return c.JSON(http.StatusNotImplemented, map[string]string{- "error": "this operation is not supported for this sandbox",- })- }- // Logged, not returned: internal errors carry upstream service names,- // resource ids, and wording.- log.Printf("microvm: operation failed: %v", err)- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": "the sandbox could not complete this operation",- })-}--// parseSizeImages reads the tier→image map from-// OPENSANDBOX_MICROVM_SIZE_IMAGES, formatted "1024=arn:...,8192=arn:...".-//-// Only tiers listed here are offered beyond the default; an unlisted size is-// refused at create rather than served from the default image. Malformed-// entries are dropped with a log rather than failing startup — a typo in one-// tier must not take the whole cell down, but it must not silently become a-// wrong-size sandbox either, and dropping it makes that tier 501 instead.-func parseSizeImages(raw string) map[int]string {- if strings.TrimSpace(raw) == "" {- return nil- }- out := map[int]string{}- for _, pair := range strings.Split(raw, ",") {- pair = strings.TrimSpace(pair)- if pair == "" {- continue- }- k, v, found := strings.Cut(pair, "=")- mb, err := strconv.Atoi(strings.TrimSpace(k))- if !found || err != nil || mb <= 0 || strings.TrimSpace(v) == "" {- log.Printf("microvm: ignoring malformed SIZE_IMAGES entry %q — that tier will be refused, not downsized", pair)- continue- }- out[mb] = strings.TrimSpace(v)- }- if len(out) == 0 {- return nil- }- return out-}--// sortedTiers lists configured tier sizes in ascending order, for logging.-func sortedTiers(m map[int]string) []int {- out := make([]int, 0, len(m))- for mb := range m {- out = append(out, mb)- }- sort.Ints(out)- return out-}--func envInt(key string, def int) int {- if v := os.Getenv(key); v != "" {- if n, err := strconv.Atoi(v); err == nil && n >= 0 {- return n- }- log.Printf("microvm: ignoring malformed %s=%q, using %d", key, v, def)- }- return def-}--// ServesOwnStock: warm hosts come from this backend's own pool (awsvm.Pool),-// claimed inside Claim, not from the cell's Postgres pool. See SelfStocking.-func (b *microvmBackend) ServesOwnStock() bool { return true }diff --git a/internal/api/microvm_backend_test.go b/internal/api/microvm_backend_test.godeleted file mode 100644index 879c8d59..00000000--- a/internal/api/microvm_backend_test.go+++ /dev/null@@ -1,188 +0,0 @@-package api--import (- "context"- "errors"- "fmt"- "net/http"- "net/http/httptest"- "strings"- "testing"-- "github.com/labstack/echo/v4"- "github.com/opensandbox/opensandbox/internal/awsvm"- "github.com/opensandbox/opensandbox/pkg/types"-)--// The MicroVM backend is off by default and its hooks sit in three handlers the-// QEMU fleet uses on every request (createSandbox, killSandboxByID,-// execRunAsyncRoute). These tests pin the property that makes that safe: with-// the backend disabled, every hook is inert.-//-// This is the regression guard for a real bug found the hard way — the claim-// was originally placed behind the worker-registry check, which made it-// unreachable on a MicroVM-only cell. Placement in these handlers is load-// bearing in both directions.--// The Backend contract itself is covered generically in-// backend_conformance_test.go. What remains here is this backend's own-// lifecycle wiring — the calls the router makes at startup and shutdown, which-// no other backend has and which must not panic when the runtime is disabled.-// That nil case IS the QEMU fleet.-func TestNilMicrovmBackendIsInert(t *testing.T) {- var b *microvmBackend // explicitly nil, as on a QEMU cell-- if id, ok := b.claimPooled("sb-test", types.SandboxConfig{}); ok || id != "" {- t.Fatalf("nil backend claimed a box: id=%q ok=%v", id, ok)- }- if d := b.Depth(); d != 0 {- t.Fatalf("nil backend reported depth %d", d)- }- owned, err := b.Kill(context.Background(), "sb-test")- if owned || err != nil {- t.Fatalf("nil backend claimed ownership on Kill: owned=%v err=%v", owned, err)- }- // Must not panic.- b.Close()- b.Restore(context.Background(), nil)- b.StartReconciler(context.Background(), nil)- b.StartUsageTicker(context.Background(), nil)- b.StartCapacityReporter(context.Background(), nil, "")- b.StartEventPublisher(context.Background(), nil, nil, "", nil)-}--// execManagerFor decides whether a sandbox is served in-process or dispatched-// to a worker. On a QEMU cell it must never claim a sandbox, or exec would be-// routed to a backend that does not hold it.-func TestExecManagerForDeclinesWhenBackendDisabled(t *testing.T) {- s := &Server{} // microvm nil- if mgr, ok := s.execManagerFor("sb-anything"); ok || mgr != nil {- t.Fatalf("disabled backend claimed sandbox routing: mgr=%v ok=%v", mgr, ok)- }-}--// ErrUnsupported must surface as 501, not 500: a 500 reads as our bug and-// invites a retry, while the operation can never succeed on this runtime.-func TestRespondManagerErrMapsUnsupportedTo501(t *testing.T) {- e := echo.New()- rec := httptest.NewRecorder()- c := e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)-- if err := respondManagerErr(c, awsvm.ErrUnsupported); err != nil {- t.Fatalf("respondManagerErr: %v", err)- }- if rec.Code != http.StatusNotImplemented {- t.Fatalf("unsupported op returned %d, want 501", rec.Code)- }-}--// Anything that is not ErrUnsupported stays a 500 — a transport failure or a-// dead box is a real error and must not be reported as "not implemented".-func TestRespondManagerErrKeeps500ForRealErrors(t *testing.T) {- e := echo.New()- rec := httptest.NewRecorder()- c := e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)-- if err := respondManagerErr(c, errors.New("connection reset")); err != nil {- t.Fatalf("respondManagerErr: %v", err)- }- if rec.Code != http.StatusInternalServerError {- t.Fatalf("ordinary error returned %d, want 500", rec.Code)- }-}--// A full region and a rate limit are different problems with opposite fixes:-// raise the quota vs. wait a second. The response has to say which, or an-// operator tunes the wrong knob and a client cannot decide whether to retry.-func TestRespondCreateErrDistinguishesQuotaFromThrottle(t *testing.T) {- newCtx := func() (echo.Context, *httptest.ResponseRecorder) {- e := echo.New()- rec := httptest.NewRecorder()- return e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec), rec- }-- c, rec := newCtx()- if err := respondCreateErr(c, fmt.Errorf("run: %w", awsvm.ErrQuotaExceeded)); err != nil {- t.Fatalf("respondCreateErr: %v", err)- }- if rec.Code != http.StatusServiceUnavailable {- t.Fatalf("quota returned %d, want 503", rec.Code)- }- if !strings.Contains(rec.Body.String(), "out of capacity") {- t.Fatalf("quota body does not say out of capacity: %s", rec.Body.String())- }- // Retrying cannot help until a box is released, so we must not invite it.- if got := rec.Header().Get("Retry-After"); got != "" {- t.Fatalf("quota set Retry-After=%q, inviting a retry storm at a full region", got)- }-- c, rec = newCtx()- if err := respondCreateErr(c, fmt.Errorf("run: %w", awsvm.ErrThrottled)); err != nil {- t.Fatalf("respondCreateErr: %v", err)- }- if rec.Code != http.StatusServiceUnavailable {- t.Fatalf("throttle returned %d, want 503", rec.Code)- }- if rec.Header().Get("Retry-After") == "" {- t.Fatal("throttle is transient but gave the client no Retry-After")- }- if strings.Contains(rec.Body.String(), "out of capacity") {- t.Fatal("throttle reported as out of capacity — sends operators to raise a quota that is fine")- }-}--// Anything unclassified stays a 500: reporting an unknown failure as capacity-// exhaustion would hide a real bug behind a plausible-looking operational-// message.-func TestRespondCreateErrKeeps500ForUnknown(t *testing.T) {- e := echo.New()- rec := httptest.NewRecorder()- c := e.NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)-- if err := respondCreateErr(c, errors.New("connection reset")); err != nil {- t.Fatalf("respondCreateErr: %v", err)- }- if rec.Code != http.StatusInternalServerError {- t.Fatalf("unknown error returned %d, want 500", rec.Code)- }-}--// microvmWorkerID round-trips through worker_id. That encoding is the only-// durable link between a sandbox and its AWS box; if it breaks, a restarted-// control plane cannot rebuild its map and the boxes are both unroutable and-// unreapable.-func TestMicrovmWorkerIDRoundTrips(t *testing.T) {- const id = "microvm-abc123"- got, ok := parseMicrovmWorkerID(microvmWorkerID(id))- if !ok || got != id {- t.Fatalf("round-trip failed: got %q ok=%v", got, ok)- }-- // A real worker id must never be mistaken for a MicroVM row, or the- // reconciler would start closing live QEMU sandboxes.- for _, notOurs := range []string{"worker-eastus2-7", "", "microvm:", "microvm", "vmhost:", "vmhost"} {- if _, ok := parseMicrovmWorkerID(notOurs); ok {- t.Fatalf("parsed %q as a MicroVM worker id", notOurs)- }- }-}--// Rows written before the vendor-neutral rename still carry the old prefix.-// They must stay parseable: the restore path uses this to rebuild the sandbox→-// box map, so a parse failure leaves those sandboxes unroutable and their boxes-// running until the provider's duration cap with nothing able to reap them.-func TestParseMicrovmWorkerIDAcceptsLegacyPrefix(t *testing.T) {- got, ok := parseMicrovmWorkerID("microvm:microvm-abc123")- if !ok || got != "microvm-abc123" {- t.Fatalf("legacy prefix not parsed: got %q ok=%v", got, ok)- }-}--// The written form must be the neutral one. worker_id is returned in the create-// response and written to D1, so writing the old prefix would keep advertising-// the provider to every customer.-func TestMicrovmWorkerIDWritesNeutralPrefix(t *testing.T) {- if got := microvmWorkerID("abc123"); strings.Contains(got, "microvm") {- t.Fatalf("microvmWorkerID produced %q, which names the runtime", got)- }-}diff --git a/internal/api/microvm_common.go b/internal/api/microvm_common.gonew file mode 100644index 00000000..51d8efaa--- /dev/null+++ b/internal/api/microvm_common.go@@ -0,0 +1,238 @@+package api++import (+ "context"+ "errors"+ "fmt"+ "log"+ "net/http"+ "os"+ "sort"+ "strconv"+ "strings"+ "time"++ awsconfig "github.com/aws/aws-sdk-go-v2/config"+ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/awsvm"+)++// microvm_common.go — the parts of the MicroVM runtime that are not specific to+// how we talk to a box.+//+// There used to be two MicroVM backends: an agent-tunnel one (a gRPC channel+// held per box, brokered by the control plane) and the direct-exec "lite" one+// in lite_backend.go. The tunnel backend is gone; lite is the runtime. What+// survives here is everything that was never about the tunnel — enabling the+// runtime, building the AWS client, and the worker_id encoding that outlives+// any single backend because it is written into rows, D1, and the dashboard.++// microvmEnabled reports whether this cell serves MicroVM-backed sandboxes.+// Off unless explicitly turned on: this backend is regional (us-east-1 today)+// and cannot serve a cell whose customers expect QEMU semantics like fork,+// which it does not implement.+func microvmEnabled() bool {+ return os.Getenv("OPENSANDBOX_MICROVM_ENABLED") == "1"+}++// newMicrovmClient builds the AWS client from environment config.+func newMicrovmClient(ctx context.Context) (*awsvm.Client, error) {+ image := os.Getenv("OPENSANDBOX_MICROVM_IMAGE_ARN")+ if image == "" {+ return nil, fmt.Errorf("OPENSANDBOX_MICROVM_ENABLED=1 but OPENSANDBOX_MICROVM_IMAGE_ARN is unset")+ }+ region := os.Getenv("OPENSANDBOX_MICROVM_REGION")+ if region == "" {+ region = "us-east-1"+ }++ awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region))+ if err != nil {+ return nil, fmt.Errorf("microvm: load AWS config: %w", err)+ }++ // Idle policy. Measured on dev: with idle=60s and suspended=300s, a sandbox+ // was TERMINATED — disk and all — roughly six minutes after its last+ // request. The old defaults (900/1800) put that at 45 minutes of inactivity,+ // which silently destroys any sandbox a customer steps away from.+ //+ // idle seconds without inbound proxy traffic before AWS suspends.+ // suspended seconds a box may stay suspended before AWS TERMINATES it.+ // This, not the 8h ceiling, is what actually bounds a parked+ // sandbox, and when it fires the disk goes with it.+ // resume whether an inbound request wakes a suspended box. With this+ // off, nothing can reach a box during its suspended window, so+ // the window always runs out and the sandbox is destroyed.+ //+ // Both default to the 8h hard ceiling so neither timer fires before the cap+ // does, leaving the cap as the single deadline to reason about — and the one+ // the blob promotion works against. Auto-resume defaults ON so that anything+ // which does suspend is recoverable rather than doomed.+ idleSec := envInt("OPENSANDBOX_MICROVM_IDLE_SECONDS", 28_800)+ suspendedSec := envInt("OPENSANDBOX_MICROVM_SUSPENDED_SECONDS", 28_800)+ autoResume := os.Getenv("OPENSANDBOX_MICROVM_AUTO_RESUME") != "0"+ sizeImages := parseSizeImages(os.Getenv("OPENSANDBOX_MICROVM_SIZE_IMAGES"))+ defaultMemoryMB := envInt("OPENSANDBOX_MICROVM_DEFAULT_MEMORY_MB", 0)+ // Empty pins nothing and takes the image's latest active version, which is+ // what production wants. Setting it is for A/B: a republished image changes+ // every box in the fleet at once, so without a way to pin an older version+ // there is no way to tell "the image regressed" from "something else did".+ imageVersion := os.Getenv("OPENSANDBOX_MICROVM_IMAGE_VERSION")+ client := awsvm.NewClient(awsCfg, awsvm.Config{+ Region: region,+ ImageIdentifier: image,+ ImageVersion: imageVersion,+ DefaultMemoryMB: defaultMemoryMB,+ SizeImages: sizeImages,+ ExecutionRoleArn: os.Getenv("OPENSANDBOX_MICROVM_EXECUTION_ROLE_ARN"),+ MaxIdleDurationSeconds: int32(idleSec),+ SuspendedDurationSeconds: int32(suspendedSec),+ AutoResume: autoResume,+ })+ if len(sizeImages) > 0 {+ log.Printf("microvm: size tiers — default %dMB pooled, cold-only: %v",+ client.Config().DefaultMemoryMB, sortedTiers(sizeImages))+ }+ log.Printf("microvm: idle policy — suspend after %ds idle, terminate after %ds suspended, auto-resume=%v",+ idleSec, suspendedSec, autoResume)+ if imageVersion != "" {+ log.Printf("microvm: image version PINNED to %s (unset OPENSANDBOX_MICROVM_IMAGE_VERSION for latest)", imageVersion)+ }++ return client, nil+}++// ── worker_id encoding ──────────────────────────────────────────────────────+//+// A MicroVM has no worker, so worker_id carries the host id instead. Reusing+// the column rather than adding one is deliberate — it is the only durable link+// between our sandbox id and the host, and without it a control-plane restart+// loses the mapping: the sandboxes become unroutable AND unreapable, billing+// compute until the hard duration cap.+//+// worker_id travels well beyond the database — it is returned in the create+// response, written to D1 sandboxes_index, and rendered in the dashboard — so+// both halves of it are ours to choose, and neither describes the runtime.+const microvmWorkerPrefix = "vmhost:"++// legacyWorkerPrefix is still read so rows predating the current encoding stay+// routable and reapable; dropping it would strand those hosts billing until+// their duration cap with nothing able to parse, reconcile, or terminate them.+// Never written.+const legacyWorkerPrefix = "microvm:"++// hostIDPrefix is the fixed prefix the platform puts on every host id. Trimmed+// on the way into worker_id and restored on the way out, so the id we publish+// is ours end to end while the value we hand back to the platform is unchanged.+// A host id that does not carry it is stored verbatim.+const hostIDPrefix = "microvm-"++// microvmPublisherWorkerID is the event publisher's fallback stamp, used only+// for a sandbox whose host binding is already gone from memory — which in+// practice means its final flush during shutdown or after a reconcile drop.+// The per-sandbox resolver supplies the real owner in every other case.+const microvmPublisherWorkerID = "vmhost-cp"++// microvmWorkerID encodes a host id for storage in worker_id.+func microvmWorkerID(microvmID string) string {+ return microvmWorkerPrefix + strings.TrimPrefix(microvmID, hostIDPrefix)+}++// parseMicrovmWorkerID recovers the host id, reporting whether the row is+// backed by this runtime at all.+func parseMicrovmWorkerID(workerID string) (string, bool) {+ for _, prefix := range []string{microvmWorkerPrefix, legacyWorkerPrefix} {+ if !strings.HasPrefix(workerID, prefix) {+ continue+ }+ id := strings.TrimPrefix(workerID, prefix)+ if id == "" {+ return "", false+ }+ // Rows stored before the id was trimmed already carry it.+ if !strings.HasPrefix(id, hostIDPrefix) {+ id = hostIDPrefix + id+ }+ return id, true+ }+ return "", false+}++// respondManagerErr maps a manager error to a response.+//+// The distinction matters to callers: a 500 invites a retry and reads as our+// bug, while 501 says the operation will never succeed on this runtime. The+// MicroVM runtime returns ErrUnsupported for fork and for SetResourceLimits+// (sizing belongs to the image, so there is no per-sandbox knob to turn).+func respondManagerErr(c echo.Context, err error) error {+ if errors.Is(err, awsvm.ErrUnsupported) {+ return c.JSON(http.StatusNotImplemented, map[string]string{+ "error": "this operation is not supported for this sandbox",+ })+ }+ // Logged, not returned: internal errors carry upstream service names,+ // resource ids, and wording.+ log.Printf("microvm: operation failed: %v", err)+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "the sandbox could not complete this operation",+ })+}++// parseSizeImages reads the tier→image map from+// OPENSANDBOX_MICROVM_SIZE_IMAGES, formatted "1024=arn:...,8192=arn:...".+//+// Only tiers listed here are offered beyond the default; an unlisted size is+// refused at create rather than served from the default image. Malformed+// entries are dropped with a log rather than failing startup — a typo in one+// tier must not take the whole cell down, but it must not silently become a+// wrong-size sandbox either, and dropping it makes that tier 501 instead.+func parseSizeImages(raw string) map[int]string {+ if strings.TrimSpace(raw) == "" {+ return nil+ }+ out := map[int]string{}+ for _, pair := range strings.Split(raw, ",") {+ pair = strings.TrimSpace(pair)+ if pair == "" {+ continue+ }+ k, v, found := strings.Cut(pair, "=")+ mb, err := strconv.Atoi(strings.TrimSpace(k))+ if !found || err != nil || mb <= 0 || strings.TrimSpace(v) == "" {+ log.Printf("microvm: ignoring malformed SIZE_IMAGES entry %q — that tier will be refused, not downsized", pair)+ continue+ }+ out[mb] = strings.TrimSpace(v)+ }+ if len(out) == 0 {+ return nil+ }+ return out+}++// sortedTiers lists configured tier sizes in ascending order, for logging.+func sortedTiers(m map[int]string) []int {+ out := make([]int, 0, len(m))+ for mb := range m {+ out = append(out, mb)+ }+ sort.Ints(out)+ return out+}++func envInt(key string, def int) int {+ if v := os.Getenv(key); v != "" {+ if n, err := strconv.Atoi(v); err == nil && n >= 0 {+ return n+ }+ log.Printf("microvm: ignoring malformed %s=%q, using %d", key, v, def)+ }+ return def+}++// microvmReconcileInterval is how often the backend re-checks its bindings+// against the platform. Nothing else ever notices one of these boxes dying —+// no worker reports in for them — so this ticker is the only liveness signal+// the control plane has for the runtime.+const microvmReconcileInterval = 5 * time.Minutediff --git a/internal/api/microvm_direct.go b/internal/api/microvm_direct.godeleted file mode 100644index dc39b04c..00000000--- a/internal/api/microvm_direct.go+++ /dev/null@@ -1,39 +0,0 @@-package api--import (- "net/http"-- "github.com/labstack/echo/v4"-- "github.com/opensandbox/opensandbox/internal/awsvm"-)--// microvm_direct.go — hands the edge what it needs to talk to a MicroVM without-// going through this process.-//-// Every exec today travels edge → (CF tunnel) → control plane → agent tunnel →-// guest, and the control plane leg alone is the majority of time-to-first-exec-// because the CP lives in a different region from the boxes. Nothing about that-// leg is load-bearing: a MicroVM's endpoint is a public TLS host and its-// credential is a plain, port-scoped header token, so the edge can hold the-// agent tunnel itself and the CP drops out of the data path entirely.-//-// This route exists to measure that claim before building on it. It is-// read-only and mints nothing the CP does not already mint for its own dials.--// microvmDirectInfo handles GET /internal/microvm/direct/:id.-func (s *Server) microvmDirectInfo(c echo.Context) error {- if s.microvm == nil || s.microvm.manager == nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": "microvm backend not enabled on this cell"})- }- endpoint, token, port, err := s.microvm.manager.DirectInfo(c.Request().Context(), c.Param("id"))- if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})- }- return c.JSON(http.StatusOK, map[string]any{- "endpoint": endpoint,- "token": token,- "port": port,- "path": awsvm.AgentTunnelPath,- })-}diff --git a/internal/api/microvm_hibernation.go b/internal/api/microvm_hibernation.godeleted file mode 100644index b92e5dc3..00000000--- a/internal/api/microvm_hibernation.go+++ /dev/null@@ -1,108 +0,0 @@-package api--import (- "context"- "log"- "time"-- "github.com/opensandbox/opensandbox/internal/db"-)--// microvm_hibernation.go — retiring the suspended box behind a hibernation.-//-// Hibernate exports the workspace to blob storage and then suspends the box, so-// from that moment there are two copies: a durable archive, and a suspended-// host that can serve a ~1s resume instead of a restore. The host is the-// disposable one — it goes on holding regional memory quota, which is the-// ceiling on warm-pool depth, purely to make a quick wake quicker.-//-// This sweep retires it. Two conditions, and the order matters:-//-// 1. the upload must have completed. A suspended box whose archive is still in-// flight is the ONLY copy of that sandbox, and terminating it loses the-// customer's data outright. Not slowly, not recoverably — the box is gone-// and the blob is a partial object nothing can restore from.-//-// 2. the dwell must have elapsed. Customers who hibernate and wake within the-// same minute are common, and for them the suspended box is the difference-// between a resume and a full restore.-//-// Condition 1 is a safety invariant and has no timeout: if an upload is stuck-// for an hour, the box lives for an hour. Condition 2 is a tunable comfort-// margin on top.--// hibernationDwell is how long a suspended box is kept after its archive is-// durable. Short enough to bound quota, long enough to cover the-// hibernate-then-immediately-wake pattern.-const hibernationDwell = 10 * time.Minute--// hibernationSweepInterval paces the sweep. Well under the dwell so a box is-// retired close to its deadline rather than a whole period late.-const hibernationSweepInterval = 2 * time.Minute--// StartHibernationExpiry runs the sweep for the life of the process.-func (b *microvmBackend) StartHibernationExpiry(ctx context.Context, store *db.Store) {- if b == nil || store == nil {- return- }- go func() {- t := time.NewTicker(hibernationSweepInterval)- defer t.Stop()- for {- select {- case <-ctx.Done():- return- case <-t.C:- b.expireHibernations(ctx, store)- }- }- }()- log.Printf("microvm: hibernation expiry started (dwell=%s, gated on upload completion)", hibernationDwell)-}--// expireHibernations terminates suspended boxes whose archive is safely stored-// and whose dwell has passed.-func (b *microvmBackend) expireHibernations(ctx context.Context, store *db.Store) {- rows, err := store.ListRetirableHibernations(ctx, b.WorkerIDPrefixes(), time.Now().Add(-hibernationDwell))- if err != nil {- log.Printf("microvm: hibernation expiry query failed: %v", err)- return- }- var retired int- for _, r := range rows {- microvmID, ok := parseMicrovmWorkerID(r.WorkerID)- if !ok {- continue- }- if !safeToRetire(r) {- continue- }- if err := b.client.Terminate(ctx, microvmID); err != nil {- log.Printf("microvm: expire %s: terminate: %v", r.SandboxID, err)- continue- }- if err := store.SetHibernationMode(ctx, r.SandboxID, "deep"); err != nil {- log.Printf("microvm: expire %s: mark deep: %v", r.SandboxID, err)- }- b.manager.Forget(r.SandboxID)- retired++- }- if retired > 0 {- log.Printf("microvm: hibernation expiry retired %d suspended box(es) to blob-only", retired)- }-}--// safeToRetire reports whether a suspended box can be terminated.-//-// Separate from the query on purpose. The SQL already filters on uploaded_at,-// but this is the single line standing between a customer's files and-// deletion, and a WHERE clause is easy to loosen by accident three refactors-// from now. Checking it again in code — where it can be tested without a-// database — makes the invariant something a test can hold onto.-//-// Until the archive is uploaded the suspended box is the ONLY copy of that-// sandbox: the blob is a partial object nothing can restore from. Terminating-// then does not degrade the wake, it destroys the sandbox.-func safeToRetire(r db.RetirableHibernation) bool {- return r.UploadedAt != nil-}diff --git a/internal/api/microvm_hibernation_test.go b/internal/api/microvm_hibernation_test.godeleted file mode 100644index 2a88183b..00000000--- a/internal/api/microvm_hibernation_test.go+++ /dev/null@@ -1,30 +0,0 @@-package api--import (- "testing"- "time"-- "github.com/opensandbox/opensandbox/internal/db"-)--// A suspended box may only be released once its archive is durable. Before-// that it is the only copy of the sandbox, and terminating it destroys the-// customer's files outright — there is no degraded wake, there is nothing.-//-// This is the invariant the whole hibernation design rests on, so it is pinned-// here rather than left to a WHERE clause.-func TestSuspendedBoxIsNeverRetiredBeforeItsUploadCompletes(t *testing.T) {- if safeToRetire(db.RetirableHibernation{SandboxID: "sb-1", UploadedAt: nil}) {- t.Fatal("retired a hibernation whose archive had not finished uploading — the sandbox would be destroyed")- }-}--// Once the archive is stored the box is only a latency cache, and holding it-// costs regional memory quota — the ceiling on warm-pool depth. Failing to-// release it is a slow capacity leak.-func TestRetiresOnceTheArchiveIsDurable(t *testing.T) {- at := time.Now().Add(-time.Minute)- if !safeToRetire(db.RetirableHibernation{SandboxID: "sb-1", UploadedAt: &at}) {- t.Fatal("kept a suspended box after its archive was safely uploaded")- }-}diff --git a/internal/api/microvm_orphan_test.go b/internal/api/microvm_orphan_test.godeleted file mode 100644index 7273e99f..00000000--- a/internal/api/microvm_orphan_test.go+++ /dev/null@@ -1,159 +0,0 @@-package api--import (- "context"- "os"- "testing"- "time"-- "github.com/aws/aws-sdk-go-v2/aws"- lambdamicrovms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"- mvtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"-- "github.com/opensandbox/opensandbox/internal/awsvm"-)--// sweepAPI serves a fixed inventory to the orphan sweep and records every-// termination it attempts. Only the calls the sweep makes are implemented.-type sweepAPI struct {- items []mvtypes.MicrovmItem- getImage map[string]string // id → ImageArn returned by GetMicrovm- getState map[string]mvtypes.MicrovmState- terminated []string- gets int-}--func (f *sweepAPI) ListMicrovms(context.Context, *lambdamicrovms.ListMicrovmsInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ListMicrovmsOutput, error) {- return &lambdamicrovms.ListMicrovmsOutput{Items: f.items}, nil-}-func (f *sweepAPI) GetMicrovm(_ context.Context, in *lambdamicrovms.GetMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {- f.gets++- id := aws.ToString(in.MicrovmIdentifier)- state := mvtypes.MicrovmStateRunning- if s, ok := f.getState[id]; ok {- state = s- }- return &lambdamicrovms.GetMicrovmOutput{- MicrovmId: aws.String(id),- ImageArn: aws.String(f.getImage[id]),- State: state,- }, nil-}-func (f *sweepAPI) TerminateMicrovm(_ context.Context, in *lambdamicrovms.TerminateMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error) {- f.terminated = append(f.terminated, aws.ToString(in.MicrovmIdentifier))- return &lambdamicrovms.TerminateMicrovmOutput{}, nil-}-func (f *sweepAPI) RunMicrovm(context.Context, *lambdamicrovms.RunMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {- panic("sweep must not launch")-}-func (f *sweepAPI) SuspendMicrovm(context.Context, *lambdamicrovms.SuspendMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.SuspendMicrovmOutput, error) {- panic("sweep must not suspend")-}-func (f *sweepAPI) ResumeMicrovm(context.Context, *lambdamicrovms.ResumeMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ResumeMicrovmOutput, error) {- panic("sweep must not resume")-}-func (f *sweepAPI) CreateMicrovmAuthToken(context.Context, *lambdamicrovms.CreateMicrovmAuthTokenInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error) {- panic("sweep must not mint tokens")-}--func summary(id, image string, age time.Duration) mvtypes.MicrovmItem {- return mvtypes.MicrovmItem{- MicrovmId: aws.String(id),- ImageArn: aws.String(image),- State: mvtypes.MicrovmStateRunning,- StartedAt: aws.Time(time.Now().Add(-age)),- }-}--func sweepBackend(t *testing.T, f *sweepAPI) *microvmBackend {- t.Helper()- const ourImage = "arn:ours"- c := awsvm.NewClientWithAPI(f, awsvm.Config{ImageIdentifier: ourImage})- return µvmBackend{- client: c,- pool: awsvm.NewPool(c, awsvm.PoolConfig{}),- manager: awsvm.NewManager(c, os.TempDir()),- }-}--// This AWS account is shared with other products. The image check is the only-// thing standing between the sweep and someone else's fleet, so it must require-// a POSITIVE match — an unknown image has to protect a box, not expose it.-//-// The original guard read `ImageArn != "" && ImageArn != ourImage`, which skipped-// the comparison entirely when the field was empty. ListMicrovms returns a-// reduced projection, so "empty" is a routine answer, not a rare one — that-// version would have terminated every foreign box whose image it failed to read.-func TestOrphanSweepNeverReapsWhatItCannotProveIsOurs(t *testing.T) {- t.Setenv("OPENSANDBOX_MICROVM_ORPHAN_REAP", "1")- old := 2 * orphanMinAge-- f := &sweepAPI{- items: []mvtypes.MicrovmItem{- summary("microvm-ours", "arn:ours", old),- summary("microvm-theirs", "arn:someone-else", old),- summary("microvm-blank", "", old), // list omitted it; Get says foreign- summary("microvm-hidden", "", old), // list omitted it; Get says ours- },- getImage: map[string]string{- "microvm-blank": "arn:someone-else",- "microvm-hidden": "arn:ours",- },- }- b := sweepBackend(t, f)- b.sweepOrphans(context.Background())-- got := map[string]bool{}- for _, id := range f.terminated {- got[id] = true- }- if !got["microvm-ours"] {- t.Error("did not reap microvm-ours — an abandoned box of ours keeps holding quota")- }- if !got["microvm-hidden"] {- t.Error("did not reap microvm-hidden — a Get proved it ours, so the list projection gap should not shield it")- }- if got["microvm-theirs"] {- t.Fatal("TERMINATED ANOTHER PRODUCT'S BOX (microvm-theirs) — foreign image was reaped")- }- if got["microvm-blank"] {- t.Fatal("TERMINATED ANOTHER PRODUCT'S BOX (microvm-blank) — empty list image fell through the guard")- }-}--// If the image cannot be established at all, nothing is eligible. A sweep that-// reaps on ignorance is worse than one that reaps nothing.-func TestOrphanSweepReapsNothingWhenOwnershipIsUnknowable(t *testing.T) {- t.Setenv("OPENSANDBOX_MICROVM_ORPHAN_REAP", "1")- old := 2 * orphanMinAge-- f := &sweepAPI{- items: []mvtypes.MicrovmItem{- summary("microvm-a", "", old),- summary("microvm-b", "", old),- },- getImage: map[string]string{}, // Get returns "" too- }- b := sweepBackend(t, f)- b.sweepOrphans(context.Background())-- if len(f.terminated) != 0 {- t.Fatalf("terminated %v with no provable ownership", f.terminated)- }-}--// Young boxes must be skipped before the image lookup, or a large foreign fleet-// costs a GetMicrovm each on an account that already throttles ListMicrovms.-func TestOrphanSweepDoesNotProbeYoungBoxes(t *testing.T) {- f := &sweepAPI{- items: []mvtypes.MicrovmItem{- summary("microvm-young", "", time.Minute),- },- }- b := sweepBackend(t, f)- b.sweepOrphans(context.Background())-- if f.gets != 0 {- t.Fatalf("issued %d GetMicrovm call(s) for a box too young to reap", f.gets)- }-}diff --git a/internal/awsvm/agent.go b/internal/awsvm/agent.godeleted file mode 100644index baac1dc2..00000000--- a/internal/awsvm/agent.go+++ /dev/null@@ -1,646 +0,0 @@-package awsvm--import (- "context"- "crypto/tls"- "fmt"- "io"- "log"- "net"- "net/http"- "sync"- "time"-- "github.com/gorilla/websocket"- "github.com/opensandbox/opensandbox/internal/wsconn"- "google.golang.org/grpc"- "google.golang.org/grpc/connectivity"- "google.golang.org/grpc/credentials/insecure"- "google.golang.org/grpc/keepalive"-- pb "github.com/opensandbox/opensandbox/proto/agent"-)--// agent.go — talking to osb-agent inside a MicroVM.-//-// This is the load-bearing assumption of the whole backend. In the QEMU world-// the host reaches the agent over a private virtio-serial/vsock channel it owns-// end to end. Here there is no host: the only way in is Lambda's public HTTPS-// endpoint for that MicroVM, which proxies to a guest port when the request-// carries a JWE in X-aws-proxy-auth and the port in X-aws-proxy-port.-//-// Plain gRPC over that proxy does NOT work, and this is the file where that was-// found. The proxy speaks HTTP/2, but it strips HTTP/2 trailers — and gRPC-// delivers grpc-status in trailers. The result is the worst possible failure-// mode: the RPC reaches the agent, the command runs in the guest, and the client-// then reports "server closed the stream without sending trailers" with no-// result. Confirmed by round-tripping an unannounced trailer through the proxy-// (lost) versus the same exchange against a local Go server (preserved), so it-// is the platform and not our stack.-//-// Two further constraints found the same way, both load-bearing:-// - The proxy forwards ONLY to the port declared in the image's hook config.-// A second listener is unreachable: gRPC to the agent's own port returned-// 502 while the identical call to the declared port was answered.-// - Requests do arrive intact in every other respect, and WebSockets pass-// through cleanly, which is what makes the tunnel below possible.-//-// So the agent protocol IS reused unchanged — every RPC, streaming included —-// but carried inside a WebSocket where the proxy cannot see or discard the-// trailers. The token comes from a provider function rather than a fixed string-// because tokens expire after at most 60 minutes and a long-lived sandbox will-// outlive several of them.--// tokenProvider returns a currently-valid JWE for a MicroVM. Called on every-// RPC, so it must be cheap on the hit path (Client.AuthToken caches).-type tokenProvider func(ctx context.Context) (string, error)--// agentConn is one MicroVM's agent channel.-type agentConn struct {- conn *grpc.ClientConn- client pb.SandboxAgentClient-}--// agentTunnelPath is the guest WebSocket endpoint carrying gRPC. Must match-// cmd/microvm-hooks.-const agentTunnelPath = "/osb/agent-grpc"--// AgentTunnelPath exposes the tunnel path to callers outside this package that-// dial the same endpoint themselves — see Manager.DirectInfo.-const AgentTunnelPath = agentTunnelPath--// dialAgent opens a gRPC channel to the agent behind a MicroVM endpoint.-//-// The channel runs over a WebSocket rather than straight HTTP/2, because-// Lambda's proxy strips HTTP/2 trailers and gRPC carries its status there — so-// direct gRPC executes the command in the guest and then loses the result.-// Inside a WebSocket the proxy forwards opaque frames and the gRPC stream,-// trailers included, survives untouched. See internal/wsconn.-//-// Deliberately NOT grpc.WithBlock(): the endpoint is a public TLS service that-// may be mid-resume, and blocking here would put connection setup on the-// caller's critical path. gRPC connects lazily on the first RPC, and if the box-// is suspended, Lambda holds that request while it auto-resumes.-// holdIdle selects the keepalive contract for a channel, and the two callers-// want opposite things from it.-//-// A CUSTOMER sandbox should be allowed to fall idle and suspend — that is how-// this backend stops billing compute for a box nobody is using — so its channel-// must not ping when there are no active RPCs.-//-// POOL STOCK is the exact inverse: the pool's whole job is to keep a box warm-// and reachable so the first exec doesn't pay a handshake, and it pays for that-// on purpose. With PermitWithoutStream false, a stocked channel emits nothing-// between the pool's 30s application pings, so a transport that dies in between-// is discovered only by a ping that then has to rebuild it inside pingTimeout-// (3s) — which is far less than a WebSocket upgrade plus guest attach. Two of-// those in a row retire the channel, and gRPC's reconnect backoff climbs toward-// ~2 minutes, so the box stays cold. Measured consequence: 96% of edge reserves-// found warm_tunnel=false despite every box having been dialled successfully at-// manufacture (7456 launches, zero pre-dial failures).-type holdIdle bool--const (- idleMaySuspend holdIdle = false // customer sandboxes- idleKeepWarm holdIdle = true // pool stock-)--func dialAgent(endpoint string, port int32, token tokenProvider, hold holdIdle) (*agentConn, error) {- if endpoint == "" {- return nil, fmt.Errorf("awsvm: empty MicroVM endpoint")- }- host := hostOnly(endpoint)-- // The proxy authenticates the WebSocket handshake, so the auth headers ride- // on the upgrade rather than on each RPC. Per-RPC metadata would never be- // seen by the proxy at all — it only sees the opaque tunnel.- dialTunnel := func(ctx context.Context, _ string) (net.Conn, error) {- v, err := token(ctx)- if err != nil {- return nil, fmt.Errorf("awsvm: auth token: %w", err)- }- hdr := http.Header{}- hdr.Set("X-aws-proxy-auth", v)- hdr.Set("X-aws-proxy-port", fmt.Sprintf("%d", port))-- d := &websocket.Dialer{- HandshakeTimeout: 20 * time.Second,- TLSClientConfig: &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12},- ReadBufferSize: 64 * 1024,- WriteBufferSize: 64 * 1024,- }- ws, resp, err := d.DialContext(ctx, "wss://"+host+agentTunnelPath, hdr)- if err != nil {- if resp != nil {- return nil, fmt.Errorf("awsvm: agent tunnel handshake to %s (http %d): %w", host, resp.StatusCode, err)- }- return nil, fmt.Errorf("awsvm: agent tunnel handshake to %s: %w", host, err)- }- return wsconn.New(ws), nil- }-- conn, err := grpc.NewClient(host+":443",- // The tunnel already runs over TLS to the proxy; inside it we speak- // cleartext HTTP/2 to the guest's loopback agent.- grpc.WithTransportCredentials(insecure.NewCredentials()),- grpc.WithContextDialer(dialTunnel),- // The guest can return large file reads; match the QEMU path's ceiling- // so behaviour doesn't silently differ between backends.- grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(256*1024*1024),- grpc.MaxCallSendMsgSize(256*1024*1024),- ),- // See holdIdle: pool stock keeps its transport alive between pings,- // customer sandboxes are allowed to fall idle and suspend.- grpc.WithKeepaliveParams(keepalive.ClientParameters{- Time: 60 * time.Second,- Timeout: 20 * time.Second,- PermitWithoutStream: bool(hold),- }),- )- if err != nil {- return nil, fmt.Errorf("awsvm: dial agent at %s: %w", host, err)- }- return &agentConn{conn: conn, client: pb.NewSandboxAgentClient(conn)}, nil-}--// DialAgentConnected dials the agent tunnel and waits until the channel is-// actually READY, rather than returning a lazy channel that would do the real-// work on the first RPC. That distinction is the whole point: gRPC connects on-// demand by default, so a "pre-dialled" channel that was never forced open-// would still hand the full handshake cost to the first exec.-func (c *Client) DialAgentConnected(ctx context.Context, microvmID, endpoint string) (*agentConn, error) {- // Pool stock: hold the transport open between the pool's 30s pings.- a, err := dialAgent(endpoint, c.cfg.AgentPort, func(ctx context.Context) (string, error) {- return c.AuthToken(ctx, microvmID)- }, idleKeepWarm)- if err != nil {- return nil, err- }-- a.conn.Connect()- for {- s := a.conn.GetState()- if s == connectivity.Ready {- return a, nil- }- if !a.conn.WaitForStateChange(ctx, s) {- _ = a.Close()- return nil, fmt.Errorf("awsvm: agent tunnel to %s not ready: %w", microvmID, ctx.Err())- }- }-}--func (a *agentConn) Close() error {- if a == nil || a.conn == nil {- return nil- }- return a.conn.Close()-}--// hostOnly strips scheme and any trailing path from an endpoint so it can be-// used as a gRPC dial target and TLS server name.-func hostOnly(endpoint string) string {- h := endpoint- for _, prefix := range []string{"https://", "http://"} {- if len(h) > len(prefix) && h[:len(prefix)] == prefix {- h = h[len(prefix):]- break- }- }- for i := 0; i < len(h); i++ {- if h[i] == '/' {- return h[:i]- }- }- return h-}--// agentPool keeps one channel per sandbox. gRPC channels are expensive to build-// relative to an exec (TLS handshake + HTTP/2 setup), and the benchmark's shape-// — create, exec, destroy — would otherwise pay that handshake on the one call-// that gets measured.-type agentPool struct {- mu sync.Mutex- conns map[string]*agentConn- // failures counts CONSECUTIVE failed keepalive pings per sandbox. Reset by- // any success, and by dropping the channel. See pingTracked.- failures map[string]int-}--func newAgentPool() *agentPool {- return &agentPool{conns: make(map[string]*agentConn), failures: make(map[string]int)}-}--// get returns the cached channel for a sandbox, dialing if needed.-func (p *agentPool) get(sandboxID, endpoint string, port int32, token tokenProvider) (*agentConn, error) {- p.mu.Lock()- if c, ok := p.conns[sandboxID]; ok {- // A cached channel is only useful if it is still usable. Serving one- // that has been shut down is a permanent, silent break: every exec on- // that sandbox returns "grpc: the client connection is closing" in- // milliseconds and nothing ever re-dials, because this map hit is what- // suppresses the dial. Shutdown is terminal in gRPC — it never- // reconnects — so drop it and fall through to a fresh dial. Any other- // state (Idle, Connecting, TransientFailure) does recover on its own- // and must be left alone, or a blip would churn channels under load.- if c.conn == nil || c.conn.GetState() == connectivity.Shutdown {- delete(p.conns, sandboxID)- p.mu.Unlock()- _ = c.Close()- } else {- p.mu.Unlock()- return c, nil- }- } else {- p.mu.Unlock()- }-- // Reaching here on a claimed box means the pre-dialled tunnel did not- // survive to the first exec, which is exactly the ~330ms TTI penalty we are- // hunting. Logged so the cold path is visible instead of merely slow.- log.Printf("awsvm: agent COLD DIAL for %s (%s) — no warm tunnel in pool", sandboxID, endpoint)- // Customer sandbox: let it fall idle and suspend.- c, err := dialAgent(endpoint, port, token, idleMaySuspend)- if err != nil {- return nil, err- }-- p.mu.Lock()- // Another goroutine may have dialed while we were: keep theirs, drop ours,- // so a burst of concurrent execs on one box converges to a single channel.- if existing, ok := p.conns[sandboxID]; ok {- p.mu.Unlock()- _ = c.Close()- return existing, nil- }- p.conns[sandboxID] = c- p.mu.Unlock()- return c, nil-}--// put installs an already-dialled channel for a sandbox — used by the claim-// path to adopt the tunnel the pool established while the box waited in stock.-func (p *agentPool) put(sandboxID string, c *agentConn) {- p.mu.Lock()- old := p.conns[sandboxID]- p.conns[sandboxID] = c- p.mu.Unlock()- if old != nil && old != c {- _ = old.Close()- }-}--// drop closes and forgets a sandbox's channel — on destroy, or after an error-// that suggests the endpoint is gone.-func (p *agentPool) drop(sandboxID string) {- p.mu.Lock()- c := p.conns[sandboxID]- delete(p.conns, sandboxID)- p.mu.Unlock()- if c != nil {- _ = c.Close()- }-}--// warm reconnects the channels of the given sandboxes if they have gone idle.-// Returns how many needed it.-//-// Used for boxes reserved to the edge but not yet claimed by a customer: they-// are warm stock, so keeping their tunnel established is the whole point, and-// none of the idle-suspend reasoning that justifies PermitWithoutStream:false-// applies to a box with no customer on it yet.-//-// Connect() rather than a probe RPC: it restores the transport without touching-// the guest, so nothing that watches for sandbox activity can mistake it for-// any.-func (p *agentPool) warm(sandboxIDs map[string]struct{}) int {- p.mu.Lock()- conns := make([]*agentConn, 0, len(sandboxIDs))- for id := range sandboxIDs {- if c, ok := p.conns[id]; ok && c.conn != nil {- conns = append(conns, c)- }- }- p.mu.Unlock()-- // Only Idle is re-warmable here. Connect() is a no-op on a conn already in- // TransientFailure — it is retrying on gRPC's own backoff, which grows toward- // ~2 minutes — so counting those as "re-warmed" reports work that did not- // happen. Healing them is pingTracked's job: it retires the channel so the- // next get() re-dials.- n := 0- for _, c := range conns {- switch c.conn.GetState() {- case connectivity.Ready, connectivity.Connecting, connectivity.Shutdown, connectivity.TransientFailure:- default: // Idle- c.conn.Connect()- n++- }- }- return n-}--// detach removes a sandbox's channel WITHOUT closing it, handing ownership to-// the caller. drop() is the closing variant; this exists for the one case where-// the channel outlives the binding — an edge reservation returning to stock.-func (p *agentPool) detach(sandboxID string) *agentConn {- p.mu.Lock()- c := p.conns[sandboxID]- delete(p.conns, sandboxID)- p.mu.Unlock()- return c-}--func (p *agentPool) closeAll() {- p.mu.Lock()- conns := p.conns- p.conns = make(map[string]*agentConn)- p.mu.Unlock()- for _, c := range conns {- _ = c.Close()- }-}--// --- keepalive ----//-// Pool boxes are idle by definition: they exist so that nobody has to wait for-// one. But AWS SUSPENDS an idle MicroVM, and the next payload pays the resume —-// measured at ~1s on the first exec against a box that has been sitting, and-// paid identically by the control-plane path and by the edge's direct path,-// because it is the platform waking the VM rather than anything in our-// transport. An overnight gap suspends the entire pool.-//-// A Ping is real guest traffic, so it resets the idle timer in a way that a-// merely-open connection does not. It also keeps the AWS proxy's own connection-// to the guest port attached, which is the OTHER thing a first payload pays for-// (the WebSocket 101 comes from the proxy; the proxy only dials the guest when-// payload first arrives).--// A dead box must not be allowed to starve a live one of its keepalive.-//-// These two numbers together bound how long a maintenance tick can take, and-// the worst case is every box failing: len(stock)/pingConcurrency * pingTimeout.-// At 16/5s that is 130/16*5 = ~41s for a 130-box pool — longer than the 30s-// tick period, so the tick overruns, the NEXT tick starts late, and the boxes-// that were still healthy miss their keepalive and go idle too. That is not a-// hypothetical: dev decayed 130 → 75 → 55 → 30 live tunnels over ten minutes-// while the tick timestamps drifted off their 30s cadence, each dead box paying-// a full 5s timeout and dragging the healthy ones down with it.-//-// At 64/3s the same all-dead pool costs 130/64*3 = ~6s, comfortably inside the-// period. The timeout is still many times a healthy ping (single-digit ms-// through an established tunnel), so it only bites on boxes that are already-// gone.-const (- pingConcurrency = 64- pingTimeout = 3 * time.Second-)--func (a *agentConn) ping(ctx context.Context) error {- if a == nil || a.client == nil {- return nil- }- _, err := a.client.Ping(ctx, &pb.PingRequest{})- return err-}--// proxyTouchPath is the guest endpoint the idle-timer touch requests. Served by-// cmd/microvm-hooks on the declared hook port; cheap, side-effect free, and it-// answers from the guest rather than the proxy, so a 200 also proves the whole-// path is intact.-const proxyTouchPath = "/healthz"--// proxyTouchTimeout bounds one touch. Deliberately generous relative to how long-// /healthz takes (single-digit ms): if the box has ALREADY suspended, this-// request is what wakes it, and Lambda holds it for the length of a snapshot-// restore. Timing out at a "reasonable" few seconds would abort our own resume-// and leave the box suspended, which is the failure this exists to prevent.-const proxyTouchTimeout = 30 * time.Second--// proxyTouchClient is shared so touches reuse TCP/TLS connections instead of-// paying a fresh handshake per box per tick.-var proxyTouchClient = &http.Client{- Timeout: proxyTouchTimeout,- Transport: &http.Transport{- MaxIdleConns: 256,- MaxIdleConnsPerHost: 2,- IdleConnTimeout: 90 * time.Second,- ForceAttemptHTTP2: true,- TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},- },-}--// proxyTouch sends one real HTTP request through a MicroVM's proxy endpoint, to-// reset AWS's idle timer.-//-// This exists because our agent keepalive CANNOT do it, by construction. AWS-// defines idleness as "no inbound traffic through the MicroVM proxy endpoint"-// for maxIdleDurationSeconds — and the keepalive sends HTTP/2 PINGs INSIDE an-// already-established WebSocket. Those are bytes on a connection the proxy-// forwards opaquely; they are not new inbound requests, and they do not count.-// The evidence is unambiguous: stocked boxes with a keepalive pinging them every-// 30s still suspended at exactly the 15-minute idle window, then answered every-// subsequent exec with 502, then were terminated 30 minutes later.-//-// So the touch has to be a fresh request at the proxy's own layer. It is the-// only thing in this package that AWS's idle accounting can actually see.-//-// A non-2xx is returned as an error but is NOT proof the box is bad: a 502 here-// means the proxy could not reach the guest AT THIS MOMENT, which includes a box-// mid-resume. Callers log it; nothing evicts on it.-func proxyTouch(ctx context.Context, endpoint string, port int32, token tokenProvider) error {- if endpoint == "" {- return fmt.Errorf("awsvm: empty MicroVM endpoint")- }- v, err := token(ctx)- if err != nil {- return fmt.Errorf("awsvm: auth token: %w", err)- }- host := hostOnly(endpoint)- req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+host+proxyTouchPath, nil)- if err != nil {- return err- }- req.Header.Set("X-aws-proxy-auth", v)- req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", port))-- resp, err := proxyTouchClient.Do(req)- if err != nil {- return fmt.Errorf("awsvm: idle touch %s: %w", host, err)- }- // Drain before closing or the connection cannot be reused, which would turn- // every touch into a fresh TLS handshake.- _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))- _ = resp.Body.Close()- if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return fmt.Errorf("awsvm: idle touch %s: http %d", host, resp.StatusCode)- }- return nil-}--// warmShellTimeout bounds the manufacture-time warm-up. Generous, because it-// runs on a box nobody is waiting for and the whole point is to absorb a slow-// first shell rather than skip it.-const warmShellTimeout = 20 * time.Second--// warmShell runs one throwaway command so the customer's first exec doesn't-// have to be the one that pays for a cold box.-//-// Every exec arrives as `/bin/sh -lc <cmd>`, and on a box that has never run one-// the login shell has to fault in the shell itself and source the whole profile-// chain. Measured on dev across 6 fresh boxes: the FIRST exec costs 928ms median-// even when the command is `true`, while the second is 143ms — and `node -v`-// against a warm shell is 144ms, indistinguishable. So the ~800ms is entirely-// first-shell startup, not the command, and it is paid exactly once per box.-//-// Paying it here means it lands on a pool box during manufacture instead of on-// a customer's first command. `node --version` is folded in because it is the-// default template's runtime and costs another ~100ms cold; the `|| true` keeps-// this correct on an image without node, where warming the shell is still the-// point.-func (a *agentConn) warmShell(ctx context.Context) error {- if a == nil || a.client == nil {- return nil- }- _, err := a.client.Exec(ctx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-lc", "node --version >/dev/null 2>&1 || true"},- TimeoutSeconds: int32(warmShellTimeout / time.Second),- })- return err-}--// pingEach pings every channel and returns the outcome per index (nil = ok),-// bounded so a large pool cannot open hundreds of concurrent RPCs on a-// maintenance tick.-//-// Per-index rather than a bare tally because the caller has to be able to act on-// a specific box: a channel that keeps failing has to be retired and re-dialled,-// and that is impossible if all the tick knows is how many failed. Returning the-// error rather than a bool matters for the same reason — "75 failed" with the-// cause discarded is a number nobody can act on, which is exactly how a pool-// decaying to a third of its tunnels stayed invisible in the log.-func pingEach(ctx context.Context, conns []*agentConn) []error {- errs := make([]error, len(conns))- if len(conns) == 0 {- return errs- }- sem := make(chan struct{}, pingConcurrency)- var wg sync.WaitGroup- for i, c := range conns {- wg.Add(1)- // Each goroutine owns its own slot, so no lock is needed.- go func(i int, c *agentConn) {- defer wg.Done()- sem <- struct{}{}- defer func() { <-sem }()- pctx, cancel := context.WithTimeout(ctx, pingTimeout)- defer cancel()- errs[i] = c.ping(pctx)- }(i, c)- }- wg.Wait()- return errs-}--// pingAll is the tally-only form, for callers with nothing to heal.-func pingAll(ctx context.Context, conns []*agentConn) (ok, failed int) {- for _, err := range pingEach(ctx, conns) {- if err != nil {- failed++- } else {- ok++- }- }- return ok, failed-}--// pingTracked pings the channels held for the given sandbox ids (edge-// reservations, which are the boxes customers actually claim) and RETIRES any-// that keep failing.-//-// Same defect, same fix, as Pool.warmTunnels — see maxAgentPingFailures. A-// channel that has gone bad was never replaced here either: warm() could only-// call Connect(), which does nothing to a conn already in TransientFailure, and-// get() explicitly leaves every non-Shutdown state alone on the theory that it-// "does recover on its own". Measured on dev, it does not: a 130-box pool decayed-// to 5 live tunnels and stayed there.-//-// This path matters more than stock's, not less. These boxes are one claim away-// from a customer, so a dead channel here IS the cold dial on someone's first-// exec. Dropping the entry closes the channel and forgets it, which is exactly-// what get() needs to re-dial with a freshly minted token.-func (p *agentPool) pingTracked(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed, retired int, sample error) {- p.mu.Lock()- ids := make([]string, 0, len(sandboxIDs))- conns := make([]*agentConn, 0, len(sandboxIDs))- for id := range sandboxIDs {- if c, found := p.conns[id]; found && c.conn != nil {- ids = append(ids, id)- conns = append(conns, c)- }- }- p.mu.Unlock()-- errs := pingEach(ctx, conns)-- type doomedConn struct {- id string- conn *agentConn- }- var doomed []doomedConn- p.mu.Lock()- for i, err := range errs {- id := ids[i]- if err == nil {- delete(p.failures, id)- ok++- continue- }- failed++- if sample == nil {- sample = err- }- p.failures[id]++- if p.failures[id] >= maxAgentPingFailures {- doomed = append(doomed, doomedConn{id: id, conn: conns[i]})- delete(p.failures, id)- }- }- // A sandbox that stops being reserved while mid-failure would otherwise leave- // its count behind forever. Bounded cleanup, since the caller passes the full- // current set every tick.- for id := range p.failures {- if _, still := sandboxIDs[id]; !still {- delete(p.failures, id)- }- }- p.mu.Unlock()-- // Retire only the exact channel that failed. A plain drop() would close- // whatever the map holds NOW, and if the box was claimed between the ping and- // here, put() has already installed a fresh channel for its new owner —- // closing that would hand the customer a broken tunnel instead of healing one.- for _, d := range doomed {- if p.dropIf(d.id, d.conn) {- retired++- }- }- return ok, failed, retired, sample-}--// dropIf closes and forgets a sandbox's channel only if it is still the one the-// caller expects. Reports whether it did.-func (p *agentPool) dropIf(sandboxID string, want *agentConn) bool {- p.mu.Lock()- c, found := p.conns[sandboxID]- if !found || c != want {- p.mu.Unlock()- return false- }- delete(p.conns, sandboxID)- p.mu.Unlock()- _ = c.Close()- return true-}diff --git a/internal/awsvm/keepalive_test.go b/internal/awsvm/keepalive_test.godeleted file mode 100644index 792ed937..00000000--- a/internal/awsvm/keepalive_test.go+++ /dev/null@@ -1,206 +0,0 @@-package awsvm--import (- "errors"- "testing"- "time"-)--// The bug these cover: a stocked box's agent channel that went bad was never-// replaced. warmTunnels healed a MISSING channel by re-dialling, but a channel-// that was present-and-dead only ever got ClientConn.Connect() — a no-op on a-// conn already in TransientFailure — so the pool decayed monotonically and every-// exec that landed on one of those boxes paid a full cold dial. Measured on dev-// at a 130-box pool: 75 live tunnels, then 55, then 30.--func TestFailedPingRetiresChannelForRedial(t *testing.T) {- p, _ := testPool(t, PoolConfig{TargetStock: 2})-- entry := &StockEntry{MicrovmID: "mvm-dead"}- entry.agent = &agentConn{}- live := []*StockEntry{entry}- boom := errors.New("agent tunnel handshake: 401")-- // One failure is forgiven: a box that is merely mid-resume must not have a- // working tunnel churned out from under it.- ok, failed, retired, dead, sample := p.applyPingResults(live, []error{boom})- if ok != 0 || failed != 1 || retired != 0 {- t.Fatalf("first failure: ok=%d failed=%d retired=%d, want 0/1/0", ok, failed, retired)- }- if len(dead) != 0 {- t.Fatalf("first failure closed %d channel(s), want 0", len(dead))- }- if entry.agent == nil {- t.Fatal("first failure cleared the channel; one blip must be tolerated")- }- if sample == nil {- t.Fatal("sampled error not returned — an unexplained failure count is what hid this bug")- }-- // The second consecutive failure retires it, so the bounded re-dial path- // rebuilds it next tick with a freshly minted token.- _, _, retired, dead, _ = p.applyPingResults(live, []error{boom})- if retired != 1 {- t.Fatalf("retired = %d after %d consecutive failures, want 1", retired, maxAgentPingFailures)- }- if len(dead) != 1 {- t.Fatalf("returned %d channel(s) to close, want 1 — not closing it leaks the socket", len(dead))- }- if entry.agent != nil {- t.Fatal("agent still set after retirement; warmTunnels only re-dials entries with agent == nil")- }-}--func TestSuccessfulPingResetsTheFailureRun(t *testing.T) {- p, _ := testPool(t, PoolConfig{TargetStock: 2})-- entry := &StockEntry{MicrovmID: "mvm-flaky"}- entry.agent = &agentConn{}- live := []*StockEntry{entry}-- // Fail, recover, fail: the run is broken by the success, so this must not- // count as two consecutive failures and retire a working channel.- p.applyPingResults(live, []error{errors.New("timeout")})- p.applyPingResults(live, []error{nil})- if entry.agentFailures != 0 {- t.Fatalf("agentFailures = %d after a success, want 0", entry.agentFailures)- }- _, _, retired, _, _ := p.applyPingResults(live, []error{errors.New("timeout")})- if retired != 0 {- t.Fatalf("retired a channel whose failures were not consecutive")- }- if entry.agent == nil {- t.Fatal("cleared the channel of a box that answered in between")- }-}--// A box claimed between the ping and the fold-back has had its channel handed to-// the manager, which clears this field. Closing the conn we pinged would tear-// down a live customer's tunnel.-func TestRetirementNeverClosesAChannelTheEntryNoLongerHolds(t *testing.T) {- p, _ := testPool(t, PoolConfig{TargetStock: 2})-- entry := &StockEntry{MicrovmID: "mvm-claimed"}- entry.agent = &agentConn{}- live := []*StockEntry{entry}- boom := errors.New("unavailable")-- p.applyPingResults(live, []error{boom})- // TrackClaimed transfers ownership and clears the field.- entry.agent = nil-- _, _, retired, dead, _ := p.applyPingResults(live, []error{boom})- if retired != 0 || len(dead) != 0 {- t.Fatalf("retired=%d closed=%d for an entry that no longer owns its channel, want 0/0", retired, len(dead))- }-}--// The same defect lived on the edge-reservation path, where it matters more:-// these boxes are one claim away from a customer, so a dead channel here IS the-// cold dial on someone's first exec. warm() could only call Connect() (a no-op-// in TransientFailure) and get() deliberately left every non-Shutdown state-// alone, so nothing ever replaced a channel that had gone bad.-func TestDropIfOnlyRetiresTheChannelThatFailed(t *testing.T) {- p := newAgentPool()- failed := &agentConn{}- p.conns["sb-1"] = failed-- if !p.dropIf("sb-1", failed) {- t.Fatal("dropIf refused to retire the channel it was given")- }- if _, still := p.conns["sb-1"]; still {- t.Fatal("channel still cached after retirement; get() re-dials only on a miss")- }-- // The hazard: the box is claimed between the ping and the retirement, and- // put() installs a fresh channel for its new owner. Retiring by id alone- // would close that one and hand the customer a broken tunnel.- fresh := &agentConn{}- p.conns["sb-2"] = fresh- stale := &agentConn{}- if p.dropIf("sb-2", stale) {- t.Fatal("dropIf closed a channel that had already been replaced")- }- if p.conns["sb-2"] != fresh {- t.Fatal("the new owner's channel was evicted")- }-}--func TestPingTrackedForgetsFailureCountsForUnreservedBoxes(t *testing.T) {- p := newAgentPool()- // Left over from a box that stopped being reserved while mid-failure. Without- // pruning, this map grows for the process's lifetime.- p.failures["sb-gone"] = 1-- p.pingTracked(t.Context(), map[string]struct{}{"sb-here": {}})- if _, leaked := p.failures["sb-gone"]; leaked {- t.Fatal("failure count retained for a box that is no longer reserved")- }-}--// The idle-timer touch is the ONLY thing in this package AWS's idle accounting-// can see — an h2 PING inside an established tunnel is not inbound proxy-// traffic. So the one property that matters is that the touch cadence stays-// comfortably inside whatever idle window the box was launched with, for every-// window someone might configure. Getting this wrong does not fail loudly: the-// box is suspended, answers 502, and is terminated half an hour later.-func TestIdleTouchIntervalStaysInsideTheIdleWindow(t *testing.T) {- for _, tc := range []struct {- name string- windowSec int32- want time.Duration- mustCover bool // the interval must leave room for two missed touches- }{- // The 8h ceiling, which is the default. A literal third would be 2h40m —- // long enough that a window lowered elsewhere would go unnoticed for- // hours, so the ceiling clamp holds it at 15 minutes.- {name: "8h ceiling", windowSec: 28_800, want: 15 * time.Minute, mustCover: true},- // The old default, and the one that was actually suspending stock.- {name: "old 15m default", windowSec: 900, want: 5 * time.Minute, mustCover: true},- // The service minimum. A third is 20s, floored to a minute — which no- // longer covers two missed touches, and cannot: we refuse to send a- // network request per box more often than that.- {name: "service minimum", windowSec: 60, want: time.Minute, mustCover: false},- // Unset — the pool must still touch on some sane cadence rather than- // treating "no window" as "never suspends".- {name: "unconfigured", windowSec: 0, want: 5 * time.Minute, mustCover: true},- } {- t.Run(tc.name, func(t *testing.T) {- c := NewClientWithAPI(&poolAPI{}, Config{- ImageIdentifier: "arn:image",- MaxIdleDurationSeconds: tc.windowSec,- })- // Config.applyDefaults raises a zero window to the ceiling, so drive- // the unconfigured case through the field the method actually reads.- if tc.windowSec == 0 {- c.cfg.MaxIdleDurationSeconds = 0- }- got := NewPool(c, PoolConfig{TargetStock: 1}).idleTouchInterval()- if got != tc.want {- t.Fatalf("idleTouchInterval() = %s, want %s", got, tc.want)- }- if got < time.Minute {- t.Fatalf("interval %s would touch every box more than once a minute", got)- }- window := time.Duration(tc.windowSec) * time.Second- if tc.mustCover && tc.windowSec > 0 && got*3 > window {- t.Fatalf("interval %s leaves no room for two missed touches inside a %s window", got, window)- }- })- }-}--func TestPingEachReportsPerIndexSoFailuresCanBeAttributed(t *testing.T) {- // A nil client pings OK (see agentConn.ping), which is enough to prove the- // result slice stays aligned with the input — the property retirement relies- // on to map a failure back to the entry that owns the channel.- conns := []*agentConn{{}, {}, {}}- errs := pingEach(t.Context(), conns)- if len(errs) != len(conns) {- t.Fatalf("pingEach returned %d results for %d conns", len(errs), len(conns))- }- ok, failed := pingAll(t.Context(), conns)- if ok != 3 || failed != 0 {- t.Fatalf("pingAll = %d ok / %d failed, want 3/0", ok, failed)- }-}diff --git a/internal/awsvm/manager.go b/internal/awsvm/manager.godeleted file mode 100644index 938379a7..00000000--- a/internal/awsvm/manager.go+++ /dev/null@@ -1,1064 +0,0 @@-package awsvm--import (- "bytes"- "context"- "errors"- "fmt"- "io"- "log"- "os"- "sync"- "time"-- "github.com/opensandbox/opensandbox/internal/sandbox"- "github.com/opensandbox/opensandbox/internal/storage"- "github.com/opensandbox/opensandbox/pkg/types"- pb "github.com/opensandbox/opensandbox/proto/agent"-)--// manager.go — sandbox.Manager over Lambda MicroVMs.-//-// The QEMU manager owns processes, disks, networking and snapshots. This one-// owns almost nothing: AWS holds the VM, and the two things we keep locally are-// a sandboxID→MicroVM mapping and a pool of agent channels. That asymmetry is-// the point — it is why the backend is a few hundred lines instead of the-// tens of thousands internal/qemu needs.-//-// Deliberately unsupported here (see ErrUnsupported): checkpoints, fork-from--// checkpoint, and resource limits. The first two are snapshot-and-disk-// operations with no counterpart in this service — a MicroVM image is built-// through an API, not captured from a running box. The third has no knob to-// turn: sizing belongs to the image, not the sandbox (see deliveredSize). They-// return a typed error the control plane can turn into a clean 501 rather than-// a panic or, worse, a silent success.-//-// Reboot and power-cycle ARE supported (PowerCycleSandbox delegates to-// RebootSandbox); template/checkpoint caches are inert rather than erroring,-// since "" is a truthful answer to "is it cached locally".--// ErrUnsupported marks a Manager capability this backend does not implement.-// Callers should surface it as "not available on this runtime", never retry it.-//-// The API boundary substitutes its own text, so this string is not-// customer-visible today — but error text is exactly what escapes into a-// response, a webhook, or a support ticket later, so it stays generic.-var ErrUnsupported = errors.New("awsvm: operation not supported by this sandbox runtime")--func unsupported(op string) error { return fmt.Errorf("%s: %w", op, ErrUnsupported) }--// entry is one sandbox's local bookkeeping.-type entry struct {- sandboxID string- microvmID string- endpoint string- template string- cpuCount int- memoryMB int- startedAt time.Time-}--// Manager implements sandbox.Manager against AWS Lambda MicroVMs.-type Manager struct {- client *Client- agents *agentPool- dataDir string-- // term paces destroys against the TerminateMicrovm quota. See terminator.go- // for why a direct call on this path leaked a box on every throttle.- term *terminator-- mu sync.RWMutex- byID map[string]*entry-}--// Compile-time proof this backend satisfies the same contract as internal/qemu.-// internal/firecracker carried this same assertion and still rotted, because-// nothing built it — keep this package in the build/test matrix.-var _ sandbox.Manager = (*Manager)(nil)--// NewManager builds the backend. dataDir is only used for the Manager's own-// scratch space; unlike QEMU there are no disks to keep there.-func NewManager(client *Client, dataDir string) *Manager {- return &Manager{- client: client,- agents: newAgentPool(),- dataDir: dataDir,- term: newTerminator(client),- byID: make(map[string]*entry),- }-}--// track records a sandboxID→MicroVM binding. Exported so the pool filler can-// hand pre-launched boxes to the manager at claim time without a second-// RunMicrovm — the fast path where the edge answers a create from stock.-// TrackClaimed binds a pooled box to a sandbox id and adopts the tunnel the-// pool already established, so the customer's first exec is warm (~85ms) rather-// than paying the ~1.4s dial. This is the claim path: still zero AWS calls.-func (m *Manager) TrackClaimed(sandboxID string, e *StockEntry, cfg types.SandboxConfig) {- m.Track(sandboxID, &Box{ID: e.MicrovmID, Endpoint: e.Endpoint}, cfg)- // Whether the warm tunnel actually reached the customer. This is the single- // biggest term in benchmark TTI — TTI measures the FIRST exec, and a cold- // dial costs ~330ms against an 82ms warm call — so it is worth one line.- log.Printf("awsvm: TrackClaimed %s (box %s) warm_tunnel=%v", sandboxID, e.MicrovmID, e.agent != nil)- if e.agent != nil {- m.agents.put(sandboxID, e.agent)- // TRANSFER OWNERSHIP. The pool and the manager would otherwise hold the- // same *agentConn, and Pool.terminate closes e.agent — so any pool-side- // path that retires this entry (expireReservations, aged-stock retire,- // overshoot shed) would close the tunnel of a box a customer is already- // using. The binding survives that, so the sandbox keeps routing and- // every exec fails instantly with "grpc: the client connection is- // closing" until the box is destroyed. Observed on dev: exec dead in- // ~5ms from localhost, no network involved.- //- // Clearing the pool's reference is the whole fix: the manager now owns- // the channel and closes it in agents.drop (destroy/Forget), and- // terminate's nil check makes the pool a no-op on an adopted entry.- e.agent = nil- }-}--// What a MicroVM actually gets, regardless of what the create asked for.-//-// 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.-//-// The default image's minimumMemoryInMiB, used when Config.DefaultMemoryMB is-// unset. MUST track the image or every box is metered at the wrong size.-//-// Raised 2048 → 4096 on 2026-08-24 (image version 12.0) so the backend actually-// delivers the platform default: the API defaults a create to 4096 and QEMU-// gives 4096, while this image gave 2048 — so every default create was silently-// served half what it asked for, and metered at the half.-//-// Lambda gives a full vCPU from 2048 up (peak scales to 4x), so 4096 keeps the-// 1-vCPU tier promise. Supported sizes are an ENUM, not a free integer:-// [512, 1024, 2048, 4096, 8192] on base image al2023-1.-const (- deliveredMicrovmMemoryMB = 4096- deliveredMicrovmCPUCount = 1-)--// vcpusForMemory reports the vCPU count that goes with a memory tier.-//-// We do NOT control this. There is no vCPU field anywhere in the API —-// CpuConfiguration carries an Architecture (x86_64/arm64) and nothing else — so-// the platform allocates CPU as a function of memory. The tier table is-// therefore the honest reading of what a customer on that tier is buying, and-// the same number QEMU delivers for it, which is what parity means here.-//-// Unknown tiers fall back to the baseline rather than guessing upward: over--// reporting cpuCount is an overcharge, and the meter reads this.-//-// NOT VALIDATED per tier. The proportional allocation is documented for the-// default only; the 1024 tier is the one to check first, because it is the only-// tier whose memory sits BELOW the baseline where a full vCPU is known good.-func vcpusForMemory(memoryMB int) int {- for _, t := range types.AllowedResourceTiers {- if t.MemoryMB == memoryMB {- return t.VCPUs- }- }- return deliveredMicrovmCPUCount-}--// deliveredSize reports what the platform actually provides for a request,-// given the memory the resolved image delivers.-//-// RunMicrovmInput has no memory or vCPU field — sizing is a property of the-// IMAGE. Offering more than one size means running more than one image and-// picking at launch (Config.SizeImages); within a single image there is no knob-// to turn at all.-//-// 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 images cannot satisfy.-func deliveredSize(sandboxID string, requestedMemoryMB, requestedCPUCount, deliveredMemoryMB int) (memoryMB, cpuCount int) {- if deliveredMemoryMB <= 0 {- deliveredMemoryMB = deliveredMicrovmMemoryMB- }- cpuCount = vcpusForMemory(deliveredMemoryMB)- if requestedMemoryMB > deliveredMemoryMB || requestedCPUCount > cpuCount {- log.Printf("awsvm: %s requested %dMB/%dcpu but this backend delivers %dMB/%dcpu — "+- "metering the delivered size (sizing is a property of the image)",- sandboxID, requestedMemoryMB, requestedCPUCount,- deliveredMemoryMB, cpuCount)- }- return deliveredMemoryMB, cpuCount-}--// Track records a sandbox→MicroVM binding and returns the size it recorded.-//-// The return values exist so callers can report the DELIVERED size rather than-// the requested one. Get reads them back off the entry; Create used to echo-// cfg.MemoryMB/cfg.CpuCount straight back instead, so a create asking for 8 GB-// answered "8192" and the very next Get on the same sandbox answered "2048".-// Same reasoning as deliveredSize itself: the requested number is not a fact-// about this sandbox, and repeating it anywhere is how it ends up believed.-func (m *Manager) Track(sandboxID string, box *Box, cfg types.SandboxConfig) (memoryMB, cpuCount int) {- // Which tier this box actually is. A request for a tier we do not offer is- // rejected in Create long before here; if one somehow reaches this point,- // resolving to the default is the safe direction (it is what the box- // physically is) and deliveredSize logs the mismatch.- _, deliveredMB, _ := m.config().ImageForMemory(cfg.MemoryMB)- memoryMB, cpuCount = deliveredSize(sandboxID, cfg.MemoryMB, cfg.CpuCount, deliveredMB)- m.mu.Lock()- m.byID[sandboxID] = &entry{- sandboxID: sandboxID,- microvmID: box.ID,- endpoint: box.Endpoint,- template: cfg.Template,- cpuCount: cpuCount,- memoryMB: memoryMB,- startedAt: time.Now(),- }- m.mu.Unlock()- return memoryMB, cpuCount-}--// config returns the client's resolved config, tolerating a nil client.-//-// Track runs on paths that construct a Manager without one (tests, and the-// bookkeeping-only callers that never talk to AWS), so reaching through-// m.client unguarded turns a pure in-memory bind into a panic. Defaults applied-// here match applyDefaults so an unconfigured Manager still resolves the-// default tier rather than reporting 0 MB.-func (m *Manager) config() Config {- if m == nil || m.client == nil {- return Config{DefaultMemoryMB: deliveredMicrovmMemoryMB}- }- return m.client.Config()-}--// MicrovmIDFor returns the AWS MicroVM id bound to a sandbox, from memory only.-//-// Separate from Get because Get calls AWS to report live status. Callers on a-// hot path that only need the binding — the event publisher stamps one on every-// envelope it flushes — must not turn that into a GetMicrovm per event.-func (m *Manager) MicrovmIDFor(sandboxID string) (string, bool) {- e, err := m.lookup(sandboxID)- if err != nil {- return "", false- }- return e.microvmID, true-}--func (m *Manager) lookup(sandboxID string) (*entry, error) {- m.mu.RLock()- e, ok := m.byID[sandboxID]- m.mu.RUnlock()- if !ok {- return nil, fmt.Errorf("awsvm: sandbox %s not found", sandboxID)- }- return e, nil-}--// agentFor returns the sandbox's agent channel, dialing on first use. The token-// provider closes over the MicroVM id so refreshes are transparent to callers.-func (m *Manager) agentFor(e *entry) (*agentConn, error) {- return m.agents.get(e.sandboxID, e.endpoint, m.client.Config().AgentPort,- func(ctx context.Context) (string, error) {- return m.client.AuthToken(ctx, e.microvmID)- })-}--// ── Lifecycle ───────────────────────────────────────────────────────────────--// Create launches a MicroVM for a sandbox. The sandbox id is used as the AWS-// client token so a retried create rejoins the same VM instead of leaking one —-// leaked VMs hold regional memory quota, which is the real cap on pool depth.-func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {- sandboxID := cfg.SandboxID- if sandboxID == "" {- return nil, fmt.Errorf("awsvm: create requires a pre-assigned sandbox id")- }- // Pick the image that delivers the requested size. A tier with no image- // configured is refused rather than served from the default: handing a 16 GB- // request a 4 GB box, and billing it as 4 GB, is a silent wrong-size- // delivery — the failure mode ErrUnsupported exists to make impossible.- image, _, ok := m.config().ImageForMemory(cfg.MemoryMB)- if !ok {- return nil, fmt.Errorf("awsvm: %s: no image configured for %dMB: %w",- sandboxID, cfg.MemoryMB, ErrUnsupported)- }- box, err := m.client.RunImage(ctx, sandboxID, image)- if err != nil {- return nil, err- }- memoryMB, cpuCount := m.Track(sandboxID, box, cfg)- log.Printf("awsvm: created %s (microvm=%s endpoint=%s)", sandboxID, box.ID, box.Endpoint)-- // Delivered, not requested — see Track. Get answers from the same numbers.- return &types.Sandbox{- ID: sandboxID,- Template: cfg.Template,- Status: types.SandboxStatusRunning,- StartedAt: time.Now(),- CpuCount: cpuCount,- MemoryMB: memoryMB,- }, 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-}--// TrackedBindings returns every sandbox id this manager is routing, mapped to-// the MicroVM behind it.-//-// TrackedMicrovmIDs answers "which boxes are spoken for", which is what the-// orphan sweep needs. This answers the other direction — "which bindings do we-// hold" — which is what a reconciler needs to find bindings whose sandbox no-// longer exists. Those are invisible to any pass driven by the sessions table,-// because such a pass can only visit sandboxes that still have a row.-func (m *Manager) TrackedBindings() map[string]string {- if m == nil {- return nil- }- m.mu.RLock()- defer m.mu.RUnlock()- out := make(map[string]string, len(m.byID))- for id, e := range m.byID {- out[id] = e.microvmID- }- return out-}--func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {- e, err := m.lookup(id)- if err != nil {- return nil, err- }- box, err := m.client.Get(ctx, e.microvmID)- if err != nil {- return nil, err- }- return &types.Sandbox{- ID: id,- Template: e.template,- Status: statusFor(box),- StartedAt: e.startedAt,- CpuCount: e.cpuCount,- MemoryMB: e.memoryMB,- }, nil-}--// statusFor maps MicroVM lifecycle onto our sandbox status.-//-// SUSPENDED reads as RUNNING, not hibernated: the box is alive and auto-resume-// brings it back on the next request, so callers must keep treating it as-// serving. Reporting it as hibernated would make the reconciler's liveness-// check close a row whose box is fine.-//-// Only TERMINATING/TERMINATED read as stopped. That distinction is what the-// reconciler keys on to decide whether a row still has a host behind it.-func statusFor(b *Box) types.SandboxStatus {- switch {- case b == nil:- return types.SandboxStatusStopped- case !b.Alive():- return types.SandboxStatusStopped- default:- return types.SandboxStatusRunning- }-}--func (m *Manager) Kill(ctx context.Context, id string) error {- e, err := m.lookup(id)- if err != nil {- return nil // already gone; destroy is idempotent- }- m.agents.drop(id)- // Forget the binding first, then hand the box to the paced queue. Order- // matters: the sandbox is gone from the caller's perspective the moment this- // returns, and leaving it routable while the terminate drains would let an- // exec land on a box already condemned.- m.mu.Lock()- delete(m.byID, id)- m.mu.Unlock()-- // A throttled terminate used to surface as a 500 AND leave the box running —- // a leak on the customer-facing delete path, which is where a share of the- // orphan population came from. Queued, it retries at the quota instead.- if m.term.enqueue(e.microvmID) {- return nil- }- // Queue full: better to pay the call inline than lose the box.- return m.client.Terminate(ctx, e.microvmID)-}--func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {- m.mu.RLock()- entries := make([]*entry, 0, len(m.byID))- for _, e := range m.byID {- entries = append(entries, e)- }- m.mu.RUnlock()-- out := make([]types.Sandbox, 0, len(entries))- for _, e := range entries {- out = append(out, types.Sandbox{- ID: e.sandboxID,- Template: e.template,- Status: types.SandboxStatusRunning,- StartedAt: e.startedAt,- CpuCount: e.cpuCount,- MemoryMB: e.memoryMB,- })- }- return out, nil-}--func (m *Manager) Count(ctx context.Context) (int, error) {- m.mu.RLock()- defer m.mu.RUnlock()- return len(m.byID), nil-}--// IsSandboxAlive gates billing, so it asks AWS rather than trusting local state:-// a stale in-memory entry driving usage events on a terminated VM is the exact-// "ghost VM" bug this call exists to prevent.-func (m *Manager) IsSandboxAlive(ctx context.Context, id string) (bool, error) {- e, err := m.lookup(id)- if err != nil {- return false, nil- }- box, err := m.client.Get(ctx, e.microvmID)- if err != nil {- return false, nil- }- return box.Alive(), nil-}--func (m *Manager) Close() { m.agents.closeAll() }--// DetachAgent surrenders a sandbox's agent channel without closing it. Only the-// edge-release path should use this: it is handing a still-good tunnel back to-// the pool rather than throwing it away. Every other unbind wants Forget.-func (m *Manager) DetachAgent(sandboxID string) *agentConn {- if m == nil {- return nil- }- return m.agents.detach(sandboxID)-}--// WarmAgents re-establishes idle agent channels for the given sandboxes. See-// agentPool.warm — intended for edge reservations awaiting a customer.-func (m *Manager) WarmAgents(sandboxIDs map[string]struct{}) int {- if m == nil || len(sandboxIDs) == 0 {- return 0- }- return m.agents.warm(sandboxIDs)-}--// ── Execution ───────────────────────────────────────────────────────────────--func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {- e, err := m.lookup(sandboxID)- if err != nil {- return nil, err- }- a, err := m.agentFor(e)- if err != nil {- return nil, err- }-- timeout := int32(cfg.Timeout)- if timeout <= 0 {- timeout = 60- }- command, args := cfg.Command, cfg.Args- if len(args) == 0 {- args = []string{"-c", command}- command = "/bin/sh"- }-- resp, err := a.client.Exec(ctx, &pb.ExecRequest{- Command: command,- Args: args,- Envs: cfg.Env,- Cwd: cfg.Cwd,- TimeoutSeconds: timeout,- })- if err != nil {- return nil, fmt.Errorf("awsvm: exec in %s: %w", sandboxID, err)- }- return &types.ProcessResult{- ExitCode: int(resp.ExitCode),- Stdout: resp.Stdout,- Stderr: resp.Stderr,- }, nil-}--// ── Filesystem ──────────────────────────────────────────────────────────────--func (m *Manager) ReadFile(ctx context.Context, sandboxID, path string) (string, error) {- a, err := m.agent(sandboxID)- if err != nil {- return "", err- }- resp, err := a.client.ReadFile(ctx, &pb.ReadFileRequest{Path: path})- if err != nil {- return "", err- }- return string(resp.Content), nil-}--func (m *Manager) WriteFile(ctx context.Context, sandboxID, path, content string) error {- a, err := m.agent(sandboxID)- if err != nil {- return err- }- _, err = a.client.WriteFile(ctx, &pb.WriteFileRequest{Path: path, Content: []byte(content)})- return err-}--func (m *Manager) ListDir(ctx context.Context, sandboxID, path string) ([]types.EntryInfo, error) {- a, err := m.agent(sandboxID)- if err != nil {- return nil, err- }- resp, err := a.client.ListDir(ctx, &pb.ListDirRequest{Path: path})- if err != nil {- return nil, err- }- out := make([]types.EntryInfo, 0, len(resp.Entries))- for _, e := range resp.Entries {- out = append(out, types.EntryInfo{Name: e.Name, IsDir: e.IsDir, Size: e.Size, Path: e.Path})- }- return out, nil-}--func (m *Manager) MakeDir(ctx context.Context, sandboxID, path string) error {- a, err := m.agent(sandboxID)- if err != nil {- return err- }- _, err = a.client.MakeDir(ctx, &pb.MakeDirRequest{Path: path})- return err-}--func (m *Manager) Remove(ctx context.Context, sandboxID, path string) error {- a, err := m.agent(sandboxID)- if err != nil {- return err- }- _, err = a.client.Remove(ctx, &pb.RemoveRequest{Path: path})- return err-}--func (m *Manager) Exists(ctx context.Context, sandboxID, path string) (bool, error) {- a, err := m.agent(sandboxID)- if err != nil {- return false, err- }- resp, err := a.client.Exists(ctx, &pb.ExistsRequest{Path: path})- if err != nil {- return false, err- }- return resp.Exists, nil-}--func (m *Manager) Stat(ctx context.Context, sandboxID, path string) (*types.FileInfo, error) {- a, err := m.agent(sandboxID)- if err != nil {- return nil, err- }- resp, err := a.client.Stat(ctx, &pb.StatRequest{Path: path})- if err != nil {- return nil, err- }- return &types.FileInfo{- Name: resp.Name, IsDir: resp.IsDir, Size: resp.Size,- Mode: resp.Mode, ModTime: resp.ModTime, Path: resp.Path,- }, nil-}--// agent is the lookup+dial shorthand the filesystem methods share.-func (m *Manager) agent(sandboxID string) (*agentConn, error) {- e, err := m.lookup(sandboxID)- if err != nil {- return nil, err- }- return m.agentFor(e)-}--// ── Monitoring ──────────────────────────────────────────────────────────────--func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {- a, err := m.agent(sandboxID)- if err != nil {- return nil, err- }- resp, err := a.client.Stats(ctx, &pb.StatsRequest{})- if err != nil {- return nil, err- }- return &sandbox.SandboxStats{- CPUPercent: resp.CpuPercent,- MemUsage: resp.MemUsage,- MemLimit: resp.MemLimit,- NetInput: resp.NetInput,- NetOutput: resp.NetOutput,- PIDs: int(resp.Pids),- }, nil-}--func (m *Manager) DataDir() string { return m.dataDir }--func (m *Manager) ContainerName(id string) string { return "microvm-" + id }--// HostPort has no meaning here: there is no host publishing a port. Customer-// traffic reaches the guest through the MicroVM's own HTTPS endpoint, so 0 is-// the honest answer rather than a fabricated port.-func (m *Manager) HostPort(ctx context.Context, sandboxID string) (int, error) { return 0, nil }--// ContainerAddr returns the endpoint a caller should use to reach a guest port.-// Unlike the QEMU backend this is a public HTTPS endpoint, and the caller must-// also present an auth token plus X-aws-proxy-port.-func (m *Manager) ContainerAddr(ctx context.Context, sandboxID string, port int) (string, error) {- e, err := m.lookup(sandboxID)- if err != nil {- return "", err- }- return AgentURL(e.endpoint), nil-}--// ── Hibernation ─────────────────────────────────────────────────────────────--// Hibernate captures the workspace to blob storage, then suspends the box.-//-// The order is the whole design. Exporting BEFORE suspending means the archive-// is produced by a running box, so no ResumeMicrovm is ever needed to make one-// — which matters because Resume is rate-limited at 5/s and boxes created-// together expire together. Once the blob exists the suspended box is a pure-// latency cache: it can be terminated at any moment without losing anything but-// wake speed, which is what lets the expiry sweep free regional memory quota-// aggressively.-//-// Suspending first and exporting later would invert all of that: every-// promotion would need a Resume, and there would be a window where the box is-// suspended and no durable copy exists yet — a wake during that window has-// nothing to restore from.-func (m *Manager) Hibernate(ctx context.Context, sandboxID string, store *storage.CheckpointStore) (*sandbox.HibernateResult, error) {- e, err := m.lookup(sandboxID)- if err != nil {- return nil, err- }- if store == nil {- return nil, fmt.Errorf("awsvm: hibernate %s: no checkpoint store configured", sandboxID)- }-- rc, _, err := m.ExportWorkspace(ctx, sandboxID)- if err != nil {- return nil, err- }- defer rc.Close()-- // Spool to disk: the store uploads from a path, not a stream.- local, size, err := stageArchive(rc, m.dataDir)- if err != nil {- return nil, fmt.Errorf("awsvm: hibernate %s: stage archive: %w", sandboxID, err)- }- defer os.Remove(local)-- key := hibernationKey(sandboxID)- uploaded, err := store.Upload(ctx, key, local)- if err != nil {- return nil, fmt.Errorf("awsvm: hibernate %s: upload: %w", sandboxID, err)- }- if uploaded > 0 {- size = uploaded- }-- // Only now is it safe to stop serving. A failure above leaves the box- // running and the sandbox usable, which is the right way to fail.- if err := m.client.Suspend(ctx, e.microvmID); err != nil {- return nil, fmt.Errorf("awsvm: hibernate %s: suspend: %w", sandboxID, err)- }- return &sandbox.HibernateResult{SandboxID: sandboxID, HibernationKey: key, SizeBytes: size}, nil-}--// Wake takes the fastest path that is still correct.-//-// box SUSPENDED Resume in place, ~1s, processes intact-// box gone launch a replacement and restore the archive into it-//-// Callers do not choose: which tier a sandbox is in depends on how long it sat-// and how quota pressure fell, neither of which the caller knows. Returning the-// best available answer means a wake degrades in latency rather than failing.-func (m *Manager) Wake(ctx context.Context, sandboxID, hibernationKey string, store *storage.CheckpointStore, _ int) (*types.Sandbox, error) {- // Still tracked and alive? Resume is strictly cheaper than a restore, and- // it keeps whatever the customer left running.- if e, err := m.lookup(sandboxID); err == nil {- if box, gErr := m.client.Get(ctx, e.microvmID); gErr == nil && box.Alive() {- if err := m.client.Resume(ctx, e.microvmID); err != nil {- return nil, fmt.Errorf("awsvm: wake %s: resume: %w", sandboxID, err)- }- // The cached gRPC channel did not survive the suspend: the proxy- // drops it, and reusing it fails the next call with an abnormal- // websocket close rather than anything that reads like "reconnect".- // Dropping it here makes the next use dial fresh.- m.agents.drop(sandboxID)- return &types.Sandbox{- ID: sandboxID, Template: e.template, Status: types.SandboxStatusRunning,- StartedAt: e.startedAt, CpuCount: e.cpuCount, MemoryMB: e.memoryMB,- }, nil- }- }-- // The box is gone, so the archive is the sandbox now.- if store == nil || hibernationKey == "" {- return nil, fmt.Errorf("awsvm: wake %s: host is gone and no archive was recorded", sandboxID)- }- return m.restoreFromArchive(ctx, sandboxID, hibernationKey, store)-}--// restoreFromArchive launches a replacement box and unpacks the workspace into-// it. Deliberately separate from Wake so the expensive path is legible.-func (m *Manager) restoreFromArchive(ctx context.Context, sandboxID, key string, store *storage.CheckpointStore) (*types.Sandbox, error) {- rc, err := store.Download(ctx, key)- if err != nil {- return nil, fmt.Errorf("awsvm: wake %s: download archive: %w", sandboxID, err)- }- defer rc.Close()-- box, err := m.client.Run(ctx, "")- if err != nil {- return nil, fmt.Errorf("awsvm: wake %s: launch replacement: %w", sandboxID, err)- }- ready, err := m.client.WaitRunning(ctx, box.ID, 60*time.Second)- if err != nil {- // Do not leak a box we cannot use: it bills and holds quota until the cap.- go func() { _ = m.client.Terminate(context.WithoutCancel(ctx), box.ID) }()- return nil, fmt.Errorf("awsvm: wake %s: replacement never became ready: %w", sandboxID, err)- }-- cfg := types.SandboxConfig{SandboxID: sandboxID}- if e, lErr := m.lookup(sandboxID); lErr == nil {- cfg.MemoryMB, cfg.CpuCount = e.memoryMB, e.cpuCount- }- // Drop before tracking: the pooled connection is keyed by sandbox id, and- // this sandbox now lives on a different host entirely.- m.agents.drop(sandboxID)- m.Track(sandboxID, ready, cfg)-- if err := m.ImportWorkspace(ctx, sandboxID, rc); err != nil {- go func() { _ = m.client.Terminate(context.WithoutCancel(ctx), ready.ID) }()- return nil, err- }- return &types.Sandbox{- ID: sandboxID, Status: types.SandboxStatusRunning, StartedAt: ready.StartedAt,- CpuCount: cfg.CpuCount, MemoryMB: cfg.MemoryMB,- }, nil-}--// ── Not supported on this backend ───────────────────────────────────────────--// SetResourceLimits is a no-op: a MicroVM's shape is fixed by its image and run-// configuration, and cannot be resized in place the way virtio-mem allows.-// Returning nil rather than an error keeps the control plane's post-claim grow-// step harmless instead of failing every create.-// SetResourceLimits cannot be honoured on this backend.-//-// Sizing is a property of the IMAGE (see deliveredSize): RunMicrovmInput has no-// memory or vCPU field, and the only knob in the whole API is-// Resources.MinimumMemoryInMiB at image build/update time — which is-// account-wide for every box on that image, not per sandbox.-//-// This used to `return nil`, which made a resize request answer 200 OK and-// change nothing. That is the failure mode ErrUnsupported exists to prevent: a-// caller cannot tell a silent success apart from a real one, so it believes a-// limit is in force that was never applied. 501 tells the truth — the operation-// will never succeed on this runtime, so do not retry it.-func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {- return unsupported("SetResourceLimits")-}--// 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) {- 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.-//-// This works for the same reason exec does: the agent channel is a real gRPC-// connection tunnelled inside a WebSocket, so server-streaming RPCs traverse it-// unchanged. (It was briefly stubbed as unsupported on the assumption that-// streaming through Lambda's proxy was unsafe — the tunnel is precisely what-// makes that assumption obsolete.)-func (m *Manager) ReadFileStream(ctx context.Context, sandboxID, path string) (io.ReadCloser, int64, error) {- a, err := m.agent(sandboxID)- if err != nil {- return nil, 0, err- }- stream, err := a.client.ReadFileStream(ctx, &pb.ReadFileStreamRequest{Path: path})- if err != nil {- return nil, 0, fmt.Errorf("awsvm: read file stream %s: %w", path, err)- }-- // Pull the first chunk eagerly: total_size only rides on it, and callers- // need the size before they start reading.- first, err := stream.Recv()- if err != nil {- if err == io.EOF {- return io.NopCloser(bytes.NewReader(nil)), 0, nil- }- return nil, 0, fmt.Errorf("awsvm: read file stream %s: %w", path, err)- }-- pr, pw := io.Pipe()- go func() {- defer pw.Close()- if _, err := pw.Write(first.Data); err != nil {- return- }- for {- chunk, err := stream.Recv()- if err == io.EOF {- return- }- if err != nil {- // Surface the failure to the reader rather than truncating- // silently, which would look like a short but successful file.- pw.CloseWithError(fmt.Errorf("awsvm: read file stream %s: %w", path, err))- return- }- if _, err := pw.Write(chunk.Data); err != nil {- return- }- }- }()- return pr, first.TotalSize, nil-}--// WriteFileStream streams a file into the guest. Client-streaming gRPC over the-// same tunnel; path and mode ride the first message only, per the proto.-func (m *Manager) WriteFileStream(ctx context.Context, sandboxID, path string, mode uint32, r io.Reader) (int64, error) {- a, err := m.agent(sandboxID)- if err != nil {- return 0, err- }- stream, err := a.client.WriteFileStream(ctx)- if err != nil {- return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)- }-- buf := make([]byte, 256*1024)- first := true- for {- n, readErr := r.Read(buf)- if n > 0 {- msg := &pb.WriteFileStreamRequest{Data: buf[:n]}- if first {- msg.Path, msg.Mode = path, mode- first = false- }- if err := stream.Send(msg); err != nil {- return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)- }- }- if readErr == io.EOF {- break- }- if readErr != nil {- return 0, fmt.Errorf("awsvm: write file stream %s: read source: %w", path, readErr)- }- }- // An empty file still needs one message, or the agent never learns the path.- if first {- if err := stream.Send(&pb.WriteFileStreamRequest{Path: path, Mode: mode}); err != nil {- return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)- }- }-- resp, err := stream.CloseAndRecv()- if err != nil {- return 0, fmt.Errorf("awsvm: write file stream %s: %w", path, err)- }- return 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 {- 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, m.RebootSandbox(ctx, sandboxID)-}--func (m *Manager) TemplateCachePath(templateID, filename string) string { return "" }--func (m *Manager) CheckpointCachePath(checkpointID, filename string) string { return "" }--func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, _ *storage.CheckpointStore, _ func()) (string, string, int64, error) {- return "", "", 0, unsupported("CreateCheckpoint")-}--func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {- return unsupported("RestoreFromCheckpoint")-}--func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {- return nil, unsupported("ForkFromCheckpoint")-}--// Forget drops a sandbox from the in-memory map without touching AWS.-//-// For a hibernation that has been retired to blob-only: the box is already-// terminated, and leaving the binding behind would make Route claim the sandbox-// is served in-process, sending the next request to a host that no longer-// exists instead of down the restore path.-func (m *Manager) Forget(sandboxID string) {- if m == nil {- return- }- m.mu.Lock()- delete(m.byID, sandboxID)- m.mu.Unlock()- m.agents.drop(sandboxID)-}--// DirectInfo returns everything a caller OUTSIDE this process needs to reach a-// sandbox's agent itself: the MicroVM's public endpoint, a proxy auth token,-// and the guest port that token is scoped to.-//-// This is the seam for taking the control plane out of the exec data path. The-// endpoint is a public TLS host and the token is a plain header credential — the-// same one dialAgent presents on the WebSocket upgrade — so a caller that-// speaks the tunnel protocol gets an identical channel without relaying through-// here. Tokens are cached and port-scoped by AuthToken, so this is cheap to call-// and cannot widen access beyond the agent port.-func (m *Manager) DirectInfo(ctx context.Context, sandboxID string) (endpoint, token string, port int32, err error) {- e, err := m.lookup(sandboxID)- if err != nil {- return "", "", 0, err- }- tok, err := m.client.AuthToken(ctx, e.microvmID)- if err != nil {- return "", "", 0, err- }- return e.endpoint, tok, m.client.Config().AgentPort, nil-}--// PingAgents keeps the given sandboxes' boxes out of AWS's idle policy. See the-// keepalive block in agent.go for why an open connection is not enough.-//-// Also retires channels that keep failing, so a reservation whose tunnel died-// does not hand its eventual customer a cold dial. retired counts those; sample-// is one representative failure, for the caller to log.-func (m *Manager) PingAgents(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed, retired int, sample error) {- return m.agents.pingTracked(ctx, sandboxIDs)-}diff --git a/internal/awsvm/manager_status_test.go b/internal/awsvm/manager_status_test.godeleted file mode 100644index 4207e0e7..00000000--- a/internal/awsvm/manager_status_test.go+++ /dev/null@@ -1,37 +0,0 @@-package awsvm--import (- "testing"-- "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"- ostypes "github.com/opensandbox/opensandbox/pkg/types"-)--// statusFor is what the reconciler keys on to decide whether a sandbox still-// has a host behind it. Getting SUSPENDED wrong in either direction is-// expensive: reporting it stopped closes rows whose box is fine, and reporting-// TERMINATED as running leaves dead rows holding concurrency quota forever —-// which is exactly what happened when the sweep read only the error and never-// the status.-func TestStatusForDistinguishesAliveFromTerminated(t *testing.T) {- for _, tc := range []struct {- state types.MicrovmState- want ostypes.SandboxStatus- }{- {types.MicrovmStateRunning, ostypes.SandboxStatusRunning},- {types.MicrovmStatePending, ostypes.SandboxStatusRunning},- // Alive and auto-resumable — must NOT read as stopped.- {types.MicrovmStateSuspended, ostypes.SandboxStatusRunning},- {types.MicrovmStateSuspending, ostypes.SandboxStatusRunning},- // Gone. The row must be closable.- {types.MicrovmStateTerminated, ostypes.SandboxStatusStopped},- {types.MicrovmStateTerminating, ostypes.SandboxStatusStopped},- } {- if got := statusFor(&Box{State: tc.state}); got != tc.want {- t.Errorf("state %s -> %s, want %s", tc.state, got, tc.want)- }- }- if got := statusFor(nil); got != ostypes.SandboxStatusStopped {- t.Errorf("nil box -> %s, want stopped", got)- }-}diff --git a/internal/awsvm/pool.go b/internal/awsvm/pool.godeleted file mode 100644index a5c967a7..00000000--- a/internal/awsvm/pool.go+++ /dev/null@@ -1,1292 +0,0 @@-package awsvm--import (- "context"- "errors"- "fmt"- "log"- "sync"- "time"-- "google.golang.org/grpc/connectivity"-)--// pool.go — a warm pool of RUNNING MicroVMs.-//-// The shape here is dictated entirely by the service's rate limits, not by-// preference. Lambda MicroVMs allows (account+region defaults):-//-// RunMicrovm 5/s ResumeMicrovm 5/s-// SuspendMicrovm 2/s TerminateMicrovm 10/s-// CreateMicrovmAuthToken 50/s-//-// A burst of 100 creates cannot call RunMicrovm — that is 20 seconds of-// launching. It cannot call ResumeMicrovm either, so the cheaper design of-// holding stock SUSPENDED (which bills snapshot storage instead of compute) is-// unavailable: waking 100 suspended boxes is throttled just as hard as-// launching them.-//-// What is left is the only shape that survives a burst: keep the stock RUNNING-// and make the claim path do ZERO AWS calls. The edge pops a pre-launched box-// with a pre-minted token and answers immediately; every rate-limited call-// happens on this background loop, minutes before the customer arrives.-//-// The costs of that choice, all of them real:-// - stocked boxes bill compute the whole time they wait, not storage-// - idle-suspend must be off, or stock silently drifts into SUSPENDED and the-// next claim pays a throttled Resume-// - every box dies at the 8h service cap (running+suspended combined,-// adjustable=false), so the pool needs continuous rolling replacement-// - auth tokens last at most 60 minutes, so stock has to be re-tokened in-// place or it goes stale while waiting-type PoolConfig struct {- // TargetStock is how many RUNNING boxes to keep ready.- TargetStock int-- // MaxBoxAge retires a box before the service's hard 8h ceiling. Leave- // headroom: a box that hits the cap is terminated by Lambda underneath us,- // and a claim that lands on it fails the customer's create.- MaxBoxAge time.Duration-- // LaunchInterval paces RunMicrovm calls. Must stay at or under the account's- // RunMicrovm rate quota — exceeding it earns ThrottlingException, and a- // throttled top-up means the pool silently runs dry under churn.- LaunchInterval time.Duration-- // TokenRefreshMargin re-mints a stocked box's token this long before it- // expires, so a claim never hands out a token about to die.- TokenRefreshMargin time.Duration-- // ReadyTimeout bounds how long a launching box may stay PENDING before we- // give up and terminate it. A box that never reaches RUNNING still burns- // regional memory quota, so waiting forever quietly shrinks pool capacity.- ReadyTimeout time.Duration-- // PreDialTimeout bounds establishing a stocked box's agent tunnel. Exceeding- // it costs only a cold first exec on that box, never the box itself.- PreDialTimeout time.Duration-- // MaxTotalBoxes caps pool stock PLUS everything claimed out of it, against- // the regional memory quota. 0 disables the cap.- //- // TargetStock alone is not a safety property. It bounds what the pool holds,- // not what exists: a claimed box leaves the stock, the filler sees a hole and- // launches a replacement, so pool + live sandboxes grows without limit as- // load rises. That is exactly how a 200-box pool alongside 300 live sandboxes- // put this account over its 1024GB ceiling and turned every create into- // ServiceQuotaExceeded — the filler was chasing its target while blind to the- // boxes doing the actual work.- //- // With a budget set, the pool becomes something a burst can DRAIN rather than- // a floor it fights: claims consume stock, refill waits until those boxes are- // released, and the total never exceeds what the region will allow.- MaxTotalBoxes int-- // InUse reports boxes alive outside the pool — claimed sandboxes still doing- // work. Supplied by the owner because the pool deliberately forgets a box the- // moment it is claimed; the manager is what tracks it afterwards.- //- // Nil means "nothing else exists", which is only true in tests.- InUse func() int-- // InUseDetail explains the InUse number for the budget log — the terms it is- // computed from, so a refill freeze names its own cause instead of needing a- // live investigation to decompose. Optional; must be cheap and must not- // block, since it runs inside the pool's own tick.- InUseDetail func() string-- // RefillDelay is how long the filler stands down after finding itself at- // MaxTotalBoxes.- //- // Standing down matters because the budget check alone only skips a tick.- // At the ceiling that re-probes every LaunchInterval, so the instant any box- // is released the pool launches a replacement and is immediately at the- // ceiling again — it tracks the budget exactly, and every one of those- // launches is a RunMicrovm call competing with the customer creates that are- // cold precisely because the pool is empty. Measured on dev: 366 boxes- // manufactured in 30 minutes against 28 "regional MicroVM quota exhausted"- // creates, the pool and its own customers bidding for the same quota.- //- // A cooldown makes the pool yield instead. It re-probes once per delay, so- // releases accumulate into real headroom before the filler spends quota on- // them, and a burst's cold creates get the regional quota to themselves.- // Time-bounded rather than event-driven on purpose: a delay armed by every- // claim would be pushed forward indefinitely by sustained traffic and the- // pool would never refill at all.- RefillDelay time.Duration-- // OnExpire is called after a stale edge reservation has been terminated.- //- // Reserving for the edge binds a sandbox id to the box BEFORE any customer- // claims it, so that routing and the warm tunnel resolve the instant the- // edge answers a create. When the reservation dies instead of being claimed,- // that binding has to die with it — otherwise the control plane keeps- // routing a live sandbox id to a terminated box, and every operation on it- // fails somewhere deep in the agent tunnel rather than with "not found".- //- // Called without the pool lock held, so implementations may take their own.- OnExpire func(microvmID string)-- // OnMaintain runs on each maintenance tick, after the pool has warmed its- // own stock.- //- // It exists because the pool cannot warm the boxes that matter most. An- // edge reservation moves its agent channel to the manager (TrackClaimed) and- // leaves p.stock, so a box staged in a PoolStock shard — the exact box the- // next create will be handed — is invisible to warmTunnels. Those sit for- // minutes with no traffic, their tunnels lapse, and the cost lands on the- // customer's first exec, which is what TTI measures. Only the owner knows- // which sandbox ids are reserved-but-unclaimed, so it does that warming.- //- // Called without the pool lock held.- OnMaintain func()-}--func (c *PoolConfig) applyDefaults() {- // Zero is a real setting, not "unset": it means run cold-create-only, with- // no warm stock. Every caller resolves its own default before constructing- // a PoolConfig (the control plane via envInt, the harness via a flag), so a- // 0 arriving here is deliberate. Defaulting it up — as this did — silently- // launched 20 boxes for an operator who asked for none, which is the same- // zero-value trap that made OPENSANDBOX_MAX_WORKERS=0 keep provisioning.- if c.TargetStock < 0 {- c.TargetStock = 0- }- if c.MaxBoxAge <= 0 {- // 8h service cap minus an hour of slack for retirement to keep up.- c.MaxBoxAge = 7 * time.Hour- }- if c.LaunchInterval <= 0 {- // 5/s is the default RunMicrovm quota; 250ms paces at 4/s to leave room- // for retirement launches and any other caller in the account.- c.LaunchInterval = 250 * time.Millisecond- }- if c.TokenRefreshMargin <= 0 {- c.TokenRefreshMargin = 10 * time.Minute- }- if c.ReadyTimeout <= 0 {- c.ReadyTimeout = 45 * time.Second- }- if c.PreDialTimeout <= 0 {- c.PreDialTimeout = 30 * time.Second- }- if c.RefillDelay <= 0 {- c.RefillDelay = time.Minute- }-}--// StockEntry is one ready-to-claim box. Everything a caller needs to talk to it-// is here, which is the whole point: claiming touches no AWS API.-type StockEntry struct {- MicrovmID string- Endpoint string- Token string-- // agent is a gRPC channel already dialled and connected through the- // WebSocket tunnel. Establishing it costs ~1.4s (token mint, WS handshake,- // HTTP/2 setup) against ~85ms for an exec on an established channel, so- // leaving it to the first exec would put that 1.4s squarely on the- // customer's create→first-command path. Doing it here spends it while the- // box is idle in stock, for the same reason tokens are pre-minted.- agent *agentConn-- // agentFailures counts CONSECUTIVE failed keepalive pings on the channel- // above. Reset by any success. Once it reaches maxAgentPingFailures the- // channel is retired and re-dialled — see warmTunnels.- agentFailures int-- // redialFailures counts CONSECUTIVE failed attempts to give this box a- // tunnel back. Reset by any success.- //- // Retiring a channel used to be the end of the line: the box went- // tunnel-less, the re-dial failed silently, and it sat in stock — countable- // by Depth(), claimable by the edge, dead to every customer that got it —- // until MaxBoxAge (7h) evicted it on age alone. Measured on dev: 34 in stock- // against ONE live microVM in the whole account, and creates kept succeeding- // onto the corpses. A box whose tunnel cannot be rebuilt with a freshly- // minted token is not cold, it is gone, and stock must say so.- redialFailures int-- // lastProxyTouch is when this box last received a real inbound request- // through its AWS proxy endpoint — the only kind of traffic AWS's idle- // accounting can see. Zero means "never since we started tracking", which- // makes the box due immediately. See Pool.touchIdleTimers.- lastProxyTouch time.Time-- tokenMintedAt time.Time- launchedAt time.Time-}--// reservation is a stocked box promised to the edge, with the moment it was-// promised so the reaper can tell a claim that is in flight from one that is-// never coming.-type reservation struct {- entry *StockEntry- at time.Time-}--// reservationTTL bounds how long the edge may hold a box without binding it.-// Short enough that a dead DO does not quietly shrink the pool, but it MUST-// comfortably exceed the PoolStock DO's own ENTRY_TTL_MS (10 minutes), because-// a reservation the DO still counts as stock is one it will happily hand to a-// customer. Expiring first would mean the edge answering a create with a box-// this pool had already terminated — a 201 for a sandbox that does not exist.-// 15 minutes matches the QEMU edge_reserved reaper for the same reason.-const reservationTTL = 15 * time.Minute--// Pool keeps TargetStock boxes launched, tokened and fresh.-type Pool struct {- client *Client- cfg PoolConfig-- // preDial establishes a box's agent tunnel while it waits in stock. It is a- // field rather than a direct call so tests can disable it: dialling is real- // network I/O against a real MicroVM endpoint, which a fake AWS API cannot- // satisfy — without this seam the unit tests block on a doomed handshake.- preDial func(ctx context.Context, microvmID, endpoint string) (*agentConn, error)-- mu sync.Mutex- stock []*StockEntry- // budgetLoggedAt rate-limits the at-budget notice; see overBudget.- budgetLoggedAt time.Time- // reserved holds boxes promised to the edge's PoolStock DO but not yet- // bound to a sandbox. They stay HERE rather than moving to the DO because- // the pre-dialled tunnel is a live gRPC channel in this process — it cannot- // be serialized to a Durable Object. The DO holds only the identity; the- // control plane keeps the thing that makes a claim fast.- //- // A reservation is deliberately not a claim: nothing is bound, no sandbox- // id exists yet, and an unclaimed one returns to stock. That is what makes- // an edge that dies mid-create cost a box for one reaper interval instead- // of until the 8h cap.- reserved map[string]*reservation- // 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- // boot time — each one burning memory quota we cannot get back quickly.- inflight int-}--// AgentPort is the guest port this pool's tokens are scoped to. Callers handing-// a box's reach-info to something outside this process need it, because the-// credential is only valid for that one port.-func (p *Pool) AgentPort() int32 { return p.client.Config().AgentPort }--func NewPool(client *Client, cfg PoolConfig) *Pool {- cfg.applyDefaults()- p := &Pool{client: client, cfg: cfg}- p.preDial = client.DialAgentConnected- return p-}--// Claim removes a ready box from stock and returns it. No AWS calls, no-// blocking, no error path — a miss simply means the caller must fall back to a-// direct create (and eat the RunMicrovm rate limit) or fail fast.-func (p *Pool) Claim() (*StockEntry, bool) {- p.mu.Lock()- defer p.mu.Unlock()- for len(p.stock) > 0 {- e := p.stock[len(p.stock)-1]- p.stock = p.stock[:len(p.stock)-1]- // Skip anything that aged out while queued rather than handing a- // customer a box Lambda is about to terminate underneath them.- if time.Since(e.launchedAt) < p.cfg.MaxBoxAge {- return e, true- }- go p.terminate(e)- }- return nil, false-}--// Reserve promises up to n boxes to the edge and returns them. The caller gets-// identity only — MicrovmID, Endpoint, Token — which is all the DO needs to-// hand a box to a customer; the tunnel stays here.-//-// Returns fewer than n (possibly none) when stock is short. That is not an-// error: the edge falls back to asking the control plane, which is the same-// path it uses when the DO is cold.-func (p *Pool) Reserve(n int) []*StockEntry {- if n <= 0 {- return nil- }- p.mu.Lock()- defer p.mu.Unlock()- if p.reserved == nil {- p.reserved = make(map[string]*reservation)- }- now := time.Now()- out := make([]*StockEntry, 0, n)- for len(out) < n {- if len(p.stock) == 0 {- break- }- e := p.stock[len(p.stock)-1]- p.stock = p.stock[:len(p.stock)-1]- // Same age rule as Claim: never promise a box Lambda is about to- // terminate underneath the customer.- if time.Since(e.launchedAt) >= p.cfg.MaxBoxAge {- go p.terminate(e)- continue- }- p.reserved[e.MicrovmID] = &reservation{entry: e, at: now}- out = append(out, e)- }- return out-}--// ClaimReserved binds a previously reserved box, returning the full entry so the-// caller can adopt its tunnel. Reports false if the reservation is unknown —-// already claimed, expired back to stock, or never made — which the caller must-// treat as a miss rather than a failure, because the edge can legitimately race-// the reaper.-func (p *Pool) ClaimReserved(microvmID string) (*StockEntry, bool) {- p.mu.Lock()- defer p.mu.Unlock()- r, ok := p.reserved[microvmID]- if !ok {- return nil, false- }- delete(p.reserved, microvmID)- return r.entry, true-}--// ReleaseReserved returns an unclaimed reservation to stock — the edge deciding-// it does not need the box after all. Cheaper than letting it expire, and the-// box keeps its warm tunnel.-func (p *Pool) ReleaseReserved(microvmID string) bool {- p.mu.Lock()- defer p.mu.Unlock()- r, ok := p.reserved[microvmID]- if !ok {- return false- }- delete(p.reserved, microvmID)- p.stock = append(p.stock, r.entry)- return true-}--// AttachAgent gives a stocked box back its agent channel.-//-// Pairs with Manager.DetachAgent on the release path. TrackClaimed transfers a-// reservation's tunnel to the manager, so a reservation the edge hands back has-// none — and re-dialling it costs the next customer ~470ms on their first exec-// (measured: 549ms cold vs 76ms warm). Since the release path knows the channel-// is still good and that no customer ever held it, moving it back is strictly-// better than closing it and dialling again.-//-// warmTunnels re-dials anything that still ends up tunnel-less; this just keeps-// the common case from needing it, because the 30s maintenance tick loses the-// race when the DO releases a batch and immediately re-reserves it.-func (p *Pool) AttachAgent(microvmID string, a *agentConn) {- if a == nil {- return- }- p.mu.Lock()- for _, e := range p.stock {- if e.MicrovmID == microvmID && e.agent == nil {- e.agent = a- p.mu.Unlock()- return- }- }- p.mu.Unlock()- // Left stock between the release and here — don't leak the channel.- _ = a.Close()-}--// expireReservations TERMINATES promises the edge never redeemed. It does not-// return them to stock, and that distinction is a security boundary rather than-// a cleanup preference.-//-// A reservation carries a pre-minted auth token, handed to the DO. When a-// reservation goes stale we cannot tell "the DO died before handing this out"-// from "the DO gave it to a customer and the finalize was lost" — and in the-// second case the customer holds a live token for that box. Re-pooling it would-// hand a second customer a box the first can still reach: cross-tenant access.-// Burning a warm box is the cheap outcome; the other one is a breach.-//-// This mirrors the QEMU edge-claim reaper, which destroys stale edge_reserved-// rows for exactly this reason (see edge_claim.go). ReleaseReserved is the safe-// counterpart: there the edge is positively asserting it never handed the box-// out, which is knowledge this path does not have.-func (p *Pool) expireReservations() int {- p.mu.Lock()- stale := make([]*StockEntry, 0)- for id, r := range p.reserved {- if time.Since(r.at) < reservationTTL {- continue- }- delete(p.reserved, id)- stale = append(stale, r.entry)- }- p.mu.Unlock()-- for _, e := range stale {- go p.terminate(e)- // Drop the sandbox binding the reserve made, so nothing keeps routing a- // live id to a box that no longer exists. Ordering does not matter — the- // box is doomed either way — but this must not run under p.mu, because- // the callback reaches back into the backend.- if p.cfg.OnExpire != nil {- p.cfg.OnExpire(e.MicrovmID)- }- }- return len(stale)-}--// ReservedDepth reports outstanding reservations, for telemetry and for the-// sizing invariant.-func (p *Pool) ReservedDepth() int {- p.mu.Lock()- defer p.mu.Unlock()- return len(p.reserved)-}--// Depth reports current stock, for telemetry and for the sizing invariant: the-// edge's shards must not target more stock in aggregate than the pool can hold,-// or shards starve while hoarding — the same failure that cost us 1045ms vs-// 174ms on the QEMU fleet.-func (p *Pool) Depth() int {- p.mu.Lock()- defer p.mu.Unlock()- return len(p.stock)-}--// Run drives the maintenance loop until ctx is cancelled. Everything-// rate-limited lives here, deliberately far from any customer request.-func (p *Pool) Run(ctx context.Context) {- log.Printf("awsvm: pool starting (target=%d maxAge=%s launchInterval=%s)",- p.cfg.TargetStock, p.cfg.MaxBoxAge, p.cfg.LaunchInterval)-- launch := time.NewTicker(p.cfg.LaunchInterval)- defer launch.Stop()- maintain := time.NewTicker(30 * time.Second)- defer maintain.Stop()-- for {- select {- case <-ctx.Done():- return- case <-launch.C:- // One launch per tick is what keeps us under the RunMicrovm quota.- // Topping up "as fast as possible" is exactly how you earn a- // ThrottlingException storm.- //- // The launch itself runs in its own goroutine because it now waits- // 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- }- // Budget before target: when a burst has drained the pool into live- // sandboxes, the right move is to WAIT for them rather than launch- // replacements alongside them. Refilling here is what doubles the- // footprint and trips the regional quota.- if p.overBudget() {- // Stand down rather than re-probe at tick rate. Skipping the tick- // alone leaves the filler glued to the ceiling: it wakes every- // LaunchInterval, and the moment a single box is released it spends- // a RunMicrovm on a replacement and is at the ceiling again. Those- // launches contend for the same regional quota as the customer- // creates that went cold because the pool was drained, so the pool- // competes with the burst it exists to absorb. Backing off lets- // releases pool up into real headroom first.- p.standDown(p.cfg.RefillDelay)- 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)- }- }()- }- case <-maintain.C:- p.refreshTokens(ctx)- p.retireAged(ctx)- p.warmTunnels(ctx)- // Runs in its own goroutine: a touch against a box that has already- // suspended is held by Lambda for the length of a snapshot restore,- // and blocking the maintenance tick on that would stall token- // refresh, retirement and reservation expiry behind it.- go p.touchIdleTimers(ctx)- if p.cfg.OnMaintain != nil {- p.cfg.OnMaintain()- }- if n := p.expireReservations(); n > 0 {- log.Printf("awsvm: pool re-pooled %d unclaimed edge reservation(s)", n)- }- }- }-}--// 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)-}--// standDown pauses launches for d without logging, for callers that have-// already said why. Never shortens an existing pause: a quota backoff and a-// budget backoff can be armed in the same window, and the longer one is the one-// that reflects a condition we know has not cleared.-func (p *Pool) standDown(d time.Duration) {- if d <= 0 {- return- }- until := time.Now().Add(d)- p.mu.Lock()- if until.After(p.backoffUntil) {- p.backoffUntil = until- }- p.mu.Unlock()-}--// 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-// the target when deciding whether to launch more.-// overBudget reports whether pool stock plus everything claimed out of it has-// reached MaxTotalBoxes, in which case the filler must stand down.-//-// Logged at most once per cooldown rather than per tick: hitting the budget is a-// normal steady state during a burst, not an incident, and a line every-// LaunchInterval would bury the log in it.-func (p *Pool) overBudget() bool {- if p.cfg.MaxTotalBoxes <= 0 {- return false- }- inUse := 0- if p.cfg.InUse != nil {- inUse = p.cfg.InUse()- }- total := p.committed() + inUse- if total < p.cfg.MaxTotalBoxes {- return false- }- // Gate on the refill delay rather than a fixed minute so the notice tracks- // however long the filler is actually standing down, and at 9/10 of it so a- // once-per-delay caller cannot alias against the window and go silent.- p.mu.Lock()- quiet := time.Since(p.budgetLoggedAt) < p.cfg.RefillDelay*9/10- if !quiet {- p.budgetLoggedAt = time.Now()- }- p.mu.Unlock()- if !quiet {- // Decomposed on purpose. "N in use + M committed" says the budget is- // full but not which term is holding it, and the two have opposite- // fixes: a stuck committed() means the pool is hoarding stock or has- // launches wedged in flight, while a stuck in-use means bindings the- // manager still counts for sandboxes that are gone. Diagnosing a refill- // freeze from the undecomposed line took a full benchmark session and- // several wrong answers, because every latency number measured during it- // was taken against a capped pool without that being visible.- p.mu.Lock()- stock, inflight, reserved := len(p.stock), p.inflight, len(p.reserved)- p.mu.Unlock()- detail := ""- if p.cfg.InUseDetail != nil {- detail = " " + p.cfg.InUseDetail()- }- log.Printf("awsvm: pool at box budget (%d in use + %d committed >= %d) — refill paused %s to leave regional quota for creates [stock=%d inflight=%d reserved=%d%s]",- inUse, p.committed(), p.cfg.MaxTotalBoxes, p.cfg.RefillDelay, stock, inflight, reserved, detail)- }- return true-}--func (p *Pool) committed() int {- p.mu.Lock()- defer p.mu.Unlock()- // Reservations count: they are boxes we own and will hand out. Omitting- // them would make the filler see a hole that isn't there and launch- // replacements for boxes already promised, overshooting the target by- // however many creates the edge has in flight.- return len(p.stock) + p.inflight + len(p.reserved)-}--func (p *Pool) launchOne(ctx context.Context) error {- p.mu.Lock()- p.inflight++- p.mu.Unlock()- defer func() {- p.mu.Lock()- p.inflight--- p.mu.Unlock()- }()-- // Generous relative to boot: this bounds the whole launch including the wait- // for RUNNING, and ReadyTimeout is the tighter budget inside it.- runCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)- defer cancel()-- // No client token: each pool box is a fresh VM with no caller-facing- // identity to be idempotent against. Sandbox ids are assigned at claim.- box, err := p.client.Run(runCtx, "")- if err != nil {- return err- }-- // Do not park a box until Lambda says it is RUNNING. RunMicrovm returns- // while the VM is still restoring, and a claim that lands on a PENDING box- // gets 502 from the proxy — the pool's whole job is to absorb that wait so- // the customer never sees it.- ready, err := p.client.WaitRunning(runCtx, box.ID, p.cfg.ReadyTimeout)- if err != nil {- go p.terminateID(box.ID)- return err- }- box = ready-- token, err := p.client.AuthToken(runCtx, box.ID)- if err != nil {- // A box we cannot token is useless as stock and would otherwise sit- // burning quota and compute until the age cap.- go p.terminateID(box.ID)- return err- }-- // Pre-establish the agent tunnel so the first exec is warm. A failure here- // is not fatal: the box is still perfectly usable, the first exec just pays- // the dial itself, which is strictly better than discarding a launched box.- var agent *agentConn- if p.preDial != nil {- dialCtx, cancelDial := context.WithTimeout(runCtx, p.cfg.PreDialTimeout)- a, derr := p.preDial(dialCtx, box.ID, box.Endpoint)- cancelDial()- if derr != nil {- log.Printf("awsvm: pool pre-dial %s failed, box still usable cold: %v", box.ID, derr)- } else {- agent = a- // Spend the box's first-shell cost here rather than on the- // customer's first command — see agentConn.warmShell. Best effort:- // a box that fails to warm is still a perfectly good box, it just- // starts cold like it did before.- warmCtx, cancelWarm := context.WithTimeout(runCtx, warmShellTimeout)- if werr := agent.warmShell(warmCtx); werr != nil {- log.Printf("awsvm: pool warm-up exec %s failed, box starts cold: %v", box.ID, werr)- }- cancelWarm()- }- }-- p.mu.Lock()- p.stock = append(p.stock, &StockEntry{- MicrovmID: box.ID,- Endpoint: box.Endpoint,- Token: token,- agent: agent,- tokenMintedAt: time.Now(),- launchedAt: time.Now(),- })- depth := len(p.stock)- p.mu.Unlock()-- log.Printf("awsvm: pool +1 %s (depth=%d/%d)", box.ID, depth, p.cfg.TargetStock)- return nil-}--// refreshTokens re-mints tokens that are approaching expiry. Tokens cap at 60-// minutes, so any box that waits in stock longer than that outlives its token;-// without this the pool fills with entries whose credentials are already dead.-// CreateMicrovmAuthToken is quota'd at 50/s, comfortably above stock size, so-// this can run in one pass.-func (p *Pool) refreshTokens(ctx context.Context) {- cutoff := time.Duration(authTokenMaxMinutes)*time.Minute - p.cfg.TokenRefreshMargin-- p.mu.Lock()- stale := make([]*StockEntry, 0)- for _, e := range p.stock {- if time.Since(e.tokenMintedAt) >= cutoff {- stale = append(stale, e)- }- }- p.mu.Unlock()-- for _, e := range stale {- tokenCtx, cancel := context.WithTimeout(ctx, 15*time.Second)- token, err := p.client.AuthToken(tokenCtx, e.MicrovmID)- cancel()- if err != nil {- log.Printf("awsvm: pool token refresh %s: %v", e.MicrovmID, err)- continue- }- p.mu.Lock()- e.Token = token- e.tokenMintedAt = time.Now()- p.mu.Unlock()- }- if len(stale) > 0 {- log.Printf("awsvm: pool refreshed %d token(s)", len(stale))- }-}--// retireAged terminates stock approaching the 8h ceiling so the launch loop can-// replace it. Retiring early is the point: a box terminated by Lambda mid-claim-// is a failed create, and success rate multiplies the benchmark score directly.-func (p *Pool) retireAged(ctx context.Context) {- p.mu.Lock()- kept := p.stock[:0]- var retire []*StockEntry- for _, e := range p.stock {- if time.Since(e.launchedAt) >= p.cfg.MaxBoxAge {- retire = append(retire, e)- continue- }- kept = append(kept, e)- }- p.stock = kept- p.mu.Unlock()-- for _, e := range retire {- p.terminate(e)- }- if len(retire) > 0 {- log.Printf("awsvm: pool retired %d aged box(es)", len(retire))- }-}--// warmTunnels keeps every stocked box's agent channel in READY, so the first-// exec after a claim does not pay to re-establish it.-//-// Pre-dialling at manufacture is not enough on its own. dialAgent sets-// PermitWithoutStream:false — deliberately, so an idle CUSTOMER sandbox is-// allowed to suspend instead of being held RUNNING by keepalive pings — which-// means a box waiting in stock sends no traffic at all and the proxy drops its-// WebSocket tunnel. gRPC keeps the ClientConn, so nothing looks broken and no-// re-dial is logged; the cost simply lands on the customer's first RPC as a-// silent tunnel re-handshake. Measured on dev: first exec 383ms vs 75ms warm,-// and TTI is defined by exactly that first call.-//-// Reconnecting is done with conn.Connect() rather than a probe RPC: it restores-// the transport without touching the guest, so this cannot be mistaken for-// sandbox activity by anything that watches for it. Only stock is warmed —-// claimed boxes keep the existing idle-and-suspend behaviour untouched.-func (p *Pool) warmTunnels(ctx context.Context) {- p.mu.Lock()- conns := make([]*agentConn, 0, len(p.stock))- // Kept aligned with conns so a ping failure can be attributed back to the- // entry that owns the channel, which is what makes retiring one possible.- live := make([]*StockEntry, 0, len(p.stock))- var missing []*StockEntry- for _, e := range p.stock {- if e.agent != nil {- conns = append(conns, e.agent)- live = append(live, e)- continue- }- // No tunnel at all. The common cause is a round trip through the edge:- // TrackClaimed transfers ownership of the channel to the manager (and- // clears this field, so the pool can never close a live customer's- // tunnel), then EdgeRelease hands the unused reservation back to stock —- // and what returns has no tunnel and no way to get one. Measured on dev:- // ~130 boxes released across 8 batches produced 134 reserves with- // warm_tunnel=false against 136 with it, i.e. half of all creates were- // paying a cold dial on their first exec.- //- // Re-dialling here rather than in ReleaseReserved is deliberate: stock- // with no tunnel is wrong however it got that way, so healing it in the- // maintenance tick covers every cause, including ones we have not found.- if len(missing) < warmDialPerTick {- missing = append(missing, e)- }- }- p.mu.Unlock()-- // Keepalive: touch every stocked box so it never goes idle long enough for- // AWS to suspend it. This is the expensive-on-purpose half of the trade —- // an unsuspended box bills compute while it waits — and it is what keeps a- // claim's first exec off the ~1s resume path.- //- // A channel that keeps failing is RETIRED here rather than nudged. The- // re-warm loop below can only call ClientConn.Connect(), which moves an Idle- // conn to Connecting and does nothing at all to one already in- // TransientFailure — and gRPC's own reconnect backoff climbs toward ~2- // minutes, so a channel that went bad stays bad. Nothing else ever replaced- // it either: the re-dial path below heals a MISSING tunnel (e.agent == nil)- // and a dead-but-present one is not missing, so it was never a candidate.- //- // The result was a pool that decayed monotonically and never recovered —- // measured on dev at a 130-box pool: 75 live tunnels, then 55, then 30, with- // the tick reporting "re-warmed 75" every 30s while re-warming nothing. Every- // exec against one of those boxes pays a full cold dial (~1.1s guest attach),- // which is precisely the cost this pre-dial exists to avoid.- //- // Retiring means: close the channel, clear the field, and let the bounded- // re-dial above rebuild it on the next tick with a freshly minted token. That- // also covers the case Connect() could never have fixed — the token expired,- // so the WebSocket upgrade itself is being refused and only a new dial with a- // new credential can succeed.- ok, failed, retired, dead, sample := p.applyPingResults(live, pingEach(ctx, conns))- for _, a := range dead {- _ = a.Close()- }- if ok+failed > 0 {- // The sampled error is the point of the line. "75 failed" on its own is- // unactionable, and was: it took watching the count decay across ten- // minutes to work out that anything was wrong at all.- msg := fmt.Sprintf("awsvm: pool keepalive pinged %d stocked box(es) (%d failed", ok, failed)- if retired > 0 {- msg += fmt.Sprintf(", %d channel(s) retired for re-dial", retired)- }- msg += ")"- if sample != nil {- msg += fmt.Sprintf("; first failure: %v", sample)- }- log.Print(msg)- }-- if p.preDial != nil {- redialed, redialFailed := 0, 0- var firstErr error- var firstErrBox string- var evicted []*StockEntry- for _, e := range missing {- dialCtx, cancel := context.WithTimeout(ctx, p.cfg.PreDialTimeout)- a, err := p.preDial(dialCtx, e.MicrovmID, e.Endpoint)- cancel()- if err != nil {- // The error was previously discarded here, and the line below- // reported len(missing) — boxes ATTEMPTED — so a tick that healed- // nothing logged identically to one that healed everything. That- // is why a pool sitting at 1 live box out of 34 in stock looked- // healthy: this is the only place that knows why a stocked box- // cannot get a tunnel, and it threw the reason away.- redialFailed++- if firstErr == nil {- firstErr, firstErrBox = err, e.MicrovmID- }- // Count it against the box, and evict once it is out of chances.- // The dial mints a fresh token first, so an expired credential- // cannot cause this; what remains is a box that is gone.- p.mu.Lock()- e.redialFailures++- doomed := e.redialFailures >= maxRedialFailures- if doomed {- for i, s := range p.stock {- if s == e {- p.stock = append(p.stock[:i], p.stock[i+1:]...)- break- }- }- }- p.mu.Unlock()- if doomed {- evicted = append(evicted, e)- }- continue // still usable cold; try again next tick- }- redialed++- p.mu.Lock()- e.redialFailures = 0- p.mu.Unlock()- // Re-check under the lock: the entry may have been reserved or- // terminated while we dialled, and installing a tunnel on an entry- // that has left stock would leak the channel.- p.mu.Lock()- stillStocked := false- for _, s := range p.stock {- if s == e && s.agent == nil {- s.agent = a- stillStocked = true- break- }- }- p.mu.Unlock()- if !stillStocked {- _ = a.Close()- }- }- if len(missing) > 0 {- // Successes and failures separately, plus a sampled error. A count of- // attempts cannot distinguish "stock is healing" from "stock is dead- // and every dial is refused", and those have completely different- // fixes. `capped` marks the ticks where warmDialPerTick truncated the- // work, so a backlog is visible rather than looking like a steady- // trickle of the same 32 boxes.- msg := fmt.Sprintf("awsvm: pool re-dial: %d healed, %d failed, of %d tunnel-less stocked box(es)",- redialed, redialFailed, len(missing))- if len(missing) >= warmDialPerTick {- msg += " (capped this tick — more are waiting)"- }- if len(evicted) > 0 {- msg += fmt.Sprintf("; EVICTED %d unreachable box(es) after %d consecutive failures", len(evicted), maxRedialFailures)- }- if firstErr != nil {- msg += fmt.Sprintf("; first failure %s: %v", firstErrBox, firstErr)- }- log.Print(msg)- }- // Outside the lock: terminate reaches AWS. These boxes are already out- // of stock, so nothing can claim them while this runs.- for _, e := range evicted {- go p.terminate(e)- }- }-- // Nudge Idle channels back to Connecting. This is a genuine, cheap win — an- // Idle conn has no transport but no problem either, and Connect() rebuilds it- // before a customer needs it.- //- // TransientFailure is counted SEPARATELY and deliberately not nudged.- // Connect() is documented as a no-op on a conn that is already trying, and- // these are already trying — on gRPC's own backoff, which grows toward ~2- // minutes. Lumping the two together is what produced "re-warmed 75 idle agent- // tunnel(s)" every 30s on a pool where nothing was being re-warmed and the- // live count was falling: the number described an intention, not an effect.- // Failing channels are healed by the retirement above, not here.- idle, failing := 0, 0- for _, a := range conns {- if a.conn == nil {- continue- }- switch a.conn.GetState() {- case connectivity.Ready, connectivity.Connecting:- // Already warm, or already on its way.- case connectivity.Shutdown:- // Terminal — the entry is dead stock; retireAged/terminate owns it.- case connectivity.TransientFailure:- failing++- default: // Idle- a.conn.Connect()- idle++- }- }- if idle > 0 || failing > 0 {- log.Printf("awsvm: pool tunnels of %d stocked: %d idle re-connected, %d in transient failure (awaiting retirement)",- len(conns), idle, failing)- }-}--// idleTouchConcurrency bounds how many idle-timer touches run at once. Lower-// than pingConcurrency because these are full HTTPS requests to distinct hosts-// rather than RPCs on channels we already hold, and because they are never-// urgent: the pacing below gives every box a wide window to be served in.-const idleTouchConcurrency = 16--// idleTouchInterval is how often each stocked box must receive a real proxy-// request, derived from the idle window AWS was actually configured with.-//-// A third of the window, so a box survives two consecutive missed touches — a-// maintenance tick that is late, or a touch that fails — before AWS can suspend-// it. Clamped at both ends: never more often than once a minute (this is a-// network request per box and the pool can be large), and never less often than-// every 15 minutes (at the 8h ceiling a third would be 2h40m, which is long-// enough that a lowered idle window elsewhere would go unnoticed for hours).-func (p *Pool) idleTouchInterval() time.Duration {- window := time.Duration(p.client.Config().MaxIdleDurationSeconds) * time.Second- if window <= 0 {- window = 15 * time.Minute- }- iv := window / 3- if iv < time.Minute {- iv = time.Minute- }- if iv > 15*time.Minute {- iv = 15 * time.Minute- }- return iv-}--// touchIdleTimers sends one real inbound request through the proxy endpoint of-// every stocked box that is due for one, so AWS never counts it idle.-//-// This is the half of the keepalive that AWS can see. warmTunnels keeps our own-// agent channel healthy — which is what makes a claim's first exec fast — but it-// does all of that INSIDE an established WebSocket, and AWS measures idleness by-// inbound requests through the proxy endpoint. So the pool could hold a box-// perfectly warm by every measure we had, while AWS independently decided nobody-// had touched it in 15 minutes and suspended it. That is what produced stock-// answering 502, and then stock being terminated outright 30 minutes later.-//-// Belt to the ceiling's braces: with maxIdleDurationSeconds now defaulted to the-// 8h total-lifetime cap, no box should ever reach its idle window before-// MaxBoxAge retires it anyway. This runs regardless, cheaply, because that-// ceiling is a default someone can lower with an env var and the failure mode-// when they do is silent, delayed, and destroys sandboxes.-//-// Failures are logged and nothing more. A failed touch is not evidence the box-// is bad — a 502 here includes a box mid-resume — and warmTunnels already owns-// the decision to retire or evict on evidence it can actually trust.-func (p *Pool) touchIdleTimers(ctx context.Context) {- interval := p.idleTouchInterval()- now := time.Now()-- p.mu.Lock()- due := make([]*StockEntry, 0, len(p.stock))- for _, e := range p.stock {- if e.lastProxyTouch.IsZero() || now.Sub(e.lastProxyTouch) >= interval {- due = append(due, e)- }- }- p.mu.Unlock()- if len(due) == 0 {- return- }-- var (- mu sync.Mutex- ok int- failed int- sample error- sampleBox string- touched []*StockEntry- wg sync.WaitGroup- )- sem := make(chan struct{}, idleTouchConcurrency)- for _, e := range due {- wg.Add(1)- go func(e *StockEntry) {- defer wg.Done()- sem <- struct{}{}- defer func() { <-sem }()-- err := proxyTouch(ctx, e.Endpoint, p.client.Config().AgentPort,- func(ctx context.Context) (string, error) {- return p.client.AuthToken(ctx, e.MicrovmID)- })-- mu.Lock()- defer mu.Unlock()- if err != nil {- failed++- if sample == nil {- sample, sampleBox = err, e.MicrovmID- }- return- }- ok++- touched = append(touched, e)- }(e)- }- wg.Wait()-- // Stamped under the pool lock, and only on success: every other reader of- // lastProxyTouch holds p.mu, and a box whose touches keep failing must stay- // due on every tick rather than drift quietly toward suspension.- if len(touched) > 0 {- stamp := time.Now()- p.mu.Lock()- for _, e := range touched {- e.lastProxyTouch = stamp- }- p.mu.Unlock()- }-- msg := fmt.Sprintf("awsvm: pool idle-timer touch: %d ok, %d failed, of %d due (every %s)",- ok, failed, len(due), interval)- if sample != nil {- msg += fmt.Sprintf("; first failure %s: %v", sampleBox, sample)- }- log.Print(msg)-}--// applyPingResults folds one tick's keepalive outcome back into the stock,-// returning the channels the caller must close.-//-// Split out from warmTunnels so the retirement rule is testable without a live-// gRPC channel: agentConn.ping talks to a real client, so the only way to-// exercise "two consecutive failures retire the tunnel" in a unit test is to-// drive the decision directly.-//-// errs is aligned with live by index — see pingEach.-func (p *Pool) applyPingResults(live []*StockEntry, errs []error) (ok, failed, retired int, dead []*agentConn, sample error) {- p.mu.Lock()- defer p.mu.Unlock()- for i, err := range errs {- if i >= len(live) {- break- }- e := live[i]- if err == nil {- e.agentFailures = 0- ok++- continue- }- failed++- if sample == nil {- sample = err- }- e.agentFailures++- if e.agentFailures < maxAgentPingFailures {- continue- }- // Only ever close what the entry STILL holds. Between the ping and here- // the box may have been claimed, and TrackClaimed transfers the channel- // to the manager and clears this field — closing the pinged conn blindly- // would tear down a live customer's tunnel.- if e.agent != nil {- dead = append(dead, e.agent)- e.agent = nil- e.agentFailures = 0- retired++- }- }- return ok, failed, retired, dead, sample-}--func (p *Pool) terminate(e *StockEntry) {- // Close the pre-dialled tunnel too, or retiring stock leaks a goroutine and- // a socket per box.- if e.agent != nil {- _ = e.agent.Close()- }- 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.-// warmDialPerTick bounds how many tunnel-less stock boxes are re-dialled per-// maintenance tick. Each dial is a real WebSocket+TLS handshake to the proxy, so-// healing a fully cold pool all at once would burst hundreds of them; spreading-// the work costs a few ticks and keeps the pool's own traffic predictable.-const warmDialPerTick = 32--// maxAgentPingFailures is how many CONSECUTIVE failed keepalive pings retire a-// stocked box's channel for re-dial. Two, at a 30s tick, means one blip is-// forgiven and a genuinely dead channel is replaced within ~a minute.-//-// Not one: a single ping can lose to a box that is mid-resume, and churning a-// working tunnel costs a full re-dial for nothing. Not five: every tick spent-// waiting is a tick where any create landing on that box hands its customer a-// cold dial.-const maxAgentPingFailures = 2--// maxRedialFailures is how many CONSECUTIVE failed re-dials evict a stocked box-// entirely. Three, at a 30s tick, means ~90s of a box being unreachable with a-// freshly minted token before the pool stops counting it as stock. Deliberately-// larger than maxAgentPingFailures: retiring a channel is cheap and reversible,-// while eviction terminates the box, so it should need more evidence.-const maxRedialFailures = 3--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(), 3*time.Minute)- defer cancel()- 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)+len(p.reserved))- for _, e := range p.stock {- ids[e.MicrovmID] = struct{}{}- }- // Reserved boxes are owned, just spoken for. Leaving them out would make- // the orphan sweep classify every in-flight edge claim as abandoned and- // terminate boxes out from under customers mid-create — the worst possible- // bug in this file.- for id := range p.reserved {- ids[id] = struct{}{}- }- return ids-}--// Drain terminates all stock. Called on shutdown so a restarting filler does not-// abandon boxes — abandoned boxes hold both compute cost and regional quota-// until they hit the 8h cap.-func (p *Pool) Drain() {- p.mu.Lock()- stock := p.stock- p.stock = nil- // Reserved boxes are ours too. A shutdown that drained only stock would- // abandon every outstanding reservation to the 8h cap — the same leak this- // function exists to prevent, just through a different door.- for id, r := range p.reserved {- stock = append(stock, r.entry)- delete(p.reserved, id)- }- p.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.WaitGroup- for _, e := range stock {- <-tick.C- wg.Add(1)- go func(e *StockEntry) {- defer wg.Done()- p.terminate(e)- }(e)- }- wg.Wait()- if len(stock) > 0 {- log.Printf("awsvm: pool drained %d box(es)", len(stock))- }-}diff --git a/internal/awsvm/pool_test.go b/internal/awsvm/pool_test.godeleted file mode 100644index 59b812b7..00000000--- a/internal/awsvm/pool_test.go+++ /dev/null@@ -1,640 +0,0 @@-package awsvm--import (- "context"- "errors"- "fmt"- "sync"- "sync/atomic"- "testing"- "time"-- "github.com/aws/aws-sdk-go-v2/aws"- "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"- "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"-)--// poolAPI counts the AWS calls the pool makes, so the tests can assert on the-// property that actually matters: claiming must not touch AWS at all.-type poolAPI struct {- API- mu sync.Mutex- runs int- gets int- tokens int- terminates []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.runErr- f.mu.Unlock()- if runErr != nil {- return nil, runErr- }- return &lambdamicrovms.RunMicrovmOutput{- MicrovmId: aws.String(id),- Endpoint: aws.String(id + ".microvm.aws.dev"),- ImageArn: aws.String("arn:image"),- }, nil-}--// GetMicrovm reports RUNNING immediately. Real boxes spend seconds PENDING —-// that gap is exactly why the pool waits before stocking a box — but these-// tests are about call accounting, not boot timing, so waiting here would only-// make them slow.-func (f *poolAPI) GetMicrovm(_ context.Context, in *lambdamicrovms.GetMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {- f.mu.Lock()- f.gets++- f.mu.Unlock()- id := aws.ToString(in.MicrovmIdentifier)- return &lambdamicrovms.GetMicrovmOutput{- MicrovmId: aws.String(id),- Endpoint: aws.String(id + ".microvm.aws.dev"),- ImageArn: aws.String("arn:image"),- State: types.MicrovmStateRunning,- }, nil-}--func (f *poolAPI) CreateMicrovmAuthToken(_ context.Context, in *lambdamicrovms.CreateMicrovmAuthTokenInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error) {- f.mu.Lock()- f.tokens++- n := f.tokens- f.mu.Unlock()- return &lambdamicrovms.CreateMicrovmAuthTokenOutput{- AuthToken: map[string]string{"X-aws-proxy-auth": fmt.Sprintf("jwe-%d", n)},- }, nil-}--func (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-}--func (f *poolAPI) counts() (int, int, int) {- f.mu.Lock()- defer f.mu.Unlock()- return f.runs, f.tokens, len(f.terminates)-}--func testPool(t *testing.T, cfg PoolConfig) (*Pool, *poolAPI) {- t.Helper()- f := &poolAPI{}- c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})- p := NewPool(c, cfg)- // No real endpoints behind the fake API, so pre-dialling would block on a- // handshake that can never complete. The claim-path accounting these tests- // assert on is unaffected.- p.preDial = nil- return p, f-}--// The whole design rests on this: a claim must make ZERO AWS calls. Any call on-// this path reintroduces the 5/s RunMicrovm / ResumeMicrovm ceiling and a-// burst-100 becomes a 20-second launch window.-func TestClaimMakesNoAWSCalls(t *testing.T) {- p, f := testPool(t, PoolConfig{TargetStock: 5})- for i := 0; i < 5; i++ {- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }- runsBefore, tokensBefore, termsBefore := f.counts()-- for i := 0; i < 5; i++ {- e, ok := p.Claim()- if !ok {- t.Fatalf("claim %d missed on a full pool", i)- }- if e.Endpoint == "" || e.Token == "" {- t.Fatalf("claim returned an entry without endpoint/token: %+v", e)- }- }-- runs, tokens, terms := f.counts()- if runs != runsBefore || tokens != tokensBefore || terms != termsBefore {- t.Fatalf("claiming hit AWS: runs %d→%d tokens %d→%d terminates %d→%d",- runsBefore, runs, tokensBefore, tokens, termsBefore, terms)- }-}--// An empty pool must fail fast rather than block or launch inline — the caller-// decides whether to eat a rate-limited direct create.-func TestClaimOnEmptyPoolMisses(t *testing.T) {- p, f := testPool(t, PoolConfig{TargetStock: 1})- if _, ok := p.Claim(); ok {- t.Fatal("claim succeeded on an empty pool")- }- if runs, _, _ := f.counts(); runs != 0 {- t.Fatalf("empty claim triggered %d RunMicrovm call(s)", runs)- }-}--// Boxes die at the 8h service cap whether we like it or not. Handing one out-// near the ceiling means Lambda terminates it under the customer, so aged stock-// must be skipped and cleaned up instead.-func TestClaimSkipsAndTerminatesAgedStock(t *testing.T) {- p, f := testPool(t, PoolConfig{TargetStock: 2, MaxBoxAge: time.Hour})- for i := 0; i < 2; i++ {- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }- p.mu.Lock()- for _, e := range p.stock {- e.launchedAt = time.Now().Add(-2 * time.Hour)- }- p.mu.Unlock()-- if _, ok := p.Claim(); ok {- t.Fatal("claim handed out a box past MaxBoxAge")- }- // Termination is fired asynchronously; give it a moment.- deadline := time.Now().Add(2 * time.Second)- for time.Now().Before(deadline) {- if _, _, terms := f.counts(); terms == 2 {- return- }- time.Sleep(10 * time.Millisecond)- }- _, _, terms := f.counts()- t.Fatalf("aged stock not terminated: %d of 2", terms)-}--// Stock that outlives its token is worse than no stock: the claim succeeds and-// the customer's first request fails auth.-func TestRefreshTokensRemintsStaleEntries(t *testing.T) {- p, f := testPool(t, PoolConfig{TargetStock: 2, TokenRefreshMargin: 10 * time.Minute})- for i := 0; i < 2; i++ {- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }- _, tokensAfterLaunch, _ := f.counts()-- p.mu.Lock()- for _, e := range p.stock {- e.tokenMintedAt = time.Now().Add(-55 * time.Minute) // inside the margin- // Force a client-cache miss too, else AuthToken returns the cached value.- delete(p.client.tokens, e.MicrovmID)- }- p.mu.Unlock()-- p.refreshTokens(context.Background())-- _, tokensNow, _ := f.counts()- if tokensNow != tokensAfterLaunch+2 {- t.Fatalf("re-minted %d token(s), want 2", tokensNow-tokensAfterLaunch)- }- p.mu.Lock()- defer p.mu.Unlock()- for _, e := range p.stock {- if time.Since(e.tokenMintedAt) > time.Minute {- t.Fatal("entry still carries a stale tokenMintedAt after refresh")- }- }-}--// A restarting filler must not abandon boxes: they hold compute cost and-// regional quota until the 8h cap.-func TestDrainTerminatesAllStock(t *testing.T) {- p, f := testPool(t, PoolConfig{TargetStock: 3})- for i := 0; i < 3; i++ {- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }- p.Drain()-- if got := p.Depth(); got != 0 {- t.Fatalf("depth after drain = %d, want 0", got)- }- if _, _, terms := f.counts(); terms != 3 {- t.Fatalf("drain terminated %d box(es), want 3", terms)- }-}--// The launch loop must respect the RunMicrovm quota. Defaults pace under 5/s.-func TestDefaultLaunchIntervalStaysUnderRunQuota(t *testing.T) {- var cfg PoolConfig- cfg.applyDefaults()- rate := float64(time.Second) / float64(cfg.LaunchInterval)- if rate > 5.0 {- t.Fatalf("default launch rate %.1f/s exceeds the RunMicrovm quota of 5/s", rate)- }- if cfg.MaxBoxAge >= 8*time.Hour {- t.Fatalf("MaxBoxAge %s leaves no headroom under the 8h service cap", cfg.MaxBoxAge)- }-}--// TargetStock 0 means "no warm stock, cold-create only" — a real operating mode-// now that a pool miss launches a box instead of failing. It used to be-// defaulted up to 20, which launched twenty boxes for an operator who asked for-// none, and quietly invalidated any test of the cold path.-func TestZeroTargetStockKeepsPoolEmpty(t *testing.T) {- p, f := testPool(t, PoolConfig{TargetStock: 0})- _ = f- if got := p.cfg.TargetStock; got != 0 {- t.Fatalf("TargetStock 0 became %d — pool would stock boxes nobody asked for", got)- }- if d := p.Depth(); d != 0 {- t.Fatalf("empty-target pool reported depth %d", d)- }- if _, ok := p.Claim(); ok {- 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)- }- }-}--// A reservation is owned stock, not free stock. Every accounting path has to-// agree on that, and each of these assertions corresponds to a distinct way the-// pool could quietly destroy itself.-func TestReservationsHoldTheirInvariants(t *testing.T) {- p, f := testPool(t, PoolConfig{TargetStock: 4})- for i := 0; i < 4; i++ {- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }-- got := p.Reserve(3)- if len(got) != 3 {- t.Fatalf("Reserve(3) returned %d", len(got))- }- if p.Depth() != 1 {- t.Fatalf("stock after reserving 3 of 4 = %d, want 1", p.Depth())- }- // committed must still see all four, or the filler launches replacements- // for boxes that were merely promised.- if c := p.committed(); c != 4 {- t.Fatalf("committed = %d, want 4 (reservations are owned)", c)- }- // The orphan sweep keys off StockIDs. A reserved box missing here would be- // terminated mid-create.- ids := p.StockIDs()- if len(ids) != 4 {- t.Fatalf("StockIDs = %d, want 4 (stock + reserved)", len(ids))- }- for _, e := range got {- if _, ok := ids[e.MicrovmID]; !ok {- t.Fatalf("reserved box %s absent from StockIDs — the sweep would reap it", e.MicrovmID)- }- }-- // Claim binds exactly one, and only once.- e0 := got[0]- if _, ok := p.ClaimReserved(e0.MicrovmID); !ok {- t.Fatal("ClaimReserved missed a live reservation")- }- if _, ok := p.ClaimReserved(e0.MicrovmID); ok {- t.Fatal("ClaimReserved returned the same reservation twice")- }-- // Release puts one back as usable stock.- if !p.ReleaseReserved(got[1].MicrovmID) {- t.Fatal("ReleaseReserved missed a live reservation")- }- if p.Depth() != 2 {- t.Fatalf("stock after release = %d, want 2", p.Depth())- }-- // A stale reservation is DESTROYED, never returned to stock: its token may- // already be in a customer's hands, and re-issuing the box would be- // cross-tenant access. Burning a warm box is the cheap failure.- stockBefore := p.Depth()- p.mu.Lock()- for _, r := range p.reserved {- r.at = time.Now().Add(-2 * reservationTTL)- }- p.mu.Unlock()- if n := p.expireReservations(); n != 1 {- t.Fatalf("expireReservations retired %d, want 1", n)- }- if p.ReservedDepth() != 0 {- t.Fatalf("reservations outstanding after expiry: %d", p.ReservedDepth())- }- if p.Depth() != stockBefore {- t.Fatalf("stock grew from %d to %d — an expired reservation was re-pooled, which can hand a live token to a second tenant",- stockBefore, p.Depth())- }- deadline := time.Now().Add(2 * time.Second)- for time.Now().Before(deadline) {- if _, _, terms := f.counts(); terms >= 1 {- break- }- time.Sleep(10 * time.Millisecond)- }- if _, _, terms := f.counts(); terms < 1 {- t.Fatal("expired reservation was neither re-pooled nor terminated — it leaks quota")- }-}--// A reservation binds a sandbox id to a box before any customer claims it, so-// the control plane can route that id the instant the edge answers a create.-// When the reservation dies instead, the binding has to die with it — otherwise-// a live sandbox id keeps resolving to a terminated box and every operation on-// it fails deep in the agent tunnel instead of cleanly.-func TestExpiringReservationNotifiesTheOwner(t *testing.T) {- var mu sync.Mutex- var forgot []string- p, _ := testPool(t, PoolConfig{- TargetStock: 2,- OnExpire: func(microvmID string) {- mu.Lock()- defer mu.Unlock()- forgot = append(forgot, microvmID)- },- })- for i := 0; i < 2; i++ {- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }- got := p.Reserve(2)- if len(got) != 2 {- t.Fatalf("Reserve(2) returned %d", len(got))- }-- p.mu.Lock()- for _, r := range p.reserved {- r.at = time.Now().Add(-2 * reservationTTL)- }- p.mu.Unlock()- if n := p.expireReservations(); n != 2 {- t.Fatalf("expireReservations retired %d, want 2", n)- }-- mu.Lock()- defer mu.Unlock()- if len(forgot) != 2 {- t.Fatalf("OnExpire fired %d time(s), want 2 — a binding survived its box", len(forgot))- }- for _, e := range got {- found := false- for _, id := range forgot {- if id == e.MicrovmID {- found = true- }- }- if !found {- t.Errorf("OnExpire never reported %s — its sandbox id still routes to a dead box", e.MicrovmID)- }- }-}--// The edge's PoolStock DO holds reserved boxes in its own stock for up to-// ENTRY_TTL_MS (10 minutes, cloudflare-workers/api-edge/src/pool_stock.ts)-// before releasing them. If this pool expired a reservation first it would-// terminate a box the DO still believes it owns, and the next create to pop that-// entry would get a 201 for a sandbox that does not exist.-//-// This is a real bug that shipped in the first cut of the reservation layer,-// where the TTL was 2 minutes. The margin belongs to us, so pin it.-func TestReservationTTLOutlivesTheEdgeStockTTL(t *testing.T) {- const doEntryTTL = 10 * time.Minute- if reservationTTL <= doEntryTTL {- t.Fatalf("reservationTTL=%s does not exceed the DO's stock TTL (%s) — the edge would hand out terminated boxes",- reservationTTL, doEntryTTL)- }-}--// TargetStock bounds what the pool HOLDS, not what exists. A claimed box leaves-// the stock, so a target-only filler launches a replacement alongside every box-// doing real work — pool + live sandboxes grows without limit as load rises.-// That is how a 200-box pool alongside 300 live sandboxes put this account past-// its 1024GB regional ceiling and turned every create into ServiceQuotaExceeded.-//-// With a budget the pool becomes drainable: claims consume stock and refill-// waits for those boxes to be released.-func TestPoolStopsRefillingAtTheBoxBudget(t *testing.T) {- inUse := 0- p, f := testPool(t, PoolConfig{- TargetStock: 10,- MaxTotalBoxes: 12,- InUse: func() int { return inUse },- })-- // Nothing claimed: the pool fills to its target as usual.- for i := 0; i < 10; i++ {- if p.overBudget() {- t.Fatalf("refused to fill at stock=%d with nothing claimed", p.Depth())- }- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }- if p.Depth() != 10 {- t.Fatalf("stock = %d, want 10", p.Depth())- }-- // A burst claims eight. Stock drops to 2, and a target-only filler would- // launch eight replacements — 10 stock + 8 claimed = 18 boxes, half again- // over the budget of 12.- for i := 0; i < 8; i++ {- if _, ok := p.Claim(); !ok {- t.Fatalf("claim %d missed", i)- }- inUse++- }- if p.Depth() != 2 {- t.Fatalf("stock after 8 claims = %d, want 2", p.Depth())- }-- // Refill is allowed up to the budget, not up to the target: 8 claimed + 2- // stock = 10, so exactly 2 more boxes may be launched.- for i := 0; i < 2; i++ {- if p.overBudget() {- t.Fatalf("stopped refilling at %d claimed + %d committed, under the budget of 12", inUse, p.committed())- }- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne: %v", err)- }- }- // Now at the ceiling. This is the assertion that matters: the pool is 6 short- // of its target and must still refuse, because the missing boxes are alive as- // customer sandboxes rather than gone.- if total := p.committed() + inUse; total != 12 {- t.Fatalf("total = %d, want 12", total)- }- if !p.overBudget() {- t.Fatalf("pool kept refilling at the budget: %d claimed + %d committed, target %d — this is the overrun that exhausted the region",- inUse, p.committed(), 10)- }-- // As the burst drains, refill resumes.- inUse = 5- if p.overBudget() {- t.Fatalf("still refusing to refill at %d claimed + %d committed, under the budget of 12", inUse, p.committed())- }- if err := p.launchOne(context.Background()); err != nil {- t.Fatalf("launchOne after release: %v", err)- }- if f.runs == 0 {- t.Fatal("no launches recorded")- }-}--// A pool with no budget configured must behave exactly as before — cells that-// nobody has sized should not silently stop filling.-func TestPoolWithoutBudgetAlwaysRefills(t *testing.T) {- p, _ := testPool(t, PoolConfig{TargetStock: 3})- if p.overBudget() {- t.Fatal("unbudgeted pool refused to refill")- }-}--// Refusing to launch at the budget is not the same as standing down. Before the-// backoff, the filler re-evaluated the budget every LaunchInterval, so the-// instant any box was released it spent a RunMicrovm on a replacement and was at-// the ceiling again — tracking the budget exactly, and bidding for the same-// regional quota as the customer creates that had gone cold because the pool was-// drained. Measured on dev: 366 boxes manufactured in 30 minutes alongside 28-// creates rejected with "regional MicroVM quota exhausted".-//-// The observable difference is how often the loop asks. This counts that.-func TestAtBudgetTheFillerStandsDownInsteadOfProbingEveryTick(t *testing.T) {- var probes int64- const (- interval = time.Millisecond- delay = 150 * time.Millisecond- window = 750 * time.Millisecond- )- p, f := testPool(t, PoolConfig{- TargetStock: 50,- MaxTotalBoxes: 10,- LaunchInterval: interval,- RefillDelay: delay,- // Pinned at the ceiling for the whole window: the burst has not drained.- InUse: func() int { atomic.AddInt64(&probes, 1); return 10 },- })-- ctx, cancel := context.WithCancel(context.Background())- go p.Run(ctx)- time.Sleep(window)- cancel()-- got := atomic.LoadInt64(&probes)- // One probe per delay, so ~5 across the window. Without the backoff the loop- // evaluates the budget once per LaunchInterval — ~750, two orders of- // magnitude more, every one of them a candidate launch.- if max := int64(window/delay) + 3; got > max {- t.Fatalf("budget evaluated %d times in %s, want at most %d — the filler is still spinning at tick rate, which is what makes it race customer creates for the regional quota",- got, window, max)- }- if got == 0 {- t.Fatal("budget never evaluated — the filler stood down permanently and would not refill when the burst drains")- }- if runs, _, _ := f.counts(); runs != 0 {- t.Fatalf("launched %d box(es) while at the budget", runs)- }-}--// The stand-down must never shorten an existing pause. A budget backoff landing-// during a quota backoff would otherwise let the pool resume launching straight-// into a quota that has not recovered.-func TestStandDownNeverShortensAnExistingPause(t *testing.T) {- p, _ := testPool(t, PoolConfig{TargetStock: 1})-- p.suppressLaunches(time.Hour, errors.New("regional quota exhausted"))- p.standDown(time.Millisecond)-- if !p.launchSuppressed() {- t.Fatal("a short budget backoff cancelled a long quota backoff — the pool would relaunch into an exhausted quota")- }-}diff --git a/internal/awsvm/sizing_test.go b/internal/awsvm/sizing_test.godeleted file mode 100644index 0773b757..00000000--- a/internal/awsvm/sizing_test.go+++ /dev/null@@ -1,188 +0,0 @@-package awsvm--import (- "context"- "errors"- "sync"- "testing"-- "github.com/aws/aws-sdk-go-v2/aws"- "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"- mvtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"- "github.com/opensandbox/opensandbox/pkg/types"-)--// imageSpyAPI records which image each RunMicrovm asked for. Sizing is a-// property of the image here, so "did we launch the right image" IS "did the-// customer get the size they paid for" — there is nothing else to assert on.-type imageSpyAPI struct {- API- mu sync.Mutex- images []string- n int-}--func (f *imageSpyAPI) RunMicrovm(_ context.Context, in *lambdamicrovms.RunMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {- f.mu.Lock()- f.n++- id := "mvm-" + string(rune('a'+f.n-1))- f.images = append(f.images, aws.ToString(in.ImageIdentifier))- f.mu.Unlock()- return &lambdamicrovms.RunMicrovmOutput{- MicrovmId: aws.String(id),- Endpoint: aws.String(id + ".microvm.aws.dev"),- }, nil-}--func (f *imageSpyAPI) GetMicrovm(_ context.Context, in *lambdamicrovms.GetMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {- id := aws.ToString(in.MicrovmIdentifier)- return &lambdamicrovms.GetMicrovmOutput{- MicrovmId: aws.String(id),- Endpoint: aws.String(id + ".microvm.aws.dev"),- State: mvtypes.MicrovmStateRunning,- }, nil-}--func (f *imageSpyAPI) launched() []string {- f.mu.Lock()- defer f.mu.Unlock()- return append([]string(nil), f.images...)-}--func tieredManager(t *testing.T) (*Manager, *imageSpyAPI) {- t.Helper()- spy := &imageSpyAPI{}- c := NewClientWithAPI(spy, Config{- ImageIdentifier: "arn:default",- DefaultMemoryMB: 4096,- SizeImages: map[int]string{8192: "arn:8gb"},- })- return NewManager(c, t.TempDir()), spy-}--// Create and Get must report the SAME size, and it must be the delivered one.-//-// Create used to echo cfg.MemoryMB/cfg.CpuCount straight back while Track-// recorded deliveredSize, so a create asking for 8 GB answered "8192" and an-// immediate Get on the same sandbox answered "2048". Whichever number a caller-// happened to read became what it believed.-func TestCreateReportsDeliveredSizeAndAgreesWithGet(t *testing.T) {- m, _ := tieredManager(t)-- sb, err := m.Create(context.Background(), types.SandboxConfig{SandboxID: "sb-def"})- if err != nil {- t.Fatalf("Create: %v", err)- }- if sb.MemoryMB != 4096 {- t.Errorf("Create reported %dMB, want the delivered 4096", sb.MemoryMB)- }- got, err := m.Get(context.Background(), "sb-def")- if err != nil {- t.Fatalf("Get: %v", err)- }- if got.MemoryMB != sb.MemoryMB || got.CpuCount != sb.CpuCount {- t.Errorf("Get says %dMB/%dcpu but Create said %dMB/%dcpu — the two must never disagree",- got.MemoryMB, got.CpuCount, sb.MemoryMB, sb.CpuCount)- }-}--// A configured tier must launch ITS image, not the default one.-func TestCreateLaunchesTheTierImage(t *testing.T) {- m, spy := tieredManager(t)-- sb, err := m.Create(context.Background(), types.SandboxConfig{SandboxID: "sb-8g", MemoryMB: 8192})- if err != nil {- t.Fatalf("Create: %v", err)- }- if launched := spy.launched(); len(launched) != 1 || launched[0] != "arn:8gb" {- t.Fatalf("launched %v, want [arn:8gb] — a tier served from the default image is a silent downsize", launched)- }- if sb.MemoryMB != 8192 {- t.Errorf("Create reported %dMB for the 8 GB tier, want 8192", sb.MemoryMB)- }- if sb.CpuCount != 2 {- t.Errorf("CpuCount=%d for the 8 GB tier, want 2 to match the published tier table", sb.CpuCount)- }-}--// A tier with no image must be REFUSED, never quietly served from the default.-//-// This is the whole reason ImageForMemory returns a bool instead of defaulting:-// handing a 16 GB request a 4 GB box, and metering it at 4 GB, is a wrong-size-// delivery the customer has no way to detect.-func TestUnconfiguredTierIsRefusedNotDownsized(t *testing.T) {- m, spy := tieredManager(t)-- _, err := m.Create(context.Background(), types.SandboxConfig{SandboxID: "sb-16g", MemoryMB: 16384})- if err == nil {- t.Fatal("Create succeeded for an unconfigured tier — that means a downsized box was handed out")- }- if !errors.Is(err, ErrUnsupported) {- t.Errorf("Create returned %v, want ErrUnsupported so the API answers 501", err)- }- if launched := spy.launched(); len(launched) != 0 {- t.Errorf("launched %v for a refused tier — nothing should have been started", launched)- }-}--// Only the default tier may be served from warm stock. This is what stops the-// pool handing a big request a default-size box.-func TestOnlyTheDefaultTierIsPoolable(t *testing.T) {- cfg := Config{ImageIdentifier: "arn:default", DefaultMemoryMB: 4096, SizeImages: map[int]string{8192: "arn:8gb"}}- cfg.applyDefaults()-- if !cfg.IsDefaultTier(0) {- t.Error("unspecified size must be poolable — it is what the default create asks for")- }- if !cfg.IsDefaultTier(4096) {- t.Error("naming the default size explicitly must still be poolable")- }- if cfg.IsDefaultTier(8192) || cfg.IsDefaultTier(16384) {- t.Error("a non-default tier must miss the pool — warm stock is all one image")- }-}--// OwnedImages must cover every tier, or the orphan sweep treats tier boxes as-// another product's and never reclaims them.-func TestOwnedImagesCoversEveryTier(t *testing.T) {- cfg := Config{ImageIdentifier: "arn:default", SizeImages: map[int]string{8192: "arn:8gb", 1024: "arn:1gb"}}- owned := map[string]bool{}- for _, arn := range cfg.OwnedImages() {- owned[arn] = true- }- for _, want := range []string{"arn:default", "arn:8gb", "arn:1gb"} {- if !owned[want] {- t.Errorf("OwnedImages missing %s — orphans on that image would never be reclaimed", want)- }- }-}--// deliveredSize ignores the ask and reports what the resolved image provides.-func TestDeliveredSizeIgnoresTheRequest(t *testing.T) {- for _, tc := range []struct {- requestedMB, requestedCPU, deliveredMB, wantMB, wantCPU int- }{- {8192, 4, 4096, 4096, 1}, // asked above the tier it resolved to- {512, 1, 4096, 4096, 1}, // asked below- {0, 0, 4096, 4096, 1}, // unspecified- {8192, 2, 8192, 8192, 2}, // the 8 GB tier, honoured- {16384, 4, 16384, 16384, 4}, // the 16 GB tier, honoured- } {- mem, cpu := deliveredSize("sb-x", tc.requestedMB, tc.requestedCPU, tc.deliveredMB)- if mem != tc.wantMB || cpu != tc.wantCPU {- t.Errorf("deliveredSize(req %d/%d, delivered %d) = %d/%d; want %d/%d",- tc.requestedMB, tc.requestedCPU, tc.deliveredMB, mem, cpu, tc.wantMB, tc.wantCPU)- }- }-}--// A Manager with no client must still bind, not panic: several callers build-// one for bookkeeping only and never talk to AWS.-func TestTrackToleratesAClientlessManager(t *testing.T) {- m := NewManager(nil, t.TempDir())- mem, cpu := m.Track("sb-nil", &Box{ID: "mvm-nil"}, types.SandboxConfig{})- if mem != deliveredMicrovmMemoryMB || cpu != deliveredMicrovmCPUCount {- t.Errorf("Track on a clientless Manager gave %d/%d, want the baseline %d/%d",- mem, cpu, deliveredMicrovmMemoryMB, deliveredMicrovmCPUCount)- }-}diff --git a/internal/awsvm/workspace.go b/internal/awsvm/workspace.godeleted file mode 100644index 947106ea..00000000--- a/internal/awsvm/workspace.go+++ /dev/null@@ -1,178 +0,0 @@-package awsvm--import (- "context"- "fmt"- "io"- "os"- "path/filepath"- "time"-- "github.com/opensandbox/opensandbox/pkg/types"-)--// workspace.go — moving a sandbox's files in and out of blob storage.-//-// This is what hibernation means on this backend. AWS exposes Suspend/Resume-// but no way to export a snapshot (the SDK has 24 operations and none of them-// save state), so a sandbox that must outlive its host has to be captured as-// ordinary files. The 8h ceiling counts RUNNING and SUSPENDED together and is-// not adjustable, so "outlive its host" is every sandbox parked longer than-// that.-//-// Only /home/sandbox travels. The image is the system on this backend, so-// anything installed outside the workspace does not survive a restore — a-// narrower promise than a QEMU disk snapshot, and one worth stating plainly-// rather than discovering.--// workspaceDir is the only path that survives hibernation. It matches the-// agent's working directory (see deploy/microvm/Dockerfile).-const workspaceDir = "/home/sandbox"--// archivePath is where the tarball is staged inside the guest. /tmp is-// deliberately outside workspaceDir: including the archive in its own input-// would race the writer against the reader.-const archivePath = "/tmp/osb-workspace.tgz"--// exportTimeout bounds the in-guest tar. Generous because it scales with the-// customer's data, and the alternative to waiting is losing it.-const exportTimeout = 10 * time.Minute--// maxWorkspaceBytes caps what will be captured. Past this the export fails-// loudly rather than silently truncating: a restore that quietly drops half a-// customer's files is worse than a hibernate that refuses.-const maxWorkspaceBytes = 2 << 30 // 2 GiB--// ExportWorkspace archives the sandbox's workspace and returns it for upload,-// along with its size. The caller closes the reader.-//-// Two steps rather than streaming `tar czf -` straight out: Exec is one-shot-// and buffers its output, so piping a multi-gigabyte archive through it would-// hold the whole thing in the control plane's memory. Writing to a file inside-// the guest and streaming that back keeps memory flat.-func (m *Manager) ExportWorkspace(ctx context.Context, sandboxID string) (io.ReadCloser, int64, error) {- // The cancel is deliberately NOT deferred: the reader returned below is- // still streaming when this function returns, and cancelling here would- // kill it mid-read — the stream fails with "context canceled" on every- // archive large enough to still be in flight, which is every archive that- // matters. Ownership passes to the returned ReadCloser instead.- ctx, cancel := context.WithTimeout(ctx, exportTimeout)- failed := true- defer func() {- if failed {- cancel()- }- }()-- // -C so paths are relative: a restore must be able to land them in the same- // place without depending on the absolute layout of the machine that made- // the archive.- res, err := m.Exec(ctx, sandboxID, types.ProcessConfig{- Command: "sh",- Args: []string{"-c", fmt.Sprintf(- "rm -f %s && tar czf %s -C %s . && stat -c %%s %s",- archivePath, archivePath, workspaceDir, archivePath)},- })- if err != nil {- return nil, 0, fmt.Errorf("awsvm: export %s: tar: %w", sandboxID, err)- }- if res.ExitCode != 0 {- return nil, 0, fmt.Errorf("awsvm: export %s: tar exit %d: %s", sandboxID, res.ExitCode, trimOut(res.Stderr))- }-- var size int64- if _, err := fmt.Sscanf(trimOut(res.Stdout), "%d", &size); err != nil {- return nil, 0, fmt.Errorf("awsvm: export %s: unreadable archive size %q: %w", sandboxID, trimOut(res.Stdout), err)- }- if size > maxWorkspaceBytes {- return nil, 0, fmt.Errorf("awsvm: export %s: workspace archive is %d bytes, over the %d limit",- sandboxID, size, maxWorkspaceBytes)- }-- rc, _, err := m.ReadFileStream(ctx, sandboxID, archivePath)- if err != nil {- return nil, 0, fmt.Errorf("awsvm: export %s: read archive: %w", sandboxID, err)- }- failed = false- return &cancelOnClose{ReadCloser: rc, cancel: cancel}, size, nil-}--// cancelOnClose ties a context's lifetime to the stream it feeds, so the-// timeout still bounds the read but only expires when the caller is done.-type cancelOnClose struct {- io.ReadCloser- cancel context.CancelFunc-}--func (c *cancelOnClose) Close() error {- err := c.ReadCloser.Close()- c.cancel()- return err-}--// ImportWorkspace restores an archive produced by ExportWorkspace into a-// running sandbox.-//-// The unpack is additive rather than a wipe-and-replace: the target is a fresh-// box from the image, so its workspace holds the image's own scaffolding, and-// deleting that before unpacking would strip files the sandbox expects.-func (m *Manager) ImportWorkspace(ctx context.Context, sandboxID string, r io.Reader) error {- ctx, cancel := context.WithTimeout(ctx, exportTimeout)- defer cancel()-- // 0644, not 0600: the stream is written by the agent's file service while- // exec runs as the unprivileged sandbox user, so a mode only the writer can- // read makes the untar fail with "Cannot open: Permission denied" — after a- // full download, which is the most expensive possible place to discover it.- if _, err := m.WriteFileStream(ctx, sandboxID, archivePath, 0o644, r); err != nil {- return fmt.Errorf("awsvm: import %s: write archive: %w", sandboxID, err)- }- res, err := m.Exec(ctx, sandboxID, types.ProcessConfig{- Command: "sh",- // Cleanup is best-effort and must not affect the exit code: the archive- // is written by the agent's file service but exec runs as the- // unprivileged sandbox user, and /tmp is sticky — so the rm fails with- // "Operation not permitted" even though the restore itself succeeded.- // Letting that decide the result fails every wake after a working untar.- Args: []string{"-c", fmt.Sprintf("tar xzf %s -C %s && { rm -f %s 2>/dev/null || true; }",- archivePath, workspaceDir, archivePath)},- })- if err != nil {- return fmt.Errorf("awsvm: import %s: untar: %w", sandboxID, err)- }- if res.ExitCode != 0 {- return fmt.Errorf("awsvm: import %s: untar exit %d: %s", sandboxID, res.ExitCode, trimOut(res.Stderr))- }- return nil-}--// stageArchive spools a reader to a local temp file, because CheckpointStore-// uploads from a path rather than a stream. Returns the path and its size; the-// caller removes it.-func stageArchive(r io.Reader, dir string) (string, int64, error) {- f, err := os.CreateTemp(dir, "osb-hib-*.tgz")- if err != nil {- return "", 0, err- }- defer f.Close()- n, err := io.Copy(f, r)- if err != nil {- _ = os.Remove(f.Name())- return "", 0, err- }- return f.Name(), n, nil-}--// hibernationKey is the blob path for a sandbox's workspace archive. One key-// per sandbox: CreateHibernation supersedes the previous record and hands back-// the old key to delete, so storage stays bounded at one archive per sandbox.-func hibernationKey(sandboxID string) string {- return filepath.Join("hibernations", sandboxID+".tgz")-}--func trimOut(s string) string {- if len(s) > 400 {- return s[:400]- }- return s-}diff --git a/internal/awsvm/workspace_test.go b/internal/awsvm/workspace_test.godeleted file mode 100644index 7d162fc3..00000000--- a/internal/awsvm/workspace_test.go+++ /dev/null@@ -1,126 +0,0 @@-package awsvm--import (- "bytes"- "context"- "io"- "os"- "strings"- "testing"-)--// workspace_test.go — the archive path, which is the only thing standing-// between a hibernated sandbox and losing the customer's files.--// The archive must not live inside the directory it archives. Staging it in-// the workspace would make tar read a file it is concurrently writing, which-// produces a corrupt archive on exactly the large workspaces where corruption-// is least recoverable.-func TestArchiveIsStagedOutsideTheWorkspace(t *testing.T) {- if strings.HasPrefix(archivePath, workspaceDir) {- t.Fatalf("archive %q is inside the workspace %q — tar would read its own output",- archivePath, workspaceDir)- }-}--// The workspace path must match what the image actually gives the customer.-// Archiving the wrong directory restores an empty sandbox and reports success.-func TestWorkspaceDirMatchesTheImage(t *testing.T) {- if workspaceDir != "/home/sandbox" {- t.Fatalf("workspaceDir is %q; deploy/microvm/Dockerfile puts the customer in /home/sandbox", workspaceDir)- }-}--// One key per sandbox, and it must contain the sandbox id. A shared or-// colliding key would let one sandbox's wake restore another's files.-func TestHibernationKeyIsPerSandbox(t *testing.T) {- a, b := hibernationKey("sb-aaa"), hibernationKey("sb-bbb")- if a == b {- t.Fatalf("two sandboxes share the archive key %q", a)- }- if !strings.Contains(a, "sb-aaa") {- t.Fatalf("key %q does not identify its sandbox", a)- }- if hibernationKey("sb-aaa") != a {- t.Fatal("key is not stable across calls — a wake could not find its own archive")- }-}--// stageArchive spools to disk because the blob store uploads from a path. It-// must report the byte count it actually wrote: that number is persisted as the-// hibernation size and is how a truncated upload would be noticed.-func TestStageArchiveReportsWhatItWrote(t *testing.T) {- dir := t.TempDir()- payload := bytes.Repeat([]byte("x"), 4096)-- path, n, err := stageArchive(bytes.NewReader(payload), dir)- if err != nil {- t.Fatalf("stageArchive: %v", err)- }- defer os.Remove(path)-- if n != int64(len(payload)) {- t.Fatalf("reported %d bytes, wrote %d", n, len(payload))- }- got, err := os.ReadFile(path)- if err != nil {- t.Fatalf("read staged archive: %v", err)- }- if !bytes.Equal(got, payload) {- t.Fatalf("staged archive differs from input (%d vs %d bytes)", len(got), len(payload))- }-}--// A staging failure must not leave a partial file behind. The caller removes-// the path it is given, and on error there is no path to remove — so anything-// already written has to be cleaned up here or it leaks disk on every failure.-func TestStageArchiveCleansUpOnFailure(t *testing.T) {- dir := t.TempDir()-- _, _, err := stageArchive(failingReader{}, dir)- if err == nil {- t.Fatal("stageArchive succeeded on a failing reader")- }- entries, rErr := os.ReadDir(dir)- if rErr != nil {- t.Fatalf("read dir: %v", rErr)- }- if len(entries) != 0 {- t.Fatalf("left %d file(s) behind after a failed stage", len(entries))- }-}--type failingReader struct{}--func (failingReader) Read([]byte) (int, error) { return 0, errRead }--var errRead = &readErr{}--type readErr struct{}--func (*readErr) Error() string { return "read failed" }--// ExportWorkspace returns a stream that is still being read after the function-// returns. Deferring the context cancel there kills the read mid-flight — it-// fails with "context canceled" on exactly the archives big enough to still be-// in transit, which is every archive worth having. The cancel must travel with-// the stream and fire on Close.-func TestExportStreamOutlivesTheCallThatCreatedIt(t *testing.T) {- ctx, cancel := context.WithCancel(context.Background())- inner := io.NopCloser(strings.NewReader("payload"))- rc := &cancelOnClose{ReadCloser: inner, cancel: cancel}-- // Still readable after the creating scope would have returned.- if _, err := io.ReadAll(rc); err != nil {- t.Fatalf("stream unreadable before Close: %v", err)- }- if ctx.Err() != nil {- t.Fatal("context was cancelled while the stream was still open")- }- if err := rc.Close(); err != nil {- t.Fatalf("Close: %v", err)- }- if ctx.Err() == nil {- t.Fatal("Close did not release the context — the timeout would leak")- }-}