An open-source, faster Devin alternative
TypeScript
refinements
Brian Reardon3376c9846f70
diff --git a/internal/agent/stats.go b/internal/agent/stats.goindex 3281492c..a565e7bf 100644--- a/internal/agent/stats.go+++ b/internal/agent/stats.go@@ -37,7 +37,14 @@ func (s *Server) Shutdown(ctx context.Context, req *pb.ShutdownRequest) (*pb.Shufunc (s *Server) Stats(ctx context.Context, req *pb.StatsRequest) (*pb.StatsResponse, error) {resp := &pb.StatsResponse{}- // Memory from /proc/meminfo+ // Memory from /proc/meminfo. Note we use MemAvailable, not MemFree —+ // MemAvailable is the kernel's own working-set estimate that subtracts+ // reclaimable page cache + slab. So MemTotal-MemAvailable already+ // excludes file-cache pressure (e.g. a `dd` workload won't make this+ // climb to 100% even though page cache fills RAM). The autoscaler reads+ // this value via mem_pct; treating it as a working-set proxy is correct.+ // It is also an upper bound on resident anon memory, so the worker's+ // scale-down OOM floor uses MemUsage * 1.05 as a safe lower bound.memTotal, memAvail := readMemInfo()resp.MemLimit = memTotalresp.MemUsage = memTotal - memAvaildiff --git a/internal/controlplane/autoscaler.go b/internal/controlplane/autoscaler.goindex ccd97bb0..5786bfee 100644--- a/internal/controlplane/autoscaler.go+++ b/internal/controlplane/autoscaler.go@@ -2,7 +2,6 @@ package controlplaneimport ("context"- "fmt""log""sort""sync"@@ -66,8 +65,11 @@ const (type AutoscalerSandboxStore interface {// ListAutoscaleEnabled returns running sandboxes with autoscale_enabled=true.ListAutoscaleEnabled(ctx context.Context) ([]db.AutoscaleSandbox, error)- // UpdateAutoscaleLastEvent records a scale event for cooldown tracking.- UpdateAutoscaleLastEvent(ctx context.Context, sandboxID string, t time.Time) error+ // ClaimAutoscaleEvent atomically claims the right to apply a scale event,+ // guarding against (a) a manual scale that disabled autoscale concurrently+ // and (b) two CPs deciding on the same pre-event row. Returns true if the+ // caller has the claim and may proceed with the gRPC.+ ClaimAutoscaleEvent(ctx context.Context, sandboxID string, prev, now time.Time) (bool, error)}// AutoscalerRegistry is the small subset of WorkerRegistry the autoscaler@@ -161,13 +163,21 @@ func (a *Autoscaler) tick(ctx context.Context) {}func (a *Autoscaler) evaluateOne(ctx context.Context, sb db.AutoscaleSandbox) {- // 1. Fetch current stats from the worker.- memPct, err := a.fetchMemPct(ctx, sb)- if err != nil {- // Transient — log at low frequency and skip.- log.Printf("autoscaler: %s stats fetch failed: %v", sb.SandboxID, err)+ // 1. Fetch current stats from the worker. The registry's cached stats+ // also provide the live MemLimit which is the authoritative current+ // memory size (sandbox_sessions.config does NOT update on scale).+ stats, _, ok := a.registry.GetSandboxStats(sb.SandboxID)+ if !ok {+ // No recent heartbeat — skip this tick; data should appear within ~10s.+ return+ }+ if stats.MemLimit == 0 {+ // Defensive: without a known limit we can't compute a tier. Skip.+ log.Printf("autoscaler: %s no MemLimit in heartbeat; skipping", sb.SandboxID)return}+ sb.CurrentMB = int(stats.MemLimit / (1024 * 1024))+ memPct := stats.MemPct// 2. Record sample.a.recordSample(sb.SandboxID, memPct)@@ -178,33 +188,29 @@ func (a *Autoscaler) evaluateOne(ctx context.Context, sb db.AutoscaleSandbox) {return}- // 4. Apply.+ // 4. Claim the right to scale (atomic CAS — closes manual-vs-auto race+ // and multi-CP race in one step). If 0 rows updated, someone else won.+ now := time.Now()+ claimed, err := a.store.ClaimAutoscaleEvent(ctx, sb.SandboxID, sb.LastEventAt, now)+ if err != nil {+ log.Printf("autoscaler: %s claim failed: %v", sb.SandboxID, err)+ return+ }+ if !claimed {+ log.Printf("autoscaler: %s claim lost (manual scale or peer CP raced); skipping", sb.SandboxID)+ return+ }++ // 5. Apply. Cooldown is already burned (intentional — gRPC failures+ // shouldn't retry-storm at every tick; wait the cooldown out).if err := a.setter.SetSandboxMemoryMB(ctx, sb.SandboxID, target); err != nil {log.Printf("autoscaler: %s scale %d→%d MB failed: %v", sb.SandboxID, sb.CurrentMB, target, err)return}- if err := a.store.UpdateAutoscaleLastEvent(ctx, sb.SandboxID, time.Now()); err != nil {- log.Printf("autoscaler: %s update last_event failed: %v", sb.SandboxID, err)- }log.Printf("autoscaler: %s scaled %d MB → %d MB (mem=%.1f%% min=%d max=%d)",sb.SandboxID, sb.CurrentMB, target, memPct, sb.MinMB, sb.MaxMB)}-// fetchMemPct returns the latest cached mem_pct for a sandbox. Stats are-// populated by worker heartbeats — see internal/qemu/stats_collector.go on-// the worker side and redis_registry.go's handleHeartbeat ingestion.-//-// Returns ok=false (via the err) if no recent heartbeat has carried this-// sandbox. The autoscaler skips the tick for that sandbox; on the next-// heartbeat (~10s later) the data should appear.-func (a *Autoscaler) fetchMemPct(_ context.Context, sb db.AutoscaleSandbox) (float64, error) {- stats, _, ok := a.registry.GetSandboxStats(sb.SandboxID)- if !ok {- return 0, fmt.Errorf("no cached stats for %s — worker heartbeat may be stale", sb.SandboxID)- }- return stats.MemPct, nil-}-func (a *Autoscaler) recordSample(sandboxID string, memPct float64) {a.mu.Lock()defer a.mu.Unlock()@@ -241,7 +247,10 @@ func (a *Autoscaler) decideTarget(sb db.AutoscaleSandbox) int {now := time.Now()// Scale up: 1-min above threshold, current < max, off scale-up cooldown.- if avg1 > scaleUpMemPctThreshold && currentMB < sb.MaxMB {+ // Require at least window1m samples (≥2) so a single noisy reading on a+ // freshly-(re)started CP can't trigger a scale-up before we've had a+ // chance to confirm it.+ if avg1 > scaleUpMemPctThreshold && currentMB < sb.MaxMB && len(s.memSamples) >= window1m {if !sb.LastEventAt.IsZero() && now.Sub(sb.LastEventAt) < scaleUpCooldown {return 0}diff --git a/internal/db/sandbox_autoscale.go b/internal/db/sandbox_autoscale.goindex ffbbe6cf..f825d2c2 100644--- a/internal/db/sandbox_autoscale.go+++ b/internal/db/sandbox_autoscale.go@@ -10,11 +10,17 @@ import (// tick. Defined here (not in internal/controlplane) so the db package owns// its own row type and the autoscaler imports from db rather than the// other way around — avoids the controlplane↔db import cycle.+//+// CurrentMB is intentionally NOT set from sandbox_sessions.config: that+// column is the original creation memory and never updates after a scale+// event (manual or autoscale). The autoscaler populates CurrentMB from the+// live worker heartbeat (registry.SandboxStats.MemLimit) before deciding+// scale targets — that's the only authoritative current size.type AutoscaleSandbox struct {SandboxID stringWorkerID stringOrgID string- CurrentMB int // current memoryMB, parsed from sandbox_sessions.config+ CurrentMB int // populated by autoscaler from registry stats, NOT from DBMinMB int // user-configured floor (0 = unset)MaxMB int // user-configured ceiling (0 = unset)LastEventAt time.Time // zero if never scaled@@ -60,14 +66,11 @@ func (s *Store) GetSandboxAutoscale(ctx context.Context, sandboxID string) (enab// The partial index added in migration 032 keeps this scan cheap regardless// of total session count.//-// CurrentMB is parsed from sandbox_sessions.config — the canonical source--// of-truth for sandbox sizing. We don't track it as a separate column to-// avoid drift between the autoscale "what we think it is" and the worker's-// actual virtio-mem state.+// CurrentMB is left at zero — populated by the caller from live heartbeat+// stats. See the AutoscaleSandbox doc comment.func (s *Store) ListAutoscaleEnabled(ctx context.Context) ([]AutoscaleSandbox, error) {rows, err := s.pool.Query(ctx, `SELECT sandbox_id, worker_id, org_id::text,- COALESCE((config->>'memoryMB')::int, 0) AS current_mb,COALESCE(autoscale_min_mb, 0) AS min_mb,COALESCE(autoscale_max_mb, 0) AS max_mb,COALESCE(autoscale_last_event_at, '1970-01-01'::timestamptz) AS last_event_at@@ -83,7 +86,7 @@ func (s *Store) ListAutoscaleEnabled(ctx context.Context) ([]AutoscaleSandbox, efor rows.Next() {var sb AutoscaleSandboxif err := rows.Scan(&sb.SandboxID, &sb.WorkerID, &sb.OrgID,- &sb.CurrentMB, &sb.MinMB, &sb.MaxMB, &sb.LastEventAt); err != nil {+ &sb.MinMB, &sb.MaxMB, &sb.LastEventAt); err != nil {return nil, err}out = append(out, sb)@@ -91,12 +94,39 @@ func (s *Store) ListAutoscaleEnabled(ctx context.Context) ([]AutoscaleSandbox, ereturn out, rows.Err()}-// UpdateAutoscaleLastEvent stamps the cooldown anchor after a scale event-// (either direction). The autoscaler reads this before deciding whether-// the per-direction cooldown has elapsed.-func (s *Store) UpdateAutoscaleLastEvent(ctx context.Context, sandboxID string, t time.Time) error {- _, err := s.pool.Exec(ctx, `- UPDATE sandbox_sessions SET autoscale_last_event_at = $1 WHERE sandbox_id = $2- `, t, sandboxID)- return err+// ClaimAutoscaleEvent atomically claims the right to apply a scale event for+// this sandbox. Performs a CAS on (autoscale_enabled, autoscale_last_event_at):+//+// - autoscale_enabled must still be TRUE — guards against a manual /scale+// call (which sets enabled=false) racing with an in-flight autoscaler tick.+// - autoscale_last_event_at must equal the value the caller observed —+// guards against two control planes both deciding to scale on the same+// pre-event row.+//+// If either guard fails, RowsAffected is 0 and the caller MUST NOT proceed+// with the scale: another writer either disabled autoscale or already+// claimed the event. On success the cooldown anchor is updated to `now`,+// so a subsequent gRPC failure simply means we'll retry on the next cooldown+// boundary rather than retry-storming.+//+// `prev` is the LastEventAt value the caller read from ListAutoscaleEnabled+// (zero-valued for never-scaled sandboxes — handled via IS NOT DISTINCT FROM).+func (s *Store) ClaimAutoscaleEvent(ctx context.Context, sandboxID string, prev, now time.Time) (bool, error) {+ // Treat the seeded sentinel from ListAutoscaleEnabled (1970-01-01) as+ // "never scaled" so the CAS matches the actual NULL stored on the row.+ var prevArg interface{} = prev+ if prev.Year() <= 1970 {+ prevArg = nil+ }+ tag, err := s.pool.Exec(ctx, `+ UPDATE sandbox_sessions+ SET autoscale_last_event_at = $1+ WHERE sandbox_id = $2+ AND autoscale_enabled = TRUE+ AND autoscale_last_event_at IS NOT DISTINCT FROM $3+ `, now, sandboxID, prevArg)+ if err != nil {+ return false, err+ }+ return tag.RowsAffected() == 1, nil}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex fa3163a1..eb0eca62 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -1921,6 +1921,26 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPi}if additionalMB != vm.virtioMemRequestedMB {+ // Shrink-safety: if we're reducing memory, ensure the new total+ // won't be below the guest's working set. virtio-mem unplug below+ // resident anon memory will OOM-kill processes inside the guest.+ // We use MemUsage (= MemTotal - MemAvailable from /proc/meminfo+ // inside the guest) as a conservative upper bound on anon — it+ // includes some active page cache but is always ≥ resident anon.+ // 5% headroom covers transient growth during the unplug window.+ if additionalMB < vm.virtioMemRequestedMB && vm.agent != nil {+ newTotalMB := vm.baseMemoryMB + additionalMB+ if stats, statsErr := vm.agent.Stats(ctx); statsErr == nil && stats != nil && stats.MemUsage > 0 {+ usedMB := int(stats.MemUsage / (1024 * 1024))+ floorMB := usedMB * 105 / 100+ if newTotalMB < floorMB {+ log.Printf("qemu: virtio-mem %s: refusing shrink to %dMB — working set %dMB requires ≥%dMB",+ sandboxID, newTotalMB, usedMB, floorMB)+ return fmt.Errorf("oom_floor: target %dMB below guest working set (%dMB used, %dMB floor)",+ newTotalMB, usedMB, floorMB)+ }+ }+ }if err := vm.qmp.SetVirtioMemSize(additionalMB); err != nil {log.Printf("qemu: virtio-mem %s: set %dMB failed: %v — returning insufficient capacity error", sandboxID, additionalMB, err)return fmt.Errorf("insufficient_capacity: cannot hotplug %dMB on this worker: %w", additionalMB, err)