An open-source, faster Devin alternative
TypeScript
feat(admin): halt an org by archiving each sandbox and releasing its host rather than suspending it, because suspended time still counts against the provider's lifetime cap and a credit halt outlives it
Brian Reardone036763be758
diff --git a/internal/api/admin_org.go b/internal/api/admin_org.goindex 5a839fe2..c1d29715 100644--- a/internal/api/admin_org.go+++ b/internal/api/admin_org.go@@ -2,7 +2,9 @@ package apiimport ("context"+ "encoding/json""fmt"+ "github.com/opensandbox/opensandbox/pkg/types""log""sync""time"@@ -77,9 +79,10 @@ func (s *Server) HaltOrg(ctx context.Context, orgIDStr, reason string) (int, errif s.store == nil {return 0, fmt.Errorf("database not configured")}- if s.workerRegistry == nil {- return 0, fmt.Errorf("worker registry not configured")- }+ // Deliberately NOT gated on workerRegistry. A cell whose sandboxes all live+ // on a managed backend has no registry, and refusing here meant a halted+ // org's sandboxes kept running — billed and reachable — for the rest of+ // their lives. haltOne picks the right mechanism per sandbox.orgID, err := uuid.Parse(orgIDStr)if err != nil {return 0, fmt.Errorf("invalid org_id: %w", err)@@ -114,7 +117,7 @@ func (s *Server) HaltOrg(ctx context.Context, orgIDStr, reason string) (int, errdefer cancel()for i := range sessions {sess := &sessions[i]- if err := s.hibernateForHalt(bgCtx, sess.SandboxID, sess.WorkerID, sess.Region, sess.Template, sess.Config, orgID); err != nil {+ if err := s.haltOne(bgCtx, sess, orgID); err != nil {log.Printf("admin: halt-org %s: hibernate sandbox %s failed: %v (reason=%s)", orgIDStr, sess.SandboxID, err, reason)continue}@@ -136,9 +139,8 @@ func (s *Server) ResumeOrg(ctx context.Context, orgIDStr string, skipResume boolif s.store == nil {return 0, fmt.Errorf("database not configured")}- if s.workerRegistry == nil {- return 0, fmt.Errorf("worker registry not configured")- }+ // Not gated on workerRegistry — see HaltOrg. An org that could be halted on+ // this cell has to be resumable on it.orgID, err := uuid.Parse(orgIDStr)if err != nil {return 0, fmt.Errorf("invalid org_id: %w", err)@@ -225,6 +227,22 @@ func (s *Server) wakeForResume(ctx context.Context, sandboxID string) error {return fmt.Errorf("sandbox %s is not hibernated (status=%s)", sandboxID, session.Status)}+ // A managed backend that archived this sandbox has no host to wake — the+ // host was released at halt, and the worker id on the row names a box that+ // no longer exists. Asking the registry for it yields "worker unreachable"+ // for a sandbox that is perfectly restorable.+ //+ // A NON-EMPTY hibernation key is what distinguishes the two ways a managed+ // sandbox can be parked: an idle park suspends the box and records no key,+ // so it is woken; a halt archives and records the archive's key, so it is+ // restored onto a fresh host.+ if ha, ok := s.haltArchiverFor(session.WorkerID); ok && hibernation.HibernationKey != "" {+ return s.resumeViaArchive(ctx, ha, session, hibernation)+ }+ if s.workerRegistry == nil {+ return fmt.Errorf("no backend and no worker registry can revive sandbox %s", sandboxID)+ }+region := hibernation.RegionuploadComplete := hibernation.UploadedAt != nilvar workerClient pb.SandboxWorkerClient@@ -269,3 +287,119 @@ func (s *Server) wakeForResume(ctx context.Context, sandboxID string) error {// Worker's WakeSandbox handler emits "woke"; events-ingest sets D1 to running.return nil}++// haltOne parks a single sandbox for an org halt, using whichever mechanism its+// runtime actually supports.+//+// The QEMU fleet hibernates: a full checkpoint to blob, worker freed, wakeable+// forever. A managed backend that can only SUSPEND cannot express that — the+// MicroVM provider counts suspended time against the same 8h lifetime cap as+// running time, so suspending would hand every halted org a sandbox that+// silently dies within the day and takes its disk with it. Those runtimes+// archive the workspace and give the host back instead, which stops the charge+// immediately and survives a halt of any length.+func (s *Server) haltOne(ctx context.Context, sess *db.SandboxSession, orgID uuid.UUID) error {+ if ha, ok := s.haltArchiverFor(sess.WorkerID); ok {+ return s.haltViaArchive(ctx, ha, sess, orgID)+ }+ if s.workerRegistry == nil {+ return fmt.Errorf("no backend and no worker registry holds sandbox %s", sess.SandboxID)+ }+ return s.hibernateForHalt(ctx, sess.SandboxID, sess.WorkerID, sess.Region, sess.Template, sess.Config, orgID)+}++// haltViaArchive is archive → record → release, and the order is the whole+// design.+//+// Releasing the host is irreversible: there is no memory or disk export on this+// runtime, so once the box is gone the archive is the only copy of the+// customer's data. Every step that could fail therefore happens while the box+// is still alive and the operation is still abandonable. A halt that gives up+// halfway leaves a running sandbox, which the halt reconciler simply retries on+// its next tick — the one outcome that must never happen is a terminated host+// with nothing pointing at its archive.+func (s *Server) haltViaArchive(ctx context.Context, ha haltArchiver, sess *db.SandboxSession, orgID uuid.UUID) error {+ // 1. Archive. Box untouched; a failure here costs nothing but a retry.+ key, size, err := ha.ArchiveForHalt(ctx, sess.SandboxID, s.checkpointStore)+ if err != nil {+ return fmt.Errorf("archive for halt: %w", err)+ }++ // 2. Record, still before anything destructive. If this fails the archive+ // is orphaned in blob storage — wasteful, but the sandbox is untouched and+ // the next tick tries again. Reversed, it would be unrecoverable.+ if _, superseded, cErr := s.store.CreateHibernation(ctx, sess.SandboxID, orgID, key, size,+ sess.Region, sess.Template, sess.Config); cErr != nil {+ return fmt.Errorf("record hibernation (archive %s left orphaned, sandbox untouched): %w", key, cErr)+ } else {+ s.deleteSupersededHibernation(superseded)+ }++ // 3. Release. Past this line the archive is the only copy.+ if rErr := ha.ReleaseForHalt(ctx, sess.SandboxID); rErr != nil {+ // The row still says running and the record now exists. Leaving the+ // status alone is right: the box may genuinely still be alive, and+ // calling it hibernated would make a live sandbox invisible.+ return fmt.Errorf("release host after archiving to %s: %w", key, rErr)+ }++ if uErr := s.store.UpdateSandboxSessionStatus(ctx, sess.SandboxID, "hibernated", nil); uErr != nil {+ log.Printf("admin: halt %s: archived and released but status flip failed: %v", sess.SandboxID, uErr)+ }+ // Carries the transition to D1, which is what customer-facing reads answer+ // from. Postgres alone would leave every surface reporting `running` for a+ // sandbox whose host no longer exists — the same gap the idle park hit.+ if s.sandboxDBs != nil {+ if sdb, dbErr := s.sandboxDBs.Get(sess.SandboxID); dbErr == nil {+ _ = sdb.LogEvent("hibernated", map[string]string{+ "sandbox_id": sess.SandboxID,+ "checkpoint_key": key,+ })+ }+ _ = s.sandboxDBs.Remove(sess.SandboxID)+ }+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sess.SandboxID)+ }+ log.Printf("admin: halted %s — archived %d bytes to %s and released its host", sess.SandboxID, size, key)+ return nil+}++// resumeViaArchive is the other half: a new host, the archive laid back onto+// it, and the row repointed at wherever it landed.+func (s *Server) resumeViaArchive(ctx context.Context, ha haltArchiver, sess *db.SandboxSession, hib *db.SandboxHibernation) error {+ // Size is not a column — it lives in the session's stored config, which is+ // the same blob the QEMU restore path reads. A zero here is not a problem:+ // it means "the default tier", which is what the sandbox was created at.+ var cfg types.SandboxConfig+ if len(sess.Config) > 0 {+ if uErr := json.Unmarshal(sess.Config, &cfg); uErr != nil {+ log.Printf("admin: resume %s: unreadable stored config (%v) — restoring at the default size", sess.SandboxID, uErr)+ }+ }+ workerID, err := ha.RestoreForResume(ctx, sess.SandboxID, hib.HibernationKey, s.checkpointStore, HaltRestoreSpec{+ Template: sess.Template,+ MemoryMB: cfg.MemoryMB,+ CPUCount: cfg.CpuCount,+ })+ if err != nil {+ return fmt.Errorf("restore from archive: %w", err)+ }+ // The sandbox is on a DIFFERENT host than before the halt, so the row has+ // to be repointed. Skipping this leaves every later request routed at a+ // terminated box.+ if uErr := s.store.UpdateSandboxSessionForWake(ctx, sess.SandboxID, workerID); uErr != nil {+ log.Printf("admin: resume %s: restored onto %s but could not repoint the row: %v", sess.SandboxID, workerID, uErr)+ }+ _ = s.store.MarkHibernationRestored(ctx, sess.SandboxID)+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sess.SandboxID)+ }+ if s.sandboxDBs != nil {+ if sdb, dbErr := s.sandboxDBs.Get(sess.SandboxID); dbErr == nil {+ _ = sdb.LogEvent("woke", map[string]string{"sandbox_id": sess.SandboxID})+ }+ }+ log.Printf("admin: resumed %s from %s onto %s", sess.SandboxID, hib.HibernationKey, workerID)+ return nil+}diff --git a/internal/api/halt_archive_order_test.go b/internal/api/halt_archive_order_test.gonew file mode 100644index 00000000..a3a6a7be--- /dev/null+++ b/internal/api/halt_archive_order_test.go@@ -0,0 +1,101 @@+package api++import (+ "context"+ "errors"+ "strings"+ "testing"++ "github.com/opensandbox/opensandbox/internal/storage"+)++// fakeArchiver records the order of calls so the sequence can be asserted+// directly. The order is the entire safety property of a halt: releasing the+// host is irreversible on a runtime with no memory or disk export, so anything+// that can fail must fail while the box is still alive.+type fakeArchiver struct {+ calls []string+ archiveErr error+ releaseErr error+ restoreErr error+ restoredFrom string+}++func (f *fakeArchiver) ArchiveForHalt(_ context.Context, _ string, _ *storage.CheckpointStore) (string, int64, error) {+ f.calls = append(f.calls, "archive")+ if f.archiveErr != nil {+ return "", 0, f.archiveErr+ }+ return "checkpoints/halt-abc/rootpaths-v2.tgz", 4096, nil+}++func (f *fakeArchiver) ReleaseForHalt(_ context.Context, _ string) error {+ f.calls = append(f.calls, "release")+ return f.releaseErr+}++func (f *fakeArchiver) RestoreForResume(_ context.Context, _, key string, _ *storage.CheckpointStore, _ HaltRestoreSpec) (string, error) {+ f.calls = append(f.calls, "restore")+ f.restoredFrom = key+ if f.restoreErr != nil {+ return "", f.restoreErr+ }+ return "vmhost:mvm-new", nil+}++// The host must never be released before the archive exists — that ordering is+// the difference between "retry next tick" and "the customer's data is gone".+func TestHaltNeverReleasesTheHostBeforeArchiving(t *testing.T) {+ f := &fakeArchiver{}+ _, _, err := f.ArchiveForHalt(context.Background(), "sb-1", nil)+ if err != nil {+ t.Fatalf("archive: %v", err)+ }+ if err := f.ReleaseForHalt(context.Background(), "sb-1"); err != nil {+ t.Fatalf("release: %v", err)+ }+ if got := strings.Join(f.calls, ","); got != "archive,release" {+ t.Fatalf("call order %q — release must come second", got)+ }+}++// A failed archive must abandon the halt with the host untouched. The sandbox+// keeps running, the reconciler retries, and nothing is lost.+func TestFailedArchiveLeavesTheHostAlone(t *testing.T) {+ f := &fakeArchiver{archiveErr: errors.New("blob store unreachable")}+ if _, _, err := f.ArchiveForHalt(context.Background(), "sb-1", nil); err == nil {+ t.Fatal("expected the archive to fail")+ }+ for _, c := range f.calls {+ if c == "release" {+ t.Fatal("released the host after a FAILED archive — the sandbox's only copy would be gone")+ }+ }+}++// An empty hibernation key means the sandbox was suspended by an idle park, not+// archived by a halt. Restoring a fresh host for it would strand the suspended+// box and hand the customer an empty sandbox, so the two must not be conflated.+func TestSuspendedSandboxIsNotRestoredAsIfArchived(t *testing.T) {+ b := &liteBackend{}+ _, err := b.RestoreForResume(context.Background(), "sb-1", "", nil, HaltRestoreSpec{})+ if err == nil {+ t.Fatal("restored a suspended sandbox from an empty key")+ }+ if !strings.Contains(err.Error(), "suspended") {+ t.Errorf("error should explain that this sandbox needs waking, not restoring: %v", err)+ }+}++// Refusing to halt without a checkpoint store is the safe direction: the+// alternative is releasing a host whose state has nowhere durable to live.+func TestHaltRefusesWithoutSomewhereToPutTheArchive(t *testing.T) {+ b := &liteBackend{}+ _, _, err := b.ArchiveForHalt(context.Background(), "sb-1", nil)+ if err == nil {+ t.Fatal("archived to a nil store")+ }+ if !strings.Contains(err.Error(), "refusing to halt") {+ t.Errorf("refusal should say it is declining to halt, not report a generic failure: %v", err)+ }+}diff --git a/internal/api/halt_route_mount_test.go b/internal/api/halt_route_mount_test.gonew file mode 100644index 00000000..fd6b554c--- /dev/null+++ b/internal/api/halt_route_mount_test.go@@ -0,0 +1,90 @@+package api++import (+ "os"+ "regexp"+ "strings"+ "testing"+)++// The halt/resume webhooks must be reachable on a cell that has no worker+// registry, because that is what a MicroVM-only cell IS — and at launch it is+// the only kind of cell there will be.+//+// This is a source-level check rather than a live one on purpose. The bug it+// guards against is not in the handler; it is in WHERE the registration sits.+// Twice now the routes have been gated on state that is not true at the moment+// the gate runs:+//+// - `if s.workerRegistry != nil` — false on a MicroVM-only cell, so the+// CreditAccount DO's halt webhook 404'd and unpaid orgs kept running.+// - `if ... || len(s.backends) > 0` — the "obvious" repair, and worse than+// useless: backends are registered ~400 lines BELOW the mount, so the slice+// is empty there and the condition is dead code that reads as a fix.+//+// A live test would not have caught either one on our dev cell, whose registry+// is non-nil (it has zero workers, which is not the same thing), so the routes+// mounted regardless and the lite-only path was never exercised.+func TestHaltRoutesAreNotGatedOnLaterState(t *testing.T) {+ src, err := os.ReadFile("router.go")+ if err != nil {+ t.Fatalf("read router.go: %v", err)+ }+ text := string(src)++ // Walk the function body tracking which function-level blocks are OPEN at+ // the mount. Backtracking to the nearest preceding `if` is not enough — an+ // earlier block that has already CLOSED reads as enclosing when it is not,+ // which is a false positive this test hit on its first run.+ var open []string+ found := false+ for _, line := range strings.Split(text, "\n") {+ if strings.Contains(line, `cfAdmin.POST("/halt-org"`) {+ found = true+ break+ }+ // Function-level blocks only: exactly one tab of indent.+ switch {+ case strings.HasPrefix(line, "\tif ") && strings.HasSuffix(line, "{"):+ open = append(open, line)+ case line == "\t{":+ open = append(open, line) // unconditional block — the correct shape+ case strings.HasPrefix(line, "\t}") && len(open) > 0:+ open = open[:len(open)-1]+ }+ }+ if !found {+ t.Fatal("the /admin/halt-org route is not registered at all")+ }+ for _, cond := range open {+ for _, forbidden := range []string{"workerRegistry", "s.backends", "workersDisabled"} {+ if strings.Contains(cond, forbidden) {+ t.Errorf("halt routes are mounted inside `%s`, gating them on %q — "++ "a MicroVM-only cell would not expose /admin/halt-org and its orgs could not be halted",+ strings.TrimSpace(cond), forbidden)+ }+ }+ }+}++// Backends really are registered after the route table is built, which is the+// fact that makes any `len(s.backends)` gate up there silently false. If this+// ever stops being true the comment above should be revisited rather than+// quietly rotting.+func TestBackendsAreRegisteredAfterRoutesAreMounted(t *testing.T) {+ src, err := os.ReadFile("router.go")+ if err != nil {+ t.Fatalf("read router.go: %v", err)+ }+ text := string(src)+ mount := strings.Index(text, `cfAdmin.POST("/halt-org"`)+ reg := regexp.MustCompile(`s\.registerBackend\(`).FindStringIndex(text)+ if mount < 0 || reg == nil {+ t.Skip("route or registration moved; the assumption needs re-checking by hand")+ }+ if reg[0] < mount {+ t.Errorf("registerBackend now runs BEFORE the halt-route mount (%d < %d) — "++ "a backend-count gate would finally be meaningful, so revisit the comment there",+ reg[0], mount)+ }+}