Skip to content

An open-source, faster Devin alternative

TypeScript

golden snapshot for templates, and some other fixes

Brian Reardonc5074adcc27e
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.go
index 6a7c4d05..567228e8 100644
--- a/internal/api/image_builder.go
+++ b/internal/api/image_builder.go
@@ -460,8 +460,9 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag
defer cancel()
resp, err := grpcClient.CreateCheckpoint(cpCtx, &pb.CreateCheckpointRequest{
- SandboxId: buildSandboxID,
- CheckpointId: checkpointID.String(),
+ SandboxId: buildSandboxID,
+ CheckpointId: checkpointID.String(),
+ PrepareGolden: true, // prepare golden snapshot for instant template creates
})
if err != nil {
return uuid.Nil, fmt.Errorf("failed to checkpoint build sandbox: %w", err)
@@ -490,6 +491,14 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag
if s.store != nil {
_ = s.store.SetCheckpointReady(ctx, checkpointID, rootfsKey, workspaceKey, 0)
}
+
+ // Prepare golden snapshot for combined mode
+ type goldenPreparer interface {
+ RegisterTemplateGoldenFromCache(checkpointID string)
+ }
+ if gp, ok := s.manager.(goldenPreparer); ok {
+ go gp.RegisterTemplateGoldenFromCache(checkpointID.String())
+ }
}
return checkpointID, nil
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index e576f042..eae6289e 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -898,10 +898,15 @@ func (s *Server) createCheckpoint(c echo.Context) error {
// Dispatch checkpoint creation in background — return immediately with status "processing".
// The heavy work (SyncFS + pause + memory snapshot + drive copy + resume + S3 upload)
- // runs async. Clients poll listCheckpoints for status=ready.
+ // runs async. The sandbox is registered as pending so exec requests block until the VM
+ // resumes, rather than failing with 500.
+ pending := &pendingCreate{ready: make(chan struct{})}
+ s.pendingCreates.Store(sandboxID, pending)
+
if s.workerRegistry != nil {
grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
if err != nil {
+ s.pendingCreates.Delete(sandboxID)
return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker not available: " + err.Error()})
}
@@ -913,11 +918,19 @@ func (s *Server) createCheckpoint(c echo.Context) error {
SandboxId: sandboxID,
CheckpointId: checkpointID.String(),
})
+
+ // Signal that the sandbox is usable again (VM resumed, agent reconnected).
+ // This unblocks any exec/file requests that arrived during the checkpoint pause.
+ pending.err = err
+ close(pending.ready)
+
if err != nil {
log.Printf("api: async checkpoint %s failed: %v", checkpointID, err)
_ = s.store.SetCheckpointFailed(context.Background(), checkpointID, err.Error())
return
}
+ // Mark ready immediately — S3 upload continues async inside CreateCheckpoint
+ // but the checkpoint is locally usable now.
_ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, 0)
log.Printf("api: checkpoint %s ready", checkpointID)
}()
@@ -927,6 +940,11 @@ func (s *Server) createCheckpoint(c echo.Context) error {
defer cancel()
rootfsKey, workspaceKey, err := s.manager.CreateCheckpoint(bgCtx, sandboxID, checkpointID.String(), s.checkpointStore, func() {})
+
+ // Signal sandbox usable
+ pending.err = err
+ close(pending.ready)
+
if err != nil {
log.Printf("api: async checkpoint %s failed: %v", checkpointID, err)
_ = s.store.SetCheckpointFailed(context.Background(), checkpointID, err.Error())
@@ -936,6 +954,7 @@ func (s *Server) createCheckpoint(c echo.Context) error {
log.Printf("api: checkpoint %s ready", checkpointID)
}()
} else {
+ s.pendingCreates.Delete(sandboxID)
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
@@ -1216,6 +1235,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
cfg.TemplateRootfsKey = *cp.RootfsS3Key
cfg.TemplateWorkspaceKey = *cp.WorkspaceS3Key
cfg.SandboxID = sandboxID
+ cfg.CheckpointID = checkpointID.String()
forkMgr, hasFork := s.manager.(interface {
ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 22c6337d..6bc15b70 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -93,8 +93,9 @@ type Manager struct {
nextCID uint32 // next guest CID to assign (starts at 3, 0-2 are reserved)
uploadWg sync.WaitGroup // tracks in-flight async S3 uploads
- goldenMu sync.RWMutex
- golden *GoldenSnapshot // pre-booted default VM snapshot for fast creation
+ goldenMu sync.RWMutex
+ golden *GoldenSnapshot // pre-booted default VM snapshot for fast creation
+ templateGoldens map[string]*GoldenSnapshot // per-checkpoint golden snapshots for templates/images
}
// NewManager creates a new Firecracker-backed sandbox manager.
@@ -140,10 +141,11 @@ func NewManager(cfg Config) (*Manager, error) {
}
return &Manager{
- cfg: cfg,
- subnets: NewSubnetAllocator(),
- vms: make(map[string]*VMInstance),
- nextCID: 3, // CIDs 0-2 are reserved (hypervisor=0, local=1, host=2)
+ cfg: cfg,
+ subnets: NewSubnetAllocator(),
+ vms: make(map[string]*VMInstance),
+ nextCID: 3, // CIDs 0-2 are reserved (hypervisor=0, local=1, host=2)
+ templateGoldens: make(map[string]*GoldenSnapshot),
}, nil
}
@@ -180,6 +182,15 @@ func (m *Manager) createWithID(ctx context.Context, id string, cfg types.Sandbox
log.Printf("firecracker: golden snapshot create failed for %s: %v, falling back to cold boot", id, err)
}
}
+ // Per-template golden snapshot: if creating from a checkpoint (image/snapshot),
+ // try the golden snapshot path keyed by checkpoint ID.
+ if cfg.CheckpointID != "" && cfg.TemplateRootfsKey != "" {
+ if sb, err := m.createFromGoldenSnapshot(ctx, id, cfg); err == nil {
+ return sb, nil
+ } else if err != errNoGoldenSnapshot {
+ log.Printf("firecracker: template golden snapshot create failed for %s (cp=%s): %v, falling back to cold boot", id, cfg.CheckpointID, err)
+ }
+ }
sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", id)
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
index ebaa3801..434094d8 100644
--- a/internal/firecracker/snapshot.go
+++ b/internal/firecracker/snapshot.go
@@ -2230,11 +2230,97 @@ func (m *Manager) PrepareGoldenSnapshot() error {
return nil
}
+// registerTemplateGoldenFromCache creates a per-checkpoint golden snapshot by reflink-copying
+// files from the checkpoint cache. Called after CreateCheckpoint when the checkpoint is for
+// an image/snapshot build. All copies are reflink (instant CoW) — no extra VM boot needed.
+func (m *Manager) RegisterTemplateGoldenFromCache(checkpointID string) {
+ m.goldenMu.RLock()
+ existing := m.templateGoldens[checkpointID]
+ m.goldenMu.RUnlock()
+ if existing != nil {
+ return
+ }
+
+ t0 := time.Now()
+ cacheDir := m.checkpointCacheDir(checkpointID)
+ goldenDir := filepath.Join(m.cfg.DataDir, "golden-snapshot", "template-"+checkpointID)
+
+ // Verify checkpoint cache has all required files
+ requiredFiles := []string{
+ filepath.Join(cacheDir, "rootfs.ext4"),
+ filepath.Join(cacheDir, "workspace.ext4"),
+ filepath.Join(cacheDir, "snapshot", "mem"),
+ filepath.Join(cacheDir, "snapshot", "vmstate"),
+ filepath.Join(cacheDir, "snapshot", "snapshot-meta.json"),
+ }
+ for _, f := range requiredFiles {
+ if !fileExists(f) {
+ log.Printf("firecracker: template golden %s: missing %s, skipping", checkpointID, f)
+ return
+ }
+ }
+
+ os.RemoveAll(goldenDir)
+ if err := os.MkdirAll(filepath.Join(goldenDir, "snapshot"), 0755); err != nil {
+ log.Printf("firecracker: template golden %s: mkdir failed: %v", checkpointID, err)
+ return
+ }
+
+ // Reflink-copy drives and snapshot files (~1ms total with CoW)
+ copies := [][2]string{
+ {filepath.Join(cacheDir, "rootfs.ext4"), filepath.Join(goldenDir, "rootfs.ext4")},
+ {filepath.Join(cacheDir, "workspace.ext4"), filepath.Join(goldenDir, "workspace.ext4")},
+ {filepath.Join(cacheDir, "snapshot", "mem"), filepath.Join(goldenDir, "snapshot", "mem")},
+ {filepath.Join(cacheDir, "snapshot", "vmstate"), filepath.Join(goldenDir, "snapshot", "vmstate")},
+ }
+ for _, cp := range copies {
+ if err := copyFileReflink(cp[0], cp[1]); err != nil {
+ log.Printf("firecracker: template golden %s: copy %s failed: %v", checkpointID, cp[0], err)
+ os.RemoveAll(goldenDir)
+ return
+ }
+ }
+
+ // Read the checkpoint's snapshot metadata and use it for the golden snapshot
+ metaBytes, err := os.ReadFile(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json"))
+ if err != nil {
+ log.Printf("firecracker: template golden %s: read meta failed: %v", checkpointID, err)
+ os.RemoveAll(goldenDir)
+ return
+ }
+ var meta SnapshotMeta
+ if err := json.Unmarshal(metaBytes, &meta); err != nil {
+ log.Printf("firecracker: template golden %s: parse meta failed: %v", checkpointID, err)
+ os.RemoveAll(goldenDir)
+ return
+ }
+
+ // Write golden snapshot metadata (copy to golden dir)
+ _ = os.WriteFile(filepath.Join(goldenDir, "snapshot", "snapshot-meta.json"), metaBytes, 0644)
+
+ gs := &GoldenSnapshot{
+ Dir: goldenDir,
+ Meta: meta,
+ Ready: true,
+ }
+ m.goldenMu.Lock()
+ m.templateGoldens[checkpointID] = gs
+ m.goldenMu.Unlock()
+
+ log.Printf("firecracker: template golden snapshot ready for %s at %s (%dms)", checkpointID, goldenDir, time.Since(t0).Milliseconds())
+}
+
// createFromGoldenSnapshot creates a new sandbox using the pre-booted golden snapshot.
// Returns errNoGoldenSnapshot if no golden snapshot is available.
func (m *Manager) createFromGoldenSnapshot(ctx context.Context, id string, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ // Pick the right golden snapshot: per-template if CheckpointID is set, otherwise the default.
m.goldenMu.RLock()
- gs := m.golden
+ var gs *GoldenSnapshot
+ if cfg.CheckpointID != "" {
+ gs = m.templateGoldens[cfg.CheckpointID]
+ } else {
+ gs = m.golden
+ }
m.goldenMu.RUnlock()
if gs == nil || !gs.Ready {
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 9b2d1fd3..10a4d779 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -88,7 +88,8 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
NetworkEnabled: req.NetworkEnabled,
ImageRef: req.ImageRef,
Port: int(req.Port),
- SandboxID: req.SandboxId, // use server-assigned ID if provided
+ SandboxID: req.SandboxId, // use server-assigned ID if provided
+ CheckpointID: req.CheckpointId, // for per-template golden snapshots
}
// Warm fork: if checkpoint_id is set, try snapshot-based fork first.
@@ -514,7 +515,10 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpo
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.
+ // The onReady callback fires after the async mem file move + S3 upload completes.
+ // If prepare_golden is set, it also creates a golden snapshot from the cache.
+ prepareGolden := req.PrepareGolden
+ mgr := s.manager
var onReady func()
if s.store != nil {
cpID, _ := uuid.Parse(checkpointID)
@@ -524,6 +528,24 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpo
} else {
log.Printf("grpc: CreateCheckpoint: checkpoint %s is now ready", checkpointID)
}
+ // Create golden snapshot after mem file is in place
+ if prepareGolden {
+ type goldenPreparer interface {
+ RegisterTemplateGoldenFromCache(checkpointID string)
+ }
+ if gp, ok := mgr.(goldenPreparer); ok {
+ gp.RegisterTemplateGoldenFromCache(checkpointID)
+ }
+ }
+ }
+ } else if prepareGolden {
+ onReady = func() {
+ type goldenPreparer interface {
+ RegisterTemplateGoldenFromCache(checkpointID string)
+ }
+ if gp, ok := mgr.(goldenPreparer); ok {
+ gp.RegisterTemplateGoldenFromCache(checkpointID)
+ }
}
}
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index a64be3af..243520f9 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -58,6 +58,9 @@ type SandboxConfig struct {
// SandboxID allows pre-determining the sandbox ID for async creation.
// If empty, a new ID is generated automatically.
SandboxID string `json:"-"`
+ // CheckpointID is the source checkpoint for template/snapshot creates.
+ // Used by the worker to key per-template golden snapshots.
+ CheckpointID string `json:"-"`
}
// SandboxListResponse is the response for listing sandboxes.
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 4e096f66..a53cb728 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
-// protoc v7.34.0
+// protoc v6.33.4
// source: proto/worker/worker.proto
package worker
@@ -2375,7 +2375,8 @@ func (x *GetSandboxStatsResponse) GetPids() int32 {
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
+ CheckpointId string `protobuf:"bytes,2,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"` // UUID assigned by control plane
+ PrepareGolden bool `protobuf:"varint,3,opt,name=prepare_golden,json=prepareGolden,proto3" json:"prepare_golden,omitempty"` // If true, also create a per-template golden snapshot for fast future creates
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -2424,6 +2425,13 @@ func (x *CreateCheckpointRequest) GetCheckpointId() string {
return ""
}
+func (x *CreateCheckpointRequest) GetPrepareGolden() bool {
+ if x != nil {
+ return x.PrepareGolden
+ }
+ return false
+}
+
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"`
@@ -2769,11 +2777,12 @@ 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\x04pids\"]\n" +
+ "\x04pids\x18\x06 \x01(\x05R\x04pids\"\x84\x01\n" +
"\x17CreateCheckpointRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +
- "\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\"h\n" +
+ "\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\x12%\n" +
+ "\x0eprepare_golden\x18\x03 \x01(\bR\rprepareGolden\"h\n" +
"\x18CreateCheckpointResponse\x12\"\n" +
"\rrootfs_s3_key\x18\x01 \x01(\tR\vrootfsS3Key\x12(\n" +
"\x10workspace_s3_key\x18\x02 \x01(\tR\x0eworkspaceS3Key\"^\n" +
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 91acad5f..d3da2db1 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -273,6 +273,7 @@ message GetSandboxStatsResponse {
message CreateCheckpointRequest {
string sandbox_id = 1;
string checkpoint_id = 2; // UUID assigned by control plane
+ bool prepare_golden = 3; // If true, also create a per-template golden snapshot for fast future creates
}
message CreateCheckpointResponse {
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index 9696af6d..99375341 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
-// - protoc v7.34.0
+// - protoc v6.33.4
// source: proto/worker/worker.proto
package worker