Skip to content

An open-source, faster Devin alternative

TypeScript

fix(rows): stamp the provider's hard deadline on the row at write time so a sandbox row expires with its host instead of leaking, and classify a genuinely-absent host as terminal so reconcile can close it

Brian Reardon5e2824ea0ff7
diff --git a/cloudflare-workers/api-edge/migrations/0007_sandboxes_index_end_at.sql b/cloudflare-workers/api-edge/migrations/0007_sandboxes_index_end_at.sql
new file mode 100644
index 00000000..6dfde08c
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/0007_sandboxes_index_end_at.sql
@@ -0,0 +1,13 @@
+-- sandboxes_index.end_at — when the runtime's provider will destroy the host,
+-- regardless of anything we or the customer do.
+--
+-- Distinct from stopped_at, which records when a sandbox actually ended. This
+-- one is in the FUTURE for a running sandbox: the MicroVM runtime terminates a
+-- host at a hard cap measured from its launch, and until now that deadline was
+-- known only to the cell's Postgres. The customer-facing read is answered from
+-- D1, so a sandbox could be minutes from termination with nothing in any API
+-- response saying so.
+--
+-- Unix seconds, matching created_at / stopped_at. NULL means no such deadline,
+-- which is every QEMU sandbox — those end when someone ends them.
+ALTER TABLE sandboxes_index ADD COLUMN end_at INTEGER;
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index 3ac45921..461b0b88 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -272,6 +272,10 @@ describe("api-edge sandbox create", () => {
0,
2048,
expect.any(Number),
+ // end_at: this CP response carries no deadline, and the absence must
+ // reach the column as NULL rather than as a fabricated timestamp — a
+ // wrong deadline here would make a live sandbox read as expired.
+ null,
]);
});
});
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 7680eebe..b2f09471 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -348,6 +348,8 @@ interface SandboxCreateResult {
workerID?: string;
status?: string;
memoryMB?: number;
+ // RFC3339, present only when the serving runtime enforces a hard deadline.
+ endAt?: string;
}
function isWebSocketUpgrade(req: Request): boolean {
@@ -1406,13 +1408,13 @@ async function insertSandboxIndex(
// create the row doesn't exist yet, so the plain INSERT branch runs.
await env.OPENCOMPUTER_DB.prepare(
`INSERT INTO sandboxes_index
- (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)
+ (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at, end_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10)
ON CONFLICT(id) DO UPDATE SET
org_id=excluded.org_id, user_id=excluded.user_id, cell_id=excluded.cell_id,
worker_id=excluded.worker_id, status=excluded.status,
cpu_count=excluded.cpu_count, memory_mb=excluded.memory_mb,
- last_event_at=excluded.last_event_at
+ last_event_at=excluded.last_event_at, end_at=excluded.end_at
WHERE sandboxes_index.status NOT IN ('stopped', 'error')`,
)
.bind(
@@ -1425,6 +1427,7 @@ async function insertSandboxIndex(
fallbackCpuCount,
parsed.memoryMB ?? fallbackMemoryMB,
Math.floor(Date.now() / 1000),
+ unixFromISO(parsed.endAt),
)
.run();
}
@@ -2366,6 +2369,18 @@ interface SandboxRow {
created_at: number;
last_event_at: number | null;
stopped_at: number | null;
+ end_at: number | null;
+}
+
+// unixFromISO turns the control plane's RFC3339 deadline into the unix seconds
+// the index stores. Anything unparseable becomes NULL rather than a guess: a
+// bogus deadline in the past would make a live sandbox look expired to every
+// reader that treats this column as terminal.
+function unixFromISO(v: unknown): number | null {
+ if (typeof v !== "string" || v === "") return null;
+ const ms = Date.parse(v);
+ if (!Number.isFinite(ms) || ms <= 0) return null;
+ return Math.floor(ms / 1000);
}
function isoFromUnix(secs: number | null): string {
@@ -2384,7 +2399,11 @@ function sandboxRowToJSON(r: SandboxRow): Record<string, unknown> {
cpuCount: r.cpu_count ?? 0,
memoryMB: r.memory_mb ?? 0,
startedAt: isoFromUnix(r.created_at),
- endAt: isoFromUnix(r.stopped_at),
+ // "When does this sandbox end" — the actual end once it has ended, and
+ // otherwise the deadline its provider will enforce. Previously this was
+ // stopped_at alone, which meant a running sandbox always reported the Go
+ // zero time here no matter how close it was to being terminated.
+ endAt: isoFromUnix(r.stopped_at ?? r.end_at),
};
}
@@ -2393,7 +2412,7 @@ async function listSandboxes(req: Request, env: Env): Promise<Response> {
if (!caller) return json({ error: "missing or invalid API key" }, 401);
const { results } = await env.OPENCOMPUTER_DB.prepare(
`SELECT id, cell_id, worker_id, status, template_id, cpu_count, memory_mb,
- created_at, last_event_at, stopped_at
+ created_at, last_event_at, stopped_at, end_at
FROM sandboxes_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,
)
.bind(caller.orgID)
@@ -2406,7 +2425,7 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>
if (!caller) return json({ error: "missing or invalid API key" }, 401);
const row = await env.OPENCOMPUTER_DB.prepare(
`SELECT id, org_id, cell_id, worker_id, status, template_id, cpu_count, memory_mb,
- created_at, last_event_at, stopped_at
+ created_at, last_event_at, stopped_at, end_at
FROM sandboxes_index WHERE id = ?1`,
)
.bind(id)
@@ -5395,17 +5414,17 @@ export default {
});
const fcText = await fcResp.text();
if (fcResp.status >= 200 && fcResp.status < 300) {
- let parsed: { sandboxID?: string; workerID?: string; status?: string; memoryMB?: number } = {};
+ let parsed: SandboxCreateResult = {};
try {
- parsed = JSON.parse(fcText);
+ parsed = JSON.parse(fcText) as SandboxCreateResult;
} catch {
/* leave empty */
}
if (parsed.sandboxID) {
await env.OPENCOMPUTER_DB.prepare(
`INSERT OR REPLACE INTO sandboxes_index
- (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)`,
+ (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at, end_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10)`,
)
.bind(
parsed.sandboxID,
@@ -5417,6 +5436,7 @@ export default {
fcCpu,
parsed.memoryMB ?? fcMem,
Math.floor(Date.now() / 1000),
+ unixFromISO(parsed.endAt),
)
.run();
}
diff --git a/internal/awsvm/client.go b/internal/awsvm/client.go
index 63cd5073..5ec559cd 100644
--- a/internal/awsvm/client.go
+++ b/internal/awsvm/client.go
@@ -123,6 +123,21 @@ type Config struct {
SuspendedDurationSeconds int32
}
+// deliveredMicrovmMemoryMB is the default image's minimumMemoryInMiB, used when
+// Config.DefaultMemoryMB is unset. MUST track the image or every box is metered
+// at the wrong size — the meter prices on what List() reports, so whatever is
+// recorded here is what the customer is billed for.
+//
+// Raised 2048 → 4096 on 2026-08-24 (image version 12.0) so the runtime actually
+// delivers the platform default: the API defaults a create to 4096 and QEMU
+// gives 4096, while this image gave 2048 — so every default create was silently
+// served half what it asked for, and metered at the half.
+//
+// Lambda gives a full vCPU from 2048 up (peak scales to 4x), so 4096 keeps the
+// 1-vCPU tier promise. Supported sizes are an ENUM, not a free integer:
+// [512, 1024, 2048, 4096, 8192] on base image al2023-1.
+const deliveredMicrovmMemoryMB = 4096
+
func (c *Config) applyDefaults() {
if c.AgentPort == 0 {
// The declared hook port — see the field comment for why this is not
@@ -184,6 +199,21 @@ func (c Config) ImageForMemory(memoryMB int) (image string, deliveredMB int, ok
return "", 0, false
}
+// Deadline reports when the provider will destroy a host launched at
+// launchedAt, or the zero time if that cannot be known.
+//
+// The zero-in/zero-out rule is load-bearing and deliberately not a "sensible
+// default": callers write this onto a database row that other reads treat as
+// terminal once passed. A zero launch time that silently became `0001-01-01 +
+// 8h` would be in the past for every row it touched, and would expire every
+// live sandbox at once. Unknown must stay unknown.
+func (c Config) Deadline(launchedAt time.Time) time.Time {
+ if launchedAt.IsZero() || c.MaxDurationSeconds <= 0 {
+ return time.Time{}
+ }
+ return launchedAt.Add(time.Duration(c.MaxDurationSeconds) * time.Second)
+}
+
// IsDefaultTier reports whether a request can be served from warm stock. Only
// the default tier is pooled, so this is what gates a pool claim.
func (c Config) IsDefaultTier(memoryMB int) bool {
@@ -343,13 +373,22 @@ func (c *Client) Get(ctx context.Context, id string) (*Box, error) {
MicrovmIdentifier: aws.String(id),
})
if err != nil {
- return nil, fmt.Errorf("awsvm: get microvm %s: %w", id, err)
+ // Classified, not just wrapped: callers have to be able to tell "this
+ // host is gone for good" from "I could not reach AWS just now", because
+ // the correct response to each is opposite. See ErrNotFound.
+ return nil, fmt.Errorf("awsvm: get microvm %s: %w", id, classifyLookupError(err))
}
return &Box{
ID: aws.ToString(out.MicrovmId),
Endpoint: aws.ToString(out.Endpoint),
ImageArn: aws.ToString(out.ImageArn),
State: out.State,
+ // Carried because the host's launch time is what its hard deadline is
+ // derived from (Config.MaxDurationSeconds after this). List() always
+ // populated it and Get() silently did not, so a sandbox re-adopted
+ // after a control-plane restart came back with no launch time and
+ // therefore no deadline.
+ StartedAt: aws.ToTime(out.StartedAt),
}, nil
}
diff --git a/internal/awsvm/client_test.go b/internal/awsvm/client_test.go
index d0ddd7d5..a9786bc8 100644
--- a/internal/awsvm/client_test.go
+++ b/internal/awsvm/client_test.go
@@ -283,3 +283,44 @@ func TestListGivesUpAfterListAttempts(t *testing.T) {
t.Fatalf("made %d attempts, want listAttempts=%d", f.calls, listAttempts)
}
}
+
+// An unknown launch time must yield NO deadline, never a deadline in the past.
+//
+// This is the most dangerous arithmetic in the expiry design. Deadline() feeds a
+// database column that every other read treats as terminal once passed, so a
+// zero launch time quietly becoming `0001-01-01 + 8h` would be in the past for
+// every row it touched — expiring the entire fleet's live sandboxes at once.
+// Get() genuinely used to return boxes with no StartedAt, so this input is real
+// rather than theoretical.
+func TestDeadlineIsUnknownRatherThanPastWhenLaunchTimeIsUnknown(t *testing.T) {
+ cfg := Config{ImageIdentifier: "arn:image"}
+ cfg.applyDefaults()
+
+ if got := cfg.Deadline(time.Time{}); !got.IsZero() {
+ t.Fatalf("a zero launch time produced deadline %s — every row stamped with it "+
+ "would read as already expired, closing live sandboxes", got)
+ }
+
+ launched := time.Now().Add(-2 * time.Hour)
+ got := cfg.Deadline(launched)
+ if got.IsZero() {
+ t.Fatal("a known launch time produced no deadline")
+ }
+ if want := launched.Add(time.Duration(cfg.MaxDurationSeconds) * time.Second); !got.Equal(want) {
+ t.Fatalf("deadline = %s, want %s", got, want)
+ }
+ // A box launched two hours ago has six hours left, not eight: the deadline
+ // runs from LAUNCH, not from when a customer claimed it. Getting this wrong
+ // would let a row outlive its host by however long the box sat warm.
+ if remaining := time.Until(got); remaining > 6*time.Hour+time.Minute {
+ t.Fatalf("deadline leaves %s — measured from claim rather than launch", remaining)
+ }
+}
+
+// A host with no configured maximum has no deadline either.
+func TestDeadlineIsUnknownWithoutAConfiguredMaximum(t *testing.T) {
+ cfg := Config{ImageIdentifier: "arn:image", MaxDurationSeconds: 0}
+ if got := cfg.Deadline(time.Now()); !got.IsZero() {
+ t.Fatalf("deadline %s invented from an unset maximum", got)
+ }
+}
diff --git a/internal/awsvm/errors.go b/internal/awsvm/errors.go
index d7af1d50..d2052725 100644
--- a/internal/awsvm/errors.go
+++ b/internal/awsvm/errors.go
@@ -25,6 +25,28 @@ var (
ErrThrottled = errors.New("awsvm: MicroVM API rate limit exceeded")
)
+// ErrUnsupported marks a Manager capability this runtime does not implement.
+// Callers should surface it as "not available on this runtime", never retry it.
+//
+// The API boundary substitutes its own text, so this string is not
+// customer-visible today — but error text is exactly what escapes into a
+// response, a webhook, or a support ticket later, so it stays generic.
+var ErrUnsupported = errors.New("awsvm: operation not supported by this sandbox runtime")
+
+// ErrNotFound marks a host AWS has no record of — TERMINAL, and the distinction
+// from a transient lookup failure is the whole point of the sentinel.
+//
+// Reconcile's rule is "never close a row on an error", because a throttle or a
+// timeout must not be allowed to end a live customer's sandbox. But GetMicrovm
+// answers ResourceNotFoundException for a box that is genuinely gone, and
+// lumping that in with transient errors made the rule say "never close this row
+// EVER" — the box is permanently absent, so the error recurs forever and the
+// row sits `running` for the life of the database. Measured on dev as three
+// rows the reconciler skipped silently on every pass.
+//
+// A caller may treat this, and only this, as proof the host is gone.
+var ErrNotFound = errors.New("awsvm: microvm does not exist")
+
// classifyLaunchError maps an AWS launch error onto the sentinels above,
// leaving anything else untouched. Errors are matched by type rather than by
// message so an SDK wording change cannot silently reclassify them.
@@ -46,3 +68,26 @@ func classifyLaunchError(err error) error {
}
return err
}
+
+// classifyLookupError maps a describe/lookup error onto the sentinels above.
+// Separate from classifyLaunchError because the interesting case is the
+// opposite one: a launch never returns not-found, and a lookup never returns
+// quota-exceeded.
+func classifyLookupError(err error) error {
+ if err == nil {
+ return nil
+ }
+ var missing *types.ResourceNotFoundException
+ if errors.As(err, &missing) {
+ return errors.Join(ErrNotFound, err)
+ }
+ var throttle *types.ThrottlingException
+ if errors.As(err, &throttle) {
+ return errors.Join(ErrThrottled, err)
+ }
+ var tooMany *types.TooManyRequestsException
+ if errors.As(err, &tooMany) {
+ return errors.Join(ErrThrottled, err)
+ }
+ return err
+}
diff --git a/internal/awsvm/errors_test.go b/internal/awsvm/errors_test.go
index cd1ed6f0..79c0c961 100644
--- a/internal/awsvm/errors_test.go
+++ b/internal/awsvm/errors_test.go
@@ -1,10 +1,12 @@
package awsvm
import (
+ "context"
"errors"
"fmt"
"testing"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
"github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
)
@@ -61,3 +63,60 @@ func TestClassifyLaunchErrorPassesNil(t *testing.T) {
t.Fatalf("classifyLaunchError(nil) = %v, want nil", got)
}
}
+
+// getNotFoundAPI answers GetMicrovm the way AWS does for a host it has no
+// record of — the steady state for a box terminated some time ago.
+type getNotFoundAPI struct {
+ API
+ err error
+}
+
+func (f *getNotFoundAPI) GetMicrovm(context.Context, *lambdamicrovms.GetMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {
+ return nil, f.err
+}
+
+// A host AWS has forgotten must be reported as TERMINAL, distinctly from a
+// lookup that merely failed.
+//
+// This is the leak that motivated the sentinel. Reconcile's rule is "never
+// close a row on an error" — correct for a throttle, catastrophic for
+// not-found, because the error is permanent: the box will never come back, so
+// the row sits `running` for the life of the database and the sandbox shows as
+// live to the customer forever. Measured on dev as three such rows, skipped
+// silently on every 5-minute pass.
+func TestGetReportsAForgottenHostAsTerminalNotTransient(t *testing.T) {
+ c := NewClientWithAPI(&getNotFoundAPI{err: &types.ResourceNotFoundException{}}, Config{ImageIdentifier: "arn:image"})
+
+ _, err := c.Get(context.Background(), "microvm-gone")
+ if err == nil {
+ t.Fatal("Get succeeded for a host AWS does not have")
+ }
+ if !errors.Is(err, ErrNotFound) {
+ t.Fatalf("not-found was not classified as terminal (%v) — the reconciler "+
+ "would treat it as 'could not tell' and never close the row", err)
+ }
+ // The opposite direction matters just as much: a transient failure must NOT
+ // look like proof the host is gone, or a throttle ends live sandboxes.
+ if errors.Is(err, ErrThrottled) {
+ t.Fatal("not-found also matched ErrThrottled — the two must stay distinguishable")
+ }
+}
+
+func TestGetKeepsTransientFailuresTransient(t *testing.T) {
+ for name, apiErr := range map[string]error{
+ "throttling": &types.ThrottlingException{},
+ "too many reqs": &types.TooManyRequestsException{},
+ } {
+ t.Run(name, func(t *testing.T) {
+ c := NewClientWithAPI(&getNotFoundAPI{err: apiErr}, Config{ImageIdentifier: "arn:image"})
+ _, err := c.Get(context.Background(), "microvm-1")
+ if errors.Is(err, ErrNotFound) {
+ t.Fatal("a transient failure was classified as proof the host is gone — " +
+ "the reconciler would close a LIVE customer's sandbox")
+ }
+ if !errors.Is(err, ErrThrottled) {
+ t.Fatalf("transient failure not classified as throttled: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/db/migrations/056_sandbox_end_at.down.sql b/internal/db/migrations/056_sandbox_end_at.down.sql
new file mode 100644
index 00000000..fa161672
--- /dev/null
+++ b/internal/db/migrations/056_sandbox_end_at.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS idx_sandbox_sessions_running_end_at;
+ALTER TABLE sandbox_sessions DROP COLUMN IF EXISTS end_at;
diff --git a/internal/db/migrations/056_sandbox_end_at.up.sql b/internal/db/migrations/056_sandbox_end_at.up.sql
new file mode 100644
index 00000000..b207c44f
--- /dev/null
+++ b/internal/db/migrations/056_sandbox_end_at.up.sql
@@ -0,0 +1,31 @@
+-- A hard deadline stamped on the row when a sandbox is placed, so that a row
+-- outliving its host is not something anyone has to notice.
+--
+-- The problem this solves: a managed host can be destroyed by its provider with
+-- no callback to us — AWS terminates every MicroVM at a hard 8h cap regardless
+-- of what we do. Nothing tells the control plane. Until something sweeps, the
+-- row still says `running`, so the sandbox counts against the org's concurrency
+-- limit and shows as live in the dashboard. Correctness therefore depended on a
+-- reaper having run recently, and a reaper that fails, falls behind, or skips a
+-- row (as one did — see awsvm.ErrNotFound) leaks that row permanently.
+--
+-- With a deadline on the row, a reader can settle the question itself:
+--
+-- status = 'running' AND (end_at IS NULL OR end_at > now())
+--
+-- No sweep required. The reconciler stops being what makes the state correct
+-- and becomes only what frees the row sooner.
+--
+-- NULL means "no known deadline" and is the default, so every existing row and
+-- every QEMU sandbox is unaffected: a QEMU VM has no provider-imposed lifetime,
+-- and inventing one here would start expiring live sandboxes. Only runtimes
+-- that actually know their host's death time stamp this.
+ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS end_at TIMESTAMPTZ;
+
+-- Partial index: every gated read is "running rows for an org", and the
+-- deadline check rides along on it. Restricted to running rows because
+-- terminal rows are never asked this question and they are the bulk of the
+-- table.
+CREATE INDEX IF NOT EXISTS idx_sandbox_sessions_running_end_at
+ ON sandbox_sessions (org_id, end_at)
+ WHERE status = 'running';
diff --git a/internal/db/store.go b/internal/db/store.go
index d42c8046..e5d272c0 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -226,6 +226,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{53, "migrations/053_default_org_concurrency_50.up.sql"},
{54, "migrations/054_sandbox_pool.up.sql"},
{55, "migrations/055_orgs_runtime.up.sql"},
+ {56, "migrations/056_sandbox_end_at.up.sql"},
}
for _, m := range migrations {
@@ -1561,9 +1562,16 @@ func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, status
var rows pgx.Rows
var err error
if status != "" {
+ // A caller asking for 'running' means "alive", so a row past its
+ // deadline is excluded here rather than waiting for a sweep to relabel
+ // it — otherwise the dashboard shows sandboxes the customer no longer
+ // has. Other statuses are terminal and carry no deadline, so the
+ // predicate is a no-op for them.
rows, err = s.pool.Query(ctx,
`SELECT id, sandbox_id, org_id, user_id, template, region, worker_id, status, config, metadata, started_at, stopped_at, error_msg, based_on_checkpoint_id, last_patch_sequence, patch_error, golden_version
- FROM sandbox_sessions WHERE org_id = $1 AND status = $2 ORDER BY started_at DESC LIMIT $3 OFFSET $4`,
+ FROM sandbox_sessions
+ WHERE org_id = $1 AND status = $2 AND ($2 <> 'running' OR end_at IS NULL OR end_at > now())
+ ORDER BY started_at DESC LIMIT $3 OFFSET $4`,
orgID, status, limit, offset)
} else {
rows, err = s.pool.Query(ctx,
@@ -1611,6 +1619,10 @@ type MicrovmSessionRef struct {
// price on memory/cpu, so a restore that dropped them would silently
// re-meter every surviving sandbox at the backend's default.
Config []byte
+ // EndAt is the host's known death time, or zero if it has none. A row past
+ // it can be closed with NO provider call — which is the point: the pass
+ // that tidies up must not itself depend on the provider being reachable.
+ EndAt time.Time
}
// ListMicrovmSessions returns running MicroVM-backed sandboxes.
@@ -1630,7 +1642,10 @@ func (s *Store) ListMicrovmSessions(ctx context.Context, prefixes []string) ([]M
// so adding a runtime cannot leave this predicate behind — the failure
// that would look like sandboxes surviving a restart unroutable, with
// their hosts running and nothing able to reap them.
- `SELECT sandbox_id, worker_id, config FROM sandbox_sessions
+ // Deliberately NOT deadline-filtered: this is the one query that WANTS
+ // expired rows, because closing them is its job. Every other read hides
+ // them; this one collects them.
+ `SELECT sandbox_id, worker_id, config, end_at FROM sandbox_sessions
WHERE worker_id LIKE ANY($1) AND status = 'running'
ORDER BY started_at DESC
LIMIT 1000`, likePatterns(prefixes))
@@ -1643,10 +1658,15 @@ func (s *Store) ListMicrovmSessions(ctx context.Context, prefixes []string) ([]M
for rows.Next() {
var sandboxID, workerID string
var config []byte
- if err := rows.Scan(&sandboxID, &workerID, &config); err != nil {
+ var endAt *time.Time
+ if err := rows.Scan(&sandboxID, &workerID, &config, &endAt); err != nil {
return nil, err
}
- out = append(out, MicrovmSessionRef{SandboxID: sandboxID, WorkerID: workerID, Config: config})
+ ref := MicrovmSessionRef{SandboxID: sandboxID, WorkerID: workerID, Config: config}
+ if endAt != nil {
+ ref.EndAt = *endAt
+ }
+ out = append(out, ref)
}
return out, rows.Err()
}
@@ -1708,10 +1728,18 @@ func (s *Store) ListSandboxIDsByWorkerStatus(ctx context.Context, workerID, stat
return ids, rows.Err()
}
+// CountActiveSandboxes is what the org concurrency limit is enforced against,
+// which makes it the read where a leaked row hurts a customer most: a row still
+// saying `running` for a host that no longer exists consumes a slot, and the
+// customer is refused a create they are entitled to.
+//
+// The deadline check is what makes that impossible to reach rather than
+// something a sweep has to get to in time. See migration 056.
func (s *Store) CountActiveSandboxes(ctx context.Context, orgID uuid.UUID) (int, error) {
var count int
err := s.pool.QueryRow(ctx,
- `SELECT COUNT(*) FROM sandbox_sessions WHERE org_id = $1 AND status = 'running'`, orgID,
+ `SELECT COUNT(*) FROM sandbox_sessions
+ WHERE org_id = $1 AND status = 'running' AND (end_at IS NULL OR end_at > now())`, orgID,
).Scan(&count)
return count, err
}
@@ -2760,6 +2788,23 @@ func (s *Store) SetSandboxGoldenVersion(ctx context.Context, sandboxID, goldenVe
return err
}
+// SetSandboxEndAt stamps the host's hard deadline on the row.
+//
+// Guarded on status: a sandbox that already reached a terminal state must not
+// have a future deadline written onto it, because the gated reads only consult
+// end_at for running rows and a resurrected-looking row is worse than a stale
+// one. See migration 056 for what the column buys.
+func (s *Store) SetSandboxEndAt(ctx context.Context, sandboxID string, endAt time.Time) error {
+ if endAt.IsZero() {
+ return nil
+ }
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET end_at = $1
+ WHERE sandbox_id = $2 AND status IN ('pending', 'running')`,
+ endAt, sandboxID)
+ return err
+}
+
// SetSandboxCheckpointID sets the based_on_checkpoint_id for a sandbox session.
func (s *Store) SetSandboxCheckpointID(ctx context.Context, sandboxID string, checkpointID uuid.UUID) error {
_, err := s.pool.Exec(ctx,