Skip to content

An open-source, faster Devin alternative

TypeScript

db+api: apply F3/F9/F10/F11 doc revisions

Igor Zalutski31d4b32347ae
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 30ff57f4..685fe624 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -631,7 +631,7 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {
if s.sandboxDomain != "" {
resp["sandboxDomain"] = s.sandboxDomain
}
- s.mergeTagsInto(c.Request().Context(), resp, sandboxID)
+ s.mergeTagsInto(c.Request().Context(), orgID, resp, sandboxID)
return c.JSON(http.StatusOK, resp)
}
@@ -660,7 +660,7 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {
resp["patchError"] = *session.PatchError
}
- s.mergeTagsInto(c.Request().Context(), resp, sandboxID)
+ s.mergeTagsInto(c.Request().Context(), orgID, resp, sandboxID)
return c.JSON(http.StatusOK, resp)
}
@@ -820,7 +820,7 @@ func (s *Server) listSandboxesRemote(c echo.Context) error {
// is unreachable, list still returns without tag fields rather
// than 500.
if s.store != nil {
- if sets, err := s.store.GetSandboxTagsMulti(c.Request().Context(), ids); err == nil {
+ if sets, err := s.store.GetSandboxTagsMulti(c.Request().Context(), orgID, ids); err == nil {
for _, entry := range result {
sid, _ := entry["sandboxID"].(string)
set := sets[sid]
diff --git a/internal/api/sandbox_tags.go b/internal/api/sandbox_tags.go
index 0def0d8d..682f5cd2 100644
--- a/internal/api/sandbox_tags.go
+++ b/internal/api/sandbox_tags.go
@@ -89,7 +89,8 @@ func (s *Server) getSandboxTags(c echo.Context) error {
if err := s.ownsSandbox(c, sandboxID); err != nil {
return err
}
- set, err := s.store.GetSandboxTags(c.Request().Context(), sandboxID)
+ orgID, _ := auth.GetOrgID(c)
+ set, err := s.store.GetSandboxTags(c.Request().Context(), orgID, sandboxID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
@@ -136,7 +137,7 @@ func (s *Server) putSandboxTags(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
// Re-read to return the canonical state + fresh tagsLastUpdatedAt.
- set, err := s.store.GetSandboxTags(c.Request().Context(), sandboxID)
+ set, err := s.store.GetSandboxTags(c.Request().Context(), orgID, sandboxID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
diff --git a/internal/api/sandbox_tags_hydrate.go b/internal/api/sandbox_tags_hydrate.go
index 90d531b5..bbc80779 100644
--- a/internal/api/sandbox_tags_hydrate.go
+++ b/internal/api/sandbox_tags_hydrate.go
@@ -5,7 +5,10 @@ import (
"encoding/json"
"time"
+ "github.com/google/uuid"
"github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
)
// Tag hydration helpers for the GET /sandboxes* response additions.
@@ -16,15 +19,18 @@ import (
// Fail-soft: if the store isn't configured or the tag query errors,
// the sandbox response is returned as-is rather than 500. Tags are
// purely additive and should never break the primary sandbox read.
+//
+// Every call takes orgID so the (org_id, sandbox_id) lookup scope
+// from migration 026 is preserved end-to-end.
// mergeTagsInto mutates a response map, adding `tags` (always, even
// if empty) and `tagsLastUpdatedAt` (nil when the sandbox has no
// tags). Intended for the remote paths, which already build maps.
-func (s *Server) mergeTagsInto(ctx context.Context, resp map[string]interface{}, sandboxID string) {
+func (s *Server) mergeTagsInto(ctx context.Context, orgID uuid.UUID, resp map[string]interface{}, sandboxID string) {
if s.store == nil {
return
}
- set, err := s.store.GetSandboxTags(ctx, sandboxID)
+ set, err := s.store.GetSandboxTags(ctx, orgID, sandboxID)
if err != nil {
return
}
@@ -48,6 +54,10 @@ func (s *Server) withTagsHydrated(c echo.Context, sb interface{}, sandboxID stri
if s.store == nil {
return sb
}
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return sb
+ }
buf, err := json.Marshal(sb)
if err != nil {
return sb
@@ -56,7 +66,7 @@ func (s *Server) withTagsHydrated(c echo.Context, sb interface{}, sandboxID stri
if err := json.Unmarshal(buf, &m); err != nil {
return sb
}
- s.mergeTagsInto(c.Request().Context(), m, sandboxID)
+ s.mergeTagsInto(c.Request().Context(), orgID, m, sandboxID)
return m
}
@@ -66,6 +76,10 @@ func (s *Server) withTagsHydratedList(c echo.Context, sandboxes interface{}) int
if s.store == nil {
return sandboxes
}
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return sandboxes
+ }
buf, err := json.Marshal(sandboxes)
if err != nil {
return sandboxes
@@ -81,7 +95,7 @@ func (s *Server) withTagsHydratedList(c echo.Context, sandboxes interface{}) int
ids = append(ids, id)
}
}
- sets, err := s.store.GetSandboxTagsMulti(c.Request().Context(), ids)
+ sets, err := s.store.GetSandboxTagsMulti(c.Request().Context(), orgID, ids)
if err != nil {
return sandboxes
}
@@ -100,3 +114,4 @@ func (s *Server) withTagsHydratedList(c echo.Context, sandboxes interface{}) int
}
return arr
}
+
diff --git a/internal/api/usage.go b/internal/api/usage.go
index f306d4c8..557061a2 100644
--- a/internal/api/usage.go
+++ b/internal/api/usage.go
@@ -8,6 +8,7 @@ import (
"strings"
"time"
+ "github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
@@ -81,12 +82,20 @@ func parseUsageQuery(c echo.Context) (db.UsageQuery, error) {
q.Limit = 50
}
- // filter[tag:<key>]=v1,v2 — repeatable. filter[tag:<key>]= (empty)
- // means the sandbox lacks that tag key.
+ // filter[tag:<key>]=v1,v2 — one param per dimension. Comma-
+ // separated values are OR-ed within the dimension; different
+ // dimensions are AND-ed across. Repeating the same `filter[...]`
+ // key is explicitly rejected (design F10) — the SDK's natural
+ // shape is a map, and accepting repeats would diverge SDK
+ // semantics from HTTP semantics. `filter[tag:<key>]=` (empty)
+ // means "sandbox lacks that tag key."
for rawKey, vals := range c.QueryParams() {
if !strings.HasPrefix(rawKey, "filter[") || !strings.HasSuffix(rawKey, "]") {
continue
}
+ if len(vals) > 1 {
+ return q, fmt.Errorf("filter %q was passed more than once; use comma-separated values within one param", rawKey)
+ }
dim := strings.TrimSuffix(strings.TrimPrefix(rawKey, "filter["), "]")
if !strings.HasPrefix(dim, "tag:") {
return q, fmt.Errorf("filter dimension %q not supported (only tag:<key> in v1)", dim)
@@ -182,7 +191,7 @@ func (s *Server) getUsage(c echo.Context) error {
}
// groupBy=sandbox — hydrate alias/status/tags on each row.
- items, err := s.hydrateSandboxUsageItems(ctx, rows)
+ items, err := s.hydrateSandboxUsageItems(ctx, q.OrgID, rows)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
@@ -193,22 +202,23 @@ func (s *Server) getUsage(c echo.Context) error {
// hydrateSandboxUsageItems enriches the minimal scale-event rows with
// fields the handler is responsible for: alias (from
// sandbox_sessions.config JSONB — design F1), status, tag set,
-// tagsLastUpdatedAt.
-func (s *Server) hydrateSandboxUsageItems(ctx context.Context, rows []db.UsageRow) ([]map[string]interface{}, error) {
+// tagsLastUpdatedAt. Both the tag fetch and the session fetch are
+// batched — the 500-row × 10s-handler budget rules out N+1 lookups
+// (design F11).
+func (s *Server) hydrateSandboxUsageItems(ctx context.Context, orgID uuid.UUID, rows []db.UsageRow) ([]map[string]interface{}, error) {
ids := make([]string, 0, len(rows))
for _, r := range rows {
ids = append(ids, r.SandboxID)
}
- // Single batched tag fetch.
- tagSets, err := s.store.GetSandboxTagsMulti(ctx, ids)
+ tagSets, err := s.store.GetSandboxTagsMulti(ctx, orgID, ids)
+ if err != nil {
+ return nil, err
+ }
+ sessions, err := s.store.GetLatestSandboxSessionsMulti(ctx, orgID, ids)
if err != nil {
return nil, err
}
- // Per-sandbox session lookup for alias + status. The store doesn't
- // yet have a batched-by-id variant; N+1 is tolerable in v1 given
- // the 500-row limit and the 10s handler budget. If this shows up
- // hot, promote to a batched GetSandboxSessionsMulti.
out := make([]map[string]interface{}, 0, len(rows))
for _, r := range rows {
item := map[string]interface{}{
@@ -216,7 +226,7 @@ func (s *Server) hydrateSandboxUsageItems(ctx context.Context, rows []db.UsageRo
"memoryGbSeconds": r.MemoryGbSeconds,
"diskOverageGbSeconds": r.DiskOverageGbSeconds,
}
- if sess, err := s.store.GetSandboxSession(ctx, r.SandboxID); err == nil {
+ if sess, ok := sessions[r.SandboxID]; ok {
item["status"] = sess.Status
if alias := aliasFromConfig(sess.Config); alias != "" {
item["alias"] = alias
@@ -303,6 +313,9 @@ func (s *Server) getSandboxUsage(c echo.Context) error {
}
to = t
}
+ if !to.After(from) {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "`to` must be after `from`"})
+ }
if to.Sub(from) > 90*24*time.Hour {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "query window must be <= 90 days"})
}
@@ -316,7 +329,7 @@ func (s *Server) getSandboxUsage(c echo.Context) error {
}
sess, _ := s.store.GetSandboxSession(ctx, sandboxID)
- tagSet, err := s.store.GetSandboxTags(ctx, sandboxID)
+ tagSet, err := s.store.GetSandboxTags(ctx, orgID, sandboxID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
diff --git a/internal/db/migrations/026_sandbox_tags.up.sql b/internal/db/migrations/026_sandbox_tags.up.sql
index bde879f7..7f483ae2 100644
--- a/internal/db/migrations/026_sandbox_tags.up.sql
+++ b/internal/db/migrations/026_sandbox_tags.up.sql
@@ -1,15 +1,20 @@
-- Sandbox tags — per-sandbox customer-defined groupings (team, env,
-- customer, …) used to attribute usage without touching the Stripe
-- pricing path. Row-per-tag so grouping SQL is a single join and
--- per-sandbox tag-count limits are trivial. org_id is denormalized
--- so GET /tags can filter on (org_id, key) without a join.
+-- per-sandbox tag-count limits are trivial.
+--
+-- org_id is part of the primary key, not just a filter column. Sandbox
+-- IDs are short `sb-xxxxxxxx` strings generated independently per
+-- create path and the schema does not enforce cross-org uniqueness — a
+-- `(sandbox_id, key)` PK would let a collision alias tag state across
+-- tenants. Every read, join, and write scopes on (org_id, sandbox_id).
CREATE TABLE IF NOT EXISTS sandbox_tags (
org_id UUID NOT NULL,
sandbox_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- PRIMARY KEY (sandbox_id, key)
+ PRIMARY KEY (org_id, sandbox_id, key)
);
CREATE INDEX IF NOT EXISTS idx_sandbox_tags_org_key_value
diff --git a/internal/db/sandbox_tags.go b/internal/db/sandbox_tags.go
index 167b582d..1fcb4fa9 100644
--- a/internal/db/sandbox_tags.go
+++ b/internal/db/sandbox_tags.go
@@ -21,13 +21,20 @@ type TagKeyStats struct {
ValueCount int
}
+// All tag methods take an org_id. The PK on sandbox_tags is (org_id,
+// sandbox_id, key) because sandbox IDs are short `sb-xxxxxxxx` strings
+// with no schema-enforced cross-org uniqueness. Keying the table and
+// every read/write path on (org_id, sandbox_id) is the tenancy
+// boundary — handler ownership checks are belt-and-suspenders on top.
+
// GetSandboxTags returns the tag map plus the latest updated_at across
// rows for one sandbox. Returns an empty map and nil timestamp when the
// sandbox has no tags.
-func (s *Store) GetSandboxTags(ctx context.Context, sandboxID string) (SandboxTagSet, error) {
+func (s *Store) GetSandboxTags(ctx context.Context, orgID uuid.UUID, sandboxID string) (SandboxTagSet, error) {
rows, err := s.pool.Query(ctx,
- `SELECT key, value, updated_at FROM sandbox_tags WHERE sandbox_id = $1`,
- sandboxID)
+ `SELECT key, value, updated_at FROM sandbox_tags
+ WHERE org_id = $1 AND sandbox_id = $2`,
+ orgID, sandboxID)
if err != nil {
return SandboxTagSet{}, fmt.Errorf("query sandbox tags: %w", err)
}
@@ -50,15 +57,17 @@ func (s *Store) GetSandboxTags(ctx context.Context, sandboxID string) (SandboxTa
}
// GetSandboxTagsMulti returns tag sets keyed by sandbox_id for a batch of
-// sandboxes — used to hydrate GET /sandboxes and /sandboxes/{id} without
-// N+1 queries. Sandboxes with no tags are absent from the result map.
-func (s *Store) GetSandboxTagsMulti(ctx context.Context, sandboxIDs []string) (map[string]SandboxTagSet, error) {
+// sandboxes within one org — used to hydrate GET /sandboxes and
+// /sandboxes/{id} without N+1 queries. Sandboxes with no tags are
+// absent from the result map.
+func (s *Store) GetSandboxTagsMulti(ctx context.Context, orgID uuid.UUID, sandboxIDs []string) (map[string]SandboxTagSet, error) {
if len(sandboxIDs) == 0 {
return map[string]SandboxTagSet{}, nil
}
rows, err := s.pool.Query(ctx,
`SELECT sandbox_id, key, value, updated_at FROM sandbox_tags
- WHERE sandbox_id = ANY($1)`, sandboxIDs)
+ WHERE org_id = $1 AND sandbox_id = ANY($2)`,
+ orgID, sandboxIDs)
if err != nil {
return nil, fmt.Errorf("query multi sandbox tags: %w", err)
}
@@ -85,9 +94,11 @@ func (s *Store) GetSandboxTagsMulti(ctx context.Context, sandboxIDs []string) (m
return out, rows.Err()
}
-// ReplaceSandboxTags atomically replaces the full tag set for a sandbox.
-// An empty map clears all tags. updated_at on retained rows is refreshed
-// only if the value changed — idempotent PUTs don't bump the timestamp.
+// ReplaceSandboxTags atomically replaces the full tag set for a sandbox
+// within the caller's org. An empty map clears all tags. updated_at is
+// only refreshed on rows whose value actually changed — idempotent
+// PUTs don't bump the timestamp, which would otherwise confuse the
+// tagsLastUpdatedAt signal that dashboards rely on.
func (s *Store) ReplaceSandboxTags(ctx context.Context, orgID uuid.UUID, sandboxID string, tags map[string]string) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -95,12 +106,10 @@ func (s *Store) ReplaceSandboxTags(ctx context.Context, orgID uuid.UUID, sandbox
}
defer tx.Rollback(ctx)
- // Diff against current state so we only bump updated_at when something
- // actually changed. Retagging is supposed to rewrite attribution going
- // forward (see design), and tagsLastUpdatedAt is the signal dashboards
- // rely on — so we must not bump it on no-op PUTs.
curRows, err := tx.Query(ctx,
- `SELECT key, value FROM sandbox_tags WHERE sandbox_id = $1`, sandboxID)
+ `SELECT key, value FROM sandbox_tags
+ WHERE org_id = $1 AND sandbox_id = $2`,
+ orgID, sandboxID)
if err != nil {
return err
}
@@ -118,17 +127,16 @@ func (s *Store) ReplaceSandboxTags(ctx context.Context, orgID uuid.UUID, sandbox
return err
}
- // Delete keys that are no longer present.
for k := range current {
if _, keep := tags[k]; !keep {
if _, err := tx.Exec(ctx,
- `DELETE FROM sandbox_tags WHERE sandbox_id = $1 AND key = $2`,
- sandboxID, k); err != nil {
+ `DELETE FROM sandbox_tags
+ WHERE org_id = $1 AND sandbox_id = $2 AND key = $3`,
+ orgID, sandboxID, k); err != nil {
return err
}
}
}
- // Upsert changed or new keys.
for k, v := range tags {
if cur, ok := current[k]; ok && cur == v {
continue
@@ -136,8 +144,8 @@ func (s *Store) ReplaceSandboxTags(ctx context.Context, orgID uuid.UUID, sandbox
if _, err := tx.Exec(ctx,
`INSERT INTO sandbox_tags (org_id, sandbox_id, key, value, updated_at)
VALUES ($1, $2, $3, $4, now())
- ON CONFLICT (sandbox_id, key) DO UPDATE
- SET value = EXCLUDED.value, updated_at = now(), org_id = EXCLUDED.org_id`,
+ ON CONFLICT (org_id, sandbox_id, key) DO UPDATE
+ SET value = EXCLUDED.value, updated_at = now()`,
orgID, sandboxID, k, v); err != nil {
return err
}
diff --git a/internal/db/store.go b/internal/db/store.go
index 5b160e0e..775097b5 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -662,6 +662,41 @@ func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*Sandb
return session, nil
}
+// GetLatestSandboxSessionsMulti returns the most recent session per
+// sandbox_id for an org — one row per ID, picked by MAX(started_at)
+// via DISTINCT ON. Used by the /usage groupBy=sandbox handler to
+// hydrate alias/status without issuing a GetSandboxSession per row
+// (design F11: 500-row × 10s budget rules out N+1). Sandboxes with
+// no session in the result map aren't included.
+func (s *Store) GetLatestSandboxSessionsMulti(ctx context.Context, orgID uuid.UUID, sandboxIDs []string) (map[string]*SandboxSession, error) {
+ if len(sandboxIDs) == 0 {
+ return map[string]*SandboxSession{}, nil
+ }
+ rows, err := s.pool.Query(ctx,
+ `SELECT DISTINCT ON (sandbox_id)
+ 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 sandbox_id = ANY($2)
+ ORDER BY sandbox_id, started_at DESC`,
+ orgID, sandboxIDs)
+ if err != nil {
+ return nil, fmt.Errorf("failed to batch-load sandbox sessions: %w", err)
+ }
+ defer rows.Close()
+
+ out := map[string]*SandboxSession{}
+ for rows.Next() {
+ sess := &SandboxSession{}
+ if err := rows.Scan(&sess.ID, &sess.SandboxID, &sess.OrgID, &sess.UserID, &sess.Template,
+ &sess.Region, &sess.WorkerID, &sess.Status, &sess.Config, &sess.Metadata,
+ &sess.StartedAt, &sess.StoppedAt, &sess.ErrorMsg, &sess.BasedOnCheckpointID, &sess.LastPatchSequence, &sess.PatchError, &sess.GoldenVersion); err != nil {
+ return nil, err
+ }
+ out[sess.SandboxID] = sess
+ }
+ return out, rows.Err()
+}
+
func (s *Store) ListSandboxSessions(ctx context.Context, orgID uuid.UUID, status string, limit, offset int) ([]SandboxSession, error) {
var rows pgx.Rows
var err error
diff --git a/internal/db/usage_query.go b/internal/db/usage_query.go
index e2e8fd36..92841aec 100644
--- a/internal/db/usage_query.go
+++ b/internal/db/usage_query.go
@@ -136,7 +136,11 @@ func (b *builderState) windowWhere(orgArg, fromArg, toArg string) string {
}
// filterJoins emits JOIN clauses that restrict `e.sandbox_id` to the
-// filter set. Non-empty value slice → INNER JOIN on matching rows.
+// filter set. All joins scope on (org_id, sandbox_id) — sandbox_tags
+// is keyed on both (see migration 026) because sandbox IDs are not
+// schema-unique across orgs.
+//
+// Non-empty value slice → INNER JOIN on matching rows.
// Empty slice → LEFT JOIN + IS NULL, meaning "key absent."
func (b *builderState) filterJoins(filters []UsageFilter) string {
if len(filters) == 0 {
@@ -147,15 +151,14 @@ func (b *builderState) filterJoins(filters []UsageFilter) string {
alias := fmt.Sprintf("ft%d", i)
keyArg := b.arg(f.TagKey)
if len(f.Values) == 0 {
- // key-absent
sb.WriteString(fmt.Sprintf(
- " LEFT JOIN sandbox_tags %s ON %s.sandbox_id = e.sandbox_id AND %s.key = %s",
- alias, alias, alias, keyArg))
+ " LEFT JOIN sandbox_tags %s ON %s.org_id = e.org_id AND %s.sandbox_id = e.sandbox_id AND %s.key = %s",
+ alias, alias, alias, alias, keyArg))
} else {
valArg := b.arg(f.Values)
sb.WriteString(fmt.Sprintf(
- " INNER JOIN sandbox_tags %s ON %s.sandbox_id = e.sandbox_id AND %s.key = %s AND %s.value = ANY(%s)",
- alias, alias, alias, keyArg, alias, valArg))
+ " INNER JOIN sandbox_tags %s ON %s.org_id = e.org_id AND %s.sandbox_id = e.sandbox_id AND %s.key = %s AND %s.value = ANY(%s)",
+ alias, alias, alias, alias, keyArg, alias, valArg))
}
}
return sb.String()
@@ -230,7 +233,7 @@ func BuildUsageQuery(q UsageQuery) (sqlText string, args []any, err error) {
case "tag":
tagKeyArg := b.arg(tagKey)
groupJoin = fmt.Sprintf(
- " LEFT JOIN sandbox_tags gt ON gt.sandbox_id = e.sandbox_id AND gt.key = %s",
+ " LEFT JOIN sandbox_tags gt ON gt.org_id = e.org_id AND gt.sandbox_id = e.sandbox_id AND gt.key = %s",
tagKeyArg)
// Only rows with a value go in items; untagged is queried separately.
extra += " AND gt.value IS NOT NULL"
@@ -321,7 +324,7 @@ SELECT
COALESCE(SUM(GREATEST(e.disk_mb - %d, 0)::float / 1024.0 * %s), 0) AS disk_overage_gb_seconds,
COUNT(DISTINCT e.sandbox_id) AS sandbox_count
FROM sandbox_scale_events e%s
-LEFT JOIN sandbox_tags gt ON gt.sandbox_id = e.sandbox_id AND gt.key = %s
+LEFT JOIN sandbox_tags gt ON gt.org_id = e.org_id AND gt.sandbox_id = e.sandbox_id AND gt.key = %s
WHERE %s%s AND gt.sandbox_id IS NULL`,
dur,
20480, dur,
@@ -455,6 +458,11 @@ func (s *Store) ExecuteOrgTotals(ctx context.Context, q UsageQuery) (UsageTotals
// GET /sandboxes/{id}/usage: GB-second numbers plus first/last session
// timestamps clamped to the query window. Tag hydration is left to
// the handler (which calls GetSandboxTags).
+//
+// Timestamps are explicitly clamped into [from, to] (design F9):
+// without the clamp, long-lived sandboxes leak endpoints outside the
+// requested window. The SQL uses GREATEST(MIN(started_at), from) and
+// LEAST(MAX(...), to).
func (s *Store) SandboxUsageWindow(ctx context.Context, orgID uuid.UUID, sandboxID string, from, to time.Time) (mem, disk float64, firstStartedAt *time.Time, lastEndedAt *time.Time, err error) {
// Usage numbers from scale events, identical math to GetOrgUsage.
err = s.pool.QueryRow(ctx, `
@@ -469,17 +477,18 @@ WHERE e.org_id = $1 AND e.sandbox_id = $4
return 0, 0, nil, nil, fmt.Errorf("sandbox usage query: %w", err)
}
- // Lifetime bounds from sandbox_sessions (see design: session-level
- // is more intuitive than scale-event edges for "when did this
- // sandbox exist").
+ // Lifetime bounds from sandbox_sessions, clamped into [from, to].
+ // Session-level MIN/MAX is more intuitive than scale-event edges
+ // for "when did this sandbox exist" and is stable across scale
+ // churn — see design D1.
var minStart *time.Time
var anyOpen bool
var maxEnd *time.Time
row := s.pool.QueryRow(ctx, `
SELECT
- MIN(started_at),
+ GREATEST(MIN(started_at), $3),
BOOL_OR(stopped_at IS NULL AND status IN ('running', 'hibernated')),
- MAX(COALESCE(stopped_at, now()))
+ LEAST(MAX(COALESCE(stopped_at, now())), $4)
FROM sandbox_sessions
WHERE org_id = $1 AND sandbox_id = $2
AND started_at < $4
diff --git a/internal/db/usage_query_test.go b/internal/db/usage_query_test.go
index 4990426f..486fccd9 100644
--- a/internal/db/usage_query_test.go
+++ b/internal/db/usage_query_test.go
@@ -199,6 +199,36 @@ func TestCursorRoundTrip(t *testing.T) {
}
}
+// Pins the tenancy boundary: every sandbox_tags join must scope on
+// org_id, not just sandbox_id. Sandbox IDs are not schema-unique
+// across orgs, so a sandbox_id-only join could alias tag state across
+// tenants on collision. Migration 026 reflects the same decision in
+// the PK.
+func TestBuildUsageQuery_JoinsIncludeOrgID(t *testing.T) {
+ q := baseQuery()
+ q.GroupBy = "tag:team"
+ q.Filters = []UsageFilter{
+ {TagKey: "env", Values: []string{"prod"}},
+ {TagKey: "region", Values: nil}, // key-absent
+ }
+ sql, _, err := BuildUsageQuery(q)
+ if err != nil {
+ t.Fatalf("BuildUsageQuery: %v", err)
+ }
+ // Every sandbox_tags alias — gt, ft0, ft1 — must constrain
+ // ON org_id.
+ expects := []string{
+ "gt.org_id = e.org_id",
+ "ft0.org_id = e.org_id",
+ "ft1.org_id = e.org_id",
+ }
+ for _, want := range expects {
+ if !strings.Contains(sql, want) {
+ t.Errorf("missing org-scoped join predicate %q:\n%s", want, sql)
+ }
+ }
+}
+
func TestBuildUntaggedTotals(t *testing.T) {
q := baseQuery()
q.GroupBy = "tag:env"