Skip to content

An open-source, faster Devin alternative

TypeScript

add alert system based on shared env

Brian Reardona2f81d657f1a
diff --git a/cmd/server/main.go b/cmd/server/main.go
index eaf3f0d9..c38f6652 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -16,6 +16,7 @@ import (
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
+ "github.com/opensandbox/opensandbox/internal/alert"
"github.com/opensandbox/opensandbox/internal/api"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/billing"
@@ -558,6 +559,10 @@ func main() {
// every time the autoscaler shuffles things around.
RedisClient: redisRegistry.RedisClient(),
CellID: cfg.CellID,
+ // Roll-stuck alerts (version skew past deadline / creation
+ // backoff) to Slack. No-op when the webhook is unset.
+ Alerter: alert.New(cfg.AlertSlackWebhook, cfg.CellID),
+ RollStuckDeadline: cfg.RollStuckDeadline,
})
defer scaler.Stop()
scalerOrchestrator = scaler
@@ -824,6 +829,10 @@ func main() {
Store: opts.Store,
ParityURL: cfg.UsageParityURL,
Secret: cfg.CFEventSecret,
+ // Same Slack sink as the roll monitor; alerts only on systemic,
+ // sustained, material drift (defaults inside the checker).
+ Alerter: alert.New(cfg.AlertSlackWebhook, cfg.CellID),
+ CellID: cfg.CellID,
})
if parity != nil {
parity.Start(ctx)
diff --git a/internal/alert/alert.go b/internal/alert/alert.go
new file mode 100644
index 00000000..0b696408
--- /dev/null
+++ b/internal/alert/alert.go
@@ -0,0 +1,154 @@
+// Package alert delivers operational alerts to an external sink (currently a
+// Slack incoming webhook). It is deliberately tiny and dependency-free so any
+// producer — the scaler's roll-health monitor today, reconcilers or CI-driven
+// pings later — can fire alerts through one call site:
+//
+// alerter.Send(ctx, alert.Alert{Severity: alert.Critical, Title: "...", Detail: "...", DedupKey: "..."})
+//
+// A Slack sink is used when a webhook URL is configured; otherwise Send is a
+// no-op, so callers never have to nil-check and dev/local stays quiet.
+package alert
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "net/http"
+ "sync"
+ "time"
+)
+
+// Severity ranks an alert. Slack shows all; a future PagerDuty sink can gate
+// paging on Critical without changing any producer.
+type Severity int
+
+const (
+ Info Severity = iota
+ Warning
+ Critical
+)
+
+func (s Severity) String() string {
+ switch s {
+ case Critical:
+ return "critical"
+ case Warning:
+ return "warning"
+ default:
+ return "info"
+ }
+}
+
+func (s Severity) emoji() string {
+ switch s {
+ case Critical:
+ return ":rotating_light:"
+ case Warning:
+ return ":warning:"
+ default:
+ return ":information_source:"
+ }
+}
+
+// Alert is one operational notification.
+type Alert struct {
+ Severity Severity
+ Title string
+ Detail string
+ // DedupKey collapses repeats for the same underlying condition: an alert
+ // with a non-empty key won't re-fire within the sink's cooldown window.
+ // Empty = always send (use for one-shot events).
+ DedupKey string
+}
+
+// Alerter delivers alerts. Implementations are safe for concurrent use and
+// never block the caller on delivery failure (they log and move on).
+type Alerter interface {
+ Send(ctx context.Context, a Alert)
+}
+
+// Nop drops all alerts. Returned by New when no sink is configured.
+type Nop struct{}
+
+// Send implements Alerter.
+func (Nop) Send(context.Context, Alert) {}
+
+// DefaultCooldown is how long a given DedupKey is suppressed after firing, so a
+// persistent condition re-pings periodically rather than every tick.
+const DefaultCooldown = 30 * time.Minute
+
+// New returns a Slack-webhook Alerter when webhookURL is set, otherwise a Nop.
+// envLabel (e.g. "prod-eastus2") is prefixed to every message so a shared
+// channel can tell clusters apart.
+func New(webhookURL, envLabel string) Alerter {
+ if webhookURL == "" {
+ return Nop{}
+ }
+ return &slackAlerter{
+ url: webhookURL,
+ env: envLabel,
+ client: &http.Client{Timeout: 10 * time.Second},
+ cooldown: DefaultCooldown,
+ lastSent: map[string]time.Time{},
+ now: time.Now,
+ }
+}
+
+type slackAlerter struct {
+ url string
+ env string
+ client *http.Client
+ cooldown time.Duration
+
+ mu sync.Mutex
+ lastSent map[string]time.Time
+ now func() time.Time // injectable for tests
+}
+
+// Send posts to the Slack webhook, honoring the per-DedupKey cooldown. Delivery
+// errors are logged, never returned — alerting must not break the caller.
+func (s *slackAlerter) Send(ctx context.Context, a Alert) {
+ if a.DedupKey != "" && !s.allow(a.DedupKey) {
+ return
+ }
+ title := a.Title
+ if s.env != "" {
+ title = "[" + s.env + "] " + title
+ }
+ text := fmt.Sprintf("%s *%s*", a.Severity.emoji(), title)
+ if a.Detail != "" {
+ text += "\n" + a.Detail
+ }
+ body, _ := json.Marshal(map[string]string{"text": text})
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body))
+ if err != nil {
+ log.Printf("alert: build request: %v", err)
+ return
+ }
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := s.client.Do(req)
+ if err != nil {
+ log.Printf("alert: slack post failed: %v", err)
+ return
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode >= 300 {
+ log.Printf("alert: slack returned status %d", resp.StatusCode)
+ }
+}
+
+// allow reports whether key may fire now (outside its cooldown) and records the
+// send. The first call for a key always allows.
+func (s *slackAlerter) allow(key string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ now := s.now()
+ if last, ok := s.lastSent[key]; ok && now.Sub(last) < s.cooldown {
+ return false
+ }
+ s.lastSent[key] = now
+ return true
+}
diff --git a/internal/alert/alert_test.go b/internal/alert/alert_test.go
new file mode 100644
index 00000000..baa07546
--- /dev/null
+++ b/internal/alert/alert_test.go
@@ -0,0 +1,104 @@
+package alert
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// captureServer records the JSON bodies POSTed to it.
+func captureServer(t *testing.T) (*httptest.Server, *[]string, *sync.Mutex) {
+ t.Helper()
+ var mu sync.Mutex
+ var bodies []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ mu.Lock()
+ bodies = append(bodies, string(b))
+ mu.Unlock()
+ w.WriteHeader(200)
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &bodies, &mu
+}
+
+func TestNew_NopWhenNoURL(t *testing.T) {
+ if _, ok := New("", "prod").(Nop); !ok {
+ t.Fatal("empty webhook URL must yield a Nop alerter")
+ }
+ // Nop.Send must not panic.
+ New("", "").Send(context.Background(), Alert{Title: "x"})
+}
+
+func TestSend_PostsFormattedMessage(t *testing.T) {
+ srv, bodies, mu := captureServer(t)
+ a := New(srv.URL, "prod-eastus2")
+ a.Send(context.Background(), Alert{Severity: Critical, Title: "roll stuck", Detail: "3/5 workers stale"})
+
+ mu.Lock()
+ defer mu.Unlock()
+ if len(*bodies) != 1 {
+ t.Fatalf("want 1 POST, got %d", len(*bodies))
+ }
+ var payload map[string]string
+ if err := json.Unmarshal([]byte((*bodies)[0]), &payload); err != nil {
+ t.Fatalf("body not JSON: %v", err)
+ }
+ text := payload["text"]
+ for _, want := range []string{"[prod-eastus2]", "roll stuck", "3/5 workers stale"} {
+ if !contains(text, want) {
+ t.Errorf("message %q missing %q", text, want)
+ }
+ }
+}
+
+func TestSend_CooldownDedup(t *testing.T) {
+ srv, bodies, mu := captureServer(t)
+ s := New(srv.URL, "").(*slackAlerter)
+ base := time.Unix(1_000_000, 0)
+ var nowNs atomic.Int64
+ nowNs.Store(base.UnixNano())
+ s.now = func() time.Time { return time.Unix(0, nowNs.Load()) }
+
+ fire := func() { s.Send(context.Background(), Alert{Title: "t", DedupKey: "roll:eastus2"}) }
+
+ fire() // first: allowed
+ fire() // within cooldown: suppressed
+ nowNs.Store(base.Add(DefaultCooldown - time.Minute).UnixNano())
+ fire() // still within cooldown: suppressed
+ nowNs.Store(base.Add(DefaultCooldown + time.Minute).UnixNano())
+ fire() // past cooldown: allowed
+
+ mu.Lock()
+ defer mu.Unlock()
+ if len(*bodies) != 2 {
+ t.Fatalf("cooldown: want 2 sends, got %d", len(*bodies))
+ }
+}
+
+func TestSend_DistinctKeysNotSuppressed(t *testing.T) {
+ srv, bodies, mu := captureServer(t)
+ a := New(srv.URL, "")
+ a.Send(context.Background(), Alert{Title: "a", DedupKey: "k1"})
+ a.Send(context.Background(), Alert{Title: "b", DedupKey: "k2"})
+ mu.Lock()
+ defer mu.Unlock()
+ if len(*bodies) != 2 {
+ t.Fatalf("distinct keys: want 2 sends, got %d", len(*bodies))
+ }
+}
+
+func contains(s, sub string) bool {
+ for i := 0; i+len(sub) <= len(s); i++ {
+ if s[i:i+len(sub)] == sub {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 545f927c..cbffdcbd 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -60,6 +60,15 @@ type Config struct {
// Redis (Upstash) for worker discovery
RedisURL string
+ // AlertSlackWebhook, when set, routes operational alerts (roll-stuck, etc.)
+ // to a Slack incoming webhook. Empty → alerts are dropped (dev/local).
+ AlertSlackWebhook string
+
+ // RollStuckDeadline overrides how long a rolling replace may be
+ // non-converging before it alerts (Go duration). 0 → scaler default 45m.
+ // Set short (e.g. 2m) on dev to validate the alert path.
+ RollStuckDeadline time.Duration
+
// Worker capacity
MaxCapacity int
@@ -337,6 +346,9 @@ func Load() (*Config, error) {
RedisURL: os.Getenv("OPENSANDBOX_REDIS_URL"),
+ AlertSlackWebhook: os.Getenv("OPENSANDBOX_ALERT_SLACK_WEBHOOK"),
+ RollStuckDeadline: envDuration("OPENSANDBOX_ROLL_STUCK_DEADLINE"),
+
MaxCapacity: envOrDefaultInt("OPENSANDBOX_MAX_CAPACITY", 50),
SandboxDomain: envOrDefault("OPENSANDBOX_SANDBOX_DOMAIN", "localhost"),
@@ -512,6 +524,16 @@ func envOrDefaultInt(key string, fallback int) int {
return fallback
}
+// envDuration parses a Go duration from key; returns 0 when unset or invalid.
+func envDuration(key string) time.Duration {
+ if v := os.Getenv(key); v != "" {
+ if d, err := time.ParseDuration(v); err == nil {
+ return d
+ }
+ }
+ return 0
+}
+
func envOrDefaultFloat(key string, fallback float64) float64 {
if v := os.Getenv(key); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil {
diff --git a/internal/config/keyvault.go b/internal/config/keyvault.go
index 2d4b7aab..b5152243 100644
--- a/internal/config/keyvault.go
+++ b/internal/config/keyvault.go
@@ -155,6 +155,9 @@ var kvMapping = map[string]string{
// encrypt secret-store entries and any cell can decrypt them.
"shared-cf-edge-base-url": "OPENSANDBOX_CF_EDGE_BASE_URL",
"shared-secret-encryption-key": "OPENSANDBOX_SECRET_ENCRYPTION_KEY",
+ // Operational alert sink (Slack webhook); shared — any service that alerts
+ // reads the same OPENSANDBOX_ALERT_SLACK_WEBHOOK.
+ "shared-alert-slack-webhook": "OPENSANDBOX_ALERT_SLACK_WEBHOOK",
}
// LoadSecretsFromKeyVault fetches secrets from Azure Key Vault and sets them
diff --git a/internal/controlplane/roll_health.go b/internal/controlplane/roll_health.go
new file mode 100644
index 00000000..915fd685
--- /dev/null
+++ b/internal/controlplane/roll_health.go
@@ -0,0 +1,180 @@
+package controlplane
+
+import (
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/alert"
+)
+
+// rollHealthConfig tunes the roll-stuck detector.
+type rollHealthConfig struct {
+ // Deadline is how long a condition (version skew or creation backoff) may
+ // persist before it's treated as a stuck roll worth alerting. A healthy
+ // rolling replace converges well under this. Default 45m.
+ Deadline time.Duration
+ // clearGrace tolerates brief gaps — e.g. the creation-backoff window
+ // expiring for a single tick between retries — without resetting the
+ // persistence timer. Default 3m.
+ clearGrace time.Duration
+}
+
+// rollFleetSnapshot is the per-region view the monitor evaluates each tick.
+type rollFleetSnapshot struct {
+ region string
+ targetVersion string
+ workers []*WorkerInfo
+ backoffActive bool
+ backoffUntil time.Time
+}
+
+// rollHealthMonitor watches for a rolling replace that has stopped making
+// progress and alerts (subject to the alerter's cooldown). It covers the two
+// failure modes we've actually hit in prod:
+//
+// - version skew: workers stuck on an old worker_version long after the roll
+// should have finished — a wedged drain, workers that won't come up, etc.
+// - creation backoff: the scaler can't launch replacement workers at all
+// (Azure core quota / capacity exhausted), so the roll can never proceed.
+//
+// A single deadline separates a normal in-flight roll from a stuck one, so it
+// needs no per-worker drain state: if skew persists past the deadline it's
+// stuck regardless of the reason.
+type rollHealthMonitor struct {
+ alerter alert.Alerter
+ deadline time.Duration
+ grace time.Duration
+ now func() time.Time
+
+ mu sync.Mutex
+ firstSeen map[string]time.Time // condition key -> when it began
+ lastSeen map[string]time.Time // condition key -> last tick it was true
+}
+
+func newRollHealthMonitor(alerter alert.Alerter, cfg rollHealthConfig) *rollHealthMonitor {
+ if alerter == nil {
+ alerter = alert.Nop{}
+ }
+ deadline := cfg.Deadline
+ if deadline <= 0 {
+ deadline = 45 * time.Minute
+ }
+ grace := cfg.clearGrace
+ if grace <= 0 {
+ grace = 3 * time.Minute
+ }
+ return &rollHealthMonitor{
+ alerter: alerter,
+ deadline: deadline,
+ grace: grace,
+ now: time.Now,
+ firstSeen: map[string]time.Time{},
+ lastSeen: map[string]time.Time{},
+ }
+}
+
+// observe evaluates one region snapshot, advancing persistence timers and
+// firing alerts for conditions that have been continuously true past the
+// deadline. Safe to call every scaler tick; the alerter dedups repeats.
+func (m *rollHealthMonitor) observe(ctx context.Context, snap rollFleetSnapshot) {
+ now := m.now()
+
+ // --- version skew: workers not yet on the target version ---
+ stale := staleWorkers(snap)
+ skewKey := "roll_skew:" + snap.region
+ if len(stale) > 0 {
+ if since, firing := m.track(skewKey, now); firing {
+ m.alerter.Send(ctx, alert.Alert{
+ Severity: alert.Critical,
+ Title: fmt.Sprintf("rolling replace stuck in %s", snap.region),
+ Detail: fmt.Sprintf("%d/%d workers still not on target version %q after ~%s. Stale: %s",
+ len(stale), len(snap.workers), snap.targetVersion, roundDur(now.Sub(since)), strings.Join(staleIDs(stale), ", ")),
+ DedupKey: skewKey,
+ })
+ }
+ } else {
+ m.reset(skewKey, now)
+ }
+
+ // --- creation backoff: scaler cannot launch replacement workers ---
+ backoffKey := "roll_backoff:" + snap.region
+ if snap.backoffActive {
+ if since, firing := m.track(backoffKey, now); firing {
+ m.alerter.Send(ctx, alert.Alert{
+ Severity: alert.Critical,
+ Title: fmt.Sprintf("scaler cannot create workers in %s", snap.region),
+ Detail: fmt.Sprintf("creation backoff active for ~%s (until %s) — likely core quota or capacity exhausted. Scale-up and rolling replace are blocked until this clears.",
+ roundDur(now.Sub(since)), snap.backoffUntil.Format(time.RFC3339)),
+ DedupKey: backoffKey,
+ })
+ }
+ } else {
+ m.reset(backoffKey, now)
+ }
+}
+
+// track records that a condition is true at now and reports whether it has
+// persisted past the deadline. The first observation starts the timer.
+func (m *rollHealthMonitor) track(key string, now time.Time) (since time.Time, firing bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ first, ok := m.firstSeen[key]
+ if !ok {
+ first = now
+ m.firstSeen[key] = first
+ }
+ m.lastSeen[key] = now
+ return first, now.Sub(first) >= m.deadline
+}
+
+// reset is called on a tick where the condition is false. It clears the timers
+// only after the condition has been false longer than the grace window, so a
+// one-tick flicker doesn't discard accumulated progress.
+func (m *rollHealthMonitor) reset(key string, now time.Time) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ last, ok := m.lastSeen[key]
+ if !ok {
+ return
+ }
+ if now.Sub(last) >= m.grace {
+ delete(m.firstSeen, key)
+ delete(m.lastSeen, key)
+ }
+}
+
+// staleWorkers returns workers whose reported version differs from the target.
+// A worker with no reported version yet is ignored (still registering).
+func staleWorkers(snap rollFleetSnapshot) []*WorkerInfo {
+ if snap.targetVersion == "" {
+ return nil
+ }
+ var out []*WorkerInfo
+ for _, w := range snap.workers {
+ if w.WorkerVersion != "" && w.WorkerVersion != snap.targetVersion {
+ out = append(out, w)
+ }
+ }
+ return out
+}
+
+func staleIDs(ws []*WorkerInfo) []string {
+ out := make([]string, 0, len(ws))
+ for _, w := range ws {
+ out = append(out, fmt.Sprintf("%s(%s)", w.ID, w.WorkerVersion))
+ }
+ sort.Strings(out)
+ return out
+}
+
+// roundDur rounds a duration to a readable granularity for alert text.
+func roundDur(d time.Duration) time.Duration {
+ if d >= time.Minute {
+ return d.Round(time.Minute)
+ }
+ return d.Round(time.Second)
+}
diff --git a/internal/controlplane/roll_health_test.go b/internal/controlplane/roll_health_test.go
new file mode 100644
index 00000000..9279fb61
--- /dev/null
+++ b/internal/controlplane/roll_health_test.go
@@ -0,0 +1,144 @@
+package controlplane
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/alert"
+)
+
+type fakeAlerter struct {
+ mu sync.Mutex
+ sent []alert.Alert
+}
+
+func (f *fakeAlerter) Send(_ context.Context, a alert.Alert) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.sent = append(f.sent, a)
+}
+
+func (f *fakeAlerter) count() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return len(f.sent)
+}
+
+func (f *fakeAlerter) last() alert.Alert {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.sent[len(f.sent)-1]
+}
+
+// newTestMonitor returns a monitor with a controllable clock (via the returned
+// pointer) and a 45m deadline / 3m grace.
+func newTestMonitor(fa alert.Alerter) (*rollHealthMonitor, *time.Time) {
+ m := newRollHealthMonitor(fa, rollHealthConfig{Deadline: 45 * time.Minute, clearGrace: 3 * time.Minute})
+ clock := time.Unix(1_700_000_000, 0)
+ m.now = func() time.Time { return clock }
+ return m, &clock
+}
+
+func workers(target string, versions ...string) []*WorkerInfo {
+ out := make([]*WorkerInfo, len(versions))
+ for i, v := range versions {
+ out[i] = &WorkerInfo{ID: "w" + string(rune('0'+i)), Region: "eastus2", WorkerVersion: v}
+ }
+ return out
+}
+
+// An in-progress roll (skew younger than the deadline) must not alert.
+func TestRollHealth_InProgressNoAlert(t *testing.T) {
+ fa := &fakeAlerter{}
+ m, clock := newTestMonitor(fa)
+ snap := rollFleetSnapshot{region: "eastus2", targetVersion: "new", workers: workers("new", "new", "old")}
+
+ m.observe(context.Background(), snap) // t=0, skew begins
+ *clock = clock.Add(30 * time.Minute) // < 45m deadline
+ m.observe(context.Background(), snap)
+ if fa.count() != 0 {
+ t.Fatalf("in-progress roll should not alert, got %d", fa.count())
+ }
+}
+
+// Skew that persists past the deadline alerts, and the message names the stale worker.
+func TestRollHealth_StuckSkewAlerts(t *testing.T) {
+ fa := &fakeAlerter{}
+ m, clock := newTestMonitor(fa)
+ snap := rollFleetSnapshot{region: "eastus2", targetVersion: "new", workers: workers("new", "new", "old")}
+
+ m.observe(context.Background(), snap) // t=0
+ *clock = clock.Add(46 * time.Minute) // past deadline
+ m.observe(context.Background(), snap)
+
+ if fa.count() == 0 {
+ t.Fatal("stuck skew past deadline must alert")
+ }
+ a := fa.last()
+ if a.Severity != alert.Critical || !strings.Contains(a.Title, "rolling replace stuck") {
+ t.Errorf("unexpected alert: %+v", a)
+ }
+ if !strings.Contains(a.Detail, "old") || a.DedupKey != "roll_skew:eastus2" {
+ t.Errorf("alert detail/key wrong: %+v", a)
+ }
+}
+
+// Once the fleet converges the timer clears, so a later transient skew restarts
+// the clock rather than instantly alerting.
+func TestRollHealth_ConvergenceClears(t *testing.T) {
+ fa := &fakeAlerter{}
+ m, clock := newTestMonitor(fa)
+ stale := rollFleetSnapshot{region: "eastus2", targetVersion: "new", workers: workers("new", "old")}
+ converged := rollFleetSnapshot{region: "eastus2", targetVersion: "new", workers: workers("new", "new")}
+
+ m.observe(context.Background(), stale) // t=0 skew begins
+ *clock = clock.Add(10 * time.Minute)
+ m.observe(context.Background(), converged) // converged
+ *clock = clock.Add(5 * time.Minute) // past grace → timer cleared
+ m.observe(context.Background(), converged)
+ *clock = clock.Add(20 * time.Minute)
+ m.observe(context.Background(), stale) // fresh skew, only 20m old
+ if fa.count() != 0 {
+ t.Fatalf("cleared+fresh skew should not alert yet, got %d", fa.count())
+ }
+}
+
+// A one-tick backoff flicker (inside the grace window) must not reset the timer.
+func TestRollHealth_BackoffFlickerKeepsTimer(t *testing.T) {
+ fa := &fakeAlerter{}
+ m, clock := newTestMonitor(fa)
+ until := time.Unix(1_700_000_000, 0).Add(10 * time.Minute)
+ active := rollFleetSnapshot{region: "eastus2", targetVersion: "", backoffActive: true, backoffUntil: until}
+ inactive := rollFleetSnapshot{region: "eastus2", targetVersion: "", backoffActive: false}
+
+ m.observe(context.Background(), active) // t=0 backoff begins
+ *clock = clock.Add(44 * time.Minute)
+ m.observe(context.Background(), active) // t=44m, keeps lastSeen fresh (real ticks are 30s)
+ *clock = clock.Add(1 * time.Minute)
+ m.observe(context.Background(), inactive) // t=45m flicker: 1m gap < 3m grace → timer kept
+ *clock = clock.Add(1 * time.Minute) // t=46m, past 45m deadline
+ m.observe(context.Background(), active)
+
+ if fa.count() == 0 {
+ t.Fatal("backoff persisting past deadline (through a flicker) must alert")
+ }
+ if !strings.Contains(fa.last().Title, "cannot create workers") {
+ t.Errorf("expected creation-backoff alert, got %+v", fa.last())
+ }
+}
+
+// No target version yet → never a false skew alert.
+func TestRollHealth_NoTargetNoAlert(t *testing.T) {
+ fa := &fakeAlerter{}
+ m, clock := newTestMonitor(fa)
+ snap := rollFleetSnapshot{region: "eastus2", targetVersion: "", workers: workers("", "v1", "v2")}
+ m.observe(context.Background(), snap)
+ *clock = clock.Add(90 * time.Minute)
+ m.observe(context.Background(), snap)
+ if fa.count() != 0 {
+ t.Fatalf("no target version must not alert, got %d", fa.count())
+ }
+}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index f4858d9b..5091d385 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -14,6 +14,7 @@ import (
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
+ "github.com/opensandbox/opensandbox/internal/alert"
"github.com/opensandbox/opensandbox/internal/compute"
"github.com/opensandbox/opensandbox/internal/db"
pb "github.com/opensandbox/opensandbox/proto/worker"
@@ -107,6 +108,13 @@ type ScalerConfig struct {
// Empty → use the pool's configured default. Non-quota errors fail the
// launch immediately without burning the rest of the list.
MachineSizes []string
+
+ // Alerter receives roll-stuck alerts (version skew past a deadline, or
+ // creation backoff blocking scale-up). nil → alerts are dropped.
+ Alerter alert.Alerter
+ // RollStuckDeadline is how long a roll may be non-converging before it
+ // alerts. 0 → default 45m.
+ RollStuckDeadline time.Duration
}
// pendingLaunch tracks an EC2 instance that was launched but hasn't registered yet.
@@ -149,6 +157,10 @@ type Scaler struct {
// Rolling replacement: version-aware AMI updates
targetWorkerVersion string // desired worker version (from SSM); workers not matching this get replaced
refreshCount int // tick counter for AMI refresh interval
+
+ // rollHealth alerts when a rolling replace stalls (version skew past a
+ // deadline) or can't proceed (creation backoff). Always non-nil.
+ rollHealth *rollHealthMonitor
}
// NewScaler creates a new autoscaling controller.
@@ -192,6 +204,7 @@ func NewScaler(cfg ScalerConfig) *Scaler {
machineSizes: cfg.MachineSizes,
rdb: cfg.RedisClient,
cellID: cfg.CellID,
+ rollHealth: newRollHealthMonitor(cfg.Alerter, rollHealthConfig{Deadline: cfg.RollStuckDeadline}),
}
}
@@ -296,6 +309,30 @@ func (s *Scaler) evaluate() {
for _, region := range regions {
s.evaluateRegion(ctx, region)
}
+
+ // Roll-stuck alerting runs after the per-region eval, outside
+ // evaluateRegion's lock, so a slow alert delivery can never stall a scaling
+ // decision.
+ s.checkRollHealth(ctx, regions)
+}
+
+// checkRollHealth evaluates rolling-replace convergence per region and alerts on
+// stalls (version skew past the deadline, or creation backoff blocking
+// scale-up). Reads only concurrency-safe registry/state.
+func (s *Scaler) checkRollHealth(ctx context.Context, regions []string) {
+ if s.rollHealth == nil {
+ return
+ }
+ for _, region := range regions {
+ backoffUntil, backoffActive := s.state.GetCreationBackoffUntil(region)
+ s.rollHealth.observe(ctx, rollFleetSnapshot{
+ region: region,
+ targetVersion: s.targetWorkerVersion,
+ workers: s.registry.GetWorkersByRegion(region),
+ backoffActive: backoffActive,
+ backoffUntil: backoffUntil,
+ })
+ }
}
func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
diff --git a/internal/controlplane/usage_parity.go b/internal/controlplane/usage_parity.go
index 8126113f..a9a7cdf3 100644
--- a/internal/controlplane/usage_parity.go
+++ b/internal/controlplane/usage_parity.go
@@ -12,6 +12,7 @@ import (
"strconv"
"time"
+ "github.com/opensandbox/opensandbox/internal/alert"
"github.com/opensandbox/opensandbox/internal/db"
)
@@ -47,6 +48,17 @@ type UsageParityChecker struct {
grace time.Duration // wait this long past a bucket's end before checking
tolerance float64 // fractional drift to tolerate before flagging (e.g. 0.02)
+ // Alerting fires only on SYSTEMIC, SUSTAINED, MATERIAL drift — far above the
+ // per-org log tolerance — so small-org rounding, the known managed-agent
+ // edge>cell skew, and one-off settlement blips don't page anyone.
+ alerter alert.Alerter
+ cellID string
+ alertPct float64 // drift fraction that counts as a material breach (>> tolerance)
+ alertMinGBs float64 // per-org usage floor to be "material" (ignores tiny-org rounding)
+ alertMinOrgs int // material breaching orgs before it's "systemic"
+ alertConsecutive int // consecutive over-threshold buckets before alerting
+ consecutiveBreaches int // run-length of over-threshold buckets (state)
+
client *http.Client
stopCh chan struct{}
doneCh chan struct{}
@@ -72,6 +84,14 @@ type UsageParityConfig struct {
Period time.Duration // default 1h (one closed bucket per run)
Grace time.Duration // default 10m, must match the rollup cron's GRACE_SECONDS
Tolerance float64 // default 0.02 (2%)
+
+ // Alerting (all optional; sensible defaults). Alerter nil => no alerts.
+ Alerter alert.Alerter
+ CellID string
+ AlertPct float64 // default 0.10 (10%) — material breach threshold
+ AlertMinGBs float64 // default 100 GB·s — per-org materiality floor
+ AlertMinOrgs int // default 3 — breaching orgs for "systemic"
+ AlertConsecutive int // default 2 — consecutive buckets before alerting
}
// NewUsageParityChecker returns nil if ParityURL/Secret/Store are unset.
@@ -93,17 +113,39 @@ func NewUsageParityChecker(cfg UsageParityConfig) *UsageParityChecker {
if cfg.Tolerance <= 0 {
cfg.Tolerance = 0.02
}
+ if cfg.AlertPct <= 0 {
+ cfg.AlertPct = 0.10
+ }
+ if cfg.AlertMinGBs <= 0 {
+ cfg.AlertMinGBs = 100
+ }
+ if cfg.AlertMinOrgs <= 0 {
+ cfg.AlertMinOrgs = 3
+ }
+ if cfg.AlertConsecutive <= 0 {
+ cfg.AlertConsecutive = 2
+ }
+ alerter := cfg.Alerter
+ if alerter == nil {
+ alerter = alert.Nop{}
+ }
return &UsageParityChecker{
- store: cfg.Store,
- parityURL: cfg.ParityURL,
- path: u.Path,
- secret: cfg.Secret,
- period: cfg.Period,
- grace: cfg.Grace,
- tolerance: cfg.Tolerance,
- client: &http.Client{Timeout: 20 * time.Second},
- stopCh: make(chan struct{}),
- doneCh: make(chan struct{}),
+ store: cfg.Store,
+ parityURL: cfg.ParityURL,
+ path: u.Path,
+ secret: cfg.Secret,
+ period: cfg.Period,
+ grace: cfg.Grace,
+ tolerance: cfg.Tolerance,
+ alerter: alerter,
+ cellID: cfg.CellID,
+ alertPct: cfg.AlertPct,
+ alertMinGBs: cfg.AlertMinGBs,
+ alertMinOrgs: cfg.AlertMinOrgs,
+ alertConsecutive: cfg.AlertConsecutive,
+ client: &http.Client{Timeout: 20 * time.Second},
+ stopCh: make(chan struct{}),
+ doneCh: make(chan struct{}),
}
}
@@ -180,6 +222,11 @@ func (c *UsageParityChecker) tick(ctx context.Context) error {
checked, flagged, skippedFree := 0, 0, 0
var worstPct float64
var worstOrg string
+ // Materiality accounting for alerting — separate from the per-org log flag.
+ var totalCell, totalEdge float64
+ materialBreaches := 0
+ var worstMatPct float64
+ var worstMatOrg string
for org := range union {
// Free orgs are accounted for at the edge by the CreditAccount DO
// (events-ingest fans out /debit per usage_tick), not by writes to
@@ -202,6 +249,17 @@ func (c *UsageParityChecker) tick(ctx context.Context) error {
checked++
drift := edgeGB - cellGB
pct := driftPct(cellGB, edgeGB)
+ totalCell += cellGB
+ totalEdge += edgeGB
+ // A material breach: meaningful usage AND well past the alert threshold,
+ // so tiny-org rounding can't count toward a page.
+ if math.Max(cellGB, edgeGB) >= c.alertMinGBs && math.Abs(pct) > c.alertPct {
+ materialBreaches++
+ if math.Abs(pct) > math.Abs(worstMatPct) {
+ worstMatPct = pct
+ worstMatOrg = org
+ }
+ }
if math.Abs(pct) > c.tolerance {
flagged++
log.Printf("usage_parity: DRIFT org=%s bucket=%s cell=%.3f edge=%.3f gb·s drift=%+.3f (%+.1f%%)",
@@ -215,9 +273,42 @@ func (c *UsageParityChecker) tick(ctx context.Context) error {
log.Printf("usage_parity: bucket=%s checked=%d flagged=%d skipped_free=%d (tolerance=%.1f%%) worst=%s (%+.1f%%)",
from.Format(time.RFC3339), checked, flagged, skippedFree, c.tolerance*100, worstOrg, worstPct*100)
+
+ c.evaluateBillingAlert(ctx, materialBreaches, worstMatOrg, worstMatPct, totalCell, totalEdge)
return nil
}
+// evaluateBillingAlert fires a Slack alert only when drift is SYSTEMIC (≥N
+// material orgs off, or a material cell-wide aggregate past the threshold) AND
+// SUSTAINED across consecutive buckets. This deliberately ignores the per-org
+// log flag: tiny-org rounding, the known managed-agent edge>cell skew, and
+// one-off settlement blips must never page. It never bills — shadow evidence
+// only — so a Warning (not a page) is the right severity.
+func (c *UsageParityChecker) evaluateBillingAlert(ctx context.Context, materialBreaches int, worstOrg string, worstPct, totalCell, totalEdge float64) {
+ aggPct := driftPct(totalCell, totalEdge)
+ aggMaterial := totalCell >= c.alertMinGBs*float64(c.alertMinOrgs)
+ systemic := materialBreaches >= c.alertMinOrgs || (aggMaterial && math.Abs(aggPct) > c.alertPct)
+ if !systemic {
+ c.consecutiveBreaches = 0
+ return
+ }
+ c.consecutiveBreaches++
+ if c.consecutiveBreaches < c.alertConsecutive {
+ return // one bad bucket isn't enough — wait for it to persist
+ }
+ worst := worstOrg
+ if worst == "" {
+ worst = "n/a"
+ }
+ c.alerter.Send(ctx, alert.Alert{
+ Severity: alert.Warning,
+ Title: fmt.Sprintf("edge/cell billing drift in %s", c.cellID),
+ Detail: fmt.Sprintf("%d orgs >%.0f%% off (worst %s %+.1f%%), cell-aggregate %+.1f%% — sustained %d buckets. Edge-metered GB·s disagrees with cell scale_events; investigate before flipping billing live.",
+ materialBreaches, c.alertPct*100, worst, worstPct*100, aggPct*100, c.consecutiveBreaches),
+ DedupKey: "billing_drift:" + c.cellID,
+ })
+}
+
// cellGBSeconds sums the cell's authoritative GB-seconds for an org over the
// window from sandbox_scale_events (via GetOrgUsage, which already clips to the
// window and excludes agent-subscription sandboxes).
diff --git a/internal/controlplane/usage_parity_alert_test.go b/internal/controlplane/usage_parity_alert_test.go
new file mode 100644
index 00000000..e1d49292
--- /dev/null
+++ b/internal/controlplane/usage_parity_alert_test.go
@@ -0,0 +1,79 @@
+package controlplane
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/internal/alert"
+)
+
+func newTestParity(fa alert.Alerter) *UsageParityChecker {
+ return &UsageParityChecker{
+ alerter: fa,
+ cellID: "eastus2",
+ alertPct: 0.10,
+ alertMinGBs: 100,
+ alertMinOrgs: 3,
+ alertConsecutive: 2,
+ }
+}
+
+// Systemic drift (≥3 material orgs) must alert — but only once it has persisted
+// across the required number of consecutive buckets, not on the first.
+func TestBillingAlert_SystemicSustained(t *testing.T) {
+ fa := &fakeAlerter{}
+ p := newTestParity(fa)
+ // 3 material breaches, cell aggregate +25%.
+ p.evaluateBillingAlert(context.Background(), 3, "org-abc", 0.25, 1000, 1250)
+ if fa.count() != 0 {
+ t.Fatalf("one bucket must not alert, got %d", fa.count())
+ }
+ p.evaluateBillingAlert(context.Background(), 3, "org-abc", 0.25, 1000, 1250)
+ if fa.count() != 1 {
+ t.Fatalf("second consecutive bucket must alert, got %d", fa.count())
+ }
+ a := fa.last()
+ if a.Severity != alert.Warning || !strings.Contains(a.Title, "billing drift") || a.DedupKey != "billing_drift:eastus2" {
+ t.Errorf("unexpected alert: %+v", a)
+ }
+}
+
+// A clean bucket between two breaching ones resets the counter, so a transient
+// single-bucket blip never reaches the consecutive threshold.
+func TestBillingAlert_TransientResets(t *testing.T) {
+ fa := &fakeAlerter{}
+ p := newTestParity(fa)
+ p.evaluateBillingAlert(context.Background(), 3, "x", 0.2, 1000, 1200) // breach, streak=1
+ p.evaluateBillingAlert(context.Background(), 0, "", 0, 1000, 1005) // clean (0.5% agg), reset
+ p.evaluateBillingAlert(context.Background(), 3, "x", 0.2, 1000, 1200) // breach again, streak=1
+ if fa.count() != 0 {
+ t.Fatalf("transient blips must not alert, got %d", fa.count())
+ }
+}
+
+// Fewer than minOrgs breaches but a material cell-wide aggregate over threshold
+// is still systemic (a couple of big orgs badly off).
+func TestBillingAlert_AggregatePath(t *testing.T) {
+ fa := &fakeAlerter{}
+ p := newTestParity(fa)
+ // Only 2 breaching orgs (< 3) but aggregate is +20% on a material cell.
+ p.evaluateBillingAlert(context.Background(), 2, "x", 0.30, 1000, 1200)
+ p.evaluateBillingAlert(context.Background(), 2, "x", 0.30, 1000, 1200)
+ if fa.count() != 1 {
+ t.Fatalf("material aggregate over threshold must alert after 2 buckets, got %d", fa.count())
+ }
+}
+
+// Tiny totals with no material breaches (all small-org rounding) never alert,
+// no matter how many buckets — the floors keep noise out.
+func TestBillingAlert_SmallOrgNoiseNeverAlerts(t *testing.T) {
+ fa := &fakeAlerter{}
+ p := newTestParity(fa)
+ for i := 0; i < 5; i++ {
+ p.evaluateBillingAlert(context.Background(), 0, "", 0, 5, 9) // below the 300 GB·s aggregate floor
+ }
+ if fa.count() != 0 {
+ t.Fatalf("small-org noise must never alert, got %d", fa.count())
+ }
+}