Skip to content

An open-source, faster Devin alternative

TypeScript

fixes wip

Brian Reardonce477bdfcd4b
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.ts
index 25db4425..f0e1eba9 100644
--- a/cloudflare-workers/events-ingest/src/index.ts
+++ b/cloudflare-workers/events-ingest/src/index.ts
@@ -189,15 +189,18 @@ export default {
const tsSec = Math.floor((Date.parse(e.timestamp) || Date.now()) / 1000);
if (e.type === "stopped") return lifecycleStopped.bind(tsSec, e.sandbox_id);
if (e.type === "hibernated") return lifecycleHibernated.bind(tsSec, e.sandbox_id);
- if (e.type === "migrated") {
- // worker_id moves with the sandbox; payload carries the new one
- // (the CP-side publishSandboxLifecycleEvent uses the envelope's
- // worker_id field rather than payload for migrated events).
+ if (e.type === "migrated" || e.type === "woke") {
+ // worker_id moves with the sandbox. For "migrated" the scaler
+ // set the new owner; for "woke" the wake handler set it (a
+ // sandbox that hibernated on worker A can wake on worker B
+ // after a rolling replace — without this D1 keeps showing A).
+ // The CP-side publishSandboxLifecycleEvent uses the envelope's
+ // worker_id field rather than payload for these events.
return lifecycleMigrated.bind(e.worker_id ?? "", tsSec, e.sandbox_id);
}
- // "running", "woke", "created" all set the row to running (created
- // is handled by the edge on POST, but accept here for redundancy
- // in case of replay against a future cell-only create path).
+ // "running", "created" set the row to running (created is handled
+ // by the edge on POST, but accept here for redundancy in case of
+ // replay against a future cell-only create path).
return lifecycleRunning.bind(tsSec, e.sandbox_id);
});
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 32b57663..d4093999 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -15,10 +15,12 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/redis/go-redis/v9"
"github.com/opensandbox/opensandbox/internal/analytics"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/blobstore"
+ "github.com/opensandbox/opensandbox/internal/cellevents"
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/metrics"
@@ -426,11 +428,33 @@ func main() {
defer store.Close()
log.Println("opensandbox-worker: PostgreSQL store connected (auto-wake enabled)")
- _, stopped, err := store.ReconcileWorkerSessions(ctx, cfg.WorkerID)
+ hibernated, stopped, err := store.ReconcileWorkerSessions(ctx, cfg.WorkerID)
if err != nil {
log.Printf("opensandbox-worker: warning: session reconciliation failed: %v", err)
- } else if stopped > 0 {
- log.Printf("opensandbox-worker: reconciled %d unrecoverable sessions as stopped", stopped)
+ } else {
+ if len(stopped) > 0 {
+ log.Printf("opensandbox-worker: reconciled %d unrecoverable sessions as stopped", len(stopped))
+ }
+ if len(hibernated) > 0 {
+ log.Printf("opensandbox-worker: reconciled %d sessions as hibernated", len(hibernated))
+ }
+ // Mirror PG state changes to D1 via the cell events stream.
+ // Without these XADDs, the dashboard keeps the rows at the
+ // pre-restart state ("running" on a worker that just rebooted).
+ // Brief redis client just for the emit; heartbeat + event
+ // publisher create their own later in startup.
+ if cfg.RedisURL != "" && cfg.CellID != "" && (len(hibernated) > 0 || len(stopped) > 0) {
+ if opts, optErr := redis.ParseURL(cfg.RedisURL); optErr == nil {
+ emitRDB := redis.NewClient(opts)
+ for _, o := range hibernated {
+ cellevents.PublishLifecycle(ctx, emitRDB, cfg.CellID, "hibernated", o.SandboxID, o.WorkerID, o.OrgID, "worker_restart")
+ }
+ for _, o := range stopped {
+ cellevents.PublishLifecycle(ctx, emitRDB, cfg.CellID, "stopped", o.SandboxID, o.WorkerID, o.OrgID, "worker_restart")
+ }
+ _ = emitRDB.Close()
+ }
+ }
}
// Wire up metadata server billing callback
@@ -676,8 +700,22 @@ func main() {
fixed, err := store.ReconcileWorkerReconnect(context.Background(), cfg.WorkerID, runningIDs)
if err != nil {
log.Printf("opensandbox-worker: reconnect reconciliation failed: %v", err)
- } else if fixed > 0 {
- log.Printf("opensandbox-worker: reconnect reconciliation: %d sessions restored to running", fixed)
+ } else if len(fixed) > 0 {
+ log.Printf("opensandbox-worker: reconnect reconciliation: %d sessions restored to running", len(fixed))
+ // Mirror to D1: emit `running` events so the dashboard
+ // reflects the recovery. Without these, D1 keeps the
+ // `error` status from the maintenance loop's previous
+ // sweep — customer sees their sandbox as broken until
+ // the next state-changing event.
+ if cfg.RedisURL != "" && cfg.CellID != "" {
+ if opts, optErr := redis.ParseURL(cfg.RedisURL); optErr == nil {
+ emitRDB := redis.NewClient(opts)
+ for _, o := range fixed {
+ cellevents.PublishLifecycle(context.Background(), emitRDB, cfg.CellID, "running", o.SandboxID, o.WorkerID, o.OrgID, "worker_reconnect")
+ }
+ _ = emitRDB.Close()
+ }
+ }
}
})
}
diff --git a/internal/cellevents/publish.go b/internal/cellevents/publish.go
new file mode 100644
index 00000000..4705096a
--- /dev/null
+++ b/internal/cellevents/publish.go
@@ -0,0 +1,70 @@
+// Package cellevents is a tiny helper for XADDing sandbox lifecycle events
+// to a cell's events stream. Lives in its own package so both worker and
+// control-plane code can publish without pulling in the full controlplane
+// graph (compute, nats, echo, …).
+package cellevents
+
+import (
+ "context"
+ "encoding/json"
+ "log"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/redis/go-redis/v9"
+)
+
+// PublishLifecycle XADDs a sandbox lifecycle event (`stopped`, `hibernated`,
+// `migrated`, `woke`, `running`, `created`) to the cell's events stream.
+// Used for state changes where the canonical worker-side per-sandbox SQLite
+// path didn't run — CP-side orphan sweeps, the maintenance loop's dead-worker
+// reconciler, worker startup / reconnect reconciliation.
+//
+// Retries up to 3 times with a short backoff so a Redis hiccup doesn't
+// permanently drop the event. Returns true if the XADD landed on some
+// attempt; false if all three failed (caller logs the failure context).
+func PublishLifecycle(ctx context.Context, rdb *redis.Client, cellID, eventType, sandboxID, workerID string, orgID uuid.UUID, reason string) bool {
+ if rdb == nil || cellID == "" || sandboxID == "" {
+ return false
+ }
+ envelope := map[string]any{
+ "id": uuid.NewString(),
+ "type": eventType,
+ "sandbox_id": sandboxID,
+ "org_id": orgID.String(),
+ "worker_id": workerID,
+ "cell_id": cellID,
+ "payload": map[string]any{"reason": reason},
+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
+ }
+ body, err := json.Marshal(envelope)
+ if err != nil {
+ log.Printf("cellevents: marshal %s: %v", eventType, err)
+ return false
+ }
+ stream := "events:" + cellID
+ backoff := 200 * time.Millisecond
+ for attempt := 1; attempt <= 3; attempt++ {
+ xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ err := rdb.XAdd(xaddCtx, &redis.XAddArgs{
+ Stream: stream,
+ MaxLen: 100000,
+ Approx: true,
+ Values: map[string]any{"event": string(body)},
+ }).Err()
+ cancel()
+ if err == nil {
+ return true
+ }
+ log.Printf("cellevents: %s sandbox=%s attempt %d/3 failed: %v", eventType, sandboxID, attempt, err)
+ if attempt < 3 {
+ select {
+ case <-ctx.Done():
+ return false
+ case <-time.After(backoff):
+ }
+ backoff *= 2
+ }
+ }
+ return false
+}
diff --git a/internal/controlplane/event_publish.go b/internal/controlplane/event_publish.go
index e9a38553..e1e41884 100644
--- a/internal/controlplane/event_publish.go
+++ b/internal/controlplane/event_publish.go
@@ -2,68 +2,16 @@ package controlplane
import (
"context"
- "encoding/json"
- "log"
- "time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
+
+ "github.com/opensandbox/opensandbox/internal/cellevents"
)
-// PublishLifecycle XADDs a sandbox lifecycle event (`stopped`, `hibernated`,
-// `migrated`, etc.) to the cell's events stream. Used for CP-side state
-// changes — the scaler's orphan sweep, the maintenance loop's dead-worker
-// reconciler — where the worker's per-sandbox SQLite never emitted because
-// the worker is gone or never got involved.
-//
-// Retries up to 3 times with a short backoff so a Redis hiccup doesn't
-// permanently drop the event. Drops on this path produce ghost rows in D1
-// sandboxes_index that only the periodic reconciler can clean up.
-//
-// Returns true if the XADD succeeded on some attempt, false if all three
-// failed (caller logs/decides next steps).
+// PublishLifecycle is preserved here as a re-export for existing callers
+// (scaler, cmd/server). The implementation lives in internal/cellevents so
+// the worker can publish without pulling in the controlplane graph.
func PublishLifecycle(ctx context.Context, rdb *redis.Client, cellID, eventType, sandboxID, workerID string, orgID uuid.UUID, reason string) bool {
- if rdb == nil || cellID == "" || sandboxID == "" {
- return false
- }
- envelope := map[string]any{
- "id": uuid.NewString(),
- "type": eventType,
- "sandbox_id": sandboxID,
- "org_id": orgID.String(),
- "worker_id": workerID,
- "cell_id": cellID,
- "payload": map[string]any{"reason": reason},
- "timestamp": time.Now().UTC().Format(time.RFC3339Nano),
- }
- body, err := json.Marshal(envelope)
- if err != nil {
- log.Printf("PublishLifecycle marshal %s: %v", eventType, err)
- return false
- }
- stream := "events:" + cellID
- backoff := 200 * time.Millisecond
- for attempt := 1; attempt <= 3; attempt++ {
- xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
- err := rdb.XAdd(xaddCtx, &redis.XAddArgs{
- Stream: stream,
- MaxLen: 100000,
- Approx: true,
- Values: map[string]any{"event": string(body)},
- }).Err()
- cancel()
- if err == nil {
- return true
- }
- log.Printf("PublishLifecycle %s sandbox=%s attempt %d/3 failed: %v", eventType, sandboxID, attempt, err)
- if attempt < 3 {
- select {
- case <-ctx.Done():
- return false
- case <-time.After(backoff):
- }
- backoff *= 2
- }
- }
- return false
+ return cellevents.PublishLifecycle(ctx, rdb, cellID, eventType, sandboxID, workerID, orgID, reason)
}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index b53b9f50..d5bea10e 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -1513,10 +1513,21 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
if err := s.store.FailMigrationPostQMP(ctx, sandboxID, "migration failed after QMP transfer; source VM gone, target failed to complete"); err != nil {
log.Printf("scaler: migrate %s: FailMigrationPostQMP failed: %v", sandboxID, err)
}
+ // Source VM is gone, target failed. Emit a `stopped` event so
+ // D1 reflects the unreachable state — otherwise the dashboard
+ // keeps showing the sandbox as running on the dead source.
+ var failOrgID uuid.UUID
+ if sess, err := s.store.GetSandboxSession(context.Background(), sandboxID); err == nil && sess != nil {
+ failOrgID = sess.OrgID
+ }
+ s.publishStopped(context.Background(), sandboxID, sourceWorkerID, failOrgID, "migration_post_qmp_failed")
} else {
if err := s.store.FailMigration(ctx, sandboxID); err != nil {
log.Printf("scaler: migrate %s: FailMigration failed: %v", sandboxID, err)
}
+ // Pre-QMP path: sandbox is back on source. No `migrated` event
+ // fired yet (only fires on success), so D1's worker_id was
+ // never moved off source. No event needed.
}
}()
}
diff --git a/internal/db/store.go b/internal/db/store.go
index aec40c97..448dba39 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -1314,34 +1314,51 @@ func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newW
// ReconcileWorkerSessions marks stale "running" sessions for a worker on startup.
// Sessions with an active checkpoint are set to "hibernated" (recoverable via wake-on-request).
// Sessions without a checkpoint are set to "stopped" (VM is gone, no recovery possible).
-// Returns the count of sessions transitioned to each state.
-func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (hibernated, stopped int, err error) {
+// Returns the affected sandbox identities so the caller can emit lifecycle
+// events; without them D1 drifts from PG every time a worker restarts.
+func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (hibernated, stopped []OrphanedSandbox, err error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
- return 0, 0, fmt.Errorf("failed to begin tx: %w", err)
+ return nil, nil, fmt.Errorf("failed to begin tx: %w", err)
}
defer tx.Rollback(ctx)
// First: mark sessions that have an active hibernation as "hibernated"
- res1, err := tx.Exec(ctx,
+ hibernatedRows, err := tx.Query(ctx,
`UPDATE sandbox_sessions SET status = 'hibernated'
WHERE worker_id = $1 AND status = 'running'
AND sandbox_id IN (
SELECT sandbox_id FROM sandbox_hibernations
WHERE restored_at IS NULL AND expired_at IS NULL
- )`, workerID)
+ )
+ RETURNING sandbox_id, org_id, worker_id`, workerID)
if err != nil {
- return 0, 0, fmt.Errorf("failed to reconcile hibernated sessions: %w", err)
+ return nil, nil, fmt.Errorf("failed to reconcile hibernated sessions: %w", err)
}
+ for hibernatedRows.Next() {
+ var o OrphanedSandbox
+ if scanErr := hibernatedRows.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); scanErr == nil {
+ hibernated = append(hibernated, o)
+ }
+ }
+ hibernatedRows.Close()
// Second: mark remaining "running" sessions as "stopped"
- res2, err := tx.Exec(ctx,
+ stoppedRows, err := tx.Query(ctx,
`UPDATE sandbox_sessions SET status = 'stopped', stopped_at = now(),
error_msg = 'worker restarted'
- WHERE worker_id = $1 AND status = 'running'`, workerID)
+ WHERE worker_id = $1 AND status = 'running'
+ RETURNING sandbox_id, org_id, worker_id`, workerID)
if err != nil {
- return int(res1.RowsAffected()), 0, fmt.Errorf("failed to reconcile stopped sessions: %w", err)
+ return hibernated, nil, fmt.Errorf("failed to reconcile stopped sessions: %w", err)
+ }
+ for stoppedRows.Next() {
+ var o OrphanedSandbox
+ if scanErr := stoppedRows.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); scanErr == nil {
+ stopped = append(stopped, o)
+ }
}
+ stoppedRows.Close()
// Close any open scale_events for sessions we just transitioned off running
// on this worker, so billing stops at reconciliation time.
@@ -1352,30 +1369,41 @@ func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (h
SELECT sandbox_id FROM sandbox_sessions
WHERE worker_id = $1 AND status IN ('hibernated', 'stopped')
)`, workerID); err != nil {
- return int(res1.RowsAffected()), int(res2.RowsAffected()), fmt.Errorf("failed to close scale events: %w", err)
+ return hibernated, stopped, fmt.Errorf("failed to close scale events: %w", err)
}
if err := tx.Commit(ctx); err != nil {
- return 0, 0, fmt.Errorf("failed to commit reconcile tx: %w", err)
+ return nil, nil, fmt.Errorf("failed to commit reconcile tx: %w", err)
}
- return int(res1.RowsAffected()), int(res2.RowsAffected()), nil
+ return hibernated, stopped, nil
}
// ReconcileWorkerReconnect fixes sandbox sessions after a worker reconnects from
// a network outage. Sandboxes that are actually running locally but marked as
-// "error" in the DB are reset to "running". Returns the number of sessions fixed.
-func (s *Store) ReconcileWorkerReconnect(ctx context.Context, workerID string, runningSandboxIDs []string) (fixed int, err error) {
+// "error" in the DB are reset to "running". Returns the affected sandbox
+// identities so the caller can emit `running` events — without them D1 keeps
+// the old `error` status (or worse, drifts to whatever the maintenance loop
+// last wrote).
+func (s *Store) ReconcileWorkerReconnect(ctx context.Context, workerID string, runningSandboxIDs []string) (fixed []OrphanedSandbox, err error) {
if len(runningSandboxIDs) == 0 {
- return 0, nil
+ return nil, nil
}
- res, err := s.pool.Exec(ctx,
+ rows, err := s.pool.Query(ctx,
`UPDATE sandbox_sessions SET status = 'running', error_msg = NULL
WHERE worker_id = $1 AND status = 'error'
- AND sandbox_id = ANY($2)`, workerID, runningSandboxIDs)
+ AND sandbox_id = ANY($2)
+ RETURNING sandbox_id, org_id, worker_id`, workerID, runningSandboxIDs)
if err != nil {
- return 0, fmt.Errorf("reconcile worker reconnect: %w", err)
+ return nil, fmt.Errorf("reconcile worker reconnect: %w", err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var o OrphanedSandbox
+ if scanErr := rows.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); scanErr == nil {
+ fixed = append(fixed, o)
+ }
}
- return int(res.RowsAffected()), nil
+ return fixed, nil
}
// UpsertWorkspaceBackup creates or updates a workspace-only backup record for a sandbox.