An open-source, faster Devin alternative
TypeScript
add backfill
Brian Reardona64fd0530bb9
diff --git a/cmd/backfill/main.go b/cmd/backfill/main.gonew file mode 100644index 00000000..befacdfa--- /dev/null+++ b/cmd/backfill/main.go@@ -0,0 +1,650 @@+// backfill copies the global control-plane tables from a cell's PostgreSQL+// into the edge Cloudflare D1 database, for the PG → D1 cutover.+//+// It runs in three modes against the same code path:+//+// --mode=full snapshot every row (no watermark filter). Run once up front.+// --mode=delta only rows with updated_at > --since. Run repeatedly to keep+// D1 fresh while PG is still live; cheap, idempotent.+// --mode=final identical to delta — the name documents intent (the last+// delta run during the write blackout at the cutover moment).+//+// Every write is an UPSERT keyed on the D1 primary key, so re-runs and+// overlapping deltas converge. The watermark is updated_at across all tables+// (added uniformly by migration 040_add_updated_at). Each run prints the new+// max watermark to feed --since of the next run.+//+// Usage:+//+// OPENSANDBOX_DATABASE_URL=postgres://... \+// OPENSANDBOX_CF_API_TOKEN=... \+// go run ./cmd/backfill \+// --mode=full \+// --cell=azure-westus2-cell-0 \+// --home-cell=azure-westus2-cell-0 \+// --blob-prefix="azure-blob://opencomputer-prod/" \+// --account=1241f114453e32d292197e3fb36210b2 \+// --database=f9e534bf-a9f3-4b30-81cd-f9eb9087e96d+//+// The 9 global identity/billing/catalog tables are pure PG→D1. sandboxes_index+// and checkpoints_index are per-cell projections: cell_id/owner_cell_id come+// from --cell (single existing cell at first cutover), and checkpoints_index+// derives golden_hash from sandbox_sessions.golden_version — checkpoints whose+// golden can't be recovered are skipped (logged) since they stay restorable in+// their home cell.+package main++import (+ "bytes"+ "context"+ "encoding/hex"+ "encoding/json"+ "flag"+ "fmt"+ "log"+ "net/http"+ "os"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"++ "github.com/opensandbox/opensandbox/internal/crypto"+)++// rawLiteral marks a value that must be inlined into the SQL text verbatim+// instead of being sent as a bound parameter — used for SQLite blob literals+// (X'..hex..'), which can't travel as JSON params over the D1 HTTP API.+type rawLiteral string++// tableSpec describes one PG→D1 table copy.+type tableSpec struct {+ d1Table string+ cols []string // D1 column order for the INSERT+ pk []string // conflict-target columns+ // query returns the PG SQL + args. full=true omits the watermark filter;+ // otherwise the query must filter updated_at > to_timestamp($1).+ query func(full bool) (string, []any)+ // assemble maps one PG row (pgx rows.Values(), in the query's select order)+ // into a D1 row aligned with cols, plus the row's watermark (unix s) and a+ // skip flag for rows we intentionally drop.+ assemble func(src []any) (row []any, wm int64, skip bool)+}++func main() {+ mode := flag.String("mode", "", "full | delta | final")+ since := flag.Float64("since", 0, "delta/final: only rows with updated_at > this unix-seconds watermark")+ cell := flag.String("cell", "", "cell_id for sandboxes_index.cell_id")+ homeCell := flag.String("home-cell", "", "home_cell stamped on every backfilled org (defaults to --cell)")+ blobPrefix := flag.String("blob-prefix", "", "prefix prepended to rootfs_s3_key to form checkpoints_index.s3_url")+ account := flag.String("account", os.Getenv("OPENSANDBOX_CF_ACCOUNT_ID"), "Cloudflare account id")+ database := flag.String("database", os.Getenv("OPENSANDBOX_D1_DATABASE_ID"), "D1 database id")+ sandboxStates := flag.String("sandbox-states", "running,hibernated", "comma list of sandbox statuses to include in sandboxes_index")+ only := flag.String("tables", "", "optional comma list to restrict which D1 tables to sync (default all)")+ batchParams := flag.Int("batch-params", 90, "max bound params per D1 query (rows are chunked to fit)")+ dryRun := flag.Bool("dry-run", false, "query + count only; no D1 writes")+ flag.Parse()++ if *mode != "full" && *mode != "delta" && *mode != "final" {+ log.Fatal("--mode must be full, delta, or final")+ }+ full := *mode == "full"+ if !full && *since <= 0 {+ log.Fatal("--since (unix seconds) is required for delta/final mode")+ }+ if *cell == "" {+ log.Fatal("--cell is required")+ }+ if *homeCell == "" {+ *homeCell = *cell+ }+ if *blobPrefix == "" {+ log.Fatal("--blob-prefix is required (for checkpoints_index.s3_url)")+ }++ dbURL := os.Getenv("OPENSANDBOX_DATABASE_URL")+ if dbURL == "" {+ log.Fatal("OPENSANDBOX_DATABASE_URL is required")+ }+ token := os.Getenv("OPENSANDBOX_CF_API_TOKEN")+ if !*dryRun {+ if token == "" || *account == "" || *database == "" {+ log.Fatal("OPENSANDBOX_CF_API_TOKEN, --account, and --database are required unless --dry-run")+ }+ }++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)+ defer cancel()++ conn, err := pgx.Connect(ctx, dbURL)+ if err != nil {+ log.Fatalf("connect pg: %v", err)+ }+ defer conn.Close(ctx)++ d1 := &d1Client{+ http: &http.Client{Timeout: 60 * time.Second},+ account: *account,+ database: *database,+ token: token,+ dryRun: *dryRun,+ }++ var wanted map[string]bool+ if *only != "" {+ wanted = map[string]bool{}+ for _, t := range strings.Split(*only, ",") {+ wanted[strings.TrimSpace(t)] = true+ }+ }++ // secret_store_entries can't be raw-copied: the cell encrypts via the+ // keyring ([2B version][nonce][ct]) but the edge expects bare [nonce][ct].+ // So we decrypt with the cell keyring and re-encrypt in the edge's bare+ // format using the shared base key. Needs OPENSANDBOX_SECRET_ENCRYPTION_KEY.+ var keyring *crypto.KeyRing+ var reenc *crypto.Encryptor+ if wanted == nil || wanted["secret_store_entries"] {+ baseKey := os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY")+ if baseKey == "" {+ log.Fatal("OPENSANDBOX_SECRET_ENCRYPTION_KEY is required to backfill secret_store_entries (decrypt + re-encrypt); exclude it via --tables or set the key")+ }+ var err error+ if keyring, err = crypto.NewKeyRingFromEnv(); err != nil {+ log.Fatalf("build decrypt keyring: %v", err)+ }+ if reenc, err = crypto.NewEncryptor(baseKey); err != nil {+ log.Fatalf("build re-encryptor: %v", err)+ }+ }++ specs := buildSpecs(*cell, *homeCell, *blobPrefix, *sandboxStates, keyring, reenc)++ log.Printf("backfill mode=%s since=%.0f cell=%s dry-run=%v", *mode, *since, *cell, *dryRun)+ var globalMaxWM int64+ for _, spec := range specs {+ if wanted != nil && !wanted[spec.d1Table] {+ continue+ }+ n, skipped, maxWM, err := syncTable(ctx, conn, d1, spec, full, *since, *batchParams)+ if err != nil {+ log.Fatalf("%s: %v", spec.d1Table, err)+ }+ if maxWM > globalMaxWM {+ globalMaxWM = maxWM+ }+ log.Printf(" %-24s synced=%-7d skipped=%-5d maxWatermark=%d", spec.d1Table, n, skipped, maxWM)+ }++ if globalMaxWM > 0 {+ log.Printf("DONE. Next run: --mode=delta --since=%d", globalMaxWM)+ } else {+ log.Printf("DONE. No rows matched (watermark unchanged).")+ }+}++// syncTable runs one table's PG query, assembles D1 rows, and upserts them in+// param-bounded batches. Returns synced count, skipped count, and max watermark.+func syncTable(ctx context.Context, conn *pgx.Conn, d1 *d1Client, spec tableSpec, full bool, since float64, batchParams int) (int, int, int64, error) {+ sql, args := spec.query(full)+ if !full {+ args = append(args, since)+ }+ rows, err := conn.Query(ctx, sql, args...)+ if err != nil {+ return 0, 0, 0, fmt.Errorf("pg query: %w", err)+ }+ defer rows.Close()++ var batch [][]any+ synced, skipped := 0, 0+ var maxWM int64++ // rowsPerBatch keeps total bound params under batchParams. rawLiteral cells+ // don't count, but we conservatively size on the full column count.+ rowsPerBatch := max(batchParams/len(spec.cols), 1)++ flush := func() error {+ if len(batch) == 0 {+ return nil+ }+ if err := d1.upsert(ctx, spec, batch); err != nil {+ return err+ }+ synced += len(batch)+ batch = batch[:0]+ return nil+ }++ for rows.Next() {+ vals, err := rows.Values()+ if err != nil {+ return 0, 0, 0, fmt.Errorf("scan: %w", err)+ }+ row, wm, skip := spec.assemble(vals)+ if skip {+ skipped+++ continue+ }+ if wm > maxWM {+ maxWM = wm+ }+ batch = append(batch, row)+ if len(batch) >= rowsPerBatch {+ if err := flush(); err != nil {+ return 0, 0, 0, err+ }+ }+ }+ if err := rows.Err(); err != nil {+ return 0, 0, 0, fmt.Errorf("iterate: %w", err)+ }+ if err := flush(); err != nil {+ return 0, 0, 0, err+ }+ return synced, skipped, maxWM, nil+}++// ---- D1 HTTP client ------------------------------------------------------++type d1Client struct {+ http *http.Client+ account string+ database string+ token string+ dryRun bool+}++type d1Response struct {+ Success bool `json:"success"`+ Errors []struct {+ Code int `json:"code"`+ Message string `json:"message"`+ } `json:"errors"`+}++// upsert builds a multi-row INSERT ... ON CONFLICT DO UPDATE for the batch and+// executes it against D1. rawLiteral cells are inlined; all others are bound+// params.+func (c *d1Client) upsert(ctx context.Context, spec tableSpec, batch [][]any) error {+ var b strings.Builder+ fmt.Fprintf(&b, "INSERT INTO %s (%s) VALUES ", spec.d1Table, strings.Join(spec.cols, ", "))++ params := make([]any, 0, len(batch)*len(spec.cols))+ for i, row := range batch {+ if i > 0 {+ b.WriteString(", ")+ }+ b.WriteByte('(')+ for j, v := range row {+ if j > 0 {+ b.WriteString(", ")+ }+ if lit, ok := v.(rawLiteral); ok {+ b.WriteString(string(lit))+ } else {+ b.WriteByte('?')+ params = append(params, v)+ }+ }+ b.WriteByte(')')+ }++ // ON CONFLICT upsert: update every non-PK column from the excluded row.+ pkSet := map[string]bool{}+ for _, k := range spec.pk {+ pkSet[k] = true+ }+ var setClauses []string+ for _, col := range spec.cols {+ if !pkSet[col] {+ setClauses = append(setClauses, fmt.Sprintf("%s = excluded.%s", col, col))+ }+ }+ fmt.Fprintf(&b, " ON CONFLICT(%s) DO UPDATE SET %s",+ strings.Join(spec.pk, ", "), strings.Join(setClauses, ", "))++ if c.dryRun {+ return nil+ }+ return c.query(ctx, b.String(), params)+}++func (c *d1Client) query(ctx context.Context, sql string, params []any) error {+ body, _ := json.Marshal(map[string]any{"sql": sql, "params": params})+ url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/d1/database/%s/query", c.account, c.database)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return err+ }+ req.Header.Set("Authorization", "Bearer "+c.token)+ req.Header.Set("Content-Type", "application/json")++ resp, err := c.http.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ var parsed d1Response+ if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {+ return fmt.Errorf("decode d1 response (http %d): %w", resp.StatusCode, err)+ }+ if !parsed.Success {+ if len(parsed.Errors) > 0 {+ return fmt.Errorf("d1 error %d: %s", parsed.Errors[0].Code, parsed.Errors[0].Message)+ }+ return fmt.Errorf("d1 request failed (http %d)", resp.StatusCode)+ }+ return nil+}++// ---- helpers -------------------------------------------------------------++// toInt64 normalizes pgx numeric scan results (int32/int64) to int64; nil → 0.+func toInt64(v any) int64 {+ switch n := v.(type) {+ case int64:+ return n+ case int32:+ return int64(n)+ case int:+ return int64(n)+ }+ return 0+}++// where appends the watermark filter for delta/final modes.+func where(full bool, base, filter string) string {+ if full {+ return base+ }+ return base + " " + filter+}++// ---- table specs ---------------------------------------------------------++func buildSpecs(cell, homeCell, blobPrefix, sandboxStates string, keyring *crypto.KeyRing, reenc *crypto.Encryptor) []tableSpec {+ activeStates := map[string]bool{}+ for _, s := range strings.Split(sandboxStates, ",") {+ activeStates[strings.TrimSpace(s)] = true+ }++ return []tableSpec{+ // orgs ---------------------------------------------------------------+ {+ d1Table: "orgs",+ pk: []string{"id"},+ cols: []string{+ "id", "name", "slug", "plan", "home_cell", "stripe_customer_id",+ "stripe_subscription_id", "workos_org_id", "is_personal", "owner_user_id",+ "created_at", "updated_at", "is_halted", "halted_at", "custom_domain",+ "cf_hostname_id", "domain_verification_status", "domain_ssl_status",+ "verification_txt_name", "verification_txt_value", "ssl_txt_name",+ "ssl_txt_value", "free_credits_remaining_cents", "credit_balance_cents",+ "max_concurrent_sandboxes", "max_sandbox_timeout_sec", "max_disk_mb",+ "max_memory_gb", "billing_mode", "last_usage_reported_at",+ },+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT id::text, name, slug, plan, stripe_customer_id, stripe_subscription_id,+ workos_org_id, is_personal::int, owner_user_id::text,+ EXTRACT(EPOCH FROM created_at)::bigint, EXTRACT(EPOCH FROM updated_at)::bigint,+ custom_domain, cf_hostname_id, domain_verification_status, domain_ssl_status,+ verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,+ free_credits_remaining_cents, credit_balance_cents,+ max_concurrent_sandboxes, max_sandbox_timeout_sec, max_disk_mb, max_memory_gb,+ billing_mode, EXTRACT(EPOCH FROM last_usage_reported_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM orgs`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ wm := toInt64(s[27])+ row := []any{+ s[0], s[1], s[2], s[3], homeCell, s[4], // id..stripe_customer_id, home_cell injected+ s[5], s[6], s[7], s[8], // stripe_sub, workos_org, is_personal, owner_user+ s[9], s[10], 0, nil, s[11], // created, updated, is_halted=0, halted_at=NULL, custom_domain+ s[12], s[13], s[14], // cf_hostname, dom_verif, dom_ssl+ s[15], s[16], s[17], s[18], // verif/ssl txt+ s[19], s[20], // free_credits, credit_balance+ s[21], s[22], s[23], s[24], // quotas+ s[25], s[26], // billing_mode, last_usage_reported_at+ }+ return row, wm, false+ },+ },++ // users --------------------------------------------------------------+ {+ d1Table: "users",+ pk: []string{"id"},+ cols: []string{"id", "email", "workos_user_id", "name", "created_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT id::text, email, workos_user_id, name,+ EXTRACT(EPOCH FROM created_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM users`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ return []any{s[0], s[1], s[2], s[3], s[4]}, toInt64(s[5]), false+ },+ },++ // org_memberships (derived from users.org_id/role) ------------------+ {+ d1Table: "org_memberships",+ pk: []string{"org_id", "user_id"},+ cols: []string{"org_id", "user_id", "role", "created_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT org_id::text, id::text, role,+ EXTRACT(EPOCH FROM created_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM users`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ return []any{s[0], s[1], s[2], s[3]}, toInt64(s[4]), false+ },+ },++ // api_keys -----------------------------------------------------------+ {+ d1Table: "api_keys",+ pk: []string{"id"},+ cols: []string{"id", "org_id", "created_by", "key_hash", "key_prefix", "name",+ "scopes", "last_used", "expires_at", "created_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT id::text, org_id::text, created_by::text, key_hash, key_prefix, name,+ array_to_json(scopes)::text,+ EXTRACT(EPOCH FROM last_used)::bigint, EXTRACT(EPOCH FROM expires_at)::bigint,+ EXTRACT(EPOCH FROM created_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM api_keys`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ return []any{s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9]}, toInt64(s[10]), false+ },+ },++ // templates ----------------------------------------------------------+ {+ d1Table: "templates",+ pk: []string{"id"},+ cols: []string{"id", "org_id", "name", "tag", "template_type", "image_ref",+ "rootfs_s3_key", "workspace_s3_key", "dockerfile", "is_public", "status",+ "cells_available", "created_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT id::text, org_id::text, name, tag, template_type, image_ref,+ rootfs_s3_key, workspace_s3_key, dockerfile, is_public::int, status,+ EXTRACT(EPOCH FROM created_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM templates`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ row := []any{s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], "[]", s[11]}+ return row, toInt64(s[12]), false+ },+ },++ // secret_stores ------------------------------------------------------+ {+ d1Table: "secret_stores",+ pk: []string{"id"},+ cols: []string{"id", "org_id", "name", "egress_allowlist", "created_at", "updated_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT id::text, org_id::text, name, array_to_json(egress_allowlist)::text,+ EXTRACT(EPOCH FROM created_at)::bigint, EXTRACT(EPOCH FROM updated_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM secret_stores`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ return []any{s[0], s[1], s[2], s[3], s[4], s[5]}, toInt64(s[6]), false+ },+ },++ // secret_store_entries (BYTEA → BLOB literal) ------------------------+ {+ d1Table: "secret_store_entries",+ pk: []string{"id"},+ cols: []string{"id", "store_id", "name", "encrypted_value", "allowed_hosts", "created_at", "updated_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT id::text, store_id::text, name, encode(encrypted_value, 'hex'),+ array_to_json(allowed_hosts)::text,+ EXTRACT(EPOCH FROM created_at)::bigint, EXTRACT(EPOCH FROM updated_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM secret_store_entries`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ hexCt, _ := s[3].(string)+ raw, err := hex.DecodeString(hexCt)+ if err != nil {+ log.Printf(" secret_store_entries %v: bad hex — SKIPPED: %v", s[0], err)+ return nil, 0, true+ }+ // Decrypt with the cell keyring (strips version header, tries+ // rotated keys), re-encrypt bare so the edge can read it.+ plaintext, err := keyring.Decrypt(raw)+ if err != nil {+ log.Printf(" secret_store_entries %v: DECRYPT FAILED (investigate — real secret won't survive cutover) — SKIPPED: %v", s[0], err)+ return nil, 0, true+ }+ reencrypted, err := reenc.Encrypt(plaintext)+ if err != nil {+ log.Printf(" secret_store_entries %v: re-encrypt failed — SKIPPED: %v", s[0], err)+ return nil, 0, true+ }+ ev := rawLiteral("X'" + hex.EncodeToString(reencrypted) + "'")+ return []any{s[0], s[1], s[2], ev, s[4], s[5], s[6]}, toInt64(s[7]), false+ },+ },++ // agent_subscriptions (shape mismatch) -------------------------------+ {+ d1Table: "agent_subscriptions",+ pk: []string{"id"},+ cols: []string{"id", "org_id", "agent_id", "feature", "status", "stripe_item_id", "created_at", "cancelled_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT id::text, org_id::text, agent_id, feature, status, stripe_subscription_id,+ EXTRACT(EPOCH FROM created_at)::bigint, EXTRACT(EPOCH FROM canceled_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM agent_subscriptions`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ return []any{s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]}, toInt64(s[8]), false+ },+ },++ // org_subscription_items (memory_mb → tier) --------------------------+ {+ d1Table: "org_subscription_items",+ pk: []string{"org_id", "tier"},+ cols: []string{"org_id", "tier", "stripe_item_id", "price_id"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT org_id::text, memory_mb::text, stripe_subscription_item_id,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM org_subscription_items`,+ `WHERE updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ return []any{s[0], s[1], s[2], ""}, toInt64(s[3]), false+ },+ },++ // sandboxes_index (latest session per sandbox, active states) --------+ {+ d1Table: "sandboxes_index",+ pk: []string{"id"},+ cols: []string{"id", "org_id", "user_id", "cell_id", "worker_id", "status", "template_id", "created_at", "last_event_at", "stopped_at"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT DISTINCT ON (sandbox_id)+ sandbox_id, org_id::text, user_id::text, worker_id, status,+ based_on_template_id::text,+ EXTRACT(EPOCH FROM started_at)::bigint,+ EXTRACT(EPOCH FROM COALESCE(stopped_at, started_at))::bigint,+ EXTRACT(EPOCH FROM stopped_at)::bigint,+ EXTRACT(EPOCH FROM updated_at)::bigint AS _wm+ FROM sandbox_sessions`,+ `WHERE updated_at > to_timestamp($1)`) ++ ` ORDER BY sandbox_id, started_at DESC`, nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ status, _ := s[4].(string)+ if !activeStates[status] {+ return nil, 0, true+ }+ row := []any{s[0], s[1], s[2], cell, s[3], s[4], s[5], s[6], s[7], s[8]}+ return row, toInt64(s[9]), false+ },+ },++ // checkpoints_index (golden_hash from session; skip unrecoverable) ---+ {+ d1Table: "checkpoints_index",+ pk: []string{"id"},+ cols: []string{"id", "sandbox_id", "org_id", "owner_cell_id", "s3_url", "size_bytes", "golden_hash", "workspace_size", "created_at", "expires_at", "replicated_to"},+ query: func(full bool) (string, []any) {+ return where(full, `+ SELECT c.id::text, c.sandbox_id, c.org_id::text, c.rootfs_s3_key, c.size_bytes,+ s.golden_version,+ EXTRACT(EPOCH FROM c.created_at)::bigint,+ EXTRACT(EPOCH FROM c.updated_at)::bigint AS _wm+ FROM sandbox_checkpoints c+ LEFT JOIN LATERAL (+ SELECT golden_version FROM sandbox_sessions ss+ WHERE ss.sandbox_id = c.sandbox_id AND ss.golden_version IS NOT NULL+ ORDER BY ss.started_at DESC LIMIT 1+ ) s ON true+ WHERE c.status = 'ready'`,+ `AND c.updated_at > to_timestamp($1)`), nil+ },+ assemble: func(s []any) ([]any, int64, bool) {+ golden, _ := s[5].(string)+ rootfsKey, _ := s[3].(string)+ if golden == "" || rootfsKey == "" {+ return nil, 0, true // unrecoverable golden or missing bytes — home-cell restorable+ }+ row := []any{+ s[0], s[1], s[2], cell, blobPrefix + rootfsKey, s[4], golden,+ nil, s[6], nil, "[]", // workspace_size NULL, expires_at NULL, replicated_to '[]'+ }+ return row, toInt64(s[7]), false+ },+ },+ }+}diff --git a/cmd/seed-dev-secrets/main.go b/cmd/seed-dev-secrets/main.gonew file mode 100644index 00000000..5cf026e5--- /dev/null+++ b/cmd/seed-dev-secrets/main.go@@ -0,0 +1,252 @@+// seed-dev-secrets inserts known-plaintext secrets into the dev cell PG,+// encrypted the SAME way the legacy CP encrypts them (via the keyring, which+// prepends a 2-byte version header). This gives the PG→D1 backfill real+// keyring-format ciphertext to decrypt-and-re-encrypt, and gives us known+// plaintexts to assert against after backfill.+//+// Run ON the dev CP VM (it has both PG reachability and the shared key):+//+// OPENSANDBOX_DATABASE_URL=... OPENSANDBOX_SECRET_ENCRYPTION_KEY=... \+// ./seed-dev-secrets [--dry-run]+//+// --verify mode: after the backfill has run, fetch the 10 entries back from+// D1 and assert each decrypts to its known plaintext via BOTH consumers:+// - CP path: keyring.Decrypt (the real runtime decryptor, edgeclient.go)+// - edge path: NewEncryptor.Decrypt — byte-identical to api-edge/src/crypto.ts+// decryptSecret (nonce = blob[0:12], AES-GCM)+//+// OPENSANDBOX_SECRET_ENCRYPTION_KEY=... OPENSANDBOX_CF_API_TOKEN=... \+// ./seed-dev-secrets --verify --account=<acct> --database=<d1-id>+//+// Idempotent (fixed UUIDs + ON CONFLICT DO NOTHING).+//+// Teardown:+// DELETE FROM secret_store_entries WHERE id::text LIKE 'e7000000-%';+// DELETE FROM secret_stores WHERE id::text LIKE 'c5000000-%';+package main++import (+ "bytes"+ "context"+ "encoding/hex"+ "encoding/json"+ "flag"+ "fmt"+ "log"+ "net/http"+ "os"+ "strings"+ "time"++ "github.com/jackc/pgx/v5"++ "github.com/opensandbox/opensandbox/internal/crypto"+)++type secret struct {+ storeIdx int+ entryID string+ name string+ plaintext string+ allowedHosts []string+}++var stores = []struct {+ id, orgID, name string+ egress []string+}{+ {"c5000000-0000-0000-0000-000000000001", "aaaaaaaa-0000-0000-0000-000000000001", "ks-store-a", []string{"api.openai.com"}},+ {"c5000000-0000-0000-0000-000000000002", "aaaaaaaa-0000-0000-0000-000000000002", "ks-store-b", []string{"*.github.com", "api.stripe.com"}},+ {"c5000000-0000-0000-0000-000000000003", "aaaaaaaa-0000-0000-0000-000000000003", "ks-store-c", []string{}},+}++var secrets = []secret{+ {1, "e7000000-0000-0000-0000-000000000001", "OPENAI_API_KEY", "sk-test-openai-abc123", []string{"api.openai.com"}},+ {1, "e7000000-0000-0000-0000-000000000002", "GITHUB_TOKEN", "ghp_testtoken456", []string{"*.github.com"}},+ {1, "e7000000-0000-0000-0000-000000000003", "DB_PASSWORD", "p@ssw0rd-with-symbols!#$", []string{}},+ {1, "e7000000-0000-0000-0000-000000000004", "EMPTYISH", "", []string{}},+ {2, "e7000000-0000-0000-0000-000000000005", "STRIPE_SECRET_KEY", "sk_test_stripe_789", []string{"api.stripe.com"}},+ {2, "e7000000-0000-0000-0000-000000000006", "SLACK_BOT_TOKEN", "xoxb-slack-bot-0001", []string{"slack.com"}},+ {2, "e7000000-0000-0000-0000-000000000007", "UNICODE_VALUE", "héllo-wörld-🔐-secret", []string{}},+ {3, "e7000000-0000-0000-0000-000000000008", "AWS_SECRET_ACCESS_KEY", "aws/secret+with/slashes", []string{"*.amazonaws.com"}},+ {3, "e7000000-0000-0000-0000-000000000009", "WEBHOOK_SECRET", "whsec_longvalue_0123456789abcdef", []string{}},+ {3, "e7000000-0000-0000-0000-000000000010", "JWT_SIGNING_KEY", "a-256-bit-signing-key-value-here", []string{}},+}++func main() {+ dryRun := flag.Bool("dry-run", false, "encrypt + print the plaintext map but don't write to PG")+ verify := flag.Bool("verify", false, "fetch the backfilled entries from D1 and assert they decrypt to the known plaintexts")+ account := flag.String("account", "", "CF account id (verify mode)")+ database := flag.String("database", "", "D1 database id (verify mode)")+ flag.Parse()++ if os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY") == "" {+ log.Fatal("OPENSANDBOX_SECRET_ENCRYPTION_KEY is required")+ }+ ring, err := crypto.NewKeyRingFromEnv()+ if err != nil {+ log.Fatalf("build keyring: %v", err)+ }+ if ring == nil {+ log.Fatal("keyring is nil — OPENSANDBOX_SECRET_ENCRYPTION_KEY not set")+ }++ if *verify {+ runVerify(ring, *account, *database)+ return+ }++ runSeed(ring, *dryRun)+}++func runSeed(ring *crypto.KeyRing, dryRun bool) {+ dbURL := os.Getenv("OPENSANDBOX_DATABASE_URL")+ if dbURL == "" {+ log.Fatal("OPENSANDBOX_DATABASE_URL is required")+ }+ enc := ring.AsEncryptor() // keyring-backed → version-prefixed, like legacy CP secrets++ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer cancel()+ conn, err := pgx.Connect(ctx, dbURL)+ if err != nil {+ log.Fatalf("connect pg: %v", err)+ }+ defer conn.Close(ctx)++ for _, s := range stores {+ if dryRun {+ log.Printf("[dry-run] store %s (%s) org=%s", s.id, s.name, s.orgID)+ continue+ }+ if _, err := conn.Exec(ctx,+ `INSERT INTO secret_stores (id, org_id, name, egress_allowlist)+ VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING`,+ s.id, s.orgID, s.name, s.egress); err != nil {+ log.Fatalf("insert store %s: %v", s.name, err)+ }+ }++ log.Printf("=== known secrets (entry_id | store.name | plaintext) ===")+ for _, sec := range secrets {+ st := stores[sec.storeIdx-1]+ ct, err := enc.Encrypt([]byte(sec.plaintext))+ if err != nil {+ log.Fatalf("encrypt %s: %v", sec.name, err)+ }+ log.Printf("%s | %s.%s | %q", sec.entryID, st.name, sec.name, sec.plaintext)+ if dryRun {+ continue+ }+ if _, err := conn.Exec(ctx,+ `INSERT INTO secret_store_entries (id, store_id, name, encrypted_value, allowed_hosts)+ VALUES ($1, $2, $3, $4, $5) ON CONFLICT (id) DO NOTHING`,+ sec.entryID, st.id, sec.name, ct, sec.allowedHosts); err != nil {+ log.Fatalf("insert entry %s: %v", sec.name, err)+ }+ }+ if dryRun {+ log.Printf("DONE (dry-run, nothing written)")+ } else {+ log.Printf("DONE: seeded %d stores + %d known secrets", len(stores), len(secrets))+ }+}++func runVerify(ring *crypto.KeyRing, account, database string) {+ token := os.Getenv("OPENSANDBOX_CF_API_TOKEN")+ if account == "" || database == "" || token == "" {+ log.Fatal("--account, --database, and OPENSANDBOX_CF_API_TOKEN are required for --verify")+ }+ // bareEnc.Decrypt replicates the edge's decryptSecret exactly (nonce=blob[0:12]).+ bareEnc, err := crypto.NewEncryptor(os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY"))+ if err != nil {+ log.Fatalf("build bare encryptor: %v", err)+ }++ ids := make([]string, len(secrets))+ for i, s := range secrets {+ ids[i] = "'" + s.entryID + "'"+ }+ sql := fmt.Sprintf("SELECT id, hex(encrypted_value) AS hexv FROM secret_store_entries WHERE id IN (%s)", strings.Join(ids, ","))++ rows, err := d1Query(account, database, token, sql)+ if err != nil {+ log.Fatalf("d1 query: %v", err)+ }+ got := map[string]string{} // entry_id → hex ciphertext+ for _, r := range rows {+ id, _ := r["id"].(string)+ hv, _ := r["hexv"].(string)+ got[id] = hv+ }++ pass, fail := 0, 0+ for _, sec := range secrets {+ hv, ok := got[sec.entryID]+ if !ok {+ log.Printf("FAIL %s (%s): not found in D1", sec.name, sec.entryID)+ fail+++ continue+ }+ blob, err := hex.DecodeString(hv)+ if err != nil {+ log.Printf("FAIL %s: bad hex from D1: %v", sec.name, err)+ fail+++ continue+ }+ cpPT, cpErr := ring.Decrypt(blob) // CP runtime path+ edgePT, edgeErr := bareEnc.Decrypt(blob) // edge decryptSecret replica+ cpOK := cpErr == nil && string(cpPT) == sec.plaintext+ edgeOK := edgeErr == nil && string(edgePT) == sec.plaintext+ if cpOK && edgeOK {+ log.Printf("PASS %s: CP+edge both decrypt to %q", sec.name, sec.plaintext)+ pass+++ } else {+ log.Printf("FAIL %s: cpOK=%v (err=%v) edgeOK=%v (err=%v)", sec.name, cpOK, cpErr, edgeOK, edgeErr)+ fail+++ }+ }+ log.Printf("=== VERIFY: %d pass, %d fail ===", pass, fail)+ if fail > 0 {+ os.Exit(1)+ }+}++func d1Query(account, database, token, sql string) ([]map[string]any, error) {+ body, _ := json.Marshal(map[string]any{"sql": sql})+ url := fmt.Sprintf("https://api.cloudflare.com/client/v4/accounts/%s/d1/database/%s/query", account, database)+ req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))+ if err != nil {+ return nil, err+ }+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("Content-Type", "application/json")+ resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ var parsed struct {+ Success bool `json:"success"`+ Errors []struct {+ Message string `json:"message"`+ } `json:"errors"`+ Result []struct {+ Results []map[string]any `json:"results"`+ } `json:"result"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil {+ return nil, fmt.Errorf("decode (http %d): %w", resp.StatusCode, err)+ }+ if !parsed.Success {+ if len(parsed.Errors) > 0 {+ return nil, fmt.Errorf("d1: %s", parsed.Errors[0].Message)+ }+ return nil, fmt.Errorf("d1 failed (http %d)", resp.StatusCode)+ }+ if len(parsed.Result) == 0 {+ return nil, nil+ }+ return parsed.Result[0].Results, nil+}diff --git a/deploy/dev/seed_dev.sql b/deploy/dev/seed_dev.sqlnew file mode 100644index 00000000..66375242--- /dev/null+++ b/deploy/dev/seed_dev.sql@@ -0,0 +1,166 @@+-- Seed data for the dev cell PG (opensandbox-prod RG, westus2) so the PG → D1+-- backfill test exercises every table and every code path.+--+-- Dev's schema already matches prod (migration 40); this only adds DATA. It is+-- idempotent (ON CONFLICT DO NOTHING) and all rows use recognizable seed UUIDs+-- (aaaaaaaa-… orgs, bbbbbbbb-… users, etc.) + 'seed-' names, so re-running is a+-- no-op and teardown is trivial (see bottom of file).+--+-- Coverage notes (why the CASE/MOD variation exists):+-- * orgs — free/pro, legacy/unified billing, with/without custom_domain + stripe ids+-- * users — owner/admin/member roles (drives org_memberships derivation)+-- * api_keys — single vs multi scope, with/without last_used + expires_at+-- * templates — org-owned vs public (NULL org_id), ready vs building+-- * agent_subs — active vs canceled (tests canceled_at→cancelled_at mapping)+-- * org_sub_items — varied memory_mb (tests memory_mb→tier mapping)+-- * sandbox_sessions— running/hibernated (indexed) + stopped/error (skipped); some NULL golden_version+-- * sandbox_checkpts— ready vs processing (skipped), some NULL rootfs (skipped),+-- some on a sandbox with NULL golden_version (skipped) — exercises all 3 skip branches++-- orgs ----------------------------------------------------------------------+INSERT INTO orgs (id, name, slug, plan, billing_mode, custom_domain,+ stripe_customer_id, stripe_subscription_id, is_personal,+ credit_balance_cents, free_credits_remaining_cents)+SELECT ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'Seed Org '||i,+ 'seed-org-'||lpad(i::text,2,'0'),+ CASE WHEN i%2=0 THEN 'pro' ELSE 'free' END,+ CASE WHEN i%2=0 THEN 'unified' ELSE 'legacy' END,+ CASE WHEN i%3=0 THEN 'seed'||i||'.example.com' ELSE NULL END,+ CASE WHEN i%2=0 THEN 'cus_seed'||i ELSE NULL END,+ CASE WHEN i%2=0 THEN 'sub_seed'||i ELSE NULL END,+ (i%4=0),+ 1000*i,+ 500+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- users (one per seed org; varied roles) ------------------------------------+INSERT INTO users (id, org_id, email, name, role, workos_user_id)+SELECT ('bbbbbbbb-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'seed-user-'||lpad(i::text,2,'0')||'@example.com',+ 'Seed User '||i,+ CASE WHEN i%3=0 THEN 'owner' WHEN i%3=1 THEN 'admin' ELSE 'member' END,+ CASE WHEN i%2=0 THEN 'wos_user_seed'||i ELSE NULL END+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- api_keys ------------------------------------------------------------------+INSERT INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name,+ scopes, last_used, expires_at)+SELECT ('cccccccc-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ ('bbbbbbbb-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'seedhash_'||i,+ 'sk_seed'||i,+ 'Seed Key '||i,+ CASE WHEN i%2=0 THEN ARRAY['sandbox:*','templates:read'] ELSE ARRAY['sandbox:*'] END,+ CASE WHEN i%2=0 THEN now()-(i||' days')::interval ELSE NULL END,+ CASE WHEN i%3=0 THEN now()+(30||' days')::interval ELSE NULL END+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- templates (org-owned + public) --------------------------------------------+INSERT INTO templates (id, org_id, name, tag, template_type, image_ref,+ is_public, status, rootfs_s3_key, workspace_s3_key)+SELECT ('dddddddd-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ CASE WHEN i%4=0 THEN NULL ELSE ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid END,+ 'seed-template-'||i,+ 'latest',+ CASE WHEN i%2=0 THEN 'dockerfile' ELSE 'image' END,+ 'registry/seed:'||i,+ (i%4=0),+ CASE WHEN i%5=0 THEN 'building' ELSE 'ready' END,+ 'templates/seed/'||i||'/rootfs.ext4',+ 'templates/seed/'||i||'/workspace.ext4'+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- secret_stores -------------------------------------------------------------+INSERT INTO secret_stores (id, org_id, name, egress_allowlist)+SELECT ('eeeeeeee-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'seed-store-'||i,+ CASE WHEN i%2=0 THEN ARRAY['api.openai.com','*.github.com'] ELSE ARRAY[]::text[] END+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- secret_store_entries are NOT seeded here. The backfill decrypts each entry+-- with the cell keyring and re-encrypts for the edge, so they must be REAL+-- keyring-format ciphertext (dummy bytes can't be decrypted). They're seeded+-- with known plaintexts by `cmd/seed-dev-secrets` (run on the CP, which has the+-- key), so the edge-decrypt verification can assert the round-trip.++-- agent_subscriptions (active + canceled) -----------------------------------+INSERT INTO agent_subscriptions (id, org_id, agent_id, feature, stripe_customer_id,+ stripe_subscription_id, stripe_price_id, status,+ current_period_end, cancel_at_period_end, canceled_at)+SELECT ('1a1a1a1a-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'agent-'||i,+ CASE WHEN i%2=0 THEN 'telegram' ELSE 'premium-tools' END,+ 'cus_seed'||i,+ 'sub_seed'||i,+ 'price_seed'||i,+ CASE WHEN i%3=0 THEN 'canceled' ELSE 'active' END,+ now()+(30||' days')::interval,+ (i%3=0),+ CASE WHEN i%3=0 THEN now()-(i||' days')::interval ELSE NULL END+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- org_subscription_items (varied memory tiers) ------------------------------+INSERT INTO org_subscription_items (org_id, memory_mb, stripe_subscription_item_id)+SELECT ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 512*i,+ 'si_seed'||i+FROM generate_series(1,10) i+ON CONFLICT (org_id, memory_mb) DO NOTHING;++-- sandbox_sessions (all statuses; some NULL golden_version) ------------------+INSERT INTO sandbox_sessions (id, sandbox_id, org_id, user_id, template, region,+ worker_id, status, based_on_template_id, golden_version,+ started_at, stopped_at)+SELECT ('2a2a2a2a-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'seed-sb-'||lpad(i::text,2,'0'),+ ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ CASE WHEN i%2=0 THEN ('bbbbbbbb-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid ELSE NULL END,+ 'seed-template-'||i,+ 'westus2',+ 'seed-worker-'||(i%3),+ CASE WHEN i%4=0 THEN 'stopped' WHEN i%4=1 THEN 'running'+ WHEN i%4=2 THEN 'hibernated' ELSE 'error' END,+ CASE WHEN i%4=0 THEN NULL ELSE ('dddddddd-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid END,+ CASE WHEN i%5=0 THEN NULL ELSE 'golden-'||(i%3) END,+ now()-(i||' hours')::interval,+ CASE WHEN i%4 IN (0,3) THEN now()-((i-1)||' hours')::interval ELSE NULL END+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- sandbox_checkpoints (ready/processing; NULL rootfs; NULL-golden sandboxes) -+INSERT INTO sandbox_checkpoints (id, sandbox_id, org_id, name, rootfs_s3_key,+ workspace_s3_key, status, size_bytes)+SELECT ('3a3a3a3a-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'seed-sb-'||lpad(i::text,2,'0'),+ ('aaaaaaaa-0000-0000-0000-'||lpad(i::text,12,'0'))::uuid,+ 'seed-ckpt-'||i,+ CASE WHEN i%6=0 THEN NULL+ ELSE 'checkpoints/seed-sb-'||lpad(i::text,2,'0')||'/ckpt'||i||'/rootfs.tar.zst' END,+ 'checkpoints/seed-sb-'||lpad(i::text,2,'0')||'/ckpt'||i||'/workspace.tar.zst',+ CASE WHEN i%3=0 THEN 'processing' ELSE 'ready' END,+ 1024*1024*i+FROM generate_series(1,10) i+ON CONFLICT (id) DO NOTHING;++-- Teardown (run to remove all seed data):+-- DELETE FROM sandbox_checkpoints WHERE id::text LIKE '3a3a3a3a-%';+-- DELETE FROM sandbox_sessions WHERE id::text LIKE '2a2a2a2a-%';+-- DELETE FROM org_subscription_items WHERE stripe_subscription_item_id LIKE 'si_seed%';+-- DELETE FROM agent_subscriptions WHERE id::text LIKE '1a1a1a1a-%';+-- DELETE FROM secret_store_entries WHERE id::text LIKE 'ffffffff-%';+-- DELETE FROM secret_stores WHERE id::text LIKE 'eeeeeeee-%';+-- DELETE FROM templates WHERE id::text LIKE 'dddddddd-%';+-- DELETE FROM api_keys WHERE id::text LIKE 'cccccccc-%';+-- DELETE FROM users WHERE id::text LIKE 'bbbbbbbb-%';+-- DELETE FROM orgs WHERE id::text LIKE 'aaaaaaaa-%';diff --git a/internal/db/migrations/040_add_updated_at.down.sql b/internal/db/migrations/040_add_updated_at.down.sqlnew file mode 100644index 00000000..b72cf01a--- /dev/null+++ b/internal/db/migrations/040_add_updated_at.down.sql@@ -0,0 +1,67 @@+-- Reverse 040_add_updated_at: drop triggers, columns, and the shared function.+-- Wrapped per-table in IF EXISTS so partial-applied envs reverse cleanly.++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'users') THEN+ DROP TRIGGER IF EXISTS users_set_updated_at ON users;+ ALTER TABLE users DROP COLUMN IF EXISTS updated_at;+ END IF;+END $$;++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'api_keys') THEN+ DROP TRIGGER IF EXISTS api_keys_set_updated_at ON api_keys;+ ALTER TABLE api_keys DROP COLUMN IF EXISTS updated_at;+ END IF;+END $$;++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'org_memberships') THEN+ DROP TRIGGER IF EXISTS org_memberships_set_updated_at ON org_memberships;+ ALTER TABLE org_memberships DROP COLUMN IF EXISTS updated_at;+ END IF;+END $$;++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'templates') THEN+ DROP TRIGGER IF EXISTS templates_set_updated_at ON templates;+ ALTER TABLE templates DROP COLUMN IF EXISTS updated_at;+ END IF;+END $$;++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'sandbox_sessions') THEN+ DROP TRIGGER IF EXISTS sandbox_sessions_set_updated_at ON sandbox_sessions;+ ALTER TABLE sandbox_sessions DROP COLUMN IF EXISTS updated_at;+ END IF;+END $$;++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'sandbox_checkpoints') THEN+ DROP TRIGGER IF EXISTS sandbox_checkpoints_set_updated_at ON sandbox_checkpoints;+ ALTER TABLE sandbox_checkpoints DROP COLUMN IF EXISTS updated_at;+ END IF;+END $$;++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'org_subscription_items') THEN+ DROP TRIGGER IF EXISTS org_subscription_items_set_updated_at ON org_subscription_items;+ ALTER TABLE org_subscription_items DROP COLUMN IF EXISTS updated_at;+ END IF;+END $$;++DROP FUNCTION IF EXISTS set_updated_at();diff --git a/internal/db/migrations/040_add_updated_at.up.sql b/internal/db/migrations/040_add_updated_at.up.sqlnew file mode 100644index 00000000..797797c3--- /dev/null+++ b/internal/db/migrations/040_add_updated_at.up.sql@@ -0,0 +1,166 @@+-- Add updated_at columns + auto-update triggers to tables that don't have+-- them, so the upcoming prod → D1 backfill script can use a uniform+-- watermark (updated_at) across every table during the cutover delta sync.+--+-- Without this, no delta-sync strategy catches row UPDATEs between the+-- initial snapshot and the cutover window — only INSERTs (via created_at)+-- — and a customer who renames their workspace, rotates a key, or has a+-- sandbox status change in that gap would silently desync into D1.+--+-- Why the trigger and not just DEFAULT now(): in Postgres, DEFAULT only+-- fires on INSERT, never on UPDATE. We need updated_at to track "last+-- modified", which requires a BEFORE UPDATE trigger. The trigger function+-- is shared across all tables — define once, reuse seven times.+--+-- Why nullable then backfilled then NOT NULL: ALTER TABLE ADD COLUMN with+-- a volatile DEFAULT (now()) forces PG to rewrite the table (slow on big+-- tables, locks). Splitting into "add nullable" → "backfill" → "set NOT+-- NULL + DEFAULT" keeps the schema change instant and the backfill+-- well-bounded.+--+-- Why each table is wrapped in IF EXISTS: prod and dev fleets have drifted+-- over time — some envs predate certain migrations (e.g. dev was missing+-- org_memberships at the time 040 was written). Wrapping each block in a+-- DO $$ ... IF EXISTS THEN ... END $$ makes the migration safely+-- idempotent across whatever schema actually exists, instead of failing+-- hard on the first missing table.+--+-- Tables targeted (no updated_at today):+-- users, api_keys, org_memberships, templates,+-- sandbox_sessions, sandbox_checkpoints, org_subscription_items+--+-- Tables skipped (already have a usable watermark):+-- orgs.updated_at, secret_stores.updated_at, secret_store_entries.updated_at,+-- agent_subscriptions.updated_at, image_cache.last_used_at,+-- usage_snapshots.snapshot_ts.++-- Shared trigger function — sets NEW.updated_at = now() on every UPDATE.+-- CREATE OR REPLACE so re-running the migration is a no-op for the function.+CREATE OR REPLACE FUNCTION set_updated_at()+RETURNS TRIGGER AS $$+BEGIN+ NEW.updated_at = now();+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++-- ── users ─────────────────────────────────────────────────────────────+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'users') THEN+ ALTER TABLE users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;+ UPDATE users SET updated_at = created_at WHERE updated_at IS NULL;+ ALTER TABLE users ALTER COLUMN updated_at SET NOT NULL;+ ALTER TABLE users ALTER COLUMN updated_at SET DEFAULT now();+ DROP TRIGGER IF EXISTS users_set_updated_at ON users;+ CREATE TRIGGER users_set_updated_at+ BEFORE UPDATE ON users+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+ END IF;+END $$;++-- ── api_keys ──────────────────────────────────────────────────────────+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'api_keys') THEN+ ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;+ UPDATE api_keys SET updated_at = created_at WHERE updated_at IS NULL;+ ALTER TABLE api_keys ALTER COLUMN updated_at SET NOT NULL;+ ALTER TABLE api_keys ALTER COLUMN updated_at SET DEFAULT now();+ DROP TRIGGER IF EXISTS api_keys_set_updated_at ON api_keys;+ CREATE TRIGGER api_keys_set_updated_at+ BEFORE UPDATE ON api_keys+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+ END IF;+END $$;++-- ── org_memberships ───────────────────────────────────────────────────+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'org_memberships') THEN+ ALTER TABLE org_memberships ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;+ UPDATE org_memberships SET updated_at = created_at WHERE updated_at IS NULL;+ ALTER TABLE org_memberships ALTER COLUMN updated_at SET NOT NULL;+ ALTER TABLE org_memberships ALTER COLUMN updated_at SET DEFAULT now();+ DROP TRIGGER IF EXISTS org_memberships_set_updated_at ON org_memberships;+ CREATE TRIGGER org_memberships_set_updated_at+ BEFORE UPDATE ON org_memberships+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+ END IF;+END $$;++-- ── templates ─────────────────────────────────────────────────────────+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'templates') THEN+ ALTER TABLE templates ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;+ UPDATE templates SET updated_at = created_at WHERE updated_at IS NULL;+ ALTER TABLE templates ALTER COLUMN updated_at SET NOT NULL;+ ALTER TABLE templates ALTER COLUMN updated_at SET DEFAULT now();+ DROP TRIGGER IF EXISTS templates_set_updated_at ON templates;+ CREATE TRIGGER templates_set_updated_at+ BEFORE UPDATE ON templates+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+ END IF;+END $$;++-- ── sandbox_sessions ──────────────────────────────────────────────────+-- Sandbox sessions have started_at + stopped_at but no single "modified"+-- timestamp; for the backfill watermark, the most recent of the two is+-- the right historical anchor (a stopped sandbox last "changed" when it+-- stopped; a running one when it started).+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'sandbox_sessions') THEN+ ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;+ UPDATE sandbox_sessions+ SET updated_at = COALESCE(stopped_at, started_at)+ WHERE updated_at IS NULL;+ ALTER TABLE sandbox_sessions ALTER COLUMN updated_at SET NOT NULL;+ ALTER TABLE sandbox_sessions ALTER COLUMN updated_at SET DEFAULT now();+ DROP TRIGGER IF EXISTS sandbox_sessions_set_updated_at ON sandbox_sessions;+ CREATE TRIGGER sandbox_sessions_set_updated_at+ BEFORE UPDATE ON sandbox_sessions+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+ END IF;+END $$;++-- ── sandbox_checkpoints ───────────────────────────────────────────────+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'sandbox_checkpoints') THEN+ ALTER TABLE sandbox_checkpoints ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;+ UPDATE sandbox_checkpoints SET updated_at = created_at WHERE updated_at IS NULL;+ ALTER TABLE sandbox_checkpoints ALTER COLUMN updated_at SET NOT NULL;+ ALTER TABLE sandbox_checkpoints ALTER COLUMN updated_at SET DEFAULT now();+ DROP TRIGGER IF EXISTS sandbox_checkpoints_set_updated_at ON sandbox_checkpoints;+ CREATE TRIGGER sandbox_checkpoints_set_updated_at+ BEFORE UPDATE ON sandbox_checkpoints+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+ END IF;+END $$;++-- ── org_subscription_items ────────────────────────────────────────────+-- No created_at on this table — backfill existing rows to now() so they+-- get a sensible historical watermark. Subsequent UPDATEs flow through+-- the trigger.+DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'org_subscription_items') THEN+ ALTER TABLE org_subscription_items ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ;+ UPDATE org_subscription_items SET updated_at = now() WHERE updated_at IS NULL;+ ALTER TABLE org_subscription_items ALTER COLUMN updated_at SET NOT NULL;+ ALTER TABLE org_subscription_items ALTER COLUMN updated_at SET DEFAULT now();+ DROP TRIGGER IF EXISTS org_subscription_items_set_updated_at ON org_subscription_items;+ CREATE TRIGGER org_subscription_items_set_updated_at+ BEFORE UPDATE ON org_subscription_items+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+ END IF;+END $$;diff --git a/internal/db/migrations/040_credit_halt.down.sql b/internal/db/migrations/041_credit_halt.down.sqlsimilarity index 100%rename from internal/db/migrations/040_credit_halt.down.sqlrename to internal/db/migrations/041_credit_halt.down.sqldiff --git a/internal/db/migrations/040_credit_halt.up.sql b/internal/db/migrations/041_credit_halt.up.sqlsimilarity index 100%rename from internal/db/migrations/040_credit_halt.up.sqlrename to internal/db/migrations/041_credit_halt.up.sqldiff --git a/internal/db/migrations/041_strip_global_concerns.down.sql b/internal/db/migrations/041_strip_global_concerns.down.sqldeleted file mode 100644index 3484321c..00000000--- a/internal/db/migrations/041_strip_global_concerns.down.sql+++ /dev/null@@ -1,137 +0,0 @@--- Down migration for 041_strip_global_concerns.------ This is a one-way cutover in practice: D1 is the source of truth post-041,--- so even if we recreate the table SHAPES here, there's no path to recreate--- the DATA (it never existed in PG once D1 took over). We recreate schema for--- the rare case of forensic comparison against a pre-cutover dump.------ FK constraints on cell-local tables that referenced these globals are--- NOT restored here — the columns survived as plain UUIDs and re-adding the--- FKs would 23503-fail on every row.--BEGIN;--CREATE TABLE IF NOT EXISTS orgs (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- name TEXT NOT NULL,- slug TEXT NOT NULL UNIQUE,- plan TEXT NOT NULL DEFAULT 'free',- max_concurrent_sandboxes INT NOT NULL DEFAULT 5,- max_sandbox_timeout_sec INT NOT NULL DEFAULT 3600,- workos_org_id TEXT UNIQUE,- is_personal BOOLEAN NOT NULL DEFAULT false,- owner_user_id UUID,- credit_balance_cents INT NOT NULL DEFAULT 3000,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()-);--CREATE TABLE IF NOT EXISTS users (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- org_id UUID NOT NULL,- email TEXT NOT NULL UNIQUE,- name TEXT,- role TEXT NOT NULL DEFAULT 'member',- workos_user_id TEXT UNIQUE,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()-);--CREATE TABLE IF NOT EXISTS api_keys (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- org_id UUID NOT NULL,- created_by UUID,- key_hash TEXT NOT NULL UNIQUE,- key_prefix TEXT NOT NULL,- name TEXT NOT NULL,- scopes TEXT[] NOT NULL DEFAULT '{sandbox:*}',- last_used TIMESTAMPTZ,- expires_at TIMESTAMPTZ,- created_at TIMESTAMPTZ NOT NULL DEFAULT now()-);-CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);--CREATE TABLE IF NOT EXISTS user_sessions (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL,- access_token TEXT NOT NULL UNIQUE,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- expires_at TIMESTAMPTZ NOT NULL DEFAULT now() + INTERVAL '7 days'-);-CREATE INDEX IF NOT EXISTS idx_user_sessions_token ON user_sessions(access_token);-CREATE INDEX IF NOT EXISTS idx_user_sessions_user ON user_sessions(user_id);--CREATE TABLE IF NOT EXISTS templates (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- org_id UUID,- name TEXT NOT NULL,- tag TEXT NOT NULL DEFAULT 'latest',- template_type TEXT NOT NULL DEFAULT 'dockerfile',- image_ref TEXT,- rootfs_s3_key TEXT,- workspace_s3_key TEXT,- dockerfile TEXT,- is_public BOOLEAN NOT NULL DEFAULT false,- status TEXT NOT NULL DEFAULT 'ready',- created_by_sandbox_id TEXT,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- UNIQUE(org_id, name, tag)-);--CREATE TABLE IF NOT EXISTS secret_stores (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- org_id UUID NOT NULL,- name TEXT NOT NULL,- egress_allowlist TEXT[] NOT NULL DEFAULT '{}',- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),- UNIQUE(org_id, name)-);-CREATE INDEX IF NOT EXISTS idx_secret_stores_org ON secret_stores(org_id);--CREATE TABLE IF NOT EXISTS secret_store_entries (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- store_id UUID NOT NULL,- name TEXT NOT NULL,- encrypted_value BYTEA NOT NULL,- allowed_hosts TEXT[] NOT NULL DEFAULT '{}',- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),- UNIQUE(store_id, name)-);-CREATE INDEX IF NOT EXISTS idx_secret_store_entries_store ON secret_store_entries(store_id);--CREATE TABLE IF NOT EXISTS usage_snapshots (- org_id UUID NOT NULL,- snapshot_ts TIMESTAMPTZ NOT NULL,- cpu_seconds INT NOT NULL,- wall_seconds INT NOT NULL,- memory_gb_seconds DOUBLE PRECISION NOT NULL,- sandbox_count INT NOT NULL,- cost_cents INT NOT NULL,- reported_to_stripe BOOLEAN NOT NULL DEFAULT false,- PRIMARY KEY (org_id, snapshot_ts)-);--CREATE TABLE IF NOT EXISTS org_subscription_items (- org_id UUID NOT NULL,- tier TEXT NOT NULL,- stripe_item_id TEXT NOT NULL,- price_id TEXT NOT NULL,- PRIMARY KEY (org_id, tier)-);--CREATE TABLE IF NOT EXISTS agent_subscriptions (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- org_id UUID NOT NULL,- agent_id TEXT NOT NULL,- feature TEXT NOT NULL,- stripe_customer_id TEXT NOT NULL,- stripe_subscription_id TEXT NOT NULL,- stripe_price_id TEXT NOT NULL,- status TEXT NOT NULL,- current_period_end TIMESTAMPTZ,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()-);--COMMIT;diff --git a/internal/db/migrations/041_strip_global_concerns.up.sql b/internal/db/migrations/041_strip_global_concerns.up.sqldeleted file mode 100644index d467ad39..00000000--- a/internal/db/migrations/041_strip_global_concerns.up.sql+++ /dev/null@@ -1,37 +0,0 @@--- Strip global concerns from per-cell PG. Identity (orgs/users/api_keys),--- templates, and secret stores now live in D1 (the edge layer). The CP is a--- stateless executor: it receives a capability token with org_id + plan, and--- fetches templates + secret-store entries via HMAC'd /internal/* endpoints--- on the edge at sandbox-create time.------ This migration drops:--- - Identity: orgs, users, api_keys, user_sessions--- - Templates: templates--- - Secrets: secret_stores, secret_store_entries--- - Stripe: org_subscription_items, usage_snapshots (D1 owns these now)--- - Agents: agent_subscriptions (depends on orgs)------ Tables that survive (cell-local concerns):--- - sandbox_sessions, sandbox_checkpoints, image_cache, preview_urls,--- workers, snapshots, image_patches, migration_state, …------ FK constraints from cell-local tables that pointed at the global tables--- are auto-dropped by `DROP TABLE ... CASCADE` — the org_id/user_id columns--- themselves are preserved as free-text UUID tags (no longer enforced).--BEGIN;---- Wipe local copies of global tables. CASCADE drops dependent FK constraints--- on cell-local tables without dropping their columns.-DROP TABLE IF EXISTS user_sessions CASCADE;-DROP TABLE IF EXISTS api_keys CASCADE;-DROP TABLE IF EXISTS agent_subscriptions CASCADE;-DROP TABLE IF EXISTS secret_store_entries CASCADE;-DROP TABLE IF EXISTS secret_stores CASCADE;-DROP TABLE IF EXISTS templates CASCADE;-DROP TABLE IF EXISTS org_subscription_items CASCADE;-DROP TABLE IF EXISTS usage_snapshots CASCADE;-DROP TABLE IF EXISTS users CASCADE;-DROP TABLE IF EXISTS orgs CASCADE;--COMMIT;diff --git a/internal/db/store.go b/internal/db/store.goindex ee7a9871..00bf45db 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -137,8 +137,8 @@ func (s *Store) Migrate(ctx context.Context) error {{37, "migrations/037_agent_subscriptions.up.sql"},{38, "migrations/038_hibernation_upload_status.up.sql"},{39, "migrations/039_checkpoint_failure_detail.up.sql"},- {40, "migrations/040_credit_halt.up.sql"},- {41, "migrations/041_strip_global_concerns.up.sql"},+ {40, "migrations/040_add_updated_at.up.sql"},+ {41, "migrations/041_credit_halt.up.sql"},}for _, m := range migrations {diff --git a/seed-dev-secrets b/seed-dev-secretsnew file mode 100755index 00000000..5d8e5c0dBinary files /dev/null and b/seed-dev-secrets differ