Skip to content

An open-source, faster Devin alternative

TypeScript

fix(webhooks): CP records created/resumed + drop CP dormancy gate + outbox is a queue

Igor Zalutskiae1b10c5fd12
diff --git a/internal/controlplane/lifecycle_outbox_relay.go b/internal/controlplane/lifecycle_outbox_relay.go
index d889b63d..dc8539fc 100644
--- a/internal/controlplane/lifecycle_outbox_relay.go
+++ b/internal/controlplane/lifecycle_outbox_relay.go
@@ -100,8 +100,8 @@ func (r *LifecycleOutboxRelay) drainSafe() {
}
}
if len(sent) > 0 {
- if err := r.store.MarkLifecycleOutboxSent(ctx, sent); err != nil {
- log.Printf("lifecycle_outbox_relay: mark sent (%d): %v", len(sent), err)
+ if err := r.store.DeleteLifecycleOutbox(ctx, sent); err != nil {
+ log.Printf("lifecycle_outbox_relay: delete relayed (%d): %v", len(sent), err)
return // retry next tick; the re-publish is idempotent via the stable id
}
}
diff --git a/internal/db/store.go b/internal/db/store.go
index 874a3f28..5f8a8fb6 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -793,8 +793,13 @@ func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgI
// and meant a customer's PUT to /secret-stores/:id/entries/:name didn't
// propagate to running sandboxes — they kept the value from create-time.
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, secretStoreID *uuid.UUID) (*SandboxSession, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback(ctx)
session := &SandboxSession{}
- err := s.pool.QueryRow(ctx,
+ err = tx.QueryRow(ctx,
`INSERT INTO sandbox_sessions (sandbox_id, org_id, user_id, template, region, worker_id, config, metadata, status, secret_store_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
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, golden_version`,
@@ -805,6 +810,23 @@ func (s *Store) CreateSandboxSessionWithStatus(ctx context.Context, sandboxID st
if err != nil {
return nil, fmt.Errorf("failed to create sandbox session: %w", err)
}
+ // Record sandbox.created in-tx (deterministic id → at most one per sandbox).
+ // This is the single webhook source for `created`: the worker's stream
+ // "created" feeds D1 sandboxes_index, not webhooks. The edge applies the
+ // dormancy gate. (sandbox-webhooks-rearchitecture.md)
+ createdData, _ := json.Marshal(map[string]string{"template": template})
+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{
+ ID: sandboxID + ":sandbox.created",
+ OrgID: orgID,
+ SandboxID: sandboxID,
+ Type: "sandbox.created",
+ Data: createdData,
+ }); err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return nil, err
+ }
return session, nil
}
@@ -1760,11 +1782,37 @@ func (s *Store) MarkHibernationUploadFailed(ctx context.Context, hibernationKey,
// UpdateSandboxSessionForWake changes a hibernated session back to running on a new worker.
func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newWorkerID string) error {
- _, err := s.pool.Exec(ctx,
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx)
+ var orgID uuid.UUID
+ err = tx.QueryRow(ctx,
`UPDATE sandbox_sessions SET status = 'running', worker_id = $1, stopped_at = NULL
- WHERE sandbox_id = $2 AND status = 'hibernated'`,
- newWorkerID, sandboxID)
- return err
+ WHERE sandbox_id = $2 AND status = 'hibernated'
+ RETURNING org_id`,
+ newWorkerID, sandboxID).Scan(&orgID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Not hibernated (already running/gone) — nothing to wake, no resumed event.
+ return tx.Commit(ctx)
+ }
+ if err != nil {
+ return err
+ }
+ // Record sandbox.resumed in-tx. Recurring (hibernate→wake cycles) → unique id;
+ // the status='hibernated' guard above ensures exactly one per actual wake.
+ // This is the single webhook source for `resumed` (the worker's stream "woke"
+ // feeds D1 sandboxes_index, not webhooks). (sandbox-webhooks-rearchitecture.md)
+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{
+ ID: sandboxID + ":sandbox.resumed:" + uuid.NewString(),
+ OrgID: orgID,
+ SandboxID: sandboxID,
+ Type: "sandbox.resumed",
+ }); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
}
// ReconcileWorkerSessions marks stale "running" sessions for a worker on startup.
diff --git a/internal/db/webhooks.go b/internal/db/webhooks.go
index e122169b..c1bc2212 100644
--- a/internal/db/webhooks.go
+++ b/internal/db/webhooks.go
@@ -56,23 +56,13 @@ type LifecycleEvent struct {
// exactly one place. Both origins call it (CP in-tx; worker via the ingress's
// own tx through RecordLifecycleEvent).
func recordLifecycleEvent(ctx context.Context, tx pgx.Tx, ev LifecycleEvent) error {
- // Dormancy gate: only record an event if the org has a live destination that
- // could receive it (org-wide, or scoped to this sandbox). A destination's
- // watermark only ever delivers events created AFTER it, so skipping events
- // for an org with no matching destination can never cause a miss — and it
- // keeps sandbox_lifecycle_events empty for the (vast majority of) orgs not
- // using webhooks. Paused (disabled) destinations count, since pause queues.
- var relevant bool
- if err := tx.QueryRow(ctx,
- `SELECT EXISTS(SELECT 1 FROM webhook_destinations
- WHERE org_id = $1 AND deleted_at IS NULL
- AND (sandbox_id IS NULL OR sandbox_id = $2))`,
- ev.OrgID, ev.SandboxID).Scan(&relevant); err != nil {
- return fmt.Errorf("webhook destination check: %w", err)
- }
- if !relevant {
- return nil // dormant: nothing could receive this event
- }
+ // All-Svix-at-edge: the CP records every CP-origin lifecycle event to the
+ // outbox unconditionally; the relay publishes them to the cell stream and the
+ // EDGE applies the dormancy gate (orgs.has_webhooks in D1) before calling
+ // Svix. There is no CP-side gate — the CP no longer knows which orgs have
+ // webhooks; that index lives at the edge. The outbox is a transient queue
+ // (the relay deletes rows after publishing), so it stays bounded.
+ // (sandbox-webhooks-rearchitecture.md)
if len(ev.Data) == 0 {
ev.Data = json.RawMessage("{}")
}
@@ -148,16 +138,15 @@ type LifecycleOutboxRow struct {
Ts time.Time
}
-// DrainLifecycleOutbox returns up to `batch` unrelayed lifecycle events (oldest
-// first by seq). The webhook re-architecture relays these to the events:{cell}
-// stream; MarkLifecycleOutboxSent then stamps them relayed. (Reuses the
-// sandbox_lifecycle_events.materialized_at column as the relayed marker.)
-// See .agents/work/sandbox-webhooks-rearchitecture.md.
+// DrainLifecycleOutbox returns up to `batch` lifecycle events (oldest first by
+// seq). The relay publishes these to the events:{cell} stream, then deletes them
+// via DeleteLifecycleOutbox. The outbox is a transient queue — the stream + edge
+// + Svix are the durable downstream (and dedupe on the stable event id), so rows
+// don't need to be retained. See .agents/work/sandbox-webhooks-rearchitecture.md.
func (s *Store) DrainLifecycleOutbox(ctx context.Context, batch int) ([]LifecycleOutboxRow, error) {
rows, err := s.pool.Query(ctx,
`SELECT id, org_id, sandbox_id, type, data, ts
FROM sandbox_lifecycle_events
- WHERE materialized_at IS NULL
ORDER BY seq
LIMIT $1`, batch)
if err != nil {
@@ -177,15 +166,15 @@ func (s *Store) DrainLifecycleOutbox(ctx context.Context, batch int) ([]Lifecycl
return out, rows.Err()
}
-// MarkLifecycleOutboxSent stamps the given events relayed (materialized_at=now()).
-// Idempotent: a re-publish of an already-relayed event is harmless (the edge and
-// Svix both dedupe on the stable event id).
-func (s *Store) MarkLifecycleOutboxSent(ctx context.Context, ids []string) error {
+// DeleteLifecycleOutbox removes the given events after they've been published to
+// the stream. A row left behind (delete fails) is harmlessly re-published next
+// tick — the edge and Svix dedupe on the stable event id.
+func (s *Store) DeleteLifecycleOutbox(ctx context.Context, ids []string) error {
if len(ids) == 0 {
return nil
}
_, err := s.pool.Exec(ctx,
- `UPDATE sandbox_lifecycle_events SET materialized_at = now() WHERE id = ANY($1)`, ids)
+ `DELETE FROM sandbox_lifecycle_events WHERE id = ANY($1)`, ids)
return err
}