An open-source, faster Devin alternative
TypeScript
fix(billing): bill the final usage slice on every destroy path and stop the zombie-tick guard dropping it, so a short sandbox is charged for the time it actually ran
Brian Reardon4f9958e1d12c
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 950f7e6c..e4a4a490 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -447,17 +447,42 @@ export default {];const owners = await resolveSandboxOwners(env, tickSandboxIds);const TERMINAL_STATUSES = new Set(["stopped", "terminated", "failed", "error"]);- let droppedZombieTicks = 0;+ // Split by cause. These used to share one counter, which is why the bug+ // below survived: the terminal drops fire constantly and legitimately (they+ // are the ghost-tick defence doing its job), so a handful of wrongly-dropped+ // closing slices hid inside a number that always looked busy. Measured on+ // dev: 57,633 periodic drops — correct — masking 2,685 closing slices that+ // should have billed. A dropped FINAL tick is always worth looking at; a+ // dropped periodic one usually is not.+ let droppedTerminalTicks = 0;+ let droppedNonOwnerTicks = 0;+ // isFinalTick: the slice emitted BY a destroy or hibernate, as opposed to+ // one from the periodic sampler. The producer sets it (internal/worker/+ // usage_ticker.go flushSlice); absent means "not final", so an older cell+ // that does not send it behaves exactly as before.+ const isFinalTick = (e: SandboxEventEnvelope): boolean =>+ ((e.payload ?? {}) as { final?: boolean }).final === true;const tickFromCurrentWorker = (e: SandboxEventEnvelope): boolean => {if (!owners.ok) return true;const row = e.sandbox_id ? owners.byId.get(e.sandbox_id) : undefined;if (!row) return true; // no index row yet — don't drop a legit fresh create- if (TERMINAL_STATUSES.has(row.status)) {- droppedZombieTicks++;+ // A terminal sandbox must not keep accruing usage — that is the ghost-tick+ // bleed this guard exists for. But the CLOSING slice is emitted at the+ // moment the sandbox ends, so it necessarily races the very status change+ // that makes this test true, and dropping it means any sandbox that lived+ // and died inside one 20s sampling window bills nothing at all.+ //+ // Exempting it here is not a hole: the ownership test below then applies+ // to final ticks, which today they never reach because this branch returns+ // first. A closing slice from a worker that no longer owns the sandbox —+ // a migration source handing off — is still dropped, which is correct,+ // because the destination goes on billing it.+ if (TERMINAL_STATUSES.has(row.status) && !isFinalTick(e)) {+ droppedTerminalTicks++;return false;}if (row.worker_id && e.worker_id && row.worker_id !== e.worker_id) {- droppedZombieTicks++;+ droppedNonOwnerTicks++;return false;}return true;@@ -496,8 +521,11 @@ export default {);});- if (droppedZombieTicks > 0) {- console.warn(`events-ingest: dropped ${droppedZombieTicks} usage_tick(s) from non-owner/terminal sandboxes (zombie-tick guard)`);+ if (droppedTerminalTicks > 0 || droppedNonOwnerTicks > 0) {+ console.warn(+ `events-ingest: zombie-tick guard dropped ${droppedTerminalTicks} tick(s) for terminal sandboxes ` ++ `and ${droppedNonOwnerTicks} from non-owner workers`,+ );}try {diff --git a/cloudflare-workers/events-ingest/wrangler.toml b/cloudflare-workers/events-ingest/wrangler.tomlindex 140cd77c..7696f99f 100644--- a/cloudflare-workers/events-ingest/wrangler.toml+++ b/cloudflare-workers/events-ingest/wrangler.toml@@ -28,9 +28,22 @@ binding = "OPENCOMPUTER_DB"database_name = "opencomputer-dev"database_id = "f9e534bf-a9f3-4b30-81cd-f9eb9087e96d"-[[r2_buckets]]-binding = "EVENTS_ARCHIVE"-bucket_name = "events-archive-dev"+# R2 raw-batch archive. COMMENTED OUT ON DEV ONLY: R2 is not enabled on this+# Cloudflare account, so the binding fails validation and makes the worker+# UNDEPLOYABLE — `wrangler deploy` dies with "Please enable R2 through the+# Cloudflare Dashboard (10136)". That is why dev drifted onto an old version.+#+# Safe to omit: the archive is explicitly best-effort and already wrapped in a+# try/catch whose comment says archive failure must not block the ack, because+# D1 is the durable record. With the binding gone the put throws a TypeError+# that the same catch swallows — identical behaviour to the "R2 archive failed+# (continuing)" it logs today, minus the deploy blocker.+#+# Restore this the moment R2 is enabled on the dev account. wrangler.prod.toml+# keeps its binding and is untouched.+# [[r2_buckets]]+# binding = "EVENTS_ARCHIVE"+# bucket_name = "events-archive-dev"# CreditAccount DO is owned by api-edge; reference it here for /debit calls.[[durable_objects.bindings]]diff --git a/internal/awsvm/terminator.go b/internal/awsvm/terminator.goindex 36c339dd..4c97a727 100644--- a/internal/awsvm/terminator.go+++ b/internal/awsvm/terminator.go@@ -170,3 +170,50 @@ func (t *terminator) close() {close(t.stop)}}++// ── shared with other backends ──────────────────────────────────────────────++// Terminator is the exported face of the paced destroy queue.+//+// It exists because the direct-exec backend (internal/awsvmlite) had exactly+// the bug this file was written to fix, and reimplementing it there would have+// been the second copy of a rate limiter for one shared quota. The quota is per+// ACCOUNT and region, not per backend — two unpaced callers racing it is the+// same failure as one.+//+// Deliberately a thin wrapper rather than exporting the type: the queue's+// lifecycle (the lazy start, the dedupe set) is not something a caller should+// be able to reach into, and Manager keeps using the unexported form unchanged.+type Terminator struct{ t *terminator }++// NewTerminator builds a paced destroy queue over a client. The worker starts+// lazily on the first Enqueue, so an idle backend costs nothing.+func NewTerminator(client *Client) *Terminator {+ return &Terminator{t: newTerminator(client)}+}++// Enqueue schedules a box for termination, returning false only when the queue+// is full — which tells the caller to terminate synchronously rather than lose+// the box entirely.+func (t *Terminator) Enqueue(microvmID string) bool {+ if t == nil {+ return false+ }+ return t.t.enqueue(microvmID)+}++// Depth reports the backlog, for telemetry.+func (t *Terminator) Depth() int {+ if t == nil {+ return 0+ }+ return t.t.depth()+}++// Close stops the worker.+func (t *Terminator) Close() {+ if t == nil {+ return+ }+ t.t.close()+}diff --git a/internal/awsvm/terminator_test.go b/internal/awsvm/terminator_test.goindex 5fb210ad..422a2587 100644--- a/internal/awsvm/terminator_test.go+++ b/internal/awsvm/terminator_test.go@@ -9,7 +9,6 @@ import ("github.com/aws/aws-sdk-go-v2/aws"lambdamicrovms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"mvtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"- "github.com/opensandbox/opensandbox/pkg/types")// termAPI records terminate calls and can fail the first N of them the way a@@ -120,54 +119,3 @@ func TestTerminateQueuePacesBulkDestroys(t *testing.T) {n, elapsed, min)}}--// Kill must stop routing the sandbox immediately, even though the terminate-// itself drains asynchronously — an exec landing on a condemned box is worse-// than a slightly stale inventory.-func TestKillUnbindsBeforeTheTerminateDrains(t *testing.T) {- f := &termAPI{failFor: map[string]int{"mvm-9": 2}}- c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})- m := NewManager(c, t.TempDir())- m.Track("sb-9", &Box{ID: "mvm-9"}, types.SandboxConfig{})-- if err := m.Kill(context.Background(), "sb-9"); err != nil {- t.Fatalf("Kill returned %v — a queued destroy must not fail the caller", err)- }- if _, ok := m.MicrovmIDFor("sb-9"); ok {- t.Fatal("sandbox still routes after Kill — an exec could reach a condemned box")- }- if !waitFor(t, 10*time.Second, func() bool { return len(f.done()) == 1 }) {- t.Fatal("box was never actually terminated")- }-}--// The pool's box budget treats TrackedMicrovmIDs as "in use", so a binding that-// outlives its box silently shrinks the headroom the pool is allowed to refill-// into. Measured on dev: 112 phantom bindings against 130 boxes actually alive,-// which would have made the pool refuse to restock during exactly the burst it-// was sized for. Forget is what the reconciler calls when it finds a dead box;-// this pins the invariant that doing so actually returns the budget.-func TestForgottenSandboxesStopCountingAgainstTheBudget(t *testing.T) {- f := &termAPI{}- c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})- m := NewManager(c, t.TempDir())-- m.Track("sb-live", &Box{ID: "mvm-live"}, types.SandboxConfig{})- m.Track("sb-dead", &Box{ID: "mvm-dead"}, types.SandboxConfig{})- if got := len(m.TrackedMicrovmIDs()); got != 2 {- t.Fatalf("tracked %d boxes, want 2", got)- }-- m.Forget("sb-dead")-- tracked := m.TrackedMicrovmIDs()- if _, phantom := tracked["mvm-dead"]; phantom {- t.Fatal("a forgotten sandbox still counts as in use — the pool budget would refuse to refill against a box that no longer exists")- }- if _, ok := tracked["mvm-live"]; !ok || len(tracked) != 1 {- t.Fatalf("Forget disturbed the live binding: %v", tracked)- }- if len(f.done()) != 0 {- t.Fatalf("Forget terminated %v — the box is already gone, and on a shared account we must never issue a destroy we did not decide on", f.done())- }-}diff --git a/internal/worker/usage_final_flag_test.go b/internal/worker/usage_final_flag_test.gonew file mode 100644index 00000000..a39b8434--- /dev/null+++ b/internal/worker/usage_final_flag_test.go@@ -0,0 +1,82 @@+package worker++import (+ "encoding/json"+ "testing"+ "time"++ "github.com/opensandbox/opensandbox/internal/sandbox"+)++// decodeTicks pulls the usage_tick payloads a ticker wrote for a sandbox.+func decodeTicks(t *testing.T, dbs *sandbox.SandboxDBManager, sandboxID string) []map[string]any {+ t.Helper()+ sdb, err := dbs.Get(sandboxID)+ if err != nil {+ t.Fatalf("open sandbox db: %v", err)+ }+ evs, err := sdb.GetUnsyncedEvents(100)+ if err != nil {+ t.Fatalf("read events: %v", err)+ }+ var out []map[string]any+ for _, e := range evs {+ if e.Type != "usage_tick" {+ continue+ }+ var p map[string]any+ if err := json.Unmarshal([]byte(e.Payload), &p); err != nil {+ t.Fatalf("payload not json: %v", err)+ }+ out = append(out, p)+ }+ return out+}++// The closing slice must be marked `final`, and an ordinary mid-life slice must+// not be.+//+// This flag is the difference between a sandbox being billed and being free.+// events-ingest discards usage_ticks for sandboxes already terminal in its+// index — correct for a straggler, and exactly wrong for the tick emitted BY+// the destroy. Unflagged, the closing slice is dropped, so any sandbox that+// lived and died inside one 20s sampling window bills nothing at all. Measured+// on dev: 2,685 such slices discarded.+//+// Scale is the control. It also flushes a slice, but the sandbox keeps running+// and keeps being sampled, so it is NOT final — marking it so would let a tick+// bypass the terminal check for a sandbox that is genuinely still alive.+func TestClosingSliceIsMarkedFinalAndMidLifeSliceIsNot(t *testing.T) {+ dbs := sandbox.NewSandboxDBManager(t.TempDir())+ ticker := newTestTicker(20*time.Second, 10)+ ticker.sandboxDBs = dbs+ startedAt := time.Now().Add(-4 * time.Second)++ ticker.OnSandboxDestroy("sb-destroyed", 4096, 1, startedAt)+ ticker.OnSandboxHibernate("sb-parked", 4096, 1, startedAt)+ ticker.OnSandboxScale("sb-resized", 4096, 1, startedAt)++ for _, tc := range []struct {+ sandboxID string+ wantFinal bool+ why string+ }{+ {"sb-destroyed", true, "a destroy ends the sandbox; its closing slice is the only record a short-lived sandbox ever produces"},+ {"sb-parked", true, "a hibernate stops it being billable until wake, so the slice before parking is closing too"},+ {"sb-resized", false, "a scale flushes a slice but the sandbox keeps running and keeps being sampled"},+ } {+ ticks := decodeTicks(t, dbs, tc.sandboxID)+ if len(ticks) != 1 {+ t.Fatalf("%s: got %d usage_tick(s), want exactly 1 — a duplicate would double-bill now that these are no longer discarded", tc.sandboxID, len(ticks))+ }+ got, _ := ticks[0]["final"].(bool)+ if got != tc.wantFinal {+ t.Errorf("%s: final=%v, want %v — %s", tc.sandboxID, got, tc.wantFinal, tc.why)+ }+ // The slice has to carry what it is priced on, or the consumer inserts a+ // zero-sized sample and the sandbox is billed for nothing anyway.+ if ticks[0]["memory_mb"] == nil || ticks[0]["interval_s"] == nil {+ t.Errorf("%s: slice missing pricing dimensions: %v", tc.sandboxID, ticks[0])+ }+ }+}diff --git a/internal/worker/usage_ticker.go b/internal/worker/usage_ticker.goindex 47574a44..e51228a9 100644--- a/internal/worker/usage_ticker.go+++ b/internal/worker/usage_ticker.go@@ -467,6 +467,20 @@ func (t *UsageTicker) flushSlice(sandboxID string, memoryMB, cpuCount int, start"interval_s": intervalSec,"memory_mb": memoryMB,"cpu_count": cpuCount,+ // final marks the last billable slice of this sandbox's life — the one+ // emitted BY a destroy or hibernate rather than by the periodic sampler.+ //+ // The consumer needs it because it cannot infer it. events-ingest drops+ // usage_ticks for sandboxes that are already terminal in its index — a+ // good rule for a straggler from a dead sandbox, and exactly wrong for+ // this tick, which is *supposed* to arrive as the sandbox ends. Without+ // the flag the closing slice was silently discarded, so every sandbox+ // that lived and died between two 20s samples billed nothing at all.+ //+ // Derived from dropState rather than passed in by each hook on purpose:+ // dropState ALREADY means "this sandbox stops being billable now", so+ // the two cannot drift, and a hook added later cannot forget to set it.+ "final": dropState,}); err != nil {log.Printf("usage_ticker: flushSlice %s: LogEvent failed: %v", sandboxID, err)}