An open-source, faster Devin alternative
TypeScript
feat(backend,scaler): reach MicroVM hibernation through the API, assign runtimes from D1, and stop the disk-pressure thrash
Brian Reardon262cf653904b
diff --git a/cloudflare-workers/api-edge/migrations/0006_orgs_runtime.sql b/cloudflare-workers/api-edge/migrations/0006_orgs_runtime.sqlnew file mode 100644index 00000000..05fbace7--- /dev/null+++ b/cloudflare-workers/api-edge/migrations/0006_orgs_runtime.sql@@ -0,0 +1,24 @@+-- orgs.runtime — which sandbox backend an org's creates land on.+--+-- Values: NULL / '' = the QEMU worker fleet (the default and the safe answer),+-- 'qemu' = the same, stated explicitly,+-- 'microvm' = the AWS Lambda MicroVM backend.+--+-- Why this lives in D1 rather than cell configuration: which runtime serves an+-- org is a property OF THE ORG. Expressing it as per-cell config (an env var on+-- each control plane) means every cell that could serve that org has to be kept+-- in sync by hand, and a cell that missed the update serves them on the wrong+-- runtime with no error raised anywhere. One row here is authoritative for+-- every cell at once.+--+-- The edge reads this alongside plan and billing_provider when it mints the+-- capability token for a create, and the cell reads it off the token — so this+-- costs no extra query on the create path. Absent means the fleet, which is why+-- adding the column changes nothing for the orgs already in this table: they+-- keep the runtime with the full feature set (checkpoints, fork, PTY, custom+-- templates), and a runtime is opted into one row at a time.+--+-- NOTE: placement is permanent. This decides where an org's NEW sandboxes land;+-- sandboxes already running keep their backend, resolved from their persisted+-- worker_id. Changing this value never moves or strands an existing sandbox.+ALTER TABLE orgs ADD COLUMN runtime TEXT;diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex f6a857bb..a06b589d 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -131,6 +131,7 @@ export interface FinalizeMsg {baseURL: string;plan: string;billingProvider: string;+ runtime: string;sandboxID: string;workerID: string;bodyText: string;@@ -170,13 +171,18 @@ async function cachedCapToken(cellID: string,plan: string,billingProvider: string,+ runtime: string,userID: string | null,): Promise<string> {- const key = `${orgID}|${cellID}|${plan}|${billingProvider}|${userID ?? ""}`;+ // runtime is in the cache key deliberately. It is the org's sandbox backend+ // assignment, and leaving it out would mean a D1 change did not take effect+ // until the entry aged out — an org would keep landing on the old runtime for+ // up to a minute after being reassigned, with nothing to explain why.+ const key = `${orgID}|${cellID}|${plan}|${billingProvider}|${runtime}|${userID ?? ""}`;const hit = capTokenCache.get(key);const nowMs = Date.now();if (hit && nowMs - hit.mintedAtMs < 60_000) return hit.token;- const token = await mintCapToken(secret, orgID, cellID, plan, billingProvider, userID);+ const token = await mintCapToken(secret, orgID, cellID, plan, billingProvider, runtime, userID);if (capTokenCache.size >= CACHE_MAX) capTokenCache.clear();capTokenCache.set(key, { token, mintedAtMs: nowMs });return token;@@ -188,6 +194,7 @@ async function mintCapToken(cellID: string,plan: string,billingProvider: string,+ runtime: string,userID: string | null,): Promise<string> {const now = Math.floor(Date.now() / 1000);@@ -204,6 +211,11 @@ async function mintCapToken(// Only set when known; empty lets the cell keep its existing cell-PG value// (so a wake/preview token never clobbers an autumn flag set at create time).if (billingProvider) payload.billing_provider = billingProvider;+ // Which sandbox runtime this org's creates belong on (orgs.runtime). Omitted+ // when unset, and the cell reads absent as "the QEMU fleet" — so an org with+ // no assignment, and every token minted before this field existed, resolves+ // to the backend with the full feature set rather than a specialised one.+ if (runtime) payload.runtime = runtime;if (userID) payload.user_id = userID;const enc = new TextEncoder();const signingInput =@@ -614,7 +626,7 @@ async function loadCreateContextCold(if (ctx) {ctx.waitUntil(env.OPENCOMPUTER_DB.prepare(- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider FROM orgs WHERE id = ?1",+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1",).bind(orgID).first<OrgPolicy>()@@ -683,7 +695,7 @@ async function loadCreateContextCold(if (!orgWarm2) {stmts.push(env.OPENCOMPUTER_DB.prepare(- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider FROM orgs WHERE id = ?1",+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1",).bind(orgID),);kinds.push("org");@@ -925,6 +937,10 @@ interface OrgPolicy {max_concurrent_sandboxes: number;max_disk_mb: number;billing_provider: string;+ // Which sandbox runtime this org's creates belong on. NULL/"" is the QEMU+ // fleet — so every org that predates this column keeps its current runtime+ // and opting one in is a single-row change.+ runtime: string | null;}// loadOrgPolicy reads an org's routing + policy fields from D1. Returns null@@ -934,7 +950,7 @@ async function loadOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | null>const cached = orgPolicyCache.get(orgID);if (cached && nowMs - cached.cachedAtMs < ORG_POLICY_TTL_MS) return cached.policy;const policy = await env.OPENCOMPUTER_DB.prepare(- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider FROM orgs WHERE id = ?1",+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1",).bind(orgID).first<OrgPolicy>();@@ -1415,6 +1431,7 @@ async function finalizeEdgeClaim(cell: CellRow,plan: string,billingProvider: string,+ runtime: string,sandboxID: string,workerID: string,bodyText: string,@@ -1428,7 +1445,7 @@ async function finalizeEdgeClaim(// Minted HERE (off the response path) rather than on the create hot path —// only this finalize call ever consumes it on the edge-claim route, and the// HMAC sign was one of the larger CPU items at burst-100 concurrency.- const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, billingProvider, caller.userID);+ const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, billingProvider, runtime, caller.userID);let body: Record<string, unknown> = {};try {body = bodyText ? (JSON.parse(bodyText) as Record<string, unknown>) : {};@@ -1631,6 +1648,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): ProbaseURL: cell.base_url,plan,billingProvider: org.billing_provider,+ runtime: org.runtime ?? "",sandboxID: box.id,workerID: box.workerID,bodyText,@@ -1639,11 +1657,11 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Proenv.FINALIZE_QUEUE.send(msg).catch((e) => {// Enqueue failed — finalize inline so the box still binds.console.error(`edge-claim: finalize enqueue failed for ${box.id}, running inline:`, e);- return finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, box.id, box.workerID, bodyText);+ return finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, org.runtime ?? "", box.id, box.workerID, bodyText);}),);} else {- ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, box.id, box.workerID, bodyText));+ ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, org.runtime ?? "", box.id, box.workerID, bodyText));}if (env.DIAG === "1") console.log(`create-timing ${box.id} ${phases.join(" ")}`);return new Response(JSON.stringify(resp), {@@ -1658,7 +1676,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro// CP fallback from here on — mint the cap-token the cell requires (the// edge-claim path above returns without ever needing it).- const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, caller.userID);+ const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID);// SSE build streaming: image/snapshot creates can take minutes (apt installs,// etc.). Preserve live streaming, but index the final `result` event inline@@ -1902,7 +1920,10 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal// tokens and API keys), so the same handler chain that runs for SDK// X-API-Key auth runs here. cell_id in the token guards against replay// against a different cell.- const token = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, route.cellID, orgPol?.plan ?? "free", "", caller.userID);+ // "" runtime: this token is for data-plane sub-ops on an EXISTING sandbox,+ // whose backend is already fixed by its persisted worker_id. Runtime only+ // decides placement, and placement has already happened.+ const token = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, route.cellID, orgPol?.plan ?? "free", "", "", caller.userID);const headers = new Headers();for (const [k, v] of req.headers.entries()) {@@ -2042,7 +2063,7 @@ async function proxyToCellAuthed(: await pickCell(env, org.home_cell, null);if (!cell) return json({ error: "no cell available to serve request" }, 503);- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, "", caller.userID);+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, "", "", caller.userID);const url = new URL(req.url);const target = cell.base_url.replace(/\/$/, "") + (opts.pathOverride ?? url.pathname) + url.search;@@ -3501,7 +3522,7 @@ async function runPausedCapEnforcer(env: Env): Promise<void> {let promoted = 0;for (const v of victims.results ?? []) {try {- const token = await mintCapToken(env.SESSION_JWT_SECRET, org.org_id, v.cell_id, "", "", null);+ const token = await mintCapToken(env.SESSION_JWT_SECRET, org.org_id, v.cell_id, "", "", "", null);const resp = await fetch(v.base_url.replace(/\/$/, "") + `/internal/sandboxes/${v.id}/deep-hibernate`,{ method: "POST", headers: { authorization: "Bearer " + token } },@@ -3919,7 +3940,7 @@ export default {const fcGate = await enforceCreatePolicy(env, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk }, fcActive);if (fcGate) return fcGate;const plan = org.plan === "pro" ? "pro" : "free";- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, plan, org.billing_provider, caller.userID);+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID);const fcResp = await fetch(cell.base_url.replace(/\/$/, "") + path, {method: "POST",headers: { authorization: "Bearer " + token, "content-type": "application/json" },@@ -4121,6 +4142,7 @@ export default {{ cell_id: b.cellID, base_url: b.baseURL } as CellRow,b.plan,b.billingProvider,+ b.runtime ?? "",b.sandboxID,b.workerID,b.bodyText,diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex c8ef396c..5118f46a 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -454,6 +454,14 @@ func main() {cacheDir := filepath.Join(cfg.DataDir, "checkpoints")if err := checkpointStore.SetCacheDir(cacheDir); err != nil {log.Printf("opensandbox-worker: warning: checkpoint cache disabled: %v", err)+ } else {+ // Evict on a timer, not only when something is being cached.+ // Demand-driven eviction latches: past the routing-exclusion+ // threshold a worker receives no new sandboxes, so nothing+ // downloads a checkpoint, so eviction is never invoked and the+ // disk never comes back down. The worker stays out of the fleet+ // holding space it would have released on request.+ checkpointStore.StartEvictionSweeper(context.Background())}}}diff --git a/internal/api/backend.go b/internal/api/backend.goindex 011bb259..a1a5a30d 100644--- a/internal/api/backend.go+++ b/internal/api/backend.go@@ -3,8 +3,11 @@ package apiimport ("context"+ "github.com/google/uuid"+"github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/pkg/types"@@ -94,6 +97,22 @@ func ManagedWorkerIDPrefixes() []string {return out}+// Runtime identifiers, as stored in D1 orgs.runtime and carried on the+// capability token the edge mints for every create.+//+// Deliberately NOT Backend.Name(), which is documented as a label for logs and+// telemetry. These strings are persisted config and production routing: renaming+// a backend for readability must never repoint customer traffic.+//+// The empty string is the QEMU fleet, and that is the whole safety property of+// this design — an org with no runtime set, a cap token minted before this+// existed, or a create that never passed the edge all resolve to the runtime+// with the full feature set.+const (+ runtimeQEMU = "qemu"+ runtimeMicrovm = "microvm"+)+// Placer is a Backend that can accept new sandboxes.//// Split from Backend because the two capabilities are genuinely independent: a@@ -105,10 +124,39 @@ func ManagedWorkerIDPrefixes() []string {type Placer interface {Backend+ // Accepts reports whether this backend will take a particular sandbox,+ // asked BEFORE Claim and before any side effect.+ //+ // This is the only place a create can change runtimes. Once Claim returns,+ // the sandbox belongs to that backend for its whole life: every later+ // route, hibernate, wake, and reap resolves through OwnsWorkerID on the+ // persisted worker_id, and nothing migrates a sandbox between runtimes.+ // That is deliberate — two runtimes with different snapshot formats, CPU+ // architectures, and lifetime ceilings cannot hand a sandbox back and+ // forth, and a system that tried would fail in ways no one could reason+ // about.+ //+ // So Accepts answers two questions that both have to be settled up front:+ // whether this backend is allowed to serve the org, and whether it can+ // honour the request at all. Declining is normal and cheap; the caller+ // simply offers the sandbox to the next registered Placer.+ //+ // Note what this does NOT do: it is never consulted after a create.+ // Narrowing the rules — removing an org from an allowlist, say — changes+ // where NEW sandboxes land and must never strand the ones already running.+ Accepts(p placement) bool+// Claim places a new sandbox and returns the worker_id to persist. An// error is terminal for the create — the caller must not fall through to// another path, because a backend that could not place a sandbox has// already decided the answer.+ //+ // Terminal rather than "try the next backend" on purpose. A silent+ // failover would mean a create that asked for one runtime and quietly got+ // another: benchmark numbers that measure the wrong thing, and capability+ // promises made by a backend that never saw the request. Accepts is where+ // a backend declines; Claim failing means the answer was yes and the+ // placement still did not work.Claim(ctx context.Context, p placement) (workerID string, err error)// Activate starts the host chosen by Claim. It runs AFTER the pending row@@ -140,6 +188,56 @@ type Placer interface {Release(ctx context.Context, sandboxID, workerID string)}+// Hibernator is a Backend that parks and revives a sandbox in process.+//+// Optional in the same way Placer is, and for the same reason: the capability+// is genuinely independent of serving sandboxes. The QEMU fleet deliberately+// does NOT implement it. Its hibernate and wake dispatch over gRPC to one+// specific worker, and which one is not a detail — a wake prefers the worker+// that hibernated the sandbox because the qcow2 files are still on its disk,+// and refuses a cross-worker wake while the archive upload is unfinished. That+// is placement logic with physics behind it, and this interface has no+// vocabulary for it. Those paths stay on the worker registry+// (hibernateSandboxRemote / wakeSandboxRemote), untouched.+//+// What this interface is for is the other shape: a backend whose sandboxes the+// control plane manages directly, where hibernate is a call into a local+// manager rather than a hop to a host that owns the disk.+type Hibernator interface {+ Backend++ // Hibernate parks the sandbox and reports where its archive landed, so the+ // caller can record it. It does not write to the database — who owns the+ // row is the caller's decision, not the runtime's.+ Hibernate(ctx context.Context, sandboxID string) (*sandbox.HibernateResult, error)++ // Wake revives the sandbox and returns the worker_id now serving it.+ //+ // Returning the id is the whole point rather than an afterthought: a+ // restore from the archive lands on a NEW host, so the persisted row must+ // follow it. A wake that revived the sandbox but left worker_id pointing at+ // the dead host would leave every later route, ownership check, and reap+ // looking in the wrong place — the sandbox would be alive and unreachable.+ Wake(ctx context.Context, sandboxID, hibernationKey string, timeoutSeconds int) (workerID string, err error)+}++// hibernatorFor resolves the backend that can park or revive a sandbox, keyed+// on the worker_id persisted for it.+//+// Deliberately OwnsWorkerID and not Route. Route asks the live routing map,+// which is exactly the wrong question here: a deep-hibernated sandbox has no+// host at all — the retirement sweep terminated it and called Forget — so Route+// answers "not mine" for precisely the sandboxes a wake exists to serve.+// OwnsWorkerID answers from what is in the database, which outlives the host.+func (s *Server) hibernatorFor(workerID string) (Hibernator, bool) {+ b, ok := s.backendForWorkerID(workerID)+ if !ok {+ return nil, false+ }+ h, ok := b.(Hibernator)+ return h, ok+}+// placement is the request-scoped input to Claim.//// Region is here rather than on the backend because it is a property of the@@ -149,7 +247,18 @@ type Placer interface {type placement struct {sandboxID stringregion string- cfg types.SandboxConfig+ // orgID is who the sandbox is for.+ orgID uuid.UUID+ // runtime is which backend the org is assigned to, from D1 orgs.runtime by+ // way of the capability token. Empty means the QEMU fleet.+ //+ // It rides on the token rather than being read from config or a database+ // here for one reason: which runtime serves an org is a property OF THE ORG,+ // not of the cell that happens to serve it. Per-cell configuration for a+ // per-org fact needs every cell kept in sync by hand, and a cell that missed+ // an update silently serves that org on the wrong runtime.+ runtime string+ cfg types.SandboxConfig}// activation is everything needed to start a host Claim already chose.@@ -244,15 +353,60 @@ func (s *Server) backendForWorkerID(workerID string) (Backend, bool) {// poll, persistence, token minting, and response shaping in one function on// the path that serves all current traffic. That split is worth doing// deliberately, not as a side effect of introducing the seam.-func (s *Server) claimBackend() (Placer, bool) {+// claimBackend picks the runtime that will serve a create: the first+// registered Placer that accepts it.+//+// Registration order is the policy. A backend registered earlier gets first+// refusal, so a runtime with its own warm stock is offered every create before+// the fleet, and the fleet serves whatever it declines. Moving a+// registerBackend call changes which runtime serves production traffic.+//+// First-accept rather than best-match: there is no scoring here, and there+// should not be. Placement has to be decidable from the request alone, because+// the decision is permanent — see Accepts.+func (s *Server) claimBackend(p placement) (Placer, bool) {for _, b := range s.backends {- if p, ok := b.(Placer); ok {- return p, true+ placer, ok := b.(Placer)+ if !ok {+ continue}+ if !placer.Accepts(p) {+ continue+ }+ return placer, true}return nil, false}+// orgRuntime reads the runtime this org is assigned to off the capability+// token the edge minted for this request.+//+// Empty whenever there is no token — combined mode, and any path that did not+// come through the edge. That resolves to the QEMU fleet, which is the only+// safe default: a create whose runtime we cannot establish must land on the+// backend that can serve anything, never on a specialised one.+func runtimeFor(c echo.Context) string {+ claims, _ := c.Get(capClaimsKey).(*auth.CapabilityClaims)+ if claims == nil {+ return ""+ }+ return claims.Runtime+}++// canPlace reports whether any registered backend would take a create for this+// org, used only to choose between the shared create flow and legacy combined+// mode.+//+// Region is deliberately absent: it is resolved further down createSandboxRemote+// (template lookup can override it), so it is not known here. That is safe+// today because no backend gates on region, and the authoritative decision is+// made in createSandboxRemote with the complete placement. A backend that ever+// does gate on region must not rely on this pre-check.+func (s *Server) canPlace(orgID uuid.UUID, runtime string, cfg types.SandboxConfig) bool {+ _, ok := s.claimBackend(placement{orgID: orgID, runtime: runtime, cfg: cfg})+ return ok+}+// dispatchDataPlane picks between serving a request in-process and proxying it// to the worker that holds the sandbox.//diff --git a/internal/api/backend_conformance_test.go b/internal/api/backend_conformance_test.goindex 1b4d39c2..dd2ca562 100644--- a/internal/api/backend_conformance_test.go+++ b/internal/api/backend_conformance_test.go@@ -227,6 +227,11 @@ type fakeBackend struct {// fakePlacer is a fakeBackend that can also accept new sandboxes.type fakePlacer struct{ *fakeBackend }+// Accepts everything: these fakes exist to exercise registration order and+// routing, not placement policy, and a fake that declined would silently make+// every ordering assertion vacuous.+func (f *fakePlacer) Accepts(placement) bool { return true }+func (f *fakePlacer) RequiresPersistedRow() bool { return false }func (f *fakePlacer) Release(context.Context, string, string) {}@@ -270,7 +275,7 @@ func TestRegistryDispatchesToTheHoldingBackend(t *testing.T) {}// "first" is registered ahead of "second" but cannot place, so creates must// skip it rather than being diverted to a backend that would fail them.- claim, ok := s.claimBackend()+ claim, ok := s.claimBackend(placement{})if !ok || claim.Name() != "second" {t.Fatalf("claimBackend picked %v, want the first backend that can place", claim)}@@ -286,7 +291,7 @@ func TestNoBackendsRoutesNothing(t *testing.T) {if _, _, ok := s.backendFor(context.Background(), "sb-1"); ok {t.Fatal("empty registry claimed a sandbox")}- if _, ok := s.claimBackend(); ok {+ if _, ok := s.claimBackend(placement{}); ok {t.Fatal("empty registry offered to serve a create")}if mgr, ok := s.execManagerFor("sb-1"); ok || mgr != nil {diff --git a/internal/api/backend_gating_test.go b/internal/api/backend_gating_test.gonew file mode 100644index 00000000..54b7f00e--- /dev/null+++ b/internal/api/backend_gating_test.go@@ -0,0 +1,147 @@+package api++import (+ "testing"++ "github.com/google/uuid"++ "github.com/opensandbox/opensandbox/pkg/types"+)++// backend_gating_test.go — which runtime serves a create, and the one-way street.+//+// Assignment lives in D1 orgs.runtime and reaches the cell on the capability+// token. Two properties have to hold, and they pull in opposite directions:+//+// strict at create — nobody unassigned lands on a specialised runtime+// absent afterwards — reassigning an org must not strand what is running+//+// The second is the one that would be missed. Placement is permanent: a sandbox+// resolves its backend from the persisted worker_id forever after. If runtime+// were ever consulted post-create, moving an org back to QEMU would orphan its+// live MicroVM sandboxes — the rollback would cause the outage.++// The empty runtime is the load-bearing default. Every org that predates the+// D1 column, every token minted before the claim existed, and every create that+// never passed the edge arrives with "" — and all of them must land on the+// fleet, which is the only backend that can serve anything.+func TestUnassignedRuntimeGoesToTheFleet(t *testing.T) {+ var fleet workerBackend+ micro := µvmBackend{}++ if !fleet.Accepts(placement{runtime: ""}) {+ t.Error("fleet declined an unassigned create — orgs with no D1 runtime would 503")+ }+ if micro.Accepts(placement{runtime: ""}) {+ t.Error("MicroVM accepted an unassigned create — an org would reach a specialised runtime by default")+ }+}++// An explicit assignment routes to exactly that runtime and no other.+func TestRuntimeAssignmentRoutesExactly(t *testing.T) {+ var fleet workerBackend+ micro := µvmBackend{}++ if !micro.Accepts(placement{runtime: runtimeMicrovm}) {+ t.Error("MicroVM declined an org assigned to it — the assignment would do nothing")+ }+ if fleet.Accepts(placement{runtime: runtimeMicrovm}) {+ t.Error("fleet accepted a microvm-assigned create — the org would silently get the wrong runtime")+ }+ if !fleet.Accepts(placement{runtime: runtimeQEMU}) {+ t.Error("fleet declined an org explicitly assigned to it")+ }+ if micro.Accepts(placement{runtime: runtimeQEMU}) {+ t.Error("MicroVM accepted a qemu-assigned create")+ }+}++// Selection must skip a declining backend and reach the next Placer, which is+// how an unassigned org reaches the fleet on a cell running both.+func TestUnassignedFallsThroughToTheFleet(t *testing.T) {+ s := &Server{}+ s.registerBackend(µvmBackend{})+ s.registerBackend(&fakePlacer{&fakeBackend{name: "fleet"}})++ got, ok := s.claimBackend(placement{runtime: ""})+ if !ok {+ t.Fatal("no backend accepted an unassigned create — every existing customer would 503")+ }+ if got.Name() != "fleet" {+ t.Fatalf("unassigned create placed on %q, want the fleet", got.Name())+ }+}++// An org assigned to a runtime this cell does not run must FAIL, not fall+// through. Silently serving the other runtime is the exact outcome this design+// exists to prevent — it would mean benchmark numbers measuring QEMU, and+// capability promises made by a backend that never saw the request.+func TestAssignedRuntimeAbsentOnCellFailsRatherThanFallsBack(t *testing.T) {+ // The real fleet backend, not the permissive fake: this test is precisely+ // about what the fleet refuses, so a fake that accepts everything would+ // assert nothing.+ s := &Server{}+ s.registerBackend(&workerBackend{}) // no microvm backend on this cell++ if _, ok := s.claimBackend(placement{runtime: runtimeMicrovm}); ok {+ t.Fatal("a microvm-assigned create was served by another runtime — " ++ "the org would silently get QEMU instead of failing loudly")+ }+}++// THE one-way-street property: runtime is a create-time input and nothing else.+// Ownership afterwards comes from the persisted worker_id.+//+// Written as a test because the failure is silent and delayed. Reassigning an+// org to stop new MicroVM traffic must not make the sandboxes it already has+// unreachable — otherwise the rollback IS the incident.+func TestReassigningRuntimeNeverStrandsRunningSandboxes(t *testing.T) {+ b := µvmBackend{}+ s := &Server{backends: []Backend{b}}++ // The org has been moved back to the fleet: no NEW create lands here.+ if b.Accepts(placement{runtime: runtimeQEMU}) {+ t.Fatal("precondition failed: backend should decline a reassigned org")+ }++ // What it already placed still resolves to it.+ workerID := microvmWorkerID("microvm-alreadyrunning")+ if !b.OwnsWorkerID(workerID) {+ t.Error("backend disowned a worker_id it issued — routing, reap and billing would all miss it")+ }+ if _, ok := s.hibernatorFor(workerID); !ok {+ t.Error("hibernate/wake stopped resolving for an existing sandbox after reassignment")+ }+}++// A create the backend cannot honour is declined even when the org IS assigned+// to it. A custom template is a QEMU checkpoint; there is no such artifact on+// this runtime, so accepting one builds from the wrong image and reports+// success.+func TestDeclinesRequestsItCannotServe(t *testing.T) {+ b := µvmBackend{}++ if b.Accepts(placement{runtime: runtimeMicrovm, cfg: types.SandboxConfig{Template: "customer-toolchain-v3"}}) {+ t.Error("accepted a custom template it cannot build — the sandbox would come from the wrong image")+ }+ for _, tmpl := range []string{"", "default"} {+ if !b.Accepts(placement{runtime: runtimeMicrovm, cfg: types.SandboxConfig{Template: tmpl}}) {+ t.Errorf("declined template %q, which maps to its own image", tmpl)+ }+ }+}++// The org id is carried for logging and future policy but must not by itself+// decide placement — runtime does. A stray org check here would resurrect the+// per-cell config problem this replaced.+func TestOrgIDAloneDoesNotDecidePlacement(t *testing.T) {+ b := µvmBackend{}+ org := uuid.MustParse("11111111-1111-4111-8111-111111111111")++ if b.Accepts(placement{orgID: org, runtime: ""}) {+ t.Error("an org reached MicroVM without a runtime assignment")+ }+ if !b.Accepts(placement{orgID: org, runtime: runtimeMicrovm}) {+ t.Error("an assigned org was declined")+ }+}diff --git a/internal/api/backend_hibernation.go b/internal/api/backend_hibernation.gonew file mode 100644index 00000000..32d7a336--- /dev/null+++ b/internal/api/backend_hibernation.go@@ -0,0 +1,158 @@+package api++import (+ "context"+ "encoding/json"+ "log"+ "net/http"+ "time"++ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// backend_hibernation.go — hibernate and wake for backends that hold their own+// sandboxes.+//+// The QEMU fleet reaches these operations by gRPC to one specific worker, and+// which worker is load-bearing: a wake prefers the machine that hibernated the+// sandbox because the qcow2 files are still on its disk, and refuses to move+// while the archive upload is unfinished. That logic stays in+// hibernateSandboxRemote / wakeSandboxRemote, untouched by any of this.+//+// A managed backend has no such hop — the control plane holds the manager, so+// the operation is a local call. Before this those handlers had no way to say+// so: both branch on `s.workerRegistry != nil`, and a backend-served cell HAS a+// registry (it still answers worker_id lookups) with no workers in it. So every+// hibernate and wake on such a cell dispatched into an empty fleet and failed+// with "no workers available", which is why the MicroVM tiered hibernation was+// reachable from cmd/microvm-harness and from nothing else.+//+// What is deliberately NOT shared with the QEMU path: the row-side bookkeeping+// below is written out again rather than factored into a helper both call. The+// two differ in ways that matter — which worker_id gets persisted, whether a+// checkpoint-patch pass applies — and a single function with two modes would+// hide exactly the differences worth seeing.++// hibernatorForSandbox resolves the backend that can park or revive a sandbox,+// along with its session row, which the caller needs either way.+//+// Returns false when no registered backend owns the sandbox, which is the+// common case: the QEMU fleet does not implement Hibernator, so its sandboxes+// fall through to the worker-registry paths unchanged.+func (s *Server) hibernatorForSandbox(ctx context.Context, sandboxID string) (Hibernator, *db.SandboxSession, bool) {+ if s == nil || s.store == nil {+ return nil, nil, false+ }+ session, err := s.store.GetSandboxSession(ctx, sandboxID)+ if err != nil || session == nil {+ // No row means nothing to resolve ownership from. Fall through rather+ // than guess — the registry paths have their own not-found answers.+ return nil, nil, false+ }+ h, ok := s.hibernatorFor(session.WorkerID)+ if !ok {+ return nil, nil, false+ }+ return h, session, true+}++// hibernateViaBackend parks a sandbox on a backend that holds it.+func (s *Server) hibernateViaBackend(c echo.Context, sandboxID string, h Hibernator, session *db.SandboxSession) error {+ ctx := c.Request().Context()++ result, err := h.Hibernate(ctx, sandboxID)+ if err != nil {+ log.Printf("api: hibernate %s via %s: %v", sandboxID, h.Name(), err)+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "failed to hibernate the sandbox",+ })+ }++ // Record the archive before flipping status. A row marked hibernated with+ // no hibernation record is unwakeable — GetActiveHibernation finds nothing+ // — so the order here is what makes the sandbox recoverable.+ orgID, hasOrg := auth.GetOrgID(c)+ if s.store != nil && hasOrg {+ cfg := json.RawMessage("{}")+ template, region := "base", s.region+ if session != nil {+ cfg = session.Config+ template = session.Template+ region = session.Region+ }+ if _, superseded, cErr := s.store.CreateHibernation(ctx, sandboxID, orgID,+ result.HibernationKey, result.SizeBytes, region, template, cfg); cErr != nil {+ log.Printf("api: hibernate %s: record hibernation: %v", sandboxID, cErr)+ } else {+ s.deleteSupersededHibernation(superseded)+ }+ _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "hibernated", nil)+ }++ if s.router != nil {+ s.router.MarkHibernated(sandboxID, 600*time.Second)+ }+ if s.sandboxDBs != nil {+ _ = s.sandboxDBs.Remove(sandboxID)+ }++ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": sandboxID,+ "status": "hibernated",+ "hibernationKey": result.HibernationKey,+ "sizeBytes": result.SizeBytes,+ })+}++// wakeViaBackend revives a sandbox on a backend that holds it.+func (s *Server) wakeViaBackend(c echo.Context, sandboxID string, h Hibernator, session *db.SandboxSession, req types.WakeRequest) error {+ ctx := c.Request().Context()++ // Already running: a wake is idempotent from the customer's side, and+ // re-entering the restore path for a live sandbox would rebuild it from an+ // archive that is older than the sandbox itself.+ if session != nil && session.Status == "running" {+ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": sandboxID, "status": "running",+ })+ }++ hibernation, err := s.store.GetActiveHibernation(ctx, sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active hibernation found"})+ }++ workerID, err := h.Wake(ctx, sandboxID, hibernation.HibernationKey, req.Timeout)+ if err != nil {+ log.Printf("api: wake %s via %s: %v", sandboxID, h.Name(), err)+ return c.JSON(http.StatusInternalServerError, map[string]string{+ "error": "failed to wake the sandbox",+ })+ }++ // Persist the host that is actually serving it now. A restore lands on a+ // NEW host, so writing the old worker_id here would leave a live sandbox+ // that routing, ownership checks, and the reaper all look for in the wrong+ // place. This is also what flips the row back to running.+ if err := s.store.UpdateSandboxSessionForWake(ctx, sandboxID, workerID); err != nil {+ log.Printf("api: wake %s: update session to %s: %v", sandboxID, workerID, err)+ }+ _ = s.store.MarkHibernationRestored(ctx, sandboxID)++ if s.router != nil {+ timeout := req.Timeout+ if timeout < 0 {+ timeout = 0+ }+ s.router.Register(sandboxID, time.Duration(timeout)*time.Second)+ }++ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": sandboxID,+ "status": "running",+ })+}diff --git a/internal/api/backend_hibernation_test.go b/internal/api/backend_hibernation_test.gonew file mode 100644index 00000000..9d83f122--- /dev/null+++ b/internal/api/backend_hibernation_test.go@@ -0,0 +1,96 @@+package api++import (+ "context"+ "testing"++ "github.com/opensandbox/opensandbox/internal/awsvm"+)++// backend_hibernation_test.go — which backend answers a hibernate or a wake.+//+// The dispatch decision here is a fork in the road with no error path: pick+// wrong and the request either goes to an empty worker fleet ("no workers+// available" for a sandbox this process could have woken) or into a local+// manager that has never heard of the sandbox. Neither failure looks like a+// routing bug from the outside, so the routing is what these tests pin.++// The QEMU fleet must NOT implement Hibernator. Its hibernate and wake depend+// on reaching one specific worker — a wake prefers the machine holding the+// qcow2 files and refuses to move while the archive upload is unfinished — and+// none of that survives being expressed as "call the local manager".+//+// This is a type assertion rather than a behavioural test because that is where+// the decision actually lives: the moment workerBackend grows a Hibernate+// method, every QEMU hibernate silently changes path, with no compiler error+// and no test failure anywhere else.+func TestWorkerBackendIsNotAHibernator(t *testing.T) {+ var b Backend = &workerBackend{}+ if _, ok := b.(Hibernator); ok {+ t.Fatal("workerBackend implements Hibernator — QEMU hibernate/wake would " ++ "bypass wakeSandboxRemote and lose source-worker affinity")+ }+}++// ...and the MicroVM backend must, or the handlers fall through to the registry+// branch and the whole tiered hibernation is unreachable over HTTP again.+func TestMicrovmBackendIsAHibernator(t *testing.T) {+ var b Backend = µvmBackend{}+ if _, ok := b.(Hibernator); !ok {+ t.Fatal("microvmBackend does not implement Hibernator — hibernate/wake " ++ "would dispatch into an empty worker fleet")+ }+}++// The resolver must key on durable ownership, not the live routing map.+//+// This is the case that motivated hibernatorFor existing at all. A deep-+// hibernated sandbox has no host: the retirement sweep terminated the suspended+// box and called Forget, so the manager tracks nothing and Route answers "not+// mine". If dispatch consulted Route, it would decline for exactly the+// sandboxes wake exists to serve, and the request would fall through to a+// worker fleet that cannot restore an archive it has never seen.+//+// OwnsWorkerID reads the persisted worker_id instead, which outlives the host.+func TestHibernatorResolvesASandboxWhoseHostIsGone(t *testing.T) {+ // A backend tracking nothing — the state after retirement to blob-only.+ b := µvmBackend{manager: awsvm.NewManager(nil, "")}+ s := &Server{backends: []Backend{b}}++ workerID := microvmWorkerID("microvm-deadbeef")++ if _, routed := b.Route(context.Background(), "sb-parked"); routed {+ t.Fatal("precondition failed: Route claims a sandbox with no tracked host")+ }+ if h, ok := s.hibernatorFor(workerID); !ok || h == nil {+ t.Fatalf("hibernatorFor declined %q for a backend that owns it — a "++ "blob-only hibernation would be unwakeable", workerID)+ }+}++// A worker_id belonging to some other runtime must not resolve here, or a QEMU+// sandbox's wake would be handed to the MicroVM manager and restored from an+// archive it cannot read.+func TestHibernatorDeclinesForeignWorkerIDs(t *testing.T) {+ s := &Server{backends: []Backend{µvmBackend{manager: awsvm.NewManager(nil, "")}}}++ for _, workerID := range []string{+ "worker-abc123", // a real registered QEMU worker+ "", // never persisted+ "vmhost", // prefix-adjacent but not a valid encoded id+ hostIDPrefix + "raw", // a raw host id, which Claim must never persist+ } {+ if h, ok := s.hibernatorFor(workerID); ok {+ t.Errorf("hibernatorFor claimed foreign worker_id %q (got %T)", workerID, h)+ }+ }+}++// With no backends registered — every QEMU cell — the resolver must decline so+// both handlers fall through to their existing registry paths untouched.+func TestHibernatorDeclinesWithNoBackends(t *testing.T) {+ s := &Server{}+ if _, ok := s.hibernatorFor("worker-abc"); ok {+ t.Fatal("resolved a hibernator on a cell with no backends registered")+ }+}diff --git a/internal/api/hibernation_reclaim.go b/internal/api/hibernation_reclaim.godeleted file mode 100644index 0925b7dd..00000000--- a/internal/api/hibernation_reclaim.go+++ /dev/null@@ -1,175 +0,0 @@-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.godeleted file mode 100644index bca836c9..00000000--- a/internal/api/hibernation_reclaim_test.go+++ /dev/null@@ -1,66 +0,0 @@-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.goindex de04c353..a8910528 100644--- a/internal/api/microvm_backend.go+++ b/internal/api/microvm_backend.go@@ -19,6 +19,7 @@ import ("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"@@ -53,6 +54,11 @@ type microvmBackend struct {pool *awsvm.Poolmanager *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@@ -88,7 +94,7 @@ func microvmEnabled() bool {// 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) (*microvmBackend, error) {+func newMicrovmBackend(ctx context.Context, checkpointStore *storage.CheckpointStore) (*microvmBackend, error) {if !microvmEnabled() {return nil, nil}@@ -158,11 +164,12 @@ func newMicrovmBackend(ctx context.Context) (*microvmBackend, error) {region, image, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))return µvmBackend{- client: client,- pool: pool,- manager: awsvm.NewManager(client, os.TempDir()),- coldSlots: make(chan struct{}, maxColdCreates),- stopPool: stop,+ client: client,+ pool: pool,+ manager: awsvm.NewManager(client, os.TempDir()),+ checkpointStore: checkpointStore,+ coldSlots: make(chan struct{}, maxColdCreates),+ stopPool: stop,}, nil}@@ -715,6 +722,93 @@ func (b *microvmBackend) Release(ctx context.Context, sandboxID, _ string) {}}+// 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)}diff --git a/internal/api/microvm_hibernation.go b/internal/api/microvm_hibernation.goindex 07874c16..b92e5dc3 100644--- a/internal/api/microvm_hibernation.go+++ b/internal/api/microvm_hibernation.go@@ -92,7 +92,6 @@ func (b *microvmBackend) expireHibernations(ctx context.Context, store *db.Store}}-// safeToRetire reports whether a suspended box can be terminated.//// Separate from the query on purpose. The SQL already filters on uploaded_at,diff --git a/internal/api/router.go b/internal/api/router.goindex 64c6cbfe..c3276a4f 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -804,7 +804,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// AWS call is ever made, so the QEMU fleet is unaffected. When it IS enabled// but misconfigured, fail loudly rather than silently serving QEMU from a// cell the operator believes is running MicroVMs.- if mvm, err := newMicrovmBackend(context.Background()); err != nil {+ if mvm, err := newMicrovmBackend(context.Background(), s.checkpointStore); err != nil {log.Fatalf("opensandbox: microvm backend: %v", err)} else if mvm != nil {s.microvm = mvm@@ -853,12 +853,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, os.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/api/sandbox.go b/internal/api/sandbox.goindex 6bf4e599..1eb03207 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -189,7 +189,7 @@ func (s *Server) createSandbox(c echo.Context) error {// condition is backend registration, not the worker registry: a cell served// by a backend has no registry and no local manager, so gating on the// registry made every create there fail with "server-only mode".- if _, ok := s.claimBackend(); ok {+ if s.canPlace(uuid.UUID(orgID), runtimeFor(c), cfg) {return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg, secretStoreID)}@@ -856,7 +856,10 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty// start the host, promote. runCreate owns that order; the closures below own// what each step means here. Before this the sequence was inline and the// persist-before-activate constraint was a comment.- backend, ok := s.claimBackend()+ orgRuntime := runtimeFor(c)+ backend, ok := s.claimBackend(placement{+ region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,+ })if !ok {// No registered backend can accept a sandbox. A cell in this state can// still serve the ones it already has, so this is a capacity answer.@@ -881,7 +884,10 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyvar host activatedworkerID, err := runCreate(ctx, sandboxID, createSteps{claim: func(ctx context.Context) (string, error) {- return backend.Claim(ctx, placement{sandboxID: sandboxID, region: region, cfg: cfg})+ return backend.Claim(ctx, placement{+ sandboxID: sandboxID, region: region,+ orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,+ })},persistRequired: backend.RequiresPersistedRow(),@@ -2028,6 +2034,15 @@ func (s *Server) hibernateSandbox(c echo.Context) error {id := c.Param("id")ctx := c.Request().Context()+ // A backend that parks its own sandboxes gets first refusal, BEFORE the+ // registry branch below. Order is not cosmetic: a backend-served cell still+ // has a worker registry — it is what answers worker_id lookups — but no+ // workers in it, so falling through would dispatch every hibernate to a+ // fleet that does not exist and fail with "no workers available".+ if h, sess, ok := s.hibernatorForSandbox(ctx, id); ok {+ return s.hibernateViaBackend(c, id, h, sess)+ }+// Server mode: dispatch to worker via gRPCif s.workerRegistry != nil {return s.hibernateSandboxRemote(c, id)@@ -2251,6 +2266,16 @@ func (s *Server) wakeSandbox(c echo.Context) error {// halt_reconciler still enforces against running sandboxes; this wake// path is reached only after the edge has gated on D1.is_halted.+ // A backend that revives its own sandboxes gets first refusal, for the same+ // reason as hibernate: the registry is non-nil on such a cell but empty, so+ // falling through answers "no workers available" for a sandbox this process+ // can wake itself. It also covers both tiers — the backend decides whether+ // to resume a suspended host or rebuild from the archive — so the paused+ // branch below stays QEMU's alone.+ if h, sess, ok := s.hibernatorForSandbox(ctx, id); ok {+ return s.wakeViaBackend(c, id, h, sess, req)+ }+// Server mode: pick any worker, dispatch via gRPCif s.workerRegistry != nil {return s.wakeSandboxRemote(c, id, req)diff --git a/internal/api/worker_backend.go b/internal/api/worker_backend.goindex 5bd1372b..e1ed77d3 100644--- a/internal/api/worker_backend.go+++ b/internal/api/worker_backend.go@@ -172,6 +172,18 @@ func (w *workerBackend) selectWorker(ctx context.Context, region string) (*contr}}+// Accepts takes every create not explicitly assigned elsewhere.+//+// The empty runtime is the load-bearing case: an org with no D1 assignment, a+// capability token minted before the field existed, and a create that never+// passed the edge all arrive here. That is deliberate — this is the runtime+// with the full feature set (checkpoints, fork, PTY, custom templates, resize),+// so it is the only safe answer to "we do not know". A newer runtime declines+// what it cannot serve; this one has nowhere to pass a create on to.+func (w *workerBackend) Accepts(p placement) bool {+ return p.runtime == "" || p.runtime == runtimeQEMU+}+// Claim chooses a worker. No side effects on the fleet: the VM is not started// until Activate, so a failure here costs nothing but the selection attempt.func (w *workerBackend) Claim(ctx context.Context, p placement) (string, error) {diff --git a/internal/auth/jwt.go b/internal/auth/jwt.goindex 944074fb..74d79ebc 100644--- a/internal/auth/jwt.go+++ b/internal/auth/jwt.go@@ -149,6 +149,18 @@ type CapabilityClaims struct {// orgs are autumn (metered, no free-tier ceiling) vs legacy, without a// separate sync. Empty on older tokens / paths — the cell leaves it untouched.BillingProvider string `json:"billing_provider,omitempty"`+ // Runtime mirrors orgs.runtime from D1 ("" | "qemu" | "microvm") and tells+ // the cell which sandbox backend this org's creates belong on.+ //+ // Carried here rather than configured per-cell because which runtime serves+ // an org is a property OF THE ORG: per-cell config for a per-org fact means+ // every cell kept in sync by hand, and a cell that missed an update serves+ // that org on the wrong runtime with no error anywhere.+ //+ // Empty means the QEMU fleet, which is what makes this safe to deploy: every+ // org that predates the field, and every token minted before it existed,+ // resolves to the runtime with the full feature set.+ Runtime string `json:"runtime,omitempty"`}// CapabilityIssuer is the Issuer string on capability tokens — lets the CP@@ -160,7 +172,7 @@ const CapabilityIssuer = "opensandbox-edge"// be empty when the caller doesn't have it handy — the cell will then// fall back to a PG lookup, which is a small performance hit but never// incorrect.-func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID, plan, billingProvider string, userID *string, ttl time.Duration) (string, error) {+func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID, plan, billingProvider, runtime string, userID *string, ttl time.Duration) (string, error) {now := time.Now()claims := CapabilityClaims{RegisteredClaims: jwt.RegisteredClaims{@@ -173,6 +185,7 @@ func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID, plan, billingProvider stCellID: cellID,UserID: userID,Plan: plan,+ Runtime: runtime,BillingProvider: billingProvider,}token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex 61068bfd..cfa67f2d 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -17,32 +17,38 @@ import ("github.com/opensandbox/opensandbox/internal/alert""github.com/opensandbox/opensandbox/internal/compute""github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/diskpolicy"pb "github.com/opensandbox/opensandbox/proto/worker")const (- scaleUpThreshold = 0.50 // Scale up when utilization > 50% (gives ~3 min runway for new worker to boot)- scaleDownThreshold = 0.20 // Scale down when utilization < 20%- maxWorkersPerRegion = 10 // Hard cap to prevent runaway launches+ scaleUpThreshold = 0.50 // Scale up when utilization > 50% (gives ~3 min runway for new worker to boot)+ scaleDownThreshold = 0.20 // Scale down when utilization < 20%+ maxWorkersPerRegion = 10 // Hard cap to prevent runaway launchespendingWorkerTTL = 10 * time.Minute // How long to wait for a launched worker to register// Resource-based scaling thresholds (applied per-worker, trigger on ANY worker exceeding)- resourceCPUThreshold = 70.0 // Scale up if any worker CPU > 70%- resourceMemThreshold = 70.0 // Scale up if any worker memory > 70%- resourceDiskThreshold = 60.0 // Scale up if any worker disk > 60%+ resourceCPUThreshold = 70.0 // Scale up if any worker CPU > 70%+ resourceMemThreshold = 70.0 // Scale up if any worker memory > 70%+ // Disk rungs come from the shared ladder (internal/diskpolicy) rather than+ // being written here. The checkpoint cache has to release space BEFORE any+ // of these fire, and it lives in a package this one does not import — two+ // independent numbers is exactly how the 60-80% band opened up, where the+ // scaler acted on pressure only the cache could relieve.+ resourceDiskThreshold = diskpolicy.ScaleUpPct// Evacuation thresholds (per-worker, triggers live migration of sandboxes OFF the hot worker)evacuationCPUThreshold = 80.0evacuationMemThreshold = 80.0- evacuationDiskThreshold = 70.0+ evacuationDiskThreshold = diskpolicy.EvacuatePct// Emergency thresholds — above these, hibernate sandboxes to free resources immediately// (no migration target needed, just dump to S3 and delete local files)emergencyCPUThreshold = 95.0emergencyMemThreshold = 95.0- emergencyDiskThreshold = 90.0- evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker- evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches+ emergencyDiskThreshold = diskpolicy.EmergencyPct+ evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker+ evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches// drainTimeout caps total wall-clock time for a single drain. With// per-target serialization (one in-flight migration per target), a// drain bottlenecked on a single target processes sandboxes serially@@ -52,7 +58,7 @@ const (// of a full drain. Bumping to 6h leaves headroom for large workloads;// genuine stuck drains are caught by per-migration timeouts + the// natural-expiry fallback in drainWorker.- drainTimeout = 6 * time.Hour+ drainTimeout = 6 * time.HourcreationFailureThreshold = 3 // consecutive failures before exponential backoffcreationBackoffMin = 1 * time.Minute // initial backoff after threshold hit@@ -86,14 +92,14 @@ type OrphanCleaner interface {type ScalerConfig struct {Pool compute.PoolRegistry ScalerRegistry- Store *db.Store // for updating session worker_id after migration+ Store *db.Store // for updating session worker_id after migrationStateStore ScalerStateStore // optional: persists scaler state to Redis (nil = in-memory)WorkerImage stringCooldown time.Duration // minimum time between scale-up actions per regionInterval time.Duration // how often to evaluate scaling (0 = default 30s)- MinWorkers int // minimum total workers per region (0 = default 1). Always kept running.- MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.- IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.+ MinWorkers int // minimum total workers per region (0 = default 1). Always kept running.+ MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.+ IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.// Event emit for D1 sandboxes_index sync. After a scaler-triggered// migration succeeds (rolling replace, evacuation), XADD a "migrated"@@ -140,17 +146,17 @@ type Scaler struct {image stringcooldown time.Durationinterval time.Duration- minWorkers int- maxWorkers int- idleReserve int+ minWorkers int+ maxWorkers int+ idleReserve int- rdb *redis.Client- cellID string+ rdb *redis.Client+ cellID string- mu sync.Mutex // protects stop/cancel- cancel context.CancelFunc- wg sync.WaitGroup- running bool+ mu sync.Mutex // protects stop/cancel+ cancel context.CancelFunc+ wg sync.WaitGroup+ running boolmachineSizes []string // ranked list of provider-specific sizes for scale-up fallback@@ -745,6 +751,23 @@ func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []if s.state.IsDraining(w.MachineID) {continue}+ // Nothing to evacuate. Evacuation moves sandboxes off a worker, so a+ // worker holding none cannot be relieved by it — and this loop feeds a+ // lightest-first sort, so an empty worker sorts to the FRONT and is+ // selected every single time. It then takes the global evacuation lock,+ // runs a no-op batch, and starves whichever worker was genuinely hot.+ //+ // Pressure on an empty worker is real but is not sandbox pressure: it+ // is the checkpoint cache, logs, or orphaned files. Logged rather than+ // dropped silently, because that distinction is exactly what made the+ // cache-eviction latch invisible — the scaler appeared to be working on+ // the problem while doing nothing that could ever fix it.+ if w.Current == 0 {+ log.Printf("scaler: worker %s over threshold (cpu=%.1f%% mem=%.1f%% disk=%.1f%%) but holds NO sandboxes — "++ "not evacuable; pressure is host-side (cache/logs/orphans), not sandbox load",+ w.ID, w.CPUPct, w.MemPct, w.DiskPct)+ continue+ }if last, ok := s.state.GetLastEvacuation(w.ID); ok && time.Since(last) < evacuationCooldown {continue}diff --git a/internal/controlplane/scaler_test.go b/internal/controlplane/scaler_test.goindex 663bed17..a9a6f46b 100644--- a/internal/controlplane/scaler_test.go+++ b/internal/controlplane/scaler_test.go@@ -173,12 +173,12 @@ func (p *mockPool) DestroyMachine(_ context.Context, machineID string) error {return nil}-func (p *mockPool) DrainMachine(_ context.Context, _ string) error { return nil }-func (p *mockPool) StartMachine(_ context.Context, _ string) error { return nil }-func (p *mockPool) StopMachine(_ context.Context, _ string) error { return nil }-func (p *mockPool) HealthCheck(_ context.Context, _ string) error { return nil }-func (p *mockPool) CleanupOrphanedResources(_ context.Context) (int, error) { return 0, nil }-func (p *mockPool) ListMachines(_ context.Context) ([]*compute.Machine, error) { return nil, nil }+func (p *mockPool) DrainMachine(_ context.Context, _ string) error { return nil }+func (p *mockPool) StartMachine(_ context.Context, _ string) error { return nil }+func (p *mockPool) StopMachine(_ context.Context, _ string) error { return nil }+func (p *mockPool) HealthCheck(_ context.Context, _ string) error { return nil }+func (p *mockPool) CleanupOrphanedResources(_ context.Context) (int, error) { return 0, nil }+func (p *mockPool) ListMachines(_ context.Context) ([]*compute.Machine, error) { return nil, nil }func (p *mockPool) SupportedRegions(_ context.Context) ([]string, error) {return []string{"us-east-1"}, nil}@@ -1980,3 +1980,73 @@ func TestInMemoryScalerState_ConcurrentAccess(t *testing.T) {}wg.Wait()}++// An empty worker is never evacuable, and must never be chosen.+//+// Evacuation moves sandboxes off a worker, so a worker holding none cannot be+// relieved by it. Before the Current==0 guard this was not merely wasteful: the+// candidate list is sorted LIGHTEST FIRST, so an empty worker sorted to the+// front and won selection on every tick. It then took the global evacuation+// lock, ran a batch with nothing in it, and starved the worker that was+// actually hot.+//+// The disk case below is the one seen in production: a worker sitting in disk+// pressure caused entirely by the checkpoint cache, with zero sandboxes on it.+func TestEvacuationSkipsWorkersWithNoSandboxes(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ // Empty but over the disk threshold — cache, not sandbox load.+ reg.addWorker(&WorkerInfo{+ ID: "empty-hot", MachineID: "osb-worker-empty", Region: "us-east-1",+ Capacity: 50, Current: 0, CPUPct: 10, MemPct: 10, DiskPct: 79,+ })+ // Genuinely hot, with sandboxes that could actually move.+ reg.addWorker(&WorkerInfo{+ ID: "real-hot", MachineID: "osb-worker-real", Region: "us-east-1",+ Capacity: 50, Current: 40, CPUPct: 85, MemPct: 50, DiskPct: 30,+ })+ // Somewhere to migrate to.+ reg.addWorker(&WorkerInfo{+ ID: "cold", MachineID: "osb-worker-cold", Region: "us-east-1",+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,+ })++ s := newTestScaler(reg, pool)+ s.evacuateHotWorkers(context.Background(), "us-east-1", reg.GetWorkersByRegion("us-east-1"))++ if _, ok := s.state.GetLastEvacuation("empty-hot"); ok {+ t.Error("evacuated a worker with zero sandboxes — a no-op that holds the global " ++ "evacuation lock and starves genuinely hot workers")+ }+ if _, ok := s.state.GetLastEvacuation("real-hot"); !ok {+ t.Error("the worker with sandboxes to move was not evacuated — the empty worker " ++ "won selection by sorting lightest-first")+ }+}++// A fleet where every over-threshold worker is empty must resolve to doing+// nothing at all, and must not leave the evacuation lock held — the next tick+// has to be able to act the moment a real candidate appears.+func TestAllEmptyHotWorkersLeaveTheLockFree(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ reg.addWorker(&WorkerInfo{+ ID: "empty-a", MachineID: "osb-worker-a", Region: "us-east-1",+ Capacity: 50, Current: 0, CPUPct: 10, MemPct: 10, DiskPct: 79,+ })+ reg.addWorker(&WorkerInfo{+ ID: "empty-b", MachineID: "osb-worker-b", Region: "us-east-1",+ Capacity: 50, Current: 0, CPUPct: 90, MemPct: 10, DiskPct: 20,+ })++ s := newTestScaler(reg, pool)+ s.evacuateHotWorkers(context.Background(), "us-east-1", reg.GetWorkersByRegion("us-east-1"))++ if !s.state.TryAcquireEvacuationLock() {+ t.Fatal("evacuation lock still held after a tick that evacuated nothing — " ++ "the next genuinely hot worker would be skipped")+ }+ s.state.ReleaseEvacuationLock()+}diff --git a/internal/db/hibernation_reclaim_test.go b/internal/db/hibernation_reclaim_test.godeleted file mode 100644index 2e75a7f4..00000000--- a/internal/db/hibernation_reclaim_test.go+++ /dev/null@@ -1,50 +0,0 @@-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.sqldeleted file mode 100644index 0d1ee4f7..00000000--- a/internal/db/migrations/055_hibernation_blob_reclaim.down.sql+++ /dev/null@@ -1,2 +0,0 @@-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.sqldeleted file mode 100644index cefa0410..00000000--- a/internal/db/migrations/055_hibernation_blob_reclaim.up.sql+++ /dev/null@@ -1,37 +0,0 @@--- 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.goindex 3c06b982..b3ef98be 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -202,7 +202,6 @@ 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 {@@ -1937,13 +1936,17 @@ 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.+// KNOWN LEAK: this does not free the archive, and nothing else does either.+// From the moment restored_at is set the object is unreachable —+// GetActiveHibernation matches only restored_at IS NULL — so it is not a+// recovery copy, it is a permanent orphan in blob storage. Measured on prod+// 2026-08-17: ~10 TB across ~6.7k restored rows, on a bucket growing+// ~600 GB/day.+//+// Left in place deliberately for now. Reclaiming it means deleting customer+// data on a predicate that has never run against real data, and the archives+// share the checkpoints/ prefix with user checkpoints. That is a separate+// change with its own soak, not a rider on this one.func (s *Store) MarkHibernationRestored(ctx context.Context, sandboxID string) error {_, err := s.pool.Exec(ctx,`UPDATE sandbox_hibernations SET restored_at = now()@@ -1952,129 +1955,6 @@ func (s *Store) MarkHibernationRestored(ctx context.Context, sandboxID string) ereturn 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→diff --git a/internal/diskpolicy/policy.go b/internal/diskpolicy/policy.gonew file mode 100644index 00000000..64be3a48--- /dev/null+++ b/internal/diskpolicy/policy.go@@ -0,0 +1,57 @@+// Package diskpolicy holds the disk-pressure ladder — the one place the+// checkpoint cache and the scaler both read their thresholds from.+//+// They used to be independent numbers in packages that do not import each+// other: the cache kept a 20% reserve (evicting only above 80% full) while the+// scaler began scaling up at 60% and live-migrating sandboxes off at 70%. Two+// subsystems, one disk, no shared definition of "full".+//+// That produced a band from 60% to 80% in which the scaler was spending money+// and moving customer VMs while the largest reclaimable pool on the box — the+// checkpoint cache — was behaving exactly as designed and releasing nothing.+// Worse, the scaler's two responses cannot fix that cause: evacuating a sandbox+// frees its directory, not the cache. So the box stayed full, and the scaler+// kept reacting to pressure it had no way to relieve.+//+// The ordering below is the invariant that prevents it: the cache gives back+// everything it can BEFORE the scaler takes any action at all. By the time the+// scaler sees pressure, that pressure is real — it is sandboxes, not cache, and+// adding a worker is genuinely the right answer.+//+// TestLadderIsOrdered pins the relationship. Change a number here and the test+// tells you whether you broke it; change one in the scaler or the cache and+// there is now nowhere else to change it.+package diskpolicy++// The ladder, as percentage-full of the data volume.+const (+ // CacheEvictPct is where the checkpoint cache starts releasing LRU entries.+ //+ // First rung deliberately, and below ScaleUpPct with headroom to spare: the+ // cache is elastic and sandboxes are not, so the elastic thing must yield+ // first. Everything the cache holds is a latency optimisation — evicting it+ // costs a cold restore on the next fork of that checkpoint, which is a far+ // cheaper mistake than launching a worker or migrating a live VM.+ //+ // This bounds the cache at roughly this share of the volume rather than the+ // ~80% it could previously reach. That is the intended trade.+ CacheEvictPct = 55.0++ // ScaleUpPct is where the scaler adds a worker.+ ScaleUpPct = 60.0++ // EvacuatePct is where the scaler live-migrates sandboxes off a hot worker.+ EvacuatePct = 70.0++ // RoutingExcludePct is where a worker stops receiving new sandboxes.+ //+ // This rung is why eviction must not be demand-driven. Exclusion stops the+ // traffic that used to be the ONLY trigger for eviction, so a cache that+ // evicts only when something is being downloaded can never shrink once its+ // worker crosses this line — the worker latches out of the fleet and stays+ // there. See CheckpointStore.StartEvictionSweeper.+ RoutingExcludePct = 85.0++ // EmergencyPct is where sandboxes are hibernated to free space immediately.+ EmergencyPct = 90.0+)diff --git a/internal/diskpolicy/policy_test.go b/internal/diskpolicy/policy_test.gonew file mode 100644index 00000000..a29d6e15--- /dev/null+++ b/internal/diskpolicy/policy_test.go@@ -0,0 +1,84 @@+package diskpolicy++import "testing"++// The ladder only works in order. Each rung is a different actor reacting to+// the same disk, and reordering any two of them produces a system that fights+// itself rather than one that escalates.++// The invariant the whole package exists for: the cache must release space+// before the scaler spends any.+//+// Violate this and you get the 2026-08 failure mode back — a worker sitting at+// 79% full with the scaler adding capacity and migrating customer VMs, while+// the cache holds hundreds of gigabytes it considers legitimately in use. The+// scaler cannot win that fight: evacuating a sandbox frees its directory, and+// the bytes occupying the disk are cache it never touches.+func TestCacheEvictsBeforeScalerActs(t *testing.T) {+ if CacheEvictPct >= ScaleUpPct {+ t.Fatalf("CacheEvictPct (%.0f) must be below ScaleUpPct (%.0f) — otherwise the scaler "++ "launches workers to relieve pressure the cache could have released for free",+ CacheEvictPct, ScaleUpPct)+ }+ if CacheEvictPct >= EvacuatePct {+ t.Fatalf("CacheEvictPct (%.0f) must be below EvacuatePct (%.0f) — otherwise live customer "++ "VMs are migrated to reclaim space the cache was still holding",+ CacheEvictPct, EvacuatePct)+ }+}++// The full ordering. Written out rung by rung because the failure of any single+// pair is its own distinct incident, and a generic "sorted" assertion would+// report the wrong one.+func TestLadderIsOrdered(t *testing.T) {+ rungs := []struct {+ name string+ pct float64+ }{+ {"CacheEvictPct", CacheEvictPct},+ {"ScaleUpPct", ScaleUpPct},+ {"EvacuatePct", EvacuatePct},+ {"RoutingExcludePct", RoutingExcludePct},+ {"EmergencyPct", EmergencyPct},+ }+ for i := 1; i < len(rungs); i++ {+ if rungs[i-1].pct >= rungs[i].pct {+ t.Errorf("%s (%.0f) must be below %s (%.0f): the ladder escalates, so a later "++ "rung firing first means the cheaper response never gets a chance",+ rungs[i-1].name, rungs[i-1].pct, rungs[i].name, rungs[i].pct)+ }+ }+}++// Headroom between the cache and the scaler is deliberate, not incidental.+//+// Without a gap, a burst of sandbox writes crossing the cache threshold trips+// the scaler in the same instant — before eviction has had a sweep interval to+// take effect. The gap is what turns "the cache is about to give space back"+// into a state the scaler never has to react to.+func TestCacheHasHeadroomBeforeScaleUp(t *testing.T) {+ const minHeadroom = 5.0+ if got := ScaleUpPct - CacheEvictPct; got < minHeadroom {+ t.Fatalf("only %.0f points between CacheEvictPct and ScaleUpPct, want at least %.0f — "++ "a write burst would trip the scaler before eviction could take effect", got, minHeadroom)+ }+}++// Every rung is a percentage of a volume. A value outside 0-100 is a typo that+// would silently disable whichever actor reads it.+func TestRungsArePercentages(t *testing.T) {+ for _, r := range []struct {+ name string+ pct float64+ }{+ {"CacheEvictPct", CacheEvictPct},+ {"ScaleUpPct", ScaleUpPct},+ {"EvacuatePct", EvacuatePct},+ {"RoutingExcludePct", RoutingExcludePct},+ {"EmergencyPct", EmergencyPct},+ } {+ if r.pct <= 0 || r.pct >= 100 {+ t.Errorf("%s = %.0f is not a usable fill percentage", r.name, r.pct)+ }+ }+}diff --git a/internal/storage/cache_evict_test.go b/internal/storage/cache_evict_test.gonew file mode 100644index 00000000..1d3326da--- /dev/null+++ b/internal/storage/cache_evict_test.go@@ -0,0 +1,72 @@+package storage++import (+ "context"+ "testing"++ "github.com/opensandbox/opensandbox/internal/diskpolicy"+)++// cache_evict_test.go — when the checkpoint cache gives space back.+//+// Getting this wrong does not look like a cache bug. It looks like a scaler+// that will not stop launching workers, because the scaler is reacting to disk+// the cache is holding and only the cache can release.++// The reserve must be whatever the shared ladder says, not a local fraction.+//+// The literal it replaced was `totalBytes / 5` — a 20% reserve, meaning the+// cache happily filled to 80% of the volume. The scaler starts scaling up at+// 60% and evacuating at 70%, so the cache's own definition of "comfortable"+// began 20 points ABOVE the point at which the rest of the system considered+// the box in trouble.+func TestReserveTracksTheSharedLadder(t *testing.T) {+ const total = 1000++ got := cacheReserveBytes(total)+ want := uint64(float64(total) * (100 - diskpolicy.CacheEvictPct) / 100)+ if got != want {+ t.Fatalf("reserve = %d, want %d (%.0f%% free)", got, want, 100-diskpolicy.CacheEvictPct)+ }++ // The property that matters, stated independently of the formula: the cache+ // must still consider itself over budget at a fill level the scaler has+ // already started reacting to.+ usedAtScaleUp := uint64(float64(total) * diskpolicy.ScaleUpPct / 100)+ availAtScaleUp := total - usedAtScaleUp+ if availAtScaleUp > got {+ t.Fatalf("at %.0f%% full the cache still considers itself comfortable "++ "(avail %d > reserve %d) — the scaler would be adding workers while the cache holds space",+ diskpolicy.ScaleUpPct, availAtScaleUp, got)+ }+}++// The old 20% reserve, pinned as a regression guard. Anyone reintroducing it —+// or any value that lets the cache outgrow the scaler's first rung — trips this.+func TestCacheCannotFillPastTheScalerThreshold(t *testing.T) {+ const total = 1_000_000+ reserve := cacheReserveBytes(total)++ maxCacheFillPct := 100 * float64(total-reserve) / float64(total)+ if maxCacheFillPct >= diskpolicy.ScaleUpPct {+ t.Fatalf("cache may fill to %.0f%% of the volume, at or beyond the scaler's %.0f%% "++ "scale-up threshold — this is the 60-80%% dead band, restored",+ maxCacheFillPct, diskpolicy.ScaleUpPct)+ }+}++// The sweeper must be inert when caching is disabled. It is started from the+// worker's boot path, where a cache dir is optional, and a nil-guard failure+// there takes down the whole worker rather than degrading one feature.+func TestSweeperIsInertWithoutACacheDir(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ var nilStore *CheckpointStore+ nilStore.StartEvictionSweeper(ctx) // must not panic++ (&CheckpointStore{}).StartEvictionSweeper(ctx) // no cacheDir — must not panic++ // And eviction itself must decline rather than statfs("").+ (&CheckpointStore{}).evictIfNeeded()+}diff --git a/internal/storage/s3.go b/internal/storage/s3.goindex 33ff945d..51560cbe 100644--- a/internal/storage/s3.go+++ b/internal/storage/s3.go@@ -15,6 +15,7 @@ import ("time""github.com/opensandbox/opensandbox/internal/blobstore"+ "github.com/opensandbox/opensandbox/internal/diskpolicy""golang.org/x/sys/unix")@@ -381,13 +382,83 @@ func (s *CheckpointStore) downloadFromS3(ctx context.Context, key string) (io.Rereturn body, nil}-// evictIfNeeded removes the oldest cached checkpoints when the filesystem-// is low on space. Policy: keep 20% of total filesystem space free for-// active sandboxes (workspaces, container layers, temp files).+// cacheReserveBytes is how much of the volume must stay free for the cache to+// consider itself within budget: everything above diskpolicy.CacheEvictPct+// full.+//+// Pulled out as a pure function so the arithmetic has a test. It replaced a+// literal `totalBytes / 5` — a 20% reserve that let the cache fill to 80% of+// the volume, which is above every threshold the scaler reacts to.+func cacheReserveBytes(totalBytes uint64) uint64 {+ return uint64(float64(totalBytes) * (100 - diskpolicy.CacheEvictPct) / 100)+}++// cacheSweepInterval paces the background eviction sweep.+//+// The common tick costs one statfs and returns, so this can be frequent. It+// needs to be well inside the time the scaler takes to react — a sweep that ran+// hourly would let a worker sit in disk pressure for most of an hour with+// reclaimable space on it.+const cacheSweepInterval = time.Minute++// StartEvictionSweeper evicts on a timer for the life of the process.+//+// This exists because eviction used to be reachable ONLY from cacheFromFile and+// downloadAndCache — that is, only while something was being written into the+// cache. That coupling turns disk pressure into a latch:+//+// worker crosses RoutingExcludePct → stops receiving sandboxes+// → nothing downloads checkpoints → evictIfNeeded is never called+// → the cache never shrinks → the worker never comes back+//+// Exclusion removes the very traffic that was the only trigger for the cleanup+// that would end the exclusion. A worker in that state stays out of the fleet+// until someone restarts it, holding hundreds of gigabytes it would happily+// have released if anything had asked.+//+// A timer asks.+func (s *CheckpointStore) StartEvictionSweeper(ctx context.Context) {+ if s == nil || s.cacheDir == "" {+ return+ }+ go func() {+ t := time.NewTicker(cacheSweepInterval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ s.evictIfNeeded()+ }+ }+ }()+ log.Printf("checkpoint-cache: eviction sweeper started (every %s, target %.0f%% full)",+ cacheSweepInterval, diskpolicy.CacheEvictPct)+}++// evictIfNeeded removes the oldest cached checkpoints once the filesystem is+// fuller than diskpolicy.CacheEvictPct.+//+// That threshold is deliberately the FIRST rung of the disk-pressure ladder,+// below every scaler reaction. The cache is elastic and sandboxes are not, so+// the elastic thing yields first: everything held here is a latency+// optimisation, and paying a cold restore on the next fork is far cheaper than+// launching a worker or live-migrating a customer's VM to reclaim the same+// bytes.+//+// It previously kept a flat 20% reserve — evicting only above 80% full — while+// the scaler began scaling up at 60% and evacuating at 70%. In that band the+// scaler was reacting to pressure it could not relieve, because evacuating a+// sandbox frees its directory and never touches this cache.func (s *CheckpointStore) evictIfNeeded() {s.cacheMu.Lock()defer s.cacheMu.Unlock()+ if s.cacheDir == "" {+ return+ }+var stat unix.Statfs_tif err := unix.Statfs(s.cacheDir, &stat); err != nil {log.Printf("checkpoint-cache: statfs failed: %v", err)@@ -396,7 +467,8 @@ func (s *CheckpointStore) evictIfNeeded() {totalBytes := stat.Blocks * uint64(stat.Bsize)availBytes := stat.Bavail * uint64(stat.Bsize)- reserveBytes := totalBytes / 5 // 20% reserve++ reserveBytes := cacheReserveBytes(totalBytes)if availBytes > reserveBytes {return