An open-source, faster Devin alternative
TypeScript
fix(webhooks): review round 2 — pause semantics, failure paths, deterministic ids
Igor Zalutskie9ba834be377
diff --git a/docs/sandboxes/webhooks.mdx b/docs/sandboxes/webhooks.mdxindex e9b4fbb4..ec0b84b3 100644--- a/docs/sandboxes/webhooks.mdx+++ b/docs/sandboxes/webhooks.mdx@@ -34,7 +34,7 @@ Subscribe to all events, or filter with `eventTypes` (exact like `sandbox.stoppe| Event | When | `event.data` || --- | --- | --- |-| `sandbox.created` | the sandbox resource is accepted | `template`, `cpuCount`, `memoryMB` |+| `sandbox.created` | the sandbox resource is accepted | `template` || `sandbox.ready` | the VM has booted and can run commands | — || `sandbox.hibernated` | the sandbox was paused (disk persisted) | — || `sandbox.resumed` | a hibernated sandbox woke | — |diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 24e713bb..96031f4e 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -43,6 +43,12 @@ func (s *Server) createSandbox(c echo.Context) error {ctx := c.Request().Context()+ // Validate inline webhook specs up-front so a typo fails the create instead+ // of silently producing a sandbox without the requested callback (P2 review).+ if err := validateInlineWebhooks(ctx, cfg.Webhooks); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }+// When the edge is the Pro-billing authority (PRO_BILLING_AUTHORITY=edge),// a billing-relevant create must arrive via the edge (cap-token), not a raw// API key hitting the CP directly — the direct path bypasses the edge's@@ -260,8 +266,8 @@ func (s *Server) createSandbox(c echo.Context) error {}// Combined-mode create writes the session directly as 'running' (no// pending→running promotion), so emit sandbox.ready here; the remote- // path emits it in-tx on the promotion.- s.recordLifecycle(ctx, orgID, sb.ID, types.WebhookEventReady, nil)+ // path emits it in-tx on the promotion. Deterministic id → at most one.+ s.recordLifecycleID(ctx, orgID, sb.ID, types.WebhookEventReady, sb.ID+":sandbox.ready", nil)}// Preview-URL auth: same flow as createSandboxRemote — validate the@@ -534,6 +540,20 @@ func flattenSecretAllowedHosts(m map[string][]string) map[string]string {return out}+// isTransientWorkerErr reports whether a worker gRPC error is transient (worker+// restarting / unreachable) and the create should be retried rather than 500'd.+func isTransientWorkerErr(err error) bool {+ if err == nil {+ return false+ }+ s := err.Error()+ return strings.Contains(s, "connection refused") ||+ strings.Contains(s, "Unavailable") ||+ strings.Contains(s, "transport is closing") ||+ strings.Contains(s, "no such host") ||+ strings.Contains(s, "i/o timeout")+}+// createSandboxRemote dispatches sandbox creation to a remote worker via gRPC.// secretStoreID is the resolved store UUID (or nil) from resolveSecretStoreInto;// passed straight to CreateSandboxSessionWithStatus so the row's secret_store_id@@ -682,6 +702,16 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty_ = s.store.SoftDeleteWebhookDestination(ctx, orgID, w.ID)}}+ // A worker that is restarting/unreachable is transient — return a+ // retryable 503 (with Retry-After) instead of a raw 500 so callers retry+ // and the edge can reselect a worker.+ if isTransientWorkerErr(err) {+ c.Response().Header().Set("Retry-After", "2")+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "worker temporarily unavailable, please retry: " + err.Error(),+ "code": "worker_unavailable",+ })+ }return c.JSON(http.StatusInternalServerError, map[string]string{"error": "worker create failed: " + err.Error(),})@@ -2214,11 +2244,14 @@ func (s *Server) createCheckpoint(c echo.Context) error {}// Persist the actual archive size from the worker's response.// Pre-fix this was hardcoded to 0, leaving size_bytes meaningless.- _ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, grpcResp.SizeBytes)- log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, grpcResp.SizeBytes)- s.recordLifecycle(context.Background(), orgID, sandboxID, types.WebhookEventCheckpointCreated, map[string]any{- "checkpointId": checkpointID.String(),- })+ if cperr := s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, grpcResp.SizeBytes); cperr != nil {+ log.Printf("api: checkpoint %s SetCheckpointReady failed: %v", checkpointID, cperr)+ } else {+ log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, grpcResp.SizeBytes)+ s.recordLifecycleID(context.Background(), orgID, sandboxID, types.WebhookEventCheckpointCreated,+ sandboxID+":sandbox.checkpoint.created:"+checkpointID.String(),+ map[string]any{"checkpointId": checkpointID.String()})+ }golden := ""if session.GoldenVersion != nil {golden = *session.GoldenVersion@@ -2257,8 +2290,14 @@ func (s *Server) createCheckpoint(c echo.Context) error {})return}- _ = s.store.SetCheckpointReady(context.Background(), checkpointID, rootfsKey, workspaceKey, sizeBytes)- log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, sizeBytes)+ if cperr := s.store.SetCheckpointReady(context.Background(), checkpointID, rootfsKey, workspaceKey, sizeBytes); cperr != nil {+ log.Printf("api: checkpoint %s SetCheckpointReady failed: %v", checkpointID, cperr)+ } else {+ log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, sizeBytes)+ s.recordLifecycleID(context.Background(), orgID, sandboxID, types.WebhookEventCheckpointCreated,+ sandboxID+":sandbox.checkpoint.created:"+checkpointID.String(),+ map[string]any{"checkpointId": checkpointID.String()})+ }golden := ""if session.GoldenVersion != nil {golden = *session.GoldenVersion@@ -2781,9 +2820,9 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st// Emit sandbox.forked on the child, carrying the parent sandbox id (the// sandbox the checkpoint was taken from). The child also gets created// (worker) + ready (the running promotion above).- s.recordLifecycle(ctx, orgID, sandboxID, types.WebhookEventForked, map[string]any{- "parentId": cp.SandboxID,- })+ s.recordLifecycleID(ctx, orgID, sandboxID, types.WebhookEventForked,+ sandboxID+":sandbox.forked",+ map[string]any{"parentId": cp.SandboxID})}s.applyPendingPatches(sandboxID, workerID)@@ -3366,6 +3405,11 @@ func (s *Server) deletePreviewURL(c echo.Context) error {_ = s.store.DeletePreviewURL(ctx, previewURL.ID)+ if orgID, ok := auth.GetOrgID(c); ok {+ s.recordLifecycle(ctx, orgID, sandboxID, types.WebhookEventPreviewURLChanged, map[string]any{+ "port": port, "url": nil,+ })+ }return c.NoContent(http.StatusNoContent)}diff --git a/internal/api/webhooks.go b/internal/api/webhooks.goindex 4337f6cc..6cb3fe06 100644--- a/internal/api/webhooks.go+++ b/internal/api/webhooks.go@@ -116,11 +116,11 @@ func webhookRequestHash(req types.CreateWebhookRequest) string {return hex.EncodeToString(h.Sum(nil))}-// recordLifecycle records a CP-origin lifecycle event for a sandbox in its own-// transaction. Best-effort: a failure is logged, never fails the request. Used-// for the events the control plane emits directly (ready on the local create-// path, checkpoint.created, forked, scaled, preview_url.changed).-func (s *Server) recordLifecycle(ctx context.Context, orgID uuid.UUID, sandboxID, evType string, data map[string]any) {+// recordLifecycleID records a CP-origin lifecycle event with an explicit,+// caller-supplied event id (use a deterministic id for once-per-entity events so+// ON CONFLICT dedups replays). Own transaction; best-effort (logged, never fails+// the request).+func (s *Server) recordLifecycleID(ctx context.Context, orgID uuid.UUID, sandboxID, evType, id string, data map[string]any) {if s.store == nil || orgID == uuid.Nil || sandboxID == "" {return}@@ -129,7 +129,7 @@ func (s *Server) recordLifecycle(ctx context.Context, orgID uuid.UUID, sandboxIDraw, _ = json.Marshal(data)}if err := s.store.RecordLifecycleEvent(ctx, db.LifecycleEvent{- ID: fmt.Sprintf("%s:%s:%d", sandboxID, evType, time.Now().UnixNano()),+ ID: id,OrgID: orgID,SandboxID: sandboxID,Type: evType,@@ -139,6 +139,14 @@ func (s *Server) recordLifecycle(ctx context.Context, orgID uuid.UUID, sandboxID}}+// recordLifecycle records a recurring CP-origin event (scaled, preview_url.changed)+// — each occurrence is a distinct delivery, so the id is made unique per call.+// (Once-per-entity events use recordLifecycleID with a deterministic id.)+func (s *Server) recordLifecycle(ctx context.Context, orgID uuid.UUID, sandboxID, evType string, data map[string]any) {+ s.recordLifecycleID(ctx, orgID, sandboxID, evType,+ fmt.Sprintf("%s:%s:%d", sandboxID, evType, time.Now().UnixNano()), data)+}+// registerInlineWebhooks registers webhooks supplied inline on sandbox create,// each pinned to the sandbox with no watermark floor (created_after_event_seq=0// → full lifecycle from `created`). Best-effort: a bad URL or register error is@@ -234,7 +242,13 @@ func (s *Server) createWebhook(c echo.Context) error {case db.WebhookIdemConflict:return c.JSON(http.StatusConflict, map[string]string{"error": "Idempotency-Key reused with a different request"})case db.WebhookIdemInProgress:- return c.JSON(http.StatusConflict, map[string]string{"error": "a request with this Idempotency-Key is already in progress"})+ // Transient: another request holds the claim. Signal retryability so+ // clients/agents don't treat it as fatal.+ c.Response().Header().Set("Retry-After", "1")+ return c.JSON(http.StatusConflict, map[string]string{+ "error": "a request with this Idempotency-Key is already in progress; retry shortly",+ "code": "idempotency_in_progress",+ })case db.WebhookIdemClaimed:claimed = true}@@ -306,6 +320,24 @@ func (s *Server) createWebhook(c echo.Context) error {return c.JSON(status, resp)}+// validateInlineWebhooks checks inline webhook specs up-front (URL + event+// types) so a bad spec fails sandbox creation rather than being silently skipped+// (P2 review). Returns nil if all are valid (or none supplied).+func validateInlineWebhooks(ctx context.Context, specs []types.SandboxWebhookSpec) error {+ for _, w := range specs {+ if w.URL == "" {+ return fmt.Errorf("webhooks[].url is required")+ }+ if err := webhook.ValidateURL(ctx, w.URL); err != nil {+ return fmt.Errorf("invalid webhook url: %w", err)+ }+ if bad := firstInvalidEventType(w.EventTypes); bad != "" {+ return fmt.Errorf("unknown event type: %s", bad)+ }+ }+ return nil+}+// firstInvalidEventType returns the first eventTypes entry that isn't a valid// exact type or "prefix.*" wildcard, or "" if all are valid.func firstInvalidEventType(ets []string) string {diff --git a/internal/db/store.go b/internal/db/store.goindex cf888ff2..46c48bb1 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -867,23 +867,33 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu_ = tx.QueryRow(ctx,`SELECT org_id FROM sandbox_sessions WHERE sandbox_id = $1`, sandboxID).Scan(&orgID)if orgID != uuid.Nil {- var evType string+ var evType, evID stringvar data json.RawMessageswitch status {case "stopped":evType = "sandbox.stopped"+ evID = sandboxID + ":sandbox.stopped" // terminal: once per sandboxdata = json.RawMessage(`{"reason":"user_requested"}`)case "error":evType = "sandbox.stopped"+ evID = sandboxID + ":sandbox.stopped"data = json.RawMessage(`{"reason":"crash"}`)case "hibernated":+ // Recurs across hibernate/wake cycles — namespace by the+ // hibernation count so each cycle is a distinct, deterministic id.+ var n int+ _ = tx.QueryRow(ctx, `SELECT count(*) FROM sandbox_hibernations WHERE sandbox_id = $1`, sandboxID).Scan(&n)evType = "sandbox.hibernated"+ evID = fmt.Sprintf("%s:sandbox.hibernated:%d", sandboxID, n)case "running":+ // Boot promotion = ready. Deterministic id dedups a repeat+ // "running" update on an already-running row (idempotent promote).evType = "sandbox.ready"+ evID = sandboxID + ":sandbox.ready"}if evType != "" {if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{- ID: fmt.Sprintf("%s:%s:%d", sandboxID, evType, time.Now().UnixNano()),+ ID: evID,OrgID: orgID,SandboxID: sandboxID,Type: evType,@@ -989,17 +999,23 @@ func (s *Store) FailMigrationPostQMP(ctx context.Context, sandboxID, errorMsg streturn fmt.Errorf("begin tx: %w", err)}defer tx.Rollback(ctx)- tag, err := tx.Exec(ctx,+ var orgID uuid.UUID+ err = tx.QueryRow(ctx,`UPDATE sandbox_sessions SET status = 'error', migrating_to_worker = '', stopped_at = now(), error_msg = $2- WHERE sandbox_id = $1 AND status = 'migrating'`,- sandboxID, errorMsg)+ WHERE sandbox_id = $1 AND status = 'migrating'+ RETURNING org_id`,+ sandboxID, errorMsg).Scan(&orgID)if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return tx.Commit(ctx) // not migrating — nothing to do+ }return err}- if tag.RowsAffected() > 0 {- if err := closeOpenScaleEventsForSandboxes(ctx, tx, []string{sandboxID}); err != nil {- return fmt.Errorf("close scale events: %w", err)- }+ if err := closeOpenScaleEventsForSandboxes(ctx, tx, []string{sandboxID}); err != nil {+ return fmt.Errorf("close scale events: %w", err)+ }+ if err := recordOrphanStoppedTx(ctx, tx, []OrphanedSandbox{{SandboxID: sandboxID, OrgID: orgID}}); err != nil {+ return fmt.Errorf("record stopped event: %w", err)}return tx.Commit(ctx)}@@ -1059,6 +1075,9 @@ func (s *Store) MarkOrphanedOnWorker(ctx context.Context, workerID, errorMsg strreturn nil, fmt.Errorf("close scale events: %w", err)}}+ if err := recordOrphanStoppedTx(ctx, tx, orphans); err != nil {+ return nil, fmt.Errorf("record stopped events: %w", err)+ }if err := tx.Commit(ctx); err != nil {return nil, err}@@ -1143,6 +1162,11 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strincontinue}}+ if err := recordOrphanStoppedTx(ctx, tx, batchOrphans); err != nil {+ log.Printf("MarkOrphanedSandboxes: record stopped events for worker %s: %v", workerID, err)+ tx.Rollback(ctx)+ continue+ }if err := tx.Commit(ctx); err != nil {continue}diff --git a/internal/db/webhooks.go b/internal/db/webhooks.goindex 52d58d3b..4bae380a 100644--- a/internal/db/webhooks.go+++ b/internal/db/webhooks.go@@ -89,6 +89,29 @@ func (s *Store) RecordLifecycleEvent(ctx context.Context, ev LifecycleEvent) errreturn tx.Commit(ctx)}+// recordOrphanStoppedTx records sandbox.stopped (reason crash) for sandboxes+// moved to a terminal failure state OUTSIDE UpdateSandboxSessionStatus (migration+// failure, orphan/dead-worker sweeps), within the caller's tx so the webhook is+// durable with the state change. The id matches the normal stopped id so a+// sandbox can never get two stopped events.+func recordOrphanStoppedTx(ctx context.Context, tx pgx.Tx, orphans []OrphanedSandbox) error {+ for _, o := range orphans {+ if o.OrgID == uuid.Nil || o.SandboxID == "" {+ continue+ }+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{+ ID: o.SandboxID + ":sandbox.stopped",+ OrgID: o.OrgID,+ SandboxID: o.SandboxID,+ Type: "sandbox.stopped",+ Data: json.RawMessage(`{"reason":"crash"}`),+ }); err != nil {+ return err+ }+ }+ return nil+}+// CurrentLifecycleSeq returns the current max event seq, used as a destination's// creation watermark (it then receives only strictly-later events).func (s *Store) CurrentLifecycleSeq(ctx context.Context) (int64, error) {@@ -566,9 +589,13 @@ type matchedDest struct {}func matchDestinationsTx(ctx context.Context, tx pgx.Tx, e lifecycleEventRow) ([]matchedDest, error) {+ // Match disabled destinations too: enabled=false means PAUSE, not drop, so we+ // create the delivery rows now and let them queue. The dispatcher's claim+ // (ClaimDueDeliveries) is what skips disabled destinations, so paused rows+ // simply wait and deliver on re-enable.rows, err := tx.Query(ctx,`SELECT id, event_types FROM webhook_destinations- WHERE org_id = $1 AND enabled AND deleted_at IS NULL+ WHERE org_id = $1 AND deleted_at IS NULLAND (sandbox_id IS NULL OR sandbox_id = $2)AND created_after_event_seq < $3`,e.OrgID, e.SandboxID, e.Seq)