Skip to content

An open-source, faster Devin alternative

TypeScript

fix(storage,microvm,edge): stop three append-only leaks — hibernation archives, migration disks, and D1 telemetry"

Brian Reardone9a8cb017768
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 2a29e2d4..f6a857bb 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -43,6 +43,7 @@ import {
import { runAutumnMeter } from "./autumn_meter";
import { disableManagedBilling, enableManagedBilling } from "./model_billing";
import { runModelMeter } from "./model_meter";
+import { runRetentionSweep } from "./retention";
import * as secretStores from "./secret_stores";
import * as snapshots from "./snapshots";
import * as templates from "./templates";
@@ -4085,6 +4086,14 @@ export default {
ctx.waitUntil(
runPausedCapEnforcer(env).catch((err) => console.error("paused-cap: run failed", err)),
);
+ // Telemetry retention, also regardless of billing config. D1 caps a database
+ // at 10 GB with no way to raise it, and when events/usage_samples reach it
+ // EVERY insert fails — including the capacity heartbeat, which freezes
+ // cells.capacity_updated_at and takes every create in the region down with
+ // "no cells available with capacity". See retention.ts.
+ ctx.waitUntil(
+ runRetentionSweep(env).catch((err) => console.error("retention: run failed", err)),
+ );
if (!env.AUTUMN_SECRET_KEY) return;
ctx.waitUntil(
runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),
diff --git a/cloudflare-workers/api-edge/src/retention.ts b/cloudflare-workers/api-edge/src/retention.ts
new file mode 100644
index 00000000..56506e4d
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/retention.ts
@@ -0,0 +1,102 @@
+/**
+ * retention.ts — bounded deletion of append-only telemetry.
+ *
+ * D1 caps a database at 10 GB and there is no way to raise it. `events` and
+ * `usage_samples` are append-only and grow ~3.1M rows/day between them, so
+ * without this they reach the cap on their own schedule.
+ *
+ * What that looks like is not "the telemetry tables stop working". Every INSERT
+ * in the database fails at once, including the capacity heartbeat, so
+ * `cells.capacity_updated_at` freezes; the edge routes on that being fresher
+ * than 120s, so within two minutes every create in the region answers
+ * "no cells available with capacity" while the cells are perfectly healthy.
+ * In-place UPDATEs keep working, which is what makes it confusing: billing
+ * watermarks keep advancing while sandbox creation is completely down.
+ *
+ * That is exactly how prod fell over on 2026-08-17.
+ *
+ * The sweep runs on the existing five-minute cron and deletes a bounded slice
+ * per tick. Bounded rather than "delete everything older than the cutoff": a single
+ * unbounded DELETE across millions of rows is the kind of statement that times
+ * out, and a sweep that fails is a sweep that does nothing. At the default batch
+ * size it removes ~4x the ingest rate, so it converges and then idles.
+ */
+
+export interface RetentionEnv {
+ OPENCOMPUTER_DB: D1Database;
+ /** Days of telemetry to keep. Default 14. */
+ TELEMETRY_RETENTION_DAYS?: string;
+ /** Rows to delete per table per tick. Default 20000. */
+ TELEMETRY_RETENTION_BATCH?: string;
+}
+
+const DEFAULT_RETENTION_DAYS = 14;
+const DEFAULT_BATCH = 20_000;
+
+function intFromEnv(v: string | undefined, def: number): number {
+ const n = v ? parseInt(v, 10) : NaN;
+ return Number.isFinite(n) && n > 0 ? n : def;
+}
+
+/**
+ * runRetentionSweep deletes one bounded batch of aged rows from each telemetry
+ * table. Safe to call every tick; a no-op once the tables are inside retention.
+ */
+export async function runRetentionSweep(env: RetentionEnv): Promise<void> {
+ const days = intFromEnv(env.TELEMETRY_RETENTION_DAYS, DEFAULT_RETENTION_DAYS);
+ const batch = intFromEnv(env.TELEMETRY_RETENTION_BATCH, DEFAULT_BATCH);
+ const cutoffMs = Date.now() - days * 86_400_000;
+
+ // events carries no billing meaning — it is the admin/event feed — so the age
+ // cutoff is the only constraint.
+ await sweep(env, "events", "id", cutoffMs, batch);
+
+ // usage_samples DOES carry billing meaning: the Autumn meter reads it and
+ // advances orgs.autumn_usage_watermark past what it has charged for. Deleting
+ // a sample the meter has not read yet silently loses revenue, and nothing
+ // downstream would ever notice. So the cutoff is the EARLIER of the age
+ // cutoff and the least-advanced watermark across all orgs — never delete
+ // something no one has billed.
+ //
+ // Watermarks are stored in SECONDS while ts is milliseconds; conflating the
+ // two reads as 1970 and would make this delete everything.
+ const wm = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT MIN(autumn_usage_watermark) AS wm FROM orgs
+ WHERE autumn_usage_watermark IS NOT NULL AND autumn_usage_watermark > 0`,
+ ).first<{ wm: number | null }>();
+
+ let sampleCutoffMs = cutoffMs;
+ if (wm?.wm) {
+ sampleCutoffMs = Math.min(cutoffMs, wm.wm * 1000);
+ }
+ await sweep(env, "usage_samples", "rowid", sampleCutoffMs, batch);
+}
+
+/**
+ * sweep deletes up to `limit` rows older than `cutoffMs` from `table`.
+ *
+ * The subselect on a key column is deliberate: D1 does not support DELETE with
+ * a bare LIMIT, so bounding the work means naming the rows first.
+ */
+async function sweep(
+ env: RetentionEnv,
+ table: "events" | "usage_samples",
+ key: "id" | "rowid",
+ cutoffMs: number,
+ limit: number,
+): Promise<void> {
+ try {
+ const res = await env.OPENCOMPUTER_DB.prepare(
+ `DELETE FROM ${table} WHERE ${key} IN (
+ SELECT ${key} FROM ${table} WHERE ts < ?1 LIMIT ?2)`,
+ )
+ .bind(cutoffMs, limit)
+ .run();
+ const n = res.meta?.changes ?? 0;
+ if (n > 0) console.log(`retention: ${table} deleted ${n} rows older than ${new Date(cutoffMs).toISOString()}`);
+ } catch (err) {
+ // Never throw: this shares a tick with billing meters, and a retention
+ // failure must not take those down with it.
+ console.error(`retention: ${table} sweep failed`, err);
+ }
+}
diff --git a/cmd/microvm-harness/main.go b/cmd/microvm-harness/main.go
index 26cc464f..ecb0e457 100644
--- a/cmd/microvm-harness/main.go
+++ b/cmd/microvm-harness/main.go
@@ -37,8 +37,10 @@ import (
"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"
)
@@ -51,15 +53,17 @@ const (
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)")
- probe = flag.Bool("probe", false, "instead of exec, probe plain HTTP /healthz on the hook port to isolate proxy reachability from gRPC")
+ 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.
@@ -125,6 +129,29 @@ func main() {
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)
@@ -435,3 +462,237 @@ func trim(s string) string {
}
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/internal/api/hibernation_reclaim.go b/internal/api/hibernation_reclaim.go
new file mode 100644
index 00000000..0925b7dd
--- /dev/null
+++ b/internal/api/hibernation_reclaim.go
@@ -0,0 +1,175 @@
+package api
+
+import (
+ "context"
+ "log"
+ "strings"
+ "time"
+)
+
+// hibernation_reclaim.go — freeing hibernation archives nothing can wake.
+//
+// Hibernation uploads an archive per sandbox and, until this existed, exactly
+// one thing ever deleted one: CreateHibernation superseding a previous archive
+// for the same sandbox. Every other end-of-life freed nothing.
+//
+// The two that matter are both permanent:
+//
+// - a WAKE. MarkHibernationRestored stamps restored_at and stops. From that
+// instant GetActiveHibernation cannot match the row (it filters on
+// restored_at IS NULL), so the object is unreachable by every code path in
+// the system. It is not a recovery copy; it is garbage with a bill.
+// - a DESTROY. Nothing consults sandbox_hibernations when a sandbox dies, so
+// the archive outlives the sandbox indefinitely.
+//
+// Measured on prod 2026-08-17: ~11 TB unreachable against ~16 TB live, on a
+// bucket growing ~600 GB/day.
+//
+// The sweep runs out of band rather than deleting inline at the wake. A wake is
+// latency-critical and a blob delete is a network round-trip to object storage
+// that can fail; putting it on that path would trade a storage leak for a
+// slower, flakier wake. Deferring costs only the grace period.
+
+// hibernationReclaimInterval paces the sweep.
+const hibernationReclaimInterval = 5 * time.Minute
+
+// hibernationReclaimGrace is how long an archive is left alone before it is
+// considered dead, measured from hibernated_at.
+//
+// The hazard this buys off is an upload still in flight for a row the sweep is
+// about to delete underneath: the archive is written asynchronously, so a row
+// can look dead by status while its bytes are still being written. An hour is
+// far past any upload that is going to succeed (the largest measured, 500 MB,
+// took ~2m30s) while still reclaiming same-day.
+const hibernationReclaimGrace = time.Hour
+
+// hibernationReclaimBatch bounds deletions per tick. Each is a round-trip to
+// object storage, so this is a rate limit, not a correctness bound — the sweep
+// resumes wherever it left off. At this size the backlog drains in hours while
+// staying well clear of the storage provider's request limits.
+const hibernationReclaimBatch = 200
+
+// StartHibernationReclaim runs the sweep for the life of the process.
+func (s *Server) StartHibernationReclaim(ctx context.Context) {
+ if s == nil || s.store == nil || s.checkpointStore == nil {
+ return
+ }
+ grace := time.Duration(envInt("OPENSANDBOX_HIBERNATION_RECLAIM_GRACE_SECONDS",
+ int(hibernationReclaimGrace/time.Second))) * time.Second
+ batch := envInt("OPENSANDBOX_HIBERNATION_RECLAIM_BATCH", hibernationReclaimBatch)
+
+ // Batch 0 is the off switch, and it has to be expressible. Coercing a zero
+ // up to a default is how "disabled" quietly becomes "enabled" — if this
+ // sweep ever starts deleting something it should not, an operator needs a
+ // way to stop it that does not require a new build.
+ if batch == 0 {
+ log.Printf("api: hibernation reclaim DISABLED (OPENSANDBOX_HIBERNATION_RECLAIM_BATCH=0)")
+ return
+ }
+
+ go func() {
+ t := time.NewTicker(hibernationReclaimInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ s.reclaimHibernationBlobs(ctx, grace, batch)
+ }
+ }
+ }()
+ log.Printf("api: hibernation reclaim started (grace=%s, batch=%d/%s)",
+ grace, batch, hibernationReclaimInterval)
+}
+
+// reclaimHibernationBlobs deletes one bounded batch of dead archives.
+func (s *Server) reclaimHibernationBlobs(ctx context.Context, grace time.Duration, batch int) {
+ rows, err := s.store.ListReclaimableHibernations(ctx, grace, batch)
+ if err != nil {
+ log.Printf("api: hibernation reclaim query failed: %v", err)
+ return
+ }
+ if len(rows) == 0 {
+ return
+ }
+
+ var freed, deleted, skipped int64
+ byReason := map[string]int{}
+ for _, r := range rows {
+ if ctx.Err() != nil {
+ return
+ }
+ if !deletableBlobKey(r.HibernationKey) {
+ // Nothing to delete in object storage, but the row must still leave
+ // the queue or the sweep re-reads it every tick forever.
+ if err := s.store.MarkHibernationBlobDeleted(ctx, r.ID); err != nil {
+ log.Printf("api: hibernation reclaim: mark %s: %v", r.SandboxID, err)
+ }
+ skipped++
+ continue
+ }
+
+ delCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ err := s.checkpointStore.Delete(delCtx, r.HibernationKey)
+ cancel()
+ if err != nil {
+ // Leave blob_deleted_at unset so the next tick retries. A delete
+ // that failed must not be recorded as done — that is precisely how
+ // an object gets stranded with no record that it still exists.
+ log.Printf("api: hibernation reclaim: delete %s (%s): %v", r.HibernationKey, r.Reason, err)
+ continue
+ }
+ if err := s.store.MarkHibernationBlobDeleted(ctx, r.ID); err != nil {
+ // The object is already gone; failing to stamp only costs a
+ // duplicate delete next tick, which object stores treat as success.
+ log.Printf("api: hibernation reclaim: mark %s deleted: %v", r.SandboxID, err)
+ }
+ deleted++
+ freed += r.SizeBytes
+ byReason[r.Reason]++
+ }
+
+ if deleted > 0 || skipped > 0 {
+ log.Printf("api: hibernation reclaim freed %d archive(s), %d MB %v (%d keyless)",
+ deleted, freed>>20, byReason, skipped)
+ }
+}
+
+// checkpointObjectSuffixes are the object names a USER CHECKPOINT is made of.
+//
+// Hibernation archives and customer checkpoints share the checkpoints/ prefix:
+//
+// hibernation archive checkpoints/<sandbox>/<epoch>.tar.zst
+// user checkpoint checkpoints/<sandbox>/<uuid>/rootfs.tar.zst
+//
+// so prefix alone cannot tell them apart. The leaf name can.
+var checkpointObjectSuffixes = []string{"/rootfs.tar.zst", "/workspace.tar.zst"}
+
+// deletableBlobKey reports whether a hibernation key names an object this sweep
+// is allowed to delete.
+//
+// Two kinds of key are not deletable objects at all: "local://" marks an
+// archive kept on the worker's own disk, which no central sweep can or should
+// touch, and an empty key belongs to a hibernation that failed before it ever
+// named one. Handing either to Delete would at best error every tick and at
+// worst address the wrong thing.
+//
+// The third check is the one that matters. This sweep only ever reads
+// hibernation_key, so on today's code it cannot see a checkpoint — but "the
+// query only returns hibernation rows" is an argument about the caller, and
+// customer checkpoints are not something to protect with an argument. A
+// hibernation archive is a single timestamped object and never carries these
+// leaf names, so refusing them costs nothing and makes deleting a customer
+// checkpoint structurally impossible rather than merely unlikely.
+func deletableBlobKey(key string) bool {
+ if key == "" || strings.HasPrefix(key, "local://") {
+ return false
+ }
+ for _, suffix := range checkpointObjectSuffixes {
+ if strings.HasSuffix(key, suffix) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/api/hibernation_reclaim_test.go b/internal/api/hibernation_reclaim_test.go
new file mode 100644
index 00000000..bca836c9
--- /dev/null
+++ b/internal/api/hibernation_reclaim_test.go
@@ -0,0 +1,66 @@
+package api
+
+import "testing"
+
+// hibernation_reclaim_test.go — the guards standing between the reclaim sweep
+// and customer data.
+//
+// This sweep deletes objects from blob storage permanently. The tests that
+// matter here are not "does it delete things" but "what will it refuse to
+// delete", so they are written as refusals.
+
+// The reclaim sweep must never delete a user checkpoint. Hibernation archives
+// and customer checkpoints share the checkpoints/ prefix and are told apart
+// only by their leaf name:
+//
+// hibernation archive checkpoints/<sandbox>/<epoch>.tar.zst
+// user checkpoint checkpoints/<sandbox>/<uuid>/rootfs.tar.zst
+//
+// The sweep reads hibernation_key and so should never see a checkpoint at all,
+// but "the query is right" is a property of the caller. This is the property of
+// the deleter.
+func TestReclaimRefusesUserCheckpointObjects(t *testing.T) {
+ checkpoints := []string{
+ "checkpoints/sb-00311f36/cf4024d5-25ea-4ddb-a646-ef8448aea0db/rootfs.tar.zst",
+ "checkpoints/sb-00311f36/cf4024d5-25ea-4ddb-a646-ef8448aea0db/workspace.tar.zst",
+ "checkpoints/sb-build-9516bc9e/a3cc86f0-3aea-429a-a7f9-417824f8c337/rootfs.tar.zst",
+ }
+ for _, key := range checkpoints {
+ if deletableBlobKey(key) {
+ t.Errorf("sweep would delete the user checkpoint %q", key)
+ }
+ }
+}
+
+// The archives the sweep exists to free must actually be deletable, or the
+// guard above has quietly turned the whole thing into a no-op while still
+// logging success.
+func TestReclaimAcceptsHibernationArchives(t *testing.T) {
+ archives := []string{
+ "checkpoints/sb-c25159be/1755400000.tar.zst",
+ "hibernations/sb-d064ceb0.tgz",
+ }
+ for _, key := range archives {
+ if !deletableBlobKey(key) {
+ t.Errorf("sweep refuses the hibernation archive %q — nothing would ever be freed", key)
+ }
+ }
+}
+
+// A "local://" key names an archive on a worker's own disk. The control plane
+// cannot reach it, and handing it to the blob store would address something
+// else entirely or error on every tick forever.
+func TestReclaimRefusesLocalArchives(t *testing.T) {
+ if deletableBlobKey("local:///data/hibernations/sb-abc.tar.zst") {
+ t.Fatal("sweep would hand a worker-local path to the blob store")
+ }
+}
+
+// An empty key belongs to a hibernation that failed before it named an object.
+// There is nothing to delete, and an empty key passed through to a bucket
+// delete is an unpredictable request, not a no-op.
+func TestReclaimRefusesEmptyKey(t *testing.T) {
+ if deletableBlobKey("") {
+ t.Fatal("sweep would issue a delete for an empty key")
+ }
+}
diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.go
index 4929d758..de04c353 100644
--- a/internal/api/microvm_backend.go
+++ b/internal/api/microvm_backend.go
@@ -107,15 +107,45 @@ func newMicrovmBackend(ctx context.Context) (*microvmBackend, error) {
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"
client := awsvm.NewClient(awsCfg, awsvm.Config{
- Region: region,
- ImageIdentifier: image,
- ExecutionRoleArn: os.Getenv("OPENSANDBOX_MICROVM_EXECUTION_ROLE_ARN"),
- // Idle-suspend stays off for pooled stock: a box that suspends itself
- // while waiting turns the next claim into a ResumeMicrovm, which is
- // rate-limited at 5/s — exactly the cost the pool exists to avoid.
- AutoResume: false,
+ Region: region,
+ ImageIdentifier: image,
+ ExecutionRoleArn: os.Getenv("OPENSANDBOX_MICROVM_EXECUTION_ROLE_ARN"),
+ MaxIdleDurationSeconds: int32(idleSec),
+ SuspendedDurationSeconds: int32(suspendedSec),
+ AutoResume: autoResume,
})
+ log.Printf("microvm: idle policy — suspend after %ds idle, terminate after %ds suspended, auto-resume=%v",
+ idleSec, suspendedSec, autoResume)
pool := awsvm.NewPool(client, awsvm.PoolConfig{
TargetStock: envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20),
@@ -293,9 +323,17 @@ func (b *microvmBackend) reconcileOnce(ctx context.Context, store *db.Store) {
if !ok {
continue
}
- // Already tracked and healthy — nothing to do. Skipping avoids a
+ // Already tracked AND still alive — nothing to do. Skipping avoids a
// GetMicrovm per sandbox per tick once the map is warm.
- if _, err := b.manager.Get(ctx, r.SandboxID); err == nil {
+ //
+ // 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)
diff --git a/internal/api/microvm_hibernation.go b/internal/api/microvm_hibernation.go
new file mode 100644
index 00000000..07874c16
--- /dev/null
+++ b/internal/api/microvm_hibernation.go
@@ -0,0 +1,109 @@
+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.go
new file mode 100644
index 00000000..2a88183b
--- /dev/null
+++ b/internal/api/microvm_hibernation_test.go
@@ -0,0 +1,30 @@
+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/router.go b/internal/api/router.go
index fc5ad096..64c6cbfe 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -825,6 +825,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// local SQLite; without this half nothing ever reads it, and the
// sandboxes run free while every log line says billing is working.
mvm.StartEventPublisher(context.Background(), s.sandboxDBs, s.redisClient, s.cellID, s.store)
+ // Release suspended boxes once their archive is durable. Without this a
+ // hibernation holds regional memory quota — the ceiling on warm-pool
+ // depth — for the whole life of the box rather than the 10 minutes it
+ // is actually useful as a fast-wake cache.
+ mvm.StartHibernationExpiry(context.Background(), s.store)
// Capacity, but only when no registry-backed reporter is publishing it
// already — two writers on one stream would alternate between MicroVM
// depth and worker counts, flapping the cell in and out of the edge's
@@ -848,6 +853,12 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.registerBackend(wb)
}
+ // Free hibernation archives no wake can reach. Deliberately outside the
+ // backend blocks above: this is about blobs, not runtimes, and the archives
+ // that piled up were written by the QEMU path. Gating it on a backend would
+ // have left the leak running on the cells that caused it.
+ s.StartHibernationReclaim(context.Background())
+
return s
}
diff --git a/internal/awsvm/manager.go b/internal/awsvm/manager.go
index 8f4d591a..8097eabf 100644
--- a/internal/awsvm/manager.go
+++ b/internal/awsvm/manager.go
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"log"
+ "os"
"sync"
"time"
@@ -205,9 +206,15 @@ func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
}, nil
}
-// statusFor maps MicroVM lifecycle onto our sandbox status. SUSPENDED reads as
-// hibernated: state is preserved and auto-resume brings it back on demand,
-// which is exactly our paused-hibernation contract.
+// 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:
@@ -454,34 +461,130 @@ func (m *Manager) ContainerAddr(ctx context.Context, sandboxID string, port int)
// ── Hibernation ─────────────────────────────────────────────────────────────
-// Hibernate suspends the MicroVM. AWS snapshots memory and disk itself, so
-// there is no checkpoint to upload and no key to hand back — which is why
-// SizeBytes is 0 and the store argument is ignored.
-func (m *Manager) Hibernate(ctx context.Context, sandboxID string, _ *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
+// 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 err := m.client.Suspend(ctx, e.microvmID); err != nil {
+ 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
}
- return &sandbox.HibernateResult{SandboxID: sandboxID, HibernationKey: e.microvmID}, nil
+ 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 resumes a suspended MicroVM. Callers that are about to send a request
-// could skip this and let auto-resume cover it, but waking explicitly keeps the
-// control plane's state machine honest about when the box became RUNNING.
-func (m *Manager) Wake(ctx context.Context, sandboxID string, _ string, _ *storage.CheckpointStore, _ int) (*types.Sandbox, error) {
- e, err := m.lookup(sandboxID)
+// 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, err
+ return nil, fmt.Errorf("awsvm: wake %s: download archive: %w", sandboxID, err)
}
- if err := m.client.Resume(ctx, e.microvmID); err != nil {
+ 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, Template: e.template, Status: types.SandboxStatusRunning,
- StartedAt: e.startedAt, CpuCount: e.cpuCount, MemoryMB: e.memoryMB,
+ ID: sandboxID, Status: types.SandboxStatusRunning, StartedAt: ready.StartedAt,
+ CpuCount: cfg.CpuCount, MemoryMB: cfg.MemoryMB,
}, nil
}
@@ -621,3 +724,19 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
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)
+}
diff --git a/internal/awsvm/manager_status_test.go b/internal/awsvm/manager_status_test.go
new file mode 100644
index 00000000..4207e0e7
--- /dev/null
+++ b/internal/awsvm/manager_status_test.go
@@ -0,0 +1,37 @@
+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/workspace.go b/internal/awsvm/workspace.go
new file mode 100644
index 00000000..947106ea
--- /dev/null
+++ b/internal/awsvm/workspace.go
@@ -0,0 +1,178 @@
+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.go
new file mode 100644
index 00000000..7d162fc3
--- /dev/null
+++ b/internal/awsvm/workspace_test.go
@@ -0,0 +1,126 @@
+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")
+ }
+}
diff --git a/internal/db/hibernation_reclaim_test.go b/internal/db/hibernation_reclaim_test.go
new file mode 100644
index 00000000..2e75a7f4
--- /dev/null
+++ b/internal/db/hibernation_reclaim_test.go
@@ -0,0 +1,50 @@
+package db
+
+import "testing"
+
+// The reclaim query decides which sandboxes are dead enough that their
+// hibernation archive can be deleted, and it does so with its own hardcoded
+// status list because the predicate has to run inside SQL. Two lists meaning
+// the same thing is how they drift.
+//
+// Drift in either direction costs something real:
+//
+// - a status terminal here but missing from reclaimTerminalStatuses leaks
+// archives forever, which is the bug this whole path exists to fix;
+// - a status in reclaimTerminalStatuses that is NOT terminal deletes the
+// archive of a sandbox someone can still wake.
+func TestReclaimTerminalStatusesMatchIsTerminal(t *testing.T) {
+ for _, status := range reclaimTerminalStatuses {
+ if !isTerminalSessionStatus(status) {
+ t.Errorf("reclaimTerminalStatuses has %q, which isTerminalSessionStatus says is NOT terminal — "+
+ "the sweep would delete the archive of a wakeable sandbox", status)
+ }
+ }
+
+ // And the other direction: every status the codebase calls terminal must be
+ // reclaimable, or archives pile up under a status nobody thought to add.
+ known := []string{"stopped", "error", "failed", "terminated", "running", "hibernated", "paused", "pooled"}
+ inReclaim := make(map[string]bool, len(reclaimTerminalStatuses))
+ for _, s := range reclaimTerminalStatuses {
+ inReclaim[s] = true
+ }
+ for _, status := range known {
+ if isTerminalSessionStatus(status) && !inReclaim[status] {
+ t.Errorf("%q is terminal but missing from reclaimTerminalStatuses — its archives leak forever", status)
+ }
+ }
+}
+
+// The statuses a sandbox can still be woken from must never appear in the
+// reclaim list. Spelled out separately from the pinning test above because this
+// is the invariant a reader needs to see stated, not derived: these are the
+// sandboxes whose archive is load-bearing.
+func TestWakeableStatusesAreNeverReclaimed(t *testing.T) {
+ for _, status := range []string{"hibernated", "paused", "running", "pooled", "migrating"} {
+ for _, r := range reclaimTerminalStatuses {
+ if r == status {
+ t.Fatalf("%q is in reclaimTerminalStatuses — waking that sandbox would find its archive deleted", status)
+ }
+ }
+ }
+}
diff --git a/internal/db/migrations/055_hibernation_blob_reclaim.down.sql b/internal/db/migrations/055_hibernation_blob_reclaim.down.sql
new file mode 100644
index 00000000..0d1ee4f7
--- /dev/null
+++ b/internal/db/migrations/055_hibernation_blob_reclaim.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS idx_hibernations_reclaimable;
+ALTER TABLE sandbox_hibernations DROP COLUMN IF EXISTS blob_deleted_at;
diff --git a/internal/db/migrations/055_hibernation_blob_reclaim.up.sql b/internal/db/migrations/055_hibernation_blob_reclaim.up.sql
new file mode 100644
index 00000000..cefa0410
--- /dev/null
+++ b/internal/db/migrations/055_hibernation_blob_reclaim.up.sql
@@ -0,0 +1,37 @@
+-- Reclaim for hibernation archives.
+--
+-- Until now the only thing that ever freed a hibernation blob was SUPERSEDE:
+-- CreateHibernation expires the previous row for the same sandbox and hands its
+-- key back to be deleted. Every other way a hibernation ends its useful life
+-- freed nothing.
+--
+-- Two of those matter, and both are permanent leaks:
+--
+-- * A WAKE. MarkHibernationRestored stamps restored_at and stops there. The
+-- archive is then unreachable — GetActiveHibernation only matches rows with
+-- restored_at IS NULL — so it is not a recovery copy, it is garbage that no
+-- code path can read.
+--
+-- * A DESTROY. Nothing looks at hibernations when a sandbox dies, so an
+-- archive outlives the sandbox it belongs to indefinitely.
+--
+-- On prod (2026-08-17) that was ~11 TB of unreachable archives against ~16 TB
+-- genuinely live, on a bucket growing ~600 GB/day.
+--
+-- blob_deleted_at is the reclaim watermark. It records that the object is gone
+-- from blob storage, which is what makes the sweep idempotent and resumable: a
+-- sweep that dies halfway re-runs without re-deleting, and a delete that fails
+-- is simply retried on the next tick. It is deliberately separate from
+-- expired_at — expired_at is a statement about the RECORD (this archive no
+-- longer represents the sandbox), blob_deleted_at is a statement about the
+-- OBJECT (the bytes are gone). Conflating them would make a failed delete
+-- indistinguishable from a completed one.
+ALTER TABLE sandbox_hibernations ADD COLUMN IF NOT EXISTS blob_deleted_at timestamptz;
+
+-- The sweep scans for un-reclaimed rows and nothing else, so the index carries
+-- only those. It empties itself as the backlog drains: once a row is reclaimed
+-- it leaves the index for good, which keeps this small forever rather than
+-- growing with the table.
+CREATE INDEX IF NOT EXISTS idx_hibernations_reclaimable
+ ON sandbox_hibernations (hibernated_at)
+ WHERE blob_deleted_at IS NULL;
diff --git a/internal/db/store.go b/internal/db/store.go
index 2222497b..3c06b982 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -202,6 +202,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{52, "migrations/052_paused_hibernation_mode.up.sql"},
{53, "migrations/053_default_org_concurrency_50.up.sql"},
{54, "migrations/054_sandbox_pool.up.sql"},
+ {55, "migrations/055_hibernation_blob_reclaim.up.sql"},
}
for _, m := range migrations {
@@ -1935,6 +1936,14 @@ func (s *Store) GetActiveHibernation(ctx context.Context, sandboxID string) (*Sa
}
// MarkHibernationRestored marks the active hibernation for a sandbox as restored.
+//
+// This does not delete the archive, and deliberately so: the wake has just
+// finished and the sandbox is live, so the blob delete does not belong on the
+// wake's critical path. The row becomes reclaimable instead and the sweep in
+// internal/api/hibernation_reclaim.go frees the object out of band. Note that
+// from this moment the archive is already unreachable — GetActiveHibernation
+// matches only restored_at IS NULL — so nothing is keeping it alive but the
+// sweep's grace period.
func (s *Store) MarkHibernationRestored(ctx context.Context, sandboxID string) error {
_, err := s.pool.Exec(ctx,
`UPDATE sandbox_hibernations SET restored_at = now()
@@ -1943,6 +1952,129 @@ func (s *Store) MarkHibernationRestored(ctx context.Context, sandboxID string) e
return err
}
+// ReclaimableHibernation is a hibernation archive that no wake can reach,
+// queued for deletion from blob storage.
+type ReclaimableHibernation struct {
+ ID uuid.UUID
+ SandboxID string
+ HibernationKey string
+ SizeBytes int64
+ // Reason is why this archive is dead, for the sweep's log. Operators
+ // reading "reclaimed 4000 archives" need to know which leak produced them.
+ Reason string
+}
+
+// reclaimTerminalStatuses lists the session statuses that mean a sandbox is
+// gone for good, so its archive can never be woken into anything.
+//
+// Kept as an explicit allow-list rather than "anything that is not hibernated":
+// this drives deletion, and an unrecognised status must fall through to "leave
+// it alone", not to "delete it". A sandbox that is paused, migrating, or in
+// some status added after this was written keeps its archive.
+//
+// TestReclaimTerminalStatusesMatchIsTerminal pins this against
+// isTerminalSessionStatus so the two cannot drift apart.
+var reclaimTerminalStatuses = []string{"stopped", "error", "failed", "terminated"}
+
+// ListReclaimableHibernations returns archives that are safe to delete from
+// blob storage, oldest first, bounded by limit.
+//
+// Three ways an archive dies, and none of them freed anything before this:
+//
+// - restored: a wake consumed it. GetActiveHibernation filters on
+// restored_at IS NULL, so the object is already unreachable by every code
+// path — it is not a recovery copy.
+// - expired: superseded by a newer hibernation. CreateHibernation hands the
+// old key back for an inline delete, but that delete is best-effort and
+// silent on failure, so this catches whatever it dropped.
+// - orphaned: the sandbox reached a terminal status, or its session row is
+// gone entirely. Nothing will ever wake it.
+//
+// The grace period is the safety margin. It is measured from hibernated_at
+// rather than from the event that killed the archive, because the risk being
+// bought off is an upload still in flight for a row this sweep is about to
+// delete underneath. Anything younger than the grace is left for a later tick.
+//
+// What is deliberately NOT selected: a row that is unrestored, unexpired, and
+// belongs to a live hibernated sandbox. That is the set a wake can still use,
+// and it is the whole reason this query is an allow-list of dead states rather
+// than a deny-list of live ones.
+func (s *Store) ListReclaimableHibernations(ctx context.Context, grace time.Duration, limit int) ([]ReclaimableHibernation, error) {
+ if limit <= 0 {
+ limit = 500
+ }
+ cutoff := time.Now().Add(-grace)
+
+ rows, err := s.pool.Query(ctx,
+ `SELECT h.id, h.sandbox_id, h.hibernation_key, h.size_bytes,
+ CASE
+ WHEN h.restored_at IS NOT NULL THEN 'restored'
+ WHEN h.expired_at IS NOT NULL THEN 'superseded'
+ WHEN s.sandbox_id IS NULL THEN 'orphaned'
+ ELSE 'terminal'
+ END AS reason
+ FROM sandbox_hibernations h
+ LEFT JOIN sandbox_sessions s ON s.sandbox_id = h.sandbox_id
+ WHERE h.blob_deleted_at IS NULL
+ AND h.hibernated_at < $1
+ AND (
+ h.restored_at IS NOT NULL
+ OR h.expired_at IS NOT NULL
+ OR s.sandbox_id IS NULL
+ OR s.status = ANY($2)
+ )
+ ORDER BY h.hibernated_at
+ LIMIT $3`,
+ cutoff, reclaimTerminalStatuses, limit)
+ if err != nil {
+ return nil, fmt.Errorf("list reclaimable hibernations: %w", err)
+ }
+ defer rows.Close()
+
+ var out []ReclaimableHibernation
+ for rows.Next() {
+ var r ReclaimableHibernation
+ if err := rows.Scan(&r.ID, &r.SandboxID, &r.HibernationKey, &r.SizeBytes, &r.Reason); err != nil {
+ return nil, fmt.Errorf("scan reclaimable hibernation: %w", err)
+ }
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
+
+// MarkHibernationBlobDeleted records that the archive is gone from blob
+// storage, which takes the row out of the sweep for good.
+//
+// Only ever called after a successful delete. Stamping it optimistically would
+// make a failed delete indistinguishable from a completed one and strand the
+// object forever — exactly the leak this whole path exists to fix.
+func (s *Store) MarkHibernationBlobDeleted(ctx context.Context, id uuid.UUID) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_hibernations SET blob_deleted_at = now() WHERE id = $1`, id)
+ return err
+}
+
+// CountReclaimableHibernations reports how much is still queued for reclaim, so
+// the sweep can log a backlog that shrinks instead of a rate with no
+// denominator.
+func (s *Store) CountReclaimableHibernations(ctx context.Context, grace time.Duration) (count int64, bytes int64, err error) {
+ cutoff := time.Now().Add(-grace)
+ err = s.pool.QueryRow(ctx,
+ `SELECT count(*), COALESCE(SUM(h.size_bytes), 0)
+ FROM sandbox_hibernations h
+ LEFT JOIN sandbox_sessions s ON s.sandbox_id = h.sandbox_id
+ WHERE h.blob_deleted_at IS NULL
+ AND h.hibernated_at < $1
+ AND (
+ h.restored_at IS NOT NULL
+ OR h.expired_at IS NOT NULL
+ OR s.sandbox_id IS NULL
+ OR s.status = ANY($2)
+ )`,
+ cutoff, reclaimTerminalStatuses).Scan(&count, &bytes)
+ return count, bytes, err
+}
+
// MarkHibernationUploaded records that the async S3 archive upload completed
// for a specific hibernation_key. Matches by key (not sandbox_id) because a
// sandbox can have multiple hibernation rows in flight when hibernate→wake→
@@ -3609,3 +3741,65 @@ func (s *Store) UpdateAgentSubscriptionFromStripe(
)
return err
}
+
+// RetirableHibernation is a suspended sandbox whose host can be released.
+type RetirableHibernation struct {
+ SandboxID string
+ WorkerID string
+ UploadedAt *time.Time
+}
+
+// ListRetirableHibernations returns hibernated sandboxes whose archive is
+// safely uploaded and whose dwell has elapsed, so their host can be terminated.
+//
+// The uploaded_at IS NOT NULL condition is the safety of the whole scheme, not
+// an optimization. Between hibernating and the upload landing, the suspended
+// box is the ONLY copy of that sandbox — the blob is a partial object nothing
+// can restore from. Terminating on a timer alone would destroy customer data
+// for any workspace slower to upload than the dwell, and the bigger the
+// workspace the likelier it is to lose it.
+//
+// Deliberately no timeout on that condition: a stuck upload holds its box
+// indefinitely, which costs quota and is strictly preferable to the alternative.
+func (s *Store) ListRetirableHibernations(ctx context.Context, prefixes []string, hibernatedBefore time.Time) ([]RetirableHibernation, error) {
+ if len(prefixes) == 0 {
+ return nil, nil
+ }
+ rows, err := s.pool.Query(ctx,
+ `SELECT ss.sandbox_id, ss.worker_id, sh.uploaded_at
+ FROM sandbox_sessions ss
+ JOIN sandbox_hibernations sh ON sh.sandbox_id = ss.sandbox_id
+ WHERE ss.worker_id LIKE ANY($1)
+ AND ss.status = 'hibernated'
+ AND coalesce(ss.hibernation_mode, '') <> 'deep'
+ AND sh.expired_at IS NULL
+ AND sh.restored_at IS NULL
+ AND sh.uploaded_at IS NOT NULL
+ AND sh.hibernated_at < $2
+ ORDER BY sh.hibernated_at`,
+ likePatterns(prefixes), hibernatedBefore)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var out []RetirableHibernation
+ for rows.Next() {
+ var r RetirableHibernation
+ if err := rows.Scan(&r.SandboxID, &r.WorkerID, &r.UploadedAt); err != nil {
+ return nil, err
+ }
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
+
+// SetHibernationMode records which tier a hibernated sandbox is in: 'paused'
+// while a suspended host still backs it, 'deep' once only the archive remains.
+// Wake reads this to know whether a resume is even possible.
+func (s *Store) SetHibernationMode(ctx context.Context, sandboxID, mode string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET hibernation_mode = $1 WHERE sandbox_id = $2`,
+ mode, sandboxID)
+ return err
+}
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index e33e8d74..32ded66d 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -328,6 +328,17 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco
log.Printf("qemu: live migration %s → %s complete (%dms)",
sandboxID, incomingAddr, time.Since(t0).Milliseconds())
+ // The pre-copied disks have served their purpose: the destination pulled
+ // them during PrepareMigrationIncoming and the VM is now running there.
+ // Nothing reads them again.
+ //
+ // Every cleanup path in this file used to be os.RemoveAll on local staging
+ // dirs, so the uploaded copies were never freed at all — 2.6 TB of them on
+ // prod by 2026-08-17. Keys are per-sandbox rather than per-migration, so a
+ // re-migration overwrites and the leak is bounded at one disk set per
+ // sandbox ever migrated, but it never returns to zero on its own.
+ mc.deleteMigrationBlobs(sandboxID)
+
// Source cleanup: quit QEMU, release network
_ = vm.qmp.Quit()
vm.qmp.Close()
@@ -897,6 +908,42 @@ func (m *Manager) LiveMigrate(ctx context.Context, sandboxID, incomingAddr strin
}
// uploadFile uploads a local file to S3.
+// migrationBlobKeys lists every object a pre-copy can produce for a sandbox.
+//
+// Built from the sandbox id rather than threaded through from the upload
+// because there are two pre-copy shapes — the merged single-disk path and the
+// split rootfs+workspace path, the latter compressed — and a cleanup that only
+// knew about the variant it was told about would silently leave the others
+// behind. Deleting a key that was never written is a no-op on object storage,
+// so over-listing is free and under-listing leaks.
+func migrationBlobKeys(sandboxID string) []string {
+ return []string{
+ fmt.Sprintf("migrations/%s/rootfs.qcow2", sandboxID),
+ fmt.Sprintf("migrations/%s/workspace.qcow2.zst", sandboxID),
+ fmt.Sprintf("migrations/%s/workspace.qcow2", sandboxID),
+ }
+}
+
+// deleteMigrationBlobs removes a sandbox's pre-copied disks from blob storage.
+//
+// Best-effort by design: the migration itself has already succeeded by the time
+// this runs, so a failure here is a storage cost, not a correctness problem,
+// and it must not turn a completed migration into a reported failure. Whatever
+// this drops — including the blobs of migrations that failed before reaching
+// cleanup — is swept up later by the orphan reconciler.
+func (mc *MigrationCoordinator) deleteMigrationBlobs(sandboxID string) {
+ if mc.checkpointStore == nil {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ for _, key := range migrationBlobKeys(sandboxID) {
+ if err := mc.checkpointStore.Delete(ctx, key); err != nil {
+ log.Printf("qemu: migration %s: delete pre-copy blob %s: %v", sandboxID, key, err)
+ }
+ }
+}
+
func (mc *MigrationCoordinator) uploadFile(ctx context.Context, localPath, s3Key string) (int64, error) {
info, err := os.Stat(localPath)
if err != nil {