An open-source, faster Devin alternative
TypeScript
feat(api): dispatch managed runtimes through the backend seam — PTY and exec-session splices that translate the guest's framed protocol to the binary contract the SDK expects, plus an audit test pinning the recurring bug where a handler reaches for the worker registry without asking who holds the sandbox
Brian Reardon162ee1c1d623
diff --git a/internal/api/backend.go b/internal/api/backend.goindex 5308f9fe..366aad1f 100644--- a/internal/api/backend.go+++ b/internal/api/backend.go@@ -2,6 +2,8 @@ package apiimport ("context"+ "fmt"+ "net/http""sync""time"@@ -13,6 +15,8 @@ import ("github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/pkg/types"++ "github.com/opensandbox/opensandbox/internal/storage")// backend.go — the seam between sandbox runtimes.@@ -86,7 +90,7 @@ type Backend interface {// cmd/server before any Server exists, and because its predicate should cover// backends that are currently disabled: rows written while one was enabled// outlive the flag, and forgetting them would reap live sandboxes.-var knownBackends = []Backend{(*microvmBackend)(nil)}+var knownBackends = []Backend{(*liteBackend)(nil)}// ManagedWorkerIDPrefixes is the union of every known backend's worker_id// prefixes, for callers that must recognize managed sandboxes in SQL before the@@ -275,6 +279,74 @@ func (s *Server) hibernatorFor(workerID string) (Hibernator, bool) {return h, ok}+// IdleTimeouter is a backend that can park a sandbox after a period of+// customer inactivity.+//+// Separate from Hibernator because the two answer different questions: that one+// parks on demand, this one decides WHEN. A runtime may honour a timeout only+// partly — a provider that destroys hosts on its own schedule caps what any+// timeout can promise — so the setter reports the value actually in force+// rather than echoing the request.+type IdleTimeouter interface {+ // SetIdleTimeout applies a timeout and returns the one now in effect.+ // Zero means no timeout is running, whether because the caller asked for+ // none or because the runtime could not honour the one requested.+ SetIdleTimeout(sandboxID string, d time.Duration) (time.Duration, error)+}++// checkpointKindUnsupported reports whether the runtime holding a sandbox is+// unable to capture memory state, which is what a "full" checkpoint is.+//+// Asked of the backend rather than hardcoded per runtime: the property being+// tested is "can this host's RAM be snapshotted", and only the backend knows.+// A worker-held sandbox answers false and every existing QEMU path is+// unchanged.+func (s *Server) checkpointKindUnsupported(workerID string) bool {+ b, ok := s.backendForWorkerID(workerID)+ if !ok {+ return false+ }+ c, ok := b.(MemoryStateCapturer)+ return ok && !c.CapturesMemoryState()+}++// MemoryStateCapturer is a backend that can say whether its hosts support+// snapshotting RAM. Absent means "yes", so a backend that never thought about+// it keeps today's behaviour.+type MemoryStateCapturer interface {+ CapturesMemoryState() bool+}++// dispatchIdleTimeout sends a timeout request to the backend that owns the+// sandbox, falling back to the proxy for a worker-held one.+//+// Needed because the proxy route is wrapped in refuseIfManaged, which 501s+// every managed sandbox — correct while this runtime had no idle policy, and+// wrong now that it does. Without this the customer's timeout is rejected+// outright. Mirrors dispatchPTY.+func (s *Server) dispatchIdleTimeout(local, proxied echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ if s.store != nil {+ if session, err := s.store.GetSandboxSession(c.Request().Context(), c.Param("id")); err == nil && session != nil {+ if _, ok := s.idleTimeouterFor(session.WorkerID); ok {+ return local(c)+ }+ }+ }+ return proxied(c)+ }+}++// idleTimeouterFor resolves the backend that owns a sandbox's idle policy.+func (s *Server) idleTimeouterFor(workerID string) (IdleTimeouter, bool) {+ b, ok := s.backendForWorkerID(workerID)+ if !ok {+ return nil, false+ }+ t, ok := b.(IdleTimeouter)+ return t, ok+}+// placement is the request-scoped input to Claim.//// Region is here rather than on the backend because it is a property of the@@ -329,6 +401,11 @@ type activated struct {sandboxID stringstatus stringgoldenVersion string+ // endAt is when the runtime's provider will destroy this host regardless of+ // anything we do, or zero when there is no such deadline (the QEMU fleet) or+ // it cannot be determined. Stamped on the row so that a row outliving its+ // host stops being something a sweep has to notice — see migration 056.+ endAt time.Time}// registerBackend adds a runtime to the dispatch set.@@ -401,6 +478,87 @@ func (s *Server) backendForWorkerID(workerID string) (Backend, bool) {// 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.+// HaltRestoreSpec is the shape a halted sandbox has to come back as. Carried+// explicitly rather than re-read from the runtime, because by resume time the+// runtime holds nothing: the host was released at halt.+type HaltRestoreSpec struct {+ Template string+ MemoryMB int+ CPUCount int+}++// haltArchiver is implemented by a backend whose sandboxes can be parked in a+// way that OUTLIVES their host — the state goes to durable storage and the host+// is given back entirely.+//+// This exists because suspending is not enough on every runtime. The MicroVM+// provider counts suspended time against the same hard lifetime cap as running+// time, so a suspended sandbox still dies at the cap and takes its disk with+// it. A credit halt routinely lasts days, so parking that way would quietly+// destroy the data of every org that failed to pay within one lifetime.+//+// The three methods are deliberately NOT one call. Archiving and releasing are+// separated so the caller can durably record the archive while the host is+// still alive: releasing first would mean a failed record write leaves an+// archive nothing points at and a host that no longer exists, which is+// unrecoverable. Everything else in this file that destroys something records+// it first for the same reason.+type haltArchiver interface {+ // ArchiveForHalt writes durable state to the checkpoint store and does NOT+ // touch the host.+ ArchiveForHalt(ctx context.Context, sandboxID string, store *storage.CheckpointStore) (key string, sizeBytes int64, err error)+ // ReleaseForHalt terminates the host. The point of no return — only safe+ // once the archive from ArchiveForHalt has been recorded.+ ReleaseForHalt(ctx context.Context, sandboxID string) error+ // RestoreForResume gives the sandbox a NEW host and lays the archive back+ // onto it, returning the worker id now serving it.+ RestoreForResume(ctx context.Context, sandboxID, key string, store *storage.CheckpointStore, spec HaltRestoreSpec) (workerID string, err error)+}++// haltArchiverFor resolves the backend that can deep-park a sandbox, keyed by+// the worker id on its row.+//+// Keyed by worker id rather than by a live lookup because at RESUME time the+// sandbox has no host at all — the id is the only surviving evidence of which+// runtime was serving it.+func (s *Server) haltArchiverFor(workerID string) (haltArchiver, bool) {+ b, ok := s.backendForWorkerID(workerID)+ if !ok {+ return nil, false+ }+ ha, ok := b.(haltArchiver)+ return ha, ok+}++// placementExplainer is implemented by a Placer that can say WHY it refused a+// create, when the reason is permanent.+//+// Without it every refusal collapses into "out of capacity", which is both+// wrong and actively misleading for a request we are never going to serve: a+// customer asking for a size this region does not offer is told to wait for+// capacity and retry, and no amount of waiting or retrying will change the+// answer. Only permanent reasons belong here — a transient shortage really is+// a capacity answer and should stay one.+type placementExplainer interface {+ ExplainRefusal(p placement) error+}++// explainRefusal asks every registered backend whether it refused this create+// for a permanent reason, returning the first such reason. Nil means no+// backend claimed a permanent objection, so the refusal is a capacity answer.+func (s *Server) explainRefusal(p placement) error {+ for _, b := range s.backends {+ ex, ok := b.(placementExplainer)+ if !ok {+ continue+ }+ if err := ex.ExplainRefusal(p); err != nil {+ return err+ }+ }+ return nil+}+func (s *Server) claimBackend(p placement) (Placer, bool) {for _, b := range s.backends {placer, ok := b.(Placer)@@ -531,6 +689,29 @@ func (s *Server) dispatchDataPlane(local, proxied echo.HandlerFunc) echo.Handler}}+// refuseIfManaged wraps a proxy-only route so a sandbox held by a registered+// backend is answered rather than proxied.+//+// The routes this guards — PTY, agent sessions, mounts, timeout, token refresh,+// bidi exec streaming — are the ones no managed backend implements, so they go+// straight to the worker proxy. That was not a graceful degradation. The proxy+// resolves through the worker registry, a managed sandbox has no entry there,+// and it concludes the worker was lost and writes the row to `stopped`: one PTY+// request would destroy a healthy sandbox and every later request would 410.+//+// 501 is the honest answer — this runtime will never serve this — as opposed to+// a 5xx that invites a retry against a sandbox that is fine.+func (s *Server) refuseIfManaged(proxied echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ if b, _, ok := s.backendFor(c.Request().Context(), c.Param("id")); ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{+ "error": fmt.Sprintf("%s sandboxes do not support this operation", b.Name()),+ })+ }+ return proxied(c)+ }+}+// managerFor returns the manager that should serve this request: the holding// backend's when one holds the sandbox, otherwise the local manager.//diff --git a/internal/api/backend_conformance_test.go b/internal/api/backend_conformance_test.goindex 6161a4a6..7a07305b 100644--- a/internal/api/backend_conformance_test.go+++ b/internal/api/backend_conformance_test.go@@ -40,29 +40,10 @@ type conformanceBackend struct {var conformanceBackends = []conformanceBackend{{- name: "vmhost",- buildDisabled: func() Backend { return (*microvmBackend)(nil) },- ownedWorkerID: microvmWorkerID("abc123"),- foreignWorkerIDs: []string{- "w-azure-osb-worker-2512f614", // a real QEMU worker- "worker-eastus2-7",- "",- "vmhost:", // prefix with no id- "vmhost", // prefix without separator- "microvm:", // legacy prefix, no id- // A RAW provider host id. This is the shape the provider SDK- // returns, and it is deliberately NOT owned — which is why Claim- // must encode before returning a worker_id. Returning the raw id- // made every row invisible to the orphan sweep, the restore scan,- // and the event publisher, all of which match on the prefixes.- hostIDPrefix + "abc123",- },- },- {- // The direct-exec data plane over the SAME hosts. Its identity answers- // are deliberately identical to vmhost's — the worker_id names the box,- // and switching data planes must not orphan the other one's rows — so- // running the whole contract against it is what proves that stayed true.+ // The MicroVM runtime. Its identity answers still cover the encoding the+ // deleted agent-tunnel backend wrote as well as its own — the worker_id+ // names the box, and rows written by the other data plane must not be+ // orphaned, because a row nothing claims is a box nothing terminates.name: "vmhost-lite",buildDisabled: func() Backend { return (*liteBackend)(nil) },ownedWorkerID: microvmWorkerID("abc123"),@@ -78,33 +59,35 @@ var conformanceBackends = []conformanceBackend{},}-// The two managed backends must never both be registered on a cell: they-// manufacture from one image against one regional quota, and two fillers each-// believing they own the fleet overrun it and starve each other. The exclusion-// lives in newMicrovmBackend, which stands down when the lite flag is set.-func TestManagedBackendsAreMutuallyExclusive(t *testing.T) {+// There is one MicroVM backend now. OPENSANDBOX_MICROVM_LITE used to select+// between two data planes on the same fleet; the agent-tunnel one is deleted,+// so the flag must no longer be able to turn the runtime off — a cell that+// enabled MicroVMs and got no MicroVM backend registered would serve nothing+// and fall through to a worker fleet it does not have.+func TestMicrovmRuntimeEnablesOnItsOwnFlag(t *testing.T) {t.Setenv("OPENSANDBOX_MICROVM_ENABLED", "1")- t.Setenv("OPENSANDBOX_MICROVM_IMAGE_ARN", "arn:aws:test:::image/x")- t.Setenv("OPENSANDBOX_MICROVM_LITE", "1")- // No AWS call is reached: the stand-down is checked before the client is- // built, which is also what makes this test runnable without credentials.- b, err := newMicrovmBackend(context.Background(), nil)- if err != nil {- t.Fatalf("newMicrovmBackend: %v", err)- }- if b != nil {- t.Fatal("the agent-tunnel backend built itself while the direct-exec one is enabled — both would fill from the same quota")+ for _, lite := range []string{"1", "", "0"} {+ t.Setenv("OPENSANDBOX_MICROVM_LITE", lite)+ if !liteEnabled() {+ t.Fatalf("OPENSANDBOX_MICROVM_LITE=%q disabled the MicroVM runtime — "++ "the backend it used to select no longer exists, so this cell "++ "would register no MicroVM backend at all", lite)+ }}}-// ...and with the flag off, nothing changes for the path production runs. A-// regression here would silently take prod's MicroVM cells off their backend.-func TestAgentBackendStillBuildsWithoutTheLiteFlag(t *testing.T) {- t.Setenv("OPENSANDBOX_MICROVM_ENABLED", "1")- t.Setenv("OPENSANDBOX_MICROVM_LITE", "")+// ...and it stays off for every cell that never asked for it, which is every+// QEMU cell in production. No AWS call may be reached from a build here.+func TestMicrovmRuntimeStaysOffWhenUnasked(t *testing.T) {+ t.Setenv("OPENSANDBOX_MICROVM_ENABLED", "")+ t.Setenv("OPENSANDBOX_MICROVM_LITE", "1")if liteEnabled() {- t.Fatal("liteEnabled() is true with the flag unset")+ t.Fatal("the MicroVM runtime enabled itself on a cell that did not ask for it")+ }+ b, err := newLiteBackend(context.Background(), nil)+ if err != nil || b != nil {+ t.Fatalf("newLiteBackend built something with the runtime disabled: %v, %v", b, err)}}diff --git a/internal/api/backend_dispatch_audit_test.go b/internal/api/backend_dispatch_audit_test.gonew file mode 100644index 00000000..3e22b9fa--- /dev/null+++ b/internal/api/backend_dispatch_audit_test.go@@ -0,0 +1,144 @@+package api++import (+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "testing"+)++// backend_dispatch_audit_test.go — the recurring bug, pinned.+//+// A handler that opens with `if s.workerRegistry != nil { …Remote(…) }` and+// never asks who holds the sandbox can only ever answer "no gRPC connection to+// worker vmhost:…" for a managed runtime — for an operation whose manager+// implements it correctly. That is not a graceful degradation; it reads as an+// outage, and the manager code sits there unreachable and unnoticed.+//+// It has now happened four separate times: the proxy routes that marked healthy+// MicroVM sandboxes `stopped`, PTY, reboot/power-cycle, and stats. The cause is+// structural — internal/api/backend.go was introduced AFTER these handlers+// existed, and nothing forces a route through it.+//+// So this test is the forcing function. A handler is either backend-aware, or+// it is on the list below with a reason.++// knownUnwired are handlers that dispatch to the worker path without consulting+// the backend seam, and are deliberately still that way.+//+// Removing an entry as you wire one up is the point. ADDING one should be a+// conscious act with a reason next to it, not something a new route falls into.+var knownUnwired = map[string]string{+ // createCheckpoint and restoreCheckpoint are wired (2026-08-31). What is+ // left of the family is genuinely QEMU-shaped: promotion is a disk_only→full+ // transition a workspace archive has no tier for, and fork CREATES a+ // sandbox, which belongs to the placement path rather than a manager call.+ "promoteCheckpointToFull": "checkpoint handlers mix DB bookkeeping with dispatch",+ "createFromCheckpointCore": "fork needs the create/placement flow, not a manager call",+ "execPatchOnSandbox": "checkpoint-patch path, follows the checkpoint family",++ // Scaling is a QEMU capability (virtio-mem). The managed runtimes size by+ // image and have nothing to dispatch; this wants a 501 like setLimits got.++ // Reads that answer from the database rather than the runtime.+ "listSandboxes": "answers from the sandboxes table, not the runtime",++ // Worker-fleet operations. A managed backend has no worker to drain,+ // evict, or manufacture pool stock on, so there is nothing to dispatch.+ "adminSetWorkerDraining": "operates on a worker, not a sandbox",+ "adminForceHibernate": "empties one worker; managed backends have none",+ "adminEvictWorker": "operates on a worker, not a sandbox",+ "listWorkers": "enumerates the worker fleet",+ "manufacturePoolBoxOn": "QEMU pool manufacture; lite pools via its own manager",+ "reconcilePool": "QEMU pool reconciliation",+ "WipeWorkerPool": "QEMU pool teardown",+ "tryClaimPooled": "claims from the QEMU pool specifically",+ "proxyWorkerHTTP": "the worker leg of an already-dispatched proxy",++ // Live migration is a QEMU capability (dirty-page transfer between two+ // hosts we own). Managed backends cannot migrate at all.+ "migrateSandbox": "live migration is QEMU-only",+ "findScaleMigrationTargets": "live migration is QEMU-only",+ "migrateForScale": "live migration is QEMU-only",++ // Edge-claim finalize dispatches to the MicroVM backend through its own+ // EdgeFinalize path; the registry call here is the QEMU branch.+ "claimFinalize": "QEMU branch; MicroVM finalize goes via EdgeFinalize",+ "reapStaleEdgeReservations": "QEMU branch; MicroVM reservations reaped by the backend",++ // Org halt/resume are wired as of 2026-09-01: haltOne and wakeForResume+ // ask haltArchiverFor first. hibernateForHalt is what remains of the QEMU+ // half — the leg haltOne chooses, exactly like a `…Remote` function.+ "hibernateForHalt": "the QEMU leg, chosen by haltOne after it asks the seam",+ "internalDeepHibernate": "deep hibernation is a QEMU checkpoint tier",+ "hibernateDeepFallback": "deep hibernation is a QEMU checkpoint tier",+ "adminReport": "admin aggregate, not a per-sandbox dispatch",+ "buildImage": "image build is worker-fleet only",+}++func TestHandlersConsultTheBackendSeamBeforeTheWorkerRegistry(t *testing.T) {+ aware := []string{+ "backendFor", "execManagerFor", "hibernatorFor", "managerFor",+ "backendForWorkerID", "ptyBackendFor", "execSessionBackendFor",+ "haltArchiverFor",+ }+ fnRe := regexp.MustCompile(`(?ms)^func \(s \*Server\) (\w+)\([^\n]*\{\n(.*?)\n\}`)++ // Every file that touches the registry, not a hand-kept subset. The+ // secret-refresh fanout lived in projects.go and so was invisible to this+ // test for as long as the list was curated by hand.+ paths, err := filepath.Glob("*.go")+ if err != nil {+ t.Fatalf("glob: %v", err)+ }+ for _, path := range paths {+ if strings.HasSuffix(path, "_test.go") {+ continue+ }+ src, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ for _, m := range fnRe.FindAllStringSubmatch(string(src), -1) {+ name, body := m[1], m[2]+ // ANY use of the registry, not just the `!= nil` guard. The bug+ // this test exists to catch also wears two other costumes: an+ // early `if s.workerRegistry == nil { return }`, which turns the+ // whole operation into a silent no-op on a registry-less cell,+ // and a bare `s.workerRegistry.GetWorkerClient(…)`.+ reg := -1+ for _, use := range []string{"s.workerRegistry != nil", "s.workerRegistry == nil", "s.workerRegistry."} {+ if i := strings.Index(body, use); i >= 0 && (reg < 0 || i < reg) {+ reg = i+ }+ }+ if reg < 0 {+ continue+ }+ // A `…Remote` function IS the worker leg — a seam-aware caller+ // already chose it. Requiring it to re-ask would be circular.+ if strings.HasSuffix(name, "Remote") {+ continue+ }+ first := -1+ for _, a := range aware {+ if i := strings.Index(body, a); i >= 0 && (first < 0 || i < first) {+ first = i+ }+ }+ backendFirst := first >= 0 && first < reg+ _, allowed := knownUnwired[name]++ if !backendFirst && !allowed {+ t.Errorf("%s (%s) dispatches to the worker registry without asking who holds the sandbox — "++ "a managed sandbox can only get 'no gRPC connection to worker vmhost:…'. "++ "Add an execManagerFor/backendFor branch before it, or add it to knownUnwired with a reason.",+ name, path)+ }+ if backendFirst && allowed {+ t.Errorf("%s (%s) is backend-aware now — remove it from knownUnwired", name, path)+ }+ }+ }+}diff --git a/internal/api/backend_gating_test.go b/internal/api/backend_gating_test.goindex 328360e8..6d25d4be 100644--- a/internal/api/backend_gating_test.go+++ b/internal/api/backend_gating_test.go@@ -1,8 +1,11 @@package apiimport (+ "context"+ "errors""net/http""net/http/httptest"+ "strings""testing""time"@@ -10,6 +13,8 @@ import ("github.com/labstack/echo/v4""github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/awsvm"+ "github.com/opensandbox/opensandbox/internal/awsvmlite""github.com/opensandbox/opensandbox/pkg/types")@@ -19,6 +24,18 @@ func newTestEchoContext() echo.Context {return echo.New().NewContext(req, httptest.NewRecorder())}+// newGatingLite builds the MicroVM backend in the state placement decisions are+// made from: a client whose image config is populated (so size gating has a+// default tier to compare against) and nothing else. Placement reads no+// manager, no pool, and no network.+func newGatingLite() *liteBackend {+ return &liteBackend{+ client: awsvm.NewClientWithAPI(nil, awsvm.Config{+ ImageIdentifier: "arn:test:image",+ }),+ }+}+// 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@@ -38,7 +55,7 @@ func newTestEchoContext() echo.Context {// fleet, which is the only backend that can serve anything.func TestUnassignedRuntimeGoesToTheFleet(t *testing.T) {var fleet workerBackend- micro := µvmBackend{}+ micro := newGatingLite()if !fleet.Accepts(placement{runtime: ""}) {t.Error("fleet declined an unassigned create — orgs with no D1 runtime would 503")@@ -51,7 +68,7 @@ func TestUnassignedRuntimeGoesToTheFleet(t *testing.T) {// An explicit assignment routes to exactly that runtime and no other.func TestRuntimeAssignmentRoutesExactly(t *testing.T) {var fleet workerBackend- micro := µvmBackend{}+ micro := newGatingLite()if !micro.Accepts(placement{runtime: runtimeMicrovm}) {t.Error("MicroVM declined an org assigned to it — the assignment would do nothing")@@ -71,7 +88,7 @@ func TestRuntimeAssignmentRoutesExactly(t *testing.T) {// how an unassigned org reaches the fleet on a cell running both.func TestUnassignedFallsThroughToTheFleet(t *testing.T) {s := &Server{}- s.registerBackend(µvmBackend{})+ s.registerBackend(newGatingLite())s.registerBackend(&fakePlacer{&fakeBackend{name: "fleet"}})got, ok := s.claimBackend(placement{runtime: ""})@@ -107,7 +124,7 @@ func TestAssignedRuntimeAbsentOnCellFailsRatherThanFallsBack(t *testing.T) {// 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{}+ b := newGatingLite()s := &Server{backends: []Backend{b}}// The org has been moved back to the fleet: no NEW create lands here.@@ -126,18 +143,28 @@ func TestReassigningRuntimeNeverStrandsRunningSandboxes(t *testing.T) {}// 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.+// to it. Size is the case that must be caught HERE: memory is a property of the+// image, so a tier this cell has published no image for can never be corrected+// after launch — declining turns it into a clean placement failure instead of a+// sandbox that is quietly the wrong size and metered at the size it was asked+// for.+//+// Templates are deliberately NOT in that category any more. A template is+// served by claiming a pooled default box and unpacking the template's+// workspace archive onto it, so it costs a tarball rather than a published+// image; and placement is handed the template NAME, not the resolved drive+// keys, so whether a specific template is servable simply cannot be decided at+// this point. That refusal lives in Activate, which has the keys — see+// TestActivateRefusesARootfsBearingTemplate.func TestDeclinesRequestsItCannotServe(t *testing.T) {- b := µvmBackend{}+ b := newGatingLite()- 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")+ if b.Accepts(placement{runtime: runtimeMicrovm, cfg: types.SandboxConfig{MemoryMB: 65536}}) {+ t.Error("accepted a size tier with no published image — memory cannot be adjusted after launch, so the sandbox would be silently the wrong size")}- for _, tmpl := range []string{"", "default"} {+ for _, tmpl := range []string{"", "default", "customer-toolchain-v3"} {if !b.Accepts(placement{runtime: runtimeMicrovm, cfg: types.SandboxConfig{Template: tmpl}}) {- t.Errorf("declined template %q, which maps to its own image", tmpl)+ t.Errorf("declined template %q — templates are served from a workspace archive on a pooled box", tmpl)}}}@@ -146,7 +173,7 @@ func TestDeclinesRequestsItCannotServe(t *testing.T) {// 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{}+ b := newGatingLite()org := uuid.MustParse("11111111-1111-4111-8111-111111111111")if b.Accepts(placement{orgID: org, runtime: ""}) {@@ -201,3 +228,83 @@ func TestOrgRuntimeCacheExpires(t *testing.T) {t.Errorf("live entry not served: got %q ok=%v", got, ok)}}++// Templates are accepted at placement, so the refusal for one this runtime+// cannot honour has to land here, where the resolved drive keys exist.+//+// A template carrying a ROOTFS drive was made on the QEMU fleet, where a+// snapshot captures the whole disk. This runtime can replay only the workspace+// half, and doing that silently is the dangerous outcome: the customer gets+// their files back while every system change the snapshot was taken for is+// dropped — a template that looks like it worked and didn't. The empty rootfs+// key is a sound "made here" marker because this runtime's own CreateCheckpoint+// returns "" for it and the store persists that as an empty string, not NULL.+func TestActivateRefusesARootfsBearingTemplate(t *testing.T) {+ b := newGatingLite()+ // An empty manager: it holds no boxes, so the restore path fails cleanly+ // instead of reaching AWS. The rootfs guard must fire before it either way.+ b.mgr = awsvmlite.New(nil, awsvmlite.Config{})+ _, err := b.Activate(context.Background(), activation{+ sandboxID: "sb-cross-runtime",+ templateRootfsKey: "templates/qemu-made/rootfs.qcow2",+ templateWorkspaceKey: "templates/qemu-made/workspace.tgz",+ })+ if err == nil {+ t.Fatal("accepted a QEMU-made template — the customer would get the workspace half " ++ "and silently lose every system change the snapshot was taken for")+ }++ // ...and a template with no rootfs drive is not refused by that guard. It+ // reaches the restore, which fails here only because there is no box.+ _, err = b.Activate(context.Background(), activation{+ sandboxID: "sb-native",+ templateWorkspaceKey: "templates/lite-made/workspace.tgz",+ })+ if err != nil && strings.Contains(err.Error(), "carries a rootfs image") {+ t.Fatal("a workspace-only template was refused as cross-runtime")+ }+}++// Resizing is refused by the runtime, not by a hardcoded rule in the handler.+//+// The scale handler used to fall through to the worker registry, and a managed+// cell HAS a registry with no workers in it — so a customer asking to resize a+// MicroVM sandbox got "no gRPC connection to worker vmhost:…", which reads as+// an outage rather than as "this runtime has no sizing knob". Memory is a+// property of the image here; there is nothing to turn.+func TestResizeIsRefusedByTheRuntimeWithAReason(t *testing.T) {+ m := awsvmlite.New(nil, awsvmlite.Config{})+ sm := awsvmlite.NewSandboxManager(m)++ err := sm.SetResourceLimits(context.Background(), "sb-1", 0, 8<<30, 400000, 100000)+ if err == nil {+ t.Fatal("SetResourceLimits succeeded on a runtime whose size is fixed by its image")+ }+ if !errors.Is(err, awsvm.ErrUnsupported) {+ t.Fatalf("resize failed with %v, want ErrUnsupported — respondManagerErr maps only "++ "that to 501, so anything else surfaces as a 500 and reads as our bug", err)+ }+}++// A runtime that cannot snapshot RAM must say so, so the checkpoint API can+// refuse a full capture up front instead of accepting one and silently never+// producing it.+func TestRuntimeWithoutMemoryCaptureDeclaresItself(t *testing.T) {+ var b Backend = &liteBackend{}+ c, ok := b.(MemoryStateCapturer)+ if !ok {+ t.Fatal("liteBackend no longer declares its memory-capture capability — " ++ "the checkpoint API would accept a full checkpoint it cannot make")+ }+ if c.CapturesMemoryState() {+ t.Fatal("claimed memory capture on a runtime whose provider offers no way to read host RAM")+ }++ // The fleet says nothing, which must keep meaning "yes" — a backend that+ // never considered the question must not start refusing full checkpoints.+ var fleet Backend = &workerBackend{}+ if _, declares := fleet.(MemoryStateCapturer); declares {+ t.Fatal("workerBackend now declares memory capture; if that is deliberate it must " ++ "return true, or every QEMU full checkpoint starts 501ing")+ }+}diff --git a/internal/api/backend_hibernation.go b/internal/api/backend_hibernation.goindex 32d7a336..ee9eebd4 100644--- a/internal/api/backend_hibernation.go+++ b/internal/api/backend_hibernation.go@@ -29,7 +29,7 @@ import (// 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.+// implemented and unreachable over HTTP.//// 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. Thediff --git a/internal/api/backend_hibernation_test.go b/internal/api/backend_hibernation_test.goindex 9d83f122..ead54ae2 100644--- a/internal/api/backend_hibernation_test.go+++ b/internal/api/backend_hibernation_test.go@@ -4,7 +4,7 @@ import ("context""testing"- "github.com/opensandbox/opensandbox/internal/awsvm"+ "github.com/opensandbox/opensandbox/internal/awsvmlite")// backend_hibernation_test.go — which backend answers a hibernate or a wake.@@ -35,9 +35,9 @@ func TestWorkerBackendIsNotAHibernator(t *testing.T) {// ...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{}+ var b Backend = &liteBackend{}if _, ok := b.(Hibernator); !ok {- t.Fatal("microvmBackend does not implement Hibernator — hibernate/wake " ++ t.Fatal("liteBackend does not implement Hibernator — hibernate/wake " +"would dispatch into an empty worker fleet")}}@@ -54,7 +54,7 @@ func TestMicrovmBackendIsAHibernator(t *testing.T) {// 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, "")}+ b := &liteBackend{mgr: awsvmlite.New(nil, awsvmlite.Config{})}s := &Server{backends: []Backend{b}}workerID := microvmWorkerID("microvm-deadbeef")@@ -72,7 +72,7 @@ func TestHibernatorResolvesASandboxWhoseHostIsGone(t *testing.T) {// 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, "")}}}+ s := &Server{backends: []Backend{&liteBackend{mgr: awsvmlite.New(nil, awsvmlite.Config{})}}}for _, workerID := range []string{"worker-abc123", // a real registered QEMU workerdiff --git a/internal/api/backend_refuse_managed_test.go b/internal/api/backend_refuse_managed_test.gonew file mode 100644index 00000000..326982f2--- /dev/null+++ b/internal/api/backend_refuse_managed_test.go@@ -0,0 +1,111 @@+package api++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/sandbox"+)++// backend_refuse_managed_test.go — the routes a managed backend does not serve+// must not destroy the sandbox they were asked about.+//+// PTY, agent sessions and mounts bypass dispatchDataPlane and go straight to+// the worker proxy. That proxy resolves a sandbox through the worker registry,+// and a managed sandbox is deliberately absent from it — so the proxy read+// "held by a backend" as "worker lost", wrote the session row to `stopped`, and+// returned 410 for every subsequent request. The sandbox itself kept running+// and billing, unreachable.+//+// One unsupported call should cost a 501, not the sandbox.++// stubBackend holds exactly the sandbox ids it is given.+type stubBackend struct {+ name string+ held map[string]struct{}+}++func (b *stubBackend) Name() string { return b.name }+func (b *stubBackend) OwnsWorkerID(id string) bool { return id == "vmhost:box-1" }+func (b *stubBackend) WorkerIDPrefixes() []string { return []string{"vmhost:"} }+func (b *stubBackend) Capacity() (int, int, int) { return 1, 1, len(b.held) }+func (b *stubBackend) Route(_ context.Context, sandboxID string) (sandbox.Manager, bool) {+ if _, ok := b.held[sandboxID]; ok {+ // A nil manager is fine here: refuseIfManaged decides on ownership+ // alone, and must not depend on the manager implementing anything.+ return nil, true+ }+ return nil, false+}+func (b *stubBackend) Reconcile(context.Context, *db.Store) {}+func (b *stubBackend) Close() {}++// call runs refuseIfManaged for a sandbox id and reports the status written and+// whether the wrapped proxy handler ran.+func call(t *testing.T, s *Server, sandboxID string) (status int, proxied bool) {+ t.Helper()+ e := echo.New()+ req := httptest.NewRequest(http.MethodPost, "/api/sandboxes/"+sandboxID+"/pty", nil)+ rec := httptest.NewRecorder()+ c := e.NewContext(req, rec)+ c.SetParamNames("id")+ c.SetParamValues(sandboxID)++ h := s.refuseIfManaged(func(echo.Context) error {+ proxied = true+ return c.NoContent(http.StatusOK)+ })+ if err := h(c); err != nil {+ t.Fatalf("handler returned error: %v", err)+ }+ return rec.Code, proxied+}++// The whole point: a backend-held sandbox is answered, never proxied. Reaching+// the proxy is what closed the row.+func TestManagedSandboxIsRefusedNotProxied(t *testing.T) {+ s := &Server{}+ s.backends = append(s.backends, &stubBackend{+ name: "vmhost-lite",+ held: map[string]struct{}{"sbx-managed": {}},+ })++ status, proxied := call(t, s, "sbx-managed")+ if proxied {+ t.Fatal("a managed sandbox reached the worker proxy — the proxy would find no registered worker and mark the row stopped")+ }+ if status != http.StatusNotImplemented {+ t.Errorf("status = %d, want 501: this runtime will never serve PTY, and a retryable code invites the client to keep asking", status)+ }+}++// The other direction matters just as much. Every QEMU sandbox depends on+// falling through to the proxy, so the guard must be invisible to them.+func TestUnheldSandboxStillProxies(t *testing.T) {+ s := &Server{}+ s.backends = append(s.backends, &stubBackend{+ name: "vmhost-lite",+ held: map[string]struct{}{"sbx-managed": {}},+ })++ status, proxied := call(t, s, "sbx-on-a-worker")+ if !proxied {+ t.Fatal("a worker-held sandbox was refused — this would break PTY for the entire QEMU fleet")+ }+ if status != http.StatusOK {+ t.Errorf("status = %d, want 200", status)+ }+}++// With no backends registered at all — a plain QEMU cell — nothing is refused.+func TestNoBackendsRefusesNothing(t *testing.T) {+ s := &Server{}+ if _, proxied := call(t, s, "sbx-anything"); !proxied {+ t.Fatal("a cell with no managed backends refused a proxy route")+ }+}diff --git a/internal/api/create_flow.go b/internal/api/create_flow.goindex ac8e5eaa..4583e74f 100644--- a/internal/api/create_flow.go+++ b/internal/api/create_flow.go@@ -240,6 +240,17 @@ func respondCreateErr(c echo.Context, err error) error {"hint": "retry once a sandbox is released, or contact support to raise your capacity",})+ case errors.Is(err, ErrSizeUnavailable):+ // 400, not 503: the request names a size this region does not offer,+ // so it is malformed rather than unlucky. The message carries the+ // sizes that ARE offered, because "not available" without them leaves+ // the caller guessing at a list only we can see.+ log.Printf("create: size unavailable: %v", err)+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": err.Error(),+ "hint": "request one of the listed sizes, or contact support to have another published",+ })+case errors.Is(err, awsvm.ErrThrottled):// Transient by construction — say so, and give a concrete delay so// clients space retries instead of hammering.diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex f064c7dd..eec2a747 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -17,6 +17,7 @@ import ("github.com/gorilla/websocket""github.com/labstack/echo/v4""github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/awsvmlite""github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/pkg/types"@@ -640,6 +641,17 @@ func (s *Server) dashboardGetSessionStats(c echo.Context) error {})}+ // A managed backend holds this sandbox in-process and has no registered+ // worker, so neither branch below can reach it — the gRPC path answers+ // "worker not available" for a runtime whose manager implements Stats.+ if mgr, ok := s.execManagerFor(sandboxID); ok {+ stats, err := mgr.Stats(c.Request().Context(), sandboxID)+ if err != nil {+ return respondManagerErr(c, err)+ }+ return c.JSON(http.StatusOK, stats)+ }+// Combined mode: get stats directly from managerif s.manager != nil {stats, err := s.manager.Stats(c.Request().Context(), sandboxID)@@ -701,6 +713,20 @@ func (s *Server) dashboardCreatePTY(c echo.Context) error {})}+ // A managed backend serves its own terminals — see pty_managed.go. Checked+ // first because such a sandbox has no registered worker, so the gRPC branch+ // below can only report the worker unavailable. This is the dashboard's+ // terminal; without it the web UI cannot open a shell on a MicroVM sandbox.+ if b, ok := s.ptyBackendFor(c.Request().Context(), sandboxID); ok {+ sessionID, err := b.PTYCreate(c.Request().Context(), sandboxID, awsvmlite.PTYRequest{+ Cols: int32(req.Cols), Rows: int32(req.Rows), Shell: req.Shell,+ })+ if err != nil {+ return respondManagerErr(c, err)+ }+ return c.JSON(http.StatusCreated, types.PTYSession{SessionID: sessionID, SandboxID: sandboxID})+ }+// Server mode: proxy PTY creation to the worker via gRPCif s.ptyManager == nil && s.workerRegistry != nil {grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)@@ -775,6 +801,29 @@ func (s *Server) dashboardPTYWebSocket(c echo.Context) error {sessionID := c.Param("sessionId")// Server mode: proxy WebSocket to the worker's HTTP API+ // Managed backend: splice the browser's socket to the box's, exactly as the+ // API route does. Dial before upgrading, because a 101 cannot be retracted+ // and a box that refuses has to stay reportable as an HTTP status.+ if b, ok := s.ptyBackendFor(c.Request().Context(), sandboxID); ok {+ box, err := b.DialPTY(context.Background(), sandboxID, sessionID)+ if err != nil {+ return c.JSON(http.StatusBadGateway, map[string]string{"error": "could not attach to the terminal"})+ }+ defer box.Close()+ client, err := ptyUpgrader.Upgrade(c.Response(), c.Request(), nil)+ if err != nil {+ return nil+ }+ defer client.Close()+ done := make(chan struct{}, 2)+ go pumpWS(client, box, done)+ go pumpWS(box, client, done)+ <-done+ _ = client.SetReadDeadline(time.Now())+ _ = box.SetReadDeadline(time.Now())+ return nil+ }+if s.ptyManager == nil && s.workerRegistry != nil {return s.dashboardPTYWebSocketRemote(c, sandboxID, sessionID, session)}@@ -985,6 +1034,14 @@ func (s *Server) dashboardResizePTY(c echo.Context) error {// Server mode: proxy resize to the worker via HTTP// The worker doesn't have a dedicated resize gRPC call, so we proxy the HTTP request.+ // Managed backend serves its own terminals; see dashboardCreatePTY.+ if b, ok := s.ptyBackendFor(c.Request().Context(), sandboxID); ok {+ if err := b.PTYResize(c.Request().Context(), sandboxID, sessionID, int32(req.Cols), int32(req.Rows)); err != nil {+ return respondManagerErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+ }+if s.ptyManager == nil && s.workerRegistry != nil {return s.proxyWorkerHTTP(c, session, "POST",fmt.Sprintf("/sandboxes/%s/pty/%s/resize", sandboxID, sessionID),@@ -1016,6 +1073,14 @@ func (s *Server) dashboardKillPTY(c echo.Context) error {sessionID := c.Param("sessionId")// Server mode: proxy kill to the worker via HTTP+ // Managed backend serves its own terminals; see dashboardCreatePTY.+ if b, ok := s.ptyBackendFor(c.Request().Context(), sandboxID); ok {+ if err := b.PTYKill(c.Request().Context(), sandboxID, sessionID); err != nil {+ return respondManagerErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+ }+if s.ptyManager == nil && s.workerRegistry != nil {return s.proxyWorkerHTTP(c, session, "DELETE",fmt.Sprintf("/sandboxes/%s/pty/%s", sandboxID, sessionID), nil)@@ -1056,6 +1121,14 @@ func (s *Server) dashboardRebootSession(c echo.Context) error {if err != nil {return err}+ // Backend first: a managed sandbox has no worker to dispatch to.+ if mgr, ok := s.execManagerFor(sandboxID); ok {+ if err := mgr.RebootSandbox(c.Request().Context(), sandboxID); err != nil {+ return respondManagerErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+ }+if s.workerRegistry != nil {client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)if err != nil {@@ -1085,6 +1158,14 @@ func (s *Server) dashboardPowerCycleSession(c echo.Context) error {if err != nil {return err}+ // Backend first: a managed sandbox has no worker to dispatch to.+ if mgr, ok := s.execManagerFor(sandboxID); ok {+ if _, err := mgr.PowerCycleSandbox(c.Request().Context(), sandboxID); err != nil {+ return respondManagerErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+ }+if s.workerRegistry != nil {client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)if err != nil {diff --git a/internal/api/edge_claim.go b/internal/api/edge_claim.goindex 40d34b09..0000d5d1 100644--- a/internal/api/edge_claim.go+++ b/internal/api/edge_claim.go@@ -8,7 +8,6 @@ import ("net/http""time"- "github.com/google/uuid""github.com/labstack/echo/v4""github.com/opensandbox/opensandbox/internal/auth"@@ -16,16 +15,6 @@ import (pb "github.com/opensandbox/opensandbox/proto/worker")-// processEpoch identifies THIS control-plane process to the edge's PoolStock-// DOs. Any backend whose edge reservations live in memory rather than in-// Postgres stamps its reserve responses with it, so a DO holding stock from a-// previous process can tell that every id it has is dead and drop them (see-// edgeReservePool for the failure this prevents).-//-// Generated per process, deliberately: a value derived from anything stable —-// hostname, cell id, config — would survive the restart it exists to detect.-var processEpoch = uuid.New().String()-// Edge claim: the api-edge Worker's PoolStock Durable Object reserves parked// pool boxes ahead of time (edge-reserve), answers default-shape creates// entirely at the edge (pop + mint token + 201), then finalizes the claim@@ -144,49 +133,6 @@ func (s *Server) edgeReservePool(c echo.Context) error {region = "local"}- // A cell whose backend keeps its own stock answers from that instead of the- // Postgres pool — its boxes have no rows to flip.- //- // That difference is why this branch carries an epoch and the Postgres one- // below does not. A PG reservation is a row: it survives a restart, so stock- // the DO is holding stays valid across one. An in-memory reservation does- // not. The sandbox id, the manager binding behind it, and the pool entry- // itself all live in this process, so a restart silently invalidates every- // id the DO is holding — and with no epoch the DO would keep serving up to- // SHARDS × TARGET_STOCK of them for the full ENTRY_TTL. Each one 201s a- // create for a box that no longer routes, so the customer's first exec finds- // no binding and 500s. Measured on dev after a restart: 46 and 47 lost- // finalizes in consecutive 10-minute buckets.- //- // The DO drops its whole stock when this value changes (see pool_stock.ts),- // which bounds the exposure to one restock cycle.- if ec, ok := s.edgeClaimBackend(); ok {- boxes := ec.EdgeReserve(req.Count)- out := make([]map[string]interface{}, 0, len(boxes))- for _, b := range boxes {- // From here the edge may hand this id to a customer at any moment,- // so anything that arrives for it before claim-finalize waits- // rather than 404s. See THE FINALIZE RACE above.- s.registerEdgePending(b.SandboxID)- e := map[string]interface{}{"sandboxID": b.SandboxID, "workerID": b.WorkerID}- // Reach-info, when the backend has it (see edgeBox). Lets the edge- // warm the box's agent tunnel while it is still stock, so the first- // exec doesn't pay for attaching to the guest.- if b.Endpoint != "" && b.Token != "" {- e["endpoint"] = b.Endpoint- e["token"] = b.Token- e["port"] = b.Port- }- out = append(out, e)- }- return c.JSON(http.StatusOK, map[string]interface{}{- "region": region,- "sandboxDomain": s.sandboxDomain,- "epoch": processEpoch,- "boxes": out,- })- }-boxes, err := s.store.ReservePooledForEdge(c.Request().Context(), region, poolTemplateName(), req.Count)if err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})@@ -219,9 +165,6 @@ func (s *Server) edgeReleasePool(c echo.Context) error {for _, id := range req.SandboxIDs {s.resolveEdgePending(id, nil)}- if ec, ok := s.edgeClaimBackend(); ok {- return c.JSON(http.StatusOK, map[string]int{"released": ec.EdgeRelease(req.SandboxIDs)})- }n, err := s.store.ReleaseEdgeReservations(c.Request().Context(), req.SandboxIDs)if err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})@@ -279,45 +222,6 @@ func (s *Server) claimFinalize(c echo.Context) error {cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))metadataJSON, _ := json.Marshal(cfg.Metadata)- // Backend-owned stock: redeem the reservation in memory, then write the row- // the QEMU path flips instead of inserts. There is no ClaimSandbox call and- // no worker to reach — the box was bound and its tunnel adopted back at- // reserve, which is the whole reason this finalize can run after the- // customer already holds their 201.- if ec, ok := s.edgeClaimBackend(); ok {- workerID, err := ec.EdgeFinalize(cfg.SandboxID, cfg)- if err != nil {- // The reservation is gone (reaped, or a duplicate delivery of a- // finalize that already ran). Nothing to bind and nothing to undo.- log.Printf("sandbox: EDGE CLAIM FINALIZE LOST %s (%v)", cfg.SandboxID, err)- finalizeErr = err- return c.JSON(http.StatusConflict, map[string]string{"error": "reservation lost"})- }- template := cfg.Template- if template == "" {- template = "default"- }- if s.store != nil {- if _, err := s.store.CreateSandboxSessionWithStatus(ctx, cfg.SandboxID, orgID, auth.GetUserID(c),- template, s.poolStockRegion(), workerID, cfgJSON, metadataJSON, "running", nil); err != nil {- // The host is live and the customer holds a token for it, so- // failing here does not take it back. Report it and let the- // orphan sweep reclaim a box with no row — the mechanism that- // exists for exactly this hole.- log.Printf("sandbox: edge claim-finalize row insert %s failed: %v", cfg.SandboxID, err)- finalizeErr = err- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})- }- }- s.emitEvent("create", cfg.SandboxID, workerID, "claimed from warm pool (edge)")- log.Printf("sandbox: EDGE CLAIM FINALIZED %s (worker=%s)", cfg.SandboxID, workerID)- finalizeErr = nil- return c.JSON(http.StatusOK, map[string]string{- "sandboxID": cfg.SandboxID,- "workerID": workerID,- "status": "running",- })- }box, err := s.store.ClaimReservedSession(ctx, cfg.SandboxID, orgID, auth.GetUserID(c), cfgJSON, metadataJSON, nil)if err != nil {// Reservation lost (reaped/drained). Nothing is bound; make sure the@@ -389,11 +293,25 @@ func (s *Server) claimFinalize(c echo.Context) error {s.emitEvent("create", box.SandboxID, box.WorkerID, "claimed from warm pool (edge)")log.Printf("sandbox: EDGE CLAIM FINALIZED %s (worker=%s)", box.SandboxID, box.WorkerID)finalizeErr = nil- return c.JSON(http.StatusOK, map[string]string{+ out := map[string]string{"sandboxID": box.SandboxID,"workerID": box.WorkerID,"status": "running",- })+ }+ // An edge-claimed box was launched before this request, so its deadline is+ // measured from ITS launch and not from now. Asking the backend keeps that+ // distinction; computing it here would restart the clock and hand every+ // claimed box a deadline later than the one its provider will enforce.+ if b, ok := s.backendForWorkerID(box.WorkerID); ok {+ if d, ok := b.(interface {+ DeadlineFor(string) time.Time+ }); ok {+ if at := d.DeadlineFor(box.SandboxID); !at.IsZero() {+ out["endAt"] = at.UTC().Format(time.RFC3339)+ }+ }+ }+ return c.JSON(http.StatusOK, out)}// reapStaleEdgeReservations destroys edge_reserved boxes older thandiff --git a/internal/api/exec_session_managed.go b/internal/api/exec_session_managed.gonew file mode 100644index 00000000..90a86190--- /dev/null+++ b/internal/api/exec_session_managed.go@@ -0,0 +1,302 @@+package api++// exec_session_managed.go — exec sessions for a backend the control plane holds.+//+// Same shape as pty_managed.go, and it reuses its splice: a session's stream and+// a terminal's differ in what the frames MEAN, not in how they travel, and the+// control plane is deliberately not in the business of understanding either.+// Both sides — the customer's SDK and the guest — already agree on the format;+// anything interpreted here would be a second implementation of it, on the path+// where a bug shows up as garbled output rather than an error.++import (+ "context"+ "encoding/base64"+ "encoding/binary"+ "encoding/json"+ "log"+ "net/http"+ "strconv"+ "time"++ "github.com/gorilla/websocket"+ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/awsvmlite"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// execSessionBackend is implemented by a backend that runs sessions itself.+type execSessionBackend interface {+ ExecSessionCreate(ctx context.Context, sandboxID string, req awsvmlite.ExecSessionRequest) (string, error)+ ExecSessionList(ctx context.Context, sandboxID string) ([]awsvmlite.ExecSessionInfo, error)+ ExecSessionKill(ctx context.Context, sandboxID, sessionID string, signal int32) error+ ExecSessionGetResult(ctx context.Context, sandboxID, sessionID string) (*awsvmlite.ExecSessionResult, error)+ DialExecSession(ctx context.Context, sandboxID, sessionID string) (*websocket.Conn, error)+}++func (s *Server) execSessionBackendFor(ctx context.Context, sandboxID string) (execSessionBackend, bool) {+ b, _, ok := s.backendFor(ctx, sandboxID)+ if !ok {+ return nil, false+ }+ eb, ok := b.(execSessionBackend)+ return eb, ok+}++// dispatchExecSession serves a session route locally when a managed backend+// holds the sandbox, and otherwise falls through — to the worker proxy in+// server mode, or to the existing local handler on a cell that has a session+// manager of its own.+func (s *Server) dispatchExecSession(local, fallback echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ if _, ok := s.execSessionBackendFor(c.Request().Context(), c.Param("id")); ok {+ return local(c)+ }+ return fallback(c)+ }+}++func (s *Server) createExecSessionManaged(c echo.Context) error {+ id := c.Param("id")+ b, ok := s.execSessionBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "exec sessions are not supported for this sandbox"})+ }+ var req types.ExecSessionCreateRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})+ }+ if req.Command == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "cmd is required"})+ }+ sessionID, err := b.ExecSessionCreate(c.Request().Context(), id, awsvmlite.ExecSessionRequest{+ Command: req.Command,+ Args: req.Args,+ Env: req.Env,+ Cwd: req.Cwd,+ TimeoutSec: int32(req.Timeout),+ MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),+ })+ if err != nil {+ return respondFSErr(c, err)+ }+ return c.JSON(http.StatusCreated, types.ExecSessionInfo{SessionID: sessionID, SandboxID: id, Command: req.Command, Args: req.Args, Running: true})+}++func (s *Server) listExecSessionsManaged(c echo.Context) error {+ id := c.Param("id")+ b, ok := s.execSessionBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "exec sessions are not supported for this sandbox"})+ }+ sessions, err := b.ExecSessionList(c.Request().Context(), id)+ if err != nil {+ return respondFSErr(c, err)+ }+ out := make([]types.ExecSessionInfo, 0, len(sessions))+ for _, sess := range sessions {+ info := types.ExecSessionInfo{+ SessionID: sess.SessionID,+ SandboxID: id,+ Command: sess.Command,+ Args: sess.Args,+ Running: sess.Running,+ AttachedClients: sess.AttachedClients,+ }+ if sess.StartedAt > 0 {+ info.StartedAt = time.Unix(sess.StartedAt, 0).UTC().Format(time.RFC3339)+ }+ // Only meaningful once the process has exited; reporting 0 for a running+ // command reads as "succeeded".+ if !sess.Running {+ code := int(sess.ExitCode)+ info.ExitCode = &code+ }+ out = append(out, info)+ }+ // A bare array, matching the worker-backed handler+ // (exec_session.go's listExecSessions). The SDK types this response as+ // ExecSessionInfo[] and does no unwrapping, so wrapping it in+ // {"sessions": …} made exec.list() return an object where the caller — and+ // TypeScript — expected a list. Every .find/.filter on it silently blew up,+ // and only on this runtime.+ if out == nil {+ // Never null: `for (const s of null)` is a crash, whereas an empty list+ // is the honest answer for a sandbox with no sessions.+ out = []types.ExecSessionInfo{}+ }+ return c.JSON(http.StatusOK, out)+}++func (s *Server) killExecSessionManaged(c echo.Context) error {+ id, sessionID := c.Param("id"), c.Param("sessionID")+ b, ok := s.execSessionBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "exec sessions are not supported for this sandbox"})+ }+ var signal int32+ if raw := c.QueryParam("signal"); raw != "" {+ if n, err := strconv.Atoi(raw); err == nil {+ signal = int32(n)+ }+ }+ if err := b.ExecSessionKill(c.Request().Context(), id, sessionID, signal); err != nil {+ return respondFSErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+}++func (s *Server) execResultManaged(c echo.Context) error {+ id, sessionID := c.Param("id"), c.Param("sessionID")+ b, ok := s.execSessionBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "exec sessions are not supported for this sandbox"})+ }+ res, err := b.ExecSessionGetResult(c.Request().Context(), id, sessionID)+ if err != nil {+ return respondFSErr(c, err)+ }+ out := types.ExecSessionResult{+ Running: res.Running,+ Stdout: res.Stdout,+ Stderr: res.Stderr,+ }+ if res.ExitCode != nil {+ code := int(*res.ExitCode)+ out.ExitCode = &code+ }+ return c.JSON(http.StatusOK, out)+}++// execSessionWebSocketManaged splices the customer's socket to the session's.+//+// Dial before upgrade, for the same reason as the PTY path: a 101 cannot be+// retracted, so a box that refuses has to be reportable as an ordinary status.+func (s *Server) execSessionWebSocketManaged(c echo.Context) error {+ id, sessionID := c.Param("id"), c.Param("sessionID")+ b, ok := s.execSessionBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "exec sessions are not supported for this sandbox"})+ }++ // Not the request context: it dies with the handler, and this socket has to+ // live for the length of the attachment.+ box, err := b.DialExecSession(context.Background(), id, sessionID)+ if err != nil {+ log.Printf("exec session: dial %s/%s: %v", id, sessionID, err)+ return c.JSON(http.StatusBadGateway, map[string]string{"error": "could not attach to the session"})+ }+ defer box.Close()++ client, err := ptyUpgrader.Upgrade(c.Response(), c.Request(), nil)+ if err != nil {+ log.Printf("exec session: upgrade %s/%s: %v", id, sessionID, err)+ return nil+ }+ defer client.Close()++ // Translated, like the PTY path and for the same reason: the guest frames+ // its output as JSON so stdout and stderr stay distinguishable on one+ // connection, while the customer-facing contract set by the QEMU path is+ // binary — a leading stream byte, 0x04 for end-of-scrollback, 0x03 plus a+ // big-endian exit code. Same SDK on both runtimes, so the difference must+ // die here rather than reach it.+ done := make(chan struct{}, 2)+ go pumpExecToClient(client, box, done)+ go pumpExecToBox(box, client, done)+ <-done++ // Detaching closes both sockets, which the guest reads as this client+ // leaving. The SESSION is untouched — it outlives its clients by design.+ _ = client.SetReadDeadline(time.Now())+ _ = box.SetReadDeadline(time.Now())+ return nil+}++// execGuestFrame mirrors cmd/microvm-hooks' execFrame — a private copy, because+// it is a wire contract with a separately-deployed binary.+type execGuestFrame struct {+ Stream string `json:"stream,omitempty"` // stdout | stderr | exit | scrollbackEnd+ Data string `json:"data,omitempty"` // base64+ ExitCode int32 `json:"exitCode,omitempty"`+ Error string `json:"error,omitempty"`+}++// Stream markers on the customer-facing side. Defined here next to the+// translation that emits them so the two cannot drift apart silently.+const (+ execStreamStdout byte = 0x01+ execStreamStderr byte = 0x02+ execStreamExit byte = 0x03+ execScrollbackEnd byte = 0x04+)++// pumpExecToClient converts the guest's JSON frames into the binary framing the+// SDK decodes.+func pumpExecToClient(client, box *websocket.Conn, done chan<- struct{}) {+ defer func() { done <- struct{}{} }()+ for {+ _, msg, err := box.ReadMessage()+ if err != nil {+ return+ }+ var f execGuestFrame+ if err := json.Unmarshal(msg, &f); err != nil {+ // Unrecognised: pass it through rather than drop it, so a guest+ // that ever speaks the binary protocol directly still works.+ if err := client.WriteMessage(websocket.BinaryMessage, msg); err != nil {+ return+ }+ continue+ }++ switch f.Stream {+ case "stdout", "stderr":+ data, dErr := base64.StdEncoding.DecodeString(f.Data)+ if dErr != nil {+ continue+ }+ marker := execStreamStdout+ if f.Stream == "stderr" {+ marker = execStreamStderr+ }+ out := make([]byte, 1+len(data))+ out[0] = marker+ copy(out[1:], data)+ if err := client.WriteMessage(websocket.BinaryMessage, out); err != nil {+ return+ }+ case "scrollbackEnd":+ if err := client.WriteMessage(websocket.BinaryMessage, []byte{execScrollbackEnd}); err != nil {+ return+ }+ case "exit":+ out := make([]byte, 5)+ out[0] = execStreamExit+ binary.BigEndian.PutUint32(out[1:], uint32(f.ExitCode))+ _ = client.WriteMessage(websocket.BinaryMessage, out)+ // The command is over. Returning closes the socket, which is how+ // the SDK's `done` promise settles.+ return+ }+ }+}++// pumpExecToBox wraps the customer's stdin into the guest's frames.+func pumpExecToBox(box, client *websocket.Conn, done chan<- struct{}) {+ defer func() { done <- struct{}{} }()+ for {+ _, msg, err := client.ReadMessage()+ if err != nil {+ return+ }+ frame, mErr := json.Marshal(ptyClientFrame{Data: base64.StdEncoding.EncodeToString(msg)})+ if mErr != nil {+ return+ }+ if err := box.WriteMessage(websocket.TextMessage, frame); err != nil {+ return+ }+ }+}diff --git a/internal/api/filesystem.go b/internal/api/filesystem.goindex 6818796c..edb0afe3 100644--- a/internal/api/filesystem.go+++ b/internal/api/filesystem.go@@ -2,6 +2,7 @@ package apiimport ("context"+ "errors""fmt""io""net/http"@@ -35,15 +36,11 @@ func (s *Server) readFile(c echo.Context) error {if s.router != nil {if err := s.router.Route(c.Request().Context(), id, "readFile", routeOp); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}} else {if err := routeOp(c.Request().Context()); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}}defer reader.Close()@@ -79,15 +76,11 @@ func (s *Server) writeFile(c echo.Context) error {if s.router != nil {if err := s.router.Route(c.Request().Context(), id, "writeFile", routeOp); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}} else {if err := routeOp(c.Request().Context()); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}}@@ -116,15 +109,11 @@ func (s *Server) listDir(c echo.Context) error {if s.router != nil {if err := s.router.Route(c.Request().Context(), id, "listDir", routeOp); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}} else {if err := routeOp(c.Request().Context()); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}}@@ -151,15 +140,11 @@ func (s *Server) makeDir(c echo.Context) error {if s.router != nil {if err := s.router.Route(c.Request().Context(), id, "makeDir", routeOp); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}} else {if err := routeOp(c.Request().Context()); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}}@@ -186,17 +171,34 @@ func (s *Server) removeFile(c echo.Context) error {if s.router != nil {if err := s.router.Route(c.Request().Context(), id, "removeFile", routeOp); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}} else {if err := routeOp(c.Request().Context()); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })+ return respondFSErr(c, err)}}return c.NoContent(http.StatusNoContent)}++// respondFSErr answers a filesystem failure with the status the runtime+// reported, falling back to 500.+//+// ADDITIVE ON PURPOSE. Every one of these sites used to be an unconditional+// 500, which made "no such file" indistinguishable from "the sandbox is+// broken" — the SDK cannot tell which to retry, and a caller polling for a file+// that will never exist retries forever. Only an error that actually carries a+// status is treated differently, and today that is exactly the MicroVM guest+// (see awsvmlite's httpError, which preserves the code the agent's gRPC status+// was mapped to). The QEMU fleet's errors do not implement this interface, so+// its responses are byte-for-byte what they were.+func respondFSErr(c echo.Context, err error) error {+ var coded interface{ StatusCode() int }+ if errors.As(err, &coded) {+ if code := coded.StatusCode(); code >= 400 && code < 600 {+ return c.JSON(code, map[string]string{"error": err.Error()})+ }+ }+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+}diff --git a/internal/api/filesystem_error_test.go b/internal/api/filesystem_error_test.gonew file mode 100644index 00000000..b2c08b0d--- /dev/null+++ b/internal/api/filesystem_error_test.go@@ -0,0 +1,76 @@+package api++import (+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/labstack/echo/v4"+)++// filesystem_error_test.go — a missing file is an answer, not a fault.+//+// Every filesystem handler used to answer 500 for any error, which made "no+// such file" indistinguishable from "the sandbox is broken". A caller cannot+// decide whether to retry on that, so an SDK polling for a file that will never+// appear retries forever.+//+// The mapping is deliberately ADDITIVE: only a runtime whose error carries a+// status is treated differently. The QEMU fleet's errors do not, so its+// responses are unchanged — which is the property worth a test, because a+// regression there reaches every existing customer.++type codedErr struct {+ code int+ msg string+}++func (e codedErr) Error() string { return e.msg }+func (e codedErr) StatusCode() int { return e.code }++func recorded(t *testing.T, err error) int {+ t.Helper()+ rec := httptest.NewRecorder()+ c := echo.New().NewContext(httptest.NewRequest(http.MethodGet, "/", nil), rec)+ if rerr := respondFSErr(c, err); rerr != nil {+ t.Fatalf("respondFSErr returned %v", rerr)+ }+ return rec.Code+}++// A runtime that reports a status gets that status through to the customer.+func TestCodedErrorKeepsItsStatus(t *testing.T) {+ for _, code := range []int{http.StatusNotFound, http.StatusForbidden, http.StatusConflict, http.StatusInsufficientStorage} {+ if got := recorded(t, codedErr{code: code, msg: "boom"}); got != code {+ t.Errorf("status = %d, want %d", got, code)+ }+ }+}++// Wrapped is still coded — handlers wrap on the way out, and errors.As is what+// makes that survive.+func TestWrappedCodedErrorKeepsItsStatus(t *testing.T) {+ err := fmt.Errorf("read file: %w", codedErr{code: http.StatusNotFound, msg: "no such file"})+ if got := recorded(t, err); got != http.StatusNotFound {+ t.Errorf("status = %d, want 404 through the wrapper", got)+ }+}++// The QEMU path: a plain error is still a 500, exactly as before.+func TestPlainErrorIsStillFiveHundred(t *testing.T) {+ if got := recorded(t, errors.New("qemu: agent unreachable")); got != http.StatusInternalServerError {+ t.Errorf("status = %d, want 500 — existing fleet behaviour must not change", got)+ }+}++// A nonsense status is not passed through: a runtime reporting 0 or 200 for a+// failure must not turn into a success or an invalid response.+func TestImplausibleStatusFallsBackToFiveHundred(t *testing.T) {+ for _, code := range []int{0, 200, 302, 700} {+ if got := recorded(t, codedErr{code: code, msg: "weird"}); got != http.StatusInternalServerError {+ t.Errorf("status %d mapped to %d, want 500", code, got)+ }+ }+}diff --git a/internal/api/lite_backend.go b/internal/api/lite_backend.goindex ad1aff83..4bae549d 100644--- a/internal/api/lite_backend.go+++ b/internal/api/lite_backend.go@@ -4,45 +4,52 @@ import ("context""encoding/json""errors"+ "fmt""log""os"+ "strconv"+ "strings""time""github.com/google/uuid"+ "github.com/gorilla/websocket""github.com/opensandbox/opensandbox/internal/awsvm""github.com/opensandbox/opensandbox/internal/awsvmlite""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")-// lite_backend.go — the same MicroVM fleet, reached without a tunnel.+// lite_backend.go — the MicroVM runtime.//-// This is a SECOND way of talking to the boxes microvm_backend.go already-// launches, not a second fleet: same image, same region, same idle policy, same-// regional quota, built from the same newMicrovmClient. What differs is the data-// plane. Where that backend carries gRPC to osb-agent inside a WebSocket — the-// only way to reach it, because Lambda's proxy strips the HTTP/2 trailers gRPC-// reports status in — this one issues a plain HTTPS POST to a hook endpoint in-// the guest. See internal/awsvmlite for the measurement that motivated it.+// A box is reached with a plain HTTPS POST to a hook endpoint in the guest,+// which translates it into loopback gRPC inside the box (cmd/microvm-hooks).+// That indirection is not an optimisation, it is the only thing that works:+// the platform's proxy forwards guest traffic to exactly one declared port and+// strips the HTTP/2 trailers gRPC reports status in, so gRPC cannot survive the+// hop from outside — but it is fine over loopback on the far side of it.//-// The two are mutually exclusive on a cell, because they would otherwise-// compete for the same regional quota while each believed it owned the fleet.-// OPENSANDBOX_MICROVM_LITE=1 selects this one; anything else keeps the agent-// path, which is what production runs.-//-// Deliberately absent, relative to the agent path: hibernate/wake, file-// transfer, streaming, PTY, checkpoints, edge-claim, and the warm-tunnel tier.-// Their absence is the experiment. What remains is create, exec, destroy.--// liteEnabled reports whether this cell serves MicroVMs over the direct exec-// path instead of the agent tunnel. Requires the MicroVM backend to be enabled-// at all — this is a choice of data plane, not an independent runtime.+// The predecessor carried gRPC to osb-agent inside a WebSocket tunnel held per+// box by this process. It is deleted (see microvm_common.go); this backend is+// what the runtime is. See internal/awsvmlite for the measurement that+// motivated the change.++// liteEnabled reports whether this cell serves MicroVM-backed sandboxes. It is+// microvmEnabled by another name — kept as its own function because the call+// sites read better for it, and because OPENSANDBOX_MICROVM_LITE used to select+// between two data planes and operators still have it set.func liteEnabled() bool {- return microvmEnabled() && os.Getenv("OPENSANDBOX_MICROVM_LITE") == "1"+ if os.Getenv("OPENSANDBOX_MICROVM_LITE") == "0" {+ // Honouring this would mean serving nothing at all: the agent-tunnel+ // backend it used to select no longer exists. Say so rather than boot a+ // MicroVM cell with no MicroVM backend registered.+ log.Printf("microvm: ignoring OPENSANDBOX_MICROVM_LITE=0 — the agent-tunnel backend it selected has been removed; unset the variable")+ }+ return microvmEnabled()}type liteBackend struct {@@ -60,7 +67,7 @@ type liteBackend struct {// newLiteBackend builds the direct-exec MicroVM backend, or returns nil if this// cell is not configured for it.-func newLiteBackend(ctx context.Context) (*liteBackend, error) {+func newLiteBackend(ctx context.Context, checkpointStore *storage.CheckpointStore) (*liteBackend, error) {if !liteEnabled() {return nil, nil}@@ -76,11 +83,17 @@ func newLiteBackend(ctx context.Context) (*liteBackend, error) {mgr := awsvmlite.New(client, awsvmlite.Config{WarmTarget: warm,+ // How many sandboxes may sit hibernated. A parked box holds regional+ // quota it can never give back, so this is a guard on the warm pool+ // rather than a limit AWS imposes — see awsvmlite/hibernate.go.+ SuspendedCap: envInt("OPENSANDBOX_MICROVM_LITE_SUSPENDED_CAP", 0),TouchInterval: time.Duration(envInt("OPENSANDBOX_MICROVM_LITE_TOUCH_SECONDS", 300)) * time.Second,})runCtx, stop := context.WithCancel(context.Background())- b := &liteBackend{client: client, mgr: mgr, sm: awsvmlite.NewSandboxManager(mgr), stopRun: stop}+ b := &liteBackend{client: client, mgr: mgr,+ sm: awsvmlite.NewSandboxManager(mgr).WithCheckpointStore(checkpointStore),+ stopRun: stop}go mgr.Run(runCtx)log.Printf("vmhost-lite: backend enabled (region=%s warm=%d) — direct exec, no agent tunnel",@@ -97,10 +110,11 @@ var _ Placer = (*liteBackend)(nil)func (b *liteBackend) Name() string { return "vmhost-lite" }-// WorkerIDPrefixes and OwnsWorkerID are deliberately IDENTICAL to the agent-// path's. A worker_id names which box holds a sandbox, and the box is the same-// box — switching data planes must not orphan the rows written by the other one,-// because a row nothing claims is a box nothing terminates.+// WorkerIDPrefixes and OwnsWorkerID keep reading the encoding the deleted+// agent-tunnel backend wrote as well as this one's. A worker_id names which box+// holds a sandbox, and the box is the same box — a row nothing claims is a box+// nothing terminates. Both are nil-safe: knownBackends calls them on the zero+// value, before any Server exists.func (b *liteBackend) WorkerIDPrefixes() []string {return []string{microvmWorkerPrefix, legacyWorkerPrefix}}@@ -166,6 +180,9 @@ func (b *liteBackend) Close() {if n := b.mgr.DrainWarm(drainCtx); n > 0 {log.Printf("vmhost-lite: released %d warm box(es) on shutdown", n)}+ // After the drain, not before: closing the queue first would drop whatever+ // DrainWarm just enqueued.+ b.mgr.CloseTerminator()}// ── Placer ──────────────────────────────────────────────────────────────────@@ -175,6 +192,37 @@ func (b *liteBackend) Close() {// whichever of the two backends this cell registered, and a cell that accepted// a different set of creates depending on its data plane would make the choice// visible to customers.+// ErrSizeUnavailable means the requested memory size has no published image in+// this region. Permanent for the request as written: size is fixed at launch+// from a per-tier image, so there is no later point at which a sandbox created+// at the wrong size could be corrected, and no retry that finds a tier we never+// published.+var ErrSizeUnavailable = errors.New("requested sandbox size is not available in this region")++// ExplainRefusal names the one refusal in Accepts that a customer can act on.+//+// Deliberately silent about the template case: whether a named template is+// servable is not decidable here (Accepts only sees the template NAME), so+// claiming it as the reason would sometimes be a lie.+func (b *liteBackend) ExplainRefusal(p placement) error {+ if b == nil || p.runtime != runtimeMicrovm {+ return nil+ }+ if _, _, ok := b.client.Config().ImageForMemory(p.cfg.MemoryMB); !ok {+ offered := sortedTiers(b.client.Config().SizeImages)+ sizes := make([]string, 0, len(offered)+1)+ sizes = append(sizes, strconv.Itoa(b.client.Config().DefaultMemoryMB))+ for _, mb := range offered {+ if mb != b.client.Config().DefaultMemoryMB {+ sizes = append(sizes, strconv.Itoa(mb))+ }+ }+ return fmt.Errorf("%w: %dMB was requested; this region offers %s MB",+ ErrSizeUnavailable, p.cfg.MemoryMB, strings.Join(sizes, ", "))+ }+ return nil+}+func (b *liteBackend) Accepts(p placement) bool {if b == nil {return false@@ -182,7 +230,21 @@ func (b *liteBackend) Accepts(p placement) bool {if p.runtime != runtimeMicrovm {return false}- if p.cfg.Template != "" && p.cfg.Template != "default" && p.cfg.Template != poolTemplateName() {+ // Named templates are ACCEPTED now. They are served by claiming a pooled+ // default box and unpacking the template's workspace archive onto it (see+ // Activate), so a template costs a tarball rather than a published image+ // per template.+ //+ // Whether a specific template is servable cannot be decided here —+ // placement carries the template NAME, not the resolved drive keys — so the+ // refusal for a template this runtime cannot honour lives in Activate,+ // where the keys are available.+ // Sizes are images, and only the tiers this cell has published images for+ // can be served. Declining here is what turns an unavailable size into a+ // clean placement failure instead of a sandbox that is quietly the wrong+ // size — memory cannot be adjusted after launch, so there is no later point+ // at which the mistake could be corrected.+ if _, _, ok := b.client.Config().ImageForMemory(p.cfg.MemoryMB); !ok {return false}return true@@ -212,9 +274,73 @@ func (b *liteBackend) Claim(ctx context.Context, p placement) (string, error) {return microvmWorkerID(box.MicrovmID), nil}-// Activate has nothing to do: Claim returns a box that is already RUNNING.-func (b *liteBackend) Activate(_ context.Context, a activation) (activated, error) {- return activated{sandboxID: a.sandboxID, status: "running"}, nil+// Activate applies the sandbox's environment, if it has one.+//+// Claim returns a box that is already RUNNING, so there is nothing to start —+// but `envs` on a create used to be dropped here in silence: Claim carries only+// template and size, and nothing else ever looked at cfg.Envs. The create+// returned 200 and the customer's program saw an unset variable.+//+// Conditional, because this is the create path. A create with no envs — which+// is every pooled create the benchmark makes — does not pay for this at all.+// One that has them pays one request, before the response, because the first+// exec can arrive the moment the caller has the sandbox id and an environment+// applied afterwards would reach some commands and not others.+func (b *liteBackend) Activate(ctx context.Context, a activation) (activated, error) {+ // A template's workspace, restored into the box we just claimed.+ //+ // This is how templates and forks work on this runtime: the sandbox starts+ // from the POOLED default image — so it keeps the fast claim — and the+ // template is a tarball unpacked on top, rather than a custom AWS image per+ // template. See internal/awsvmlite/checkpoint.go.+ //+ // Before envs and secrets deliberately: the archive can contain dotfiles+ // and shell profiles, and the environment should be applied to the sandbox+ // the customer will actually get, not to one that is about to be written+ // over.+ if a.templateRootfsKey != "" {+ // A template with a ROOTFS drive came from the QEMU fleet, where a+ // snapshot captures the whole disk. This runtime can only replay the+ // workspace half, and doing that silently would hand the customer their+ // files while dropping every system change the snapshot was taken for —+ // a template that looks like it worked and isn't.+ //+ // The empty rootfs key is a reliable marker here because this runtime's+ // own CreateCheckpoint returns "" for it (there is nothing to capture),+ // and the store writes that through as an empty string rather than NULL.+ return activated{}, fmt.Errorf(+ "vmhost-lite: template for %s carries a rootfs image, which this runtime cannot restore", a.sandboxID)+ }+ if a.templateWorkspaceKey != "" {+ if err := b.mgr.RestoreWorkspaceKey(ctx, a.sandboxID, a.templateWorkspaceKey); err != nil {+ return activated{}, fmt.Errorf("vmhost-lite: restore template into %s: %w", a.sandboxID, err)+ }+ }++ switch {+ case awsvmlite.HasSecrets(a.cfg):+ // INSTEAD OF SetEnvs, not as well as. The guest seals the secrets and+ // merges the plaintext envs into ONE environment; a SetEnvs afterwards+ // would replace that with an environment holding none of the sealed+ // values, silently disabling the secret store.+ if err := b.mgr.SetSecrets(ctx, a.sandboxID, a.cfg); err != nil {+ return activated{}, fmt.Errorf("vmhost-lite: set secrets on %s: %w", a.sandboxID, err)+ }+ case len(a.cfg.Envs) > 0:+ if err := b.mgr.SetEnvs(ctx, a.sandboxID, a.cfg.Envs); err != nil {+ // Fail the create rather than hand back a sandbox whose environment+ // is not what was asked for. Silently proceeding is what this whole+ // change exists to stop.+ return activated{}, fmt.Errorf("vmhost-lite: set envs on %s: %w", a.sandboxID, err)+ }+ }+ // The host's hard deadline, carried to the row. Zero when unknown, which+ // the persist step treats as "no deadline" rather than "already expired".+ return activated{+ sandboxID: a.sandboxID,+ status: "running",+ endAt: b.mgr.DeadlineFor(a.sandboxID),+ }, nil}// RequiresPersistedRow is true: this backend rebuilds its bindings FROM these@@ -232,11 +358,230 @@ func (b *liteBackend) Release(ctx context.Context, sandboxID, _ string) {if b == nil {return}+ // Metering happens inside Destroy, via the lifecycle observer, so that+ // every path that kills a box bills it — this one, the customer's DELETE,+ // the idle sweep and the shutdown drain. Doing it here would have covered+ // only create-cleanup.if err := b.mgr.Destroy(ctx, sandboxID); err != nil {log.Printf("vmhost-lite: release %s: %v", sandboxID, err)}}+var _ MemoryStateCapturer = (*liteBackend)(nil)++// CapturesMemoryState is false: this runtime's provider offers suspend/resume+// but no way to read a running host's RAM out, so a checkpoint here is the+// workspace archive and nothing more. Saying so lets the checkpoint API refuse+// a full capture with a reason instead of accepting one it cannot make.+func (b *liteBackend) CapturesMemoryState() bool { return false }++var _ IdleTimeouter = (*liteBackend)(nil)++// SetIdleTimeout applies a customer's idle timeout, reporting what is actually+// in force. See internal/awsvmlite/idle.go — a timeout at or beyond the host's+// remaining life is refused, because the provider ends the host at its cap+// whatever we do and pretending otherwise would be a promise this runtime+// cannot keep.+func (b *liteBackend) SetIdleTimeout(sandboxID string, d time.Duration) (time.Duration, error) {+ if b == nil {+ return 0, errors.New("vmhost-lite: backend disabled")+ }+ return b.mgr.SetIdleTimeout(sandboxID, d)+}++// StartIdleSweeper parks sandboxes whose customer-set idle timeout has elapsed.+//+// It lives here rather than in the manager because parking is a database+// transition as much as a provider call. Suspending the box alone would leave+// the row reading `running` — the customer sees a live sandbox that is actually+// asleep, it keeps consuming their concurrency limit — and, worse, wake answers+// "no active hibernation found" because nothing recorded one, stranding the+// sandbox parked for good. So this mirrors the customer-initiated path+// (hibernateViaBackend) exactly: park, record, flip, flush.+func (b *liteBackend) StartIdleSweeper(ctx context.Context, store *db.Store, sandboxDBs *sandbox.SandboxDBManager) {+ if b == nil || store == nil {+ return+ }+ go func() {+ t := time.NewTicker(awsvmlite.IdleSweepInterval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ for _, sandboxID := range b.mgr.ExpiredIdle(time.Now()) {+ b.parkIdle(ctx, store, sandboxDBs, sandboxID)+ }+ }+ }+ }()+ log.Printf("vmhost-lite: idle sweeper started (every %s)", awsvmlite.IdleSweepInterval)+}++// parkIdle performs the whole park, in the order that keeps the sandbox+// recoverable.+func (b *liteBackend) parkIdle(ctx context.Context, store *db.Store, sandboxDBs *sandbox.SandboxDBManager, sandboxID string) {+ session, err := store.GetSandboxSession(ctx, sandboxID)+ if err != nil || session == nil {+ // No row to move. Parking anyway would produce exactly the invisible+ // asleep-but-"running" sandbox this function exists to avoid.+ log.Printf("vmhost-lite: idle-park %s skipped — no session row (%v)", sandboxID, err)+ return+ }+ result, err := b.Hibernate(ctx, sandboxID)+ if err != nil {+ // Most likely the suspended cap is full. Leave it running and retry+ // next pass: a customer who asked for "park when idle" has not asked to+ // be billed differently because the cell was busy, but nor have they+ // asked for anything destructive.+ log.Printf("vmhost-lite: idle-park %s failed (%v) — retrying next sweep", sandboxID, err)+ return+ }+ // Record BEFORE flipping status, same as the customer path: a row marked+ // hibernated with no hibernation record is unwakeable.+ // The key is empty on this runtime: parking is a provider-side suspend, so+ // the disk stays where it is and there is no archive to name. The record+ // still has to exist — wake looks it up and 404s without one.+ if _, _, cErr := store.CreateHibernation(ctx, sandboxID, session.OrgID,+ result.HibernationKey, result.SizeBytes, session.Region, session.Template, session.Config); cErr != nil {+ // The box is ALREADY asleep at this point, and without a record wake+ // answers "no active hibernation found" — the sandbox would be parked+ // and unreachable for good. Undo the park rather than leave it there;+ // the next sweep will try again. Being billed for a few more minutes is+ // strictly better than being stranded.+ log.Printf("vmhost-lite: idle-park %s: record hibernation failed (%v) — waking it back", sandboxID, cErr)+ if _, wErr := b.Wake(ctx, sandboxID, "", 0); wErr != nil {+ log.Printf("vmhost-lite: idle-park %s: CRITICAL could not wake back after a failed park: %v", sandboxID, wErr)+ }+ return+ }+ if uErr := store.UpdateSandboxSessionStatus(ctx, sandboxID, "hibernated", nil); uErr != nil {+ log.Printf("vmhost-lite: idle-park %s: status flip failed: %v", sandboxID, uErr)+ }+ if sandboxDBs != nil {+ // The lifecycle event is what carries this to D1 sandboxes_index, which+ // is what the edge answers GET /sandboxes/:id from. Postgres alone is+ // not enough: a customer-initiated hibernate travels THROUGH the edge,+ // which updates D1 itself, but a park decided here has no such request+ // to piggyback on. Without this the sandbox is asleep while every+ // customer-facing surface still reports it running.+ if sdb, dbErr := sandboxDBs.Get(sandboxID); dbErr == nil {+ _ = sdb.LogEvent("hibernated", map[string]string{+ "sandbox_id": sandboxID,+ "checkpoint_key": result.HibernationKey,+ })+ }+ // Remove flushes what was just logged — the lifecycle event above and+ // the closing usage slice — before the per-sandbox DB is dropped.+ _ = sandboxDBs.Remove(sandboxID)+ }+ log.Printf("vmhost-lite: parked %s after its idle timeout", sandboxID)+}++// ── Hibernation ─────────────────────────────────────────────────────────────++// Compile-time proof this backend can park and revive its own sandboxes.+// Without it, hibernate and wake dispatch into the worker registry — which on+// this cell is empty — and fail with "no workers available" for a sandbox that+// is running perfectly well. That is exactly how the agent path's tiered+// hibernation ended up reachable from a test harness and from nothing else.+var _ Hibernator = (*liteBackend)(nil)++// Hibernate suspends the box. There is no archive and therefore no key: the+// state is the suspended box. See internal/awsvmlite/hibernate.go for the+// tradeoff, and in particular for why this is capped.+func (b *liteBackend) Hibernate(ctx context.Context, sandboxID string) (*sandbox.HibernateResult, error) {+ if b == nil {+ return nil, errors.New("vmhost-lite: backend disabled")+ }+ if err := b.mgr.Hibernate(ctx, sandboxID); err != nil {+ return nil, err+ }+ return &sandbox.HibernateResult{SandboxID: sandboxID}, nil+}++// Wake resumes the box and reports the worker_id still serving the sandbox.+//+// Unchanged, deliberately: a suspend/resume never moves the sandbox, so the+// persisted row already points at the right box. Returning a different id here+// would rewrite a correct row with a wrong one.+func (b *liteBackend) Wake(ctx context.Context, sandboxID, _ string, _ int) (string, error) {+ if b == nil {+ return "", errors.New("vmhost-lite: backend disabled")+ }+ if err := b.mgr.Wake(ctx, sandboxID); err != nil {+ return "", err+ }+ box, ok := b.mgr.BoxFor(sandboxID)+ if !ok {+ return "", fmt.Errorf("vmhost-lite: woke %s but hold no box for it", sandboxID)+ }+ return microvmWorkerID(box.MicrovmID), nil+}++// PreviewTarget reports how to reach a port inside this sandbox's guest, for+// the preview-URL proxy. False means this backend does not hold the sandbox.+//+// The port returned is the runtime's HOOK port, not the customer's: Lambda's+// proxy forwards only to the port declared on the image, so the customer's port+// travels in the path (/oc/port/<port>/...) and is fanned out inside the guest.+func (b *liteBackend) PreviewTarget(sandboxID string) (host, token string, hookPort int32, ok bool) {+ if b == nil {+ return "", "", 0, false+ }+ h, t, p, err := b.mgr.PreviewTarget(sandboxID)+ if err != nil {+ return "", "", 0, false+ }+ return h, t, p, true+}++// ── Terminals ───────────────────────────────────────────────────────────────+//+// Delegated straight to the manager. They live on the backend rather than on+// the sandbox.Manager adapter because a terminal is not one of sandbox.Manager's+// operations — it is a session with a socket, and forcing it into that+// interface would mean every runtime grew a method only this one implements.++func (b *liteBackend) PTYCreate(ctx context.Context, sandboxID string, req awsvmlite.PTYRequest) (string, error) {+ return b.mgr.PTYCreate(ctx, sandboxID, req)+}++func (b *liteBackend) PTYResize(ctx context.Context, sandboxID, sessionID string, cols, rows int32) error {+ return b.mgr.PTYResize(ctx, sandboxID, sessionID, cols, rows)+}++func (b *liteBackend) PTYKill(ctx context.Context, sandboxID, sessionID string) error {+ return b.mgr.PTYKill(ctx, sandboxID, sessionID)+}++func (b *liteBackend) DialPTY(ctx context.Context, sandboxID, sessionID string) (*websocket.Conn, error) {+ return b.mgr.DialPTY(ctx, sandboxID, sessionID)+}++// ── Exec sessions ───────────────────────────────────────────────────────────++func (b *liteBackend) ExecSessionCreate(ctx context.Context, sandboxID string, req awsvmlite.ExecSessionRequest) (string, error) {+ return b.mgr.ExecSessionCreate(ctx, sandboxID, req)+}++func (b *liteBackend) ExecSessionList(ctx context.Context, sandboxID string) ([]awsvmlite.ExecSessionInfo, error) {+ return b.mgr.ExecSessionList(ctx, sandboxID)+}++func (b *liteBackend) ExecSessionKill(ctx context.Context, sandboxID, sessionID string, signal int32) error {+ return b.mgr.ExecSessionKill(ctx, sandboxID, sessionID, signal)+}++func (b *liteBackend) ExecSessionGetResult(ctx context.Context, sandboxID, sessionID string) (*awsvmlite.ExecSessionResult, error) {+ return b.mgr.ExecSessionGetResult(ctx, sandboxID, sessionID)+}++func (b *liteBackend) DialExecSession(ctx context.Context, sandboxID, sessionID string) (*websocket.Conn, error) {+ return b.mgr.DialExecSession(ctx, sandboxID, sessionID)+}+// ── Reconciliation ──────────────────────────────────────────────────────────// Restore rebuilds the sandbox→box map from the database after a restart.@@ -259,7 +604,30 @@ func (b *liteBackend) Reconcile(ctx context.Context, store *db.Store) {}bound := b.mgr.Bindings()+ // One fleet-wide liveness answer for this pass.+ //+ // Without it, a sandbox that is BOTH held in memory AND has a row was never+ // liveness-checked by either loop below: the adopt loop skipped it because+ // it was held, and the forget loop skipped it because a row existed. So when+ // AWS reaped its box at the 8h cap the binding survived indefinitely —+ // measured on prod as bound=15 against exactly ONE live box.+ //+ // That number is not cosmetic. Capacity() reports len(Bound()) as the cell's+ // running count, which is what the edge routes on, so a count that only ever+ // grows makes the cell look progressively busier than it is.+ //+ // nil means the lookup FAILED, which is deliberately different from "nothing+ // is alive": dropping every binding on a transient AWS error would close out+ // every live sandbox on the cell.+ live, liveErr := b.mgr.LiveMicrovmIDs(ctx)+ if liveErr != nil {+ log.Printf("vmhost-lite: reconcile: fleet liveness unavailable (%v) — "++ "skipping the stale-binding sweep this pass", liveErr)+ live = nil+ }+var adopted, closed int+ var evicted, skipped, expired intseen := make(map[string]struct{}, len(rows))for _, r := range rows {seen[r.SandboxID] = struct{}{}@@ -267,7 +635,33 @@ func (b *liteBackend) Reconcile(ctx context.Context, store *db.Store) {if !ok {continue}- if _, held := bound[r.SandboxID]; held {+ // Past its deadline: the provider has destroyed this host by its own+ // contract, so no API call is needed to know that. Doing this FIRST is+ // what makes the pass useful even when AWS is unreachable — the case+ // where a liveness-based sweep can do nothing at all.+ //+ // The gated reads already hide this row, so closing it is bookkeeping+ // rather than a correctness fix. That is the intended shape.+ if !r.EndAt.IsZero() && time.Now().After(r.EndAt) {+ if _, held := bound[r.SandboxID]; held {+ b.mgr.Forget(r.SandboxID)+ }+ msg := "microvm reached its maximum lifetime"+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)+ expired+++ continue+ }+ if microvmID2, held := bound[r.SandboxID]; held {+ // Held AND has a row — the case that used to fall through both+ // loops unchecked. Verify the box is still there.+ if live != nil {+ if _, alive := live[microvmID2]; !alive {+ b.mgr.Forget(r.SandboxID)+ msg := "microvm no longer exists"+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)+ evicted+++ }+ }continue}// Sizing is re-derived from the row rather than defaulted, so a restart@@ -282,11 +676,37 @@ func (b *liteBackend) Reconcile(ctx context.Context, store *db.Store) {meta = awsvmlite.Meta{Template: cfg.Template, MemoryMB: cfg.MemoryMB, CPUCount: cfg.CpuCount}}}+ // The fleet listing answers this without another API call, and it is+ // strictly better than a per-row GetMicrovm: one call for the whole+ // pass, and — decisively — no ambiguity between "gone" and "could not+ // ask". A host absent from a listing that SUCCEEDED is gone.+ if live != nil {+ if _, stillThere := live[microvmID]; !stillThere {+ msg := "microvm no longer exists"+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)+ closed+++ continue+ }+ }alive, err := b.mgr.Adopt(ctx, r.SandboxID, microvmID, meta)if err != nil {- // Could not prove anything. Leaving the row alone is the safe- // direction: a transient describe failure must never close out a- // live sandbox.+ // ErrNotFound is PROOF, not a failure to observe. AWS has no record+ // of this host and never will again, so the old blanket "skip on any+ // error" left the row `running` for the life of the database — the+ // error recurs identically on every pass. Measured on dev as three+ // rows skipped silently, forever.+ if errors.Is(err, awsvm.ErrNotFound) {+ msg := "microvm no longer exists"+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)+ closed+++ continue+ }+ // Genuinely unknown — a throttle or timeout must never end a live+ // sandbox — so leave the row for the next pass, but SAY SO. The+ // silent continue is what let those three rows go unnoticed.+ skipped+++ log.Printf("vmhost-lite: reconcile %s: liveness unknown (%v) — leaving row running for the next pass",+ r.SandboxID, err)continue}if !alive {@@ -302,21 +722,26 @@ func (b *liteBackend) Reconcile(ctx context.Context, store *db.Store) {// path that never called Kill. Nothing else would ever drop it, and it would// keep being metered.var forgotten int- for sandboxID := range bound {+ for sandboxID, microvmID := range bound {if _, ok := seen[sandboxID]; ok {continue}- alive, err := b.mgr.Alive(ctx, sandboxID)- if err != nil || alive {+ if live == nil {+ continue // liveness unknown this pass; never drop on a guess+ }+ if _, alive := live[microvmID]; alive {continue}b.mgr.Forget(sandboxID)forgotten++}- if adopted > 0 || closed > 0 || forgotten > 0 {- log.Printf("vmhost-lite: reconciled — adopted %d, closed %d dead row(s), forgot %d dead binding(s)",- adopted, closed, forgotten)+ // skipped is in the summary deliberately: a row this pass could not resolve+ // is the one that becomes a permanent leak if the cause is not transient,+ // so it must be visible without turning on debug logging.+ if adopted > 0 || closed > 0 || forgotten > 0 || evicted > 0 || skipped > 0 || expired > 0 {+ log.Printf("vmhost-lite: reconciled — adopted %d, closed %d dead row(s), expired %d past-deadline row(s), forgot %d dead binding(s), evicted %d stale binding(s), skipped %d unresolved row(s)",+ adopted, closed, expired, forgotten, evicted, skipped)}}@@ -356,6 +781,9 @@ func (b *liteBackend) StartUsageTicker(ctx context.Context, sandboxDBs *sandbox.return}b.usageTicker = t+ // The manager fires the metering boundaries, because it is where a box+ // actually dies — see SetLifecycleObserver.+ b.mgr.SetLifecycleObserver(t)t.Start(ctx)log.Printf("vmhost-lite: usage ticker started")}@@ -376,12 +804,18 @@ func (b *liteBackend) StartEventPublisher(ctx context.Context, sandboxDBs *sandb// events-ingest drops a tick whose worker_id disagrees with// sandboxes_index.worker_id, and each of these sandboxes has its own, so the// id has to be resolved per sandbox rather than stamped fleet-wide.+ //+ // WorkerIDFor, not BoxFor: the closing tick of a destroyed sandbox is+ // drained after its binding is gone, so a live-only lookup missed and the+ // publisher stamped a generic fallback id — which never matches the row, so+ // the tick was discarded as coming from a non-owner worker. That silently+ // unbilled the last slice of every destroyed sandbox.workerIDs := func(sandboxID string) (string, bool) {- box, ok := b.mgr.BoxFor(sandboxID)+ microvmID, ok := b.mgr.WorkerIDFor(sandboxID)if !ok {return "", false}- return microvmWorkerID(box.MicrovmID), true+ return microvmWorkerID(microvmID), true}var meta worker.MetadataResolver@@ -470,7 +904,10 @@ func (b *liteBackend) Status() map[string]any {"enabled": true,"warm": b.mgr.Depth(),"bound": len(b.mgr.Bound()),- "region": b.client.Config().Region,+ // Parked boxes hold regional quota that can never be reclaimed, so this+ // is the number that explains a warm pool which will not fill.+ "suspended": b.mgr.SuspendedCount(),+ "region": b.client.Config().Region,}}@@ -478,3 +915,98 @@ func (b *liteBackend) Status() map[string]any {// cell's Postgres pool is not its supply. See SelfStocking — consulting that// pool for these creates measured 49-78ms of guaranteed miss per create.func (b *liteBackend) ServesOwnStock() bool { return true }++// ── Halt: archive, release, restore ─────────────────────────────────────────++// Compile-time proof this backend can park a sandbox in a way that outlives its+// host. Without it an org halt falls through to the worker registry, which on+// this cell is empty, and the org's sandboxes keep running while the org is+// halted — billed and reachable, which is the opposite of a halt.+var _ haltArchiver = (*liteBackend)(nil)++// ArchiveForHalt copies the sandbox's durable state to the checkpoint store.+//+// Deliberately does NOT touch the box. Suspending is what a customer hibernate+// does and it is wrong here: the provider counts suspended time against the+// same 8h lifetime cap as running time, so a suspended sandbox still dies at+// the cap and takes its disk with it. A credit halt lasts as long as it takes+// someone to pay, which is routinely longer than that.+//+// What survives is the workspace, not the process tree. There is no memory+// capture on this runtime (see CapturesMemoryState), so a halted-and-resumed+// sandbox comes back as a fresh boot holding its files — the honest limit, and+// the reason halt is not offered as a customer-facing pause.+func (b *liteBackend) ArchiveForHalt(ctx context.Context, sandboxID string, store *storage.CheckpointStore) (string, int64, error) {+ if b == nil {+ return "", 0, errors.New("vmhost-lite: backend disabled")+ }+ if store == nil {+ // Without a store there is nowhere durable to put the state, and+ // releasing the host would destroy it. Refusing leaves the sandbox+ // running, which is recoverable; proceeding would not be.+ return "", 0, errors.New("vmhost-lite: no checkpoint store configured — refusing to halt, the archive would have nowhere to go")+ }+ // Keyed by a fresh id rather than the sandbox id: a sandbox can be halted,+ // resumed and halted again, and reusing one key would have the second+ // archive overwrite the first while the first was still the recorded+ // hibernation for anything that had not yet resumed.+ key := awsvmlite.WorkspaceKey("halt-" + uuid.NewString())+ size, err := b.mgr.CheckpointWorkspace(ctx, sandboxID, key, store)+ if err != nil {+ return "", 0, fmt.Errorf("vmhost-lite: archive %s for halt: %w", sandboxID, err)+ }+ return key, size, nil+}++// ReleaseForHalt terminates the host. The point of no return: after this the+// archive is the only copy, so the caller must have recorded it first.+func (b *liteBackend) ReleaseForHalt(ctx context.Context, sandboxID string) error {+ if b == nil {+ return errors.New("vmhost-lite: backend disabled")+ }+ // Destroy bills the closing usage slice on the way out, which is the whole+ // point of halting: the charge stops here rather than running to the cap.+ return b.mgr.Destroy(ctx, sandboxID)+}++// RestoreForResume gives the sandbox a brand new host and lays the archive back+// onto it.+//+// Not a wake: there is nothing to wake. The host was released at halt, so this+// claims a fresh box and rebinds the SAME sandbox id to it, which is why the+// caller has to write the returned worker id back onto the row.+func (b *liteBackend) RestoreForResume(ctx context.Context, sandboxID, key string, store *storage.CheckpointStore, spec HaltRestoreSpec) (string, error) {+ if b == nil {+ return "", errors.New("vmhost-lite: backend disabled")+ }+ // Key first, deliberately. An empty key means the sandbox was SUSPENDED,+ // not archived — that is what an idle park records. Restoring a fresh box+ // for it would strand the suspended one and hand the customer an empty+ // sandbox. That diagnosis is more specific than a missing store and stays+ // true regardless of how this cell is configured, so it must not be+ // masked by the config check below.+ if key == "" {+ return "", errors.New("vmhost-lite: no archive key — this sandbox was suspended, not halted; wake it instead")+ }+ if store == nil {+ return "", errors.New("vmhost-lite: no checkpoint store configured")+ }+ box, _, err := b.mgr.Claim(ctx, sandboxID, awsvmlite.Meta{+ Template: spec.Template,+ MemoryMB: spec.MemoryMB,+ CPUCount: spec.CPUCount,+ })+ if err != nil {+ return "", fmt.Errorf("vmhost-lite: claim a host for %s: %w", sandboxID, err)+ }+ if err := b.mgr.RestoreWorkspace(ctx, sandboxID, key, store); err != nil {+ // Give the box back. A claimed host with none of the customer's data on+ // it is worse than no host at all: it bills, it answers, and it looks+ // like a resumed sandbox that has silently lost everything.+ if dErr := b.mgr.Destroy(ctx, sandboxID); dErr != nil {+ log.Printf("vmhost-lite: resume %s: restore failed AND could not release the host: %v", sandboxID, dErr)+ }+ return "", fmt.Errorf("vmhost-lite: restore %s from %s: %w", sandboxID, key, err)+ }+ return microvmWorkerID(box.MicrovmID), nil+}diff --git a/internal/api/lite_size_refusal_test.go b/internal/api/lite_size_refusal_test.gonew file mode 100644index 00000000..62a784a7--- /dev/null+++ b/internal/api/lite_size_refusal_test.go@@ -0,0 +1,65 @@+package api++import (+ "errors"+ "strings"+ "testing"++ "github.com/opensandbox/opensandbox/internal/awsvm"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// A size we do not publish must be refused with a reason the customer can act+// on. The failure this guards against is not the refusal — Accepts already+// declines correctly — it is the refusal arriving as "out of capacity", which+// tells someone to wait for a shortage that will never clear.+func TestSizeRefusalNamesTheSizesActuallyOffered(t *testing.T) {+ cfg := awsvm.Config{+ ImageIdentifier: "arn:default",+ DefaultMemoryMB: 4096,+ SizeImages: map[int]string{8192: "arn:8192"},+ }++ for _, tc := range []struct {+ name string+ memoryMB int+ wantErr bool+ }{+ {"the default size is always offered", 0, false},+ {"an explicitly published tier is offered", 8192, false},+ {"an unpublished tier is refused", 16384, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ b := &liteBackend{client: awsvm.NewClientWithAPI(nil, cfg)}+ err := b.ExplainRefusal(placement{+ runtime: runtimeMicrovm,+ cfg: types.SandboxConfig{MemoryMB: tc.memoryMB},+ })+ if tc.wantErr != (err != nil) {+ t.Fatalf("memoryMB=%d: got err=%v, wanted err=%v", tc.memoryMB, err, tc.wantErr)+ }+ if !tc.wantErr {+ return+ }+ if !errors.Is(err, ErrSizeUnavailable) {+ t.Errorf("refusal does not carry ErrSizeUnavailable, so respondCreateErr will fall through to a 503: %v", err)+ }+ // The list is the whole point — "not available" alone leaves the+ // caller guessing at a set only we can see.+ for _, want := range []string{"4096", "8192"} {+ if !strings.Contains(err.Error(), want) {+ t.Errorf("refusal omits offered size %s: %q", want, err.Error())+ }+ }+ })+ }+}++// A create for another runtime must not be explained by this backend, or every+// QEMU capacity failure would be reported as a MicroVM size problem.+func TestSizeRefusalStaysSilentForOtherRuntimes(t *testing.T) {+ b := &liteBackend{client: awsvm.NewClientWithAPI(nil, awsvm.Config{DefaultMemoryMB: 4096})}+ if err := b.ExplainRefusal(placement{runtime: "", cfg: types.SandboxConfig{MemoryMB: 16384}}); err != nil {+ t.Fatalf("explained a refusal for a non-MicroVM create: %v", err)+ }+}diff --git a/internal/api/pty_managed.go b/internal/api/pty_managed.gonew file mode 100644index 00000000..6023cf05--- /dev/null+++ b/internal/api/pty_managed.go@@ -0,0 +1,250 @@+package api++// pty_managed.go — serving PTY for a backend the control plane holds.+//+// The fleet reaches a terminal by proxying to the worker that owns the sandbox.+// A managed backend has no worker, so those routes were refused (see+// refuseIfManaged, and the bug it exists to prevent). These handlers serve them+// in-process instead: three small JSON calls, and one WebSocket spliced through+// to the box.+//+// The splice is deliberately DUMB. Both sides speak the same frame format —+// the customer's SDK to us, and us to the guest — so this copies messages+// without interpreting them. Anything smarter would be a second implementation+// of a protocol that already has one, on the path where a bug shows up as a+// corrupted terminal rather than an error.++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "log"+ "net/http"+ "time"++ "github.com/gorilla/websocket"+ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/awsvmlite"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// ptyBackend is implemented by a backend that can serve terminals itself.+type ptyBackend interface {+ PTYCreate(ctx context.Context, sandboxID string, req awsvmlite.PTYRequest) (string, error)+ PTYResize(ctx context.Context, sandboxID, sessionID string, cols, rows int32) error+ PTYKill(ctx context.Context, sandboxID, sessionID string) error+ DialPTY(ctx context.Context, sandboxID, sessionID string) (*websocket.Conn, error)+}++// ptyBackendFor returns the backend serving this sandbox's terminals, if any.+func (s *Server) ptyBackendFor(ctx context.Context, sandboxID string) (ptyBackend, bool) {+ b, _, ok := s.backendFor(ctx, sandboxID)+ if !ok {+ return nil, false+ }+ pb, ok := b.(ptyBackend)+ return pb, ok+}++// dispatchPTY serves a PTY route locally when a managed backend holds the+// sandbox, and otherwise hands it to the proxy — which is every QEMU sandbox,+// unchanged.+func (s *Server) dispatchPTY(local, proxied echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ if _, ok := s.ptyBackendFor(c.Request().Context(), c.Param("id")); ok {+ return local(c)+ }+ return proxied(c)+ }+}++func (s *Server) createPTYManaged(c echo.Context) error {+ id := c.Param("id")+ b, ok := s.ptyBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "terminals are not supported for this sandbox"})+ }+ var req types.PTYCreateRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})+ }+ sessionID, err := b.PTYCreate(c.Request().Context(), id, awsvmlite.PTYRequest{+ Cols: int32(req.Cols), Rows: int32(req.Rows), Shell: req.Shell,+ })+ if err != nil {+ return respondFSErr(c, err)+ }+ return c.JSON(http.StatusCreated, types.PTYSession{SessionID: sessionID, SandboxID: id})+}++func (s *Server) resizePTYManaged(c echo.Context) error {+ id, sessionID := c.Param("id"), c.Param("sessionID")+ b, ok := s.ptyBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "terminals are not supported for this sandbox"})+ }+ var req types.PTYResizeRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})+ }+ if err := b.PTYResize(c.Request().Context(), id, sessionID, int32(req.Cols), int32(req.Rows)); err != nil {+ return respondFSErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+}++func (s *Server) killPTYManaged(c echo.Context) error {+ id, sessionID := c.Param("id"), c.Param("sessionID")+ b, ok := s.ptyBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "terminals are not supported for this sandbox"})+ }+ if err := b.PTYKill(c.Request().Context(), id, sessionID); err != nil {+ return respondFSErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+}++// ptyUpgrader accepts the customer's side of the terminal.+var ptyUpgrader = websocket.Upgrader{+ ReadBufferSize: 32 * 1024,+ WriteBufferSize: 32 * 1024,+ // The edge has already authenticated this request; there is no browser+ // origin to check it against.+ CheckOrigin: func(*http.Request) bool { return true },+}++// ptyWebSocketManaged splices the customer's terminal socket to the box's.+//+// Dial FIRST, upgrade second. Upgrading commits a 101 that cannot be taken+// back, so a box that refuses the connection would leave the customer with an+// open socket and no way to be told why — this way the failure is an ordinary+// HTTP status.+func (s *Server) ptyWebSocketManaged(c echo.Context) error {+ id, sessionID := c.Param("id"), c.Param("sessionID")+ b, ok := s.ptyBackendFor(c.Request().Context(), id)+ if !ok {+ return c.JSON(http.StatusNotImplemented, map[string]string{"error": "terminals are not supported for this sandbox"})+ }++ // Not the request context: it is cancelled when the handler returns, and+ // this socket has to outlive that for the length of the session.+ box, err := b.DialPTY(context.Background(), id, sessionID)+ if err != nil {+ log.Printf("pty: dial %s/%s: %v", id, sessionID, err)+ return c.JSON(http.StatusBadGateway, map[string]string{"error": "could not attach to the terminal"})+ }+ defer box.Close()++ client, err := ptyUpgrader.Upgrade(c.Response(), c.Request(), nil)+ if err != nil {+ log.Printf("pty: upgrade %s/%s: %v", id, sessionID, err)+ return nil // Upgrade already wrote a response+ }+ defer client.Close()++ // Either direction ending ends the session: a terminal with one live half+ // is a terminal that echoes into nothing.+ // TRANSLATED, not spliced. The guest speaks a framed protocol+ // ({data:base64, cols, rows}) because a PTY needs an out-of-band resize;+ // the customer-facing contract, set by the QEMU path, is raw binary frames+ // with resize over HTTP. Passing the guest's frames straight through made a+ // terminal that works on one runtime print base64 JSON on the other — the+ // customer's SDK is identical, so the runtime must not be visible here.+ done := make(chan struct{}, 2)+ go pumpPTYToClient(client, box, done)+ go pumpPTYToBox(box, client, done)+ <-done++ // Nudge the other pump: closing both sockets makes its blocked read return,+ // so neither goroutine outlives the session.+ _ = client.SetReadDeadline(time.Now())+ _ = box.SetReadDeadline(time.Now())+ return nil+}++// pumpWS copies messages one way until either side fails.+func pumpWS(dst, src *websocket.Conn, done chan<- struct{}) {+ defer func() { done <- struct{}{} }()+ for {+ mt, msg, err := src.ReadMessage()+ if err != nil {+ return+ }+ if err := dst.WriteMessage(mt, msg); err != nil {+ return+ }+ }+}++// ptyServerFrame / ptyClientFrame mirror cmd/microvm-hooks' oc_stream.go. Kept+// as private copies rather than shared types because they are a WIRE contract+// with a separately-deployed binary: an import would let a change here silently+// imply a guest that has not been rebuilt.+type ptyServerFrame struct {+ Data string `json:"data,omitempty"`+ Exited bool `json:"exited,omitempty"`+ ExitCode int32 `json:"exitCode,omitempty"`+ Error string `json:"error,omitempty"`+}++type ptyClientFrame struct {+ Data string `json:"data,omitempty"`+ Cols int32 `json:"cols,omitempty"`+ Rows int32 `json:"rows,omitempty"`+}++// pumpPTYToClient unwraps the guest's frames into the raw bytes a terminal+// expects.+func pumpPTYToClient(client, box *websocket.Conn, done chan<- struct{}) {+ defer func() { done <- struct{}{} }()+ for {+ _, msg, err := box.ReadMessage()+ if err != nil {+ return+ }+ var f ptyServerFrame+ if err := json.Unmarshal(msg, &f); err != nil {+ // Not a frame we understand. Forwarding it raw is the safer+ // failure: a guest that ever sends plain bytes still works, and+ // the alternative is a terminal that silently drops output.+ if err := client.WriteMessage(websocket.BinaryMessage, msg); err != nil {+ return+ }+ continue+ }+ if f.Data != "" {+ out, dErr := base64.StdEncoding.DecodeString(f.Data)+ if dErr != nil {+ continue+ }+ if err := client.WriteMessage(websocket.BinaryMessage, out); err != nil {+ return+ }+ }+ if f.Exited {+ // The shell is gone; closing tells the customer's socket so rather+ // than leaving it open against a dead PTY.+ return+ }+ }+}++// pumpPTYToBox wraps the customer's keystrokes into the guest's frames.+func pumpPTYToBox(box, client *websocket.Conn, done chan<- struct{}) {+ defer func() { done <- struct{}{} }()+ for {+ _, msg, err := client.ReadMessage()+ if err != nil {+ return+ }+ frame, mErr := json.Marshal(ptyClientFrame{Data: base64.StdEncoding.EncodeToString(msg)})+ if mErr != nil {+ return+ }+ if err := box.WriteMessage(websocket.TextMessage, frame); err != nil {+ return+ }+ }+}diff --git a/internal/api/pty_managed_test.go b/internal/api/pty_managed_test.gonew file mode 100644index 00000000..dde4c863--- /dev/null+++ b/internal/api/pty_managed_test.go@@ -0,0 +1,112 @@+package api++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+)++// pty_managed_test.go — the splice, which is where a terminal breaks quietly.+//+// A PTY that drops a frame does not error; it renders wrong. A pump that+// outlives its session does not error either; it leaks a goroutine and a PTY on+// the box, once per detach, until the box dies.++var testUpgrader = websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}++// wsPair returns a connected client/server pair over a real socket.+func wsPair(t *testing.T) (client, server *websocket.Conn, closeAll func()) {+ t.Helper()+ srvCh := make(chan *websocket.Conn, 1)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ c, err := testUpgrader.Upgrade(w, r, nil)+ if err != nil {+ t.Errorf("upgrade: %v", err)+ return+ }+ srvCh <- c+ <-r.Context().Done()+ }))+ c, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(srv.URL, "http"), nil)+ if err != nil {+ t.Fatalf("dial: %v", err)+ }+ s := <-srvCh+ return c, s, func() { c.Close(); s.Close(); srv.Close() }+}++// Frames cross the splice byte-for-byte. The two sides speak the same protocol,+// so anything this handler "helpfully" rewrote would be a second, divergent+// implementation of it.+func TestPumpCopiesFramesVerbatim(t *testing.T) {+ aClient, aServer, closeA := wsPair(t)+ defer closeA()+ bClient, bServer, closeB := wsPair(t)+ defer closeB()++ done := make(chan struct{}, 2)+ go pumpWS(bClient, aServer, done)++ payload := `{"data":"aGVsbG8=","cols":120,"rows":40}`+ if err := aClient.WriteMessage(websocket.TextMessage, []byte(payload)); err != nil {+ t.Fatalf("write: %v", err)+ }+ _ = bServer.SetReadDeadline(time.Now().Add(3 * time.Second))+ mt, got, err := bServer.ReadMessage()+ if err != nil {+ t.Fatalf("read through the splice: %v", err)+ }+ if mt != websocket.TextMessage {+ t.Errorf("message type = %d, want text — a rewritten type breaks binary PTY output", mt)+ }+ if string(got) != payload {+ t.Errorf("frame = %q, want it unchanged: %q", got, payload)+ }+}++// A pump must end when its source closes, or every detached terminal leaves a+// goroutine and a live PTY behind on the box.+func TestPumpEndsWhenSourceCloses(t *testing.T) {+ aClient, aServer, closeA := wsPair(t)+ defer closeA()+ bClient, _, closeB := wsPair(t)+ defer closeB()++ done := make(chan struct{}, 1)+ go pumpWS(bClient, aServer, done)++ aClient.Close()++ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatal("pump outlived its source socket — one leaked goroutine and PTY per detach")+ }+}++// And when its destination closes: the customer hanging up must tear down the+// box side too, not just stop reading from it.+func TestPumpEndsWhenDestinationCloses(t *testing.T) {+ aClient, aServer, closeA := wsPair(t)+ defer closeA()+ bClient, _, closeB := wsPair(t)+ defer closeB()++ done := make(chan struct{}, 1)+ go pumpWS(bClient, aServer, done)++ bClient.Close()+ // A write has to be attempted before a closed destination is noticed, which+ // is what this frame is for.+ _ = aClient.WriteMessage(websocket.TextMessage, []byte(`{"data":"eA=="}`))++ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatal("pump outlived its destination socket")+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex b99dcd64..27c35325 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -82,8 +82,7 @@ type Server struct {stripeClient *billing.StripeClient // nil if Stripe not configuredredisClient *redis.Client // nil if Redis not configured (for health checks)adminEvents *AdminEventBus // real-time event bus for admin dashboard- microvm *microvmBackend // managed-host backend; nil unless enabled (see microvm_backend.go)- lite *liteBackend // direct-exec managed-host backend; mutually exclusive with microvm (see lite_backend.go)+ lite *liteBackend // managed-host (MicroVM) backend; nil unless enabled (see lite_backend.go)materialize *materializer // memoizes per-org/user row creation off the create hot path (materialize.go)orgRuntime *orgRuntimeCache // memoizes orgs.runtime for the direct-to-cell create path (backend.go)templateCache *templateCache // caches name→template so create doesn't call the edge every time (template_cache.go)@@ -276,6 +275,16 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, os.redisClient = opts.RedisClients.adminEvents = NewAdminEventBus()+ // Teach the proxy which worker_ids name a managed backend, so a request+ // that reaches it for one is refused rather than mistaken for a lost+ // worker and closed out. See SetManagedWorkerID.+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.SetManagedWorkerID(func(workerID string) bool {+ _, ok := s.backendForWorkerID(workerID)+ return ok+ })+ }+// Wire up readiness waiting so the proxy blocks until async creates finishif s.sandboxAPIProxy != nil {s.sandboxAPIProxy.SetWaitForReady(func(ctx context.Context, sandboxID string) error {@@ -342,6 +351,27 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// trust" — same as POST /internal/sandboxes/create.cp := opts.ControlPlaneProxysandboxDomain := opts.SandboxDomain+ // Preview traffic for a sandbox this process holds cannot go through+ // the worker lookup — there is no registered worker. Hand the proxy a+ // resolver so it can reach the guest port through the runtime's own+ // proxy instead. Returns false for every worker-held sandbox, which+ // leaves the fleet path exactly as it was.+ if cp != nil {+ cp.SetManagedPreview(func(sandboxID string) (proxy.ManagedPreview, bool) {+ for _, b := range s.backends {+ pv, ok := b.(interface {+ PreviewTarget(string) (string, string, int32, bool)+ })+ if !ok {+ continue+ }+ if host, token, hookPort, found := pv.PreviewTarget(sandboxID); found {+ return proxy.ManagedPreview{Host: host, Token: token, HookPort: hookPort}, true+ }+ }+ return proxy.ManagedPreview{}, false+ })+ }e.Any("/internal/preview/:id/:port/*", func(c echo.Context) error {id := c.Param("id")portStr := c.Param("port")@@ -408,9 +438,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, ointernal.POST("/pool/edge-reserve", s.edgeReservePool)internal.POST("/pool/edge-release", s.edgeReleasePool)internal.POST("/sandboxes/claim-finalize", s.claimFinalize)- // Direct-path seam (see microvm_direct.go): lets the edge dial a- // MicroVM's agent itself instead of relaying exec through this process.- internal.GET("/microvm/direct/:id", s.microvmDirectInfo)// Cross-cell paused-cap enforcement: the edge (which has the org-global// view via D1) calls this to promote a specific paused sandbox to deep// hibernation, reclaiming its worker RAM.@@ -458,9 +485,26 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// distinct middleware chain from the human-API-key /admin group above.// Echo treats route registrations independently — there's no conflict.//- // Only mounted when this CP can actually halt sandboxes (workers registry- // present); a server-only CP without workers has no work to do here.- if s.workerRegistry != nil {+ // Mounted UNCONDITIONALLY, and that is deliberate.+ //+ // This was `if s.workerRegistry != nil`. That reads as "only if this cell+ // has workers", but the registry is built for any server-mode CP with+ // Redis (cmd/server/main.go), so a MicroVM-only cell has a NON-NIL,+ // EMPTY one and the routes did mount. The gate was not the outage — it was+ // a tripwire whose premise had quietly become wrong, and it would have+ // become an outage the moment a cell ran in combined mode, where the+ // registry IS nil and /internal/sandboxes/create disappears with it.+ //+ // The obvious repair — `|| len(s.backends) > 0` — is a TRAP: backends are+ // registered ~400 lines below this point, so the slice is always empty+ // here and the condition silently stays false. Any gate written in terms+ // of state this function populates later has the same defect.+ //+ // So there is no gate. The routes are HMAC-authenticated, and a cell with+ // nothing to halt answers `halted: 0`, which is both honest and cheap. A+ // 404 was never the better answer: it is indistinguishable from a broken+ // deployment.+ {if s.cfAdminSecret == "" {log.Printf("api: WARNING: CF admin webhooks mounted without CF_ADMIN_SECRET — anyone can halt/resume orgs. Set OPENSANDBOX_CF_ADMIN_SECRET in production.")}@@ -604,10 +648,14 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, omethod, path stringlocal echo.HandlerFunc}{- {http.MethodPost, "/sandboxes/:id/exec", s.createExecSession},- {http.MethodGet, "/sandboxes/:id/exec", s.listExecSessions},- {http.MethodGet, "/sandboxes/:id/exec/:sessionID/result", s.execResult},- {http.MethodPost, "/sandboxes/:id/exec/:sessionID/kill", s.killExecSession},+ // Sessions are served in-process for a managed backend and by the+ // existing handler otherwise. Wrapped rather than replaced: the+ // local handlers below reach for s.execSessionManager, which is+ // legitimately nil on a cell whose sandboxes all live in a backend.+ {http.MethodPost, "/sandboxes/:id/exec", s.dispatchExecSession(s.createExecSessionManaged, s.createExecSession)},+ {http.MethodGet, "/sandboxes/:id/exec", s.dispatchExecSession(s.listExecSessionsManaged, s.listExecSessions)},+ {http.MethodGet, "/sandboxes/:id/exec/:sessionID/result", s.dispatchExecSession(s.execResultManaged, s.execResult)},+ {http.MethodPost, "/sandboxes/:id/exec/:sessionID/kill", s.dispatchExecSession(s.killExecSessionManaged, s.killExecSession)},{http.MethodPost, "/sandboxes/:id/exec/run", s.execRun},{http.MethodPost, "/sandboxes/:id/exec/run-async", s.execRunAsyncRoute},@@ -625,32 +673,51 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// in-process do not implement PTY, agent sessions, or bidi streaming, so// routing them here would answer a request no manager can serve. They// reach the worker path exactly as before.- api.GET("/sandboxes/:id/exec/:sessionID", wsHandler)+ //+ // refuseIfManaged wraps every one of them. Reaching the proxy with a+ // backend-held sandbox is not a harmless miss: the proxy looks the+ // sandbox up in the worker registry, finds nothing (a managed sandbox is+ // never registered), concludes the worker was lost and writes the row to+ // `stopped`. One PTY request destroyed a healthy MicroVM sandbox, and+ // every later request to it returned 410. See refuseIfManaged.+ mpxy := s.refuseIfManaged(pxy)+ mws := s.refuseIfManaged(wsHandler)++ // Attaching to a session's live output. Served in-process for a managed+ // backend (see exec_session_managed.go); every worker-held sandbox+ // still reaches the broker or the proxy exactly as before.+ api.GET("/sandboxes/:id/exec/:sessionID", s.dispatchExecSession(s.execSessionWebSocketManaged, mws))// Agent- api.POST("/sandboxes/:id/agent", pxy)- api.GET("/sandboxes/:id/agent", pxy)- api.GET("/sandboxes/:id/agent/:sid", wsHandler)- api.POST("/sandboxes/:id/agent/:sid/prompt", pxy)- api.POST("/sandboxes/:id/agent/:sid/interrupt", pxy)- api.POST("/sandboxes/:id/agent/:sid/kill", pxy)+ api.POST("/sandboxes/:id/agent", mpxy)+ api.GET("/sandboxes/:id/agent", mpxy)+ api.GET("/sandboxes/:id/agent/:sid", mws)+ api.POST("/sandboxes/:id/agent/:sid/prompt", mpxy)+ api.POST("/sandboxes/:id/agent/:sid/interrupt", mpxy)+ api.POST("/sandboxes/:id/agent/:sid/kill", mpxy)// Mounts (FUSE)- api.POST("/sandboxes/:id/mounts", pxy)- api.GET("/sandboxes/:id/mounts", pxy)- api.DELETE("/sandboxes/:id/mounts", pxy)-- // PTY- api.POST("/sandboxes/:id/pty", pxy)- api.GET("/sandboxes/:id/pty/:sessionID", wsHandler)- api.POST("/sandboxes/:id/pty/:sessionID/resize", pxy)- api.DELETE("/sandboxes/:id/pty/:sessionID", pxy)-- // Timeout- api.POST("/sandboxes/:id/timeout", pxy)+ api.POST("/sandboxes/:id/mounts", mpxy)+ api.GET("/sandboxes/:id/mounts", mpxy)+ api.DELETE("/sandboxes/:id/mounts", mpxy)++ // PTY. Unlike the routes above these ARE served for a managed backend —+ // in-process, over a WebSocket opened to the box for the life of the+ // session and closed with it. See pty_managed.go. A worker-held sandbox+ // still takes the proxy, unchanged.+ api.POST("/sandboxes/:id/pty", s.dispatchPTY(s.createPTYManaged, mpxy))+ api.GET("/sandboxes/:id/pty/:sessionID", s.dispatchPTY(s.ptyWebSocketManaged, mws))+ api.POST("/sandboxes/:id/pty/:sessionID/resize", s.dispatchPTY(s.resizePTYManaged, mpxy))+ api.DELETE("/sandboxes/:id/pty/:sessionID", s.dispatchPTY(s.killPTYManaged, mpxy))++ // Timeout. Served in-process for a managed backend, which owns its own+ // idle policy (the router below only tracks worker-held sandboxes, so a+ // managed one set through it would silently never fire). Worker-held+ // sandboxes still take the proxy, unchanged.+ api.POST("/sandboxes/:id/timeout", s.dispatchIdleTimeout(s.setTimeout, mpxy))// Token refresh- api.POST("/sandboxes/:id/token/refresh", pxy)+ api.POST("/sandboxes/:id/token/refresh", mpxy)} else {// Combined/worker mode: handle locallyapi.POST("/sandboxes/:id/exec", s.createExecSession)@@ -853,14 +920,18 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// Serve web dashboard SPA at root (catch-all after API/auth routes)s.serveDashboardUI(e, frontendURL)- // The direct-exec MicroVM backend (OPENSANDBOX_MICROVM_LITE=1). Selected- // INSTEAD of the agent-tunnel one below, never alongside it: both manufacture- // boxes from the same image against the same regional quota, and two fillers- // each believing they own the fleet would overrun it and starve each other.+ // The managed-host (MicroVM) backend — see lite_backend.go. Enabled by+ // OPENSANDBOX_MICROVM_ENABLED=1; nil otherwise, and no AWS call is ever made,+ // so a QEMU cell is unaffected. When it IS enabled but misconfigured, fail+ // loudly rather than silently serving QEMU from a cell the operator believes+ // is running MicroVMs.//- // See lite_backend.go. The trade is total — no files, no hibernate, no- // streaming — so this is a measurement configuration, not a default.- if lite, err := newLiteBackend(context.Background()); err != nil {+ // This was once one of two MicroVM backends, the other holding a gRPC agent+ // tunnel per box brokered by this process. That one is deleted: reaching the+ // guest over plain JSON through the platform's own proxy is both faster and+ // the only thing that works across it, and running two fillers against one+ // regional quota meant each overran and starved the other.+ if lite, err := newLiteBackend(context.Background(), s.checkpointStore); err != nil {log.Fatalf("opensandbox: vmhost-lite backend: %v", err)} else if lite != nil {s.lite = lite@@ -871,57 +942,15 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, olite.StartReconciler(context.Background(), s.store)lite.StartUsageTicker(context.Background(), s.sandboxDBs)lite.StartEventPublisher(context.Background(), s.sandboxDBs, s.redisClient, s.cellID, s.store)+ // Customer-set idle timeouts. Driven from here, not the manager, because+ // parking has to move the row and record a hibernation or the sandbox is+ // stranded asleep. See StartIdleSweeper.+ lite.StartIdleSweeper(context.Background(), s.store, s.sandboxDBs)if s.workerRegistry == nil || s.workersDisabled {lite.StartCapacityReporter(context.Background(), s.redisClient, s.cellID)}}- // AWS Lambda MicroVM backend. Disabled by default: this returns nil and no- // 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(), s.checkpointStore); err != nil {- log.Fatalf("opensandbox: microvm backend: %v", err)- } else if mvm != nil {- s.microvm = mvm- // A reservation that dies unclaimed must wake anything parked on its- // finalize — see THE FINALIZE RACE in edge_claim.go.- mvm.onReservationLost = s.resolveEdgePending- // Registering it is what makes every claim/route site find it. Before- // this the sites each hardcoded their own check, and any new one- // silently defaulted to the worker path.- s.registerBackend(mvm)- // Rebuild the sandbox→MicroVM map before serving. A restart otherwise- // leaves live sandboxes unroutable and their boxes unreapable.- mvm.Restore(context.Background(), s.store)- // Nothing else will ever notice a MicroVM dying — no worker reports in- // for these — so sweep on a ticker for the lifetime of the process.- mvm.StartReconciler(context.Background(), s.store)- // Billing: no worker exists to emit usage ticks for these sandboxes, so- // the control plane emits them itself over the same interface.- mvm.StartUsageTicker(context.Background(), s.sandboxDBs)- // ...and drains them to the cell stream. The ticker alone writes to- // local SQLite; without this half nothing ever reads it, and the- // sandboxes run free while every log line says billing is working.- mvm.StartEventPublisher(context.Background(), s.sandboxDBs, s.redisClient, s.cellID, s.store)- // Release suspended boxes once their archive is durable. Without this a- // hibernation holds regional memory quota — the ceiling on warm-pool- // depth — for the whole life of the box rather than the 10 minutes it- // is actually useful as a fast-wake cache.- mvm.StartHibernationExpiry(context.Background(), s.store)- // Capacity, but only when no registry-backed reporter is publishing it- // already — two writers on one stream would alternate between MicroVM- // depth and worker counts, flapping the cell in and out of the edge's- // routing set. Keyed on workersDisabled rather than a nil registry: a- // MicroVM cell in server mode still HAS a registry (worker_id lookups,- // lifecycle publishing), it just never has workers in it, and gating on- // the registry left the worker-counting reporter running to publish- // available_workers=0 forever.- if s.workerRegistry == nil || s.workersDisabled {- mvm.StartCapacityReporter(context.Background(), s.redisClient, s.cellID)- }- }-// The QEMU fleet, registered last so it is the fall-through rather than the// preference: a cell running both serves creates from the backend that holds// its own warm stock, and reaches the fleet only when that one declines.diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 1b2f8e23..abcebcfe 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -15,6 +15,7 @@ import ("github.com/jackc/pgx/v5""github.com/labstack/echo/v4""github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/awsvm""github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/edgeclient"@@ -894,9 +895,8 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty// yields the same answer it would further down.tr.mark("tmpl")orgRuntime := s.runtimeFor(c)- backend, ok := s.claimBackend(placement{- region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,- })+ place := placement{region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg}+ backend, ok := s.claimBackend(place)// This is the FLEET's warm pool: rows in this cell's Postgres, claimed by// resume+rebind on a QEMU worker. A backend that keeps its own warm stock@@ -938,8 +938,16 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty// what each step means here. Before this the sequence was inline and the// persist-before-activate constraint was a comment.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.+ // Ask first whether a backend refused for a reason a retry can never+ // fix — an unavailable size being the one that matters, since telling+ // that customer to wait for capacity sends them to support about a+ // shortage that does not exist.+ if why := s.explainRefusal(place); why != nil {+ return respondCreateErr(c, why)+ }+ // Otherwise 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.return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "out of capacity: no sandbox capacity is currently available in this region",})@@ -1024,6 +1032,14 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyif host.goldenVersion != "" {_ = s.store.SetSandboxGoldenVersion(ctx, sandboxID, host.goldenVersion)}+ // The host's hard deadline, stamped BEFORE the status flip for the+ // same reason as the golden: once the row reads `running` it is+ // live to every other reader, and a running row with no deadline is+ // exactly the leak this closes. No-ops when the runtime has no such+ // deadline, which is every QEMU sandbox.+ if !host.endAt.IsZero() {+ _ = s.store.SetSandboxEndAt(ctx, sandboxID, host.endAt)+ }return s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "running", nil)},@@ -1087,6 +1103,13 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty"region": region,"workerID": workerID,}+ // The provider's hard deadline, so the index the edge reads can carry it.+ // Already stamped on the PG row above, but PG is per-cell and the+ // customer-facing read is answered from D1 — without this the stamp is+ // invisible to the only reader that matters.+ if !host.endAt.IsZero() {+ resp["endAt"] = host.endAt.UTC().Format(time.RFC3339)+ }if s.sandboxDomain != "" {resp["sandboxDomain"] = s.sandboxDomain}@@ -1103,6 +1126,17 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyfunc (s *Server) getSandbox(c echo.Context) error {id := c.Param("id")+ // The holding backend knows the live state; the worker registry does not+ // know this sandbox exists. Asking AWS rather than the local binding is+ // deliberate — see awsvmlite's Get.+ if mgr, ok := s.execManagerFor(id); ok {+ sb, err := mgr.Get(c.Request().Context(), id)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ return c.JSON(http.StatusOK, sb)+ }+// Server mode with worker registry: look up from PG and issue fresh tokenif s.workerRegistry != nil {return s.getSandboxRemote(c, id)@@ -1511,10 +1545,6 @@ func (s *Server) listSandboxesRemote(c echo.Context) error {}func (s *Server) setTimeout(c echo.Context) error {- if s.router == nil {- return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)- }-id := c.Param("id")var req types.TimeoutRequest@@ -1531,8 +1561,34 @@ func (s *Server) setTimeout(c echo.Context) error {"error": "timeout must be non-negative (0 disables auto-hibernate)",})}+ want := time.Duration(req.Timeout) * time.Second++ // A managed backend owns its own idle policy, because s.router only tracks+ // sandboxes the QEMU fleet holds — a managed sandbox is not in it, so the+ // call below would silently do nothing and the customer's timeout would+ // never fire.+ if session, err := s.store.GetSandboxSession(c.Request().Context(), id); err == nil && session != nil {+ if t, ok := s.idleTimeouterFor(session.WorkerID); ok {+ effective, err := t.SetIdleTimeout(id, want)+ if err != nil {+ return respondManagerErr(c, err)+ }+ // Reported rather than assumed: a runtime whose provider destroys+ // hosts on its own schedule cannot honour a timeout longer than the+ // host has left, so the answer may not be what was asked for. The+ // sandbox's end_at carries when it actually dies.+ return c.JSON(http.StatusOK, map[string]interface{}{+ "timeout": int(effective.Seconds()),+ "requested": req.Timeout,+ "applied": effective == want,+ })+ }+ }- s.router.SetTimeout(id, time.Duration(req.Timeout)*time.Second)+ if s.router == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ s.router.SetTimeout(id, want)return c.NoContent(http.StatusNoContent)}@@ -1649,6 +1705,13 @@ func (s *Server) effectiveBillingProvider(c echo.Context, orgID uuid.UUID) strinfunc (s *Server) setLimits(c echo.Context) error {id := c.Param("id")++ // Sizing is a property of the image on the managed runtimes, so this is a+ // 501 rather than a failed worker dispatch. Answering it here is what makes+ // the difference visible to a caller instead of looking like an outage.+ if _, ok := s.execManagerFor(id); ok {+ return respondManagerErr(c, fmt.Errorf("set resource limits: %w", awsvm.ErrUnsupported))+ }ctx := c.Request().Context()var req struct {@@ -1757,6 +1820,27 @@ func (s *Server) scaleSandbox(c echo.Context) error {cpuMaxUsec := int64(cpuPercent) * 1000cpuPeriodUsec := int64(100000)+ // Ask the runtime that owns the sandbox BEFORE anything is written.+ //+ // Placed here rather than next to the worker dispatch below for two+ // reasons. It has to be before the autoscale-disable, or a scale that the+ // runtime cannot perform still turns the customer's autoscaling off — a+ // side effect from a request that then fails. And it has to be before the+ // registry branch, because a managed cell still HAS a worker registry (it+ // answers worker_id lookups) with no workers in it, so falling through+ // answers "no gRPC connection to worker vmhost:..." for a runtime whose+ // real answer is "sizing is a property of the image and cannot change".+ if mgr, ok := s.execManagerFor(id); ok {+ if err := mgr.SetResourceLimits(c.Request().Context(), id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {+ return respondManagerErr(c, err)+ }+ return c.JSON(http.StatusOK, map[string]interface{}{+ "sandboxID": id,+ "memoryMB": req.MemoryMB,+ "cpuPercent": cpuPercent,+ })+ }+// Manual scale disables autoscale. Rationale: a user explicitly setting a// size has signalled they want predictability — letting the autoscaler// override would surprise them. They can re-enable via PUT /autoscale.@@ -2582,6 +2666,19 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.Wfunc (s *Server) rebootSandbox(c echo.Context) error {id := c.Param("id")+ // A backend that holds this sandbox serves the reboot itself. Checked+ // BEFORE the registry branch: a managed sandbox has no registered worker,+ // so the remote path below can only answer "no gRPC connection to worker+ // vmhost:…" — which is what it did, for a runtime whose manager implements+ // RebootSandbox perfectly well. Found on dev; the manager code was correct+ // and simply unreachable.+ if mgr, ok := s.execManagerFor(id); ok {+ if err := mgr.RebootSandbox(c.Request().Context(), id); err != nil {+ return respondManagerErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+ }+if s.workerRegistry != nil {return s.rebootSandboxRemote(c, id)}@@ -2626,6 +2723,14 @@ func (s *Server) rebootSandboxRemote(c echo.Context, sandboxID string) error {func (s *Server) powerCycleSandbox(c echo.Context) error {id := c.Param("id")+ // Backend first, for the same reason as rebootSandbox above.+ if mgr, ok := s.execManagerFor(id); ok {+ if _, err := mgr.PowerCycleSandbox(c.Request().Context(), id); err != nil {+ return respondManagerErr(c, err)+ }+ return c.NoContent(http.StatusNoContent)+ }+if s.workerRegistry != nil {return s.powerCycleSandboxRemote(c, id)}@@ -2710,9 +2815,24 @@ func (s *Server) createCheckpoint(c echo.Context) error {if req.Name == "" {return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})}+ // Whether the CUSTOMER chose a kind, before any defaulting. The difference+ // decides whether an impossible kind is an error or just the wrong default:+ // asking for "full" is a request to refuse, while asking for "a checkpoint"+ // on a runtime that only makes one sort is a request to satisfy.+ kindWasExplicit := req.Kind != ""+ noMemoryCapture := s.checkpointKindUnsupported(session.WorkerID)+kind := req.Kindif kind == "" {+ // Default follows the runtime. `full` is right for the fleet, but on a+ // runtime that cannot capture RAM it would turn every plain+ // createCheckpoint(name) — the call the SDK makes when the caller says+ // nothing — into a 501, leaving that runtime with no working checkpoint+ // API at all.kind = "full"+ if noMemoryCapture {+ kind = "disk_only"+ }}if kind != "full" && kind != "disk_only" {return c.JSON(http.StatusBadRequest, map[string]string{"error": "kind must be full or disk_only"})@@ -2722,6 +2842,37 @@ func (s *Server) createCheckpoint(c echo.Context) error {}shouldPromoteToFull := shouldPromoteCheckpoint(kind, req.PromoteToFull)+ // A runtime with no memory-state capture can produce neither a full+ // checkpoint nor a promotion of one, because both mean "boot a VM from this+ // and capture its RAM". Refuse here, where there is still a response to+ // carry the reason.+ //+ // Without this the request is accepted, the disk half succeeds, and the+ // promotion is handed to a background goroutine that reaches for a worker+ // this cell does not have — so the customer is told their checkpoint is+ // being promoted and it silently never is. A 501 saying the operation does+ // not exist here is the truthful answer, and the disk-only checkpoint they+ // can have is one flag away.+ if noMemoryCapture {+ // Only an EXPLICIT ask is refused, on both axes. A plain disk_only+ // request defaults to promoteToFull=nil, which shouldPromoteCheckpoint+ // reads as yes; and a plain createCheckpoint(name) sends no kind at all.+ // Refusing either would reject the ordinary checkpoint this runtime+ // makes perfectly well, which is the one customers actually use.+ explicitlyWantsMemory := (kindWasExplicit && kind == "full") ||+ (req.PromoteToFull != nil && *req.PromoteToFull)+ if explicitlyWantsMemory {+ return c.JSON(http.StatusNotImplemented, map[string]string{+ "error": "checkpoints on this sandbox capture the filesystem; live memory state cannot be captured on this runtime",+ })+ }+ // Asked for by default rather than by the customer: take the disk-only+ // checkpoint and skip a promotion that cannot happen, instead of+ // queueing a background job that reaches for a worker this cell has+ // none of and fails out of sight.+ shouldPromoteToFull = false+ }+// Enforce checkpoint limits per kind. Full checkpoints are heavier because// they include memory/CPU state; disk-only checkpoints are cheaper and get// a larger sandbox-local budget.@@ -2798,7 +2949,21 @@ func (s *Server) createCheckpoint(c echo.Context) error {pending := &pendingCreate{ready: make(chan struct{})}s.pendingCreates.Store(sandboxID, pending)- if s.workerRegistry != nil {+ // Who actually takes the checkpoint. A backend holding this sandbox runs it+ // in-process; the worker path cannot, because such a sandbox has no entry in+ // the registry and the dispatch below could only report the worker missing.+ //+ // Everything above this line — the retention sweep, the checkpoint row, the+ // pending-create gate — is identical either way and stays where it is. Only+ // the dispatch differs, and the in-process branch further down was already+ // written for exactly this; it just reached for s.manager, which is nil on a+ // control plane.+ cpManager, cpManaged := s.execManagerFor(sandboxID)+ if !cpManaged {+ cpManager = s.manager+ }++ if s.workerRegistry != nil && !cpManaged {grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)if err != nil {s.pendingCreates.Delete(sandboxID)@@ -2870,7 +3035,7 @@ func (s *Server) createCheckpoint(c echo.Context) error {"kind": kind,})}()- } else if s.manager != nil {+ } else if cpManager != nil {go func() {bgCtx, cancel := context.WithTimeout(context.Background(), 20*time.Minute)defer cancel()@@ -2882,14 +3047,14 @@ func (s *Server) createCheckpoint(c echo.Context) error {type diskOnlyCheckpointer interface {CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (string, string, int64, error)}- diskMgr, ok := s.manager.(diskOnlyCheckpointer)+ diskMgr, ok := cpManager.(diskOnlyCheckpointer)if !ok {err = fmt.Errorf("manager does not support disk-only checkpoints")} else {rootfsKey, workspaceKey, sizeBytes, err = diskMgr.CreateDiskOnlyCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})}} else {- rootfsKey, workspaceKey, sizeBytes, err = s.manager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})+ rootfsKey, workspaceKey, sizeBytes, err = cpManager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})}// Signal sandbox usable@@ -3124,7 +3289,14 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)}- if s.workerRegistry != nil {+ // Same seam as createCheckpoint: a backend holding this sandbox restores it+ // in-process. Nothing else in this handler changes.+ rsManager, rsManaged := s.execManagerFor(sandboxID)+ if !rsManaged {+ rsManager = s.manager+ }++ if s.workerRegistry != nil && !rsManaged {grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)if err != nil {s.pendingCreates.Delete(sandboxID)@@ -3145,9 +3317,16 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {pending.err = restoreErrclose(pending.ready)}()- } else if s.manager != nil {+ } else if rsManager != nil {go func() {- restoreErr := s.manager.RestoreFromCheckpoint(context.Background(), sandboxID, checkpointID.String())+ // BOUNDED, like the gRPC branch above. pendingCreates gates every+ // subsequent request to this sandbox until ready is closed, so an+ // unbounded restore that wedges does not merely fail — it makes the+ // sandbox unreachable forever, and the caller sees its own connection+ // time out rather than an error anyone can act on.+ bgCtx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)+ defer cancel()+ restoreErr := rsManager.RestoreFromCheckpoint(bgCtx, sandboxID, checkpointID.String())if restoreErr != nil {log.Printf("api: async restore %s/%s failed: %v", sandboxID, checkpointID, restoreErr)}diff --git a/internal/api/signed_urls.go b/internal/api/signed_urls.goindex 10cdc60a..4237abbf 100644--- a/internal/api/signed_urls.go+++ b/internal/api/signed_urls.go@@ -147,6 +147,16 @@ func (s *Server) signedDownload(c echo.Context) error {// Rewrite query params so readFile/proxy picks up the right path.c.QueryParams().Set("path", path)+ // A backend holding this sandbox serves the read in-process. Checked before+ // the proxy branch because a managed sandbox has no registered worker, so+ // the proxy can only refuse it — which meant presigned download did not+ // work on the MicroVM runtime at all. readFile resolves the right manager+ // through managerFor, so it already does the correct thing here; it was+ // simply unreachable.+ if _, ok := s.execManagerFor(sandboxID); ok {+ return s.readFile(c)+ }+if s.sandboxAPIProxy != nil {// Server mode: proxy to worker. Rewrite the request path so the proxy// strips /api and forwards to the worker's /sandboxes/:id/files endpoint.@@ -194,6 +204,11 @@ func (s *Server) signedUpload(c echo.Context) error {// Delegate to the existing file write logic.c.QueryParams().Set("path", path)+ // Backend first, for the same reason as signedDownload above.+ if _, ok := s.execManagerFor(sandboxID); ok {+ return s.writeFile(c)+ }+if s.sandboxAPIProxy != nil {c.Request().URL.Path = fmt.Sprintf("/api/sandboxes/%s/files", sandboxID)return s.sandboxAPIProxy.ProxyHandler(c)diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.goindex d621f707..d25361db 100644--- a/internal/proxy/controlplane_proxy.go+++ b/internal/proxy/controlplane_proxy.go@@ -28,6 +28,11 @@ type ControlPlaneProxy struct {store *db.Storeregistry *controlplane.RedisWorkerRegistrytransport *http.Transport+ // managedPreview resolves how to reach a guest port on a runtime this+ // control plane holds in-process. nil, or a false return, sends the+ // request down the worker path below unchanged — which is every QEMU+ // sandbox. See preview_managed.go.+ managedPreview func(sandboxID string) (ManagedPreview, bool)}// NewControlPlaneProxy creates a proxy for control plane subdomain routing.@@ -125,6 +130,21 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string, port int)}}+ // A managed runtime holds its sandbox in this process and publishes no host+ // port for it — the guest is reached through the runtime's own proxy, over+ // TLS, with the customer's port carried in the path. Nothing below can+ // serve that: the worker lookup would find no registered worker.+ //+ // Placed AFTER the preview-auth gate so a protected preview URL is still+ // protected, and before the hibernation branch because a suspended MicroVM+ // auto-resumes on the inbound request — there is no archive to restore and+ // no worker to pick.+ if p.managedPreview != nil {+ if t, ok := p.managedPreview(sandboxID); ok {+ return p.serveManagedPreview(c, sandboxID, port, t)+ }+ }+// If the sandbox is hibernated, wake it on-demand before proxyingif session.Status == "hibernated" {// Free-tier credits gate: don't auto-wake via preview URL if thediff --git a/internal/proxy/preview_managed.go b/internal/proxy/preview_managed.gonew file mode 100644index 00000000..8b291970--- /dev/null+++ b/internal/proxy/preview_managed.go@@ -0,0 +1,100 @@+package proxy++// preview_managed.go — reaching a customer's own server on a managed runtime.+//+// The fleet path below dials the sandbox's container directly over TCP, because+// on QEMU the host publishes a port for it. A MicroVM has no such port: Lambda's+// proxy forwards guest traffic ONLY to the port declared on the image, so a+// second listener inside the guest is simply unreachable from outside (verified+// — the agent listens on 8081 and requests to it return 502 while the identical+// request to 8080 arrives).+//+// So the fan-out happens inside the guest. Everything enters on the hook port+// and cmd/microvm-hooks proxies /oc/port/<port>/... to 127.0.0.1:<port>. From+// out here that means three differences from the fleet path, and they are why+// this is a separate branch rather than a flag on doProxy:+//+// TLS, not raw TCP the box is reached over HTTPS+// two headers the proxy authenticates on them and routes on them+// a path prefix the port is in the path, not the address+//+// Retrofitting doProxy to do all three conditionally would put branches on the+// path every existing customer's preview URL takes, to serve a runtime none of+// them are on.++import (+ "log"+ "net/http"+ "net/http/httputil"+ "net/url"+ "strconv"+ "strings"++ "github.com/labstack/echo/v4"+)++// ManagedPreview is how to reach a guest port on a runtime the control plane+// holds in-process.+type ManagedPreview struct {+ // Host is the box's HTTPS host, without a scheme.+ Host string+ // Token authenticates to the runtime's proxy.+ Token string+ // HookPort is the port the runtime's proxy will forward to — the guest's+ // front door, NOT the customer's port. The customer's port travels in the+ // path.+ HookPort int32+}++// SetManagedPreview installs a resolver for sandboxes served by a managed+// backend. Returning false sends the request down the fleet path unchanged,+// which is what every QEMU sandbox does.+func (p *ControlPlaneProxy) SetManagedPreview(fn func(sandboxID string) (ManagedPreview, bool)) {+ p.managedPreview = fn+}++// serveManagedPreview forwards a preview request to a guest port through the+// runtime's proxy.+//+// WebSocket and SSE both survive: ReverseProxy forwards an Upgrade and answers+// a 101 by splicing the connection, and FlushInterval -1 stops an event stream+// being buffered into silence. The runtime's own proxy passes both through —+// that was measured before any of this was built, with an echo endpoint over a+// WebSocket through the same hop.+func (p *ControlPlaneProxy) serveManagedPreview(c echo.Context, sandboxID string, port int, t ManagedPreview) error {+ req := c.Request()+ // The customer's path, which becomes the tail of the guest's port route.+ tail := strings.TrimPrefix(req.URL.Path, "/")++ target := &url.URL{Scheme: "https", Host: t.Host}+ rp := &httputil.ReverseProxy{+ Rewrite: func(pr *httputil.ProxyRequest) {+ pr.Out.URL.Scheme = target.Scheme+ pr.Out.URL.Host = target.Host+ pr.Out.URL.Path = "/oc/port/" + strconv.Itoa(port) + "/" + tail+ pr.Out.URL.RawQuery = req.URL.RawQuery+ // Host must be the BOX, not the preview hostname: the runtime's+ // proxy routes on it, and sending the customer's vanity host would+ // not resolve to anything.+ pr.Out.Host = target.Host+ pr.Out.Header.Set("X-aws-proxy-auth", t.Token)+ pr.Out.Header.Set("X-aws-proxy-port", strconv.FormatInt(int64(t.HookPort), 10))+ // Forwarded headers so the customer's server sees the real client+ // rather than the control plane.+ pr.SetXForwarded()+ pr.Out.Header.Set("X-Forwarded-Host", req.Host)+ pr.Out.Header.Set("X-Forwarded-Proto", "https")+ },+ FlushInterval: -1,+ ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {+ // Almost always the customer's server not being up yet, which is a+ // normal state and must read as such rather than as a broken+ // sandbox — serveUpstreamUnavailable is the same page the fleet+ // path shows for it.+ log.Printf("proxy: managed preview %s port %d: %v", sandboxID, port, err)+ _ = serveUpstreamUnavailable(c, sandboxID, port)+ },+ }+ rp.ServeHTTP(c.Response(), req)+ return nil+}diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.goindex c1eb0494..ab54e298 100644--- a/internal/proxy/sandbox_api_proxy.go+++ b/internal/proxy/sandbox_api_proxy.go@@ -89,9 +89,13 @@ type SandboxAPIProxy struct {store *db.Storeregistry *controlplane.RedisWorkerRegistryjwtIssuer *auth.JWTIssuer- transport *http.Transport // shared connection pool for all proxy requests- routeCache *proxyRouteCache // sandbox→worker cache to avoid DB lookup per request+ transport *http.Transport // shared connection pool for all proxy requests+ routeCache *proxyRouteCache // sandbox→worker cache to avoid DB lookup per requestwaitForReady func(ctx context.Context, sandboxID string) error // blocks until async sandbox creation completes; nil = no-op+ // managedWorkerID reports whether a persisted worker_id belongs to a backend+ // the control plane serves in-process rather than to a registered worker.+ // nil on a cell with no such backend, where every worker_id is a real worker.+ managedWorkerID func(workerID string) bool}// NewSandboxAPIProxy creates a new sandbox API proxy.@@ -124,6 +128,19 @@ func (p *SandboxAPIProxy) SetWaitForReady(fn func(ctx context.Context, sandboxIDp.waitForReady = fn}+// SetManagedWorkerID tells the proxy which worker_ids name a managed backend+// (MicroVM, and anything else the control plane holds in-process) rather than a+// worker in the registry.+//+// Without it those sandboxes are indistinguishable from a sandbox whose worker+// died: the registry has no entry either way. tryRecoverOrFail reads that as an+// unrecoverable loss and CLOSES THE ROW — so a single request to a route the+// backend does not implement would mark a perfectly healthy sandbox stopped.+// See the check in tryRecoverOrFail.+func (p *SandboxAPIProxy) SetManagedWorkerID(fn func(workerID string) bool) {+ p.managedWorkerID = fn+}+// ResolvedRoute is the output of ResolveWorker: the worker's HTTP base// URL, its registered worker ID, and a fresh short-TTL sandbox JWT to// hand the worker on this request. Used by callers that need to do@@ -494,7 +511,7 @@ func (p *SandboxAPIProxy) doHTTP(c echo.Context, sandboxID, workerURL, token str}proxy := httputil.NewSingleHostReverseProxy(target)- proxy.FlushInterval = -1 // flush chunks immediately+ proxy.FlushInterval = -1 // flush chunks immediatelyproxy.Transport = p.transport // shared connection pool — avoids ephemeral port exhaustionproxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {@@ -633,6 +650,22 @@ func (p *SandboxAPIProxy) tryRecoverOrFail(c echo.Context, ctx context.Context,})}+ // A managed backend holds this sandbox in the control plane's own process,+ // so "not in the worker registry" is its normal state, not a lost worker.+ // Everything below assumes the opposite and would close the row.+ //+ // This is the LAST line of defence rather than the only one: the routes that+ // reach here are the ones a managed backend does not implement (PTY, agent+ // sessions, mounts), and the router refuses those in front of the proxy. The+ // check stays because the failure it prevents is silent and permanent — a+ // route added later, or a request arriving before Reconcile has rebuilt the+ // in-memory binding, would otherwise destroy a running sandbox.+ if p.managedWorkerID != nil && p.managedWorkerID(session.WorkerID) {+ return c.JSON(http.StatusNotImplemented, map[string]string{+ "error": fmt.Sprintf("sandbox %s runs on a runtime that does not support this operation", sandboxID),+ })+ }+checkpoint, err := p.store.GetActiveHibernation(ctx, sandboxID)if err == nil && checkpoint != nil {log.Printf("sandbox-api-proxy: sandbox %s has active hibernation, attempting recovery wake", sandboxID)