From 8109162b97683d8062f8d3ef3c24cb6044dfecbd Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 07:59:59 -0500 Subject: [PATCH 01/20] Apply the coordinator schema as goose migrations Replace the boot-time DDL loop in PostgresStore.migrate with pressly/goose v3. Version 1 is the 255 statements the loop ran, unchanged and in order, outside a transaction. Versions 2 to 5 are the retired-backfill guard and the three concurrent index builds, with their code unchanged. Goose records each version in goose_db_version and holds a session advisory lock, so a second coordinator applies nothing. The migration session sets lock_timeout 3s and statement_timeout 10min, and migrate retries a lock timeout up to three times. Check in the pg_dump of the pre-goose schema as coordinator/store/schema/schema.sql. Tests prove that goose builds that schema on a fresh database, leaves a legacy database unchanged apart from goose_db_version, applies once under two concurrent runners, and retries a lock timeout. goose v3.28.0 needs Go 1.26 and the coordinator image builds with Go 1.25, so this pins v3.27.3 and raises the go directive to 1.25.7. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + CONTRIBUTING.md | 2 +- coordinator/store/app_attest_archive.go | 17 - .../store/app_attest_builds_postgres.go | 5 - coordinator/store/app_attest_enrollment.go | 2 - coordinator/store/app_attest_readiness.go | 5 - coordinator/store/app_attest_receipts.go | 18 - coordinator/store/app_attest_rotation.go | 8 - coordinator/store/app_attest_shadow.go | 6 - .../store/cacheroutingstate_postgres.go | 63 - coordinator/store/cacheroutingstate_test.go | 10 +- coordinator/store/global_payouts_postgres.go | 17 - coordinator/store/machine_inventory_schema.go | 37 - coordinator/store/migration_harness_test.go | 207 + .../store/migrations/request_waterfall.sql | 4 +- coordinator/store/model_demand_migration.go | 54 - coordinator/store/model_price_test.go | 12 +- .../store/model_token_promotions_schema.go | 40 - coordinator/store/postgres.go | 1336 +------ coordinator/store/postgres_autopilot.go | 5 - .../store/postgres_billing_columns_test.go | 1 + .../store/postgres_log_report_privacy.go | 36 - .../store/postgres_log_report_privacy_test.go | 31 +- coordinator/store/postgres_migrations.go | 155 + coordinator/store/postgres_migrations_test.go | 186 + coordinator/store/postgres_model_demand.go | 12 - .../store/postgres_request_outcomes.go | 12 - .../store/postgres_retired_backfills_test.go | 10 +- coordinator/store/postgres_test.go | 6 +- .../profile_prediction_migration_test.go | 4 +- coordinator/store/profile_records_test.go | 11 +- .../store/provider_earnings_startup_test.go | 14 +- .../provider_earnings_window_index_test.go | 11 +- .../store/provider_trust_reuse_test.go | 8 +- coordinator/store/route_telemetry_test.go | 33 +- .../schema/migrations/00001_baseline.sql | 1838 +++++++++ coordinator/store/schema/schema.sql | 3340 +++++++++++++++++ .../verification_scheduler_store_test.go | 8 +- docs/README.md | 3 +- docs/architecture/request-accounting.md | 4 +- docs/architecture/storage.md | 119 +- docs/architecture/system-profiler.md | 6 +- docs/developer/build.md | 4 +- docs/developer/database-migrations.md | 78 + docs/operations/coordinator-deploy.md | 56 +- docs/reference/app-attest-shadow.md | 4 +- go.mod | 40 +- go.sum | 88 +- mise.toml | 4 +- 49 files changed, 6112 insertions(+), 1863 deletions(-) delete mode 100644 coordinator/store/machine_inventory_schema.go create mode 100644 coordinator/store/migration_harness_test.go delete mode 100644 coordinator/store/model_demand_migration.go delete mode 100644 coordinator/store/model_token_promotions_schema.go delete mode 100644 coordinator/store/postgres_log_report_privacy.go create mode 100644 coordinator/store/postgres_migrations.go create mode 100644 coordinator/store/postgres_migrations_test.go create mode 100644 coordinator/store/schema/migrations/00001_baseline.sql create mode 100644 coordinator/store/schema/schema.sql create mode 100644 docs/developer/database-migrations.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e454778e1..b0d0f40f4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## Unreleased — coordinator schema migrations + +- Apply the coordinator's Postgres schema as numbered goose migrations instead of re-running every DDL statement at each boot. The first boot records the existing schema as version 1 without changing it; later boots apply only new versions. Migration statements stop waiting for a lock after 3 seconds and retry up to three times, and coordinators that start together take turns on an advisory lock. +- Check in the schema as `coordinator/store/schema/schema.sql` and test that the migrations build exactly that schema. New schema changes go in a new numbered migration file. + ## Unreleased — leaderboard availability - Add a concurrent BRIN time index for recent provider-earnings rankings, enable range autosummarization, and keep planner statistics current. Return an uncached 503 when ranking queries fail instead of showing and caching an empty leaderboard. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 31da218386..70403e6d29 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,7 +39,7 @@ The full map is [`docs/architecture/overview.md`](docs/architecture/overview.md) ### Prerequisites - macOS on Apple Silicon for anything under `provider-swift/`; the coordinator, sidecar, e2e suite, and UIs build on macOS or Linux. -- Toolchains are pinned in [`mise.toml`](mise.toml) and installed with `mise install`: Go `1.25.0`, Rust `1.88.0`, Node `22`, Swift `6.3`, Python `3.12`, plus `jq`, `gh`, `awscli`, `gcloud`. Xcode Command Line Tools and `cmake` are needed for the provider's metallib. +- Toolchains are pinned in [`mise.toml`](mise.toml) and installed with `mise install`: Go `1.25.7`, Rust `1.88.0`, Node `22`, Swift `6.3`, Python `3.12`, plus `jq`, `gh`, `awscli`, `gcloud`. Xcode Command Line Tools and `cmake` are needed for the provider's metallib. - A working `git` config with `user.name` and `user.email`. ### First-time clone diff --git a/coordinator/store/app_attest_archive.go b/coordinator/store/app_attest_archive.go index ab42413074..e020bd67ac 100644 --- a/coordinator/store/app_attest_archive.go +++ b/coordinator/store/app_attest_archive.go @@ -51,20 +51,3 @@ type AppAttestDecision struct { KeyID string Owner string } - -const appAttestArchiveDDL = ` -CREATE TABLE IF NOT EXISTS app_attest_evidence ( - id TEXT PRIMARY KEY, session_id TEXT NOT NULL, key_id TEXT NOT NULL, received_at TIMESTAMPTZ NOT NULL, - action TEXT NOT NULL, sha256 TEXT NOT NULL, context JSONB NOT NULL, - outcome TEXT NOT NULL DEFAULT 'pending', details JSONB NOT NULL DEFAULT '{}', completed_at TIMESTAMPTZ -); -CREATE INDEX IF NOT EXISTS app_attest_evidence_session ON app_attest_evidence(session_id,received_at DESC); -CREATE INDEX IF NOT EXISTS app_attest_evidence_key ON app_attest_evidence(key_id,received_at DESC); -CREATE INDEX IF NOT EXISTS app_attest_evidence_time ON app_attest_evidence(received_at DESC); -CREATE INDEX IF NOT EXISTS app_attest_evidence_pending ON app_attest_evidence(received_at) WHERE outcome='pending'; -CREATE TABLE IF NOT EXISTS app_attest_evidence_blobs ( - evidence_id TEXT PRIMARY KEY REFERENCES app_attest_evidence(id), - proof_field TEXT NOT NULL, proof BYTEA NOT NULL -); -REVOKE ALL ON app_attest_evidence_blobs FROM PUBLIC; -` diff --git a/coordinator/store/app_attest_builds_postgres.go b/coordinator/store/app_attest_builds_postgres.go index 668563527f..9c8f8b92cf 100644 --- a/coordinator/store/app_attest_builds_postgres.go +++ b/coordinator/store/app_attest_builds_postgres.go @@ -9,11 +9,6 @@ import ( "github.com/jackc/pgx/v5" ) -const appAttestBuildDDL = `CREATE TABLE IF NOT EXISTS app_attest_build_qualifications ( - binary_hash TEXT PRIMARY KEY CHECK (binary_hash ~ '^[0-9a-f]{64}$'), - record JSONB NOT NULL -)` - func (s *PostgresStore) ListAppAttestBuildQualifications(ctx context.Context) ([]AppAttestBuildQualification, error) { rows, err := s.pool.Query(ctx, `SELECT record FROM app_attest_build_qualifications`) if err != nil { diff --git a/coordinator/store/app_attest_enrollment.go b/coordinator/store/app_attest_enrollment.go index c381f1f8cf..7983898153 100644 --- a/coordinator/store/app_attest_enrollment.go +++ b/coordinator/store/app_attest_enrollment.go @@ -27,8 +27,6 @@ type AppAttestEnrollmentStore interface { GetAppAttestEnrollment(context.Context, string) (*AppAttestEnrollment, error) } -const appAttestEnrollmentDDL = `CREATE TABLE IF NOT EXISTS app_attest_enrollments (id TEXT PRIMARY KEY,owner TEXT NOT NULL,key_id TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL,context JSONB NOT NULL)` - func (s *PostgresStore) SaveAppAttestEnrollment(ctx context.Context, e AppAttestEnrollment) error { raw, err := json.Marshal(e) if err != nil { diff --git a/coordinator/store/app_attest_readiness.go b/coordinator/store/app_attest_readiness.go index 9dd6f395ad..df58fa56b7 100644 --- a/coordinator/store/app_attest_readiness.go +++ b/coordinator/store/app_attest_readiness.go @@ -17,11 +17,6 @@ type AppAttestReadinessStore interface { RevokeAppAttestKey(context.Context, string, string, string) (bool, error) } -const appAttestRevocationDDL = `CREATE TABLE IF NOT EXISTS app_attest_key_revocations ( - key_id TEXT PRIMARY KEY REFERENCES app_attest_shadow_keys(key_id), - account_id TEXT NOT NULL, reason TEXT NOT NULL, revoked_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -)` - func (s *PostgresStore) GetAppAttestReadiness(ctx context.Context, key string) (AppAttestReadiness, error) { var result AppAttestReadiness // Read revocation and receipt in one snapshot. A failed query is unknown, diff --git a/coordinator/store/app_attest_receipts.go b/coordinator/store/app_attest_receipts.go index 9282387369..35cde1441b 100644 --- a/coordinator/store/app_attest_receipts.go +++ b/coordinator/store/app_attest_receipts.go @@ -26,21 +26,3 @@ type AppAttestReceiptStore interface { ClaimAppAttestReceipt(context.Context, time.Time) (*AppAttestReceipt, error) SaveAppAttestReceiptRefresh(context.Context, AppAttestReceipt) error } - -const appAttestReceiptDDL = ` -CREATE TABLE IF NOT EXISTS app_attest_receipts ( - id TEXT PRIMARY KEY,key_id TEXT NOT NULL,evidence_id TEXT NOT NULL,parent_id TEXT NOT NULL, - received_at TIMESTAMPTZ NOT NULL,outcome TEXT NOT NULL,http_status INTEGER NOT NULL, - details JSONB NOT NULL,context JSONB NOT NULL,next_at TIMESTAMPTZ NOT NULL,expires_at TIMESTAMPTZ NOT NULL -); -CREATE INDEX IF NOT EXISTS app_attest_receipts_key ON app_attest_receipts(key_id,received_at DESC); -CREATE INDEX IF NOT EXISTS app_attest_receipts_recovery ON app_attest_receipts(key_id,received_at DESC) WHERE outcome='receipt_creation_time'; -CREATE TABLE IF NOT EXISTS app_attest_receipt_blobs ( - receipt_id TEXT PRIMARY KEY REFERENCES app_attest_receipts(id),body BYTEA NOT NULL,response_body BYTEA NOT NULL -); -REVOKE ALL ON app_attest_receipt_blobs FROM PUBLIC; -CREATE TABLE IF NOT EXISTS app_attest_receipt_jobs ( - key_id TEXT PRIMARY KEY,receipt_id TEXT NOT NULL REFERENCES app_attest_receipts(id),next_at TIMESTAMPTZ NOT NULL, - lease_until TIMESTAMPTZ,attempts BIGINT NOT NULL DEFAULT 0 -); -` diff --git a/coordinator/store/app_attest_rotation.go b/coordinator/store/app_attest_rotation.go index 7e8d6cef62..f5f24c5311 100644 --- a/coordinator/store/app_attest_rotation.go +++ b/coordinator/store/app_attest_rotation.go @@ -59,14 +59,6 @@ type AppAttestRotationLimit struct { // against small thresholds, so an exact count is never needed. const AppAttestRotationCountCap = 100 -const appAttestKeyRotationDDL = ` -CREATE TABLE IF NOT EXISTS app_attest_key_rotations ( - key_id TEXT PRIMARY KEY, machine_id TEXT NOT NULL, account_id TEXT NOT NULL, - requested_at TIMESTAMPTZ NOT NULL, failures INTEGER NOT NULL, reason TEXT NOT NULL -); -CREATE INDEX IF NOT EXISTS app_attest_key_rotations_machine ON app_attest_key_rotations(machine_id,requested_at DESC); -` - // appAttestRotationFailureContext mirrors the archived evidence context // fields used by the memory backend; PostgreSQL evaluates the same rule. type appAttestRotationFailureContext struct { diff --git a/coordinator/store/app_attest_shadow.go b/coordinator/store/app_attest_shadow.go index 6df4f8f706..be5d5362f3 100644 --- a/coordinator/store/app_attest_shadow.go +++ b/coordinator/store/app_attest_shadow.go @@ -31,12 +31,6 @@ type AppAttestShadowKey struct { UpdatedAt time.Time `json:"-"` } -const appAttestShadowDDL = `CREATE TABLE IF NOT EXISTS app_attest_shadow_keys ( - key_id TEXT PRIMARY KEY, owner TEXT NOT NULL, evidence JSONB NOT NULL, - counter BIGINT NOT NULL DEFAULT 0 CHECK (counter >= 0 AND counter <= 4294967295), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -)` - func cloneAppAttestKey(k AppAttestShadowKey) *AppAttestShadowKey { k.PublicKey = bytes.Clone(k.PublicKey) if k.ValidationCategory != nil { diff --git a/coordinator/store/cacheroutingstate_postgres.go b/coordinator/store/cacheroutingstate_postgres.go index 90c1032297..171e91390b 100644 --- a/coordinator/store/cacheroutingstate_postgres.go +++ b/coordinator/store/cacheroutingstate_postgres.go @@ -12,69 +12,6 @@ import ( crs "github.com/eigeninference/d-inference/coordinator/store/cacheroutingstate" ) -// cacheRoutingHoldersDDL and cacheRoutingDemandDDL are the durable copies of -// the registry's in-memory holder and demand indexes (see -// cacheroutingstate/records.go). Keys are HMACs under the route key; the -// provider-confirmed chain hash is not stored (cacheRoutingHoldersDropChainHashDDL -// removes the column earlier builds of this branch created), and no prompt -// content is. The primary key is (key, cache_epoch): a holder key names a -// boundary, an epoch names one provider's SSD root, and a boundary is held by -// at most the configured number of providers. -const cacheRoutingHoldersDDL = `CREATE TABLE IF NOT EXISTS cache_routing_holders ( - key TEXT NOT NULL, - cache_epoch TEXT NOT NULL, - tier TEXT NOT NULL DEFAULT '', - model_id TEXT NOT NULL, - model_aggregate_hash TEXT NOT NULL DEFAULT '', - prompt_contract_id TEXT NOT NULL DEFAULT '', - block_hash_version TEXT NOT NULL DEFAULT '', - ready_boundary_mode TEXT NOT NULL DEFAULT '', - anchor_token_count INTEGER NOT NULL DEFAULT 0, - required_recompute_tokens INTEGER NOT NULL DEFAULT 0, - stage_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - measured_stage_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - measured_expires_at TIMESTAMPTZ, - updated_at TIMESTAMPTZ NOT NULL, - expires_at TIMESTAMPTZ NOT NULL, - PRIMARY KEY (key, cache_epoch) -)` - -// The chain hash column of earlier builds is dropped, and its values with it. -const cacheRoutingHoldersDropChainHashDDL = `ALTER TABLE cache_routing_holders DROP COLUMN IF EXISTS anchor_chain_hash` - -// Tables created by earlier builds of this branch pick up the columns added -// since; each ADD is a no-op once present. -const cacheRoutingHoldersBackfillColumnsDDL = `ALTER TABLE cache_routing_holders - ADD COLUMN IF NOT EXISTS measured_stage_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - ADD COLUMN IF NOT EXISTS measured_expires_at TIMESTAMPTZ, - ADD COLUMN IF NOT EXISTS ready_boundary_mode TEXT NOT NULL DEFAULT ''` - -// The prune deletes rows whose effective expiry under the active TTL has -// passed, written as `expires_at <= now OR updated_at <= now - ttl` so both -// halves are index-served (a bitmap OR over the two indexes) instead of a -// full scan every five minutes; a boot-time load orders by the clamped -// expression and scans the table once. -const cacheRoutingHoldersExpiryIndexDDL = `CREATE INDEX IF NOT EXISTS idx_cache_routing_holders_expires ON cache_routing_holders(expires_at)` - -const cacheRoutingHoldersUpdatedIndexDDL = `CREATE INDEX IF NOT EXISTS idx_cache_routing_holders_updated ON cache_routing_holders(updated_at)` - -const cacheRoutingDemandDDL = `CREATE TABLE IF NOT EXISTS cache_routing_demand ( - key TEXT PRIMARY KEY, - seen_at TIMESTAMPTZ NOT NULL -)` - -const cacheRoutingDemandSeenIndexDDL = `CREATE INDEX IF NOT EXISTS idx_cache_routing_demand_seen ON cache_routing_demand(seen_at)` - -// cacheRoutingMetaDDL records the derived cache-key generation the rows were -// written under (a non-secret fingerprint), so a change of generation (a -// master-key rotation, a bumped derivation version) resets the tables instead -// of restoring rows no request can ever match. -const cacheRoutingMetaDDL = `CREATE TABLE IF NOT EXISTS cache_routing_meta ( - name TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at TIMESTAMPTZ NOT NULL DEFAULT now() -)` - const cacheRoutingKeyFingerprintName = "key_fingerprint" const cacheHolderInsertColumns = 15 diff --git a/coordinator/store/cacheroutingstate_test.go b/coordinator/store/cacheroutingstate_test.go index b7e14b55e3..16658c63bb 100644 --- a/coordinator/store/cacheroutingstate_test.go +++ b/coordinator/store/cacheroutingstate_test.go @@ -325,7 +325,7 @@ func TestCacheRoutingStateRejectsInvalidRecords(t *testing.T) { // The durable copy never holds the provider-confirmed chain hash: a boundary // is named by its keyed identifier and token count only, and the column an -// earlier build of this branch created is dropped by the schema loop. +// earlier build of this branch created is dropped by the baseline. func TestCacheRoutingHoldersTableStoresNoChainHash(t *testing.T) { for name, s := range cacheRoutingStateBackends(t) { pg, ok := As[*PostgresStore](s) @@ -343,17 +343,17 @@ func TestCacheRoutingHoldersTableStoresNoChainHash(t *testing.T) { return n } if count() != 0 { - t.Fatal("anchor_chain_hash exists after the schema loop") + t.Fatal("anchor_chain_hash exists after the migrations") } // A table an earlier build created carries the column; the - // schema loop's drop removes it, and its values with it. + // baseline's drop removes it, and its values with it. if _, err := pg.pool.Exec(ctx, `ALTER TABLE cache_routing_holders ADD COLUMN IF NOT EXISTS anchor_chain_hash TEXT NOT NULL DEFAULT ''`); err != nil { t.Fatal(err) } if count() != 1 { t.Fatal("fixture column missing") } - if _, err := pg.pool.Exec(ctx, cacheRoutingHoldersDropChainHashDDL); err != nil { + if _, err := pg.pool.Exec(ctx, baselineStatement(t, "ALTER TABLE cache_routing_holders DROP COLUMN IF EXISTS anchor_chain_hash")); err != nil { t.Fatalf("drop migration: %v", err) } if count() != 0 { @@ -364,7 +364,7 @@ func TestCacheRoutingHoldersTableStoresNoChainHash(t *testing.T) { if _, err := pg.pool.Exec(ctx, `ALTER TABLE cache_routing_holders DROP COLUMN IF EXISTS ready_boundary_mode`); err != nil { t.Fatal(err) } - if _, err := pg.pool.Exec(ctx, cacheRoutingHoldersBackfillColumnsDDL); err != nil { + if _, err := pg.pool.Exec(ctx, baselineStatement(t, "ALTER TABLE cache_routing_holders\n ADD COLUMN IF NOT EXISTS measured_stage_ms")); err != nil { t.Fatalf("backfill migration: %v", err) } var n int diff --git a/coordinator/store/global_payouts_postgres.go b/coordinator/store/global_payouts_postgres.go index c8a7e6c9d0..c04e4eafa4 100644 --- a/coordinator/store/global_payouts_postgres.go +++ b/coordinator/store/global_payouts_postgres.go @@ -11,23 +11,6 @@ import ( var _ GlobalPayoutStore = (*PostgresStore)(nil) -const globalPayoutSchema = ` -CREATE TABLE IF NOT EXISTS global_payout_recipients ( - account_id TEXT PRIMARY KEY, country TEXT NOT NULL, data JSONB NOT NULL -); -CREATE TABLE IF NOT EXISTS global_payout_withdrawals ( - id TEXT PRIMARY KEY, account_id TEXT NOT NULL, status TEXT NOT NULL, - external_id TEXT NOT NULL DEFAULT '', submitted_at TIMESTAMPTZ NOT NULL, - checked_at TIMESTAMPTZ NOT NULL, lease_until TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, data JSONB NOT NULL -); -ALTER TABLE global_payout_withdrawals ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ NOT NULL DEFAULT 'infinity'; -UPDATE global_payout_withdrawals SET expires_at=(data->>'expires_at')::timestamptz WHERE status='quoted' AND expires_at='infinity'; -CREATE INDEX IF NOT EXISTS global_payout_quote_expiry ON global_payout_withdrawals(expires_at) WHERE status='quoted'; -CREATE UNIQUE INDEX IF NOT EXISTS global_payout_external_id ON global_payout_withdrawals(external_id) WHERE external_id <> ''; -CREATE INDEX IF NOT EXISTS global_payout_account ON global_payout_withdrawals(account_id, submitted_at DESC); -CREATE INDEX IF NOT EXISTS global_payout_reconcile ON global_payout_withdrawals(checked_at) WHERE status IN ('pending','processing','posted'); -` - func payoutContext() (context.Context, context.CancelFunc) { return context.WithTimeout(context.Background(), 5*time.Second) } diff --git a/coordinator/store/machine_inventory_schema.go b/coordinator/store/machine_inventory_schema.go deleted file mode 100644 index f5eee2f58f..0000000000 --- a/coordinator/store/machine_inventory_schema.go +++ /dev/null @@ -1,37 +0,0 @@ -package store - -const machineInventoryDDL = ` -CREATE TABLE IF NOT EXISTS darkbloom_machines ( - id TEXT PRIMARY KEY, assurance TEXT NOT NULL, merged_into TEXT REFERENCES darkbloom_machines(id), - first_seen TIMESTAMPTZ NOT NULL, last_seen TIMESTAMPTZ NOT NULL -); -CREATE INDEX IF NOT EXISTS darkbloom_machines_merged_into ON darkbloom_machines(merged_into) WHERE merged_into IS NOT NULL; -CREATE TABLE IF NOT EXISTS darkbloom_machine_aliases ( - kind TEXT NOT NULL, scope TEXT NOT NULL, digest TEXT NOT NULL, - machine_id TEXT NOT NULL REFERENCES darkbloom_machines(id), verified_at TIMESTAMPTZ NOT NULL, - PRIMARY KEY(kind,scope,digest) -); -CREATE TABLE IF NOT EXISTS darkbloom_machine_sessions ( - session_id TEXT PRIMARY KEY, machine_id TEXT NOT NULL REFERENCES darkbloom_machines(id), - original_machine_id TEXT NOT NULL REFERENCES darkbloom_machines(id), account_id TEXT NOT NULL, - first_seen TIMESTAMPTZ NOT NULL, last_seen TIMESTAMPTZ NOT NULL, disconnected_at TIMESTAMPTZ, - observation JSONB NOT NULL -); -CREATE INDEX IF NOT EXISTS darkbloom_machine_sessions_seen ON darkbloom_machine_sessions(last_seen DESC); -CREATE INDEX IF NOT EXISTS darkbloom_machine_sessions_open ON darkbloom_machine_sessions(last_seen,session_id) WHERE disconnected_at IS NULL; -CREATE INDEX IF NOT EXISTS darkbloom_machine_sessions_machine ON darkbloom_machine_sessions(machine_id,last_seen DESC); -CREATE TABLE IF NOT EXISTS darkbloom_machine_merges ( - source_id TEXT PRIMARY KEY REFERENCES darkbloom_machines(id), target_id TEXT NOT NULL REFERENCES darkbloom_machines(id), - session_id TEXT NOT NULL, merged_at TIMESTAMPTZ NOT NULL, reason TEXT NOT NULL -); -CREATE TABLE IF NOT EXISTS darkbloom_machine_observations ( - session_id TEXT NOT NULL, observed_at TIMESTAMPTZ NOT NULL, observation JSONB NOT NULL, - PRIMARY KEY(session_id,observed_at) -); -CREATE TABLE IF NOT EXISTS app_attest_shadow_events ( - id TEXT PRIMARY KEY, session_id TEXT NOT NULL, observed_at TIMESTAMPTZ NOT NULL, - stage TEXT NOT NULL, outcome TEXT NOT NULL, fields JSONB NOT NULL -); -CREATE INDEX IF NOT EXISTS app_attest_shadow_events_session ON app_attest_shadow_events(session_id,observed_at DESC); -CREATE INDEX IF NOT EXISTS app_attest_shadow_events_time ON app_attest_shadow_events(observed_at DESC); -` diff --git a/coordinator/store/migration_harness_test.go b/coordinator/store/migration_harness_test.go new file mode 100644 index 0000000000..bad7c0fbc6 --- /dev/null +++ b/coordinator/store/migration_harness_test.go @@ -0,0 +1,207 @@ +package store + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + "github.com/pressly/goose/v3/lock" +) + +// baselineStatements returns the statement blocks of the goose baseline in +// file order. +func baselineStatements(t testing.TB) []string { + t.Helper() + b, err := migrationFiles.ReadFile(migrationDir + "/00001_baseline.sql") + if err != nil { + t.Fatalf("read baseline: %v", err) + } + var out []string + for _, block := range strings.Split(string(b), "-- +goose StatementBegin\n")[1:] { + end := strings.Index(block, "\n-- +goose StatementEnd") + if end < 0 { + t.Fatalf("baseline block without StatementEnd: %.80s", block) + } + out = append(out, block[:end]) + } + return out +} + +// baselineStatement returns the one baseline statement that contains text. +func baselineStatement(t testing.TB, text string) string { + t.Helper() + var found []string + for _, stmt := range baselineStatements(t) { + if strings.Contains(stmt, text) { + found = append(found, stmt) + } + } + if len(found) != 1 { + t.Fatalf("%d baseline statements contain %q, want 1", len(found), text) + } + return found[0] +} + +// forgetMigrationVersions drops the goose version table, so the next +// migration run treats the database as one a pre-goose binary last migrated +// and applies every version again. It holds the goose advisory lock, so a +// migration run of another test package on the shared database is not cut in +// half. +func forgetMigrationVersions(t testing.TB, s *PostgresStore) { + t.Helper() + ctx := context.Background() + conn, err := s.pool.Acquire(ctx) + if err != nil { + t.Fatalf("acquire connection: %v", err) + } + defer conn.Release() + if _, err := conn.Exec(ctx, "SELECT pg_advisory_lock($1)", lock.DefaultLockID); err != nil { + t.Fatalf("take goose lock: %v", err) + } + defer func() { _, _ = conn.Exec(ctx, "SELECT pg_advisory_unlock($1)", lock.DefaultLockID) }() + if _, err := conn.Exec(ctx, "DROP TABLE IF EXISTS "+migrationVersionTable); err != nil { + t.Fatalf("drop %s: %v", migrationVersionTable, err) + } +} + +// replayMigrations runs every migration again on s, as the first goose boot +// does on a database that a pre-goose binary migrated. +func replayMigrations(t testing.TB, s *PostgresStore) { + t.Helper() + forgetMigrationVersions(t, s) + if err := s.migrate(context.Background()); err != nil { + t.Fatalf("replay migrations: %v", err) + } +} + +// loadSchemaFile applies schema/schema.sql (the pg_dump of the pre-goose +// schema) to the database at pool. The session settings at the top of the +// dump are skipped: some name settings older servers do not have, and the +// empty search_path would stay on the pooled connection. +func loadSchemaFile(t testing.TB, pool *pgxpool.Pool) { + t.Helper() + b, err := os.ReadFile(filepath.Join("schema", "schema.sql")) + if err != nil { + t.Fatalf("read schema file: %v", err) + } + var kept []string + for _, line := range strings.Split(string(b), "\n") { + if strings.HasPrefix(line, "SET ") || strings.HasPrefix(line, "SELECT pg_catalog.set_config(") { + continue + } + kept = append(kept, line) + } + if _, err := pool.Exec(context.Background(), strings.Join(kept, "\n")); err != nil { + t.Fatalf("load schema file: %v", err) + } +} + +// schemaSnapshotSQL describes every object in the current schema as sorted +// text lines: relations, columns in order, constraints, indexes, triggers, +// functions and sequences. Privileges and comments are left out, as in the +// checked-in dump. The goose version table is left out. +const schemaSnapshotSQL = ` +WITH ns AS (SELECT oid FROM pg_namespace WHERE nspname = current_schema()), +rel AS (SELECT c.* FROM pg_class c WHERE c.relnamespace = (SELECT oid FROM ns) + AND c.relname NOT LIKE 'goose_db_version%') +SELECT line FROM ( + SELECT format('relation %s kind=%s options=%s', relname, relkind, COALESCE(reloptions::text, '')) AS line + FROM rel + UNION ALL + SELECT format('column %s.%s position=%s type=%s not_null=%s default=%s identity=%s generated=%s', + c.relname, a.attname, + row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum), + format_type(a.atttypid, a.atttypmod), a.attnotnull, + COALESCE(pg_get_expr(d.adbin, d.adrelid), ''), a.attidentity, a.attgenerated) + FROM rel c + JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped + LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE c.relkind IN ('r', 'p', 'v', 'm') + UNION ALL + SELECT format('constraint %s %s %s', c.relname, con.conname, pg_get_constraintdef(con.oid)) + FROM pg_constraint con JOIN rel c ON c.oid = con.conrelid + UNION ALL + SELECT format('index %s valid=%s', pg_get_indexdef(i.indexrelid), i.indisvalid) + FROM pg_index i JOIN rel c ON c.oid = i.indexrelid + UNION ALL + SELECT 'trigger ' || pg_get_triggerdef(tg.oid) + FROM pg_trigger tg JOIN rel c ON c.oid = tg.tgrelid + WHERE NOT tg.tgisinternal + UNION ALL + SELECT 'function ' || pg_get_functiondef(p.oid) + FROM pg_proc p WHERE p.pronamespace = (SELECT oid FROM ns) + UNION ALL + SELECT format('sequence %s type=%s start=%s increment=%s min=%s max=%s cache=%s cycle=%s', + c.relname, format_type(s.seqtypid, NULL), s.seqstart, s.seqincrement, + s.seqmin, s.seqmax, s.seqcache, s.seqcycle) + FROM pg_sequence s JOIN rel c ON c.oid = s.seqrelid + UNION ALL + SELECT format('sequence-owner %s %s.%s', seq.relname, tab.relname, a.attname) + FROM pg_depend dep + JOIN rel seq ON seq.oid = dep.objid AND seq.relkind = 'S' + JOIN pg_class tab ON tab.oid = dep.refobjid + JOIN pg_attribute a ON a.attrelid = dep.refobjid AND a.attnum = dep.refobjsubid + WHERE dep.classid = 'pg_class'::regclass AND dep.deptype IN ('a', 'i') +) objects +ORDER BY line` + +func schemaSnapshot(t testing.TB, pool *pgxpool.Pool) []string { + t.Helper() + rows, err := pool.Query(context.Background(), schemaSnapshotSQL) + if err != nil { + t.Fatalf("snapshot schema: %v", err) + } + defer rows.Close() + var lines []string + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatalf("scan schema snapshot: %v", err) + } + lines = append(lines, line) + } + if err := rows.Err(); err != nil { + t.Fatalf("read schema snapshot: %v", err) + } + return lines +} + +// assertSameSchema fails with the lines only one snapshot has. +func assertSameSchema(t testing.TB, wantName string, want []string, gotName string, got []string) { + t.Helper() + count := map[string]int{} + for _, line := range want { + count[line]++ + } + for _, line := range got { + count[line]-- + } + var diff []string + for line, n := range count { + switch { + case n > 0: + diff = append(diff, "only in "+wantName+": "+line) + case n < 0: + diff = append(diff, "only in "+gotName+": "+line) + } + } + if len(diff) > 0 { + t.Fatalf("schemas differ (%d lines):\n%s", len(diff), strings.Join(diff, "\n")) + } + if len(want) == 0 { + t.Fatal("empty schema snapshot") + } +} + +func openTestPool(t testing.TB, databaseURL string) *pgxpool.Pool { + t.Helper() + pool, err := pgxpool.New(context.Background(), databaseURL) + if err != nil { + t.Fatalf("open pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} diff --git a/coordinator/store/migrations/request_waterfall.sql b/coordinator/store/migrations/request_waterfall.sql index d682a7000a..8d1dd18422 100644 --- a/coordinator/store/migrations/request_waterfall.sql +++ b/coordinator/store/migrations/request_waterfall.sql @@ -2,8 +2,8 @@ -- profiler's request_profiles row with the routing-telemetry inference_routes -- row on (request_id, attempt). Consumed by the admin UI / ad-hoc analysis. -- --- THIS VIEW IS NOT IN THE COORDINATOR'S BOOT MIGRATION SLICE (postgres.go --- migrate()). Like dedupe_provider_earnings.sql it is applied BY HAND with psql, +-- THIS VIEW IS NOT A COORDINATOR MIGRATION (coordinator/store/schema/migrations). +-- Like dedupe_provider_earnings.sql it is applied BY HAND with psql, -- out of band and off the deploy path: -- -- psql "$EIGENINFERENCE_DATABASE_URL" -f coordinator/store/migrations/request_waterfall.sql diff --git a/coordinator/store/model_demand_migration.go b/coordinator/store/model_demand_migration.go deleted file mode 100644 index 2ccae69b27..0000000000 --- a/coordinator/store/model_demand_migration.go +++ /dev/null @@ -1,54 +0,0 @@ -package store - -// One counter row per UTC hour, model and consumer keeps reads compact and -// applies old/new outcome deltas under a single row lock. Projection writers -// order batches by this key to avoid cross-model lock inversions. -const modelDemandHourlyDDL = `CREATE TABLE IF NOT EXISTS model_demand_hourly ( - hour TIMESTAMPTZ NOT NULL, - model TEXT NOT NULL, - consumer_hash TEXT NOT NULL, - requests BIGINT NOT NULL, - completed BIGINT NOT NULL, - capacity_rejected BIGINT NOT NULL, - latency_rejected BIGINT NOT NULL, - timed_out BIGINT NOT NULL, - failed BIGINT NOT NULL, - cancelled BIGINT NOT NULL, - unknown BIGINT NOT NULL, - excluded BIGINT NOT NULL, - http_429 BIGINT NOT NULL, - PRIMARY KEY(hour,model,consumer_hash) -)` - -const modelDemandRollupFunctionDDL = `CREATE OR REPLACE FUNCTION update_model_demand_hourly() RETURNS trigger AS $$ -BEGIN - IF TG_OP='UPDATE' AND OLD.outcome=NEW.outcome AND (OLD.http_status=429)=(NEW.http_status=429) THEN RETURN NEW; END IF; - INSERT INTO model_demand_hourly (hour,model,consumer_hash,requests,completed,capacity_rejected,latency_rejected,timed_out,failed,cancelled,unknown,excluded,http_429) - VALUES (date_trunc('hour',NEW.received_at,'UTC'),NEW.model,NEW.consumer_hash, - 1-CASE WHEN TG_OP='UPDATE' THEN 1 ELSE 0 END, - (NEW.outcome='completed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='completed')::integer ELSE 0 END, - (NEW.outcome='capacity_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='capacity_rejected')::integer ELSE 0 END, - (NEW.outcome='latency_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='latency_rejected')::integer ELSE 0 END, - (NEW.outcome='timed_out')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='timed_out')::integer ELSE 0 END, - (NEW.outcome='failed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='failed')::integer ELSE 0 END, - (NEW.outcome='cancelled')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='cancelled')::integer ELSE 0 END, - (NEW.outcome='unknown')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='unknown')::integer ELSE 0 END, - (NEW.outcome='excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='excluded')::integer ELSE 0 END, - (NEW.http_status=429 AND NEW.outcome<>'excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.http_status=429 AND OLD.outcome<>'excluded')::integer ELSE 0 END) - ON CONFLICT (hour,model,consumer_hash) DO UPDATE SET - requests=model_demand_hourly.requests+EXCLUDED.requests, - completed=model_demand_hourly.completed+EXCLUDED.completed, - capacity_rejected=model_demand_hourly.capacity_rejected+EXCLUDED.capacity_rejected, - latency_rejected=model_demand_hourly.latency_rejected+EXCLUDED.latency_rejected, - timed_out=model_demand_hourly.timed_out+EXCLUDED.timed_out, - failed=model_demand_hourly.failed+EXCLUDED.failed, - cancelled=model_demand_hourly.cancelled+EXCLUDED.cancelled, - unknown=model_demand_hourly.unknown+EXCLUDED.unknown, - excluded=model_demand_hourly.excluded+EXCLUDED.excluded, - http_429=model_demand_hourly.http_429+EXCLUDED.http_429; - RETURN NEW; -END; -$$ LANGUAGE plpgsql` - -const modelDemandRollupTriggerDDL = `CREATE OR REPLACE TRIGGER model_demand_rollup - AFTER INSERT OR UPDATE ON model_demand_requests FOR EACH ROW EXECUTE FUNCTION update_model_demand_hourly()` diff --git a/coordinator/store/model_price_test.go b/coordinator/store/model_price_test.go index d41aeb0952..971414967c 100644 --- a/coordinator/store/model_price_test.go +++ b/coordinator/store/model_price_test.go @@ -91,7 +91,7 @@ func TestPostgresModelPriceCacheTracksCacheRead(t *testing.T) { } // A model_prices table created before cache_read_price existed gains the -// column on the next migrate() with existing rows reading back as unset. +// column when the baseline replays, with existing rows reading back as unset. func TestPostgresModelPricesMigrationAddsCacheReadColumn(t *testing.T) { s := testPostgresStore(t) ctx := context.Background() @@ -103,9 +103,7 @@ func TestPostgresModelPricesMigrationAddsCacheReadColumn(t *testing.T) { "INSERT INTO model_prices (account_id, model, input_price, output_price) VALUES ('platform', $1, 50000, 200000)", model); err != nil { t.Fatalf("insert legacy row: %v", err) } - if err := s.migrate(ctx); err != nil { - t.Fatalf("migrate: %v", err) - } + replayMigrations(t, s) got, ok := s.GetModelPrice("platform", model) if !ok || got.InputPrice != 50_000 || got.OutputPrice != 200_000 || got.CacheReadPrice != nil { t.Fatalf("legacy row after migration = %+v ok=%v, want cache_read_price unset", got, ok) @@ -116,7 +114,7 @@ func TestPostgresModelPricesMigrationAddsCacheReadColumn(t *testing.T) { } // A usage table created before cached_tokens existed gains the column on the -// next migrate(); rows written before it read back as 0 cached tokens (they +// baseline replay; rows written before it read back as 0 cached tokens (they // were billed at the full input price) and new rows persist their count. func TestPostgresUsageMigrationAddsCachedTokensColumn(t *testing.T) { s := testPostgresStore(t) @@ -131,9 +129,7 @@ func TestPostgresUsageMigrationAddsCachedTokensColumn(t *testing.T) { hashKey(consumer), legacyReq); err != nil { t.Fatalf("insert legacy row: %v", err) } - if err := s.migrate(ctx); err != nil { - t.Fatalf("migrate: %v", err) - } + replayMigrations(t, s) s.RecordUsage(UsageRecord{ProviderID: "p", ConsumerKey: consumer, Model: "m", RequestID: uniqueID("new-usage"), PromptTokens: 100, CachedTokens: 60, CompletionTokens: 10, CostMicroUSD: 5}) byReq := map[string]UsageRecord{} diff --git a/coordinator/store/model_token_promotions_schema.go b/coordinator/store/model_token_promotions_schema.go deleted file mode 100644 index c97d683e36..0000000000 --- a/coordinator/store/model_token_promotions_schema.go +++ /dev/null @@ -1,40 +0,0 @@ -package store - -const modelTokenPromotionDDL = ` -CREATE TABLE IF NOT EXISTS model_token_promotions ( - model_id TEXT PRIMARY KEY, - tokens BIGINT NOT NULL CHECK (tokens > 0 AND tokens <= 1000000000000), - claim_starts_at TIMESTAMPTZ NOT NULL, - claim_ends_at TIMESTAMPTZ CHECK (claim_ends_at > claim_starts_at), - signup_cutoff_at TIMESTAMPTZ NOT NULL, - max_claims BIGINT NOT NULL CHECK (max_claims>0 AND max_claims<=1000000), - claimed_count BIGINT NOT NULL DEFAULT 0 CHECK (claimed_count>=0 AND claimed_count<=max_claims), - enabled BOOLEAN NOT NULL DEFAULT TRUE -); -CREATE TABLE IF NOT EXISTS model_token_grants ( - account_id TEXT NOT NULL REFERENCES users(account_id), - model_id TEXT NOT NULL REFERENCES model_token_promotions(model_id), - total_tokens BIGINT NOT NULL CHECK (total_tokens > 0), - used_tokens BIGINT NOT NULL DEFAULT 0 CHECK (used_tokens >= 0), - reserved_tokens BIGINT NOT NULL DEFAULT 0 CHECK (reserved_tokens >= 0), - claimed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (account_id, model_id), - CHECK (used_tokens + reserved_tokens <= total_tokens) -); -CREATE TABLE IF NOT EXISTS model_token_provider_carries ( - account_id TEXT PRIMARY KEY, - remainder BIGINT NOT NULL DEFAULT 0 CHECK (remainder >= 0 AND remainder < 100000000) -); -CREATE TABLE IF NOT EXISTS model_token_reservations ( - id TEXT PRIMARY KEY, - account_id TEXT NOT NULL, - model_id TEXT NOT NULL, - state TEXT NOT NULL CHECK (state IN ('reserved','settled','released')), - record JSONB NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - touched_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - FOREIGN KEY (account_id, model_id) REFERENCES model_token_grants(account_id, model_id) -); -ALTER TABLE model_token_reservations ADD COLUMN IF NOT EXISTS touched_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); -CREATE INDEX IF NOT EXISTS idx_model_token_reservations_open ON model_token_reservations(touched_at) WHERE state = 'reserved'; -` diff --git a/coordinator/store/postgres.go b/coordinator/store/postgres.go index 5c0fa0aedd..5475b5e63e 100644 --- a/coordinator/store/postgres.go +++ b/coordinator/store/postgres.go @@ -11,7 +11,8 @@ package store // or not at all. The Debit operation uses a conditional UPDATE that only // succeeds if the balance is sufficient, preventing negative balances. // -// Schema migrations run automatically on startup via the migrate() method. +// NewPostgres applies pending schema migrations before it returns +// (postgres_migrations.go). import ( "context" @@ -53,7 +54,7 @@ type cachedPrice struct { } // NewPostgres creates a new PostgresStore connected to the given database URL. -// It runs schema migrations on startup. +// It applies pending schema migrations before it returns. func NewPostgres(ctx context.Context, scfg Config) (*PostgresStore, error) { return newPostgresWithPoolConfig(ctx, scfg, nil) } @@ -115,1099 +116,13 @@ func (s *PostgresStore) Close() { s.pool.Close() } -const legacyCacheAffinityGuardFunction = `CREATE OR REPLACE FUNCTION clear_legacy_cache_affinity_key() -RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - NEW.cache_affinity_key := ''; - RETURN NEW; -END $$` - -const legacyCacheAffinityGuardTrigger = `DO $$ BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM pg_trigger tg - JOIN pg_class target ON target.oid = tg.tgrelid - JOIN pg_namespace ns ON ns.oid = target.relnamespace - WHERE tg.tgname = 'clear_legacy_cache_affinity_key' - AND NOT tg.tgisinternal - AND target.relname = 'inference_routes' - AND ns.nspname = current_schema() - ) THEN - CREATE TRIGGER clear_legacy_cache_affinity_key - BEFORE INSERT OR UPDATE OF cache_affinity_key ON inference_routes - FOR EACH ROW EXECUTE FUNCTION clear_legacy_cache_affinity_key(); - END IF; -END $$` - -const legacyCacheAffinityScrubMigration = `DO $$ BEGIN - IF NOT EXISTS (SELECT 1 FROM schema_migrations WHERE id = 'scrub_inference_route_cache_affinity_v1') THEN - IF EXISTS ( - SELECT 1 FROM information_schema.columns - WHERE table_schema = current_schema() - AND table_name = 'inference_routes' - AND column_name = 'cache_affinity_key' - ) THEN - UPDATE inference_routes SET cache_affinity_key = '' WHERE cache_affinity_key <> ''; - END IF; - INSERT INTO schema_migrations (id) VALUES ('scrub_inference_route_cache_affinity_v1'); - END IF; -END $$` - -// migrate runs the schema creation statements. -func (s *PostgresStore) migrate(ctx context.Context) error { - migrations := []string{ - globalPayoutSchema, - // schema_migrations records one-time data migrations that must run at most - // once rather than on every boot. Idempotent DDL (CREATE/ALTER ... IF [NOT] - // EXISTS) does not need this; it gates destructive one-shot DML scrubs - // (the cache-affinity and log-report serial scrubs) behind a marker id, - // and keeps the markers checkRetiredBackfills requires. - `CREATE TABLE IF NOT EXISTS schema_migrations ( - id TEXT PRIMARY KEY, - applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - - `CREATE TABLE IF NOT EXISTS providers ( - id TEXT PRIMARY KEY, - hardware JSONB NOT NULL, - models JSONB NOT NULL, - backend TEXT NOT NULL, - location JSONB, - registered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), - trust_level TEXT NOT NULL DEFAULT 'none', - attested BOOLEAN NOT NULL DEFAULT FALSE, - attestation_result JSONB, - se_public_key TEXT NOT NULL DEFAULT '', - public_key TEXT NOT NULL DEFAULT '', - serial_number TEXT NOT NULL DEFAULT '', - mda_verified BOOLEAN NOT NULL DEFAULT FALSE, - mda_cert_chain JSONB, - version TEXT NOT NULL DEFAULT '', - runtime_verified BOOLEAN NOT NULL DEFAULT FALSE, - python_hash TEXT NOT NULL DEFAULT '', - runtime_hash TEXT NOT NULL DEFAULT '', - last_challenge_verified TIMESTAMPTZ, - failed_challenges INT NOT NULL DEFAULT 0, - account_id TEXT NOT NULL DEFAULT '', - lifetime_requests_served BIGINT NOT NULL DEFAULT 0, - lifetime_tokens_generated BIGINT NOT NULL DEFAULT 0, - last_session_requests_served BIGINT NOT NULL DEFAULT 0, - last_session_tokens_generated BIGINT NOT NULL DEFAULT 0, - lifetime_stats JSONB NOT NULL DEFAULT '{}'::jsonb, - last_session_stats JSONB NOT NULL DEFAULT '{}'::jsonb - )`, - // Migrate existing providers table: add new columns if upgrading from previous schema - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS location JSONB; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS trust_level TEXT NOT NULL DEFAULT 'none'; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS attested BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS attestation_result JSONB; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS se_public_key TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS public_key TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS serial_number TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS mda_verified BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS mda_cert_chain JSONB; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS version TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS runtime_verified BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS python_hash TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS runtime_hash TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_challenge_verified TIMESTAMPTZ; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS failed_challenges INT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS account_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS lifetime_requests_served BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS lifetime_tokens_generated BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_session_requests_served BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_session_tokens_generated BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS lifetime_stats JSONB NOT NULL DEFAULT '{}'::jsonb; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_session_stats JSONB NOT NULL DEFAULT '{}'::jsonb; EXCEPTION WHEN others THEN NULL; END $$`, - `CREATE INDEX IF NOT EXISTS idx_providers_serial ON providers(serial_number) WHERE serial_number != ''`, - `CREATE INDEX IF NOT EXISTS idx_providers_account ON providers(account_id, last_seen DESC) WHERE account_id != ''`, - - // Migrate usage table: add request_id and cost columns - `DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS request_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS cost_micro_usd BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS request_location JSONB; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS public_model TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - - // Provider reputation — persistent reputation tracking - `CREATE TABLE IF NOT EXISTS provider_reputation ( - provider_id TEXT PRIMARY KEY REFERENCES providers(id), - total_jobs INT NOT NULL DEFAULT 0, - successful_jobs INT NOT NULL DEFAULT 0, - failed_jobs INT NOT NULL DEFAULT 0, - total_uptime_seconds BIGINT NOT NULL DEFAULT 0, - avg_response_time_ms BIGINT NOT NULL DEFAULT 0, - challenges_passed INT NOT NULL DEFAULT 0, - challenges_failed INT NOT NULL DEFAULT 0, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE TABLE IF NOT EXISTS api_keys ( - key_hash TEXT PRIMARY KEY, - raw_prefix TEXT NOT NULL, - owner_account_id TEXT NOT NULL DEFAULT '', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - active BOOLEAN NOT NULL DEFAULT TRUE - )`, - `DO $$ BEGIN - ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS owner_account_id TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - // Multi-key support: per-key id, name, limits, expiry, last-used. - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS name TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS limit_micro_usd BIGINT; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS limit_reset TEXT NOT NULL DEFAULT 'none'; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS rpm_limit BIGINT; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS itpm_limit BIGINT; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS otpm_limit BIGINT; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS allowed_models TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMPTZ; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS self_route_only BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$`, - // Backfill stable IDs for legacy rows (deterministic from the hash so - // it is stable across restarts and idempotent). - `UPDATE api_keys SET id = 'key_' || substr(md5(key_hash), 1, 24) WHERE id IS NULL OR id = ''`, - `CREATE UNIQUE INDEX IF NOT EXISTS idx_api_keys_id ON api_keys(id) WHERE id <> ''`, - `CREATE INDEX IF NOT EXISTS idx_api_keys_owner ON api_keys(owner_account_id) WHERE owner_account_id <> ''`, - `CREATE TABLE IF NOT EXISTS usage ( - id BIGSERIAL PRIMARY KEY, - provider_id TEXT NOT NULL, - consumer_key_hash TEXT NOT NULL, - key_id TEXT NOT NULL DEFAULT '', - model TEXT NOT NULL, - public_model TEXT NOT NULL DEFAULT '', - prompt_tokens INTEGER NOT NULL, - cached_tokens INTEGER NOT NULL DEFAULT 0, - completion_tokens INTEGER NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - request_id TEXT NOT NULL DEFAULT '', - cost_micro_usd BIGINT NOT NULL DEFAULT 0, - request_location JSONB - )`, - // Per-key usage attribution — ALTER for DBs upgrading from a usage - // table created before key_id existed. Must run AFTER CREATE TABLE usage. - `DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS key_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS public_model TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - // Prompt tokens billed at the cache-read rate; rows written before the - // column existed had no cache discount, so 0 is the truthful backfill. - // Deliberately not wrapped in an exception handler: RecordUsage writes - // this column, so a failed ALTER (lock timeout, missing privilege) must - // abort startup rather than lose every usage row after settlement. - `ALTER TABLE usage ADD COLUMN IF NOT EXISTS cached_tokens INTEGER NOT NULL DEFAULT 0`, - // Indexes for usage queries (stats, billing, per-consumer history). - `CREATE INDEX IF NOT EXISTS idx_usage_created ON usage(created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_usage_consumer ON usage(consumer_key_hash, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_usage_provider ON usage(provider_id, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_usage_key ON usage(key_id, created_at DESC) WHERE key_id <> ''`, - - `CREATE TABLE IF NOT EXISTS payments ( - id BIGSERIAL PRIMARY KEY, - tx_hash TEXT UNIQUE, - consumer_address TEXT NOT NULL, - provider_address TEXT NOT NULL, - amount_usd TEXT NOT NULL, - model TEXT NOT NULL, - prompt_tokens INTEGER NOT NULL, - completion_tokens INTEGER NOT NULL, - memo TEXT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - // withdrawable_micro_usd trails updated_at: existing databases gained - // it through the retired backfill_withdrawable_balance_v1 migration, - // which added it with this exact definition and physical position. - `CREATE TABLE IF NOT EXISTS balances ( - account_id TEXT PRIMARY KEY, - balance_micro_usd BIGINT NOT NULL DEFAULT 0, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - withdrawable_micro_usd BIGINT NOT NULL DEFAULT 0 - )`, - `CREATE TABLE IF NOT EXISTS ledger_entries ( - id BIGSERIAL PRIMARY KEY, - account_id TEXT NOT NULL, - entry_type TEXT NOT NULL, - amount_micro_usd BIGINT NOT NULL, - balance_after BIGINT NOT NULL, - reference TEXT NOT NULL DEFAULT '', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_ledger_account ON ledger_entries(account_id, created_at DESC)`, - // Partial index for the public leaderboard/network-totals reward scans, - // which filter ledger_entries by reward entry_type across all accounts. - // Without it, each cache miss seq-scans the whole (multi-million-row) - // ledger to find the handful of reward rows. Predicate is derived from - // RewardLedgerTypes so it matches the query's IN-list exactly. - `CREATE INDEX IF NOT EXISTS idx_ledger_reward ON ledger_entries(account_id, created_at DESC) WHERE entry_type IN (` + rewardLedgerTypesSQLList() + `)`, - - // Referral system tables - `CREATE TABLE IF NOT EXISTS referrers ( - account_id TEXT PRIMARY KEY, - code TEXT UNIQUE NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_referrers_code ON referrers(code)`, - - `CREATE TABLE IF NOT EXISTS referrals ( - referred_account TEXT PRIMARY KEY, - referrer_code TEXT NOT NULL REFERENCES referrers(code), - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_referrals_code ON referrals(referrer_code)`, - - // Billing sessions table - `CREATE TABLE IF NOT EXISTS billing_sessions ( - id TEXT PRIMARY KEY, - account_id TEXT NOT NULL, - payment_method TEXT NOT NULL, - amount_micro_usd BIGINT NOT NULL, - external_id TEXT NOT NULL DEFAULT '', - status TEXT NOT NULL DEFAULT 'pending', - referral_code TEXT NOT NULL DEFAULT '', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - completed_at TIMESTAMPTZ - )`, - `CREATE INDEX IF NOT EXISTS idx_billing_sessions_account ON billing_sessions(account_id)`, - `CREATE INDEX IF NOT EXISTS idx_billing_sessions_external ON billing_sessions(external_id)`, - - // Custom pricing — per-account model price overrides - `CREATE TABLE IF NOT EXISTS model_prices ( - account_id TEXT NOT NULL, - model TEXT NOT NULL, - input_price BIGINT NOT NULL, - output_price BIGINT NOT NULL, - cache_read_price BIGINT, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (account_id, model) - )`, - // Cache-read rate for prompt tokens served from a provider's prefix - // cache (OpenRouter pricing.input_cache_read). Nullable: NULL means the - // row sets none and billing derives the rate from input_price, so - // existing rows gain the default cache discount without a backfill. - // Not wrapped in an exception handler: GetModelPrice selects this - // column, so a failed ALTER must abort startup rather than make every - // price lookup miss and bill at the default rates. - `ALTER TABLE model_prices ADD COLUMN IF NOT EXISTS cache_read_price BIGINT`, - - // Users — Privy identity → internal account mapping - `CREATE TABLE IF NOT EXISTS users ( - account_id TEXT PRIMARY KEY, - privy_user_id TEXT UNIQUE NOT NULL, - email TEXT NOT NULL DEFAULT '', - role TEXT NOT NULL DEFAULT '', - platform_fee_percent BIGINT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `DO $$ BEGIN - ALTER TABLE users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy ON users(privy_user_id)`, - - // The legacy admin-managed supported_models catalog was replaced by the - // manifest-backed model_registry below. Drop the stale duplicate table if - // it is still present from an older deployment. - `DROP TABLE IF EXISTS supported_models`, - - `CREATE TABLE IF NOT EXISTS model_registry ( - id TEXT PRIMARY KEY, - display_name TEXT NOT NULL, - family TEXT NOT NULL DEFAULT '', - architecture TEXT NOT NULL DEFAULT '', - quantization TEXT NOT NULL DEFAULT '', - max_context_length INTEGER NOT NULL DEFAULT 0, - max_output_length INTEGER NOT NULL DEFAULT 0, - min_ram_gb INTEGER NOT NULL DEFAULT 0, - capabilities TEXT[] NOT NULL DEFAULT '{}', - required_provider_capabilities TEXT[] NOT NULL DEFAULT '{}', - status TEXT NOT NULL DEFAULT 'beta', - description TEXT NOT NULL DEFAULT '', - runtime_parameters JSONB NOT NULL DEFAULT '{}', - metadata JSONB NOT NULL DEFAULT '{}', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_model_registry_status ON model_registry(status)`, - `CREATE TABLE IF NOT EXISTS model_versions ( - id BIGSERIAL PRIMARY KEY, - model_id TEXT NOT NULL REFERENCES model_registry(id) ON DELETE CASCADE, - version TEXT NOT NULL, - r2_prefix TEXT NOT NULL, - aggregate_sha256 TEXT NOT NULL, - total_size_bytes BIGINT NOT NULL, - file_count INTEGER NOT NULL, - status TEXT NOT NULL DEFAULT 'ready', - uploaded_by TEXT NOT NULL DEFAULT '', - uploaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - promoted_at TIMESTAMPTZ, - metadata JSONB NOT NULL DEFAULT '{}', - UNIQUE(model_id, version) - )`, - `ALTER TABLE model_versions ADD COLUMN IF NOT EXISTS hugging_face_artifact JSONB`, - `DO $$ BEGIN - ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS max_context_length INTEGER NOT NULL DEFAULT 0; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS max_output_length INTEGER NOT NULL DEFAULT 0; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS runtime_parameters JSONB NOT NULL DEFAULT '{}'; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS required_provider_capabilities TEXT[] NOT NULL DEFAULT '{}'; - EXCEPTION WHEN others THEN NULL; - END $$`, - `UPDATE model_registry - SET required_provider_capabilities = ( - SELECT ARRAY_AGG(DISTINCT capability ORDER BY capability) - FROM UNNEST(required_provider_capabilities || - ARRAY['apple_m5', 'mlx_nax']::TEXT[]) AS capability - ) - WHERE id = 'EigenLabs/Qwen3.8-27B-4bit' - AND NOT (required_provider_capabilities @> - ARRAY['apple_m5', 'mlx_nax']::TEXT[])`, - `CREATE INDEX IF NOT EXISTS idx_model_versions_model ON model_versions(model_id)`, - `CREATE TABLE IF NOT EXISTS model_version_files ( - id BIGSERIAL PRIMARY KEY, - model_version_id BIGINT NOT NULL REFERENCES model_versions(id) ON DELETE CASCADE, - path TEXT NOT NULL, - size_bytes BIGINT NOT NULL, - sha256 TEXT NOT NULL, - role TEXT NOT NULL, - UNIQUE(model_version_id, path) - )`, - `CREATE INDEX IF NOT EXISTS idx_model_version_files_version ON model_version_files(model_version_id)`, - `CREATE TABLE IF NOT EXISTS model_active_versions ( - model_id TEXT PRIMARY KEY REFERENCES model_registry(id) ON DELETE CASCADE, - model_version_id BIGINT NOT NULL REFERENCES model_versions(id) ON DELETE RESTRICT, - activated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE TABLE IF NOT EXISTS publishing_api_keys ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - key_hash TEXT NOT NULL, - active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - last_used_at TIMESTAMPTZ - )`, - `CREATE UNIQUE INDEX IF NOT EXISTS idx_publishing_api_keys_hash ON publishing_api_keys(key_hash)`, - - // Model aliases (public-facing names → a desired concrete build). An alias - // resolves to a single desired_build (the build providers converge to) with - // an optional previous_build that stays acceptable during a rollout. Lets us - // swap the underlying quant (fp8 → qat-4bit) behind a stable consumer-facing - // model name. The legacy `builds` JSONB column is kept (nullable, default - // '[]') only so an older coordinator binary doesn't choke on the table; it - // is no longer read or written — drop it in a follow-up release. - `CREATE TABLE IF NOT EXISTS model_aliases ( - alias_id TEXT PRIMARY KEY, - display_name TEXT NOT NULL DEFAULT '', - builds JSONB NOT NULL DEFAULT '[]'::jsonb, - active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - // Declarative desired/previous build pointers (additive migration). - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS desired_build TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS previous_build TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - // Alias lineage: former desired/previous builds rotated out by later - // upserts, so a provider returning from a long offline period is still - // recognized as part of the alias's fleet. - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS retired_builds JSONB NOT NULL DEFAULT '[]'::jsonb; EXCEPTION WHEN others THEN NULL; END $$`, - // OpenRouter-only aliases clone an existing public alias or concrete model - // while keeping an independent API id and marketplace identities. Existing - // rows predate source_kind and therefore retain standard-alias semantics. - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS openrouter_only BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS source_model TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS source_kind TEXT NOT NULL DEFAULT 'standard_alias'; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS openrouter_slug TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS hugging_face_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - - // Backfill desired_build from the old `builds` JSON: pick the highest-weight - // active build of each alias that hasn't been migrated yet. DISTINCT ON keeps - // exactly one (highest-weight) build per alias so the UPDATE...FROM join is - // deterministic. One-shot; safe to re-run because it only touches rows still - // on the empty default. - `DO $$ BEGIN - UPDATE model_aliases a - SET desired_build = sub.build_id - FROM ( - SELECT DISTINCT ON (alias_id) alias_id, (b->>'build_id') AS build_id - FROM model_aliases, jsonb_array_elements(builds) AS b - WHERE COALESCE((b->>'active')::boolean, true) - AND COALESCE((b->>'weight')::int, 0) > 0 - ORDER BY alias_id, COALESCE((b->>'weight')::int, 0) DESC - ) sub - WHERE a.alias_id = sub.alias_id AND a.desired_build = ''; - EXCEPTION WHEN others THEN NULL; END $$`, - // The weighted-ramp migration controller is gone; drop its table. - `DROP TABLE IF EXISTS model_migrations`, - - // Releases (provider binary versioning) - `CREATE TABLE IF NOT EXISTS releases ( - version TEXT NOT NULL, - platform TEXT NOT NULL, - backend TEXT NOT NULL DEFAULT '', - binary_hash TEXT NOT NULL DEFAULT '', - bundle_hash TEXT NOT NULL DEFAULT '', - metallib_hash TEXT NOT NULL DEFAULT '', - python_hash TEXT NOT NULL DEFAULT '', - runtime_hash TEXT NOT NULL DEFAULT '', - template_hashes TEXT NOT NULL DEFAULT '', - grpc_binary_hash TEXT NOT NULL DEFAULT '', - url TEXT NOT NULL DEFAULT '', - changelog TEXT NOT NULL DEFAULT '', - active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (version, platform) - )`, - `DO $$ BEGIN - ALTER TABLE releases ADD COLUMN IF NOT EXISTS backend TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE releases ADD COLUMN IF NOT EXISTS metallib_hash TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE releases ADD COLUMN IF NOT EXISTS changelog TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE releases ADD COLUMN IF NOT EXISTS python_hash TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE releases ADD COLUMN IF NOT EXISTS runtime_hash TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE releases ADD COLUMN IF NOT EXISTS template_hashes TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - `DO $$ BEGIN - ALTER TABLE releases ADD COLUMN IF NOT EXISTS grpc_binary_hash TEXT NOT NULL DEFAULT ''; - EXCEPTION WHEN others THEN NULL; - END $$`, - - // Device authorization (RFC 8628-style) - `CREATE TABLE IF NOT EXISTS device_codes ( - device_code TEXT PRIMARY KEY, - user_code TEXT UNIQUE NOT NULL, - account_id TEXT NOT NULL DEFAULT '', - status TEXT NOT NULL DEFAULT 'pending', - expires_at TIMESTAMPTZ NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_device_codes_user ON device_codes(user_code)`, - - // Provider tokens — long-lived auth linking provider machines to accounts - `CREATE TABLE IF NOT EXISTS provider_tokens ( - token_hash TEXT PRIMARY KEY, - account_id TEXT NOT NULL, - label TEXT NOT NULL DEFAULT '', - active BOOLEAN NOT NULL DEFAULT TRUE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_provider_tokens_account ON provider_tokens(account_id)`, - - // Invite codes - `CREATE TABLE IF NOT EXISTS invite_codes ( - code TEXT PRIMARY KEY, - amount_micro_usd BIGINT NOT NULL, - max_uses INTEGER NOT NULL DEFAULT 1, - used_count INTEGER NOT NULL DEFAULT 0, - active BOOLEAN NOT NULL DEFAULT TRUE, - expires_at TIMESTAMPTZ, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE TABLE IF NOT EXISTS invite_redemptions ( - code TEXT NOT NULL REFERENCES invite_codes(code), - account_id TEXT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (code, account_id) - )`, - - // Provider earnings — per-node tracking - `CREATE TABLE IF NOT EXISTS provider_earnings ( - id BIGSERIAL PRIMARY KEY, - account_id TEXT NOT NULL, - provider_id TEXT NOT NULL, - provider_key TEXT NOT NULL DEFAULT '', - job_id TEXT NOT NULL, - model TEXT NOT NULL, - amount_micro_usd BIGINT NOT NULL, - prompt_tokens INTEGER NOT NULL DEFAULT 0, - completion_tokens INTEGER NOT NULL DEFAULT 0, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_provider_earnings_account ON provider_earnings(account_id, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_provider_earnings_provider ON provider_earnings(provider_key, created_at DESC)`, - - // Materialized per-account earnings summaries (key_type 'account') — - // atomically maintained by CreditProviderAccount, RecordProviderEarning - // and floor-draw settlement. Eliminates full-table SUM scans on - // /v1/provider/account-earnings. Rows with key_type 'provider' are no - // longer written or read; they stay so an older binary still boots. - `CREATE TABLE IF NOT EXISTS earnings_summary ( - key TEXT NOT NULL, - key_type TEXT NOT NULL, - total_count BIGINT NOT NULL DEFAULT 0, - total_micro_usd BIGINT NOT NULL DEFAULT 0, - total_prompt_tokens BIGINT NOT NULL DEFAULT 0, - total_completion_tokens BIGINT NOT NULL DEFAULT 0, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (key, key_type) - )`, - - // Provider payouts — wallet-based payout history for unlinked providers - `CREATE TABLE IF NOT EXISTS provider_payouts ( - id BIGSERIAL PRIMARY KEY, - provider_address TEXT NOT NULL, - amount_micro_usd BIGINT NOT NULL, - model TEXT NOT NULL DEFAULT '', - job_id TEXT NOT NULL DEFAULT '', - settled BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_provider_payouts_address ON provider_payouts(provider_address, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_provider_payouts_settled ON provider_payouts(settled, created_at DESC)`, - - // Stripe Connect — bank/card payouts - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_account_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_account_status TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_account_country TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_destination_type TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_destination_last4 TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_instant_eligible BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$`, - `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_stripe_account ON users(stripe_account_id) WHERE stripe_account_id != ''`, - - // Account role + per-account platform fee override (service accounts, e.g. OpenRouter). - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS platform_fee_percent BIGINT; EXCEPTION WHEN others THEN NULL; END $$`, - - `CREATE TABLE IF NOT EXISTS stripe_withdrawals ( - id TEXT PRIMARY KEY, - account_id TEXT NOT NULL, - stripe_account_id TEXT NOT NULL, - transfer_id TEXT NOT NULL DEFAULT '', - payout_id TEXT NOT NULL DEFAULT '', - amount_micro_usd BIGINT NOT NULL, - fee_micro_usd BIGINT NOT NULL DEFAULT 0, - net_micro_usd BIGINT NOT NULL, - method TEXT NOT NULL, - status TEXT NOT NULL, - failure_reason TEXT NOT NULL DEFAULT '', - refunded BOOLEAN NOT NULL DEFAULT FALSE, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_account ON stripe_withdrawals(account_id, created_at DESC)`, - `CREATE UNIQUE INDEX IF NOT EXISTS idx_stripe_withdrawals_transfer ON stripe_withdrawals(transfer_id) WHERE transfer_id != ''`, - `CREATE UNIQUE INDEX IF NOT EXISTS idx_stripe_withdrawals_payout ON stripe_withdrawals(payout_id) WHERE payout_id != ''`, - `CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_status ON stripe_withdrawals(status, created_at)`, - `CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_stripe_account ON stripe_withdrawals(stripe_account_id, status)`, - `DO $$ BEGIN ALTER TABLE stripe_withdrawals ADD COLUMN IF NOT EXISTS fee_refunded BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE stripe_withdrawals ADD COLUMN IF NOT EXISTS sweep_payout_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_sweep_payout ON stripe_withdrawals(sweep_payout_id) WHERE sweep_payout_id != ''`, - - // Telemetry events table + indices removed. - // Datadog is the sole durable sink for telemetry — the Postgres table - // was the single largest source of DB write pressure under provider load - // (60 providers × batch/10s × 50 rows × 5 indexes = ~30-40% of the - // connection pool). No read endpoints consumed this table.', - - // Materialized usage totals — eliminates full-table scan of usage - // on every stats cache miss. Single counter row incremented - // atomically by RecordUsage. - `CREATE TABLE IF NOT EXISTS usage_totals ( - id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), - total_requests BIGINT NOT NULL DEFAULT 0, - total_prompt_tokens BIGINT NOT NULL DEFAULT 0, - total_completion_tokens BIGINT NOT NULL DEFAULT 0 - )`, - // The single counter row is seeded after this loop, by - // checkRetiredBackfills, and only while usage is empty. - - // Partial index for UsageLocationBuckets — only rows with a - // non-null request_location are ever queried. - `CREATE INDEX IF NOT EXISTS idx_usage_request_location_notnull ON usage(created_at DESC) WHERE request_location IS NOT NULL`, - - // Provider log reports — providers upload 24h unified logs for debugging. - // serial_number is retained only as a rollback-compatible legacy column. - // The write guard and one-time scrub keep it empty. - `CREATE TABLE IF NOT EXISTS provider_log_reports ( - id BIGSERIAL PRIMARY KEY, - serial_number TEXT NOT NULL DEFAULT '', - provider_id TEXT NOT NULL DEFAULT '', - account_id TEXT NOT NULL DEFAULT '', - log_data BYTEA NOT NULL, - log_size_bytes BIGINT NOT NULL DEFAULT 0, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `ALTER TABLE provider_log_reports ALTER COLUMN serial_number SET DEFAULT ''`, - providerLogReportSerialGuardFunction, - providerLogReportSerialGuardTrigger, - providerLogReportSerialScrubMigration, - `DROP INDEX IF EXISTS idx_log_reports_serial`, - - // Provider sessions — durable connect→disconnect history for uptime/downtime. - // One row per websocket connection; disconnected_at IS NULL while open. - // session_id is UNIQUE so the async open/close paths are order-independent - // (open = INSERT ON CONFLICT DO NOTHING; close = upsert) — a fast - // connect→disconnect where close races ahead of open cannot leave a - // permanently-open row. - `CREATE TABLE IF NOT EXISTS provider_sessions ( - id BIGSERIAL PRIMARY KEY, - session_id TEXT NOT NULL UNIQUE, - serial_number TEXT NOT NULL DEFAULT '', - account_id TEXT NOT NULL DEFAULT '', - connected_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), - disconnected_at TIMESTAMPTZ, - disconnect_reason TEXT NOT NULL DEFAULT '' - )`, - `CREATE INDEX IF NOT EXISTS idx_provider_sessions_serial ON provider_sessions(serial_number, connected_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_provider_sessions_connected ON provider_sessions(connected_at DESC)`, - // Partial index over still-open sessions — speeds the online-now count and - // the startup reconcile. (session_id lookups use the UNIQUE index.) - `CREATE INDEX IF NOT EXISTS idx_provider_sessions_open ON provider_sessions(connected_at) WHERE disconnected_at IS NULL`, - - // Inference routing telemetry — per-request scheduler decisions and outcomes. - // Contains no prompt or response content. - `CREATE TABLE IF NOT EXISTS inference_routes ( - id BIGSERIAL PRIMARY KEY, - request_id TEXT NOT NULL, - attempt INTEGER NOT NULL DEFAULT 0, - provider_id TEXT NOT NULL DEFAULT '', - model TEXT NOT NULL, - public_model TEXT NOT NULL DEFAULT '', - consumer_key_hash TEXT NOT NULL DEFAULT '', - key_id TEXT NOT NULL DEFAULT '', - outcome TEXT NOT NULL DEFAULT '', - cost_ms DOUBLE PRECISION, - state_ms DOUBLE PRECISION, - queue_ms DOUBLE PRECISION, - pending_ms DOUBLE PRECISION, - backlog_ms DOUBLE PRECISION, - this_req_ms DOUBLE PRECISION, - health_ms DOUBLE PRECISION, - ttft_ms DOUBLE PRECISION, - best_ttft_ms DOUBLE PRECISION, - effective_queue INTEGER, - candidate_count INTEGER, - capacity_rejections INTEGER, - model_too_large_rejections INTEGER, - vision_rejections INTEGER, - ttft_rejections INTEGER, - effective_tps DOUBLE PRECISION, - static_tps DOUBLE PRECISION, - provider_status TEXT, - provider_trust_level TEXT, - provider_version TEXT, - hardware_chip TEXT, - hardware_chip_family TEXT, - hardware_tier TEXT, - memory_gb INTEGER, - gpu_cores INTEGER, - cpu_cores INTEGER, - system_memory_pressure DOUBLE PRECISION, - system_cpu_usage DOUBLE PRECISION, - system_thermal_state TEXT, - gpu_memory_active_gb DOUBLE PRECISION, - gpu_memory_peak_gb DOUBLE PRECISION, - gpu_memory_cache_gb DOUBLE PRECISION, - slot_state TEXT, - backend_running INTEGER, - backend_waiting INTEGER, - active_token_budget_used BIGINT, - active_token_budget_max BIGINT, - queued_token_budget BIGINT, - estimated_prompt_tokens INTEGER, - requested_max_tokens INTEGER, - requires_vision BOOLEAN NOT NULL DEFAULT FALSE, - has_tools BOOLEAN NOT NULL DEFAULT FALSE, - self_route_only BOOLEAN NOT NULL DEFAULT FALSE, - prefer_owner BOOLEAN NOT NULL DEFAULT FALSE, - cache_affinity_key TEXT NOT NULL DEFAULT '', - final_status TEXT NOT NULL DEFAULT '', - error_code INTEGER, - error_class TEXT, - prompt_tokens INTEGER, - completion_tokens INTEGER, - reasoning_tokens INTEGER, - cost_micro_usd BIGINT, - actual_ttft_ms DOUBLE PRECISION, - dispatch_to_first_chunk_ms DOUBLE PRECISION, - total_duration_ms DOUBLE PRECISION, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - provider_region TEXT, - consumer_region TEXT, - parse_ms DOUBLE PRECISION, - reserve_ms DOUBLE PRECISION, - route_ms DOUBLE PRECISION, - encrypt_ms DOUBLE PRECISION, - queue_wait_ms DOUBLE PRECISION, - dispatch_ms DOUBLE PRECISION, - actual_decode_tps DOUBLE PRECISION, - admitted_but_failed BOOL, - used_backup BOOL, - backup_won BOOL, - error_reason TEXT, - UNIQUE(request_id, attempt) - )`, - `CREATE INDEX IF NOT EXISTS idx_inference_routes_created ON inference_routes(created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_inference_routes_provider ON inference_routes(provider_id, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_inference_routes_model ON inference_routes(model, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_inference_routes_request ON inference_routes(request_id)`, - `DO $$ - BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM pg_index i - JOIN pg_class t ON t.oid = i.indrelid - WHERE t.oid = 'inference_routes'::regclass - AND i.indisunique - AND ARRAY( - SELECT a.attname::text - FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) - JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum - ORDER BY k.ord - ) = ARRAY['request_id', 'attempt'] - ) THEN - CREATE UNIQUE INDEX idx_inference_routes_request_attempt_unique ON inference_routes(request_id, attempt); - END IF; - END $$`, - // Phase 1 additions to inference_routes: coarse geo, coordinator-side - // latency decomposition, measured decode TPS, and admission/backup-race - // outcome flags. Added idempotently so a dev DB that already created the - // Phase 0 table picks them up. New columns are appended AFTER updated_at - // in the CREATE TABLE above so fresh and ALTER'd DBs share one column - // order (InferenceRouteRecordsSince scans `SELECT *` positionally). - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS provider_region TEXT`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS consumer_region TEXT`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS parse_ms DOUBLE PRECISION`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS reserve_ms DOUBLE PRECISION`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS route_ms DOUBLE PRECISION`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS encrypt_ms DOUBLE PRECISION`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS queue_wait_ms DOUBLE PRECISION`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS dispatch_ms DOUBLE PRECISION`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS actual_decode_tps DOUBLE PRECISION`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS admitted_but_failed BOOL`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS used_backup BOOL`, - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS backup_won BOOL`, - // DAR-341: normalized provider/coordinator error reason. Nullable and - // appended so fresh DBs match upgraded DB column order for SELECT * scans. - `ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS error_reason TEXT`, - // Route keys are memory-only HMACs. Scrub legacy persisted SHA-256 - // prompt-cache identifiers once. The trigger also clears writes from an - // older coordinator during blue-green overlap or emergency rollback while - // retaining that binary's expected SQL shape. - legacyCacheAffinityGuardFunction, - legacyCacheAffinityGuardTrigger, - legacyCacheAffinityScrubMigration, - - // Rejected inbound inference requests (4xx/5xx) at any pipeline stage, - // with the request shape and a counterfactual servability snapshot - // ("could the fleet have served it?"). Contains no prompt or response - // content. - `CREATE TABLE IF NOT EXISTS request_rejections ( - id BIGSERIAL PRIMARY KEY, - request_id TEXT, - endpoint TEXT, - stage TEXT, - reason_code TEXT, - http_status INT, - consumer_key_hash TEXT, - key_id TEXT, - client_class TEXT, - requested_model TEXT, - resolved_model TEXT, - stream BOOL, - n INT, - estimated_prompt_tokens INT, - requested_max_tokens INT, - requires_vision BOOL, - has_image BOOL, - has_audio BOOL, - has_tools BOOL, - tool_count INT, - response_format TEXT, - self_route_only BOOL, - prefer_owner BOOL, - params JSONB, - request_body_bytes INT, - retry_after_ms INT, - could_have_served BOOL, - candidate_count INT, - capacity_rejections INT, - model_too_large_rejections INT, - vision_rejections INT, - warm_provider_existed BOOL, - best_ttft_ms DOUBLE PRECISION, - shortfall_micro_usd BIGINT, - limit_kind TEXT, - over_by BIGINT, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `CREATE INDEX IF NOT EXISTS idx_request_rejections_created ON request_rejections(created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_request_rejections_reason ON request_rejections(reason_code, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_request_rejections_model ON request_rejections(resolved_model, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_request_rejections_status ON request_rejections(http_status, created_at DESC)`, - `CREATE INDEX IF NOT EXISTS idx_request_rejections_servable ON request_rejections(could_have_served, created_at DESC) WHERE could_have_served = true`, - - // APNs code-identity attestation reuse cache (W5 Fix 2). Persists the - // in-memory reuse cache so a blue-green deploy / restart does not wipe it - // and provoke a fleet-wide push storm against Apple's ~3/hour/device push - // budget. One row per device (keyed by Secure Enclave public key). The - // row records that the device completed a FULL code-identity round-trip at - // attested_at on binary version; the freshness + version gate is applied on - // READ (in the coordinator), so a stale/wrong-version row never extends - // trust — it only lets the coordinator skip a redundant push. - `CREATE TABLE IF NOT EXISTS code_attestations ( - se_pubkey TEXT PRIMARY KEY, - version TEXT NOT NULL DEFAULT '', - attested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - apns_token TEXT NOT NULL DEFAULT '', - node_public_key TEXT NOT NULL DEFAULT '', - binary_hash TEXT NOT NULL DEFAULT '' - )`, - // Token-binding column for reuse (Codex #7): additive for DBs whose - // code_attestations table predates it (the CREATE above is a no-op there). - `ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS apns_token TEXT NOT NULL DEFAULT ''`, - `ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS node_public_key TEXT NOT NULL DEFAULT ''`, - // Attested binary identity (Codex 05:55Z P1): additive; a pre-existing - // row's empty hash marks a legacy identity-less proof, which never - // authorizes a release-transition resume (real APNs challenge instead). - `ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS binary_hash TEXT NOT NULL DEFAULT ''`, - `ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS continuous_coverage_until TIMESTAMPTZ`, - // Durable APNs admission state is deliberately separate from successful - // attestation evidence. Spending a push budget never creates trust. - `CREATE TABLE IF NOT EXISTS code_attest_push_budgets ( - se_pubkey TEXT NOT NULL, - token_hash TEXT NOT NULL DEFAULT '', - next_push_at TIMESTAMPTZ NOT NULL, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - PRIMARY KEY (se_pubkey, token_hash) - )`, - `DO $$ - DECLARE key_columns TEXT[]; - BEGIN - SELECT array_agg(a.attname::TEXT ORDER BY k.ordinality) - INTO key_columns - FROM pg_constraint c - CROSS JOIN LATERAL unnest(c.conkey) - WITH ORDINALITY AS k(attnum, ordinality) - JOIN pg_attribute a - ON a.attrelid = c.conrelid AND a.attnum = k.attnum - WHERE c.conrelid = 'code_attest_push_budgets'::regclass - AND c.contype = 'p'; - IF key_columns IS DISTINCT FROM - ARRAY['se_pubkey', 'token_hash']::TEXT[] THEN - ALTER TABLE code_attest_push_budgets - DROP CONSTRAINT IF EXISTS code_attest_push_budgets_pkey; - ALTER TABLE code_attest_push_budgets - ADD CONSTRAINT code_attest_push_budgets_pkey - PRIMARY KEY (se_pubkey, token_hash); - END IF; - END $$`, - `CREATE INDEX IF NOT EXISTS idx_code_attest_push_budgets_due - ON code_attest_push_budgets(next_push_at)`, - // Durable rotation-clear cooldown (Codex 06:36Z P1): the sentinel row - // records the last honored floor clear so restart/blue-green peers - // share one anti-abuse clear budget. NULL = never cleared (legacy rows - // and fresh sentinels clear immediately, preserving genuine-rotation UX). - `ALTER TABLE code_attest_push_budgets - ADD COLUMN IF NOT EXISTS last_clear_at TIMESTAMPTZ`, - - // Durable provider device evidence. The legacy binary_hash/verified_at - // columns remain accepted during migration, but application proof is never - // fabricated from them. - `CREATE TABLE IF NOT EXISTS provider_trust_reuse ( - se_pubkey TEXT PRIMARY KEY, - serial TEXT NOT NULL DEFAULT '', - trust_level TEXT NOT NULL DEFAULT '', - binary_hash TEXT NOT NULL DEFAULT '', - sip_enabled BOOL NOT NULL DEFAULT FALSE, - secure_boot_full BOOL NOT NULL DEFAULT FALSE, - mda_udid TEXT NOT NULL DEFAULT '', - verified_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - last_verified_binary_hash TEXT NOT NULL DEFAULT '', - hardware_proof_verified_at TIMESTAMPTZ, - application_proof_verified_at TIMESTAMPTZ, - evidence_generation BIGINT NOT NULL DEFAULT 1, - revocation_generation BIGINT NOT NULL DEFAULT 0, - revocation_event_id TEXT NOT NULL DEFAULT '', - revoked_at TIMESTAMPTZ - )`, - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS last_verified_binary_hash TEXT NOT NULL DEFAULT ''`, - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS hardware_proof_verified_at TIMESTAMPTZ`, - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS application_proof_verified_at TIMESTAMPTZ`, - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS evidence_generation BIGINT NOT NULL DEFAULT 1`, - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS revocation_generation BIGINT NOT NULL DEFAULT 0`, - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS revocation_event_id TEXT NOT NULL DEFAULT ''`, - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS revoked_at TIMESTAMPTZ`, - // Coordinator-measured continuous-liveness watermark (connection - // continuity trust reuse). Written only by the coordinator; NULL for - // pre-migration rows means "no continuity evidence" (fail-safe). - `ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS continuous_coverage_until TIMESTAMPTZ`, - `UPDATE provider_trust_reuse - SET hardware_proof_verified_at = verified_at - WHERE hardware_proof_verified_at IS NULL`, - `UPDATE provider_trust_reuse - SET last_verified_binary_hash = binary_hash - WHERE last_verified_binary_hash = '' AND binary_hash <> ''`, - `ALTER TABLE provider_trust_reuse ALTER COLUMN hardware_proof_verified_at SET DEFAULT NOW()`, - `ALTER TABLE provider_trust_reuse ALTER COLUMN hardware_proof_verified_at SET NOT NULL`, - - // Durable bounded verification scheduler. This table contains retry and - // short claim metadata only; provider/session IDs are intentionally absent - // and a row is never trust authority. - `CREATE TABLE IF NOT EXISTS provider_verification_jobs ( - se_pubkey TEXT NOT NULL, - serial TEXT NOT NULL DEFAULT '', - udid TEXT NOT NULL DEFAULT '', - task_kind TEXT NOT NULL, - task_state TEXT NOT NULL, - priority SMALLINT NOT NULL, - retry_stage INTEGER NOT NULL DEFAULT 0, - previous_delay_ns BIGINT NOT NULL DEFAULT 0, - next_attempt_at TIMESTAMPTZ, - last_outcome TEXT NOT NULL DEFAULT 'none', - reopen_pending BOOLEAN NOT NULL DEFAULT FALSE, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - claim_owner TEXT NOT NULL DEFAULT '', - claim_expires_at TIMESTAMPTZ, - PRIMARY KEY (se_pubkey, task_kind) - )`, - `ALTER TABLE provider_verification_jobs - ADD COLUMN IF NOT EXISTS reopen_pending BOOLEAN NOT NULL DEFAULT FALSE`, - `CREATE INDEX IF NOT EXISTS idx_provider_verification_jobs_due - ON provider_verification_jobs(priority, next_attempt_at) - WHERE task_state IN ('pending', 'backoff')`, - `CREATE INDEX IF NOT EXISTS idx_provider_verification_jobs_claim - ON provider_verification_jobs(claim_expires_at) - WHERE claim_owner <> ''`, - - // Base-rewards per-job settlement idempotency relies on a partial UNIQUE - // index on provider_earnings(job_id). DAR-349: that index is built AFTER - // this migration loop, CONCURRENTLY and at most once, by - // ensureProviderEarningsJobIndex — NEVER with a boot-time dedupe DELETE. - // The old `DELETE ... GROUP BY job_id` here full-scanned and locked this - // hot table (~900k rows / ~443MB) for ~15m on deploy, blocking the - // coordinator from binding :8080 and causing a production outage, while - // doing no useful work (prod duplicate count is 0). Offline dedupe, if it - // is ever needed, lives in coordinator/store/migrations/dedupe_provider_earnings.sql. - - // Base-rewards: unify sessions↔earnings identity (design §8). - `DO $$ BEGIN ALTER TABLE provider_sessions ADD COLUMN IF NOT EXISTS provider_key TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$`, - `CREATE INDEX IF NOT EXISTS idx_provider_sessions_key ON provider_sessions(provider_key, connected_at) WHERE provider_key <> ''`, - - // Base-rewards: idempotent epoch settlement, one row per (provider_key, epoch_id). - `CREATE TABLE IF NOT EXISTS provider_floor_draws ( - id BIGSERIAL PRIMARY KEY, - provider_key TEXT NOT NULL, - account_id TEXT NOT NULL DEFAULT '', - epoch_id TEXT NOT NULL, - amount_micro_usd BIGINT NOT NULL, - floor_micro_usd BIGINT NOT NULL DEFAULT 0, - earned_micro_usd BIGINT NOT NULL DEFAULT 0, - uptime_frac DOUBLE PRECISION NOT NULL DEFAULT 0, - memory_gb INTEGER NOT NULL DEFAULT 0, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (provider_key, epoch_id) - )`, - `CREATE INDEX IF NOT EXISTS idx_floor_draws_epoch ON provider_floor_draws(epoch_id)`, - `CREATE INDEX IF NOT EXISTS idx_floor_draws_account ON provider_floor_draws(account_id, epoch_id)`, - - // System profiler (docs/reports request-profiler plan §2.1/§2.4): two NEW - // append-only telemetry tables, no ALTER on any existing table. The DDL - // text lives in the request/fleet constants below so tests can pin the Go - // column lists to it. Both tables are created empty on first boot, so the - // plain CREATE INDEX statements never lock a populated table; any FUTURE - // index on these tables must be built CONCURRENTLY outside this loop - // (see ensureProviderEarningsJobIndex). The request_waterfall view is NOT - // here — it is applied by hand from store/migrations/request_waterfall.sql. - modelDemandTableDDL, - modelDemandHourlyDDL, - modelDemandRollupFunctionDDL, - modelDemandRollupTriggerDDL, - `CREATE INDEX IF NOT EXISTS idx_model_demand_received ON model_demand_requests (received_at)`, - `CREATE TABLE IF NOT EXISTS model_demand_collection (singleton BOOLEAN PRIMARY KEY CHECK(singleton), started_at TIMESTAMPTZ NOT NULL)`, - `INSERT INTO model_demand_collection (singleton,started_at) VALUES (TRUE,NOW()) ON CONFLICT DO NOTHING`, - requestOutcomesTableDDL, - `CREATE INDEX IF NOT EXISTS idx_request_outcomes_received ON request_outcomes (received_at, coord_request_id)`, - requestProfilesTableDDL, - requestProfilesCreatedIndexDDL, - requestProfilesCoordIndexDDL, - requestProfilesProviderIndexDDL, - fleetSnapshotsTableDDL, - fleetSnapshotsSampledIndexDDL, - // request_profiles / fleet_snapshots are profiler-only and cold (never - // hot-path locked), so idempotent ADD COLUMN IF NOT EXISTS is safe here; - // it upgrades a database that first booted at 02832be21 (before the - // request-shape columns) or before the fleet capability columns. Only - // duplicate_column (two coordinators racing the same ALTER) is swallowed; - // any other failure aborts boot so a half-migrated schema is never served. - `DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS estimated_prompt_tokens INT NOT NULL DEFAULT 0; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS requested_max_tokens INT NOT NULL DEFAULT 0; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS requires_vision BOOL NOT NULL DEFAULT FALSE; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS has_tools BOOL NOT NULL DEFAULT FALSE; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS predictive_bypass TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS reservation_ttft_ceiling_ms DOUBLE PRECISION; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS dispatch_budget_ms BIGINT; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE fleet_snapshots ADD COLUMN IF NOT EXISTS provider_version TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - // free_for_load_gb became nullable (nil = provider did not report it); idempotent. - `ALTER TABLE fleet_snapshots ALTER COLUMN free_for_load_gb DROP NOT NULL`, - `DO $$ BEGIN ALTER TABLE fleet_snapshots ADD COLUMN IF NOT EXISTS model_vision BOOL NOT NULL DEFAULT FALSE; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - `DO $$ BEGIN ALTER TABLE fleet_snapshots ADD COLUMN IF NOT EXISTS template_render_ok BOOL; EXCEPTION WHEN duplicate_column THEN NULL; END $$`, - fleetSnapshotsProviderIndexDDL, - } - - migrations = append(migrations, autopilotDDL) - migrations = append(migrations, appAttestShadowDDL, machineInventoryDDL, appAttestArchiveDDL, appAttestEnrollmentDDL, appAttestReceiptDDL) - migrations = append(migrations, appAttestRevocationDDL, appAttestBuildDDL, appAttestKeyRotationDDL, modelTokenPromotionDDL) - migrations = append(migrations, cacheRoutingHoldersDDL, cacheRoutingHoldersBackfillColumnsDDL, cacheRoutingHoldersDropChainHashDDL, cacheRoutingHoldersExpiryIndexDDL, cacheRoutingHoldersUpdatedIndexDDL, cacheRoutingDemandDDL, cacheRoutingDemandSeenIndexDDL, cacheRoutingMetaDDL) - for i, m := range migrations { - started := time.Now() - _, err := s.pool.Exec(ctx, m) - logStartupMigration(fmt.Sprintf("schema_statement_%03d", i), started, err) - if err != nil { - return fmt.Errorf("migration statement %d failed: %w", i, err) - } - } - - retiredStarted := time.Now() - retiredErr := s.checkRetiredBackfills(ctx) - logStartupMigration("retired_backfills", retiredStarted, retiredErr) - if retiredErr != nil { - return retiredErr - } - - if err := s.ensureProviderRestoreIndexes(ctx); err != nil { - return err - } - - // DAR-349: build the provider_earnings(job_id) partial unique index outside - // the loop — CONCURRENTLY, duplicate-checked, and at most once — so coordinator - // startup never runs a long, lock-holding data migration on this hot table. - if err := s.ensureProviderEarningsJobIndex(ctx); err != nil { - return err - } - if err := s.ensureProviderEarningsWindowIndex(ctx); err != nil { - return err - } - return nil -} - // ensureProviderEarningsJobIndex creates the partial UNIQUE index that backs the // `ON CONFLICT (job_id) WHERE job_id <> ” DO NOTHING` idempotency used by // RecordProviderEarning and CreditProviderAccount. // // DAR-349: this MUST stay cheap and non-blocking on the serving startup path. -// - Fast path: if a valid index already exists, return immediately (every boot -// after the first does no work here). +// - Fast path: if a valid index already exists, return immediately (a +// database that already has the index does no work here). // - It NEVER deletes rows. If existing data would violate uniqueness it fails // loudly with an actionable message rather than running a destructive, // table-locking cleanup at boot (the original outage). @@ -1218,7 +133,7 @@ func (s *PostgresStore) migrate(ctx context.Context) error { func (s *PostgresStore) ensureProviderEarningsJobIndex(ctx context.Context) error { const idxName = "idx_provider_earnings_job" - // Already present AND valid? No-op fast path for every boot after the first. + // Already present AND valid? No-op fast path. var valid bool if err := s.pool.QueryRow(ctx, ` SELECT COALESCE(( @@ -4823,242 +3738,3 @@ func (s *PostgresStore) CloseOpenProviderSessions(ctx context.Context, staleBefo } return int(tag.RowsAffected()), nil } - -// System profiler DDL (boot slice). Column names are the snake_case of the -// RequestProfileRecord / FleetSnapshotRow field names; nullability mirrors Go -// pointer-ness (pointer and json.RawMessage fields are nullable, everything -// else is NOT NULL with a zero default so zero values — 0, empty string, -// false — round-trip as themselves). -// Per-table autovacuum thresholds are tightened because both tables are -// insert-heavy with a rolling retention DELETE. -const ( - requestProfilesTableDDL = `CREATE TABLE IF NOT EXISTS request_profiles ( - id BIGSERIAL PRIMARY KEY, - coord_request_id TEXT NOT NULL, - request_id TEXT NOT NULL, - attempt INT NOT NULL, - backup_of TEXT NOT NULL DEFAULT '', - winning BOOL NOT NULL DEFAULT FALSE, - endpoint TEXT NOT NULL DEFAULT '', - stream BOOL NOT NULL DEFAULT FALSE, - model TEXT NOT NULL DEFAULT '', - public_model TEXT NOT NULL DEFAULT '', - provider_id TEXT NOT NULL DEFAULT '', - provider_version TEXT NOT NULL DEFAULT '', - chip_family TEXT NOT NULL DEFAULT '', - kv_backend TEXT NOT NULL DEFAULT '', - final_status TEXT NOT NULL DEFAULT '', - error_reason TEXT NOT NULL DEFAULT '', - terminal_cause TEXT NOT NULL DEFAULT '', - client_outcome TEXT NOT NULL DEFAULT '', - provider_outcome TEXT NOT NULL DEFAULT '', - client_gone_phase TEXT NOT NULL DEFAULT '', - first_content_budget_ms INT NOT NULL DEFAULT 0, - admission_mode TEXT NOT NULL DEFAULT '', - predictive_bypass TEXT NOT NULL DEFAULT '', - reservation_ttft_ceiling_ms DOUBLE PRECISION, - dispatch_budget_ms BIGINT, - estimated_prompt_tokens INT NOT NULL DEFAULT 0, - requested_max_tokens INT NOT NULL DEFAULT 0, - requires_vision BOOL NOT NULL DEFAULT FALSE, - has_tools BOOL NOT NULL DEFAULT FALSE, - received_at TIMESTAMPTZ NOT NULL, - - auth_done_us BIGINT, - ratelimit_done_us BIGINT, - sealed_open_us BIGINT, - handler_entry_us BIGINT, - parsed_us BIGINT, - reserved_us BIGINT, - media_fetched_us BIGINT, - preflight_done_us BIGINT, - plan_done_us BIGINT, - attempt_start_us BIGINT, - reserve_lock_acquired_us BIGINT, - reserve_done_us BIGINT, - queued_us BIGINT, - dequeued_us BIGINT, - topup_done_us BIGINT, - encrypted_us BIGINT, - write_submitted_us BIGINT, - write_dequeued_us BIGINT, - write_done_us BIGINT, - accepted_us BIGINT, - first_chunk_ingress_us BIGINT, - first_chunk_dequeued_us BIGINT, - first_content_ingress_us BIGINT, - first_content_us BIGINT, - headers_written_us BIGINT, - first_flush_us BIGINT, - last_flush_us BIGINT, - client_gone_us BIGINT, - cancel_sent_us BIGINT, - complete_ingress_us BIGINT, - done_flushed_us BIGINT, - finalized_us BIGINT, - settle_db_us BIGINT, - db_us BIGINT, - db_calls INT NOT NULL DEFAULT 0, - - body_bytes INT NOT NULL DEFAULT 0, - sealed_body_bytes INT NOT NULL DEFAULT 0, - auth_kind TEXT NOT NULL DEFAULT '', - auth_db_read BOOL NOT NULL DEFAULT FALSE, - reserve_mode TEXT NOT NULL DEFAULT '', - media_items INT NOT NULL DEFAULT 0, - media_bytes BIGINT NOT NULL DEFAULT 0, - preflight_outcome TEXT NOT NULL DEFAULT '', - plan_outcome TEXT NOT NULL DEFAULT '', - chunks_in INT NOT NULL DEFAULT 0, - chunks_out INT NOT NULL DEFAULT 0, - bytes_out BIGINT NOT NULL DEFAULT 0, - decrypt_us_total BIGINT NOT NULL DEFAULT 0, - max_chunk_gap_us BIGINT NOT NULL DEFAULT 0, - held_preamble_chunks INT NOT NULL DEFAULT 0, - client_write_err BOOL NOT NULL DEFAULT FALSE, - attempts_total INT NOT NULL DEFAULT 0, - failed_attempts INT NOT NULL DEFAULT 0, - failed_attempts_us BIGINT NOT NULL DEFAULT 0, - backup_launched BOOL NOT NULL DEFAULT FALSE, - backup_won BOOL NOT NULL DEFAULT FALSE, - transport_est_us BIGINT, - slept_us BIGINT, - timing_anomaly BOOL NOT NULL DEFAULT FALSE, - - candidate_set_size INT NOT NULL DEFAULT 0, - scanned INT NOT NULL DEFAULT 0, - gate_rejections JSONB, - runner_up_provider_id TEXT NOT NULL DEFAULT '', - runner_up_cost_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - near_tie_pool_size INT NOT NULL DEFAULT 0, - selection_path TEXT NOT NULL DEFAULT '', - best_idle_provider_id TEXT NOT NULL DEFAULT '', - best_idle_ttft_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - predicted_ttft_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - raw_ttft_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - predicted_decode_tps DOUBLE PRECISION NOT NULL DEFAULT 0, - snapshot_age_ms INT NOT NULL DEFAULT 0, - pending_for_model INT NOT NULL DEFAULT 0, - total_pending INT NOT NULL DEFAULT 0, - capacity_rate_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - cache_discount_ms DOUBLE PRECISION NOT NULL DEFAULT 0, - shadow_would_shed BOOL, - shadow_idle_alternative BOOL, - lock_wait_us BIGINT NOT NULL DEFAULT 0, - scan_us BIGINT NOT NULL DEFAULT 0, - admit_us BIGINT NOT NULL DEFAULT 0, - preflight_us BIGINT NOT NULL DEFAULT 0, - ttft_calibration_ratio DOUBLE PRECISION NOT NULL DEFAULT 0, - prefill_decode_ratio DOUBLE PRECISION NOT NULL DEFAULT 0, - queue_position_at_enqueue INT NOT NULL DEFAULT 0, - queue_depth_at_enqueue INT NOT NULL DEFAULT 0, - drain_trigger TEXT NOT NULL DEFAULT '', - candidates JSONB, - - prov_total_us BIGINT, - prov_first_delta_us BIGINT, - prov_engine_submit_us BIGINT, - prov_engine_admitted_us BIGINT, - prov_prompt_prep_us BIGINT, - prov_load_wait_us BIGINT, - prov_load_cold BOOL, - prov_running_at_admit INT, - prov_waiting_at_admit INT, - prov_kv_bytes_in_use_at_admit BIGINT, - prov_cancel_stage TEXT NOT NULL DEFAULT '', - eng_queue_wait_ns BIGINT, - eng_first_token_ns BIGINT, - eng_prompt_computed_ns BIGINT, - eng_prefill_chunks INT, - eng_decode_steps INT, - eng_mtp_accepted INT, - eng_finish_reason TEXT NOT NULL DEFAULT '', - provider_profile JSONB, - provider_profile_valid BOOL NOT NULL DEFAULT FALSE, - provider_profile_invalid_reason TEXT NOT NULL DEFAULT '', - provider_profile_consistent BOOL, - - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - UNIQUE (request_id, attempt) - ) WITH (autovacuum_vacuum_scale_factor=0.02, autovacuum_analyze_scale_factor=0.01)` - requestProfilesCreatedIndexDDL = `CREATE INDEX IF NOT EXISTS idx_request_profiles_created ON request_profiles(created_at DESC)` - requestProfilesCoordIndexDDL = `CREATE INDEX IF NOT EXISTS idx_request_profiles_coord ON request_profiles(coord_request_id)` - requestProfilesProviderIndexDDL = `CREATE INDEX IF NOT EXISTS idx_request_profiles_provider ON request_profiles(provider_id, created_at DESC)` - - fleetSnapshotsTableDDL = `CREATE TABLE IF NOT EXISTS fleet_snapshots ( - id BIGSERIAL PRIMARY KEY, - sampled_at TIMESTAMPTZ NOT NULL, - provider_id TEXT NOT NULL, - model TEXT NOT NULL DEFAULT '', - eligibility_reason TEXT NOT NULL DEFAULT '', - slot_state TEXT NOT NULL DEFAULT '', - num_running INT NOT NULL DEFAULT 0, - num_waiting INT NOT NULL DEFAULT 0, - queued_prefill_tokens INT NOT NULL DEFAULT 0, - partial_prefill_rows INT NOT NULL DEFAULT 0, - active_token_budget_used BIGINT NOT NULL DEFAULT 0, - active_token_budget_max BIGINT NOT NULL DEFAULT 0, - kv_bytes_in_use BIGINT NOT NULL DEFAULT 0, - kv_bytes_capacity BIGINT NOT NULL DEFAULT 0, - observed_decode_tps DOUBLE PRECISION NOT NULL DEFAULT 0, - observed_prefill_tps DOUBLE PRECISION NOT NULL DEFAULT 0, - isolated_prefill_tps DOUBLE PRECISION NOT NULL DEFAULT 0, - ewma_initialized BOOL, - max_concurrency INT NOT NULL DEFAULT 0, - pending_count INT NOT NULL DEFAULT 0, - effective_cap INT NOT NULL DEFAULT 0, - cooldown_active BOOL NOT NULL DEFAULT FALSE, - breaker_open BOOL NOT NULL DEFAULT FALSE, - clamp_active BOOL NOT NULL DEFAULT FALSE, - ejected BOOL NOT NULL DEFAULT FALSE, - gpu_memory_active_gb DOUBLE PRECISION NOT NULL DEFAULT 0, - gpu_memory_peak_gb DOUBLE PRECISION NOT NULL DEFAULT 0, - free_for_load_gb DOUBLE PRECISION, - memory_pressure DOUBLE PRECISION NOT NULL DEFAULT 0, - cpu_usage DOUBLE PRECISION NOT NULL DEFAULT 0, - thermal_state TEXT NOT NULL DEFAULT '', - low_power_mode BOOL, - memory_pressure_level TEXT NOT NULL DEFAULT '', - steps_executed BIGINT NOT NULL DEFAULT 0, - step_wall_ns_total BIGINT NOT NULL DEFAULT 0, - decode_rows_total BIGINT NOT NULL DEFAULT 0, - prefill_tokens_total BIGINT NOT NULL DEFAULT 0, - mtp_rounds_total BIGINT NOT NULL DEFAULT 0, - mtp_proposed_total BIGINT NOT NULL DEFAULT 0, - mtp_accepted_total BIGINT NOT NULL DEFAULT 0, - heartbeat_age_ms INT NOT NULL DEFAULT 0, - wedge_suspected BOOL NOT NULL DEFAULT FALSE, - eval_in_flight_ms BIGINT NOT NULL DEFAULT 0, - requests_served BIGINT NOT NULL DEFAULT 0, - tokens_generated BIGINT NOT NULL DEFAULT 0, - cancellations_received BIGINT NOT NULL DEFAULT 0, - cancellations_before_output BIGINT NOT NULL DEFAULT 0, - cancellations_partial_complete BIGINT NOT NULL DEFAULT 0, - generation_errors_after_output BIGINT NOT NULL DEFAULT 0, - chunk_encryption_errors BIGINT NOT NULL DEFAULT 0, - stream_closed_without_terminal BIGINT NOT NULL DEFAULT 0, - cancel_during_model_load BIGINT NOT NULL DEFAULT 0, - usage_gaps BIGINT NOT NULL DEFAULT 0, - cancel_stage_pre_accept_total BIGINT NOT NULL DEFAULT 0, - cancel_stage_pre_engine_total BIGINT NOT NULL DEFAULT 0, - cancel_stage_prefill_total BIGINT NOT NULL DEFAULT 0, - cancel_stage_decode_total BIGINT NOT NULL DEFAULT 0, - cancel_stage_post_terminal_total BIGINT NOT NULL DEFAULT 0, - tokens_after_cancel_total BIGINT NOT NULL DEFAULT 0, - cancel_abort_ns_sum BIGINT NOT NULL DEFAULT 0, - queue_depth_total INT NOT NULL DEFAULT 0, - queue_depth_by_model JSONB, - inflight_requests INT NOT NULL DEFAULT 0, - reserve_lock_wait_p95_us BIGINT NOT NULL DEFAULT 0, - profile_sink_depth INT NOT NULL DEFAULT 0, - profile_sink_dropped_total BIGINT NOT NULL DEFAULT 0, - route_sink_dropped_total BIGINT NOT NULL DEFAULT 0, - unknown_request_frames_total BIGINT NOT NULL DEFAULT 0, - goroutines INT NOT NULL DEFAULT 0, - provider_version TEXT NOT NULL DEFAULT '', - model_vision BOOL NOT NULL DEFAULT FALSE, - template_render_ok BOOL - ) WITH (autovacuum_vacuum_scale_factor=0.02, autovacuum_analyze_scale_factor=0.01)` - fleetSnapshotsSampledIndexDDL = `CREATE INDEX IF NOT EXISTS idx_fleet_snapshots_sampled ON fleet_snapshots(sampled_at DESC)` - fleetSnapshotsProviderIndexDDL = `CREATE INDEX IF NOT EXISTS idx_fleet_snapshots_provider ON fleet_snapshots(provider_id, sampled_at DESC)` -) diff --git a/coordinator/store/postgres_autopilot.go b/coordinator/store/postgres_autopilot.go index 1e66988536..016e1f25cf 100644 --- a/coordinator/store/postgres_autopilot.go +++ b/coordinator/store/postgres_autopilot.go @@ -6,11 +6,6 @@ import ( "time" ) -const autopilotDDL = `CREATE TABLE IF NOT EXISTS autopilot_events ( - command_id TEXT NOT NULL, phase TEXT NOT NULL, at TIMESTAMPTZ NOT NULL, - record JSONB NOT NULL, PRIMARY KEY(command_id,phase) -); CREATE INDEX IF NOT EXISTS autopilot_events_at ON autopilot_events(at)` - func (s *PostgresStore) RecordAutopilot(ctx context.Context, records []AutopilotRecord) error { for _, r := range records { if err := validateAutopilotRecord(r); err != nil { diff --git a/coordinator/store/postgres_billing_columns_test.go b/coordinator/store/postgres_billing_columns_test.go index e03f3e9637..e6c0381751 100644 --- a/coordinator/store/postgres_billing_columns_test.go +++ b/coordinator/store/postgres_billing_columns_test.go @@ -31,6 +31,7 @@ func TestPostgresBillingColumnMigrationFailureAbortsStartup(t *testing.T) { if _, err := s.pool.Exec(ctx, "ALTER TABLE "+tc.table+" DROP COLUMN "+tc.column); err != nil { t.Fatalf("drop %s.%s: %v", tc.table, tc.column, err) } + forgetMigrationVersions(t, s) s.Close() // A long reader holds the table, so the ADD COLUMN cannot take its diff --git a/coordinator/store/postgres_log_report_privacy.go b/coordinator/store/postgres_log_report_privacy.go deleted file mode 100644 index f90fe08e70..0000000000 --- a/coordinator/store/postgres_log_report_privacy.go +++ /dev/null @@ -1,36 +0,0 @@ -package store - -const providerLogReportSerialGuardFunction = `CREATE OR REPLACE FUNCTION clear_provider_log_report_serial() -RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN - NEW.serial_number := ''; - RETURN NEW; -END $$` - -const providerLogReportSerialGuardTrigger = `DO $$ BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM pg_trigger tg - JOIN pg_class target ON target.oid = tg.tgrelid - JOIN pg_namespace ns ON ns.oid = target.relnamespace - WHERE tg.tgname = 'clear_provider_log_report_serial' - AND NOT tg.tgisinternal - AND target.relname = 'provider_log_reports' - AND ns.nspname = current_schema() - ) THEN - CREATE TRIGGER clear_provider_log_report_serial - BEFORE INSERT OR UPDATE OF serial_number ON provider_log_reports - FOR EACH ROW EXECUTE FUNCTION clear_provider_log_report_serial(); - END IF; -END $$` - -const providerLogReportSerialScrubMigration = `DO $$ BEGIN - IF NOT EXISTS ( - SELECT 1 FROM schema_migrations - WHERE id = 'scrub_provider_log_report_serials_v1' - ) THEN - UPDATE provider_log_reports SET serial_number = '' WHERE serial_number <> ''; - INSERT INTO schema_migrations (id) - VALUES ('scrub_provider_log_report_serials_v1') - ON CONFLICT (id) DO NOTHING; - END IF; -END $$` diff --git a/coordinator/store/postgres_log_report_privacy_test.go b/coordinator/store/postgres_log_report_privacy_test.go index ed03887427..b67da2b50c 100644 --- a/coordinator/store/postgres_log_report_privacy_test.go +++ b/coordinator/store/postgres_log_report_privacy_test.go @@ -8,11 +8,24 @@ import ( "time" ) +// The log-report serial scrub and its write guard are baseline statements. +func providerLogReportSerialGuardFunction(t testing.TB) string { + return baselineStatement(t, "CREATE OR REPLACE FUNCTION clear_provider_log_report_serial()") +} + +func providerLogReportSerialGuardTrigger(t testing.TB) string { + return baselineStatement(t, "CREATE TRIGGER clear_provider_log_report_serial") +} + +func providerLogReportSerialScrubMigration(t testing.TB) string { + return baselineStatement(t, "UPDATE provider_log_reports SET serial_number = ''") +} + func TestProviderLogReportSerialPrivacyMigration(t *testing.T) { combined := strings.Join([]string{ - providerLogReportSerialGuardFunction, - providerLogReportSerialGuardTrigger, - providerLogReportSerialScrubMigration, + providerLogReportSerialGuardFunction(t), + providerLogReportSerialGuardTrigger(t), + providerLogReportSerialScrubMigration(t), }, "\n") for _, required := range []string{ "NEW.serial_number := ''", @@ -64,9 +77,9 @@ func TestProviderLogReportSerialPrivacyMigrationPostgres(t *testing.T) { ON provider_log_reports(serial_number, created_at DESC)`, `INSERT INTO provider_log_reports (serial_number, account_id, log_data) VALUES ('historical-hardware-identity', 'account-1', '\x01')`, - providerLogReportSerialGuardFunction, - providerLogReportSerialGuardTrigger, - providerLogReportSerialScrubMigration, + providerLogReportSerialGuardFunction(t), + providerLogReportSerialGuardTrigger(t), + providerLogReportSerialScrubMigration(t), `DROP INDEX IF EXISTS idx_log_reports_serial`, } { if _, err := conn.Exec(ctx, statement); err != nil { @@ -126,9 +139,9 @@ func TestProviderLogReportSerialPrivacyMigrationPostgres(t *testing.T) { } for _, statement := range []string{ - providerLogReportSerialGuardFunction, - providerLogReportSerialGuardTrigger, - providerLogReportSerialScrubMigration, + providerLogReportSerialGuardFunction(t), + providerLogReportSerialGuardTrigger(t), + providerLogReportSerialScrubMigration(t), `DROP INDEX IF EXISTS idx_log_reports_serial`, } { if _, err := conn.Exec(ctx, statement); err != nil { diff --git a/coordinator/store/postgres_migrations.go b/coordinator/store/postgres_migrations.go new file mode 100644 index 0000000000..ecbd4984e3 --- /dev/null +++ b/coordinator/store/postgres_migrations.go @@ -0,0 +1,155 @@ +package store + +import ( + "context" + "database/sql" + "embed" + "errors" + "fmt" + "io/fs" + "log/slog" + "strconv" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5/stdlib" + "github.com/pressly/goose/v3" + "github.com/pressly/goose/v3/lock" +) + +// Schema changes are numbered goose migrations. SQL files live in +// schema/migrations; the Go steps are listed in goMigrations. Goose applies +// each version once and records it in migrationVersionTable. The +// schema_migrations table is a different thing: it holds the markers of the +// one-shot data migrations in the baseline. +// +//go:embed schema/migrations/*.sql +var migrationFiles embed.FS + +const ( + migrationDir = "schema/migrations" + migrationVersionTable = "goose_db_version" + + // A DDL statement that waits for a lock blocks every later query on the + // table. The lock timeout stops that queue after a few seconds; migrate + // then tries again. + migrationLockTimeout = 3 * time.Second + // Upper bound for one statement in the migration session. + migrationStatementTimeout = 10 * time.Minute + migrationAttempts = 3 +) + +// lockNotAvailable is the SQLSTATE of a lock_timeout failure. +const lockNotAvailable = "55P03" + +// migrate applies every pending migration. Coordinators that start together +// take turns on the goose advisory lock: the first applies the pending +// versions and the others find nothing left to apply. A lock timeout is +// retried a few times, with a short pause. +func (s *PostgresStore) migrate(ctx context.Context) error { + for attempt := 1; ; attempt++ { + err := s.migrateOnce(ctx) + if err == nil || attempt == migrationAttempts || !isLockTimeout(err) { + return err + } + slog.Warn("postgres migration hit lock_timeout; retrying", "attempt", attempt) + select { + case <-ctx.Done(): + return err + case <-time.After(time.Duration(attempt) * time.Second): + } + } +} + +func isLockTimeout(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == lockNotAvailable +} + +// migrateOnce runs goose once on a small pool of its own, so the session +// timeouts apply to the migration connections and not to the serving pool. +func (s *PostgresStore) migrateOnce(ctx context.Context) error { + cfg := s.pool.Config() + // One connection holds the advisory lock and runs the SQL migrations; goose + // records Go migration versions on a second one. + cfg.MinConns = 0 + cfg.MaxConns = 2 + // A timeout set in the database URL wins over these defaults. + for name, value := range map[string]time.Duration{ + "lock_timeout": migrationLockTimeout, + "statement_timeout": migrationStatementTimeout, + } { + if _, set := cfg.ConnConfig.RuntimeParams[name]; !set { + cfg.ConnConfig.RuntimeParams[name] = strconv.FormatInt(value.Milliseconds(), 10) + } + } + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return fmt.Errorf("store: open migration pool: %w", err) + } + defer pool.Close() + db := stdlib.OpenDBFromPool(pool) + defer db.Close() + + provider, err := s.newMigrationProvider(db) + if err != nil { + return err + } + results, err := provider.Up(ctx) + var partial *goose.PartialError + if errors.As(err, &partial) { + results = append(partial.Applied, partial.Failed) + } + for _, r := range results { + result := "applied" + if r.Error != nil { + result = "failed" + } + slog.Info("postgres migration", "version", r.Source.Version, "result", result, + "duration_ms", r.Duration.Milliseconds()) + } + if err != nil { + return fmt.Errorf("store: apply migrations: %w", err) + } + return nil +} + +func (s *PostgresStore) newMigrationProvider(db *sql.DB) (*goose.Provider, error) { + fsys, err := fs.Sub(migrationFiles, migrationDir) + if err != nil { + return nil, fmt.Errorf("store: open embedded migrations: %w", err) + } + locker, err := lock.NewPostgresSessionLocker() + if err != nil { + return nil, fmt.Errorf("store: create migration locker: %w", err) + } + provider, err := goose.NewProvider(goose.DialectPostgres, db, fsys, + goose.WithSessionLocker(locker), + goose.WithTableName(migrationVersionTable), + goose.WithDisableGlobalRegistry(true), + goose.WithGoMigrations(s.goMigrations()...), + ) + if err != nil { + return nil, fmt.Errorf("store: create migration provider: %w", err) + } + return provider, nil +} + +// goMigrations are the startup steps that ran after the old boot-time DDL +// loop, in the same order. They keep their code and run on the store pool, +// which sets no session timeouts, as before: a CREATE INDEX CONCURRENTLY that +// times out leaves an invalid index, and these steps do not repair one. +func (s *PostgresStore) goMigrations() []*goose.Migration { + step := func(version int64, run func(context.Context) error) *goose.Migration { + return goose.NewGoMigration(version, &goose.GoFunc{ + RunDB: func(ctx context.Context, _ *sql.DB) error { return run(ctx) }, + }, nil) + } + return []*goose.Migration{ + step(2, s.checkRetiredBackfills), + step(3, s.ensureProviderRestoreIndexes), + step(4, s.ensureProviderEarningsJobIndex), + step(5, s.ensureProviderEarningsWindowIndex), + } +} diff --git a/coordinator/store/postgres_migrations_test.go b/coordinator/store/postgres_migrations_test.go new file mode 100644 index 0000000000..c168ee408e --- /dev/null +++ b/coordinator/store/postgres_migrations_test.go @@ -0,0 +1,186 @@ +package store + +import ( + "bytes" + "context" + "log/slog" + "strings" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/stdlib" + "github.com/pressly/goose/v3" +) + +// A fresh database built by goose has exactly the schema that the pre-goose +// boot loop built (schema/schema.sql). +func TestMigrationsBuildCheckedInSchema(t *testing.T) { + ctx := context.Background() + gooseURL := newThrowawayTestDatabase(t) + s, err := NewPostgres(ctx, Config{DatabaseURL: gooseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + + dumpPool := openTestPool(t, newThrowawayTestDatabase(t)) + loadSchemaFile(t, dumpPool) + + assertSameSchema(t, "schema/schema.sql", schemaSnapshot(t, dumpPool), "goose", schemaSnapshot(t, s.pool)) +} + +// A database that a pre-goose binary migrated meets goose for the first +// time: every migration runs, and nothing changes except the new goose +// version table. +func TestMigrationsLeaveLegacyDatabaseUnchanged(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + pool := openTestPool(t, databaseURL) + loadSchemaFile(t, pool) + // The rows the pre-goose boot leaves on a fresh database. + for _, stmt := range []string{ + `INSERT INTO schema_migrations (id, applied_at) VALUES + ('scrub_provider_log_report_serials_v1', '2026-01-02T03:04:05Z'), + ('scrub_inference_route_cache_affinity_v1', '2026-01-02T03:04:05Z'), + ('backfill_withdrawable_balance_v1', '2026-01-02T03:04:05Z'), + ('backfill_usage_totals_v1', '2026-01-02T03:04:05Z'), + ('backfill_earnings_summary_v1', '2026-01-02T03:04:05Z')`, + `INSERT INTO usage_totals VALUES (1, 0, 0, 0)`, + `INSERT INTO model_demand_collection VALUES (TRUE, '2026-01-02T03:04:05Z')`, + } { + if _, err := pool.Exec(ctx, stmt); err != nil { + t.Fatalf("seed legacy rows: %v", err) + } + } + const rowsSQL = `SELECT 'marker ' || id || ' ' || applied_at FROM schema_migrations + UNION ALL SELECT 'usage_totals ' || id || ' ' || total_requests FROM usage_totals + UNION ALL SELECT 'collection ' || started_at FROM model_demand_collection + ORDER BY 1` + readRows := func() []string { + rows, err := pool.Query(ctx, rowsSQL) + if err != nil { + t.Fatalf("read rows: %v", err) + } + defer rows.Close() + var out []string + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatalf("scan row: %v", err) + } + out = append(out, line) + } + return out + } + schemaBefore, rowsBefore := schemaSnapshot(t, pool), readRows() + + s, err := NewPostgres(ctx, Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres on legacy database: %v", err) + } + t.Cleanup(s.Close) + + assertSameSchema(t, "legacy", schemaBefore, "after goose", schemaSnapshot(t, pool)) + assertSameSchema(t, "legacy rows", rowsBefore, "rows after goose", readRows()) + var versions []int64 + rows, err := pool.Query(ctx, `SELECT version_id FROM `+migrationVersionTable+` ORDER BY id`) + if err != nil { + t.Fatalf("read goose versions: %v", err) + } + defer rows.Close() + for rows.Next() { + var v int64 + if err := rows.Scan(&v); err != nil { + t.Fatal(err) + } + versions = append(versions, v) + } + if len(versions) != 6 || versions[0] != 0 || versions[5] != 5 { + t.Fatalf("goose versions = %v, want 0 through 5", versions) + } +} + +// Two coordinators that start together: the goose advisory lock lets one +// apply the migrations, and the other then finds nothing to apply. +func TestConcurrentMigrationsApplyOnce(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + runners := make([]*goose.Provider, 2) + for i := range runners { + s := &PostgresStore{pool: openTestPool(t, databaseURL)} + db := stdlib.OpenDBFromPool(s.pool) + t.Cleanup(func() { _ = db.Close() }) + provider, err := s.newMigrationProvider(db) + if err != nil { + t.Fatal(err) + } + runners[i] = provider + } + + var wg sync.WaitGroup + applied := make([]int, len(runners)) + errs := make([]error, len(runners)) + for i, provider := range runners { + wg.Add(1) + go func() { + defer wg.Done() + results, err := provider.Up(ctx) + applied[i], errs[i] = len(results), err + }() + } + wg.Wait() + for i, err := range errs { + if err != nil { + t.Fatalf("runner %d: %v", i, err) + } + } + if applied[0]+applied[1] != 5 || (applied[0] != 0 && applied[1] != 0) { + t.Fatalf("applied = %v, want one runner to apply all 5 versions and the other none", applied) + } + var rows, distinct int + pool := openTestPool(t, databaseURL) + if err := pool.QueryRow(ctx, `SELECT count(*), count(DISTINCT version_id) FROM `+migrationVersionTable).Scan(&rows, &distinct); err != nil { + t.Fatal(err) + } + if rows != 6 || distinct != 6 { + t.Fatalf("goose version rows = %d (%d distinct), want 6", rows, distinct) + } +} + +// A DDL statement that waits longer than the lock timeout fails, and migrate +// runs goose again once the lock is free. +func TestMigrateRetriesLockTimeout(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + s, err := NewPostgres(ctx, Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + forgetMigrationVersions(t, s) + + holder := openTestPool(t, databaseURL) + tx, err := holder.Begin(ctx) + if err != nil { + t.Fatal(err) + } + // The baseline alters provider_trust_reuse outside an exception block, + // so the lock timeout reaches migrate. + if _, err := tx.Exec(ctx, `LOCK TABLE provider_trust_reuse IN ACCESS EXCLUSIVE MODE`); err != nil { + t.Fatal(err) + } + release := time.AfterFunc(migrationLockTimeout+time.Second, func() { _ = tx.Rollback(context.Background()) }) + defer release.Stop() + + var logs bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + defer slog.SetDefault(previous) + if err := s.migrate(ctx); err != nil { + t.Fatalf("migrate with a held lock: %v", err) + } + if !strings.Contains(logs.String(), "hit lock_timeout; retrying") { + t.Fatalf("migrate did not retry after a lock timeout; logs:\n%s", logs.String()) + } +} diff --git a/coordinator/store/postgres_model_demand.go b/coordinator/store/postgres_model_demand.go index 4d4f94e4b9..242ef12bda 100644 --- a/coordinator/store/postgres_model_demand.go +++ b/coordinator/store/postgres_model_demand.go @@ -8,18 +8,6 @@ import ( "github.com/jackc/pgx/v5" ) -const modelDemandTableDDL = `CREATE TABLE IF NOT EXISTS model_demand_requests ( - id BIGSERIAL UNIQUE, - coord_request_id TEXT PRIMARY KEY, - received_at TIMESTAMPTZ NOT NULL, - model TEXT NOT NULL, - consumer_hash TEXT NOT NULL, - outcome TEXT NOT NULL, - http_status INTEGER NOT NULL, - revision BIGINT NOT NULL, - evidence_conflict BOOLEAN NOT NULL DEFAULT FALSE -)` - // Retained public evidence remains authoritative after the diagnostic ledger // expires. Receipt/model/consumer identity is immutable at every revision. const modelDemandProjectionConflictSQL = `model_demand_requests.evidence_conflict OR EXCLUDED.evidence_conflict diff --git a/coordinator/store/postgres_request_outcomes.go b/coordinator/store/postgres_request_outcomes.go index 07825530eb..c88b85cbda 100644 --- a/coordinator/store/postgres_request_outcomes.go +++ b/coordinator/store/postgres_request_outcomes.go @@ -8,18 +8,6 @@ import ( "github.com/jackc/pgx/v5" ) -// Typed cohort/revision columns keep time-window reads indexed. The versioned -// payload contains only the fixed, bounded RequestOutcomeRecord schema. -const requestOutcomesTableDDL = `CREATE TABLE IF NOT EXISTS request_outcomes ( - id BIGSERIAL UNIQUE, - coord_request_id TEXT PRIMARY KEY CHECK (coord_request_id <> ''), - received_at TIMESTAMPTZ NOT NULL, - updated_at TIMESTAMPTZ NOT NULL, - revision BIGINT NOT NULL, - evidence_conflict BOOLEAN NOT NULL DEFAULT FALSE, - record JSONB NOT NULL -)` - func (s *PostgresStore) RecordRequestOutcomes(ctx context.Context, records []RequestOutcomeRecord) error { for _, r := range records { if err := validateRequestOutcome(r); err != nil { diff --git a/coordinator/store/postgres_retired_backfills_test.go b/coordinator/store/postgres_retired_backfills_test.go index 2195988549..dfa7352cc6 100644 --- a/coordinator/store/postgres_retired_backfills_test.go +++ b/coordinator/store/postgres_retired_backfills_test.go @@ -13,7 +13,9 @@ import ( // to pin checkRetiredBackfills: a fresh database records the retired // backfill markers and keeps booting once it holds data, a prod-shaped // database with the markers boots untouched, and a database holding data a -// retired backfill never processed refuses to start. +// retired backfill never processed refuses to start. Goose runs the guard +// once, so a reboot below first forgets the goose versions: the guard runs +// again only on a database that a pre-goose binary migrated. func bootRetiredBackfillStore(t *testing.T, databaseURL string) (*PostgresStore, error) { t.Helper() @@ -90,7 +92,8 @@ func TestRetiredBackfillGuardRecordsMarkersOnFreshDatabase(t *testing.T) { } // The same database, now holding data in every retired-backfill table, - // must keep booting. + // must keep booting when the guard runs again. + forgetMigrationVersions(t, s) again := mustBootRetiredBackfillStore(t, databaseURL) if totals, err := again.UsageTotals(); err != nil || totals.Requests != 1 { t.Fatalf("usage totals after reboot = %+v, %v; want the counter preserved", totals, err) @@ -129,6 +132,7 @@ func TestRetiredBackfillGuardBootsProdShapedDatabase(t *testing.T) { mustExecRetiredBackfill(t, s, `UPDATE usage_totals SET total_requests = 41, total_prompt_tokens = 4100, total_completion_tokens = 820 WHERE id = 1`) + forgetMigrationVersions(t, s) s.Close() again := mustBootRetiredBackfillStore(t, databaseURL) @@ -156,6 +160,7 @@ func TestRetiredBackfillGuardRefusesDataWithoutMarker(t *testing.T) { // row either. mustExecRetiredBackfill(t, s, `DELETE FROM usage_totals`) } + forgetMigrationVersions(t, s) s.Close() _, err := bootRetiredBackfillStore(t, databaseURL) @@ -194,6 +199,7 @@ func TestRetiredBackfillGuardRefusesBalancesWithoutWithdrawableColumn(t *testing // missing. mustExecRetiredBackfill(t, s, `DELETE FROM schema_migrations WHERE id = 'backfill_withdrawable_balance_v1'`) mustExecRetiredBackfill(t, s, `ALTER TABLE balances DROP COLUMN withdrawable_micro_usd`) + forgetMigrationVersions(t, s) s.Close() _, err := bootRetiredBackfillStore(t, databaseURL) diff --git a/coordinator/store/postgres_test.go b/coordinator/store/postgres_test.go index 982b1893f3..2a0540e408 100644 --- a/coordinator/store/postgres_test.go +++ b/coordinator/store/postgres_test.go @@ -543,10 +543,8 @@ func TestPostgresMigrateNeverDeletesModelPrices(t *testing.T) { } } - // Simulated restart. - if err := s.migrate(ctx); err != nil { - t.Fatalf("migrate: %v", err) - } + // Simulated first goose boot, which replays the baseline. + replayMigrations(t, s) for _, p := range prices { if mp, ok := s.GetModelPrice(p.account, p.model); !ok || mp.InputPrice != 50_000 || mp.OutputPrice != 200_000 { diff --git a/coordinator/store/profile_prediction_migration_test.go b/coordinator/store/profile_prediction_migration_test.go index 01d3200b94..c0116a7c3c 100644 --- a/coordinator/store/profile_prediction_migration_test.go +++ b/coordinator/store/profile_prediction_migration_test.go @@ -23,9 +23,7 @@ func TestPostgresPredictionColumnsUpgradeKeepsUnknownHistory(t *testing.T) { t.Fatal(err) } for i := 0; i < 2; i++ { - if err := s.migrate(ctx); err != nil { - t.Fatalf("upgrade %d: %v", i, err) - } + replayMigrations(t, s) } rows := s.RequestProfilesSinceFiltered(time.Time{}, RequestProfileFilter{}) if len(rows) != 1 || rows[0].RequestID != old.RequestID || rows[0].AdmissionMode != "" || rows[0].PredictiveBypass != "" || rows[0].ReservationTTFTCeilingMs != nil || rows[0].DispatchBudgetMs != nil { diff --git a/coordinator/store/profile_records_test.go b/coordinator/store/profile_records_test.go index e1c69ad53a..073956d637 100644 --- a/coordinator/store/profile_records_test.go +++ b/coordinator/store/profile_records_test.go @@ -148,7 +148,7 @@ func TestRequestProfileColumnsStayAligned(t *testing.T) { t.Fatalf("duplicate request_profiles column %q", col) } seen[col] = true - if !strings.Contains(requestProfilesTableDDL, "\n\t\t\t"+col+" ") { + if !strings.Contains(baselineStatement(t, "CREATE TABLE IF NOT EXISTS request_profiles ("), "\n\t\t\t"+col+" ") { t.Errorf("request_profiles DDL lacks column %q", col) } } @@ -170,7 +170,7 @@ func TestRequestProfileColumnsStayAligned(t *testing.T) { t.Fatalf("duplicate fleet_snapshots column %q", col) } seen[col] = true - if !strings.Contains(fleetSnapshotsTableDDL, "\n\t\t\t"+col+" ") { + if !strings.Contains(baselineStatement(t, "CREATE TABLE IF NOT EXISTS fleet_snapshots ("), "\n\t\t\t"+col+" ") { t.Errorf("fleet_snapshots DDL lacks column %q", col) } } @@ -547,10 +547,9 @@ func TestPostgresPruneTelemetryRespectsBatch(t *testing.T) { func TestPostgresProfilerMigrationIdempotent(t *testing.T) { s := testPostgresStore(t) ctx := context.Background() - // NewPostgres already ran migrate once; a restart runs it again. - if err := s.migrate(ctx); err != nil { - t.Fatalf("re-running migrate: %v", err) - } + // NewPostgres already ran the migrations once; replaying them on the + // migrated database must change nothing. + replayMigrations(t, s) for _, idx := range []string{ "idx_request_profiles_created", "idx_request_profiles_coord", "idx_request_profiles_provider", "request_profiles_request_id_attempt_key", diff --git a/coordinator/store/provider_earnings_startup_test.go b/coordinator/store/provider_earnings_startup_test.go index 3dff4c66a9..cad76ea43e 100644 --- a/coordinator/store/provider_earnings_startup_test.go +++ b/coordinator/store/provider_earnings_startup_test.go @@ -31,24 +31,22 @@ func TestMigrate_NoBootTimeProviderEarningsDedupe(t *testing.T) { // TestProviderEarningsJobIndex_BootSafe verifies the safe replacement: startup // builds a valid partial unique index on provider_earnings(job_id) without a -// dedupe DELETE, migrate() is re-entrant, and the index backs the idempotent +// dedupe DELETE, the migrations are re-entrant, and the index backs the idempotent // ON CONFLICT write path. Runs only with DATABASE_URL (throwaway test DB). func TestProviderEarningsJobIndex_BootSafe(t *testing.T) { s := testPostgresStore(t) // t.Skip()s when DATABASE_URL is unset - ctx := context.Background() // NewPostgres -> migrate -> ensureProviderEarningsJobIndex left a VALID index. if !jobIndexValid(t, s) { t.Fatal("idx_provider_earnings_job missing or invalid after startup") } - // Re-entrancy: a coordinator restart re-runs migrate() and must not error or - // do heavy work (the valid-index fast path makes index creation a no-op). - if err := s.migrate(ctx); err != nil { - t.Fatalf("re-running migrate (restart): %v", err) - } + // Re-entrancy: replaying the migrations (the first goose boot of a + // database that already has the index) must not error or do heavy work + // (the valid-index fast path makes index creation a no-op). + replayMigrations(t, s) if !jobIndexValid(t, s) { - t.Fatal("idx_provider_earnings_job invalid after re-running migrate") + t.Fatal("idx_provider_earnings_job invalid after replaying migrations") } // RecordProviderEarning is idempotent for a non-empty job_id (ON CONFLICT diff --git a/coordinator/store/provider_earnings_window_index_test.go b/coordinator/store/provider_earnings_window_index_test.go index 06c17b57f8..1b28db84c9 100644 --- a/coordinator/store/provider_earnings_window_index_test.go +++ b/coordinator/store/provider_earnings_window_index_test.go @@ -53,12 +53,11 @@ func TestProviderEarningsWindowIndexBootSafe(t *testing.T) { } assertWindowIndex("after startup") - // A restart re-runs migrate(): the valid-index fast path and the - // already-set reloption make both steps no-ops rather than errors. - if err := s.migrate(ctx); err != nil { - t.Fatalf("re-running migrate (restart): %v", err) - } - assertWindowIndex("after re-running migrate") + // Replaying the migrations (the first goose boot of a database that + // already has the index): the valid-index fast path and the already-set + // reloption make both steps no-ops rather than errors. + replayMigrations(t, s) + assertWindowIndex("after replaying migrations") // The index is on created_at and is a working BRIN index: summarising a // freshly inserted row's block range must succeed. (Which index the planner diff --git a/coordinator/store/provider_trust_reuse_test.go b/coordinator/store/provider_trust_reuse_test.go index 4037df7214..2d8dea42aa 100644 --- a/coordinator/store/provider_trust_reuse_test.go +++ b/coordinator/store/provider_trust_reuse_test.go @@ -269,12 +269,8 @@ func TestPostgresProviderTrustReuseLegacyMigrationIsIdempotent(t *testing.T) { ); err != nil { t.Fatalf("insert legacy row: %v", err) } - if err := st.migrate(ctx); err != nil { - t.Fatalf("first migration: %v", err) - } - if err := st.migrate(ctx); err != nil { - t.Fatalf("second migration: %v", err) - } + replayMigrations(t, st) + replayMigrations(t, st) rows, err := st.ListProviderTrustReuse(ctx) if err != nil { t.Fatalf("list migrated row: %v", err) diff --git a/coordinator/store/route_telemetry_test.go b/coordinator/store/route_telemetry_test.go index f323e238f1..ceb01b234f 100644 --- a/coordinator/store/route_telemetry_test.go +++ b/coordinator/store/route_telemetry_test.go @@ -9,18 +9,31 @@ import ( "time" ) +// The cache-affinity scrub and its write guard are baseline statements. +func legacyCacheAffinityGuardFunction(t testing.TB) string { + return baselineStatement(t, "CREATE OR REPLACE FUNCTION clear_legacy_cache_affinity_key()") +} + +func legacyCacheAffinityGuardTrigger(t testing.TB) string { + return baselineStatement(t, "CREATE TRIGGER clear_legacy_cache_affinity_key") +} + +func legacyCacheAffinityScrubMigration(t testing.TB) string { + return baselineStatement(t, "VALUES ('scrub_inference_route_cache_affinity_v1')") +} + func TestLegacyCacheAffinityScrubMigration(t *testing.T) { for _, required := range []string{ "scrub_inference_route_cache_affinity_v1", "UPDATE inference_routes SET cache_affinity_key = ''", "INSERT INTO schema_migrations", } { - if !strings.Contains(legacyCacheAffinityScrubMigration, required) { + if !strings.Contains(legacyCacheAffinityScrubMigration(t), required) { t.Fatalf("legacy cache-affinity scrub migration missing %q", required) } } - if !strings.Contains(legacyCacheAffinityGuardFunction, "NEW.cache_affinity_key := ''") || - !strings.Contains(legacyCacheAffinityGuardTrigger, "BEFORE INSERT OR UPDATE OF cache_affinity_key") { + if !strings.Contains(legacyCacheAffinityGuardFunction(t), "NEW.cache_affinity_key := ''") || + !strings.Contains(legacyCacheAffinityGuardTrigger(t), "BEFORE INSERT OR UPDATE OF cache_affinity_key") { t.Fatal("legacy cache-affinity write guard is incomplete") } for _, required := range []string{ @@ -28,7 +41,7 @@ func TestLegacyCacheAffinityScrubMigration(t *testing.T) { "target.relname = 'inference_routes'", "ns.nspname = current_schema()", } { - if !strings.Contains(legacyCacheAffinityGuardTrigger, required) { + if !strings.Contains(legacyCacheAffinityGuardTrigger(t), required) { t.Fatalf("legacy cache-affinity trigger existence check missing %q", required) } } @@ -79,9 +92,9 @@ func TestLegacyCacheAffinityMigrationScrubsAndInstallsScopedTrigger(t *testing.T } for _, migration := range []string{ - legacyCacheAffinityGuardFunction, - legacyCacheAffinityGuardTrigger, - legacyCacheAffinityScrubMigration, + legacyCacheAffinityGuardFunction(t), + legacyCacheAffinityGuardTrigger(t), + legacyCacheAffinityScrubMigration(t), } { if _, err := conn.Exec(ctx, migration); err != nil { t.Fatalf("run cache-affinity migration: %v\n%s", err, migration) @@ -142,9 +155,9 @@ func TestLegacyCacheAffinityMigrationScrubsAndInstallsScopedTrigger(t *testing.T // A restart must remain idempotent with both same-named triggers present. for _, migration := range []string{ - legacyCacheAffinityGuardFunction, - legacyCacheAffinityGuardTrigger, - legacyCacheAffinityScrubMigration, + legacyCacheAffinityGuardFunction(t), + legacyCacheAffinityGuardTrigger(t), + legacyCacheAffinityScrubMigration(t), } { if _, err := conn.Exec(ctx, migration); err != nil { t.Fatalf("re-run cache-affinity migration: %v", err) diff --git a/coordinator/store/schema/migrations/00001_baseline.sql b/coordinator/store/schema/migrations/00001_baseline.sql new file mode 100644 index 0000000000..d5b2a6f774 --- /dev/null +++ b/coordinator/store/schema/migrations/00001_baseline.sql @@ -0,0 +1,1838 @@ +-- Baseline: the 255 statements that (*PostgresStore).migrate ran on every +-- boot before goose, unchanged and in the same order (see postgres.go and the +-- DDL constants at commit 48d2be45 for their history). Each block runs as one +-- call outside a transaction, as before. On a database that already has this +-- schema every statement is a no-op. Do not edit this file; add a new +-- numbered migration instead (docs/developer/database-migrations.md). +-- +goose NO TRANSACTION +-- +goose Up +-- +goose StatementBegin + +CREATE TABLE IF NOT EXISTS global_payout_recipients ( + account_id TEXT PRIMARY KEY, country TEXT NOT NULL, data JSONB NOT NULL +); +CREATE TABLE IF NOT EXISTS global_payout_withdrawals ( + id TEXT PRIMARY KEY, account_id TEXT NOT NULL, status TEXT NOT NULL, + external_id TEXT NOT NULL DEFAULT '', submitted_at TIMESTAMPTZ NOT NULL, + checked_at TIMESTAMPTZ NOT NULL, lease_until TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, data JSONB NOT NULL +); +ALTER TABLE global_payout_withdrawals ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ NOT NULL DEFAULT 'infinity'; +UPDATE global_payout_withdrawals SET expires_at=(data->>'expires_at')::timestamptz WHERE status='quoted' AND expires_at='infinity'; +CREATE INDEX IF NOT EXISTS global_payout_quote_expiry ON global_payout_withdrawals(expires_at) WHERE status='quoted'; +CREATE UNIQUE INDEX IF NOT EXISTS global_payout_external_id ON global_payout_withdrawals(external_id) WHERE external_id <> ''; +CREATE INDEX IF NOT EXISTS global_payout_account ON global_payout_withdrawals(account_id, submitted_at DESC); +CREATE INDEX IF NOT EXISTS global_payout_reconcile ON global_payout_withdrawals(checked_at) WHERE status IN ('pending','processing','posted'); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS schema_migrations ( + id TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS providers ( + id TEXT PRIMARY KEY, + hardware JSONB NOT NULL, + models JSONB NOT NULL, + backend TEXT NOT NULL, + location JSONB, + registered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), + trust_level TEXT NOT NULL DEFAULT 'none', + attested BOOLEAN NOT NULL DEFAULT FALSE, + attestation_result JSONB, + se_public_key TEXT NOT NULL DEFAULT '', + public_key TEXT NOT NULL DEFAULT '', + serial_number TEXT NOT NULL DEFAULT '', + mda_verified BOOLEAN NOT NULL DEFAULT FALSE, + mda_cert_chain JSONB, + version TEXT NOT NULL DEFAULT '', + runtime_verified BOOLEAN NOT NULL DEFAULT FALSE, + python_hash TEXT NOT NULL DEFAULT '', + runtime_hash TEXT NOT NULL DEFAULT '', + last_challenge_verified TIMESTAMPTZ, + failed_challenges INT NOT NULL DEFAULT 0, + account_id TEXT NOT NULL DEFAULT '', + lifetime_requests_served BIGINT NOT NULL DEFAULT 0, + lifetime_tokens_generated BIGINT NOT NULL DEFAULT 0, + last_session_requests_served BIGINT NOT NULL DEFAULT 0, + last_session_tokens_generated BIGINT NOT NULL DEFAULT 0, + lifetime_stats JSONB NOT NULL DEFAULT '{}'::jsonb, + last_session_stats JSONB NOT NULL DEFAULT '{}'::jsonb + ); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS location JSONB; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS trust_level TEXT NOT NULL DEFAULT 'none'; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS attested BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS attestation_result JSONB; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS se_public_key TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS public_key TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS serial_number TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS mda_verified BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS mda_cert_chain JSONB; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS version TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS runtime_verified BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS python_hash TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS runtime_hash TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_challenge_verified TIMESTAMPTZ; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS failed_challenges INT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS account_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS lifetime_requests_served BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS lifetime_tokens_generated BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_session_requests_served BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_session_tokens_generated BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS lifetime_stats JSONB NOT NULL DEFAULT '{}'::jsonb; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE providers ADD COLUMN IF NOT EXISTS last_session_stats JSONB NOT NULL DEFAULT '{}'::jsonb; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_providers_serial ON providers(serial_number) WHERE serial_number != ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_providers_account ON providers(account_id, last_seen DESC) WHERE account_id != ''; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS request_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS cost_micro_usd BIGINT NOT NULL DEFAULT 0; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS request_location JSONB; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS public_model TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_reputation ( + provider_id TEXT PRIMARY KEY REFERENCES providers(id), + total_jobs INT NOT NULL DEFAULT 0, + successful_jobs INT NOT NULL DEFAULT 0, + failed_jobs INT NOT NULL DEFAULT 0, + total_uptime_seconds BIGINT NOT NULL DEFAULT 0, + avg_response_time_ms BIGINT NOT NULL DEFAULT 0, + challenges_passed INT NOT NULL DEFAULT 0, + challenges_failed INT NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS api_keys ( + key_hash TEXT PRIMARY KEY, + raw_prefix TEXT NOT NULL, + owner_account_id TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + active BOOLEAN NOT NULL DEFAULT TRUE + ); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS owner_account_id TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS name TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS limit_micro_usd BIGINT; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS limit_reset TEXT NOT NULL DEFAULT 'none'; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS rpm_limit BIGINT; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS itpm_limit BIGINT; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS otpm_limit BIGINT; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS allowed_models TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMPTZ; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS self_route_only BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +UPDATE api_keys SET id = 'key_' || substr(md5(key_hash), 1, 24) WHERE id IS NULL OR id = ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE UNIQUE INDEX IF NOT EXISTS idx_api_keys_id ON api_keys(id) WHERE id <> ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_api_keys_owner ON api_keys(owner_account_id) WHERE owner_account_id <> ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS usage ( + id BIGSERIAL PRIMARY KEY, + provider_id TEXT NOT NULL, + consumer_key_hash TEXT NOT NULL, + key_id TEXT NOT NULL DEFAULT '', + model TEXT NOT NULL, + public_model TEXT NOT NULL DEFAULT '', + prompt_tokens INTEGER NOT NULL, + cached_tokens INTEGER NOT NULL DEFAULT 0, + completion_tokens INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + request_id TEXT NOT NULL DEFAULT '', + cost_micro_usd BIGINT NOT NULL DEFAULT 0, + request_location JSONB + ); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS key_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE usage ADD COLUMN IF NOT EXISTS public_model TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE usage ADD COLUMN IF NOT EXISTS cached_tokens INTEGER NOT NULL DEFAULT 0; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_usage_created ON usage(created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_usage_consumer ON usage(consumer_key_hash, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_usage_provider ON usage(provider_id, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_usage_key ON usage(key_id, created_at DESC) WHERE key_id <> ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS payments ( + id BIGSERIAL PRIMARY KEY, + tx_hash TEXT UNIQUE, + consumer_address TEXT NOT NULL, + provider_address TEXT NOT NULL, + amount_usd TEXT NOT NULL, + model TEXT NOT NULL, + prompt_tokens INTEGER NOT NULL, + completion_tokens INTEGER NOT NULL, + memo TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS balances ( + account_id TEXT PRIMARY KEY, + balance_micro_usd BIGINT NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + withdrawable_micro_usd BIGINT NOT NULL DEFAULT 0 + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS ledger_entries ( + id BIGSERIAL PRIMARY KEY, + account_id TEXT NOT NULL, + entry_type TEXT NOT NULL, + amount_micro_usd BIGINT NOT NULL, + balance_after BIGINT NOT NULL, + reference TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_ledger_account ON ledger_entries(account_id, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_ledger_reward ON ledger_entries(account_id, created_at DESC) WHERE entry_type IN ('referral_reward','admin_reward'); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS referrers ( + account_id TEXT PRIMARY KEY, + code TEXT UNIQUE NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_referrers_code ON referrers(code); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS referrals ( + referred_account TEXT PRIMARY KEY, + referrer_code TEXT NOT NULL REFERENCES referrers(code), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_referrals_code ON referrals(referrer_code); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS billing_sessions ( + id TEXT PRIMARY KEY, + account_id TEXT NOT NULL, + payment_method TEXT NOT NULL, + amount_micro_usd BIGINT NOT NULL, + external_id TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', + referral_code TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + completed_at TIMESTAMPTZ + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_billing_sessions_account ON billing_sessions(account_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_billing_sessions_external ON billing_sessions(external_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_prices ( + account_id TEXT NOT NULL, + model TEXT NOT NULL, + input_price BIGINT NOT NULL, + output_price BIGINT NOT NULL, + cache_read_price BIGINT, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (account_id, model) + ); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE model_prices ADD COLUMN IF NOT EXISTS cache_read_price BIGINT; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS users ( + account_id TEXT PRIMARY KEY, + privy_user_id TEXT UNIQUE NOT NULL, + email TEXT NOT NULL DEFAULT '', + role TEXT NOT NULL DEFAULT '', + platform_fee_percent BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy ON users(privy_user_id); +-- +goose StatementEnd +-- +goose StatementBegin +DROP TABLE IF EXISTS supported_models; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_registry ( + id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + family TEXT NOT NULL DEFAULT '', + architecture TEXT NOT NULL DEFAULT '', + quantization TEXT NOT NULL DEFAULT '', + max_context_length INTEGER NOT NULL DEFAULT 0, + max_output_length INTEGER NOT NULL DEFAULT 0, + min_ram_gb INTEGER NOT NULL DEFAULT 0, + capabilities TEXT[] NOT NULL DEFAULT '{}', + required_provider_capabilities TEXT[] NOT NULL DEFAULT '{}', + status TEXT NOT NULL DEFAULT 'beta', + description TEXT NOT NULL DEFAULT '', + runtime_parameters JSONB NOT NULL DEFAULT '{}', + metadata JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_model_registry_status ON model_registry(status); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_versions ( + id BIGSERIAL PRIMARY KEY, + model_id TEXT NOT NULL REFERENCES model_registry(id) ON DELETE CASCADE, + version TEXT NOT NULL, + r2_prefix TEXT NOT NULL, + aggregate_sha256 TEXT NOT NULL, + total_size_bytes BIGINT NOT NULL, + file_count INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'ready', + uploaded_by TEXT NOT NULL DEFAULT '', + uploaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + promoted_at TIMESTAMPTZ, + metadata JSONB NOT NULL DEFAULT '{}', + UNIQUE(model_id, version) + ); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE model_versions ADD COLUMN IF NOT EXISTS hugging_face_artifact JSONB; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS max_context_length INTEGER NOT NULL DEFAULT 0; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS max_output_length INTEGER NOT NULL DEFAULT 0; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS runtime_parameters JSONB NOT NULL DEFAULT '{}'; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE model_registry ADD COLUMN IF NOT EXISTS required_provider_capabilities TEXT[] NOT NULL DEFAULT '{}'; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +UPDATE model_registry + SET required_provider_capabilities = ( + SELECT ARRAY_AGG(DISTINCT capability ORDER BY capability) + FROM UNNEST(required_provider_capabilities || + ARRAY['apple_m5', 'mlx_nax']::TEXT[]) AS capability + ) + WHERE id = 'EigenLabs/Qwen3.8-27B-4bit' + AND NOT (required_provider_capabilities @> + ARRAY['apple_m5', 'mlx_nax']::TEXT[]); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_model_versions_model ON model_versions(model_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_version_files ( + id BIGSERIAL PRIMARY KEY, + model_version_id BIGINT NOT NULL REFERENCES model_versions(id) ON DELETE CASCADE, + path TEXT NOT NULL, + size_bytes BIGINT NOT NULL, + sha256 TEXT NOT NULL, + role TEXT NOT NULL, + UNIQUE(model_version_id, path) + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_model_version_files_version ON model_version_files(model_version_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_active_versions ( + model_id TEXT PRIMARY KEY REFERENCES model_registry(id) ON DELETE CASCADE, + model_version_id BIGINT NOT NULL REFERENCES model_versions(id) ON DELETE RESTRICT, + activated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS publishing_api_keys ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + key_hash TEXT NOT NULL, + active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_used_at TIMESTAMPTZ + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE UNIQUE INDEX IF NOT EXISTS idx_publishing_api_keys_hash ON publishing_api_keys(key_hash); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_aliases ( + alias_id TEXT PRIMARY KEY, + display_name TEXT NOT NULL DEFAULT '', + builds JSONB NOT NULL DEFAULT '[]'::jsonb, + active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS desired_build TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS previous_build TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS retired_builds JSONB NOT NULL DEFAULT '[]'::jsonb; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS openrouter_only BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS source_model TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS source_kind TEXT NOT NULL DEFAULT 'standard_alias'; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS openrouter_slug TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE model_aliases ADD COLUMN IF NOT EXISTS hugging_face_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + UPDATE model_aliases a + SET desired_build = sub.build_id + FROM ( + SELECT DISTINCT ON (alias_id) alias_id, (b->>'build_id') AS build_id + FROM model_aliases, jsonb_array_elements(builds) AS b + WHERE COALESCE((b->>'active')::boolean, true) + AND COALESCE((b->>'weight')::int, 0) > 0 + ORDER BY alias_id, COALESCE((b->>'weight')::int, 0) DESC + ) sub + WHERE a.alias_id = sub.alias_id AND a.desired_build = ''; + EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DROP TABLE IF EXISTS model_migrations; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS releases ( + version TEXT NOT NULL, + platform TEXT NOT NULL, + backend TEXT NOT NULL DEFAULT '', + binary_hash TEXT NOT NULL DEFAULT '', + bundle_hash TEXT NOT NULL DEFAULT '', + metallib_hash TEXT NOT NULL DEFAULT '', + python_hash TEXT NOT NULL DEFAULT '', + runtime_hash TEXT NOT NULL DEFAULT '', + template_hashes TEXT NOT NULL DEFAULT '', + grpc_binary_hash TEXT NOT NULL DEFAULT '', + url TEXT NOT NULL DEFAULT '', + changelog TEXT NOT NULL DEFAULT '', + active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (version, platform) + ); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE releases ADD COLUMN IF NOT EXISTS backend TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE releases ADD COLUMN IF NOT EXISTS metallib_hash TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE releases ADD COLUMN IF NOT EXISTS changelog TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE releases ADD COLUMN IF NOT EXISTS python_hash TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE releases ADD COLUMN IF NOT EXISTS runtime_hash TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE releases ADD COLUMN IF NOT EXISTS template_hashes TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + ALTER TABLE releases ADD COLUMN IF NOT EXISTS grpc_binary_hash TEXT NOT NULL DEFAULT ''; + EXCEPTION WHEN others THEN NULL; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS device_codes ( + device_code TEXT PRIMARY KEY, + user_code TEXT UNIQUE NOT NULL, + account_id TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'pending', + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_device_codes_user ON device_codes(user_code); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_tokens ( + token_hash TEXT PRIMARY KEY, + account_id TEXT NOT NULL, + label TEXT NOT NULL DEFAULT '', + active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_tokens_account ON provider_tokens(account_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS invite_codes ( + code TEXT PRIMARY KEY, + amount_micro_usd BIGINT NOT NULL, + max_uses INTEGER NOT NULL DEFAULT 1, + used_count INTEGER NOT NULL DEFAULT 0, + active BOOLEAN NOT NULL DEFAULT TRUE, + expires_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS invite_redemptions ( + code TEXT NOT NULL REFERENCES invite_codes(code), + account_id TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (code, account_id) + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_earnings ( + id BIGSERIAL PRIMARY KEY, + account_id TEXT NOT NULL, + provider_id TEXT NOT NULL, + provider_key TEXT NOT NULL DEFAULT '', + job_id TEXT NOT NULL, + model TEXT NOT NULL, + amount_micro_usd BIGINT NOT NULL, + prompt_tokens INTEGER NOT NULL DEFAULT 0, + completion_tokens INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_earnings_account ON provider_earnings(account_id, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_earnings_provider ON provider_earnings(provider_key, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS earnings_summary ( + key TEXT NOT NULL, + key_type TEXT NOT NULL, + total_count BIGINT NOT NULL DEFAULT 0, + total_micro_usd BIGINT NOT NULL DEFAULT 0, + total_prompt_tokens BIGINT NOT NULL DEFAULT 0, + total_completion_tokens BIGINT NOT NULL DEFAULT 0, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (key, key_type) + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_payouts ( + id BIGSERIAL PRIMARY KEY, + provider_address TEXT NOT NULL, + amount_micro_usd BIGINT NOT NULL, + model TEXT NOT NULL DEFAULT '', + job_id TEXT NOT NULL DEFAULT '', + settled BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_payouts_address ON provider_payouts(provider_address, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_payouts_settled ON provider_payouts(settled, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_account_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_account_status TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_account_country TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_destination_type TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_destination_last4 TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS stripe_instant_eligible BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE UNIQUE INDEX IF NOT EXISTS idx_users_stripe_account ON users(stripe_account_id) WHERE stripe_account_id != ''; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE users ADD COLUMN IF NOT EXISTS platform_fee_percent BIGINT; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS stripe_withdrawals ( + id TEXT PRIMARY KEY, + account_id TEXT NOT NULL, + stripe_account_id TEXT NOT NULL, + transfer_id TEXT NOT NULL DEFAULT '', + payout_id TEXT NOT NULL DEFAULT '', + amount_micro_usd BIGINT NOT NULL, + fee_micro_usd BIGINT NOT NULL DEFAULT 0, + net_micro_usd BIGINT NOT NULL, + method TEXT NOT NULL, + status TEXT NOT NULL, + failure_reason TEXT NOT NULL DEFAULT '', + refunded BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_account ON stripe_withdrawals(account_id, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE UNIQUE INDEX IF NOT EXISTS idx_stripe_withdrawals_transfer ON stripe_withdrawals(transfer_id) WHERE transfer_id != ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE UNIQUE INDEX IF NOT EXISTS idx_stripe_withdrawals_payout ON stripe_withdrawals(payout_id) WHERE payout_id != ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_status ON stripe_withdrawals(status, created_at); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_stripe_account ON stripe_withdrawals(stripe_account_id, status); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE stripe_withdrawals ADD COLUMN IF NOT EXISTS fee_refunded BOOLEAN NOT NULL DEFAULT FALSE; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE stripe_withdrawals ADD COLUMN IF NOT EXISTS sweep_payout_id TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_stripe_withdrawals_sweep_payout ON stripe_withdrawals(sweep_payout_id) WHERE sweep_payout_id != ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS usage_totals ( + id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1), + total_requests BIGINT NOT NULL DEFAULT 0, + total_prompt_tokens BIGINT NOT NULL DEFAULT 0, + total_completion_tokens BIGINT NOT NULL DEFAULT 0 + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_usage_request_location_notnull ON usage(created_at DESC) WHERE request_location IS NOT NULL; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_log_reports ( + id BIGSERIAL PRIMARY KEY, + serial_number TEXT NOT NULL DEFAULT '', + provider_id TEXT NOT NULL DEFAULT '', + account_id TEXT NOT NULL DEFAULT '', + log_data BYTEA NOT NULL, + log_size_bytes BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_log_reports ALTER COLUMN serial_number SET DEFAULT ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION clear_provider_log_report_serial() +RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + NEW.serial_number := ''; + RETURN NEW; +END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_trigger tg + JOIN pg_class target ON target.oid = tg.tgrelid + JOIN pg_namespace ns ON ns.oid = target.relnamespace + WHERE tg.tgname = 'clear_provider_log_report_serial' + AND NOT tg.tgisinternal + AND target.relname = 'provider_log_reports' + AND ns.nspname = current_schema() + ) THEN + CREATE TRIGGER clear_provider_log_report_serial + BEFORE INSERT OR UPDATE OF serial_number ON provider_log_reports + FOR EACH ROW EXECUTE FUNCTION clear_provider_log_report_serial(); + END IF; +END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + IF NOT EXISTS ( + SELECT 1 FROM schema_migrations + WHERE id = 'scrub_provider_log_report_serials_v1' + ) THEN + UPDATE provider_log_reports SET serial_number = '' WHERE serial_number <> ''; + INSERT INTO schema_migrations (id) + VALUES ('scrub_provider_log_report_serials_v1') + ON CONFLICT (id) DO NOTHING; + END IF; +END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DROP INDEX IF EXISTS idx_log_reports_serial; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_sessions ( + id BIGSERIAL PRIMARY KEY, + session_id TEXT NOT NULL UNIQUE, + serial_number TEXT NOT NULL DEFAULT '', + account_id TEXT NOT NULL DEFAULT '', + connected_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(), + disconnected_at TIMESTAMPTZ, + disconnect_reason TEXT NOT NULL DEFAULT '' + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_sessions_serial ON provider_sessions(serial_number, connected_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_sessions_connected ON provider_sessions(connected_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_sessions_open ON provider_sessions(connected_at) WHERE disconnected_at IS NULL; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS inference_routes ( + id BIGSERIAL PRIMARY KEY, + request_id TEXT NOT NULL, + attempt INTEGER NOT NULL DEFAULT 0, + provider_id TEXT NOT NULL DEFAULT '', + model TEXT NOT NULL, + public_model TEXT NOT NULL DEFAULT '', + consumer_key_hash TEXT NOT NULL DEFAULT '', + key_id TEXT NOT NULL DEFAULT '', + outcome TEXT NOT NULL DEFAULT '', + cost_ms DOUBLE PRECISION, + state_ms DOUBLE PRECISION, + queue_ms DOUBLE PRECISION, + pending_ms DOUBLE PRECISION, + backlog_ms DOUBLE PRECISION, + this_req_ms DOUBLE PRECISION, + health_ms DOUBLE PRECISION, + ttft_ms DOUBLE PRECISION, + best_ttft_ms DOUBLE PRECISION, + effective_queue INTEGER, + candidate_count INTEGER, + capacity_rejections INTEGER, + model_too_large_rejections INTEGER, + vision_rejections INTEGER, + ttft_rejections INTEGER, + effective_tps DOUBLE PRECISION, + static_tps DOUBLE PRECISION, + provider_status TEXT, + provider_trust_level TEXT, + provider_version TEXT, + hardware_chip TEXT, + hardware_chip_family TEXT, + hardware_tier TEXT, + memory_gb INTEGER, + gpu_cores INTEGER, + cpu_cores INTEGER, + system_memory_pressure DOUBLE PRECISION, + system_cpu_usage DOUBLE PRECISION, + system_thermal_state TEXT, + gpu_memory_active_gb DOUBLE PRECISION, + gpu_memory_peak_gb DOUBLE PRECISION, + gpu_memory_cache_gb DOUBLE PRECISION, + slot_state TEXT, + backend_running INTEGER, + backend_waiting INTEGER, + active_token_budget_used BIGINT, + active_token_budget_max BIGINT, + queued_token_budget BIGINT, + estimated_prompt_tokens INTEGER, + requested_max_tokens INTEGER, + requires_vision BOOLEAN NOT NULL DEFAULT FALSE, + has_tools BOOLEAN NOT NULL DEFAULT FALSE, + self_route_only BOOLEAN NOT NULL DEFAULT FALSE, + prefer_owner BOOLEAN NOT NULL DEFAULT FALSE, + cache_affinity_key TEXT NOT NULL DEFAULT '', + final_status TEXT NOT NULL DEFAULT '', + error_code INTEGER, + error_class TEXT, + prompt_tokens INTEGER, + completion_tokens INTEGER, + reasoning_tokens INTEGER, + cost_micro_usd BIGINT, + actual_ttft_ms DOUBLE PRECISION, + dispatch_to_first_chunk_ms DOUBLE PRECISION, + total_duration_ms DOUBLE PRECISION, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + provider_region TEXT, + consumer_region TEXT, + parse_ms DOUBLE PRECISION, + reserve_ms DOUBLE PRECISION, + route_ms DOUBLE PRECISION, + encrypt_ms DOUBLE PRECISION, + queue_wait_ms DOUBLE PRECISION, + dispatch_ms DOUBLE PRECISION, + actual_decode_tps DOUBLE PRECISION, + admitted_but_failed BOOL, + used_backup BOOL, + backup_won BOOL, + error_reason TEXT, + UNIQUE(request_id, attempt) + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_inference_routes_created ON inference_routes(created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_inference_routes_provider ON inference_routes(provider_id, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_inference_routes_model ON inference_routes(model, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_inference_routes_request ON inference_routes(request_id); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ + BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_index i + JOIN pg_class t ON t.oid = i.indrelid + WHERE t.oid = 'inference_routes'::regclass + AND i.indisunique + AND ARRAY( + SELECT a.attname::text + FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) + JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum + ORDER BY k.ord + ) = ARRAY['request_id', 'attempt'] + ) THEN + CREATE UNIQUE INDEX idx_inference_routes_request_attempt_unique ON inference_routes(request_id, attempt); + END IF; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS provider_region TEXT; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS consumer_region TEXT; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS parse_ms DOUBLE PRECISION; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS reserve_ms DOUBLE PRECISION; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS route_ms DOUBLE PRECISION; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS encrypt_ms DOUBLE PRECISION; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS queue_wait_ms DOUBLE PRECISION; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS dispatch_ms DOUBLE PRECISION; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS actual_decode_tps DOUBLE PRECISION; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS admitted_but_failed BOOL; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS used_backup BOOL; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS backup_won BOOL; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE inference_routes ADD COLUMN IF NOT EXISTS error_reason TEXT; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION clear_legacy_cache_affinity_key() +RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + NEW.cache_affinity_key := ''; + RETURN NEW; +END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_trigger tg + JOIN pg_class target ON target.oid = tg.tgrelid + JOIN pg_namespace ns ON ns.oid = target.relnamespace + WHERE tg.tgname = 'clear_legacy_cache_affinity_key' + AND NOT tg.tgisinternal + AND target.relname = 'inference_routes' + AND ns.nspname = current_schema() + ) THEN + CREATE TRIGGER clear_legacy_cache_affinity_key + BEFORE INSERT OR UPDATE OF cache_affinity_key ON inference_routes + FOR EACH ROW EXECUTE FUNCTION clear_legacy_cache_affinity_key(); + END IF; +END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM schema_migrations WHERE id = 'scrub_inference_route_cache_affinity_v1') THEN + IF EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = current_schema() + AND table_name = 'inference_routes' + AND column_name = 'cache_affinity_key' + ) THEN + UPDATE inference_routes SET cache_affinity_key = '' WHERE cache_affinity_key <> ''; + END IF; + INSERT INTO schema_migrations (id) VALUES ('scrub_inference_route_cache_affinity_v1'); + END IF; +END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS request_rejections ( + id BIGSERIAL PRIMARY KEY, + request_id TEXT, + endpoint TEXT, + stage TEXT, + reason_code TEXT, + http_status INT, + consumer_key_hash TEXT, + key_id TEXT, + client_class TEXT, + requested_model TEXT, + resolved_model TEXT, + stream BOOL, + n INT, + estimated_prompt_tokens INT, + requested_max_tokens INT, + requires_vision BOOL, + has_image BOOL, + has_audio BOOL, + has_tools BOOL, + tool_count INT, + response_format TEXT, + self_route_only BOOL, + prefer_owner BOOL, + params JSONB, + request_body_bytes INT, + retry_after_ms INT, + could_have_served BOOL, + candidate_count INT, + capacity_rejections INT, + model_too_large_rejections INT, + vision_rejections INT, + warm_provider_existed BOOL, + best_ttft_ms DOUBLE PRECISION, + shortfall_micro_usd BIGINT, + limit_kind TEXT, + over_by BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_rejections_created ON request_rejections(created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_rejections_reason ON request_rejections(reason_code, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_rejections_model ON request_rejections(resolved_model, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_rejections_status ON request_rejections(http_status, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_rejections_servable ON request_rejections(could_have_served, created_at DESC) WHERE could_have_served = true; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS code_attestations ( + se_pubkey TEXT PRIMARY KEY, + version TEXT NOT NULL DEFAULT '', + attested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + apns_token TEXT NOT NULL DEFAULT '', + node_public_key TEXT NOT NULL DEFAULT '', + binary_hash TEXT NOT NULL DEFAULT '' + ); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS apns_token TEXT NOT NULL DEFAULT ''; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS node_public_key TEXT NOT NULL DEFAULT ''; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS binary_hash TEXT NOT NULL DEFAULT ''; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE code_attestations ADD COLUMN IF NOT EXISTS continuous_coverage_until TIMESTAMPTZ; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS code_attest_push_budgets ( + se_pubkey TEXT NOT NULL, + token_hash TEXT NOT NULL DEFAULT '', + next_push_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (se_pubkey, token_hash) + ); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ + DECLARE key_columns TEXT[]; + BEGIN + SELECT array_agg(a.attname::TEXT ORDER BY k.ordinality) + INTO key_columns + FROM pg_constraint c + CROSS JOIN LATERAL unnest(c.conkey) + WITH ORDINALITY AS k(attnum, ordinality) + JOIN pg_attribute a + ON a.attrelid = c.conrelid AND a.attnum = k.attnum + WHERE c.conrelid = 'code_attest_push_budgets'::regclass + AND c.contype = 'p'; + IF key_columns IS DISTINCT FROM + ARRAY['se_pubkey', 'token_hash']::TEXT[] THEN + ALTER TABLE code_attest_push_budgets + DROP CONSTRAINT IF EXISTS code_attest_push_budgets_pkey; + ALTER TABLE code_attest_push_budgets + ADD CONSTRAINT code_attest_push_budgets_pkey + PRIMARY KEY (se_pubkey, token_hash); + END IF; + END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_code_attest_push_budgets_due + ON code_attest_push_budgets(next_push_at); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE code_attest_push_budgets + ADD COLUMN IF NOT EXISTS last_clear_at TIMESTAMPTZ; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_trust_reuse ( + se_pubkey TEXT PRIMARY KEY, + serial TEXT NOT NULL DEFAULT '', + trust_level TEXT NOT NULL DEFAULT '', + binary_hash TEXT NOT NULL DEFAULT '', + sip_enabled BOOL NOT NULL DEFAULT FALSE, + secure_boot_full BOOL NOT NULL DEFAULT FALSE, + mda_udid TEXT NOT NULL DEFAULT '', + verified_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_verified_binary_hash TEXT NOT NULL DEFAULT '', + hardware_proof_verified_at TIMESTAMPTZ, + application_proof_verified_at TIMESTAMPTZ, + evidence_generation BIGINT NOT NULL DEFAULT 1, + revocation_generation BIGINT NOT NULL DEFAULT 0, + revocation_event_id TEXT NOT NULL DEFAULT '', + revoked_at TIMESTAMPTZ + ); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS last_verified_binary_hash TEXT NOT NULL DEFAULT ''; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS hardware_proof_verified_at TIMESTAMPTZ; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS application_proof_verified_at TIMESTAMPTZ; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS evidence_generation BIGINT NOT NULL DEFAULT 1; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS revocation_generation BIGINT NOT NULL DEFAULT 0; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS revocation_event_id TEXT NOT NULL DEFAULT ''; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS revoked_at TIMESTAMPTZ; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ADD COLUMN IF NOT EXISTS continuous_coverage_until TIMESTAMPTZ; +-- +goose StatementEnd +-- +goose StatementBegin +UPDATE provider_trust_reuse + SET hardware_proof_verified_at = verified_at + WHERE hardware_proof_verified_at IS NULL; +-- +goose StatementEnd +-- +goose StatementBegin +UPDATE provider_trust_reuse + SET last_verified_binary_hash = binary_hash + WHERE last_verified_binary_hash = '' AND binary_hash <> ''; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ALTER COLUMN hardware_proof_verified_at SET DEFAULT NOW(); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_trust_reuse ALTER COLUMN hardware_proof_verified_at SET NOT NULL; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_verification_jobs ( + se_pubkey TEXT NOT NULL, + serial TEXT NOT NULL DEFAULT '', + udid TEXT NOT NULL DEFAULT '', + task_kind TEXT NOT NULL, + task_state TEXT NOT NULL, + priority SMALLINT NOT NULL, + retry_stage INTEGER NOT NULL DEFAULT 0, + previous_delay_ns BIGINT NOT NULL DEFAULT 0, + next_attempt_at TIMESTAMPTZ, + last_outcome TEXT NOT NULL DEFAULT 'none', + reopen_pending BOOLEAN NOT NULL DEFAULT FALSE, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + claim_owner TEXT NOT NULL DEFAULT '', + claim_expires_at TIMESTAMPTZ, + PRIMARY KEY (se_pubkey, task_kind) + ); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE provider_verification_jobs + ADD COLUMN IF NOT EXISTS reopen_pending BOOLEAN NOT NULL DEFAULT FALSE; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_verification_jobs_due + ON provider_verification_jobs(priority, next_attempt_at) + WHERE task_state IN ('pending', 'backoff'); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_verification_jobs_claim + ON provider_verification_jobs(claim_expires_at) + WHERE claim_owner <> ''; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE provider_sessions ADD COLUMN IF NOT EXISTS provider_key TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN others THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_provider_sessions_key ON provider_sessions(provider_key, connected_at) WHERE provider_key <> ''; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS provider_floor_draws ( + id BIGSERIAL PRIMARY KEY, + provider_key TEXT NOT NULL, + account_id TEXT NOT NULL DEFAULT '', + epoch_id TEXT NOT NULL, + amount_micro_usd BIGINT NOT NULL, + floor_micro_usd BIGINT NOT NULL DEFAULT 0, + earned_micro_usd BIGINT NOT NULL DEFAULT 0, + uptime_frac DOUBLE PRECISION NOT NULL DEFAULT 0, + memory_gb INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (provider_key, epoch_id) + ); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_floor_draws_epoch ON provider_floor_draws(epoch_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_floor_draws_account ON provider_floor_draws(account_id, epoch_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_demand_requests ( + id BIGSERIAL UNIQUE, + coord_request_id TEXT PRIMARY KEY, + received_at TIMESTAMPTZ NOT NULL, + model TEXT NOT NULL, + consumer_hash TEXT NOT NULL, + outcome TEXT NOT NULL, + http_status INTEGER NOT NULL, + revision BIGINT NOT NULL, + evidence_conflict BOOLEAN NOT NULL DEFAULT FALSE +); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_demand_hourly ( + hour TIMESTAMPTZ NOT NULL, + model TEXT NOT NULL, + consumer_hash TEXT NOT NULL, + requests BIGINT NOT NULL, + completed BIGINT NOT NULL, + capacity_rejected BIGINT NOT NULL, + latency_rejected BIGINT NOT NULL, + timed_out BIGINT NOT NULL, + failed BIGINT NOT NULL, + cancelled BIGINT NOT NULL, + unknown BIGINT NOT NULL, + excluded BIGINT NOT NULL, + http_429 BIGINT NOT NULL, + PRIMARY KEY(hour,model,consumer_hash) +); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION update_model_demand_hourly() RETURNS trigger AS $$ +BEGIN + IF TG_OP='UPDATE' AND OLD.outcome=NEW.outcome AND (OLD.http_status=429)=(NEW.http_status=429) THEN RETURN NEW; END IF; + INSERT INTO model_demand_hourly (hour,model,consumer_hash,requests,completed,capacity_rejected,latency_rejected,timed_out,failed,cancelled,unknown,excluded,http_429) + VALUES (date_trunc('hour',NEW.received_at,'UTC'),NEW.model,NEW.consumer_hash, + 1-CASE WHEN TG_OP='UPDATE' THEN 1 ELSE 0 END, + (NEW.outcome='completed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='completed')::integer ELSE 0 END, + (NEW.outcome='capacity_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='capacity_rejected')::integer ELSE 0 END, + (NEW.outcome='latency_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='latency_rejected')::integer ELSE 0 END, + (NEW.outcome='timed_out')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='timed_out')::integer ELSE 0 END, + (NEW.outcome='failed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='failed')::integer ELSE 0 END, + (NEW.outcome='cancelled')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='cancelled')::integer ELSE 0 END, + (NEW.outcome='unknown')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='unknown')::integer ELSE 0 END, + (NEW.outcome='excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='excluded')::integer ELSE 0 END, + (NEW.http_status=429 AND NEW.outcome<>'excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.http_status=429 AND OLD.outcome<>'excluded')::integer ELSE 0 END) + ON CONFLICT (hour,model,consumer_hash) DO UPDATE SET + requests=model_demand_hourly.requests+EXCLUDED.requests, + completed=model_demand_hourly.completed+EXCLUDED.completed, + capacity_rejected=model_demand_hourly.capacity_rejected+EXCLUDED.capacity_rejected, + latency_rejected=model_demand_hourly.latency_rejected+EXCLUDED.latency_rejected, + timed_out=model_demand_hourly.timed_out+EXCLUDED.timed_out, + failed=model_demand_hourly.failed+EXCLUDED.failed, + cancelled=model_demand_hourly.cancelled+EXCLUDED.cancelled, + unknown=model_demand_hourly.unknown+EXCLUDED.unknown, + excluded=model_demand_hourly.excluded+EXCLUDED.excluded, + http_429=model_demand_hourly.http_429+EXCLUDED.http_429; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE OR REPLACE TRIGGER model_demand_rollup + AFTER INSERT OR UPDATE ON model_demand_requests FOR EACH ROW EXECUTE FUNCTION update_model_demand_hourly(); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_model_demand_received ON model_demand_requests (received_at); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS model_demand_collection (singleton BOOLEAN PRIMARY KEY CHECK(singleton), started_at TIMESTAMPTZ NOT NULL); +-- +goose StatementEnd +-- +goose StatementBegin +INSERT INTO model_demand_collection (singleton,started_at) VALUES (TRUE,NOW()) ON CONFLICT DO NOTHING; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS request_outcomes ( + id BIGSERIAL UNIQUE, + coord_request_id TEXT PRIMARY KEY CHECK (coord_request_id <> ''), + received_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + revision BIGINT NOT NULL, + evidence_conflict BOOLEAN NOT NULL DEFAULT FALSE, + record JSONB NOT NULL +); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_outcomes_received ON request_outcomes (received_at, coord_request_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS request_profiles ( + id BIGSERIAL PRIMARY KEY, + coord_request_id TEXT NOT NULL, + request_id TEXT NOT NULL, + attempt INT NOT NULL, + backup_of TEXT NOT NULL DEFAULT '', + winning BOOL NOT NULL DEFAULT FALSE, + endpoint TEXT NOT NULL DEFAULT '', + stream BOOL NOT NULL DEFAULT FALSE, + model TEXT NOT NULL DEFAULT '', + public_model TEXT NOT NULL DEFAULT '', + provider_id TEXT NOT NULL DEFAULT '', + provider_version TEXT NOT NULL DEFAULT '', + chip_family TEXT NOT NULL DEFAULT '', + kv_backend TEXT NOT NULL DEFAULT '', + final_status TEXT NOT NULL DEFAULT '', + error_reason TEXT NOT NULL DEFAULT '', + terminal_cause TEXT NOT NULL DEFAULT '', + client_outcome TEXT NOT NULL DEFAULT '', + provider_outcome TEXT NOT NULL DEFAULT '', + client_gone_phase TEXT NOT NULL DEFAULT '', + first_content_budget_ms INT NOT NULL DEFAULT 0, + admission_mode TEXT NOT NULL DEFAULT '', + predictive_bypass TEXT NOT NULL DEFAULT '', + reservation_ttft_ceiling_ms DOUBLE PRECISION, + dispatch_budget_ms BIGINT, + estimated_prompt_tokens INT NOT NULL DEFAULT 0, + requested_max_tokens INT NOT NULL DEFAULT 0, + requires_vision BOOL NOT NULL DEFAULT FALSE, + has_tools BOOL NOT NULL DEFAULT FALSE, + received_at TIMESTAMPTZ NOT NULL, + + auth_done_us BIGINT, + ratelimit_done_us BIGINT, + sealed_open_us BIGINT, + handler_entry_us BIGINT, + parsed_us BIGINT, + reserved_us BIGINT, + media_fetched_us BIGINT, + preflight_done_us BIGINT, + plan_done_us BIGINT, + attempt_start_us BIGINT, + reserve_lock_acquired_us BIGINT, + reserve_done_us BIGINT, + queued_us BIGINT, + dequeued_us BIGINT, + topup_done_us BIGINT, + encrypted_us BIGINT, + write_submitted_us BIGINT, + write_dequeued_us BIGINT, + write_done_us BIGINT, + accepted_us BIGINT, + first_chunk_ingress_us BIGINT, + first_chunk_dequeued_us BIGINT, + first_content_ingress_us BIGINT, + first_content_us BIGINT, + headers_written_us BIGINT, + first_flush_us BIGINT, + last_flush_us BIGINT, + client_gone_us BIGINT, + cancel_sent_us BIGINT, + complete_ingress_us BIGINT, + done_flushed_us BIGINT, + finalized_us BIGINT, + settle_db_us BIGINT, + db_us BIGINT, + db_calls INT NOT NULL DEFAULT 0, + + body_bytes INT NOT NULL DEFAULT 0, + sealed_body_bytes INT NOT NULL DEFAULT 0, + auth_kind TEXT NOT NULL DEFAULT '', + auth_db_read BOOL NOT NULL DEFAULT FALSE, + reserve_mode TEXT NOT NULL DEFAULT '', + media_items INT NOT NULL DEFAULT 0, + media_bytes BIGINT NOT NULL DEFAULT 0, + preflight_outcome TEXT NOT NULL DEFAULT '', + plan_outcome TEXT NOT NULL DEFAULT '', + chunks_in INT NOT NULL DEFAULT 0, + chunks_out INT NOT NULL DEFAULT 0, + bytes_out BIGINT NOT NULL DEFAULT 0, + decrypt_us_total BIGINT NOT NULL DEFAULT 0, + max_chunk_gap_us BIGINT NOT NULL DEFAULT 0, + held_preamble_chunks INT NOT NULL DEFAULT 0, + client_write_err BOOL NOT NULL DEFAULT FALSE, + attempts_total INT NOT NULL DEFAULT 0, + failed_attempts INT NOT NULL DEFAULT 0, + failed_attempts_us BIGINT NOT NULL DEFAULT 0, + backup_launched BOOL NOT NULL DEFAULT FALSE, + backup_won BOOL NOT NULL DEFAULT FALSE, + transport_est_us BIGINT, + slept_us BIGINT, + timing_anomaly BOOL NOT NULL DEFAULT FALSE, + + candidate_set_size INT NOT NULL DEFAULT 0, + scanned INT NOT NULL DEFAULT 0, + gate_rejections JSONB, + runner_up_provider_id TEXT NOT NULL DEFAULT '', + runner_up_cost_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + near_tie_pool_size INT NOT NULL DEFAULT 0, + selection_path TEXT NOT NULL DEFAULT '', + best_idle_provider_id TEXT NOT NULL DEFAULT '', + best_idle_ttft_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + predicted_ttft_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + raw_ttft_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + predicted_decode_tps DOUBLE PRECISION NOT NULL DEFAULT 0, + snapshot_age_ms INT NOT NULL DEFAULT 0, + pending_for_model INT NOT NULL DEFAULT 0, + total_pending INT NOT NULL DEFAULT 0, + capacity_rate_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + cache_discount_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + shadow_would_shed BOOL, + shadow_idle_alternative BOOL, + lock_wait_us BIGINT NOT NULL DEFAULT 0, + scan_us BIGINT NOT NULL DEFAULT 0, + admit_us BIGINT NOT NULL DEFAULT 0, + preflight_us BIGINT NOT NULL DEFAULT 0, + ttft_calibration_ratio DOUBLE PRECISION NOT NULL DEFAULT 0, + prefill_decode_ratio DOUBLE PRECISION NOT NULL DEFAULT 0, + queue_position_at_enqueue INT NOT NULL DEFAULT 0, + queue_depth_at_enqueue INT NOT NULL DEFAULT 0, + drain_trigger TEXT NOT NULL DEFAULT '', + candidates JSONB, + + prov_total_us BIGINT, + prov_first_delta_us BIGINT, + prov_engine_submit_us BIGINT, + prov_engine_admitted_us BIGINT, + prov_prompt_prep_us BIGINT, + prov_load_wait_us BIGINT, + prov_load_cold BOOL, + prov_running_at_admit INT, + prov_waiting_at_admit INT, + prov_kv_bytes_in_use_at_admit BIGINT, + prov_cancel_stage TEXT NOT NULL DEFAULT '', + eng_queue_wait_ns BIGINT, + eng_first_token_ns BIGINT, + eng_prompt_computed_ns BIGINT, + eng_prefill_chunks INT, + eng_decode_steps INT, + eng_mtp_accepted INT, + eng_finish_reason TEXT NOT NULL DEFAULT '', + provider_profile JSONB, + provider_profile_valid BOOL NOT NULL DEFAULT FALSE, + provider_profile_invalid_reason TEXT NOT NULL DEFAULT '', + provider_profile_consistent BOOL, + + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (request_id, attempt) + ) WITH (autovacuum_vacuum_scale_factor=0.02, autovacuum_analyze_scale_factor=0.01); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_profiles_created ON request_profiles(created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_profiles_coord ON request_profiles(coord_request_id); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_request_profiles_provider ON request_profiles(provider_id, created_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS fleet_snapshots ( + id BIGSERIAL PRIMARY KEY, + sampled_at TIMESTAMPTZ NOT NULL, + provider_id TEXT NOT NULL, + model TEXT NOT NULL DEFAULT '', + eligibility_reason TEXT NOT NULL DEFAULT '', + slot_state TEXT NOT NULL DEFAULT '', + num_running INT NOT NULL DEFAULT 0, + num_waiting INT NOT NULL DEFAULT 0, + queued_prefill_tokens INT NOT NULL DEFAULT 0, + partial_prefill_rows INT NOT NULL DEFAULT 0, + active_token_budget_used BIGINT NOT NULL DEFAULT 0, + active_token_budget_max BIGINT NOT NULL DEFAULT 0, + kv_bytes_in_use BIGINT NOT NULL DEFAULT 0, + kv_bytes_capacity BIGINT NOT NULL DEFAULT 0, + observed_decode_tps DOUBLE PRECISION NOT NULL DEFAULT 0, + observed_prefill_tps DOUBLE PRECISION NOT NULL DEFAULT 0, + isolated_prefill_tps DOUBLE PRECISION NOT NULL DEFAULT 0, + ewma_initialized BOOL, + max_concurrency INT NOT NULL DEFAULT 0, + pending_count INT NOT NULL DEFAULT 0, + effective_cap INT NOT NULL DEFAULT 0, + cooldown_active BOOL NOT NULL DEFAULT FALSE, + breaker_open BOOL NOT NULL DEFAULT FALSE, + clamp_active BOOL NOT NULL DEFAULT FALSE, + ejected BOOL NOT NULL DEFAULT FALSE, + gpu_memory_active_gb DOUBLE PRECISION NOT NULL DEFAULT 0, + gpu_memory_peak_gb DOUBLE PRECISION NOT NULL DEFAULT 0, + free_for_load_gb DOUBLE PRECISION, + memory_pressure DOUBLE PRECISION NOT NULL DEFAULT 0, + cpu_usage DOUBLE PRECISION NOT NULL DEFAULT 0, + thermal_state TEXT NOT NULL DEFAULT '', + low_power_mode BOOL, + memory_pressure_level TEXT NOT NULL DEFAULT '', + steps_executed BIGINT NOT NULL DEFAULT 0, + step_wall_ns_total BIGINT NOT NULL DEFAULT 0, + decode_rows_total BIGINT NOT NULL DEFAULT 0, + prefill_tokens_total BIGINT NOT NULL DEFAULT 0, + mtp_rounds_total BIGINT NOT NULL DEFAULT 0, + mtp_proposed_total BIGINT NOT NULL DEFAULT 0, + mtp_accepted_total BIGINT NOT NULL DEFAULT 0, + heartbeat_age_ms INT NOT NULL DEFAULT 0, + wedge_suspected BOOL NOT NULL DEFAULT FALSE, + eval_in_flight_ms BIGINT NOT NULL DEFAULT 0, + requests_served BIGINT NOT NULL DEFAULT 0, + tokens_generated BIGINT NOT NULL DEFAULT 0, + cancellations_received BIGINT NOT NULL DEFAULT 0, + cancellations_before_output BIGINT NOT NULL DEFAULT 0, + cancellations_partial_complete BIGINT NOT NULL DEFAULT 0, + generation_errors_after_output BIGINT NOT NULL DEFAULT 0, + chunk_encryption_errors BIGINT NOT NULL DEFAULT 0, + stream_closed_without_terminal BIGINT NOT NULL DEFAULT 0, + cancel_during_model_load BIGINT NOT NULL DEFAULT 0, + usage_gaps BIGINT NOT NULL DEFAULT 0, + cancel_stage_pre_accept_total BIGINT NOT NULL DEFAULT 0, + cancel_stage_pre_engine_total BIGINT NOT NULL DEFAULT 0, + cancel_stage_prefill_total BIGINT NOT NULL DEFAULT 0, + cancel_stage_decode_total BIGINT NOT NULL DEFAULT 0, + cancel_stage_post_terminal_total BIGINT NOT NULL DEFAULT 0, + tokens_after_cancel_total BIGINT NOT NULL DEFAULT 0, + cancel_abort_ns_sum BIGINT NOT NULL DEFAULT 0, + queue_depth_total INT NOT NULL DEFAULT 0, + queue_depth_by_model JSONB, + inflight_requests INT NOT NULL DEFAULT 0, + reserve_lock_wait_p95_us BIGINT NOT NULL DEFAULT 0, + profile_sink_depth INT NOT NULL DEFAULT 0, + profile_sink_dropped_total BIGINT NOT NULL DEFAULT 0, + route_sink_dropped_total BIGINT NOT NULL DEFAULT 0, + unknown_request_frames_total BIGINT NOT NULL DEFAULT 0, + goroutines INT NOT NULL DEFAULT 0, + provider_version TEXT NOT NULL DEFAULT '', + model_vision BOOL NOT NULL DEFAULT FALSE, + template_render_ok BOOL + ) WITH (autovacuum_vacuum_scale_factor=0.02, autovacuum_analyze_scale_factor=0.01); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_fleet_snapshots_sampled ON fleet_snapshots(sampled_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS estimated_prompt_tokens INT NOT NULL DEFAULT 0; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS requested_max_tokens INT NOT NULL DEFAULT 0; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS requires_vision BOOL NOT NULL DEFAULT FALSE; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS has_tools BOOL NOT NULL DEFAULT FALSE; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS predictive_bypass TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS reservation_ttft_ceiling_ms DOUBLE PRECISION; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE request_profiles ADD COLUMN IF NOT EXISTS dispatch_budget_ms BIGINT; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE fleet_snapshots ADD COLUMN IF NOT EXISTS provider_version TEXT NOT NULL DEFAULT ''; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE fleet_snapshots ALTER COLUMN free_for_load_gb DROP NOT NULL; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE fleet_snapshots ADD COLUMN IF NOT EXISTS model_vision BOOL NOT NULL DEFAULT FALSE; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +DO $$ BEGIN ALTER TABLE fleet_snapshots ADD COLUMN IF NOT EXISTS template_render_ok BOOL; EXCEPTION WHEN duplicate_column THEN NULL; END $$; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_fleet_snapshots_provider ON fleet_snapshots(provider_id, sampled_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS autopilot_events ( + command_id TEXT NOT NULL, phase TEXT NOT NULL, at TIMESTAMPTZ NOT NULL, + record JSONB NOT NULL, PRIMARY KEY(command_id,phase) +); CREATE INDEX IF NOT EXISTS autopilot_events_at ON autopilot_events(at); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS app_attest_shadow_keys ( + key_id TEXT PRIMARY KEY, owner TEXT NOT NULL, evidence JSONB NOT NULL, + counter BIGINT NOT NULL DEFAULT 0 CHECK (counter >= 0 AND counter <= 4294967295), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +-- +goose StatementEnd +-- +goose StatementBegin + +CREATE TABLE IF NOT EXISTS darkbloom_machines ( + id TEXT PRIMARY KEY, assurance TEXT NOT NULL, merged_into TEXT REFERENCES darkbloom_machines(id), + first_seen TIMESTAMPTZ NOT NULL, last_seen TIMESTAMPTZ NOT NULL +); +CREATE INDEX IF NOT EXISTS darkbloom_machines_merged_into ON darkbloom_machines(merged_into) WHERE merged_into IS NOT NULL; +CREATE TABLE IF NOT EXISTS darkbloom_machine_aliases ( + kind TEXT NOT NULL, scope TEXT NOT NULL, digest TEXT NOT NULL, + machine_id TEXT NOT NULL REFERENCES darkbloom_machines(id), verified_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY(kind,scope,digest) +); +CREATE TABLE IF NOT EXISTS darkbloom_machine_sessions ( + session_id TEXT PRIMARY KEY, machine_id TEXT NOT NULL REFERENCES darkbloom_machines(id), + original_machine_id TEXT NOT NULL REFERENCES darkbloom_machines(id), account_id TEXT NOT NULL, + first_seen TIMESTAMPTZ NOT NULL, last_seen TIMESTAMPTZ NOT NULL, disconnected_at TIMESTAMPTZ, + observation JSONB NOT NULL +); +CREATE INDEX IF NOT EXISTS darkbloom_machine_sessions_seen ON darkbloom_machine_sessions(last_seen DESC); +CREATE INDEX IF NOT EXISTS darkbloom_machine_sessions_open ON darkbloom_machine_sessions(last_seen,session_id) WHERE disconnected_at IS NULL; +CREATE INDEX IF NOT EXISTS darkbloom_machine_sessions_machine ON darkbloom_machine_sessions(machine_id,last_seen DESC); +CREATE TABLE IF NOT EXISTS darkbloom_machine_merges ( + source_id TEXT PRIMARY KEY REFERENCES darkbloom_machines(id), target_id TEXT NOT NULL REFERENCES darkbloom_machines(id), + session_id TEXT NOT NULL, merged_at TIMESTAMPTZ NOT NULL, reason TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS darkbloom_machine_observations ( + session_id TEXT NOT NULL, observed_at TIMESTAMPTZ NOT NULL, observation JSONB NOT NULL, + PRIMARY KEY(session_id,observed_at) +); +CREATE TABLE IF NOT EXISTS app_attest_shadow_events ( + id TEXT PRIMARY KEY, session_id TEXT NOT NULL, observed_at TIMESTAMPTZ NOT NULL, + stage TEXT NOT NULL, outcome TEXT NOT NULL, fields JSONB NOT NULL +); +CREATE INDEX IF NOT EXISTS app_attest_shadow_events_session ON app_attest_shadow_events(session_id,observed_at DESC); +CREATE INDEX IF NOT EXISTS app_attest_shadow_events_time ON app_attest_shadow_events(observed_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin + +CREATE TABLE IF NOT EXISTS app_attest_evidence ( + id TEXT PRIMARY KEY, session_id TEXT NOT NULL, key_id TEXT NOT NULL, received_at TIMESTAMPTZ NOT NULL, + action TEXT NOT NULL, sha256 TEXT NOT NULL, context JSONB NOT NULL, + outcome TEXT NOT NULL DEFAULT 'pending', details JSONB NOT NULL DEFAULT '{}', completed_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS app_attest_evidence_session ON app_attest_evidence(session_id,received_at DESC); +CREATE INDEX IF NOT EXISTS app_attest_evidence_key ON app_attest_evidence(key_id,received_at DESC); +CREATE INDEX IF NOT EXISTS app_attest_evidence_time ON app_attest_evidence(received_at DESC); +CREATE INDEX IF NOT EXISTS app_attest_evidence_pending ON app_attest_evidence(received_at) WHERE outcome='pending'; +CREATE TABLE IF NOT EXISTS app_attest_evidence_blobs ( + evidence_id TEXT PRIMARY KEY REFERENCES app_attest_evidence(id), + proof_field TEXT NOT NULL, proof BYTEA NOT NULL +); +REVOKE ALL ON app_attest_evidence_blobs FROM PUBLIC; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS app_attest_enrollments (id TEXT PRIMARY KEY,owner TEXT NOT NULL,key_id TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL,context JSONB NOT NULL); +-- +goose StatementEnd +-- +goose StatementBegin + +CREATE TABLE IF NOT EXISTS app_attest_receipts ( + id TEXT PRIMARY KEY,key_id TEXT NOT NULL,evidence_id TEXT NOT NULL,parent_id TEXT NOT NULL, + received_at TIMESTAMPTZ NOT NULL,outcome TEXT NOT NULL,http_status INTEGER NOT NULL, + details JSONB NOT NULL,context JSONB NOT NULL,next_at TIMESTAMPTZ NOT NULL,expires_at TIMESTAMPTZ NOT NULL +); +CREATE INDEX IF NOT EXISTS app_attest_receipts_key ON app_attest_receipts(key_id,received_at DESC); +CREATE INDEX IF NOT EXISTS app_attest_receipts_recovery ON app_attest_receipts(key_id,received_at DESC) WHERE outcome='receipt_creation_time'; +CREATE TABLE IF NOT EXISTS app_attest_receipt_blobs ( + receipt_id TEXT PRIMARY KEY REFERENCES app_attest_receipts(id),body BYTEA NOT NULL,response_body BYTEA NOT NULL +); +REVOKE ALL ON app_attest_receipt_blobs FROM PUBLIC; +CREATE TABLE IF NOT EXISTS app_attest_receipt_jobs ( + key_id TEXT PRIMARY KEY,receipt_id TEXT NOT NULL REFERENCES app_attest_receipts(id),next_at TIMESTAMPTZ NOT NULL, + lease_until TIMESTAMPTZ,attempts BIGINT NOT NULL DEFAULT 0 +); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS app_attest_key_revocations ( + key_id TEXT PRIMARY KEY REFERENCES app_attest_shadow_keys(key_id), + account_id TEXT NOT NULL, reason TEXT NOT NULL, revoked_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS app_attest_build_qualifications ( + binary_hash TEXT PRIMARY KEY CHECK (binary_hash ~ '^[0-9a-f]{64}$'), + record JSONB NOT NULL +); +-- +goose StatementEnd +-- +goose StatementBegin + +CREATE TABLE IF NOT EXISTS app_attest_key_rotations ( + key_id TEXT PRIMARY KEY, machine_id TEXT NOT NULL, account_id TEXT NOT NULL, + requested_at TIMESTAMPTZ NOT NULL, failures INTEGER NOT NULL, reason TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS app_attest_key_rotations_machine ON app_attest_key_rotations(machine_id,requested_at DESC); +-- +goose StatementEnd +-- +goose StatementBegin + +CREATE TABLE IF NOT EXISTS model_token_promotions ( + model_id TEXT PRIMARY KEY, + tokens BIGINT NOT NULL CHECK (tokens > 0 AND tokens <= 1000000000000), + claim_starts_at TIMESTAMPTZ NOT NULL, + claim_ends_at TIMESTAMPTZ CHECK (claim_ends_at > claim_starts_at), + signup_cutoff_at TIMESTAMPTZ NOT NULL, + max_claims BIGINT NOT NULL CHECK (max_claims>0 AND max_claims<=1000000), + claimed_count BIGINT NOT NULL DEFAULT 0 CHECK (claimed_count>=0 AND claimed_count<=max_claims), + enabled BOOLEAN NOT NULL DEFAULT TRUE +); +CREATE TABLE IF NOT EXISTS model_token_grants ( + account_id TEXT NOT NULL REFERENCES users(account_id), + model_id TEXT NOT NULL REFERENCES model_token_promotions(model_id), + total_tokens BIGINT NOT NULL CHECK (total_tokens > 0), + used_tokens BIGINT NOT NULL DEFAULT 0 CHECK (used_tokens >= 0), + reserved_tokens BIGINT NOT NULL DEFAULT 0 CHECK (reserved_tokens >= 0), + claimed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (account_id, model_id), + CHECK (used_tokens + reserved_tokens <= total_tokens) +); +CREATE TABLE IF NOT EXISTS model_token_provider_carries ( + account_id TEXT PRIMARY KEY, + remainder BIGINT NOT NULL DEFAULT 0 CHECK (remainder >= 0 AND remainder < 100000000) +); +CREATE TABLE IF NOT EXISTS model_token_reservations ( + id TEXT PRIMARY KEY, + account_id TEXT NOT NULL, + model_id TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('reserved','settled','released')), + record JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + touched_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + FOREIGN KEY (account_id, model_id) REFERENCES model_token_grants(account_id, model_id) +); +ALTER TABLE model_token_reservations ADD COLUMN IF NOT EXISTS touched_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); +CREATE INDEX IF NOT EXISTS idx_model_token_reservations_open ON model_token_reservations(touched_at) WHERE state = 'reserved'; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS cache_routing_holders ( + key TEXT NOT NULL, + cache_epoch TEXT NOT NULL, + tier TEXT NOT NULL DEFAULT '', + model_id TEXT NOT NULL, + model_aggregate_hash TEXT NOT NULL DEFAULT '', + prompt_contract_id TEXT NOT NULL DEFAULT '', + block_hash_version TEXT NOT NULL DEFAULT '', + ready_boundary_mode TEXT NOT NULL DEFAULT '', + anchor_token_count INTEGER NOT NULL DEFAULT 0, + required_recompute_tokens INTEGER NOT NULL DEFAULT 0, + stage_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + measured_stage_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + measured_expires_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (key, cache_epoch) +); +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE cache_routing_holders + ADD COLUMN IF NOT EXISTS measured_stage_ms DOUBLE PRECISION NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS measured_expires_at TIMESTAMPTZ, + ADD COLUMN IF NOT EXISTS ready_boundary_mode TEXT NOT NULL DEFAULT ''; +-- +goose StatementEnd +-- +goose StatementBegin +ALTER TABLE cache_routing_holders DROP COLUMN IF EXISTS anchor_chain_hash; +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_cache_routing_holders_expires ON cache_routing_holders(expires_at); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_cache_routing_holders_updated ON cache_routing_holders(updated_at); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS cache_routing_demand ( + key TEXT PRIMARY KEY, + seen_at TIMESTAMPTZ NOT NULL +); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE INDEX IF NOT EXISTS idx_cache_routing_demand_seen ON cache_routing_demand(seen_at); +-- +goose StatementEnd +-- +goose StatementBegin +CREATE TABLE IF NOT EXISTS cache_routing_meta ( + name TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +-- +goose StatementEnd diff --git a/coordinator/store/schema/schema.sql b/coordinator/store/schema/schema.sql new file mode 100644 index 0000000000..80eb7b281f --- /dev/null +++ b/coordinator/store/schema/schema.sql @@ -0,0 +1,3340 @@ +-- +-- PostgreSQL database dump +-- + + + +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +-- +-- Name: clear_legacy_cache_affinity_key(); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.clear_legacy_cache_affinity_key() RETURNS trigger + LANGUAGE plpgsql + AS $$ BEGIN + NEW.cache_affinity_key := ''; + RETURN NEW; +END $$; + + +-- +-- Name: clear_provider_log_report_serial(); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.clear_provider_log_report_serial() RETURNS trigger + LANGUAGE plpgsql + AS $$ BEGIN + NEW.serial_number := ''; + RETURN NEW; +END $$; + + +-- +-- Name: update_model_demand_hourly(); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.update_model_demand_hourly() RETURNS trigger + LANGUAGE plpgsql + AS $$ +BEGIN + IF TG_OP='UPDATE' AND OLD.outcome=NEW.outcome AND (OLD.http_status=429)=(NEW.http_status=429) THEN RETURN NEW; END IF; + INSERT INTO model_demand_hourly (hour,model,consumer_hash,requests,completed,capacity_rejected,latency_rejected,timed_out,failed,cancelled,unknown,excluded,http_429) + VALUES (date_trunc('hour',NEW.received_at,'UTC'),NEW.model,NEW.consumer_hash, + 1-CASE WHEN TG_OP='UPDATE' THEN 1 ELSE 0 END, + (NEW.outcome='completed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='completed')::integer ELSE 0 END, + (NEW.outcome='capacity_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='capacity_rejected')::integer ELSE 0 END, + (NEW.outcome='latency_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='latency_rejected')::integer ELSE 0 END, + (NEW.outcome='timed_out')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='timed_out')::integer ELSE 0 END, + (NEW.outcome='failed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='failed')::integer ELSE 0 END, + (NEW.outcome='cancelled')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='cancelled')::integer ELSE 0 END, + (NEW.outcome='unknown')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='unknown')::integer ELSE 0 END, + (NEW.outcome='excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='excluded')::integer ELSE 0 END, + (NEW.http_status=429 AND NEW.outcome<>'excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.http_status=429 AND OLD.outcome<>'excluded')::integer ELSE 0 END) + ON CONFLICT (hour,model,consumer_hash) DO UPDATE SET + requests=model_demand_hourly.requests+EXCLUDED.requests, + completed=model_demand_hourly.completed+EXCLUDED.completed, + capacity_rejected=model_demand_hourly.capacity_rejected+EXCLUDED.capacity_rejected, + latency_rejected=model_demand_hourly.latency_rejected+EXCLUDED.latency_rejected, + timed_out=model_demand_hourly.timed_out+EXCLUDED.timed_out, + failed=model_demand_hourly.failed+EXCLUDED.failed, + cancelled=model_demand_hourly.cancelled+EXCLUDED.cancelled, + unknown=model_demand_hourly.unknown+EXCLUDED.unknown, + excluded=model_demand_hourly.excluded+EXCLUDED.excluded, + http_429=model_demand_hourly.http_429+EXCLUDED.http_429; + RETURN NEW; +END; +$$; + + +SET default_tablespace = ''; + +SET default_table_access_method = heap; + +-- +-- Name: api_keys; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.api_keys ( + key_hash text NOT NULL, + raw_prefix text NOT NULL, + owner_account_id text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + active boolean DEFAULT true NOT NULL, + id text DEFAULT ''::text NOT NULL, + name text DEFAULT ''::text NOT NULL, + limit_micro_usd bigint, + limit_reset text DEFAULT 'none'::text NOT NULL, + rpm_limit bigint, + itpm_limit bigint, + otpm_limit bigint, + allowed_models text DEFAULT ''::text NOT NULL, + expires_at timestamp with time zone, + last_used_at timestamp with time zone, + self_route_only boolean DEFAULT false NOT NULL +); + + +-- +-- Name: app_attest_build_qualifications; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_build_qualifications ( + binary_hash text NOT NULL, + record jsonb NOT NULL, + CONSTRAINT app_attest_build_qualifications_binary_hash_check CHECK ((binary_hash ~ '^[0-9a-f]{64}$'::text)) +); + + +-- +-- Name: app_attest_enrollments; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_enrollments ( + id text NOT NULL, + owner text NOT NULL, + key_id text NOT NULL, + created_at timestamp with time zone NOT NULL, + context jsonb NOT NULL +); + + +-- +-- Name: app_attest_evidence; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_evidence ( + id text NOT NULL, + session_id text NOT NULL, + key_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + action text NOT NULL, + sha256 text NOT NULL, + context jsonb NOT NULL, + outcome text DEFAULT 'pending'::text NOT NULL, + details jsonb DEFAULT '{}'::jsonb NOT NULL, + completed_at timestamp with time zone +); + + +-- +-- Name: app_attest_evidence_blobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_evidence_blobs ( + evidence_id text NOT NULL, + proof_field text NOT NULL, + proof bytea NOT NULL +); + + +-- +-- Name: app_attest_key_revocations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_key_revocations ( + key_id text NOT NULL, + account_id text NOT NULL, + reason text NOT NULL, + revoked_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: app_attest_key_rotations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_key_rotations ( + key_id text NOT NULL, + machine_id text NOT NULL, + account_id text NOT NULL, + requested_at timestamp with time zone NOT NULL, + failures integer NOT NULL, + reason text NOT NULL +); + + +-- +-- Name: app_attest_receipt_blobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_receipt_blobs ( + receipt_id text NOT NULL, + body bytea NOT NULL, + response_body bytea NOT NULL +); + + +-- +-- Name: app_attest_receipt_jobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_receipt_jobs ( + key_id text NOT NULL, + receipt_id text NOT NULL, + next_at timestamp with time zone NOT NULL, + lease_until timestamp with time zone, + attempts bigint DEFAULT 0 NOT NULL +); + + +-- +-- Name: app_attest_receipts; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_receipts ( + id text NOT NULL, + key_id text NOT NULL, + evidence_id text NOT NULL, + parent_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + outcome text NOT NULL, + http_status integer NOT NULL, + details jsonb NOT NULL, + context jsonb NOT NULL, + next_at timestamp with time zone NOT NULL, + expires_at timestamp with time zone NOT NULL +); + + +-- +-- Name: app_attest_shadow_events; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_shadow_events ( + id text NOT NULL, + session_id text NOT NULL, + observed_at timestamp with time zone NOT NULL, + stage text NOT NULL, + outcome text NOT NULL, + fields jsonb NOT NULL +); + + +-- +-- Name: app_attest_shadow_keys; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_shadow_keys ( + key_id text NOT NULL, + owner text NOT NULL, + evidence jsonb NOT NULL, + counter bigint DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT app_attest_shadow_keys_counter_check CHECK (((counter >= 0) AND (counter <= '4294967295'::bigint))) +); + + +-- +-- Name: autopilot_events; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.autopilot_events ( + command_id text NOT NULL, + phase text NOT NULL, + at timestamp with time zone NOT NULL, + record jsonb NOT NULL +); + + +-- +-- Name: balances; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.balances ( + account_id text NOT NULL, + balance_micro_usd bigint DEFAULT 0 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + withdrawable_micro_usd bigint DEFAULT 0 NOT NULL +); + + +-- +-- Name: billing_sessions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.billing_sessions ( + id text NOT NULL, + account_id text NOT NULL, + payment_method text NOT NULL, + amount_micro_usd bigint NOT NULL, + external_id text DEFAULT ''::text NOT NULL, + status text DEFAULT 'pending'::text NOT NULL, + referral_code text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + completed_at timestamp with time zone +); + + +-- +-- Name: cache_routing_demand; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.cache_routing_demand ( + key text NOT NULL, + seen_at timestamp with time zone NOT NULL +); + + +-- +-- Name: cache_routing_holders; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.cache_routing_holders ( + key text NOT NULL, + cache_epoch text NOT NULL, + tier text DEFAULT ''::text NOT NULL, + model_id text NOT NULL, + model_aggregate_hash text DEFAULT ''::text NOT NULL, + prompt_contract_id text DEFAULT ''::text NOT NULL, + block_hash_version text DEFAULT ''::text NOT NULL, + ready_boundary_mode text DEFAULT ''::text NOT NULL, + anchor_token_count integer DEFAULT 0 NOT NULL, + required_recompute_tokens integer DEFAULT 0 NOT NULL, + stage_ms double precision DEFAULT 0 NOT NULL, + measured_stage_ms double precision DEFAULT 0 NOT NULL, + measured_expires_at timestamp with time zone, + updated_at timestamp with time zone NOT NULL, + expires_at timestamp with time zone NOT NULL +); + + +-- +-- Name: cache_routing_meta; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.cache_routing_meta ( + name text NOT NULL, + value text NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: code_attest_push_budgets; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.code_attest_push_budgets ( + se_pubkey text NOT NULL, + token_hash text DEFAULT ''::text NOT NULL, + next_push_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + last_clear_at timestamp with time zone +); + + +-- +-- Name: code_attestations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.code_attestations ( + se_pubkey text NOT NULL, + version text DEFAULT ''::text NOT NULL, + attested_at timestamp with time zone DEFAULT now() NOT NULL, + apns_token text DEFAULT ''::text NOT NULL, + node_public_key text DEFAULT ''::text NOT NULL, + binary_hash text DEFAULT ''::text NOT NULL, + continuous_coverage_until timestamp with time zone +); + + +-- +-- Name: darkbloom_machine_aliases; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_aliases ( + kind text NOT NULL, + scope text NOT NULL, + digest text NOT NULL, + machine_id text NOT NULL, + verified_at timestamp with time zone NOT NULL +); + + +-- +-- Name: darkbloom_machine_merges; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_merges ( + source_id text NOT NULL, + target_id text NOT NULL, + session_id text NOT NULL, + merged_at timestamp with time zone NOT NULL, + reason text NOT NULL +); + + +-- +-- Name: darkbloom_machine_observations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_observations ( + session_id text NOT NULL, + observed_at timestamp with time zone NOT NULL, + observation jsonb NOT NULL +); + + +-- +-- Name: darkbloom_machine_sessions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_sessions ( + session_id text NOT NULL, + machine_id text NOT NULL, + original_machine_id text NOT NULL, + account_id text NOT NULL, + first_seen timestamp with time zone NOT NULL, + last_seen timestamp with time zone NOT NULL, + disconnected_at timestamp with time zone, + observation jsonb NOT NULL +); + + +-- +-- Name: darkbloom_machines; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machines ( + id text NOT NULL, + assurance text NOT NULL, + merged_into text, + first_seen timestamp with time zone NOT NULL, + last_seen timestamp with time zone NOT NULL +); + + +-- +-- Name: device_codes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.device_codes ( + device_code text NOT NULL, + user_code text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + status text DEFAULT 'pending'::text NOT NULL, + expires_at timestamp with time zone NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: earnings_summary; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.earnings_summary ( + key text NOT NULL, + key_type text NOT NULL, + total_count bigint DEFAULT 0 NOT NULL, + total_micro_usd bigint DEFAULT 0 NOT NULL, + total_prompt_tokens bigint DEFAULT 0 NOT NULL, + total_completion_tokens bigint DEFAULT 0 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: fleet_snapshots; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.fleet_snapshots ( + id bigint NOT NULL, + sampled_at timestamp with time zone NOT NULL, + provider_id text NOT NULL, + model text DEFAULT ''::text NOT NULL, + eligibility_reason text DEFAULT ''::text NOT NULL, + slot_state text DEFAULT ''::text NOT NULL, + num_running integer DEFAULT 0 NOT NULL, + num_waiting integer DEFAULT 0 NOT NULL, + queued_prefill_tokens integer DEFAULT 0 NOT NULL, + partial_prefill_rows integer DEFAULT 0 NOT NULL, + active_token_budget_used bigint DEFAULT 0 NOT NULL, + active_token_budget_max bigint DEFAULT 0 NOT NULL, + kv_bytes_in_use bigint DEFAULT 0 NOT NULL, + kv_bytes_capacity bigint DEFAULT 0 NOT NULL, + observed_decode_tps double precision DEFAULT 0 NOT NULL, + observed_prefill_tps double precision DEFAULT 0 NOT NULL, + isolated_prefill_tps double precision DEFAULT 0 NOT NULL, + ewma_initialized boolean, + max_concurrency integer DEFAULT 0 NOT NULL, + pending_count integer DEFAULT 0 NOT NULL, + effective_cap integer DEFAULT 0 NOT NULL, + cooldown_active boolean DEFAULT false NOT NULL, + breaker_open boolean DEFAULT false NOT NULL, + clamp_active boolean DEFAULT false NOT NULL, + ejected boolean DEFAULT false NOT NULL, + gpu_memory_active_gb double precision DEFAULT 0 NOT NULL, + gpu_memory_peak_gb double precision DEFAULT 0 NOT NULL, + free_for_load_gb double precision, + memory_pressure double precision DEFAULT 0 NOT NULL, + cpu_usage double precision DEFAULT 0 NOT NULL, + thermal_state text DEFAULT ''::text NOT NULL, + low_power_mode boolean, + memory_pressure_level text DEFAULT ''::text NOT NULL, + steps_executed bigint DEFAULT 0 NOT NULL, + step_wall_ns_total bigint DEFAULT 0 NOT NULL, + decode_rows_total bigint DEFAULT 0 NOT NULL, + prefill_tokens_total bigint DEFAULT 0 NOT NULL, + mtp_rounds_total bigint DEFAULT 0 NOT NULL, + mtp_proposed_total bigint DEFAULT 0 NOT NULL, + mtp_accepted_total bigint DEFAULT 0 NOT NULL, + heartbeat_age_ms integer DEFAULT 0 NOT NULL, + wedge_suspected boolean DEFAULT false NOT NULL, + eval_in_flight_ms bigint DEFAULT 0 NOT NULL, + requests_served bigint DEFAULT 0 NOT NULL, + tokens_generated bigint DEFAULT 0 NOT NULL, + cancellations_received bigint DEFAULT 0 NOT NULL, + cancellations_before_output bigint DEFAULT 0 NOT NULL, + cancellations_partial_complete bigint DEFAULT 0 NOT NULL, + generation_errors_after_output bigint DEFAULT 0 NOT NULL, + chunk_encryption_errors bigint DEFAULT 0 NOT NULL, + stream_closed_without_terminal bigint DEFAULT 0 NOT NULL, + cancel_during_model_load bigint DEFAULT 0 NOT NULL, + usage_gaps bigint DEFAULT 0 NOT NULL, + cancel_stage_pre_accept_total bigint DEFAULT 0 NOT NULL, + cancel_stage_pre_engine_total bigint DEFAULT 0 NOT NULL, + cancel_stage_prefill_total bigint DEFAULT 0 NOT NULL, + cancel_stage_decode_total bigint DEFAULT 0 NOT NULL, + cancel_stage_post_terminal_total bigint DEFAULT 0 NOT NULL, + tokens_after_cancel_total bigint DEFAULT 0 NOT NULL, + cancel_abort_ns_sum bigint DEFAULT 0 NOT NULL, + queue_depth_total integer DEFAULT 0 NOT NULL, + queue_depth_by_model jsonb, + inflight_requests integer DEFAULT 0 NOT NULL, + reserve_lock_wait_p95_us bigint DEFAULT 0 NOT NULL, + profile_sink_depth integer DEFAULT 0 NOT NULL, + profile_sink_dropped_total bigint DEFAULT 0 NOT NULL, + route_sink_dropped_total bigint DEFAULT 0 NOT NULL, + unknown_request_frames_total bigint DEFAULT 0 NOT NULL, + goroutines integer DEFAULT 0 NOT NULL, + provider_version text DEFAULT ''::text NOT NULL, + model_vision boolean DEFAULT false NOT NULL, + template_render_ok boolean +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01'); + + +-- +-- Name: fleet_snapshots_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.fleet_snapshots_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: fleet_snapshots_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.fleet_snapshots_id_seq OWNED BY public.fleet_snapshots.id; + + +-- +-- Name: global_payout_recipients; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.global_payout_recipients ( + account_id text NOT NULL, + country text NOT NULL, + data jsonb NOT NULL +); + + +-- +-- Name: global_payout_withdrawals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.global_payout_withdrawals ( + id text NOT NULL, + account_id text NOT NULL, + status text NOT NULL, + external_id text DEFAULT ''::text NOT NULL, + submitted_at timestamp with time zone NOT NULL, + checked_at timestamp with time zone NOT NULL, + lease_until timestamp with time zone NOT NULL, + expires_at timestamp with time zone NOT NULL, + data jsonb NOT NULL +); + + +-- +-- Name: inference_routes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.inference_routes ( + id bigint NOT NULL, + request_id text NOT NULL, + attempt integer DEFAULT 0 NOT NULL, + provider_id text DEFAULT ''::text NOT NULL, + model text NOT NULL, + public_model text DEFAULT ''::text NOT NULL, + consumer_key_hash text DEFAULT ''::text NOT NULL, + key_id text DEFAULT ''::text NOT NULL, + outcome text DEFAULT ''::text NOT NULL, + cost_ms double precision, + state_ms double precision, + queue_ms double precision, + pending_ms double precision, + backlog_ms double precision, + this_req_ms double precision, + health_ms double precision, + ttft_ms double precision, + best_ttft_ms double precision, + effective_queue integer, + candidate_count integer, + capacity_rejections integer, + model_too_large_rejections integer, + vision_rejections integer, + ttft_rejections integer, + effective_tps double precision, + static_tps double precision, + provider_status text, + provider_trust_level text, + provider_version text, + hardware_chip text, + hardware_chip_family text, + hardware_tier text, + memory_gb integer, + gpu_cores integer, + cpu_cores integer, + system_memory_pressure double precision, + system_cpu_usage double precision, + system_thermal_state text, + gpu_memory_active_gb double precision, + gpu_memory_peak_gb double precision, + gpu_memory_cache_gb double precision, + slot_state text, + backend_running integer, + backend_waiting integer, + active_token_budget_used bigint, + active_token_budget_max bigint, + queued_token_budget bigint, + estimated_prompt_tokens integer, + requested_max_tokens integer, + requires_vision boolean DEFAULT false NOT NULL, + has_tools boolean DEFAULT false NOT NULL, + self_route_only boolean DEFAULT false NOT NULL, + prefer_owner boolean DEFAULT false NOT NULL, + cache_affinity_key text DEFAULT ''::text NOT NULL, + final_status text DEFAULT ''::text NOT NULL, + error_code integer, + error_class text, + prompt_tokens integer, + completion_tokens integer, + reasoning_tokens integer, + cost_micro_usd bigint, + actual_ttft_ms double precision, + dispatch_to_first_chunk_ms double precision, + total_duration_ms double precision, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + provider_region text, + consumer_region text, + parse_ms double precision, + reserve_ms double precision, + route_ms double precision, + encrypt_ms double precision, + queue_wait_ms double precision, + dispatch_ms double precision, + actual_decode_tps double precision, + admitted_but_failed boolean, + used_backup boolean, + backup_won boolean, + error_reason text +); + + +-- +-- Name: inference_routes_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.inference_routes_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: inference_routes_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.inference_routes_id_seq OWNED BY public.inference_routes.id; + + +-- +-- Name: invite_codes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.invite_codes ( + code text NOT NULL, + amount_micro_usd bigint NOT NULL, + max_uses integer DEFAULT 1 NOT NULL, + used_count integer DEFAULT 0 NOT NULL, + active boolean DEFAULT true NOT NULL, + expires_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: invite_redemptions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.invite_redemptions ( + code text NOT NULL, + account_id text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: ledger_entries; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.ledger_entries ( + id bigint NOT NULL, + account_id text NOT NULL, + entry_type text NOT NULL, + amount_micro_usd bigint NOT NULL, + balance_after bigint NOT NULL, + reference text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: ledger_entries_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.ledger_entries_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: ledger_entries_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.ledger_entries_id_seq OWNED BY public.ledger_entries.id; + + +-- +-- Name: model_active_versions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_active_versions ( + model_id text NOT NULL, + model_version_id bigint NOT NULL, + activated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: model_aliases; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_aliases ( + alias_id text NOT NULL, + display_name text DEFAULT ''::text NOT NULL, + builds jsonb DEFAULT '[]'::jsonb NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + desired_build text DEFAULT ''::text NOT NULL, + previous_build text DEFAULT ''::text NOT NULL, + retired_builds jsonb DEFAULT '[]'::jsonb NOT NULL, + openrouter_only boolean DEFAULT false NOT NULL, + source_model text DEFAULT ''::text NOT NULL, + source_kind text DEFAULT 'standard_alias'::text NOT NULL, + openrouter_slug text DEFAULT ''::text NOT NULL, + hugging_face_id text DEFAULT ''::text NOT NULL +); + + +-- +-- Name: model_demand_collection; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_demand_collection ( + singleton boolean NOT NULL, + started_at timestamp with time zone NOT NULL, + CONSTRAINT model_demand_collection_singleton_check CHECK (singleton) +); + + +-- +-- Name: model_demand_hourly; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_demand_hourly ( + hour timestamp with time zone NOT NULL, + model text NOT NULL, + consumer_hash text NOT NULL, + requests bigint NOT NULL, + completed bigint NOT NULL, + capacity_rejected bigint NOT NULL, + latency_rejected bigint NOT NULL, + timed_out bigint NOT NULL, + failed bigint NOT NULL, + cancelled bigint NOT NULL, + unknown bigint NOT NULL, + excluded bigint NOT NULL, + http_429 bigint NOT NULL +); + + +-- +-- Name: model_demand_requests; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_demand_requests ( + id bigint NOT NULL, + coord_request_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + model text NOT NULL, + consumer_hash text NOT NULL, + outcome text NOT NULL, + http_status integer NOT NULL, + revision bigint NOT NULL, + evidence_conflict boolean DEFAULT false NOT NULL +); + + +-- +-- Name: model_demand_requests_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.model_demand_requests_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: model_demand_requests_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.model_demand_requests_id_seq OWNED BY public.model_demand_requests.id; + + +-- +-- Name: model_prices; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_prices ( + account_id text NOT NULL, + model text NOT NULL, + input_price bigint NOT NULL, + output_price bigint NOT NULL, + cache_read_price bigint, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: model_registry; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_registry ( + id text NOT NULL, + display_name text NOT NULL, + family text DEFAULT ''::text NOT NULL, + architecture text DEFAULT ''::text NOT NULL, + quantization text DEFAULT ''::text NOT NULL, + max_context_length integer DEFAULT 0 NOT NULL, + max_output_length integer DEFAULT 0 NOT NULL, + min_ram_gb integer DEFAULT 0 NOT NULL, + capabilities text[] DEFAULT '{}'::text[] NOT NULL, + required_provider_capabilities text[] DEFAULT '{}'::text[] NOT NULL, + status text DEFAULT 'beta'::text NOT NULL, + description text DEFAULT ''::text NOT NULL, + runtime_parameters jsonb DEFAULT '{}'::jsonb NOT NULL, + metadata jsonb DEFAULT '{}'::jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: model_token_grants; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_grants ( + account_id text NOT NULL, + model_id text NOT NULL, + total_tokens bigint NOT NULL, + used_tokens bigint DEFAULT 0 NOT NULL, + reserved_tokens bigint DEFAULT 0 NOT NULL, + claimed_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT model_token_grants_check CHECK (((used_tokens + reserved_tokens) <= total_tokens)), + CONSTRAINT model_token_grants_reserved_tokens_check CHECK ((reserved_tokens >= 0)), + CONSTRAINT model_token_grants_total_tokens_check CHECK ((total_tokens > 0)), + CONSTRAINT model_token_grants_used_tokens_check CHECK ((used_tokens >= 0)) +); + + +-- +-- Name: model_token_promotions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_promotions ( + model_id text NOT NULL, + tokens bigint NOT NULL, + claim_starts_at timestamp with time zone NOT NULL, + claim_ends_at timestamp with time zone, + signup_cutoff_at timestamp with time zone NOT NULL, + max_claims bigint NOT NULL, + claimed_count bigint DEFAULT 0 NOT NULL, + enabled boolean DEFAULT true NOT NULL, + CONSTRAINT model_token_promotions_check CHECK ((claim_ends_at > claim_starts_at)), + CONSTRAINT model_token_promotions_check1 CHECK (((claimed_count >= 0) AND (claimed_count <= max_claims))), + CONSTRAINT model_token_promotions_max_claims_check CHECK (((max_claims > 0) AND (max_claims <= 1000000))), + CONSTRAINT model_token_promotions_tokens_check CHECK (((tokens > 0) AND (tokens <= '1000000000000'::bigint))) +); + + +-- +-- Name: model_token_provider_carries; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_provider_carries ( + account_id text NOT NULL, + remainder bigint DEFAULT 0 NOT NULL, + CONSTRAINT model_token_provider_carries_remainder_check CHECK (((remainder >= 0) AND (remainder < 100000000))) +); + + +-- +-- Name: model_token_reservations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_reservations ( + id text NOT NULL, + account_id text NOT NULL, + model_id text NOT NULL, + state text NOT NULL, + record jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + touched_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT model_token_reservations_state_check CHECK ((state = ANY (ARRAY['reserved'::text, 'settled'::text, 'released'::text]))) +); + + +-- +-- Name: model_version_files; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_version_files ( + id bigint NOT NULL, + model_version_id bigint NOT NULL, + path text NOT NULL, + size_bytes bigint NOT NULL, + sha256 text NOT NULL, + role text NOT NULL +); + + +-- +-- Name: model_version_files_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.model_version_files_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: model_version_files_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.model_version_files_id_seq OWNED BY public.model_version_files.id; + + +-- +-- Name: model_versions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_versions ( + id bigint NOT NULL, + model_id text NOT NULL, + version text NOT NULL, + r2_prefix text NOT NULL, + aggregate_sha256 text NOT NULL, + total_size_bytes bigint NOT NULL, + file_count integer NOT NULL, + status text DEFAULT 'ready'::text NOT NULL, + uploaded_by text DEFAULT ''::text NOT NULL, + uploaded_at timestamp with time zone DEFAULT now() NOT NULL, + promoted_at timestamp with time zone, + metadata jsonb DEFAULT '{}'::jsonb NOT NULL, + hugging_face_artifact jsonb +); + + +-- +-- Name: model_versions_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.model_versions_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: model_versions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.model_versions_id_seq OWNED BY public.model_versions.id; + + +-- +-- Name: payments; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.payments ( + id bigint NOT NULL, + tx_hash text, + consumer_address text NOT NULL, + provider_address text NOT NULL, + amount_usd text NOT NULL, + model text NOT NULL, + prompt_tokens integer NOT NULL, + completion_tokens integer NOT NULL, + memo text, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: payments_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.payments_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: payments_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.payments_id_seq OWNED BY public.payments.id; + + +-- +-- Name: provider_earnings; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_earnings ( + id bigint NOT NULL, + account_id text NOT NULL, + provider_id text NOT NULL, + provider_key text DEFAULT ''::text NOT NULL, + job_id text NOT NULL, + model text NOT NULL, + amount_micro_usd bigint NOT NULL, + prompt_tokens integer DEFAULT 0 NOT NULL, + completion_tokens integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +) +WITH (autovacuum_analyze_scale_factor='0.005'); + + +-- +-- Name: provider_earnings_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_earnings_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_earnings_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_earnings_id_seq OWNED BY public.provider_earnings.id; + + +-- +-- Name: provider_floor_draws; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_floor_draws ( + id bigint NOT NULL, + provider_key text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + epoch_id text NOT NULL, + amount_micro_usd bigint NOT NULL, + floor_micro_usd bigint DEFAULT 0 NOT NULL, + earned_micro_usd bigint DEFAULT 0 NOT NULL, + uptime_frac double precision DEFAULT 0 NOT NULL, + memory_gb integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_floor_draws_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_floor_draws_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_floor_draws_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_floor_draws_id_seq OWNED BY public.provider_floor_draws.id; + + +-- +-- Name: provider_log_reports; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_log_reports ( + id bigint NOT NULL, + serial_number text DEFAULT ''::text NOT NULL, + provider_id text DEFAULT ''::text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + log_data bytea NOT NULL, + log_size_bytes bigint DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_log_reports_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_log_reports_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_log_reports_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_log_reports_id_seq OWNED BY public.provider_log_reports.id; + + +-- +-- Name: provider_payouts; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_payouts ( + id bigint NOT NULL, + provider_address text NOT NULL, + amount_micro_usd bigint NOT NULL, + model text DEFAULT ''::text NOT NULL, + job_id text DEFAULT ''::text NOT NULL, + settled boolean DEFAULT false NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_payouts_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_payouts_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_payouts_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_payouts_id_seq OWNED BY public.provider_payouts.id; + + +-- +-- Name: provider_reputation; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_reputation ( + provider_id text NOT NULL, + total_jobs integer DEFAULT 0 NOT NULL, + successful_jobs integer DEFAULT 0 NOT NULL, + failed_jobs integer DEFAULT 0 NOT NULL, + total_uptime_seconds bigint DEFAULT 0 NOT NULL, + avg_response_time_ms bigint DEFAULT 0 NOT NULL, + challenges_passed integer DEFAULT 0 NOT NULL, + challenges_failed integer DEFAULT 0 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_sessions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_sessions ( + id bigint NOT NULL, + session_id text NOT NULL, + serial_number text DEFAULT ''::text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + connected_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen timestamp with time zone DEFAULT now() NOT NULL, + disconnected_at timestamp with time zone, + disconnect_reason text DEFAULT ''::text NOT NULL, + provider_key text DEFAULT ''::text NOT NULL +); + + +-- +-- Name: provider_sessions_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_sessions_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_sessions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_sessions_id_seq OWNED BY public.provider_sessions.id; + + +-- +-- Name: provider_tokens; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_tokens ( + token_hash text NOT NULL, + account_id text NOT NULL, + label text DEFAULT ''::text NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_trust_reuse; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_trust_reuse ( + se_pubkey text NOT NULL, + serial text DEFAULT ''::text NOT NULL, + trust_level text DEFAULT ''::text NOT NULL, + binary_hash text DEFAULT ''::text NOT NULL, + sip_enabled boolean DEFAULT false NOT NULL, + secure_boot_full boolean DEFAULT false NOT NULL, + mda_udid text DEFAULT ''::text NOT NULL, + verified_at timestamp with time zone DEFAULT now() NOT NULL, + last_verified_binary_hash text DEFAULT ''::text NOT NULL, + hardware_proof_verified_at timestamp with time zone DEFAULT now() NOT NULL, + application_proof_verified_at timestamp with time zone, + evidence_generation bigint DEFAULT 1 NOT NULL, + revocation_generation bigint DEFAULT 0 NOT NULL, + revocation_event_id text DEFAULT ''::text NOT NULL, + revoked_at timestamp with time zone, + continuous_coverage_until timestamp with time zone +); + + +-- +-- Name: provider_verification_jobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_verification_jobs ( + se_pubkey text NOT NULL, + serial text DEFAULT ''::text NOT NULL, + udid text DEFAULT ''::text NOT NULL, + task_kind text NOT NULL, + task_state text NOT NULL, + priority smallint NOT NULL, + retry_stage integer DEFAULT 0 NOT NULL, + previous_delay_ns bigint DEFAULT 0 NOT NULL, + next_attempt_at timestamp with time zone, + last_outcome text DEFAULT 'none'::text NOT NULL, + reopen_pending boolean DEFAULT false NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + claim_owner text DEFAULT ''::text NOT NULL, + claim_expires_at timestamp with time zone +); + + +-- +-- Name: providers; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.providers ( + id text NOT NULL, + hardware jsonb NOT NULL, + models jsonb NOT NULL, + backend text NOT NULL, + location jsonb, + registered_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen timestamp with time zone DEFAULT now() NOT NULL, + trust_level text DEFAULT 'none'::text NOT NULL, + attested boolean DEFAULT false NOT NULL, + attestation_result jsonb, + se_public_key text DEFAULT ''::text NOT NULL, + public_key text DEFAULT ''::text NOT NULL, + serial_number text DEFAULT ''::text NOT NULL, + mda_verified boolean DEFAULT false NOT NULL, + mda_cert_chain jsonb, + version text DEFAULT ''::text NOT NULL, + runtime_verified boolean DEFAULT false NOT NULL, + python_hash text DEFAULT ''::text NOT NULL, + runtime_hash text DEFAULT ''::text NOT NULL, + last_challenge_verified timestamp with time zone, + failed_challenges integer DEFAULT 0 NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + lifetime_requests_served bigint DEFAULT 0 NOT NULL, + lifetime_tokens_generated bigint DEFAULT 0 NOT NULL, + last_session_requests_served bigint DEFAULT 0 NOT NULL, + last_session_tokens_generated bigint DEFAULT 0 NOT NULL, + lifetime_stats jsonb DEFAULT '{}'::jsonb NOT NULL, + last_session_stats jsonb DEFAULT '{}'::jsonb NOT NULL +); + + +-- +-- Name: publishing_api_keys; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.publishing_api_keys ( + id text NOT NULL, + name text NOT NULL, + key_hash text NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + last_used_at timestamp with time zone +); + + +-- +-- Name: referrals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.referrals ( + referred_account text NOT NULL, + referrer_code text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: referrers; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.referrers ( + account_id text NOT NULL, + code text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: releases; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.releases ( + version text NOT NULL, + platform text NOT NULL, + backend text DEFAULT ''::text NOT NULL, + binary_hash text DEFAULT ''::text NOT NULL, + bundle_hash text DEFAULT ''::text NOT NULL, + metallib_hash text DEFAULT ''::text NOT NULL, + python_hash text DEFAULT ''::text NOT NULL, + runtime_hash text DEFAULT ''::text NOT NULL, + template_hashes text DEFAULT ''::text NOT NULL, + grpc_binary_hash text DEFAULT ''::text NOT NULL, + url text DEFAULT ''::text NOT NULL, + changelog text DEFAULT ''::text NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: request_outcomes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.request_outcomes ( + id bigint NOT NULL, + coord_request_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone NOT NULL, + revision bigint NOT NULL, + evidence_conflict boolean DEFAULT false NOT NULL, + record jsonb NOT NULL, + CONSTRAINT request_outcomes_coord_request_id_check CHECK ((coord_request_id <> ''::text)) +); + + +-- +-- Name: request_outcomes_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.request_outcomes_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: request_outcomes_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.request_outcomes_id_seq OWNED BY public.request_outcomes.id; + + +-- +-- Name: request_profiles; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.request_profiles ( + id bigint NOT NULL, + coord_request_id text NOT NULL, + request_id text NOT NULL, + attempt integer NOT NULL, + backup_of text DEFAULT ''::text NOT NULL, + winning boolean DEFAULT false NOT NULL, + endpoint text DEFAULT ''::text NOT NULL, + stream boolean DEFAULT false NOT NULL, + model text DEFAULT ''::text NOT NULL, + public_model text DEFAULT ''::text NOT NULL, + provider_id text DEFAULT ''::text NOT NULL, + provider_version text DEFAULT ''::text NOT NULL, + chip_family text DEFAULT ''::text NOT NULL, + kv_backend text DEFAULT ''::text NOT NULL, + final_status text DEFAULT ''::text NOT NULL, + error_reason text DEFAULT ''::text NOT NULL, + terminal_cause text DEFAULT ''::text NOT NULL, + client_outcome text DEFAULT ''::text NOT NULL, + provider_outcome text DEFAULT ''::text NOT NULL, + client_gone_phase text DEFAULT ''::text NOT NULL, + first_content_budget_ms integer DEFAULT 0 NOT NULL, + admission_mode text DEFAULT ''::text NOT NULL, + predictive_bypass text DEFAULT ''::text NOT NULL, + reservation_ttft_ceiling_ms double precision, + dispatch_budget_ms bigint, + estimated_prompt_tokens integer DEFAULT 0 NOT NULL, + requested_max_tokens integer DEFAULT 0 NOT NULL, + requires_vision boolean DEFAULT false NOT NULL, + has_tools boolean DEFAULT false NOT NULL, + received_at timestamp with time zone NOT NULL, + auth_done_us bigint, + ratelimit_done_us bigint, + sealed_open_us bigint, + handler_entry_us bigint, + parsed_us bigint, + reserved_us bigint, + media_fetched_us bigint, + preflight_done_us bigint, + plan_done_us bigint, + attempt_start_us bigint, + reserve_lock_acquired_us bigint, + reserve_done_us bigint, + queued_us bigint, + dequeued_us bigint, + topup_done_us bigint, + encrypted_us bigint, + write_submitted_us bigint, + write_dequeued_us bigint, + write_done_us bigint, + accepted_us bigint, + first_chunk_ingress_us bigint, + first_chunk_dequeued_us bigint, + first_content_ingress_us bigint, + first_content_us bigint, + headers_written_us bigint, + first_flush_us bigint, + last_flush_us bigint, + client_gone_us bigint, + cancel_sent_us bigint, + complete_ingress_us bigint, + done_flushed_us bigint, + finalized_us bigint, + settle_db_us bigint, + db_us bigint, + db_calls integer DEFAULT 0 NOT NULL, + body_bytes integer DEFAULT 0 NOT NULL, + sealed_body_bytes integer DEFAULT 0 NOT NULL, + auth_kind text DEFAULT ''::text NOT NULL, + auth_db_read boolean DEFAULT false NOT NULL, + reserve_mode text DEFAULT ''::text NOT NULL, + media_items integer DEFAULT 0 NOT NULL, + media_bytes bigint DEFAULT 0 NOT NULL, + preflight_outcome text DEFAULT ''::text NOT NULL, + plan_outcome text DEFAULT ''::text NOT NULL, + chunks_in integer DEFAULT 0 NOT NULL, + chunks_out integer DEFAULT 0 NOT NULL, + bytes_out bigint DEFAULT 0 NOT NULL, + decrypt_us_total bigint DEFAULT 0 NOT NULL, + max_chunk_gap_us bigint DEFAULT 0 NOT NULL, + held_preamble_chunks integer DEFAULT 0 NOT NULL, + client_write_err boolean DEFAULT false NOT NULL, + attempts_total integer DEFAULT 0 NOT NULL, + failed_attempts integer DEFAULT 0 NOT NULL, + failed_attempts_us bigint DEFAULT 0 NOT NULL, + backup_launched boolean DEFAULT false NOT NULL, + backup_won boolean DEFAULT false NOT NULL, + transport_est_us bigint, + slept_us bigint, + timing_anomaly boolean DEFAULT false NOT NULL, + candidate_set_size integer DEFAULT 0 NOT NULL, + scanned integer DEFAULT 0 NOT NULL, + gate_rejections jsonb, + runner_up_provider_id text DEFAULT ''::text NOT NULL, + runner_up_cost_ms double precision DEFAULT 0 NOT NULL, + near_tie_pool_size integer DEFAULT 0 NOT NULL, + selection_path text DEFAULT ''::text NOT NULL, + best_idle_provider_id text DEFAULT ''::text NOT NULL, + best_idle_ttft_ms double precision DEFAULT 0 NOT NULL, + predicted_ttft_ms double precision DEFAULT 0 NOT NULL, + raw_ttft_ms double precision DEFAULT 0 NOT NULL, + predicted_decode_tps double precision DEFAULT 0 NOT NULL, + snapshot_age_ms integer DEFAULT 0 NOT NULL, + pending_for_model integer DEFAULT 0 NOT NULL, + total_pending integer DEFAULT 0 NOT NULL, + capacity_rate_ms double precision DEFAULT 0 NOT NULL, + cache_discount_ms double precision DEFAULT 0 NOT NULL, + shadow_would_shed boolean, + shadow_idle_alternative boolean, + lock_wait_us bigint DEFAULT 0 NOT NULL, + scan_us bigint DEFAULT 0 NOT NULL, + admit_us bigint DEFAULT 0 NOT NULL, + preflight_us bigint DEFAULT 0 NOT NULL, + ttft_calibration_ratio double precision DEFAULT 0 NOT NULL, + prefill_decode_ratio double precision DEFAULT 0 NOT NULL, + queue_position_at_enqueue integer DEFAULT 0 NOT NULL, + queue_depth_at_enqueue integer DEFAULT 0 NOT NULL, + drain_trigger text DEFAULT ''::text NOT NULL, + candidates jsonb, + prov_total_us bigint, + prov_first_delta_us bigint, + prov_engine_submit_us bigint, + prov_engine_admitted_us bigint, + prov_prompt_prep_us bigint, + prov_load_wait_us bigint, + prov_load_cold boolean, + prov_running_at_admit integer, + prov_waiting_at_admit integer, + prov_kv_bytes_in_use_at_admit bigint, + prov_cancel_stage text DEFAULT ''::text NOT NULL, + eng_queue_wait_ns bigint, + eng_first_token_ns bigint, + eng_prompt_computed_ns bigint, + eng_prefill_chunks integer, + eng_decode_steps integer, + eng_mtp_accepted integer, + eng_finish_reason text DEFAULT ''::text NOT NULL, + provider_profile jsonb, + provider_profile_valid boolean DEFAULT false NOT NULL, + provider_profile_invalid_reason text DEFAULT ''::text NOT NULL, + provider_profile_consistent boolean, + created_at timestamp with time zone DEFAULT now() NOT NULL +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01'); + + +-- +-- Name: request_profiles_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.request_profiles_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: request_profiles_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.request_profiles_id_seq OWNED BY public.request_profiles.id; + + +-- +-- Name: request_rejections; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.request_rejections ( + id bigint NOT NULL, + request_id text, + endpoint text, + stage text, + reason_code text, + http_status integer, + consumer_key_hash text, + key_id text, + client_class text, + requested_model text, + resolved_model text, + stream boolean, + n integer, + estimated_prompt_tokens integer, + requested_max_tokens integer, + requires_vision boolean, + has_image boolean, + has_audio boolean, + has_tools boolean, + tool_count integer, + response_format text, + self_route_only boolean, + prefer_owner boolean, + params jsonb, + request_body_bytes integer, + retry_after_ms integer, + could_have_served boolean, + candidate_count integer, + capacity_rejections integer, + model_too_large_rejections integer, + vision_rejections integer, + warm_provider_existed boolean, + best_ttft_ms double precision, + shortfall_micro_usd bigint, + limit_kind text, + over_by bigint, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: request_rejections_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.request_rejections_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: request_rejections_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.request_rejections_id_seq OWNED BY public.request_rejections.id; + + +-- +-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.schema_migrations ( + id text NOT NULL, + applied_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: stripe_withdrawals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.stripe_withdrawals ( + id text NOT NULL, + account_id text NOT NULL, + stripe_account_id text NOT NULL, + transfer_id text DEFAULT ''::text NOT NULL, + payout_id text DEFAULT ''::text NOT NULL, + amount_micro_usd bigint NOT NULL, + fee_micro_usd bigint DEFAULT 0 NOT NULL, + net_micro_usd bigint NOT NULL, + method text NOT NULL, + status text NOT NULL, + failure_reason text DEFAULT ''::text NOT NULL, + refunded boolean DEFAULT false NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + fee_refunded boolean DEFAULT false NOT NULL, + sweep_payout_id text DEFAULT ''::text NOT NULL +); + + +-- +-- Name: usage; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.usage ( + id bigint NOT NULL, + provider_id text NOT NULL, + consumer_key_hash text NOT NULL, + key_id text DEFAULT ''::text NOT NULL, + model text NOT NULL, + public_model text DEFAULT ''::text NOT NULL, + prompt_tokens integer NOT NULL, + cached_tokens integer DEFAULT 0 NOT NULL, + completion_tokens integer NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + request_id text DEFAULT ''::text NOT NULL, + cost_micro_usd bigint DEFAULT 0 NOT NULL, + request_location jsonb +); + + +-- +-- Name: usage_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.usage_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: usage_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.usage_id_seq OWNED BY public.usage.id; + + +-- +-- Name: usage_totals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.usage_totals ( + id integer DEFAULT 1 NOT NULL, + total_requests bigint DEFAULT 0 NOT NULL, + total_prompt_tokens bigint DEFAULT 0 NOT NULL, + total_completion_tokens bigint DEFAULT 0 NOT NULL, + CONSTRAINT usage_totals_id_check CHECK ((id = 1)) +); + + +-- +-- Name: users; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.users ( + account_id text NOT NULL, + privy_user_id text NOT NULL, + email text DEFAULT ''::text NOT NULL, + role text DEFAULT ''::text NOT NULL, + platform_fee_percent bigint, + created_at timestamp with time zone DEFAULT now() NOT NULL, + stripe_account_id text DEFAULT ''::text NOT NULL, + stripe_account_status text DEFAULT ''::text NOT NULL, + stripe_account_country text DEFAULT ''::text NOT NULL, + stripe_destination_type text DEFAULT ''::text NOT NULL, + stripe_destination_last4 text DEFAULT ''::text NOT NULL, + stripe_instant_eligible boolean DEFAULT false NOT NULL +); + + +-- +-- Name: fleet_snapshots id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.fleet_snapshots ALTER COLUMN id SET DEFAULT nextval('public.fleet_snapshots_id_seq'::regclass); + + +-- +-- Name: inference_routes id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.inference_routes ALTER COLUMN id SET DEFAULT nextval('public.inference_routes_id_seq'::regclass); + + +-- +-- Name: ledger_entries id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.ledger_entries ALTER COLUMN id SET DEFAULT nextval('public.ledger_entries_id_seq'::regclass); + + +-- +-- Name: model_demand_requests id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_requests ALTER COLUMN id SET DEFAULT nextval('public.model_demand_requests_id_seq'::regclass); + + +-- +-- Name: model_version_files id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files ALTER COLUMN id SET DEFAULT nextval('public.model_version_files_id_seq'::regclass); + + +-- +-- Name: model_versions id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions ALTER COLUMN id SET DEFAULT nextval('public.model_versions_id_seq'::regclass); + + +-- +-- Name: payments id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.payments ALTER COLUMN id SET DEFAULT nextval('public.payments_id_seq'::regclass); + + +-- +-- Name: provider_earnings id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_earnings ALTER COLUMN id SET DEFAULT nextval('public.provider_earnings_id_seq'::regclass); + + +-- +-- Name: provider_floor_draws id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_floor_draws ALTER COLUMN id SET DEFAULT nextval('public.provider_floor_draws_id_seq'::regclass); + + +-- +-- Name: provider_log_reports id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_log_reports ALTER COLUMN id SET DEFAULT nextval('public.provider_log_reports_id_seq'::regclass); + + +-- +-- Name: provider_payouts id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_payouts ALTER COLUMN id SET DEFAULT nextval('public.provider_payouts_id_seq'::regclass); + + +-- +-- Name: provider_sessions id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_sessions ALTER COLUMN id SET DEFAULT nextval('public.provider_sessions_id_seq'::regclass); + + +-- +-- Name: request_outcomes id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_outcomes ALTER COLUMN id SET DEFAULT nextval('public.request_outcomes_id_seq'::regclass); + + +-- +-- Name: request_profiles id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_profiles ALTER COLUMN id SET DEFAULT nextval('public.request_profiles_id_seq'::regclass); + + +-- +-- Name: request_rejections id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_rejections ALTER COLUMN id SET DEFAULT nextval('public.request_rejections_id_seq'::regclass); + + +-- +-- Name: usage id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.usage ALTER COLUMN id SET DEFAULT nextval('public.usage_id_seq'::regclass); + + +-- +-- Name: api_keys api_keys_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.api_keys + ADD CONSTRAINT api_keys_pkey PRIMARY KEY (key_hash); + + +-- +-- Name: app_attest_build_qualifications app_attest_build_qualifications_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_build_qualifications + ADD CONSTRAINT app_attest_build_qualifications_pkey PRIMARY KEY (binary_hash); + + +-- +-- Name: app_attest_enrollments app_attest_enrollments_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_enrollments + ADD CONSTRAINT app_attest_enrollments_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_evidence_blobs app_attest_evidence_blobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_evidence_blobs + ADD CONSTRAINT app_attest_evidence_blobs_pkey PRIMARY KEY (evidence_id); + + +-- +-- Name: app_attest_evidence app_attest_evidence_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_evidence + ADD CONSTRAINT app_attest_evidence_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_key_revocations app_attest_key_revocations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_key_revocations + ADD CONSTRAINT app_attest_key_revocations_pkey PRIMARY KEY (key_id); + + +-- +-- Name: app_attest_key_rotations app_attest_key_rotations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_key_rotations + ADD CONSTRAINT app_attest_key_rotations_pkey PRIMARY KEY (key_id); + + +-- +-- Name: app_attest_receipt_blobs app_attest_receipt_blobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_blobs + ADD CONSTRAINT app_attest_receipt_blobs_pkey PRIMARY KEY (receipt_id); + + +-- +-- Name: app_attest_receipt_jobs app_attest_receipt_jobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_jobs + ADD CONSTRAINT app_attest_receipt_jobs_pkey PRIMARY KEY (key_id); + + +-- +-- Name: app_attest_receipts app_attest_receipts_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipts + ADD CONSTRAINT app_attest_receipts_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_shadow_events app_attest_shadow_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_shadow_events + ADD CONSTRAINT app_attest_shadow_events_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_shadow_keys app_attest_shadow_keys_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_shadow_keys + ADD CONSTRAINT app_attest_shadow_keys_pkey PRIMARY KEY (key_id); + + +-- +-- Name: autopilot_events autopilot_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.autopilot_events + ADD CONSTRAINT autopilot_events_pkey PRIMARY KEY (command_id, phase); + + +-- +-- Name: balances balances_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.balances + ADD CONSTRAINT balances_pkey PRIMARY KEY (account_id); + + +-- +-- Name: billing_sessions billing_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.billing_sessions + ADD CONSTRAINT billing_sessions_pkey PRIMARY KEY (id); + + +-- +-- Name: cache_routing_demand cache_routing_demand_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.cache_routing_demand + ADD CONSTRAINT cache_routing_demand_pkey PRIMARY KEY (key); + + +-- +-- Name: cache_routing_holders cache_routing_holders_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.cache_routing_holders + ADD CONSTRAINT cache_routing_holders_pkey PRIMARY KEY (key, cache_epoch); + + +-- +-- Name: cache_routing_meta cache_routing_meta_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.cache_routing_meta + ADD CONSTRAINT cache_routing_meta_pkey PRIMARY KEY (name); + + +-- +-- Name: code_attest_push_budgets code_attest_push_budgets_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.code_attest_push_budgets + ADD CONSTRAINT code_attest_push_budgets_pkey PRIMARY KEY (se_pubkey, token_hash); + + +-- +-- Name: code_attestations code_attestations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.code_attestations + ADD CONSTRAINT code_attestations_pkey PRIMARY KEY (se_pubkey); + + +-- +-- Name: darkbloom_machine_aliases darkbloom_machine_aliases_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_aliases + ADD CONSTRAINT darkbloom_machine_aliases_pkey PRIMARY KEY (kind, scope, digest); + + +-- +-- Name: darkbloom_machine_merges darkbloom_machine_merges_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_merges + ADD CONSTRAINT darkbloom_machine_merges_pkey PRIMARY KEY (source_id); + + +-- +-- Name: darkbloom_machine_observations darkbloom_machine_observations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_observations + ADD CONSTRAINT darkbloom_machine_observations_pkey PRIMARY KEY (session_id, observed_at); + + +-- +-- Name: darkbloom_machine_sessions darkbloom_machine_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_sessions + ADD CONSTRAINT darkbloom_machine_sessions_pkey PRIMARY KEY (session_id); + + +-- +-- Name: darkbloom_machines darkbloom_machines_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machines + ADD CONSTRAINT darkbloom_machines_pkey PRIMARY KEY (id); + + +-- +-- Name: device_codes device_codes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.device_codes + ADD CONSTRAINT device_codes_pkey PRIMARY KEY (device_code); + + +-- +-- Name: device_codes device_codes_user_code_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.device_codes + ADD CONSTRAINT device_codes_user_code_key UNIQUE (user_code); + + +-- +-- Name: earnings_summary earnings_summary_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.earnings_summary + ADD CONSTRAINT earnings_summary_pkey PRIMARY KEY (key, key_type); + + +-- +-- Name: fleet_snapshots fleet_snapshots_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.fleet_snapshots + ADD CONSTRAINT fleet_snapshots_pkey PRIMARY KEY (id); + + +-- +-- Name: global_payout_recipients global_payout_recipients_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.global_payout_recipients + ADD CONSTRAINT global_payout_recipients_pkey PRIMARY KEY (account_id); + + +-- +-- Name: global_payout_withdrawals global_payout_withdrawals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.global_payout_withdrawals + ADD CONSTRAINT global_payout_withdrawals_pkey PRIMARY KEY (id); + + +-- +-- Name: inference_routes inference_routes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.inference_routes + ADD CONSTRAINT inference_routes_pkey PRIMARY KEY (id); + + +-- +-- Name: inference_routes inference_routes_request_id_attempt_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.inference_routes + ADD CONSTRAINT inference_routes_request_id_attempt_key UNIQUE (request_id, attempt); + + +-- +-- Name: invite_codes invite_codes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.invite_codes + ADD CONSTRAINT invite_codes_pkey PRIMARY KEY (code); + + +-- +-- Name: invite_redemptions invite_redemptions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.invite_redemptions + ADD CONSTRAINT invite_redemptions_pkey PRIMARY KEY (code, account_id); + + +-- +-- Name: ledger_entries ledger_entries_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.ledger_entries + ADD CONSTRAINT ledger_entries_pkey PRIMARY KEY (id); + + +-- +-- Name: model_active_versions model_active_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_active_versions + ADD CONSTRAINT model_active_versions_pkey PRIMARY KEY (model_id); + + +-- +-- Name: model_aliases model_aliases_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_aliases + ADD CONSTRAINT model_aliases_pkey PRIMARY KEY (alias_id); + + +-- +-- Name: model_demand_collection model_demand_collection_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_collection + ADD CONSTRAINT model_demand_collection_pkey PRIMARY KEY (singleton); + + +-- +-- Name: model_demand_hourly model_demand_hourly_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_hourly + ADD CONSTRAINT model_demand_hourly_pkey PRIMARY KEY (hour, model, consumer_hash); + + +-- +-- Name: model_demand_requests model_demand_requests_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_requests + ADD CONSTRAINT model_demand_requests_id_key UNIQUE (id); + + +-- +-- Name: model_demand_requests model_demand_requests_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_requests + ADD CONSTRAINT model_demand_requests_pkey PRIMARY KEY (coord_request_id); + + +-- +-- Name: model_prices model_prices_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_prices + ADD CONSTRAINT model_prices_pkey PRIMARY KEY (account_id, model); + + +-- +-- Name: model_registry model_registry_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_registry + ADD CONSTRAINT model_registry_pkey PRIMARY KEY (id); + + +-- +-- Name: model_token_grants model_token_grants_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_grants + ADD CONSTRAINT model_token_grants_pkey PRIMARY KEY (account_id, model_id); + + +-- +-- Name: model_token_promotions model_token_promotions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_promotions + ADD CONSTRAINT model_token_promotions_pkey PRIMARY KEY (model_id); + + +-- +-- Name: model_token_provider_carries model_token_provider_carries_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_provider_carries + ADD CONSTRAINT model_token_provider_carries_pkey PRIMARY KEY (account_id); + + +-- +-- Name: model_token_reservations model_token_reservations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_reservations + ADD CONSTRAINT model_token_reservations_pkey PRIMARY KEY (id); + + +-- +-- Name: model_version_files model_version_files_model_version_id_path_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files + ADD CONSTRAINT model_version_files_model_version_id_path_key UNIQUE (model_version_id, path); + + +-- +-- Name: model_version_files model_version_files_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files + ADD CONSTRAINT model_version_files_pkey PRIMARY KEY (id); + + +-- +-- Name: model_versions model_versions_model_id_version_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions + ADD CONSTRAINT model_versions_model_id_version_key UNIQUE (model_id, version); + + +-- +-- Name: model_versions model_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions + ADD CONSTRAINT model_versions_pkey PRIMARY KEY (id); + + +-- +-- Name: payments payments_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.payments + ADD CONSTRAINT payments_pkey PRIMARY KEY (id); + + +-- +-- Name: payments payments_tx_hash_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.payments + ADD CONSTRAINT payments_tx_hash_key UNIQUE (tx_hash); + + +-- +-- Name: provider_earnings provider_earnings_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_earnings + ADD CONSTRAINT provider_earnings_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_floor_draws provider_floor_draws_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_floor_draws + ADD CONSTRAINT provider_floor_draws_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_floor_draws provider_floor_draws_provider_key_epoch_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_floor_draws + ADD CONSTRAINT provider_floor_draws_provider_key_epoch_id_key UNIQUE (provider_key, epoch_id); + + +-- +-- Name: provider_log_reports provider_log_reports_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_log_reports + ADD CONSTRAINT provider_log_reports_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_payouts provider_payouts_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_payouts + ADD CONSTRAINT provider_payouts_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_reputation provider_reputation_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_reputation + ADD CONSTRAINT provider_reputation_pkey PRIMARY KEY (provider_id); + + +-- +-- Name: provider_sessions provider_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_sessions + ADD CONSTRAINT provider_sessions_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_sessions provider_sessions_session_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_sessions + ADD CONSTRAINT provider_sessions_session_id_key UNIQUE (session_id); + + +-- +-- Name: provider_tokens provider_tokens_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_tokens + ADD CONSTRAINT provider_tokens_pkey PRIMARY KEY (token_hash); + + +-- +-- Name: provider_trust_reuse provider_trust_reuse_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_trust_reuse + ADD CONSTRAINT provider_trust_reuse_pkey PRIMARY KEY (se_pubkey); + + +-- +-- Name: provider_verification_jobs provider_verification_jobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_verification_jobs + ADD CONSTRAINT provider_verification_jobs_pkey PRIMARY KEY (se_pubkey, task_kind); + + +-- +-- Name: providers providers_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.providers + ADD CONSTRAINT providers_pkey PRIMARY KEY (id); + + +-- +-- Name: publishing_api_keys publishing_api_keys_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.publishing_api_keys + ADD CONSTRAINT publishing_api_keys_pkey PRIMARY KEY (id); + + +-- +-- Name: referrals referrals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrals + ADD CONSTRAINT referrals_pkey PRIMARY KEY (referred_account); + + +-- +-- Name: referrers referrers_code_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrers + ADD CONSTRAINT referrers_code_key UNIQUE (code); + + +-- +-- Name: referrers referrers_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrers + ADD CONSTRAINT referrers_pkey PRIMARY KEY (account_id); + + +-- +-- Name: releases releases_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.releases + ADD CONSTRAINT releases_pkey PRIMARY KEY (version, platform); + + +-- +-- Name: request_outcomes request_outcomes_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_outcomes + ADD CONSTRAINT request_outcomes_id_key UNIQUE (id); + + +-- +-- Name: request_outcomes request_outcomes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_outcomes + ADD CONSTRAINT request_outcomes_pkey PRIMARY KEY (coord_request_id); + + +-- +-- Name: request_profiles request_profiles_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_profiles + ADD CONSTRAINT request_profiles_pkey PRIMARY KEY (id); + + +-- +-- Name: request_profiles request_profiles_request_id_attempt_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_profiles + ADD CONSTRAINT request_profiles_request_id_attempt_key UNIQUE (request_id, attempt); + + +-- +-- Name: request_rejections request_rejections_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_rejections + ADD CONSTRAINT request_rejections_pkey PRIMARY KEY (id); + + +-- +-- Name: schema_migrations schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.schema_migrations + ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (id); + + +-- +-- Name: stripe_withdrawals stripe_withdrawals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.stripe_withdrawals + ADD CONSTRAINT stripe_withdrawals_pkey PRIMARY KEY (id); + + +-- +-- Name: usage usage_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.usage + ADD CONSTRAINT usage_pkey PRIMARY KEY (id); + + +-- +-- Name: usage_totals usage_totals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.usage_totals + ADD CONSTRAINT usage_totals_pkey PRIMARY KEY (id); + + +-- +-- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_pkey PRIMARY KEY (account_id); + + +-- +-- Name: users users_privy_user_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_privy_user_id_key UNIQUE (privy_user_id); + + +-- +-- Name: app_attest_evidence_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_key ON public.app_attest_evidence USING btree (key_id, received_at DESC); + + +-- +-- Name: app_attest_evidence_pending; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_pending ON public.app_attest_evidence USING btree (received_at) WHERE (outcome = 'pending'::text); + + +-- +-- Name: app_attest_evidence_session; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_session ON public.app_attest_evidence USING btree (session_id, received_at DESC); + + +-- +-- Name: app_attest_evidence_time; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_time ON public.app_attest_evidence USING btree (received_at DESC); + + +-- +-- Name: app_attest_key_rotations_machine; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_key_rotations_machine ON public.app_attest_key_rotations USING btree (machine_id, requested_at DESC); + + +-- +-- Name: app_attest_receipts_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_receipts_key ON public.app_attest_receipts USING btree (key_id, received_at DESC); + + +-- +-- Name: app_attest_receipts_recovery; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_receipts_recovery ON public.app_attest_receipts USING btree (key_id, received_at DESC) WHERE (outcome = 'receipt_creation_time'::text); + + +-- +-- Name: app_attest_shadow_events_session; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_shadow_events_session ON public.app_attest_shadow_events USING btree (session_id, observed_at DESC); + + +-- +-- Name: app_attest_shadow_events_time; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_shadow_events_time ON public.app_attest_shadow_events USING btree (observed_at DESC); + + +-- +-- Name: autopilot_events_at; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX autopilot_events_at ON public.autopilot_events USING btree (at); + + +-- +-- Name: darkbloom_machine_sessions_machine; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machine_sessions_machine ON public.darkbloom_machine_sessions USING btree (machine_id, last_seen DESC); + + +-- +-- Name: darkbloom_machine_sessions_open; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machine_sessions_open ON public.darkbloom_machine_sessions USING btree (last_seen, session_id) WHERE (disconnected_at IS NULL); + + +-- +-- Name: darkbloom_machine_sessions_seen; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machine_sessions_seen ON public.darkbloom_machine_sessions USING btree (last_seen DESC); + + +-- +-- Name: darkbloom_machines_merged_into; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machines_merged_into ON public.darkbloom_machines USING btree (merged_into) WHERE (merged_into IS NOT NULL); + + +-- +-- Name: global_payout_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX global_payout_account ON public.global_payout_withdrawals USING btree (account_id, submitted_at DESC); + + +-- +-- Name: global_payout_external_id; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX global_payout_external_id ON public.global_payout_withdrawals USING btree (external_id) WHERE (external_id <> ''::text); + + +-- +-- Name: global_payout_quote_expiry; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX global_payout_quote_expiry ON public.global_payout_withdrawals USING btree (expires_at) WHERE (status = 'quoted'::text); + + +-- +-- Name: global_payout_reconcile; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX global_payout_reconcile ON public.global_payout_withdrawals USING btree (checked_at) WHERE (status = ANY (ARRAY['pending'::text, 'processing'::text, 'posted'::text])); + + +-- +-- Name: idx_api_keys_id; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_api_keys_id ON public.api_keys USING btree (id) WHERE (id <> ''::text); + + +-- +-- Name: idx_api_keys_owner; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_api_keys_owner ON public.api_keys USING btree (owner_account_id) WHERE (owner_account_id <> ''::text); + + +-- +-- Name: idx_billing_sessions_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_billing_sessions_account ON public.billing_sessions USING btree (account_id); + + +-- +-- Name: idx_billing_sessions_external; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_billing_sessions_external ON public.billing_sessions USING btree (external_id); + + +-- +-- Name: idx_cache_routing_demand_seen; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_cache_routing_demand_seen ON public.cache_routing_demand USING btree (seen_at); + + +-- +-- Name: idx_cache_routing_holders_expires; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_cache_routing_holders_expires ON public.cache_routing_holders USING btree (expires_at); + + +-- +-- Name: idx_cache_routing_holders_updated; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_cache_routing_holders_updated ON public.cache_routing_holders USING btree (updated_at); + + +-- +-- Name: idx_code_attest_push_budgets_due; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_code_attest_push_budgets_due ON public.code_attest_push_budgets USING btree (next_push_at); + + +-- +-- Name: idx_device_codes_user; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_device_codes_user ON public.device_codes USING btree (user_code); + + +-- +-- Name: idx_fleet_snapshots_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_fleet_snapshots_provider ON public.fleet_snapshots USING btree (provider_id, sampled_at DESC); + + +-- +-- Name: idx_fleet_snapshots_sampled; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_fleet_snapshots_sampled ON public.fleet_snapshots USING btree (sampled_at DESC); + + +-- +-- Name: idx_floor_draws_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_floor_draws_account ON public.provider_floor_draws USING btree (account_id, epoch_id); + + +-- +-- Name: idx_floor_draws_epoch; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_floor_draws_epoch ON public.provider_floor_draws USING btree (epoch_id); + + +-- +-- Name: idx_inference_routes_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_created ON public.inference_routes USING btree (created_at DESC); + + +-- +-- Name: idx_inference_routes_model; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_model ON public.inference_routes USING btree (model, created_at DESC); + + +-- +-- Name: idx_inference_routes_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_provider ON public.inference_routes USING btree (provider_id, created_at DESC); + + +-- +-- Name: idx_inference_routes_request; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_request ON public.inference_routes USING btree (request_id); + + +-- +-- Name: idx_ledger_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_ledger_account ON public.ledger_entries USING btree (account_id, created_at DESC); + + +-- +-- Name: idx_ledger_reward; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_ledger_reward ON public.ledger_entries USING btree (account_id, created_at DESC) WHERE (entry_type = ANY (ARRAY['referral_reward'::text, 'admin_reward'::text])); + + +-- +-- Name: idx_model_demand_received; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_demand_received ON public.model_demand_requests USING btree (received_at); + + +-- +-- Name: idx_model_registry_status; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_registry_status ON public.model_registry USING btree (status); + + +-- +-- Name: idx_model_token_reservations_open; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_token_reservations_open ON public.model_token_reservations USING btree (touched_at) WHERE (state = 'reserved'::text); + + +-- +-- Name: idx_model_version_files_version; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_version_files_version ON public.model_version_files USING btree (model_version_id); + + +-- +-- Name: idx_model_versions_model; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_versions_model ON public.model_versions USING btree (model_id); + + +-- +-- Name: idx_provider_earnings_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_earnings_account ON public.provider_earnings USING btree (account_id, created_at DESC); + + +-- +-- Name: idx_provider_earnings_created_at_brin; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_earnings_created_at_brin ON public.provider_earnings USING brin (created_at) WITH (autosummarize='on'); + + +-- +-- Name: idx_provider_earnings_job; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_provider_earnings_job ON public.provider_earnings USING btree (job_id) WHERE (job_id <> ''::text); + + +-- +-- Name: idx_provider_earnings_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_earnings_provider ON public.provider_earnings USING btree (provider_key, created_at DESC); + + +-- +-- Name: idx_provider_payouts_address; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_payouts_address ON public.provider_payouts USING btree (provider_address, created_at DESC); + + +-- +-- Name: idx_provider_payouts_settled; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_payouts_settled ON public.provider_payouts USING btree (settled, created_at DESC); + + +-- +-- Name: idx_provider_sessions_connected; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_connected ON public.provider_sessions USING btree (connected_at DESC); + + +-- +-- Name: idx_provider_sessions_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_key ON public.provider_sessions USING btree (provider_key, connected_at) WHERE (provider_key <> ''::text); + + +-- +-- Name: idx_provider_sessions_open; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_open ON public.provider_sessions USING btree (connected_at) WHERE (disconnected_at IS NULL); + + +-- +-- Name: idx_provider_sessions_serial; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_serial ON public.provider_sessions USING btree (serial_number, connected_at DESC); + + +-- +-- Name: idx_provider_tokens_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_tokens_account ON public.provider_tokens USING btree (account_id); + + +-- +-- Name: idx_provider_verification_jobs_claim; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_verification_jobs_claim ON public.provider_verification_jobs USING btree (claim_expires_at) WHERE (claim_owner <> ''::text); + + +-- +-- Name: idx_provider_verification_jobs_due; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_verification_jobs_due ON public.provider_verification_jobs USING btree (priority, next_attempt_at) WHERE (task_state = ANY (ARRAY['pending'::text, 'backoff'::text])); + + +-- +-- Name: idx_providers_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_account ON public.providers USING btree (account_id, last_seen DESC) WHERE (account_id <> ''::text); + + +-- +-- Name: idx_providers_restore_se_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_restore_se_key ON public.providers USING btree (se_public_key, last_seen DESC, id DESC) WHERE (se_public_key <> ''::text); + + +-- +-- Name: idx_providers_restore_serial; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_restore_serial ON public.providers USING btree (serial_number, last_seen DESC, id DESC) WHERE (serial_number <> ''::text); + + +-- +-- Name: idx_providers_serial; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_serial ON public.providers USING btree (serial_number) WHERE (serial_number <> ''::text); + + +-- +-- Name: idx_publishing_api_keys_hash; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_publishing_api_keys_hash ON public.publishing_api_keys USING btree (key_hash); + + +-- +-- Name: idx_referrals_code; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_referrals_code ON public.referrals USING btree (referrer_code); + + +-- +-- Name: idx_referrers_code; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_referrers_code ON public.referrers USING btree (code); + + +-- +-- Name: idx_request_outcomes_received; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_outcomes_received ON public.request_outcomes USING btree (received_at, coord_request_id); + + +-- +-- Name: idx_request_profiles_coord; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_profiles_coord ON public.request_profiles USING btree (coord_request_id); + + +-- +-- Name: idx_request_profiles_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_profiles_created ON public.request_profiles USING btree (created_at DESC); + + +-- +-- Name: idx_request_profiles_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_profiles_provider ON public.request_profiles USING btree (provider_id, created_at DESC); + + +-- +-- Name: idx_request_rejections_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_created ON public.request_rejections USING btree (created_at DESC); + + +-- +-- Name: idx_request_rejections_model; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_model ON public.request_rejections USING btree (resolved_model, created_at DESC); + + +-- +-- Name: idx_request_rejections_reason; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_reason ON public.request_rejections USING btree (reason_code, created_at DESC); + + +-- +-- Name: idx_request_rejections_servable; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_servable ON public.request_rejections USING btree (could_have_served, created_at DESC) WHERE (could_have_served = true); + + +-- +-- Name: idx_request_rejections_status; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_status ON public.request_rejections USING btree (http_status, created_at DESC); + + +-- +-- Name: idx_stripe_withdrawals_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_account ON public.stripe_withdrawals USING btree (account_id, created_at DESC); + + +-- +-- Name: idx_stripe_withdrawals_payout; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_stripe_withdrawals_payout ON public.stripe_withdrawals USING btree (payout_id) WHERE (payout_id <> ''::text); + + +-- +-- Name: idx_stripe_withdrawals_status; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_status ON public.stripe_withdrawals USING btree (status, created_at); + + +-- +-- Name: idx_stripe_withdrawals_stripe_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_stripe_account ON public.stripe_withdrawals USING btree (stripe_account_id, status); + + +-- +-- Name: idx_stripe_withdrawals_sweep_payout; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_sweep_payout ON public.stripe_withdrawals USING btree (sweep_payout_id) WHERE (sweep_payout_id <> ''::text); + + +-- +-- Name: idx_stripe_withdrawals_transfer; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_stripe_withdrawals_transfer ON public.stripe_withdrawals USING btree (transfer_id) WHERE (transfer_id <> ''::text); + + +-- +-- Name: idx_usage_consumer; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_consumer ON public.usage USING btree (consumer_key_hash, created_at DESC); + + +-- +-- Name: idx_usage_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_created ON public.usage USING btree (created_at DESC); + + +-- +-- Name: idx_usage_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_key ON public.usage USING btree (key_id, created_at DESC) WHERE (key_id <> ''::text); + + +-- +-- Name: idx_usage_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_provider ON public.usage USING btree (provider_id, created_at DESC); + + +-- +-- Name: idx_usage_request_location_notnull; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_request_location_notnull ON public.usage USING btree (created_at DESC) WHERE (request_location IS NOT NULL); + + +-- +-- Name: idx_users_privy; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_users_privy ON public.users USING btree (privy_user_id); + + +-- +-- Name: idx_users_stripe_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_users_stripe_account ON public.users USING btree (stripe_account_id) WHERE (stripe_account_id <> ''::text); + + +-- +-- Name: inference_routes clear_legacy_cache_affinity_key; Type: TRIGGER; Schema: public; Owner: - +-- + +CREATE TRIGGER clear_legacy_cache_affinity_key BEFORE INSERT OR UPDATE OF cache_affinity_key ON public.inference_routes FOR EACH ROW EXECUTE FUNCTION public.clear_legacy_cache_affinity_key(); + + +-- +-- Name: provider_log_reports clear_provider_log_report_serial; Type: TRIGGER; Schema: public; Owner: - +-- + +CREATE TRIGGER clear_provider_log_report_serial BEFORE INSERT OR UPDATE OF serial_number ON public.provider_log_reports FOR EACH ROW EXECUTE FUNCTION public.clear_provider_log_report_serial(); + + +-- +-- Name: model_demand_requests model_demand_rollup; Type: TRIGGER; Schema: public; Owner: - +-- + +CREATE TRIGGER model_demand_rollup AFTER INSERT OR UPDATE ON public.model_demand_requests FOR EACH ROW EXECUTE FUNCTION public.update_model_demand_hourly(); + + +-- +-- Name: app_attest_evidence_blobs app_attest_evidence_blobs_evidence_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_evidence_blobs + ADD CONSTRAINT app_attest_evidence_blobs_evidence_id_fkey FOREIGN KEY (evidence_id) REFERENCES public.app_attest_evidence(id); + + +-- +-- Name: app_attest_key_revocations app_attest_key_revocations_key_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_key_revocations + ADD CONSTRAINT app_attest_key_revocations_key_id_fkey FOREIGN KEY (key_id) REFERENCES public.app_attest_shadow_keys(key_id); + + +-- +-- Name: app_attest_receipt_blobs app_attest_receipt_blobs_receipt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_blobs + ADD CONSTRAINT app_attest_receipt_blobs_receipt_id_fkey FOREIGN KEY (receipt_id) REFERENCES public.app_attest_receipts(id); + + +-- +-- Name: app_attest_receipt_jobs app_attest_receipt_jobs_receipt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_jobs + ADD CONSTRAINT app_attest_receipt_jobs_receipt_id_fkey FOREIGN KEY (receipt_id) REFERENCES public.app_attest_receipts(id); + + +-- +-- Name: darkbloom_machine_aliases darkbloom_machine_aliases_machine_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_aliases + ADD CONSTRAINT darkbloom_machine_aliases_machine_id_fkey FOREIGN KEY (machine_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_merges darkbloom_machine_merges_source_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_merges + ADD CONSTRAINT darkbloom_machine_merges_source_id_fkey FOREIGN KEY (source_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_merges darkbloom_machine_merges_target_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_merges + ADD CONSTRAINT darkbloom_machine_merges_target_id_fkey FOREIGN KEY (target_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_sessions darkbloom_machine_sessions_machine_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_sessions + ADD CONSTRAINT darkbloom_machine_sessions_machine_id_fkey FOREIGN KEY (machine_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_sessions darkbloom_machine_sessions_original_machine_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_sessions + ADD CONSTRAINT darkbloom_machine_sessions_original_machine_id_fkey FOREIGN KEY (original_machine_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machines darkbloom_machines_merged_into_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machines + ADD CONSTRAINT darkbloom_machines_merged_into_fkey FOREIGN KEY (merged_into) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: invite_redemptions invite_redemptions_code_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.invite_redemptions + ADD CONSTRAINT invite_redemptions_code_fkey FOREIGN KEY (code) REFERENCES public.invite_codes(code); + + +-- +-- Name: model_active_versions model_active_versions_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_active_versions + ADD CONSTRAINT model_active_versions_model_id_fkey FOREIGN KEY (model_id) REFERENCES public.model_registry(id) ON DELETE CASCADE; + + +-- +-- Name: model_active_versions model_active_versions_model_version_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_active_versions + ADD CONSTRAINT model_active_versions_model_version_id_fkey FOREIGN KEY (model_version_id) REFERENCES public.model_versions(id) ON DELETE RESTRICT; + + +-- +-- Name: model_token_grants model_token_grants_account_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_grants + ADD CONSTRAINT model_token_grants_account_id_fkey FOREIGN KEY (account_id) REFERENCES public.users(account_id); + + +-- +-- Name: model_token_grants model_token_grants_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_grants + ADD CONSTRAINT model_token_grants_model_id_fkey FOREIGN KEY (model_id) REFERENCES public.model_token_promotions(model_id); + + +-- +-- Name: model_token_reservations model_token_reservations_account_id_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_reservations + ADD CONSTRAINT model_token_reservations_account_id_model_id_fkey FOREIGN KEY (account_id, model_id) REFERENCES public.model_token_grants(account_id, model_id); + + +-- +-- Name: model_version_files model_version_files_model_version_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files + ADD CONSTRAINT model_version_files_model_version_id_fkey FOREIGN KEY (model_version_id) REFERENCES public.model_versions(id) ON DELETE CASCADE; + + +-- +-- Name: model_versions model_versions_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions + ADD CONSTRAINT model_versions_model_id_fkey FOREIGN KEY (model_id) REFERENCES public.model_registry(id) ON DELETE CASCADE; + + +-- +-- Name: provider_reputation provider_reputation_provider_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_reputation + ADD CONSTRAINT provider_reputation_provider_id_fkey FOREIGN KEY (provider_id) REFERENCES public.providers(id); + + +-- +-- Name: referrals referrals_referrer_code_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrals + ADD CONSTRAINT referrals_referrer_code_fkey FOREIGN KEY (referrer_code) REFERENCES public.referrers(code); + + +-- +-- PostgreSQL database dump complete +-- + + diff --git a/coordinator/store/verification_scheduler_store_test.go b/coordinator/store/verification_scheduler_store_test.go index ddc970479f..9408400f21 100644 --- a/coordinator/store/verification_scheduler_store_test.go +++ b/coordinator/store/verification_scheduler_store_test.go @@ -211,12 +211,8 @@ func TestPostgresVerificationSchedulerMigrationIsIdempotent(t *testing.T) { ); err != nil { t.Fatalf("install legacy budget key: %v", err) } - if err := st.migrate(context.Background()); err != nil { - t.Fatalf("second scheduler migration: %v", err) - } - if err := st.migrate(context.Background()); err != nil { - t.Fatalf("third scheduler migration: %v", err) - } + replayMigrations(t, st) + replayMigrations(t, st) var compositeBudgetKey bool err := st.pool.QueryRow(context.Background(), ` SELECT EXISTS ( diff --git a/docs/README.md b/docs/README.md index 03ae36f79d..e854ada6a5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # Darkbloom documentation -> Last updated: 2026-09-28 +> Last updated: 2026-10-03 > Darkbloom is a decentralized private-inference network: an OpenAI- and > Anthropic-compatible HTTP API served by a Go coordinator that routes each @@ -104,6 +104,7 @@ - [`developer/navigation.md`](developer/navigation.md): find implementation and tests, choose descriptive filenames, and check path dependencies when moving files. - [`developer/build.md`](developer/build.md): build the coordinator, sidecar, provider, and UIs; toolchain pins. - [`developer/test.md`](developer/test.md): every test suite, what CI runs, how to run the e2e suite. +- [`developer/database-migrations.md`](developer/database-migrations.md): add a numbered goose migration and regenerate the checked-in schema. - [`developer/threat-model-review.md`](developer/threat-model-review.md): configure full PR text scans against the threat model and non-blocking author feedback. - [`developer/serving-performance-qualification.md`](developer/serving-performance-qualification.md): measure and review exact serving profiles before promoting concurrency limits or prefill policy. diff --git a/docs/architecture/request-accounting.md b/docs/architecture/request-accounting.md index 332bf9c095..9ee0d14680 100644 --- a/docs/architecture/request-accounting.md +++ b/docs/architecture/request-accounting.md @@ -1,6 +1,6 @@ # Incoming request accounting -> Last updated: 2026-09-26 +> Last updated: 2026-10-03 `request_outcomes` records unsampled observations of incoming inference requests, including early rejections, independently of sampled attempt profiles. Operators use this source to distinguish final request outcomes from internal retries. The public Stats page exposes a narrower, explicitly scoped recorded-request view; it does not establish traffic-wide completeness. @@ -126,7 +126,7 @@ outcomes. `coordinator/store/postgres_request_outcomes.go` (`RecordRequestOutcomes`) projects the winning revision into `model_demand_requests` in the same -transaction. Its trigger in `coordinator/store/model_demand_migration.go` +transaction. Its trigger `model_demand_rollup` (`coordinator/store/schema/migrations/00001_baseline.sql`) applies old/new deltas to `model_demand_hourly`; duplicate snapshots, late terminals and stale writes cannot create additional requests. Sticky evidence conflicts become unknown. The compact projection keeps revisions for 31 days, diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 39d20c97ab..482279a1fb 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -1,6 +1,6 @@ # Storage -> Last updated: 2026-10-02 +> Last updated: 2026-10-03 What the coordinator persists, through which interface, in which backend, and how the schema reaches a fresh database; then what a provider keeps on its own @@ -31,7 +31,7 @@ The additive [App Attest inventory and evidence tables](../reference/app-attest- Machine-session reconciliation uses a partial index over open sessions and bounded, row-locked batches to repair missed disconnect writes after contention or restart. Fresh inventory or provider-session heartbeats preserve liveness. Known closures retain their timestamp; inferred stale closures are labelled and can recover when fresh observations resume. Older observations and confirmed disconnects are fenced in `ObserveMachine`. See the [inventory lifecycle](../reference/app-attest-shadow.md#machine-inventory-and-identity) and `coordinator/store/machine_inventory_reconcile.go`. -Canonical history and reward queries use the existing inventory tables. `coordinator/store/machine_inventory_schema.go` adds the reverse-merge index `darkbloom_machines_merged_into`; include it in additive migration preflight. `coordinator/store/postgres_machine_floor_settlement.go` serializes canonical/raw-session settlement with inventory merges, preventing duplicate same-epoch floors without rewriting existing balances. Serving leases remain in memory and are re-established after reconnect. +Canonical history and reward queries use the existing inventory tables. The baseline adds the reverse-merge index `darkbloom_machines_merged_into` (`coordinator/store/schema/migrations/00001_baseline.sql`). `coordinator/store/postgres_machine_floor_settlement.go` serializes canonical/raw-session settlement with inventory merges, preventing duplicate same-epoch floors without rewriting existing balances. Serving leases remain in memory and are re-established after reconnect. Provider `attestation_result` JSON additively retains `OSVersion` from the signed registration blob (`coordinator/attestation/attestation.go`, `VerificationResult`). @@ -91,7 +91,7 @@ them to Datadog only (see [`telemetry.md`](telemetry.md)). | Backend | File | Selected when | Durability | |---|---|---|---| -| `PostgresStore` | `coordinator/store/postgres.go` (+ `postgres_*.go`) | `EIGENINFERENCE_DATABASE_URL` is set | Durable; the only backend for dev and production. In production the database is AWS RDS, outside the coordinator VM and its container, so a container swap or VM reboot cannot touch it ([`../operations/coordinator-deploy.md`](../operations/coordinator-deploy.md)). | +| `PostgresStore` | `coordinator/store/postgres.go` (+ `postgres_*.go`) | `EIGENINFERENCE_DATABASE_URL` is set | Durable; the only backend for dev and production. In production the database is Cloud SQL for PostgreSQL 17 in the `darkbloom-mainnet` project, with the read replica `d-inference-prod-pg17-ro`; it is outside the coordinator VM and its container, so a container swap or VM reboot cannot touch it ([`../operations/coordinator-deploy.md`](../operations/coordinator-deploy.md)). | | `MemoryStore` | `coordinator/store/memory.go` | No DSN **and** `EIGENINFERENCE_ALLOW_MEMORY_STORE=true` | Process memory; everything is lost on exit. | Selection is in `main` (`coordinator/cmd/coordinator/main.go`): with a DSN it @@ -111,22 +111,45 @@ stats endpoint can hold connections for seconds while heartbeat upserts, billing settlements and inference completions also need them. The DSN itself is the only connection-level knob; there is no separate host/user/password set. -### Migrations run inside the process, at every boot - -`coordinator --migrate-only` applies the same migrations and exits before admin -key seeding, listeners, or background workers. It requires a PostgreSQL URL; -there is no memory-store fallback or schema-skip mode. Normal startup still -checks every migration. There is no versioned migration directory for the -schema. `PostgresStore.migrate` (`coordinator/store/postgres.go`) executes an -ordered slice of idempotent statements — `CREATE TABLE IF NOT EXISTS`, -`ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, `DROP TABLE IF EXISTS` -for retired tables — on every start, followed by -`checkRetiredBackfills` (`postgres_retired_backfills.go`), -`ensureProviderRestoreIndexes` (`postgres_startup.go`) and -`ensureProviderEarningsJobIndex`, then `ensureProviderEarningsWindowIndex` -(`coordinator/store/postgres_earnings_window_index.go`). One-shot *data* migrations are gated by a row -in `schema_migrations` so they run at most once. Two SQL files under -`coordinator/store/migrations/` are deliberately **not** on that path and are +### Migrations are numbered goose versions + +The schema is a list of numbered migrations, applied by +[goose](https://github.com/pressly/goose) (`github.com/pressly/goose/v3`). +`NewPostgres` calls `PostgresStore.migrate` +(`coordinator/store/postgres_migrations.go`) before it returns. Goose applies +each version once and records it in `goose_db_version`; a later boot finds +nothing to apply. `coordinator --migrate-only` runs the same step and exits +before admin key seeding, listeners or background workers. It requires a +PostgreSQL URL; there is no memory-store fallback or schema-skip mode. + +| Version | Source | What it does | +|---|---|---| +| 1 | `coordinator/store/schema/migrations/00001_baseline.sql` | The 255 statements that the pre-goose boot ran on every start, unchanged and in the same order. Each block runs on its own, outside a transaction. On a database that already has the schema, every statement is a no-op. | +| 2 | `checkRetiredBackfills` (`coordinator/store/postgres_retired_backfills.go`) | The retired-backfill guard below. | +| 3 | `ensureProviderRestoreIndexes` (`coordinator/store/postgres_startup.go`) | Builds the two provider-restore indexes `CONCURRENTLY`. | +| 4 | `ensureProviderEarningsJobIndex` (`coordinator/store/postgres.go`) | Builds the `provider_earnings(job_id)` unique index `CONCURRENTLY`. | +| 5 | `ensureProviderEarningsWindowIndex` (`coordinator/store/postgres_earnings_window_index.go`) | Builds the BRIN time index and sets the analyze cadence. | + +Versions 2 to 5 are Go migrations (`goMigrations`). They keep the code they had +before goose and run on the store pool. The SQL migrations run on a separate +two-connection pool whose sessions set `lock_timeout` to 3 s and +`statement_timeout` to 10 min (`migrationLockTimeout`, +`migrationStatementTimeout`); a value set in the database URL wins. A DDL +statement that cannot get its lock in time fails instead of queueing every +later query on the table behind it, and `migrate` runs goose again, up to three +attempts. Goose holds a session advisory lock while it applies versions, so +two coordinators that start together take turns: one applies, the other then +finds nothing to apply. Out-of-order versions are refused. + +`coordinator/store/schema/schema.sql` is the `pg_dump --schema-only` of the +schema the migrations build, without `goose_db_version`. +`TestMigrationsBuildCheckedInSchema` builds a fresh database with goose and +fails when its schema differs from that file. To add a migration, follow +[Add a database migration](../developer/database-migrations.md). + +`schema_migrations` is a separate, older table. It holds the markers of the +one-shot data migrations inside the baseline and of the retired backfills. +Two SQL files under `coordinator/store/migrations/` are not migrations and are applied by hand with `psql`: `dedupe_provider_earnings.sql` (an offline cleanup that once ran at boot, held a relation lock for ~15 minutes on the production table and kept the coordinator from binding its port) and @@ -140,8 +163,9 @@ The one-shot backfills that derived `earnings_summary`, `usage_totals` and `balances.withdrawable_micro_usd` from history (markers `backfill_earnings_summary_v1`, `backfill_usage_totals_v1`, `backfill_withdrawable_balance_v1`) have run in production and are retired -after v0.9.10. The schema slice now creates `balances` with -`withdrawable_micro_usd`. `checkRetiredBackfills` then guards the boot: +after v0.9.10. The baseline creates `balances` with +`withdrawable_micro_usd`. `checkRetiredBackfills` (version 2) then guards the +first goose boot of a database: - it fails if `balances.withdrawable_micro_usd` is missing; - it records each marker whose source table (`balances`, `usage`, @@ -170,8 +194,8 @@ inserted earning rows, so duplicate non-empty job IDs never increment twice. draw settlement and MemoryStore. The record-only method does not credit balances or create ledger entries. -Postgres startup logs connection time and individual schema statement durations -as bounded phase labels, plus named index phases. Logs omit SQL and +Postgres startup logs connection time, one `postgres migration` line per +applied version with its duration, and named index phases. Logs omit SQL and parameters. Preparing migrations before the drain moves index builds out of the cutover window; concurrent index creation can still wait for old transactions. See the [deployment procedure](../operations/coordinator-deploy.md) for the approval and compatibility boundary. @@ -205,11 +229,12 @@ historical provider record. flowchart LR A[ReadAppConfig] --> B{DATABASE_URL set?} B -- yes --> C[pgxpool connect + Ping] - C --> D[migrate: idempotent DDL slice] - D --> E[one-shot data migrations\ngated by schema_migrations;\nretired-backfill guard] - E --> F[ensureProviderEarningsJobIndex\nCONCURRENTLY, fast-path if present] - F --> F2[ensureProviderEarningsWindowIndex\nBRIN CONCURRENTLY + analyze cadence] - F2 --> G[SeedKey admin key] + C --> L[goose advisory lock] + L --> V{pending versions\nin goose_db_version?} + V -- none --> G[SeedKey admin key] + V -- some --> D[apply each pending version once:\n1 baseline, 2 retired-backfill guard,\n3-5 CONCURRENTLY indexes] + D --> G + D -. lock_timeout .-> L B -- no, ALLOW_MEMORY_STORE=true --> H[NewMemory + 15 min pruner] B -- no --> X[exit 1] D -. any error .-> X @@ -223,7 +248,7 @@ Roughly forty tables; grouped by what would be lost if the family vanished. |---|---|---| | Identity and access | `api_keys`, `users`, `device_codes`, `provider_tokens`, `publishing_api_keys`, `invite_codes`, `invite_redemptions` | Keys are stored as hashes with a display prefix; `users` carries the Stripe Connect fields. | | Money | `balances`, `ledger_entries`, `billing_sessions`, `model_prices`, `referrers`, `referrals`, `stripe_withdrawals`, `global_payout_recipients`, `global_payout_withdrawals`, `provider_earnings`, `earnings_summary`, `provider_payouts`, `provider_floor_draws`, `payments` (legacy) | The ledger is append-only; `balances` is the materialised view of it. `model_prices.cache_read_price` is nullable: `NULL` means the row sets no cache-read rate and billing derives one from `input_price` (`payments.RatesFor`). Semantics in [`billing.md`](billing.md). | -| Public model demand | `model_demand_requests`, `model_demand_hourly`, `model_demand_collection` | One compact projection per scoped coordinator UUID, hourly counters updated atomically by trigger, and a persistent collection epoch; `coordinator/store/model_demand_migration.go`, `coordinator/store/postgres_model_demand.go`. | +| Public model demand | `model_demand_requests`, `model_demand_hourly`, `model_demand_collection` | One compact projection per scoped coordinator UUID, hourly counters updated atomically by the `model_demand_rollup` trigger, and a persistent collection epoch; `coordinator/store/postgres_model_demand.go`. | | Usage and routing telemetry | `usage`, `usage_totals`, `inference_routes`, `request_rejections`, `request_profiles`, `fleet_snapshots`, `request_outcomes` | Row per request, per dispatched attempt, per rejection, per profiled attempt, per fleet sample; `usage_totals` is a single-row counter seeded at boot by `checkRetiredBackfills` and incremented by `RecordUsage`. `usage.cached_tokens` (`INTEGER NOT NULL DEFAULT 0`) is the subset of `prompt_tokens` billed at the cache-read rate; rows written before the column existed read 0, which is what they were billed. It and `model_prices.cache_read_price` are added by plain `ALTER TABLE … ADD COLUMN IF NOT EXISTS` statements, not exception-swallowing `DO` blocks. Settlement reads and writes both columns, so if either cannot be added (a lock timeout, a missing privilege), startup fails rather than boot a coordinator that bills at the default rates and drops usage rows. | | Provider fleet and trust | `providers`, `provider_reputation`, `provider_sessions`, `provider_trust_reuse`, `provider_verification_jobs`, `code_attestations`, `code_attest_push_budgets`, `provider_log_reports` | Trust reuse and code attestations are durable. `code_attestations.continuous_coverage_until` is compare-and-updated only for the exact original proof tuple; it never refreshes `attested_at` or inserts proof. This allows bounded same-process resume after a redeploy; see [`security/attestation.md`](security/attestation.md). `provider_log_reports.serial_number` is kept empty by trigger. | | Models and releases | `model_registry`, `model_versions`, `model_version_files`, `model_active_versions`, `model_aliases`, `releases` | The catalog the registry syncs at boot; see [`model-registry.md`](model-registry.md). | @@ -236,7 +261,7 @@ Claims, result application and definitive-rejection records use one locked Postg Payouts marked `manual_reconciliation_required` without an external payment ID are excluded from automatic scans and claims; their pending row and debit are retained. A verified external ID permits readback reconciliation to resume (`coordinator/store/global_payouts.go`, `GlobalPayout.RequiresManualReconciliation`). -Global Payouts uses separate recipient and withdrawal tables with immutable request data, persisted dispatch counts, definitive rejection records, an indexed quote expiry and a unique external-payment index. `GlobalPayoutStore` is accessed through `store.As` so decorators preserve the capability. These mutations do not write the cached users table. The migration creates the payout tables and adds/backfills indexed quote expiry for an earlier Global Payouts schema (`coordinator/store/global_payouts_postgres.go`, `globalPayoutSchema`). Cleanup locks and removes only expired, never-confirmed quotes in bounded batches; confirmed payout and ledger records are retained (`coordinator/store/global_payouts_maintenance.go`, `PruneExpiredGlobalPayoutQuotes`). +Global Payouts uses separate recipient and withdrawal tables with immutable request data, persisted dispatch counts, definitive rejection records, an indexed quote expiry and a unique external-payment index. `GlobalPayoutStore` is accessed through `store.As` so decorators preserve the capability. These mutations do not write the cached users table. The baseline creates the payout tables and adds/backfills indexed quote expiry for an earlier Global Payouts schema (`coordinator/store/schema/migrations/00001_baseline.sql`). Cleanup locks and removes only expired, never-confirmed quotes in bounded batches; confirmed payout and ledger records are retained (`coordinator/store/global_payouts_maintenance.go`, `PruneExpiredGlobalPayoutQuotes`). Quote invalidation is serialized with confirmation. An invalidation flag prevents an earlier request timestamp from admitting a canceled quote; an already-confirmed payout is returned unchanged for reconciliation (`coordinator/store/global_payouts_quote_expiry.go`, `ExpireGlobalPayoutQuote`). @@ -287,14 +312,16 @@ KV blocks under a per-model key, not tokens. `store.Config.Check` fails and `main` exits unless a DSN is present or the memory store is opted into by name (`coordinator/store/config.go`, `coordinator/cmd/coordinator/main.go`). -2. **Schema changes ship with the binary and are idempotent.** Every statement - in `PostgresStore.migrate` can run on an already-migrated database; the - process serves traffic only after the whole slice succeeds - (`coordinator/store/postgres.go`). -3. **Committed migration progress is not applied twice.** One-shot data - migrations commit their `schema_migrations` marker in the same statement or - transaction as their update (`coordinator/store/postgres.go`, - `coordinator/store/postgres_log_report_privacy.go`). +2. **Schema changes ship with the binary as numbered migrations.** The process + serves traffic only after every pending version applies; a version applies + once and is recorded in `goose_db_version` + (`coordinator/store/postgres_migrations.go`). The baseline statements are + idempotent, so its first run on a pre-goose database changes nothing. +3. **Committed migration progress is not applied twice.** Goose records a + version after it succeeds, under a session advisory lock. One-shot data + migrations in the baseline commit their `schema_migrations` marker in the + same statement or transaction as their update + (`coordinator/store/schema/migrations/00001_baseline.sql`). 4. **Boot never holds a long lock on a hot table.** The `provider_earnings(job_id)` unique index is built `CONCURRENTLY`, only after a duplicate check, and skipped when already valid; the dedupe that violated @@ -312,8 +339,9 @@ KV blocks under a per-model key, not tokens. 6. **Nothing prompt-derived is persisted.** `TelemetryStore` rows carry token counts, timings and outcomes only; the `serial_number` column of `provider_log_reports` and the legacy `cache_affinity_key` column are kept - empty by triggers (`coordinator/store/postgres_log_report_privacy.go`, - `legacyCacheAffinityGuardTrigger` in `coordinator/store/postgres.go`). + empty by the triggers `clear_provider_log_report_serial` and + `clear_legacy_cache_affinity_key` + (`coordinator/store/schema/migrations/00001_baseline.sql`). 7. **Provider secrets never leave the Keychain in the clear.** The KV KEK is wrapped by a Secure Enclave key and the SSD cache is unreadable without it (`provider-swift/Sources/ProviderCore/KVCache/WrappedKEKStorage.swift`). @@ -322,7 +350,9 @@ KV blocks under a per-model key, not tokens. | Symptom | Cause | Where to look | |---|---|---| -| Coordinator exits 1 at boot with `store: run migrations` | A DDL statement failed (permissions, a hand-edited schema, or a `CREATE INDEX` waiting on a lock) | The logged statement; `pg_stat_activity` for blockers. | +| Coordinator exits 1 at boot with `store: run migrations` | A migration failed (permissions, a hand-edited schema, or a lock still held after three `lock_timeout` attempts) | The failed `postgres migration` version in the log; `pg_stat_activity` for blockers. | +| Boot fails with `missing (out-of-order) migration` | A version below the database's highest was never applied, for example two branches added migrations and the higher one deployed first | `SELECT * FROM goose_db_version`; renumber the unapplied migration above the highest applied version. | +| Boot fails with `found duplicate migration version` | Two migration files use the same number | Renumber one of them. | | Boot fails with `database holds data that retired backfills never processed` or `balances.withdrawable_micro_usd is missing` | The database has billing, usage or earnings history but never ran a backfill retired after v0.9.10 | Boot a coordinator built from v0.9.10 (which still runs them) against it once, then redeploy (`checkRetiredBackfills`). | | Boot fails with an actionable `provider_earnings` duplicate message | Rows share a non-empty `job_id`, so the unique index cannot be built | Run `dedupe_provider_earnings.sql` offline, then redeploy. | | `EIGENINFERENCE_DATABASE_URL is required in production` | No DSN and no memory-store opt-in | The environment file; see [`../operations/coordinator-deploy.md`](../operations/coordinator-deploy.md). | @@ -339,7 +369,8 @@ KV blocks under a per-model key, not tokens. | Interface and record types | `coordinator/store/interface.go`, `coordinator/store/interface_domains.go` | | Earnings rankings and startup time index | `coordinator/store/postgres_leaderboard.go` (`Leaderboard`), `coordinator/store/postgres_earnings_window_index.go` (`ensureProviderEarningsWindowIndex`), `coordinator/store/postgres_startup.go` (`ensureConcurrentIndex`) | | Backend selection and validation | `coordinator/store/config.go`, `coordinator/cmd/coordinator/main.go` | -| Postgres pool, schema, one-shot migrations | `coordinator/store/postgres.go`, `coordinator/store/postgres_log_report_privacy.go`, `coordinator/store/postgres_retired_backfills.go` | +| Postgres pool | `coordinator/store/postgres.go` | +| Migrations | `coordinator/store/postgres_migrations.go` (`migrate`, `goMigrations`), `coordinator/store/schema/migrations/`, `coordinator/store/schema/schema.sql`, `coordinator/store/postgres_retired_backfills.go` | | Provider identity and usage reads | `coordinator/store/postgres_provider_read.go` (`providerRecordColumns`, `scanProviderRecord`, `GetProviderRecord`); `coordinator/store/provider_restore.go` (`GetProviderForRestore`, using the same projection); `coordinator/store/postgres_usage_read.go` (`readUsageRecords`, `UsageRecords`); `coordinator/store/postgres_row.go` (`rowScanner`) | | Domain files | `coordinator/store/postgres_model_registry.go`, `coordinator/store/postgres_base_rewards.go`, `coordinator/store/postgres_profiles.go`, `coordinator/store/route_telemetry.go`, `coordinator/store/usage_time_series.go`, `coordinator/store/apikey.go` | | Memory backend | `coordinator/store/memory.go`, `coordinator/store/memory_base_rewards.go` | @@ -360,7 +391,7 @@ KV blocks under a per-model key, not tokens. ## Model token grants -`coordinator/store/model_token_promotions_schema.go` (`modelTokenPromotionDDL`) adds `model_token_promotions`, account/model keyed `model_token_grants`, durable `model_token_reservations`, and provider-account keyed `model_token_provider_carries`. The carry row retains a sub-micro-dollar payout remainder in `[0, 100000000)`; the additive table also works when upgrading an existing promotion schema. Promotion model IDs deliberately do not reference the model registry, allowing pre-launch setup. The promotion row serializes claims, enforces the maximum claim count and validates the user table’s authoritative account creation timestamp. Account/model uniqueness makes duplicate claims idempotent. Grant counters enforce nonnegative usage/reservations and prevent their sum from exceeding the grant. Reservation terminal state prevents duplicate spending, refunds and provider credit. Claim windows do not expire previously issued grants. +The baseline adds `model_token_promotions`, account/model keyed `model_token_grants`, durable `model_token_reservations`, and provider-account keyed `model_token_provider_carries`. The carry row retains a sub-micro-dollar payout remainder in `[0, 100000000)`; the additive table also works when upgrading an existing promotion schema. Promotion model IDs deliberately do not reference the model registry, allowing pre-launch setup. The promotion row serializes claims, enforces the maximum claim count and validates the user table’s authoritative account creation timestamp. Account/model uniqueness makes duplicate claims idempotent. Grant counters enforce nonnegative usage/reservations and prevent their sum from exceeding the grant. Reservation terminal state prevents duplicate spending, refunds and provider credit. Claim windows do not expire previously issued grants. `coordinator/store/model_token_settlement_postgres.go` (`SettleModelTokenReservation`) updates grant usage, consumer money, fractional payout carry and provider earnings in one transaction, locking balance rows in account order before the carry row. `coordinator/store/model_token_earnings_postgres.go` (`carryModelTokenEarningPostgres`) updates the remainder; the reservation persists the credited whole-micro-dollar payout so replay returns the original result without accumulating fractions again. The optional backend capability is discovered through `store.As`; grants bypass the user/model read-through caches and no user/model invalidation is needed. Lease recovery is in `coordinator/store/model_token_leases.go` (`ReleaseStaleModelTokenReservations`). Operational details: [model token promotions](../operations/model-token-promotions.md). @@ -383,7 +414,7 @@ existing pool through `StripeSettlementForMaintenance` without startup migration ## Autopilot operation ledger -`coordinator/store/postgres_autopilot.go` (`autopilotDDL`, `RecordAutopilot`) +`coordinator/store/postgres_autopilot.go` (`RecordAutopilot`) creates `autopilot_events`, keyed by `(command_id, phase)` with an indexed `at` timestamp and a bounded typed JSON record. Insert retries are idempotent. The ledger stores model/control metadata without prompts or free-form provider diff --git a/docs/architecture/system-profiler.md b/docs/architecture/system-profiler.md index e60aa9cefa..bb180c4cd0 100644 --- a/docs/architecture/system-profiler.md +++ b/docs/architecture/system-profiler.md @@ -1,6 +1,6 @@ # System profiler -> Last updated: 2026-09-29 +> Last updated: 2026-10-03 The profiler answers "where did the time go, and what did the router know when it chose?" for one request, without carrying a single prompt-derived byte. It @@ -245,7 +245,7 @@ JSON-encoded on the sink worker. ### Tables -`request_profiles` (DDL `requestProfilesTableDDL`, `coordinator/store/postgres.go`; +`request_profiles` (DDL in `coordinator/store/schema/migrations/00001_baseline.sql`; column order pinned by `requestProfileColumns`, `coordinator/store/profile_records.go`): | Group | Columns | @@ -266,7 +266,7 @@ nullable, everything else `NOT NULL DEFAULT` zero. `id BIGSERIAL PRIMARY KEY`, `idx_request_profiles_provider (provider_id, created_at DESC)`. Both tables use `autovacuum_vacuum_scale_factor = 0.02`, `autovacuum_analyze_scale_factor = 0.01`. -`fleet_snapshots` (`fleetSnapshotsTableDDL`; `fleetSnapshotColumns`): +`fleet_snapshots` (DDL in the same baseline; `fleetSnapshotColumns`): | Group | Columns | |---|---| diff --git a/docs/developer/build.md b/docs/developer/build.md index f01c31e0a1..528606dd7e 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build -> Last updated: 2026-10-01 +> Last updated: 2026-10-03 The provider test runner isolates daemon-state and loaded-model snapshots in a temporary directory for each run. Unit-test providers must not overwrite the @@ -280,7 +280,7 @@ jobs queued behind a provider quota do not shorten the critical path. See | Tool | Pin | Used by | |---|---|---| - | `go` | `1.25.0` | coordinator, e2e (matches `go 1.25.0` in [`go.mod`](../../go.mod)) | + | `go` | `1.25.7` | coordinator, e2e (matches `go 1.25.7` in [`go.mod`](../../go.mod)) | | `rust` | `1.88.0` | `coordinator/promptsidecar` (matches `rust-version = "1.88"` in `coordinator/promptsidecar/Cargo.toml` and the `rust:1.88.0-alpine` builder in `coordinator/Dockerfile`) | | `node` | `22` | `console-ui`, `admin-ui` | | `swift` | `6.3` | `provider-swift` (the local `libs/mlx-swift` package declares `swift-tools-version: 6.3`; `provider-swift/Package.swift` itself is `6.1`) | diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md new file mode 100644 index 0000000000..d9faecec6f --- /dev/null +++ b/docs/developer/database-migrations.md @@ -0,0 +1,78 @@ +# Add a database migration + +> Last updated: 2026-10-03 + +How to change the coordinator's Postgres schema. Every schema change is a new +numbered goose migration under `coordinator/store/schema/migrations/`. Do not +put DDL in Go strings, and do not edit a migration that has merged. The +mechanism is explained in +[storage](../architecture/storage.md#migrations-are-numbered-goose-versions). + +## Prerequisites + +- Docker, with a throwaway Postgres 17 server: + `docker run -d --name dinf-store-pg -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:17`. +- `DATABASE_URL` pointing at that server, as for the other Postgres tests + ([test](test.md)). + +## Steps + +1. Pick the next version: one more than the highest file number in + `coordinator/store/schema/migrations/` or the highest version in + `goMigrations` (`coordinator/store/postgres_migrations.go`). If a branch that + merges before yours takes the same number, renumber yours. +2. Create `coordinator/store/schema/migrations/NNNNN_short_name.sql`: + + ```sql + -- +goose Up + ALTER TABLE providers ADD COLUMN example TEXT; + ``` + + Goose runs the file in one transaction. Put `-- +goose NO TRANSACTION` at + the top for `CREATE INDEX CONCURRENTLY` or `DROP INDEX CONCURRENTLY`, and + use one such statement per file. Wrap a statement that contains `;` (a + `DO` block or a function body) in `-- +goose StatementBegin` and + `-- +goose StatementEnd`. +3. Keep each statement short and lock-safe. The migration session sets + `lock_timeout` to 3 s and `statement_timeout` to 10 min. Add a column + without a volatile default; add a constraint `NOT VALID`, then `VALIDATE` + it; build indexes on large tables `CONCURRENTLY`. Do not swallow errors in a + `DO ... EXCEPTION WHEN others` block: a failure must stop the boot. +4. Regenerate the schema file from a database built by the migrations: + + ```bash + docker exec dinf-store-pg createdb -U postgres schema_dump + EIGENINFERENCE_DATABASE_URL='postgres://postgres:pg@127.0.0.1:55432/schema_dump?sslmode=disable' \ + go run ./coordinator/cmd/coordinator --migrate-only + docker exec dinf-store-pg pg_dump -U postgres --schema-only --no-owner --no-privileges \ + --exclude-table=goose_db_version schema_dump \ + | grep -v '^\\restrict \|^\\unrestrict \|^-- Dumped from database version\|^-- Dumped by pg_dump version' \ + > coordinator/store/schema/schema.sql + ``` + + Use a `pg_dump` of the same major version as production (17). +5. Update `MemoryStore` and the docs that describe the changed tables + ([storage](../architecture/storage.md)). + +## Verify + +```bash +DATABASE_URL='postgres://postgres:pg@127.0.0.1:55432/postgres?sslmode=disable' \ + go test ./coordinator/store -run 'TestMigrations|TestConcurrentMigrations' -count=1 +``` + +`TestMigrationsBuildCheckedInSchema` fails when `schema.sql` does not match +what the migrations build. + +## Troubleshooting + +| Symptom | Fix | +|---|---| +| `found duplicate migration version` | Two files share a number; renumber yours. | +| `missing (out-of-order) migration` on a shared database | A higher version was applied first; renumber the unapplied file above it. | +| A statement fails with `canceling statement due to lock timeout` three times | A long query holds the table; rerun when it ends, or make the statement take a weaker lock. | + +## Related + +- [Storage](../architecture/storage.md) — what the migrations build and why +- [Test](test.md) — running the Postgres tests diff --git a/docs/operations/coordinator-deploy.md b/docs/operations/coordinator-deploy.md index ef85d4e7eb..599a4c02e3 100644 --- a/docs/operations/coordinator-deploy.md +++ b/docs/operations/coordinator-deploy.md @@ -1,6 +1,6 @@ # Deploy the coordinator (production) -> Last updated: 2026-09-30 +> Last updated: 2026-10-03 Runbook for swapping the production coordinator container on the GCE VM `darkbloom-coordinator` to a Cloud-Build image of a reviewed `master` commit, @@ -39,7 +39,7 @@ For bank payout configuration and validation, follow [Global Payouts](global-pay - `gcloud` authenticated with IAM to SSH via IAP into project `darkbloom-mainnet` and to read Cloud Build / Artifact Registry. -- `psql` access to the production RDS database (`PROD_DB_URL`) for the +- `psql` access to the production Cloud SQL database (`PROD_DB_URL`) for the pre-swap lock check. - Explicit human approval for the production mutation (rule 1 in [README.md](README.md) is the canonical statement), recorded where your team @@ -66,7 +66,7 @@ For bank payout configuration and validation, follow [Global Payouts](global-pay | Container | `coordinator`: `--network host`, `--restart unless-stopped`, `--stop-timeout 690`, `-v /mnt/disks/userdata:/mnt/disks/userdata`, `--env-file /etc/d-inference/env`; entrypoint [`coordinator/deploy/start.sh`](../../coordinator/deploy/start.sh) | | Inside the container | `start.sh` symlinks `/data -> /mnt/disks/userdata`, starts MicroMDM on `:9002` (state in `/data/micromdm`, command webhook `http://localhost:8080/v1/mdm/webhook`), then `exec coordinator` as PID 1. `/usr/local/bin/promptsidecar` is spawned by the coordinator when `EIGENINFERENCE_PROMPT_SIDECAR_ENABLED=true` | | Persistent disk | `/mnt/disks/userdata`: MicroMDM BoltDB, prompt-contract artifacts (`EIGENINFERENCE_PROMPT_SIDECAR_ARTIFACT_ROOT=/mnt/disks/userdata/prompt-contracts`), logs. **Omitting the bind mount boots a blank MDM and drops the fleet to `self_signed` trust** (2026-07-04 incident) | -| Database | AWS RDS PostgreSQL via `EIGENINFERENCE_DATABASE_URL`; schema migrations run at coordinator start | +| Database | Cloud SQL for PostgreSQL 17 in `darkbloom-mainnet` (read replica `d-inference-prod-pg17-ro`) via `EIGENINFERENCE_DATABASE_URL`; pending goose migrations apply at coordinator start | | Env file | `/etc/d-inference/env`, root-only `0600`, on the boot disk (never tmpfs). Managed by [`deploy/gcp/prod/refresh-env.sh`](../../deploy/gcp/prod/refresh-env.sh) with [`deploy/gcp/prod/required-env-keys.txt`](../../deploy/gcp/prod/required-env-keys.txt) and [`deploy/gcp/prod/release-env-defaults`](../../deploy/gcp/prod/release-env-defaults); applied at boot by [`deploy/gcp/prod/darkbloom-env-refresh.service`](../../deploy/gcp/prod/darkbloom-env-refresh.service) (`Before=docker.service`) | | Fallback | The previous container is renamed `coordinator_fallback_` and kept stopped | @@ -114,9 +114,12 @@ by hand; shell variables do not cross SSH. ### 2. Pre-swap checks (VM and DB) -Startup runs schema migrations. An `ALTER TABLE` queued behind a long query's -relation lock hangs the deploy (2026-07-03 outage — the fix was killing the -blocker, not restarting). No rows means safe to proceed: +Startup applies pending goose migrations +([storage](../architecture/storage.md#migrations-are-numbered-goose-versions)). +A migration statement waits at most 3 s for a lock (`lock_timeout`); after +three failed attempts the coordinator exits 1. Before goose, an `ALTER TABLE` +queued behind a long query's relation lock hung the deploy (2026-07-03 +outage). No rows means safe to proceed: ```bash psql "$PROD_DB_URL" -c "select pid, now()-query_start as runtime, state, left(query,80) @@ -128,7 +131,7 @@ psql "$PROD_DB_URL" -c "select count(*) as blocked from pg_locks where granted = A coordinator built after v0.9.10 refuses to start on a database that holds billing, usage or earnings rows but never ran the retired one-shot backfills (`checkRetiredBackfills`, see -[storage](../architecture/storage.md#migrations-run-inside-the-process-at-every-boot)). +[storage](../architecture/storage.md#migrations-are-numbered-goose-versions)). Production ran them; confirm all three markers before the swap (three rows): ```bash @@ -184,6 +187,27 @@ second ordinary coordinator container. Rerun the blocked-query/lock checks and verify current serving health after preparation; success is not approval to swap. +#### First deploy of a goose build + +The first coordinator built with goose (`coordinator/store/postgres_migrations.go`) +applies versions 1 to 5 to production once. On a schema that the previous +coordinator built they change nothing. A lock timeout inside one of the +baseline's `DO ... EXCEPTION WHEN others` blocks is swallowed, and goose still +records version 1. After that deploy, confirm the versions and compare the +production schema with the checked-in file of the deployed commit (read-only; +use a `pg_dump` 17 client): + +```bash +psql "$PROD_DB_URL" -c "select version_id from goose_db_version order by id;" # 0 through 5 +pg_dump "$PROD_DB_URL" --schema-only --no-owner --no-privileges --exclude-table=goose_db_version \ + | grep -v '^\\restrict \|^\\unrestrict \|^-- Dumped from database version\|^-- Dumped by pg_dump version' \ + | diff - coordinator/store/schema/schema.sql +``` + +Only objects applied by hand, such as the `request_waterfall` view, may +differ. A missing column or index means a swallowed statement; apply it under +a separate approved operation. + New provider-recovery indexes are built concurrently and checked for validity. An interrupted build that leaves an invalid index fails closed with its index name; repair it under a separate approved operation. Ordinary startup still applies @@ -300,9 +324,11 @@ sudo docker run -d --name coordinator \ ``` Startup takes ~15–40 s (MicroMDM init, migrations, listeners). If `/health` -does not answer after ~60 s, suspect a migration behind a DB lock: re-run the -`pg_stat_activity` query and `pg_terminate_backend()` the blocker. **Do -not restart the container again** — restarts stack migrations. +does not answer after ~60 s, or the container exits with `store: run +migrations`, suspect a migration behind a DB lock: re-run the +`pg_stat_activity` query and `pg_terminate_backend()` the blocker. Goose +holds an advisory lock while it migrates, so a second container waits for the +first instead of running the same DDL. ## Verification @@ -335,7 +361,7 @@ curl -fsS localhost:8080/v1/cache/status | jq -e \ # Fleet trust rebuild (~2 min) and MDM sanity. sudo docker logs coordinator 2>&1 | grep -c "upgraded live provider to hardware trust" # should climb sudo docker logs coordinator 2>&1 | grep -c "device not found in MDM" # baseline is a few dozen; hundreds = missing volume mount → Rollback -sudo docker logs coordinator 2>&1 | grep "postgres migration completed" # one line per migration; result already_applied on steady state +sudo docker logs coordinator 2>&1 | grep '"postgres migration"' # one line per applied version; none when nothing was pending # Public. curl -fsS https://api.darkbloom.dev/health @@ -402,7 +428,11 @@ cause in the deploy record; the failed candidate image stays in Artifact Registry for diagnosis. Providers reconnect on their own; the live registry is in-process and rebuilt -from reconnects, durable state is in RDS and on the persistent disk. +from reconnects, durable state is in Cloud SQL and on the persistent disk. + +A previous image built before goose boots on a goose-migrated database: it runs +its own boot DDL and ignores `goose_db_version`. An older goose image applies +nothing, because every version it knows is already recorded. ## Environment file @@ -460,7 +490,7 @@ reference copy; editing it changes nothing on the host. | Symptom | Likely cause | Fix | |---|---|---| -| No `/health` after 60 s | migration behind an RDS relation lock | `pg_stat_activity` → `pg_terminate_backend()`; do not restart the container | +| No `/health` after 60 s, or exit with `store: run migrations` | migration behind a relation lock (three `lock_timeout` attempts failed) | `pg_stat_activity` → `pg_terminate_backend()`; do not restart the container | | Exit at boot with `database holds data that retired backfills never processed` or `balances.withdrawable_micro_usd is missing` | the database never ran a one-shot backfill retired after v0.9.10 (not production, which has all three markers) | roll back to the captured image, which runs the backfills at start, then redeploy the candidate | | Fleet drops to `self_signed`; "device not found in MDM" storm | container started without `-v /mnt/disks/userdata:/mnt/disks/userdata` (blank MicroMDM) | Rollback, then redo the swap with the mount | | `/v1/models` empty; providers `self_signed` | MicroMDM not running or `MICROMDM_API_KEY` ≠ `EIGENINFERENCE_MDM_API_KEY` | fix the env file, recreate the container | diff --git a/docs/reference/app-attest-shadow.md b/docs/reference/app-attest-shadow.md index e9c5131fa2..9ac86d5a80 100644 --- a/docs/reference/app-attest-shadow.md +++ b/docs/reference/app-attest-shadow.md @@ -1,6 +1,6 @@ # App Attest shadow protocol, machine inventory, and evidence -> Last updated: 2026-09-27 +> Last updated: 2026-10-03 App Attest shadow collection records stable machine identities, fleet adoption, submitted proofs and receipts alongside legacy verification. Shadow alone changes no routing, rewards or trust. The separately enabled [provider authorization path](provider-authorization.md) uses qualified evidence for MDM-optional serving and rewards. DeviceCheck's separate two-bit API remains deferred. @@ -155,7 +155,7 @@ PostgreSQL is the durable archive itself, including its normal database backup p | Tables | Contents | Code | |---|---|---| -| `darkbloom_machines`, `darkbloom_machine_aliases`, `darkbloom_machine_merges` | UUIDs, evidence level, private hashed aliases, canonical merges | `coordinator/store/machine_inventory_schema.go` | +| `darkbloom_machines`, `darkbloom_machine_aliases`, `darkbloom_machine_merges` | UUIDs, evidence level, private hashed aliases, canonical merges | `coordinator/store/schema/migrations/00001_baseline.sql` | | `darkbloom_machine_sessions`, `darkbloom_machine_observations` | Original/current machine attribution, authenticated account, liveness, reported OS/build/hardware, protocol, legacy comparison, refused-frame counts | Same file | | `app_attest_shadow_events` | Durable stage/outcome/timing observations | Same file | | `app_attest_evidence`, `app_attest_evidence_blobs` | One record per processed proof submission, original proof field, decoded bytes, checksum, expected transcript, actual reply context, evaluation time, root/verifier/policy/build identifiers, result | `coordinator/store/app_attest_archive.go` | diff --git a/go.mod b/go.mod index c390282207..190c7a0ccb 100644 --- a/go.mod +++ b/go.mod @@ -1,27 +1,33 @@ module github.com/eigeninference/d-inference -go 1.25.0 +go 1.25.7 require ( filippo.io/age v1.3.1 - github.com/fxamacker/cbor/v2 v2.9.0 github.com/DataDog/datadog-go/v5 v5.8.3 + github.com/fxamacker/cbor/v2 v2.9.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 - github.com/jackc/pgx/v5 v5.9.2 + github.com/jackc/pgx/v5 v5.10.0 github.com/openai/openai-go v1.12.0 + github.com/pressly/goose/v3 v3.27.3 github.com/smallstep/pkcs7 v0.2.1 github.com/stretchr/testify v1.11.1 go.etcd.io/bbolt v1.4.3 - golang.org/x/crypto v0.51.0 - golang.org/x/mod v0.35.0 - golang.org/x/net v0.55.0 + golang.org/x/crypto v0.54.0 + golang.org/x/mod v0.38.0 + golang.org/x/net v0.57.0 golang.org/x/time v0.15.0 gopkg.in/DataDog/dd-trace-go.v1 v1.74.8 nhooyr.io/websocket v1.8.17 software.sslmate.com/src/go-pkcs12 v0.7.1 ) +require ( + github.com/mfridman/interpolate v0.0.2 // indirect + github.com/sethvargo/go-retry v0.4.0 // indirect +) + require ( filippo.io/hpke v0.4.0 // indirect github.com/DataDog/datadog-agent/comp/core/tagger/origindetection v0.67.0 // indirect @@ -47,7 +53,7 @@ require ( github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/ebitengine/purego v0.8.3 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect @@ -87,22 +93,22 @@ require ( go.opentelemetry.io/collector/pdata v1.31.0 // indirect go.opentelemetry.io/collector/semconv v0.125.0 // indirect go.opentelemetry.io/contrib/bridges/otelzap v0.10.0 // indirect - go.opentelemetry.io/otel v1.43.0 // indirect + go.opentelemetry.io/otel v1.44.0 // indirect go.opentelemetry.io/otel/log v0.11.0 // indirect - go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/otel/metric v1.44.0 // indirect go.opentelemetry.io/otel/sdk v1.43.0 // indirect - go.opentelemetry.io/otel/trace v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.44.0 // indirect go.uber.org/atomic v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect - golang.org/x/sync v0.20.0 - golang.org/x/sys v0.45.0 // indirect - golang.org/x/text v0.37.0 // indirect + golang.org/x/exp v0.0.0-20260718201538-764159d718ef // indirect + golang.org/x/sync v0.22.0 + golang.org/x/sys v0.47.0 + golang.org/x/text v0.40.0 // indirect golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect - google.golang.org/grpc v1.79.3 // indirect - google.golang.org/protobuf v1.36.10 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a // indirect + google.golang.org/grpc v1.82.1 // indirect + google.golang.org/protobuf v1.36.11 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 125d6d9fd6..e93b8ec619 100644 --- a/go.sum +++ b/go.sum @@ -65,8 +65,8 @@ github.com/ebitengine/purego v0.8.3/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= @@ -99,28 +99,34 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= -github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= +github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= +github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc= github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ= +github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= +github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/open-telemetry/opentelemetry-collector-contrib/pkg/sampling v0.125.0 h1:0dOJCEtabevxxDQmxed69oMzSw+gb3ErCnFwFYZFu0M= github.com/open-telemetry/opentelemetry-collector-contrib/pkg/sampling v0.125.0/go.mod h1:QwzQhtxPThXMUDW1XRXNQ+l0GrI2BRsvNhX6ZuKyAds= github.com/open-telemetry/opentelemetry-collector-contrib/processor/probabilisticsamplerprocessor v0.125.0 h1:F68/Nbpcvo3JZpaWlRUDJtG7xs8FHBZ7A8GOMauDkyc= @@ -142,14 +148,20 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= +github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA= +github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY= github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg= github.com/puzpuzpuz/xsync/v3 v3.5.1/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/richardartoul/molecule v1.0.1-0.20240531184615-7ca0df43c0b3 h1:4+LEVOB87y175cLJC/mbsgKmoDOjrBldtXvioEy96WY= github.com/richardartoul/molecule v1.0.1-0.20240531184615-7ca0df43c0b3/go.mod h1:vl5+MqJ1nBINuSsUI2mGgH79UweUT/B5Fy8857PqyyI= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/secure-systems-lab/go-securesystemslib v0.9.0 h1:rf1HIbL64nUpEIZnjLZ3mcNEL9NBPB0iuVjyxvq3LZc= github.com/secure-systems-lab/go-securesystemslib v0.9.0/go.mod h1:DVHKMcZ+V4/woA/peqr+L0joiRXbPpQ042GgJckkFgw= +github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw= +github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/shirou/gopsutil/v4 v4.25.3 h1:SeA68lsu8gLggyMbmCn8cmp97V1TI9ld9sVzAUcKcKE= github.com/shirou/gopsutil/v4 v4.25.3/go.mod h1:xbuxyoZj+UsgnZrENu3lQivsngRR5BdjbJwf2fv4szA= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= @@ -240,18 +252,18 @@ go.opentelemetry.io/collector/semconv v0.125.0 h1:SyRP617YGvNSWRSKMy7Lbk9RaJSR+q go.opentelemetry.io/collector/semconv v0.125.0/go.mod h1:te6VQ4zZJO5Lp8dM2XIhDxDiL45mwX0YAQQWRQ0Qr9U= go.opentelemetry.io/contrib/bridges/otelzap v0.10.0 h1:ojdSRDvjrnm30beHOmwsSvLpoRF40MlwNCA+Oo93kXU= go.opentelemetry.io/contrib/bridges/otelzap v0.10.0/go.mod h1:oTTm4g7NEtHSV2i/0FeVdPaPgUIZPfQkFbq0vbzqnv0= -go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= -go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= go.opentelemetry.io/otel/log v0.11.0 h1:c24Hrlk5WJ8JWcwbQxdBqxZdOK7PcP/LFtOtwpDTe3Y= go.opentelemetry.io/otel/log v0.11.0/go.mod h1:U/sxQ83FPmT29trrifhQg+Zj2lo1/IPN1PF6RTFqdwc= -go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= -go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= -go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= -go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= @@ -269,10 +281,10 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= -golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= -golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 h1:bsqhLWFR6G6xiQcb+JoGqdKdRU6WzPWmK8E0jxTjzo4= -golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= +golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= +golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/exp v0.0.0-20260718201538-764159d718ef h1:LkZ48HFgy/TvhTI0bcWkjgFkgLyKUwcTbDjS0DUjw+A= +golang.org/x/exp v0.0.0-20260718201538-764159d718ef/go.mod h1:EdfpwwqSu+0Li0mzskwHU6FWDV3t9Q+RZDo3QMUtL3Q= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -281,8 +293,8 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM= -golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -295,8 +307,8 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= -golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= -golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -307,8 +319,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= -golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -330,8 +342,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= -golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -350,8 +362,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= -golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= -golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -369,16 +381,16 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU= golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= -gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= -gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= -google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= -google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a h1:qI/YMH1ep2qQtqcp00gMQyoU7mjvbhg88GJKCvfoLj0= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260720211330-0afa2a65878a/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= +google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/DataDog/dd-trace-go.v1 v1.74.8 h1:h96ji92t9eXbPvSWhJ+lrPWetHiQNYlt48JKRO09NFA= gopkg.in/DataDog/dd-trace-go.v1 v1.74.8/go.mod h1:LpHbtHsCZBlm1HWrlVOUQcEXwMWZnU6yMvmtd1GvSDI= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -391,6 +403,14 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/apimachinery v0.32.3 h1:JmDuDarhDmA/Li7j3aPrwhpNBA94Nvk5zLeOge9HH1U= k8s.io/apimachinery v0.32.3/go.mod h1:GpHVgxoKlTxClKcteaeuF1Ul/lDVb74KpZcxcmLDElE= +modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws= +modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog= +modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y= nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= software.sslmate.com/src/go-pkcs12 v0.7.1 h1:bxkUPRsvTPNRBZa4M/aSX4PyMOEbq3V8I6hbkG4F4Q8= diff --git a/mise.toml b/mise.toml index 67ea034ac3..651acba4e2 100644 --- a/mise.toml +++ b/mise.toml @@ -1,6 +1,6 @@ [tools] -# Coordinator (Go control plane). Source of truth: go.mod `go 1.25.0`. -go = "1.25.0" +# Coordinator (Go control plane). Source of truth: go.mod `go 1.25.7`. +go = "1.25.7" # Prompt-contract sidecar. CI and the coordinator container use the same # release so Cargo.lock resolution and language semantics stay reproducible. From 13ccc729bed58906bb457d813a9986acb75fb95b Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 08:10:27 -0500 Subject: [PATCH 02/20] Name the new migration file without citing a missing path docs-check treats an inline-code repo path as a citation; the placeholder file name failed Docs Lint. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- docs/developer/database-migrations.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index d9faecec6f..2887b17ee6 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -21,7 +21,8 @@ mechanism is explained in `coordinator/store/schema/migrations/` or the highest version in `goMigrations` (`coordinator/store/postgres_migrations.go`). If a branch that merges before yours takes the same number, renumber yours. -2. Create `coordinator/store/schema/migrations/NNNNN_short_name.sql`: +2. In `coordinator/store/schema/migrations/`, create `NNNNN_short_name.sql`, + where `NNNNN` is the version with leading zeros: ```sql -- +goose Up From e634061f5ab76ad5caedb3bae07a4c8dde600f27 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 08:16:14 -0500 Subject: [PATCH 03/20] Generate the api_keys store queries with sqlc Add sqlc v1.31.1 (pinned through go run in the Makefile; a go.mod tool directive would need Go 1.26). sqlc reads coordinator/store/schema/schema.sql and generates coordinator/store/storedb from queries/api_keys.sql. The api_keys methods of PostgresStore move to postgres_api_keys.go and call the generated queries; the Store interface, MemoryStore and CachedStore do not change. make sqlc-generate regenerates the code. make sqlc-check fails when the schema file or the generated code is stale; CI runs it in the Coordinator Tests job, whose Postgres service moves to 17 to match production. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 +- CHANGELOG.md | 1 + Makefile | 14 + coordinator/store/apikey_backends_test.go | 109 +++++++ coordinator/store/postgres.go | 373 ---------------------- coordinator/store/postgres_api_keys.go | 352 ++++++++++++++++++++ coordinator/store/queries/api_keys.sql | 50 +++ coordinator/store/sqlc.yaml | 27 ++ coordinator/store/storedb/api_keys.sql.go | 357 +++++++++++++++++++++ coordinator/store/storedb/db.go | 32 ++ coordinator/store/storedb/models.go | 28 ++ docs/architecture/storage.md | 7 +- docs/developer/build.md | 2 + docs/developer/database-migrations.md | 11 +- docs/developer/test.md | 7 +- 15 files changed, 996 insertions(+), 380 deletions(-) create mode 100644 coordinator/store/apikey_backends_test.go create mode 100644 coordinator/store/postgres_api_keys.go create mode 100644 coordinator/store/queries/api_keys.sql create mode 100644 coordinator/store/sqlc.yaml create mode 100644 coordinator/store/storedb/api_keys.sql.go create mode 100644 coordinator/store/storedb/db.go create mode 100644 coordinator/store/storedb/models.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f21c190f9..63fe1b7c12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,7 +66,7 @@ jobs: runs-on: blacksmith-16vcpu-ubuntu-2404 services: postgres: - image: postgres:16 + image: postgres:17 env: POSTGRES_USER: testbed POSTGRES_PASSWORD: testbed @@ -105,6 +105,10 @@ jobs: --coverprofile "$RUNNER_TEMP/coverage.out" \ --output-dir "$RUNNER_TEMP/coordinator-tests" \ $packages + - name: Check sqlc code and schema file + env: + DATABASE_URL: postgres://testbed:testbed@127.0.0.1:5432/testbed?sslmode=disable + run: make sqlc-check - name: Upload coordinator test timings if: ${{ !cancelled() }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index b0d0f40f4a..7f709a28dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - Apply the coordinator's Postgres schema as numbered goose migrations instead of re-running every DDL statement at each boot. The first boot records the existing schema as version 1 without changing it; later boots apply only new versions. Migration statements stop waiting for a lock after 3 seconds and retry up to three times, and coordinators that start together take turns on an advisory lock. - Check in the schema as `coordinator/store/schema/schema.sql` and test that the migrations build exactly that schema. New schema changes go in a new numbered migration file. +- Generate the coordinator's API-key queries with sqlc from that schema; `make sqlc-check` fails CI when the generated code or the schema file is stale. API-key behaviour does not change. ## Unreleased — leaderboard availability diff --git a/Makefile b/Makefile index d1c04fc1b8..1a1d4d6581 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,7 @@ .DEFAULT_GOAL := help .PHONY: help \ coordinator-test coordinator-build coordinator-build-linux coordinator \ + sqlc-generate sqlc-check \ prompt-sidecar-format prompt-sidecar-check prompt-sidecar-test prompt-sidecar-build prompt-sidecar \ provider-build provider-test provider benchmark-gemma-contbatch benchmark-wrapper-test \ ui-install ui-build ui-lint ui-test ui \ @@ -28,6 +29,19 @@ coordinator-build-linux: ## Cross-compile coordinator for linux/amd64 (EigenClou coordinator: coordinator-test coordinator-build ## Test + build coordinator +# sqlc v1.31.1 needs Go 1.26, newer than go.mod, so it runs pinned through +# `go run` instead of a go.mod tool directive. +SQLC := go run github.com/sqlc-dev/sqlc/cmd/sqlc@v1.31.1 +SQLC_CONFIG := coordinator/store/sqlc.yaml + +sqlc-generate: ## Regenerate coordinator/store/storedb from coordinator/store/queries + $(SQLC) generate -f $(SQLC_CONFIG) + +sqlc-check: ## Fail if storedb or coordinator/store/schema/schema.sql is stale (needs DATABASE_URL) + @test -n "$$DATABASE_URL" || { echo "sqlc-check: set DATABASE_URL to a disposable Postgres server"; exit 1; } + go test ./coordinator/store -run '^TestMigrationsBuildCheckedInSchema$$' -count=1 + $(SQLC) diff -f $(SQLC_CONFIG) + # ---- Prompt-contract sidecar (Rust) --------------------------------------- prompt-sidecar-format: ## Check Rust sidecar formatting diff --git a/coordinator/store/apikey_backends_test.go b/coordinator/store/apikey_backends_test.go new file mode 100644 index 0000000000..7ad2872318 --- /dev/null +++ b/coordinator/store/apikey_backends_test.go @@ -0,0 +1,109 @@ +package store + +import ( + "testing" + "time" +) + +// The api_keys lifecycle on every backend: memory always, Postgres (the +// sqlc queries) when DATABASE_URL is set. +func TestAPIKeyLifecycleOnEveryBackend(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + account := uniqueID("acct-keys") + limit := int64(7_000_000) + rpm := int64(60) + expires := time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond) + raw, rec, err := s.CreateAPIKey(account, APIKeyCreate{ + Name: "prod", LimitMicroUSD: &limit, RPMLimit: &rpm, LimitReset: KeyResetWeekly, + AllowedModels: []string{"m1", "m2"}, ExpiresAt: &expires, + }) + if err != nil { + t.Fatalf("CreateAPIKey: %v", err) + } + if got := s.GetKeyAccount(raw); got != account { + t.Fatalf("GetKeyAccount = %q, want %q", got, account) + } + + got, err := s.GetAPIKeyByID(account, rec.ID) + if err != nil { + t.Fatalf("GetAPIKeyByID: %v", err) + } + if got.Name != "prod" || got.Label != rec.Label || got.KeyHash != rec.KeyHash || + got.LimitMicroUSD == nil || *got.LimitMicroUSD != limit || + got.RPMLimit == nil || *got.RPMLimit != rpm || got.ITPMLimit != nil || + got.LimitReset != KeyResetWeekly || len(got.AllowedModels) != 2 || + got.ExpiresAt == nil || !got.ExpiresAt.Equal(expires) || got.LastUsedAt != nil { + t.Fatalf("GetAPIKeyByID = %+v", got) + } + if _, err := s.GetAPIKeyByID(uniqueID("other"), rec.ID); err == nil { + t.Fatal("GetAPIKeyByID for another owner must fail") + } + + used := time.Now().UTC().Truncate(time.Microsecond) + s.TouchAPIKey(rec.ID, used) + if got, err := s.GetAPIKeyByID(account, rec.ID); err != nil || got.LastUsedAt == nil || !got.LastUsedAt.Equal(used) { + t.Fatalf("after TouchAPIKey: %+v, %v", got, err) + } + + s.RecordUsage(UsageRecord{ProviderID: "prov", ConsumerKey: account, KeyID: rec.ID, Model: "model", + RequestID: uniqueID("req"), PromptTokens: 1, CompletionTokens: 1, CostMicroUSD: 2_500_000}) + if spend := s.KeySpendSince(rec.ID, time.Time{}); spend != 2_500_000 { + t.Fatalf("lifetime KeySpendSince = %d, want 2500000", spend) + } + if spend := s.KeySpendSince(rec.ID, time.Now().UTC().AddDate(0, 0, 1)); spend != 0 { + t.Fatalf("future KeySpendSince = %d, want 0", spend) + } + + mutable := *got + mutable.Name = "renamed" + mutable.LimitMicroUSD = nil + mutable.RPMLimit = nil + mutable.LimitReset = KeyResetNone + mutable.AllowedModels = nil + mutable.Disabled = true + updated, err := s.UpdateAPIKey(account, rec.ID, mutable) + if err != nil { + t.Fatalf("UpdateAPIKey: %v", err) + } + if updated.Name != "renamed" || updated.LimitMicroUSD != nil || updated.RPMLimit != nil || + updated.LimitReset != KeyResetNone || updated.AllowedModels != nil || !updated.Disabled { + t.Fatalf("UpdateAPIKey = %+v", updated) + } + if _, err := s.UpdateAPIKey(uniqueID("other"), rec.ID, mutable); err == nil { + t.Fatal("UpdateAPIKey for another owner must fail") + } + if _, err := s.AuthenticateKey(raw); err == nil { + t.Fatal("a disabled key must not authenticate") + } + + newRaw, rotated, err := s.RotateAPIKey(account, rec.ID) + if err != nil { + t.Fatalf("RotateAPIKey: %v", err) + } + if rotated.ID == rec.ID || newRaw == raw || rotated.Name != "renamed" || !rotated.Disabled { + t.Fatalf("RotateAPIKey = %+v", rotated) + } + if _, _, err := s.RotateAPIKey(account, rec.ID); err == nil { + t.Fatal("rotating the replaced id must fail") + } + keys, err := s.ListAPIKeys(account) + if err != nil || len(keys) != 1 || keys[0].ID != rotated.ID { + t.Fatalf("ListAPIKeys = %+v, %v; want only the rotated key", keys, err) + } + + if err := s.RevokeAPIKeyByID(uniqueID("other"), rotated.ID); err == nil { + t.Fatal("RevokeAPIKeyByID for another owner must fail") + } + if err := s.RevokeAPIKeyByID(account, rotated.ID); err != nil { + t.Fatalf("RevokeAPIKeyByID: %v", err) + } + if keys, err := s.ListAPIKeys(account); err != nil || keys == nil || len(keys) != 0 { + t.Fatalf("ListAPIKeys after revoke = %#v, %v; want an empty list", keys, err) + } + if err := s.RevokeAPIKeyByID(account, rotated.ID); err == nil { + t.Fatal("revoking a deleted key must fail") + } + }) + } +} diff --git a/coordinator/store/postgres.go b/coordinator/store/postgres.go index 5475b5e63e..a8c95b3151 100644 --- a/coordinator/store/postgres.go +++ b/coordinator/store/postgres.go @@ -191,379 +191,6 @@ func hashKey(key string) string { // HashKey returns the SHA-256 hex digest of the given API key. func HashKey(key string) string { return hashKey(key) } -// apiKeyColumns is the canonical SELECT list for reading an api_keys row into -// an APIKey via scanAPIKeyRow. -const apiKeyColumns = `id, owner_account_id, name, raw_prefix, key_hash, active, - limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, - allowed_models, expires_at, created_at, last_used_at, self_route_only` - -// scanAPIKeyRow scans one api_keys row (selected via apiKeyColumns) into APIKey. -func scanAPIKeyRow(row rowScanner) (*APIKey, error) { - var ( - k APIKey - active bool - limit *int64 - rpm *int64 - itpm *int64 - otpm *int64 - allowed string - expiresAt *time.Time - lastUsedAt *time.Time - ) - if err := row.Scan(&k.ID, &k.OwnerAccountID, &k.Name, &k.Label, &k.KeyHash, &active, - &limit, &k.LimitReset, &rpm, &itpm, &otpm, - &allowed, &expiresAt, &k.CreatedAt, &lastUsedAt, &k.SelfRouteOnly); err != nil { - return nil, err - } - k.Disabled = !active - k.LimitMicroUSD = limit - k.RPMLimit = rpm - k.ITPMLimit = itpm - k.OTPMLimit = otpm - k.LimitReset = NormalizeResetWindow(k.LimitReset) - k.AllowedModels = decodeModelList(allowed) - k.ExpiresAt = expiresAt - k.LastUsedAt = lastUsedAt - return &k, nil -} - -// encodeModelList serializes a model allow-list for storage. Empty → "". -func encodeModelList(models []string) string { - if len(models) == 0 { - return "" - } - b, err := json.Marshal(models) - if err != nil { - return "" - } - return string(b) -} - -// decodeModelList parses a stored model allow-list. "" / invalid → nil. -func decodeModelList(s string) []string { - if s == "" || s == "[]" { - return nil - } - var out []string - if err := json.Unmarshal([]byte(s), &out); err != nil { - return nil - } - if len(out) == 0 { - return nil - } - return out -} - -// insertAPIKey writes a fully-formed key record. Shared by CreateAPIKey/SeedKey. -func (s *PostgresStore) insertAPIKey(ctx context.Context, rec *APIKey, onConflictDoNothing bool) error { - q := `INSERT INTO api_keys - (id, key_hash, raw_prefix, owner_account_id, name, active, - limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, - allowed_models, expires_at, created_at, self_route_only) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)` - if onConflictDoNothing { - q += ` ON CONFLICT (key_hash) DO NOTHING` - } - _, err := s.pool.Exec(ctx, q, - rec.ID, rec.KeyHash, rec.Label, rec.OwnerAccountID, rec.Name, !rec.Disabled, - rec.LimitMicroUSD, NormalizeResetWindow(rec.LimitReset), rec.RPMLimit, rec.ITPMLimit, rec.OTPMLimit, - encodeModelList(rec.AllowedModels), rec.ExpiresAt, rec.CreatedAt, rec.SelfRouteOnly, - ) - return err -} - -// CreateKeyForAccount generates a new API key linked to a specific account. -func (s *PostgresStore) CreateKeyForAccount(accountID string) (string, error) { - raw, _, err := s.CreateAPIKey(accountID, APIKeyCreate{}) - return raw, err -} - -// CreateAPIKey mints a new API key with optional per-key limits. -func (s *PostgresStore) CreateAPIKey(accountID string, opts APIKeyCreate) (string, *APIKey, error) { - raw, err := GenerateRawKey() - if err != nil { - return "", nil, fmt.Errorf("store: generate key: %w", err) - } - id, err := GenerateKeyID() - if err != nil { - return "", nil, fmt.Errorf("store: generate key id: %w", err) - } - rec := &APIKey{ - ID: id, - OwnerAccountID: accountID, - Name: opts.Name, - Label: KeyLabel(raw), - KeyHash: hashKey(raw), - LimitMicroUSD: opts.LimitMicroUSD, - LimitReset: NormalizeResetWindow(opts.LimitReset), - RPMLimit: opts.RPMLimit, - ITPMLimit: opts.ITPMLimit, - OTPMLimit: opts.OTPMLimit, - AllowedModels: opts.AllowedModels, - SelfRouteOnly: opts.SelfRouteOnly, - ExpiresAt: opts.ExpiresAt, - CreatedAt: time.Now().UTC(), - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := s.insertAPIKey(ctx, rec, false); err != nil { - return "", nil, fmt.Errorf("store: insert key: %w", err) - } - return raw, rec, nil -} - -// SeedKey inserts a specific raw key into the database. This is used for -// bootstrapping the admin key. If the key already exists, it is a no-op. -func (s *PostgresStore) SeedKey(rawKey string) error { - id, err := GenerateKeyID() - if err != nil { - return fmt.Errorf("store: generate key id: %w", err) - } - rec := &APIKey{ - ID: id, - Name: "admin", - Label: KeyLabel(rawKey), - KeyHash: hashKey(rawKey), - LimitReset: KeyResetNone, - CreatedAt: time.Now().UTC(), - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - if err := s.insertAPIKey(ctx, rec, true); err != nil { - return fmt.Errorf("store: seed key: %w", err) - } - return nil -} - -// GetKeyAccount returns the account ID that owns this key, or "" if unlinked. -func (s *PostgresStore) GetKeyAccount(key string) string { - h := hashKey(key) - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - var accountID string - err := s.pool.QueryRow(ctx, - `SELECT owner_account_id FROM api_keys WHERE key_hash = $1 AND active = TRUE`, h, - ).Scan(&accountID) - if err != nil { - return "" - } - return accountID -} - -// AuthenticateKey resolves a raw key to its active record for request auth. -func (s *PostgresStore) AuthenticateKey(rawKey string) (*APIKey, error) { - h := hashKey(rawKey) - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - row := s.pool.QueryRow(ctx, - `SELECT `+apiKeyColumns+` FROM api_keys WHERE key_hash = $1`, h) - k, err := scanAPIKeyRow(row) - if err != nil { - return nil, err - } - if k.Disabled { - return nil, fmt.Errorf("key disabled") - } - if k.ExpiresAt != nil && time.Now().After(*k.ExpiresAt) { - return nil, fmt.Errorf("key expired") - } - return k, nil -} - -// ListAPIKeys returns all keys owned by an account, newest first. -func (s *PostgresStore) ListAPIKeys(accountID string) ([]APIKey, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - rows, err := s.pool.Query(ctx, - `SELECT `+apiKeyColumns+` FROM api_keys WHERE owner_account_id = $1 AND id <> '' ORDER BY created_at DESC`, accountID) - if err != nil { - return nil, err - } - defer rows.Close() - - out := make([]APIKey, 0) - for rows.Next() { - k, err := scanAPIKeyRow(rows) - if err != nil { - return nil, err - } - out = append(out, *k) - } - return out, rows.Err() -} - -// GetAPIKeyByID returns a single key by ID, scoped to the owner. -func (s *PostgresStore) GetAPIKeyByID(accountID, id string) (*APIKey, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - row := s.pool.QueryRow(ctx, - `SELECT `+apiKeyColumns+` FROM api_keys WHERE id = $1 AND owner_account_id = $2`, id, accountID) - return scanAPIKeyRow(row) -} - -// UpdateAPIKey overwrites mutable fields of a key, scoped to the owner. -func (s *PostgresStore) UpdateAPIKey(accountID, id string, mutable APIKey) (*APIKey, error) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - tag, err := s.pool.Exec(ctx, - `UPDATE api_keys SET - name = $1, active = $2, limit_micro_usd = $3, limit_reset = $4, - rpm_limit = $5, itpm_limit = $6, otpm_limit = $7, - allowed_models = $8, expires_at = $9, self_route_only = $10 - WHERE id = $11 AND owner_account_id = $12`, - mutable.Name, !mutable.Disabled, mutable.LimitMicroUSD, NormalizeResetWindow(mutable.LimitReset), - mutable.RPMLimit, mutable.ITPMLimit, mutable.OTPMLimit, - encodeModelList(mutable.AllowedModels), mutable.ExpiresAt, mutable.SelfRouteOnly, - id, accountID, - ) - if err != nil { - return nil, err - } - if tag.RowsAffected() == 0 { - return nil, fmt.Errorf("key not found") - } - return s.GetAPIKeyByID(accountID, id) -} - -// RevokeAPIKeyByID permanently deletes a key by ID, scoped to the owner. -func (s *PostgresStore) RevokeAPIKeyByID(accountID, id string) error { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - tag, err := s.pool.Exec(ctx, - `DELETE FROM api_keys WHERE id = $1 AND owner_account_id = $2`, id, accountID) - if err != nil { - return err - } - if tag.RowsAffected() == 0 { - return fmt.Errorf("key not found") - } - return nil -} - -// RotateAPIKey atomically replaces a key within a transaction (see Store -// interface). The old key is deleted and the new key inserted in the same tx; -// a concurrent rotate of the same id finds the row gone and returns not-found. -func (s *PostgresStore) RotateAPIKey(accountID, id string) (string, *APIKey, error) { - raw, err := GenerateRawKey() - if err != nil { - return "", nil, fmt.Errorf("store: generate key: %w", err) - } - newID, err := GenerateKeyID() - if err != nil { - return "", nil, fmt.Errorf("store: generate key id: %w", err) - } - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - tx, err := s.pool.Begin(ctx) - if err != nil { - return "", nil, fmt.Errorf("store: begin rotate tx: %w", err) - } - defer tx.Rollback(ctx) - - old, err := scanAPIKeyRow(tx.QueryRow(ctx, - `SELECT `+apiKeyColumns+` FROM api_keys WHERE id = $1 AND owner_account_id = $2 FOR UPDATE`, id, accountID)) - if err != nil { - return "", nil, fmt.Errorf("key not found") - } - - rec := &APIKey{ - ID: newID, - OwnerAccountID: accountID, - Name: old.Name, - Label: KeyLabel(raw), - KeyHash: hashKey(raw), - Disabled: old.Disabled, - LimitMicroUSD: old.LimitMicroUSD, - LimitReset: NormalizeResetWindow(old.LimitReset), - RPMLimit: old.RPMLimit, - ITPMLimit: old.ITPMLimit, - OTPMLimit: old.OTPMLimit, - AllowedModels: old.AllowedModels, - SelfRouteOnly: old.SelfRouteOnly, - ExpiresAt: old.ExpiresAt, - CreatedAt: time.Now().UTC(), - } - if _, err := tx.Exec(ctx, - `INSERT INTO api_keys - (id, key_hash, raw_prefix, owner_account_id, name, active, - limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, - allowed_models, expires_at, created_at, self_route_only) - VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)`, - rec.ID, rec.KeyHash, rec.Label, rec.OwnerAccountID, rec.Name, !rec.Disabled, - rec.LimitMicroUSD, rec.LimitReset, rec.RPMLimit, rec.ITPMLimit, rec.OTPMLimit, - encodeModelList(rec.AllowedModels), rec.ExpiresAt, rec.CreatedAt, rec.SelfRouteOnly, - ); err != nil { - return "", nil, fmt.Errorf("store: insert rotated key: %w", err) - } - if _, err := tx.Exec(ctx, - `DELETE FROM api_keys WHERE id = $1 AND owner_account_id = $2`, id, accountID); err != nil { - return "", nil, fmt.Errorf("store: delete old key: %w", err) - } - if err := tx.Commit(ctx); err != nil { - return "", nil, fmt.Errorf("store: commit rotate: %w", err) - } - return raw, rec, nil -} - -// TouchAPIKey records that a key was used at the given time. -func (s *PostgresStore) TouchAPIKey(id string, at time.Time) { - if id == "" { - return - } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _, _ = s.pool.Exec(ctx, `UPDATE api_keys SET last_used_at = $1 WHERE id = $2`, at.UTC(), id) -} - -// KeySpendSince returns total micro-USD charged to a key since `since` (UTC). -func (s *PostgresStore) KeySpendSince(keyID string, since time.Time) int64 { - if keyID == "" { - return 0 - } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - var total int64 - err := s.pool.QueryRow(ctx, - `SELECT COALESCE(SUM(cost_micro_usd), 0) FROM usage - WHERE key_id = $1 AND ($2::timestamptz IS NULL OR created_at >= $2)`, - keyID, nullSince(since), - ).Scan(&total) - if err != nil { - return 0 - } - return total -} - -// RevokeKey deactivates a key. Returns true if the key existed and was active. -func (s *PostgresStore) RevokeKey(key string) bool { - h := hashKey(key) - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - tag, err := s.pool.Exec(ctx, - `UPDATE api_keys SET active = FALSE WHERE key_hash = $1 AND active = TRUE`, - h, - ) - if err != nil { - return false - } - return tag.RowsAffected() > 0 -} - // UsageByConsumer returns usage records for a specific consumer key. func (s *PostgresStore) UsageByConsumer(consumerKey string) []UsageRecord { h := hashKey(consumerKey) diff --git a/coordinator/store/postgres_api_keys.go b/coordinator/store/postgres_api_keys.go new file mode 100644 index 0000000000..c278afc1f2 --- /dev/null +++ b/coordinator/store/postgres_api_keys.go @@ -0,0 +1,352 @@ +package store + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/eigeninference/d-inference/coordinator/store/storedb" +) + +// The api_keys queries are generated by sqlc from queries/api_keys.sql +// (make sqlc-generate). + +func (s *PostgresStore) queries() *storedb.Queries { return storedb.New(s.pool) } + +// apiKeyFromRow converts one api_keys row into an APIKey. +func apiKeyFromRow(row storedb.ApiKey) *APIKey { + return &APIKey{ + ID: row.ID, + OwnerAccountID: row.OwnerAccountID, + Name: row.Name, + Label: row.RawPrefix, + KeyHash: row.KeyHash, + Disabled: !row.Active, + LimitMicroUSD: row.LimitMicroUsd, + LimitReset: NormalizeResetWindow(row.LimitReset), + RPMLimit: row.RpmLimit, + ITPMLimit: row.ItpmLimit, + OTPMLimit: row.OtpmLimit, + AllowedModels: decodeModelList(row.AllowedModels), + ExpiresAt: row.ExpiresAt, + CreatedAt: row.CreatedAt, + LastUsedAt: row.LastUsedAt, + SelfRouteOnly: row.SelfRouteOnly, + } +} + +// insertAPIKeyParams maps a fully-formed key record to its insert columns. +func insertAPIKeyParams(rec *APIKey) storedb.InsertAPIKeyParams { + return storedb.InsertAPIKeyParams{ + ID: rec.ID, + KeyHash: rec.KeyHash, + RawPrefix: rec.Label, + OwnerAccountID: rec.OwnerAccountID, + Name: rec.Name, + Active: !rec.Disabled, + LimitMicroUsd: rec.LimitMicroUSD, + LimitReset: NormalizeResetWindow(rec.LimitReset), + RpmLimit: rec.RPMLimit, + ItpmLimit: rec.ITPMLimit, + OtpmLimit: rec.OTPMLimit, + AllowedModels: encodeModelList(rec.AllowedModels), + ExpiresAt: rec.ExpiresAt, + CreatedAt: rec.CreatedAt, + SelfRouteOnly: rec.SelfRouteOnly, + } +} + +// encodeModelList serializes a model allow-list for storage. Empty → "". +func encodeModelList(models []string) string { + if len(models) == 0 { + return "" + } + b, err := json.Marshal(models) + if err != nil { + return "" + } + return string(b) +} + +// decodeModelList parses a stored model allow-list. "" / invalid → nil. +func decodeModelList(s string) []string { + if s == "" || s == "[]" { + return nil + } + var out []string + if err := json.Unmarshal([]byte(s), &out); err != nil { + return nil + } + if len(out) == 0 { + return nil + } + return out +} + +// CreateKeyForAccount generates a new API key linked to a specific account. +func (s *PostgresStore) CreateKeyForAccount(accountID string) (string, error) { + raw, _, err := s.CreateAPIKey(accountID, APIKeyCreate{}) + return raw, err +} + +// CreateAPIKey mints a new API key with optional per-key limits. +func (s *PostgresStore) CreateAPIKey(accountID string, opts APIKeyCreate) (string, *APIKey, error) { + raw, err := GenerateRawKey() + if err != nil { + return "", nil, fmt.Errorf("store: generate key: %w", err) + } + id, err := GenerateKeyID() + if err != nil { + return "", nil, fmt.Errorf("store: generate key id: %w", err) + } + rec := &APIKey{ + ID: id, + OwnerAccountID: accountID, + Name: opts.Name, + Label: KeyLabel(raw), + KeyHash: hashKey(raw), + LimitMicroUSD: opts.LimitMicroUSD, + LimitReset: NormalizeResetWindow(opts.LimitReset), + RPMLimit: opts.RPMLimit, + ITPMLimit: opts.ITPMLimit, + OTPMLimit: opts.OTPMLimit, + AllowedModels: opts.AllowedModels, + SelfRouteOnly: opts.SelfRouteOnly, + ExpiresAt: opts.ExpiresAt, + CreatedAt: time.Now().UTC(), + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := s.queries().InsertAPIKey(ctx, insertAPIKeyParams(rec)); err != nil { + return "", nil, fmt.Errorf("store: insert key: %w", err) + } + return raw, rec, nil +} + +// SeedKey inserts a specific raw key into the database. This is used for +// bootstrapping the admin key. If the key already exists, it is a no-op. +func (s *PostgresStore) SeedKey(rawKey string) error { + id, err := GenerateKeyID() + if err != nil { + return fmt.Errorf("store: generate key id: %w", err) + } + rec := &APIKey{ + ID: id, + Name: "admin", + Label: KeyLabel(rawKey), + KeyHash: hashKey(rawKey), + LimitReset: KeyResetNone, + CreatedAt: time.Now().UTC(), + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := s.queries().InsertAPIKeyIfAbsent(ctx, storedb.InsertAPIKeyIfAbsentParams(insertAPIKeyParams(rec))); err != nil { + return fmt.Errorf("store: seed key: %w", err) + } + return nil +} + +// GetKeyAccount returns the account ID that owns this key, or "" if unlinked. +func (s *PostgresStore) GetKeyAccount(key string) string { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + accountID, err := s.queries().GetActiveKeyAccount(ctx, hashKey(key)) + if err != nil { + return "" + } + return accountID +} + +// AuthenticateKey resolves a raw key to its active record for request auth. +func (s *PostgresStore) AuthenticateKey(rawKey string) (*APIKey, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + row, err := s.queries().GetAPIKeyByHash(ctx, hashKey(rawKey)) + if err != nil { + return nil, err + } + k := apiKeyFromRow(row) + if k.Disabled { + return nil, fmt.Errorf("key disabled") + } + if k.ExpiresAt != nil && time.Now().After(*k.ExpiresAt) { + return nil, fmt.Errorf("key expired") + } + return k, nil +} + +// ListAPIKeys returns all keys owned by an account, newest first. +func (s *PostgresStore) ListAPIKeys(accountID string) ([]APIKey, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + rows, err := s.queries().ListAPIKeysByOwner(ctx, accountID) + if err != nil { + return nil, err + } + out := make([]APIKey, 0, len(rows)) + for _, row := range rows { + out = append(out, *apiKeyFromRow(row)) + } + return out, nil +} + +// GetAPIKeyByID returns a single key by ID, scoped to the owner. +func (s *PostgresStore) GetAPIKeyByID(accountID, id string) (*APIKey, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + row, err := s.queries().GetAPIKeyByID(ctx, storedb.GetAPIKeyByIDParams{ID: id, OwnerAccountID: accountID}) + if err != nil { + return nil, err + } + return apiKeyFromRow(row), nil +} + +// UpdateAPIKey overwrites mutable fields of a key, scoped to the owner. +func (s *PostgresStore) UpdateAPIKey(accountID, id string, mutable APIKey) (*APIKey, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + updated, err := s.queries().UpdateAPIKey(ctx, storedb.UpdateAPIKeyParams{ + Name: mutable.Name, + Active: !mutable.Disabled, + LimitMicroUsd: mutable.LimitMicroUSD, + LimitReset: NormalizeResetWindow(mutable.LimitReset), + RpmLimit: mutable.RPMLimit, + ItpmLimit: mutable.ITPMLimit, + OtpmLimit: mutable.OTPMLimit, + AllowedModels: encodeModelList(mutable.AllowedModels), + ExpiresAt: mutable.ExpiresAt, + SelfRouteOnly: mutable.SelfRouteOnly, + ID: id, + OwnerAccountID: accountID, + }) + if err != nil { + return nil, err + } + if updated == 0 { + return nil, fmt.Errorf("key not found") + } + return s.GetAPIKeyByID(accountID, id) +} + +// RevokeAPIKeyByID permanently deletes a key by ID, scoped to the owner. +func (s *PostgresStore) RevokeAPIKeyByID(accountID, id string) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + deleted, err := s.queries().DeleteAPIKeyByID(ctx, storedb.DeleteAPIKeyByIDParams{ID: id, OwnerAccountID: accountID}) + if err != nil { + return err + } + if deleted == 0 { + return fmt.Errorf("key not found") + } + return nil +} + +// RotateAPIKey atomically replaces a key within a transaction (see Store +// interface). The old key is deleted and the new key inserted in the same tx; +// a concurrent rotate of the same id finds the row gone and returns not-found. +func (s *PostgresStore) RotateAPIKey(accountID, id string) (string, *APIKey, error) { + raw, err := GenerateRawKey() + if err != nil { + return "", nil, fmt.Errorf("store: generate key: %w", err) + } + newID, err := GenerateKeyID() + if err != nil { + return "", nil, fmt.Errorf("store: generate key id: %w", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + tx, err := s.pool.Begin(ctx) + if err != nil { + return "", nil, fmt.Errorf("store: begin rotate tx: %w", err) + } + defer tx.Rollback(ctx) + q := storedb.New(tx) + + oldRow, err := q.GetAPIKeyByIDForUpdate(ctx, storedb.GetAPIKeyByIDForUpdateParams{ID: id, OwnerAccountID: accountID}) + if err != nil { + return "", nil, fmt.Errorf("key not found") + } + old := apiKeyFromRow(oldRow) + + rec := &APIKey{ + ID: newID, + OwnerAccountID: accountID, + Name: old.Name, + Label: KeyLabel(raw), + KeyHash: hashKey(raw), + Disabled: old.Disabled, + LimitMicroUSD: old.LimitMicroUSD, + LimitReset: NormalizeResetWindow(old.LimitReset), + RPMLimit: old.RPMLimit, + ITPMLimit: old.ITPMLimit, + OTPMLimit: old.OTPMLimit, + AllowedModels: old.AllowedModels, + SelfRouteOnly: old.SelfRouteOnly, + ExpiresAt: old.ExpiresAt, + CreatedAt: time.Now().UTC(), + } + if err := q.InsertAPIKey(ctx, insertAPIKeyParams(rec)); err != nil { + return "", nil, fmt.Errorf("store: insert rotated key: %w", err) + } + if _, err := q.DeleteAPIKeyByID(ctx, storedb.DeleteAPIKeyByIDParams{ID: id, OwnerAccountID: accountID}); err != nil { + return "", nil, fmt.Errorf("store: delete old key: %w", err) + } + if err := tx.Commit(ctx); err != nil { + return "", nil, fmt.Errorf("store: commit rotate: %w", err) + } + return raw, rec, nil +} + +// TouchAPIKey records that a key was used at the given time. +func (s *PostgresStore) TouchAPIKey(id string, at time.Time) { + if id == "" { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + lastUsed := at.UTC() + _ = s.queries().TouchAPIKey(ctx, storedb.TouchAPIKeyParams{LastUsedAt: &lastUsed, ID: id}) +} + +// KeySpendSince returns total micro-USD charged to a key since `since` (UTC). +func (s *PostgresStore) KeySpendSince(keyID string, since time.Time) int64 { + if keyID == "" { + return 0 + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + params := storedb.KeySpendSinceParams{KeyID: keyID} + if !since.IsZero() { + params.Since = &since + } + total, err := s.queries().KeySpendSince(ctx, params) + if err != nil { + return 0 + } + return total +} + +// RevokeKey deactivates a key. Returns true if the key existed and was active. +func (s *PostgresStore) RevokeKey(key string) bool { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + deactivated, err := s.queries().DeactivateAPIKeyByHash(ctx, hashKey(key)) + if err != nil { + return false + } + return deactivated > 0 +} diff --git a/coordinator/store/queries/api_keys.sql b/coordinator/store/queries/api_keys.sql new file mode 100644 index 0000000000..6592dd6b9b --- /dev/null +++ b/coordinator/store/queries/api_keys.sql @@ -0,0 +1,50 @@ +-- name: InsertAPIKey :exec +INSERT INTO api_keys + (id, key_hash, raw_prefix, owner_account_id, name, active, + limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, + allowed_models, expires_at, created_at, self_route_only) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15); + +-- name: InsertAPIKeyIfAbsent :exec +INSERT INTO api_keys + (id, key_hash, raw_prefix, owner_account_id, name, active, + limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, + allowed_models, expires_at, created_at, self_route_only) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) +ON CONFLICT (key_hash) DO NOTHING; + +-- name: GetActiveKeyAccount :one +SELECT owner_account_id FROM api_keys WHERE key_hash = $1 AND active = TRUE; + +-- name: GetAPIKeyByHash :one +SELECT * FROM api_keys WHERE key_hash = $1; + +-- name: ListAPIKeysByOwner :many +SELECT * FROM api_keys WHERE owner_account_id = $1 AND id <> '' ORDER BY created_at DESC; + +-- name: GetAPIKeyByID :one +SELECT * FROM api_keys WHERE id = $1 AND owner_account_id = $2; + +-- name: GetAPIKeyByIDForUpdate :one +SELECT * FROM api_keys WHERE id = $1 AND owner_account_id = $2 FOR UPDATE; + +-- name: UpdateAPIKey :execrows +UPDATE api_keys SET + name = $1, active = $2, limit_micro_usd = $3, limit_reset = $4, + rpm_limit = $5, itpm_limit = $6, otpm_limit = $7, + allowed_models = $8, expires_at = $9, self_route_only = $10 +WHERE id = $11 AND owner_account_id = $12; + +-- name: DeleteAPIKeyByID :execrows +DELETE FROM api_keys WHERE id = $1 AND owner_account_id = $2; + +-- name: TouchAPIKey :exec +UPDATE api_keys SET last_used_at = $1 WHERE id = $2; + +-- name: KeySpendSince :one +SELECT COALESCE(SUM(cost_micro_usd), 0)::bigint AS total_micro_usd FROM usage +WHERE key_id = sqlc.arg('key_id') + AND (sqlc.narg('since')::timestamptz IS NULL OR created_at >= sqlc.narg('since')); + +-- name: DeactivateAPIKeyByHash :execrows +UPDATE api_keys SET active = FALSE WHERE key_hash = $1 AND active = TRUE; diff --git a/coordinator/store/sqlc.yaml b/coordinator/store/sqlc.yaml new file mode 100644 index 0000000000..be1b1dbb9a --- /dev/null +++ b/coordinator/store/sqlc.yaml @@ -0,0 +1,27 @@ +version: "2" +sql: + - engine: postgresql + schema: schema/schema.sql + queries: queries + gen: + go: + package: storedb + out: storedb + sql_package: pgx/v5 + emit_pointers_for_null_types: true + omit_unused_structs: true + overrides: + - db_type: pg_catalog.timestamptz + go_type: time.Time + - db_type: pg_catalog.timestamptz + nullable: true + go_type: + type: time.Time + pointer: true + - db_type: timestamptz + go_type: time.Time + - db_type: timestamptz + nullable: true + go_type: + type: time.Time + pointer: true diff --git a/coordinator/store/storedb/api_keys.sql.go b/coordinator/store/storedb/api_keys.sql.go new file mode 100644 index 0000000000..532dc54979 --- /dev/null +++ b/coordinator/store/storedb/api_keys.sql.go @@ -0,0 +1,357 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: api_keys.sql + +package storedb + +import ( + "context" + "time" +) + +const deactivateAPIKeyByHash = `-- name: DeactivateAPIKeyByHash :execrows +UPDATE api_keys SET active = FALSE WHERE key_hash = $1 AND active = TRUE +` + +func (q *Queries) DeactivateAPIKeyByHash(ctx context.Context, keyHash string) (int64, error) { + result, err := q.db.Exec(ctx, deactivateAPIKeyByHash, keyHash) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteAPIKeyByID = `-- name: DeleteAPIKeyByID :execrows +DELETE FROM api_keys WHERE id = $1 AND owner_account_id = $2 +` + +type DeleteAPIKeyByIDParams struct { + ID string + OwnerAccountID string +} + +func (q *Queries) DeleteAPIKeyByID(ctx context.Context, arg DeleteAPIKeyByIDParams) (int64, error) { + result, err := q.db.Exec(ctx, deleteAPIKeyByID, arg.ID, arg.OwnerAccountID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const getAPIKeyByHash = `-- name: GetAPIKeyByHash :one +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE key_hash = $1 +` + +func (q *Queries) GetAPIKeyByHash(ctx context.Context, keyHash string) (ApiKey, error) { + row := q.db.QueryRow(ctx, getAPIKeyByHash, keyHash) + var i ApiKey + err := row.Scan( + &i.KeyHash, + &i.RawPrefix, + &i.OwnerAccountID, + &i.CreatedAt, + &i.Active, + &i.ID, + &i.Name, + &i.LimitMicroUsd, + &i.LimitReset, + &i.RpmLimit, + &i.ItpmLimit, + &i.OtpmLimit, + &i.AllowedModels, + &i.ExpiresAt, + &i.LastUsedAt, + &i.SelfRouteOnly, + ) + return i, err +} + +const getAPIKeyByID = `-- name: GetAPIKeyByID :one +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE id = $1 AND owner_account_id = $2 +` + +type GetAPIKeyByIDParams struct { + ID string + OwnerAccountID string +} + +func (q *Queries) GetAPIKeyByID(ctx context.Context, arg GetAPIKeyByIDParams) (ApiKey, error) { + row := q.db.QueryRow(ctx, getAPIKeyByID, arg.ID, arg.OwnerAccountID) + var i ApiKey + err := row.Scan( + &i.KeyHash, + &i.RawPrefix, + &i.OwnerAccountID, + &i.CreatedAt, + &i.Active, + &i.ID, + &i.Name, + &i.LimitMicroUsd, + &i.LimitReset, + &i.RpmLimit, + &i.ItpmLimit, + &i.OtpmLimit, + &i.AllowedModels, + &i.ExpiresAt, + &i.LastUsedAt, + &i.SelfRouteOnly, + ) + return i, err +} + +const getAPIKeyByIDForUpdate = `-- name: GetAPIKeyByIDForUpdate :one +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE id = $1 AND owner_account_id = $2 FOR UPDATE +` + +type GetAPIKeyByIDForUpdateParams struct { + ID string + OwnerAccountID string +} + +func (q *Queries) GetAPIKeyByIDForUpdate(ctx context.Context, arg GetAPIKeyByIDForUpdateParams) (ApiKey, error) { + row := q.db.QueryRow(ctx, getAPIKeyByIDForUpdate, arg.ID, arg.OwnerAccountID) + var i ApiKey + err := row.Scan( + &i.KeyHash, + &i.RawPrefix, + &i.OwnerAccountID, + &i.CreatedAt, + &i.Active, + &i.ID, + &i.Name, + &i.LimitMicroUsd, + &i.LimitReset, + &i.RpmLimit, + &i.ItpmLimit, + &i.OtpmLimit, + &i.AllowedModels, + &i.ExpiresAt, + &i.LastUsedAt, + &i.SelfRouteOnly, + ) + return i, err +} + +const getActiveKeyAccount = `-- name: GetActiveKeyAccount :one +SELECT owner_account_id FROM api_keys WHERE key_hash = $1 AND active = TRUE +` + +func (q *Queries) GetActiveKeyAccount(ctx context.Context, keyHash string) (string, error) { + row := q.db.QueryRow(ctx, getActiveKeyAccount, keyHash) + var owner_account_id string + err := row.Scan(&owner_account_id) + return owner_account_id, err +} + +const insertAPIKey = `-- name: InsertAPIKey :exec +INSERT INTO api_keys + (id, key_hash, raw_prefix, owner_account_id, name, active, + limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, + allowed_models, expires_at, created_at, self_route_only) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) +` + +type InsertAPIKeyParams struct { + ID string + KeyHash string + RawPrefix string + OwnerAccountID string + Name string + Active bool + LimitMicroUsd *int64 + LimitReset string + RpmLimit *int64 + ItpmLimit *int64 + OtpmLimit *int64 + AllowedModels string + ExpiresAt *time.Time + CreatedAt time.Time + SelfRouteOnly bool +} + +func (q *Queries) InsertAPIKey(ctx context.Context, arg InsertAPIKeyParams) error { + _, err := q.db.Exec(ctx, insertAPIKey, + arg.ID, + arg.KeyHash, + arg.RawPrefix, + arg.OwnerAccountID, + arg.Name, + arg.Active, + arg.LimitMicroUsd, + arg.LimitReset, + arg.RpmLimit, + arg.ItpmLimit, + arg.OtpmLimit, + arg.AllowedModels, + arg.ExpiresAt, + arg.CreatedAt, + arg.SelfRouteOnly, + ) + return err +} + +const insertAPIKeyIfAbsent = `-- name: InsertAPIKeyIfAbsent :exec +INSERT INTO api_keys + (id, key_hash, raw_prefix, owner_account_id, name, active, + limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, + allowed_models, expires_at, created_at, self_route_only) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) +ON CONFLICT (key_hash) DO NOTHING +` + +type InsertAPIKeyIfAbsentParams struct { + ID string + KeyHash string + RawPrefix string + OwnerAccountID string + Name string + Active bool + LimitMicroUsd *int64 + LimitReset string + RpmLimit *int64 + ItpmLimit *int64 + OtpmLimit *int64 + AllowedModels string + ExpiresAt *time.Time + CreatedAt time.Time + SelfRouteOnly bool +} + +func (q *Queries) InsertAPIKeyIfAbsent(ctx context.Context, arg InsertAPIKeyIfAbsentParams) error { + _, err := q.db.Exec(ctx, insertAPIKeyIfAbsent, + arg.ID, + arg.KeyHash, + arg.RawPrefix, + arg.OwnerAccountID, + arg.Name, + arg.Active, + arg.LimitMicroUsd, + arg.LimitReset, + arg.RpmLimit, + arg.ItpmLimit, + arg.OtpmLimit, + arg.AllowedModels, + arg.ExpiresAt, + arg.CreatedAt, + arg.SelfRouteOnly, + ) + return err +} + +const keySpendSince = `-- name: KeySpendSince :one +SELECT COALESCE(SUM(cost_micro_usd), 0)::bigint AS total_micro_usd FROM usage +WHERE key_id = $1 + AND ($2::timestamptz IS NULL OR created_at >= $2) +` + +type KeySpendSinceParams struct { + KeyID string + Since *time.Time +} + +func (q *Queries) KeySpendSince(ctx context.Context, arg KeySpendSinceParams) (int64, error) { + row := q.db.QueryRow(ctx, keySpendSince, arg.KeyID, arg.Since) + var total_micro_usd int64 + err := row.Scan(&total_micro_usd) + return total_micro_usd, err +} + +const listAPIKeysByOwner = `-- name: ListAPIKeysByOwner :many +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE owner_account_id = $1 AND id <> '' ORDER BY created_at DESC +` + +func (q *Queries) ListAPIKeysByOwner(ctx context.Context, ownerAccountID string) ([]ApiKey, error) { + rows, err := q.db.Query(ctx, listAPIKeysByOwner, ownerAccountID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ApiKey + for rows.Next() { + var i ApiKey + if err := rows.Scan( + &i.KeyHash, + &i.RawPrefix, + &i.OwnerAccountID, + &i.CreatedAt, + &i.Active, + &i.ID, + &i.Name, + &i.LimitMicroUsd, + &i.LimitReset, + &i.RpmLimit, + &i.ItpmLimit, + &i.OtpmLimit, + &i.AllowedModels, + &i.ExpiresAt, + &i.LastUsedAt, + &i.SelfRouteOnly, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const touchAPIKey = `-- name: TouchAPIKey :exec +UPDATE api_keys SET last_used_at = $1 WHERE id = $2 +` + +type TouchAPIKeyParams struct { + LastUsedAt *time.Time + ID string +} + +func (q *Queries) TouchAPIKey(ctx context.Context, arg TouchAPIKeyParams) error { + _, err := q.db.Exec(ctx, touchAPIKey, arg.LastUsedAt, arg.ID) + return err +} + +const updateAPIKey = `-- name: UpdateAPIKey :execrows +UPDATE api_keys SET + name = $1, active = $2, limit_micro_usd = $3, limit_reset = $4, + rpm_limit = $5, itpm_limit = $6, otpm_limit = $7, + allowed_models = $8, expires_at = $9, self_route_only = $10 +WHERE id = $11 AND owner_account_id = $12 +` + +type UpdateAPIKeyParams struct { + Name string + Active bool + LimitMicroUsd *int64 + LimitReset string + RpmLimit *int64 + ItpmLimit *int64 + OtpmLimit *int64 + AllowedModels string + ExpiresAt *time.Time + SelfRouteOnly bool + ID string + OwnerAccountID string +} + +func (q *Queries) UpdateAPIKey(ctx context.Context, arg UpdateAPIKeyParams) (int64, error) { + result, err := q.db.Exec(ctx, updateAPIKey, + arg.Name, + arg.Active, + arg.LimitMicroUsd, + arg.LimitReset, + arg.RpmLimit, + arg.ItpmLimit, + arg.OtpmLimit, + arg.AllowedModels, + arg.ExpiresAt, + arg.SelfRouteOnly, + arg.ID, + arg.OwnerAccountID, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/coordinator/store/storedb/db.go b/coordinator/store/storedb/db.go new file mode 100644 index 0000000000..3d8ce51fbc --- /dev/null +++ b/coordinator/store/storedb/db.go @@ -0,0 +1,32 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package storedb + +import ( + "context" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +type DBTX interface { + Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) + Query(context.Context, string, ...interface{}) (pgx.Rows, error) + QueryRow(context.Context, string, ...interface{}) pgx.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx pgx.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/coordinator/store/storedb/models.go b/coordinator/store/storedb/models.go new file mode 100644 index 0000000000..48fbac1341 --- /dev/null +++ b/coordinator/store/storedb/models.go @@ -0,0 +1,28 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package storedb + +import ( + "time" +) + +type ApiKey struct { + KeyHash string + RawPrefix string + OwnerAccountID string + CreatedAt time.Time + Active bool + ID string + Name string + LimitMicroUsd *int64 + LimitReset string + RpmLimit *int64 + ItpmLimit *int64 + OtpmLimit *int64 + AllowedModels string + ExpiresAt *time.Time + LastUsedAt *time.Time + SelfRouteOnly bool +} diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 482279a1fb..7eaa51375f 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -144,7 +144,11 @@ finds nothing to apply. Out-of-order versions are refused. `coordinator/store/schema/schema.sql` is the `pg_dump --schema-only` of the schema the migrations build, without `goose_db_version`. `TestMigrationsBuildCheckedInSchema` builds a fresh database with goose and -fails when its schema differs from that file. To add a migration, follow +fails when its schema differs from that file. The file is also the schema that +sqlc reads: the api_keys queries are SQL in `coordinator/store/queries/api_keys.sql`, +and `make sqlc-generate` turns them into Go in `coordinator/store/storedb` +(`coordinator/store/sqlc.yaml`). sqlc reads the dump, not the migrations, +because it cannot see columns that the baseline adds inside `DO` blocks. To add a migration, follow [Add a database migration](../developer/database-migrations.md). `schema_migrations` is a separate, older table. It holds the markers of the @@ -371,6 +375,7 @@ KV blocks under a per-model key, not tokens. | Backend selection and validation | `coordinator/store/config.go`, `coordinator/cmd/coordinator/main.go` | | Postgres pool | `coordinator/store/postgres.go` | | Migrations | `coordinator/store/postgres_migrations.go` (`migrate`, `goMigrations`), `coordinator/store/schema/migrations/`, `coordinator/store/schema/schema.sql`, `coordinator/store/postgres_retired_backfills.go` | +| Generated queries (sqlc) | `coordinator/store/sqlc.yaml`, `coordinator/store/queries/`, `coordinator/store/storedb/`; api_keys in `coordinator/store/postgres_api_keys.go` | | Provider identity and usage reads | `coordinator/store/postgres_provider_read.go` (`providerRecordColumns`, `scanProviderRecord`, `GetProviderRecord`); `coordinator/store/provider_restore.go` (`GetProviderForRestore`, using the same projection); `coordinator/store/postgres_usage_read.go` (`readUsageRecords`, `UsageRecords`); `coordinator/store/postgres_row.go` (`rowScanner`) | | Domain files | `coordinator/store/postgres_model_registry.go`, `coordinator/store/postgres_base_rewards.go`, `coordinator/store/postgres_profiles.go`, `coordinator/store/route_telemetry.go`, `coordinator/store/usage_time_series.go`, `coordinator/store/apikey.go` | | Memory backend | `coordinator/store/memory.go`, `coordinator/store/memory_base_rewards.go` | diff --git a/docs/developer/build.md b/docs/developer/build.md index 528606dd7e..945d401e4b 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -794,6 +794,8 @@ local stub servers; its default observation mode sends only public GETs. | `coordinator-build` | `go build ./cmd/coordinator` → `./coordinator/coordinator` | | `coordinator-build-linux` | `GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o coordinator-linux ./cmd/coordinator` | | `coordinator` | `coordinator-test` + `coordinator-build` | +| `sqlc-generate` | `go run github.com/sqlc-dev/sqlc/cmd/sqlc@v1.31.1 generate -f coordinator/store/sqlc.yaml` → `coordinator/store/storedb` | +| `sqlc-check` | Needs `DATABASE_URL`. `TestMigrationsBuildCheckedInSchema` (fails when `coordinator/store/schema/schema.sql` is stale), then `sqlc diff` (fails when `coordinator/store/storedb` is stale) | | `prompt-sidecar-format` | `cargo fmt --all -- --check` | | `prompt-sidecar-check` | `cargo check --locked --all-targets` + `cargo clippy --locked --all-targets -- -D warnings` | | `prompt-sidecar-test` | `cargo test --locked --all-targets` | diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index 2887b17ee6..392298f22f 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -52,7 +52,9 @@ mechanism is explained in ``` Use a `pg_dump` of the same major version as production (17). -5. Update `MemoryStore` and the docs that describe the changed tables +5. If a query in `coordinator/store/queries/` reads the changed table, run + `make sqlc-generate` so `coordinator/store/storedb` matches the new schema. +6. Update `MemoryStore` and the docs that describe the changed tables ([storage](../architecture/storage.md)). ## Verify @@ -63,7 +65,12 @@ DATABASE_URL='postgres://postgres:pg@127.0.0.1:55432/postgres?sslmode=disable' \ ``` `TestMigrationsBuildCheckedInSchema` fails when `schema.sql` does not match -what the migrations build. +what the migrations build. CI also runs `make sqlc-check`, which runs that test +and fails when the generated sqlc code is stale: + +```bash +DATABASE_URL='postgres://postgres:pg@127.0.0.1:55432/postgres?sslmode=disable' make sqlc-check +``` ## Troubleshooting diff --git a/docs/developer/test.md b/docs/developer/test.md index e5dd34bc24..c36874f716 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test -> Last updated: 2026-10-01 +> Last updated: 2026-10-03 The provider test runner isolates daemon-state and loaded-model snapshots in a temporary directory for each run. Unit-test providers must not overwrite the @@ -918,7 +918,8 @@ positive, negative and missing operands in Store tests that need Postgres skip themselves when `DATABASE_URL` is unset (`coordinator/store/harness_test.go`, `testPostgresStore`); CI provides a -`postgres:16` service with user/password/db `testbed`. The pre-push hook runs +`postgres:17` service with user/password/db `testbed`, and runs +`make sqlc-check` against it after the tests. The pre-push hook runs `go test $(go list ./... | grep -v /internal/api)` from `coordinator/` to skip the slow WebSocket integration tests; run the full set before merging. @@ -2368,7 +2369,7 @@ token IDs are accepted. | Workflow | Trigger | Jobs (name → what runs) | |---|---|---| -| [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) | push, PR | **Release Integrity** — release/script checks and offline provider CI/cache/routing guards · **Docs Lint** — `scripts/docs-check.sh` · **Coordinator Tests** — `scripts/run-coordinator-tests.py --race --coverprofile` over every package except the top-level `e2e` integration package (`coordinator/internal/e2e` and `e2e/testbed/...` run), isolated API/registry shards and runner guards, with `postgres:16` service + `gofmt` on tracked Go files outside frozen report evidence; total statement coverage in the job summary, merged `coverage.out` and timing evidence kept 14 days · **Coordinator Lint** — `golangci-lint run` (v2.1.6) · **Prompt Sidecar Tests** — cargo fmt/check/clippy/test on Rust 1.88.0, static musl Docker stage, `verify-prompt-sidecar-linux.sh`, then `cargo llvm-cov` (0.9.1) line coverage in the job summary · **Provider Unit Tests** (macOS 12-vcpu) — full debug test build, matched Metal, serial/fresh-process provider tests and installer checks · **Provider SDK Tests** (independent macOS 12-vcpu) — full nested test build and all required numerical/SDK selectors through checked wrappers · **Provider Prompt Parity** (independent macOS 12-vcpu) — `verify-prompt-parity.sh`, pinned Swift/Go/Rust vectors and sustained sidecar load proof · **Provider Tests** (Linux aggregate) — requires all three provider lanes to succeed · **Swift Build + Cache** — release build of `darkbloom` + `darkbloom-fan-helper` · **Console UI Lint & Build** — Node 22, `npm ci`, lint, vitest, and Next.js build | +| [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) | push, PR | **Release Integrity** — release/script checks and offline provider CI/cache/routing guards · **Docs Lint** — `scripts/docs-check.sh` · **Coordinator Tests** — `scripts/run-coordinator-tests.py --race --coverprofile` over every package except the top-level `e2e` integration package (`coordinator/internal/e2e` and `e2e/testbed/...` run), isolated API/registry shards and runner guards, with `postgres:17` service, `make sqlc-check` + `gofmt` on tracked Go files outside frozen report evidence; total statement coverage in the job summary, merged `coverage.out` and timing evidence kept 14 days · **Coordinator Lint** — `golangci-lint run` (v2.1.6) · **Prompt Sidecar Tests** — cargo fmt/check/clippy/test on Rust 1.88.0, static musl Docker stage, `verify-prompt-sidecar-linux.sh`, then `cargo llvm-cov` (0.9.1) line coverage in the job summary · **Provider Unit Tests** (macOS 12-vcpu) — full debug test build, matched Metal, serial/fresh-process provider tests and installer checks · **Provider SDK Tests** (independent macOS 12-vcpu) — full nested test build and all required numerical/SDK selectors through checked wrappers · **Provider Prompt Parity** (independent macOS 12-vcpu) — `verify-prompt-parity.sh`, pinned Swift/Go/Rust vectors and sustained sidecar load proof · **Provider Tests** (Linux aggregate) — requires all three provider lanes to succeed · **Swift Build + Cache** — release build of `darkbloom` + `darkbloom-fan-helper` · **Console UI Lint & Build** — Node 22, `npm ci`, lint, vitest, and Next.js build | | [`.github/workflows/integration.yml`](../../.github/workflows/integration.yml) | push to `master`/`main`, PR | **E2E Integration Tests** (macOS, 75 min budget): install Postgres 16, `swift build -c debug`, cargo sidecar build, metallib staging, HF snapshot downloads; lanes: paged @ 8 blocking gate (`TestIntegration\|TestProfile` minus exact-cache) → exact-cache routing paged @ 8 (blocking; explicit SSD opt-in and repeat demand) → default-posture smoke (`EXPECT_KV_BACKEND=contiguous`) | | [`.github/workflows/benchmarks.yml`](../../.github/workflows/benchmarks.yml) | PR, gated by the `benchmarks` environment (manual approval) | **E2E Benchmarks** — `go test ./e2e/ -count=1 -v -timeout 40m -p=1 -run 'TestBenchmark'`, posts `BENCHMARK_MD_PATH` as a PR comment | | [`.github/workflows/release-swift.yml`](../../.github/workflows/release-swift.yml) | tag `v*`, manual | Provider release; see [`../operations/provider-release.md`](../operations/provider-release.md) | From b79afa999f1f9788f3261103cb41da40ee9d65a3 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 08:32:03 -0500 Subject: [PATCH 04/20] Add soft-delete columns and erase-path indexes New goose migrations 6 to 17, no change to the baseline: - 6-12: one CREATE INDEX CONCURRENTLY per file on the account columns that account erasure filters by; each drops an invalid leftover first and waits up to 1 min for older snapshots. - 13: deleted_at TIMESTAMPTZ on users, api_keys, providers, provider_tokens. - 14-16: users.privy_user_id is unique among live users only. - 17: referrals.referrer_code foreign key with ON UPDATE CASCADE, added NOT VALID and validated. Every read that returns a live user, key, provider record or provider token now filters deleted_at IS NULL, including GetProviderForRestore. MemoryStore mirrors this with DeletedAt fields. Nothing sets deleted_at yet; tests set it and prove each read hides the row on both stores. Regenerate schema.sql and the sqlc code; keep the pre-goose dump as testdata for the upgrade test. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + coordinator/store/interface.go | 12 + .../store/machine_inventory_backfill.go | 2 +- coordinator/store/memory.go | 34 +- .../store/memory_machine_continuity.go | 2 +- coordinator/store/migration_harness_test.go | 23 +- .../store/model_token_promotions_memory.go | 2 +- .../store/model_token_promotions_postgres.go | 2 +- coordinator/store/postgres.go | 13 +- coordinator/store/postgres_analytics_flows.go | 2 +- .../store/postgres_machine_continuity.go | 2 +- coordinator/store/postgres_migrations_test.go | 92 +- coordinator/store/postgres_provider_read.go | 2 +- coordinator/store/provider_restore.go | 3 +- coordinator/store/queries/api_keys.sql | 12 +- .../00006_provider_sessions_account_index.sql | 12 + ...007_provider_log_reports_account_index.sql | 12 + .../00008_device_codes_account_index.sql | 12 + ...rkbloom_machine_sessions_account_index.sql | 12 + ...model_token_reservations_account_index.sql | 12 + ...ference_routes_consumer_key_hash_index.sql | 12 + ...est_rejections_consumer_key_hash_index.sql | 12 + .../migrations/00013_soft_delete_columns.sql | 10 + .../00014_users_privy_live_index.sql | 12 + ...015_users_privy_drop_unique_constraint.sql | 2 + .../00016_users_privy_drop_old_index.sql | 8 + .../00017_referrals_referrer_code_cascade.sql | 11 + coordinator/store/schema/schema.sql | 77 +- coordinator/store/soft_delete_reads_test.go | 284 ++ coordinator/store/storedb/api_keys.sql.go | 16 +- coordinator/store/storedb/models.go | 1 + .../store/testdata/schema_pre_goose.sql | 3340 +++++++++++++++++ docs/architecture/storage.md | 43 +- docs/developer/database-migrations.md | 21 +- docs/operations/coordinator-deploy.md | 11 +- 35 files changed, 4031 insertions(+), 93 deletions(-) create mode 100644 coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql create mode 100644 coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql create mode 100644 coordinator/store/schema/migrations/00008_device_codes_account_index.sql create mode 100644 coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql create mode 100644 coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql create mode 100644 coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql create mode 100644 coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql create mode 100644 coordinator/store/schema/migrations/00013_soft_delete_columns.sql create mode 100644 coordinator/store/schema/migrations/00014_users_privy_live_index.sql create mode 100644 coordinator/store/schema/migrations/00015_users_privy_drop_unique_constraint.sql create mode 100644 coordinator/store/schema/migrations/00016_users_privy_drop_old_index.sql create mode 100644 coordinator/store/schema/migrations/00017_referrals_referrer_code_cascade.sql create mode 100644 coordinator/store/soft_delete_reads_test.go create mode 100644 coordinator/store/testdata/schema_pre_goose.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f709a28dc..b7c1a6e5d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Apply the coordinator's Postgres schema as numbered goose migrations instead of re-running every DDL statement at each boot. The first boot records the existing schema as version 1 without changing it; later boots apply only new versions. Migration statements stop waiting for a lock after 3 seconds and retry up to three times, and coordinators that start together take turns on an advisory lock. - Check in the schema as `coordinator/store/schema/schema.sql` and test that the migrations build exactly that schema. New schema changes go in a new numbered migration file. - Generate the coordinator's API-key queries with sqlc from that schema; `make sqlc-check` fails CI when the generated code or the schema file is stale. API-key behaviour does not change. +- Prepare account erasure: add `deleted_at` to users, API keys, provider records and provider tokens, hide soft-deleted rows from every live read, let a Privy user sign up again after erasure, index the erase paths, and cascade referrer code changes to referrals. Nothing sets `deleted_at` yet. After this release runs, roll back only to coordinator images built with goose. ## Unreleased — leaderboard availability diff --git a/coordinator/store/interface.go b/coordinator/store/interface.go index ef5a00f4a4..b9f584f861 100644 --- a/coordinator/store/interface.go +++ b/coordinator/store/interface.go @@ -507,6 +507,9 @@ type APIKey struct { ExpiresAt *time.Time `json:"expires_at,omitempty"` CreatedAt time.Time `json:"created_at"` LastUsedAt *time.Time `json:"last_used_at,omitempty"` + + // DeletedAt marks a soft-deleted key; no read returns it. + DeletedAt *time.Time `json:"-"` } // APIKeyCreate carries the create-time options for a new API key. All limit @@ -560,6 +563,9 @@ type User struct { StripeDestinationType string `json:"stripe_destination_type,omitempty"` // "bank" | "card" | "" StripeDestinationLast4 string `json:"stripe_destination_last4,omitempty"` StripeInstantEligible bool `json:"stripe_instant_eligible,omitempty"` // debit-card destination supports Instant Payouts + + // DeletedAt marks a soft-deleted user; no read returns it. + DeletedAt *time.Time `json:"-"` } // MaxStripeWithdrawalsByStatusLimit caps ListStripeWithdrawalsByStatus result @@ -775,6 +781,9 @@ type ProviderToken struct { Label string `json:"label"` // human-readable label (e.g. hostname) Active bool `json:"active"` CreatedAt time.Time `json:"created_at"` + + // DeletedAt marks a soft-deleted token; no read returns it. + DeletedAt *time.Time `json:"-"` } // InviteCode represents a coordinator-generated invite code that grants credits. @@ -890,6 +899,9 @@ type ProviderRecord struct { LastSessionStats json.RawMessage `json:"last_session_stats,omitempty"` RegisteredAt time.Time `json:"registered_at"` LastSeen time.Time `json:"last_seen"` + + // DeletedAt marks a soft-deleted provider record; no read returns it. + DeletedAt *time.Time `json:"-"` } // ProviderSession is one connect→disconnect lifecycle of a provider machine. diff --git a/coordinator/store/machine_inventory_backfill.go b/coordinator/store/machine_inventory_backfill.go index 6631c43b88..f9b39c85fb 100644 --- a/coordinator/store/machine_inventory_backfill.go +++ b/coordinator/store/machine_inventory_backfill.go @@ -20,7 +20,7 @@ func (s *PostgresStore) BackfillMachineInventory(ctx context.Context, limit int) } rows, err := s.pool.Query(ctx, `SELECT p.id,COALESCE(p.account_id,''),COALESCE(p.se_public_key,''),COALESCE(p.public_key,''),p.attestation_result,COALESCE(p.version,''),p.hardware,p.last_seen FROM providers p LEFT JOIN darkbloom_machine_sessions m ON m.session_id=p.id - WHERE m.session_id IS NULL AND p.last_seen < CURRENT_TIMESTAMP - interval '5 minutes' + WHERE m.session_id IS NULL AND p.deleted_at IS NULL AND p.last_seen < CURRENT_TIMESTAMP - interval '5 minutes' AND NOT EXISTS(SELECT 1 FROM provider_sessions ps WHERE ps.session_id=p.id AND ps.disconnected_at IS NULL) ORDER BY p.id LIMIT $1`, limit) if err != nil { diff --git a/coordinator/store/memory.go b/coordinator/store/memory.go index 46c4255919..66290c0d98 100644 --- a/coordinator/store/memory.go +++ b/coordinator/store/memory.go @@ -353,7 +353,7 @@ func (s *MemoryStore) CreateAPIKey(accountID string, opts APIKeyCreate) (string, func (s *MemoryStore) GetKeyAccount(key string) string { s.mu.RLock() defer s.mu.RUnlock() - if rec, ok := s.keyRecords[key]; ok { + if rec, ok := s.keyRecords[key]; ok && rec.DeletedAt == nil { return rec.OwnerAccountID } return "" @@ -364,7 +364,7 @@ func (s *MemoryStore) AuthenticateKey(rawKey string) (*APIKey, error) { s.mu.RLock() defer s.mu.RUnlock() rec, ok := s.keyRecords[rawKey] - if !ok { + if !ok || rec.DeletedAt != nil { return nil, fmt.Errorf("key not found") } if rec.Disabled { @@ -399,7 +399,7 @@ func (s *MemoryStore) ListAPIKeys(accountID string) ([]APIKey, error) { defer s.mu.RUnlock() out := make([]APIKey, 0) for _, rec := range s.keyRecords { - if rec.OwnerAccountID != accountID || rec.ID == "" { + if rec.OwnerAccountID != accountID || rec.ID == "" || rec.DeletedAt != nil { continue } out = append(out, *cloneAPIKey(rec)) @@ -417,7 +417,7 @@ func (s *MemoryStore) GetAPIKeyByID(accountID, id string) (*APIKey, error) { return nil, fmt.Errorf("key not found") } rec, ok := s.keyRecords[raw] - if !ok || rec.OwnerAccountID != accountID { + if !ok || rec.OwnerAccountID != accountID || rec.DeletedAt != nil { return nil, fmt.Errorf("key not found") } return cloneAPIKey(rec), nil @@ -432,7 +432,7 @@ func (s *MemoryStore) UpdateAPIKey(accountID, id string, mutable APIKey) (*APIKe return nil, fmt.Errorf("key not found") } rec, ok := s.keyRecords[raw] - if !ok || rec.OwnerAccountID != accountID { + if !ok || rec.OwnerAccountID != accountID || rec.DeletedAt != nil { return nil, fmt.Errorf("key not found") } rec.Name = mutable.Name @@ -482,7 +482,7 @@ func (s *MemoryStore) RotateAPIKey(accountID, id string) (string, *APIKey, error return "", nil, fmt.Errorf("key not found") } old, ok := s.keyRecords[oldRaw] - if !ok || old.OwnerAccountID != accountID { + if !ok || old.OwnerAccountID != accountID || old.DeletedAt != nil { return "", nil, fmt.Errorf("key not found") } rec := &APIKey{ @@ -1131,7 +1131,7 @@ func (s *MemoryStore) UsageFlowBuckets(since time.Time, providerLocs map[string] if loc, ok := providerLocs[providerID]; ok && loc != nil { return loc } - if rec, ok := s.providerRecords[providerID]; ok { + if rec, ok := s.providerRecords[providerID]; ok && rec.DeletedAt == nil { return rec.Location } return nil @@ -1950,7 +1950,9 @@ func (s *MemoryStore) CreateUser(user *User) error { s.mu.Lock() defer s.mu.Unlock() - if _, exists := s.usersByPrivyID[user.PrivyUserID]; exists { + // A soft-deleted user does not hold its Privy ID, as with the partial + // unique index in Postgres. + if existing, exists := s.usersByPrivyID[user.PrivyUserID]; exists && existing.DeletedAt == nil { return fmt.Errorf("user with Privy ID %q already exists", user.PrivyUserID) } if _, exists := s.usersByAccountID[user.AccountID]; exists { @@ -1970,7 +1972,7 @@ func (s *MemoryStore) GetUserByPrivyID(privyUserID string) (*User, error) { defer s.mu.RUnlock() u, ok := s.usersByPrivyID[privyUserID] - if !ok { + if !ok || u.DeletedAt != nil { return nil, fmt.Errorf("user with Privy ID %q %w", privyUserID, ErrNotFound) } copy := *u @@ -1983,7 +1985,7 @@ func (s *MemoryStore) GetUserByAccountID(accountID string) (*User, error) { defer s.mu.RUnlock() u, ok := s.usersByAccountID[accountID] - if !ok { + if !ok || u.DeletedAt != nil { return nil, fmt.Errorf("user with account ID %q %w", accountID, ErrNotFound) } copy := *u @@ -2035,7 +2037,7 @@ func (s *MemoryStore) GetUserByStripeAccount(stripeAccountID string) (*User, err defer s.mu.RUnlock() u, ok := s.usersByStripeAccountID[stripeAccountID] - if !ok { + if !ok || u.DeletedAt != nil { return nil, fmt.Errorf("user with Stripe account %q not found", stripeAccountID) } copy := *u @@ -2048,7 +2050,7 @@ func (s *MemoryStore) GetUserByEmail(email string) (*User, error) { defer s.mu.RUnlock() lower := strings.ToLower(email) for _, u := range s.usersByAccountID { - if strings.ToLower(u.Email) == lower { + if strings.ToLower(u.Email) == lower && u.DeletedAt == nil { copy := *u return ©, nil } @@ -2437,7 +2439,7 @@ func (s *MemoryStore) GetProviderToken(token string) (*ProviderToken, error) { h := hashKey(token) pt, ok := s.providerTokens[h] - if !ok { + if !ok || pt.DeletedAt != nil { return nil, errors.New("provider token not found") } if !pt.Active { @@ -2749,7 +2751,7 @@ func (s *MemoryStore) GetProviderRecord(_ context.Context, id string) (*Provider defer s.mu.RUnlock() p, ok := s.providerRecords[id] - if !ok { + if !ok || p.DeletedAt != nil { return nil, fmt.Errorf("provider %q not found", id) } cp := *p @@ -2772,7 +2774,7 @@ func (s *MemoryStore) GetMDAChainBySerial(_ context.Context, serial string) (jso // recently seen non-empty chain. var best *ProviderRecord for _, p := range s.providerRecords { - if p.SerialNumber != serial || len(p.MDACertChain) == 0 { + if p.SerialNumber != serial || len(p.MDACertChain) == 0 || p.DeletedAt != nil { continue } if best == nil || p.LastSeen.After(best.LastSeen) { @@ -2797,7 +2799,7 @@ func (s *MemoryStore) ListProvidersByAccount(_ context.Context, accountID string records := make([]ProviderRecord, 0) for _, p := range s.providerRecords { - if p.AccountID == accountID { + if p.AccountID == accountID && p.DeletedAt == nil { cp := *p if p.Location != nil { loc := *p.Location diff --git a/coordinator/store/memory_machine_continuity.go b/coordinator/store/memory_machine_continuity.go index dc680d481d..2d531325ae 100644 --- a/coordinator/store/memory_machine_continuity.go +++ b/coordinator/store/memory_machine_continuity.go @@ -34,7 +34,7 @@ func (s *MemoryStore) ResolveMachineContinuity(ctx context.Context, sessionID, a continue } p := s.providerRecords[priorID] - if p != nil && p.AccountID == account && newerProviderRecord(p, result.Previous) { + if p != nil && p.AccountID == account && p.DeletedAt == nil && newerProviderRecord(p, result.Previous) { result.Previous = p } } diff --git a/coordinator/store/migration_harness_test.go b/coordinator/store/migration_harness_test.go index bad7c0fbc6..fc1a4d7fde 100644 --- a/coordinator/store/migration_harness_test.go +++ b/coordinator/store/migration_harness_test.go @@ -77,13 +77,24 @@ func replayMigrations(t testing.TB, s *PostgresStore) { } } -// loadSchemaFile applies schema/schema.sql (the pg_dump of the pre-goose -// schema) to the database at pool. The session settings at the top of the -// dump are skipped: some name settings older servers do not have, and the -// empty search_path would stay on the pooled connection. -func loadSchemaFile(t testing.TB, pool *pgxpool.Pool) { +const ( + // checkedInSchemaFile is the pg_dump of the schema the migrations build. + checkedInSchemaFile = "schema/schema.sql" + // preGooseSchemaFile is the pg_dump of the schema the pre-goose boot + // loop built: the state of every database before its first goose run. + preGooseSchemaFile = "testdata/schema_pre_goose.sql" + // lastPreGooseVersion is the last version that only replays the + // pre-goose boot. + lastPreGooseVersion = 5 +) + +// loadSchemaFile applies a pg_dump schema file to the database at pool. The +// session settings at the top of the dump are skipped: some name settings +// older servers do not have, and the empty search_path would stay on the +// pooled connection. +func loadSchemaFile(t testing.TB, pool *pgxpool.Pool, path string) { t.Helper() - b, err := os.ReadFile(filepath.Join("schema", "schema.sql")) + b, err := os.ReadFile(filepath.FromSlash(path)) if err != nil { t.Fatalf("read schema file: %v", err) } diff --git a/coordinator/store/model_token_promotions_memory.go b/coordinator/store/model_token_promotions_memory.go index 159550b046..31e89680e0 100644 --- a/coordinator/store/model_token_promotions_memory.go +++ b/coordinator/store/model_token_promotions_memory.go @@ -39,7 +39,7 @@ func (s *MemoryStore) ClaimModelTokenPromotion(account, model string, now time.T s.mu.Lock() defer s.mu.Unlock() u := s.usersByAccountID[account] - if u == nil || u.PrivyUserID == "" || u.Role == RoleService { + if u == nil || u.DeletedAt != nil || u.PrivyUserID == "" || u.Role == RoleService { return nil, ErrPromotionIneligible } if _, exists := s.modelTokenGrants[account][model]; exists { diff --git a/coordinator/store/model_token_promotions_postgres.go b/coordinator/store/model_token_promotions_postgres.go index 65a8ff9edc..d3b8be4eef 100644 --- a/coordinator/store/model_token_promotions_postgres.go +++ b/coordinator/store/model_token_promotions_postgres.go @@ -60,7 +60,7 @@ func (s *PostgresStore) ClaimModelTokenPromotion(account, model string, now time return nil, err } var user User - err = tx.QueryRow(ctx, `SELECT account_id,privy_user_id,role,created_at FROM users WHERE account_id=$1`, account).Scan(&user.AccountID, &user.PrivyUserID, &user.Role, &user.CreatedAt) + err = tx.QueryRow(ctx, `SELECT account_id,privy_user_id,role,created_at FROM users WHERE account_id=$1 AND deleted_at IS NULL`, account).Scan(&user.AccountID, &user.PrivyUserID, &user.Role, &user.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrPromotionIneligible } diff --git a/coordinator/store/postgres.go b/coordinator/store/postgres.go index a8c95b3151..663df1bb9e 100644 --- a/coordinator/store/postgres.go +++ b/coordinator/store/postgres.go @@ -1247,7 +1247,7 @@ func (s *PostgresStore) GetUserByPrivyID(privyUserID string) (*User, error) { defer cancel() row := s.pool.QueryRow(ctx, - `SELECT `+userSelectColumns+` FROM users WHERE privy_user_id = $1`, privyUserID, + `SELECT `+userSelectColumns+` FROM users WHERE privy_user_id = $1 AND deleted_at IS NULL`, privyUserID, ) u, err := scanUser(row) if err != nil { @@ -1262,7 +1262,7 @@ func (s *PostgresStore) GetUserByAccountID(accountID string) (*User, error) { defer cancel() row := s.pool.QueryRow(ctx, - `SELECT `+userSelectColumns+` FROM users WHERE account_id = $1`, accountID, + `SELECT `+userSelectColumns+` FROM users WHERE account_id = $1 AND deleted_at IS NULL`, accountID, ) u, err := scanUser(row) if err != nil { @@ -1316,7 +1316,7 @@ func (s *PostgresStore) GetUserByStripeAccount(stripeAccountID string) (*User, e defer cancel() row := s.pool.QueryRow(ctx, - `SELECT `+userSelectColumns+` FROM users WHERE stripe_account_id = $1`, stripeAccountID, + `SELECT `+userSelectColumns+` FROM users WHERE stripe_account_id = $1 AND deleted_at IS NULL`, stripeAccountID, ) u, err := scanUser(row) if err != nil { @@ -1368,7 +1368,7 @@ func (s *PostgresStore) GetUserByEmail(email string) (*User, error) { defer cancel() row := s.pool.QueryRow(ctx, - `SELECT `+userSelectColumns+` FROM users WHERE LOWER(email) = LOWER($1)`, email, + `SELECT `+userSelectColumns+` FROM users WHERE LOWER(email) = LOWER($1) AND deleted_at IS NULL`, email, ) u, err := scanUser(row) if err != nil { @@ -1915,7 +1915,7 @@ func (s *PostgresStore) GetProviderToken(token string) (*ProviderToken, error) { var pt ProviderToken err := s.pool.QueryRow(ctx, `SELECT token_hash, account_id, label, active, created_at - FROM provider_tokens WHERE token_hash = $1 AND active = TRUE`, h, + FROM provider_tokens WHERE token_hash = $1 AND active = TRUE AND deleted_at IS NULL`, h, ).Scan(&pt.TokenHash, &pt.AccountID, &pt.Label, &pt.Active, &pt.CreatedAt) if err != nil { return nil, fmt.Errorf("store: provider token not found: %w", err) @@ -2275,6 +2275,7 @@ func (s *PostgresStore) GetMDAChainBySerial(ctx context.Context, serial string) err := s.pool.QueryRow(ctx, `SELECT mda_cert_chain FROM providers WHERE serial_number = $1 AND serial_number != '' AND mda_cert_chain IS NOT NULL + AND deleted_at IS NULL ORDER BY last_seen DESC LIMIT 1`, serial, ).Scan(&chain) if err != nil { @@ -2314,7 +2315,7 @@ func (s *PostgresStore) ListProvidersByAccount(ctx context.Context, accountID st lifetime_stats, last_session_stats, registered_at, last_seen, public_key FROM providers - WHERE account_id = $1 + WHERE account_id = $1 AND deleted_at IS NULL ORDER BY COALESCE(NULLIF(serial_number, ''), NULLIF(se_public_key, ''), id), diff --git a/coordinator/store/postgres_analytics_flows.go b/coordinator/store/postgres_analytics_flows.go index 4e04e84cc3..fe9cbcf4ba 100644 --- a/coordinator/store/postgres_analytics_flows.go +++ b/coordinator/store/postgres_analytics_flows.go @@ -56,7 +56,7 @@ SELECT u.city AS c_city, FROM located_usage u JOIN LATERAL ( SELECT location FROM providers - WHERE id = u.provider_id AND location IS NOT NULL + WHERE id = u.provider_id AND location IS NOT NULL AND deleted_at IS NULL OFFSET 0 ) p ON true GROUP BY u.city, u.region, u.region_code, u.country, u.country_code, diff --git a/coordinator/store/postgres_machine_continuity.go b/coordinator/store/postgres_machine_continuity.go index f299be12db..75276041c6 100644 --- a/coordinator/store/postgres_machine_continuity.go +++ b/coordinator/store/postgres_machine_continuity.go @@ -43,7 +43,7 @@ func (s *PostgresStore) ResolveMachineContinuity(ctx context.Context, sessionID, // Never restore through serial or SE claims, and never cross account history // even when an Apple-verified MDA serial associates two account-scoped aliases. result.Previous, err = scanProviderRecord(tx.QueryRow(ctx, `SELECT `+providerRecordColumns+` - FROM providers WHERE account_id=$2 AND id<>$3 AND id<>ALL($4::text[]) + FROM providers WHERE account_id=$2 AND id<>$3 AND id<>ALL($4::text[]) AND deleted_at IS NULL AND id IN (SELECT session_id FROM darkbloom_machine_sessions WHERE machine_id=$1 AND account_id=$2) ORDER BY last_seen DESC,id DESC LIMIT 1`, result.Machine.ID, account, sessionID, excluded)) if errors.Is(err, pgx.ErrNoRows) { diff --git a/coordinator/store/postgres_migrations_test.go b/coordinator/store/postgres_migrations_test.go index c168ee408e..ed612ab65d 100644 --- a/coordinator/store/postgres_migrations_test.go +++ b/coordinator/store/postgres_migrations_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/stdlib" "github.com/pressly/goose/v3" ) @@ -25,19 +26,20 @@ func TestMigrationsBuildCheckedInSchema(t *testing.T) { t.Cleanup(s.Close) dumpPool := openTestPool(t, newThrowawayTestDatabase(t)) - loadSchemaFile(t, dumpPool) + loadSchemaFile(t, dumpPool, checkedInSchemaFile) assertSameSchema(t, "schema/schema.sql", schemaSnapshot(t, dumpPool), "goose", schemaSnapshot(t, s.pool)) } // A database that a pre-goose binary migrated meets goose for the first -// time: every migration runs, and nothing changes except the new goose -// version table. -func TestMigrationsLeaveLegacyDatabaseUnchanged(t *testing.T) { +// time. The baseline and the Go steps (versions 1 to 5) change nothing +// except the new goose version table; the later versions then bring it to +// the checked-in schema. +func TestMigrationsUpgradeLegacyDatabase(t *testing.T) { ctx := context.Background() databaseURL := newThrowawayTestDatabase(t) pool := openTestPool(t, databaseURL) - loadSchemaFile(t, pool) + loadSchemaFile(t, pool, preGooseSchemaFile) // The rows the pre-goose boot leaves on a fresh database. for _, stmt := range []string{ `INSERT INTO schema_migrations (id, applied_at) VALUES @@ -75,13 +77,25 @@ func TestMigrationsLeaveLegacyDatabaseUnchanged(t *testing.T) { } schemaBefore, rowsBefore := schemaSnapshot(t, pool), readRows() - s, err := NewPostgres(ctx, Config{DatabaseURL: databaseURL}) + s := &PostgresStore{pool: pool} + db := stdlib.OpenDBFromPool(pool) + t.Cleanup(func() { _ = db.Close() }) + provider, err := s.newMigrationProvider(db) if err != nil { - t.Fatalf("NewPostgres on legacy database: %v", err) + t.Fatal(err) } - t.Cleanup(s.Close) + if _, err := provider.UpTo(ctx, lastPreGooseVersion); err != nil { + t.Fatalf("apply versions up to %d on legacy database: %v", lastPreGooseVersion, err) + } + assertSameSchema(t, "legacy", schemaBefore, "after the baseline", schemaSnapshot(t, pool)) + assertSameSchema(t, "legacy rows", rowsBefore, "rows after the baseline", readRows()) - assertSameSchema(t, "legacy", schemaBefore, "after goose", schemaSnapshot(t, pool)) + if err := s.migrate(ctx); err != nil { + t.Fatalf("migrate legacy database: %v", err) + } + dumpPool := openTestPool(t, newThrowawayTestDatabase(t)) + loadSchemaFile(t, dumpPool, checkedInSchemaFile) + assertSameSchema(t, "schema/schema.sql", schemaSnapshot(t, dumpPool), "upgraded legacy", schemaSnapshot(t, pool)) assertSameSchema(t, "legacy rows", rowsBefore, "rows after goose", readRows()) var versions []int64 rows, err := pool.Query(ctx, `SELECT version_id FROM `+migrationVersionTable+` ORDER BY id`) @@ -96,8 +110,9 @@ func TestMigrationsLeaveLegacyDatabaseUnchanged(t *testing.T) { } versions = append(versions, v) } - if len(versions) != 6 || versions[0] != 0 || versions[5] != 5 { - t.Fatalf("goose versions = %v, want 0 through 5", versions) + want := len(provider.ListSources()) + if len(versions) != want+1 || versions[0] != 0 || versions[want] != int64(want) { + t.Fatalf("goose versions = %v, want 0 through %d", versions, want) } } @@ -135,16 +150,17 @@ func TestConcurrentMigrationsApplyOnce(t *testing.T) { t.Fatalf("runner %d: %v", i, err) } } - if applied[0]+applied[1] != 5 || (applied[0] != 0 && applied[1] != 0) { - t.Fatalf("applied = %v, want one runner to apply all 5 versions and the other none", applied) + want := len(runners[0].ListSources()) + if applied[0]+applied[1] != want || (applied[0] != 0 && applied[1] != 0) { + t.Fatalf("applied = %v, want one runner to apply all %d versions and the other none", applied, want) } var rows, distinct int pool := openTestPool(t, databaseURL) if err := pool.QueryRow(ctx, `SELECT count(*), count(DISTINCT version_id) FROM `+migrationVersionTable).Scan(&rows, &distinct); err != nil { t.Fatal(err) } - if rows != 6 || distinct != 6 { - t.Fatalf("goose version rows = %d (%d distinct), want 6", rows, distinct) + if rows != want+1 || distinct != want+1 { + t.Fatalf("goose version rows = %d (%d distinct), want %d", rows, distinct, want+1) } } @@ -184,3 +200,49 @@ func TestMigrateRetriesLockTimeout(t *testing.T) { t.Fatalf("migrate did not retry after a lock timeout; logs:\n%s", logs.String()) } } + +// A CREATE INDEX CONCURRENTLY waits for every older snapshot. A query that +// runs longer than the 3 s session lock_timeout must not cancel it: the +// CONCURRENTLY migrations wait up to a minute, and apply on the first attempt. +func TestConcurrentIndexMigrationWaitsForOlderSnapshot(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + s, err := NewPostgres(ctx, Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + // Make version 6 pending again. + if _, err := s.pool.Exec(ctx, `DROP INDEX idx_provider_sessions_account`); err != nil { + t.Fatal(err) + } + if _, err := s.pool.Exec(ctx, `DELETE FROM `+migrationVersionTable+` WHERE version_id >= 6`); err != nil { + t.Fatal(err) + } + + holder := openTestPool(t, databaseURL) + tx, err := holder.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead}) + if err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `SELECT count(*) FROM users`); err != nil { + t.Fatal(err) + } + release := time.AfterFunc(2*migrationLockTimeout, func() { _ = tx.Rollback(context.Background()) }) + defer release.Stop() + + var logs bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + defer slog.SetDefault(previous) + if err := s.migrate(ctx); err != nil { + t.Fatalf("migrate behind an older snapshot: %v", err) + } + if strings.Contains(logs.String(), "retrying") { + t.Fatalf("the index build hit the session lock_timeout; logs:\n%s", logs.String()) + } + var valid bool + if err := s.pool.QueryRow(ctx, `SELECT indisvalid FROM pg_index WHERE indexrelid = 'idx_provider_sessions_account'::regclass`).Scan(&valid); err != nil || !valid { + t.Fatalf("idx_provider_sessions_account valid=%v err=%v", valid, err) + } +} diff --git a/coordinator/store/postgres_provider_read.go b/coordinator/store/postgres_provider_read.go index 0e01f7e3ca..86a7270600 100644 --- a/coordinator/store/postgres_provider_read.go +++ b/coordinator/store/postgres_provider_read.go @@ -43,7 +43,7 @@ func scanProviderRecord(row rowScanner) (*ProviderRecord, error) { func (s *PostgresStore) GetProviderRecord(ctx context.Context, id string) (*ProviderRecord, error) { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() - p, err := scanProviderRecord(s.pool.QueryRow(ctx, `SELECT `+providerRecordColumns+` FROM providers WHERE id = $1`, id)) + p, err := scanProviderRecord(s.pool.QueryRow(ctx, `SELECT `+providerRecordColumns+` FROM providers WHERE id = $1 AND deleted_at IS NULL`, id)) if err != nil { return nil, fmt.Errorf("store: provider not found: %w", err) } diff --git a/coordinator/store/provider_restore.go b/coordinator/store/provider_restore.go index 84d94f6bfa..e9376e9c01 100644 --- a/coordinator/store/provider_restore.go +++ b/coordinator/store/provider_restore.go @@ -27,6 +27,7 @@ func (s *PostgresStore) GetProviderForRestore(ctx context.Context, serial, seKey // column comes exclusively from the fixed literals above, never a caller. p, err := scanProviderRecord(s.pool.QueryRow(ctx, `SELECT `+providerRecordColumns+` FROM providers WHERE `+identity.column+` = $1 AND `+identity.column+` <> '' AND id <> ALL($2::text[]) + AND deleted_at IS NULL ORDER BY last_seen DESC, id DESC LIMIT 1`, identity.value, excludeIDs)) if errors.Is(err, pgx.ErrNoRows) { continue @@ -47,7 +48,7 @@ func (s *MemoryStore) GetProviderForRestore(ctx context.Context, serial, seKey s defer s.mu.RUnlock() var serialMatch, keyMatch *ProviderRecord for _, p := range s.providerRecords { - if slices.Contains(excludeIDs, p.ID) { + if slices.Contains(excludeIDs, p.ID) || p.DeletedAt != nil { continue } if serial != "" && p.SerialNumber == serial && newerProviderRecord(p, serialMatch) { diff --git a/coordinator/store/queries/api_keys.sql b/coordinator/store/queries/api_keys.sql index 6592dd6b9b..657cd2bcc6 100644 --- a/coordinator/store/queries/api_keys.sql +++ b/coordinator/store/queries/api_keys.sql @@ -14,26 +14,26 @@ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) ON CONFLICT (key_hash) DO NOTHING; -- name: GetActiveKeyAccount :one -SELECT owner_account_id FROM api_keys WHERE key_hash = $1 AND active = TRUE; +SELECT owner_account_id FROM api_keys WHERE key_hash = $1 AND active = TRUE AND deleted_at IS NULL; -- name: GetAPIKeyByHash :one -SELECT * FROM api_keys WHERE key_hash = $1; +SELECT * FROM api_keys WHERE key_hash = $1 AND deleted_at IS NULL; -- name: ListAPIKeysByOwner :many -SELECT * FROM api_keys WHERE owner_account_id = $1 AND id <> '' ORDER BY created_at DESC; +SELECT * FROM api_keys WHERE owner_account_id = $1 AND id <> '' AND deleted_at IS NULL ORDER BY created_at DESC; -- name: GetAPIKeyByID :one -SELECT * FROM api_keys WHERE id = $1 AND owner_account_id = $2; +SELECT * FROM api_keys WHERE id = $1 AND owner_account_id = $2 AND deleted_at IS NULL; -- name: GetAPIKeyByIDForUpdate :one -SELECT * FROM api_keys WHERE id = $1 AND owner_account_id = $2 FOR UPDATE; +SELECT * FROM api_keys WHERE id = $1 AND owner_account_id = $2 AND deleted_at IS NULL FOR UPDATE; -- name: UpdateAPIKey :execrows UPDATE api_keys SET name = $1, active = $2, limit_micro_usd = $3, limit_reset = $4, rpm_limit = $5, itpm_limit = $6, otpm_limit = $7, allowed_models = $8, expires_at = $9, self_route_only = $10 -WHERE id = $11 AND owner_account_id = $12; +WHERE id = $11 AND owner_account_id = $12 AND deleted_at IS NULL; -- name: DeleteAPIKeyByID :execrows DELETE FROM api_keys WHERE id = $1 AND owner_account_id = $2; diff --git a/coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql b/coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql new file mode 100644 index 0000000000..70fab1beba --- /dev/null +++ b/coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql @@ -0,0 +1,12 @@ +-- Account erasure finds rows by provider_sessions.account_id. +-- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it +-- before the next attempt. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_provider_sessions_account; +CREATE INDEX CONCURRENTLY idx_provider_sessions_account ON provider_sessions (account_id); +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql b/coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql new file mode 100644 index 0000000000..70cc88dd3b --- /dev/null +++ b/coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql @@ -0,0 +1,12 @@ +-- Account erasure finds rows by provider_log_reports.account_id. +-- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it +-- before the next attempt. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_provider_log_reports_account; +CREATE INDEX CONCURRENTLY idx_provider_log_reports_account ON provider_log_reports (account_id); +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00008_device_codes_account_index.sql b/coordinator/store/schema/migrations/00008_device_codes_account_index.sql new file mode 100644 index 0000000000..9d7bff4e18 --- /dev/null +++ b/coordinator/store/schema/migrations/00008_device_codes_account_index.sql @@ -0,0 +1,12 @@ +-- Account erasure finds rows by device_codes.account_id. +-- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it +-- before the next attempt. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_device_codes_account; +CREATE INDEX CONCURRENTLY idx_device_codes_account ON device_codes (account_id); +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql b/coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql new file mode 100644 index 0000000000..5cf6340c5c --- /dev/null +++ b/coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql @@ -0,0 +1,12 @@ +-- Account erasure finds rows by darkbloom_machine_sessions.account_id. +-- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it +-- before the next attempt. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_darkbloom_machine_sessions_account; +CREATE INDEX CONCURRENTLY idx_darkbloom_machine_sessions_account ON darkbloom_machine_sessions (account_id); +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql b/coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql new file mode 100644 index 0000000000..a73216903a --- /dev/null +++ b/coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql @@ -0,0 +1,12 @@ +-- Account erasure finds rows by model_token_reservations.account_id. +-- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it +-- before the next attempt. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_model_token_reservations_account; +CREATE INDEX CONCURRENTLY idx_model_token_reservations_account ON model_token_reservations (account_id); +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql b/coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql new file mode 100644 index 0000000000..1f10a10ac2 --- /dev/null +++ b/coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql @@ -0,0 +1,12 @@ +-- Account erasure finds rows by inference_routes.consumer_key_hash. +-- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it +-- before the next attempt. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_inference_routes_consumer_key_hash; +CREATE INDEX CONCURRENTLY idx_inference_routes_consumer_key_hash ON inference_routes (consumer_key_hash); +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql b/coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql new file mode 100644 index 0000000000..cde62cf8d3 --- /dev/null +++ b/coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql @@ -0,0 +1,12 @@ +-- Account erasure finds rows by request_rejections.consumer_key_hash. +-- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it +-- before the next attempt. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_request_rejections_consumer_key_hash; +CREATE INDEX CONCURRENTLY idx_request_rejections_consumer_key_hash ON request_rejections (consumer_key_hash); +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00013_soft_delete_columns.sql b/coordinator/store/schema/migrations/00013_soft_delete_columns.sql new file mode 100644 index 0000000000..2fe4e20f52 --- /dev/null +++ b/coordinator/store/schema/migrations/00013_soft_delete_columns.sql @@ -0,0 +1,10 @@ +-- Soft delete: a row with deleted_at set belongs to an erased account and is +-- hidden from every live read. Each ALTER commits on its own, so only one +-- table lock is held at a time. A nullable column with no default changes +-- only the catalog. +-- +goose NO TRANSACTION +-- +goose Up +ALTER TABLE users ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; +ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; +ALTER TABLE providers ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; +ALTER TABLE provider_tokens ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; diff --git a/coordinator/store/schema/migrations/00014_users_privy_live_index.sql b/coordinator/store/schema/migrations/00014_users_privy_live_index.sql new file mode 100644 index 0000000000..10f3b1fe30 --- /dev/null +++ b/coordinator/store/schema/migrations/00014_users_privy_live_index.sql @@ -0,0 +1,12 @@ +-- A Privy user ID is unique among live users only, so the same person can +-- sign up again after an erased account. Versions 15 and 16 drop the old +-- full-table unique constraint and index. +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_users_privy_live; +CREATE UNIQUE INDEX CONCURRENTLY idx_users_privy_live ON users (privy_user_id) WHERE deleted_at IS NULL; +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00015_users_privy_drop_unique_constraint.sql b/coordinator/store/schema/migrations/00015_users_privy_drop_unique_constraint.sql new file mode 100644 index 0000000000..2bf77aee1d --- /dev/null +++ b/coordinator/store/schema/migrations/00015_users_privy_drop_unique_constraint.sql @@ -0,0 +1,2 @@ +-- +goose Up +ALTER TABLE users DROP CONSTRAINT IF EXISTS users_privy_user_id_key; diff --git a/coordinator/store/schema/migrations/00016_users_privy_drop_old_index.sql b/coordinator/store/schema/migrations/00016_users_privy_drop_old_index.sql new file mode 100644 index 0000000000..a3ed49875c --- /dev/null +++ b/coordinator/store/schema/migrations/00016_users_privy_drop_old_index.sql @@ -0,0 +1,8 @@ +-- A CONCURRENTLY statement blocks no reads or writes, but it waits for every +-- older snapshot in the database; the 3 s session lock_timeout would cancel it +-- behind any query that runs longer. It waits up to 1 min instead. +-- +goose NO TRANSACTION +-- +goose Up +SET lock_timeout = '1min'; +DROP INDEX CONCURRENTLY IF EXISTS idx_users_privy; +RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00017_referrals_referrer_code_cascade.sql b/coordinator/store/schema/migrations/00017_referrals_referrer_code_cascade.sql new file mode 100644 index 0000000000..faacd6963e --- /dev/null +++ b/coordinator/store/schema/migrations/00017_referrals_referrer_code_cascade.sql @@ -0,0 +1,11 @@ +-- Let a referrer code change propagate to referrals. The new foreign key is +-- added NOT VALID (a short lock), validated without blocking writes, and then +-- replaces the old one. Each statement commits on its own; the first one +-- removes a key left by an interrupted earlier attempt. +-- +goose NO TRANSACTION +-- +goose Up +ALTER TABLE referrals DROP CONSTRAINT IF EXISTS referrals_referrer_code_cascade_fkey; +ALTER TABLE referrals ADD CONSTRAINT referrals_referrer_code_cascade_fkey + FOREIGN KEY (referrer_code) REFERENCES referrers (code) ON UPDATE CASCADE NOT VALID; +ALTER TABLE referrals VALIDATE CONSTRAINT referrals_referrer_code_cascade_fkey; +ALTER TABLE referrals DROP CONSTRAINT IF EXISTS referrals_referrer_code_fkey; diff --git a/coordinator/store/schema/schema.sql b/coordinator/store/schema/schema.sql index 80eb7b281f..5299eec5c3 100644 --- a/coordinator/store/schema/schema.sql +++ b/coordinator/store/schema/schema.sql @@ -101,7 +101,8 @@ CREATE TABLE public.api_keys ( allowed_models text DEFAULT ''::text NOT NULL, expires_at timestamp with time zone, last_used_at timestamp with time zone, - self_route_only boolean DEFAULT false NOT NULL + self_route_only boolean DEFAULT false NOT NULL, + deleted_at timestamp with time zone ); @@ -1277,7 +1278,8 @@ CREATE TABLE public.provider_tokens ( account_id text NOT NULL, label text DEFAULT ''::text NOT NULL, active boolean DEFAULT true NOT NULL, - created_at timestamp with time zone DEFAULT now() NOT NULL + created_at timestamp with time zone DEFAULT now() NOT NULL, + deleted_at timestamp with time zone ); @@ -1359,7 +1361,8 @@ CREATE TABLE public.providers ( last_session_requests_served bigint DEFAULT 0 NOT NULL, last_session_tokens_generated bigint DEFAULT 0 NOT NULL, lifetime_stats jsonb DEFAULT '{}'::jsonb NOT NULL, - last_session_stats jsonb DEFAULT '{}'::jsonb NOT NULL + last_session_stats jsonb DEFAULT '{}'::jsonb NOT NULL, + deleted_at timestamp with time zone ); @@ -1792,7 +1795,8 @@ CREATE TABLE public.users ( stripe_account_country text DEFAULT ''::text NOT NULL, stripe_destination_type text DEFAULT ''::text NOT NULL, stripe_destination_last4 text DEFAULT ''::text NOT NULL, - stripe_instant_eligible boolean DEFAULT false NOT NULL + stripe_instant_eligible boolean DEFAULT false NOT NULL, + deleted_at timestamp with time zone ); @@ -2556,14 +2560,6 @@ ALTER TABLE ONLY public.users ADD CONSTRAINT users_pkey PRIMARY KEY (account_id); --- --- Name: users users_privy_user_id_key; Type: CONSTRAINT; Schema: public; Owner: - --- - -ALTER TABLE ONLY public.users - ADD CONSTRAINT users_privy_user_id_key UNIQUE (privy_user_id); - - -- -- Name: app_attest_evidence_key; Type: INDEX; Schema: public; Owner: - -- @@ -2746,6 +2742,20 @@ CREATE INDEX idx_cache_routing_holders_updated ON public.cache_routing_holders U CREATE INDEX idx_code_attest_push_budgets_due ON public.code_attest_push_budgets USING btree (next_push_at); +-- +-- Name: idx_darkbloom_machine_sessions_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_darkbloom_machine_sessions_account ON public.darkbloom_machine_sessions USING btree (account_id); + + +-- +-- Name: idx_device_codes_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_device_codes_account ON public.device_codes USING btree (account_id); + + -- -- Name: idx_device_codes_user; Type: INDEX; Schema: public; Owner: - -- @@ -2781,6 +2791,13 @@ CREATE INDEX idx_floor_draws_account ON public.provider_floor_draws USING btree CREATE INDEX idx_floor_draws_epoch ON public.provider_floor_draws USING btree (epoch_id); +-- +-- Name: idx_inference_routes_consumer_key_hash; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_consumer_key_hash ON public.inference_routes USING btree (consumer_key_hash); + + -- -- Name: idx_inference_routes_created; Type: INDEX; Schema: public; Owner: - -- @@ -2837,6 +2854,13 @@ CREATE INDEX idx_model_demand_received ON public.model_demand_requests USING btr CREATE INDEX idx_model_registry_status ON public.model_registry USING btree (status); +-- +-- Name: idx_model_token_reservations_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_token_reservations_account ON public.model_token_reservations USING btree (account_id); + + -- -- Name: idx_model_token_reservations_open; Type: INDEX; Schema: public; Owner: - -- @@ -2886,6 +2910,13 @@ CREATE UNIQUE INDEX idx_provider_earnings_job ON public.provider_earnings USING CREATE INDEX idx_provider_earnings_provider ON public.provider_earnings USING btree (provider_key, created_at DESC); +-- +-- Name: idx_provider_log_reports_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_log_reports_account ON public.provider_log_reports USING btree (account_id); + + -- -- Name: idx_provider_payouts_address; Type: INDEX; Schema: public; Owner: - -- @@ -2900,6 +2931,13 @@ CREATE INDEX idx_provider_payouts_address ON public.provider_payouts USING btree CREATE INDEX idx_provider_payouts_settled ON public.provider_payouts USING btree (settled, created_at DESC); +-- +-- Name: idx_provider_sessions_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_account ON public.provider_sessions USING btree (account_id); + + -- -- Name: idx_provider_sessions_connected; Type: INDEX; Schema: public; Owner: - -- @@ -3026,6 +3064,13 @@ CREATE INDEX idx_request_profiles_created ON public.request_profiles USING btree CREATE INDEX idx_request_profiles_provider ON public.request_profiles USING btree (provider_id, created_at DESC); +-- +-- Name: idx_request_rejections_consumer_key_hash; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_consumer_key_hash ON public.request_rejections USING btree (consumer_key_hash); + + -- -- Name: idx_request_rejections_created; Type: INDEX; Schema: public; Owner: - -- @@ -3139,10 +3184,10 @@ CREATE INDEX idx_usage_request_location_notnull ON public.usage USING btree (cre -- --- Name: idx_users_privy; Type: INDEX; Schema: public; Owner: - +-- Name: idx_users_privy_live; Type: INDEX; Schema: public; Owner: - -- -CREATE UNIQUE INDEX idx_users_privy ON public.users USING btree (privy_user_id); +CREATE UNIQUE INDEX idx_users_privy_live ON public.users USING btree (privy_user_id) WHERE (deleted_at IS NULL); -- @@ -3326,11 +3371,11 @@ ALTER TABLE ONLY public.provider_reputation -- --- Name: referrals referrals_referrer_code_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- Name: referrals referrals_referrer_code_cascade_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - -- ALTER TABLE ONLY public.referrals - ADD CONSTRAINT referrals_referrer_code_fkey FOREIGN KEY (referrer_code) REFERENCES public.referrers(code); + ADD CONSTRAINT referrals_referrer_code_cascade_fkey FOREIGN KEY (referrer_code) REFERENCES public.referrers(code) ON UPDATE CASCADE; -- diff --git a/coordinator/store/soft_delete_reads_test.go b/coordinator/store/soft_delete_reads_test.go new file mode 100644 index 0000000000..7685cc696b --- /dev/null +++ b/coordinator/store/soft_delete_reads_test.go @@ -0,0 +1,284 @@ +package store + +import ( + "context" + "errors" + "testing" + "time" +) + +// No writer sets deleted_at yet; account erasure will. These tests set it +// the way that writer will (deleted_at only, nothing else changed) and prove +// that every live read hides the row, on both stores. + +// softDelete marks one row of table deleted. key matches account_id for +// users, id for api_keys and providers, and token_hash for provider_tokens. +func softDelete(t *testing.T, s Store, table, key string) { + t.Helper() + now := time.Now().UTC() + switch st := s.(type) { + case *PostgresStore: + column := map[string]string{"users": "account_id", "api_keys": "id", "providers": "id", "provider_tokens": "token_hash"}[table] + tag, err := st.pool.Exec(context.Background(), + `UPDATE `+table+` SET deleted_at = NOW() WHERE `+column+` = $1`, key) + if err != nil || tag.RowsAffected() != 1 { + t.Fatalf("soft-delete %s %s: %d rows, %v", table, key, tag.RowsAffected(), err) + } + case *MemoryStore: + st.mu.Lock() + defer st.mu.Unlock() + switch table { + case "users": + st.usersByAccountID[key].DeletedAt = &now + case "api_keys": + st.keyRecords[st.keysByID[key]].DeletedAt = &now + case "providers": + st.providerRecords[key].DeletedAt = &now + case "provider_tokens": + st.providerTokens[key].DeletedAt = &now + default: + t.Fatalf("unknown table %s", table) + } + default: + t.Fatalf("unsupported store %T", s) + } +} + +func TestSoftDeletedUserIsHidden(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + account := uniqueID("acct-gone") + privy := uniqueID("did:privy:gone") + email := uniqueID("gone") + "@example.com" + stripe := uniqueID("acct_stripe") + if err := s.CreateUser(&User{AccountID: account, PrivyUserID: privy, Email: email}); err != nil { + t.Fatal(err) + } + if err := s.SetUserStripeAccount(account, stripe, "ready", "US", "bank", "1234", false); err != nil { + t.Fatal(err) + } + promotions, _ := As[ModelTokenPromotionStore](s) + now := time.Now().UTC().Truncate(time.Second) + model := uniqueID("promo/model") + if err := promotions.PutModelTokenPromotion(ModelTokenPromotion{ModelID: model, Tokens: 10, ClaimStartsAt: now.Add(-time.Hour), ClaimEndsAt: promotionClaimEnd(now.Add(time.Hour)), SignupCutoffAt: now.Add(time.Hour), MaxClaims: 10, Enabled: true}); err != nil { + t.Fatal(err) + } + + softDelete(t, s, "users", account) + + if _, err := s.GetUserByAccountID(account); !errors.Is(err, ErrNotFound) { + t.Fatalf("GetUserByAccountID: %v, want ErrNotFound", err) + } + if _, err := s.GetUserByPrivyID(privy); !errors.Is(err, ErrNotFound) { + t.Fatalf("GetUserByPrivyID: %v, want ErrNotFound", err) + } + if u, err := s.GetUserByStripeAccount(stripe); err == nil { + t.Fatalf("GetUserByStripeAccount returned %+v", u) + } + if u, err := s.GetUserByEmail(email); err == nil { + t.Fatalf("GetUserByEmail returned %+v", u) + } + if _, err := promotions.ClaimModelTokenPromotion(account, model, now); !errors.Is(err, ErrPromotionIneligible) { + t.Fatalf("ClaimModelTokenPromotion: %v, want ErrPromotionIneligible", err) + } + + // The Privy ID is free again for a new live account, and only one + // live account may hold it. + again := uniqueID("acct-again") + if err := s.CreateUser(&User{AccountID: again, PrivyUserID: privy}); err != nil { + t.Fatalf("re-signup with the Privy ID of a deleted user: %v", err) + } + if u, err := s.GetUserByPrivyID(privy); err != nil || u.AccountID != again { + t.Fatalf("GetUserByPrivyID after re-signup = %+v, %v", u, err) + } + if err := s.CreateUser(&User{AccountID: uniqueID("acct-dup"), PrivyUserID: privy}); err == nil { + t.Fatal("two live users hold the same Privy ID") + } + }) + } +} + +func TestSoftDeletedAPIKeyIsHidden(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + account := uniqueID("acct-keys") + raw, gone, err := s.CreateAPIKey(account, APIKeyCreate{Name: "gone"}) + if err != nil { + t.Fatal(err) + } + _, live, err := s.CreateAPIKey(account, APIKeyCreate{Name: "live"}) + if err != nil { + t.Fatal(err) + } + + softDelete(t, s, "api_keys", gone.ID) + + if got := s.GetKeyAccount(raw); got != "" { + t.Fatalf("GetKeyAccount = %q, want empty", got) + } + if k, err := s.AuthenticateKey(raw); err == nil { + t.Fatalf("AuthenticateKey returned %+v", k) + } + if k, err := s.GetAPIKeyByID(account, gone.ID); err == nil { + t.Fatalf("GetAPIKeyByID returned %+v", k) + } + if k, err := s.UpdateAPIKey(account, gone.ID, *gone); err == nil { + t.Fatalf("UpdateAPIKey returned %+v", k) + } + if _, k, err := s.RotateAPIKey(account, gone.ID); err == nil { + t.Fatalf("RotateAPIKey returned %+v", k) + } + keys, err := s.ListAPIKeys(account) + if err != nil || len(keys) != 1 || keys[0].ID != live.ID { + t.Fatalf("ListAPIKeys = %+v, %v; want only the live key", keys, err) + } + }) + } +} + +func TestSoftDeletedProviderTokenIsHidden(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + raw := uniqueID("provider-token") + if err := s.CreateProviderToken(&ProviderToken{TokenHash: hashKey(raw), AccountID: uniqueID("acct"), Label: "mac", Active: true}); err != nil { + t.Fatal(err) + } + if _, err := s.GetProviderToken(raw); err != nil { + t.Fatalf("GetProviderToken before delete: %v", err) + } + softDelete(t, s, "provider_tokens", hashKey(raw)) + if pt, err := s.GetProviderToken(raw); err == nil { + t.Fatalf("GetProviderToken returned %+v", pt) + } + }) + } +} + +func TestSoftDeletedProviderIsHidden(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Microsecond) + account := uniqueID("acct-providers") + serial := uniqueID("serial") + seKey := uniqueID("se") + location := &ProviderLocation{City: "Gone City", Region: "Region", RegionCode: "R", Country: "Country", CountryCode: "CC"} + live := ProviderRecord{ID: uniqueID("live"), AccountID: account, SerialNumber: serial, SEPublicKey: seKey, + MDACertChain: []byte(`["live"]`), Hardware: []byte(`{}`), Models: []byte(`[]`), LastSeen: now.Add(-2 * time.Hour)} + gone := ProviderRecord{ID: uniqueID("gone"), AccountID: account, SerialNumber: serial, SEPublicKey: seKey, + MDACertChain: []byte(`["gone"]`), Location: location, Hardware: []byte(`{}`), Models: []byte(`[]`), LastSeen: now.Add(-time.Hour)} + for _, p := range []ProviderRecord{live, gone} { + if err := s.UpsertProvider(ctx, p); err != nil { + t.Fatal(err) + } + } + consumerLocation := &ProviderLocation{City: "Origin", Region: "Region", RegionCode: "R", Country: "Country", CountryCode: "CC"} + s.RecordUsage(UsageRecord{ProviderID: gone.ID, ConsumerKey: uniqueID("consumer"), Model: "m", RequestID: uniqueID("req"), + PromptTokens: 1, CompletionTokens: 1, RequestLocation: consumerLocation}) + flowsTo := func() int { + t.Helper() + buckets, err := s.UsageFlowBuckets(now.Add(-24*time.Hour), nil) + if err != nil { + t.Fatal(err) + } + n := 0 + for _, b := range buckets { + if b.ProviderCity == location.City { + n++ + } + } + return n + } + if flowsTo() != 1 { + t.Fatal("fixture: no usage flow to the provider before delete") + } + + softDelete(t, s, "providers", gone.ID) + + if p, err := s.GetProviderRecord(ctx, gone.ID); err == nil { + t.Fatalf("GetProviderRecord returned %+v", p) + } + if _, err := s.GetProviderRecord(ctx, live.ID); err != nil { + t.Fatalf("GetProviderRecord of the live record: %v", err) + } + if chain, err := s.GetMDAChainBySerial(ctx, serial); err != nil || string(chain) != `["live"]` { + t.Fatalf("GetMDAChainBySerial = %s, %v; want the live chain", chain, err) + } + list, err := s.ListProvidersByAccount(ctx, account) + if err != nil || len(list) != 1 || list[0].ID != live.ID { + t.Fatalf("ListProvidersByAccount = %+v, %v; want only the live record", list, err) + } + for _, lookup := range []struct{ serial, seKey string }{{serial, ""}, {"", seKey}} { + p, err := s.GetProviderForRestore(ctx, lookup.serial, lookup.seKey, nil) + if err != nil || p == nil || p.ID != live.ID { + t.Fatalf("GetProviderForRestore(%q, %q) = %+v, %v; want the live record", lookup.serial, lookup.seKey, p, err) + } + } + if n := flowsTo(); n != 0 { + t.Fatalf("usage flows still show the deleted provider's location (%d buckets)", n) + } + + // A deleted record is never restored, even when it is the only match. + softDelete(t, s, "providers", live.ID) + if p, err := s.GetProviderForRestore(ctx, serial, seKey, nil); err != nil || p != nil { + t.Fatalf("GetProviderForRestore restored a deleted record: %+v, %v", p, err) + } + }) + } +} + +func TestSoftDeletedProviderIsNotContinuityHistory(t *testing.T) { + for name, backend := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + inventory, _ := As[MachineInventoryStore](backend) + keys, _ := As[AppAttestShadowStore](backend) + continuity, _ := As[MachineOperationalStore](backend) + account := uniqueID("owner") + appKey := uniqueID("apple") + original, reconnect := uniqueID("original"), uniqueID("reconnect") + if _, err := keys.InsertAppAttestShadowKey(ctx, AppAttestShadowKey{KeyID: appKey, AccountID: account}); err != nil { + t.Fatal(err) + } + if _, err := inventory.ObserveMachine(ctx, MachineObservation{SessionID: original, AccountID: account, At: now, SEKey: uniqueID("se"), VerifiedAppAttestKey: appKey}); err != nil { + t.Fatal(err) + } + prior := ProviderRecord{ID: original, AccountID: account, Hardware: []byte(`{}`), Models: []byte(`[]`), LastSeen: now.Add(-time.Minute)} + if err := backend.UpsertProvider(ctx, prior); err != nil { + t.Fatal(err) + } + if _, err := inventory.ObserveMachine(ctx, MachineObservation{SessionID: reconnect, AccountID: account, At: now, SEKey: uniqueID("se"), VerifiedAppAttestKey: appKey}); err != nil { + t.Fatal(err) + } + got, err := continuity.ResolveMachineContinuity(ctx, reconnect, account, appKey, nil) + if err != nil || got.Previous == nil || got.Previous.ID != prior.ID { + t.Fatalf("fixture: continuity before delete = %+v, %v", got, err) + } + + softDelete(t, backend, "providers", prior.ID) + + got, err = continuity.ResolveMachineContinuity(ctx, reconnect, account, appKey, nil) + if err != nil || got.Previous != nil { + t.Fatalf("continuity returned a deleted provider record: %+v, %v", got.Previous, err) + } + }) + } +} + +func TestSoftDeletedProviderIsNotBackfilledPostgres(t *testing.T) { + s := testPostgresStore(t) + ctx := context.Background() + gone := uniqueID("historical-gone") + if err := s.UpsertProvider(ctx, ProviderRecord{ID: gone, AccountID: "owner", LastSeen: time.Now().UTC().Add(-10 * time.Minute), Hardware: []byte(`{}`), Models: []byte(`[]`)}); err != nil { + t.Fatal(err) + } + softDelete(t, s, "providers", gone) + if _, err := s.BackfillMachineInventory(ctx, 100); err != nil { + t.Fatal(err) + } + var exists bool + if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM darkbloom_machine_sessions WHERE session_id=$1)`, gone).Scan(&exists); err != nil || exists { + t.Fatalf("backfill recorded a deleted provider: %v %v", exists, err) + } +} diff --git a/coordinator/store/storedb/api_keys.sql.go b/coordinator/store/storedb/api_keys.sql.go index 532dc54979..de468f56a2 100644 --- a/coordinator/store/storedb/api_keys.sql.go +++ b/coordinator/store/storedb/api_keys.sql.go @@ -40,7 +40,7 @@ func (q *Queries) DeleteAPIKeyByID(ctx context.Context, arg DeleteAPIKeyByIDPara } const getAPIKeyByHash = `-- name: GetAPIKeyByHash :one -SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE key_hash = $1 +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only, deleted_at FROM api_keys WHERE key_hash = $1 AND deleted_at IS NULL ` func (q *Queries) GetAPIKeyByHash(ctx context.Context, keyHash string) (ApiKey, error) { @@ -63,12 +63,13 @@ func (q *Queries) GetAPIKeyByHash(ctx context.Context, keyHash string) (ApiKey, &i.ExpiresAt, &i.LastUsedAt, &i.SelfRouteOnly, + &i.DeletedAt, ) return i, err } const getAPIKeyByID = `-- name: GetAPIKeyByID :one -SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE id = $1 AND owner_account_id = $2 +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only, deleted_at FROM api_keys WHERE id = $1 AND owner_account_id = $2 AND deleted_at IS NULL ` type GetAPIKeyByIDParams struct { @@ -96,12 +97,13 @@ func (q *Queries) GetAPIKeyByID(ctx context.Context, arg GetAPIKeyByIDParams) (A &i.ExpiresAt, &i.LastUsedAt, &i.SelfRouteOnly, + &i.DeletedAt, ) return i, err } const getAPIKeyByIDForUpdate = `-- name: GetAPIKeyByIDForUpdate :one -SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE id = $1 AND owner_account_id = $2 FOR UPDATE +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only, deleted_at FROM api_keys WHERE id = $1 AND owner_account_id = $2 AND deleted_at IS NULL FOR UPDATE ` type GetAPIKeyByIDForUpdateParams struct { @@ -129,12 +131,13 @@ func (q *Queries) GetAPIKeyByIDForUpdate(ctx context.Context, arg GetAPIKeyByIDF &i.ExpiresAt, &i.LastUsedAt, &i.SelfRouteOnly, + &i.DeletedAt, ) return i, err } const getActiveKeyAccount = `-- name: GetActiveKeyAccount :one -SELECT owner_account_id FROM api_keys WHERE key_hash = $1 AND active = TRUE +SELECT owner_account_id FROM api_keys WHERE key_hash = $1 AND active = TRUE AND deleted_at IS NULL ` func (q *Queries) GetActiveKeyAccount(ctx context.Context, keyHash string) (string, error) { @@ -258,7 +261,7 @@ func (q *Queries) KeySpendSince(ctx context.Context, arg KeySpendSinceParams) (i } const listAPIKeysByOwner = `-- name: ListAPIKeysByOwner :many -SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only FROM api_keys WHERE owner_account_id = $1 AND id <> '' ORDER BY created_at DESC +SELECT key_hash, raw_prefix, owner_account_id, created_at, active, id, name, limit_micro_usd, limit_reset, rpm_limit, itpm_limit, otpm_limit, allowed_models, expires_at, last_used_at, self_route_only, deleted_at FROM api_keys WHERE owner_account_id = $1 AND id <> '' AND deleted_at IS NULL ORDER BY created_at DESC ` func (q *Queries) ListAPIKeysByOwner(ctx context.Context, ownerAccountID string) ([]ApiKey, error) { @@ -287,6 +290,7 @@ func (q *Queries) ListAPIKeysByOwner(ctx context.Context, ownerAccountID string) &i.ExpiresAt, &i.LastUsedAt, &i.SelfRouteOnly, + &i.DeletedAt, ); err != nil { return nil, err } @@ -317,7 +321,7 @@ UPDATE api_keys SET name = $1, active = $2, limit_micro_usd = $3, limit_reset = $4, rpm_limit = $5, itpm_limit = $6, otpm_limit = $7, allowed_models = $8, expires_at = $9, self_route_only = $10 -WHERE id = $11 AND owner_account_id = $12 +WHERE id = $11 AND owner_account_id = $12 AND deleted_at IS NULL ` type UpdateAPIKeyParams struct { diff --git a/coordinator/store/storedb/models.go b/coordinator/store/storedb/models.go index 48fbac1341..1bcaf93aee 100644 --- a/coordinator/store/storedb/models.go +++ b/coordinator/store/storedb/models.go @@ -25,4 +25,5 @@ type ApiKey struct { ExpiresAt *time.Time LastUsedAt *time.Time SelfRouteOnly bool + DeletedAt *time.Time } diff --git a/coordinator/store/testdata/schema_pre_goose.sql b/coordinator/store/testdata/schema_pre_goose.sql new file mode 100644 index 0000000000..80eb7b281f --- /dev/null +++ b/coordinator/store/testdata/schema_pre_goose.sql @@ -0,0 +1,3340 @@ +-- +-- PostgreSQL database dump +-- + + + +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET transaction_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +-- +-- Name: clear_legacy_cache_affinity_key(); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.clear_legacy_cache_affinity_key() RETURNS trigger + LANGUAGE plpgsql + AS $$ BEGIN + NEW.cache_affinity_key := ''; + RETURN NEW; +END $$; + + +-- +-- Name: clear_provider_log_report_serial(); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.clear_provider_log_report_serial() RETURNS trigger + LANGUAGE plpgsql + AS $$ BEGIN + NEW.serial_number := ''; + RETURN NEW; +END $$; + + +-- +-- Name: update_model_demand_hourly(); Type: FUNCTION; Schema: public; Owner: - +-- + +CREATE FUNCTION public.update_model_demand_hourly() RETURNS trigger + LANGUAGE plpgsql + AS $$ +BEGIN + IF TG_OP='UPDATE' AND OLD.outcome=NEW.outcome AND (OLD.http_status=429)=(NEW.http_status=429) THEN RETURN NEW; END IF; + INSERT INTO model_demand_hourly (hour,model,consumer_hash,requests,completed,capacity_rejected,latency_rejected,timed_out,failed,cancelled,unknown,excluded,http_429) + VALUES (date_trunc('hour',NEW.received_at,'UTC'),NEW.model,NEW.consumer_hash, + 1-CASE WHEN TG_OP='UPDATE' THEN 1 ELSE 0 END, + (NEW.outcome='completed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='completed')::integer ELSE 0 END, + (NEW.outcome='capacity_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='capacity_rejected')::integer ELSE 0 END, + (NEW.outcome='latency_rejected')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='latency_rejected')::integer ELSE 0 END, + (NEW.outcome='timed_out')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='timed_out')::integer ELSE 0 END, + (NEW.outcome='failed')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='failed')::integer ELSE 0 END, + (NEW.outcome='cancelled')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='cancelled')::integer ELSE 0 END, + (NEW.outcome='unknown')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='unknown')::integer ELSE 0 END, + (NEW.outcome='excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.outcome='excluded')::integer ELSE 0 END, + (NEW.http_status=429 AND NEW.outcome<>'excluded')::integer-CASE WHEN TG_OP='UPDATE' THEN (OLD.http_status=429 AND OLD.outcome<>'excluded')::integer ELSE 0 END) + ON CONFLICT (hour,model,consumer_hash) DO UPDATE SET + requests=model_demand_hourly.requests+EXCLUDED.requests, + completed=model_demand_hourly.completed+EXCLUDED.completed, + capacity_rejected=model_demand_hourly.capacity_rejected+EXCLUDED.capacity_rejected, + latency_rejected=model_demand_hourly.latency_rejected+EXCLUDED.latency_rejected, + timed_out=model_demand_hourly.timed_out+EXCLUDED.timed_out, + failed=model_demand_hourly.failed+EXCLUDED.failed, + cancelled=model_demand_hourly.cancelled+EXCLUDED.cancelled, + unknown=model_demand_hourly.unknown+EXCLUDED.unknown, + excluded=model_demand_hourly.excluded+EXCLUDED.excluded, + http_429=model_demand_hourly.http_429+EXCLUDED.http_429; + RETURN NEW; +END; +$$; + + +SET default_tablespace = ''; + +SET default_table_access_method = heap; + +-- +-- Name: api_keys; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.api_keys ( + key_hash text NOT NULL, + raw_prefix text NOT NULL, + owner_account_id text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + active boolean DEFAULT true NOT NULL, + id text DEFAULT ''::text NOT NULL, + name text DEFAULT ''::text NOT NULL, + limit_micro_usd bigint, + limit_reset text DEFAULT 'none'::text NOT NULL, + rpm_limit bigint, + itpm_limit bigint, + otpm_limit bigint, + allowed_models text DEFAULT ''::text NOT NULL, + expires_at timestamp with time zone, + last_used_at timestamp with time zone, + self_route_only boolean DEFAULT false NOT NULL +); + + +-- +-- Name: app_attest_build_qualifications; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_build_qualifications ( + binary_hash text NOT NULL, + record jsonb NOT NULL, + CONSTRAINT app_attest_build_qualifications_binary_hash_check CHECK ((binary_hash ~ '^[0-9a-f]{64}$'::text)) +); + + +-- +-- Name: app_attest_enrollments; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_enrollments ( + id text NOT NULL, + owner text NOT NULL, + key_id text NOT NULL, + created_at timestamp with time zone NOT NULL, + context jsonb NOT NULL +); + + +-- +-- Name: app_attest_evidence; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_evidence ( + id text NOT NULL, + session_id text NOT NULL, + key_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + action text NOT NULL, + sha256 text NOT NULL, + context jsonb NOT NULL, + outcome text DEFAULT 'pending'::text NOT NULL, + details jsonb DEFAULT '{}'::jsonb NOT NULL, + completed_at timestamp with time zone +); + + +-- +-- Name: app_attest_evidence_blobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_evidence_blobs ( + evidence_id text NOT NULL, + proof_field text NOT NULL, + proof bytea NOT NULL +); + + +-- +-- Name: app_attest_key_revocations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_key_revocations ( + key_id text NOT NULL, + account_id text NOT NULL, + reason text NOT NULL, + revoked_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: app_attest_key_rotations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_key_rotations ( + key_id text NOT NULL, + machine_id text NOT NULL, + account_id text NOT NULL, + requested_at timestamp with time zone NOT NULL, + failures integer NOT NULL, + reason text NOT NULL +); + + +-- +-- Name: app_attest_receipt_blobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_receipt_blobs ( + receipt_id text NOT NULL, + body bytea NOT NULL, + response_body bytea NOT NULL +); + + +-- +-- Name: app_attest_receipt_jobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_receipt_jobs ( + key_id text NOT NULL, + receipt_id text NOT NULL, + next_at timestamp with time zone NOT NULL, + lease_until timestamp with time zone, + attempts bigint DEFAULT 0 NOT NULL +); + + +-- +-- Name: app_attest_receipts; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_receipts ( + id text NOT NULL, + key_id text NOT NULL, + evidence_id text NOT NULL, + parent_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + outcome text NOT NULL, + http_status integer NOT NULL, + details jsonb NOT NULL, + context jsonb NOT NULL, + next_at timestamp with time zone NOT NULL, + expires_at timestamp with time zone NOT NULL +); + + +-- +-- Name: app_attest_shadow_events; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_shadow_events ( + id text NOT NULL, + session_id text NOT NULL, + observed_at timestamp with time zone NOT NULL, + stage text NOT NULL, + outcome text NOT NULL, + fields jsonb NOT NULL +); + + +-- +-- Name: app_attest_shadow_keys; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.app_attest_shadow_keys ( + key_id text NOT NULL, + owner text NOT NULL, + evidence jsonb NOT NULL, + counter bigint DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT app_attest_shadow_keys_counter_check CHECK (((counter >= 0) AND (counter <= '4294967295'::bigint))) +); + + +-- +-- Name: autopilot_events; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.autopilot_events ( + command_id text NOT NULL, + phase text NOT NULL, + at timestamp with time zone NOT NULL, + record jsonb NOT NULL +); + + +-- +-- Name: balances; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.balances ( + account_id text NOT NULL, + balance_micro_usd bigint DEFAULT 0 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + withdrawable_micro_usd bigint DEFAULT 0 NOT NULL +); + + +-- +-- Name: billing_sessions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.billing_sessions ( + id text NOT NULL, + account_id text NOT NULL, + payment_method text NOT NULL, + amount_micro_usd bigint NOT NULL, + external_id text DEFAULT ''::text NOT NULL, + status text DEFAULT 'pending'::text NOT NULL, + referral_code text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + completed_at timestamp with time zone +); + + +-- +-- Name: cache_routing_demand; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.cache_routing_demand ( + key text NOT NULL, + seen_at timestamp with time zone NOT NULL +); + + +-- +-- Name: cache_routing_holders; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.cache_routing_holders ( + key text NOT NULL, + cache_epoch text NOT NULL, + tier text DEFAULT ''::text NOT NULL, + model_id text NOT NULL, + model_aggregate_hash text DEFAULT ''::text NOT NULL, + prompt_contract_id text DEFAULT ''::text NOT NULL, + block_hash_version text DEFAULT ''::text NOT NULL, + ready_boundary_mode text DEFAULT ''::text NOT NULL, + anchor_token_count integer DEFAULT 0 NOT NULL, + required_recompute_tokens integer DEFAULT 0 NOT NULL, + stage_ms double precision DEFAULT 0 NOT NULL, + measured_stage_ms double precision DEFAULT 0 NOT NULL, + measured_expires_at timestamp with time zone, + updated_at timestamp with time zone NOT NULL, + expires_at timestamp with time zone NOT NULL +); + + +-- +-- Name: cache_routing_meta; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.cache_routing_meta ( + name text NOT NULL, + value text NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: code_attest_push_budgets; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.code_attest_push_budgets ( + se_pubkey text NOT NULL, + token_hash text DEFAULT ''::text NOT NULL, + next_push_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + last_clear_at timestamp with time zone +); + + +-- +-- Name: code_attestations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.code_attestations ( + se_pubkey text NOT NULL, + version text DEFAULT ''::text NOT NULL, + attested_at timestamp with time zone DEFAULT now() NOT NULL, + apns_token text DEFAULT ''::text NOT NULL, + node_public_key text DEFAULT ''::text NOT NULL, + binary_hash text DEFAULT ''::text NOT NULL, + continuous_coverage_until timestamp with time zone +); + + +-- +-- Name: darkbloom_machine_aliases; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_aliases ( + kind text NOT NULL, + scope text NOT NULL, + digest text NOT NULL, + machine_id text NOT NULL, + verified_at timestamp with time zone NOT NULL +); + + +-- +-- Name: darkbloom_machine_merges; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_merges ( + source_id text NOT NULL, + target_id text NOT NULL, + session_id text NOT NULL, + merged_at timestamp with time zone NOT NULL, + reason text NOT NULL +); + + +-- +-- Name: darkbloom_machine_observations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_observations ( + session_id text NOT NULL, + observed_at timestamp with time zone NOT NULL, + observation jsonb NOT NULL +); + + +-- +-- Name: darkbloom_machine_sessions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machine_sessions ( + session_id text NOT NULL, + machine_id text NOT NULL, + original_machine_id text NOT NULL, + account_id text NOT NULL, + first_seen timestamp with time zone NOT NULL, + last_seen timestamp with time zone NOT NULL, + disconnected_at timestamp with time zone, + observation jsonb NOT NULL +); + + +-- +-- Name: darkbloom_machines; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.darkbloom_machines ( + id text NOT NULL, + assurance text NOT NULL, + merged_into text, + first_seen timestamp with time zone NOT NULL, + last_seen timestamp with time zone NOT NULL +); + + +-- +-- Name: device_codes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.device_codes ( + device_code text NOT NULL, + user_code text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + status text DEFAULT 'pending'::text NOT NULL, + expires_at timestamp with time zone NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: earnings_summary; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.earnings_summary ( + key text NOT NULL, + key_type text NOT NULL, + total_count bigint DEFAULT 0 NOT NULL, + total_micro_usd bigint DEFAULT 0 NOT NULL, + total_prompt_tokens bigint DEFAULT 0 NOT NULL, + total_completion_tokens bigint DEFAULT 0 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: fleet_snapshots; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.fleet_snapshots ( + id bigint NOT NULL, + sampled_at timestamp with time zone NOT NULL, + provider_id text NOT NULL, + model text DEFAULT ''::text NOT NULL, + eligibility_reason text DEFAULT ''::text NOT NULL, + slot_state text DEFAULT ''::text NOT NULL, + num_running integer DEFAULT 0 NOT NULL, + num_waiting integer DEFAULT 0 NOT NULL, + queued_prefill_tokens integer DEFAULT 0 NOT NULL, + partial_prefill_rows integer DEFAULT 0 NOT NULL, + active_token_budget_used bigint DEFAULT 0 NOT NULL, + active_token_budget_max bigint DEFAULT 0 NOT NULL, + kv_bytes_in_use bigint DEFAULT 0 NOT NULL, + kv_bytes_capacity bigint DEFAULT 0 NOT NULL, + observed_decode_tps double precision DEFAULT 0 NOT NULL, + observed_prefill_tps double precision DEFAULT 0 NOT NULL, + isolated_prefill_tps double precision DEFAULT 0 NOT NULL, + ewma_initialized boolean, + max_concurrency integer DEFAULT 0 NOT NULL, + pending_count integer DEFAULT 0 NOT NULL, + effective_cap integer DEFAULT 0 NOT NULL, + cooldown_active boolean DEFAULT false NOT NULL, + breaker_open boolean DEFAULT false NOT NULL, + clamp_active boolean DEFAULT false NOT NULL, + ejected boolean DEFAULT false NOT NULL, + gpu_memory_active_gb double precision DEFAULT 0 NOT NULL, + gpu_memory_peak_gb double precision DEFAULT 0 NOT NULL, + free_for_load_gb double precision, + memory_pressure double precision DEFAULT 0 NOT NULL, + cpu_usage double precision DEFAULT 0 NOT NULL, + thermal_state text DEFAULT ''::text NOT NULL, + low_power_mode boolean, + memory_pressure_level text DEFAULT ''::text NOT NULL, + steps_executed bigint DEFAULT 0 NOT NULL, + step_wall_ns_total bigint DEFAULT 0 NOT NULL, + decode_rows_total bigint DEFAULT 0 NOT NULL, + prefill_tokens_total bigint DEFAULT 0 NOT NULL, + mtp_rounds_total bigint DEFAULT 0 NOT NULL, + mtp_proposed_total bigint DEFAULT 0 NOT NULL, + mtp_accepted_total bigint DEFAULT 0 NOT NULL, + heartbeat_age_ms integer DEFAULT 0 NOT NULL, + wedge_suspected boolean DEFAULT false NOT NULL, + eval_in_flight_ms bigint DEFAULT 0 NOT NULL, + requests_served bigint DEFAULT 0 NOT NULL, + tokens_generated bigint DEFAULT 0 NOT NULL, + cancellations_received bigint DEFAULT 0 NOT NULL, + cancellations_before_output bigint DEFAULT 0 NOT NULL, + cancellations_partial_complete bigint DEFAULT 0 NOT NULL, + generation_errors_after_output bigint DEFAULT 0 NOT NULL, + chunk_encryption_errors bigint DEFAULT 0 NOT NULL, + stream_closed_without_terminal bigint DEFAULT 0 NOT NULL, + cancel_during_model_load bigint DEFAULT 0 NOT NULL, + usage_gaps bigint DEFAULT 0 NOT NULL, + cancel_stage_pre_accept_total bigint DEFAULT 0 NOT NULL, + cancel_stage_pre_engine_total bigint DEFAULT 0 NOT NULL, + cancel_stage_prefill_total bigint DEFAULT 0 NOT NULL, + cancel_stage_decode_total bigint DEFAULT 0 NOT NULL, + cancel_stage_post_terminal_total bigint DEFAULT 0 NOT NULL, + tokens_after_cancel_total bigint DEFAULT 0 NOT NULL, + cancel_abort_ns_sum bigint DEFAULT 0 NOT NULL, + queue_depth_total integer DEFAULT 0 NOT NULL, + queue_depth_by_model jsonb, + inflight_requests integer DEFAULT 0 NOT NULL, + reserve_lock_wait_p95_us bigint DEFAULT 0 NOT NULL, + profile_sink_depth integer DEFAULT 0 NOT NULL, + profile_sink_dropped_total bigint DEFAULT 0 NOT NULL, + route_sink_dropped_total bigint DEFAULT 0 NOT NULL, + unknown_request_frames_total bigint DEFAULT 0 NOT NULL, + goroutines integer DEFAULT 0 NOT NULL, + provider_version text DEFAULT ''::text NOT NULL, + model_vision boolean DEFAULT false NOT NULL, + template_render_ok boolean +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01'); + + +-- +-- Name: fleet_snapshots_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.fleet_snapshots_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: fleet_snapshots_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.fleet_snapshots_id_seq OWNED BY public.fleet_snapshots.id; + + +-- +-- Name: global_payout_recipients; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.global_payout_recipients ( + account_id text NOT NULL, + country text NOT NULL, + data jsonb NOT NULL +); + + +-- +-- Name: global_payout_withdrawals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.global_payout_withdrawals ( + id text NOT NULL, + account_id text NOT NULL, + status text NOT NULL, + external_id text DEFAULT ''::text NOT NULL, + submitted_at timestamp with time zone NOT NULL, + checked_at timestamp with time zone NOT NULL, + lease_until timestamp with time zone NOT NULL, + expires_at timestamp with time zone NOT NULL, + data jsonb NOT NULL +); + + +-- +-- Name: inference_routes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.inference_routes ( + id bigint NOT NULL, + request_id text NOT NULL, + attempt integer DEFAULT 0 NOT NULL, + provider_id text DEFAULT ''::text NOT NULL, + model text NOT NULL, + public_model text DEFAULT ''::text NOT NULL, + consumer_key_hash text DEFAULT ''::text NOT NULL, + key_id text DEFAULT ''::text NOT NULL, + outcome text DEFAULT ''::text NOT NULL, + cost_ms double precision, + state_ms double precision, + queue_ms double precision, + pending_ms double precision, + backlog_ms double precision, + this_req_ms double precision, + health_ms double precision, + ttft_ms double precision, + best_ttft_ms double precision, + effective_queue integer, + candidate_count integer, + capacity_rejections integer, + model_too_large_rejections integer, + vision_rejections integer, + ttft_rejections integer, + effective_tps double precision, + static_tps double precision, + provider_status text, + provider_trust_level text, + provider_version text, + hardware_chip text, + hardware_chip_family text, + hardware_tier text, + memory_gb integer, + gpu_cores integer, + cpu_cores integer, + system_memory_pressure double precision, + system_cpu_usage double precision, + system_thermal_state text, + gpu_memory_active_gb double precision, + gpu_memory_peak_gb double precision, + gpu_memory_cache_gb double precision, + slot_state text, + backend_running integer, + backend_waiting integer, + active_token_budget_used bigint, + active_token_budget_max bigint, + queued_token_budget bigint, + estimated_prompt_tokens integer, + requested_max_tokens integer, + requires_vision boolean DEFAULT false NOT NULL, + has_tools boolean DEFAULT false NOT NULL, + self_route_only boolean DEFAULT false NOT NULL, + prefer_owner boolean DEFAULT false NOT NULL, + cache_affinity_key text DEFAULT ''::text NOT NULL, + final_status text DEFAULT ''::text NOT NULL, + error_code integer, + error_class text, + prompt_tokens integer, + completion_tokens integer, + reasoning_tokens integer, + cost_micro_usd bigint, + actual_ttft_ms double precision, + dispatch_to_first_chunk_ms double precision, + total_duration_ms double precision, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + provider_region text, + consumer_region text, + parse_ms double precision, + reserve_ms double precision, + route_ms double precision, + encrypt_ms double precision, + queue_wait_ms double precision, + dispatch_ms double precision, + actual_decode_tps double precision, + admitted_but_failed boolean, + used_backup boolean, + backup_won boolean, + error_reason text +); + + +-- +-- Name: inference_routes_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.inference_routes_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: inference_routes_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.inference_routes_id_seq OWNED BY public.inference_routes.id; + + +-- +-- Name: invite_codes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.invite_codes ( + code text NOT NULL, + amount_micro_usd bigint NOT NULL, + max_uses integer DEFAULT 1 NOT NULL, + used_count integer DEFAULT 0 NOT NULL, + active boolean DEFAULT true NOT NULL, + expires_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: invite_redemptions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.invite_redemptions ( + code text NOT NULL, + account_id text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: ledger_entries; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.ledger_entries ( + id bigint NOT NULL, + account_id text NOT NULL, + entry_type text NOT NULL, + amount_micro_usd bigint NOT NULL, + balance_after bigint NOT NULL, + reference text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: ledger_entries_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.ledger_entries_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: ledger_entries_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.ledger_entries_id_seq OWNED BY public.ledger_entries.id; + + +-- +-- Name: model_active_versions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_active_versions ( + model_id text NOT NULL, + model_version_id bigint NOT NULL, + activated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: model_aliases; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_aliases ( + alias_id text NOT NULL, + display_name text DEFAULT ''::text NOT NULL, + builds jsonb DEFAULT '[]'::jsonb NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + desired_build text DEFAULT ''::text NOT NULL, + previous_build text DEFAULT ''::text NOT NULL, + retired_builds jsonb DEFAULT '[]'::jsonb NOT NULL, + openrouter_only boolean DEFAULT false NOT NULL, + source_model text DEFAULT ''::text NOT NULL, + source_kind text DEFAULT 'standard_alias'::text NOT NULL, + openrouter_slug text DEFAULT ''::text NOT NULL, + hugging_face_id text DEFAULT ''::text NOT NULL +); + + +-- +-- Name: model_demand_collection; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_demand_collection ( + singleton boolean NOT NULL, + started_at timestamp with time zone NOT NULL, + CONSTRAINT model_demand_collection_singleton_check CHECK (singleton) +); + + +-- +-- Name: model_demand_hourly; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_demand_hourly ( + hour timestamp with time zone NOT NULL, + model text NOT NULL, + consumer_hash text NOT NULL, + requests bigint NOT NULL, + completed bigint NOT NULL, + capacity_rejected bigint NOT NULL, + latency_rejected bigint NOT NULL, + timed_out bigint NOT NULL, + failed bigint NOT NULL, + cancelled bigint NOT NULL, + unknown bigint NOT NULL, + excluded bigint NOT NULL, + http_429 bigint NOT NULL +); + + +-- +-- Name: model_demand_requests; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_demand_requests ( + id bigint NOT NULL, + coord_request_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + model text NOT NULL, + consumer_hash text NOT NULL, + outcome text NOT NULL, + http_status integer NOT NULL, + revision bigint NOT NULL, + evidence_conflict boolean DEFAULT false NOT NULL +); + + +-- +-- Name: model_demand_requests_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.model_demand_requests_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: model_demand_requests_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.model_demand_requests_id_seq OWNED BY public.model_demand_requests.id; + + +-- +-- Name: model_prices; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_prices ( + account_id text NOT NULL, + model text NOT NULL, + input_price bigint NOT NULL, + output_price bigint NOT NULL, + cache_read_price bigint, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: model_registry; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_registry ( + id text NOT NULL, + display_name text NOT NULL, + family text DEFAULT ''::text NOT NULL, + architecture text DEFAULT ''::text NOT NULL, + quantization text DEFAULT ''::text NOT NULL, + max_context_length integer DEFAULT 0 NOT NULL, + max_output_length integer DEFAULT 0 NOT NULL, + min_ram_gb integer DEFAULT 0 NOT NULL, + capabilities text[] DEFAULT '{}'::text[] NOT NULL, + required_provider_capabilities text[] DEFAULT '{}'::text[] NOT NULL, + status text DEFAULT 'beta'::text NOT NULL, + description text DEFAULT ''::text NOT NULL, + runtime_parameters jsonb DEFAULT '{}'::jsonb NOT NULL, + metadata jsonb DEFAULT '{}'::jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: model_token_grants; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_grants ( + account_id text NOT NULL, + model_id text NOT NULL, + total_tokens bigint NOT NULL, + used_tokens bigint DEFAULT 0 NOT NULL, + reserved_tokens bigint DEFAULT 0 NOT NULL, + claimed_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT model_token_grants_check CHECK (((used_tokens + reserved_tokens) <= total_tokens)), + CONSTRAINT model_token_grants_reserved_tokens_check CHECK ((reserved_tokens >= 0)), + CONSTRAINT model_token_grants_total_tokens_check CHECK ((total_tokens > 0)), + CONSTRAINT model_token_grants_used_tokens_check CHECK ((used_tokens >= 0)) +); + + +-- +-- Name: model_token_promotions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_promotions ( + model_id text NOT NULL, + tokens bigint NOT NULL, + claim_starts_at timestamp with time zone NOT NULL, + claim_ends_at timestamp with time zone, + signup_cutoff_at timestamp with time zone NOT NULL, + max_claims bigint NOT NULL, + claimed_count bigint DEFAULT 0 NOT NULL, + enabled boolean DEFAULT true NOT NULL, + CONSTRAINT model_token_promotions_check CHECK ((claim_ends_at > claim_starts_at)), + CONSTRAINT model_token_promotions_check1 CHECK (((claimed_count >= 0) AND (claimed_count <= max_claims))), + CONSTRAINT model_token_promotions_max_claims_check CHECK (((max_claims > 0) AND (max_claims <= 1000000))), + CONSTRAINT model_token_promotions_tokens_check CHECK (((tokens > 0) AND (tokens <= '1000000000000'::bigint))) +); + + +-- +-- Name: model_token_provider_carries; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_provider_carries ( + account_id text NOT NULL, + remainder bigint DEFAULT 0 NOT NULL, + CONSTRAINT model_token_provider_carries_remainder_check CHECK (((remainder >= 0) AND (remainder < 100000000))) +); + + +-- +-- Name: model_token_reservations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_token_reservations ( + id text NOT NULL, + account_id text NOT NULL, + model_id text NOT NULL, + state text NOT NULL, + record jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + touched_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT model_token_reservations_state_check CHECK ((state = ANY (ARRAY['reserved'::text, 'settled'::text, 'released'::text]))) +); + + +-- +-- Name: model_version_files; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_version_files ( + id bigint NOT NULL, + model_version_id bigint NOT NULL, + path text NOT NULL, + size_bytes bigint NOT NULL, + sha256 text NOT NULL, + role text NOT NULL +); + + +-- +-- Name: model_version_files_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.model_version_files_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: model_version_files_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.model_version_files_id_seq OWNED BY public.model_version_files.id; + + +-- +-- Name: model_versions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.model_versions ( + id bigint NOT NULL, + model_id text NOT NULL, + version text NOT NULL, + r2_prefix text NOT NULL, + aggregate_sha256 text NOT NULL, + total_size_bytes bigint NOT NULL, + file_count integer NOT NULL, + status text DEFAULT 'ready'::text NOT NULL, + uploaded_by text DEFAULT ''::text NOT NULL, + uploaded_at timestamp with time zone DEFAULT now() NOT NULL, + promoted_at timestamp with time zone, + metadata jsonb DEFAULT '{}'::jsonb NOT NULL, + hugging_face_artifact jsonb +); + + +-- +-- Name: model_versions_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.model_versions_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: model_versions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.model_versions_id_seq OWNED BY public.model_versions.id; + + +-- +-- Name: payments; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.payments ( + id bigint NOT NULL, + tx_hash text, + consumer_address text NOT NULL, + provider_address text NOT NULL, + amount_usd text NOT NULL, + model text NOT NULL, + prompt_tokens integer NOT NULL, + completion_tokens integer NOT NULL, + memo text, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: payments_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.payments_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: payments_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.payments_id_seq OWNED BY public.payments.id; + + +-- +-- Name: provider_earnings; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_earnings ( + id bigint NOT NULL, + account_id text NOT NULL, + provider_id text NOT NULL, + provider_key text DEFAULT ''::text NOT NULL, + job_id text NOT NULL, + model text NOT NULL, + amount_micro_usd bigint NOT NULL, + prompt_tokens integer DEFAULT 0 NOT NULL, + completion_tokens integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +) +WITH (autovacuum_analyze_scale_factor='0.005'); + + +-- +-- Name: provider_earnings_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_earnings_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_earnings_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_earnings_id_seq OWNED BY public.provider_earnings.id; + + +-- +-- Name: provider_floor_draws; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_floor_draws ( + id bigint NOT NULL, + provider_key text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + epoch_id text NOT NULL, + amount_micro_usd bigint NOT NULL, + floor_micro_usd bigint DEFAULT 0 NOT NULL, + earned_micro_usd bigint DEFAULT 0 NOT NULL, + uptime_frac double precision DEFAULT 0 NOT NULL, + memory_gb integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_floor_draws_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_floor_draws_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_floor_draws_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_floor_draws_id_seq OWNED BY public.provider_floor_draws.id; + + +-- +-- Name: provider_log_reports; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_log_reports ( + id bigint NOT NULL, + serial_number text DEFAULT ''::text NOT NULL, + provider_id text DEFAULT ''::text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + log_data bytea NOT NULL, + log_size_bytes bigint DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_log_reports_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_log_reports_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_log_reports_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_log_reports_id_seq OWNED BY public.provider_log_reports.id; + + +-- +-- Name: provider_payouts; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_payouts ( + id bigint NOT NULL, + provider_address text NOT NULL, + amount_micro_usd bigint NOT NULL, + model text DEFAULT ''::text NOT NULL, + job_id text DEFAULT ''::text NOT NULL, + settled boolean DEFAULT false NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_payouts_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_payouts_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_payouts_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_payouts_id_seq OWNED BY public.provider_payouts.id; + + +-- +-- Name: provider_reputation; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_reputation ( + provider_id text NOT NULL, + total_jobs integer DEFAULT 0 NOT NULL, + successful_jobs integer DEFAULT 0 NOT NULL, + failed_jobs integer DEFAULT 0 NOT NULL, + total_uptime_seconds bigint DEFAULT 0 NOT NULL, + avg_response_time_ms bigint DEFAULT 0 NOT NULL, + challenges_passed integer DEFAULT 0 NOT NULL, + challenges_failed integer DEFAULT 0 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_sessions; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_sessions ( + id bigint NOT NULL, + session_id text NOT NULL, + serial_number text DEFAULT ''::text NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + connected_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen timestamp with time zone DEFAULT now() NOT NULL, + disconnected_at timestamp with time zone, + disconnect_reason text DEFAULT ''::text NOT NULL, + provider_key text DEFAULT ''::text NOT NULL +); + + +-- +-- Name: provider_sessions_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.provider_sessions_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: provider_sessions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.provider_sessions_id_seq OWNED BY public.provider_sessions.id; + + +-- +-- Name: provider_tokens; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_tokens ( + token_hash text NOT NULL, + account_id text NOT NULL, + label text DEFAULT ''::text NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: provider_trust_reuse; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_trust_reuse ( + se_pubkey text NOT NULL, + serial text DEFAULT ''::text NOT NULL, + trust_level text DEFAULT ''::text NOT NULL, + binary_hash text DEFAULT ''::text NOT NULL, + sip_enabled boolean DEFAULT false NOT NULL, + secure_boot_full boolean DEFAULT false NOT NULL, + mda_udid text DEFAULT ''::text NOT NULL, + verified_at timestamp with time zone DEFAULT now() NOT NULL, + last_verified_binary_hash text DEFAULT ''::text NOT NULL, + hardware_proof_verified_at timestamp with time zone DEFAULT now() NOT NULL, + application_proof_verified_at timestamp with time zone, + evidence_generation bigint DEFAULT 1 NOT NULL, + revocation_generation bigint DEFAULT 0 NOT NULL, + revocation_event_id text DEFAULT ''::text NOT NULL, + revoked_at timestamp with time zone, + continuous_coverage_until timestamp with time zone +); + + +-- +-- Name: provider_verification_jobs; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.provider_verification_jobs ( + se_pubkey text NOT NULL, + serial text DEFAULT ''::text NOT NULL, + udid text DEFAULT ''::text NOT NULL, + task_kind text NOT NULL, + task_state text NOT NULL, + priority smallint NOT NULL, + retry_stage integer DEFAULT 0 NOT NULL, + previous_delay_ns bigint DEFAULT 0 NOT NULL, + next_attempt_at timestamp with time zone, + last_outcome text DEFAULT 'none'::text NOT NULL, + reopen_pending boolean DEFAULT false NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + claim_owner text DEFAULT ''::text NOT NULL, + claim_expires_at timestamp with time zone +); + + +-- +-- Name: providers; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.providers ( + id text NOT NULL, + hardware jsonb NOT NULL, + models jsonb NOT NULL, + backend text NOT NULL, + location jsonb, + registered_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen timestamp with time zone DEFAULT now() NOT NULL, + trust_level text DEFAULT 'none'::text NOT NULL, + attested boolean DEFAULT false NOT NULL, + attestation_result jsonb, + se_public_key text DEFAULT ''::text NOT NULL, + public_key text DEFAULT ''::text NOT NULL, + serial_number text DEFAULT ''::text NOT NULL, + mda_verified boolean DEFAULT false NOT NULL, + mda_cert_chain jsonb, + version text DEFAULT ''::text NOT NULL, + runtime_verified boolean DEFAULT false NOT NULL, + python_hash text DEFAULT ''::text NOT NULL, + runtime_hash text DEFAULT ''::text NOT NULL, + last_challenge_verified timestamp with time zone, + failed_challenges integer DEFAULT 0 NOT NULL, + account_id text DEFAULT ''::text NOT NULL, + lifetime_requests_served bigint DEFAULT 0 NOT NULL, + lifetime_tokens_generated bigint DEFAULT 0 NOT NULL, + last_session_requests_served bigint DEFAULT 0 NOT NULL, + last_session_tokens_generated bigint DEFAULT 0 NOT NULL, + lifetime_stats jsonb DEFAULT '{}'::jsonb NOT NULL, + last_session_stats jsonb DEFAULT '{}'::jsonb NOT NULL +); + + +-- +-- Name: publishing_api_keys; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.publishing_api_keys ( + id text NOT NULL, + name text NOT NULL, + key_hash text NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + last_used_at timestamp with time zone +); + + +-- +-- Name: referrals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.referrals ( + referred_account text NOT NULL, + referrer_code text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: referrers; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.referrers ( + account_id text NOT NULL, + code text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: releases; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.releases ( + version text NOT NULL, + platform text NOT NULL, + backend text DEFAULT ''::text NOT NULL, + binary_hash text DEFAULT ''::text NOT NULL, + bundle_hash text DEFAULT ''::text NOT NULL, + metallib_hash text DEFAULT ''::text NOT NULL, + python_hash text DEFAULT ''::text NOT NULL, + runtime_hash text DEFAULT ''::text NOT NULL, + template_hashes text DEFAULT ''::text NOT NULL, + grpc_binary_hash text DEFAULT ''::text NOT NULL, + url text DEFAULT ''::text NOT NULL, + changelog text DEFAULT ''::text NOT NULL, + active boolean DEFAULT true NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: request_outcomes; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.request_outcomes ( + id bigint NOT NULL, + coord_request_id text NOT NULL, + received_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone NOT NULL, + revision bigint NOT NULL, + evidence_conflict boolean DEFAULT false NOT NULL, + record jsonb NOT NULL, + CONSTRAINT request_outcomes_coord_request_id_check CHECK ((coord_request_id <> ''::text)) +); + + +-- +-- Name: request_outcomes_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.request_outcomes_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: request_outcomes_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.request_outcomes_id_seq OWNED BY public.request_outcomes.id; + + +-- +-- Name: request_profiles; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.request_profiles ( + id bigint NOT NULL, + coord_request_id text NOT NULL, + request_id text NOT NULL, + attempt integer NOT NULL, + backup_of text DEFAULT ''::text NOT NULL, + winning boolean DEFAULT false NOT NULL, + endpoint text DEFAULT ''::text NOT NULL, + stream boolean DEFAULT false NOT NULL, + model text DEFAULT ''::text NOT NULL, + public_model text DEFAULT ''::text NOT NULL, + provider_id text DEFAULT ''::text NOT NULL, + provider_version text DEFAULT ''::text NOT NULL, + chip_family text DEFAULT ''::text NOT NULL, + kv_backend text DEFAULT ''::text NOT NULL, + final_status text DEFAULT ''::text NOT NULL, + error_reason text DEFAULT ''::text NOT NULL, + terminal_cause text DEFAULT ''::text NOT NULL, + client_outcome text DEFAULT ''::text NOT NULL, + provider_outcome text DEFAULT ''::text NOT NULL, + client_gone_phase text DEFAULT ''::text NOT NULL, + first_content_budget_ms integer DEFAULT 0 NOT NULL, + admission_mode text DEFAULT ''::text NOT NULL, + predictive_bypass text DEFAULT ''::text NOT NULL, + reservation_ttft_ceiling_ms double precision, + dispatch_budget_ms bigint, + estimated_prompt_tokens integer DEFAULT 0 NOT NULL, + requested_max_tokens integer DEFAULT 0 NOT NULL, + requires_vision boolean DEFAULT false NOT NULL, + has_tools boolean DEFAULT false NOT NULL, + received_at timestamp with time zone NOT NULL, + auth_done_us bigint, + ratelimit_done_us bigint, + sealed_open_us bigint, + handler_entry_us bigint, + parsed_us bigint, + reserved_us bigint, + media_fetched_us bigint, + preflight_done_us bigint, + plan_done_us bigint, + attempt_start_us bigint, + reserve_lock_acquired_us bigint, + reserve_done_us bigint, + queued_us bigint, + dequeued_us bigint, + topup_done_us bigint, + encrypted_us bigint, + write_submitted_us bigint, + write_dequeued_us bigint, + write_done_us bigint, + accepted_us bigint, + first_chunk_ingress_us bigint, + first_chunk_dequeued_us bigint, + first_content_ingress_us bigint, + first_content_us bigint, + headers_written_us bigint, + first_flush_us bigint, + last_flush_us bigint, + client_gone_us bigint, + cancel_sent_us bigint, + complete_ingress_us bigint, + done_flushed_us bigint, + finalized_us bigint, + settle_db_us bigint, + db_us bigint, + db_calls integer DEFAULT 0 NOT NULL, + body_bytes integer DEFAULT 0 NOT NULL, + sealed_body_bytes integer DEFAULT 0 NOT NULL, + auth_kind text DEFAULT ''::text NOT NULL, + auth_db_read boolean DEFAULT false NOT NULL, + reserve_mode text DEFAULT ''::text NOT NULL, + media_items integer DEFAULT 0 NOT NULL, + media_bytes bigint DEFAULT 0 NOT NULL, + preflight_outcome text DEFAULT ''::text NOT NULL, + plan_outcome text DEFAULT ''::text NOT NULL, + chunks_in integer DEFAULT 0 NOT NULL, + chunks_out integer DEFAULT 0 NOT NULL, + bytes_out bigint DEFAULT 0 NOT NULL, + decrypt_us_total bigint DEFAULT 0 NOT NULL, + max_chunk_gap_us bigint DEFAULT 0 NOT NULL, + held_preamble_chunks integer DEFAULT 0 NOT NULL, + client_write_err boolean DEFAULT false NOT NULL, + attempts_total integer DEFAULT 0 NOT NULL, + failed_attempts integer DEFAULT 0 NOT NULL, + failed_attempts_us bigint DEFAULT 0 NOT NULL, + backup_launched boolean DEFAULT false NOT NULL, + backup_won boolean DEFAULT false NOT NULL, + transport_est_us bigint, + slept_us bigint, + timing_anomaly boolean DEFAULT false NOT NULL, + candidate_set_size integer DEFAULT 0 NOT NULL, + scanned integer DEFAULT 0 NOT NULL, + gate_rejections jsonb, + runner_up_provider_id text DEFAULT ''::text NOT NULL, + runner_up_cost_ms double precision DEFAULT 0 NOT NULL, + near_tie_pool_size integer DEFAULT 0 NOT NULL, + selection_path text DEFAULT ''::text NOT NULL, + best_idle_provider_id text DEFAULT ''::text NOT NULL, + best_idle_ttft_ms double precision DEFAULT 0 NOT NULL, + predicted_ttft_ms double precision DEFAULT 0 NOT NULL, + raw_ttft_ms double precision DEFAULT 0 NOT NULL, + predicted_decode_tps double precision DEFAULT 0 NOT NULL, + snapshot_age_ms integer DEFAULT 0 NOT NULL, + pending_for_model integer DEFAULT 0 NOT NULL, + total_pending integer DEFAULT 0 NOT NULL, + capacity_rate_ms double precision DEFAULT 0 NOT NULL, + cache_discount_ms double precision DEFAULT 0 NOT NULL, + shadow_would_shed boolean, + shadow_idle_alternative boolean, + lock_wait_us bigint DEFAULT 0 NOT NULL, + scan_us bigint DEFAULT 0 NOT NULL, + admit_us bigint DEFAULT 0 NOT NULL, + preflight_us bigint DEFAULT 0 NOT NULL, + ttft_calibration_ratio double precision DEFAULT 0 NOT NULL, + prefill_decode_ratio double precision DEFAULT 0 NOT NULL, + queue_position_at_enqueue integer DEFAULT 0 NOT NULL, + queue_depth_at_enqueue integer DEFAULT 0 NOT NULL, + drain_trigger text DEFAULT ''::text NOT NULL, + candidates jsonb, + prov_total_us bigint, + prov_first_delta_us bigint, + prov_engine_submit_us bigint, + prov_engine_admitted_us bigint, + prov_prompt_prep_us bigint, + prov_load_wait_us bigint, + prov_load_cold boolean, + prov_running_at_admit integer, + prov_waiting_at_admit integer, + prov_kv_bytes_in_use_at_admit bigint, + prov_cancel_stage text DEFAULT ''::text NOT NULL, + eng_queue_wait_ns bigint, + eng_first_token_ns bigint, + eng_prompt_computed_ns bigint, + eng_prefill_chunks integer, + eng_decode_steps integer, + eng_mtp_accepted integer, + eng_finish_reason text DEFAULT ''::text NOT NULL, + provider_profile jsonb, + provider_profile_valid boolean DEFAULT false NOT NULL, + provider_profile_invalid_reason text DEFAULT ''::text NOT NULL, + provider_profile_consistent boolean, + created_at timestamp with time zone DEFAULT now() NOT NULL +) +WITH (autovacuum_vacuum_scale_factor='0.02', autovacuum_analyze_scale_factor='0.01'); + + +-- +-- Name: request_profiles_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.request_profiles_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: request_profiles_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.request_profiles_id_seq OWNED BY public.request_profiles.id; + + +-- +-- Name: request_rejections; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.request_rejections ( + id bigint NOT NULL, + request_id text, + endpoint text, + stage text, + reason_code text, + http_status integer, + consumer_key_hash text, + key_id text, + client_class text, + requested_model text, + resolved_model text, + stream boolean, + n integer, + estimated_prompt_tokens integer, + requested_max_tokens integer, + requires_vision boolean, + has_image boolean, + has_audio boolean, + has_tools boolean, + tool_count integer, + response_format text, + self_route_only boolean, + prefer_owner boolean, + params jsonb, + request_body_bytes integer, + retry_after_ms integer, + could_have_served boolean, + candidate_count integer, + capacity_rejections integer, + model_too_large_rejections integer, + vision_rejections integer, + warm_provider_existed boolean, + best_ttft_ms double precision, + shortfall_micro_usd bigint, + limit_kind text, + over_by bigint, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: request_rejections_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.request_rejections_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: request_rejections_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.request_rejections_id_seq OWNED BY public.request_rejections.id; + + +-- +-- Name: schema_migrations; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.schema_migrations ( + id text NOT NULL, + applied_at timestamp with time zone DEFAULT now() NOT NULL +); + + +-- +-- Name: stripe_withdrawals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.stripe_withdrawals ( + id text NOT NULL, + account_id text NOT NULL, + stripe_account_id text NOT NULL, + transfer_id text DEFAULT ''::text NOT NULL, + payout_id text DEFAULT ''::text NOT NULL, + amount_micro_usd bigint NOT NULL, + fee_micro_usd bigint DEFAULT 0 NOT NULL, + net_micro_usd bigint NOT NULL, + method text NOT NULL, + status text NOT NULL, + failure_reason text DEFAULT ''::text NOT NULL, + refunded boolean DEFAULT false NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + fee_refunded boolean DEFAULT false NOT NULL, + sweep_payout_id text DEFAULT ''::text NOT NULL +); + + +-- +-- Name: usage; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.usage ( + id bigint NOT NULL, + provider_id text NOT NULL, + consumer_key_hash text NOT NULL, + key_id text DEFAULT ''::text NOT NULL, + model text NOT NULL, + public_model text DEFAULT ''::text NOT NULL, + prompt_tokens integer NOT NULL, + cached_tokens integer DEFAULT 0 NOT NULL, + completion_tokens integer NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + request_id text DEFAULT ''::text NOT NULL, + cost_micro_usd bigint DEFAULT 0 NOT NULL, + request_location jsonb +); + + +-- +-- Name: usage_id_seq; Type: SEQUENCE; Schema: public; Owner: - +-- + +CREATE SEQUENCE public.usage_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + + +-- +-- Name: usage_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: - +-- + +ALTER SEQUENCE public.usage_id_seq OWNED BY public.usage.id; + + +-- +-- Name: usage_totals; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.usage_totals ( + id integer DEFAULT 1 NOT NULL, + total_requests bigint DEFAULT 0 NOT NULL, + total_prompt_tokens bigint DEFAULT 0 NOT NULL, + total_completion_tokens bigint DEFAULT 0 NOT NULL, + CONSTRAINT usage_totals_id_check CHECK ((id = 1)) +); + + +-- +-- Name: users; Type: TABLE; Schema: public; Owner: - +-- + +CREATE TABLE public.users ( + account_id text NOT NULL, + privy_user_id text NOT NULL, + email text DEFAULT ''::text NOT NULL, + role text DEFAULT ''::text NOT NULL, + platform_fee_percent bigint, + created_at timestamp with time zone DEFAULT now() NOT NULL, + stripe_account_id text DEFAULT ''::text NOT NULL, + stripe_account_status text DEFAULT ''::text NOT NULL, + stripe_account_country text DEFAULT ''::text NOT NULL, + stripe_destination_type text DEFAULT ''::text NOT NULL, + stripe_destination_last4 text DEFAULT ''::text NOT NULL, + stripe_instant_eligible boolean DEFAULT false NOT NULL +); + + +-- +-- Name: fleet_snapshots id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.fleet_snapshots ALTER COLUMN id SET DEFAULT nextval('public.fleet_snapshots_id_seq'::regclass); + + +-- +-- Name: inference_routes id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.inference_routes ALTER COLUMN id SET DEFAULT nextval('public.inference_routes_id_seq'::regclass); + + +-- +-- Name: ledger_entries id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.ledger_entries ALTER COLUMN id SET DEFAULT nextval('public.ledger_entries_id_seq'::regclass); + + +-- +-- Name: model_demand_requests id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_requests ALTER COLUMN id SET DEFAULT nextval('public.model_demand_requests_id_seq'::regclass); + + +-- +-- Name: model_version_files id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files ALTER COLUMN id SET DEFAULT nextval('public.model_version_files_id_seq'::regclass); + + +-- +-- Name: model_versions id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions ALTER COLUMN id SET DEFAULT nextval('public.model_versions_id_seq'::regclass); + + +-- +-- Name: payments id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.payments ALTER COLUMN id SET DEFAULT nextval('public.payments_id_seq'::regclass); + + +-- +-- Name: provider_earnings id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_earnings ALTER COLUMN id SET DEFAULT nextval('public.provider_earnings_id_seq'::regclass); + + +-- +-- Name: provider_floor_draws id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_floor_draws ALTER COLUMN id SET DEFAULT nextval('public.provider_floor_draws_id_seq'::regclass); + + +-- +-- Name: provider_log_reports id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_log_reports ALTER COLUMN id SET DEFAULT nextval('public.provider_log_reports_id_seq'::regclass); + + +-- +-- Name: provider_payouts id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_payouts ALTER COLUMN id SET DEFAULT nextval('public.provider_payouts_id_seq'::regclass); + + +-- +-- Name: provider_sessions id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_sessions ALTER COLUMN id SET DEFAULT nextval('public.provider_sessions_id_seq'::regclass); + + +-- +-- Name: request_outcomes id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_outcomes ALTER COLUMN id SET DEFAULT nextval('public.request_outcomes_id_seq'::regclass); + + +-- +-- Name: request_profiles id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_profiles ALTER COLUMN id SET DEFAULT nextval('public.request_profiles_id_seq'::regclass); + + +-- +-- Name: request_rejections id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_rejections ALTER COLUMN id SET DEFAULT nextval('public.request_rejections_id_seq'::regclass); + + +-- +-- Name: usage id; Type: DEFAULT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.usage ALTER COLUMN id SET DEFAULT nextval('public.usage_id_seq'::regclass); + + +-- +-- Name: api_keys api_keys_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.api_keys + ADD CONSTRAINT api_keys_pkey PRIMARY KEY (key_hash); + + +-- +-- Name: app_attest_build_qualifications app_attest_build_qualifications_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_build_qualifications + ADD CONSTRAINT app_attest_build_qualifications_pkey PRIMARY KEY (binary_hash); + + +-- +-- Name: app_attest_enrollments app_attest_enrollments_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_enrollments + ADD CONSTRAINT app_attest_enrollments_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_evidence_blobs app_attest_evidence_blobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_evidence_blobs + ADD CONSTRAINT app_attest_evidence_blobs_pkey PRIMARY KEY (evidence_id); + + +-- +-- Name: app_attest_evidence app_attest_evidence_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_evidence + ADD CONSTRAINT app_attest_evidence_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_key_revocations app_attest_key_revocations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_key_revocations + ADD CONSTRAINT app_attest_key_revocations_pkey PRIMARY KEY (key_id); + + +-- +-- Name: app_attest_key_rotations app_attest_key_rotations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_key_rotations + ADD CONSTRAINT app_attest_key_rotations_pkey PRIMARY KEY (key_id); + + +-- +-- Name: app_attest_receipt_blobs app_attest_receipt_blobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_blobs + ADD CONSTRAINT app_attest_receipt_blobs_pkey PRIMARY KEY (receipt_id); + + +-- +-- Name: app_attest_receipt_jobs app_attest_receipt_jobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_jobs + ADD CONSTRAINT app_attest_receipt_jobs_pkey PRIMARY KEY (key_id); + + +-- +-- Name: app_attest_receipts app_attest_receipts_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipts + ADD CONSTRAINT app_attest_receipts_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_shadow_events app_attest_shadow_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_shadow_events + ADD CONSTRAINT app_attest_shadow_events_pkey PRIMARY KEY (id); + + +-- +-- Name: app_attest_shadow_keys app_attest_shadow_keys_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_shadow_keys + ADD CONSTRAINT app_attest_shadow_keys_pkey PRIMARY KEY (key_id); + + +-- +-- Name: autopilot_events autopilot_events_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.autopilot_events + ADD CONSTRAINT autopilot_events_pkey PRIMARY KEY (command_id, phase); + + +-- +-- Name: balances balances_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.balances + ADD CONSTRAINT balances_pkey PRIMARY KEY (account_id); + + +-- +-- Name: billing_sessions billing_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.billing_sessions + ADD CONSTRAINT billing_sessions_pkey PRIMARY KEY (id); + + +-- +-- Name: cache_routing_demand cache_routing_demand_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.cache_routing_demand + ADD CONSTRAINT cache_routing_demand_pkey PRIMARY KEY (key); + + +-- +-- Name: cache_routing_holders cache_routing_holders_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.cache_routing_holders + ADD CONSTRAINT cache_routing_holders_pkey PRIMARY KEY (key, cache_epoch); + + +-- +-- Name: cache_routing_meta cache_routing_meta_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.cache_routing_meta + ADD CONSTRAINT cache_routing_meta_pkey PRIMARY KEY (name); + + +-- +-- Name: code_attest_push_budgets code_attest_push_budgets_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.code_attest_push_budgets + ADD CONSTRAINT code_attest_push_budgets_pkey PRIMARY KEY (se_pubkey, token_hash); + + +-- +-- Name: code_attestations code_attestations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.code_attestations + ADD CONSTRAINT code_attestations_pkey PRIMARY KEY (se_pubkey); + + +-- +-- Name: darkbloom_machine_aliases darkbloom_machine_aliases_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_aliases + ADD CONSTRAINT darkbloom_machine_aliases_pkey PRIMARY KEY (kind, scope, digest); + + +-- +-- Name: darkbloom_machine_merges darkbloom_machine_merges_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_merges + ADD CONSTRAINT darkbloom_machine_merges_pkey PRIMARY KEY (source_id); + + +-- +-- Name: darkbloom_machine_observations darkbloom_machine_observations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_observations + ADD CONSTRAINT darkbloom_machine_observations_pkey PRIMARY KEY (session_id, observed_at); + + +-- +-- Name: darkbloom_machine_sessions darkbloom_machine_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_sessions + ADD CONSTRAINT darkbloom_machine_sessions_pkey PRIMARY KEY (session_id); + + +-- +-- Name: darkbloom_machines darkbloom_machines_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machines + ADD CONSTRAINT darkbloom_machines_pkey PRIMARY KEY (id); + + +-- +-- Name: device_codes device_codes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.device_codes + ADD CONSTRAINT device_codes_pkey PRIMARY KEY (device_code); + + +-- +-- Name: device_codes device_codes_user_code_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.device_codes + ADD CONSTRAINT device_codes_user_code_key UNIQUE (user_code); + + +-- +-- Name: earnings_summary earnings_summary_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.earnings_summary + ADD CONSTRAINT earnings_summary_pkey PRIMARY KEY (key, key_type); + + +-- +-- Name: fleet_snapshots fleet_snapshots_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.fleet_snapshots + ADD CONSTRAINT fleet_snapshots_pkey PRIMARY KEY (id); + + +-- +-- Name: global_payout_recipients global_payout_recipients_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.global_payout_recipients + ADD CONSTRAINT global_payout_recipients_pkey PRIMARY KEY (account_id); + + +-- +-- Name: global_payout_withdrawals global_payout_withdrawals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.global_payout_withdrawals + ADD CONSTRAINT global_payout_withdrawals_pkey PRIMARY KEY (id); + + +-- +-- Name: inference_routes inference_routes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.inference_routes + ADD CONSTRAINT inference_routes_pkey PRIMARY KEY (id); + + +-- +-- Name: inference_routes inference_routes_request_id_attempt_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.inference_routes + ADD CONSTRAINT inference_routes_request_id_attempt_key UNIQUE (request_id, attempt); + + +-- +-- Name: invite_codes invite_codes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.invite_codes + ADD CONSTRAINT invite_codes_pkey PRIMARY KEY (code); + + +-- +-- Name: invite_redemptions invite_redemptions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.invite_redemptions + ADD CONSTRAINT invite_redemptions_pkey PRIMARY KEY (code, account_id); + + +-- +-- Name: ledger_entries ledger_entries_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.ledger_entries + ADD CONSTRAINT ledger_entries_pkey PRIMARY KEY (id); + + +-- +-- Name: model_active_versions model_active_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_active_versions + ADD CONSTRAINT model_active_versions_pkey PRIMARY KEY (model_id); + + +-- +-- Name: model_aliases model_aliases_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_aliases + ADD CONSTRAINT model_aliases_pkey PRIMARY KEY (alias_id); + + +-- +-- Name: model_demand_collection model_demand_collection_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_collection + ADD CONSTRAINT model_demand_collection_pkey PRIMARY KEY (singleton); + + +-- +-- Name: model_demand_hourly model_demand_hourly_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_hourly + ADD CONSTRAINT model_demand_hourly_pkey PRIMARY KEY (hour, model, consumer_hash); + + +-- +-- Name: model_demand_requests model_demand_requests_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_requests + ADD CONSTRAINT model_demand_requests_id_key UNIQUE (id); + + +-- +-- Name: model_demand_requests model_demand_requests_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_demand_requests + ADD CONSTRAINT model_demand_requests_pkey PRIMARY KEY (coord_request_id); + + +-- +-- Name: model_prices model_prices_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_prices + ADD CONSTRAINT model_prices_pkey PRIMARY KEY (account_id, model); + + +-- +-- Name: model_registry model_registry_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_registry + ADD CONSTRAINT model_registry_pkey PRIMARY KEY (id); + + +-- +-- Name: model_token_grants model_token_grants_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_grants + ADD CONSTRAINT model_token_grants_pkey PRIMARY KEY (account_id, model_id); + + +-- +-- Name: model_token_promotions model_token_promotions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_promotions + ADD CONSTRAINT model_token_promotions_pkey PRIMARY KEY (model_id); + + +-- +-- Name: model_token_provider_carries model_token_provider_carries_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_provider_carries + ADD CONSTRAINT model_token_provider_carries_pkey PRIMARY KEY (account_id); + + +-- +-- Name: model_token_reservations model_token_reservations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_reservations + ADD CONSTRAINT model_token_reservations_pkey PRIMARY KEY (id); + + +-- +-- Name: model_version_files model_version_files_model_version_id_path_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files + ADD CONSTRAINT model_version_files_model_version_id_path_key UNIQUE (model_version_id, path); + + +-- +-- Name: model_version_files model_version_files_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files + ADD CONSTRAINT model_version_files_pkey PRIMARY KEY (id); + + +-- +-- Name: model_versions model_versions_model_id_version_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions + ADD CONSTRAINT model_versions_model_id_version_key UNIQUE (model_id, version); + + +-- +-- Name: model_versions model_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions + ADD CONSTRAINT model_versions_pkey PRIMARY KEY (id); + + +-- +-- Name: payments payments_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.payments + ADD CONSTRAINT payments_pkey PRIMARY KEY (id); + + +-- +-- Name: payments payments_tx_hash_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.payments + ADD CONSTRAINT payments_tx_hash_key UNIQUE (tx_hash); + + +-- +-- Name: provider_earnings provider_earnings_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_earnings + ADD CONSTRAINT provider_earnings_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_floor_draws provider_floor_draws_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_floor_draws + ADD CONSTRAINT provider_floor_draws_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_floor_draws provider_floor_draws_provider_key_epoch_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_floor_draws + ADD CONSTRAINT provider_floor_draws_provider_key_epoch_id_key UNIQUE (provider_key, epoch_id); + + +-- +-- Name: provider_log_reports provider_log_reports_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_log_reports + ADD CONSTRAINT provider_log_reports_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_payouts provider_payouts_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_payouts + ADD CONSTRAINT provider_payouts_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_reputation provider_reputation_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_reputation + ADD CONSTRAINT provider_reputation_pkey PRIMARY KEY (provider_id); + + +-- +-- Name: provider_sessions provider_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_sessions + ADD CONSTRAINT provider_sessions_pkey PRIMARY KEY (id); + + +-- +-- Name: provider_sessions provider_sessions_session_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_sessions + ADD CONSTRAINT provider_sessions_session_id_key UNIQUE (session_id); + + +-- +-- Name: provider_tokens provider_tokens_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_tokens + ADD CONSTRAINT provider_tokens_pkey PRIMARY KEY (token_hash); + + +-- +-- Name: provider_trust_reuse provider_trust_reuse_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_trust_reuse + ADD CONSTRAINT provider_trust_reuse_pkey PRIMARY KEY (se_pubkey); + + +-- +-- Name: provider_verification_jobs provider_verification_jobs_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_verification_jobs + ADD CONSTRAINT provider_verification_jobs_pkey PRIMARY KEY (se_pubkey, task_kind); + + +-- +-- Name: providers providers_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.providers + ADD CONSTRAINT providers_pkey PRIMARY KEY (id); + + +-- +-- Name: publishing_api_keys publishing_api_keys_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.publishing_api_keys + ADD CONSTRAINT publishing_api_keys_pkey PRIMARY KEY (id); + + +-- +-- Name: referrals referrals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrals + ADD CONSTRAINT referrals_pkey PRIMARY KEY (referred_account); + + +-- +-- Name: referrers referrers_code_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrers + ADD CONSTRAINT referrers_code_key UNIQUE (code); + + +-- +-- Name: referrers referrers_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrers + ADD CONSTRAINT referrers_pkey PRIMARY KEY (account_id); + + +-- +-- Name: releases releases_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.releases + ADD CONSTRAINT releases_pkey PRIMARY KEY (version, platform); + + +-- +-- Name: request_outcomes request_outcomes_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_outcomes + ADD CONSTRAINT request_outcomes_id_key UNIQUE (id); + + +-- +-- Name: request_outcomes request_outcomes_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_outcomes + ADD CONSTRAINT request_outcomes_pkey PRIMARY KEY (coord_request_id); + + +-- +-- Name: request_profiles request_profiles_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_profiles + ADD CONSTRAINT request_profiles_pkey PRIMARY KEY (id); + + +-- +-- Name: request_profiles request_profiles_request_id_attempt_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_profiles + ADD CONSTRAINT request_profiles_request_id_attempt_key UNIQUE (request_id, attempt); + + +-- +-- Name: request_rejections request_rejections_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.request_rejections + ADD CONSTRAINT request_rejections_pkey PRIMARY KEY (id); + + +-- +-- Name: schema_migrations schema_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.schema_migrations + ADD CONSTRAINT schema_migrations_pkey PRIMARY KEY (id); + + +-- +-- Name: stripe_withdrawals stripe_withdrawals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.stripe_withdrawals + ADD CONSTRAINT stripe_withdrawals_pkey PRIMARY KEY (id); + + +-- +-- Name: usage usage_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.usage + ADD CONSTRAINT usage_pkey PRIMARY KEY (id); + + +-- +-- Name: usage_totals usage_totals_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.usage_totals + ADD CONSTRAINT usage_totals_pkey PRIMARY KEY (id); + + +-- +-- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_pkey PRIMARY KEY (account_id); + + +-- +-- Name: users users_privy_user_id_key; Type: CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_privy_user_id_key UNIQUE (privy_user_id); + + +-- +-- Name: app_attest_evidence_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_key ON public.app_attest_evidence USING btree (key_id, received_at DESC); + + +-- +-- Name: app_attest_evidence_pending; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_pending ON public.app_attest_evidence USING btree (received_at) WHERE (outcome = 'pending'::text); + + +-- +-- Name: app_attest_evidence_session; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_session ON public.app_attest_evidence USING btree (session_id, received_at DESC); + + +-- +-- Name: app_attest_evidence_time; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_evidence_time ON public.app_attest_evidence USING btree (received_at DESC); + + +-- +-- Name: app_attest_key_rotations_machine; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_key_rotations_machine ON public.app_attest_key_rotations USING btree (machine_id, requested_at DESC); + + +-- +-- Name: app_attest_receipts_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_receipts_key ON public.app_attest_receipts USING btree (key_id, received_at DESC); + + +-- +-- Name: app_attest_receipts_recovery; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_receipts_recovery ON public.app_attest_receipts USING btree (key_id, received_at DESC) WHERE (outcome = 'receipt_creation_time'::text); + + +-- +-- Name: app_attest_shadow_events_session; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_shadow_events_session ON public.app_attest_shadow_events USING btree (session_id, observed_at DESC); + + +-- +-- Name: app_attest_shadow_events_time; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX app_attest_shadow_events_time ON public.app_attest_shadow_events USING btree (observed_at DESC); + + +-- +-- Name: autopilot_events_at; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX autopilot_events_at ON public.autopilot_events USING btree (at); + + +-- +-- Name: darkbloom_machine_sessions_machine; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machine_sessions_machine ON public.darkbloom_machine_sessions USING btree (machine_id, last_seen DESC); + + +-- +-- Name: darkbloom_machine_sessions_open; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machine_sessions_open ON public.darkbloom_machine_sessions USING btree (last_seen, session_id) WHERE (disconnected_at IS NULL); + + +-- +-- Name: darkbloom_machine_sessions_seen; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machine_sessions_seen ON public.darkbloom_machine_sessions USING btree (last_seen DESC); + + +-- +-- Name: darkbloom_machines_merged_into; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX darkbloom_machines_merged_into ON public.darkbloom_machines USING btree (merged_into) WHERE (merged_into IS NOT NULL); + + +-- +-- Name: global_payout_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX global_payout_account ON public.global_payout_withdrawals USING btree (account_id, submitted_at DESC); + + +-- +-- Name: global_payout_external_id; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX global_payout_external_id ON public.global_payout_withdrawals USING btree (external_id) WHERE (external_id <> ''::text); + + +-- +-- Name: global_payout_quote_expiry; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX global_payout_quote_expiry ON public.global_payout_withdrawals USING btree (expires_at) WHERE (status = 'quoted'::text); + + +-- +-- Name: global_payout_reconcile; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX global_payout_reconcile ON public.global_payout_withdrawals USING btree (checked_at) WHERE (status = ANY (ARRAY['pending'::text, 'processing'::text, 'posted'::text])); + + +-- +-- Name: idx_api_keys_id; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_api_keys_id ON public.api_keys USING btree (id) WHERE (id <> ''::text); + + +-- +-- Name: idx_api_keys_owner; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_api_keys_owner ON public.api_keys USING btree (owner_account_id) WHERE (owner_account_id <> ''::text); + + +-- +-- Name: idx_billing_sessions_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_billing_sessions_account ON public.billing_sessions USING btree (account_id); + + +-- +-- Name: idx_billing_sessions_external; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_billing_sessions_external ON public.billing_sessions USING btree (external_id); + + +-- +-- Name: idx_cache_routing_demand_seen; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_cache_routing_demand_seen ON public.cache_routing_demand USING btree (seen_at); + + +-- +-- Name: idx_cache_routing_holders_expires; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_cache_routing_holders_expires ON public.cache_routing_holders USING btree (expires_at); + + +-- +-- Name: idx_cache_routing_holders_updated; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_cache_routing_holders_updated ON public.cache_routing_holders USING btree (updated_at); + + +-- +-- Name: idx_code_attest_push_budgets_due; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_code_attest_push_budgets_due ON public.code_attest_push_budgets USING btree (next_push_at); + + +-- +-- Name: idx_device_codes_user; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_device_codes_user ON public.device_codes USING btree (user_code); + + +-- +-- Name: idx_fleet_snapshots_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_fleet_snapshots_provider ON public.fleet_snapshots USING btree (provider_id, sampled_at DESC); + + +-- +-- Name: idx_fleet_snapshots_sampled; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_fleet_snapshots_sampled ON public.fleet_snapshots USING btree (sampled_at DESC); + + +-- +-- Name: idx_floor_draws_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_floor_draws_account ON public.provider_floor_draws USING btree (account_id, epoch_id); + + +-- +-- Name: idx_floor_draws_epoch; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_floor_draws_epoch ON public.provider_floor_draws USING btree (epoch_id); + + +-- +-- Name: idx_inference_routes_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_created ON public.inference_routes USING btree (created_at DESC); + + +-- +-- Name: idx_inference_routes_model; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_model ON public.inference_routes USING btree (model, created_at DESC); + + +-- +-- Name: idx_inference_routes_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_provider ON public.inference_routes USING btree (provider_id, created_at DESC); + + +-- +-- Name: idx_inference_routes_request; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_inference_routes_request ON public.inference_routes USING btree (request_id); + + +-- +-- Name: idx_ledger_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_ledger_account ON public.ledger_entries USING btree (account_id, created_at DESC); + + +-- +-- Name: idx_ledger_reward; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_ledger_reward ON public.ledger_entries USING btree (account_id, created_at DESC) WHERE (entry_type = ANY (ARRAY['referral_reward'::text, 'admin_reward'::text])); + + +-- +-- Name: idx_model_demand_received; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_demand_received ON public.model_demand_requests USING btree (received_at); + + +-- +-- Name: idx_model_registry_status; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_registry_status ON public.model_registry USING btree (status); + + +-- +-- Name: idx_model_token_reservations_open; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_token_reservations_open ON public.model_token_reservations USING btree (touched_at) WHERE (state = 'reserved'::text); + + +-- +-- Name: idx_model_version_files_version; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_version_files_version ON public.model_version_files USING btree (model_version_id); + + +-- +-- Name: idx_model_versions_model; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_model_versions_model ON public.model_versions USING btree (model_id); + + +-- +-- Name: idx_provider_earnings_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_earnings_account ON public.provider_earnings USING btree (account_id, created_at DESC); + + +-- +-- Name: idx_provider_earnings_created_at_brin; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_earnings_created_at_brin ON public.provider_earnings USING brin (created_at) WITH (autosummarize='on'); + + +-- +-- Name: idx_provider_earnings_job; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_provider_earnings_job ON public.provider_earnings USING btree (job_id) WHERE (job_id <> ''::text); + + +-- +-- Name: idx_provider_earnings_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_earnings_provider ON public.provider_earnings USING btree (provider_key, created_at DESC); + + +-- +-- Name: idx_provider_payouts_address; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_payouts_address ON public.provider_payouts USING btree (provider_address, created_at DESC); + + +-- +-- Name: idx_provider_payouts_settled; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_payouts_settled ON public.provider_payouts USING btree (settled, created_at DESC); + + +-- +-- Name: idx_provider_sessions_connected; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_connected ON public.provider_sessions USING btree (connected_at DESC); + + +-- +-- Name: idx_provider_sessions_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_key ON public.provider_sessions USING btree (provider_key, connected_at) WHERE (provider_key <> ''::text); + + +-- +-- Name: idx_provider_sessions_open; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_open ON public.provider_sessions USING btree (connected_at) WHERE (disconnected_at IS NULL); + + +-- +-- Name: idx_provider_sessions_serial; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_sessions_serial ON public.provider_sessions USING btree (serial_number, connected_at DESC); + + +-- +-- Name: idx_provider_tokens_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_tokens_account ON public.provider_tokens USING btree (account_id); + + +-- +-- Name: idx_provider_verification_jobs_claim; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_verification_jobs_claim ON public.provider_verification_jobs USING btree (claim_expires_at) WHERE (claim_owner <> ''::text); + + +-- +-- Name: idx_provider_verification_jobs_due; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_provider_verification_jobs_due ON public.provider_verification_jobs USING btree (priority, next_attempt_at) WHERE (task_state = ANY (ARRAY['pending'::text, 'backoff'::text])); + + +-- +-- Name: idx_providers_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_account ON public.providers USING btree (account_id, last_seen DESC) WHERE (account_id <> ''::text); + + +-- +-- Name: idx_providers_restore_se_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_restore_se_key ON public.providers USING btree (se_public_key, last_seen DESC, id DESC) WHERE (se_public_key <> ''::text); + + +-- +-- Name: idx_providers_restore_serial; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_restore_serial ON public.providers USING btree (serial_number, last_seen DESC, id DESC) WHERE (serial_number <> ''::text); + + +-- +-- Name: idx_providers_serial; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_providers_serial ON public.providers USING btree (serial_number) WHERE (serial_number <> ''::text); + + +-- +-- Name: idx_publishing_api_keys_hash; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_publishing_api_keys_hash ON public.publishing_api_keys USING btree (key_hash); + + +-- +-- Name: idx_referrals_code; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_referrals_code ON public.referrals USING btree (referrer_code); + + +-- +-- Name: idx_referrers_code; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_referrers_code ON public.referrers USING btree (code); + + +-- +-- Name: idx_request_outcomes_received; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_outcomes_received ON public.request_outcomes USING btree (received_at, coord_request_id); + + +-- +-- Name: idx_request_profiles_coord; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_profiles_coord ON public.request_profiles USING btree (coord_request_id); + + +-- +-- Name: idx_request_profiles_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_profiles_created ON public.request_profiles USING btree (created_at DESC); + + +-- +-- Name: idx_request_profiles_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_profiles_provider ON public.request_profiles USING btree (provider_id, created_at DESC); + + +-- +-- Name: idx_request_rejections_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_created ON public.request_rejections USING btree (created_at DESC); + + +-- +-- Name: idx_request_rejections_model; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_model ON public.request_rejections USING btree (resolved_model, created_at DESC); + + +-- +-- Name: idx_request_rejections_reason; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_reason ON public.request_rejections USING btree (reason_code, created_at DESC); + + +-- +-- Name: idx_request_rejections_servable; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_servable ON public.request_rejections USING btree (could_have_served, created_at DESC) WHERE (could_have_served = true); + + +-- +-- Name: idx_request_rejections_status; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_request_rejections_status ON public.request_rejections USING btree (http_status, created_at DESC); + + +-- +-- Name: idx_stripe_withdrawals_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_account ON public.stripe_withdrawals USING btree (account_id, created_at DESC); + + +-- +-- Name: idx_stripe_withdrawals_payout; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_stripe_withdrawals_payout ON public.stripe_withdrawals USING btree (payout_id) WHERE (payout_id <> ''::text); + + +-- +-- Name: idx_stripe_withdrawals_status; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_status ON public.stripe_withdrawals USING btree (status, created_at); + + +-- +-- Name: idx_stripe_withdrawals_stripe_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_stripe_account ON public.stripe_withdrawals USING btree (stripe_account_id, status); + + +-- +-- Name: idx_stripe_withdrawals_sweep_payout; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_stripe_withdrawals_sweep_payout ON public.stripe_withdrawals USING btree (sweep_payout_id) WHERE (sweep_payout_id <> ''::text); + + +-- +-- Name: idx_stripe_withdrawals_transfer; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_stripe_withdrawals_transfer ON public.stripe_withdrawals USING btree (transfer_id) WHERE (transfer_id <> ''::text); + + +-- +-- Name: idx_usage_consumer; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_consumer ON public.usage USING btree (consumer_key_hash, created_at DESC); + + +-- +-- Name: idx_usage_created; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_created ON public.usage USING btree (created_at DESC); + + +-- +-- Name: idx_usage_key; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_key ON public.usage USING btree (key_id, created_at DESC) WHERE (key_id <> ''::text); + + +-- +-- Name: idx_usage_provider; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_provider ON public.usage USING btree (provider_id, created_at DESC); + + +-- +-- Name: idx_usage_request_location_notnull; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX idx_usage_request_location_notnull ON public.usage USING btree (created_at DESC) WHERE (request_location IS NOT NULL); + + +-- +-- Name: idx_users_privy; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_users_privy ON public.users USING btree (privy_user_id); + + +-- +-- Name: idx_users_stripe_account; Type: INDEX; Schema: public; Owner: - +-- + +CREATE UNIQUE INDEX idx_users_stripe_account ON public.users USING btree (stripe_account_id) WHERE (stripe_account_id <> ''::text); + + +-- +-- Name: inference_routes clear_legacy_cache_affinity_key; Type: TRIGGER; Schema: public; Owner: - +-- + +CREATE TRIGGER clear_legacy_cache_affinity_key BEFORE INSERT OR UPDATE OF cache_affinity_key ON public.inference_routes FOR EACH ROW EXECUTE FUNCTION public.clear_legacy_cache_affinity_key(); + + +-- +-- Name: provider_log_reports clear_provider_log_report_serial; Type: TRIGGER; Schema: public; Owner: - +-- + +CREATE TRIGGER clear_provider_log_report_serial BEFORE INSERT OR UPDATE OF serial_number ON public.provider_log_reports FOR EACH ROW EXECUTE FUNCTION public.clear_provider_log_report_serial(); + + +-- +-- Name: model_demand_requests model_demand_rollup; Type: TRIGGER; Schema: public; Owner: - +-- + +CREATE TRIGGER model_demand_rollup AFTER INSERT OR UPDATE ON public.model_demand_requests FOR EACH ROW EXECUTE FUNCTION public.update_model_demand_hourly(); + + +-- +-- Name: app_attest_evidence_blobs app_attest_evidence_blobs_evidence_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_evidence_blobs + ADD CONSTRAINT app_attest_evidence_blobs_evidence_id_fkey FOREIGN KEY (evidence_id) REFERENCES public.app_attest_evidence(id); + + +-- +-- Name: app_attest_key_revocations app_attest_key_revocations_key_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_key_revocations + ADD CONSTRAINT app_attest_key_revocations_key_id_fkey FOREIGN KEY (key_id) REFERENCES public.app_attest_shadow_keys(key_id); + + +-- +-- Name: app_attest_receipt_blobs app_attest_receipt_blobs_receipt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_blobs + ADD CONSTRAINT app_attest_receipt_blobs_receipt_id_fkey FOREIGN KEY (receipt_id) REFERENCES public.app_attest_receipts(id); + + +-- +-- Name: app_attest_receipt_jobs app_attest_receipt_jobs_receipt_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.app_attest_receipt_jobs + ADD CONSTRAINT app_attest_receipt_jobs_receipt_id_fkey FOREIGN KEY (receipt_id) REFERENCES public.app_attest_receipts(id); + + +-- +-- Name: darkbloom_machine_aliases darkbloom_machine_aliases_machine_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_aliases + ADD CONSTRAINT darkbloom_machine_aliases_machine_id_fkey FOREIGN KEY (machine_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_merges darkbloom_machine_merges_source_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_merges + ADD CONSTRAINT darkbloom_machine_merges_source_id_fkey FOREIGN KEY (source_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_merges darkbloom_machine_merges_target_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_merges + ADD CONSTRAINT darkbloom_machine_merges_target_id_fkey FOREIGN KEY (target_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_sessions darkbloom_machine_sessions_machine_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_sessions + ADD CONSTRAINT darkbloom_machine_sessions_machine_id_fkey FOREIGN KEY (machine_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machine_sessions darkbloom_machine_sessions_original_machine_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machine_sessions + ADD CONSTRAINT darkbloom_machine_sessions_original_machine_id_fkey FOREIGN KEY (original_machine_id) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: darkbloom_machines darkbloom_machines_merged_into_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.darkbloom_machines + ADD CONSTRAINT darkbloom_machines_merged_into_fkey FOREIGN KEY (merged_into) REFERENCES public.darkbloom_machines(id); + + +-- +-- Name: invite_redemptions invite_redemptions_code_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.invite_redemptions + ADD CONSTRAINT invite_redemptions_code_fkey FOREIGN KEY (code) REFERENCES public.invite_codes(code); + + +-- +-- Name: model_active_versions model_active_versions_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_active_versions + ADD CONSTRAINT model_active_versions_model_id_fkey FOREIGN KEY (model_id) REFERENCES public.model_registry(id) ON DELETE CASCADE; + + +-- +-- Name: model_active_versions model_active_versions_model_version_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_active_versions + ADD CONSTRAINT model_active_versions_model_version_id_fkey FOREIGN KEY (model_version_id) REFERENCES public.model_versions(id) ON DELETE RESTRICT; + + +-- +-- Name: model_token_grants model_token_grants_account_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_grants + ADD CONSTRAINT model_token_grants_account_id_fkey FOREIGN KEY (account_id) REFERENCES public.users(account_id); + + +-- +-- Name: model_token_grants model_token_grants_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_grants + ADD CONSTRAINT model_token_grants_model_id_fkey FOREIGN KEY (model_id) REFERENCES public.model_token_promotions(model_id); + + +-- +-- Name: model_token_reservations model_token_reservations_account_id_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_token_reservations + ADD CONSTRAINT model_token_reservations_account_id_model_id_fkey FOREIGN KEY (account_id, model_id) REFERENCES public.model_token_grants(account_id, model_id); + + +-- +-- Name: model_version_files model_version_files_model_version_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_version_files + ADD CONSTRAINT model_version_files_model_version_id_fkey FOREIGN KEY (model_version_id) REFERENCES public.model_versions(id) ON DELETE CASCADE; + + +-- +-- Name: model_versions model_versions_model_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.model_versions + ADD CONSTRAINT model_versions_model_id_fkey FOREIGN KEY (model_id) REFERENCES public.model_registry(id) ON DELETE CASCADE; + + +-- +-- Name: provider_reputation provider_reputation_provider_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.provider_reputation + ADD CONSTRAINT provider_reputation_provider_id_fkey FOREIGN KEY (provider_id) REFERENCES public.providers(id); + + +-- +-- Name: referrals referrals_referrer_code_fkey; Type: FK CONSTRAINT; Schema: public; Owner: - +-- + +ALTER TABLE ONLY public.referrals + ADD CONSTRAINT referrals_referrer_code_fkey FOREIGN KEY (referrer_code) REFERENCES public.referrers(code); + + +-- +-- PostgreSQL database dump complete +-- + + diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 7eaa51375f..3d57fbbd89 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -129,6 +129,10 @@ PostgreSQL URL; there is no memory-store fallback or schema-skip mode. | 3 | `ensureProviderRestoreIndexes` (`coordinator/store/postgres_startup.go`) | Builds the two provider-restore indexes `CONCURRENTLY`. | | 4 | `ensureProviderEarningsJobIndex` (`coordinator/store/postgres.go`) | Builds the `provider_earnings(job_id)` unique index `CONCURRENTLY`. | | 5 | `ensureProviderEarningsWindowIndex` (`coordinator/store/postgres_earnings_window_index.go`) | Builds the BRIN time index and sets the analyze cadence. | +| 6–12 | `00006_…` to `00012_…` | One `CONCURRENTLY` index per file for account erasure: `account_id` on `provider_sessions`, `provider_log_reports`, `device_codes`, `darkbloom_machine_sessions`, `model_token_reservations`; `consumer_key_hash` on `inference_routes` and `request_rejections`. | +| 13 | `00013_soft_delete_columns.sql` | Adds `deleted_at TIMESTAMPTZ` (nullable, no default) to `users`, `api_keys`, `providers`, `provider_tokens`. | +| 14–16 | `00014_…` to `00016_…` | Replaces the full unique key on `users.privy_user_id` with the partial unique index `idx_users_privy_live` (`WHERE deleted_at IS NULL`); drops `users_privy_user_id_key` and `idx_users_privy`. | +| 17 | `00017_referrals_referrer_code_cascade.sql` | Replaces the `referrals.referrer_code` foreign key with `referrals_referrer_code_cascade_fkey` (`ON UPDATE CASCADE`), added `NOT VALID` and then validated. | Versions 2 to 5 are Go migrations (`goMigrations`). They keep the code they had before goose and run on the store pool. The SQL migrations run on a separate @@ -137,9 +141,29 @@ two-connection pool whose sessions set `lock_timeout` to 3 s and `migrationStatementTimeout`); a value set in the database URL wins. A DDL statement that cannot get its lock in time fails instead of queueing every later query on the table behind it, and `migrate` runs goose again, up to three -attempts. Goose holds a session advisory lock while it applies versions, so -two coordinators that start together take turns: one applies, the other then -finds nothing to apply. Out-of-order versions are refused. +attempts. A `CONCURRENTLY` statement blocks no reads or writes but waits for +every older snapshot in the database, so those files raise `lock_timeout` to +1 min for their own statements and reset it after. Each of them first drops an +invalid index that an interrupted attempt left behind. Goose holds a session +advisory lock while it applies versions, so two coordinators that start +together take turns: one applies, the other then finds nothing to apply. +Out-of-order versions are refused. + +### Soft-deleted rows + +A row in `users`, `api_keys`, `providers` or `provider_tokens` whose +`deleted_at` is set belongs to an erased account. Every read that returns a +live user, key, provider record or provider token filters +`deleted_at IS NULL`, in both `PostgresStore` and `MemoryStore` (the +`DeletedAt` fields, never serialized). That covers user lookups by account, +Privy ID, Stripe account and email; promotion claims; key authentication, +listing, lookup, update and rotation; provider token lookup; provider record, +MDA chain, account listing, restore (`GetProviderForRestore`) and machine +continuity history; usage-flow provider locations; and the machine-inventory +backfill. Writes and hard deletes do not filter. No code sets `deleted_at` yet; +account erasure will, and it must also invalidate the `CachedStore` user +cache. A Privy user ID is unique among live users only, so a person can sign up +again after erasure. `coordinator/store/schema/schema.sql` is the `pg_dump --schema-only` of the schema the migrations build, without `goose_db_version`. @@ -326,7 +350,11 @@ KV blocks under a per-model key, not tokens. migrations in the baseline commit their `schema_migrations` marker in the same statement or transaction as their update (`coordinator/store/schema/migrations/00001_baseline.sql`). -4. **Boot never holds a long lock on a hot table.** The +4. **A soft-deleted row is never returned as live.** Reads of `users`, + `api_keys`, `providers` and `provider_tokens` filter `deleted_at IS NULL` + (`coordinator/store/soft_delete_reads_test.go` covers each read on both + stores). +5. **Boot never holds a long lock on a hot table.** The `provider_earnings(job_id)` unique index is built `CONCURRENTLY`, only after a duplicate check, and skipped when already valid; the dedupe that violated this lives in `coordinator/store/migrations/dedupe_provider_earnings.sql` and @@ -337,16 +365,16 @@ KV blocks under a per-model key, not tokens. `autovacuum_analyze_scale_factor` is `0.005` so planner statistics track ingestion (`ensureProviderEarningsWindowIndex`, `coordinator/store/postgres_earnings_window_index.go`). -5. **Money is micro-USD integers in an append-only ledger.** `LedgerStore` +6. **Money is micro-USD integers in an append-only ledger.** `LedgerStore` and `balances` never store floats; see [`billing.md#invariants`](billing.md#invariants). -6. **Nothing prompt-derived is persisted.** `TelemetryStore` rows carry token +7. **Nothing prompt-derived is persisted.** `TelemetryStore` rows carry token counts, timings and outcomes only; the `serial_number` column of `provider_log_reports` and the legacy `cache_affinity_key` column are kept empty by the triggers `clear_provider_log_report_serial` and `clear_legacy_cache_affinity_key` (`coordinator/store/schema/migrations/00001_baseline.sql`). -7. **Provider secrets never leave the Keychain in the clear.** The KV KEK is +8. **Provider secrets never leave the Keychain in the clear.** The KV KEK is wrapped by a Secure Enclave key and the SSD cache is unreadable without it (`provider-swift/Sources/ProviderCore/KVCache/WrappedKEKStorage.swift`). @@ -357,6 +385,7 @@ KV blocks under a per-model key, not tokens. | Coordinator exits 1 at boot with `store: run migrations` | A migration failed (permissions, a hand-edited schema, or a lock still held after three `lock_timeout` attempts) | The failed `postgres migration` version in the log; `pg_stat_activity` for blockers. | | Boot fails with `missing (out-of-order) migration` | A version below the database's highest was never applied, for example two branches added migrations and the higher one deployed first | `SELECT * FROM goose_db_version`; renumber the unapplied migration above the highest applied version. | | Boot fails with `found duplicate migration version` | Two migration files use the same number | Renumber one of them. | +| A coordinator built before goose fails to boot with a unique-violation on `idx_users_privy` | It replays its boot DDL, whose non-concurrent `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy` fails once a soft-deleted and a live user share a Privy ID | Roll back only to images built with goose; see the [deployment rollback](../operations/coordinator-deploy.md#rollback). | | Boot fails with `database holds data that retired backfills never processed` or `balances.withdrawable_micro_usd is missing` | The database has billing, usage or earnings history but never ran a backfill retired after v0.9.10 | Boot a coordinator built from v0.9.10 (which still runs them) against it once, then redeploy (`checkRetiredBackfills`). | | Boot fails with an actionable `provider_earnings` duplicate message | Rows share a non-empty `job_id`, so the unique index cannot be built | Run `dedupe_provider_earnings.sql` offline, then redeploy. | | `EIGENINFERENCE_DATABASE_URL is required in production` | No DSN and no memory-store opt-in | The environment file; see [`../operations/coordinator-deploy.md`](../operations/coordinator-deploy.md). | diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index 392298f22f..8d4f95c281 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -29,11 +29,24 @@ mechanism is explained in ALTER TABLE providers ADD COLUMN example TEXT; ``` - Goose runs the file in one transaction. Put `-- +goose NO TRANSACTION` at - the top for `CREATE INDEX CONCURRENTLY` or `DROP INDEX CONCURRENTLY`, and - use one such statement per file. Wrap a statement that contains `;` (a - `DO` block or a function body) in `-- +goose StatementBegin` and + Goose runs the file in one transaction. Wrap a statement that contains `;` + (a `DO` block or a function body) in `-- +goose StatementBegin` and `-- +goose StatementEnd`. + + For an index on a table that has data, build one index per file, outside a + transaction, and drop an invalid index that an interrupted attempt left: + + ```sql + -- +goose NO TRANSACTION + -- +goose Up + SET lock_timeout = '1min'; + DROP INDEX CONCURRENTLY IF EXISTS idx_example_account; + CREATE INDEX CONCURRENTLY idx_example_account ON example (account_id); + RESET lock_timeout; + ``` + + A `CONCURRENTLY` build waits for every older snapshot in the database, so + the 3 s session `lock_timeout` would cancel it behind any long query. 3. Keep each statement short and lock-safe. The migration session sets `lock_timeout` to 3 s and `statement_timeout` to 10 min. Add a column without a volatile default; add a constraint `NOT VALID`, then `VALIDATE` diff --git a/docs/operations/coordinator-deploy.md b/docs/operations/coordinator-deploy.md index 599a4c02e3..3f4b3e231b 100644 --- a/docs/operations/coordinator-deploy.md +++ b/docs/operations/coordinator-deploy.md @@ -430,9 +430,14 @@ Registry for diagnosis. Providers reconnect on their own; the live registry is in-process and rebuilt from reconnects, durable state is in Cloud SQL and on the persistent disk. -A previous image built before goose boots on a goose-migrated database: it runs -its own boot DDL and ignores `goose_db_version`. An older goose image applies -nothing, because every version it knows is already recorded. +An older goose image applies nothing on a newer database, because every +version it knows is already recorded. An image built before goose runs its own +boot DDL and ignores `goose_db_version`. That works until the soft-delete +migrations (versions 13 to 16) run: from then on, a soft-deleted user and a +live user can share a Privy ID, and the old boot DDL's non-concurrent +`CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy` fails, so the image cannot +boot. Deploy the goose release and let it run stable before the soft-delete +release ships; after that, every rollback image must be a goose build. ## Environment file From 04cad1043c92614323ac23151f0bf1b8c00bff7b Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 08:33:35 -0500 Subject: [PATCH 05/20] Show the schema test result in the sqlc-check log With -v the CI log shows PASS (or SKIP) for TestMigrationsBuildCheckedInSchema instead of only the package line. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 1a1d4d6581..4112b942a7 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ sqlc-generate: ## Regenerate coordinator/store/storedb from coordinator/store/qu sqlc-check: ## Fail if storedb or coordinator/store/schema/schema.sql is stale (needs DATABASE_URL) @test -n "$$DATABASE_URL" || { echo "sqlc-check: set DATABASE_URL to a disposable Postgres server"; exit 1; } - go test ./coordinator/store -run '^TestMigrationsBuildCheckedInSchema$$' -count=1 + go test ./coordinator/store -run '^TestMigrationsBuildCheckedInSchema$$' -count=1 -v $(SQLC) diff -f $(SQLC_CONFIG) # ---- Prompt-contract sidecar (Rust) --------------------------------------- From 7a634a6004cac5243092de41c2e76a95ff190138 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 08:51:48 -0500 Subject: [PATCH 06/20] Keep the CI Postgres service on 16 Moving it to 17 is outside this change. The schema check compares catalog snapshots, so it does not depend on the server version. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 +- docs/developer/test.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 63fe1b7c12..2c533fa924 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,7 +66,7 @@ jobs: runs-on: blacksmith-16vcpu-ubuntu-2404 services: postgres: - image: postgres:17 + image: postgres:16 env: POSTGRES_USER: testbed POSTGRES_PASSWORD: testbed diff --git a/docs/developer/test.md b/docs/developer/test.md index c36874f716..d2ceb89f4f 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -918,7 +918,7 @@ positive, negative and missing operands in Store tests that need Postgres skip themselves when `DATABASE_URL` is unset (`coordinator/store/harness_test.go`, `testPostgresStore`); CI provides a -`postgres:17` service with user/password/db `testbed`, and runs +`postgres:16` service with user/password/db `testbed`, and runs `make sqlc-check` against it after the tests. The pre-push hook runs `go test $(go list ./... | grep -v /internal/api)` from `coordinator/` to skip the slow WebSocket integration tests; run the full set before merging. @@ -2369,7 +2369,7 @@ token IDs are accepted. | Workflow | Trigger | Jobs (name → what runs) | |---|---|---| -| [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) | push, PR | **Release Integrity** — release/script checks and offline provider CI/cache/routing guards · **Docs Lint** — `scripts/docs-check.sh` · **Coordinator Tests** — `scripts/run-coordinator-tests.py --race --coverprofile` over every package except the top-level `e2e` integration package (`coordinator/internal/e2e` and `e2e/testbed/...` run), isolated API/registry shards and runner guards, with `postgres:17` service, `make sqlc-check` + `gofmt` on tracked Go files outside frozen report evidence; total statement coverage in the job summary, merged `coverage.out` and timing evidence kept 14 days · **Coordinator Lint** — `golangci-lint run` (v2.1.6) · **Prompt Sidecar Tests** — cargo fmt/check/clippy/test on Rust 1.88.0, static musl Docker stage, `verify-prompt-sidecar-linux.sh`, then `cargo llvm-cov` (0.9.1) line coverage in the job summary · **Provider Unit Tests** (macOS 12-vcpu) — full debug test build, matched Metal, serial/fresh-process provider tests and installer checks · **Provider SDK Tests** (independent macOS 12-vcpu) — full nested test build and all required numerical/SDK selectors through checked wrappers · **Provider Prompt Parity** (independent macOS 12-vcpu) — `verify-prompt-parity.sh`, pinned Swift/Go/Rust vectors and sustained sidecar load proof · **Provider Tests** (Linux aggregate) — requires all three provider lanes to succeed · **Swift Build + Cache** — release build of `darkbloom` + `darkbloom-fan-helper` · **Console UI Lint & Build** — Node 22, `npm ci`, lint, vitest, and Next.js build | +| [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) | push, PR | **Release Integrity** — release/script checks and offline provider CI/cache/routing guards · **Docs Lint** — `scripts/docs-check.sh` · **Coordinator Tests** — `scripts/run-coordinator-tests.py --race --coverprofile` over every package except the top-level `e2e` integration package (`coordinator/internal/e2e` and `e2e/testbed/...` run), isolated API/registry shards and runner guards, with `postgres:16` service, `make sqlc-check` + `gofmt` on tracked Go files outside frozen report evidence; total statement coverage in the job summary, merged `coverage.out` and timing evidence kept 14 days · **Coordinator Lint** — `golangci-lint run` (v2.1.6) · **Prompt Sidecar Tests** — cargo fmt/check/clippy/test on Rust 1.88.0, static musl Docker stage, `verify-prompt-sidecar-linux.sh`, then `cargo llvm-cov` (0.9.1) line coverage in the job summary · **Provider Unit Tests** (macOS 12-vcpu) — full debug test build, matched Metal, serial/fresh-process provider tests and installer checks · **Provider SDK Tests** (independent macOS 12-vcpu) — full nested test build and all required numerical/SDK selectors through checked wrappers · **Provider Prompt Parity** (independent macOS 12-vcpu) — `verify-prompt-parity.sh`, pinned Swift/Go/Rust vectors and sustained sidecar load proof · **Provider Tests** (Linux aggregate) — requires all three provider lanes to succeed · **Swift Build + Cache** — release build of `darkbloom` + `darkbloom-fan-helper` · **Console UI Lint & Build** — Node 22, `npm ci`, lint, vitest, and Next.js build | | [`.github/workflows/integration.yml`](../../.github/workflows/integration.yml) | push to `master`/`main`, PR | **E2E Integration Tests** (macOS, 75 min budget): install Postgres 16, `swift build -c debug`, cargo sidecar build, metallib staging, HF snapshot downloads; lanes: paged @ 8 blocking gate (`TestIntegration\|TestProfile` minus exact-cache) → exact-cache routing paged @ 8 (blocking; explicit SSD opt-in and repeat demand) → default-posture smoke (`EXPECT_KV_BACKEND=contiguous`) | | [`.github/workflows/benchmarks.yml`](../../.github/workflows/benchmarks.yml) | PR, gated by the `benchmarks` environment (manual approval) | **E2E Benchmarks** — `go test ./e2e/ -count=1 -v -timeout 40m -p=1 -run 'TestBenchmark'`, posts `BENCHMARK_MD_PATH` as a PR comment | | [`.github/workflows/release-swift.yml`](../../.github/workflows/release-swift.yml) | tag `v*`, manual | Provider release; see [`../operations/provider-release.md`](../operations/provider-release.md) | From c776d80a97b4c6e8268ce9f17a9acd0699aced33 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 09:29:03 -0500 Subject: [PATCH 07/20] Build migration indexes only through ensureConcurrentIndex A CREATE INDEX CONCURRENTLY in an SQL migration that fails (for example on the 3 s lock_timeout) leaves an invalid index; with IF NOT EXISTS the next attempt skips it and goose records the version. The how-to now shows index builds as Go migrations through ensureConcurrentIndex, and TestSQLMigrationsDoNotBuildIndexesConcurrently fails on an SQL file that builds one. Docs: destructive migrations must wait until no pre-goose fallback image can start; migrations and the baseline repairs run once; the startup diagram shows the unlocked pending check before the advisory lock; the 5 min lock wait and the fail-safe first deploy under long reads. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- coordinator/store/postgres_migrations_test.go | 21 ++++++++++++ docs/architecture/storage.md | 31 +++++++++++++---- docs/developer/database-migrations.md | 34 +++++++++++++++++-- docs/operations/coordinator-deploy.md | 15 ++++++-- 4 files changed, 88 insertions(+), 13 deletions(-) diff --git a/coordinator/store/postgres_migrations_test.go b/coordinator/store/postgres_migrations_test.go index c168ee408e..d5331ff432 100644 --- a/coordinator/store/postgres_migrations_test.go +++ b/coordinator/store/postgres_migrations_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "log/slog" + "regexp" "strings" "sync" "testing" @@ -184,3 +185,23 @@ func TestMigrateRetriesLockTimeout(t *testing.T) { t.Fatalf("migrate did not retry after a lock timeout; logs:\n%s", logs.String()) } } + +// A CREATE INDEX CONCURRENTLY that fails leaves an invalid index, and an +// SQL file's IF NOT EXISTS would then skip it and record the version. Index +// builds therefore run as Go migrations through ensureConcurrentIndex, +// which fails unless the index ends up valid. +func TestSQLMigrationsDoNotBuildIndexesConcurrently(t *testing.T) { + entries, err := migrationFiles.ReadDir(migrationDir) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + b, err := migrationFiles.ReadFile(migrationDir + "/" + entry.Name()) + if err != nil { + t.Fatal(err) + } + if regexp.MustCompile(`(?i)CREATE\s+(UNIQUE\s+)?INDEX\s+CONCURRENTLY`).Match(b) { + t.Errorf("%s builds an index CONCURRENTLY; use a Go migration with ensureConcurrentIndex", entry.Name()) + } + } +} diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 482279a1fb..a149796f9d 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -137,9 +137,25 @@ two-connection pool whose sessions set `lock_timeout` to 3 s and `migrationStatementTimeout`); a value set in the database URL wins. A DDL statement that cannot get its lock in time fails instead of queueing every later query on the table behind it, and `migrate` runs goose again, up to three -attempts. Goose holds a session advisory lock while it applies versions, so -two coordinators that start together take turns: one applies, the other then -finds nothing to apply. Out-of-order versions are refused. +attempts. If a long read query keeps a table busy through all three +attempts, the boot fails before it serves and changes nothing that it has not +recorded; start it again later. + +Goose first checks for pending versions without a lock; that check also +creates `goose_db_version` on a database that has none. When versions are +pending, goose takes a session advisory lock, lists the versions again, and +applies the ones still missing. Two coordinators that start together take +turns: one applies, the other waits for the lock and then finds nothing to +apply. The waiting coordinator gives up after goose's default lock wait of +5 min (60 tries, 5 s apart) and exits 1. Out-of-order versions are refused. + +Each version runs once, so the work in it no longer repeats on every boot. +The repair statements in the baseline (the `api_keys.id` backfill, the +`model_registry` capability fix for `EigenLabs/Qwen3.8-27B-4bit`, the two +`provider_trust_reuse` backfills, the `model_aliases.desired_build` and +`global_payout_withdrawals.expires_at` backfills) and versions 2 to 5 ran at +every start before goose. The current writers already write the repaired +form, so running them once is enough. `coordinator/store/schema/schema.sql` is the `pg_dump --schema-only` of the schema the migrations build, without `goose_db_version`. @@ -229,12 +245,13 @@ historical provider record. flowchart LR A[ReadAppConfig] --> B{DATABASE_URL set?} B -- yes --> C[pgxpool connect + Ping] - C --> L[goose advisory lock] - L --> V{pending versions\nin goose_db_version?} + C --> V{pending versions?\nno lock; creates\ngoose_db_version if missing} V -- none --> G[SeedKey admin key] - V -- some --> D[apply each pending version once:\n1 baseline, 2 retired-backfill guard,\n3-5 CONCURRENTLY indexes] + V -- some --> L[goose advisory lock\nwait up to 5 min] + L --> D[list versions again;\napply each pending version once:\n1 baseline, 2 retired-backfill guard,\n3-5 CONCURRENTLY indexes] D --> G - D -. lock_timeout .-> L + D -. lock_timeout, up to 3 attempts .-> V + L -. lock wait over .-> X B -- no, ALLOW_MEMORY_STORE=true --> H[NewMemory + 15 min pruner] B -- no --> X[exit 1] D -. any error .-> X diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index 2887b17ee6..8771627a61 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -30,15 +30,43 @@ mechanism is explained in ``` Goose runs the file in one transaction. Put `-- +goose NO TRANSACTION` at - the top for `CREATE INDEX CONCURRENTLY` or `DROP INDEX CONCURRENTLY`, and - use one such statement per file. Wrap a statement that contains `;` (a - `DO` block or a function body) in `-- +goose StatementBegin` and + the top for `DROP INDEX CONCURRENTLY`. Wrap a statement that contains `;` + (a `DO` block or a function body) in `-- +goose StatementBegin` and `-- +goose StatementEnd`. + + Do not put `CREATE INDEX CONCURRENTLY` in an SQL file + (`TestSQLMigrationsDoNotBuildIndexesConcurrently` fails). A build that + fails, for example on `lock_timeout`, leaves an invalid index; with + `IF NOT EXISTS` the next attempt skips it and goose records the version + with a broken index. Add a Go migration to `goMigrations` + (`coordinator/store/postgres_migrations.go`) instead: + + ```go + step(6, func(ctx context.Context) error { + return s.ensureConcurrentIndex(ctx, "idx_example_account", + `CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_example_account ON example (account_id)`) + }), + ``` + + `ensureConcurrentIndex` (`coordinator/store/postgres_startup.go`) returns at + once when a valid index exists, refuses an invalid leftover by name (drop it + by hand, then restart), builds the index, and fails unless the result is + valid. The version is recorded only after it succeeds. 3. Keep each statement short and lock-safe. The migration session sets `lock_timeout` to 3 s and `statement_timeout` to 10 min. Add a column without a volatile default; add a constraint `NOT VALID`, then `VALIDATE` it; build indexes on large tables `CONCURRENTLY`. Do not swallow errors in a `DO ... EXCEPTION WHEN others` block: a failure must stop the boot. + + A migration runs once. Nothing in it runs again on later boots, so it + cannot repair rows that a writer keeps producing; fix the writer. + + Do not drop or rename a column, or add `NOT NULL` or another constraint to + a table the baseline creates, while a coordinator image built before goose + can still be started as a rollback target. That image replays its own boot + DDL: `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and its + `DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later + `SET NOT NULL`. 4. Regenerate the schema file from a database built by the migrations: ```bash diff --git a/docs/operations/coordinator-deploy.md b/docs/operations/coordinator-deploy.md index 599a4c02e3..c41103539f 100644 --- a/docs/operations/coordinator-deploy.md +++ b/docs/operations/coordinator-deploy.md @@ -328,7 +328,11 @@ does not answer after ~60 s, or the container exits with `store: run migrations`, suspect a migration behind a DB lock: re-run the `pg_stat_activity` query and `pg_terminate_backend()` the blocker. Goose holds an advisory lock while it migrates, so a second container waits for the -first instead of running the same DDL. +first instead of running the same DDL; after 5 min of waiting it exits 1. +Long read queries can make all three `lock_timeout` attempts fail, most likely +on the first goose deploy, which replays the baseline. That failure is safe: +the coordinator exits before serving and no failed version is recorded. End +the blocker or wait for a quieter moment, then start the container again. ## Verification @@ -431,8 +435,13 @@ Providers reconnect on their own; the live registry is in-process and rebuilt from reconnects, durable state is in Cloud SQL and on the persistent disk. A previous image built before goose boots on a goose-migrated database: it runs -its own boot DDL and ignores `goose_db_version`. An older goose image applies -nothing, because every version it knows is already recorded. +its own boot DDL and ignores `goose_db_version`. That DDL also reapplies its own +schema: `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and its +`DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later +`SET NOT NULL`. So a destructive migration (drop or rename a column, tighten a +constraint on a baseline table) must wait until no pre-goose image can be +started as a fallback. An older goose image applies nothing, because every +version it knows is already recorded. ## Environment file From f829983df4f0427630afa914f98f100562ce5296 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 3 Oct 2026 09:33:51 -0500 Subject: [PATCH 08/20] Build the erase-path indexes as Go migrations Versions 6-12 and 14 were SQL files with DROP ... IF EXISTS and CREATE INDEX CONCURRENTLY. They move to indexMigrations, which build each index through buildConcurrentIndex on a connection of its own with a 1 min lock_timeout: a valid index returns at once, an invalid leftover is dropped and built again, and the migration fails unless the result is valid, so goose never records a broken index. Tests: an invalid leftover of the same name (made by a build that times out behind an older snapshot) is rebuilt and the version recorded; a unique build that cannot succeed fails migrate and leaves its version unrecorded. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- .../store/postgres_migration_indexes.go | 99 +++++++++++++++++ coordinator/store/postgres_migrations.go | 8 +- coordinator/store/postgres_migrations_test.go | 102 ++++++++++++++++++ .../00006_provider_sessions_account_index.sql | 12 --- ...007_provider_log_reports_account_index.sql | 12 --- .../00008_device_codes_account_index.sql | 12 --- ...rkbloom_machine_sessions_account_index.sql | 12 --- ...model_token_reservations_account_index.sql | 12 --- ...ference_routes_consumer_key_hash_index.sql | 12 --- ...est_rejections_consumer_key_hash_index.sql | 12 --- .../00014_users_privy_live_index.sql | 12 --- docs/architecture/storage.md | 16 +-- docs/developer/database-migrations.md | 21 ++-- 13 files changed, 228 insertions(+), 114 deletions(-) create mode 100644 coordinator/store/postgres_migration_indexes.go delete mode 100644 coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql delete mode 100644 coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql delete mode 100644 coordinator/store/schema/migrations/00008_device_codes_account_index.sql delete mode 100644 coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql delete mode 100644 coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql delete mode 100644 coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql delete mode 100644 coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql delete mode 100644 coordinator/store/schema/migrations/00014_users_privy_live_index.sql diff --git a/coordinator/store/postgres_migration_indexes.go b/coordinator/store/postgres_migration_indexes.go new file mode 100644 index 0000000000..f541afba89 --- /dev/null +++ b/coordinator/store/postgres_migration_indexes.go @@ -0,0 +1,99 @@ +package store + +import ( + "context" + "database/sql" + "fmt" + "strconv" + "time" + + "github.com/jackc/pgx/v5" + "github.com/pressly/goose/v3" +) + +// A CONCURRENTLY build blocks no reads or writes, but it waits for every +// older snapshot in the database. The 3 s session lock_timeout of the SQL +// migrations would cancel it behind any longer query, so index migrations +// wait up to a minute. +const concurrentIndexLockTimeout = time.Minute + +// indexMigrations build one index each, CONCURRENTLY, as Go migrations: an +// SQL file cannot check that the index it built is valid. +func (s *PostgresStore) indexMigrations() []*goose.Migration { + index := func(version int64, name, ddl string) *goose.Migration { + return goose.NewGoMigration(version, &goose.GoFunc{ + RunDB: func(ctx context.Context, _ *sql.DB) error { return s.buildConcurrentIndex(ctx, name, ddl) }, + }, nil) + } + return []*goose.Migration{ + // Account erasure finds rows by these columns. + index(6, "idx_provider_sessions_account", `CREATE INDEX CONCURRENTLY idx_provider_sessions_account ON provider_sessions (account_id)`), + index(7, "idx_provider_log_reports_account", `CREATE INDEX CONCURRENTLY idx_provider_log_reports_account ON provider_log_reports (account_id)`), + index(8, "idx_device_codes_account", `CREATE INDEX CONCURRENTLY idx_device_codes_account ON device_codes (account_id)`), + index(9, "idx_darkbloom_machine_sessions_account", `CREATE INDEX CONCURRENTLY idx_darkbloom_machine_sessions_account ON darkbloom_machine_sessions (account_id)`), + index(10, "idx_model_token_reservations_account", `CREATE INDEX CONCURRENTLY idx_model_token_reservations_account ON model_token_reservations (account_id)`), + index(11, "idx_inference_routes_consumer_key_hash", `CREATE INDEX CONCURRENTLY idx_inference_routes_consumer_key_hash ON inference_routes (consumer_key_hash)`), + index(12, "idx_request_rejections_consumer_key_hash", `CREATE INDEX CONCURRENTLY idx_request_rejections_consumer_key_hash ON request_rejections (consumer_key_hash)`), + // A Privy user ID is unique among live users only, so the same person + // can sign up again after an erased account. Versions 15 and 16 drop + // the old full-table unique constraint and index. + index(14, "idx_users_privy_live", `CREATE UNIQUE INDEX CONCURRENTLY idx_users_privy_live ON users (privy_user_id) WHERE deleted_at IS NULL`), + } +} + +// buildConcurrentIndex builds the index name with ddl on a connection of its +// own. It returns at once when a valid index exists. It drops an invalid +// index left by an interrupted attempt and builds again; the goose advisory +// lock keeps another migration run from building the same index meanwhile. +// It fails unless the index ends up valid, so goose never records the +// version with a broken index. +func (s *PostgresStore) buildConcurrentIndex(ctx context.Context, name, ddl string) error { + started := time.Now() + err := s.buildConcurrentIndexOnce(ctx, name, ddl) + logStartupMigration(name, started, err) + return err +} + +func (s *PostgresStore) buildConcurrentIndexOnce(ctx context.Context, name, ddl string) error { + cfg := s.pool.Config().ConnConfig + cfg.RuntimeParams["lock_timeout"] = strconv.FormatInt(concurrentIndexLockTimeout.Milliseconds(), 10) + conn, err := pgx.ConnectConfig(ctx, cfg) + if err != nil { + return fmt.Errorf("store: connect to build index %s: %w", name, err) + } + defer conn.Close(context.WithoutCancel(ctx)) + + exists, valid, err := concurrentIndexState(ctx, conn, name) + if err != nil || valid { + return err + } + // CONCURRENTLY runs outside a transaction, so each statement goes through + // the simple protocol on its own. + run := func(sql string) error { + _, err := conn.PgConn().Exec(ctx, sql).ReadAll() + return err + } + if exists { + if err := run(`DROP INDEX CONCURRENTLY IF EXISTS ` + pgx.Identifier{name}.Sanitize()); err != nil { + return fmt.Errorf("store: drop invalid index %s: %w", name, err) + } + } + if err := run(ddl); err != nil { + return fmt.Errorf("store: create index %s: %w", name, err) + } + if _, valid, err = concurrentIndexState(ctx, conn, name); err != nil || !valid { + return fmt.Errorf("store: index %s did not become valid (query error: %v)", name, err) + } + return nil +} + +// concurrentIndexState reports whether the index name exists in the current +// schema and whether it is valid and ready. +func concurrentIndexState(ctx context.Context, conn *pgx.Conn, name string) (exists, valid bool, err error) { + err = conn.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM pg_index WHERE indexrelid = to_regclass(format('%I.%I', current_schema(), $1::text))), + COALESCE((SELECT indisvalid AND indisready FROM pg_index WHERE indexrelid = to_regclass(format('%I.%I', current_schema(), $1::text))), false)`, name).Scan(&exists, &valid) + if err != nil { + err = fmt.Errorf("store: inspect index %s: %w", name, err) + } + return exists, valid, err +} diff --git a/coordinator/store/postgres_migrations.go b/coordinator/store/postgres_migrations.go index ecbd4984e3..4d1770d0ae 100644 --- a/coordinator/store/postgres_migrations.go +++ b/coordinator/store/postgres_migrations.go @@ -128,7 +128,7 @@ func (s *PostgresStore) newMigrationProvider(db *sql.DB) (*goose.Provider, error goose.WithSessionLocker(locker), goose.WithTableName(migrationVersionTable), goose.WithDisableGlobalRegistry(true), - goose.WithGoMigrations(s.goMigrations()...), + goose.WithGoMigrations(s.allGoMigrations()...), ) if err != nil { return nil, fmt.Errorf("store: create migration provider: %w", err) @@ -153,3 +153,9 @@ func (s *PostgresStore) goMigrations() []*goose.Migration { step(5, s.ensureProviderEarningsWindowIndex), } } + +// allGoMigrations are the pre-goose startup steps, then the +// CONCURRENTLY index builds. +func (s *PostgresStore) allGoMigrations() []*goose.Migration { + return append(s.goMigrations(), s.indexMigrations()...) +} diff --git a/coordinator/store/postgres_migrations_test.go b/coordinator/store/postgres_migrations_test.go index ed612ab65d..aa42465641 100644 --- a/coordinator/store/postgres_migrations_test.go +++ b/coordinator/store/postgres_migrations_test.go @@ -246,3 +246,105 @@ func TestConcurrentIndexMigrationWaitsForOlderSnapshot(t *testing.T) { t.Fatalf("idx_provider_sessions_account valid=%v err=%v", valid, err) } } + +// pendingFrom makes version and every later version pending again. +func pendingFrom(t *testing.T, s *PostgresStore, version int64) { + t.Helper() + if _, err := s.pool.Exec(context.Background(), `DELETE FROM `+migrationVersionTable+` WHERE version_id >= $1`, version); err != nil { + t.Fatal(err) + } +} + +func versionRecorded(t *testing.T, s *PostgresStore, version int64) bool { + t.Helper() + var recorded bool + if err := s.pool.QueryRow(context.Background(), `SELECT EXISTS(SELECT 1 FROM `+migrationVersionTable+` WHERE version_id = $1)`, version).Scan(&recorded); err != nil { + t.Fatal(err) + } + return recorded +} + +// An interrupted CONCURRENTLY build leaves an invalid index of the same name. +// The index migration drops it, builds again, and records the version only +// with a valid index. +func TestIndexMigrationRebuildsInvalidLeftover(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + s, err := NewPostgres(ctx, Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + if _, err := s.pool.Exec(ctx, `DROP INDEX idx_provider_sessions_account`); err != nil { + t.Fatal(err) + } + pendingFrom(t, s, 6) + + // The reviewer's reproduction: a build that times out behind an older + // snapshot fails and leaves an invalid index. + holder := openTestPool(t, databaseURL) + tx, err := holder.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead}) + if err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `SELECT count(*) FROM users`); err != nil { + t.Fatal(err) + } + builder, err := pgx.Connect(ctx, databaseURL) + if err != nil { + t.Fatal(err) + } + if _, err := builder.Exec(ctx, `SET lock_timeout = '200ms'`); err != nil { + t.Fatal(err) + } + if _, err := builder.Exec(ctx, `CREATE INDEX CONCURRENTLY idx_provider_sessions_account ON provider_sessions (account_id)`); err == nil { + t.Fatal("fixture: the build behind an older snapshot did not fail") + } + _ = builder.Close(ctx) + if err := tx.Rollback(ctx); err != nil { + t.Fatal(err) + } + var valid bool + if err := s.pool.QueryRow(ctx, `SELECT indisvalid FROM pg_index WHERE indexrelid = 'idx_provider_sessions_account'::regclass`).Scan(&valid); err != nil || valid { + t.Fatalf("fixture: leftover index valid=%v err=%v, want an invalid index", valid, err) + } + + if err := s.migrate(ctx); err != nil { + t.Fatalf("migrate with an invalid leftover index: %v", err) + } + if err := s.pool.QueryRow(ctx, `SELECT indisvalid FROM pg_index WHERE indexrelid = 'idx_provider_sessions_account'::regclass`).Scan(&valid); err != nil || !valid { + t.Fatalf("idx_provider_sessions_account valid=%v err=%v after migrate", valid, err) + } + if !versionRecorded(t, s, 6) { + t.Fatal("version 6 not recorded after a successful rebuild") + } +} + +// A build that cannot produce a valid index fails the boot, and goose does +// not record the version: here the unique live-user index meets two live +// users with the same Privy ID. +func TestIndexMigrationFailureIsNotRecorded(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + s, err := NewPostgres(ctx, Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + if _, err := s.pool.Exec(ctx, `DROP INDEX idx_users_privy_live`); err != nil { + t.Fatal(err) + } + for _, account := range []string{"first", "second"} { + if _, err := s.pool.Exec(ctx, `INSERT INTO users (account_id, privy_user_id) VALUES ($1, 'did:privy:shared')`, account); err != nil { + t.Fatal(err) + } + } + pendingFrom(t, s, 14) + + if err := s.migrate(ctx); err == nil { + t.Fatal("migrate succeeded although idx_users_privy_live cannot be built") + } + if versionRecorded(t, s, 14) { + t.Fatal("version 14 recorded although its index build failed") + } +} diff --git a/coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql b/coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql deleted file mode 100644 index 70fab1beba..0000000000 --- a/coordinator/store/schema/migrations/00006_provider_sessions_account_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Account erasure finds rows by provider_sessions.account_id. --- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it --- before the next attempt. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_provider_sessions_account; -CREATE INDEX CONCURRENTLY idx_provider_sessions_account ON provider_sessions (account_id); -RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql b/coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql deleted file mode 100644 index 70cc88dd3b..0000000000 --- a/coordinator/store/schema/migrations/00007_provider_log_reports_account_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Account erasure finds rows by provider_log_reports.account_id. --- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it --- before the next attempt. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_provider_log_reports_account; -CREATE INDEX CONCURRENTLY idx_provider_log_reports_account ON provider_log_reports (account_id); -RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00008_device_codes_account_index.sql b/coordinator/store/schema/migrations/00008_device_codes_account_index.sql deleted file mode 100644 index 9d7bff4e18..0000000000 --- a/coordinator/store/schema/migrations/00008_device_codes_account_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Account erasure finds rows by device_codes.account_id. --- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it --- before the next attempt. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_device_codes_account; -CREATE INDEX CONCURRENTLY idx_device_codes_account ON device_codes (account_id); -RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql b/coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql deleted file mode 100644 index 5cf6340c5c..0000000000 --- a/coordinator/store/schema/migrations/00009_darkbloom_machine_sessions_account_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Account erasure finds rows by darkbloom_machine_sessions.account_id. --- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it --- before the next attempt. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_darkbloom_machine_sessions_account; -CREATE INDEX CONCURRENTLY idx_darkbloom_machine_sessions_account ON darkbloom_machine_sessions (account_id); -RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql b/coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql deleted file mode 100644 index a73216903a..0000000000 --- a/coordinator/store/schema/migrations/00010_model_token_reservations_account_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Account erasure finds rows by model_token_reservations.account_id. --- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it --- before the next attempt. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_model_token_reservations_account; -CREATE INDEX CONCURRENTLY idx_model_token_reservations_account ON model_token_reservations (account_id); -RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql b/coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql deleted file mode 100644 index 1f10a10ac2..0000000000 --- a/coordinator/store/schema/migrations/00011_inference_routes_consumer_key_hash_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Account erasure finds rows by inference_routes.consumer_key_hash. --- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it --- before the next attempt. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_inference_routes_consumer_key_hash; -CREATE INDEX CONCURRENTLY idx_inference_routes_consumer_key_hash ON inference_routes (consumer_key_hash); -RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql b/coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql deleted file mode 100644 index cde62cf8d3..0000000000 --- a/coordinator/store/schema/migrations/00012_request_rejections_consumer_key_hash_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- Account erasure finds rows by request_rejections.consumer_key_hash. --- A failed CONCURRENTLY build leaves an invalid index; the DROP removes it --- before the next attempt. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_request_rejections_consumer_key_hash; -CREATE INDEX CONCURRENTLY idx_request_rejections_consumer_key_hash ON request_rejections (consumer_key_hash); -RESET lock_timeout; diff --git a/coordinator/store/schema/migrations/00014_users_privy_live_index.sql b/coordinator/store/schema/migrations/00014_users_privy_live_index.sql deleted file mode 100644 index 10f3b1fe30..0000000000 --- a/coordinator/store/schema/migrations/00014_users_privy_live_index.sql +++ /dev/null @@ -1,12 +0,0 @@ --- A Privy user ID is unique among live users only, so the same person can --- sign up again after an erased account. Versions 15 and 16 drop the old --- full-table unique constraint and index. --- A CONCURRENTLY statement blocks no reads or writes, but it waits for every --- older snapshot in the database; the 3 s session lock_timeout would cancel it --- behind any query that runs longer. It waits up to 1 min instead. --- +goose NO TRANSACTION --- +goose Up -SET lock_timeout = '1min'; -DROP INDEX CONCURRENTLY IF EXISTS idx_users_privy_live; -CREATE UNIQUE INDEX CONCURRENTLY idx_users_privy_live ON users (privy_user_id) WHERE deleted_at IS NULL; -RESET lock_timeout; diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 3d57fbbd89..935cf397e8 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -129,9 +129,9 @@ PostgreSQL URL; there is no memory-store fallback or schema-skip mode. | 3 | `ensureProviderRestoreIndexes` (`coordinator/store/postgres_startup.go`) | Builds the two provider-restore indexes `CONCURRENTLY`. | | 4 | `ensureProviderEarningsJobIndex` (`coordinator/store/postgres.go`) | Builds the `provider_earnings(job_id)` unique index `CONCURRENTLY`. | | 5 | `ensureProviderEarningsWindowIndex` (`coordinator/store/postgres_earnings_window_index.go`) | Builds the BRIN time index and sets the analyze cadence. | -| 6–12 | `00006_…` to `00012_…` | One `CONCURRENTLY` index per file for account erasure: `account_id` on `provider_sessions`, `provider_log_reports`, `device_codes`, `darkbloom_machine_sessions`, `model_token_reservations`; `consumer_key_hash` on `inference_routes` and `request_rejections`. | +| 6–12 | Go: `indexMigrations` (`coordinator/store/postgres_migration_indexes.go`) | One `CONCURRENTLY` index per version for account erasure: `account_id` on `provider_sessions`, `provider_log_reports`, `device_codes`, `darkbloom_machine_sessions`, `model_token_reservations`; `consumer_key_hash` on `inference_routes` and `request_rejections`. | | 13 | `00013_soft_delete_columns.sql` | Adds `deleted_at TIMESTAMPTZ` (nullable, no default) to `users`, `api_keys`, `providers`, `provider_tokens`. | -| 14–16 | `00014_…` to `00016_…` | Replaces the full unique key on `users.privy_user_id` with the partial unique index `idx_users_privy_live` (`WHERE deleted_at IS NULL`); drops `users_privy_user_id_key` and `idx_users_privy`. | +| 14–16 | 14 Go (`indexMigrations`); `00015_…`, `00016_…` | Replaces the full unique key on `users.privy_user_id` with the partial unique index `idx_users_privy_live` (`WHERE deleted_at IS NULL`); drops `users_privy_user_id_key` and `idx_users_privy`. | | 17 | `00017_referrals_referrer_code_cascade.sql` | Replaces the `referrals.referrer_code` foreign key with `referrals_referrer_code_cascade_fkey` (`ON UPDATE CASCADE`), added `NOT VALID` and then validated. | Versions 2 to 5 are Go migrations (`goMigrations`). They keep the code they had @@ -141,10 +141,14 @@ two-connection pool whose sessions set `lock_timeout` to 3 s and `migrationStatementTimeout`); a value set in the database URL wins. A DDL statement that cannot get its lock in time fails instead of queueing every later query on the table behind it, and `migrate` runs goose again, up to three -attempts. A `CONCURRENTLY` statement blocks no reads or writes but waits for -every older snapshot in the database, so those files raise `lock_timeout` to -1 min for their own statements and reset it after. Each of them first drops an -invalid index that an interrupted attempt left behind. Goose holds a session +attempts. Versions 6 to 12 and 14 build indexes `CONCURRENTLY` as Go +migrations (`indexMigrations`, `buildConcurrentIndex` in +`coordinator/store/postgres_migration_indexes.go`), each on a connection of its +own. A `CONCURRENTLY` build blocks no reads or writes but waits for every older +snapshot in the database, so that connection sets `lock_timeout` to 1 min +(`concurrentIndexLockTimeout`). An invalid index left by an interrupted attempt +is dropped and built again, and the version is recorded only when the index is +valid. Goose holds a session advisory lock while it applies versions, so two coordinators that start together take turns: one applies, the other then finds nothing to apply. Out-of-order versions are refused. diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index 8d4f95c281..81d13daa14 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -33,20 +33,19 @@ mechanism is explained in (a `DO` block or a function body) in `-- +goose StatementBegin` and `-- +goose StatementEnd`. - For an index on a table that has data, build one index per file, outside a - transaction, and drop an invalid index that an interrupted attempt left: + Build an index on a table that has data as a Go migration, not in an SQL + file: add it to `indexMigrations` + (`coordinator/store/postgres_migration_indexes.go`): - ```sql - -- +goose NO TRANSACTION - -- +goose Up - SET lock_timeout = '1min'; - DROP INDEX CONCURRENTLY IF EXISTS idx_example_account; - CREATE INDEX CONCURRENTLY idx_example_account ON example (account_id); - RESET lock_timeout; + ```go + index(18, "idx_example_account", `CREATE INDEX CONCURRENTLY idx_example_account ON example (account_id)`), ``` - A `CONCURRENTLY` build waits for every older snapshot in the database, so - the 3 s session `lock_timeout` would cancel it behind any long query. + `buildConcurrentIndex` returns at once when a valid index exists, drops an + invalid leftover of an interrupted attempt, builds the index on its own + connection with a 1 min `lock_timeout` (the build waits for every older + snapshot), and fails unless the result is valid. The version is recorded + only after it succeeds. 3. Keep each statement short and lock-safe. The migration session sets `lock_timeout` to 3 s and `statement_timeout` to 10 min. Add a column without a volatile default; add a constraint `NOT VALID`, then `VALIDATE` From 24bd04f71c954e8d08004796e6b3c4f6f54cf1e3 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sun, 4 Oct 2026 13:12:09 -0500 Subject: [PATCH 09/20] Document the goose schema lifecycle, migration how-to and runbook Add docs/architecture/schema-lifecycle.md as the explanation of how the schema changes: the startup path from NewPostgres through goose, the migration kinds, the locks and timeouts, the retired-backfill guard, invariants, failure modes and a code map. storage.md now links to it instead of holding the migration mechanism. Rewrite docs/developer/database-migrations.md around a decision table, steps for each migration kind, expand and contract in two releases, and the pre-goose fallback rule. Add docs/operations/schema-migration.md: scope, Cloud SQL backup, long query check, --migrate-only with its real log lines, verification queries, troubleshooting, rollback rules and the first cut-over checklist. coordinator-deploy.md links to it. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- docs/AGENTS.md | 4 +- docs/README.md | 8 +- docs/architecture/README.md | 5 +- docs/architecture/components/coordinator.md | 9 +- docs/architecture/schema-lifecycle.md | 247 ++++++++++++++++ docs/architecture/storage.md | 171 +++-------- docs/developer/build.md | 4 +- docs/developer/database-migrations.md | 222 ++++++++++---- docs/operations/README.md | 3 +- docs/operations/coordinator-deploy.md | 92 ++---- .../coordinator-startup-measurement.md | 4 +- docs/operations/schema-migration.md | 271 ++++++++++++++++++ scripts/docs-impact-rules.json | 6 +- 13 files changed, 768 insertions(+), 278 deletions(-) create mode 100644 docs/architecture/schema-lifecycle.md create mode 100644 docs/operations/schema-migration.md diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 1d60ebe8dc..e58fb45aa2 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -1,6 +1,6 @@ # Darkbloom docs — how this documentation is organised and maintained -> Last updated: 2026-09-30 +> Last updated: 2026-10-04 Rules for anyone — human or agent — who reads, writes, or checks a file under `docs/`. The code is the source of truth; a doc that disagrees with the code is @@ -174,7 +174,7 @@ and tests both historical-link handling and date-preserving, idempotent stamping | Experimental model Autopilot policy, rollout or enrollment (`coordinator/registry/autopilot*`, `coordinator/api/autopilot*`, provider runtime/CLI `Autopilot/`) | `architecture/model-autopilot.md`, `operations/model-autopilot.md`; apply the configuration, CLI, protocol and API rows for those surfaces too | | Trust level, attestation, enrollment, encryption | `architecture/security/*.md`; `provider/attestation.md`; `consumer/verification.md`; `threat-model.yaml` | | Pricing, ledger, payouts, referral | `architecture/billing.md`, `reference/pricing-model.md`, `consumer/billing.md` | -| Store schema / migration | `architecture/storage.md` | +| Store schema / migration | `architecture/schema-lifecycle.md` (versions, kinds, locks); `architecture/storage.md` (tables); `operations/schema-migration.md` if the change affects the production procedure or rollback rules | | Provider version bump (`ProviderCore.version` ↔ `LatestProviderVersion`) | `operations/provider-release.md`; `CHANGELOG.md` | | Build, test, CI, or script | `developer/build.md`, `developer/test.md`; `operations/` runbook that invokes it | | New model family or engine capability | `architecture/inference.md`, `consumer/models.md`, `provider/hardware-requirements.md` | diff --git a/docs/README.md b/docs/README.md index e854ada6a5..9ad3575ede 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # Darkbloom documentation -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 > Darkbloom is a decentralized private-inference network: an OpenAI- and > Anthropic-compatible HTTP API served by a Go coordinator that routes each @@ -42,7 +42,8 @@ - [`architecture/prefix-cache.md`](architecture/prefix-cache.md): KV layouts, encrypted SSD checkpoint streaming, exact prefix reuse by model family, and explicit resident-cache modes. - [`architecture/prompt-contract-sidecar.md`](architecture/prompt-contract-sidecar.md): the Rust sidecar that derives token boundaries for cache routing, and its failure isolation. - [`architecture/model-registry.md`](architecture/model-registry.md): model manifests, aliases, publishing, and provider downloads. -- [`architecture/storage.md`](architecture/storage.md): coordinator persistence — Postgres schema, memory store, retention. +- [`architecture/storage.md`](architecture/storage.md): coordinator persistence — Postgres tables, memory store, retention. +- [`architecture/schema-lifecycle.md`](architecture/schema-lifecycle.md): how the Postgres schema changes — goose versions, migration kinds, locks and timeouts, failure modes. - [`architecture/billing.md`](architecture/billing.md): pricing, reservations, ledger, the platform fee (stated only here), Stripe deposits and payouts, referrals, base rewards. - [`architecture/telemetry.md`](architecture/telemetry.md): what telemetry exists, how the Go/Swift/TS mirrors stay symmetric, where it goes. - [`architecture/request-accounting.md`](architecture/request-accounting.md): unsampled incoming-request evidence, coverage, revision semantics, and normalized codes. @@ -104,7 +105,7 @@ - [`developer/navigation.md`](developer/navigation.md): find implementation and tests, choose descriptive filenames, and check path dependencies when moving files. - [`developer/build.md`](developer/build.md): build the coordinator, sidecar, provider, and UIs; toolchain pins. - [`developer/test.md`](developer/test.md): every test suite, what CI runs, how to run the e2e suite. -- [`developer/database-migrations.md`](developer/database-migrations.md): add a numbered goose migration and regenerate the checked-in schema. +- [`developer/database-migrations.md`](developer/database-migrations.md): choose the migration kind, add a numbered goose migration, change a column in two releases, regenerate the checked-in schema. - [`developer/threat-model-review.md`](developer/threat-model-review.md): configure full PR text scans against the threat model and non-blocking author feedback. - [`developer/serving-performance-qualification.md`](developer/serving-performance-qualification.md): measure and review exact serving profiles before promoting concurrency limits or prefill policy. @@ -112,6 +113,7 @@ - [`operations/README.md`](operations/README.md): index and the two rules that apply to every runbook. - [`operations/coordinator-deploy.md`](operations/coordinator-deploy.md): swap the production coordinator to a reviewed build, verify, roll back. +- [`operations/schema-migration.md`](operations/schema-migration.md): back up, check, apply and verify goose migrations in production; the first goose cut-over; rollback rules. - [`operations/dev-environment.md`](operations/dev-environment.md): the GCP dev environment. - [`operations/provider-release.md`](operations/provider-release.md): cut a provider release — version bump, signing, notarization, hashing, registration, `latest/` publish, rollback. - [`operations/cache-routing-rollout.md`](operations/cache-routing-rollout.md): turn cache-aware routing on in production — percent ramp, verification, kill switch back to `off`. diff --git a/docs/architecture/README.md b/docs/architecture/README.md index e5a53b82fd..5b54d9d853 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -1,6 +1,6 @@ # Architecture — how Darkbloom works -> Last updated: 2026-09-28 +> Last updated: 2026-10-04 Explanation pages: context, mechanism, invariants, failure modes, and a code map for each part of the system. The code in `coordinator/`, @@ -65,7 +65,8 @@ how-to and runbook directories listed in [`../README.md`](../README.md). | Page | Concern | |---|---| -| [storage.md](storage.md) | Coordinator persistence: Postgres tables and migrations, memory store, retention jobs | +| [storage.md](storage.md) | Coordinator persistence: Postgres tables, memory store, retention jobs | +| [schema-lifecycle.md](schema-lifecycle.md) | How the Postgres schema changes: goose versions, migration kinds, locks and timeouts, the checked-in schema, failure modes | | [billing.md](billing.md) | Pricing, reservations, ledger, Stripe deposits and Connect payouts, referrals, base rewards | | [telemetry.md](telemetry.md) | What telemetry exists, Go/Swift/TS symmetry, retired client ingestion, Datadog | | [request-outcome-observability.md](request-outcome-observability.md) | Closed outcome taxonomy across client, provider, and billing dimensions | diff --git a/docs/architecture/components/coordinator.md b/docs/architecture/components/coordinator.md index 21163cddd3..0c379ab0a7 100644 --- a/docs/architecture/components/coordinator.md +++ b/docs/architecture/components/coordinator.md @@ -1,6 +1,6 @@ # Coordinator -> Last updated: 2026-09-04 +> Last updated: 2026-10-04 The coordinator is Darkbloom's control plane: one Go HTTP/WebSocket service (binary `coordinator/cmd/coordinator`) that authenticates consumers, picks a @@ -80,8 +80,9 @@ failure in any step marked *fatal* exits the process before it listens. memory-store opt-in, mock billing with a live Stripe key, malformed media fetch or cache-routing values, an unknown trust level). Every variable is listed in [`../../reference/configuration.md`](../../reference/configuration.md). -3. **Store** (*fatal*). Postgres when a DSN is set — connect, ping, run the - idempotent migration slice, seed the admin key — otherwise the memory store +3. **Store** (*fatal*). Postgres when a DSN is set — connect, ping, apply pending + goose migrations ([schema lifecycle](../schema-lifecycle.md)), seed the + admin key — otherwise the memory store with its 15 minute pruner. Provider sessions orphaned by the previous process are closed, best-effort, with a 10 second budget. 4. **Registry.** `registry.New`, trust floor, dedicated models, quality @@ -152,7 +153,7 @@ flowchart TD | Symptom | Likely cause | Where to look | |---|---|---| -| Process exits before binding the port | A `Check` failure, store connect/migration error, missing release inventory, or an unusable trust-reuse journal | The first `Error` log line; [`../storage.md#failure-modes`](../storage.md#failure-modes) | +| Process exits before binding the port | A `Check` failure, store connect/migration error, missing release inventory, or an unusable trust-reuse journal | The first `Error` log line; [`../storage.md#failure-modes`](../storage.md#failure-modes), [`../schema-lifecycle.md#failure-modes`](../schema-lifecycle.md#failure-modes) | | Fleet 429s for minutes after a deploy | Empty registry until providers reconnect and re-attest; release-policy enforcement bites only after its boot grace ([`EIGENINFERENCE_RELEASE_POLICY_ENFORCE_GRACE`](../../reference/configuration.md#release-policy-version-floor-and-binary-hashes)) | [`../../operations/release-policy-rollout.md`](../../operations/release-policy-rollout.md) | | CPU saturation under retry storms | Routing scans per dispatch attempt; bounded by `EIGENINFERENCE_ROUTING_CONCURRENCY` | [`../scheduling.md`](../scheduling.md) | | Streams cut during a restart | Drain grace shorter than the longest generation | `EIGENINFERENCE_DRAIN_GRACE` in [`../../reference/configuration.md`](../../reference/configuration.md) | diff --git a/docs/architecture/schema-lifecycle.md b/docs/architecture/schema-lifecycle.md new file mode 100644 index 0000000000..f099144d6e --- /dev/null +++ b/docs/architecture/schema-lifecycle.md @@ -0,0 +1,247 @@ +# Schema lifecycle + +> Last updated: 2026-10-04 + +Explanation of how the coordinator's Postgres schema changes: numbered goose +migrations that run inside `NewPostgres` before the coordinator serves, the +locks and timeouts around them, and the checked-in schema file that tests +compare against. Read this before you add a migration +([how-to](../developer/database-migrations.md)) or apply one in production +([runbook](../operations/schema-migration.md)). What the tables hold is in +[storage](storage.md). + +## Context + +Before goose, `(*PostgresStore).migrate` ran 255 DDL statements on every boot. +Each statement ran on its own, with no `lock_timeout`, so an `ALTER TABLE` +that waited behind a long query blocked every later query on that table +(the 2026-07-03 outage). Nothing stopped two coordinators from running the +same DDL at once, and repair `UPDATE`s ran again at every start. + +Goose ([`github.com/pressly/goose/v3`](https://github.com/pressly/goose)) +replaces that loop. Each schema change is a numbered version. Goose applies a +version once, records it in `goose_db_version`, and skips it on every later +boot. The 255 statements are version 1, unchanged and in the same order +(`coordinator/store/schema/migrations/00001_baseline.sql`). + +## Mechanism + +### Startup path + +`NewPostgres` (`coordinator/store/postgres.go`) opens the serving pool, pings +it, and calls `migrate` (`coordinator/store/postgres_migrations.go`). It +returns the store only after every pending version has applied. +`coordinator --migrate-only` (`coordinator/cmd/coordinator/maintenance.go`, +`runMaintenanceCommand`) calls the same `NewPostgres` with a 15-minute context +and exits; it seeds no admin key and starts no listener or worker. + +```mermaid +flowchart TD + classDef step fill:#dbeafe,stroke:#1d4ed8,color:#0b1220 + classDef check fill:#fef3c7,stroke:#b45309,color:#1f1300 + classDef ok fill:#dcfce7,stroke:#15803d,color:#052e16 + classDef fail fill:#fee2e2,stroke:#b91c1c,color:#450a0a + A["NewPostgres: parse URL, open pool, Ping"]:::step --> C["migrateOnce: own 2-connection pool
lock_timeout 3 s, statement_timeout 10 min"]:::step + C --> D{"pending versions?
(no lock; creates goose_db_version)"}:::check + D -- "none" --> S["return store"]:::ok + D -- "some" --> L["session advisory lock
(try every 5 s, up to 5 min)"]:::step + L -- "held" --> E["list versions again,
apply each pending version in order,
record each in goose_db_version"]:::step + E -- "all applied" --> S + E -- "SQLSTATE 55P03" --> R{"attempt < 3?"}:::check + R -- "yes: wait 1 s, then 2 s" --> C + R -- "no" --> X["error: store: run migrations
(coordinator exits 1)"]:::fail + E -- "any other error" --> X + L -- "5 min passed" --> X + S --> M["serve
(--migrate-only:
log and exit 0)"]:::ok +``` + +Legend: blue = step, amber = decision, green = success, red = exit 1. + +### Versions + +| Version | Source | What it does | +|---|---|---| +| 1 | `coordinator/store/schema/migrations/00001_baseline.sql` | The 255 statements of the pre-goose boot, in the same order, as one `-- +goose NO TRANSACTION` file. On a schema that a pre-goose coordinator built, every statement is a no-op. | +| 2 | `checkRetiredBackfills` (`coordinator/store/postgres_retired_backfills.go`) | Guards the retired one-shot backfills; see [Version 2](#version-2-the-retired-backfill-guard). | +| 3 | `ensureProviderRestoreIndexes` (`coordinator/store/postgres_startup.go`) | Builds `idx_providers_restore_serial` and `idx_providers_restore_se_key` `CONCURRENTLY` through `ensureConcurrentIndex`. | +| 4 | `ensureProviderEarningsJobIndex` (`coordinator/store/postgres.go`) | Drops an invalid leftover with a plain `DROP INDEX`, fails on duplicate non-empty `job_id`s, then builds the unique `idx_provider_earnings_job` `CONCURRENTLY`. | +| 5 | `ensureProviderEarningsWindowIndex` (`coordinator/store/postgres_earnings_window_index.go`) | Builds the BRIN `idx_provider_earnings_created_at_brin` through `ensureConcurrentIndex` and sets `autovacuum_analyze_scale_factor` to `0.005`. | + +Versions 2 to 5 are Go migrations, listed in `goMigrations`. They are the +startup steps that ran after the old DDL loop, with their code unchanged. +Goose reads SQL files from the embedded `migrationFiles` and refuses two +sources with the same version (`found duplicate migration version`) and an +unapplied version below the highest applied one +(`missing (out-of-order) migration`). + +### Migration kinds + +| Kind | How goose runs it | Why it exists | Example | +|---|---|---|---| +| SQL file (default) | All statements and the `goose_db_version` insert in one transaction, on the connection that holds the advisory lock | A change that must apply completely or not at all | None yet; template in the [how-to](../developer/database-migrations.md) | +| SQL file with `-- +goose NO TRANSACTION` | Each statement (or each `StatementBegin`/`StatementEnd` block) commits on its own; the version is recorded after the last one | A statement that cannot run in a transaction (`DROP INDEX CONCURRENTLY`), or a file whose locks must be held one at a time | Version 1 | +| Go migration (`goose.NewGoMigration` with `RunDB`) | Goose calls the function, then records the version on the second migration connection; no transaction | A step that must read the database before it acts, or check its result | Versions 2 and 4 | +| Concurrent index (Go migration through `ensureConcurrentIndex`) | Checks `pg_index`, builds the index with one simple-protocol statement, then checks that it is valid | `CREATE INDEX CONCURRENTLY` cannot run in a transaction, and a failed build leaves an invalid index that `IF NOT EXISTS` would hide | Versions 3 and 5 | + +An SQL file must not contain `CREATE INDEX CONCURRENTLY` +(`TestSQLMigrationsDoNotBuildIndexesConcurrently` in +`coordinator/store/postgres_migrations_test.go`). A build that fails, for +example on `lock_timeout`, leaves an invalid index; on the next attempt +`IF NOT EXISTS` skips it and goose records the version with a broken index. +`ensureConcurrentIndex` returns at once for a valid index, refuses an invalid +one by name (`index ... is invalid; repair the interrupted concurrent index +build before retrying`), and fails unless the new index is valid and ready. + +### Locks and timeouts + +| Control | Value | Where | Effect | +|---|---|---|---| +| Migration pool | `MaxConns = 2`, `MinConns = 0` | `migrateOnce` | One connection holds the advisory lock and runs SQL migrations; goose records Go migration versions on the other. The serving pool is not used for SQL migrations. | +| `lock_timeout` | `migrationLockTimeout = 3 * time.Second` | `migrateOnce` | A DDL statement that waits for a table lock fails with SQLSTATE `55P03` (`lockNotAvailable`) instead of queueing every later query behind it. | +| `statement_timeout` | `migrationStatementTimeout = 10 * time.Minute` | `migrateOnce` | Upper bound for one statement in the migration session. | +| URL override | a `lock_timeout` or `statement_timeout` parameter in `EIGENINFERENCE_DATABASE_URL` | `migrateOnce` | The URL value wins over both defaults. | +| Retries | `migrationAttempts = 3`; pauses of 1 s and 2 s | `migrate`, `isLockTimeout` | Only a lock timeout is retried. Each attempt opens a new migration pool and starts again from the pending check. | +| Advisory lock | session lock `4097083626` (goose `lock.DefaultLockID`), `pg_try_advisory_lock` every 5 s, 60 retries | `lock.NewPostgresSessionLocker` in `newMigrationProvider` | Two coordinators that start together take turns. The second one gives up after 5 min with `failed to acquire lock`. | +| Go migrations | no session timeouts unless the URL sets them | `goMigrations` run on the store pool | Keeps the pre-goose behaviour of versions 2 to 5: a `CREATE INDEX CONCURRENTLY` that times out leaves an invalid index. | +| `--migrate-only` | `context.WithTimeout(..., 15*time.Minute)` | `runMaintenanceCommand` | The whole run stops after 15 min. The serving path has no such deadline. | + +`CREATE INDEX CONCURRENTLY` blocks no reads or writes, but it waits for every +transaction that holds an older snapshot. On a busy database it can wait for a +long time; see the [runbook](../operations/schema-migration.md#3-check-for-long-running-queries) +for the pre-check. + +### Version 2: the retired-backfill guard + +The one-shot backfills that derived `earnings_summary`, `usage_totals` and +`balances.withdrawable_micro_usd` from history (markers +`backfill_earnings_summary_v1`, `backfill_usage_totals_v1`, +`backfill_withdrawable_balance_v1`) ran in production and are retired after +v0.9.10. The baseline creates `balances` with `withdrawable_micro_usd`. +`checkRetiredBackfills` then guards the first goose boot of a database: + +- it fails if `balances.withdrawable_micro_usd` is missing; +- it records each marker whose source table (`balances`, `usage`, + `provider_earnings`) is empty, because with no history the current schema is + already exact, and v0.9.10 recorded the same markers on an empty database; +- it seeds the single `usage_totals` row only while `usage` is empty; +- it fails if a source table holds rows but its marker is missing, or if the + `usage_totals` row is missing. + +A failed boot writes no marker and no counter for the data it refused, so the +remedy in the error (boot a coordinator built from v0.9.10 once, then this +build) still runs the real backfill. Databases that ran the backfills keep +their markers and their now-unused scratch tables +(`earnings_summary_backfill_pending`, `usage_totals_backfill_state`). + +The Solana-era cleanups are retired the same way: the wallet-keyed price +delete (marker `cleanup_wallet_model_prices_v1`) and the one-time column drops +`billing_sessions.chain`, `users.solana_wallet_address`, +`users.solana_wallet_id` and `releases.image_bridge_hash`. + +### Work that now runs once + +Each version runs once, so its work does not repeat on later boots. The repair +statements in the baseline (the `api_keys.id` backfill, the `model_registry` +capability fix for `EigenLabs/Qwen3.8-27B-4bit`, the two `provider_trust_reuse` +backfills, and the `model_aliases.desired_build` and +`global_payout_withdrawals.expires_at` backfills) and versions 2 to 5 ran at +every start before goose. The current writers write the repaired form, so one +run is enough. A migration cannot repair rows that a writer keeps producing; +fix the writer. + +### The checked-in schema + +`coordinator/store/schema/schema.sql` is the `pg_dump --schema-only +--no-owner --no-privileges` of the schema that the migrations build, without +`goose_db_version`. `TestMigrationsBuildCheckedInSchema` builds a fresh +database with goose and fails when its catalog differs from a database loaded +from that file. `TestMigrationsLeaveLegacyDatabaseUnchanged` loads +`schema.sql` with the marker rows that a pre-goose boot leaves and checks that +versions 1 to 5 change no object and no row. The +[how-to](../developer/database-migrations.md) regenerates the file. + +### Tables and files that are not goose versions + +`schema_migrations` is an older table. It holds the markers of the one-shot +data migrations inside the baseline and of the retired backfills, not goose +versions. Two SQL files under `coordinator/store/migrations/` are applied by +hand with `psql`, never at boot: `dedupe_provider_earnings.sql` (an offline +cleanup that once held a relation lock for about 15 minutes on the production +table) and `request_waterfall.sql` (an analysis view, kept off the boot path +so a `CREATE VIEW` cannot queue behind a long query's lock). +`coordinator/deploy/start.sh` does not touch the database. + +### Logs + +Logs carry bounded labels only, never SQL or parameters +(`logStartupMigration` in `coordinator/store/postgres_startup.go`). + +| Message | Fields | When | +|---|---|---| +| `postgres startup phase` | `phase` (`connect` or an index name), `result`, `duration_ms` | After the ping, and after each index build in versions 3 and 5 | +| `postgres migration hit lock_timeout; retrying` (warn) | `attempt` | Before attempt 2 and 3 | +| `postgres migration` | `version`, `result` (`applied` or `failed`), `duration_ms` | One line per version that goose ran, written after the attempt ends; none when nothing was pending | +| `coordinator migrations complete` | `duration_ms` | `--migrate-only` succeeded | +| `coordinator maintenance command failed` (error) | `error` | `--migrate-only` failed | +| `failed to connect to PostgreSQL` (error) | `error` | The serving path failed in `NewPostgres`, including a failed migration | + +## Invariants + +1. **The coordinator serves only after every pending version applied.** + `NewPostgres` returns an error, and `main` exits 1, when `migrate` fails + (`coordinator/store/postgres.go`, `coordinator/cmd/coordinator/main.go`). +2. **A version applies once.** Goose records it after it succeeds, under the + session advisory lock, and lists versions again after it takes the lock + (`newMigrationProvider` in `coordinator/store/postgres_migrations.go`). + `TestConcurrentMigrationsApplyOnce` runs two migrations at once. +3. **A failed version is not recorded.** A transactional SQL file rolls back + with its version row. A `NO TRANSACTION` file or a Go migration records + the version only after its last statement succeeds. +4. **A migration statement does not wait more than 3 s for a table lock** + unless the database URL sets a longer `lock_timeout` + (`migrationLockTimeout`). `TestMigrateRetriesLockTimeout` holds a lock and + checks the retry. +5. **Migrations build exactly `schema.sql`** on a fresh database + (`TestMigrationsBuildCheckedInSchema`). +6. **There are no down migrations.** No migration file has a + `-- +goose Down` section. A rollback starts an older image on the migrated + schema; it never reverts the schema. +7. **An older goose image applies nothing on a newer database.** Every version + it knows is recorded, and goose ignores recorded versions it does not + know. A pre-goose image ignores `goose_db_version` and replays its own boot + DDL. + +## Failure modes + +| Symptom | Cause | What happens / where to look | +|---|---|---| +| Exit 1 with `partial migration error (type:sql,version:N): ERROR: canceling statement due to lock timeout (SQLSTATE 55P03)` after three `postgres migration hit lock_timeout; retrying` lines | A long query held a lock that version N needed, through all three attempts | Nothing was recorded for version N; a transactional file rolled back. `pg_stat_activity` for the blocker; [runbook](../operations/schema-migration.md#lock-timeout). | +| Exit 1 with `failed to initialize: failed to acquire lock` after 5 min | Another process held the goose advisory lock for the whole lock wait | The holder in `pg_locks` (`objid = 4097083626`); [runbook](../operations/schema-migration.md#a-second-coordinator-waits-on-the-lock). | +| A `NO TRANSACTION` file failed after some statements | Its earlier statements committed; the version is not recorded | The next run executes the whole file again, so every statement in such a file must be safe to run twice (`IF NOT EXISTS`, `IF EXISTS`). | +| Exit 1 with `index ... is invalid; repair the interrupted concurrent index build before retrying` | A `CONCURRENTLY` build in version 3 or 5 was interrupted | `ensureConcurrentIndex` does not repair it; [runbook](../operations/schema-migration.md#invalid-index). | +| Exit 1 with `found duplicate migration version` | Two sources share a number | Renumber one. | +| Exit 1 with `missing (out-of-order) migration` | A version below the highest applied one was never applied, for example after two branches added migrations | `SELECT version_id FROM goose_db_version ORDER BY id`; renumber the unapplied version above the highest one. | +| Exit 1 with `database holds data that retired backfills never processed` or `balances.withdrawable_micro_usd is missing` | The database has history but never ran a backfill retired after v0.9.10 | Boot a v0.9.10 coordinator against it once, then redeploy (`checkRetiredBackfills`). | +| Exit 1 with a `provider_earnings` duplicate `job_id` message | Rows share a non-empty `job_id`, so version 4 cannot build its unique index | Run `coordinator/store/migrations/dedupe_provider_earnings.sql` offline, then redeploy. | +| A dropped column comes back, or a `SET NOT NULL` is undone, after a rollback | The rollback image was built before goose and replayed its boot DDL (`ADD COLUMN IF NOT EXISTS`; `DROP NOT NULL` on `fleet_snapshots.free_for_load_gb`) | Do not ship a destructive migration while a pre-goose image can be a fallback; see [expand and contract](../developer/database-migrations.md#change-a-column-in-two-releases-expand-and-contract). | +| A column or index that `schema.sql` has is missing in production after the first goose deploy | One of the baseline's `DO ... EXCEPTION WHEN others` blocks swallowed an error (for example a lock timeout), and goose still recorded version 1 | The `pg_dump` diff in the [first cut-over checklist](../operations/schema-migration.md#first-production-cut-over-to-goose). | + +## Code map + +| Concern | Location | +|---|---| +| Migration runner, timeouts, retries, Go migration list | `coordinator/store/postgres_migrations.go` (`migrate`, `migrateOnce`, `newMigrationProvider`, `goMigrations`) | +| SQL migrations | `coordinator/store/schema/migrations/` | +| Checked-in schema | `coordinator/store/schema/schema.sql` | +| Concurrent index helper and startup log line | `coordinator/store/postgres_startup.go` (`ensureConcurrentIndex`, `logStartupMigration`) | +| Go migration bodies | `coordinator/store/postgres_retired_backfills.go`, `coordinator/store/postgres.go` (`ensureProviderEarningsJobIndex`), `coordinator/store/postgres_earnings_window_index.go` | +| Database-only command | `coordinator/cmd/coordinator/maintenance.go` (`runMaintenanceCommand`) | +| Tests | `coordinator/store/postgres_migrations_test.go`, `coordinator/store/migration_harness_test.go` | +| Manual SQL | `coordinator/store/migrations/` | + +## Related + +- [Add a database migration](../developer/database-migrations.md) — the steps +- [Apply schema migrations in production](../operations/schema-migration.md) — backup, checks, rollback +- [Storage](storage.md) — what the tables hold and which backend runs +- [Deploy the coordinator](../operations/coordinator-deploy.md) — the container swap that runs the migrations diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index a149796f9d..c881f966fa 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -1,10 +1,10 @@ # Storage -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 -What the coordinator persists, through which interface, in which backend, and -how the schema reaches a fresh database; then what a provider keeps on its own -disk and in its Keychain. Read this to understand what survives a restart, what +What the coordinator persists, through which interface and in which backend; +then what a provider keeps on its own disk and in its Keychain. How the schema +changes is [schema lifecycle](schema-lifecycle.md). Read this to understand what survives a restart, what does not, and which files an operator may touch. Configuration values are listed once in [`../reference/configuration.md`](../reference/configuration.md); the SSD cache file format is in @@ -111,98 +111,33 @@ stats endpoint can hold connections for seconds while heartbeat upserts, billing settlements and inference completions also need them. The DSN itself is the only connection-level knob; there is no separate host/user/password set. -### Migrations are numbered goose versions +### Schema migrations -The schema is a list of numbered migrations, applied by -[goose](https://github.com/pressly/goose) (`github.com/pressly/goose/v3`). -`NewPostgres` calls `PostgresStore.migrate` -(`coordinator/store/postgres_migrations.go`) before it returns. Goose applies -each version once and records it in `goose_db_version`; a later boot finds -nothing to apply. `coordinator --migrate-only` runs the same step and exits -before admin key seeding, listeners or background workers. It requires a -PostgreSQL URL; there is no memory-store fallback or schema-skip mode. - -| Version | Source | What it does | -|---|---|---| -| 1 | `coordinator/store/schema/migrations/00001_baseline.sql` | The 255 statements that the pre-goose boot ran on every start, unchanged and in the same order. Each block runs on its own, outside a transaction. On a database that already has the schema, every statement is a no-op. | -| 2 | `checkRetiredBackfills` (`coordinator/store/postgres_retired_backfills.go`) | The retired-backfill guard below. | -| 3 | `ensureProviderRestoreIndexes` (`coordinator/store/postgres_startup.go`) | Builds the two provider-restore indexes `CONCURRENTLY`. | -| 4 | `ensureProviderEarningsJobIndex` (`coordinator/store/postgres.go`) | Builds the `provider_earnings(job_id)` unique index `CONCURRENTLY`. | -| 5 | `ensureProviderEarningsWindowIndex` (`coordinator/store/postgres_earnings_window_index.go`) | Builds the BRIN time index and sets the analyze cadence. | - -Versions 2 to 5 are Go migrations (`goMigrations`). They keep the code they had -before goose and run on the store pool. The SQL migrations run on a separate -two-connection pool whose sessions set `lock_timeout` to 3 s and -`statement_timeout` to 10 min (`migrationLockTimeout`, -`migrationStatementTimeout`); a value set in the database URL wins. A DDL -statement that cannot get its lock in time fails instead of queueing every -later query on the table behind it, and `migrate` runs goose again, up to three -attempts. If a long read query keeps a table busy through all three -attempts, the boot fails before it serves and changes nothing that it has not -recorded; start it again later. - -Goose first checks for pending versions without a lock; that check also -creates `goose_db_version` on a database that has none. When versions are -pending, goose takes a session advisory lock, lists the versions again, and -applies the ones still missing. Two coordinators that start together take -turns: one applies, the other waits for the lock and then finds nothing to -apply. The waiting coordinator gives up after goose's default lock wait of -5 min (60 tries, 5 s apart) and exits 1. Out-of-order versions are refused. - -Each version runs once, so the work in it no longer repeats on every boot. -The repair statements in the baseline (the `api_keys.id` backfill, the -`model_registry` capability fix for `EigenLabs/Qwen3.8-27B-4bit`, the two -`provider_trust_reuse` backfills, the `model_aliases.desired_build` and -`global_payout_withdrawals.expires_at` backfills) and versions 2 to 5 ran at -every start before goose. The current writers already write the repaired -form, so running them once is enough. - -`coordinator/store/schema/schema.sql` is the `pg_dump --schema-only` of the -schema the migrations build, without `goose_db_version`. -`TestMigrationsBuildCheckedInSchema` builds a fresh database with goose and -fails when its schema differs from that file. To add a migration, follow +`NewPostgres` applies every pending goose migration before it returns; the +coordinator serves only after they all succeed. Each version runs once and is +recorded in `goose_db_version`. `coordinator/store/schema/schema.sql` is the +checked-in `pg_dump` of the schema that the migrations build. The versions, +locks, timeouts and failure modes are in +[schema lifecycle](schema-lifecycle.md); adding a migration is [Add a database migration](../developer/database-migrations.md). -`schema_migrations` is a separate, older table. It holds the markers of the -one-shot data migrations inside the baseline and of the retired backfills. -Two SQL files under `coordinator/store/migrations/` are not migrations and are -applied by hand with `psql`: `dedupe_provider_earnings.sql` (an offline cleanup -that once ran at boot, held a relation lock for ~15 minutes on the production -table and kept the coordinator from binding its port) and -`request_waterfall.sql` (an analysis view joining `request_profiles` to -`inference_routes`, kept off the boot path so a `CREATE VIEW` can never queue -behind a long query's lock). `coordinator/deploy/start.sh` does not touch the -database; it only prepares the persistent disk and MicroMDM before `exec -coordinator`. - -The one-shot backfills that derived `earnings_summary`, `usage_totals` and -`balances.withdrawable_micro_usd` from history (markers -`backfill_earnings_summary_v1`, `backfill_usage_totals_v1`, -`backfill_withdrawable_balance_v1`) have run in production and are retired -after v0.9.10. The baseline creates `balances` with -`withdrawable_micro_usd`. `checkRetiredBackfills` (version 2) then guards the -first goose boot of a database: - -- it fails if `balances.withdrawable_micro_usd` is missing; -- it records each marker whose source table (`balances`, `usage`, - `provider_earnings`) is empty, because with no history the current schema is - already exact, and v0.9.10 recorded the same markers on an empty database; -- it seeds the single `usage_totals` row only while `usage` is empty; -- it fails if a source table holds rows but its marker is missing, or if the - `usage_totals` row is missing. - -A failed boot writes no marker and no counter for the data it refused, so the -remedy in the error (boot a coordinator built from v0.9.10, which still -runs them, once; then this build) still runs the real backfill. Databases that ran the -backfills keep their markers and their now-unused scratch tables -(`earnings_summary_backfill_pending`, `usage_totals_backfill_state`). - -The Solana-era cleanups are retired the same way: the wallet-keyed price delete (marker `cleanup_wallet_model_prices_v1`, -which on a fresh database ran before `users` existed and so fired on the second -boot) and the one-time column drops `billing_sessions.chain`, -`users.solana_wallet_address`, `users.solana_wallet_id` and -`releases.image_bridge_hash`. A database migrated by the current binary still -boots an older one, whose versions of these statements are no-ops or guarded. +```mermaid +flowchart LR + classDef step fill:#dbeafe,stroke:#1d4ed8,color:#0b1220 + classDef check fill:#fef3c7,stroke:#b45309,color:#1f1300 + classDef ok fill:#dcfce7,stroke:#15803d,color:#052e16 + classDef fail fill:#fee2e2,stroke:#b91c1c,color:#450a0a + A["ReadAppConfig"]:::step --> B{"EIGENINFERENCE_DATABASE_URL set?"}:::check + B -- "yes" --> C["NewPostgres: connect, Ping,
apply pending goose versions"]:::step + C -- "ok" --> G["SeedKey admin key, serve"]:::ok + C -- "error" --> X["exit 1"]:::fail + B -- "no, ALLOW_MEMORY_STORE=true" --> H["NewMemory + 15 min pruner"]:::ok + B -- "no" --> X +``` + +Legend: blue = step, amber = decision, green = serving, red = exit 1. + +### Provider earnings and history `RecordProviderEarning` and `CreditProviderAccount` maintain new summaries from inserted earning rows, so duplicate non-empty job IDs never increment twice. @@ -210,12 +145,6 @@ inserted earning rows, so duplicate non-empty job IDs never increment twice. draw settlement and MemoryStore. The record-only method does not credit balances or create ledger entries. -Postgres startup logs connection time, one `postgres migration` line per -applied version with its duration, and named index phases. Logs omit SQL and -parameters. Preparing migrations before the drain moves index builds out of the -cutover window; concurrent index creation can still wait for old transactions. See the [deployment procedure](../operations/coordinator-deploy.md) -for the approval and compatibility boundary. - Provider history is recovered on demand after successful live SE attestation, using `GetProviderForRestore` with the verified serial first, then SE key if no serial record exists. Ordered partial indexes on each identity plus @@ -241,22 +170,6 @@ Store errors are logged and do not grant hardware trust. Reputation is still loaded by the selected historical record ID. No store operation lists every historical provider record. -```mermaid -flowchart LR - A[ReadAppConfig] --> B{DATABASE_URL set?} - B -- yes --> C[pgxpool connect + Ping] - C --> V{pending versions?\nno lock; creates\ngoose_db_version if missing} - V -- none --> G[SeedKey admin key] - V -- some --> L[goose advisory lock\nwait up to 5 min] - L --> D[list versions again;\napply each pending version once:\n1 baseline, 2 retired-backfill guard,\n3-5 CONCURRENTLY indexes] - D --> G - D -. lock_timeout, up to 3 attempts .-> V - L -. lock wait over .-> X - B -- no, ALLOW_MEMORY_STORE=true --> H[NewMemory + 15 min pruner] - B -- no --> X[exit 1] - D -. any error .-> X -``` - ### Table families Roughly forty tables; grouped by what would be lost if the family vanished. @@ -266,7 +179,7 @@ Roughly forty tables; grouped by what would be lost if the family vanished. | Identity and access | `api_keys`, `users`, `device_codes`, `provider_tokens`, `publishing_api_keys`, `invite_codes`, `invite_redemptions` | Keys are stored as hashes with a display prefix; `users` carries the Stripe Connect fields. | | Money | `balances`, `ledger_entries`, `billing_sessions`, `model_prices`, `referrers`, `referrals`, `stripe_withdrawals`, `global_payout_recipients`, `global_payout_withdrawals`, `provider_earnings`, `earnings_summary`, `provider_payouts`, `provider_floor_draws`, `payments` (legacy) | The ledger is append-only; `balances` is the materialised view of it. `model_prices.cache_read_price` is nullable: `NULL` means the row sets no cache-read rate and billing derives one from `input_price` (`payments.RatesFor`). Semantics in [`billing.md`](billing.md). | | Public model demand | `model_demand_requests`, `model_demand_hourly`, `model_demand_collection` | One compact projection per scoped coordinator UUID, hourly counters updated atomically by the `model_demand_rollup` trigger, and a persistent collection epoch; `coordinator/store/postgres_model_demand.go`. | -| Usage and routing telemetry | `usage`, `usage_totals`, `inference_routes`, `request_rejections`, `request_profiles`, `fleet_snapshots`, `request_outcomes` | Row per request, per dispatched attempt, per rejection, per profiled attempt, per fleet sample; `usage_totals` is a single-row counter seeded at boot by `checkRetiredBackfills` and incremented by `RecordUsage`. `usage.cached_tokens` (`INTEGER NOT NULL DEFAULT 0`) is the subset of `prompt_tokens` billed at the cache-read rate; rows written before the column existed read 0, which is what they were billed. It and `model_prices.cache_read_price` are added by plain `ALTER TABLE … ADD COLUMN IF NOT EXISTS` statements, not exception-swallowing `DO` blocks. Settlement reads and writes both columns, so if either cannot be added (a lock timeout, a missing privilege), startup fails rather than boot a coordinator that bills at the default rates and drops usage rows. | +| Usage and routing telemetry | `usage`, `usage_totals`, `inference_routes`, `request_rejections`, `request_profiles`, `fleet_snapshots`, `request_outcomes` | Row per request, per dispatched attempt, per rejection, per profiled attempt, per fleet sample; `usage_totals` is a single-row counter seeded by `checkRetiredBackfills` (migration version 2) and incremented by `RecordUsage`. `usage.cached_tokens` (`INTEGER NOT NULL DEFAULT 0`) is the subset of `prompt_tokens` billed at the cache-read rate; rows written before the column existed read 0, which is what they were billed. It and `model_prices.cache_read_price` are added by plain `ALTER TABLE … ADD COLUMN IF NOT EXISTS` statements, not exception-swallowing `DO` blocks. Settlement reads and writes both columns, so if either cannot be added (a lock timeout, a missing privilege), startup fails rather than boot a coordinator that bills at the default rates and drops usage rows. | | Provider fleet and trust | `providers`, `provider_reputation`, `provider_sessions`, `provider_trust_reuse`, `provider_verification_jobs`, `code_attestations`, `code_attest_push_budgets`, `provider_log_reports` | Trust reuse and code attestations are durable. `code_attestations.continuous_coverage_until` is compare-and-updated only for the exact original proof tuple; it never refreshes `attested_at` or inserts proof. This allows bounded same-process resume after a redeploy; see [`security/attestation.md`](security/attestation.md). `provider_log_reports.serial_number` is kept empty by trigger. | | Models and releases | `model_registry`, `model_versions`, `model_version_files`, `model_active_versions`, `model_aliases`, `releases` | The catalog the registry syncs at boot; see [`model-registry.md`](model-registry.md). | | Cache routing state | `cache_routing_holders`, `cache_routing_demand`, `cache_routing_meta` | Write-behind copy of the registry's in-memory exact prefix-cache holder index and observed-demand index, so a restart does not start from an empty index (`coordinator/store/cacheroutingstate_postgres.go`, `coordinator/store/cacheroutingstate/records.go`, `coordinator/registry/cachepersist/persister.go`). Holders are keyed by boundary key plus the provider's cache epoch (a UUID the provider mints per model SSD root and persists), never by connection-scoped provider ID; rows name a boundary by its keyed identifier (the HMAC output under the route key; the key material itself is never stored) and token count, plus the Ready fallback and measured stage costs; the provider-confirmed chain hash is not stored, and no prompt content is. Rows are pruned in 10,000-row batches every five minutes under the active routing TTL (the effective expiry is the earlier of the stored one and `updated_at` plus the TTL, indexed on both columns), so a longer past TTL cannot leave rows in the table after they stopped loading; rows stamped more than a minute ahead of the pruning clock (a previous instance's skew) are removed too, at boot and on every prune, so a current receipt is never outranked by a quarantined future timestamp. `cache_routing_meta` records a non-secret fingerprint of the cache-key generation (HMAC of the master key over every key-derivation label, the block contract and a persistence generation, `deriveCacheKeys`); nothing is written before a boot has recorded it; a boot under a different master key finds rows whose keys can never match a request again and empties both tables with unconditional bounded deletes, recording the new generation last, instead of restoring them (`cachepersist.Restore`, `ResetCacheRoutingState`). Loads apply the current TTL to each row's expiry before ordering and capping. Losing the tables costs minutes of hit rate, nothing else. | @@ -329,16 +242,13 @@ KV blocks under a per-model key, not tokens. `store.Config.Check` fails and `main` exits unless a DSN is present or the memory store is opted into by name (`coordinator/store/config.go`, `coordinator/cmd/coordinator/main.go`). -2. **Schema changes ship with the binary as numbered migrations.** The process - serves traffic only after every pending version applies; a version applies - once and is recorded in `goose_db_version` - (`coordinator/store/postgres_migrations.go`). The baseline statements are - idempotent, so its first run on a pre-goose database changes nothing. -3. **Committed migration progress is not applied twice.** Goose records a - version after it succeeds, under a session advisory lock. One-shot data - migrations in the baseline commit their `schema_migrations` marker in the - same statement or transaction as their update - (`coordinator/store/schema/migrations/00001_baseline.sql`). +2. **Schema changes ship with the binary as numbered migrations,** and the + process serves only after every pending version applies + (`coordinator/store/postgres_migrations.go`); the migration invariants are + in [schema lifecycle](schema-lifecycle.md#invariants). +3. **One-shot data migrations in the baseline commit their + `schema_migrations` marker in the same statement or transaction as their + update** (`coordinator/store/schema/migrations/00001_baseline.sql`). 4. **Boot never holds a long lock on a hot table.** The `provider_earnings(job_id)` unique index is built `CONCURRENTLY`, only after a duplicate check, and skipped when already valid; the dedupe that violated @@ -367,11 +277,7 @@ KV blocks under a per-model key, not tokens. | Symptom | Cause | Where to look | |---|---|---| -| Coordinator exits 1 at boot with `store: run migrations` | A migration failed (permissions, a hand-edited schema, or a lock still held after three `lock_timeout` attempts) | The failed `postgres migration` version in the log; `pg_stat_activity` for blockers. | -| Boot fails with `missing (out-of-order) migration` | A version below the database's highest was never applied, for example two branches added migrations and the higher one deployed first | `SELECT * FROM goose_db_version`; renumber the unapplied migration above the highest applied version. | -| Boot fails with `found duplicate migration version` | Two migration files use the same number | Renumber one of them. | -| Boot fails with `database holds data that retired backfills never processed` or `balances.withdrawable_micro_usd is missing` | The database has billing, usage or earnings history but never ran a backfill retired after v0.9.10 | Boot a coordinator built from v0.9.10 (which still runs them) against it once, then redeploy (`checkRetiredBackfills`). | -| Boot fails with an actionable `provider_earnings` duplicate message | Rows share a non-empty `job_id`, so the unique index cannot be built | Run `dedupe_provider_earnings.sql` offline, then redeploy. | +| Coordinator exits 1 at boot with `store: run migrations` | A goose migration failed: a lock timeout, the advisory-lock wait, an invalid index, an out-of-order or duplicate version, or the retired-backfill guard | [Schema lifecycle failure modes](schema-lifecycle.md#failure-modes) and the [schema migration runbook](../operations/schema-migration.md#troubleshooting). | | `EIGENINFERENCE_DATABASE_URL is required in production` | No DSN and no memory-store opt-in | The environment file; see [`../operations/coordinator-deploy.md`](../operations/coordinator-deploy.md). | | Billing or key state gone after a restart | The process ran on the memory store | Startup log line `using in-memory store`. | | `/v1/stats` slow and pool saturated | Full scans on `usage` holding connections; the 80-connection floor is the mitigation, not a fix | `pg_stat_activity`; the read cache. | @@ -387,7 +293,7 @@ KV blocks under a per-model key, not tokens. | Earnings rankings and startup time index | `coordinator/store/postgres_leaderboard.go` (`Leaderboard`), `coordinator/store/postgres_earnings_window_index.go` (`ensureProviderEarningsWindowIndex`), `coordinator/store/postgres_startup.go` (`ensureConcurrentIndex`) | | Backend selection and validation | `coordinator/store/config.go`, `coordinator/cmd/coordinator/main.go` | | Postgres pool | `coordinator/store/postgres.go` | -| Migrations | `coordinator/store/postgres_migrations.go` (`migrate`, `goMigrations`), `coordinator/store/schema/migrations/`, `coordinator/store/schema/schema.sql`, `coordinator/store/postgres_retired_backfills.go` | +| Migrations | `coordinator/store/postgres_migrations.go`, `coordinator/store/schema/migrations/`, `coordinator/store/schema/schema.sql`; full map in [schema lifecycle](schema-lifecycle.md#code-map) | | Provider identity and usage reads | `coordinator/store/postgres_provider_read.go` (`providerRecordColumns`, `scanProviderRecord`, `GetProviderRecord`); `coordinator/store/provider_restore.go` (`GetProviderForRestore`, using the same projection); `coordinator/store/postgres_usage_read.go` (`readUsageRecords`, `UsageRecords`); `coordinator/store/postgres_row.go` (`rowScanner`) | | Domain files | `coordinator/store/postgres_model_registry.go`, `coordinator/store/postgres_base_rewards.go`, `coordinator/store/postgres_profiles.go`, `coordinator/store/route_telemetry.go`, `coordinator/store/usage_time_series.go`, `coordinator/store/apikey.go` | | Memory backend | `coordinator/store/memory.go`, `coordinator/store/memory_base_rewards.go` | @@ -404,6 +310,7 @@ KV blocks under a per-model key, not tokens. - [`security/attestation.md`](security/attestation.md) — the trust-reuse and code-attestation caches - [`prefix-cache.md`](prefix-cache.md) and [`../reference/ssd-kv-cache.md`](../reference/ssd-kv-cache.md) — the provider's on-disk cache - [`../operations/state-export.md`](../operations/state-export.md) — exporting the non-Postgres state on the persistent disk +- [`schema-lifecycle.md`](schema-lifecycle.md) — how the schema changes: goose versions, locks, timeouts - [`../operations/coordinator-deploy.md`](../operations/coordinator-deploy.md) — where the DSN is set ## Model token grants diff --git a/docs/developer/build.md b/docs/developer/build.md index 528606dd7e..e5753e2650 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 The provider test runner isolates daemon-state and loaded-model snapshots in a temporary directory for each run. Unit-test providers must not overwrite the @@ -779,7 +779,7 @@ The normal coordinator build also supports `coordinator --migrate-only`. It requires `EIGENINFERENCE_DATABASE_URL`, runs store migrations, and exits without starting the server or seeding an admin key. Container execution must override the default MicroMDM entrypoint script; see the -[deployment procedure](../operations/coordinator-deploy.md#optional-prepare-compatible-migrations-before-draining). +[schema migration runbook](../operations/schema-migration.md#4-apply-the-migrations). The [startup measurement tool](../operations/coordinator-startup-measurement.md) requires Python 3.10+ and no third-party packages or build step. Its tests use diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index 8771627a61..0a3f8f63ee 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -1,45 +1,87 @@ # Add a database migration -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 -How to change the coordinator's Postgres schema. Every schema change is a new -numbered goose migration under `coordinator/store/schema/migrations/`. Do not -put DDL in Go strings, and do not edit a migration that has merged. The -mechanism is explained in -[storage](../architecture/storage.md#migrations-are-numbered-goose-versions). +How to change the coordinator's Postgres schema: choose the migration kind, +write it as a numbered goose version, regenerate the checked-in schema, and +test it. Every schema change is a new version. Do not put DDL in Go strings, +and do not edit a migration that has merged. Why the rules exist is in +[schema lifecycle](../architecture/schema-lifecycle.md); applying a migration +in production is the [schema migration runbook](../operations/schema-migration.md). ## Prerequisites -- Docker, with a throwaway Postgres 17 server: - `docker run -d --name dinf-store-pg -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:17`. -- `DATABASE_URL` pointing at that server, as for the other Postgres tests - ([test](test.md)). +- Go as pinned in `go.mod`, and Docker. +- A throwaway Postgres 17 server, the major version that production runs: + + ```bash + docker run -d --name dinf-store-pg -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:17 + ``` + +- `DATABASE_URL` for the store tests ([test](test.md)): + + ```bash + export DATABASE_URL='postgres://postgres:pg@127.0.0.1:55432/postgres?sslmode=disable' + ``` ## Steps -1. Pick the next version: one more than the highest file number in - `coordinator/store/schema/migrations/` or the highest version in - `goMigrations` (`coordinator/store/postgres_migrations.go`). If a branch that - merges before yours takes the same number, renumber yours. -2. In `coordinator/store/schema/migrations/`, create `NNNNN_short_name.sql`, - where `NNNNN` is the version with leading zeros: +1. **Choose the kind.** Use the first row that fits. + + | Change | Kind | Example in the repo | + |---|---|---| + | Add a table, a nullable column, or a column with a constant default; add a constraint `NOT VALID` | SQL file, one transaction (the default) | Template in step 3 | + | Several `ALTER TABLE`s on busy tables that must not hold their locks together; `DROP INDEX CONCURRENTLY`; `VALIDATE CONSTRAINT` after a `NOT VALID` add | SQL file with `-- +goose NO TRANSACTION` | `coordinator/store/schema/migrations/00001_baseline.sql` | + | Create an index on a table that has rows in production | Go migration through `ensureConcurrentIndex` | `ensureProviderRestoreIndexes` (version 3) | + | A step that must read data first, check a precondition, or check its own result | Go migration | `checkRetiredBackfills` (version 2) | + | Rename or drop a column, or tighten a constraint | Two or more releases; see [expand and contract](#change-a-column-in-two-releases-expand-and-contract) | — | + | Fix rows that a writer keeps producing | Not a migration: fix the writer | — | + | A cleanup that needs a long lock | Manual SQL under `coordinator/store/migrations/`, applied under an approved operation | `coordinator/store/migrations/dedupe_provider_earnings.sql` | + +2. **Pick the version.** Use one more than the highest version in + `coordinator/store/schema/migrations/` and in `goMigrations` + (`coordinator/store/postgres_migrations.go`). SQL files and Go migrations + share one sequence. If a branch that merges before yours takes the same + number, renumber yours before it merges. + +3. **Write the migration.** Follow the part for your kind. + + *SQL file, one transaction.* Create + `coordinator/store/schema/migrations/_.sql`, where + `` is the version with leading zeros: ```sql -- +goose Up - ALTER TABLE providers ADD COLUMN example TEXT; + ALTER TABLE providers ADD COLUMN IF NOT EXISTS example TEXT; ``` - Goose runs the file in one transaction. Put `-- +goose NO TRANSACTION` at - the top for `DROP INDEX CONCURRENTLY`. Wrap a statement that contains `;` - (a `DO` block or a function body) in `-- +goose StatementBegin` and - `-- +goose StatementEnd`. + Goose runs every statement and the `goose_db_version` insert in one + transaction. A failure rolls all of it back. + + *SQL file, no transaction.* Put `-- +goose NO TRANSACTION` above + `-- +goose Up`. Each statement commits on its own, and the version is + recorded after the last one. A failure in the middle leaves the earlier + statements applied, and the next boot runs the whole file again, so every + statement must be safe to run twice (`IF NOT EXISTS`, `IF EXISTS`, or + drop-then-add). Wrap a statement that contains `;`, such as a `DO` block, + in `-- +goose StatementBegin` and `-- +goose StatementEnd`, as the baseline + does. - Do not put `CREATE INDEX CONCURRENTLY` in an SQL file - (`TestSQLMigrationsDoNotBuildIndexesConcurrently` fails). A build that - fails, for example on `lock_timeout`, leaves an invalid index; with - `IF NOT EXISTS` the next attempt skips it and goose records the version - with a broken index. Add a Go migration to `goMigrations` - (`coordinator/store/postgres_migrations.go`) instead: + *Go migration.* Write a method on `PostgresStore` that takes a + `context.Context` and returns an error, and add it to `goMigrations`: + + ```go + step(6, s.checkExampleRows), + ``` + + It runs on the store pool with no session timeouts unless the database URL + sets them. It runs once; keep it safe to run again after a failure, because + a failed run is not recorded. + + *Concurrent index.* Do not put `CREATE INDEX CONCURRENTLY` in an SQL file; + `TestSQLMigrationsDoNotBuildIndexesConcurrently` fails. Add a Go migration + that calls `ensureConcurrentIndex` (`coordinator/store/postgres_startup.go`), + as `ensureProviderRestoreIndexes` does: ```go step(6, func(ctx context.Context) error { @@ -48,26 +90,23 @@ mechanism is explained in }), ``` - `ensureConcurrentIndex` (`coordinator/store/postgres_startup.go`) returns at - once when a valid index exists, refuses an invalid leftover by name (drop it - by hand, then restart), builds the index, and fails unless the result is - valid. The version is recorded only after it succeeds. -3. Keep each statement short and lock-safe. The migration session sets - `lock_timeout` to 3 s and `statement_timeout` to 10 min. Add a column - without a volatile default; add a constraint `NOT VALID`, then `VALIDATE` - it; build indexes on large tables `CONCURRENTLY`. Do not swallow errors in a - `DO ... EXCEPTION WHEN others` block: a failure must stop the boot. - - A migration runs once. Nothing in it runs again on later boots, so it - cannot repair rows that a writer keeps producing; fix the writer. - - Do not drop or rename a column, or add `NOT NULL` or another constraint to - a table the baseline creates, while a coordinator image built before goose - can still be started as a rollback target. That image replays its own boot - DDL: `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and its - `DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later - `SET NOT NULL`. -4. Regenerate the schema file from a database built by the migrations: + The helper returns at once when a valid index exists, refuses an invalid + leftover by name, builds the index, and fails unless it is valid. The + version is recorded only after it succeeds. + +4. **Keep it lock-safe.** SQL migrations run with `lock_timeout` 3 s and + `statement_timeout` 10 min ([locks and timeouts](../architecture/schema-lifecycle.md#locks-and-timeouts)). + - Add a column without a volatile default; a nullable column with no + default changes only the catalog. + - Add a foreign key or check `NOT VALID`, then `VALIDATE` it in a separate + statement of a `NO TRANSACTION` file. + - Do not catch errors in a `DO ... EXCEPTION WHEN others` block. A failure + must stop the boot. + - Do not drop or rename a column, or add `NOT NULL` or a constraint to a + table the baseline creates, in one step; see + [destructive changes](#destructive-changes-and-the-pre-goose-fallback). + +5. **Apply it to an empty database and regenerate the schema file.** ```bash docker exec dinf-store-pg createdb -U postgres schema_dump @@ -77,31 +116,98 @@ mechanism is explained in --exclude-table=goose_db_version schema_dump \ | grep -v '^\\restrict \|^\\unrestrict \|^-- Dumped from database version\|^-- Dumped by pg_dump version' \ > coordinator/store/schema/schema.sql + docker exec dinf-store-pg dropdb -U postgres schema_dump ``` - Use a `pg_dump` of the same major version as production (17). -5. Update `MemoryStore` and the docs that describe the changed tables - ([storage](../architecture/storage.md)). + The `--migrate-only` run logs one `postgres migration` line per version + with `"result":"applied"`, then `coordinator migrations complete`. Use the + `pg_dump` inside the container, so that its major version matches + production (17). Review `git diff coordinator/store/schema/schema.sql`: it + must show only your change. + +6. **Update the rest of the store.** Make `MemoryStore` + (`coordinator/store/memory.go`) match, and update the docs that describe + the changed tables ([storage](../architecture/storage.md)). ## Verify ```bash -DATABASE_URL='postgres://postgres:pg@127.0.0.1:55432/postgres?sslmode=disable' \ - go test ./coordinator/store -run 'TestMigrations|TestConcurrentMigrations' -count=1 +go test ./coordinator/store -count=1 \ + -run 'TestMigrations|TestConcurrentMigrations|TestMigrateRetries|TestSQLMigrations' +``` + +| Test | Fails when | +|---|---| +| `TestMigrationsBuildCheckedInSchema` | `schema.sql` differs from what the migrations build | +| `TestMigrationsLeaveLegacyDatabaseUnchanged` | Versions 1 to 5 change a database that a pre-goose coordinator built | +| `TestConcurrentMigrationsApplyOnce` | Two runs at once apply a version twice | +| `TestSQLMigrationsDoNotBuildIndexesConcurrently` | An SQL file contains `CREATE [UNIQUE] INDEX CONCURRENTLY` | + +Then run the store tests for the tables you changed, on both backends. + +## Change a column in two releases (expand and contract) + +A rollback starts the previous image on the migrated schema; nothing reverts +the schema ([invariants](../architecture/schema-lifecycle.md#invariants)). +`--migrate-only` can also run while the previous image still serves. So each +release must work on the schema of the release after it. A breaking change +therefore ships in steps, and the contract step ships two releases after the +expand step. + +```mermaid +flowchart LR + classDef rel fill:#dbeafe,stroke:#1d4ed8,color:#0b1220 + classDef fb fill:#f1f5f9,stroke:#475569,color:#0f172a + N["Release N: expand
migration adds new_col
code writes old_col and new_col,
reads COALESCE(new_col, old_col)"]:::rel + N1["Release N+1: switch
no migration
code reads and writes new_col only"]:::rel + N2["Release N+2: contract
migration drops old_col"]:::rel + F0["fallback N-1:
ignores new_col; old_col is current"]:::fb + F1["fallback N:
new_col is current"]:::fb + F2["fallback N+1:
never touches old_col"]:::fb + N --> N1 --> N2 + N -. "rollback" .-> F0 + N1 -. "rollback" .-> F1 + N2 -. "rollback" .-> F2 ``` -`TestMigrationsBuildCheckedInSchema` fails when `schema.sql` does not match -what the migrations build. +Legend: blue = release, grey = the image a rollback starts. + +1. Release N, expand: add the new column, table or index as an additive + migration. Write both shapes, and read the new one with a fallback to the + old one. Backfill old rows in small batches, as a Go migration or a + reviewed manual operation; a backfill in one statement holds row locks for + its whole run. +2. Deploy release N. Ship N+1 only after N runs in production, so that N is + the fallback image. +3. Release N+1, switch: read and write only the new shape. No migration. +4. Deploy release N+1. Ship N+2 only after N+1 runs in production. +5. Release N+2, contract: drop the old shape, or add the constraint + (`NOT VALID`, then `VALIDATE`). + +## Destructive changes and the pre-goose fallback + +A coordinator image built before goose ignores `goose_db_version` and replays +its own boot DDL. `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and +its `DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later +`SET NOT NULL`. Ship no contract step on a table the baseline creates while a +pre-goose image can be started as the fallback. The +[runbook](../operations/schema-migration.md#rollback) states which images are +safe. ## Troubleshooting | Symptom | Fix | |---|---| -| `found duplicate migration version` | Two files share a number; renumber yours. | -| `missing (out-of-order) migration` on a shared database | A higher version was applied first; renumber the unapplied file above it. | -| A statement fails with `canceling statement due to lock timeout` three times | A long query holds the table; rerun when it ends, or make the statement take a weaker lock. | +| `found duplicate migration version` | Two sources share a number; renumber yours. | +| `detected 1 missing (out-of-order) migration lower than database version` on a shared database | A higher version was applied first; renumber the unapplied one above it. | +| `canceling statement due to lock timeout` three times | Another session holds the table. Stop it, or make the statement take a weaker lock. | +| `TestMigrationsBuildCheckedInSchema` fails | `schema.sql` is stale. Repeat step 5 on an empty database. | +| The `schema.sql` diff shows objects you did not add | The dump came from a database that held other objects, or from a `pg_dump` older than 17. Repeat step 5 with a new database. | +| `index ... is invalid; repair the interrupted concurrent index build before retrying` locally | Drop the index (`DROP INDEX CONCURRENTLY `) and run again. | ## Related -- [Storage](../architecture/storage.md) — what the migrations build and why +- [Schema lifecycle](../architecture/schema-lifecycle.md) — how goose runs, locks, timeouts, failure modes +- [Apply schema migrations in production](../operations/schema-migration.md) — backup, checks, rollback +- [Storage](../architecture/storage.md) — what the tables hold - [Test](test.md) — running the Postgres tests diff --git a/docs/operations/README.md b/docs/operations/README.md index 5dc53cba74..b71dc44d00 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -1,6 +1,6 @@ # Operations runbooks -> Last updated: 2026-09-30 +> Last updated: 2026-10-04 Procedures for deploying, migrating, and operating Darkbloom production infrastructure. Every runbook has the same shape — when to use, prerequisites, @@ -15,6 +15,7 @@ shapes under [`../reference/README.md`](../reference/README.md). | [app-attest-build-qualification.md](app-attest-build-qualification.md) | Approve exact signed builds, retry publication without rebuilding, and revoke durable qualifications | | [mdm-optional-rollout.md](mdm-optional-rollout.md) | Qualify and activate App Attest serving, then scoped Darkbloom enrollment removal | | [`coordinator-deploy.md`](coordinator-deploy.md) | Swap the production coordinator container to a reviewed build, verify, roll back | +| [`schema-migration.md`](schema-migration.md) | Back up, check for long queries, apply and verify goose migrations; the first goose cut-over; rollback rules | | [`coordinator-startup-measurement.md`](coordinator-startup-measurement.md) | Measure post-stop candidate readiness, per-model routable capacity and optional disposable-test inference separately | | [`global-payouts.md`](global-payouts.md) | Enable international bank payouts, verify bank arrival and reconcile uncertain transfers | | [`provider-release.md`](provider-release.md) | Ship a provider CLI release: version bump, tag, signed and notarized bundle to R2, registration with the coordinator, rollback by deactivation | diff --git a/docs/operations/coordinator-deploy.md b/docs/operations/coordinator-deploy.md index c41103539f..d102573ed1 100644 --- a/docs/operations/coordinator-deploy.md +++ b/docs/operations/coordinator-deploy.md @@ -1,6 +1,6 @@ # Deploy the coordinator (production) -> Last updated: 2026-10-03 +> Last updated: 2026-10-04 Runbook for swapping the production coordinator container on the GCE VM `darkbloom-coordinator` to a Cloud-Build image of a reviewed `master` commit, @@ -115,11 +115,11 @@ by hand; shell variables do not cross SSH. ### 2. Pre-swap checks (VM and DB) Startup applies pending goose migrations -([storage](../architecture/storage.md#migrations-are-numbered-goose-versions)). -A migration statement waits at most 3 s for a lock (`lock_timeout`); after -three failed attempts the coordinator exits 1. Before goose, an `ALTER TABLE` -queued behind a long query's relation lock hung the deploy (2026-07-03 -outage). No rows means safe to proceed: +([schema lifecycle](../architecture/schema-lifecycle.md)). A migration +statement waits at most 3 s for a lock (`lock_timeout`); after three failed +attempts the coordinator exits 1. Before goose, an `ALTER TABLE` queued behind +a long query's relation lock hung the deploy (2026-07-03 outage). No rows +means safe to proceed: ```bash psql "$PROD_DB_URL" -c "select pid, now()-query_start as runtime, state, left(query,80) @@ -131,7 +131,7 @@ psql "$PROD_DB_URL" -c "select count(*) as blocked from pg_locks where granted = A coordinator built after v0.9.10 refuses to start on a database that holds billing, usage or earnings rows but never ran the retired one-shot backfills (`checkRetiredBackfills`, see -[storage](../architecture/storage.md#migrations-are-numbered-goose-versions)). +[schema lifecycle](../architecture/schema-lifecycle.md#version-2-the-retired-backfill-guard)). Production ran them; confirm all three markers before the swap (three rows): ```bash @@ -165,53 +165,14 @@ sudo sh -c 'umask 077; awk -F= '\''$1 ~ /^EIGENINFERENCE_CACHE_ROUTING_/ || $1 = /etc/d-inference/env | LC_ALL=C sort | sha256sum | cut -d" " -f1 > /tmp/darkbloom-cache-env.before.sha256' ``` -### Optional: prepare compatible migrations before draining +### Schema migrations -After reviewing the exact candidate's schema changes, a human-approved operator -can run its database-only command while the current coordinator serves. This is -a production database mutation and needs approval for that operation. Only -backward-compatible migrations belong before cutover; `--migrate-only` executes -all normal migrations and does not establish compatibility automatically. - -```bash -sudo docker run --rm --network host --env-file /etc/d-inference/env \ - --entrypoint /usr/local/bin/coordinator \ - "${CANDIDATE_IMAGE%:*}@${CANDIDATE_DIGEST}" --migrate-only -``` - -The executable override is mandatory: the image's default `start.sh` starts -MicroMDM and touches persistent MDM state. The database-only container needs no -userdata mount, publishes no port, seeds no admin key, starts no workers and -exits after migration success (with a 15-minute upper bound). Do not start a -second ordinary coordinator container. Rerun the blocked-query/lock checks and -verify current serving health after preparation; success is not approval to -swap. - -#### First deploy of a goose build - -The first coordinator built with goose (`coordinator/store/postgres_migrations.go`) -applies versions 1 to 5 to production once. On a schema that the previous -coordinator built they change nothing. A lock timeout inside one of the -baseline's `DO ... EXCEPTION WHEN others` blocks is swallowed, and goose still -records version 1. After that deploy, confirm the versions and compare the -production schema with the checked-in file of the deployed commit (read-only; -use a `pg_dump` 17 client): - -```bash -psql "$PROD_DB_URL" -c "select version_id from goose_db_version order by id;" # 0 through 5 -pg_dump "$PROD_DB_URL" --schema-only --no-owner --no-privileges --exclude-table=goose_db_version \ - | grep -v '^\\restrict \|^\\unrestrict \|^-- Dumped from database version\|^-- Dumped by pg_dump version' \ - | diff - coordinator/store/schema/schema.sql -``` - -Only objects applied by hand, such as the `request_waterfall` view, may -differ. A missing column or index means a swallowed statement; apply it under -a separate approved operation. - -New provider-recovery indexes are built concurrently and checked for validity. An -interrupted build that leaves an invalid index fails closed with its index name; -repair it under a separate approved operation. Ordinary startup still applies -schema checks, and this preparation does not prove a five-second handoff. +If the candidate adds goose versions, follow steps 1 to 4 of +[Apply schema migrations in production](schema-migration.md#steps) now: scope +the versions, take and record a Cloud SQL backup, check for long queries, and +optionally apply additive versions with `--migrate-only` while the current +coordinator serves. The first deploy of a goose build also follows its +[first cut-over checklist](schema-migration.md#first-production-cut-over-to-goose). ### 3. Refresh the env file and capture rollback inputs @@ -325,14 +286,9 @@ sudo docker run -d --name coordinator \ Startup takes ~15–40 s (MicroMDM init, migrations, listeners). If `/health` does not answer after ~60 s, or the container exits with `store: run -migrations`, suspect a migration behind a DB lock: re-run the -`pg_stat_activity` query and `pg_terminate_backend()` the blocker. Goose -holds an advisory lock while it migrates, so a second container waits for the -first instead of running the same DDL; after 5 min of waiting it exits 1. -Long read queries can make all three `lock_timeout` attempts fail, most likely -on the first goose deploy, which replays the baseline. That failure is safe: -the coordinator exits before serving and no failed version is recorded. End -the blocker or wait for a quieter moment, then start the container again. +migrations`, follow [schema migration troubleshooting](schema-migration.md#troubleshooting). +A failed migration exits before the coordinator serves and records no failed +version. **Do not loop restarts of the container.** ## Verification @@ -434,14 +390,9 @@ Registry for diagnosis. Providers reconnect on their own; the live registry is in-process and rebuilt from reconnects, durable state is in Cloud SQL and on the persistent disk. -A previous image built before goose boots on a goose-migrated database: it runs -its own boot DDL and ignores `goose_db_version`. That DDL also reapplies its own -schema: `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and its -`DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later -`SET NOT NULL`. So a destructive migration (drop or rename a column, tighten a -constraint on a baseline table) must wait until no pre-goose image can be -started as a fallback. An older goose image applies nothing, because every -version it knows is already recorded. +Rollback never reverts the schema. Which previous images are safe on a +migrated database is in the +[schema migration rollback rules](schema-migration.md#rollback). ## Environment file @@ -499,7 +450,7 @@ reference copy; editing it changes nothing on the host. | Symptom | Likely cause | Fix | |---|---|---| -| No `/health` after 60 s, or exit with `store: run migrations` | migration behind a relation lock (three `lock_timeout` attempts failed) | `pg_stat_activity` → `pg_terminate_backend()`; do not restart the container | +| No `/health` after 60 s, or exit with `store: run migrations` | a migration failed: a relation lock through three `lock_timeout` attempts, the 5 min advisory-lock wait, or an invalid index | [schema migration troubleshooting](schema-migration.md#troubleshooting); do not loop restarts | | Exit at boot with `database holds data that retired backfills never processed` or `balances.withdrawable_micro_usd is missing` | the database never ran a one-shot backfill retired after v0.9.10 (not production, which has all three markers) | roll back to the captured image, which runs the backfills at start, then redeploy the candidate | | Fleet drops to `self_signed`; "device not found in MDM" storm | container started without `-v /mnt/disks/userdata:/mnt/disks/userdata` (blank MicroMDM) | Rollback, then redo the swap with the mount | | `/v1/models` empty; providers `self_signed` | MicroMDM not running or `MICROMDM_API_KEY` ≠ `EIGENINFERENCE_MDM_API_KEY` | fix the env file, recreate the container | @@ -514,6 +465,7 @@ reference copy; editing it changes nothing on the host. - [dev-environment.md](dev-environment.md) — the dev coordinator (`darkbloom-dev`). - [`provider-release.md`](provider-release.md) — provider CLI release runbook. +- [`schema-migration.md`](schema-migration.md) — backup, checks and rollback rules for schema migrations. - [`../developer/build.md`](../developer/build.md) — what the Dockerfile builds. - [`../reference/configuration.md`](../reference/configuration.md) — every environment variable. - [`../architecture/cache-aware-routing.md`](../architecture/cache-aware-routing.md) — what the cache-routing controls do. diff --git a/docs/operations/coordinator-startup-measurement.md b/docs/operations/coordinator-startup-measurement.md index 4238788a37..9ff22288ab 100644 --- a/docs/operations/coordinator-startup-measurement.md +++ b/docs/operations/coordinator-startup-measurement.md @@ -1,6 +1,6 @@ # Measure coordinator startup after the old process stops -> Last updated: 2026-09-27 +> Last updated: 2026-10-04 Use `scripts/measure-coordinator-startup.py` to observe the interval after the old coordinator stops. The preceding drain is outside this measurement. The @@ -27,7 +27,7 @@ post-stop recovery. It records evidence; it does not authorize or execute a swap candidate-matching `/health` establishes that the candidate is reachable. Migrations and new index creation must be prepared separately under the -[deployment procedure](coordinator-deploy.md#optional-prepare-compatible-migrations-before-draining). +[schema migration runbook](schema-migration.md#4-apply-the-migrations). First-install index builds can still delay startup; the observer does not skip them or establish a five-second target in advance. diff --git a/docs/operations/schema-migration.md b/docs/operations/schema-migration.md new file mode 100644 index 0000000000..e2a1251f23 --- /dev/null +++ b/docs/operations/schema-migration.md @@ -0,0 +1,271 @@ +# Apply schema migrations in production + +> Last updated: 2026-10-04 + +Runbook for applying the goose migrations of a coordinator candidate to the +production database (Cloud SQL for PostgreSQL 17 in `darkbloom-mainnet`, read +replica `d-inference-prod-pg17-ro`): scope the change, back up, check for +long queries, apply, verify, and roll back. The container swap itself is +[Deploy the coordinator](coordinator-deploy.md). How the migrations run is +[schema lifecycle](../architecture/schema-lifecycle.md). + +## When to use + +- The candidate commit adds goose versions that production does not have. +- The first deploy of a coordinator built with goose; also follow the + [first cut-over checklist](#first-production-cut-over-to-goose). +- A coordinator exited at boot with `store: run migrations`. + +## Prerequisites + +- Explicit human approval for each production mutation in this runbook: the + backup, the `--migrate-only` run, the container swap, and every repair + statement ([operations rule 1](README.md)). Without it, an agent runs only + the read-only queries. +- `gcloud` with IAM on `darkbloom-mainnet` for Cloud SQL backups and IAP SSH to + the VM `darkbloom-coordinator`. +- `psql` and a `pg_dump` 17 client, and `PROD_DB_URL` for the **primary**. + Locks, `goose_db_version` and the migrations live on the primary; the + replica cannot show them. +- `CANDIDATE_COMMIT`, `CANDIDATE_IMAGE` and `CANDIDATE_DIGEST` from steps 1 + and 2 of the [deploy runbook](coordinator-deploy.md#steps), and a checkout of + `CANDIDATE_COMMIT`. + +## Steps + +```mermaid +flowchart TD + classDef step fill:#dbeafe,stroke:#1d4ed8,color:#0b1220 + classDef check fill:#fef3c7,stroke:#b45309,color:#1f1300 + classDef ok fill:#dcfce7,stroke:#15803d,color:#052e16 + classDef fail fill:#fee2e2,stroke:#b91c1c,color:#450a0a + classDef human fill:#f3e8ff,stroke:#7e22ce,color:#2e1065 + S1["1. Scope: list pending versions"]:::step --> S2["2. On-demand backup; record its ID"]:::human + S2 --> S3{"3. Long queries or
a goose lock holder?"}:::check + S3 -- "yes" --> W["wait, or end the blocker
(approved)"]:::human + W --> S3 + S3 -- "no" --> S4{"4. Run
--migrate-only
before the swap?"}:::check + S4 -- "yes (additive versions only)" --> MO["docker run ...
--migrate-only
while the old
coordinator serves"]:::human + S4 -- "no" --> SW["container swap: the new
coordinator migrates at start"]:::human + MO --> SW + SW --> V{"5. Verification queries pass?"}:::check + V -- "yes" --> OK["record versions and backup ID"]:::ok + V -- "no" --> T["Troubleshooting, or Rollback"]:::fail +``` + +Legend: blue = read-only, purple = needs approval, amber = decision, +green = done, red = failure path. + +### 1. Scope the change + +List what production has and what the candidate brings: + +```bash +psql "$PROD_DB_URL" -Atc "select coalesce(max(version_id), 0) from goose_db_version;" +git ls-tree --name-only "$CANDIDATE_COMMIT" coordinator/store/schema/migrations/ +git show "$CANDIDATE_COMMIT:coordinator/store/postgres_migrations.go" | grep -n 'step(' +``` + +An error `relation "goose_db_version" does not exist` means no goose build +has run yet: this is the [first cut-over](#first-production-cut-over-to-goose). +For each version above the production maximum, write down its kind +([migration kinds](../architecture/schema-lifecycle.md#migration-kinds)) and +whether it is additive. Note every `-- +goose NO TRANSACTION` file and every +index build. A version that drops, renames or tightens something needs the +[rollback rules](#rollback) checked before you continue. + +### 2. Take an on-demand backup and record its ID + +```bash +PRIMARY=$(gcloud sql instances describe d-inference-prod-pg17-ro \ + --project=darkbloom-mainnet --format='value(masterInstanceName)') +PRIMARY=${PRIMARY#*:} +BACKUP_NOTE="pre-migration ${CANDIDATE_COMMIT:0:7}" +gcloud sql backups create --instance="$PRIMARY" --project=darkbloom-mainnet \ + --description="$BACKUP_NOTE" +gcloud sql backups list --instance="$PRIMARY" --project=darkbloom-mainnet \ + --filter="description='$BACKUP_NOTE'" --format='table(id,status,windowStartTime)' +``` + +The replica's `masterInstanceName` names the primary. Wait for status +`SUCCESSFUL`, then record the backup ID in the deploy record. + +### 3. Check for long-running queries + +A migration statement waits 3 s for a lock, three times; a +`CREATE INDEX CONCURRENTLY` waits for every older snapshot. Each query below +should return no rows (the second returns `0`): + +```bash +psql "$PROD_DB_URL" -c "select pid, now()-query_start as runtime, state, left(query,80) + from pg_stat_activity where state <> 'idle' + and query_start < now() - interval '60 seconds' and pid <> pg_backend_pid();" +psql "$PROD_DB_URL" -c "select count(*) as blocked from pg_locks where granted = false;" +psql "$PROD_DB_URL" -c "select l.pid, a.state, now()-a.backend_start as connected + from pg_locks l join pg_stat_activity a on a.pid = l.pid + where l.locktype = 'advisory' and l.classid = 0 and l.objid = 4097083626 and l.objsubid = 1;" +``` + +The third query finds a holder of the goose advisory lock +(`lock.DefaultLockID = 4097083626`). If a query blocks, wait for it to end, or +end it with `pg_terminate_backend()` under approval. + +### 4. Apply the migrations + +Either let the container swap apply them (step 4 of the +[deploy runbook](coordinator-deploy.md#4-swap)), or apply them first with the +database-only command while the current coordinator serves. Use the +database-only command only when every pending version is additive: the +current coordinator keeps serving on the new schema. The command runs every +pending version and does not check compatibility. It moves index builds out of +the cutover window, but it does not prove a five-second handoff. + +```bash +sudo docker run --rm --network host --env-file /etc/d-inference/env \ + --entrypoint /usr/local/bin/coordinator \ + "${CANDIDATE_IMAGE%:*}@${CANDIDATE_DIGEST}" --migrate-only +``` + +The `--entrypoint` override is mandatory: the image's default `start.sh` +starts MicroMDM and touches persistent MDM state. The container needs no +userdata mount and publishes no port. The command seeds no admin key, starts +no listener or worker, and stops after 15 min +(`runMaintenanceCommand` in `coordinator/cmd/coordinator/maintenance.go`). Do +not start a second ordinary coordinator container. + +Expected JSON log lines, in this order: + +| `msg` | Fields | Meaning | +|---|---|---| +| `postgres startup phase` | `"phase":"connect","result":"applied"` | Connected and pinged | +| `postgres startup phase` | `"phase":"","result":"applied"` | One per index that versions 3 and 5 build; none when no such version is pending | +| `postgres migration` | `"version":N,"result":"applied","duration_ms":…` | One per applied version, all written after the run ends; none when nothing was pending | +| `coordinator migrations complete` | `duration_ms` | Exit 0 | + +On failure the last line is `coordinator maintenance command failed` with an +`error` field, and the exit code is 1; see [Troubleshooting](#troubleshooting). +Then rerun the step 3 queries and check `/health` of the serving coordinator. +Success here is not approval to swap. + +### 5. Verify + +Run the [verification queries](#verification). + +## Verification + +```bash +# Every candidate version is recorded, once. +psql "$PROD_DB_URL" -c "select version_id, is_applied, tstamp from goose_db_version order by id;" +# No invalid or unready index remains (expect no rows). +psql "$PROD_DB_URL" -c "select c.relname, i.indisvalid, i.indisready + from pg_index i join pg_class c on c.oid = i.indexrelid + join pg_namespace n on n.oid = c.relnamespace + where n.nspname = 'public' and not (i.indisvalid and i.indisready);" +# The schema matches the checked-in file of the candidate commit. +git show "$CANDIDATE_COMMIT:coordinator/store/schema/schema.sql" > /tmp/schema.candidate.sql +pg_dump "$PROD_DB_URL" --schema-only --no-owner --no-privileges --exclude-table=goose_db_version \ + | grep -v '^\\restrict \|^\\unrestrict \|^-- Dumped from database version\|^-- Dumped by pg_dump version' \ + | diff - /tmp/schema.candidate.sql +``` + +`goose_db_version` lists version 0 (goose writes it when it creates the table) +and then every version up to the candidate's highest. Only objects applied by +hand, such as the `request_waterfall` view +(`coordinator/store/migrations/request_waterfall.sql`), may differ in the +diff. Any other difference is a finding: record it and fix it under a separate +approved operation. + +## Troubleshooting + +### Lock timeout + +Log: three `postgres migration hit lock_timeout; retrying` warnings, then +`partial migration error (type:sql,version:N): ERROR: canceling statement due +to lock timeout (SQLSTATE 55P03)`. Version N is not recorded; a transactional +file rolled back, and the coordinator did not serve. Find the blocker with the +step 3 queries, wait for it or end it (approved), and run step 4 again. Do not +loop restarts of the container. + +### Invalid index + +Log: `index is invalid; repair the interrupted concurrent index build +before retrying` (versions 3 and 5, `ensureConcurrentIndex`). The build was +interrupted and left an invalid index; the version is not recorded. Under +approval, drop it without blocking writes, then run step 4 again: + +```bash +psql "$PROD_DB_URL" -c 'DROP INDEX CONCURRENTLY IF EXISTS ;' +``` + +Version 4 (`ensureProviderEarningsJobIndex`) drops an invalid +`idx_provider_earnings_job` itself with a plain `DROP INDEX`. That statement +takes an `ACCESS EXCLUSIVE` lock on `provider_earnings` and runs on the store +pool without a `lock_timeout`, so run step 3 first. + +### Partly applied NO TRANSACTION file + +A failed `-- +goose NO TRANSACTION` file keeps the statements that committed +before the failure, and its version is not recorded. Compare the file with +`\d ` to see which statements took effect. The next run executes the +whole file again; its statements are written to be safe to run twice, so +rerun step 4 after you remove the cause. Do not insert a row into +`goose_db_version` by hand. + +### A second coordinator waits on the lock + +Only one process migrates at a time. The other one tries the advisory lock +every 5 s and, after 5 min, exits 1 with `failed to initialize: failed to +acquire lock`. Find the holder with the third step 3 query. If it is a +`--migrate-only` run or a starting coordinator, let it finish. If it is a dead +session, end it with `pg_terminate_backend()` (approved); Postgres +releases a session lock when the session ends. + +## Rollback + +There are no down migrations; a rollback starts an older image on the +migrated schema ([deploy rollback](coordinator-deploy.md#rollback)). Choose +the image by these rules: + +1. **A goose image is safe** when the migrations after it were additive. It + finds its versions recorded and applies nothing. +2. **A pre-goose image** replays its own boot DDL and ignores + `goose_db_version`. It is safe only while no destructive migration has + applied: its `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and + its `DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later + `SET NOT NULL`. +3. **Never start a coordinator built before the + `backfill_withdrawable_balance_v1` marker existed**; the deploy runbook + states this rule. +4. **Restoring the backup is a last resort.** `gcloud sql backups restore + --restore-instance="$PRIMARY" --project=darkbloom-mainnet` + overwrites the instance and loses every write after the backup. It needs + its own approval. + +## First production cut-over to goose + +The first goose build records the existing schema as version 1 and applies +versions 2 to 5 once. They change nothing on a schema that the previous +coordinator built, but a lock timeout inside one of the baseline's +`DO ... EXCEPTION WHEN others` blocks is swallowed, and goose still records +version 1. + +- [ ] Step 1 shows `relation "goose_db_version" does not exist`. +- [ ] The candidate's highest version is 5, so the pre-goose image stays a + safe fallback ([rollback rule 2](#rollback)). +- [ ] The three retired-backfill markers exist + ([deploy step 2](coordinator-deploy.md#2-pre-swap-checks-vm-and-db)). +- [ ] Backup taken; its ID is in the deploy record (step 2). +- [ ] Step 3 is clean. +- [ ] Migrations applied (step 4 or the swap). The log shows + `postgres migration` for versions 1 to 5 with `"result":"applied"`. +- [ ] `goose_db_version` lists 0, 1, 2, 3, 4, 5. +- [ ] The invalid-index query returns no rows. +- [ ] The `pg_dump` diff shows only hand-applied objects. A missing column or + index means a swallowed statement; apply it under a separate approved + operation. + +## Related + +- [Deploy the coordinator](coordinator-deploy.md) — the container swap and its rollback +- [Schema lifecycle](../architecture/schema-lifecycle.md) — versions, locks, timeouts, failure modes +- [Add a database migration](../developer/database-migrations.md) — how migrations are written diff --git a/scripts/docs-impact-rules.json b/scripts/docs-impact-rules.json index 2b6df7a79c..c5c6913e41 100644 --- a/scripts/docs-impact-rules.json +++ b/scripts/docs-impact-rules.json @@ -79,10 +79,12 @@ "source_patterns": [ "coordinator/store/postgres.go", "coordinator/store/*migration*.go", - "coordinator/store/migrations/**" + "coordinator/store/migrations/**", + "coordinator/store/schema/**" ], "docs_any_of": [ - "docs/architecture/storage.md" + "docs/architecture/storage.md", + "docs/architecture/schema-lifecycle.md" ] }, { From 33050f73e32ff0578d7ac995285651d5b882cf39 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sun, 4 Oct 2026 13:26:16 -0500 Subject: [PATCH 10/20] Document the sqlc workflow and its type mapping Add docs/developer/sqlc.md: add a query, convert a hand-written store domain with api_keys as the worked example, naming and parameter conventions, make sqlc-generate and sqlc-check, and troubleshooting for a stale schema, DO-block columns, uncast expressions and reused parameters. Add docs/reference/sqlc-type-mapping.md, written from sqlc.yaml and the generated storedb code: the flags that change types, every mapping the current queries use with its store conversion, the query commands, and the schema types that no query reads yet. schema-lifecycle.md gains the schema.sql to sqlc to storedb to PostgresStore flow with a diagram, an invariant and code-map rows. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- docs/AGENTS.md | 1 + docs/README.md | 2 + docs/architecture/schema-lifecycle.md | 58 ++++++++++- docs/architecture/storage.md | 5 +- docs/developer/database-migrations.md | 4 +- docs/developer/sqlc.md | 145 ++++++++++++++++++++++++++ docs/reference/README.md | 3 +- docs/reference/sqlc-type-mapping.md | 89 ++++++++++++++++ 8 files changed, 299 insertions(+), 8 deletions(-) create mode 100644 docs/developer/sqlc.md create mode 100644 docs/reference/sqlc-type-mapping.md diff --git a/docs/AGENTS.md b/docs/AGENTS.md index e58fb45aa2..85885da9fe 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -175,6 +175,7 @@ and tests both historical-link handling and date-preserving, idempotent stamping | Trust level, attestation, enrollment, encryption | `architecture/security/*.md`; `provider/attestation.md`; `consumer/verification.md`; `threat-model.yaml` | | Pricing, ledger, payouts, referral | `architecture/billing.md`, `reference/pricing-model.md`, `consumer/billing.md` | | Store schema / migration | `architecture/schema-lifecycle.md` (versions, kinds, locks); `architecture/storage.md` (tables); `operations/schema-migration.md` if the change affects the production procedure or rollback rules | +| sqlc config, query file or generated type (`coordinator/store/sqlc.yaml`, `coordinator/store/queries/`) | `reference/sqlc-type-mapping.md` for a new type or override; `developer/sqlc.md` for a workflow or convention change | | Provider version bump (`ProviderCore.version` ↔ `LatestProviderVersion`) | `operations/provider-release.md`; `CHANGELOG.md` | | Build, test, CI, or script | `developer/build.md`, `developer/test.md`; `operations/` runbook that invokes it | | New model family or engine capability | `architecture/inference.md`, `consumer/models.md`, `provider/hardware-requirements.md` | diff --git a/docs/README.md b/docs/README.md index 9ad3575ede..aa6b18e4e4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -73,6 +73,7 @@ - [`reference/pricing-model.md`](reference/pricing-model.md): micro-USD units, price resolution, formulas, every billing constant (the single home for money constants), routes, service accounts. - [`reference/model-registry-format.md`](reference/model-registry-format.md): manifest schema, registration payload, alias format. - [`reference/qwen4-next-support.md`](reference/qwen4-next-support.md): native Flash-Next private identity, serving/state policy and explicitly incomplete qualification. +- [`reference/sqlc-type-mapping.md`](reference/sqlc-type-mapping.md): Postgres type and nullability → generated Go type in `storedb`, the `sqlc.yaml` flag behind it, and the store conversion. - [`reference/ssd-kv-cache.md`](reference/ssd-kv-cache.md): DBK3 on-disk format, paths, identity binding, env knobs, eviction rules, per-family reuse capability, status vocabularies. - [`glossary.md`](glossary.md): canonical terms and the page that owns each. @@ -106,6 +107,7 @@ - [`developer/build.md`](developer/build.md): build the coordinator, sidecar, provider, and UIs; toolchain pins. - [`developer/test.md`](developer/test.md): every test suite, what CI runs, how to run the e2e suite. - [`developer/database-migrations.md`](developer/database-migrations.md): choose the migration kind, add a numbered goose migration, change a column in two releases, regenerate the checked-in schema. +- [`developer/sqlc.md`](developer/sqlc.md): add a store query with sqlc, convert a hand-written store domain, `make sqlc-generate` and `make sqlc-check`. - [`developer/threat-model-review.md`](developer/threat-model-review.md): configure full PR text scans against the threat model and non-blocking author feedback. - [`developer/serving-performance-qualification.md`](developer/serving-performance-qualification.md): measure and review exact serving profiles before promoting concurrency limits or prefill policy. diff --git a/docs/architecture/schema-lifecycle.md b/docs/architecture/schema-lifecycle.md index f099144d6e..9daf6bf18a 100644 --- a/docs/architecture/schema-lifecycle.md +++ b/docs/architecture/schema-lifecycle.md @@ -4,8 +4,8 @@ Explanation of how the coordinator's Postgres schema changes: numbered goose migrations that run inside `NewPostgres` before the coordinator serves, the -locks and timeouts around them, and the checked-in schema file that tests -compare against. Read this before you add a migration +locks and timeouts around them, the checked-in schema file that tests compare +against, and the sqlc code generated from that file. Read this before you add a migration ([how-to](../developer/database-migrations.md)) or apply one in production ([runbook](../operations/schema-migration.md)). What the tables hold is in [storage](storage.md). @@ -160,6 +160,48 @@ from that file. `TestMigrationsLeaveLegacyDatabaseUnchanged` loads versions 1 to 5 change no object and no row. The [how-to](../developer/database-migrations.md) regenerates the file. +### Generated queries (sqlc) + +The api_keys queries of `PostgresStore` are SQL in +`coordinator/store/queries/api_keys.sql`. [sqlc](https://sqlc.dev) v1.31.1 +reads that file and `schema.sql` and writes typed Go into +`coordinator/store/storedb/` (`coordinator/store/sqlc.yaml`). The store +methods in `coordinator/store/postgres_api_keys.go` call the generated +`storedb.Queries` and convert each row to the public store type. + +```mermaid +flowchart TB + classDef src fill:#ede9fe,stroke:#6d28d9,color:#1e1035 + classDef step fill:#dbeafe,stroke:#1d4ed8,color:#0b1220 + classDef gen fill:#dcfce7,stroke:#15803d,color:#052e16 + classDef check fill:#fef3c7,stroke:#b45309,color:#1f1300 + M["schema/migrations/*.sql
and goMigrations"]:::src -- "goose on an empty DB,
then pg_dump" --> S["schema/schema.sql"]:::src + Q["queries/api_keys.sql"]:::src --> G["make
sqlc-generate
(sqlc.yaml)"]:::step + S --> G + G --> D["storedb/*.go
Queries, ApiKey, *Params"]:::gen + D --> P["PostgresStore methods
postgres_api_keys.go"]:::step + P --> T["store.APIKey"]:::step + C["CI check:
make sqlc-check"]:::check -. "schema test" .-> S + C -. "sqlc diff" .-> D +``` + +Legend: purple = checked-in source, blue = step or hand-written code, +green = generated code, amber = CI check. + +| Part | What it does | Where | +|---|---|---| +| Schema input | `schema: schema/schema.sql`. sqlc reads the dump, not the migrations: the baseline adds many columns inside `DO` blocks, which sqlc cannot see, so a query on such a column fails with `column "..." does not exist`. | `coordinator/store/sqlc.yaml` | +| Code generation | `sql_package: pgx/v5`, `emit_pointers_for_null_types: true`, `omit_unused_structs: true`, and `timestamptz` overrides to `time.Time` and `*time.Time` ([type mapping](../reference/sqlc-type-mapping.md)) | `coordinator/store/sqlc.yaml` | +| Database handle | `storedb.New(db DBTX)` takes the pool or a `pgx.Tx`; `PostgresStore.queries()` wraps the pool, and `RotateAPIKey` uses `storedb.New(tx)` | `coordinator/store/storedb/db.go`, `coordinator/store/postgres_api_keys.go` | +| Row conversion | `apiKeyFromRow` maps `storedb.ApiKey` to `APIKey`; `insertAPIKeyParams` maps back | `coordinator/store/postgres_api_keys.go` | +| Tool pin | `go run github.com/sqlc-dev/sqlc/cmd/sqlc@v1.31.1`: sqlc v1.31.1 needs Go 1.26, newer than `go.mod`, so it is not a `go.mod` tool | `Makefile` (`SQLC`) | +| CI check | `make sqlc-check` runs `TestMigrationsBuildCheckedInSchema`, then `sqlc diff`; the Coordinator Tests job runs it against its Postgres service | `Makefile`, `.github/workflows/ci.yml` | + +`SELECT *` in a query is expanded to the column list when the code is +generated. A running binary therefore selects only the columns it was built +with, and a new column does not break it. `MemoryStore` and `CachedStore` do +not use sqlc. Adding a query is [Write store queries with sqlc](../developer/sqlc.md). + ### Tables and files that are not goose versions `schema_migrations` is an older table. It holds the markers of the one-shot @@ -203,10 +245,13 @@ Logs carry bounded labels only, never SQL or parameters checks the retry. 5. **Migrations build exactly `schema.sql`** on a fresh database (`TestMigrationsBuildCheckedInSchema`). -6. **There are no down migrations.** No migration file has a +6. **The generated queries match `schema.sql` and the query files.** + `make sqlc-check` fails CI when `coordinator/store/storedb` is stale + (`Makefile`, `.github/workflows/ci.yml`). +7. **There are no down migrations.** No migration file has a `-- +goose Down` section. A rollback starts an older image on the migrated schema; it never reverts the schema. -7. **An older goose image applies nothing on a newer database.** Every version +8. **An older goose image applies nothing on a newer database.** Every version it knows is recorded, and goose ignores recorded versions it does not know. A pre-goose image ignores `goose_db_version` and replays its own boot DDL. @@ -220,6 +265,7 @@ Logs carry bounded labels only, never SQL or parameters | A `NO TRANSACTION` file failed after some statements | Its earlier statements committed; the version is not recorded | The next run executes the whole file again, so every statement in such a file must be safe to run twice (`IF NOT EXISTS`, `IF EXISTS`). | | Exit 1 with `index ... is invalid; repair the interrupted concurrent index build before retrying` | A `CONCURRENTLY` build in version 3 or 5 was interrupted | `ensureConcurrentIndex` does not repair it; [runbook](../operations/schema-migration.md#invalid-index). | | Exit 1 with `found duplicate migration version` | Two sources share a number | Renumber one. | +| CI fails in `make sqlc-check` | `schema.sql` or `coordinator/store/storedb` is stale | [sqlc troubleshooting](../developer/sqlc.md#troubleshooting). | | Exit 1 with `missing (out-of-order) migration` | A version below the highest applied one was never applied, for example after two branches added migrations | `SELECT version_id FROM goose_db_version ORDER BY id`; renumber the unapplied version above the highest one. | | Exit 1 with `database holds data that retired backfills never processed` or `balances.withdrawable_micro_usd is missing` | The database has history but never ran a backfill retired after v0.9.10 | Boot a v0.9.10 coordinator against it once, then redeploy (`checkRetiredBackfills`). | | Exit 1 with a `provider_earnings` duplicate `job_id` message | Rows share a non-empty `job_id`, so version 4 cannot build its unique index | Run `coordinator/store/migrations/dedupe_provider_earnings.sql` offline, then redeploy. | @@ -236,6 +282,9 @@ Logs carry bounded labels only, never SQL or parameters | Concurrent index helper and startup log line | `coordinator/store/postgres_startup.go` (`ensureConcurrentIndex`, `logStartupMigration`) | | Go migration bodies | `coordinator/store/postgres_retired_backfills.go`, `coordinator/store/postgres.go` (`ensureProviderEarningsJobIndex`), `coordinator/store/postgres_earnings_window_index.go` | | Database-only command | `coordinator/cmd/coordinator/maintenance.go` (`runMaintenanceCommand`) | +| sqlc config, queries, generated code | `coordinator/store/sqlc.yaml`, `coordinator/store/queries/`, `coordinator/store/storedb/` | +| api_keys store methods | `coordinator/store/postgres_api_keys.go` (`queries`, `apiKeyFromRow`, `insertAPIKeyParams`) | +| sqlc targets | `Makefile` (`sqlc-generate`, `sqlc-check`) | | Tests | `coordinator/store/postgres_migrations_test.go`, `coordinator/store/migration_harness_test.go` | | Manual SQL | `coordinator/store/migrations/` | @@ -243,5 +292,6 @@ Logs carry bounded labels only, never SQL or parameters - [Add a database migration](../developer/database-migrations.md) — the steps - [Apply schema migrations in production](../operations/schema-migration.md) — backup, checks, rollback +- [Write store queries with sqlc](../developer/sqlc.md) and [sqlc type mapping](../reference/sqlc-type-mapping.md) - [Storage](storage.md) — what the tables hold and which backend runs - [Deploy the coordinator](../operations/coordinator-deploy.md) — the container swap that runs the migrations diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 6ea894bceb..c2952533e5 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -116,8 +116,9 @@ the only connection-level knob; there is no separate host/user/password set. `NewPostgres` applies every pending goose migration before it returns; the coordinator serves only after they all succeed. Each version runs once and is recorded in `goose_db_version`. `coordinator/store/schema/schema.sql` is the -checked-in `pg_dump` of the schema that the migrations build. The versions, -locks, timeouts and failure modes are in +checked-in `pg_dump` of the schema that the migrations build; sqlc generates +the api_keys queries from it. The versions, +locks, timeouts, sqlc and failure modes are in [schema lifecycle](schema-lifecycle.md); adding a migration is [Add a database migration](../developer/database-migrations.md). diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index 53b40f0303..0bd2a1ff63 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -126,7 +126,8 @@ in production is the [schema migration runbook](../operations/schema-migration.m must show only your change. 6. **Regenerate the sqlc code** if a query in `coordinator/store/queries/` - reads the changed table: `make sqlc-generate`. + reads the changed table: `make sqlc-generate` + ([Write store queries with sqlc](sqlc.md)). 7. **Update the rest of the store.** Make `MemoryStore` (`coordinator/store/memory.go`) match, and update the docs that describe @@ -218,5 +219,6 @@ safe. - [Schema lifecycle](../architecture/schema-lifecycle.md) — how goose runs, locks, timeouts, failure modes - [Apply schema migrations in production](../operations/schema-migration.md) — backup, checks, rollback +- [Write store queries with sqlc](sqlc.md) — queries generated from `schema.sql` - [Storage](../architecture/storage.md) — what the tables hold - [Test](test.md) — running the Postgres tests diff --git a/docs/developer/sqlc.md b/docs/developer/sqlc.md new file mode 100644 index 0000000000..2207c4c15e --- /dev/null +++ b/docs/developer/sqlc.md @@ -0,0 +1,145 @@ +# Write store queries with sqlc + +> Last updated: 2026-10-04 + +How to add a Postgres query to the coordinator store with sqlc, how to move a +hand-written store domain to sqlc (the api_keys domain is the worked +example), and how to check the generated code. Why the store uses sqlc and +how the pieces fit is in +[schema lifecycle](../architecture/schema-lifecycle.md#generated-queries-sqlc); +the Postgres-to-Go types are in [sqlc type mapping](../reference/sqlc-type-mapping.md). + +## Prerequisites + +- Go with the default `GOTOOLCHAIN=auto`, or Go 1.26. `make sqlc-generate` + runs `go run github.com/sqlc-dev/sqlc/cmd/sqlc@v1.31.1`, and sqlc v1.31.1 + needs Go 1.26 (`Makefile`, `SQLC`). +- For `make sqlc-check`, a throwaway Postgres server and `DATABASE_URL`, as in + [Add a database migration](database-migrations.md#prerequisites). +- A `coordinator/store/schema/schema.sql` that includes the tables and columns + your query reads. If your change also adds a migration, regenerate that file + first ([step 5 of the migration how-to](database-migrations.md#steps)). + +## Steps: add a query + +1. Add the query to the domain's file in `coordinator/store/queries/`, for + example `coordinator/store/queries/api_keys.sql`. Start it with a name and + a command: + + ```sql + -- name: GetAPIKeyByID :one + SELECT * FROM api_keys WHERE id = $1 AND owner_account_id = $2; + ``` + + Follow the [conventions](#conventions) below for the name, the command and + the parameters. + +2. Generate the Go code: + + ```bash + make sqlc-generate + ``` + + sqlc writes `coordinator/store/storedb/.sql.go` and updates + `coordinator/store/storedb/models.go`. A query with one parameter takes it + as an argument; two or more become a `Params` struct + (`storedb.GetAPIKeyByIDParams`). Do not edit generated files. + +3. Call the query from the store method, through `s.queries()` or, inside a + transaction, `storedb.New(tx)`: + + ```go + row, err := s.queries().GetAPIKeyByID(ctx, storedb.GetAPIKeyByIDParams{ID: id, OwnerAccountID: accountID}) + if err != nil { + return nil, err + } + return apiKeyFromRow(row), nil + ``` + + Convert the generated row to the public store type in one function per + domain (`apiKeyFromRow` in `coordinator/store/postgres_api_keys.go`). Keep + storage encodings, such as the JSON text in `api_keys.allowed_models`, in + that function and its inverse (`insertAPIKeyParams`). + +4. If the method is new on the `Store` interface, implement it in + `MemoryStore` too and cover both backends in one test, as + `TestAPIKeyLifecycleOnEveryBackend` (`coordinator/store/apikey_backends_test.go`) + does. + +## Steps: convert a hand-written domain + +The api_keys domain moved from hand-written SQL in +`coordinator/store/postgres.go` to sqlc without a change to the `Store` +interface, `MemoryStore` or `CachedStore`. Repeat these steps for another +domain. + +1. List every SQL statement of the domain and the helpers it uses. For + api_keys the statements became twelve named queries; the helpers were the + `apiKeyColumns` select list and `scanAPIKeyRow`. +2. Write each statement as a named query in + `coordinator/store/queries/
.sql`. Keep its `WHERE`, `ORDER BY`, + `FOR UPDATE` and `ON CONFLICT` clauses exactly; `GetAPIKeyByIDForUpdate` + keeps the row lock that `RotateAPIKey` needs. +3. Run `make sqlc-generate`. +4. Move the domain's methods to `coordinator/store/postgres_.go` + (`coordinator/store/postgres_api_keys.go`) and make them call the + generated queries. Keep transactions in the store method: `RotateAPIKey` + begins the transaction on the pool and runs its read, insert and delete + through `storedb.New(tx)`. +5. Write one row-to-type function and one type-to-params function. Two + generated structs with the same fields convert directly: + `storedb.InsertAPIKeyIfAbsentParams(insertAPIKeyParams(rec))` in `SeedKey`. +6. Delete the old SQL strings and scan helpers. +7. Run the domain's existing tests unchanged, add a test that runs the same + lifecycle on both backends, and run `make sqlc-check`. + +## Conventions + +| Topic | Rule | Example | +|---|---|---| +| File | One file per table or domain under `coordinator/store/queries/` | `coordinator/store/queries/api_keys.sql` | +| Query name | Verb, noun, qualifier, in PascalCase; spell initialisms as `API`, `ID` | `GetAPIKeyByHash`, `ListAPIKeysByOwner`, `GetAPIKeyByIDForUpdate`, `InsertAPIKeyIfAbsent`, `DeactivateAPIKeyByHash` | +| Command | `:one` for one row (no row returns `pgx.ErrNoRows`); `:many` for a slice; `:exec` when only the error matters; `:execrows` when the caller needs the affected-row count | `UpdateAPIKey :execrows` lets `UpdateAPIKey` return `key not found` on 0 rows | +| Positional parameter | `$n`, each used once and compared with a column; sqlc names it after the column | `$1` in `GetActiveKeyAccount` becomes `keyHash string` | +| Named parameter | `sqlc.arg('name')` when a positional name would be unclear | `sqlc.arg('key_id')` in `KeySpendSince` | +| Nullable parameter | `sqlc.narg('name')` plus a cast; it becomes a pointer | `sqlc.narg('since')::timestamptz` becomes `Since *time.Time` | +| Reused parameter | Name it; use the same `sqlc.arg`/`sqlc.narg` each time | `since` appears twice in `KeySpendSince` and is one field | +| Expression result | Cast it, or sqlc types it `interface{}` | `COALESCE(SUM(cost_micro_usd), 0)::bigint AS total_micro_usd` returns `int64` | +| Struct names | Generated from the table name, singular, with sqlc's default casing; there are no renames in `sqlc.yaml` | table `api_keys` becomes `storedb.ApiKey`; `limit_micro_usd` becomes `LimitMicroUsd` | +| `SELECT *` | Allowed; sqlc expands it to the column list at generation time | `GetAPIKeyByHash` | + +## Verify + +```bash +make sqlc-check +``` + +It needs `DATABASE_URL`. It runs `TestMigrationsBuildCheckedInSchema` (fails +when `schema.sql` is stale), then `sqlc diff` (prints a unified diff and fails +when `coordinator/store/storedb` is stale). CI runs it in the Coordinator +Tests job. Then run the store tests of the domain on Postgres: + +```bash +go test ./coordinator/store -count=1 -run 'APIKey' +``` + +## Troubleshooting + +| Symptom | Cause | Fix | +|---|---|---| +| `make sqlc-check` prints `--- a/storedb/...` and fails | The generated code is stale | `make sqlc-generate`, then commit `coordinator/store/storedb`. | +| `sqlc-check: set DATABASE_URL to a disposable Postgres server` | `DATABASE_URL` is unset | Point it at a throwaway server. | +| `TestMigrationsBuildCheckedInSchema` fails inside `make sqlc-check` | `schema.sql` is stale | Regenerate it ([migration how-to step 5](database-migrations.md#steps)), then `make sqlc-generate`. | +| sqlc reports `column "..." does not exist` | `schema.sql` lacks the column (stale), or `sqlc.yaml` was pointed at `coordinator/store/schema/migrations/`, where the baseline adds columns inside `DO` blocks that sqlc cannot see | Regenerate `schema.sql`; keep `schema: schema/schema.sql`. | +| A result or parameter is `interface{}` | An expression or `sqlc.narg` without a cast, for example `COALESCE(SUM(x), 0)` | Cast it: `::bigint`, `::timestamptz`. | +| A parameter is `pgtype.Timestamp`, not `*time.Time` | The cast is `::timestamp` (without time zone); the overrides cover only `timestamptz` | Cast to `::timestamptz`. | +| A parameter is named `dollar_1` | A positional parameter that sqlc cannot tie to a column | Use `sqlc.arg('name')`. | +| A reused `$1` has the name of only its first column | sqlc gives a positional parameter one name | Use one `sqlc.arg('name')` for both places, or two parameters. | +| `go: downloading go1.26...` fails | `GOTOOLCHAIN=local` with an older Go | Unset `GOTOOLCHAIN` or install Go 1.26. | + +## Related + +- [Schema lifecycle](../architecture/schema-lifecycle.md#generated-queries-sqlc) — where sqlc sits between the schema and the store +- [sqlc type mapping](../reference/sqlc-type-mapping.md) — Postgres type to Go type, and the store conversion +- [Add a database migration](database-migrations.md) — change the schema that sqlc reads +- [Build](build.md#make-targets) — `sqlc-generate` and `sqlc-check` diff --git a/docs/reference/README.md b/docs/reference/README.md index f64c314b34..8c2c89f402 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -1,6 +1,6 @@ # Reference — exact shapes and values -> Last updated: 2026-09-27 +> Last updated: 2026-10-04 Tables and schemas for Darkbloom's public interfaces, wire protocol, configuration, and formats. Consult these; do not read them front to back. @@ -28,6 +28,7 @@ Every row cites the code that defines it. For how and why things work, use | [telemetry-inventory.md](telemetry-inventory.md) | Every telemetry datum collected — producer, sink, cadence, retention — and the Datadog metric-name inventory with tags and emitting file | | [pricing-model.md](pricing-model.md) | Micro-USD units, price resolution order, formulas, every billing constant (single home for money constants), routes, service accounts | | [model-registry-format.md](model-registry-format.md) | Manifest schema, registration payload, alias format | +| [sqlc-type-mapping.md](sqlc-type-mapping.md) | Postgres type and nullability → generated Go type in `coordinator/store/storedb`, the `sqlc.yaml` flag that causes it, and the store conversion | | [qwen4-next-support.md](qwen4-next-support.md) | Native Flash-Next private serving/state contract and pending qualification; not a catalog or release claim | ## Prefix cache formats diff --git a/docs/reference/sqlc-type-mapping.md b/docs/reference/sqlc-type-mapping.md new file mode 100644 index 0000000000..777e16de85 --- /dev/null +++ b/docs/reference/sqlc-type-mapping.md @@ -0,0 +1,89 @@ +# sqlc type mapping + +> Last updated: 2026-10-04 + +Reference for the Go types that sqlc v1.31.1 generates in +`coordinator/store/storedb/` from `coordinator/store/schema/schema.sql` +under `coordinator/store/sqlc.yaml`, and how the store converts each one to +its public type. How to write a query is +[Write store queries with sqlc](../developer/sqlc.md). + +## Configuration flags + +Each flag in `coordinator/store/sqlc.yaml` that changes a Go type. + +| Setting | Value | Effect on the generated types | +|---|---|---| +| `sql_package` | `pgx/v5` | Queries take a `storedb.DBTX` (`Exec`, `Query`, `QueryRow` of pgx v5; `coordinator/store/storedb/db.go`). Without the overrides below, `timestamptz` and `timestamp` come from `pgtype`. | +| `emit_pointers_for_null_types` | `true` | A nullable column or parameter becomes a pointer (`*int64`), not a `pgtype` wrapper (`pgtype.Int8`). | +| `omit_unused_structs` | `true` | `coordinator/store/storedb/models.go` holds only the table structs that a query returns (`ApiKey`). | +| `overrides`: `db_type: pg_catalog.timestamptz` | `go_type: time.Time`; with `nullable: true`, `*time.Time` | Applies to schema columns (`pg_dump` writes them as `timestamp with time zone`). Without it a column is `pgtype.Timestamptz`. | +| `overrides`: `db_type: timestamptz` | `go_type: time.Time`; with `nullable: true`, `*time.Time` | Applies to a `::timestamptz` cast in a query, as in `KeySpendSince`. Without it `Since` is `pgtype.Timestamptz`. | + +## Mappings in the generated code + +Every Postgres type that a checked-in query reads or writes. Fields are in +`storedb.ApiKey` (`coordinator/store/storedb/models.go`) and the +`*Params` structs (`coordinator/store/storedb/api_keys.sql.go`). Conversions +are in `coordinator/store/postgres_api_keys.go`. + +| Postgres type | Null | Go type in `storedb` | Caused by | Column or expression → field | Store conversion to the public type | +|---|---|---|---|---|---| +| `text` | `NOT NULL` | `string` | default | `api_keys.key_hash` → `KeyHash`; `owner_account_id` → `OwnerAccountID`; `id` → `ID`; `name` → `Name` | Copied to the `APIKey` field of the same name (`apiKeyFromRow`) | +| `text` | `NOT NULL` | `string` | default | `api_keys.raw_prefix` → `RawPrefix` | Copied to `APIKey.Label` | +| `text` | `NOT NULL` | `string` | default | `api_keys.limit_reset` → `LimitReset` | `NormalizeResetWindow` on read and write | +| `text` (JSON array) | `NOT NULL` | `string` | default | `api_keys.allowed_models` → `AllowedModels` | `decodeModelList` to `[]string` (`""`, `[]` or invalid JSON → `nil`); `encodeModelList` back (empty → `""`) | +| `boolean` | `NOT NULL` | `bool` | default | `api_keys.active` → `Active` | Inverted: `APIKey.Disabled = !row.Active`; params set `Active: !rec.Disabled` | +| `boolean` | `NOT NULL` | `bool` | default | `api_keys.self_route_only` → `SelfRouteOnly` | Copied | +| `bigint` | nullable | `*int64` | `emit_pointers_for_null_types` | `api_keys.limit_micro_usd`, `rpm_limit`, `itpm_limit`, `otpm_limit` → `LimitMicroUsd`, `RpmLimit`, `ItpmLimit`, `OtpmLimit` | Copied to `LimitMicroUSD`, `RPMLimit`, `ITPMLimit`, `OTPMLimit`; `nil` means unlimited or inherited | +| `bigint` (expression) | never null | `int64` | the `::bigint` cast | `COALESCE(SUM(cost_micro_usd), 0)::bigint` in `KeySpendSince` → result | Returned as is; an error returns `0` (`PostgresStore.KeySpendSince`) | +| `timestamptz` | `NOT NULL` | `time.Time` | override `pg_catalog.timestamptz` | `api_keys.created_at` → `CreatedAt` | Copied; writers pass `time.Now().UTC()` | +| `timestamptz` | nullable | `*time.Time` | override `pg_catalog.timestamptz`, `nullable: true` | `api_keys.expires_at`, `last_used_at` → `ExpiresAt`, `LastUsedAt` | Copied; `TouchAPIKey` passes `&lastUsed` (UTC) | +| `timestamptz` (cast parameter) | nullable | `*time.Time` | override `timestamptz`, `nullable: true`; `sqlc.narg` | `sqlc.narg('since')::timestamptz` → `KeySpendSinceParams.Since` | A zero `time.Time` becomes `nil`, which matches every row | +| `text` (parameter) | — | `string` | default | `sqlc.arg('key_id')` compared with `usage.key_id` → `KeySpendSinceParams.KeyID` | Passed as is | + +## Query commands + +| Annotation | Generated signature | Store use | +|---|---|---| +| `:one` | `(T, error)`; no row returns `pgx.ErrNoRows` | `GetAPIKeyByHash`, `GetAPIKeyByID`, `GetAPIKeyByIDForUpdate`, `GetActiveKeyAccount`, `KeySpendSince` | +| `:many` | `([]T, error)` | `ListAPIKeysByOwner` | +| `:exec` | `error` | `InsertAPIKey`, `InsertAPIKeyIfAbsent`, `TouchAPIKey` | +| `:execrows` | `(int64, error)` (rows affected) | `UpdateAPIKey`, `DeleteAPIKeyByID` (0 → `key not found`), `DeactivateAPIKeyByHash` (`RevokeKey` returns `> 0`) | + +A query with one parameter takes it as an argument +(`GetActiveKeyAccount(ctx, keyHash string)`); two or more become a +`Params` struct. `SELECT *` returns the table struct (`ApiKey`); a +narrower select returns a scalar or a `Row` struct. + +## Schema types that no query uses yet + +The schema also has these types. No checked-in query reads them, so +`storedb` has no field for them yet. The Go types below are the output of +sqlc v1.31.1 with `coordinator/store/sqlc.yaml` for a one-column probe query +on each listed column (2026-10-04). Check the generated code when you add the +first query, and move the row to the table above. + +| Postgres type | Null | Go type | Caused by | Probe column in `coordinator/store/schema/schema.sql` | +|---|---|---|---|---| +| `text` | nullable | `*string` | `emit_pointers_for_null_types` | `darkbloom_machines.merged_into` | +| `bigint` | `NOT NULL` | `int64` | default | `ledger_entries.id` | +| `integer` | `NOT NULL` | `int32` | default | `fleet_snapshots.num_running` | +| `integer` | nullable | `*int32` | `emit_pointers_for_null_types` | `inference_routes.effective_queue` | +| `smallint` | `NOT NULL` | `int16` | default | `provider_verification_jobs.priority` | +| `double precision` | `NOT NULL` | `float64` | default | `fleet_snapshots.observed_decode_tps` | +| `double precision` | nullable | `*float64` | `emit_pointers_for_null_types` | `fleet_snapshots.free_for_load_gb` | +| `boolean` | nullable | `*bool` | `emit_pointers_for_null_types` | `fleet_snapshots.ewma_initialized` | +| `jsonb` | `NOT NULL` | `[]byte` | default | `providers.hardware` | +| `jsonb` | nullable | `[]byte` (`nil` for `NULL`) | default; the pointer flag does not apply | `model_versions.hugging_face_artifact`, `fleet_snapshots.queue_depth_by_model` | +| `bytea` | `NOT NULL` | `[]byte` | default | `app_attest_evidence_blobs.proof` | +| `text[]` | `NOT NULL` | `[]string` | default | `model_registry.capabilities`; a `::text[]` parameter is also `[]string` | + +The schema has no `numeric`, `uuid`, `date` or `timestamp without time zone` +column. A `::timestamp` cast in a query generates `pgtype.Timestamp`, because +the overrides cover only `timestamptz`. + +## Related + +- [Write store queries with sqlc](../developer/sqlc.md) — add a query, convert a domain, troubleshooting +- [Schema lifecycle](../architecture/schema-lifecycle.md#generated-queries-sqlc) — how `schema.sql`, sqlc and the store fit together From f51f8e155697f67528401cd3293158de419110ce Mon Sep 17 00:00:00 2001 From: David Tai Date: Sun, 4 Oct 2026 13:43:04 -0500 Subject: [PATCH 11/20] Document soft delete, the index migrations and the soft-delete release Add docs/reference/soft-delete.md: the tables with deleted_at, every store read that hides a soft-deleted row in PostgresStore and MemoryStore, the paths that do not filter, the indexes, and what a soft delete changes. schema-lifecycle.md gains versions 6 to 17, the indexMigrations kind with its 1 min lock_timeout and leftover repair, the soft-delete model with a diagram, and the matching invariants and failure modes. The migration how-to gains real examples for each kind, the new tests and an "add soft delete to a table" procedure. The runbook gains the soft-delete rollback rules and a checklist for the soft-delete release; coordinator-deploy.md links to them instead of repeating them. Refs DBLM-552 Co-Authored-By: Claude Opus 5.5 --- docs/AGENTS.md | 1 + docs/README.md | 1 + docs/architecture/schema-lifecycle.md | 121 +++++++++++++++++++++---- docs/architecture/storage.md | 21 ++--- docs/developer/database-migrations.md | 82 +++++++++++++---- docs/operations/coordinator-deploy.md | 8 -- docs/operations/schema-migration.md | 56 ++++++++++-- docs/reference/README.md | 1 + docs/reference/soft-delete.md | 125 ++++++++++++++++++++++++++ docs/reference/sqlc-type-mapping.md | 1 + 10 files changed, 356 insertions(+), 61 deletions(-) create mode 100644 docs/reference/soft-delete.md diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 85885da9fe..e57fc45319 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -175,6 +175,7 @@ and tests both historical-link handling and date-preserving, idempotent stamping | Trust level, attestation, enrollment, encryption | `architecture/security/*.md`; `provider/attestation.md`; `consumer/verification.md`; `threat-model.yaml` | | Pricing, ledger, payouts, referral | `architecture/billing.md`, `reference/pricing-model.md`, `consumer/billing.md` | | Store schema / migration | `architecture/schema-lifecycle.md` (versions, kinds, locks); `architecture/storage.md` (tables); `operations/schema-migration.md` if the change affects the production procedure or rollback rules | +| A read or write of a soft-delete table (`users`, `api_keys`, `providers`, `provider_tokens`) | `reference/soft-delete.md` | | sqlc config, query file or generated type (`coordinator/store/sqlc.yaml`, `coordinator/store/queries/`) | `reference/sqlc-type-mapping.md` for a new type or override; `developer/sqlc.md` for a workflow or convention change | | Provider version bump (`ProviderCore.version` ↔ `LatestProviderVersion`) | `operations/provider-release.md`; `CHANGELOG.md` | | Build, test, CI, or script | `developer/build.md`, `developer/test.md`; `operations/` runbook that invokes it | diff --git a/docs/README.md b/docs/README.md index aa6b18e4e4..0688177910 100644 --- a/docs/README.md +++ b/docs/README.md @@ -73,6 +73,7 @@ - [`reference/pricing-model.md`](reference/pricing-model.md): micro-USD units, price resolution, formulas, every billing constant (the single home for money constants), routes, service accounts. - [`reference/model-registry-format.md`](reference/model-registry-format.md): manifest schema, registration payload, alias format. - [`reference/qwen4-next-support.md`](reference/qwen4-next-support.md): native Flash-Next private identity, serving/state policy and explicitly incomplete qualification. +- [`reference/soft-delete.md`](reference/soft-delete.md): the tables with `deleted_at`, every store read that hides a soft-deleted row, the paths that do not filter, the indexes, and what a soft delete changes. - [`reference/sqlc-type-mapping.md`](reference/sqlc-type-mapping.md): Postgres type and nullability → generated Go type in `storedb`, the `sqlc.yaml` flag behind it, and the store conversion. - [`reference/ssd-kv-cache.md`](reference/ssd-kv-cache.md): DBK3 on-disk format, paths, identity binding, env knobs, eviction rules, per-family reuse capability, status vocabularies. - [`glossary.md`](glossary.md): canonical terms and the page that owns each. diff --git a/docs/architecture/schema-lifecycle.md b/docs/architecture/schema-lifecycle.md index 9daf6bf18a..2fade39637 100644 --- a/docs/architecture/schema-lifecycle.md +++ b/docs/architecture/schema-lifecycle.md @@ -5,7 +5,7 @@ Explanation of how the coordinator's Postgres schema changes: numbered goose migrations that run inside `NewPostgres` before the coordinator serves, the locks and timeouts around them, the checked-in schema file that tests compare -against, and the sqlc code generated from that file. Read this before you add a migration +against, the sqlc code generated from that file, and the soft-delete model. Read this before you add a migration ([how-to](../developer/database-migrations.md)) or apply one in production ([runbook](../operations/schema-migration.md)). What the tables hold is in [storage](storage.md). @@ -66,9 +66,18 @@ Legend: blue = step, amber = decision, green = success, red = exit 1. | 3 | `ensureProviderRestoreIndexes` (`coordinator/store/postgres_startup.go`) | Builds `idx_providers_restore_serial` and `idx_providers_restore_se_key` `CONCURRENTLY` through `ensureConcurrentIndex`. | | 4 | `ensureProviderEarningsJobIndex` (`coordinator/store/postgres.go`) | Drops an invalid leftover with a plain `DROP INDEX`, fails on duplicate non-empty `job_id`s, then builds the unique `idx_provider_earnings_job` `CONCURRENTLY`. | | 5 | `ensureProviderEarningsWindowIndex` (`coordinator/store/postgres_earnings_window_index.go`) | Builds the BRIN `idx_provider_earnings_created_at_brin` through `ensureConcurrentIndex` and sets `autovacuum_analyze_scale_factor` to `0.005`. | +| 6–12 | `indexMigrations` (`coordinator/store/postgres_migration_indexes.go`) | One erase-path index per version, `CONCURRENTLY`: `account_id` on `provider_sessions`, `provider_log_reports`, `device_codes`, `darkbloom_machine_sessions`, `model_token_reservations`; `consumer_key_hash` on `inference_routes` and `request_rejections`. | +| 13 | `coordinator/store/schema/migrations/00013_soft_delete_columns.sql` | `NO TRANSACTION`: adds `deleted_at TIMESTAMPTZ` (nullable, no default) to `users`, `api_keys`, `providers`, `provider_tokens`, one `ALTER` at a time. | +| 14 | `indexMigrations` | `CREATE UNIQUE INDEX CONCURRENTLY idx_users_privy_live ON users (privy_user_id) WHERE deleted_at IS NULL`. | +| 15 | `coordinator/store/schema/migrations/00015_users_privy_drop_unique_constraint.sql` | One transaction: drops `users_privy_user_id_key`. | +| 16 | `coordinator/store/schema/migrations/00016_users_privy_drop_old_index.sql` | `NO TRANSACTION`: `SET lock_timeout = '1min'`, then `DROP INDEX CONCURRENTLY IF EXISTS idx_users_privy`. | +| 17 | `coordinator/store/schema/migrations/00017_referrals_referrer_code_cascade.sql` | `NO TRANSACTION`: adds `referrals_referrer_code_cascade_fkey` (`ON UPDATE CASCADE`) `NOT VALID`, validates it, then drops `referrals_referrer_code_fkey`. | Versions 2 to 5 are Go migrations, listed in `goMigrations`. They are the startup steps that ran after the old DDL loop, with their code unchanged. +Versions 6 to 12 and 14 are Go migrations in `indexMigrations`; +`allGoMigrations` passes both lists to goose. Goose runs SQL and Go versions +in one sequence, so version 13 adds `deleted_at` before version 14 indexes it. Goose reads SQL files from the embedded `migrationFiles` and refuses two sources with the same version (`found duplicate migration version`) and an unapplied version below the highest applied one @@ -78,19 +87,23 @@ unapplied version below the highest applied one | Kind | How goose runs it | Why it exists | Example | |---|---|---|---| -| SQL file (default) | All statements and the `goose_db_version` insert in one transaction, on the connection that holds the advisory lock | A change that must apply completely or not at all | None yet; template in the [how-to](../developer/database-migrations.md) | -| SQL file with `-- +goose NO TRANSACTION` | Each statement (or each `StatementBegin`/`StatementEnd` block) commits on its own; the version is recorded after the last one | A statement that cannot run in a transaction (`DROP INDEX CONCURRENTLY`), or a file whose locks must be held one at a time | Version 1 | +| SQL file (default) | All statements and the `goose_db_version` insert in one transaction, on the connection that holds the advisory lock | A change that must apply completely or not at all | Version 15 | +| SQL file with `-- +goose NO TRANSACTION` | Each statement (or each `StatementBegin`/`StatementEnd` block) commits on its own; the version is recorded after the last one | A statement that cannot run in a transaction (`DROP INDEX CONCURRENTLY`), or a file whose locks must be held one at a time | Versions 1, 13, 16, 17 | | Go migration (`goose.NewGoMigration` with `RunDB`) | Goose calls the function, then records the version on the second migration connection; no transaction | A step that must read the database before it acts, or check its result | Versions 2 and 4 | -| Concurrent index (Go migration through `ensureConcurrentIndex`) | Checks `pg_index`, builds the index with one simple-protocol statement, then checks that it is valid | `CREATE INDEX CONCURRENTLY` cannot run in a transaction, and a failed build leaves an invalid index that `IF NOT EXISTS` would hide | Versions 3 and 5 | +| Concurrent index (`indexMigrations`, `buildConcurrentIndex`) | Opens its own connection with a 1 min `lock_timeout`, returns at once for a valid index, drops an invalid leftover with `DROP INDEX CONCURRENTLY`, builds the index, and fails unless it is valid and ready | `CREATE INDEX CONCURRENTLY` cannot run in a transaction, and a failed build leaves an invalid index that `IF NOT EXISTS` would hide | Versions 6 to 12 and 14 | +| Concurrent index, pre-goose steps (`ensureConcurrentIndex`) | Runs on the store pool, refuses an invalid leftover, builds, checks validity | Kept unchanged from before goose | Versions 3 and 5 | An SQL file must not contain `CREATE INDEX CONCURRENTLY` (`TestSQLMigrationsDoNotBuildIndexesConcurrently` in `coordinator/store/postgres_migrations_test.go`). A build that fails, for example on `lock_timeout`, leaves an invalid index; on the next attempt `IF NOT EXISTS` skips it and goose records the version with a broken index. -`ensureConcurrentIndex` returns at once for a valid index, refuses an invalid -one by name (`index ... is invalid; repair the interrupted concurrent index -build before retrying`), and fails unless the new index is valid and ready. +`buildConcurrentIndex` (`coordinator/store/postgres_migration_indexes.go`) +repairs that case itself: the goose advisory lock keeps another migration run +from building the same index, so it can drop the leftover and build again. +`ensureConcurrentIndex` (versions 3 and 5) does not repair it; it refuses an +invalid index by name (`index ... is invalid; repair the interrupted +concurrent index build before retrying`). ### Locks and timeouts @@ -102,7 +115,9 @@ build before retrying`), and fails unless the new index is valid and ready. | URL override | a `lock_timeout` or `statement_timeout` parameter in `EIGENINFERENCE_DATABASE_URL` | `migrateOnce` | The URL value wins over both defaults. | | Retries | `migrationAttempts = 3`; pauses of 1 s and 2 s | `migrate`, `isLockTimeout` | Only a lock timeout is retried. Each attempt opens a new migration pool and starts again from the pending check. | | Advisory lock | session lock `4097083626` (goose `lock.DefaultLockID`), `pg_try_advisory_lock` every 5 s, 60 retries | `lock.NewPostgresSessionLocker` in `newMigrationProvider` | Two coordinators that start together take turns. The second one gives up after 5 min with `failed to acquire lock`. | -| Go migrations | no session timeouts unless the URL sets them | `goMigrations` run on the store pool | Keeps the pre-goose behaviour of versions 2 to 5: a `CREATE INDEX CONCURRENTLY` that times out leaves an invalid index. | +| Go migrations 2 to 5 | no session timeouts unless the URL sets them | `goMigrations` run on the store pool | Keeps the pre-goose behaviour: a `CREATE INDEX CONCURRENTLY` that times out leaves an invalid index. | +| Index migrations 6 to 12 and 14 | `concurrentIndexLockTimeout = time.Minute` as `lock_timeout`; no `statement_timeout` unless the URL sets one | `buildConcurrentIndexOnce` | The build waits up to 1 min for older snapshots instead of 3 s. It overrides a `lock_timeout` in the URL. A timeout is SQLSTATE `55P03`, so `migrate` retries it, and the retry drops the invalid leftover. | +| `DROP INDEX CONCURRENTLY` in version 16 | `SET lock_timeout = '1min'` in the file | `00016_users_privy_drop_old_index.sql` | The same wait for older snapshots, inside an SQL migration. | | `--migrate-only` | `context.WithTimeout(..., 15*time.Minute)` | `runMaintenanceCommand` | The whole run stops after 15 min. The serving path has no such deadline. | `CREATE INDEX CONCURRENTLY` blocks no reads or writes, but it waits for every @@ -155,9 +170,12 @@ fix the writer. --no-owner --no-privileges` of the schema that the migrations build, without `goose_db_version`. `TestMigrationsBuildCheckedInSchema` builds a fresh database with goose and fails when its catalog differs from a database loaded -from that file. `TestMigrationsLeaveLegacyDatabaseUnchanged` loads -`schema.sql` with the marker rows that a pre-goose boot leaves and checks that -versions 1 to 5 change no object and no row. The +from that file. `TestMigrationsUpgradeLegacyDatabase` loads +`coordinator/store/testdata/schema_pre_goose.sql`, the frozen dump of the +schema that the pre-goose boot built, with the marker rows that boot leaves. +It checks that versions 1 to `lastPreGooseVersion` (5) change no object and no +row, and that all versions then reach `schema.sql`. Never regenerate the +pre-goose dump. The [how-to](../developer/database-migrations.md) regenerates the file. ### Generated queries (sqlc) @@ -202,6 +220,56 @@ generated. A running binary therefore selects only the columns it was built with, and a new column does not break it. `MemoryStore` and `CachedStore` do not use sqlc. Adding a query is [Write store queries with sqlc](../developer/sqlc.md). +### Soft delete + +Account erasure must hide an account's rows at once and must let the same +person sign up again. Four tables carry a nullable `deleted_at TIMESTAMPTZ` +(version 13). A row with `deleted_at` set belongs to an erased account. No +code sets the column yet; the erasure writer will. Every store read that +returns a live user, key, provider record or provider token filters +`deleted_at IS NULL` in `PostgresStore` and checks `DeletedAt` in +`MemoryStore`. The full list of reads is in the +[soft-delete reference](../reference/soft-delete.md). + +```mermaid +flowchart LR + classDef step fill:#dbeafe,stroke:#1d4ed8,color:#0b1220 + classDef data fill:#ede9fe,stroke:#6d28d9,color:#1e1035 + classDef ok fill:#dcfce7,stroke:#15803d,color:#052e16 + classDef hidden fill:#fee2e2,stroke:#b91c1c,color:#450a0a + classDef future fill:#f1f5f9,stroke:#475569,color:#0f172a,stroke-dasharray: 4 3 + E["erasure writer
(not built yet)"]:::future -. "SET deleted_at = now()" .-> R[("users, api_keys,
providers, provider_tokens")]:::data + R --> F{"read filters
deleted_at IS NULL"}:::step + F -- "deleted_at set" --> H["absent: not found,
omitted, not authenticated"]:::hidden + F -- "deleted_at NULL" --> L["returned as live"]:::ok + R --> RP["GetProviderForRestore,
ResolveMachineContinuity"]:::step + RP -- "skip soft-deleted rows" --> L + R --> U["idx_users_privy_live:
UNIQUE WHERE deleted_at IS NULL"]:::step + U --> S["CreateUser with the same
Privy ID succeeds"]:::ok +``` + +Legend: purple = table, blue = read path or index, green = live result, +red = hidden, grey dashed = not built yet. + +- **Read filters.** User lookups, key authentication and listing, provider + token lookup, provider record, MDA chain and account listing, usage-flow + provider locations, and the machine-inventory backfill skip soft-deleted + rows. `UpdateAPIKey` and `RotateAPIKey` also filter, so they cannot change a + soft-deleted key. Writes and hard deletes do not filter. +- **Partial unique index.** `idx_users_privy_live` (version 14) keeps one + live user per Privy ID and ignores soft-deleted users. Versions 15 and 16 + then drop the full-table key `users_privy_user_id_key` and the index + `idx_users_privy`. On a fresh database the baseline still creates both, and + 15 and 16 drop them; goose never runs the baseline again. +- **Restore paths.** Provider history restore (`GetProviderForRestore`) and + machine continuity (`ResolveMachineContinuity`) skip soft-deleted provider + records, so an erased account's history is never attached to a new session. + Nothing restores a soft-deleted row: no code clears `deleted_at`. +- **Caches and other readers.** `CachedStore` caches users for + `UserTTL = 30 * time.Second` (`coordinator/store/cached.go`); the erasure + writer must invalidate it. `admin-ui` reads the replica with its own SQL and + does not filter. + ### Tables and files that are not goose versions `schema_migrations` is an older table. It holds the markers of the one-shot @@ -220,7 +288,7 @@ Logs carry bounded labels only, never SQL or parameters | Message | Fields | When | |---|---|---| -| `postgres startup phase` | `phase` (`connect` or an index name), `result`, `duration_ms` | After the ping, and after each index build in versions 3 and 5 | +| `postgres startup phase` | `phase` (`connect` or an index name), `result`, `duration_ms` | After the ping, and after each index build in versions 3, 5, 6 to 12 and 14 | | `postgres migration hit lock_timeout; retrying` (warn) | `attempt` | Before attempt 2 and 3 | | `postgres migration` | `version`, `result` (`applied` or `failed`), `duration_ms` | One line per version that goose ran, written after the attempt ends; none when nothing was pending | | `coordinator migrations complete` | `duration_ms` | `--migrate-only` succeeded | @@ -239,10 +307,12 @@ Logs carry bounded labels only, never SQL or parameters 3. **A failed version is not recorded.** A transactional SQL file rolls back with its version row. A `NO TRANSACTION` file or a Go migration records the version only after its last statement succeeds. -4. **A migration statement does not wait more than 3 s for a table lock** - unless the database URL sets a longer `lock_timeout` - (`migrationLockTimeout`). `TestMigrateRetriesLockTimeout` holds a lock and - checks the retry. +4. **A migration statement does not wait more than 3 s for a table lock,** + or 1 min for a `CONCURRENTLY` statement (versions 6 to 12, 14 and 16), + unless the database URL sets a longer `lock_timeout` for the SQL session + (`migrationLockTimeout`, `concurrentIndexLockTimeout`). + `TestMigrateRetriesLockTimeout` and + `TestConcurrentIndexMigrationWaitsForOlderSnapshot` cover both. 5. **Migrations build exactly `schema.sql`** on a fresh database (`TestMigrationsBuildCheckedInSchema`). 6. **The generated queries match `schema.sql` and the query files.** @@ -251,7 +321,15 @@ Logs carry bounded labels only, never SQL or parameters 7. **There are no down migrations.** No migration file has a `-- +goose Down` section. A rollback starts an older image on the migrated schema; it never reverts the schema. -8. **An older goose image applies nothing on a newer database.** Every version +8. **An index migration is recorded only with a valid index.** + `buildConcurrentIndexOnce` fails unless `indisvalid AND indisready` + (`TestIndexMigrationRebuildsInvalidLeftover`, + `TestIndexMigrationFailureIsNotRecorded` in + `coordinator/store/postgres_migrations_test.go`). +9. **A soft-deleted row is never returned as live.** Every read in the + [soft-delete reference](../reference/soft-delete.md) filters it, on both + backends (`coordinator/store/soft_delete_reads_test.go`). +10. **An older goose image applies nothing on a newer database.** Every version it knows is recorded, and goose ignores recorded versions it does not know. A pre-goose image ignores `goose_db_version` and replays its own boot DDL. @@ -264,6 +342,9 @@ Logs carry bounded labels only, never SQL or parameters | Exit 1 with `failed to initialize: failed to acquire lock` after 5 min | Another process held the goose advisory lock for the whole lock wait | The holder in `pg_locks` (`objid = 4097083626`); [runbook](../operations/schema-migration.md#a-second-coordinator-waits-on-the-lock). | | A `NO TRANSACTION` file failed after some statements | Its earlier statements committed; the version is not recorded | The next run executes the whole file again, so every statement in such a file must be safe to run twice (`IF NOT EXISTS`, `IF EXISTS`). | | Exit 1 with `index ... is invalid; repair the interrupted concurrent index build before retrying` | A `CONCURRENTLY` build in version 3 or 5 was interrupted | `ensureConcurrentIndex` does not repair it; [runbook](../operations/schema-migration.md#invalid-index). | +| An index migration (6 to 12, 14) fails with `canceling statement due to lock timeout` | A transaction held an older snapshot for more than 1 min | `migrate` retries; the next attempt drops the invalid leftover and builds again. After three attempts the coordinator exits 1 and the version is not recorded. | +| Version 14 fails with a unique violation | Two live users share a Privy ID; `users_privy_user_id_key` prevents that until version 15, unless it was removed by hand | Nothing is recorded (`TestIndexMigrationFailureIsNotRecorded`); resolve the duplicate users before redeploying. | +| A coordinator built before goose fails to boot with a unique violation on `idx_users_privy` | It replays its boot DDL; its non-concurrent `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy` fails once a soft-deleted and a live user share a Privy ID | Roll back only to goose images; see the [rollback rules](../operations/schema-migration.md#rollback). | | Exit 1 with `found duplicate migration version` | Two sources share a number | Renumber one. | | CI fails in `make sqlc-check` | `schema.sql` or `coordinator/store/storedb` is stale | [sqlc troubleshooting](../developer/sqlc.md#troubleshooting). | | Exit 1 with `missing (out-of-order) migration` | A version below the highest applied one was never applied, for example after two branches added migrations | `SELECT version_id FROM goose_db_version ORDER BY id`; renumber the unapplied version above the highest one. | @@ -276,7 +357,10 @@ Logs carry bounded labels only, never SQL or parameters | Concern | Location | |---|---| -| Migration runner, timeouts, retries, Go migration list | `coordinator/store/postgres_migrations.go` (`migrate`, `migrateOnce`, `newMigrationProvider`, `goMigrations`) | +| Migration runner, timeouts, retries, Go migration list | `coordinator/store/postgres_migrations.go` (`migrate`, `migrateOnce`, `newMigrationProvider`, `goMigrations`, `allGoMigrations`) | +| Index migrations | `coordinator/store/postgres_migration_indexes.go` (`indexMigrations`, `buildConcurrentIndex`, `concurrentIndexLockTimeout`) | +| Soft-delete reads and tests | [soft-delete reference](../reference/soft-delete.md); `coordinator/store/soft_delete_reads_test.go` | +| Frozen pre-goose schema | `coordinator/store/testdata/schema_pre_goose.sql` | | SQL migrations | `coordinator/store/schema/migrations/` | | Checked-in schema | `coordinator/store/schema/schema.sql` | | Concurrent index helper and startup log line | `coordinator/store/postgres_startup.go` (`ensureConcurrentIndex`, `logStartupMigration`) | @@ -293,5 +377,6 @@ Logs carry bounded labels only, never SQL or parameters - [Add a database migration](../developer/database-migrations.md) — the steps - [Apply schema migrations in production](../operations/schema-migration.md) — backup, checks, rollback - [Write store queries with sqlc](../developer/sqlc.md) and [sqlc type mapping](../reference/sqlc-type-mapping.md) +- [Soft delete](../reference/soft-delete.md) — every table, read path and index - [Storage](storage.md) — what the tables hold and which backend runs - [Deploy the coordinator](../operations/coordinator-deploy.md) — the container swap that runs the migrations diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 72c08b8d43..2282f27d5b 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -141,18 +141,10 @@ Legend: blue = step, amber = decision, green = serving, red = exit 1. ### Soft-deleted rows A row in `users`, `api_keys`, `providers` or `provider_tokens` whose -`deleted_at` is set belongs to an erased account. Every read that returns a -live user, key, provider record or provider token filters -`deleted_at IS NULL`, in both `PostgresStore` and `MemoryStore` (the -`DeletedAt` fields, never serialized). That covers user lookups by account, -Privy ID, Stripe account and email; promotion claims; key authentication, -listing, lookup, update and rotation; provider token lookup; provider record, -MDA chain, account listing, restore (`GetProviderForRestore`) and machine -continuity history; usage-flow provider locations; and the machine-inventory -backfill. Writes and hard deletes do not filter. No code sets `deleted_at` yet; -account erasure will, and it must also invalidate the `CachedStore` user -cache. A Privy user ID is unique among live users only, so a person can sign up -again after erasure. +`deleted_at` is set belongs to an erased account, and every live read hides +it. No code sets `deleted_at` yet. The model is in +[schema lifecycle](schema-lifecycle.md#soft-delete); every filtered read, +index and effect is in the [soft-delete reference](../reference/soft-delete.md). ### Provider earnings and history @@ -268,7 +260,8 @@ KV blocks under a per-model key, not tokens. update** (`coordinator/store/schema/migrations/00001_baseline.sql`). 4. **A soft-deleted row is never returned as live.** Reads of `users`, `api_keys`, `providers` and `provider_tokens` filter `deleted_at IS NULL` - (`coordinator/store/soft_delete_reads_test.go` covers each read on both + ([soft-delete reference](../reference/soft-delete.md); + `coordinator/store/soft_delete_reads_test.go` covers each read on both stores). 5. **Boot never holds a long lock on a hot table.** The `provider_earnings(job_id)` unique index is built `CONCURRENTLY`, only after @@ -299,7 +292,7 @@ KV blocks under a per-model key, not tokens. | Symptom | Cause | Where to look | |---|---|---| | Coordinator exits 1 at boot with `store: run migrations` | A goose migration failed: a lock timeout, the advisory-lock wait, an invalid index, an out-of-order or duplicate version, or the retired-backfill guard | [Schema lifecycle failure modes](schema-lifecycle.md#failure-modes) and the [schema migration runbook](../operations/schema-migration.md#troubleshooting). | -| A coordinator built before goose fails to boot with a unique-violation on `idx_users_privy` | It replays its boot DDL, whose non-concurrent `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy` fails once a soft-deleted and a live user share a Privy ID | Roll back only to images built with goose; see the [deployment rollback](../operations/coordinator-deploy.md#rollback). | +| A coordinator built before goose fails to boot with a unique-violation on `idx_users_privy` | It replays its boot DDL, whose non-concurrent `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy` fails once a soft-deleted and a live user share a Privy ID | Roll back only to images built with goose; see the [schema migration rollback rules](../operations/schema-migration.md#rollback). | | `EIGENINFERENCE_DATABASE_URL is required in production` | No DSN and no memory-store opt-in | The environment file; see [`../operations/coordinator-deploy.md`](../operations/coordinator-deploy.md). | | Billing or key state gone after a restart | The process ran on the memory store | Startup log line `using in-memory store`. | | `/v1/stats` slow and pool saturated | Full scans on `usage` holding connections; the 80-connection floor is the mitigation, not a fix | `pg_stat_activity`; the read cache. | diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index 48447446e7..d62669271c 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -30,18 +30,21 @@ in production is the [schema migration runbook](../operations/schema-migration.m | Change | Kind | Example in the repo | |---|---|---| - | Add a table, a nullable column, or a column with a constant default; add a constraint `NOT VALID` | SQL file, one transaction (the default) | Template in step 3 | - | Several `ALTER TABLE`s on busy tables that must not hold their locks together; `DROP INDEX CONCURRENTLY`; `VALIDATE CONSTRAINT` after a `NOT VALID` add | SQL file with `-- +goose NO TRANSACTION` | `coordinator/store/schema/migrations/00001_baseline.sql` | - | Create an index on a table that has rows in production | Go migration through `ensureConcurrentIndex` | `ensureProviderRestoreIndexes` (version 3) | + | Add a table, a nullable column, or a column with a constant default; drop a constraint; add a constraint `NOT VALID` | SQL file, one transaction (the default) | `coordinator/store/schema/migrations/00015_users_privy_drop_unique_constraint.sql` | + | Several `ALTER TABLE`s on busy tables that must not hold their locks together | SQL file with `-- +goose NO TRANSACTION` | `coordinator/store/schema/migrations/00013_soft_delete_columns.sql` | + | `VALIDATE CONSTRAINT` after a `NOT VALID` add | SQL file with `-- +goose NO TRANSACTION` | `coordinator/store/schema/migrations/00017_referrals_referrer_code_cascade.sql` | + | `DROP INDEX CONCURRENTLY` | SQL file with `-- +goose NO TRANSACTION` and `SET lock_timeout = '1min'` | `coordinator/store/schema/migrations/00016_users_privy_drop_old_index.sql` | + | Create an index on a table that has rows in production | Go migration in `indexMigrations` | Versions 6 to 12 and 14 (`coordinator/store/postgres_migration_indexes.go`) | | A step that must read data first, check a precondition, or check its own result | Go migration | `checkRetiredBackfills` (version 2) | | Rename or drop a column, or tighten a constraint | Two or more releases; see [expand and contract](#change-a-column-in-two-releases-expand-and-contract) | — | | Fix rows that a writer keeps producing | Not a migration: fix the writer | — | | A cleanup that needs a long lock | Manual SQL under `coordinator/store/migrations/`, applied under an approved operation | `coordinator/store/migrations/dedupe_provider_earnings.sql` | 2. **Pick the version.** Use one more than the highest version in - `coordinator/store/schema/migrations/` and in `goMigrations` - (`coordinator/store/postgres_migrations.go`). SQL files and Go migrations - share one sequence. If a branch that merges before yours takes the same + `coordinator/store/schema/migrations/`, in `goMigrations` + (`coordinator/store/postgres_migrations.go`) and in `indexMigrations` + (`coordinator/store/postgres_migration_indexes.go`). SQL files and Go + migrations share one sequence. If a branch that merges before yours takes the same number, renumber yours before it merges. 3. **Write the migration.** Follow the part for your kind. @@ -63,15 +66,17 @@ in production is the [schema migration runbook](../operations/schema-migration.m recorded after the last one. A failure in the middle leaves the earlier statements applied, and the next boot runs the whole file again, so every statement must be safe to run twice (`IF NOT EXISTS`, `IF EXISTS`, or - drop-then-add). Wrap a statement that contains `;`, such as a `DO` block, - in `-- +goose StatementBegin` and `-- +goose StatementEnd`, as the baseline - does. + drop-then-add, as in version 17). Wrap a statement that contains `;`, such + as a `DO` block, in `-- +goose StatementBegin` and `-- +goose StatementEnd`, + as the baseline does. A `DROP INDEX CONCURRENTLY` waits for older snapshots + like a concurrent build; set `lock_timeout = '1min'` before it and reset it + after, as version 16 does. *Go migration.* Write a method on `PostgresStore` that takes a `context.Context` and returns an error, and add it to `goMigrations`: ```go - step(6, s.checkExampleRows), + step(18, s.checkExampleRows), ``` It runs on the store pool with no session timeouts unless the database URL @@ -136,15 +141,19 @@ in production is the [schema migration runbook](../operations/schema-migration.m ```bash go test ./coordinator/store -count=1 \ - -run 'TestMigrations|TestConcurrentMigrations|TestMigrateRetries|TestSQLMigrations' + -run 'TestMigrations|TestConcurrent|TestMigrateRetries|TestSQLMigrations|TestIndexMigration' ``` | Test | Fails when | |---|---| | `TestMigrationsBuildCheckedInSchema` | `schema.sql` differs from what the migrations build | -| `TestMigrationsLeaveLegacyDatabaseUnchanged` | Versions 1 to 5 change a database that a pre-goose coordinator built | +| `TestMigrationsUpgradeLegacyDatabase` | Versions 1 to 5 change the frozen pre-goose schema (`coordinator/store/testdata/schema_pre_goose.sql`), or all versions do not reach `schema.sql` from it | | `TestConcurrentMigrationsApplyOnce` | Two runs at once apply a version twice | | `TestSQLMigrationsDoNotBuildIndexesConcurrently` | An SQL file contains `CREATE [UNIQUE] INDEX CONCURRENTLY` | +| `TestConcurrentIndexMigrationWaitsForOlderSnapshot`, `TestIndexMigrationRebuildsInvalidLeftover`, `TestIndexMigrationFailureIsNotRecorded` | An index migration gives up behind an older snapshot, keeps an invalid leftover, or records a failed build | + +Do not regenerate `coordinator/store/testdata/schema_pre_goose.sql`; it is the +schema of the last pre-goose boot. Then run the store tests for the tables you changed, on both backends. CI also runs `make sqlc-check`, which runs `TestMigrationsBuildCheckedInSchema` @@ -193,13 +202,55 @@ Legend: blue = release, grey = the image a rollback starts. 5. Release N+2, contract: drop the old shape, or add the constraint (`NOT VALID`, then `VALIDATE`). +## Add soft delete to a table + +1. Add the column in a new SQL migration. It is nullable with no default, so + it changes only the catalog: + + ```sql + -- +goose Up + ALTER TABLE example ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ; + ``` + + For several busy tables, use one `NO TRANSACTION` file, as version 13 does. +2. If a unique key must let a new live row reuse the value of an erased one, + replace it with a partial unique index, in three versions: build + `CREATE UNIQUE INDEX CONCURRENTLY ... WHERE deleted_at IS NULL` in + `indexMigrations` (version 14), drop the old constraint (version 15), then + drop the old index with `DROP INDEX CONCURRENTLY` (version 16). Read the + [pre-goose fallback rule](#destructive-changes-and-the-pre-goose-fallback) + first. +3. Add `DeletedAt *time.Time` with the tag `json:"-"` to the store type in + `coordinator/store/interface.go`. +4. Add `AND deleted_at IS NULL` to every read that returns a live row: the + hand-written SQL in `coordinator/store/` and the queries in + `coordinator/store/queries/`. Find them with: + + ```bash + grep -n -E "(FROM|JOIN)\s+example\b" coordinator/store/*.go coordinator/store/queries/*.sql + ``` + + Make each `MemoryStore` read skip a record whose `DeletedAt` is not `nil`. + Leave inserts, hard deletes and maintenance writes unfiltered. Filter an + update only when it must not change a soft-deleted row, as `UpdateAPIKey` + does. +5. If `CachedStore` (`coordinator/store/cached.go`) caches the table, the + writer that sets `deleted_at` must invalidate the cache. +6. Regenerate `schema.sql` (step 5 above) and run `make sqlc-generate`. +7. Add the table to `softDelete` in `coordinator/store/soft_delete_reads_test.go` + and a test that checks every filtered read on both backends. +8. Add the table and its reads to the [soft-delete reference](../reference/soft-delete.md). + ## Destructive changes and the pre-goose fallback A coordinator image built before goose ignores `goose_db_version` and replays its own boot DDL. `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and its `DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later -`SET NOT NULL`. Ship no contract step on a table the baseline creates while a -pre-goose image can be started as the fallback. The +`SET NOT NULL`. Its `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy` +rebuilds the index that version 16 drops, and fails once a soft-deleted and a +live user share a Privy ID, so the image cannot boot. Ship no contract step on +a table the baseline creates while a pre-goose image can be started as the +fallback. The [runbook](../operations/schema-migration.md#rollback) states which images are safe. @@ -212,12 +263,13 @@ safe. | `canceling statement due to lock timeout` three times | Another session holds the table. Stop it, or make the statement take a weaker lock. | | `TestMigrationsBuildCheckedInSchema` fails | `schema.sql` is stale. Repeat step 5 on an empty database. | | The `schema.sql` diff shows objects you did not add | The dump came from a database that held other objects, or from a `pg_dump` older than 17. Repeat step 5 with a new database. | -| `index ... is invalid; repair the interrupted concurrent index build before retrying` locally | Drop the index (`DROP INDEX CONCURRENTLY `) and run again. | +| `index ... is invalid; repair the interrupted concurrent index build before retrying` locally | Versions 3 and 5 only: drop the index (`DROP INDEX CONCURRENTLY `) and run again. An `indexMigrations` version drops and rebuilds an invalid leftover itself. | ## Related - [Schema lifecycle](../architecture/schema-lifecycle.md) — how goose runs, locks, timeouts, failure modes - [Apply schema migrations in production](../operations/schema-migration.md) — backup, checks, rollback - [Write store queries with sqlc](sqlc.md) — queries generated from `schema.sql` +- [Soft delete](../reference/soft-delete.md) — the tables, reads and indexes - [Storage](../architecture/storage.md) — what the tables hold - [Test](test.md) — running the Postgres tests diff --git a/docs/operations/coordinator-deploy.md b/docs/operations/coordinator-deploy.md index 69b0ea68fc..d102573ed1 100644 --- a/docs/operations/coordinator-deploy.md +++ b/docs/operations/coordinator-deploy.md @@ -394,14 +394,6 @@ Rollback never reverts the schema. Which previous images are safe on a migrated database is in the [schema migration rollback rules](schema-migration.md#rollback). -That old boot DDL also fails once the soft-delete migrations (versions 13 to -16) have run: from then on, a soft-deleted user and a live user can share a -Privy ID, and its non-concurrent `CREATE UNIQUE INDEX IF NOT EXISTS -idx_users_privy` fails, so the image cannot boot. Deploy the goose release and -let it run stable before the soft-delete release ships; after that, every -rollback image must be a goose build. An older goose image applies nothing on -a newer database, because every version it knows is already recorded. - ## Environment file `/etc/d-inference/env` holds secrets and operator controls together. The diff --git a/docs/operations/schema-migration.md b/docs/operations/schema-migration.md index e2a1251f23..309bdb68b0 100644 --- a/docs/operations/schema-migration.md +++ b/docs/operations/schema-migration.md @@ -64,6 +64,7 @@ List what production has and what the candidate brings: psql "$PROD_DB_URL" -Atc "select coalesce(max(version_id), 0) from goose_db_version;" git ls-tree --name-only "$CANDIDATE_COMMIT" coordinator/store/schema/migrations/ git show "$CANDIDATE_COMMIT:coordinator/store/postgres_migrations.go" | grep -n 'step(' +git show "$CANDIDATE_COMMIT:coordinator/store/postgres_migration_indexes.go" | grep -n 'index(' ``` An error `relation "goose_db_version" does not exist` means no goose build @@ -138,7 +139,7 @@ Expected JSON log lines, in this order: | `msg` | Fields | Meaning | |---|---|---| | `postgres startup phase` | `"phase":"connect","result":"applied"` | Connected and pinged | -| `postgres startup phase` | `"phase":"","result":"applied"` | One per index that versions 3 and 5 build; none when no such version is pending | +| `postgres startup phase` | `"phase":"","result":"applied"` | One per index that versions 3, 5, 6 to 12 and 14 build; none when no such version is pending | | `postgres migration` | `"version":N,"result":"applied","duration_ms":…` | One per applied version, all written after the run ends; none when nothing was pending | | `coordinator migrations complete` | `duration_ms` | Exit 0 | @@ -181,13 +182,17 @@ approved operation. Log: three `postgres migration hit lock_timeout; retrying` warnings, then `partial migration error (type:sql,version:N): ERROR: canceling statement due -to lock timeout (SQLSTATE 55P03)`. Version N is not recorded; a transactional +to lock timeout (SQLSTATE 55P03)` (`type:go` for an index migration, which +waits 1 min per attempt instead of 3 s). Version N is not recorded; a transactional file rolled back, and the coordinator did not serve. Find the blocker with the step 3 queries, wait for it or end it (approved), and run step 4 again. Do not loop restarts of the container. ### Invalid index +Versions 6 to 12 and 14 (`buildConcurrentIndex`) drop an invalid leftover and +build again on the next run; run step 4 again after you remove the cause. + Log: `index is invalid; repair the interrupted concurrent index build before retrying` (versions 3 and 5, `ensureConcurrentIndex`). The build was interrupted and left an invalid index; the version is not recorded. Under @@ -233,10 +238,21 @@ the image by these rules: applied: its `ADD COLUMN IF NOT EXISTS` brings a dropped column back, and its `DROP NOT NULL` on `fleet_snapshots.free_for_load_gb` undoes a later `SET NOT NULL`. -3. **Never start a coordinator built before the +3. **After versions 13 to 16, roll back only to a goose image.** A pre-goose + image runs `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy` at boot. If + a soft-deleted and a live user share a Privy ID, that statement fails and + the image cannot boot. If they do not, it builds the full unique index + again without `CONCURRENTLY`, and it stays after you roll forward, because + version 16 is already recorded; drop it under approval with + `DROP INDEX CONCURRENTLY IF EXISTS idx_users_privy;`. +4. **After a row has `deleted_at` set, roll back only to an image that filters + it.** Images built before versions 13 to 17 do not filter `deleted_at`, so + they return soft-deleted rows as live + ([soft-delete reads](../reference/soft-delete.md)). +5. **Never start a coordinator built before the `backfill_withdrawable_balance_v1` marker existed**; the deploy runbook states this rule. -4. **Restoring the backup is a last resort.** `gcloud sql backups restore +6. **Restoring the backup is a last resort.** `gcloud sql backups restore --restore-instance="$PRIMARY" --project=darkbloom-mainnet` overwrites the instance and loses every write after the backup. It needs its own approval. @@ -250,8 +266,10 @@ coordinator built, but a lock timeout inside one of the baseline's version 1. - [ ] Step 1 shows `relation "goose_db_version" does not exist`. -- [ ] The candidate's highest version is 5, so the pre-goose image stays a - safe fallback ([rollback rule 2](#rollback)). +- [ ] The candidate's highest version is 5: deploy a goose build without the + soft-delete versions first, so the pre-goose image stays a safe + fallback ([rollback rules 2 and 3](#rollback)). Versions 6 to 17 ship in + a later deploy ([soft-delete release](#soft-delete-release)). - [ ] The three retired-backfill markers exist ([deploy step 2](coordinator-deploy.md#2-pre-swap-checks-vm-and-db)). - [ ] Backup taken; its ID is in the deploy record (step 2). @@ -264,8 +282,34 @@ version 1. index means a swallowed statement; apply it under a separate approved operation. +## Soft-delete release + +The deploy that applies versions 6 to 17. Run it only after a goose build with +versions 1 to 5 runs in production, so that a goose image is the fallback. + +- [ ] The current production image and the fallback image are goose builds; + `goose_db_version` lists 0 to 5. +- [ ] Backup taken (step 2) and step 3 clean. The index builds wait for older + snapshots, up to 1 min per attempt. +- [ ] Migrations applied. The log shows `postgres startup phase` for the eight + indexes of versions 6 to 12 and 14, and `postgres migration` for + versions 6 to 17. +- [ ] `goose_db_version` lists 0 to 17, and the invalid-index query returns + no rows. +- [ ] The Privy key swap and the referral key are in place: + + ```bash + psql "$PROD_DB_URL" -c "select indexname from pg_indexes + where tablename = 'users' and indexname in ('idx_users_privy_live', 'idx_users_privy');" # only idx_users_privy_live + psql "$PROD_DB_URL" -c "select conname, convalidated from pg_constraint + where conname in ('users_privy_user_id_key', 'referrals_referrer_code_fkey', 'referrals_referrer_code_cascade_fkey');" # only the cascade key, validated + ``` + +- [ ] From now on, use only goose images as the fallback ([rollback rule 3](#rollback)). + ## Related - [Deploy the coordinator](coordinator-deploy.md) — the container swap and its rollback - [Schema lifecycle](../architecture/schema-lifecycle.md) — versions, locks, timeouts, failure modes - [Add a database migration](../developer/database-migrations.md) — how migrations are written +- [Soft delete](../reference/soft-delete.md) — what versions 13 to 17 change in the reads diff --git a/docs/reference/README.md b/docs/reference/README.md index 8c2c89f402..f7c2e1770e 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -28,6 +28,7 @@ Every row cites the code that defines it. For how and why things work, use | [telemetry-inventory.md](telemetry-inventory.md) | Every telemetry datum collected — producer, sink, cadence, retention — and the Datadog metric-name inventory with tags and emitting file | | [pricing-model.md](pricing-model.md) | Micro-USD units, price resolution order, formulas, every billing constant (single home for money constants), routes, service accounts | | [model-registry-format.md](model-registry-format.md) | Manifest schema, registration payload, alias format | +| [soft-delete.md](soft-delete.md) | Tables with `deleted_at`, every store read that hides a soft-deleted row (Postgres and MemoryStore), unfiltered paths, indexes, effects | | [sqlc-type-mapping.md](sqlc-type-mapping.md) | Postgres type and nullability → generated Go type in `coordinator/store/storedb`, the `sqlc.yaml` flag that causes it, and the store conversion | | [qwen4-next-support.md](qwen4-next-support.md) | Native Flash-Next private serving/state contract and pending qualification; not a catalog or release claim | diff --git a/docs/reference/soft-delete.md b/docs/reference/soft-delete.md new file mode 100644 index 0000000000..5bdd98ea41 --- /dev/null +++ b/docs/reference/soft-delete.md @@ -0,0 +1,125 @@ +# Soft delete + +> Last updated: 2026-10-04 + +Reference for the coordinator store's soft-delete columns: which tables have +`deleted_at`, every read that hides a soft-deleted row in `PostgresStore` and +`MemoryStore`, the paths that do not filter, the indexes, and what a soft +delete changes. No code sets `deleted_at` yet; the account-erasure writer +will. Why the model exists and how it fits the schema is in +[schema lifecycle](../architecture/schema-lifecycle.md#soft-delete). + +## Tables + +`coordinator/store/schema/migrations/00013_soft_delete_columns.sql` adds the +column; the Go field is `DeletedAt *time.Time` with `json:"-"` +(`coordinator/store/interface.go`). + +| Table | Column | Go type with the field | Generated field (sqlc) | +|---|---|---|---| +| `users` | `deleted_at TIMESTAMPTZ` (nullable, no default) | `User` | — | +| `api_keys` | `deleted_at TIMESTAMPTZ` (nullable, no default) | `APIKey` | `storedb.ApiKey.DeletedAt *time.Time` (`coordinator/store/storedb/models.go`) | +| `providers` | `deleted_at TIMESTAMPTZ` (nullable, no default) | `ProviderRecord` | — | +| `provider_tokens` | `deleted_at TIMESTAMPTZ` (nullable, no default) | `ProviderToken` | — | + +`PostgresStore` reads do not load the column into `DeletedAt`; they filter it +in SQL. `MemoryStore` keeps the field on its records and checks it. + +## Reads that hide a soft-deleted row + +Postgres filters `deleted_at IS NULL`; MemoryStore skips a record whose +`DeletedAt` is not `nil`. `coordinator/store/soft_delete_reads_test.go` covers +each row on both backends unless the row says Postgres only. + +### `users` + +| Store method | PostgresStore | MemoryStore | Result for a soft-deleted user | +|---|---|---|---| +| `GetUserByAccountID` | `coordinator/store/postgres.go` | `coordinator/store/memory.go` | `ErrNotFound` | +| `GetUserByPrivyID` | `coordinator/store/postgres.go` | `coordinator/store/memory.go` | `ErrNotFound` | +| `GetUserByStripeAccount` | `coordinator/store/postgres.go` | `coordinator/store/memory.go` | not found | +| `GetUserByEmail` | `coordinator/store/postgres.go` | `coordinator/store/memory.go` | not found | +| `ClaimModelTokenPromotion` | `coordinator/store/model_token_promotions_postgres.go` | `coordinator/store/model_token_promotions_memory.go` | `ErrPromotionIneligible` | +| `CreateUser` (Privy ID check) | `idx_users_privy_live` | `coordinator/store/memory.go` | The Privy ID is free; a new live user may take it | + +### `api_keys` + +PostgresStore methods are in `coordinator/store/postgres_api_keys.go`; their +SQL is in `coordinator/store/queries/api_keys.sql`. + +| Store method | Query (PostgresStore) | MemoryStore | Result for a soft-deleted key | +|---|---|---|---| +| `GetKeyAccount` | `GetActiveKeyAccount` | `coordinator/store/memory.go` | `""` | +| `AuthenticateKey` | `GetAPIKeyByHash` | `coordinator/store/memory.go` | error; the request is not authenticated | +| `ListAPIKeys` | `ListAPIKeysByOwner` | `coordinator/store/memory.go` | omitted | +| `GetAPIKeyByID` | `GetAPIKeyByID` | `coordinator/store/memory.go` | not found | +| `UpdateAPIKey` | `UpdateAPIKey` (`UPDATE ... AND deleted_at IS NULL`) | `coordinator/store/memory.go` | `key not found`; nothing changes | +| `RotateAPIKey` | `GetAPIKeyByIDForUpdate` | `coordinator/store/memory.go` | `key not found`; nothing changes | + +### `provider_tokens` + +| Store method | PostgresStore | MemoryStore | Result for a soft-deleted token | +|---|---|---|---| +| `GetProviderToken` | `coordinator/store/postgres.go` | `coordinator/store/memory.go` | `provider token not found` | + +### `providers` + +| Store method | PostgresStore | MemoryStore | Result for a soft-deleted record | +|---|---|---|---| +| `GetProviderRecord` | `coordinator/store/postgres_provider_read.go` | `coordinator/store/memory.go` | not found | +| `GetMDAChainBySerial` | `coordinator/store/postgres.go` | `coordinator/store/memory.go` | its chain is not used | +| `ListProvidersByAccount` | `coordinator/store/postgres.go` | `coordinator/store/memory.go` | omitted | +| `GetProviderForRestore` | `coordinator/store/provider_restore.go` | `coordinator/store/provider_restore.go` | not a restore candidate; an older live row can be | +| `ResolveMachineContinuity` | `coordinator/store/postgres_machine_continuity.go` | `coordinator/store/memory_machine_continuity.go` | not continuity history | +| `UsageFlowBuckets` (provider location) | `coordinator/store/postgres_analytics_flows.go` (`usageFlowBucketsSQL`) | `coordinator/store/memory.go` | its location is not used | +| `BackfillMachineInventory` | `coordinator/store/machine_inventory_backfill.go` | — (Postgres only) | not backfilled | + +## Paths that do not filter + +Writes and hard deletes act on a soft-deleted row as on any other row. + +| Table | Methods | +|---|---| +| `users` | `CreateUser` insert, `SetUserStripeAccount`, `SetUserRole`, `SetUserPlatformFeePercent` (`coordinator/store/postgres.go`) | +| `api_keys` | `CreateAPIKey` and `SeedKey` inserts (`InsertAPIKey`, `InsertAPIKeyIfAbsent`), `TouchAPIKey`, `RevokeKey` (`DeactivateAPIKeyByHash`), `RevokeAPIKeyByID` and the delete in `RotateAPIKey` (`DeleteAPIKeyByID`) | +| `provider_tokens` | `CreateProviderToken`, `RevokeProviderToken` (`coordinator/store/postgres.go`) | +| `providers` | `UpsertProvider`, `DeleteProvidersBySerial` (`coordinator/store/postgres.go`), `UpsertProviderWithReputation` (`coordinator/store/provider_record_write.go`) | +| other tables | `usage`, `provider_earnings`, `ledger_entries` and the other history tables have no `deleted_at`; `KeySpendSince` still counts a soft-deleted key's usage | +| outside the store | `admin-ui` reads the read replica with its own SQL (`admin-ui/src/lib/queries/`) and does not filter `deleted_at` | + +## Indexes + +| Index | Definition | Version | Why | +|---|---|---|---| +| `idx_users_privy_live` | `UNIQUE (privy_user_id) WHERE deleted_at IS NULL` | 14 (`indexMigrations`) | One live user per Privy ID; an erased user's ID can sign up again. Replaces `users_privy_user_id_key` (dropped by version 15) and `idx_users_privy` (dropped by version 16). | +| `idx_provider_sessions_account` | `provider_sessions (account_id)` | 6 | Erasure finds rows by account | +| `idx_provider_log_reports_account` | `provider_log_reports (account_id)` | 7 | Erasure finds rows by account | +| `idx_device_codes_account` | `device_codes (account_id)` | 8 | Erasure finds rows by account | +| `idx_darkbloom_machine_sessions_account` | `darkbloom_machine_sessions (account_id)` | 9 | Erasure finds rows by account | +| `idx_model_token_reservations_account` | `model_token_reservations (account_id)` | 10 | Erasure finds rows by account | +| `idx_inference_routes_consumer_key_hash` | `inference_routes (consumer_key_hash)` | 11 | Erasure finds rows by hashed key | +| `idx_request_rejections_consumer_key_hash` | `request_rejections (consumer_key_hash)` | 12 | Erasure finds rows by hashed key | + +All are built `CONCURRENTLY` by `indexMigrations` +(`coordinator/store/postgres_migration_indexes.go`). Only +`idx_users_privy_live` reads `deleted_at`. Version 17 also replaces the +`referrals.referrer_code` foreign key with +`referrals_referrer_code_cascade_fkey` (`ON UPDATE CASCADE`), so a referrer +code change reaches `referrals`. + +## What a soft delete changes + +| Effect | Where | +|---|---| +| The row stays in its table with `deleted_at` set; every read above treats it as absent | the reads above | +| The user's Privy ID is free for a new live user | `idx_users_privy_live`; `MemoryStore.CreateUser` | +| `CachedStore` can serve a cached user for up to `UserTTL = 30 * time.Second` after a soft delete that did not go through it; the erasure writer must invalidate the user entries | `coordinator/store/cached.go` (`DefaultCacheConfig`) | +| History rows that reference the account (usage, earnings, ledger) do not change | no `deleted_at` on those tables | +| A pre-goose coordinator image cannot boot once a soft-deleted and a live user share a Privy ID | its boot DDL runs `CREATE UNIQUE INDEX IF NOT EXISTS idx_users_privy`; see the [rollback rules](../operations/schema-migration.md#rollback) | +| Nothing clears `deleted_at`; there is no restore of a soft-deleted row | no writer of the column exists | + +## Related + +- [Schema lifecycle: soft delete](../architecture/schema-lifecycle.md#soft-delete) — the model and its invariants +- [Add a database migration: add soft delete to a table](../developer/database-migrations.md#add-soft-delete-to-a-table) +- [Apply schema migrations in production](../operations/schema-migration.md#rollback) — rollback rules after the soft-delete versions diff --git a/docs/reference/sqlc-type-mapping.md b/docs/reference/sqlc-type-mapping.md index 777e16de85..c854ae607d 100644 --- a/docs/reference/sqlc-type-mapping.md +++ b/docs/reference/sqlc-type-mapping.md @@ -39,6 +39,7 @@ are in `coordinator/store/postgres_api_keys.go`. | `bigint` (expression) | never null | `int64` | the `::bigint` cast | `COALESCE(SUM(cost_micro_usd), 0)::bigint` in `KeySpendSince` → result | Returned as is; an error returns `0` (`PostgresStore.KeySpendSince`) | | `timestamptz` | `NOT NULL` | `time.Time` | override `pg_catalog.timestamptz` | `api_keys.created_at` → `CreatedAt` | Copied; writers pass `time.Now().UTC()` | | `timestamptz` | nullable | `*time.Time` | override `pg_catalog.timestamptz`, `nullable: true` | `api_keys.expires_at`, `last_used_at` → `ExpiresAt`, `LastUsedAt` | Copied; `TouchAPIKey` passes `&lastUsed` (UTC) | +| `timestamptz` | nullable | `*time.Time` | override `pg_catalog.timestamptz`, `nullable: true` | `api_keys.deleted_at` → `DeletedAt` | Not copied by `apiKeyFromRow`: every query that returns `ApiKey` filters `deleted_at IS NULL`, so the value is always `nil` ([soft delete](soft-delete.md)) | | `timestamptz` (cast parameter) | nullable | `*time.Time` | override `timestamptz`, `nullable: true`; `sqlc.narg` | `sqlc.narg('since')::timestamptz` → `KeySpendSinceParams.Since` | A zero `time.Time` becomes `nil`, which matches every row | | `text` (parameter) | — | `string` | default | `sqlc.arg('key_id')` compared with `usage.key_id` → `KeySpendSinceParams.KeyID` | Passed as is | From 5bf78d58575d9e42a9b73c4643cdbfe43dac8ddf Mon Sep 17 00:00:00 2001 From: David Tai Date: Sun, 4 Oct 2026 15:47:45 -0500 Subject: [PATCH 12/20] refactor: share one line-query helper in the migration tests Replace the copied row-scan loops in TestMigrationsLeaveLegacyDatabaseUnchanged with queryLines, and rename assertSameSchema to assertSameLines because it also compares row lists. Co-Authored-By: Claude Opus 5.5 --- coordinator/store/migration_harness_test.go | 22 ++++++---- coordinator/store/postgres_migrations_test.go | 42 ++++--------------- 2 files changed, 21 insertions(+), 43 deletions(-) diff --git a/coordinator/store/migration_harness_test.go b/coordinator/store/migration_harness_test.go index bad7c0fbc6..7194829eee 100644 --- a/coordinator/store/migration_harness_test.go +++ b/coordinator/store/migration_harness_test.go @@ -150,27 +150,33 @@ ORDER BY line` func schemaSnapshot(t testing.TB, pool *pgxpool.Pool) []string { t.Helper() - rows, err := pool.Query(context.Background(), schemaSnapshotSQL) + return queryLines(t, pool, schemaSnapshotSQL) +} + +// queryLines returns the single text column of every row that query returns. +func queryLines(t testing.TB, pool *pgxpool.Pool, query string) []string { + t.Helper() + rows, err := pool.Query(context.Background(), query) if err != nil { - t.Fatalf("snapshot schema: %v", err) + t.Fatalf("query lines: %v", err) } defer rows.Close() var lines []string for rows.Next() { var line string if err := rows.Scan(&line); err != nil { - t.Fatalf("scan schema snapshot: %v", err) + t.Fatalf("scan line: %v", err) } lines = append(lines, line) } if err := rows.Err(); err != nil { - t.Fatalf("read schema snapshot: %v", err) + t.Fatalf("read lines: %v", err) } return lines } -// assertSameSchema fails with the lines only one snapshot has. -func assertSameSchema(t testing.TB, wantName string, want []string, gotName string, got []string) { +// assertSameLines fails with the lines only one snapshot has. +func assertSameLines(t testing.TB, wantName string, want []string, gotName string, got []string) { t.Helper() count := map[string]int{} for _, line := range want { @@ -189,10 +195,10 @@ func assertSameSchema(t testing.TB, wantName string, want []string, gotName stri } } if len(diff) > 0 { - t.Fatalf("schemas differ (%d lines):\n%s", len(diff), strings.Join(diff, "\n")) + t.Fatalf("%s and %s differ (%d lines):\n%s", wantName, gotName, len(diff), strings.Join(diff, "\n")) } if len(want) == 0 { - t.Fatal("empty schema snapshot") + t.Fatalf("%s snapshot is empty", wantName) } } diff --git a/coordinator/store/postgres_migrations_test.go b/coordinator/store/postgres_migrations_test.go index d5331ff432..0e047cbfd9 100644 --- a/coordinator/store/postgres_migrations_test.go +++ b/coordinator/store/postgres_migrations_test.go @@ -28,7 +28,7 @@ func TestMigrationsBuildCheckedInSchema(t *testing.T) { dumpPool := openTestPool(t, newThrowawayTestDatabase(t)) loadSchemaFile(t, dumpPool) - assertSameSchema(t, "schema/schema.sql", schemaSnapshot(t, dumpPool), "goose", schemaSnapshot(t, s.pool)) + assertSameLines(t, "schema/schema.sql", schemaSnapshot(t, dumpPool), "goose", schemaSnapshot(t, s.pool)) } // A database that a pre-goose binary migrated meets goose for the first @@ -58,23 +58,7 @@ func TestMigrationsLeaveLegacyDatabaseUnchanged(t *testing.T) { UNION ALL SELECT 'usage_totals ' || id || ' ' || total_requests FROM usage_totals UNION ALL SELECT 'collection ' || started_at FROM model_demand_collection ORDER BY 1` - readRows := func() []string { - rows, err := pool.Query(ctx, rowsSQL) - if err != nil { - t.Fatalf("read rows: %v", err) - } - defer rows.Close() - var out []string - for rows.Next() { - var line string - if err := rows.Scan(&line); err != nil { - t.Fatalf("scan row: %v", err) - } - out = append(out, line) - } - return out - } - schemaBefore, rowsBefore := schemaSnapshot(t, pool), readRows() + schemaBefore, rowsBefore := schemaSnapshot(t, pool), queryLines(t, pool, rowsSQL) s, err := NewPostgres(ctx, Config{DatabaseURL: databaseURL}) if err != nil { @@ -82,23 +66,11 @@ func TestMigrationsLeaveLegacyDatabaseUnchanged(t *testing.T) { } t.Cleanup(s.Close) - assertSameSchema(t, "legacy", schemaBefore, "after goose", schemaSnapshot(t, pool)) - assertSameSchema(t, "legacy rows", rowsBefore, "rows after goose", readRows()) - var versions []int64 - rows, err := pool.Query(ctx, `SELECT version_id FROM `+migrationVersionTable+` ORDER BY id`) - if err != nil { - t.Fatalf("read goose versions: %v", err) - } - defer rows.Close() - for rows.Next() { - var v int64 - if err := rows.Scan(&v); err != nil { - t.Fatal(err) - } - versions = append(versions, v) - } - if len(versions) != 6 || versions[0] != 0 || versions[5] != 5 { - t.Fatalf("goose versions = %v, want 0 through 5", versions) + assertSameLines(t, "legacy", schemaBefore, "after goose", schemaSnapshot(t, pool)) + assertSameLines(t, "legacy rows", rowsBefore, "rows after goose", queryLines(t, pool, rowsSQL)) + versions := queryLines(t, pool, `SELECT version_id::text FROM `+migrationVersionTable+` ORDER BY id`) + if got := strings.Join(versions, " "); got != "0 1 2 3 4 5" { + t.Fatalf("goose versions = %q, want 0 through 5", got) } } From 1bdf5bcd2e91bec5184bee165d93aeefeaf25a14 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sun, 4 Oct 2026 16:30:33 -0500 Subject: [PATCH 13/20] refactor: report index validity and inspect errors apart concurrentIndexState already wraps its error; return it as is, and report a not-valid index without a nil query error in the message. Co-Authored-By: Claude Opus 5.5 --- coordinator/store/postgres_migration_indexes.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/coordinator/store/postgres_migration_indexes.go b/coordinator/store/postgres_migration_indexes.go index f541afba89..a14113a3b6 100644 --- a/coordinator/store/postgres_migration_indexes.go +++ b/coordinator/store/postgres_migration_indexes.go @@ -81,8 +81,11 @@ func (s *PostgresStore) buildConcurrentIndexOnce(ctx context.Context, name, ddl if err := run(ddl); err != nil { return fmt.Errorf("store: create index %s: %w", name, err) } - if _, valid, err = concurrentIndexState(ctx, conn, name); err != nil || !valid { - return fmt.Errorf("store: index %s did not become valid (query error: %v)", name, err) + if _, valid, err = concurrentIndexState(ctx, conn, name); err != nil { + return err + } + if !valid { + return fmt.Errorf("store: index %s did not become valid", name) } return nil } From 1e45080d3af46496d088c6f3a82aa9b802296c92 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:06:13 -0700 Subject: [PATCH 14/20] Verify API-key sqlc null and rotation contracts --- .../store/contracts/apikey_backends_test.go | 71 ++++++++++++++++++- docs/AGENTS.md | 2 +- docs/README.md | 2 +- docs/architecture/schema-lifecycle.md | 2 +- docs/architecture/storage.md | 2 +- docs/developer/build.md | 2 +- docs/developer/database-migrations.md | 2 +- docs/developer/sqlc.md | 11 ++- docs/developer/test.md | 2 +- docs/reference/README.md | 2 +- docs/reference/sqlc-type-mapping.md | 2 +- 11 files changed, 86 insertions(+), 14 deletions(-) diff --git a/coordinator/tests/store/contracts/apikey_backends_test.go b/coordinator/tests/store/contracts/apikey_backends_test.go index 526de71cc3..c1dda8d876 100644 --- a/coordinator/tests/store/contracts/apikey_backends_test.go +++ b/coordinator/tests/store/contracts/apikey_backends_test.go @@ -1,6 +1,7 @@ package store_test import ( + "reflect" "testing" "time" @@ -15,9 +16,11 @@ func TestAPIKeyLifecycleOnEveryBackend(t *testing.T) { account := uniqueID("acct-keys") limit := int64(7_000_000) rpm := int64(60) + itpm, otpm := int64(12_000), int64(0) expires := time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond) raw, rec, err := s.CreateAPIKey(account, store.APIKeyCreate{ Name: "prod", LimitMicroUSD: &limit, RPMLimit: &rpm, LimitReset: store.KeyResetWeekly, + ITPMLimit: &itpm, OTPMLimit: &otpm, SelfRouteOnly: true, AllowedModels: []string{"m1", "m2"}, ExpiresAt: &expires, }) if err != nil { @@ -33,7 +36,9 @@ func TestAPIKeyLifecycleOnEveryBackend(t *testing.T) { } if got.Name != "prod" || got.Label != rec.Label || got.KeyHash != rec.KeyHash || got.LimitMicroUSD == nil || *got.LimitMicroUSD != limit || - got.RPMLimit == nil || *got.RPMLimit != rpm || got.ITPMLimit != nil || + got.RPMLimit == nil || *got.RPMLimit != rpm || + got.ITPMLimit == nil || *got.ITPMLimit != itpm || + got.OTPMLimit == nil || *got.OTPMLimit != otpm || !got.SelfRouteOnly || got.LimitReset != store.KeyResetWeekly || len(got.AllowedModels) != 2 || got.ExpiresAt == nil || !got.ExpiresAt.Equal(expires) || got.LastUsedAt != nil { t.Fatalf("GetAPIKeyByID = %+v", got) @@ -61,6 +66,10 @@ func TestAPIKeyLifecycleOnEveryBackend(t *testing.T) { mutable.Name = "renamed" mutable.LimitMicroUSD = nil mutable.RPMLimit = nil + mutable.ITPMLimit = nil + mutable.OTPMLimit = nil + mutable.SelfRouteOnly = false + mutable.ExpiresAt = nil mutable.LimitReset = store.KeyResetNone mutable.AllowedModels = nil mutable.Disabled = true @@ -69,7 +78,9 @@ func TestAPIKeyLifecycleOnEveryBackend(t *testing.T) { t.Fatalf("UpdateAPIKey: %v", err) } if updated.Name != "renamed" || updated.LimitMicroUSD != nil || updated.RPMLimit != nil || - updated.LimitReset != store.KeyResetNone || updated.AllowedModels != nil || !updated.Disabled { + updated.ITPMLimit != nil || updated.OTPMLimit != nil || updated.SelfRouteOnly || + updated.ExpiresAt != nil || updated.LimitReset != store.KeyResetNone || + updated.AllowedModels != nil || !updated.Disabled { t.Fatalf("UpdateAPIKey = %+v", updated) } if _, err := s.UpdateAPIKey(uniqueID("other"), rec.ID, mutable); err == nil { @@ -109,3 +120,59 @@ func TestAPIKeyLifecycleOnEveryBackend(t *testing.T) { }) } } + +// Rotation must retain every restriction while replacing the secret and resetting +// its last-use timestamp. The zero limits must remain distinct from SQL NULL. +func TestRotateAPIKeyPreservesRestrictionsOnEveryBackend(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + account := uniqueID("acct-rotate") + zero, inputLimit, outputLimit := int64(0), int64(12_000), int64(6_000) + expired := time.Now().UTC().Add(-time.Hour).Truncate(time.Microsecond) + raw, original, err := s.CreateAPIKey(account, store.APIKeyCreate{ + Name: "restricted", LimitMicroUSD: &zero, LimitReset: store.KeyResetDaily, + RPMLimit: &zero, ITPMLimit: &inputLimit, OTPMLimit: &outputLimit, + AllowedModels: []string{"m1", "m2"}, ExpiresAt: &expired, SelfRouteOnly: true, + }) + if err != nil { + t.Fatalf("CreateAPIKey: %v", err) + } + if _, err := s.AuthenticateKey(raw); err == nil { + t.Fatal("an expired key must not authenticate") + } + s.TouchAPIKey(original.ID, time.Now().UTC()) + if _, _, err := s.RotateAPIKey(uniqueID("other"), original.ID); err == nil { + t.Fatal("RotateAPIKey for another owner must fail") + } + newRaw, rotated, err := s.RotateAPIKey(account, original.ID) + if err != nil { + t.Fatalf("RotateAPIKey: %v", err) + } + if newRaw == raw || rotated.ID == original.ID || rotated.KeyHash == original.KeyHash { + t.Fatal("rotation must replace the key identity and secret") + } + got, err := s.GetAPIKeyByID(account, rotated.ID) + if err != nil { + t.Fatalf("GetAPIKeyByID after rotation: %v", err) + } + // Compare the complete persisted contract after excluding the four + // fields intentionally replaced by rotation. + if got.ExpiresAt == nil || !got.ExpiresAt.Equal(expired) { + t.Fatalf("rotation changed expiry: got %v, want %v", got.ExpiresAt, expired) + } + want := *original + want.ID, want.KeyHash, want.Label, want.CreatedAt = got.ID, got.KeyHash, got.Label, got.CreatedAt + // pgx may return the same instant in the local time zone. + want.ExpiresAt = got.ExpiresAt + if !reflect.DeepEqual(*got, want) { + t.Fatalf("rotation changed restrictions: got %+v, want %+v", got, want) + } + if _, err := s.AuthenticateKey(newRaw); err == nil { + t.Fatal("a rotated expired key must not authenticate") + } + if _, err := s.GetAPIKeyByID(account, original.ID); err == nil { + t.Fatal("rotation must remove the old key") + } + }) + } +} diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 5e7d8858a1..7ed7ddebfd 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -1,6 +1,6 @@ # Darkbloom docs — how this documentation is organised and maintained -> Last updated: 2026-10-04 +> Last updated: 2026-10-06 Rules for anyone — human or agent — who reads, writes, or checks a file under `docs/`. The code is the source of truth; a doc that disagrees with the code is diff --git a/docs/README.md b/docs/README.md index 89372505c8..ff8ce79b70 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # Darkbloom documentation -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 > Darkbloom is a decentralized private-inference network: an OpenAI- and > Anthropic-compatible HTTP API served by a Go coordinator that routes each diff --git a/docs/architecture/schema-lifecycle.md b/docs/architecture/schema-lifecycle.md index 04414affd5..2035a35e95 100644 --- a/docs/architecture/schema-lifecycle.md +++ b/docs/architecture/schema-lifecycle.md @@ -1,6 +1,6 @@ # Schema lifecycle -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 Explanation of how the coordinator's Postgres schema changes: numbered goose migrations that run inside `NewPostgres` before the coordinator serves, the diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 00377e5a2b..3097274975 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -1,6 +1,6 @@ # Storage -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 What the coordinator persists, through which interface and in which backend; then what a provider keeps on its own disk and in its Keychain. How the schema diff --git a/docs/developer/build.md b/docs/developer/build.md index d31be21fd6..9da2d7ba7f 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 The provider test runner isolates daemon-state and loaded-model snapshots in a temporary directory for each run. Unit-test providers must not overwrite the diff --git a/docs/developer/database-migrations.md b/docs/developer/database-migrations.md index ffff0fce23..28906f74e3 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -1,6 +1,6 @@ # Add a database migration -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 How to change the coordinator's Postgres schema: choose the migration kind, write it as a numbered goose version, regenerate the checked-in schema, and diff --git a/docs/developer/sqlc.md b/docs/developer/sqlc.md index 6374b400f7..7a73fb736f 100644 --- a/docs/developer/sqlc.md +++ b/docs/developer/sqlc.md @@ -1,6 +1,6 @@ # Write store queries with sqlc -> Last updated: 2026-10-04 +> Last updated: 2026-10-06 How to add a Postgres query to the coordinator store with sqlc, how to move a hand-written store domain to sqlc (the api_keys domain is the worked @@ -64,7 +64,11 @@ the Postgres-to-Go types are in [sqlc type mapping](../reference/sqlc-type-mappi 4. If the method is new on the `Store` interface, implement it in `MemoryStore` (`coordinator/store/memory/`) too and cover both backends in one test, as `TestAPIKeyLifecycleOnEveryBackend` - (`coordinator/tests/store/contracts/apikey_backends_test.go`) does. + (`coordinator/tests/store/contracts/apikey_backends_test.go`) does. If it writes + users or model-registry records, add the matching `CachedStore` invalidation + override in `coordinator/store/cached.go`; query generation does not provide + cache invalidation. Discover optional backend capabilities through `store.As` + so they remain available through the decorator. ## Steps: convert a hand-written domain @@ -133,7 +137,8 @@ go test ./coordinator/tests/store/... -count=1 -run 'APIKey' | A parameter is `pgtype.Timestamp`, not `*time.Time` | The cast is `::timestamp` (without time zone); the overrides cover only `timestamptz` | Cast to `::timestamptz`. | | A parameter is named `dollar_1` | A positional parameter that sqlc cannot tie to a column | Use `sqlc.arg('name')`. | | A reused `$1` has the name of only its first column | sqlc gives a positional parameter one name | Use one `sqlc.arg('name')` for both places, or two parameters. | -| `go: downloading go1.26...` fails | `GOTOOLCHAIN=local` with an older Go | Unset `GOTOOLCHAIN` or install Go 1.26. | +| `requires go >= 1.26.0` with `GOTOOLCHAIN=local` | The selected Go version is too old for sqlc | Unset `GOTOOLCHAIN` to permit automatic toolchain selection, or install Go 1.26. | +| Downloading the Go toolchain fails | The automatic download could not reach the Go module proxy | Restore proxy access, or install Go 1.26 locally. | ## Related diff --git a/docs/developer/test.md b/docs/developer/test.md index fffd5ddd36..714941db30 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 ## Nightly Linear package diff --git a/docs/reference/README.md b/docs/reference/README.md index 2d99f189d2..4563152368 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -1,6 +1,6 @@ # Reference — exact shapes and values -> Last updated: 2026-10-04 +> Last updated: 2026-10-06 Tables and schemas for Darkbloom's public interfaces, wire protocol, configuration, and formats. Consult these; do not read them front to back. diff --git a/docs/reference/sqlc-type-mapping.md b/docs/reference/sqlc-type-mapping.md index ded90b3435..446c14c1fc 100644 --- a/docs/reference/sqlc-type-mapping.md +++ b/docs/reference/sqlc-type-mapping.md @@ -1,6 +1,6 @@ # sqlc type mapping -> Last updated: 2026-10-04 +> Last updated: 2026-10-06 Reference for the Go types that sqlc v1.31.1 generates in `coordinator/store/postgres/storedb/` from `coordinator/store/postgres/schema/schema.sql` From 6e3fe88862deb005f107f3876ba7e405361eefca Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:13:35 -0700 Subject: [PATCH 15/20] Require canonical docs for sqlc changes --- scripts/docs-impact-rules.json | 12 ++++++++++++ scripts/test-docs-impact-check.py | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/scripts/docs-impact-rules.json b/scripts/docs-impact-rules.json index 71f84ffe84..a3883daaf2 100644 --- a/scripts/docs-impact-rules.json +++ b/scripts/docs-impact-rules.json @@ -223,6 +223,18 @@ "docs/architecture/schema-lifecycle.md" ] }, + { + "name": "sqlc queries and type mappings", + "source_patterns": [ + "coordinator/store/postgres/sqlc.yaml", + "coordinator/store/postgres/queries/**", + "coordinator/store/postgres/storedb/**" + ], + "docs_any_of": [ + "docs/developer/sqlc.md", + "docs/reference/sqlc-type-mapping.md" + ] + }, { "name": "provider release", "source_patterns": [ diff --git a/scripts/test-docs-impact-check.py b/scripts/test-docs-impact-check.py index 8a04fa5fe9..84b3789b38 100644 --- a/scripts/test-docs-impact-check.py +++ b/scripts/test-docs-impact-check.py @@ -55,6 +55,31 @@ def test_maintainer_override_passes(self) -> None: self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("bypassed", result.stdout) + def test_sqlc_changes_require_canonical_docs(self) -> None: + sources = ( + "coordinator/store/postgres/sqlc.yaml", + "coordinator/store/postgres/queries/api_keys.sql", + "coordinator/store/postgres/storedb/models.go", + ) + documents = ("docs/developer/sqlc.md", "docs/reference/sqlc-type-mapping.md") + for source in sources: + with self.subTest(source=source): + for unrelated in ((), ("docs/architecture/storage.md",)): + missing = self.run_check(source, *unrelated) + self.assertEqual(missing.returncode, 1, missing.stdout + missing.stderr) + self.assertIn("sqlc queries and type mappings source changed", missing.stderr) + for document in documents: + covered = self.run_check(source, document) + self.assertEqual(covered.returncode, 0, covered.stdout + covered.stderr) + overridden = self.run_check(source, labels=["docs-not-needed"]) + self.assertEqual(overridden.returncode, 0, overridden.stdout + overridden.stderr) + + ignored = self.run_check( + "coordinator/tests/store/postgres/storedb/models_test.go", + "coordinator/store/postgres/storedb/models_test.go", + ) + self.assertEqual(ignored.returncode, 0, ignored.stdout + ignored.stderr) + def test_reorganized_owners_keep_canonical_documentation_gates(self) -> None: cases = ( ("coordinator/api/routes.go", "docs/reference/api-contracts.md"), From c5824c2b5979a8e867ddb4bc35934f4bb451e9dc Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:22:51 -0700 Subject: [PATCH 16/20] Group concurrent index migration tests by responsibility --- .../store/postgres/migration_index_test.go | 150 ++++++++++++++++++ .../tests/store/postgres/migrations_test.go | 149 ----------------- docs/architecture/schema-lifecycle.md | 4 +- docs/developer/test.md | 7 + 4 files changed, 159 insertions(+), 151 deletions(-) diff --git a/coordinator/tests/store/postgres/migration_index_test.go b/coordinator/tests/store/postgres/migration_index_test.go index bfc7435060..f69f98fdef 100644 --- a/coordinator/tests/store/postgres/migration_index_test.go +++ b/coordinator/tests/store/postgres/migration_index_test.go @@ -4,8 +4,11 @@ import ( "context" "strings" "testing" + "time" "github.com/eigeninference/d-inference/coordinator/store" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" ) func TestMigrationsRefuseInvalidStripeRefundIndex(t *testing.T) { @@ -53,3 +56,150 @@ func TestMigrationsRefuseInvalidStripeRefundIndex(t *testing.T) { t.Fatalf("repaired refund index valid=%v, unique=%v", valid, unique) } } + +// A CREATE INDEX CONCURRENTLY waits for every older snapshot. A query that +// runs longer than the 3 s session lock_timeout must not cancel it: the +// CONCURRENTLY migrations wait up to a minute, and apply on the first attempt. +func TestConcurrentIndexMigrationWaitsForOlderSnapshot(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + s, err := openPostgresFixture(ctx, store.Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + if _, err := s.pool.Exec(ctx, `DROP INDEX idx_provider_sessions_account`); err != nil { + t.Fatal(err) + } + pendingFrom(t, s, 10) + + holder := openTestPool(t, databaseURL) + tx, err := holder.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead}) + if err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `SELECT count(*) FROM users`); err != nil { + t.Fatal(err) + } + release := time.AfterFunc(2*migrationLockTimeout, func() { _ = tx.Rollback(context.Background()) }) + defer release.Stop() + + logs := captureLogs(t) + if err := s.reopen(ctx); err != nil { + t.Fatalf("migrate behind an older snapshot: %v", err) + } + if strings.Contains(logs.String(), "retrying") { + t.Fatalf("the index build hit the session lock_timeout; logs:\n%s", logs.String()) + } + if valid, err := indexValid(ctx, s.pool, "idx_provider_sessions_account"); err != nil || !valid { + t.Fatalf("idx_provider_sessions_account valid=%v err=%v", valid, err) + } +} + +// pendingFrom makes version and every later version pending again. +func pendingFrom(t *testing.T, s *postgresFixture, version int64) { + t.Helper() + if _, err := s.pool.Exec(context.Background(), `DELETE FROM `+gooseVersionTable+` WHERE version_id >= $1`, version); err != nil { + t.Fatal(err) + } +} + +func versionRecorded(t *testing.T, s *postgresFixture, version int64) bool { + t.Helper() + var recorded bool + if err := s.pool.QueryRow(context.Background(), `SELECT EXISTS(SELECT 1 FROM `+gooseVersionTable+` WHERE version_id = $1)`, version).Scan(&recorded); err != nil { + t.Fatal(err) + } + return recorded +} + +// indexValid reports pg_index.indisvalid for the index name. +func indexValid(ctx context.Context, pool *pgxpool.Pool, name string) (bool, error) { + var valid bool + err := pool.QueryRow(ctx, `SELECT indisvalid FROM pg_index WHERE indexrelid = $1::text::regclass`, name).Scan(&valid) + return valid, err +} + +// An interrupted CONCURRENTLY build leaves an invalid index of the same name. +// The index migration drops it, builds again, and records the version only +// with a valid index. +func TestIndexMigrationRebuildsInvalidLeftover(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + s, err := openPostgresFixture(ctx, store.Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + if _, err := s.pool.Exec(ctx, `DROP INDEX idx_provider_sessions_account`); err != nil { + t.Fatal(err) + } + pendingFrom(t, s, 10) + + // The reviewer's reproduction: a build that times out behind an older + // snapshot fails and leaves an invalid index. + holder := openTestPool(t, databaseURL) + tx, err := holder.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead}) + if err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `SELECT count(*) FROM users`); err != nil { + t.Fatal(err) + } + builder, err := pgx.Connect(ctx, databaseURL) + if err != nil { + t.Fatal(err) + } + if _, err := builder.Exec(ctx, `SET lock_timeout = '200ms'`); err != nil { + t.Fatal(err) + } + if _, err := builder.Exec(ctx, `CREATE INDEX CONCURRENTLY idx_provider_sessions_account ON provider_sessions (account_id)`); err == nil { + t.Fatal("fixture: the build behind an older snapshot did not fail") + } + _ = builder.Close(ctx) + if err := tx.Rollback(ctx); err != nil { + t.Fatal(err) + } + if valid, err := indexValid(ctx, s.pool, "idx_provider_sessions_account"); err != nil || valid { + t.Fatalf("fixture: leftover index valid=%v err=%v, want an invalid index", valid, err) + } + + if err := s.reopen(ctx); err != nil { + t.Fatalf("migrate with an invalid leftover index: %v", err) + } + if valid, err := indexValid(ctx, s.pool, "idx_provider_sessions_account"); err != nil || !valid { + t.Fatalf("idx_provider_sessions_account valid=%v err=%v after migrate", valid, err) + } + if !versionRecorded(t, s, 10) { + t.Fatal("version 10 not recorded after a successful rebuild") + } +} + +// A build that cannot produce a valid index fails the boot, and goose does +// not record the version: here the unique live-user index meets two live +// users with the same Privy ID. +func TestIndexMigrationFailureIsNotRecorded(t *testing.T) { + ctx := context.Background() + databaseURL := newThrowawayTestDatabase(t) + s, err := openPostgresFixture(ctx, store.Config{DatabaseURL: databaseURL}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + t.Cleanup(s.Close) + if _, err := s.pool.Exec(ctx, `DROP INDEX idx_users_privy_live`); err != nil { + t.Fatal(err) + } + for _, account := range []string{"first", "second"} { + if _, err := s.pool.Exec(ctx, `INSERT INTO users (account_id, privy_user_id) VALUES ($1, 'did:privy:shared')`, account); err != nil { + t.Fatal(err) + } + } + pendingFrom(t, s, 18) + + if err := s.reopen(ctx); err == nil { + t.Fatal("migrate succeeded although idx_users_privy_live cannot be built") + } + if versionRecorded(t, s, 18) { + t.Fatal("version 18 recorded although its index build failed") + } +} diff --git a/coordinator/tests/store/postgres/migrations_test.go b/coordinator/tests/store/postgres/migrations_test.go index 33c99f0672..37ff97cf44 100644 --- a/coordinator/tests/store/postgres/migrations_test.go +++ b/coordinator/tests/store/postgres/migrations_test.go @@ -16,9 +16,7 @@ import ( "github.com/eigeninference/d-inference/coordinator/store" production "github.com/eigeninference/d-inference/coordinator/store/postgres" - "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" - "github.com/jackc/pgx/v5/pgxpool" "github.com/pressly/goose/v3/lock" ) @@ -328,150 +326,3 @@ func TestMigrationsBlockedLegacyColumnRemainsPending(t *testing.T) { t.Fatal("retry did not restore providers.version") } } - -// A CREATE INDEX CONCURRENTLY waits for every older snapshot. A query that -// runs longer than the 3 s session lock_timeout must not cancel it: the -// CONCURRENTLY migrations wait up to a minute, and apply on the first attempt. -func TestConcurrentIndexMigrationWaitsForOlderSnapshot(t *testing.T) { - ctx := context.Background() - databaseURL := newThrowawayTestDatabase(t) - s, err := openPostgresFixture(ctx, store.Config{DatabaseURL: databaseURL}) - if err != nil { - t.Fatalf("NewPostgres: %v", err) - } - t.Cleanup(s.Close) - if _, err := s.pool.Exec(ctx, `DROP INDEX idx_provider_sessions_account`); err != nil { - t.Fatal(err) - } - pendingFrom(t, s, 10) - - holder := openTestPool(t, databaseURL) - tx, err := holder.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead}) - if err != nil { - t.Fatal(err) - } - if _, err := tx.Exec(ctx, `SELECT count(*) FROM users`); err != nil { - t.Fatal(err) - } - release := time.AfterFunc(2*migrationLockTimeout, func() { _ = tx.Rollback(context.Background()) }) - defer release.Stop() - - logs := captureLogs(t) - if err := s.reopen(ctx); err != nil { - t.Fatalf("migrate behind an older snapshot: %v", err) - } - if strings.Contains(logs.String(), "retrying") { - t.Fatalf("the index build hit the session lock_timeout; logs:\n%s", logs.String()) - } - if valid, err := indexValid(ctx, s.pool, "idx_provider_sessions_account"); err != nil || !valid { - t.Fatalf("idx_provider_sessions_account valid=%v err=%v", valid, err) - } -} - -// pendingFrom makes version and every later version pending again. -func pendingFrom(t *testing.T, s *postgresFixture, version int64) { - t.Helper() - if _, err := s.pool.Exec(context.Background(), `DELETE FROM `+gooseVersionTable+` WHERE version_id >= $1`, version); err != nil { - t.Fatal(err) - } -} - -func versionRecorded(t *testing.T, s *postgresFixture, version int64) bool { - t.Helper() - var recorded bool - if err := s.pool.QueryRow(context.Background(), `SELECT EXISTS(SELECT 1 FROM `+gooseVersionTable+` WHERE version_id = $1)`, version).Scan(&recorded); err != nil { - t.Fatal(err) - } - return recorded -} - -// indexValid reports pg_index.indisvalid for the index name. -func indexValid(ctx context.Context, pool *pgxpool.Pool, name string) (bool, error) { - var valid bool - err := pool.QueryRow(ctx, `SELECT indisvalid FROM pg_index WHERE indexrelid = $1::text::regclass`, name).Scan(&valid) - return valid, err -} - -// An interrupted CONCURRENTLY build leaves an invalid index of the same name. -// The index migration drops it, builds again, and records the version only -// with a valid index. -func TestIndexMigrationRebuildsInvalidLeftover(t *testing.T) { - ctx := context.Background() - databaseURL := newThrowawayTestDatabase(t) - s, err := openPostgresFixture(ctx, store.Config{DatabaseURL: databaseURL}) - if err != nil { - t.Fatalf("NewPostgres: %v", err) - } - t.Cleanup(s.Close) - if _, err := s.pool.Exec(ctx, `DROP INDEX idx_provider_sessions_account`); err != nil { - t.Fatal(err) - } - pendingFrom(t, s, 10) - - // The reviewer's reproduction: a build that times out behind an older - // snapshot fails and leaves an invalid index. - holder := openTestPool(t, databaseURL) - tx, err := holder.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead}) - if err != nil { - t.Fatal(err) - } - if _, err := tx.Exec(ctx, `SELECT count(*) FROM users`); err != nil { - t.Fatal(err) - } - builder, err := pgx.Connect(ctx, databaseURL) - if err != nil { - t.Fatal(err) - } - if _, err := builder.Exec(ctx, `SET lock_timeout = '200ms'`); err != nil { - t.Fatal(err) - } - if _, err := builder.Exec(ctx, `CREATE INDEX CONCURRENTLY idx_provider_sessions_account ON provider_sessions (account_id)`); err == nil { - t.Fatal("fixture: the build behind an older snapshot did not fail") - } - _ = builder.Close(ctx) - if err := tx.Rollback(ctx); err != nil { - t.Fatal(err) - } - if valid, err := indexValid(ctx, s.pool, "idx_provider_sessions_account"); err != nil || valid { - t.Fatalf("fixture: leftover index valid=%v err=%v, want an invalid index", valid, err) - } - - if err := s.reopen(ctx); err != nil { - t.Fatalf("migrate with an invalid leftover index: %v", err) - } - if valid, err := indexValid(ctx, s.pool, "idx_provider_sessions_account"); err != nil || !valid { - t.Fatalf("idx_provider_sessions_account valid=%v err=%v after migrate", valid, err) - } - if !versionRecorded(t, s, 10) { - t.Fatal("version 10 not recorded after a successful rebuild") - } -} - -// A build that cannot produce a valid index fails the boot, and goose does -// not record the version: here the unique live-user index meets two live -// users with the same Privy ID. -func TestIndexMigrationFailureIsNotRecorded(t *testing.T) { - ctx := context.Background() - databaseURL := newThrowawayTestDatabase(t) - s, err := openPostgresFixture(ctx, store.Config{DatabaseURL: databaseURL}) - if err != nil { - t.Fatalf("NewPostgres: %v", err) - } - t.Cleanup(s.Close) - if _, err := s.pool.Exec(ctx, `DROP INDEX idx_users_privy_live`); err != nil { - t.Fatal(err) - } - for _, account := range []string{"first", "second"} { - if _, err := s.pool.Exec(ctx, `INSERT INTO users (account_id, privy_user_id) VALUES ($1, 'did:privy:shared')`, account); err != nil { - t.Fatal(err) - } - } - pendingFrom(t, s, 18) - - if err := s.reopen(ctx); err == nil { - t.Fatal("migrate succeeded although idx_users_privy_live cannot be built") - } - if versionRecorded(t, s, 18) { - t.Fatal("version 18 recorded although its index build failed") - } -} diff --git a/docs/architecture/schema-lifecycle.md b/docs/architecture/schema-lifecycle.md index 78eb3cbb5d..93431b1caf 100644 --- a/docs/architecture/schema-lifecycle.md +++ b/docs/architecture/schema-lifecycle.md @@ -335,7 +335,7 @@ Logs carry bounded labels only, never SQL or parameters `buildConcurrentIndexOnce` fails unless `indisvalid AND indisready` (`TestIndexMigrationRebuildsInvalidLeftover`, `TestIndexMigrationFailureIsNotRecorded` in - `coordinator/tests/store/postgres/migrations_test.go`). + `coordinator/tests/store/postgres/migration_index_test.go`). 9. **A soft-deleted row is never returned as live.** Every read in the [soft-delete reference](../reference/soft-delete.md) filters it, on both backends (`coordinator/tests/store/postgres/soft_delete_reads_test.go` @@ -379,7 +379,7 @@ Logs carry bounded labels only, never SQL or parameters | sqlc config, queries, generated code | `coordinator/store/postgres/sqlc.yaml`, `coordinator/store/postgres/queries/`, `coordinator/store/postgres/storedb/` | | api_keys store methods | `coordinator/store/postgres/apikey.go` (`queries`, `apiKeyFromRow`, `insertAPIKeyParams`) | | sqlc targets | `Makefile` (`sqlc-generate`, `sqlc-check`) | -| Tests | `coordinator/tests/store/postgres/migrations_test.go`, `coordinator/tests/store/postgres/migration_harness_test.go` | +| Tests | `coordinator/tests/store/postgres/migrations_test.go`, `coordinator/tests/store/postgres/migration_index_test.go`, `coordinator/tests/store/postgres/migration_harness_test.go` | | Manual SQL | `coordinator/store/postgres/migrations/` | ## Related diff --git a/docs/developer/test.md b/docs/developer/test.md index 6b23daae60..14f8ccb2a6 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1198,6 +1198,13 @@ index applicability, MDA trust caps, and a migration-only subprocess that exits without HTTP startup or admin-key seeding. They do not measure production startup latency or validate an overlapping coordinator handoff. +Goose startup, upgrade and advisory-lock tests live in +`coordinator/tests/store/postgres/migrations_test.go`. Concurrent-index snapshot +waits, invalid-leftover recovery and failed-version recording live in +`coordinator/tests/store/postgres/migration_index_test.go`. Run the +[migration verification commands](database-migrations.md#verify) with the same +disposable database. + Startup recovery regressions also cover catalog-verified index definitions and isolated planner applicability, transient provider/reputation retries, a shared deadline, 1013 registration teardown before duplicate eviction, and routing/capacity/load From 5f85d430fa8a250aa45d8410d5ca3e6f6056e909 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:29:52 -0700 Subject: [PATCH 17/20] Exclude soft-deleted contacts and initial MDM cohort evidence --- CHANGELOG.md | 2 + coordinator/store/memory/legacy_mdm_cohort.go | 2 +- .../store/memory/small_models_interest.go | 2 +- .../store/postgres/legacy_mdm_cohort.go | 1 + .../store/postgres/small_models_interest.go | 2 +- .../soft_delete_domain_reads_test.go | 148 ++++++++++++++++++ docs/architecture/security/enrollment.md | 8 +- docs/consumer/verification.md | 4 +- docs/developer/build.md | 2 + docs/developer/test.md | 7 +- docs/provider/attestation.md | 5 +- docs/reference/soft-delete.md | 13 +- docs/threat-model.yaml | 5 +- scripts/docs-impact-rules.json | 10 +- scripts/test-docs-impact-check.py | 11 +- 15 files changed, 206 insertions(+), 16 deletions(-) create mode 100644 coordinator/tests/store/contracts/soft_delete_domain_reads_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f3907a65bf..f73a74335f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ - Prepare account erasure: add `deleted_at` to users, API keys, provider records and provider tokens, hide soft-deleted rows from every live read, let a Privy user sign up again after erasure, index the erase paths, and cascade referrer code changes to referrals. Nothing sets `deleted_at` yet. After this release runs, roll back only to coordinator images built with goose. +- Exclude soft-deleted users from small-model interest exports before pagination, and exclude deleted users and provider records from initial legacy MDM cohort qualification. Repeated cohort reads preserve the frozen snapshot. + ## Unreleased — Stripe refund clock skew - Refund a rejected Stripe withdrawal when the coordinator clock is ahead of the PostgreSQL clock. Before, the refund check missed the withdrawal debit, refused the refund, and the recovery loop and `payout-audit --apply-refund` retried without success. The check still credits each withdrawal at most once and still refuses a ledger that does not show the exact debit. diff --git a/coordinator/store/memory/legacy_mdm_cohort.go b/coordinator/store/memory/legacy_mdm_cohort.go index da8056766f..cf281c607a 100644 --- a/coordinator/store/memory/legacy_mdm_cohort.go +++ b/coordinator/store/memory/legacy_mdm_cohort.go @@ -25,7 +25,7 @@ func (s *MemoryStore) FreezeLegacyMDMCohort(ctx context.Context) ([]store.Legacy members := map[store.LegacyMDMMachine]bool{} for _, p := range s.providerRecords { u := s.usersByAccountID[p.AccountID] - if u == nil || !u.CreatedAt.Before(cutoff) || !p.RegisteredAt.Before(cutoff) || p.AccountID == "" || p.SEPublicKey == "" || p.SerialNumber == "" || s.machineInventory == nil { + if u == nil || u.DeletedAt != nil || p.DeletedAt != nil || !u.CreatedAt.Before(cutoff) || !p.RegisteredAt.Before(cutoff) || p.AccountID == "" || p.SEPublicKey == "" || p.SerialNumber == "" || s.machineInventory == nil { continue } alias := (store.MachineObservation{AccountID: p.AccountID, SEKey: p.SEPublicKey}).Aliases()[0] diff --git a/coordinator/store/memory/small_models_interest.go b/coordinator/store/memory/small_models_interest.go index c9c291eb9b..96212eb696 100644 --- a/coordinator/store/memory/small_models_interest.go +++ b/coordinator/store/memory/small_models_interest.go @@ -50,7 +50,7 @@ func (s *MemoryStore) ListSmallModelsInterest(ctx context.Context, after string, defer s.mu.RUnlock() ids := make([]string, 0, len(s.smallModelsInterest)) for id := range s.smallModelsInterest { - if id > after { + if user := s.usersByAccountID[id]; id > after && user != nil && user.DeletedAt == nil { ids = append(ids, id) } } diff --git a/coordinator/store/postgres/legacy_mdm_cohort.go b/coordinator/store/postgres/legacy_mdm_cohort.go index fa9bdc8d1a..e82a0815e4 100644 --- a/coordinator/store/postgres/legacy_mdm_cohort.go +++ b/coordinator/store/postgres/legacy_mdm_cohort.go @@ -41,6 +41,7 @@ func (s *PostgresStore) FreezeLegacyMDMCohort(ctx context.Context) ([]store.Lega AND a.digest=encode(sha256(convert_to('legacy_se','UTF8') || '\x00'::bytea || convert_to(p.se_public_key,'UTF8')), 'hex') LEFT JOIN provider_trust_reuse r ON r.se_pubkey=p.se_public_key AND r.serial=p.serial_number WHERE p.account_id<>'' AND p.se_public_key<>'' AND p.serial_number<>'' + AND u.deleted_at IS NULL AND p.deleted_at IS NULL AND u.created_at'' AND r.sip_enabled AND r.secure_boot_full AND r.hardware_proof_verified_at>'0001-01-01T00:00:00Z'::timestamptz AND r.hardware_proof_verified_at $1 ORDER BY i.account_id LIMIT $2`, after, shared.SmallModelsInterestPageLimit(limit)) + WHERE i.account_id > $1 AND u.deleted_at IS NULL ORDER BY i.account_id LIMIT $2`, after, shared.SmallModelsInterestPageLimit(limit)) if err != nil { return nil, err } diff --git a/coordinator/tests/store/contracts/soft_delete_domain_reads_test.go b/coordinator/tests/store/contracts/soft_delete_domain_reads_test.go new file mode 100644 index 0000000000..351c78e86e --- /dev/null +++ b/coordinator/tests/store/contracts/soft_delete_domain_reads_test.go @@ -0,0 +1,148 @@ +package store_test + +import ( + "context" + "encoding/json" + "os" + "reflect" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" + "github.com/eigeninference/d-inference/coordinator/store/postgres" + "github.com/jackc/pgx/v5/pgxpool" +) + +// The erasure writer is introduced separately. Seed tombstones through memory +// records and SQL in the isolated PostgreSQL fixture to exercise these readers. +func createUserWithDeletion(t *testing.T, s store.Store, id string, deletedAt *time.Time) { + t.Helper() + if err := s.CreateUser(&store.User{AccountID: id, PrivyUserID: id, Email: id + "@example.test", DeletedAt: deletedAt}); err != nil { + t.Fatal(err) + } + if _, ok := s.(*postgres.PostgresStore); ok && deletedAt != nil { + softDeleteFixtureExec(t, `UPDATE users SET deleted_at=$1 WHERE account_id=$2`, deletedAt, id) + } +} + +func softDeleteFixtureExec(t *testing.T, query string, args ...any) { + t.Helper() + ctx := context.Background() + pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL")) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if _, err := pool.Exec(ctx, query, args...); err != nil { + t.Fatal(err) + } +} + +func TestSmallModelsInterestOmitsDeletedUsersBeforePagination(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + for _, id := range []string{"a-deleted", "b-live", "c-deleted", "d-live", "e-deleted"} { + var deletedAt *time.Time + if id != "b-live" && id != "d-live" { + deletedAt = &now + } + createUserWithDeletion(t, s, id, deletedAt) + if err := s.UpsertSmallModelsInterest(ctx, store.SmallModelsInterest{AccountID: id, MacType: "Mac Mini", Chip: "M4", RAMGB: 16}); err != nil { + t.Fatal(err) + } + } + // Deleted contacts at the start and between live rows must not consume + // the page limit or make a caller stop before all live contacts arrive. + for _, page := range []struct{ after, want string }{ + {"", "b-live"}, {"b-live", "d-live"}, {"d-live", ""}, + } { + rows, err := s.ListSmallModelsInterest(ctx, page.after, 1) + if err != nil { + t.Fatal(err) + } + if page.want == "" { + if len(rows) != 0 { + t.Fatalf("last page = %+v; want empty", rows) + } + } else if len(rows) != 1 || rows[0].AccountID != page.want || rows[0].Email != page.want+"@example.test" || rows[0].RAMGB != 16 { + t.Fatalf("page after %q = %+v; want live contact %q", page.after, rows, page.want) + } + } + rows, err := s.ListSmallModelsInterest(ctx, "", 100) + if err != nil || len(rows) != 2 || rows[0].AccountID != "b-live" || rows[1].AccountID != "d-live" { + t.Fatalf("all contacts = %+v, %v; want both live contacts", rows, err) + } + }) + } +} + +func TestLegacyMDMCohortOmitsDeletedInitialEvidence(t *testing.T) { + for _, proof := range []string{"historical", "hardware"} { + t.Run(proof, func(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + inventory, ok := store.As[store.MachineInventoryStore](s) + if !ok { + t.Fatal("missing inventory store") + } + var live store.ProviderRecord + for _, id := range []string{"deleted-user", "deleted-provider", "live"} { + var deletedAt *time.Time + if id == "deleted-user" { + deletedAt = &now + } + createUserWithDeletion(t, s, id, deletedAt) + p := store.ProviderRecord{ID: id, AccountID: id, SEPublicKey: "se-" + id, SerialNumber: "serial-" + id, RegisteredAt: now.Add(-time.Hour), LastSeen: now, Hardware: json.RawMessage(`{}`), Models: json.RawMessage(`[]`)} + if id == "deleted-provider" { + p.DeletedAt = &now + } + if proof == "hardware" { + p.TrustLevel, p.Attested = "hardware", true + p.AttestationResult, _ = json.Marshal(map[string]any{"Valid": true, "SecureEnclaveAvailable": true, "SIPEnabled": true, "SecureBootEnabled": true, "PublicKey": p.SEPublicKey, "SerialNumber": p.SerialNumber}) + } else { + legacyMDMProof(t, s, p) + } + if err := s.UpsertProvider(ctx, p); err != nil { + t.Fatal(err) + } + if _, ok := s.(*postgres.PostgresStore); ok && p.DeletedAt != nil { + softDeleteFixtureExec(t, `UPDATE providers SET deleted_at=$1 WHERE id=$2`, p.DeletedAt, p.ID) + } + if _, err := inventory.ObserveMachine(ctx, store.MachineObservation{SessionID: id, AccountID: id, SEKey: p.SEPublicKey, At: now.Add(-time.Minute)}); err != nil { + t.Fatal(err) + } + if id == "live" { + live = p + } + } + freeze, ok := store.As[store.LegacyMDMCohortStore](s) + if !ok { + t.Fatal("missing legacy MDM cohort store") + } + want := []store.LegacyMDMMachine{{AccountID: live.AccountID, SEPublicKey: live.SEPublicKey, SerialNumber: live.SerialNumber}} + rows, err := freeze.FreezeLegacyMDMCohort(ctx) + if err != nil || !reflect.DeepEqual(rows, want) { + t.Fatalf("initial freeze = %+v, %v; want %+v", rows, err, want) + } + // The filter governs initial qualification, not later reads of the + // durable snapshot. Deleting a provider does not recompute the cohort. + live.DeletedAt = &now + if err := s.UpsertProvider(ctx, live); err != nil { + t.Fatal(err) + } + if _, ok := s.(*postgres.PostgresStore); ok { + softDeleteFixtureExec(t, `UPDATE providers SET deleted_at=$1 WHERE id=$2`, live.DeletedAt, live.ID) + } + rows, err = freeze.FreezeLegacyMDMCohort(ctx) + if err != nil || !reflect.DeepEqual(rows, want) { + t.Fatalf("repeat freeze = %+v, %v; want retained snapshot %+v", rows, err, want) + } + }) + } + }) + } +} diff --git a/docs/architecture/security/enrollment.md b/docs/architecture/security/enrollment.md index b0e222779c..eb5cfc23f9 100644 --- a/docs/architecture/security/enrollment.md +++ b/docs/architecture/security/enrollment.md @@ -1,6 +1,6 @@ # MDM enrollment -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 How a provider Mac joins Darkbloom's MDM so the coordinator can ask Apple's management subsystem, rather than the provider binary, whether SIP and Secure @@ -40,7 +40,11 @@ The upcoming policy freezes a durable cohort on the first upgraded production coordinator startup, **after revocation replay**. Membership binds the stored account, Secure Enclave public key and serial of a device already successfully MDM-verified before the freeze. It is not a list of every MicroMDM enrollment, -every saved `hardware` label, or every account that owns a provider. Subsequent +every saved `hardware` label, or every account that owns a provider. Initial +qualification excludes soft-deleted accounts and provider records in both +`coordinator/store/postgres/legacy_mdm_cohort.go` and +`coordinator/store/memory/legacy_mdm_cohort.go` (`FreezeLegacyMDMCohort`). These +filters do not recompute an already frozen snapshot. Subsequent restarts reuse the frozen cohort, even when empty; new accounts, devices, keys and new account/device associations cannot expand it. Reenrollment requires the existing key under its frozen account. A new identity requires macOS 27 or later diff --git a/docs/consumer/verification.md b/docs/consumer/verification.md index a1fdf39cb1..2beaa33034 100644 --- a/docs/consumer/verification.md +++ b/docs/consumer/verification.md @@ -1,6 +1,6 @@ # Verifying provider attestation -> Last updated: 2026-10-04 +> Last updated: 2026-10-06 How a consumer reads the coordinator's trust verdict about the provider that served a request, and what that verdict does and does not prove. The verdict is @@ -14,7 +14,7 @@ An App Attest grant also depends on a fresh [durable build qualification](../ref Local profile-inventory authentication during `darkbloom unenroll` only identifies the Darkbloom enrollment for user-guided removal. It does not verify or extend serving authorization; the [provider procedure](../provider/attestation.md#app-attest-without-darkbloom-mdm) explains the separate coordinator readiness requirement. -Under the upcoming [frozen legacy MDM policy](../architecture/security/enrollment.md#frozen-legacy-authorization-cohort), legacy MDM authorization is restricted to already successfully verified devices with a durable frozen authenticated account/key/serial association. New accounts, devices and associations cannot join it after the first upgraded startup, and restarts do not reopen it. Membership alone is not verification: current posture, freshness, revocation and code-identity gates still apply. New identities require qualified App Attest; unsupported OS versions do not create a legacy fallback. No grace period has been chosen and no cohort expiry is implemented. +Under the upcoming [frozen legacy MDM policy](../architecture/security/enrollment.md#frozen-legacy-authorization-cohort), legacy MDM authorization is restricted to already successfully verified devices with a durable frozen authenticated account/key/serial association. Soft-deleted accounts and provider records cannot qualify for its initial snapshot. New accounts, devices and associations cannot join it after the first upgraded startup, and restarts do not reopen it. Membership alone is not verification: current posture, freshness, revocation and code-identity gates still apply. New identities require qualified App Attest; unsupported OS versions do not create a legacy fallback. No grace period has been chosen and no cohort expiry is implemented. New providers require macOS 27 or later and current qualified App Attest authorization; consumers do not need macOS 27 to use the API or console. diff --git a/docs/developer/build.md b/docs/developer/build.md index 9da2d7ba7f..c4a24cee8e 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -517,6 +517,8 @@ lease used after launch. See the [test procedure](test.md#connected-coordinatorp CI checks formatting of tracked Go source while preserving frozen report evidence bytes; see the [coordinator checks](test.md#2-coordinator-go). +Documentation-impact checks also cover the contact-export and legacy-cohort +store owners; see the [soft-delete reference](../reference/soft-delete.md#documentation-coverage). ```bash make coordinator-build # cd coordinator && go build ./cmd/coordinator diff --git a/docs/developer/test.md b/docs/developer/test.md index 14f8ccb2a6..5d4e946d1c 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -99,10 +99,15 @@ supply every unrelated canonical document to ensure ownership or API-contract updates cannot satisfy another domain's requirement, then verify each permitted domain document satisfies it. Go test files remain excluded from these rules. The soft-delete rule separately requires `docs/reference/soft-delete.md` for -the current live-row readers and writers; sqlc sources still require their +the current live-row readers and writers, including small-model contact exports +and initial legacy MDM cohort qualification; the cohort owners also retain their +trust-documentation requirement. sqlc sources still require their canonical generation/type docs too. New reader/writer paths must extend the rule. The tests cover both backends, generated queries, unrelated history files, test exclusions and the maintainer override. +`coordinator/tests/store/contracts/soft_delete_domain_reads_test.go` exercises +contact filtering before pagination and cohort evidence filtering in memory and +isolated PostgreSQL, including repeated reads of a frozen cohort. Shared fixtures in `coordinator/tests/protocol/testdata/` retain the protocol documentation requirement because they define cross-language wire examples. diff --git a/docs/provider/attestation.md b/docs/provider/attestation.md index 5af059a043..027221cf50 100644 --- a/docs/provider/attestation.md +++ b/docs/provider/attestation.md @@ -1,6 +1,6 @@ # Reaching and keeping `hardware` trust -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 How to check provider verification and retain legacy `hardware` trust where eligible. New providers require macOS 27 or later and current qualified App @@ -86,7 +86,8 @@ Under the upcoming [frozen legacy policy](../architecture/security/enrollment.md devices whose stored account, SE key and serial enter the durable cohort continue through legacy verification. The first upgraded production coordinator startup drains eligible historical inventory after revocation replay before -freezing; restart, a new account, a new device or a new +freezing. Soft-deleted accounts and provider records cannot qualify for that +initial snapshot; see the [cohort qualification rules](../architecture/security/enrollment.md#frozen-legacy-authorization-cohort). A restart, a new account, a new device or a new account association does not reopen eligibility. Reenrollment requires the existing key under its frozen account and the [authenticated signed enrollment request](../reference/api-contracts.md#legacy-mdm-enrollment-proof). Preserve your diff --git a/docs/reference/soft-delete.md b/docs/reference/soft-delete.md index 7a649421e6..88df2acc4e 100644 --- a/docs/reference/soft-delete.md +++ b/docs/reference/soft-delete.md @@ -30,8 +30,10 @@ in SQL. `MemoryStore` keeps the field on its records and checks it. Postgres filters `deleted_at IS NULL`; MemoryStore skips a record whose `DeletedAt` is not `nil`. `coordinator/tests/store/postgres/soft_delete_reads_test.go` -covers each PostgresStore read. No MemoryStore entry point sets `DeletedAt` -yet, so the MemoryStore checks have no test until the erasure writer exists. +covers the core PostgresStore reads. +`coordinator/tests/store/contracts/soft_delete_domain_reads_test.go` covers +contact pagination and initial legacy MDM cohort qualification on both backends, +using tombstones in the isolated fixtures. ### `users` @@ -42,6 +44,8 @@ yet, so the MemoryStore checks have no test until the erasure writer exists. | `GetUserByStripeAccount` | `coordinator/store/postgres/users.go` | `coordinator/store/memory/users.go` | not found | | `GetUserByEmail` | `coordinator/store/postgres/users.go` | `coordinator/store/memory/users.go` | not found | | `ClaimModelTokenPromotion` | `coordinator/store/postgres/model_token_promotions.go` | `coordinator/store/memory/model_token_promotions.go` | `ErrPromotionIneligible` | +| `ListSmallModelsInterest` | `coordinator/store/postgres/small_models_interest.go` | `coordinator/store/memory/small_models_interest.go` | omitted before pagination; the admin contact export excludes the email | +| `FreezeLegacyMDMCohort` (initial qualification) | `coordinator/store/postgres/legacy_mdm_cohort.go` | `coordinator/store/memory/legacy_mdm_cohort.go` | cannot qualify for the initial frozen cohort | | `CreateUser` (Privy ID check) | `idx_users_privy_live` | `coordinator/store/memory/users.go` | The Privy ID is free; a new live user may take it | ### `api_keys` @@ -75,8 +79,13 @@ methods are in `coordinator/store/memory/apikey.go`. | `GetProviderForRestore` | `coordinator/store/postgres/provider_restore.go` | `coordinator/store/memory/provider_restore.go` | not a restore candidate; an older live row can be | | `ResolveMachineContinuity` | `coordinator/store/postgres/machine_continuity.go` | `coordinator/store/memory/machine_continuity.go` | not continuity history | | `UsageFlowBuckets` (provider location) | `coordinator/store/postgres/analytics_flows.go` (`usageFlowBucketsSQL`) | `coordinator/store/memory/analytics.go` | its location is not used | +| `FreezeLegacyMDMCohort` (initial qualification) | `coordinator/store/postgres/legacy_mdm_cohort.go` | `coordinator/store/memory/legacy_mdm_cohort.go` | cannot qualify for the initial frozen cohort | | `BackfillMachineInventory` | `coordinator/store/postgres/machine_inventory_backfill.go` | — (Postgres only) | not backfilled | +`FreezeLegacyMDMCohort` applies these filters only when it first constructs the +cohort. Later calls read the persisted snapshot without recomputing membership; +see [frozen legacy authorization](../architecture/security/enrollment.md#frozen-legacy-authorization-cohort). + ## Paths that do not filter Writes and hard deletes act on a soft-deleted row as on any other row. diff --git a/docs/threat-model.yaml b/docs/threat-model.yaml index 1c94373285..099a242629 100644 --- a/docs/threat-model.yaml +++ b/docs/threat-model.yaml @@ -1,5 +1,6 @@ version: "1.1" created: "2026-05-14" +# Initial legacy MDM cohort soft-delete filtering verified 2026-10-06. # Upcoming frozen legacy MDM policy documented 2026-10-04, not a production # activation claim or a revalidation of the older threat entries. Cohort gates # restrict coordinator authorization; generic profiles remain directly copyable. @@ -984,7 +985,9 @@ trust_boundaries: - "Upcoming legacy MDM policy freezes authenticated account/SE-key/serial membership for already successfully MDM-verified devices on first upgraded startup after revocation replay. FreezeLegacyMDMCohort persists the cutoff - and cohort across restarts, including an empty cohort. New accounts, + and cohort across restarts, including an empty cohort. Initial qualification + excludes soft-deleted users and provider records; later reads preserve + the frozen snapshot. See docs/architecture/security/enrollment.md. New accounts, devices, keys and associations are excluded. Lost or hashless historical evidence may be conservatively omitted; retained hardware snapshots plus authenticated inventory may supplement it. Membership never replaces diff --git a/scripts/docs-impact-rules.json b/scripts/docs-impact-rules.json index 9feb9e05aa..126e053b91 100644 --- a/scripts/docs-impact-rules.json +++ b/scripts/docs-impact-rules.json @@ -247,7 +247,11 @@ "coordinator/store/postgres/model_token_promotions.go", "coordinator/store/postgres/analytics_flows.go", "coordinator/store/postgres/queries/api_keys.sql", - "coordinator/store/postgres/storedb/api_keys.sql.go" + "coordinator/store/postgres/storedb/api_keys.sql.go", + "coordinator/store/memory/small_models_interest.go", + "coordinator/store/memory/legacy_mdm_cohort.go", + "coordinator/store/postgres/small_models_interest.go", + "coordinator/store/postgres/legacy_mdm_cohort.go" ], "docs_any_of": [ "docs/reference/soft-delete.md" @@ -360,7 +364,9 @@ "coordinator/internal/appattest/**", "coordinator/mdm/**", "coordinator/internal/mdm/**", - "coordinator/apns/**" + "coordinator/apns/**", + "coordinator/store/memory/legacy_mdm_cohort.go", + "coordinator/store/postgres/legacy_mdm_cohort.go" ], "docs_any_of": [ "docs/architecture/security/attestation.md", diff --git a/scripts/test-docs-impact-check.py b/scripts/test-docs-impact-check.py index 17599bccb0..3ce1ed0db6 100644 --- a/scripts/test-docs-impact-check.py +++ b/scripts/test-docs-impact-check.py @@ -83,6 +83,10 @@ def test_sqlc_changes_require_canonical_docs(self) -> None: def test_soft_delete_reads_and_writes_require_canonical_docs(self) -> None: sources = ( + "coordinator/store/memory/small_models_interest.go", + "coordinator/store/memory/legacy_mdm_cohort.go", + "coordinator/store/postgres/small_models_interest.go", + "coordinator/store/postgres/legacy_mdm_cohort.go", "coordinator/store/memory/users.go", "coordinator/store/postgres/users.go", "coordinator/store/memory/device_auth.go", @@ -96,7 +100,8 @@ def test_soft_delete_reads_and_writes_require_canonical_docs(self) -> None: ) for source in sources: with self.subTest(source=source): - related = ("docs/reference/sqlc-type-mapping.md", "docs/architecture/storage.md") + related = ("docs/reference/sqlc-type-mapping.md", "docs/architecture/storage.md", + "docs/architecture/security/enrollment.md") missing = self.run_check(source, *related) self.assertEqual(missing.returncode, 1, missing.stdout + missing.stderr) self.assertIn("soft-delete reads and writes source changed", missing.stderr) @@ -327,6 +332,10 @@ def test_extracted_components_retain_behavior_and_ownership_gates(self) -> None: def test_relocated_domain_owners_require_behavior_documentation(self) -> None: cases = { + "trust and attestation": ( + "coordinator/store/memory/legacy_mdm_cohort.go", + "coordinator/store/postgres/legacy_mdm_cohort.go", + ), "HTTP and API contracts": ( "coordinator/api/releases/artifact_metadata.go", ), From e4b2fdfc2462c7441f04d3ac59dd9782c6df90b8 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Tue, 6 Oct 2026 14:08:45 -0700 Subject: [PATCH 18/20] test: format verification priorities for Go 1.26 --- .../tests/api/provider/trust/upgrade_storm_regression_test.go | 4 ++-- .../tests/api/provider/trust/verification/priority_test.go | 2 +- .../tests/api/provider/trust/verification_integration_test.go | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/coordinator/tests/api/provider/trust/upgrade_storm_regression_test.go b/coordinator/tests/api/provider/trust/upgrade_storm_regression_test.go index 350daebe39..c21c2ff82b 100644 --- a/coordinator/tests/api/provider/trust/upgrade_storm_regression_test.go +++ b/coordinator/tests/api/provider/trust/upgrade_storm_regression_test.go @@ -571,7 +571,7 @@ func TestCoordinatorRestartContinuityReconnectAvoidsMDMStorm(t *testing.T) { } priority := srv.VerificationSubmitPriority(fp.seKey, fp.serial) if priority != store.VerificationPriorityRefresh { - errCh <- fmt.Errorf("%s: submit priority = %q, want refresh (continuity candidate)", fp.id, priority) + errCh <- fmt.Errorf("%s: submit priority = %v, want refresh (continuity candidate)", fp.id, priority) return } if gen := sch.Submit( @@ -722,7 +722,7 @@ func TestCoordinatorRestartBeyondAllowanceFallsBackToSchedulerWave(t *testing.T) fp.id, job.State, job.LastOutcome) } if job.Priority != store.VerificationPriorityFirstOrExpired { - t.Fatalf("%s: scheduler priority = %q, want first/expired", fp.id, job.Priority) + t.Fatalf("%s: scheduler priority = %v, want first/expired", fp.id, job.Priority) } if due := job.NextAttemptAt.Sub(reconnectAt); due > mdmFirstVerifySpreadMax { t.Fatalf("%s: live verification due %s out, must be within %s of the declined fast-skip", diff --git a/coordinator/tests/api/provider/trust/verification/priority_test.go b/coordinator/tests/api/provider/trust/verification/priority_test.go index 48338db8df..236fdc5f91 100644 --- a/coordinator/tests/api/provider/trust/verification/priority_test.go +++ b/coordinator/tests/api/provider/trust/verification/priority_test.go @@ -114,7 +114,7 @@ func TestFailedFastSkipPromotesRefreshToImmediateDue(t *testing.T) { t.Fatalf("promoted job not persisted: %+v, %v", rec, err) } if rec.Priority != store.VerificationPriorityFirstOrExpired { - t.Fatalf("priority = %q after failed fast-skip, want promoted first/expired", rec.Priority) + t.Fatalf("priority = %v after failed fast-skip, want promoted first/expired", rec.Priority) } if due := rec.NextAttemptAt.Sub(now); due > mdmFirstVerifySpreadMax { t.Fatalf("failed fast-skip settle due %s out, must be within %s", due, mdmFirstVerifySpreadMax) diff --git a/coordinator/tests/api/provider/trust/verification_integration_test.go b/coordinator/tests/api/provider/trust/verification_integration_test.go index 02a625ae78..e18677d73a 100644 --- a/coordinator/tests/api/provider/trust/verification_integration_test.go +++ b/coordinator/tests/api/provider/trust/verification_integration_test.go @@ -41,7 +41,7 @@ func TestContinuityMissPromotesRefreshSubmitToImmediateDue(t *testing.T) { cur.Add(-20*time.Minute), cur.Add(-60*time.Second))) priority := srv.VerificationSubmitPriority("se-cont-miss", "serial-cont-miss") if priority != store.VerificationPriorityRefresh { - t.Fatalf("submit priority = %q, want refresh for a continuity candidate", priority) + t.Fatalf("submit priority = %v, want refresh for a continuity candidate", priority) } sch.Submit(context.Background(), p.ID, p, priority) @@ -62,7 +62,7 @@ func TestContinuityMissPromotesRefreshSubmitToImmediateDue(t *testing.T) { t.Fatalf("promoted job not persisted: %+v, %v", rec, err) } if rec.Priority != store.VerificationPriorityFirstOrExpired { - t.Fatalf("priority = %q after continuity miss, want promoted first/expired", rec.Priority) + t.Fatalf("priority = %v after continuity miss, want promoted first/expired", rec.Priority) } if due := rec.NextAttemptAt.Sub(now); due > mdmFirstVerifySpreadMax { t.Fatalf("continuity-miss settle due %s out, must be within %s", due, mdmFirstVerifySpreadMax) From e42e5d5c9137c6097a836d5d78418ff775292268 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Tue, 6 Oct 2026 14:19:41 -0700 Subject: [PATCH 19/20] feat(dev): add safe post-squash stack restacking --- AGENTS.md | 19 +++ CHANGELOG.md | 4 + docs/README.md | 1 + docs/developer/build.md | 5 + docs/developer/pull-requests.md | 88 ++++++++++++ docs/developer/test.md | 8 ++ scripts/restack-after-squash.py | 167 +++++++++++++++++++++ scripts/test-restack-after-squash.py | 208 +++++++++++++++++++++++++++ 8 files changed, 500 insertions(+) create mode 100644 docs/developer/pull-requests.md create mode 100644 scripts/restack-after-squash.py create mode 100644 scripts/test-restack-after-squash.py diff --git a/AGENTS.md b/AGENTS.md index 4cd149f22f..c196f3ec4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -381,6 +381,25 @@ branch's signed-commit rule does not validate commits hosted on a contributor fork, so the `Commit Signatures` contribution-policy check enforces this before merge. +**Stacked PRs** + +Use linear PR bases: the first targets `master`, each child targets its immediate +parent. Before approval, merge each refreshed parent into its child with a signed +commit and a non-force push, working from the bottom of the stack upward. +`master` is squash-only: a squash loses the original commit ancestry, so a +pre-merge parent update never guarantees conflict-free merges after the squash. +After each actual squash, run +`python3 scripts/restack-after-squash.py PARENT CHILD [DESCENDANTS...] --check`, +then `--push` (optionally `--retarget`), following +[the stacking guide](docs/developer/pull-requests.md). The script only adds +signed same-tree ancestry bridges; content differences require manual +reconciliation. Never force-push or change merge policy to repair a stack. +Use `--skip-hook` only with explicit human approval. Keep affected branches +unchanged during the operation; non-force pushes are not compare-and-swap +protection against branch deletion or rewind. Updates can dismiss approvals; +recheck CI, Verified signatures, bases and mergeability before requesting approval +again. This procedure does not authorize merging PRs. + **Every PR MUST include a before-and-after diagram (Mermaid) in its description** that details what changed — covering BOTH: - **Behavior**: the request/response flow, states, and outcomes a user or caller observes (e.g. dispatch → retry → 429/503/200). diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cd050329a..5d30356b04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased - pull-request stack tooling + +- Add a checked, signed same-tree ancestry repair for dependent PRs after each parent squash, with atomic non-force pushes and optional retargeting. Document linear bases, manual reconciliation on content differences, and renewed signature, CI and approval checks; the tool does not merge PRs or automate conflict resolution. + ## Unreleased — personal data in coordinator logs - Stop writing email addresses, IP addresses, device serial numbers and MDA UDIDs to coordinator process logs, which are forwarded to Datadog. Log lines name accounts by `account_id` (`user_id` in the access log) and providers by `provider_id`; the access log no longer has a `remote` field and the MDM webhook debug line no longer includes a body preview. Logs written before this change are not affected. diff --git a/docs/README.md b/docs/README.md index 5e3ba47acf..fb5b69591f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -108,6 +108,7 @@ - [`developer/navigation.md`](developer/navigation.md): find implementation and tests, choose descriptive filenames, and check path dependencies when moving files. - [`developer/build.md`](developer/build.md): build the coordinator, sidecar, provider, and UIs; toolchain pins. - [`developer/test.md`](developer/test.md): every test suite, what CI runs, how to run the e2e suite. +- [`developer/pull-requests.md`](developer/pull-requests.md): linear PR stacks, signed parent updates, and ancestry repair after each squash. - [`developer/database-migrations.md`](developer/database-migrations.md): choose the migration kind, add a numbered goose migration, change a column while preserving rollback compatibility, regenerate the checked-in schema. - [`developer/sqlc.md`](developer/sqlc.md): add a store query with sqlc, convert a hand-written store domain, `make sqlc-generate` and `make sqlc-check`. - [`developer/threat-model-review.md`](developer/threat-model-review.md): configure full PR text scans against the threat model and non-blocking author feedback. diff --git a/docs/developer/build.md b/docs/developer/build.md index c4a24cee8e..8fe01ef8c2 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -2,6 +2,11 @@ > Last updated: 2026-10-06 +Stack maintenance uses Python 3, Git, authenticated `gh`, and a configured commit +signer; it requires no product build. Follow [Maintain a pull-request stack](pull-requests.md) +for `scripts/restack-after-squash.py` checks, signed ancestry updates, and +post-push verification. Branch updates still require the affected CI gates. + The provider test runner isolates daemon-state and loaded-model snapshots in a temporary directory for each run. Unit-test providers must not overwrite the operator’s live status or recovery evidence (`scripts/run-provider-tests.sh`). diff --git a/docs/developer/pull-requests.md b/docs/developer/pull-requests.md new file mode 100644 index 0000000000..600fa9c148 --- /dev/null +++ b/docs/developer/pull-requests.md @@ -0,0 +1,88 @@ +# Maintain a pull-request stack + +> Last updated: 2026-10-06 + +How to keep dependent PRs reviewable before approval and restore their ancestry +after a parent is squash-merged. This procedure updates branches, not product +content or repository merge policy, and does not authorize merging PRs. + +## Prerequisites + +- Use linear bases: the first PR targets `master`; each child targets its + immediate parent, not `master` or a sibling. +- Have Python 3, Git, authenticated `gh`, repository push access, and a working + signing identity whose commits verify locally and show as Verified on GitHub. +- Use a non-shallow clone with one identical `origin` fetch and push URL for the + PR repository. All PRs must be in that repository; fork PRs are not supported. +- Coordinate with branch owners: no affected branch may change during the + operation, including deletion, rewind, or pushes from another worktree. +- Keep the parent branch and its original head available until restacking is + verified. Do not delete it immediately after the squash. + +## Steps + +1. **Refresh before approval.** Fetch current refs and merge each refreshed + parent into its child, bottom-up, using signed merge commits and non-force + pushes. Resolve content conflicts and run affected tests. Do this before + requesting approval: new commits or base changes can dismiss stale approvals. +2. **Wait for the actual squash.** `master` is squash-only. The squash represents + the parent's content with a new commit identity, not the parent's original + ancestry. Even a clean pre-merge refresh cannot guarantee no later conflicts. +3. **Check the remaining stack.** From the repository root, pass PR numbers in + immediate-parent order to `scripts/restack-after-squash.py`: + + ```bash + python3 scripts/restack-after-squash.py PARENT CHILD DESCENDANT --check + ``` + + Omit `DESCENDANT` when only one child remains; append further descendants in + order. `--check` is the default. Use `--repo OWNER/REPO` when needed to select + the repository explicitly. The script uses the merged parent's recorded base, + not a hardcoded `master` target. Check mode does not test signing or push + permissions, create commits, or change branches or PR bases. +4. **Review, then publish.** If the check succeeds and branch updates are + authorized, repeat with `--push`. Add `--retarget` to update the child's PR + base to the merged parent's base; remaining descendants keep their linear + relationship: + + ```bash + python3 scripts/restack-after-squash.py PARENT CHILD DESCENDANT --push --retarget + ``` + + Hooks remain enabled. `--skip-hook` requires explicit human authorization + for that operation; it is not a workaround for a failed check. +5. **Repeat after each squash.** When the next parent is actually squash-merged, + run check and push again for that parent and its remaining descendants. + Do not assume the previous ancestry repair covers future squashes. + +## Verify + +The script checks the actual squash tree against the original parent's head, +the descendant ancestry, linear PR bases, and current refs before constructing +signed, same-tree ancestry bridges. It publishes with an atomic non-force push; +it refuses content differences rather than choosing a conflict resolution. +These bridges change ancestry without changing each child's content. + +After every update, inspect the remote heads and PR bases, verify every new +commit displays as Verified, wait for required CI on the new heads, and recheck +mergeability and approval state. Retargeting is a separate GitHub operation, +not part of Git's atomic push; verify it even if the push succeeded. Ask for +fresh approval when an earlier approval was dismissed. + +## Troubleshooting + +- **Squash tree or ancestry differs:** stop and reconcile content manually with + the branch owners, then revalidate. Do not manufacture a same-tree bridge to + conceal a real change, force-push, or relax repository policy. +- **Refs changed or a push failed:** inspect all remote heads and rerun the + check before retrying. Atomic non-force push is not an atomic compare-and-swap + against deletion or rewind; the requirement to keep branches unchanged is + essential even when a push could otherwise fast-forward. +- **Signing, hooks, CI, or retargeting failed:** repair the failed gate and verify + remote state. A clean content tree alone is not evidence that the PR is ready. + +## Related + +- [Contribution rules](../../CONTRIBUTING.md) +- [Build](build.md) +- [Restacking tests](test.md#pull-request-restacking) diff --git a/docs/developer/test.md b/docs/developer/test.md index 3edd925c28..406f336f0c 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -2,6 +2,14 @@ > Last updated: 2026-10-06 +## Pull-request restacking + +Run `python3 scripts/test-restack-after-squash.py` for the regression suite of +`scripts/restack-after-squash.py`. Follow the [stacking guide](pull-requests.md) +for the live `--check` before an authorized `--push`; local tests do not replace +checking the actual squash, current remote refs, Verified signatures, CI, +mergeability, and approvals after an update. + ## Nightly Linear package Run from the repository root: diff --git a/scripts/restack-after-squash.py b/scripts/restack-after-squash.py new file mode 100644 index 0000000000..c29fa2c99b --- /dev/null +++ b/scripts/restack-after-squash.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Repair a linear PR stack after a squash without rewriting branch history. + +Default: verify only. Requires git, authenticated gh, and (for --push) working +commit signing and signature verification. Run in the clone with origin pointing +to the PR repository. Fork PRs are not supported. Never merges PRs or checks out +branches. Objects are fetched into temporary storage, not local refs/worktrees. + +Keep stack branches and PR metadata unchanged during operation. Nonforce pushes +reject concurrent forward/divergent updates not contained in the proposed tip, +but cannot atomically guard deletion/rewind between tip read and push. GitHub +has no atomic base compare-and-swap: --retarget's fresh checks are best-effort. +""" + +import argparse +import json +import os +from pathlib import Path +import re +import shlex +import subprocess +import sys +import tempfile + + +def run(*args, env=None): + result = subprocess.run(args, env=env, text=True, capture_output=True) + if result.returncode: + raise RuntimeError(f"{shlex.join(args)} failed:\n{result.stderr.strip()}") + return result.stdout.strip() + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("prs", nargs="+", type=int, metavar="PR", help="merged parent, open child, then descendants in order") + parser.add_argument("--repo", help="OWNER/REPO; otherwise discover via gh") + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--check", action="store_true", help="verify only (default)") + mode.add_argument("--push", action="store_true", help="create signed commits and atomically push nonforce") + parser.add_argument("--retarget", action="store_true", help="with --push, retarget only the direct child after fresh checks") + parser.add_argument("--skip-hook", action="store_true", help="explicitly disable push hooks for this invocation only") + args = parser.parse_args(argv) + require(len(args.prs) >= 2 and len(set(args.prs)) == len(args.prs) and min(args.prs) > 0, + "Supply a parent and at least one child, with distinct positive PR numbers.") + require(run("git", "rev-parse", "--is-shallow-repository") == "false", "A non-shallow clone is required.") + require(not os.environ.get("GIT_OBJECT_DIRECTORY") and not os.environ.get("GIT_ALTERNATE_OBJECT_DIRECTORIES"), + "Unset custom Git object directory variables first.") + origin = run("git", "remote", "get-url", "origin") + require(run("git", "remote", "get-url", "--push", "--all", "origin") == origin, + "Origin must have exactly one identical fetch and push URL.") + repo = args.repo or json.loads(run("gh", "repo", "view", "--json", "nameWithOwner"))["nameWithOwner"] + origin_repo = json.loads(run("gh", "repo", "view", origin, "--json", "nameWithOwner"))["nameWithOwner"] + require(repo.lower() == origin_repo.lower(), "Origin and requested GitHub repository differ.") + + def pr(number): + return json.loads(run("gh", "pr", "view", str(number), "--repo", repo, "--json", + "state,baseRefName,headRefName,headRefOid,mergeCommit,isCrossRepository")) + + def tip(ref): + rows = run("git", "ls-remote", "--refs", origin, ref).splitlines() + require(len(rows) == 1, f"Missing or ambiguous remote ref: {ref}") + oid, name = rows[0].split() + require(name == ref and re.fullmatch(r"[0-9a-f]{40}", oid), f"Invalid remote ref: {ref}") + return oid + + parent, *children = [pr(number) for number in args.prs] + require(parent["state"] == "MERGED", "Parent PR must be MERGED.") + require(not any(p["isCrossRepository"] for p in [parent, *children]), "Fork PRs are not supported.") + original = parent["headRefOid"] + squash = (parent["mergeCommit"] or {}).get("oid", "") + require(all(re.fullmatch(r"[0-9a-f]{40}", oid) for oid in [original, squash]), "Invalid parent commit OIDs.") + base = parent["baseRefName"] + base_ref = f"refs/heads/{base}" + run("git", "check-ref-format", base_ref) + snapshots = {base_ref: tip(base_ref)} + previous = parent + for number, child in zip(args.prs[1:], children): + require(child["state"] == "OPEN", f"PR #{number} must be OPEN.") + require(child["baseRefName"] == previous["headRefName"], f"PR #{number} is not based on the preceding PR branch.") + ref = f"refs/heads/{child['headRefName']}" + run("git", "check-ref-format", ref) + require(ref not in snapshots, "Stack branches must be distinct from each other and the target base.") + snapshots[ref] = tip(ref) + require(snapshots[ref] == child["headRefOid"], f"PR #{number} metadata and remote head differ; retry.") + previous = child + + def unchanged(): + for ref, oid in snapshots.items(): + require(tip(ref) == oid, f"Remote {ref} changed; nothing pushed, rerun verification.") + + with tempfile.TemporaryDirectory(prefix="restack-after-squash-") as temporary: + objects = Path(temporary) / "objects" + objects.mkdir() + env = dict(os.environ, GIT_OBJECT_DIRECTORY=str(objects), + GIT_ALTERNATE_OBJECT_DIRECTORIES=run("git", "rev-parse", "--path-format=absolute", "--git-path", "objects"), + GIT_NO_REPLACE_OBJECTS="1") + + def git(*command): + return run("git", *command, env=env) + + def ancestor(older, newer): + result = subprocess.run(["git", "merge-base", "--is-ancestor", older, newer], env=env, capture_output=True, text=True) + require(result.returncode in (0, 1), result.stderr) + return result.returncode == 0 + + git("-c", "fetch.writeCommitGraph=false", "fetch", "--no-auto-maintenance", "--no-tags", + "--no-write-fetch-head", "--recurse-submodules=no", "--refmap=", origin, *snapshots, original, squash) + unchanged() + require(ancestor(squash, snapshots[base_ref]), "Parent squash is not in its target base branch.") + require(len(git("show", "-s", "--format=%P", squash).split()) == 1, "Parent merge commit is not a single-parent squash.") + require(git("rev-parse", f"{original}^{{tree}}") == git("rev-parse", f"{squash}^{{tree}}"), + "Squash tree differs from original parent head; content-aware integration is required.") + previous = original + for number, child in zip(args.prs[1:], children): + head = child["headRefOid"] + require(ancestor(previous, head), f"PR #{number} does not contain the preceding original head.") + require(not ancestor(squash, head), f"PR #{number} already contains the squash; inspect the stack manually.") + print(f"PR #{number}: preserve tree {git('rev-parse', head + '^{tree}')} and add preceding repaired ancestry") + previous = head + + edit = ["gh", "pr", "edit", str(args.prs[1]), "--repo", repo, "--base", base] + print("After a successful push, retarget only the direct child:", shlex.join(edit)) + print("Keep stack branches/PR metadata unchanged: nonforce is not a deletion/rewind guard; GitHub has no atomic base CAS.") + print("Push hooks:", "explicitly disabled" if args.skip_hook else "enabled") + if not args.push: + print("CHECK ONLY: no commits, pushes, retargeting or local ref/worktree changes. Signing and push permissions untested.") + return + + updates = [] + previous = squash + for number, child in zip(args.prs[1:], children): + head = child["headRefOid"] + tree = git("rev-parse", head + "^{tree}") + commit = git("commit-tree", "-S", tree, "-p", head, "-p", previous, "-m", + f"Restack PR #{number} after squashed PR #{args.prs[0]} (tree unchanged)") + git("verify-commit", commit) + require(git("rev-parse", commit + "^{tree}") == tree and + git("show", "-s", "--format=%P", commit) == f"{head} {previous}", "Unexpected bridge tree or parents.") + updates.append((f"refs/heads/{child['headRefName']}", commit)) + previous = commit + unchanged() + config = ["-c", "core.hooksPath=/dev/null"] if args.skip_hook else [] + git(*config, "push", "--atomic", "--no-follow-tags", "--recurse-submodules=no", origin, + *(f"{oid}:{ref}" for ref, oid in updates)) + for ref, oid in updates: + require(tip(ref) == oid, f"Push completed but {ref} moved again; inspect before proceeding.") + print("Signed ancestry repair pushed; no PR was merged.") + if args.retarget: + fresh = pr(args.prs[1]) + require(fresh["state"] == "OPEN" and fresh["headRefOid"] == updates[0][1] and + fresh["baseRefName"] == children[0]["baseRefName"], + "Repair pushed, but child state/head/base changed; refusing retarget. Inspect manually.") + run(*edit) + print("Direct child retargeted; descendant bases unchanged.") + + +if __name__ == "__main__": + try: + main() + except (RuntimeError, OSError, ValueError, KeyError) as error: + print(f"ERROR: {error}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/test-restack-after-squash.py b/scripts/test-restack-after-squash.py new file mode 100644 index 0000000000..8cb62af3ce --- /dev/null +++ b/scripts/test-restack-after-squash.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Local Git integration tests; GitHub and signing are the only mocked boundaries.""" + +import contextlib +import importlib.util +import io +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + + +spec = importlib.util.spec_from_file_location("restack", Path(__file__).with_name("restack-after-squash.py")) +restack = importlib.util.module_from_spec(spec) +spec.loader.exec_module(restack) +REAL_RUN = restack.run + + +class RestackTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="test-restack-") + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.old_cwd = os.getcwd() + self.addCleanup(os.chdir, self.old_cwd) + self.env_patch = patch.dict(os.environ, { + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_AUTHOR_NAME": "Fixture", "GIT_AUTHOR_EMAIL": "fixture@example.test", + "GIT_COMMITTER_NAME": "Fixture", "GIT_COMMITTER_EMAIL": "fixture@example.test", + }) + self.env_patch.start() + self.addCleanup(self.env_patch.stop) + self.remote = self.root / "remote.git" + REAL_RUN("git", "init", "--bare", str(self.remote)) + self.work = self.root / "work" + REAL_RUN("git", "init", "-b", "main", str(self.work)) + os.chdir(self.work) + self.git("remote", "add", "origin", str(self.remote)) + self.commit("base") + self.git("checkout", "-b", "parent") + parent = self.commit("parent") + self.git("checkout", "-b", "child") + child = self.commit("child") + self.git("checkout", "-b", "descendant") + descendant = self.commit("descendant") + self.git("checkout", "main") + self.git("merge", "--squash", "parent") + self.git("commit", "-m", "squash parent") + self.squash = self.git("rev-parse", "HEAD") + self.git("push", "origin", "main", "parent", "child", "descendant") + self.prs = { + 1: self.metadata("MERGED", "main", "parent", parent, self.squash), + 2: self.metadata("OPEN", "parent", "child", child), + 3: self.metadata("OPEN", "child", "descendant", descendant), + } + self.calls = [] + self.mutate_before_push = None + self.mutate_before_edit = None + self.views = {} + + def git(self, *args): + return REAL_RUN("git", *args) + + def commit(self, content): + Path("content").write_text(content + "\n") + self.git("add", "content") + self.git("commit", "-m", content) + return self.git("rev-parse", "HEAD") + + @staticmethod + def metadata(state, base, branch, head, squash=None): + return dict(state=state, baseRefName=base, headRefName=branch, headRefOid=head, + mergeCommit={"oid": squash} if squash else None, isCrossRepository=False) + + def boundary(self, *args, env=None): + self.calls.append(args) + if args[0] == "gh": + if args[1:3] == ("repo", "view"): + return json.dumps({"nameWithOwner": "fixture/repo"}) + number = int(args[3]) + if args[2] == "edit": + self.prs[number]["baseRefName"] = args[-1] + return "" + self.views[number] = self.views.get(number, 0) + 1 + if self.views[number] > 1 and self.mutate_before_edit: + self.mutate_before_edit(self.prs[number]) + return json.dumps(self.prs[number]) + if args[1] == "commit-tree": + self.assertIn("-S", args) + return REAL_RUN(*(a for a in args if a != "-S"), env=env) + if args[1] == "verify-commit": + return "" + if "push" in args: + if self.mutate_before_push: + self.mutate_before_push() + result = REAL_RUN(*args, env=env) + for record in self.prs.values(): + record["headRefOid"] = self.git("--git-dir", str(self.remote), "rev-parse", record["headRefName"]) + return result + return REAL_RUN(*args, env=env) + + def invoke(self, *args): + with patch.object(restack, "run", side_effect=self.boundary), contextlib.redirect_stdout(io.StringIO()): + restack.main(list(args)) + + def remote_head(self, branch): + return self.git("--git-dir", str(self.remote), "rev-parse", branch) + + def test_default_check_leaves_refs_worktree_and_remote_unchanged(self): + before = self.git("show-ref") + remote = self.git("ls-remote", "origin") + self.invoke("1", "2", "3") + self.assertEqual(before, self.git("show-ref")) + self.assertEqual(remote, self.git("ls-remote", "origin")) + self.assertEqual("", self.git("status", "--porcelain")) + self.assertFalse(any("commit-tree" in call or "push" in call for call in self.calls)) + + def test_sequential_squashes_preserve_content_and_merge_without_conflicts(self): + original_child = self.prs[2]["headRefOid"] + original_desc = self.prs[3]["headRefOid"] + self.invoke("--push", "--retarget", "1", "2", "3") + self.git("fetch", "origin") + repaired_child = self.remote_head("child") + repaired_desc = self.remote_head("descendant") + for old, new in [(original_child, repaired_child), (original_desc, repaired_desc)]: + self.assertEqual(self.git("rev-parse", old + "^{tree}"), self.git("rev-parse", new + "^{tree}")) + self.assertEqual(f"{original_child} {self.squash}", self.git("show", "-s", "--format=%P", repaired_child)) + self.assertEqual(f"{original_desc} {repaired_child}", self.git("show", "-s", "--format=%P", repaired_desc)) + self.assertEqual("main", self.prs[2]["baseRefName"]) + self.assertEqual("child", self.prs[3]["baseRefName"]) + self.git("merge", "--squash", repaired_child) + self.git("commit", "-m", "squash child") + second_squash = self.git("rev-parse", "HEAD") + self.git("push", "origin", "main") + self.prs[2].update(state="MERGED", mergeCommit={"oid": second_squash}) + self.invoke("--push", "2", "3") + self.git("fetch", "origin") + final_desc = self.remote_head("descendant") + self.git("merge", "--squash", final_desc) + self.assertEqual(self.git("write-tree"), self.git("rev-parse", original_desc + "^{tree}")) + pushes = [call for call in self.calls if "push" in call] + self.assertTrue(all("--atomic" in call and not any("force" in arg for arg in call) for call in pushes)) + self.assertTrue(all("core.hooksPath=/dev/null" not in call for call in pushes)) + + def test_rejects_unmerged_parent_wrong_base_missing_ancestry_and_tree_mismatch(self): + cases = [(1, "state", "OPEN", "MERGED"), (2, "baseRefName", "main", "preceding PR"), + (1, "headRefOid", self.prs[3]["headRefOid"], "Squash tree differs")] + for number, key, value, message in cases: + old = self.prs[number][key] + self.prs[number][key] = value + with self.assertRaisesRegex(RuntimeError, message): + self.invoke("--push", "1", "2", "3") + self.prs[number][key] = old + self.git("--git-dir", str(self.remote), "update-ref", "refs/heads/child", self.squash) + self.prs[2]["headRefOid"] = self.squash + with self.assertRaisesRegex(RuntimeError, "preceding original head"): + self.invoke("--push", "1", "2", "3") + + def test_atomic_push_rejects_concurrent_forward_update(self): + old_child = self.remote_head("child") + old_desc = self.remote_head("descendant") + concurrent = self.git("--git-dir", str(self.remote), "commit-tree", self.git("rev-parse", old_desc + "^{tree}"), "-p", old_desc, "-m", "concurrent") + self.mutate_before_push = lambda: self.git("--git-dir", str(self.remote), "update-ref", "refs/heads/descendant", concurrent) + with self.assertRaisesRegex(RuntimeError, "failed"): + self.invoke("--push", "1", "2", "3") + self.assertEqual(old_child, self.remote_head("child")) + self.assertEqual(concurrent, self.remote_head("descendant")) + + def test_retarget_refuses_fresh_metadata_changes(self): + self.mutate_before_edit = lambda record: record.update(baseRefName="unexpected") + with self.assertRaisesRegex(RuntimeError, "refusing retarget"): + self.invoke("--push", "--retarget", "1", "2", "3") + self.assertFalse(any(call[:3] == ("gh", "pr", "edit") for call in self.calls)) + + def test_skip_hook_is_explicit_and_push_local(self): + hook = Path(".git/hooks/pre-push") + hook.write_text("#!/bin/sh\nexit 1\n") + hook.chmod(0o755) + before = self.remote_head("child") + with self.assertRaisesRegex(RuntimeError, "failed"): + self.invoke("--push", "1", "2", "3") + self.assertEqual(before, self.remote_head("child")) + self.calls.clear() + self.invoke("--push", "--skip-hook", "1", "2", "3") + pushes = [call for call in self.calls if "push" in call] + self.assertEqual(1, len(pushes)) + self.assertIn("core.hooksPath=/dev/null", pushes[0]) + self.assertFalse(any(call[:3] == ("gh", "pr", "edit") for call in self.calls)) + + def test_signature_verification_failure_never_pushes(self): + def failed_verifier(*args, env=None): + if args[:2] == ("git", "verify-commit"): + raise RuntimeError("signature verification failed") + return self.boundary(*args, env=env) + + before = self.remote_head("child") + with patch.object(restack, "run", side_effect=failed_verifier), contextlib.redirect_stdout(io.StringIO()): + with self.assertRaisesRegex(RuntimeError, "signature verification failed"): + restack.main(["--push", "1", "2", "3"]) + self.assertEqual(before, self.remote_head("child")) + self.assertFalse(any("push" in call for call in self.calls)) + + +if __name__ == "__main__": + unittest.main() From cd29e84d433d6cd5630ae50f2a615c347d816d26 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Tue, 6 Oct 2026 14:25:32 -0700 Subject: [PATCH 20/20] test: remove unused restacking test import --- scripts/test-restack-after-squash.py | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/test-restack-after-squash.py b/scripts/test-restack-after-squash.py index 8cb62af3ce..21b6a56838 100644 --- a/scripts/test-restack-after-squash.py +++ b/scripts/test-restack-after-squash.py @@ -7,7 +7,6 @@ import json import os from pathlib import Path -import subprocess import tempfile import unittest from unittest.mock import patch