Skip to content

An open-source, faster Devin alternative

TypeScript

fix(billing): pre-create sandbox session to fix scale event race (#173)

Mohamed Habibceb4981a1431
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 167d99d3..a1703f0c 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -458,7 +458,27 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
requestedMemoryMB := cfg.MemoryMB
requestedCpuCount := cfg.CpuCount
+ // Pre-generate sandbox ID so we can create the session in PG before the
+ // gRPC call. The worker's RecordScaleEvent needs the org_id from the
+ // session row, which must exist before the worker looks it up.
+ sandboxID := "sb-" + uuid.New().String()[:8]
+
+ // Create session with "pending" status before dispatching to worker.
+ if s.store != nil && hasOrg {
+ template := cfg.Template
+ if template == "" {
+ template = "default"
+ }
+ cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))
+ metadataJSON, _ := json.Marshal(cfg.Metadata)
+ _, _ = s.store.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, auth.GetUserID(c), template, region, worker.ID, cfgJSON, metadataJSON, "pending")
+ if templateID != nil {
+ _ = s.store.UpdateSandboxSessionTemplate(ctx, sandboxID, *templateID)
+ }
+ }
+
grpcResp, err := grpcClient.CreateSandbox(grpcCtx, &pb.CreateSandboxRequest{
+ SandboxId: sandboxID,
Template: cfg.Template,
Timeout: int32(cfg.Timeout),
Envs: cfg.Envs,
@@ -472,11 +492,21 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
DiskMb: int32(cfg.DiskMB),
})
if err != nil {
+ // Mark session as failed so it doesn't count as active.
+ if s.store != nil {
+ errMsg := err.Error()
+ _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "failed", &errMsg)
+ }
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": "worker create failed: " + err.Error(),
})
}
+ // Creation succeeded — promote session to running.
+ if s.store != nil {
+ _ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "running", nil)
+ }
+
// Scale to requested resources after creation (virtio-mem hotplug + cgroup).
// Golden snapshot has fixed CPU/RAM — we create with defaults then scale up.
if requestedMemoryMB > 0 || requestedCpuCount > 0 {
@@ -519,20 +549,6 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
}
}
- // Record session in PG
- if s.store != nil && hasOrg {
- template := cfg.Template
- if template == "" {
- template = "default"
- }
- cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))
- metadataJSON, _ := json.Marshal(cfg.Metadata)
- _, _ = s.store.CreateSandboxSession(ctx, grpcResp.SandboxId, orgID, auth.GetUserID(c), template, region, worker.ID, cfgJSON, metadataJSON)
- if templateID != nil {
- _ = s.store.UpdateSandboxSessionTemplate(ctx, grpcResp.SandboxId, *templateID)
- }
- }
-
s.emitEvent("create", grpcResp.SandboxId, worker.ID, fmt.Sprintf("created on %s", worker.ID[len(worker.ID)-8:]))
resp := map[string]interface{}{
diff --git a/internal/db/store.go b/internal/db/store.go
index 5551d1a2..13b90998 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -481,12 +481,16 @@ type SandboxSession struct {
}
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) {
+ return s.CreateSandboxSessionWithStatus(ctx, sandboxID, orgID, userID, template, region, workerID, config, metadata, "running")
+}
+
+func (s *Store) CreateSandboxSessionWithStatus(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage, status string) (*SandboxSession, error) {
session := &SandboxSession{}
err := 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)
+ `INSERT INTO sandbox_sessions (sandbox_id, org_id, user_id, template, region, worker_id, config, metadata, status)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, based_on_checkpoint_id, last_patch_sequence`,
- sandboxID, orgID, userID, template, region, workerID, config, metadata,
+ sandboxID, orgID, userID, template, region, workerID, config, metadata, status,
).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)
@@ -502,6 +506,14 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu
if status == "stopped" || status == "error" {
query = `UPDATE sandbox_sessions SET status = $1, stopped_at = now(), error_msg = $2 WHERE sandbox_id = $3 AND status = 'running'`
args = []interface{}{status, errorMsg, sandboxID}
+ } else if status == "failed" {
+ // Pending → failed: creation never succeeded, record the error.
+ query = `UPDATE sandbox_sessions SET status = $1, stopped_at = now(), error_msg = $2 WHERE sandbox_id = $3 AND status = 'pending'`
+ args = []interface{}{status, errorMsg, sandboxID}
+ } else if status == "running" {
+ // Pending → running: creation succeeded, promote the session.
+ query = `UPDATE sandbox_sessions SET status = $1 WHERE sandbox_id = $2 AND status IN ('running', 'pending')`
+ args = []interface{}{status, sandboxID}
} else if status == "hibernated" {
// Hibernated sandboxes are not stopped — don't set stopped_at
query = `UPDATE sandbox_sessions SET status = $1 WHERE sandbox_id = $2 AND status = 'running'`