An open-source, faster Devin alternative
TypeScript
move snapshot patches to diff off of main
Brian Reardon7c1b6545c13b
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.goindex fcb4ca01..744a3d26 100644--- a/internal/api/image_builder.go+++ b/internal/api/image_builder.go@@ -22,6 +22,7 @@ import (type ImageManifest struct {Base string `json:"base"`Steps []ImageStep `json:"steps"`+ Name string `json:"name,omitempty"` // optional — makes image addressable as a snapshot (for patches, etc.)}// ImageStep is a single build step in an image manifest.@@ -44,9 +45,13 @@ type imageBuild struct {}// computeManifestHash returns a deterministic SHA-256 hash for the manifest.+// The Name field is excluded so that naming an image doesn't change its cache key.func computeManifestHash(manifest *ImageManifest) string {- // Canonical JSON: marshal with sorted keys (Go's encoding/json sorts map keys)- data, _ := json.Marshal(manifest)+ hashInput := struct {+ Base string `json:"base"`+ Steps []ImageStep `json:"steps"`+ }{Base: manifest.Base, Steps: manifest.Steps}+ data, _ := json.Marshal(hashInput)sum := sha256.Sum256(data)return hex.EncodeToString(sum[:])}@@ -221,28 +226,33 @@ func (s *Server) resolveImageManifest(ctx context.Context, orgID uuid.UUID, manilog.Printf("image-builder: cache hit for hash %s but checkpoint %s is invalid, rebuilding",contentHash[:12], cached.CheckpointID)_ = s.store.DeleteImageCache(ctx, orgID, cached.ID)- } else if s.checkpointStore != nil {- if exists, _ := s.checkpointStore.Exists(ctx, *cp.RootfsS3Key); !exists {- log.Printf("image-builder: cache hit for hash %s but S3 object missing for checkpoint %s, rebuilding",- contentHash[:12], cached.CheckpointID)- _ = s.store.DeleteImageCache(ctx, orgID, cached.ID)- } else {- // Cache hit is valid+ } else {+ validHit := s.checkpointStore == nil+ if !validHit {+ if exists, _ := s.checkpointStore.Exists(ctx, *cp.RootfsS3Key); exists {+ validHit = true+ } else {+ log.Printf("image-builder: cache hit for hash %s but S3 object missing for checkpoint %s, rebuilding",+ contentHash[:12], cached.CheckpointID)+ _ = s.store.DeleteImageCache(ctx, orgID, cached.ID)+ }+ }+ if validHit {_ = s.store.TouchImageCacheUsage(ctx, cached.ID)+ // If manifest includes a name, assign it to the cached entry (makes it addressable as a snapshot)+ if manifest.Name != "" && (cached.Name == nil || *cached.Name != manifest.Name) {+ if err := s.store.SetImageCacheName(ctx, cached.ID, orgID, manifest.Name); err != nil {+ log.Printf("image-builder: failed to set name %q on cache entry: %v", manifest.Name, err)+ } else {+ log.Printf("image-builder: named cache entry %s as %q", cached.ID, manifest.Name)+ }+ }log.Printf("image-builder: cache hit for hash %s (checkpoint=%s)", contentHash[:12], cached.CheckpointID)if logFn != nil {logFn(0, "cache_hit", fmt.Sprintf("Image found in cache (hash=%s)", contentHash[:12]))}return *cached.CheckpointID, nil}- } else {- // No checkpoint store — trust the cache- _ = s.store.TouchImageCacheUsage(ctx, cached.ID)- log.Printf("image-builder: cache hit for hash %s (checkpoint=%s)", contentHash[:12], cached.CheckpointID)- if logFn != nil {- logFn(0, "cache_hit", fmt.Sprintf("Image found in cache (hash=%s)", contentHash[:12]))- }- return *cached.CheckpointID, nil}}if err == nil && cached.Status == "building" {diff --git a/internal/api/router.go b/internal/api/router.goindex f95f2f5f..e9b715e6 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -299,6 +299,19 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/snapshots/:name", s.getSnapshot)api.DELETE("/snapshots/:name", s.deleteSnapshot)+ // Snapshot patches (resolve snapshot name → checkpoint, then delegate to checkpoint patch logic)+ api.POST("/snapshots/:name/patches", s.createSnapshotPatch)+ api.GET("/snapshots/:name/patches", s.listSnapshotPatches)+ api.DELETE("/snapshots/:name/patches/:patchId", s.deleteSnapshotPatch)++ // Images (all cached images, named or unnamed)+ api.GET("/images", s.listImages)++ // Image patches — by name or by ID+ api.POST("/images/:name/patches", s.createImagePatch)+ api.GET("/images/:name/patches", s.listImagePatches)+ api.DELETE("/images/:name/patches/:patchId", s.deleteImagePatch)+// Secret storesapi.POST("/secret-stores", s.createSecretStore)api.GET("/secret-stores", s.listSecretStores)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 8f5f0ae3..53bc6b0e 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -631,6 +631,9 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {if s.sandboxDomain != "" {resp["sandboxDomain"] = s.sandboxDomain}+ if session.PatchError != nil {+ resp["patchError"] = *session.PatchError+ }return c.JSON(http.StatusOK, resp)}@@ -2357,14 +2360,24 @@ func (s *Server) applyPendingPatches(sandboxID, workerID string) {log.Printf("patches: %s: applying %d pending patches (from seq %d)", sandboxID, len(patches), session.LastPatchSequence+1)+ // Clear any previous patch error before applying+ _ = s.store.SetSandboxPatchError(ctx, sandboxID, nil)+for _, patch := range patches {if err := s.execPatchOnSandbox(ctx, sandboxID, workerID, &patch); err != nil {- log.Printf("patches: %s: patch seq %d failed: %v (stopping)", sandboxID, patch.Sequence, err)+ errMsg := fmt.Sprintf("patch seq %d failed: %v — delete the bad patch and retry (DELETE /snapshots/:name/patches/:id or DELETE /sandboxes/checkpoints/:id/patches/:id)", patch.Sequence, err)+ log.Printf("patches: %s: %s", sandboxID, errMsg)+ if dbErr := s.store.SetSandboxPatchError(ctx, sandboxID, &errMsg); dbErr != nil {+ log.Printf("patches: %s: failed to save patch error to DB: %v", sandboxID, dbErr)+ }return // Stop on first failure}_ = s.store.UpdateSandboxPatchSequence(ctx, sandboxID, patch.Sequence)log.Printf("patches: %s: patch seq %d applied successfully", sandboxID, patch.Sequence)}++ // All patches applied — clear any stale error+ _ = s.store.SetSandboxPatchError(ctx, sandboxID, nil)}// listCheckpointPatches returns all patches for a checkpoint.diff --git a/internal/api/snapshots.go b/internal/api/snapshots.goindex a8892a00..f464b0df 100644--- a/internal/api/snapshots.go+++ b/internal/api/snapshots.go@@ -237,3 +237,160 @@ func (s *Server) deleteSnapshot(c echo.Context) error {return c.NoContent(http.StatusNoContent)}+func (s *Server) resolveNamedCheckpoint(c echo.Context, label string) (uuid.UUID, error) {+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return uuid.Nil, fmt.Errorf("org context required")+ }++ nameOrID := c.Param("name")+ ctx := c.Request().Context()++ var entry *db.ImageCache+ var err error++ // Try as UUID first (for unnamed images referenced by ID)+ if id, parseErr := uuid.Parse(nameOrID); parseErr == nil {+ entry, err = s.store.GetImageCacheByID(ctx, orgID, id)+ } else {+ entry, err = s.store.GetImageCacheByName(ctx, orgID, nameOrID)+ }++ if err != nil {+ return uuid.Nil, fmt.Errorf("%s %q not found", label, nameOrID)+ }+ if entry.CheckpointID == nil {+ return uuid.Nil, fmt.Errorf("%s %q has no checkpoint", label, nameOrID)+ }+ return *entry.CheckpointID, nil+}++// listImages handles GET /api/images — lists all images (named and unnamed) for the org.+func (s *Server) listImages(c echo.Context) error {+ 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"})+ }++ images, err := s.store.ListImageCacheByOrg(c.Request().Context(), orgID, false)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ if images == nil {+ images = []db.ImageCache{}+ }+ return c.JSON(http.StatusOK, images)+}++// resolveSnapshotCheckpoint resolves a snapshot name to its underlying checkpoint ID.+func (s *Server) resolveSnapshotCheckpoint(c echo.Context) (uuid.UUID, error) {+ return s.resolveNamedCheckpoint(c, "snapshot")+}++// createSnapshotPatch adds a patch to a snapshot's underlying checkpoint.+// POST /api/snapshots/:name/patches+func (s *Server) createSnapshotPatch(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ checkpointID, err := s.resolveSnapshotCheckpoint(c)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }++ // Delegate to the existing checkpoint patch handler by setting the param+ c.SetParamNames("checkpointId")+ c.SetParamValues(checkpointID.String())+ return s.createCheckpointPatch(c)+}++// listSnapshotPatches lists patches for a snapshot's underlying checkpoint.+// GET /api/snapshots/:name/patches+func (s *Server) listSnapshotPatches(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ checkpointID, err := s.resolveSnapshotCheckpoint(c)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }++ c.SetParamNames("checkpointId")+ c.SetParamValues(checkpointID.String())+ return s.listCheckpointPatches(c)+}++// deleteSnapshotPatch deletes a patch from a snapshot's underlying checkpoint.+// DELETE /api/snapshots/:name/patches/:patchId+func (s *Server) deleteSnapshotPatch(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ checkpointID, err := s.resolveSnapshotCheckpoint(c)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }++ patchId := c.Param("patchId")+ c.SetParamNames("checkpointId", "patchId")+ c.SetParamValues(checkpointID.String(), patchId)+ return s.deleteCheckpointPatch(c)+}++// createImagePatch adds a patch to a named image's underlying checkpoint.+// POST /api/images/:name/patches+func (s *Server) createImagePatch(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ checkpointID, err := s.resolveNamedCheckpoint(c, "image")+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }++ c.SetParamNames("checkpointId")+ c.SetParamValues(checkpointID.String())+ return s.createCheckpointPatch(c)+}++// listImagePatches lists patches for a named image's underlying checkpoint.+// GET /api/images/:name/patches+func (s *Server) listImagePatches(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ checkpointID, err := s.resolveNamedCheckpoint(c, "image")+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }++ c.SetParamNames("checkpointId")+ c.SetParamValues(checkpointID.String())+ return s.listCheckpointPatches(c)+}++// deleteImagePatch deletes a patch from a named image's underlying checkpoint.+// DELETE /api/images/:name/patches/:patchId+func (s *Server) deleteImagePatch(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ checkpointID, err := s.resolveNamedCheckpoint(c, "image")+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})+ }++ patchId := c.Param("patchId")+ c.SetParamNames("checkpointId", "patchId")+ c.SetParamValues(checkpointID.String(), patchId)+ return s.deleteCheckpointPatch(c)+}diff --git a/internal/db/migrations/023_patch_error_tracking.up.sql b/internal/db/migrations/023_patch_error_tracking.up.sqlnew file mode 100644index 00000000..4dd082b6--- /dev/null+++ b/internal/db/migrations/023_patch_error_tracking.up.sql@@ -0,0 +1,2 @@+-- Surface patch errors to users. Cleared on next successful patch application.+ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS patch_error TEXT;diff --git a/internal/db/store.go b/internal/db/store.goindex 6120eeff..b15df44e 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -109,6 +109,7 @@ func (s *Store) Migrate(ctx context.Context) error {{22, "migrations/020_scale_events_disk_mb.up.sql"},{23, "migrations/021_migration_state.up.sql"},{24, "migrations/022_orgs_price_locked.up.sql"},+ {25, "migrations/023_patch_error_tracking.up.sql"},}for _, m := range migrations {@@ -468,6 +469,7 @@ type SandboxSession struct {BasedOnCheckpointID *uuid.UUID `json:"basedOnCheckpointId,omitempty"`LastPatchSequence int `json:"lastPatchSequence"`MigratingToWorker string `json:"migratingToWorker,omitempty"`+ PatchError *string `json:"patchError,omitempty"`}func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage) (*SandboxSession, error) {@@ -475,11 +477,11 @@ func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgIerr := s.pool.QueryRow(ctx,`INSERT INTO sandbox_sessions (sandbox_id, org_id, user_id, template, region, worker_id, config, metadata)VALUES ($1, $2, $3, $4, $5, $6, $7, $8)- RETURNING id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, based_on_checkpoint_id, last_patch_sequence`,+ RETURNING id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, based_on_checkpoint_id, last_patch_sequence, patch_error`,sandboxID, orgID, userID, template, region, workerID, config, metadata,).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata, &session.StartedAt,- &session.BasedOnCheckpointID, &session.LastPatchSequence)+ &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError)if err != nil {return nil, fmt.Errorf("failed to create sandbox session: %w", err)}@@ -600,11 +602,11 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strinfunc (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {session := &SandboxSession{}err := s.pool.QueryRow(ctx,- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_errorFROM sandbox_sessions WHERE sandbox_id = $1 ORDER BY started_at DESC LIMIT 1`, sandboxID,).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,&session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,- &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence)+ &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError)if err != nil {return nil, fmt.Errorf("sandbox session not found: %w", err)}@@ -616,12 +618,12 @@ func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, statusvar err errorif status != "" {rows, err = s.pool.Query(ctx,- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_errorFROM sandbox_sessions WHERE org_id = $1 AND status = $2 ORDER BY started_at DESC LIMIT $3 OFFSET $4`,orgID, status, limit, offset)} else {rows, err = s.pool.Query(ctx,- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_errorFROM sandbox_sessions WHERE org_id = $1 ORDER BY started_at DESC LIMIT $2 OFFSET $3`,orgID, limit, offset)}@@ -635,7 +637,7 @@ func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, statusvar sess SandboxSessionif err := rows.Scan(&sess.ID, &sess.SandboxID, &sess.OrgID, &sess.UserID, &sess.Template,&sess.Region, &sess.WorkerID, &sess.Status, &sess.Config, &sess.Metadata,- &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence); err != nil {+ &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence, &sess.PatchError); err != nil {return nil, err}sessions = append(sessions, sess)@@ -1284,6 +1286,15 @@ func (s *Store) UpdateSandboxPatchSequence(ctx context.Context, sandboxID stringreturn err}+// SetSandboxPatchError sets or clears the patch_error on a sandbox session.+// Pass nil to clear the error (e.g., after a successful patch or patch deletion).+func (s *Store) SetSandboxPatchError(ctx context.Context, sandboxID string, patchError *string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET patch_error = $1 WHERE sandbox_id = $2`,+ patchError, sandboxID)+ return err+}+// SetSandboxCheckpointID sets the based_on_checkpoint_id for a sandbox session.func (s *Store) SetSandboxCheckpointID(ctx context.Context, sandboxID string, checkpointID uuid.UUID) error {_, err := s.pool.Exec(ctx,@@ -1295,7 +1306,7 @@ func (s *Store) SetSandboxCheckpointID(ctx context.Context, sandboxID string, ch// ListSandboxesByCheckpoint returns all non-stopped sandboxes forked from a checkpoint.func (s *Store) ListSandboxesByCheckpoint(ctx context.Context, checkpointID uuid.UUID) ([]SandboxSession, error) {rows, err := s.pool.Query(ctx,- `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence+ `SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_errorFROM sandbox_sessions WHERE based_on_checkpoint_id = $1 AND status IN ('running', 'hibernated') ORDER BY started_at DESC`,checkpointID)if err != nil {@@ -1308,7 +1319,7 @@ func (s *Store) ListSandboxesByCheckpoint(ctx context.Context, checkpointID uuidvar sess SandboxSessionif err := rows.Scan(&sess.ID, &sess.SandboxID, &sess.OrgID, &sess.UserID, &sess.Template,&sess.Region, &sess.WorkerID, &sess.Status, &sess.Config, &sess.Metadata,- &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence); err != nil {+ &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence, &sess.PatchError); err != nil {return nil, err}sessions = append(sessions, sess)@@ -1479,6 +1490,28 @@ func (s *Store) GetImageCacheByName(ctx context.Context, orgID uuid.UUID, name sreturn ic, nil}+// GetImageCacheByID looks up an image cache entry by its ID, scoped to org.+func (s *Store) GetImageCacheByID(ctx context.Context, orgID uuid.UUID, id uuid.UUID) (*ImageCache, error) {+ ic := &ImageCache{}+ err := s.pool.QueryRow(ctx,+ `SELECT id, org_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at+ FROM image_cache WHERE org_id = $1 AND id = $2`,+ orgID, id,+ ).Scan(&ic.ID, &ic.OrgID, &ic.ContentHash, &ic.CheckpointID, &ic.Name, &ic.Manifest, &ic.Status, &ic.CreatedAt, &ic.LastUsedAt)+ if err != nil {+ return nil, fmt.Errorf("image %q not found: %w", id, err)+ }+ return ic, nil+}++// SetImageCacheName assigns a name to an existing cache entry, making it addressable as a snapshot.+func (s *Store) SetImageCacheName(ctx context.Context, id uuid.UUID, orgID uuid.UUID, name string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE image_cache SET name = $1 WHERE id = $2 AND org_id = $3`,+ name, id, orgID)+ return err+}+// CreateImageCache inserts a new image cache record.func (s *Store) CreateImageCache(ctx context.Context, ic *ImageCache) error {return s.pool.QueryRow(ctx,