An open-source, faster Devin alternative
TypeScript
Add manual checkpoint system for sandboxes
Brian Reardon99a18ed50824
diff --git a/cmd/server/main.go b/cmd/server/main.goindex 3f4f5490..6d7c7b3e 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -157,7 +157,7 @@ func main() {WorkerID: workerID,OnHibernate: func(sandboxID string, result *sandbox.HibernateResult) {log.Printf("opensandbox: sandbox %s auto-hibernated (key=%s, size=%d bytes)",- sandboxID, result.CheckpointKey, result.SizeBytes)+ sandboxID, result.HibernationKey, result.SizeBytes)if opts.Store != nil {_ = opts.Store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "hibernated", nil)}diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex a1bd7736..48c02bc7 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -163,14 +163,14 @@ func main() {continue}if r.HasSnapshot {- // Full snapshot on NVMe — create checkpoint record so doWake finds local files- _, _ = store.CreateCheckpoint(ctx, r.SandboxID, session.OrgID,+ // Full snapshot on NVMe — create hibernation record so doWake finds local files+ _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,"local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)_ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)snapshotCount++} else {- // Workspace only — create local sentinel checkpoint for cold boot- _, _ = store.CreateCheckpoint(ctx, r.SandboxID, session.OrgID,+ // Workspace only — create local sentinel hibernation for cold boot+ _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,"local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)_ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)workspaceCount++@@ -199,13 +199,13 @@ func main() {WorkerID: cfg.WorkerID,OnHibernate: func(sandboxID string, result *sandbox.HibernateResult) {log.Printf("opensandbox-worker: sandbox %s auto-hibernated (key=%s, size=%d bytes)",- sandboxID, result.CheckpointKey, result.SizeBytes)+ sandboxID, result.HibernationKey, result.SizeBytes)if store != nil {- // Create checkpoint record so wake-on-request can find it+ // Create hibernation record so wake-on-request can find itsession, err := store.GetSandboxSession(context.Background(), sandboxID)if err == nil {- _, _ = store.CreateCheckpoint(context.Background(), sandboxID, session.OrgID,- result.CheckpointKey, result.SizeBytes, session.Region, session.Template, session.Config)+ _, _ = store.CreateHibernation(context.Background(), sandboxID, session.OrgID,+ result.HibernationKey, result.SizeBytes, session.Region, session.Template, session.Config)}_ = store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "hibernated", nil)}@@ -346,12 +346,12 @@ func main() {}continue}- log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.CheckpointKey)+ log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)if store != nil {session, err := store.GetSandboxSession(context.Background(), r.SandboxID)if err == nil {- _, _ = store.CreateCheckpoint(context.Background(), r.SandboxID, session.OrgID,- r.CheckpointKey, 0, session.Region, session.Template, session.Config)+ _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,+ r.HibernationKey, 0, session.Region, session.Template, session.Config)_ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)}}diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex 343a9078..7638ee3e 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -708,14 +708,14 @@ func (s *Server) dashboardGetSession(c echo.Context) error {}}- // If hibernated, include checkpoint info+ // If hibernated, include hibernation infoif session.Status == "hibernated" {- checkpoint, err := s.store.GetActiveCheckpoint(c.Request().Context(), sandboxID)+ hibernation, err := s.store.GetActiveHibernation(c.Request().Context(), sandboxID)if err == nil {- resp["checkpoint"] = map[string]interface{}{- "checkpointKey": checkpoint.CheckpointKey,- "sizeBytes": checkpoint.SizeBytes,- "hibernatedAt": checkpoint.HibernatedAt,+ resp["hibernation"] = map[string]interface{}{+ "hibernationKey": hibernation.HibernationKey,+ "sizeBytes": hibernation.SizeBytes,+ "hibernatedAt": hibernation.HibernatedAt,}}}diff --git a/internal/api/router.go b/internal/api/router.goindex 6aa2e8b5..4d6f5951 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -127,6 +127,13 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)api.POST("/sandboxes/:id/wake", s.wakeSandbox)+ // Checkpoints+ api.POST("/sandboxes/:id/checkpoints", s.createCheckpoint)+ api.GET("/sandboxes/:id/checkpoints", s.listCheckpoints)+ api.POST("/sandboxes/:id/checkpoints/:checkpointId/restore", s.restoreCheckpoint)+ api.POST("/sandboxes/from-checkpoint/:checkpointId", s.createFromCheckpoint)+ api.DELETE("/sandboxes/:id/checkpoints/:checkpointId", s.deleteCheckpoint)+// Preview URLs (on-demand port-based)api.POST("/sandboxes/:id/preview", s.createPreviewURL)api.GET("/sandboxes/:id/preview", s.listPreviewURLs)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 8f98203e..ffbec1a7 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -547,7 +547,7 @@ func (s *Server) hibernateSandbox(c echo.Context) error {template = session.Templateregion = session.Region}- _, _ = s.store.CreateCheckpoint(ctx, id, orgID, result.CheckpointKey, result.SizeBytes, region, template, cfg)+ _, _ = s.store.CreateHibernation(ctx, id, orgID, result.HibernationKey, result.SizeBytes, region, template, cfg)_ = s.store.UpdateSandboxSessionStatus(ctx, id, "hibernated", nil)}@@ -556,10 +556,10 @@ func (s *Server) hibernateSandbox(c echo.Context) error {}return c.JSON(http.StatusOK, map[string]interface{}{- "sandboxID": id,- "status": "hibernated",- "checkpointKey": result.CheckpointKey,- "sizeBytes": result.SizeBytes,+ "sandboxID": id,+ "status": "hibernated",+ "hibernationKey": result.HibernationKey,+ "sizeBytes": result.SizeBytes,})}@@ -595,18 +595,18 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error})}- // Record checkpoint in PG+ // Record hibernation in PGorgID, _ := auth.GetOrgID(c)- _, _ = s.store.CreateCheckpoint(c.Request().Context(), sandboxID, orgID,+ _, _ = s.store.CreateHibernation(c.Request().Context(), sandboxID, orgID,grpcResp.CheckpointKey, grpcResp.SizeBytes,session.Region, session.Template, session.Config)_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "hibernated", nil)resp := map[string]interface{}{- "sandboxID": sandboxID,- "status": "hibernated",- "checkpointKey": grpcResp.CheckpointKey,- "sizeBytes": grpcResp.SizeBytes,+ "sandboxID": sandboxID,+ "status": "hibernated",+ "hibernationKey": grpcResp.CheckpointKey,+ "sizeBytes": grpcResp.SizeBytes,}return c.JSON(http.StatusOK, resp)@@ -638,12 +638,12 @@ func (s *Server) wakeSandbox(c echo.Context) error {})}- checkpoint, err := s.store.GetActiveCheckpoint(ctx, id)+ hibernation, err := s.store.GetActiveHibernation(ctx, id)if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": "no active checkpoint found"})+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active hibernation found"})}- sb, err := s.manager.Wake(ctx, id, checkpoint.CheckpointKey, s.checkpointStore, req.Timeout)+ sb, err := s.manager.Wake(ctx, id, hibernation.HibernationKey, s.checkpointStore, req.Timeout)if err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error(),@@ -659,7 +659,7 @@ func (s *Server) wakeSandbox(c echo.Context) error {s.router.Register(id, time.Duration(timeout)*time.Second)}- _ = s.store.MarkCheckpointRestored(ctx, id)+ _ = s.store.MarkHibernationRestored(ctx, id)_ = s.store.UpdateSandboxSessionForWake(ctx, id, s.workerID)// Issue fresh JWT@@ -683,9 +683,9 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W})}- checkpoint, err := s.store.GetActiveCheckpoint(c.Request().Context(), sandboxID)+ hibernation, err := s.store.GetActiveHibernation(c.Request().Context(), sandboxID)if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": "no active checkpoint found"})+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active hibernation found"})}session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)@@ -697,7 +697,7 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W}// Pick ANY worker in the same region- region := checkpoint.Region+ region := hibernation.Regionworker, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)if err != nil {return c.JSON(http.StatusServiceUnavailable, map[string]string{@@ -710,7 +710,7 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.WgrpcResp, err := grpcClient.WakeSandbox(grpcCtx, &pb.WakeSandboxRequest{SandboxId: sandboxID,- CheckpointKey: checkpoint.CheckpointKey,+ CheckpointKey: hibernation.HibernationKey,Timeout: int32(req.Timeout),})if err != nil {@@ -719,8 +719,8 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W})}- // Mark checkpoint as restored, update session- _ = s.store.MarkCheckpointRestored(c.Request().Context(), sandboxID)+ // Mark hibernation as restored, update session+ _ = s.store.MarkHibernationRestored(c.Request().Context(), sandboxID)_ = s.store.UpdateSandboxSessionForWake(c.Request().Context(), sandboxID, worker.ID)// Issue fresh JWT@@ -749,6 +749,428 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.Wreturn c.JSON(http.StatusOK, resp)}+// --- Checkpoint handlers ---++// createCheckpoint creates a named checkpoint of a running sandbox.+func (s *Server) createCheckpoint(c echo.Context) error {+ sandboxID := c.Param("id")+ ctx := c.Request().Context()++ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "database not configured",+ })+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{+ "error": "org context required",+ })+ }++ // Verify sandbox is running and belongs to org+ session, err := s.store.GetSandboxSession(ctx, sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ if session.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "sandbox does not belong to this organization"})+ }+ if session.Status != "running" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox must be running to create a checkpoint"})+ }++ // Parse request body+ var req struct {+ Name string `json:"name"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})+ }+ if req.Name == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})+ }++ // Enforce max 10 checkpoints per sandbox+ count, err := s.store.CountCheckpoints(ctx, sandboxID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to count checkpoints"})+ }+ if count >= 10 {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "maximum 10 checkpoints per sandbox"})+ }++ // Reserve a checkpoint UUID+ checkpointID := uuid.New()++ // Create DB record (status='processing')+ cp := &db.Checkpoint{+ ID: checkpointID,+ SandboxID: sandboxID,+ OrgID: orgID,+ Name: req.Name,+ Status: "processing",+ SandboxConfig: session.Config,+ }+ if err := s.store.CreateCheckpoint(ctx, cp); err != nil {+ if strings.Contains(err.Error(), "duplicate key") || strings.Contains(err.Error(), "unique constraint") {+ return c.JSON(http.StatusConflict, map[string]string{"error": "checkpoint name already exists for this sandbox"})+ }+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create checkpoint: " + err.Error()})+ }++ // Dispatch CreateCheckpoint gRPC to worker (server mode) or call manager directly (combined mode)+ if s.workerRegistry != nil {+ grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker not available: " + err.Error()})+ }++ grpcCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)+ defer cancel()++ grpcResp, err := grpcClient.CreateCheckpoint(grpcCtx, &pb.CreateCheckpointRequest{+ SandboxId: sandboxID,+ CheckpointId: checkpointID.String(),+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "create checkpoint failed: " + err.Error()})+ }++ // Mark checkpoint ready on the server side — the gRPC call completes after+ // the reflink copy (checkpoint is locally usable), S3 upload is async on the worker.+ _ = s.store.SetCheckpointReady(ctx, checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, 0)+ cp.Status = "ready"+ cp.RootfsS3Key = &grpcResp.RootfsS3Key+ cp.WorkspaceS3Key = &grpcResp.WorkspaceS3Key+ } else if s.manager != nil {+ rootfsKey, workspaceKey, err := s.manager.CreateCheckpoint(ctx, sandboxID, checkpointID.String(), s.checkpointStore, func() {+ // Async callback when S3 upload completes (no-op here; we mark ready below)+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "create checkpoint failed: " + err.Error()})+ }+ _ = s.store.SetCheckpointReady(ctx, checkpointID, rootfsKey, workspaceKey, 0)+ cp.Status = "ready"+ cp.RootfsS3Key = &rootfsKey+ cp.WorkspaceS3Key = &workspaceKey+ } else {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ return c.JSON(http.StatusCreated, cp)+}++// listCheckpoints returns all checkpoints for a sandbox.+func (s *Server) listCheckpoints(c echo.Context) error {+ sandboxID := c.Param("id")++ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ // Verify sandbox belongs to org+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ if session.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "sandbox does not belong to this organization"})+ }++ checkpoints, err := s.store.ListCheckpoints(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ return c.JSON(http.StatusOK, checkpoints)+}++// restoreCheckpoint restores a sandbox to a checkpoint (in-place revert).+func (s *Server) restoreCheckpoint(c echo.Context) error {+ sandboxID := c.Param("id")+ checkpointIDStr := c.Param("checkpointId")+ ctx := c.Request().Context()++ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ checkpointID, err := uuid.Parse(checkpointIDStr)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})+ }++ // Verify sandbox belongs to org and is running+ session, err := s.store.GetSandboxSession(ctx, sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ if session.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "sandbox does not belong to this organization"})+ }+ if session.Status != "running" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox must be running to restore a checkpoint"})+ }++ // Verify checkpoint exists, belongs to this sandbox, and is ready+ cp, err := s.store.GetCheckpoint(ctx, checkpointID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "checkpoint not found"})+ }+ if cp.SandboxID != sandboxID {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint does not belong to this sandbox"})+ }+ if cp.Status != "ready" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint is not ready (status: " + cp.Status + ")"})+ }++ // Dispatch RestoreCheckpoint gRPC to worker or call manager directly+ if s.workerRegistry != nil {+ grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker not available: " + err.Error()})+ }++ grpcCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)+ defer cancel()++ _, err = grpcClient.RestoreCheckpoint(grpcCtx, &pb.RestoreCheckpointRequest{+ SandboxId: sandboxID,+ CheckpointId: checkpointID.String(),+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "restore checkpoint failed: " + err.Error()})+ }+ } else if s.manager != nil {+ if err := s.manager.RestoreFromCheckpoint(ctx, sandboxID, checkpointID.String()); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "restore checkpoint failed: " + err.Error()})+ }+ } else {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ return c.JSON(http.StatusOK, map[string]string{+ "sandboxId": sandboxID,+ "checkpointId": checkpointID.String(),+ "status": "restored",+ })+}++// createFromCheckpoint creates a new sandbox from an existing checkpoint (fork).+func (s *Server) createFromCheckpoint(c echo.Context) error {+ checkpointIDStr := c.Param("checkpointId")+ ctx := c.Request().Context()++ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ checkpointID, err := uuid.Parse(checkpointIDStr)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})+ }++ // Verify checkpoint exists, belongs to org, and is ready+ cp, err := s.store.GetCheckpoint(ctx, checkpointID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "checkpoint not found"})+ }+ if cp.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "checkpoint does not belong to this organization"})+ }+ if cp.Status != "ready" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint is not ready (status: " + cp.Status + ")"})+ }++ // Parse optional overrides from request body+ var req struct {+ Timeout int `json:"timeout"`+ }+ _ = c.Bind(&req)++ // Get S3 keys from the checkpoint+ if cp.RootfsS3Key == nil || cp.WorkspaceS3Key == nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint S3 keys not available"})+ }++ // Parse the original sandbox config to reuse settings+ var originalCfg types.SandboxConfig+ _ = json.Unmarshal(cp.SandboxConfig, &originalCfg)++ timeout := req.Timeout+ if timeout <= 0 {+ timeout = originalCfg.Timeout+ }+ if timeout <= 0 {+ timeout = 300+ }++ // Create new sandbox using checkpoint drives (same flow as creating from template)+ if s.workerRegistry != nil {+ // Server mode: pick a worker and dispatch via gRPC+ region := s.region+ if region == "" {+ region = "iad"+ }++ worker, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "no workers available: " + err.Error()})+ }++ grpcCtx, cancel := context.WithTimeout(ctx, 120*time.Second)+ defer cancel()++ grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{+ Template: originalCfg.Template,+ Timeout: int32(timeout),+ Envs: originalCfg.Envs,+ MemoryMb: int32(originalCfg.MemoryMB),+ CpuCount: int32(originalCfg.CpuCount),+ NetworkEnabled: originalCfg.NetworkEnabled,+ Port: int32(originalCfg.Port),+ TemplateRootfsKey: *cp.RootfsS3Key,+ TemplateWorkspaceKey: *cp.WorkspaceS3Key,+ })+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "create from checkpoint failed: " + err.Error()})+ }++ // Issue JWT+ var token string+ if s.jwtIssuer != nil {+ t, err := s.jwtIssuer.IssueSandboxToken(orgID, grpcResp.SandboxId, worker.ID, 24*time.Hour)+ if err == nil {+ token = t+ }+ }++ // Record session+ template := originalCfg.Template+ if template == "" {+ template = "default"+ }+ cfgJSON, _ := json.Marshal(originalCfg)+ metadataJSON, _ := json.Marshal(originalCfg.Metadata)+ _, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, nil, template, region, worker.ID, cfgJSON, metadataJSON)++ return c.JSON(http.StatusCreated, map[string]interface{}{+ "sandboxID": grpcResp.SandboxId,+ "connectURL": worker.HTTPAddr,+ "token": token,+ "status": grpcResp.Status,+ "region": region,+ "workerID": worker.ID,+ "fromCheckpointId": checkpointID.String(),+ })+ }++ // Combined mode: create locally using checkpoint drives+ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ cfg := originalCfg+ cfg.Timeout = timeout+ cfg.TemplateRootfsKey = *cp.RootfsS3Key+ cfg.TemplateWorkspaceKey = *cp.WorkspaceS3Key++ sb, err := s.manager.Create(ctx, cfg)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ if s.router != nil {+ s.router.Register(sb.ID, time.Duration(timeout)*time.Second)+ }++ if s.jwtIssuer != nil {+ token, err := s.jwtIssuer.IssueSandboxToken(orgID, sb.ID, s.workerID, 24*time.Hour)+ if err == nil {+ sb.Token = token+ }+ }++ if s.store != nil {+ template := originalCfg.Template+ if template == "" {+ template = "default"+ }+ cfgJSON, _ := json.Marshal(cfg)+ metadataJSON, _ := json.Marshal(cfg.Metadata)+ _, _ = s.store.CreateSandboxSession(ctx, sb.ID, orgID, nil, template, s.region, s.workerID, cfgJSON, metadataJSON)+ }++ return c.JSON(http.StatusCreated, sb)+}++// deleteCheckpoint deletes a checkpoint.+func (s *Server) deleteCheckpoint(c echo.Context) error {+ sandboxID := c.Param("id")+ checkpointIDStr := c.Param("checkpointId")+ ctx := c.Request().Context()++ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ checkpointID, err := uuid.Parse(checkpointIDStr)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid checkpoint ID"})+ }++ // Verify checkpoint exists and belongs to this sandbox and org+ cp, err := s.store.GetCheckpoint(ctx, checkpointID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "checkpoint not found"})+ }+ if cp.SandboxID != sandboxID {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint does not belong to this sandbox"})+ }++ // Delete from DB (enforces org ownership)+ if err := s.store.DeleteCheckpoint(ctx, orgID, checkpointID); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ // Best-effort: delete S3 objects if checkpoint store is configured+ if s.checkpointStore != nil && cp.RootfsS3Key != nil && cp.WorkspaceS3Key != nil {+ go func() {+ bgCtx := context.Background()+ if err := s.checkpointStore.Delete(bgCtx, *cp.RootfsS3Key); err != nil {+ log.Printf("checkpoint: failed to delete S3 rootfs %s: %v", *cp.RootfsS3Key, err)+ }+ if err := s.checkpointStore.Delete(bgCtx, *cp.WorkspaceS3Key); err != nil {+ log.Printf("checkpoint: failed to delete S3 workspace %s: %v", *cp.WorkspaceS3Key, err)+ }+ }()+ }++ return c.NoContent(http.StatusNoContent)+}+// listSessions returns session history from PostgreSQL.func (s *Server) listWorkers(c echo.Context) error {if s.workerRegistry == nil {diff --git a/internal/db/migrations/011_rename_hibernation.down.sql b/internal/db/migrations/011_rename_hibernation.down.sqlnew file mode 100644index 00000000..57c286b0--- /dev/null+++ b/internal/db/migrations/011_rename_hibernation.down.sql@@ -0,0 +1,6 @@+-- Reverse: rename sandbox_hibernations back to sandbox_checkpoints+ALTER TABLE sandbox_hibernations RENAME TO sandbox_checkpoints;+ALTER TABLE sandbox_checkpoints RENAME COLUMN hibernation_key TO checkpoint_key;+ALTER INDEX idx_hibernations_sandbox RENAME TO idx_checkpoints_sandbox;+ALTER INDEX idx_hibernations_org RENAME TO idx_checkpoints_org;+ALTER INDEX idx_hibernations_active RENAME TO idx_checkpoints_active;diff --git a/internal/db/migrations/011_rename_hibernation.up.sql b/internal/db/migrations/011_rename_hibernation.up.sqlnew file mode 100644index 00000000..bf7ba576--- /dev/null+++ b/internal/db/migrations/011_rename_hibernation.up.sql@@ -0,0 +1,6 @@+-- Rename sandbox_checkpoints to sandbox_hibernations (these are hibernate records, not checkpoints)+ALTER TABLE sandbox_checkpoints RENAME TO sandbox_hibernations;+ALTER TABLE sandbox_hibernations RENAME COLUMN checkpoint_key TO hibernation_key;+ALTER INDEX idx_checkpoints_sandbox RENAME TO idx_hibernations_sandbox;+ALTER INDEX idx_checkpoints_org RENAME TO idx_hibernations_org;+ALTER INDEX idx_checkpoints_active RENAME TO idx_hibernations_active;diff --git a/internal/db/migrations/012_checkpoints.down.sql b/internal/db/migrations/012_checkpoints.down.sqlnew file mode 100644index 00000000..cbcdd00f--- /dev/null+++ b/internal/db/migrations/012_checkpoints.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS sandbox_checkpoints;diff --git a/internal/db/migrations/012_checkpoints.up.sql b/internal/db/migrations/012_checkpoints.up.sqlnew file mode 100644index 00000000..39ff8bc2--- /dev/null+++ b/internal/db/migrations/012_checkpoints.up.sql@@ -0,0 +1,16 @@+-- Named checkpoints for manual save/restore within a sandbox+CREATE TABLE sandbox_checkpoints (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ sandbox_id TEXT NOT NULL,+ org_id UUID NOT NULL REFERENCES orgs(id),+ name TEXT NOT NULL,+ rootfs_s3_key TEXT,+ workspace_s3_key TEXT,+ sandbox_config JSONB NOT NULL DEFAULT '{}',+ status TEXT NOT NULL DEFAULT 'processing', -- processing | ready+ size_bytes BIGINT NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX idx_checkpoints_sandbox ON sandbox_checkpoints(sandbox_id);+CREATE UNIQUE INDEX idx_checkpoints_name ON sandbox_checkpoints(sandbox_id, name);diff --git a/internal/db/store.go b/internal/db/store.goindex 314d9cda..858c5827 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -74,6 +74,8 @@ func (s *Store) Migrate(ctx context.Context) error {{8, "migrations/008_default_template.up.sql"},{9, "migrations/009_sandbox_templates.up.sql"},{10, "migrations/010_template_status.up.sql"},+ {11, "migrations/011_rename_hibernation.up.sql"},+ {12, "migrations/012_checkpoints.up.sql"},}for _, m := range migrations {@@ -614,14 +616,14 @@ func (s *Store) Pool() *pgxpool.Pool {return s.pool}-// --- Checkpoint operations ---+// --- Hibernation operations ----// SandboxCheckpoint represents a hibernated sandbox's checkpoint record.-type SandboxCheckpoint struct {+// SandboxHibernation represents a hibernated sandbox's record.+type SandboxHibernation struct {ID uuid.UUID `json:"id"`SandboxID string `json:"sandboxId"`OrgID uuid.UUID `json:"orgId"`- CheckpointKey string `json:"checkpointKey"`+ HibernationKey string `json:"hibernationKey"`SizeBytes int64 `json:"sizeBytes"`Region string `json:"region"`Template string `json:"template"`@@ -631,41 +633,41 @@ type SandboxCheckpoint struct {ExpiredAt *time.Time `json:"expiredAt,omitempty"`}-// CreateCheckpoint inserts a new checkpoint record.-func (s *Store) CreateCheckpoint(ctx context.Context, sandboxID string, orgID uuid.UUID, checkpointKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) (*SandboxCheckpoint, error) {- cp := &SandboxCheckpoint{}+// CreateHibernation inserts a new hibernation record.+func (s *Store) CreateHibernation(ctx context.Context, sandboxID string, orgID uuid.UUID, hibernationKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) (*SandboxHibernation, error) {+ cp := &SandboxHibernation{}err := s.pool.QueryRow(ctx,- `INSERT INTO sandbox_checkpoints (sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config)+ `INSERT INTO sandbox_hibernations (sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config)VALUES ($1, $2, $3, $4, $5, $6, $7)- RETURNING id, sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config, hibernated_at`,- sandboxID, orgID, checkpointKey, sizeBytes, region, template, sandboxConfig,- ).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.CheckpointKey, &cp.SizeBytes,+ RETURNING id, sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config, hibernated_at`,+ sandboxID, orgID, hibernationKey, sizeBytes, region, template, sandboxConfig,+ ).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.HibernationKey, &cp.SizeBytes,&cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt)if err != nil {- return nil, fmt.Errorf("failed to create checkpoint: %w", err)+ return nil, fmt.Errorf("failed to create hibernation: %w", err)}return cp, nil}-// GetActiveCheckpoint returns the active (not restored, not expired) checkpoint for a sandbox.-func (s *Store) GetActiveCheckpoint(ctx context.Context, sandboxID string) (*SandboxCheckpoint, error) {- cp := &SandboxCheckpoint{}+// GetActiveHibernation returns the active (not restored, not expired) hibernation for a sandbox.+func (s *Store) GetActiveHibernation(ctx context.Context, sandboxID string) (*SandboxHibernation, error) {+ cp := &SandboxHibernation{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config, hibernated_at, restored_at, expired_at- FROM sandbox_checkpoints+ `SELECT id, sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config, hibernated_at, restored_at, expired_at+ FROM sandbox_hibernationsWHERE sandbox_id = $1 AND restored_at IS NULL AND expired_at IS NULL`, sandboxID,- ).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.CheckpointKey, &cp.SizeBytes,+ ).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.HibernationKey, &cp.SizeBytes,&cp.Region, &cp.Template, &cp.SandboxConfig, &cp.HibernatedAt, &cp.RestoredAt, &cp.ExpiredAt)if err != nil {- return nil, fmt.Errorf("active checkpoint not found: %w", err)+ return nil, fmt.Errorf("active hibernation not found: %w", err)}return cp, nil}-// MarkCheckpointRestored marks the active checkpoint for a sandbox as restored.-func (s *Store) MarkCheckpointRestored(ctx context.Context, sandboxID string) error {+// MarkHibernationRestored marks the active hibernation for a sandbox as restored.+func (s *Store) MarkHibernationRestored(ctx context.Context, sandboxID string) error {_, err := s.pool.Exec(ctx,- `UPDATE sandbox_checkpoints SET restored_at = now()+ `UPDATE sandbox_hibernations SET restored_at = now()WHERE sandbox_id = $1 AND restored_at IS NULL AND expired_at IS NULL`,sandboxID)return err@@ -685,12 +687,12 @@ func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newW// Sessions without a checkpoint are set to "stopped" (VM is gone, no recovery possible).// Returns the count of sessions transitioned to each state.func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (hibernated, stopped int, err error) {- // First: mark sessions that have an active checkpoint as "hibernated"+ // First: mark sessions that have an active hibernation as "hibernated"res1, err := s.pool.Exec(ctx,`UPDATE sandbox_sessions SET status = 'hibernated'WHERE worker_id = $1 AND status = 'running'AND sandbox_id IN (- SELECT sandbox_id FROM sandbox_checkpoints+ SELECT sandbox_id FROM sandbox_hibernationsWHERE restored_at IS NULL AND expired_at IS NULL)`, workerID)if err != nil {@@ -710,18 +712,18 @@ func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (h}// UpsertWorkspaceBackup creates or updates a workspace-only backup record for a sandbox.-// Uses checkpoint_key prefix "workspace-backups/" to distinguish from full hibernation checkpoints.+// Uses hibernation_key prefix "workspace-backups/" to distinguish from full hibernation records.// Only one workspace backup is kept per sandbox (previous is overwritten).func (s *Store) UpsertWorkspaceBackup(ctx context.Context, sandboxID string, orgID uuid.UUID, backupKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) error {// Expire any existing workspace backups for this sandbox_, _ = s.pool.Exec(ctx,- `UPDATE sandbox_checkpoints SET expired_at = now()- WHERE sandbox_id = $1 AND checkpoint_key LIKE 'workspace-backups/%'+ `UPDATE sandbox_hibernations SET expired_at = now()+ WHERE sandbox_id = $1 AND hibernation_key LIKE 'workspace-backups/%'AND expired_at IS NULL AND restored_at IS NULL`, sandboxID)// Insert the new backup_, err := s.pool.Exec(ctx,- `INSERT INTO sandbox_checkpoints (sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config)+ `INSERT INTO sandbox_hibernations (sandbox_id, org_id, hibernation_key, size_bytes, region, template, sandbox_config)VALUES ($1, $2, $3, $4, $5, $6, $7)`,sandboxID, orgID, backupKey, sizeBytes, region, template, sandboxConfig)if err != nil {@@ -730,6 +732,99 @@ func (s *Store) UpsertWorkspaceBackup(ctx context.Context, sandboxID string, orgreturn nil}+// --- Checkpoint operations ---++// Checkpoint represents a named checkpoint for a sandbox.+type Checkpoint struct {+ ID uuid.UUID `json:"id"`+ SandboxID string `json:"sandboxId"`+ OrgID uuid.UUID `json:"orgId"`+ Name string `json:"name"`+ RootfsS3Key *string `json:"rootfsS3Key,omitempty"`+ WorkspaceS3Key *string `json:"workspaceS3Key,omitempty"`+ SandboxConfig json.RawMessage `json:"sandboxConfig"`+ Status string `json:"status"`+ SizeBytes int64 `json:"sizeBytes"`+ CreatedAt time.Time `json:"createdAt"`+}++// CreateCheckpoint inserts a new checkpoint record.+func (s *Store) CreateCheckpoint(ctx context.Context, cp *Checkpoint) error {+ return s.pool.QueryRow(ctx,+ `INSERT INTO sandbox_checkpoints (id, sandbox_id, org_id, name, sandbox_config)+ VALUES ($1, $2, $3, $4, $5)+ RETURNING created_at`,+ cp.ID, cp.SandboxID, cp.OrgID, cp.Name, cp.SandboxConfig,+ ).Scan(&cp.CreatedAt)+}++// SetCheckpointReady marks a checkpoint as ready after async S3 upload completes.+func (s *Store) SetCheckpointReady(ctx context.Context, checkpointID uuid.UUID, rootfsKey, workspaceKey string, sizeBytes int64) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_checkpoints SET status = 'ready', rootfs_s3_key = $2, workspace_s3_key = $3, size_bytes = $4+ WHERE id = $1`,+ checkpointID, rootfsKey, workspaceKey, sizeBytes)+ return err+}++// GetCheckpoint returns a checkpoint by ID.+func (s *Store) GetCheckpoint(ctx context.Context, checkpointID uuid.UUID) (*Checkpoint, error) {+ cp := &Checkpoint{}+ err := s.pool.QueryRow(ctx,+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, created_at+ FROM sandbox_checkpoints WHERE id = $1`, checkpointID,+ ).Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.CreatedAt)+ if err != nil {+ return nil, fmt.Errorf("checkpoint not found: %w", err)+ }+ return cp, nil+}++// ListCheckpoints returns all checkpoints for a sandbox, newest first.+func (s *Store) ListCheckpoints(ctx context.Context, sandboxID string) ([]Checkpoint, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT id, sandbox_id, org_id, name, rootfs_s3_key, workspace_s3_key, sandbox_config, status, size_bytes, created_at+ FROM sandbox_checkpoints WHERE sandbox_id = $1 ORDER BY created_at DESC`, sandboxID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var checkpoints []Checkpoint+ for rows.Next() {+ var cp Checkpoint+ if err := rows.Scan(&cp.ID, &cp.SandboxID, &cp.OrgID, &cp.Name, &cp.RootfsS3Key, &cp.WorkspaceS3Key,+ &cp.SandboxConfig, &cp.Status, &cp.SizeBytes, &cp.CreatedAt); err != nil {+ return nil, err+ }+ checkpoints = append(checkpoints, cp)+ }+ return checkpoints, rows.Err()+}++// CountCheckpoints returns the number of checkpoints for a sandbox.+func (s *Store) CountCheckpoints(ctx context.Context, sandboxID string) (int, error) {+ var count int+ err := s.pool.QueryRow(ctx,+ `SELECT COUNT(*) FROM sandbox_checkpoints WHERE sandbox_id = $1`, sandboxID).Scan(&count)+ return count, err+}++// DeleteCheckpoint deletes a checkpoint (only if owned by org).+func (s *Store) DeleteCheckpoint(ctx context.Context, orgID uuid.UUID, checkpointID uuid.UUID) error {+ tag, err := s.pool.Exec(ctx,+ `DELETE FROM sandbox_checkpoints WHERE id = $1 AND org_id = $2`,+ checkpointID, orgID)+ if err != nil {+ return err+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("checkpoint not found or not owned by org")+ }+ return nil+}+// --- Template operations ---// DBTemplate represents a template record in the database.diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.goindex fe1aa7c2..67561835 100644--- a/internal/firecracker/manager.go+++ b/internal/firecracker/manager.go@@ -147,6 +147,12 @@ func (m *Manager) allocateCID() uint32 {// Create launches a new Firecracker microVM.func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {id := "sb-" + uuid.New().String()[:8]+ return m.createWithID(ctx, id, cfg)+}++// createWithID is the internal implementation of Create that accepts a specific sandbox ID.+// Used by Create (with a new UUID) and RestoreFromCheckpoint (with the existing ID).+func (m *Manager) createWithID(ctx context.Context, id string, cfg types.SandboxConfig) (*types.Sandbox, error) {sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", id)if err := os.MkdirAll(sandboxDir, 0755); err != nil {@@ -562,9 +568,9 @@ func (m *Manager) WaitUploads(timeout time.Duration) {// HibernateAllResult holds the result of a single VM hibernation during HibernateAll.type HibernateAllResult struct {- SandboxID string- CheckpointKey string- Err error+ SandboxID string+ HibernationKey string+ Err error}// HibernateAll hibernates all running VMs concurrently.@@ -598,7 +604,7 @@ func (m *Manager) HibernateAll(ctx context.Context, checkpointStore *storage.Chelog.Printf("firecracker: HibernateAll: %s failed: %v", sandboxID, err)results = append(results, HibernateAllResult{SandboxID: sandboxID, Err: err})} else {- results = append(results, HibernateAllResult{SandboxID: sandboxID, CheckpointKey: result.CheckpointKey})+ results = append(results, HibernateAllResult{SandboxID: sandboxID, HibernationKey: result.HibernationKey})}}(id)}diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.goindex dce29f89..bd7e2acf 100644--- a/internal/firecracker/snapshot.go+++ b/internal/firecracker/snapshot.go@@ -191,7 +191,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoreturn &sandbox.HibernateResult{SandboxID: sandboxID,- CheckpointKey: checkpointKey,+ HibernationKey: checkpointKey,SizeBytes: 0, // not known yet — archive happens async}, nil}@@ -850,6 +850,215 @@ func (m *Manager) TemplateCachePath(templateID, filename string) string {return ""}+// checkpointCacheDir returns the local cache directory for a checkpoint's ext4 drives.+func (m *Manager) checkpointCacheDir(checkpointID string) string {+ return filepath.Join(m.cfg.DataDir, "checkpoints", checkpointID)+}++// CheckpointCachePath returns the local path to a cached checkpoint drive, or "" if not cached.+func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {+ p := filepath.Join(m.checkpointCacheDir(checkpointID), filename)+ if _, err := os.Stat(p); err == nil {+ return p+ }+ return ""+}++// CreateCheckpoint snapshots a running sandbox's drives (rootfs + workspace) for later restore.+// The VM is briefly paused (~10-50ms) during file copy then resumed. Archive upload is async.+// Returns the pre-computed S3 keys immediately. onReady is called when the async upload finishes.+func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return "", "", err+ }++ t0 := time.Now()++ rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)+ workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.sparse.zst", sandboxID, checkpointID)++ srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.ext4")+ srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.ext4")++ // Cache checkpoint drives locally for fast restore+ cacheDir := m.checkpointCacheDir(checkpointID)+ if err := os.MkdirAll(cacheDir, 0755); err != nil {+ return "", "", fmt.Errorf("create checkpoint cache dir: %w", err)+ }+ cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")+ cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")++ // Step 1: SyncFS (agent stays alive)+ if vm.agent != nil {+ syncCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ if syncErr := vm.agent.SyncFS(syncCtx); syncErr != nil {+ log.Printf("firecracker: CreateCheckpoint %s: SyncFS warning: %v", vm.ID, syncErr)+ }+ cancel()+ }++ // Step 2: Close gRPC connection (vsock must be inactive before pause)+ if vm.agent != nil {+ vm.agent.Close()+ vm.agent = nil+ }++ // Step 3: Pause the VM+ if err = vm.fcClient.PauseVM(); err != nil {+ if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 5*time.Second); reconnErr == nil {+ vm.agent = agent+ }+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("pause VM for checkpoint: %w", err)+ }+ log.Printf("firecracker: CreateCheckpoint %s/%s: VM paused (%dms)", vm.ID, checkpointID, time.Since(t0).Milliseconds())++ // Step 4: Copy drive files while VM is paused (drives are stable)+ copyErr := copyFileReflink(srcRootfs, cachedRootfs)+ if copyErr == nil {+ copyErr = copyFileReflink(srcWorkspace, cachedWorkspace)+ if copyErr != nil {+ os.Remove(cachedRootfs)+ }+ }++ // Step 5: Resume the VM regardless of copy result+ resumeErr := vm.fcClient.ResumeVM()+ if resumeErr != nil {+ log.Printf("firecracker: CreateCheckpoint %s: CRITICAL: resume failed: %v", vm.ID, resumeErr)+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("resume VM after checkpoint: %w", resumeErr)+ }+ log.Printf("firecracker: CreateCheckpoint %s/%s: VM resumed (%dms)", vm.ID, checkpointID, time.Since(t0).Milliseconds())++ if copyErr != nil {+ if agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second); reconnErr == nil {+ vm.agent = agent+ }+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("copy drives for checkpoint: %w", copyErr)+ }++ // Step 6: Reconnect agent+ agent, reconnErr := m.waitForAgent(ctx, vm.vsockPath, 10*time.Second)+ if reconnErr != nil {+ log.Printf("firecracker: CreateCheckpoint %s: agent reconnect failed: %v (VM still running)", vm.ID, reconnErr)+ } else {+ vm.agent = agent+ }++ // Step 7: Async compress + upload to S3+ m.uploadWg.Add(1)+ go func() {+ defer m.uploadWg.Done()++ uploadCtx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)+ defer cancel()++ t1 := time.Now()+ if err := compressAndUploadFile(uploadCtx, cachedRootfs, rootfsKey, checkpointStore); err != nil {+ log.Printf("firecracker: checkpoint %s: rootfs upload failed: %v", checkpointID, err)+ return+ }+ log.Printf("firecracker: checkpoint %s: rootfs uploaded (%dms)", checkpointID, time.Since(t1).Milliseconds())++ t2 := time.Now()+ if err := sparseCompressAndUpload(uploadCtx, cachedWorkspace, workspaceKey, checkpointStore); err != nil {+ log.Printf("firecracker: checkpoint %s: workspace upload failed: %v", checkpointID, err)+ return+ }+ log.Printf("firecracker: checkpoint %s: ready (%dms, total=%dms)", checkpointID, time.Since(t2).Milliseconds(), time.Since(t0).Milliseconds())+ if onReady != nil {+ onReady()+ }+ }()++ return rootfsKey, workspaceKey, nil+}++// RestoreFromCheckpoint reverts a running sandbox to a checkpoint.+// The current VM is killed, drives are replaced with checkpoint copies, and a new VM is cold booted.+// The sandbox ID stays the same.+func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return err+ }++ cacheDir := m.checkpointCacheDir(checkpointID)+ cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")+ cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")++ // Verify checkpoint files exist locally+ if _, err := os.Stat(cachedRootfs); err != nil {+ return fmt.Errorf("checkpoint rootfs not found locally: %w", err)+ }+ if _, err := os.Stat(cachedWorkspace); err != nil {+ return fmt.Errorf("checkpoint workspace not found locally: %w", err)+ }++ // Step 1: SyncFS (best effort — save current state in case needed)+ if vm.agent != nil {+ syncCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ _ = vm.agent.SyncFS(syncCtx)+ cancel()+ vm.agent.Close()+ vm.agent = nil+ }++ // Step 2: Kill the current Firecracker process+ if vm.cmd != nil && vm.cmd.Process != nil {+ _ = vm.cmd.Process.Kill()+ _ = vm.cmd.Wait()+ }++ // Step 2b: Clean up socket files so the new VM can bind+ _ = os.Remove(vm.vsockPath)+ if vm.apiSockPath != "" {+ _ = os.Remove(vm.apiSockPath)+ }++ // Step 3: Save VM config before removing from map+ template := vm.Template+ cpuCount := vm.CpuCount+ memoryMB := vm.MemoryMB+ guestPort := vm.GuestPort++ // Step 4: Clean up network+ if vm.network != nil {+ RemoveDNAT(vm.network)+ DeleteTAP(vm.network.TAPName)+ m.subnets.Release(vm.network.TAPName)+ }++ // Step 5: Remove old VM from tracking+ m.mu.Lock()+ delete(m.vms, sandboxID)+ m.mu.Unlock()++ // Step 6: Cold boot a fresh VM using checkpoint drives+ // Pass checkpoint cache paths as template keys so createWithID copies them+ // instead of creating fresh drives from the base image.+ cfg := types.SandboxConfig{+ Template: template,+ CpuCount: cpuCount,+ MemoryMB: memoryMB,+ Port: guestPort,+ NetworkEnabled: true,+ TemplateRootfsKey: "local://" + cachedRootfs,+ TemplateWorkspaceKey: "local://" + cachedWorkspace,+ }++ sb, err := m.createWithID(ctx, sandboxID, cfg)+ if err != nil {+ return fmt.Errorf("cold boot after checkpoint restore: %w", err)+ }+ log.Printf("firecracker: RestoreFromCheckpoint %s/%s: VM cold booted (status=%s)", sandboxID, checkpointID, sb.Status)++ return nil+}+// copyFileReflink copies a file using cp --reflink=auto (instant on XFS reflink, fallback to full copy).func copyFileReflink(src, dst string) error {cmd := exec.Command("cp", "--reflink=auto", src, dst)diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.goindex 07436ecd..3e4eb32a 100644--- a/internal/proxy/controlplane_proxy.go+++ b/internal/proxy/controlplane_proxy.go@@ -129,10 +129,10 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string, port int)// exists, it wakes the sandbox on a new worker. Otherwise, it marks the session// as stopped and returns a clear error.func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Context, sandboxID string, session *db.SandboxSession, port int) error {- // Check if there's a checkpoint we can wake from- checkpoint, err := p.store.GetActiveCheckpoint(ctx, sandboxID)+ // Check if there's a hibernation we can wake from+ checkpoint, err := p.store.GetActiveHibernation(ctx, sandboxID)if err == nil && checkpoint != nil {- log.Printf("cp-proxy: sandbox %s has active checkpoint, attempting recovery wake", sandboxID)+ log.Printf("cp-proxy: sandbox %s has active hibernation, attempting recovery wake", sandboxID)worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)if err != nil {log.Printf("cp-proxy: recovery wake failed for sandbox %s: %v", sandboxID, err)@@ -147,8 +147,8 @@ func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Contextreturn p.doHTTP(c, sandboxID, workerURL, port)}- // No checkpoint — sandbox is truly gone. Mark session as stopped.- log.Printf("cp-proxy: sandbox %s has no checkpoint and worker is gone, marking stopped", sandboxID)+ // No hibernation — sandbox is truly gone. Mark session as stopped.+ log.Printf("cp-proxy: sandbox %s has no hibernation and worker is gone, marking stopped", sandboxID)errMsg := "worker lost, sandbox not recoverable"_ = p.store.UpdateSandboxSessionStatus(ctx, sandboxID, "stopped", &errMsg)@@ -161,10 +161,10 @@ func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Context// is accessed. It picks the least loaded worker, sends a WakeSandbox gRPC call,// and updates the DB. Returns the worker entry and its HTTP address for proxying.func (p *ControlPlaneProxy) wakeHibernatedSandbox(ctx context.Context, sandboxID string) (*controlplane.WorkerEntry, string, error) {- // Look up the active checkpoint- checkpoint, err := p.store.GetActiveCheckpoint(ctx, sandboxID)+ // Look up the active hibernation+ checkpoint, err := p.store.GetActiveHibernation(ctx, sandboxID)if err != nil {- return nil, "", fmt.Errorf("no active checkpoint: %w", err)+ return nil, "", fmt.Errorf("no active hibernation: %w", err)}// Pick the least loaded worker in the same region@@ -182,15 +182,15 @@ func (p *ControlPlaneProxy) wakeHibernatedSandbox(ctx context.Context, sandboxID_, err = grpcClient.WakeSandbox(grpcCtx, &pb.WakeSandboxRequest{SandboxId: sandboxID,- CheckpointKey: checkpoint.CheckpointKey,+ CheckpointKey: checkpoint.HibernationKey,Timeout: 300, // default 5 min timeout after wake})if err != nil {return nil, "", fmt.Errorf("gRPC WakeSandbox failed: %w", err)}- // Update DB: mark checkpoint restored, update session to running on new worker- _ = p.store.MarkCheckpointRestored(ctx, sandboxID)+ // Update DB: mark hibernation restored, update session to running on new worker+ _ = p.store.MarkHibernationRestored(ctx, sandboxID)_ = p.store.UpdateSandboxSessionForWake(ctx, sandboxID, worker.ID)workerURL := worker.HTTPAddrdiff --git a/internal/sandbox/hibernate.go b/internal/sandbox/hibernate.goindex ba1d2256..ae1352a0 100644--- a/internal/sandbox/hibernate.go+++ b/internal/sandbox/hibernate.go@@ -19,9 +19,9 @@ import (// HibernateResult holds the result of a hibernate operation.type HibernateResult struct {- SandboxID string `json:"sandboxId"`- CheckpointKey string `json:"checkpointKey"`- SizeBytes int64 `json:"sizeBytes"`+ SandboxID string `json:"sandboxId"`+ HibernationKey string `json:"hibernationKey"`+ SizeBytes int64 `json:"sizeBytes"`}// Hibernate checkpoints a running sandbox, uploads to S3, and removes the container.@@ -34,7 +34,7 @@ func (m *PodmanManager) Hibernate(ctx context.Context, sandboxID string, checkpom.trimBeforeCheckpoint(ctx, name)// 2. Generate S3 key upfront so we can use it for cache path- s3Key := storage.CheckpointKey(sandboxID)+ s3Key := storage.HibernationKey(sandboxID)// 3. Checkpoint to local file// If NVMe cache is enabled, write directly to cache dir (stays after upload).@@ -104,7 +104,7 @@ func (m *PodmanManager) Hibernate(ctx context.Context, sandboxID string, checkporeturn &HibernateResult{SandboxID: sandboxID,- CheckpointKey: s3Key,+ HibernationKey: s3Key,SizeBytes: sizeBytes,}, nil}@@ -361,3 +361,18 @@ func (m *PodmanManager) SaveAsTemplate(_ context.Context, _, _ string, _ *storagfunc (m *PodmanManager) TemplateCachePath(_, _ string) string {return ""}++// CreateCheckpoint is not supported on the Podman backend (Firecracker only).+func (m *PodmanManager) CreateCheckpoint(_ context.Context, _, _ string, _ *storage.CheckpointStore, _ func()) (string, string, error) {+ return "", "", fmt.Errorf("checkpoints are only supported on Firecracker backend")+}++// RestoreFromCheckpoint is not supported on the Podman backend (Firecracker only).+func (m *PodmanManager) RestoreFromCheckpoint(_ context.Context, _, _ string) error {+ return fmt.Errorf("checkpoints are only supported on Firecracker backend")+}++// CheckpointCachePath always returns "" on the Podman backend (Firecracker only).+func (m *PodmanManager) CheckpointCachePath(_, _ string) string {+ return ""+}diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.goindex 7668528f..e871b5d5 100644--- a/internal/sandbox/interface.go+++ b/internal/sandbox/interface.go@@ -64,4 +64,9 @@ type Manager interface {// TemplateCachePath returns the local path to a cached template drive file (e.g., "rootfs.ext4"),// or "" if the template is not cached locally. Used to skip S3 download when creating from template.TemplateCachePath(templateID, filename string) string++ // Checkpointing+ CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error)+ RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpointID string) error+ CheckpointCachePath(checkpointID, filename string) string}diff --git a/internal/sandbox/router.go b/internal/sandbox/router.goindex d32e04c2..9f349cfd 100644--- a/internal/sandbox/router.go+++ b/internal/sandbox/router.go@@ -345,14 +345,14 @@ func (r *SandboxRouter) discoverAndEnsure(ctx context.Context, sandboxID string)return nil}- // Check if there's an active checkpoint (meaning it's hibernated)- checkpoint, err := r.store.GetActiveCheckpoint(ctx, sandboxID)+ // Check if there's an active hibernation (meaning it's hibernated)+ checkpoint, err := r.store.GetActiveHibernation(ctx, sandboxID)if err != nil || checkpoint == nil {- // No checkpoint found — sandbox might be running or doesn't exist+ // No hibernation found — sandbox might be running or doesn't existreturn nil}- // Found a checkpoint — register as hibernated and then ensure running+ // Found a hibernation — register as hibernated and then ensure runningr.MarkHibernated(sandboxID, r.defaultTimeout)return r.ensureRunning(ctx, sandboxID)}@@ -382,9 +382,9 @@ func (r *SandboxRouter) doWake(ctx context.Context, sandboxID string, entry *sanreturn}- checkpoint, err := r.store.GetActiveCheckpoint(wakeCtx, sandboxID)+ hibernation, err := r.store.GetActiveHibernation(wakeCtx, sandboxID)if err != nil {- wakeErr = fmt.Errorf("no active checkpoint: %w", err)+ wakeErr = fmt.Errorf("no active hibernation: %w", err)return}@@ -393,14 +393,14 @@ func (r *SandboxRouter) doWake(ctx context.Context, sandboxID string, entry *santimeout = int(r.defaultTimeout.Seconds())}- sb, err := r.manager.Wake(wakeCtx, sandboxID, checkpoint.CheckpointKey, r.checkpointStore, timeout)+ sb, err := r.manager.Wake(wakeCtx, sandboxID, hibernation.HibernationKey, r.checkpointStore, timeout)if err != nil {wakeErr = errreturn}// Update DB records- _ = r.store.MarkCheckpointRestored(wakeCtx, sandboxID)+ _ = r.store.MarkHibernationRestored(wakeCtx, sandboxID)_ = r.store.UpdateSandboxSessionForWake(wakeCtx, sandboxID, r.workerID)log.Printf("router: auto-woke sandbox %s (status=%s)", sandboxID, sb.Status)@@ -472,7 +472,7 @@ func (r *SandboxRouter) onTimeout(sandboxID string) {return}- log.Printf("router: sandbox %s hibernated on timeout (key=%s, size=%d)", sandboxID, result.CheckpointKey, result.SizeBytes)+ log.Printf("router: sandbox %s hibernated on timeout (key=%s, size=%d)", sandboxID, result.HibernationKey, result.SizeBytes)entry.mu.Lock()entry.state = StateHibernateddiff --git a/internal/storage/s3.go b/internal/storage/s3.goindex 1c026a45..c347dfff 100644--- a/internal/storage/s3.go+++ b/internal/storage/s3.go@@ -99,8 +99,8 @@ func (s *CheckpointStore) SetCacheDir(dir string) error {return nil}-// CheckpointKey returns the S3 key for a checkpoint archive.-func CheckpointKey(sandboxID string) string {+// HibernationKey returns the S3 key for a hibernation archive.+func HibernationKey(sandboxID string) string {return fmt.Sprintf("checkpoints/%s/%d.tar.zst", sandboxID, time.Now().UnixNano())}diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex c6a26557..84b1303c 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -338,7 +338,7 @@ func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSandreturn &pb.HibernateSandboxResponse{SandboxId: result.SandboxID,- CheckpointKey: result.CheckpointKey,+ CheckpointKey: result.HibernationKey,SizeBytes: result.SizeBytes,}, nil}@@ -428,12 +428,108 @@ func (s *GRPCServer) SaveAsTemplate(ctx context.Context, req *pb.SaveAsTemplateR}, nil}-// resolveTemplateDrives resolves S3 template keys to local file paths.-// Uses local template cache when available (instant reflink), otherwise downloads from S3.+func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpointRequest) (*pb.CreateCheckpointResponse, error) {+ if s.checkpointStore == nil {+ return nil, fmt.Errorf("checkpoint store not configured on this worker")+ }++ checkpointID := req.CheckpointId+ if _, err := uuid.Parse(checkpointID); err != nil {+ return nil, fmt.Errorf("invalid checkpoint ID: %w", err)+ }++ // The onReady callback marks the checkpoint as ready in the DB when the async S3 upload completes.+ var onReady func()+ if s.store != nil {+ cpID, _ := uuid.Parse(checkpointID)+ onReady = func() {+ if err := s.store.SetCheckpointReady(context.Background(), cpID, "", "", 0); err != nil {+ log.Printf("grpc: CreateCheckpoint: failed to mark checkpoint %s ready: %v", checkpointID, err)+ } else {+ log.Printf("grpc: CreateCheckpoint: checkpoint %s is now ready", checkpointID)+ }+ }+ }++ rootfsKey, workspaceKey, err := s.manager.CreateCheckpoint(ctx, req.SandboxId, checkpointID, s.checkpointStore, onReady)+ if err != nil {+ return nil, fmt.Errorf("create checkpoint failed: %w", err)+ }++ return &pb.CreateCheckpointResponse{+ RootfsS3Key: rootfsKey,+ WorkspaceS3Key: workspaceKey,+ }, nil+}++func (s *GRPCServer) RestoreCheckpoint(ctx context.Context, req *pb.RestoreCheckpointRequest) (*pb.RestoreCheckpointResponse, error) {+ checkpointID := req.CheckpointId+ if _, err := uuid.Parse(checkpointID); err != nil {+ return nil, fmt.Errorf("invalid checkpoint ID: %w", err)+ }++ // Check local cache first; if not available, download from S3+ cachedRootfs := s.manager.CheckpointCachePath(checkpointID, "rootfs.ext4")+ cachedWorkspace := s.manager.CheckpointCachePath(checkpointID, "workspace.ext4")+ if cachedRootfs == "" || cachedWorkspace == "" {+ // Need to download from S3+ if s.checkpointStore == nil {+ return nil, fmt.Errorf("checkpoint not cached locally and no S3 store configured")+ }+ log.Printf("grpc: RestoreCheckpoint %s: not cached locally, downloading from S3", checkpointID)+ rootfsKey := fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", req.SandboxId, checkpointID)+ workspaceKey := fmt.Sprintf("checkpoints/%s/%s/workspace.sparse.zst", req.SandboxId, checkpointID)++ cacheDir := filepath.Join(s.manager.DataDir(), "checkpoints", checkpointID)+ if err := os.MkdirAll(cacheDir, 0755); err != nil {+ return nil, fmt.Errorf("create checkpoint cache dir: %w", err)+ }++ cachedRootfsPath := filepath.Join(cacheDir, "rootfs.ext4")+ cachedWorkspacePath := filepath.Join(cacheDir, "workspace.ext4")++ if err := downloadAndExtract(ctx, s.checkpointStore, rootfsKey, cacheDir, extractArchiveCmd); err != nil {+ os.RemoveAll(cacheDir)+ return nil, fmt.Errorf("download checkpoint rootfs: %w", err)+ }+ if err := downloadAndExtract(ctx, s.checkpointStore, workspaceKey, cachedWorkspacePath, extractSparseCmd); err != nil {+ os.RemoveAll(cacheDir)+ return nil, fmt.Errorf("download checkpoint workspace: %w", err)+ }+ log.Printf("grpc: RestoreCheckpoint %s: cached locally at %s", checkpointID, cacheDir)+ _ = cachedRootfsPath // used implicitly by manager.CheckpointCachePath after download+ }++ if err := s.manager.RestoreFromCheckpoint(ctx, req.SandboxId, checkpointID); err != nil {+ return nil, fmt.Errorf("restore from checkpoint failed: %w", err)+ }++ return &pb.RestoreCheckpointResponse{Success: true}, nil+}++// resolveTemplateDrives resolves S3 template/checkpoint keys to local file paths.+// Uses local cache when available (instant reflink), otherwise downloads from S3.+// Handles both template keys (templates/{id}/...) and checkpoint keys (checkpoints/{sandboxID}/{checkpointID}/...).func (s *GRPCServer) resolveTemplateDrives(ctx context.Context, rootfsKey, workspaceKey string) (localRootfs, localWorkspace string, err error) {+ // Try checkpoint key format first: checkpoints/{sandboxID}/{checkpointID}/rootfs.tar.zst+ if checkpointID := extractCheckpointID(rootfsKey); checkpointID != "" {+ // Fast path: check local checkpoint cache+ cachedRootfs := s.manager.CheckpointCachePath(checkpointID, "rootfs.ext4")+ cachedWorkspace := s.manager.CheckpointCachePath(checkpointID, "workspace.ext4")+ if cachedRootfs != "" && cachedWorkspace != "" {+ log.Printf("grpc: create from checkpoint %s: using local cache", checkpointID)+ return cachedRootfs, cachedWorkspace, nil+ }++ // Slow path: download from S3 and cache locally+ log.Printf("grpc: create from checkpoint %s: downloading from S3 (rootfs=%s, workspace=%s)", checkpointID, rootfsKey, workspaceKey)+ return s.downloadAndCacheCheckpointDrives(ctx, checkpointID, rootfsKey, workspaceKey)+ }++ // Template key format: templates/{id}/rootfs.tar.zsttemplateID := extractTemplateID(rootfsKey)if templateID == "" {- return "", "", fmt.Errorf("cannot extract template ID from key: %s", rootfsKey)+ return "", "", fmt.Errorf("cannot extract template/checkpoint ID from key: %s", rootfsKey)}// Fast path: check local template cache@@ -458,6 +554,15 @@ func extractTemplateID(s3Key string) string {return ""}+// extractCheckpointID extracts the checkpoint ID from an S3 key like "checkpoints/{sandboxID}/{checkpointID}/rootfs.tar.zst".+func extractCheckpointID(s3Key string) string {+ parts := strings.Split(s3Key, "/")+ if len(parts) >= 3 && parts[0] == "checkpoints" {+ return parts[2] // parts[1] is sandboxID, parts[2] is checkpointID+ }+ return ""+}+// downloadAndCacheTemplateDrives downloads template archives from S3, extracts them,// and caches the ext4 drives locally for future use.func (s *GRPCServer) downloadAndCacheTemplateDrives(ctx context.Context, templateID, rootfsKey, workspaceKey string) (string, string, error) {@@ -489,6 +594,37 @@ func (s *GRPCServer) downloadAndCacheTemplateDrives(ctx context.Context, templatreturn cachedRootfs, cachedWorkspace, nil}+// downloadAndCacheCheckpointDrives downloads checkpoint archives from S3, extracts them,+// and caches the ext4 drives locally for future use.+func (s *GRPCServer) downloadAndCacheCheckpointDrives(ctx context.Context, checkpointID, rootfsKey, workspaceKey string) (string, string, error) {+ if s.checkpointStore == nil {+ return "", "", fmt.Errorf("checkpoint store not configured")+ }++ cacheDir := filepath.Join(s.manager.DataDir(), "checkpoints", checkpointID)+ if err := os.MkdirAll(cacheDir, 0755); err != nil {+ return "", "", fmt.Errorf("create checkpoint cache dir: %w", err)+ }++ cachedRootfs := filepath.Join(cacheDir, "rootfs.ext4")+ cachedWorkspace := filepath.Join(cacheDir, "workspace.ext4")++ // Download and extract rootfs (tar.zst)+ if err := downloadAndExtract(ctx, s.checkpointStore, rootfsKey, cacheDir, extractArchiveCmd); err != nil {+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("download rootfs: %w", err)+ }++ // Download and extract workspace (sparse.zst)+ if err := downloadAndExtract(ctx, s.checkpointStore, workspaceKey, cachedWorkspace, extractSparseCmd); err != nil {+ os.RemoveAll(cacheDir)+ return "", "", fmt.Errorf("download workspace: %w", err)+ }++ log.Printf("grpc: checkpoint %s: cached locally at %s", checkpointID, cacheDir)+ return cachedRootfs, cachedWorkspace, nil+}+// extractFunc defines how to extract a downloaded archive to a destination path.type extractFunc func(archivePath, destPath string) errordiff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex fbcb5229..c85163e0 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -58,14 +58,14 @@ type TimeoutRequest struct {Timeout int `json:"timeout"` // seconds}-// CheckpointInfo holds metadata about a hibernated sandbox's checkpoint.-type CheckpointInfo struct {- SandboxID string `json:"sandboxId"`- CheckpointKey string `json:"checkpointKey"`- SizeBytes int64 `json:"sizeBytes"`- Region string `json:"region"`- Template string `json:"template"`- HibernatedAt time.Time `json:"hibernatedAt"`+// HibernationInfo holds metadata about a hibernated sandbox.+type HibernationInfo struct {+ SandboxID string `json:"sandboxId"`+ HibernationKey string `json:"hibernationKey"`+ SizeBytes int64 `json:"sizeBytes"`+ Region string `json:"region"`+ Template string `json:"template"`+ HibernatedAt time.Time `json:"hibernatedAt"`}// WakeRequest is the request body for waking a hibernated sandbox.diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.goindex 48f05372..e980a357 100644--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@ -1942,6 +1942,206 @@ func (x *GetSandboxStatsResponse) GetPids() int32 {return 0}+type CreateCheckpointRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ CheckpointId string `protobuf:"bytes,2,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"` // UUID assigned by control plane+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *CreateCheckpointRequest) Reset() {+ *x = CreateCheckpointRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[33]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *CreateCheckpointRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*CreateCheckpointRequest) ProtoMessage() {}++func (x *CreateCheckpointRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[33]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use CreateCheckpointRequest.ProtoReflect.Descriptor instead.+func (*CreateCheckpointRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{33}+}++func (x *CreateCheckpointRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *CreateCheckpointRequest) GetCheckpointId() string {+ if x != nil {+ return x.CheckpointId+ }+ return ""+}++type CreateCheckpointResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ RootfsS3Key string `protobuf:"bytes,1,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"`+ WorkspaceS3Key string `protobuf:"bytes,2,opt,name=workspace_s3_key,json=workspaceS3Key,proto3" json:"workspace_s3_key,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *CreateCheckpointResponse) Reset() {+ *x = CreateCheckpointResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[34]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *CreateCheckpointResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*CreateCheckpointResponse) ProtoMessage() {}++func (x *CreateCheckpointResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[34]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use CreateCheckpointResponse.ProtoReflect.Descriptor instead.+func (*CreateCheckpointResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{34}+}++func (x *CreateCheckpointResponse) GetRootfsS3Key() string {+ if x != nil {+ return x.RootfsS3Key+ }+ return ""+}++func (x *CreateCheckpointResponse) GetWorkspaceS3Key() string {+ if x != nil {+ return x.WorkspaceS3Key+ }+ return ""+}++type RestoreCheckpointRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ CheckpointId string `protobuf:"bytes,2,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RestoreCheckpointRequest) Reset() {+ *x = RestoreCheckpointRequest{}+ mi := &file_proto_worker_worker_proto_msgTypes[35]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RestoreCheckpointRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RestoreCheckpointRequest) ProtoMessage() {}++func (x *RestoreCheckpointRequest) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[35]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RestoreCheckpointRequest.ProtoReflect.Descriptor instead.+func (*RestoreCheckpointRequest) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{35}+}++func (x *RestoreCheckpointRequest) GetSandboxId() string {+ if x != nil {+ return x.SandboxId+ }+ return ""+}++func (x *RestoreCheckpointRequest) GetCheckpointId() string {+ if x != nil {+ return x.CheckpointId+ }+ return ""+}++type RestoreCheckpointResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *RestoreCheckpointResponse) Reset() {+ *x = RestoreCheckpointResponse{}+ mi := &file_proto_worker_worker_proto_msgTypes[36]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *RestoreCheckpointResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*RestoreCheckpointResponse) ProtoMessage() {}++func (x *RestoreCheckpointResponse) ProtoReflect() protoreflect.Message {+ mi := &file_proto_worker_worker_proto_msgTypes[36]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use RestoreCheckpointResponse.ProtoReflect.Descriptor instead.+func (*RestoreCheckpointResponse) Descriptor() ([]byte, []int) {+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{36}+}++func (x *RestoreCheckpointResponse) GetSuccess() bool {+ if x != nil {+ return x.Success+ }+ return false+}+var File_proto_worker_worker_proto protoreflect.FileDescriptorconst file_proto_worker_worker_proto_rawDesc = "" +@@ -2099,7 +2299,21 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\tnet_input\x18\x04 \x01(\x04R\bnetInput\x12\x1d\n" +"\n" +"net_output\x18\x05 \x01(\x04R\tnetOutput\x12\x12\n" +- "\x04pids\x18\x06 \x01(\x05R\x04pids2\x9c\t\n" ++ "\x04pids\x18\x06 \x01(\x05R\x04pids\"]\n" ++ "\x17CreateCheckpointRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" ++ "\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\"h\n" ++ "\x18CreateCheckpointResponse\x12\"\n" ++ "\rrootfs_s3_key\x18\x01 \x01(\tR\vrootfsS3Key\x12(\n" ++ "\x10workspace_s3_key\x18\x02 \x01(\tR\x0eworkspaceS3Key\"^\n" ++ "\x18RestoreCheckpointRequest\x12\x1d\n" ++ "\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" ++ "\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\"5\n" ++ "\x19RestoreCheckpointResponse\x12\x18\n" ++ "\asuccess\x18\x01 \x01(\bR\asuccess2\xcd\n" ++ "\n" +"\rSandboxWorker\x12L\n" +"\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +"\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +@@ -2115,7 +2329,9 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\tPTYStream\x12\x10.worker.PTYInput\x1a\x11.worker.PTYOutput(\x010\x01\x12U\n" +"\x10HibernateSandbox\x12\x1f.worker.HibernateSandboxRequest\x1a .worker.HibernateSandboxResponse\x12F\n" +"\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponse\x12O\n" +- "\x0eSaveAsTemplate\x12\x1d.worker.SaveAsTemplateRequest\x1a\x1e.worker.SaveAsTemplateResponse\x12L\n" ++ "\x0eSaveAsTemplate\x12\x1d.worker.SaveAsTemplateRequest\x1a\x1e.worker.SaveAsTemplateResponse\x12U\n" ++ "\x10CreateCheckpoint\x12\x1f.worker.CreateCheckpointRequest\x1a .worker.CreateCheckpointResponse\x12X\n" ++ "\x11RestoreCheckpoint\x12 .worker.RestoreCheckpointRequest\x1a!.worker.RestoreCheckpointResponse\x12L\n" +"\rBuildTemplate\x12\x1c.worker.BuildTemplateRequest\x1a\x1d.worker.BuildTemplateResponse\x12R\n" +"\x0fGetSandboxStats\x12\x1e.worker.GetSandboxStatsRequest\x1a\x1f.worker.GetSandboxStatsResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"@@ -2132,49 +2348,53 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {}var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 35)+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 39)var file_proto_worker_worker_proto_goTypes = []any{- (ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream- (*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest- (*CreateSandboxResponse)(nil), // 2: worker.CreateSandboxResponse- (*DestroySandboxRequest)(nil), // 3: worker.DestroySandboxRequest- (*DestroySandboxResponse)(nil), // 4: worker.DestroySandboxResponse- (*GetSandboxRequest)(nil), // 5: worker.GetSandboxRequest- (*GetSandboxResponse)(nil), // 6: worker.GetSandboxResponse- (*ListSandboxesRequest)(nil), // 7: worker.ListSandboxesRequest- (*ListSandboxesResponse)(nil), // 8: worker.ListSandboxesResponse- (*ExecCommandRequest)(nil), // 9: worker.ExecCommandRequest- (*ExecCommandResponse)(nil), // 10: worker.ExecCommandResponse- (*ExecOutputChunk)(nil), // 11: worker.ExecOutputChunk- (*ReadFileRequest)(nil), // 12: worker.ReadFileRequest- (*ReadFileResponse)(nil), // 13: worker.ReadFileResponse- (*WriteFileRequest)(nil), // 14: worker.WriteFileRequest- (*WriteFileResponse)(nil), // 15: worker.WriteFileResponse- (*ListDirRequest)(nil), // 16: worker.ListDirRequest- (*DirEntry)(nil), // 17: worker.DirEntry- (*ListDirResponse)(nil), // 18: worker.ListDirResponse- (*CreatePTYRequest)(nil), // 19: worker.CreatePTYRequest- (*CreatePTYResponse)(nil), // 20: worker.CreatePTYResponse- (*PTYInput)(nil), // 21: worker.PTYInput- (*PTYResize)(nil), // 22: worker.PTYResize- (*PTYOutput)(nil), // 23: worker.PTYOutput- (*HibernateSandboxRequest)(nil), // 24: worker.HibernateSandboxRequest- (*HibernateSandboxResponse)(nil), // 25: worker.HibernateSandboxResponse- (*WakeSandboxRequest)(nil), // 26: worker.WakeSandboxRequest- (*WakeSandboxResponse)(nil), // 27: worker.WakeSandboxResponse- (*SaveAsTemplateRequest)(nil), // 28: worker.SaveAsTemplateRequest- (*SaveAsTemplateResponse)(nil), // 29: worker.SaveAsTemplateResponse- (*BuildTemplateRequest)(nil), // 30: worker.BuildTemplateRequest- (*BuildTemplateResponse)(nil), // 31: worker.BuildTemplateResponse- (*GetSandboxStatsRequest)(nil), // 32: worker.GetSandboxStatsRequest- (*GetSandboxStatsResponse)(nil), // 33: worker.GetSandboxStatsResponse- nil, // 34: worker.CreateSandboxRequest.EnvsEntry- nil, // 35: worker.ExecCommandRequest.EnvsEntry+ (ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream+ (*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest+ (*CreateSandboxResponse)(nil), // 2: worker.CreateSandboxResponse+ (*DestroySandboxRequest)(nil), // 3: worker.DestroySandboxRequest+ (*DestroySandboxResponse)(nil), // 4: worker.DestroySandboxResponse+ (*GetSandboxRequest)(nil), // 5: worker.GetSandboxRequest+ (*GetSandboxResponse)(nil), // 6: worker.GetSandboxResponse+ (*ListSandboxesRequest)(nil), // 7: worker.ListSandboxesRequest+ (*ListSandboxesResponse)(nil), // 8: worker.ListSandboxesResponse+ (*ExecCommandRequest)(nil), // 9: worker.ExecCommandRequest+ (*ExecCommandResponse)(nil), // 10: worker.ExecCommandResponse+ (*ExecOutputChunk)(nil), // 11: worker.ExecOutputChunk+ (*ReadFileRequest)(nil), // 12: worker.ReadFileRequest+ (*ReadFileResponse)(nil), // 13: worker.ReadFileResponse+ (*WriteFileRequest)(nil), // 14: worker.WriteFileRequest+ (*WriteFileResponse)(nil), // 15: worker.WriteFileResponse+ (*ListDirRequest)(nil), // 16: worker.ListDirRequest+ (*DirEntry)(nil), // 17: worker.DirEntry+ (*ListDirResponse)(nil), // 18: worker.ListDirResponse+ (*CreatePTYRequest)(nil), // 19: worker.CreatePTYRequest+ (*CreatePTYResponse)(nil), // 20: worker.CreatePTYResponse+ (*PTYInput)(nil), // 21: worker.PTYInput+ (*PTYResize)(nil), // 22: worker.PTYResize+ (*PTYOutput)(nil), // 23: worker.PTYOutput+ (*HibernateSandboxRequest)(nil), // 24: worker.HibernateSandboxRequest+ (*HibernateSandboxResponse)(nil), // 25: worker.HibernateSandboxResponse+ (*WakeSandboxRequest)(nil), // 26: worker.WakeSandboxRequest+ (*WakeSandboxResponse)(nil), // 27: worker.WakeSandboxResponse+ (*SaveAsTemplateRequest)(nil), // 28: worker.SaveAsTemplateRequest+ (*SaveAsTemplateResponse)(nil), // 29: worker.SaveAsTemplateResponse+ (*BuildTemplateRequest)(nil), // 30: worker.BuildTemplateRequest+ (*BuildTemplateResponse)(nil), // 31: worker.BuildTemplateResponse+ (*GetSandboxStatsRequest)(nil), // 32: worker.GetSandboxStatsRequest+ (*GetSandboxStatsResponse)(nil), // 33: worker.GetSandboxStatsResponse+ (*CreateCheckpointRequest)(nil), // 34: worker.CreateCheckpointRequest+ (*CreateCheckpointResponse)(nil), // 35: worker.CreateCheckpointResponse+ (*RestoreCheckpointRequest)(nil), // 36: worker.RestoreCheckpointRequest+ (*RestoreCheckpointResponse)(nil), // 37: worker.RestoreCheckpointResponse+ nil, // 38: worker.CreateSandboxRequest.EnvsEntry+ nil, // 39: worker.ExecCommandRequest.EnvsEntry}var file_proto_worker_worker_proto_depIdxs = []int32{- 34, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry+ 38, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse- 35, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry+ 39, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry0, // 3: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream17, // 4: worker.ListDirResponse.entries:type_name -> worker.DirEntry22, // 5: worker.PTYInput.resize:type_name -> worker.PTYResize@@ -2192,26 +2412,30 @@ var file_proto_worker_worker_proto_depIdxs = []int32{24, // 17: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest26, // 18: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest28, // 19: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest- 30, // 20: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest- 32, // 21: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest- 2, // 22: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse- 4, // 23: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse- 6, // 24: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse- 8, // 25: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse- 10, // 26: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse- 11, // 27: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk- 13, // 28: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse- 15, // 29: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse- 18, // 30: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse- 20, // 31: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse- 23, // 32: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput- 25, // 33: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse- 27, // 34: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse- 29, // 35: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse- 31, // 36: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse- 33, // 37: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse- 22, // [22:38] is the sub-list for method output_type- 6, // [6:22] is the sub-list for method input_type+ 34, // 20: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest+ 36, // 21: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest+ 30, // 22: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest+ 32, // 23: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest+ 2, // 24: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse+ 4, // 25: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse+ 6, // 26: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse+ 8, // 27: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse+ 10, // 28: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse+ 11, // 29: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk+ 13, // 30: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse+ 15, // 31: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse+ 18, // 32: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse+ 20, // 33: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse+ 23, // 34: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput+ 25, // 35: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse+ 27, // 36: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse+ 29, // 37: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse+ 35, // 38: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse+ 37, // 39: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse+ 31, // 40: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse+ 33, // 41: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse+ 24, // [24:42] is the sub-list for method output_type+ 6, // [6:24] is the sub-list for method input_type6, // [6:6] is the sub-list for extension type_name6, // [6:6] is the sub-list for extension extendee0, // [0:6] is the sub-list for field type_name@@ -2232,7 +2456,7 @@ func file_proto_worker_worker_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),NumEnums: 1,- NumMessages: 35,+ NumMessages: 39,NumExtensions: 0,NumServices: 1,},diff --git a/proto/worker/worker.proto b/proto/worker/worker.protoindex de9915aa..a1eb63ca 100644--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@ -25,6 +25,9 @@ service SandboxWorker {rpc SaveAsTemplate(SaveAsTemplateRequest) returns (SaveAsTemplateResponse);+ rpc CreateCheckpoint(CreateCheckpointRequest) returns (CreateCheckpointResponse);+ rpc RestoreCheckpoint(RestoreCheckpointRequest) returns (RestoreCheckpointResponse);+rpc BuildTemplate(BuildTemplateRequest) returns (BuildTemplateResponse);rpc GetSandboxStats(GetSandboxStatsRequest) returns (GetSandboxStatsResponse);@@ -214,3 +217,22 @@ message GetSandboxStatsResponse {uint64 net_output = 5;int32 pids = 6;}++message CreateCheckpointRequest {+ string sandbox_id = 1;+ string checkpoint_id = 2; // UUID assigned by control plane+}++message CreateCheckpointResponse {+ string rootfs_s3_key = 1;+ string workspace_s3_key = 2;+}++message RestoreCheckpointRequest {+ string sandbox_id = 1;+ string checkpoint_id = 2;+}++message RestoreCheckpointResponse {+ bool success = 1;+}diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.goindex 71f4bf1e..8924a163 100644--- a/proto/worker/worker_grpc.pb.go+++ b/proto/worker/worker_grpc.pb.go@@ -33,6 +33,8 @@ const (SandboxWorker_HibernateSandbox_FullMethodName = "/worker.SandboxWorker/HibernateSandbox"SandboxWorker_WakeSandbox_FullMethodName = "/worker.SandboxWorker/WakeSandbox"SandboxWorker_SaveAsTemplate_FullMethodName = "/worker.SandboxWorker/SaveAsTemplate"+ SandboxWorker_CreateCheckpoint_FullMethodName = "/worker.SandboxWorker/CreateCheckpoint"+ SandboxWorker_RestoreCheckpoint_FullMethodName = "/worker.SandboxWorker/RestoreCheckpoint"SandboxWorker_BuildTemplate_FullMethodName = "/worker.SandboxWorker/BuildTemplate"SandboxWorker_GetSandboxStats_FullMethodName = "/worker.SandboxWorker/GetSandboxStats")@@ -55,6 +57,8 @@ type SandboxWorkerClient interface {HibernateSandbox(ctx context.Context, in *HibernateSandboxRequest, opts ...grpc.CallOption) (*HibernateSandboxResponse, error)WakeSandbox(ctx context.Context, in *WakeSandboxRequest, opts ...grpc.CallOption) (*WakeSandboxResponse, error)SaveAsTemplate(ctx context.Context, in *SaveAsTemplateRequest, opts ...grpc.CallOption) (*SaveAsTemplateResponse, error)+ CreateCheckpoint(ctx context.Context, in *CreateCheckpointRequest, opts ...grpc.CallOption) (*CreateCheckpointResponse, error)+ RestoreCheckpoint(ctx context.Context, in *RestoreCheckpointRequest, opts ...grpc.CallOption) (*RestoreCheckpointResponse, error)BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error)GetSandboxStats(ctx context.Context, in *GetSandboxStatsRequest, opts ...grpc.CallOption) (*GetSandboxStatsResponse, error)}@@ -219,6 +223,26 @@ func (c *sandboxWorkerClient) SaveAsTemplate(ctx context.Context, in *SaveAsTempreturn out, nil}+func (c *sandboxWorkerClient) CreateCheckpoint(ctx context.Context, in *CreateCheckpointRequest, opts ...grpc.CallOption) (*CreateCheckpointResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(CreateCheckpointResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_CreateCheckpoint_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++func (c *sandboxWorkerClient) RestoreCheckpoint(ctx context.Context, in *RestoreCheckpointRequest, opts ...grpc.CallOption) (*RestoreCheckpointResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(RestoreCheckpointResponse)+ err := c.cc.Invoke(ctx, SandboxWorker_RestoreCheckpoint_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}+func (c *sandboxWorkerClient) BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(BuildTemplateResponse)@@ -257,6 +281,8 @@ type SandboxWorkerServer interface {HibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error)WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error)SaveAsTemplate(context.Context, *SaveAsTemplateRequest) (*SaveAsTemplateResponse, error)+ CreateCheckpoint(context.Context, *CreateCheckpointRequest) (*CreateCheckpointResponse, error)+ RestoreCheckpoint(context.Context, *RestoreCheckpointRequest) (*RestoreCheckpointResponse, error)BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error)GetSandboxStats(context.Context, *GetSandboxStatsRequest) (*GetSandboxStatsResponse, error)mustEmbedUnimplementedSandboxWorkerServer()@@ -311,6 +337,12 @@ func (UnimplementedSandboxWorkerServer) WakeSandbox(context.Context, *WakeSandbofunc (UnimplementedSandboxWorkerServer) SaveAsTemplate(context.Context, *SaveAsTemplateRequest) (*SaveAsTemplateResponse, error) {return nil, status.Error(codes.Unimplemented, "method SaveAsTemplate not implemented")}+func (UnimplementedSandboxWorkerServer) CreateCheckpoint(context.Context, *CreateCheckpointRequest) (*CreateCheckpointResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method CreateCheckpoint not implemented")+}+func (UnimplementedSandboxWorkerServer) RestoreCheckpoint(context.Context, *RestoreCheckpointRequest) (*RestoreCheckpointResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method RestoreCheckpoint not implemented")+}func (UnimplementedSandboxWorkerServer) BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error) {return nil, status.Error(codes.Unimplemented, "method BuildTemplate not implemented")}@@ -572,6 +604,42 @@ func _SandboxWorker_SaveAsTemplate_Handler(srv interface{}, ctx context.Context,return interceptor(ctx, in, info, handler)}+func _SandboxWorker_CreateCheckpoint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(CreateCheckpointRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).CreateCheckpoint(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_CreateCheckpoint_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).CreateCheckpoint(ctx, req.(*CreateCheckpointRequest))+ }+ return interceptor(ctx, in, info, handler)+}++func _SandboxWorker_RestoreCheckpoint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(RestoreCheckpointRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(SandboxWorkerServer).RestoreCheckpoint(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: SandboxWorker_RestoreCheckpoint_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(SandboxWorkerServer).RestoreCheckpoint(ctx, req.(*RestoreCheckpointRequest))+ }+ return interceptor(ctx, in, info, handler)+}+func _SandboxWorker_BuildTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(BuildTemplateRequest)if err := dec(in); err != nil {@@ -663,6 +731,14 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{MethodName: "SaveAsTemplate",Handler: _SandboxWorker_SaveAsTemplate_Handler,},+ {+ MethodName: "CreateCheckpoint",+ Handler: _SandboxWorker_CreateCheckpoint_Handler,+ },+ {+ MethodName: "RestoreCheckpoint",+ Handler: _SandboxWorker_RestoreCheckpoint_Handler,+ },{MethodName: "BuildTemplate",Handler: _SandboxWorker_BuildTemplate_Handler,diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.pyindex 3d106203..1b13694f 100644--- a/sdks/python/opencomputer/sandbox.py+++ b/sdks/python/opencomputer/sandbox.py@@ -184,6 +184,126 @@ class Sandbox:pty_key = self._token or self._api_keyreturn Pty(self._ops_client, self.sandbox_id, pty_url, pty_key)+ async def create_checkpoint(self, name: str) -> dict:+ """Create a named checkpoint of the running sandbox.++ Args:+ name: A unique name for this checkpoint.++ Returns:+ Checkpoint info dict with id, sandboxId, name, status, etc.+ """+ resp = await self._client.post(+ f"/sandboxes/{self.sandbox_id}/checkpoints",+ json={"name": name},+ )+ resp.raise_for_status()+ return resp.json()++ async def list_checkpoints(self) -> list[dict]:+ """List all checkpoints for this sandbox."""+ resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/checkpoints")+ resp.raise_for_status()+ return resp.json()++ async def restore_checkpoint(self, checkpoint_id: str) -> None:+ """Restore the sandbox to a previous checkpoint (in-place revert).++ The VM is rebooted from the checkpoint's drives. After restore,+ internal clients are refreshed automatically.++ Args:+ checkpoint_id: UUID of the checkpoint to restore.+ """+ resp = await self._client.post(+ f"/sandboxes/{self.sandbox_id}/checkpoints/{checkpoint_id}/restore",+ )+ resp.raise_for_status()++ # Refresh connection info since the VM was rebooted+ info = await self._client.get(f"/sandboxes/{self.sandbox_id}")+ info.raise_for_status()+ data = info.json()+ self._connect_url = data.get("connectURL", "")+ self._token = data.get("token", "")+ if self._connect_url and self._token:+ if self._data_client is not None:+ await self._data_client.aclose()+ self._data_client = httpx.AsyncClient(+ base_url=self._connect_url,+ headers={"Authorization": f"Bearer {self._token}"},+ timeout=30.0,+ )++ @classmethod+ async def create_from_checkpoint(+ cls,+ checkpoint_id: str,+ timeout: int = 300,+ api_key: str | None = None,+ api_url: str | None = None,+ ) -> Sandbox:+ """Create a new sandbox from an existing checkpoint (fork).++ Args:+ checkpoint_id: UUID of the checkpoint to fork from.+ timeout: Sandbox timeout in seconds (default 300).+ api_key: API key (or OPENCOMPUTER_API_KEY env var).+ api_url: API URL (or OPENCOMPUTER_API_URL env var).+ """+ url = api_url or os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")+ url = url.rstrip("/")+ key = api_key or os.environ.get("OPENCOMPUTER_API_KEY", "")++ api_base = url if url.endswith("/api") else f"{url}/api"++ headers = {}+ if key:+ headers["X-API-Key"] = key++ client = httpx.AsyncClient(base_url=api_base, headers=headers, timeout=120.0)++ resp = await client.post(+ f"/sandboxes/from-checkpoint/{checkpoint_id}",+ json={"timeout": timeout},+ )+ resp.raise_for_status()+ data = resp.json()++ connect_url = data.get("connectURL", "")+ token = data.get("token", "")++ data_client = None+ if connect_url and token:+ data_client = httpx.AsyncClient(+ base_url=connect_url,+ headers={"Authorization": f"Bearer {token}"},+ timeout=30.0,+ )++ return cls(+ sandbox_id=data["sandboxID"],+ status=data.get("status", "running"),+ _api_url=url,+ _api_key=key,+ _connect_url=connect_url,+ _token=token,+ _client=client,+ _data_client=data_client,+ )++ async def delete_checkpoint(self, checkpoint_id: str) -> None:+ """Delete a checkpoint.++ Args:+ checkpoint_id: UUID of the checkpoint to delete.+ """+ resp = await self._client.delete(+ f"/sandboxes/{self.sandbox_id}/checkpoints/{checkpoint_id}",+ )+ if resp.status_code != 404:+ resp.raise_for_status()+async def create_preview_url(self, port: int, domain: str | None = None, auth_config: dict | None = None) -> dict:"""Create a preview URL targeting a specific container port.diff --git a/sdks/typescript/examples/bench-checkpoints.ts b/sdks/typescript/examples/bench-checkpoints.tsnew file mode 100644index 00000000..a25188bc--- /dev/null+++ b/sdks/typescript/examples/bench-checkpoints.ts@@ -0,0 +1,221 @@+/**+ * Checkpoint Benchmark+ *+ * Measures wall-clock timing of each checkpoint operation:+ * 1. Create checkpoint (pause + drive copy + resume + S3 upload)+ * 2. List checkpoints+ * 3. Restore checkpoint (kill VM + copy drives + cold boot)+ * 4. Fork from checkpoint (new sandbox from checkpoint drives)+ * 5. Delete checkpoint+ *+ * Each operation is run multiple times and min/avg/max are reported.+ *+ * Usage:+ * npx tsx examples/bench-checkpoints.ts+ */++import { Sandbox } from "../src/index";++function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }+function cyan(msg: string) { console.log(`\x1b[36m${msg}\x1b[0m`); }+function green(msg: string) { console.log(`\x1b[32m${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m${msg}\x1b[0m`); }++async function sleep(ms: number) {+ return new Promise((r) => globalThis.setTimeout(r, ms));+}++interface Timing {+ label: string;+ samples: number[];+}++function stats(t: Timing) {+ const sorted = [...t.samples].sort((a, b) => a - b);+ const min = sorted[0];+ const max = sorted[sorted.length - 1];+ const avg = Math.round(t.samples.reduce((s, v) => s + v, 0) / t.samples.length);+ const median = sorted[Math.floor(sorted.length / 2)];+ return { min, max, avg, median };+}++function formatMs(ms: number): string {+ if (ms < 1000) return `${ms}ms`;+ return `${(ms / 1000).toFixed(2)}s`;+}++function printTable(timings: Timing[]) {+ const labelWidth = Math.max(...timings.map((t) => t.label.length), 9);+ const header = `${"Operation".padEnd(labelWidth)} ${"Runs".padStart(4)} ${"Min".padStart(8)} ${"Avg".padStart(8)} ${"Median".padStart(8)} ${"Max".padStart(8)}`;+ const sep = "─".repeat(header.length);++ console.log();+ bold(sep);+ bold(header);+ bold(sep);++ for (const t of timings) {+ const s = stats(t);+ const row = `${t.label.padEnd(labelWidth)} ${String(t.samples.length).padStart(4)} ${formatMs(s.min).padStart(8)} ${formatMs(s.avg).padStart(8)} ${formatMs(s.median).padStart(8)} ${formatMs(s.max).padStart(8)}`;+ console.log(row);+ }+ bold(sep);+ console.log();+}++async function timed<T>(fn: () => Promise<T>): Promise<{ result: T; ms: number }> {+ const start = Date.now();+ const result = await fn();+ return { result, ms: Date.now() - start };+}++async function waitForReady(sandbox: Sandbox, checkpointId: string, timeoutMs = 120000): Promise<boolean> {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ const list = await sandbox.listCheckpoints();+ const cp = list.find((c) => c.id === checkpointId);+ if (cp && cp.status === "ready") return true;+ if (cp && cp.status !== "processing") return false;+ await sleep(1000);+ }+ return false;+}++const ITERATIONS = 3;++async function main() {+ bold("\n╔══════════════════════════════════════════════════╗");+ bold("║ Checkpoint Benchmark ║");+ bold("╚══════════════════════════════════════════════════╝\n");++ dim(`Iterations per operation: ${ITERATIONS}`);+ console.log();++ const timings: Timing[] = [];+ const createTiming: Timing = { label: "Create checkpoint", samples: [] };+ const listTiming: Timing = { label: "List checkpoints", samples: [] };+ const restoreTiming: Timing = { label: "Restore (in-place)", samples: [] };+ const forkTiming: Timing = { label: "Fork from checkpoint", samples: [] };+ const deleteTiming: Timing = { label: "Delete checkpoint", samples: [] };+ const firstCmdTiming: Timing = { label: "First cmd after restore", samples: [] };++ timings.push(createTiming, listTiming, restoreTiming, firstCmdTiming, forkTiming, deleteTiming);++ const sandboxes: Sandbox[] = [];++ try {+ // ── Setup ──────────────────────────────────────────────────────+ bold("━━━ Setup ━━━\n");++ const { result: sandbox, ms: createSbMs } = await timed(() =>+ Sandbox.create({ template: "base", timeout: 300 }),+ );+ sandboxes.push(sandbox);+ dim(`Sandbox created: ${sandbox.sandboxId} (${formatMs(createSbMs)})`);++ // Write some state so the workspace isn't empty+ await sandbox.commands.run("dd if=/dev/urandom of=/workspace/payload.bin bs=1M count=10 2>/dev/null");+ await sandbox.commands.run("echo bench-state > /workspace/marker.txt");+ dim("Wrote 10 MB payload + marker file");+ console.log();++ // ── Benchmark: Create checkpoint ───────────────────────────────+ bold("━━━ Create checkpoint ━━━\n");++ const checkpointIds: string[] = [];+ for (let i = 0; i < ITERATIONS; i++) {+ const name = `bench-cp-${i}`;+ const { result: cp, ms } = await timed(() => sandbox.createCheckpoint(name));+ createTiming.samples.push(ms);+ checkpointIds.push(cp.id);+ dim(`#${i + 1}: ${formatMs(ms)} (id=${cp.id.slice(0, 8)}…, status=${cp.status})`);++ // Wait for ready before next iteration (so S3 upload doesn't compete)+ await waitForReady(sandbox, cp.id);+ }+ console.log();++ // ── Benchmark: List checkpoints ────────────────────────────────+ bold("━━━ List checkpoints ━━━\n");++ for (let i = 0; i < ITERATIONS; i++) {+ const { result: list, ms } = await timed(() => sandbox.listCheckpoints());+ listTiming.samples.push(ms);+ dim(`#${i + 1}: ${formatMs(ms)} (${list.length} checkpoints)`);+ }+ console.log();++ // ── Benchmark: Restore (in-place revert) ───────────────────────+ bold("━━━ Restore (in-place revert) ━━━\n");++ for (let i = 0; i < ITERATIONS; i++) {+ // Modify state before each restore so we can verify it works+ await sandbox.commands.run(`echo pre-restore-${i} > /workspace/marker.txt`);++ const cpId = checkpointIds[0]; // always restore to the first checkpoint+ const { ms: restoreMs } = await timed(() => sandbox.restoreCheckpoint(cpId));+ restoreTiming.samples.push(restoreMs);++ // Measure time to first command after restore+ const { result: cmd, ms: cmdMs } = await timed(() =>+ sandbox.commands.run("cat /workspace/marker.txt"),+ );+ firstCmdTiming.samples.push(cmdMs);++ const marker = cmd.stdout.trim();+ const ok = marker === "bench-state" ? "✓" : `✗ (got: ${marker})`;+ dim(`#${i + 1}: restore=${formatMs(restoreMs)}, first_cmd=${formatMs(cmdMs)} ${ok}`);+ }+ console.log();++ // ── Benchmark: Fork from checkpoint ────────────────────────────+ bold("━━━ Fork from checkpoint ━━━\n");++ for (let i = 0; i < ITERATIONS; i++) {+ const cpId = checkpointIds[0];+ const { result: forked, ms } = await timed(() => Sandbox.createFromCheckpoint(cpId));+ forkTiming.samples.push(ms);+ sandboxes.push(forked);++ // Verify the fork has correct state+ const cmd = await forked.commands.run("cat /workspace/marker.txt");+ const marker = cmd.stdout.trim();+ const ok = marker === "bench-state" ? "✓" : `✗ (got: ${marker})`;+ dim(`#${i + 1}: ${formatMs(ms)} (sandbox=${forked.sandboxId}) ${ok}`);+ }+ console.log();++ // ── Benchmark: Delete checkpoint ───────────────────────────────+ bold("━━━ Delete checkpoint ━━━\n");++ for (let i = 0; i < ITERATIONS; i++) {+ const cpId = checkpointIds[i];+ const { ms } = await timed(() => sandbox.deleteCheckpoint(cpId));+ deleteTiming.samples.push(ms);+ dim(`#${i + 1}: ${formatMs(ms)}`);+ }+ console.log();++ // ── Results ────────────────────────────────────────────────────+ bold("━━━ Results ━━━");+ printTable(timings);++ } catch (err: any) {+ red(`Fatal: ${err.message}`);+ if (err.stack) dim(err.stack);+ } finally {+ bold("━━━ Cleanup ━━━\n");+ for (const sb of sandboxes) {+ try {+ await sb.kill();+ dim(`Killed ${sb.sandboxId}`);+ } catch { /* best effort */ }+ }+ }+}++main().catch((err) => {+ console.error("Fatal:", err);+ process.exit(1);+});diff --git a/sdks/typescript/examples/run-all-tests.ts b/sdks/typescript/examples/run-all-tests.tsindex c5ea47a6..02cc4bca 100644--- a/sdks/typescript/examples/run-all-tests.ts+++ b/sdks/typescript/examples/run-all-tests.ts@@ -53,6 +53,7 @@ const SUITES: TestSuite[] = [{ name: "Domain/TLS", file: "test-domain-tls.ts", description: "Subdomains, Let's Encrypt certs, routing isolation" },{ name: "Concurrent", file: "test-concurrent.ts", description: "5 sandboxes in parallel, isolation, parallel ops" },{ name: "Hibernation", file: "test-hibernation-stress.ts", description: "Multi-cycle hibernate/wake, large state, auto-wake" },+ { name: "Checkpoints", file: "test-checkpoints.ts", description: "Create, list, restore, fork, delete checkpoints, limits" },{ name: "Timeout", file: "test-timeout.ts", slow: true, description: "30s timeout, setTimeout(), rolling timeout (takes ~2min)" },];diff --git a/sdks/typescript/examples/test-checkpoints.ts b/sdks/typescript/examples/test-checkpoints.tsnew file mode 100644index 00000000..5455a5a6--- /dev/null+++ b/sdks/typescript/examples/test-checkpoints.ts@@ -0,0 +1,244 @@+/**+ * Checkpoint Feature Test+ *+ * Tests:+ * 1. Create a named checkpoint of a running sandbox+ * 2. List checkpoints+ * 3. Create a second checkpoint with different state+ * 4. Restore to first checkpoint (in-place revert)+ * 5. Verify state was reverted+ * 6. Fork a new sandbox from a checkpoint+ * 7. Verify forked sandbox has checkpoint state+ * 8. Delete a checkpoint+ * 9. Duplicate name is rejected+ * 10. Max 10 checkpoint limit+ *+ * Usage:+ * npx tsx examples/test-checkpoints.ts+ */++import { Sandbox } from "../src/index";++function green(msg: string) { console.log(`\x1b[32m\u2713 ${msg}\x1b[0m`); }+function red(msg: string) { console.log(`\x1b[31m\u2717 ${msg}\x1b[0m`); }+function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }+function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }++let passed = 0;+let failed = 0;++function check(desc: string, condition: boolean, detail?: string) {+ if (condition) {+ green(desc);+ passed++;+ } else {+ red(`${desc}${detail ? ` (${detail})` : ""}`);+ failed++;+ }+}++async function sleep(ms: number) {+ return new Promise((r) => globalThis.setTimeout(r, ms));+}++async function waitForCheckpointReady(sandbox: Sandbox, checkpointId: string, timeoutMs = 60000): Promise<boolean> {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ const checkpoints = await sandbox.listCheckpoints();+ const cp = checkpoints.find((c) => c.id === checkpointId);+ if (cp && cp.status === "ready") return true;+ if (cp && cp.status !== "processing") return false; // failed or other+ await sleep(2000);+ }+ return false;+}++async function main() {+ bold("\n\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");+ bold("\u2551 Checkpoint Feature Test \u2551");+ bold("\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n");++ let sandbox: Sandbox | null = null;+ let forkedSandbox: Sandbox | null = null;++ try {+ // ── Setup: Create sandbox and write initial state ──────────────+ bold("━━━ Setup: Create sandbox ━━━\n");++ sandbox = await Sandbox.create({ template: "base", timeout: 300 });+ green(`Created sandbox: ${sandbox.sandboxId}`);++ // Write a marker file so we can verify state after restore+ await sandbox.commands.run("echo version-1 > /workspace/marker.txt");+ const v1 = await sandbox.commands.run("cat /workspace/marker.txt");+ check("Initial state written", v1.stdout.trim() === "version-1");+ console.log();++ // ── Test 1: Create first checkpoint ───────────────────────────+ bold("━━━ Test 1: Create checkpoint ━━━\n");++ const cp1 = await sandbox.createCheckpoint("v1-baseline");+ check("Checkpoint created", cp1.id !== undefined && cp1.id.length > 0);+ check("Checkpoint name is correct", cp1.name === "v1-baseline");+ check("Checkpoint status is processing or ready", cp1.status === "processing" || cp1.status === "ready");+ dim(`Checkpoint ID: ${cp1.id}`);+ console.log();++ // ── Test 2: List checkpoints ──────────────────────────────────+ bold("━━━ Test 2: List checkpoints ━━━\n");++ const list1 = await sandbox.listCheckpoints();+ check("List returns 1 checkpoint", list1.length === 1, `got ${list1.length}`);+ check("Listed checkpoint has correct name", list1[0]?.name === "v1-baseline");+ console.log();++ // ── Test 3: Modify state and create second checkpoint ─────────+ bold("━━━ Test 3: Create second checkpoint with different state ━━━\n");++ await sandbox.commands.run("echo version-2 > /workspace/marker.txt");+ await sandbox.commands.run("echo extra-data > /workspace/extra.txt");+ const v2 = await sandbox.commands.run("cat /workspace/marker.txt");+ check("State modified to version-2", v2.stdout.trim() === "version-2");++ const cp2 = await sandbox.createCheckpoint("v2-modified");+ check("Second checkpoint created", cp2.id !== undefined);+ dim(`Checkpoint ID: ${cp2.id}`);++ const list2 = await sandbox.listCheckpoints();+ check("List now returns 2 checkpoints", list2.length === 2, `got ${list2.length}`);+ console.log();++ // ── Test 4: Wait for first checkpoint to be ready ─────────────+ bold("━━━ Test 4: Wait for checkpoint ready ━━━\n");++ dim("Waiting for v1-baseline checkpoint to become ready...");+ const cp1Ready = await waitForCheckpointReady(sandbox, cp1.id);+ check("First checkpoint is ready", cp1Ready);++ if (!cp1Ready) {+ red("Cannot proceed with restore tests - checkpoint not ready");+ throw new Error("Checkpoint not ready");+ }+ console.log();++ // ── Test 5: Restore to first checkpoint ───────────────────────+ bold("━━━ Test 5: Restore to v1-baseline checkpoint ━━━\n");++ dim("Restoring sandbox to v1-baseline...");+ await sandbox.restoreCheckpoint(cp1.id);+ green("Restore completed");++ // Wait a moment for the VM to boot+ await sleep(3000);++ // Verify state was reverted+ const restored = await sandbox.commands.run("cat /workspace/marker.txt");+ check("Marker file reverted to version-1", restored.stdout.trim() === "version-1", `got: ${restored.stdout.trim()}`);++ // The extra.txt should NOT exist since it was created after v1+ const extraCheck = await sandbox.commands.run("test -f /workspace/extra.txt && echo exists || echo missing");+ check("Extra file does not exist after restore", extraCheck.stdout.trim() === "missing", `got: ${extraCheck.stdout.trim()}`);+ console.log();++ // ── Test 6: Wait for second checkpoint and fork ───────────────+ bold("━━━ Test 6: Fork new sandbox from v2-modified checkpoint ━━━\n");++ dim("Waiting for v2-modified checkpoint to become ready...");+ const cp2Ready = await waitForCheckpointReady(sandbox, cp2.id);+ check("Second checkpoint is ready", cp2Ready);++ if (cp2Ready) {+ dim("Creating new sandbox from v2-modified checkpoint...");+ forkedSandbox = await Sandbox.createFromCheckpoint(cp2.id);+ green(`Forked sandbox created: ${forkedSandbox.sandboxId}`);+ check("Forked sandbox has different ID", forkedSandbox.sandboxId !== sandbox.sandboxId);++ // Wait for forked sandbox to be ready+ await sleep(3000);++ // Verify the forked sandbox has v2 state+ const forkedMarker = await forkedSandbox.commands.run("cat /workspace/marker.txt");+ check("Forked sandbox has version-2 state", forkedMarker.stdout.trim() === "version-2", `got: ${forkedMarker.stdout.trim()}`);++ const forkedExtra = await forkedSandbox.commands.run("cat /workspace/extra.txt");+ check("Forked sandbox has extra.txt", forkedExtra.stdout.trim() === "extra-data", `got: ${forkedExtra.stdout.trim()}`);+ } else {+ dim("Skipping fork test - checkpoint not ready");+ }+ console.log();++ // ── Test 7: Delete a checkpoint ───────────────────────────────+ bold("━━━ Test 7: Delete checkpoint ━━━\n");++ await sandbox.deleteCheckpoint(cp2.id);+ green("Deleted v2-modified checkpoint");++ const listAfterDelete = await sandbox.listCheckpoints();+ check("List returns 1 checkpoint after delete", listAfterDelete.length === 1, `got ${listAfterDelete.length}`);+ check("Remaining checkpoint is v1-baseline", listAfterDelete[0]?.name === "v1-baseline");+ console.log();++ // ── Test 8: Duplicate name rejected ───────────────────────────+ bold("━━━ Test 8: Duplicate checkpoint name ━━━\n");++ try {+ await sandbox.createCheckpoint("v1-baseline");+ red("Should have rejected duplicate name");+ failed++;+ } catch (err: any) {+ check("Duplicate name rejected with error", err.message.includes("409") || err.message.includes("already exists"), err.message);+ }+ console.log();++ // ── Test 9: Max 10 checkpoints limit ──────────────────────────+ bold("━━━ Test 9: Max checkpoint limit ━━━\n");++ // We already have 1 checkpoint (v1-baseline), create 9 more to hit the limit+ dim("Creating 9 more checkpoints to reach the limit...");+ for (let i = 2; i <= 10; i++) {+ try {+ await sandbox.createCheckpoint(`limit-test-${i}`);+ } catch (err: any) {+ red(`Failed to create checkpoint limit-test-${i}: ${err.message}`);+ failed++;+ }+ }++ const listFull = await sandbox.listCheckpoints();+ check("10 checkpoints exist", listFull.length === 10, `got ${listFull.length}`);++ // The 11th should fail+ try {+ await sandbox.createCheckpoint("one-too-many");+ red("Should have rejected 11th checkpoint");+ failed++;+ } catch (err: any) {+ check("11th checkpoint rejected (max 10)", err.message.includes("400") || err.message.includes("maximum"), err.message);+ }+ console.log();++ } catch (err: any) {+ red(`Fatal error: ${err.message}`);+ if (err.stack) dim(err.stack);+ failed++;+ } finally {+ // Cleanup+ if (forkedSandbox) {+ try { await forkedSandbox.kill(); green("Forked sandbox killed"); } catch { /* best effort */ }+ }+ if (sandbox) {+ try { await sandbox.kill(); green("Original sandbox killed"); } catch { /* best effort */ }+ }+ }++ // --- Summary ---+ bold("========================================");+ bold(` Results: ${passed} passed, ${failed} failed`);+ bold("========================================\n");+ if (failed > 0) process.exit(1);+}++main().catch((err) => {+ console.error("Fatal error:", err);+ process.exit(1);+});diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsindex cc7ebe84..cde2dfd4 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -1,4 +1,4 @@-export { Sandbox, type SandboxOpts } from "./sandbox.js";+export { Sandbox, type SandboxOpts, type CheckpointInfo } from "./sandbox.js";export { Filesystem, type EntryInfo } from "./filesystem.js";export { Commands, type ProcessResult, type RunOpts } from "./commands.js";export { Pty, type PtySession, type PtyOpts } from "./pty.js";diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex 5e207f91..37af3501 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -26,6 +26,19 @@ interface SandboxData {token?: string;}+export interface CheckpointInfo {+ id: string;+ sandboxId: string;+ orgId: string;+ name: string;+ rootfsS3Key?: string;+ workspaceS3Key?: string;+ sandboxConfig: Record<string, unknown>;+ status: string;+ sizeBytes: number;+ createdAt: string;+}+export interface PreviewURLResult {id: string;sandboxId: string;@@ -207,6 +220,101 @@ export class Sandbox {}}+ async createCheckpoint(name: string): Promise<CheckpointInfo> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ body: JSON.stringify({ name }),+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to create checkpoint: ${resp.status} ${text}`);+ }++ return resp.json();+ }++ async listCheckpoints(): Promise<CheckpointInfo[]> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints`, {+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });++ if (!resp.ok) {+ throw new Error(`Failed to list checkpoints: ${resp.status}`);+ }++ return resp.json();+ }++ async restoreCheckpoint(checkpointId: string): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}/restore`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),+ },+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to restore checkpoint: ${resp.status} ${text}`);+ }++ // After restore, rebuild ops clients since the VM was rebooted+ const data: SandboxData = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ }).then((r) => r.json());++ this.connectUrl = data.connectURL || "";+ this.token = data.token || "";+ const opsUrl = this.connectUrl || this.apiUrl;+ const opsKey = this.connectUrl ? "" : this.apiKey;+ const opsToken = this.connectUrl ? this.token : "";+ (this as any).files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);+ (this as any).commands = new Commands(opsUrl, opsKey, this.sandboxId, opsToken);+ (this as any).pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);+ }++ static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout"> = {}): Promise<Sandbox> {+ const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");+ const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";++ const body: Record<string, unknown> = {};+ if (opts.timeout != null) body.timeout = opts.timeout;++ const resp = await fetch(`${apiUrl}/sandboxes/from-checkpoint/${checkpointId}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(apiKey ? { "X-API-Key": apiKey } : {}),+ },+ body: JSON.stringify(body),+ });++ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to create sandbox from checkpoint: ${resp.status} ${text}`);+ }++ const data: SandboxData = await resp.json();+ return new Sandbox(data, apiUrl, apiKey);+ }++ async deleteCheckpoint(checkpointId: string): Promise<void> {+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/checkpoints/${checkpointId}`, {+ method: "DELETE",+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},+ });++ if (!resp.ok && resp.status !== 404) {+ throw new Error(`Failed to delete checkpoint: ${resp.status}`);+ }+ }+async createPreviewURL(opts: { port: number; domain?: string; authConfig?: Record<string, unknown> }): Promise<PreviewURLResult> {const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {method: "POST",