Skip to content

An open-source, faster Devin alternative

TypeScript

fix parity issues, memory, and 2.5pct bug

Brian Reardonf2516a7aefcc
diff --git a/internal/controlplane/usage_parity.go b/internal/controlplane/usage_parity.go
index 10bc2a0d..8126113f 100644
--- a/internal/controlplane/usage_parity.go
+++ b/internal/controlplane/usage_parity.go
@@ -57,6 +57,11 @@ type UsageParityChecker struct {
type usageParitySource interface {
GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]db.OrgUsageSummary, error)
ListOrgIDsWithScaleEvents(ctx context.Context, from, to time.Time) ([]string, error)
+ // GetOrgPlan is used to skip free orgs, whose edge-side accounting lives
+ // in the CreditAccount DO (per-event /debit fan-out) rather than in the
+ // edge's usage_samples table. Comparing a free org's cell GB-seconds to
+ // usage_samples is a category mismatch — it will always report -100%.
+ GetOrgPlan(ctx context.Context, orgID string) (string, error)
}
// UsageParityConfig configures the checker. ParityURL empty => disabled.
@@ -172,10 +177,22 @@ func (c *UsageParityChecker) tick(ctx context.Context) error {
union[id] = struct{}{}
}
- checked, flagged := 0, 0
+ checked, flagged, skippedFree := 0, 0, 0
var worstPct float64
var worstOrg 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
+ // usage_samples. Comparing their cell GB·s against an empty
+ // usage_samples slice is a category mismatch — would always emit
+ // -100% drift and drown out real signal.
+ plan, planErr := c.store.GetOrgPlan(ctx, org)
+ if planErr != nil {
+ log.Printf("usage_parity: org=%s plan lookup failed: %v — including in check anyway", org, planErr)
+ } else if plan != "pro" {
+ skippedFree++
+ continue
+ }
cellGB, err := c.cellGBSeconds(ctx, org, from, to)
if err != nil {
log.Printf("usage_parity: org=%s cell usage: %v", org, err)
@@ -196,8 +213,8 @@ func (c *UsageParityChecker) tick(ctx context.Context) error {
}
}
- log.Printf("usage_parity: bucket=%s checked=%d flagged=%d (tolerance=%.1f%%) worst=%s (%+.1f%%)",
- from.Format(time.RFC3339), checked, flagged, c.tolerance*100, worstOrg, worstPct*100)
+ 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)
return nil
}
diff --git a/internal/db/store.go b/internal/db/store.go
index 8e8450db..1a92e684 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -286,6 +286,23 @@ func (s *Store) UpsertUserFromCapToken(ctx context.Context, userID, orgID uuid.U
// before sandbox create — when the edge has authoritatively decided this org
// is valid, but the cell PG may not have seen it yet (no backfill).
//
+// GetOrgPlan returns the plan string for an org without hydrating the full
+// row. Used by the usage-parity checker (and any other caller that just
+// needs to gate on pro vs free) to avoid an unnecessary GetOrg roundtrip.
+// Empty string + nil error when the org row doesn't exist — caller decides
+// whether that's a hard failure or a "skip silently" condition.
+func (s *Store) GetOrgPlan(ctx context.Context, orgID string) (string, error) {
+ var plan string
+ err := s.pool.QueryRow(ctx, `SELECT plan FROM orgs WHERE id = $1`, orgID).Scan(&plan)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return "", nil
+ }
+ return "", fmt.Errorf("get org plan: %w", err)
+ }
+ return plan, nil
+}
+
// Plan from the cap-token wins on insert; on conflict we update plan so a
// pro-upgrade reflected at the edge propagates to the cell on the next
// sandbox-create round-trip without a separate sync job.
diff --git a/internal/db/usage.go b/internal/db/usage.go
index 0956ee3a..7897eb5b 100644
--- a/internal/db/usage.go
+++ b/internal/db/usage.go
@@ -184,9 +184,19 @@ type OrgUsageSummary struct {
// short-circuits and the scale event is billed normally — i.e. the default
// is "bill it", which keeps us safe in all the unknown cases.
func (s *Store) GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]OrgUsageSummary, error) {
+ // The clip on ended_at is the LEAST of "the row's actual end" (or now() if
+ // still open) and "the window end $3". The previous form
+ // COALESCE(ended_at, LEAST(now(), $3))
+ // only clipped to $3 when ended_at IS NULL. A scale event with a non-null
+ // ended_at extending past the bucket's end (e.g. a sandbox that scaled at
+ // 17:14 while we're computing the 16:00 bucket) was attributed its FULL
+ // duration (16:42 → 17:14 = 32m) to that prior bucket, even though only
+ // 18m of it fell inside [16:00, 17:00). On long-running sandboxes this
+ // manifested as a phantom "edge under-counts cell" drift on every parity
+ // check that spanned a scale-event boundary.
rows, err := s.pool.Query(ctx, `
SELECT memory_mb, cpu_percent, disk_mb,
- SUM(EXTRACT(EPOCH FROM (COALESCE(ended_at, LEAST(now(), $3)) - GREATEST(started_at, $2)))) as total_seconds
+ SUM(EXTRACT(EPOCH FROM (LEAST(COALESCE(ended_at, now()), $3) - GREATEST(started_at, $2)))) as total_seconds
FROM sandbox_scale_events se
WHERE org_id = $1
AND started_at < $3
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 87bbfeaf..52e096c3 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -781,11 +781,24 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest
}
}
- // Resume billing scale event after wake. Disk size is preserved across wake —
- // pass 0 so RecordScaleEvent inherits disk_mb from the prior event.
+ // Resume billing scale event after wake. The post-wake config is whatever
+ // the manager just restored (virtio-mem plugs the snapshot back to its
+ // pre-hibernate total, so sb.MemoryMB reflects the actual running tier).
+ // Pre-fix this was hardcoded to 1024 MB / 100% CPU with a TODO, so every
+ // woken sandbox got billed at the smallest tier in cell PG regardless of
+ // the actual memory the worker just plugged in — direct cause of the
+ // "cell under-counts wake" drift the parity checker was reporting.
+ // Disk size is preserved across wake; pass 0 so RecordScaleEvent inherits
+ // disk_mb from the prior event.
if s.store != nil {
- memMB := 1024 // TODO: get actual memory from sandbox state
- cpuPct := 100
+ memMB := sb.MemoryMB
+ if memMB <= 0 {
+ memMB = 1024
+ }
+ cpuPct := (memMB * 100) / 1024
+ if cpuPct < 100 {
+ cpuPct = 100
+ }
orgID, _ := s.store.GetSandboxOrgID(ctx, sb.ID)
if orgID != "" {
if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct, 0); err != nil {
diff --git a/internal/worker/usage_ticker.go b/internal/worker/usage_ticker.go
index 30dfafe4..f4b87c5f 100644
--- a/internal/worker/usage_ticker.go
+++ b/internal/worker/usage_ticker.go
@@ -75,8 +75,16 @@ type UsageTicker struct {
interval time.Duration
costPerTickCs int // cents debited per FULL tick interval; scaled by actual interval below
- mu sync.Mutex
+ mu sync.Mutex
lastSeen map[string]time.Time // sandbox_id → last emit wall-clock
+ // fracRemainder carries the sub-second portion of elapsed time forward
+ // across emits. Without it, `int(elapsed.Seconds())` truncated each tick's
+ // fractional part — ~0.5s lost per tick on average, which compounded into
+ // a ~2.5% systematic under-count on every long-running sandbox (180 ticks
+ // × 0.5s = 90s/hr = 2.5%). With carry-forward, the remainder is bounded
+ // in [0, 1) and any cumulative leftover gets emitted the moment it crosses
+ // a whole second, so long-term drift is zero.
+ fracRemainder map[string]float64
stop chan struct{}
stopped chan struct{}
@@ -104,6 +112,7 @@ func NewUsageTicker(manager sandbox.Manager, sandboxDBs *sandbox.SandboxDBManage
interval: interval,
costPerTickCs: costPerTickCs,
lastSeen: make(map[string]time.Time),
+ fracRemainder: make(map[string]float64),
stop: make(chan struct{}),
stopped: make(chan struct{}),
}
@@ -178,10 +187,15 @@ func (t *UsageTicker) tick(ctx context.Context) {
}
aliveIDs = append(aliveIDs, sb.ID)
- intervalSec := t.intervalSecondsFor(sb, now)
+ intervalSec, newRemainder := t.intervalSecondsFor(sb, now)
if intervalSec <= 0 {
- // Pathological — clock went backwards or two ticks landed in the
- // same instant. Skip rather than emit a zero/negative debit.
+ // Pathological (clock skew, two ticks in same instant) OR a sub-
+ // second elapsed window that didn't cross a whole-second boundary
+ // yet — in either case, do not emit but DO carry the remainder
+ // forward so we emit the leftover on the next tick when it
+ // crosses ≥1s. Otherwise sub-second jitter at very fast tick
+ // rates would silently drop time.
+ t.markEmitted(sb.ID, now, newRemainder)
continue
}
@@ -206,7 +220,7 @@ func (t *UsageTicker) tick(ctx context.Context) {
log.Printf("usage_ticker: %s: LogEvent failed: %v", sb.ID, err)
continue
}
- t.markEmitted(sb.ID, now)
+ t.markEmitted(sb.ID, now, newRemainder)
emitted++
}
// Drop state for any sandbox we tracked that didn't appear alive this
@@ -217,14 +231,19 @@ func (t *UsageTicker) tick(ctx context.Context) {
log.Printf("usage_ticker: tick: emitted %d usage_tick event(s) for %d listed sandbox(es) (skipped %d as not-alive)", emitted, len(list), skippedDead)
}
-// intervalSecondsFor returns the actual elapsed time (in seconds, integer-rounded)
-// to attribute to this emit. Read-only on the state map.
-func (t *UsageTicker) intervalSecondsFor(sb types.Sandbox, now time.Time) int {
+// intervalSecondsFor returns the actual elapsed time to attribute to this emit
+// as (whole-seconds, leftover-fractional-remainder). The remainder is carried
+// forward to the next tick via markEmitted so that sub-second jitter doesn't
+// accumulate into systematic under-counts. Caller passes the new remainder back
+// to markEmitted; this function is read-only on the state map.
+func (t *UsageTicker) intervalSecondsFor(sb types.Sandbox, now time.Time) (int, float64) {
t.mu.Lock()
last, seen := t.lastSeen[sb.ID]
+ carried := t.fracRemainder[sb.ID]
t.mu.Unlock()
var elapsed time.Duration
+ capped := false
if !seen {
// First observation. Measure from sandbox start so a sandbox that
// lived briefly between two tick boundaries is attributed its actual
@@ -236,12 +255,16 @@ func (t *UsageTicker) intervalSecondsFor(sb types.Sandbox, now time.Time) int {
// retroactively backfilling history that was never measured.
if sb.StartedAt.IsZero() {
elapsed = t.interval
+ capped = true
} else {
elapsed = now.Sub(sb.StartedAt)
if elapsed > t.interval {
elapsed = t.interval
+ capped = true
}
}
+ // No prior remainder to carry on first observation.
+ carried = 0
} else {
elapsed = now.Sub(last)
// Safety cap at 2× tick interval. Steady state is 1× ± scheduling
@@ -251,12 +274,22 @@ func (t *UsageTicker) intervalSecondsFor(sb types.Sandbox, now time.Time) int {
// period of catch-up.
if max := 2 * t.interval; elapsed > max {
elapsed = max
+ capped = true
}
}
if elapsed < 0 {
- return 0
+ return 0, 0
}
- return int(elapsed.Seconds())
+ // When we deliberately capped (long gap, unknown StartedAt), the dropped
+ // time is intentional under-billing and should NOT be preserved in the
+ // remainder — otherwise the cap is meaningless.
+ if capped {
+ carried = 0
+ }
+ totalSecs := elapsed.Seconds() + carried
+ emitSecs := int(totalSecs) // floor
+ newRemainder := totalSecs - float64(emitSecs)
+ return emitSecs, newRemainder
}
// scaledCost returns cents proportional to elapsed time. Steady state at the
@@ -269,15 +302,17 @@ func (t *UsageTicker) scaledCost(intervalSec int) int {
return t.costPerTickCs * intervalSec / int(t.interval.Seconds())
}
-func (t *UsageTicker) markEmitted(sandboxID string, when time.Time) {
+func (t *UsageTicker) markEmitted(sandboxID string, when time.Time, remainder float64) {
t.mu.Lock()
t.lastSeen[sandboxID] = when
+ t.fracRemainder[sandboxID] = remainder
t.mu.Unlock()
}
func (t *UsageTicker) dropState(sandboxID string) {
t.mu.Lock()
delete(t.lastSeen, sandboxID)
+ delete(t.fracRemainder, sandboxID)
t.mu.Unlock()
}
@@ -294,6 +329,7 @@ func (t *UsageTicker) pruneStateNotIn(keep []string) {
for id := range t.lastSeen {
if _, ok := keepSet[id]; !ok {
delete(t.lastSeen, id)
+ delete(t.fracRemainder, id)
}
}
}
@@ -345,7 +381,11 @@ func (t *UsageTicker) OnSandboxHibernate(sandboxID string, memoryMB, cpuCount in
// returns early on missing lastSeen). Setting lastSeen=now gives every
// subsequent emit a measurable starting point.
func (t *UsageTicker) OnSandboxWake(sandboxID string) {
- t.markEmitted(sandboxID, time.Now())
+ // Reset the fractional remainder along with lastSeen. The pre-hibernate
+ // remainder is fully out-of-band relative to post-wake billing — keeping
+ // it would let pre-hibernate sub-second leftovers leak into the first
+ // post-wake emit.
+ t.markEmitted(sandboxID, time.Now(), 0)
}
// flushSlice emits one usage_tick for the elapsed-since-last-seen interval
diff --git a/internal/worker/usage_ticker_test.go b/internal/worker/usage_ticker_test.go
index 17b040c2..9885d29b 100644
--- a/internal/worker/usage_ticker_test.go
+++ b/internal/worker/usage_ticker_test.go
@@ -17,6 +17,7 @@ func newTestTicker(tickInterval time.Duration, costPerTickCs int) *UsageTicker {
interval: tickInterval,
costPerTickCs: costPerTickCs,
lastSeen: make(map[string]time.Time),
+ fracRemainder: make(map[string]float64),
}
}
@@ -39,7 +40,7 @@ func TestIntervalSecondsFor_FirstObservation_UsesSandboxStart(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
sb := types.Sandbox{ID: "sb-" + c.name, StartedAt: now.Add(-time.Duration(c.lifeSecs) * time.Second)}
- got := ticker.intervalSecondsFor(sb, now)
+ got, _ := ticker.intervalSecondsFor(sb, now)
if got != c.want {
t.Errorf("first-observation interval: got %d, want %d (lifeSecs=%d)", got, c.want, c.lifeSecs)
}
@@ -53,7 +54,7 @@ func TestIntervalSecondsFor_FirstObservation_ZeroStartedAtDefaultsToTick(t *test
now := time.Now()
sb := types.Sandbox{ID: "sb-no-start"} // StartedAt zero value
- got := ticker.intervalSecondsFor(sb, now)
+ got, _ := ticker.intervalSecondsFor(sb, now)
if got != 20 {
t.Errorf("no StartedAt should default to full tick interval; got %d, want 20", got)
}
@@ -67,14 +68,14 @@ func TestIntervalSecondsFor_SubsequentEmits_UseLastSeen(t *testing.T) {
sb := types.Sandbox{ID: "sb-1", StartedAt: t0.Add(-5 * time.Second)}
// First emit at t0: should use StartedAt (5s ago).
- if got := ticker.intervalSecondsFor(sb, t0); got != 5 {
+ if got, _ := ticker.intervalSecondsFor(sb, t0); got != 5 {
t.Fatalf("first emit want 5, got %d", got)
}
- ticker.markEmitted(sb.ID, t0)
+ ticker.markEmitted(sb.ID, t0, 0)
// Subsequent emit 20s later — should use lastSeen, not StartedAt (25s).
t1 := t0.Add(20 * time.Second)
- if got := ticker.intervalSecondsFor(sb, t1); got != 20 {
+ if got, _ := ticker.intervalSecondsFor(sb, t1); got != 20 {
t.Errorf("subsequent emit 20s after last want 20, got %d", got)
}
}
@@ -85,27 +86,140 @@ func TestIntervalSecondsFor_SubsequentEmits_CapsAt2xTickInterval(t *testing.T) {
t0 := time.Date(2026, 6, 4, 12, 0, 0, 0, time.UTC)
sb := types.Sandbox{ID: "sb-1", StartedAt: t0.Add(-5 * time.Second)}
- ticker.markEmitted(sb.ID, t0)
+ ticker.markEmitted(sb.ID, t0, 0)
// Simulate a big gap (e.g. hibernation we failed to detect): an hour later.
// Without the cap we'd attribute 3600 seconds; with the cap, 40.
tLate := t0.Add(time.Hour)
- got := ticker.intervalSecondsFor(sb, tLate)
+ got, _ := ticker.intervalSecondsFor(sb, tLate)
if got != 40 {
t.Errorf("gap > 2x tick should cap at 40 (= 2×20), got %d", got)
}
}
+// TestIntervalSecondsFor_FractionalRemainder_CarriesForwardNoDrift pins the
+// fix for the steady-state ~2.5% under-count.
+//
+// Pre-fix: int(elapsed.Seconds()) truncated each tick's fractional part. If
+// actual elapsed was 19.5s every tick, each one billed 19s and silently lost
+// 0.5s. Over 180 ticks/hour = 90s/hour lost = 2.5% systematic under-bill.
+//
+// Post-fix: the fractional leftover is stashed in fracRemainder and added to
+// the next tick's elapsed. After enough ticks the cumulative leftover crosses
+// a whole-second boundary and gets billed as a 20s tick instead of the usual
+// 19s. Long-term drift goes to zero; the carried value stays bounded in [0, 1).
+func TestIntervalSecondsFor_FractionalRemainder_CarriesForwardNoDrift(t *testing.T) {
+ tick := 20 * time.Second
+ ticker := newTestTicker(tick, 10)
+ t0 := time.Date(2026, 6, 4, 12, 0, 0, 0, time.UTC)
+ sb := types.Sandbox{ID: "sb-steady", StartedAt: t0}
+ ticker.markEmitted(sb.ID, t0, 0)
+
+ // Simulate 200 ticks with 19.5s elapsed each (the average inter-tick gap
+ // we observed in prod). Real total elapsed: 200 × 19.5 = 3900s. Pre-fix
+ // would bill 200 × 19 = 3800s (100s lost). Post-fix should bill 3900s ±
+ // at most one second (the in-flight remainder at the end of the run).
+ totalBilled := 0
+ now := t0
+ for i := 0; i < 200; i++ {
+ now = now.Add(19500 * time.Millisecond) // 19.5s
+ emit, rem := ticker.intervalSecondsFor(sb, now)
+ totalBilled += emit
+ ticker.markEmitted(sb.ID, now, rem)
+ if rem < 0 || rem >= 1 {
+ t.Fatalf("remainder must stay in [0,1); got %g at tick %d", rem, i)
+ }
+ }
+ // Allow ±1s for the leftover that hasn't crossed a boundary yet.
+ wantApprox := 19 * 200 // would be 19 per tick on the old code → 3800
+ wantExact := 3900 // 200 × 19.5
+ if totalBilled <= wantApprox {
+ t.Fatalf("carry-forward not working: billed %ds <= pre-fix-truncation %ds", totalBilled, wantApprox)
+ }
+ if diff := wantExact - totalBilled; diff < 0 || diff > 1 {
+ t.Fatalf("steady-state drift: billed %ds, want within 1s of %ds (off by %ds)", totalBilled, wantExact, diff)
+ }
+}
+
+// TestIntervalSecondsFor_FractionalRemainder_SubSecondTicksAccumulate pins the
+// "tick fires multiple times per second" edge case. Each individual elapsed
+// is < 1s so emit=0, but the remainder must carry so the eventual cumulative
+// crossing of 1s gets emitted. Without this, very fast ticking would drop all
+// time silently.
+func TestIntervalSecondsFor_FractionalRemainder_SubSecondTicksAccumulate(t *testing.T) {
+ tick := 20 * time.Second
+ ticker := newTestTicker(tick, 10)
+ t0 := time.Date(2026, 6, 4, 12, 0, 0, 0, time.UTC)
+ sb := types.Sandbox{ID: "sb-fast", StartedAt: t0}
+ ticker.markEmitted(sb.ID, t0, 0)
+
+ // Three sub-second ticks: 0.4s, 0.4s, 0.4s → total 1.2s elapsed.
+ // First two emit 0 but carry 0.4 and 0.8; third crosses 1s, emits 1, carries 0.2.
+ cases := []struct {
+ advanceMs int
+ wantEmit int
+ wantRemainAbout float64
+ }{
+ {400, 0, 0.4},
+ {400, 0, 0.8},
+ {400, 1, 0.2},
+ }
+ now := t0
+ totalEmit := 0
+ for i, c := range cases {
+ now = now.Add(time.Duration(c.advanceMs) * time.Millisecond)
+ emit, rem := ticker.intervalSecondsFor(sb, now)
+ totalEmit += emit
+ if emit != c.wantEmit {
+ t.Errorf("step %d: emit=%d, want %d", i, emit, c.wantEmit)
+ }
+ if abs := rem - c.wantRemainAbout; abs > 0.001 || abs < -0.001 {
+ t.Errorf("step %d: remainder=%g, want ~%g", i, rem, c.wantRemainAbout)
+ }
+ ticker.markEmitted(sb.ID, now, rem)
+ }
+ if totalEmit != 1 {
+ t.Errorf("three 0.4s ticks should emit 1s total (cumulative >= 1.0); got %d", totalEmit)
+ }
+}
+
+// TestIntervalSecondsFor_FractionalRemainder_CapDiscardsRemainder pins that
+// when intervalSecondsFor caps the elapsed (e.g. a 2× tick-interval gap from
+// a missed wake-detection), the carried remainder is also dropped. Otherwise
+// the cap is meaningless — a prior fractional carry would let us bill back
+// the very seconds we deliberately chose to drop.
+func TestIntervalSecondsFor_FractionalRemainder_CapDiscardsRemainder(t *testing.T) {
+ tick := 20 * time.Second
+ ticker := newTestTicker(tick, 10)
+ t0 := time.Date(2026, 6, 4, 12, 0, 0, 0, time.UTC)
+ sb := types.Sandbox{ID: "sb-1", StartedAt: t0}
+
+ // Seed a sizable carried remainder (0.99s) and an old lastSeen.
+ ticker.markEmitted(sb.ID, t0, 0.99)
+ // Now jump an hour into the future — that's >> 2× interval, so the cap
+ // kicks in (elapsed clamps to 40s = 2×20s).
+ tLate := t0.Add(time.Hour)
+ emit, rem := ticker.intervalSecondsFor(sb, tLate)
+ if emit != 40 {
+ t.Errorf("capped emit want 40 (2×interval); got %d", emit)
+ }
+ // With cap engaged, the carried 0.99 is discarded — new remainder should
+ // be the fractional part of 40.0 (= 0), NOT 40.99 → 40 emit + 0.99 carry.
+ if rem != 0 {
+ t.Errorf("capped tick must zero the carried remainder; got %g", rem)
+ }
+}
+
func TestIntervalSecondsFor_ClockBackwardReturnsZero(t *testing.T) {
tick := 20 * time.Second
ticker := newTestTicker(tick, 10)
t0 := time.Date(2026, 6, 4, 12, 0, 0, 0, time.UTC)
sb := types.Sandbox{ID: "sb-1", StartedAt: t0}
- ticker.markEmitted(sb.ID, t0)
+ ticker.markEmitted(sb.ID, t0, 0)
earlier := t0.Add(-5 * time.Second)
- if got := ticker.intervalSecondsFor(sb, earlier); got != 0 {
+ if got, _ := ticker.intervalSecondsFor(sb, earlier); got != 0 {
t.Errorf("clock going backwards should yield 0, got %d", got)
}
}
@@ -147,8 +261,8 @@ func TestStateLifecycle_MarkAndDrop(t *testing.T) {
ticker := newTestTicker(20*time.Second, 10)
t0 := time.Now()
- ticker.markEmitted("sb-1", t0)
- ticker.markEmitted("sb-2", t0)
+ ticker.markEmitted("sb-1", t0, 0)
+ ticker.markEmitted("sb-2", t0, 0)
// Both tracked
if len(ticker.lastSeen) != 2 {
@@ -168,9 +282,9 @@ func TestStateLifecycle_MarkAndDrop(t *testing.T) {
func TestPruneStateNotIn(t *testing.T) {
ticker := newTestTicker(20*time.Second, 10)
t0 := time.Now()
- ticker.markEmitted("sb-a", t0)
- ticker.markEmitted("sb-b", t0)
- ticker.markEmitted("sb-c", t0)
+ ticker.markEmitted("sb-a", t0, 0)
+ ticker.markEmitted("sb-b", t0, 0)
+ ticker.markEmitted("sb-c", t0, 0)
// Only sb-a and sb-c are alive this tick.
ticker.pruneStateNotIn([]string{"sb-a", "sb-c"})
@@ -224,7 +338,7 @@ func TestOnSandboxScale_TrueNoOpWhenNoStartedAtAndUnseen(t *testing.T) {
func TestOnSandboxScale_ResetsLastSeen(t *testing.T) {
ticker := newTestTicker(20*time.Second, 10)
t0 := time.Now().Add(-30 * time.Second)
- ticker.markEmitted("sb-1", t0)
+ ticker.markEmitted("sb-1", t0, 0)
// flushSlice without sandboxDBs will hit the LogEvent path and fail; we
// guard against the nil deref by skipping the LogEvent test. Just check
@@ -247,8 +361,8 @@ func TestOnSandboxScale_ResetsLastSeen(t *testing.T) {
func TestOnSandboxDestroy_DropsState(t *testing.T) {
ticker := newTestTicker(20*time.Second, 10)
t0 := time.Now().Add(-15 * time.Second)
- ticker.markEmitted("sb-1", t0)
- ticker.markEmitted("sb-2", t0)
+ ticker.markEmitted("sb-1", t0, 0)
+ ticker.markEmitted("sb-2", t0, 0)
// With nil sandboxDBs, flushSlice will skip the LogEvent but still drop
// state (state mutation happens before the Get/Log call).
@@ -296,7 +410,7 @@ func TestRegression_DestroyWithoutPriorTick_UsesStartedAt(t *testing.T) {
func TestOnSandboxHibernate_DropsState(t *testing.T) {
ticker := newTestTicker(20*time.Second, 10)
t0 := time.Now().Add(-15 * time.Second)
- ticker.markEmitted("sb-1", t0)
+ ticker.markEmitted("sb-1", t0, 0)
ticker.sandboxDBs = nil
defer func() {
@@ -313,7 +427,7 @@ func TestOnSandboxHibernate_DropsState(t *testing.T) {
func TestOnSandboxWake_SetsLastSeenToNow(t *testing.T) {
ticker := newTestTicker(20*time.Second, 10)
t0 := time.Now().Add(-1 * time.Hour) // simulate pre-hibernate state from long ago
- ticker.markEmitted("sb-1", t0)
+ ticker.markEmitted("sb-1", t0, 0)
before := time.Now()
ticker.OnSandboxWake("sb-1")
@@ -378,7 +492,7 @@ func TestRegression_ShortSandboxNoLongerOverbilled(t *testing.T) {
// Sandbox that lived 4 seconds — what sid's workload looks like.
sb := types.Sandbox{ID: "sb-bursty", StartedAt: now.Add(-4 * time.Second), MemoryMB: 4096}
- interval := ticker.intervalSecondsFor(sb, now)
+ interval, _ := ticker.intervalSecondsFor(sb, now)
cost := ticker.scaledCost(interval)
// 4s elapsed, attributed as 4s — not 20s as in the broken version.
@@ -391,9 +505,9 @@ func TestRegression_ShortSandboxNoLongerOverbilled(t *testing.T) {
}
// Sanity: a 1-hour-long-lived sandbox at steady-state still bills 10c per tick.
- ticker.markEmitted("sb-long", now.Add(-20*time.Second))
+ ticker.markEmitted("sb-long", now.Add(-20*time.Second), 0)
sbLong := types.Sandbox{ID: "sb-long", StartedAt: now.Add(-time.Hour), MemoryMB: 4096}
- if got := ticker.intervalSecondsFor(sbLong, now); got != 20 {
+ if got, _ := ticker.intervalSecondsFor(sbLong, now); got != 20 {
t.Errorf("steady-state tick want 20s, got %d", got)
}
if got := ticker.scaledCost(20); got != 10 {