Skip to content

An open-source, faster Devin alternative

TypeScript

db+api+sdk+test: apply second-review findings F12-F15

Igor Zalutski0ee461750379
diff --git a/internal/api/sandbox_tags.go b/internal/api/sandbox_tags.go
index 682f5cd2..670eadcb 100644
--- a/internal/api/sandbox_tags.go
+++ b/internal/api/sandbox_tags.go
@@ -51,9 +51,13 @@ func validateTags(tags map[string]string) error {
return nil
}
-// ownsSandbox returns a typed 404 when the sandbox is missing and a
-// typed 403 when it belongs to another org. It does not leak the
-// existence of sandboxes across orgs — both cases read 404.
+// ownsSandbox returns nil when the caller's org has a session for the
+// given sandbox ID, otherwise returns a 404 response. Uses the
+// org-scoped session lookup (design F12) — querying by sandbox_id
+// alone could return another org's row on an ID collision, which
+// would cause the rightful owner to be denied access to their own
+// sandbox. 404 in both "doesn't exist" and "not your org" paths so
+// we don't leak cross-tenant existence.
func (s *Server) ownsSandbox(c echo.Context, sandboxID string) error {
if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
@@ -64,8 +68,7 @@ func (s *Server) ownsSandbox(c echo.Context, sandboxID string) error {
if !ok {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
}
- sess, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
- if err != nil || sess.OrgID != orgID {
+ if _, err := s.store.GetSandboxSessionInOrg(c.Request().Context(), orgID, sandboxID); err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
}
return nil
diff --git a/internal/api/usage.go b/internal/api/usage.go
index 557061a2..4862b0f4 100644
--- a/internal/api/usage.go
+++ b/internal/api/usage.go
@@ -328,7 +328,7 @@ func (s *Server) getSandboxUsage(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
- sess, _ := s.store.GetSandboxSession(ctx, sandboxID)
+ sess, _ := s.store.GetSandboxSessionInOrg(ctx, orgID, 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/store.go b/internal/db/store.go
index 775097b5..c834efc0 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -662,6 +662,28 @@ func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*Sandb
return session, nil
}
+// GetSandboxSessionInOrg is the org-scoped variant of
+// GetSandboxSession — sandbox IDs are not globally unique, so every
+// read that is going to gate authorization or hydrate tenant-visible
+// fields must filter on (org_id, sandbox_id) not sandbox_id alone
+// (design F12). Returns the latest session for the (org, sandbox)
+// pair, or an error when no such session exists.
+func (s *Store) GetSandboxSessionInOrg(ctx context.Context, orgID uuid.UUID, sandboxID string) (*SandboxSession, error) {
+ session := &SandboxSession{}
+ err := s.pool.QueryRow(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 sandbox_id = $2
+ ORDER BY started_at DESC LIMIT 1`, orgID, sandboxID,
+ ).Scan(&session.ID, &session.SandboxID, &session.OrgID, &session.UserID, &session.Template,
+ &session.Region, &session.WorkerID, &session.Status, &session.Config, &session.Metadata,
+ &session.StartedAt, &session.StoppedAt, &session.ErrorMsg, &session.BasedOnCheckpointID, &session.LastPatchSequence, &session.PatchError, &session.GoldenVersion)
+ if err != nil {
+ return nil, fmt.Errorf("sandbox session not found: %w", err)
+ }
+ 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
diff --git a/internal/db/usage_query.go b/internal/db/usage_query.go
index 92841aec..56696912 100644
--- a/internal/db/usage_query.go
+++ b/internal/db/usage_query.go
@@ -481,23 +481,25 @@ WHERE e.org_id = $1 AND e.sandbox_id = $4
// 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
+ //
+ // "No session in the window" is expressed as NULL aggregates, not
+ // as a scan error — *time.Time handles NULL via nil, and BOOL_OR
+ // is COALESCE'd to false so scan never fails on empty input
+ // (design F13). A scan error here therefore means a real DB /
+ // context failure and is returned up the stack.
+ var minStart, maxEnd *time.Time
var anyOpen bool
- var maxEnd *time.Time
- row := s.pool.QueryRow(ctx, `
+ if err := s.pool.QueryRow(ctx, `
SELECT
GREATEST(MIN(started_at), $3),
- BOOL_OR(stopped_at IS NULL AND status IN ('running', 'hibernated')),
+ COALESCE(BOOL_OR(stopped_at IS NULL AND status IN ('running', 'hibernated')), false),
LEAST(MAX(COALESCE(stopped_at, now())), $4)
FROM sandbox_sessions
WHERE org_id = $1 AND sandbox_id = $2
AND started_at < $4
AND (stopped_at IS NULL OR stopped_at > $3)`,
- orgID, sandboxID, from, to)
- if err := row.Scan(&minStart, &anyOpen, &maxEnd); err != nil {
- // No session in the window is OK — the sandbox may have been
- // created then torn down before `from`. Leave first/last nil.
- return mem, disk, nil, nil, nil
+ orgID, sandboxID, from, to).Scan(&minStart, &anyOpen, &maxEnd); err != nil {
+ return 0, 0, nil, nil, fmt.Errorf("sandbox session bounds query: %w", err)
}
firstStartedAt = minStart
if !anyOpen {
diff --git a/internal/db/usage_query_pgfixture_test.go b/internal/db/usage_query_pgfixture_test.go
new file mode 100644
index 00000000..46d684f8
--- /dev/null
+++ b/internal/db/usage_query_pgfixture_test.go
@@ -0,0 +1,195 @@
+//go:build pgfixture
+
+// Reconciliation invariant for the usage aggregator. Runs only under
+// `go test -tags=pgfixture` against a real Postgres pointed at by
+// TEST_DATABASE_URL. The invariant is load-bearing for billing-
+// adjacent math — the pure-Go builder tests prove SQL shape but they
+// cannot prove the numbers line up with GetOrgUsage's rollup, which
+// is what the Stripe pipeline reports. See design
+// .agents/design/sandbox-tags-and-usage.md ("Unit is GB-seconds")
+// and work doc F5/F14.
+//
+// Run locally:
+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \
+// go test -tags=pgfixture ./internal/db/ -run Reconciliation -v
+package db
+
+import (
+ "context"
+ "math"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// DiskFreeAllowanceMB is duplicated from internal/billing because db
+// cannot import billing (billing → db would cycle). Kept in sync by
+// convention; BuildUsageQuery / BuildOrgTotals both hardcode 20480
+// for the same reason.
+const testDiskFreeAllowanceMB = 20480
+
+func openPgStore(t *testing.T) *Store {
+ t.Helper()
+ url := os.Getenv("TEST_DATABASE_URL")
+ if url == "" {
+ t.Skip("TEST_DATABASE_URL not set; skipping pgfixture test")
+ }
+ store, err := NewStore(context.Background(), url)
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ t.Cleanup(store.Close)
+ if err := store.Migrate(context.Background()); err != nil {
+ t.Fatalf("Migrate: %v", err)
+ }
+ return store
+}
+
+// seedReconciliationFixture writes a deterministic set of scale events
+// and tags scoped to a fresh org UUID. Isolation by org_id means
+// repeated runs against the same DB don't leak state — no global
+// cleanup needed.
+func seedReconciliationFixture(t *testing.T, store *Store, orgID uuid.UUID, from, to time.Time) {
+ t.Helper()
+ ctx := context.Background()
+
+ insertSE := func(sandboxID string, memMB, diskMB int, started time.Time, ended *time.Time) {
+ if _, err := store.pool.Exec(ctx,
+ `INSERT INTO sandbox_scale_events (sandbox_id, org_id, memory_mb, cpu_percent, disk_mb, started_at, ended_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,
+ sandboxID, orgID, memMB, memMB/40, diskMB, started, ended); err != nil {
+ t.Fatalf("seed scale event %s: %v", sandboxID, err)
+ }
+ }
+ insertTag := func(sandboxID, key, value string) {
+ if _, err := store.pool.Exec(ctx,
+ `INSERT INTO sandbox_tags (org_id, sandbox_id, key, value)
+ VALUES ($1, $2, $3, $4)`,
+ orgID, sandboxID, key, value); err != nil {
+ t.Fatalf("seed tag %s/%s: %v", sandboxID, key, err)
+ }
+ }
+
+ // sbx1: tagged team=payments, two scale events — one within the
+ // allowance (no disk overage), one with a 40GB workspace.
+ t1 := from.Add(2 * time.Hour)
+ t2 := from.Add(6 * time.Hour)
+ insertSE("sbx1", 4096, 20480, from.Add(-1*time.Hour), &t1)
+ insertSE("sbx1", 8192, 40960, t1, &t2)
+ insertTag("sbx1", "team", "payments")
+ insertTag("sbx1", "env", "prod")
+
+ // sbx2: tagged team=growth, one scale event, still open
+ // (ended_at NULL) — exercises the COALESCE path.
+ insertSE("sbx2", 4096, 20480, from.Add(1*time.Hour), nil)
+ insertTag("sbx2", "team", "growth")
+
+ // sbx3: untagged — tag table has no rows for it. Goes into the
+ // untagged sibling bucket on groupBy=tag:team.
+ t3 := from.Add(3 * time.Hour)
+ insertSE("sbx3", 1024, 20480, from.Add(30*time.Minute), &t3)
+
+ // sbx4: entirely before the window — must contribute zero to
+ // anything. Guards that the window clamp actually works.
+ pre := from.Add(-10 * time.Hour)
+ preEnd := from.Add(-2 * time.Hour)
+ insertSE("sbx4", 4096, 20480, pre, &preEnd)
+ insertTag("sbx4", "team", "ancient")
+}
+
+// TestReconciliationInvariant_pgfixture pins the load-bearing billing
+// claim: Σ by-sandbox == Σ by-tag + untagged == ExecuteOrgTotals ==
+// rollup from GetOrgUsage, all within float epsilon. If any of these
+// four diverge, per-tenant spend attribution diverges from what the
+// Stripe pipeline reports, which is a silent correctness bug.
+func TestReconciliationInvariant_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ orgID := uuid.New()
+ from := time.Now().UTC().Add(-24 * time.Hour).Truncate(time.Second)
+ to := time.Now().UTC().Truncate(time.Second)
+ seedReconciliationFixture(t, store, orgID, from, to)
+
+ // --- 1. GetOrgUsage rollup (what the Stripe pipeline uses).
+ summaries, err := store.GetOrgUsage(ctx, orgID.String(), from, to)
+ if err != nil {
+ t.Fatalf("GetOrgUsage: %v", err)
+ }
+ var rollupMem, rollupDisk float64
+ for _, s := range summaries {
+ rollupMem += float64(s.MemoryMB) / 1024.0 * s.TotalSeconds
+ if s.DiskMB > testDiskFreeAllowanceMB {
+ rollupDisk += float64(s.DiskMB-testDiskFreeAllowanceMB) / 1024.0 * s.TotalSeconds
+ }
+ }
+
+ // --- 2. ExecuteOrgTotals should match the rollup exactly.
+ baseQ := UsageQuery{
+ OrgID: orgID,
+ From: from,
+ To: to,
+ GroupBy: "sandbox",
+ Limit: 500,
+ }
+ totals, err := store.ExecuteOrgTotals(ctx, baseQ)
+ if err != nil {
+ t.Fatalf("ExecuteOrgTotals: %v", err)
+ }
+ assertClose(t, "org totals memory", rollupMem, totals.MemoryGbSeconds)
+ assertClose(t, "org totals disk overage", rollupDisk, totals.DiskOverageGbSeconds)
+
+ // --- 3. Σ by-sandbox == ExecuteOrgTotals.
+ rows, _, err := store.ExecuteUsageQuery(ctx, baseQ)
+ if err != nil {
+ t.Fatalf("ExecuteUsageQuery sandbox: %v", err)
+ }
+ var sbxMem, sbxDisk float64
+ for _, r := range rows {
+ sbxMem += r.MemoryGbSeconds
+ sbxDisk += r.DiskOverageGbSeconds
+ }
+ assertClose(t, "Σ by-sandbox memory", totals.MemoryGbSeconds, sbxMem)
+ assertClose(t, "Σ by-sandbox disk", totals.DiskOverageGbSeconds, sbxDisk)
+
+ // --- 4. Σ by-tag items + untagged == ExecuteOrgTotals.
+ tagQ := baseQ
+ tagQ.GroupBy = "tag:team"
+ tagRows, _, err := store.ExecuteUsageQuery(ctx, tagQ)
+ if err != nil {
+ t.Fatalf("ExecuteUsageQuery tag: %v", err)
+ }
+ untagged, err := store.ExecuteUntaggedTotals(ctx, tagQ)
+ if err != nil {
+ t.Fatalf("ExecuteUntaggedTotals: %v", err)
+ }
+ var tagMem, tagDisk float64
+ for _, r := range tagRows {
+ tagMem += r.MemoryGbSeconds
+ tagDisk += r.DiskOverageGbSeconds
+ }
+ tagMem += untagged.MemoryGbSeconds
+ tagDisk += untagged.DiskOverageGbSeconds
+ assertClose(t, "Σ by-tag memory", totals.MemoryGbSeconds, tagMem)
+ assertClose(t, "Σ by-tag disk", totals.DiskOverageGbSeconds, tagDisk)
+
+ // --- 5. Sanity: the pre-window event must not leak.
+ if rollupMem == 0 {
+ t.Fatal("expected non-zero memory usage from in-window events")
+ }
+
+ // --- 6. Untagged bucket must contain exactly one sandbox (sbx3).
+ if untagged.SandboxCount != 1 {
+ t.Errorf("untagged sandbox count = %d, want 1", untagged.SandboxCount)
+ }
+}
+
+func assertClose(t *testing.T, label string, want, got float64) {
+ t.Helper()
+ const eps = 1e-6
+ if math.Abs(want-got) > eps {
+ t.Errorf("%s: got %.9f, want %.9f (diff %.3e)", label, got, want, math.Abs(want-got))
+ }
+}
diff --git a/sdks/python/opencomputer/usage.py b/sdks/python/opencomputer/usage.py
index 2cd44190..ba59cd53 100644
--- a/sdks/python/opencomputer/usage.py
+++ b/sdks/python/opencomputer/usage.py
@@ -98,9 +98,14 @@ def _build_params(
cursor: str | None = None,
filter: dict[str, str] | None = None,
) -> list[tuple[str, str]]:
- """Build a flat list of (key, value) query params. httpx preserves
- duplicate keys when passed as a list of tuples, which is what
- `filter[tag:<key>]=...` with multiple keys expects."""
+ """Build a flat list of (key, value) query params.
+
+ v1 filter contract: one ``filter[tag:<key>]`` param per dimension.
+ Comma-separated values within a param are OR'd; different dimension
+ params are AND'd. The server rejects repeating the same
+ ``filter[...]`` key — which is naturally prevented here because the
+ ``filter`` argument is a ``dict[str, str]``.
+ """
params: list[tuple[str, str]] = []
if group_by is not None:
params.append(("groupBy", group_by))