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 75d614b051..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. @@ -18,6 +22,13 @@ - Fail startup without recording the baseline when a required schema statement fails, so a later startup retries missing columns. Preserve current consumer-settlement, legacy MDM cohort, small-model interest and Stripe refund-index schema changes as subsequent versions. - Check in the schema as `coordinator/store/postgres/schema/schema.sql` and test that the migrations build exactly that schema. New schema changes go in a new numbered migration file. +## Unreleased — soft-delete schema + +- 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. +- Suppress stale registry-supplied provider locations in memory-store usage flows when the stored provider record is soft-deleted. + ## 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/apikey_types.go b/coordinator/store/apikey_types.go index cbfc9812c9..ba76d6e4d7 100644 --- a/coordinator/store/apikey_types.go +++ b/coordinator/store/apikey_types.go @@ -48,6 +48,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 diff --git a/coordinator/store/device_auth_types.go b/coordinator/store/device_auth_types.go index d8d3bdd4fe..94750f4220 100644 --- a/coordinator/store/device_auth_types.go +++ b/coordinator/store/device_auth_types.go @@ -28,4 +28,7 @@ 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:"-"` } diff --git a/coordinator/store/memory/analytics.go b/coordinator/store/memory/analytics.go index 911b2fa6e1..69a6cce992 100644 --- a/coordinator/store/memory/analytics.go +++ b/coordinator/store/memory/analytics.go @@ -227,12 +227,16 @@ func (s *MemoryStore) UsageFlowBuckets(since time.Time, providerLocs map[string] pCoordCnt int } - // Resolve provider location: prefer live registry, fall back to stored records. + // Tombstones override registry snapshots captured before deletion. resolveProviderLoc := func(providerID string) *store.ProviderLocation { + rec := s.providerRecords[providerID] + if rec != nil && rec.DeletedAt != nil { + return nil + } if loc, ok := providerLocs[providerID]; ok && loc != nil { return loc } - if rec, ok := s.providerRecords[providerID]; ok { + if rec != nil { return rec.Location } return nil diff --git a/coordinator/store/memory/apikey.go b/coordinator/store/memory/apikey.go index eec87da0f5..bd8b3e3fb1 100644 --- a/coordinator/store/memory/apikey.go +++ b/coordinator/store/memory/apikey.go @@ -63,7 +63,7 @@ func (s *MemoryStore) CreateAPIKey(accountID string, opts store.APIKeyCreate) (s 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 "" @@ -74,7 +74,7 @@ func (s *MemoryStore) AuthenticateKey(rawKey string) (*store.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 { @@ -109,7 +109,7 @@ func (s *MemoryStore) ListAPIKeys(accountID string) ([]store.APIKey, error) { defer s.mu.RUnlock() out := make([]store.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)) @@ -127,7 +127,7 @@ func (s *MemoryStore) GetAPIKeyByID(accountID, id string) (*store.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 @@ -142,7 +142,7 @@ func (s *MemoryStore) UpdateAPIKey(accountID, id string, mutable store.APIKey) ( 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 @@ -192,7 +192,7 @@ func (s *MemoryStore) RotateAPIKey(accountID, id string) (string, *store.APIKey, 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 := &store.APIKey{ diff --git a/coordinator/store/memory/device_auth.go b/coordinator/store/memory/device_auth.go index 7853449b30..40ab9d19c1 100644 --- a/coordinator/store/memory/device_auth.go +++ b/coordinator/store/memory/device_auth.go @@ -97,7 +97,7 @@ func (s *MemoryStore) GetProviderToken(token string) (*store.ProviderToken, erro h := store.HashKey(token) pt, ok := s.providerTokens[h] - if !ok || !pt.Active { + if !ok || !pt.Active || pt.DeletedAt != nil { return nil, store.ErrProviderTokenInvalid } copy := *pt 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/machine_continuity.go b/coordinator/store/memory/machine_continuity.go index 6668717a3e..65c97226d0 100644 --- a/coordinator/store/memory/machine_continuity.go +++ b/coordinator/store/memory/machine_continuity.go @@ -64,7 +64,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/memory/model_token_promotions.go b/coordinator/store/memory/model_token_promotions.go index 582a2da880..805714be43 100644 --- a/coordinator/store/memory/model_token_promotions.go +++ b/coordinator/store/memory/model_token_promotions.go @@ -42,7 +42,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 == store.RoleService { + if u == nil || u.DeletedAt != nil || u.PrivyUserID == "" || u.Role == store.RoleService { return nil, store.ErrPromotionIneligible } if _, exists := s.modelTokenGrants[account][model]; exists { diff --git a/coordinator/store/memory/provider_restore.go b/coordinator/store/memory/provider_restore.go index 75e5d3721b..1920e5e469 100644 --- a/coordinator/store/memory/provider_restore.go +++ b/coordinator/store/memory/provider_restore.go @@ -15,7 +15,7 @@ func (s *MemoryStore) GetProviderForRestore(ctx context.Context, serial, seKey s defer s.mu.RUnlock() var serialMatch, keyMatch *store.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/memory/providers.go b/coordinator/store/memory/providers.go index abc7155588..80d9fb6422 100644 --- a/coordinator/store/memory/providers.go +++ b/coordinator/store/memory/providers.go @@ -31,7 +31,7 @@ func (s *MemoryStore) GetProviderRecord(_ context.Context, id string) (*store.Pr 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 @@ -54,7 +54,7 @@ func (s *MemoryStore) GetMDAChainBySerial(_ context.Context, serial string) (jso // recently seen non-empty chain. var best *store.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) { @@ -79,7 +79,7 @@ func (s *MemoryStore) ListProvidersByAccount(_ context.Context, accountID string records := make([]store.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/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/memory/users.go b/coordinator/store/memory/users.go index 2fdeb17eb7..9529278f43 100644 --- a/coordinator/store/memory/users.go +++ b/coordinator/store/memory/users.go @@ -12,7 +12,9 @@ func (s *MemoryStore) CreateUser(user *store.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 { @@ -32,7 +34,7 @@ func (s *MemoryStore) GetUserByPrivyID(privyUserID string) (*store.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, store.ErrNotFound) } copy := *u @@ -45,7 +47,7 @@ func (s *MemoryStore) GetUserByAccountID(accountID string) (*store.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, store.ErrNotFound) } copy := *u @@ -97,7 +99,7 @@ func (s *MemoryStore) GetUserByStripeAccount(stripeAccountID string) (*store.Use 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 @@ -110,7 +112,7 @@ func (s *MemoryStore) GetUserByEmail(email string) (*store.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 } diff --git a/coordinator/store/postgres/analytics_flows.go b/coordinator/store/postgres/analytics_flows.go index b63c2220a5..bcf6fb4588 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/device_auth.go b/coordinator/store/postgres/device_auth.go index 0af12e7607..91669c8c6b 100644 --- a/coordinator/store/postgres/device_auth.go +++ b/coordinator/store/postgres/device_auth.go @@ -107,7 +107,7 @@ func (s *PostgresStore) GetProviderToken(token string) (*store.ProviderToken, er var pt store.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 errors.Is(err, pgx.ErrNoRows) { return nil, fmt.Errorf("store: %w: %w", store.ErrProviderTokenInvalid, err) 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$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/machine_inventory_backfill.go b/coordinator/store/postgres/machine_inventory_backfill.go index 06163a77b3..a58ea4b459 100644 --- a/coordinator/store/postgres/machine_inventory_backfill.go +++ b/coordinator/store/postgres/machine_inventory_backfill.go @@ -17,7 +17,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/postgres/migration_indexes.go b/coordinator/store/postgres/migration_indexes.go new file mode 100644 index 0000000000..69059d24bd --- /dev/null +++ b/coordinator/store/postgres/migration_indexes.go @@ -0,0 +1,102 @@ +package postgres + +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(10, "idx_provider_sessions_account", `CREATE INDEX CONCURRENTLY idx_provider_sessions_account ON provider_sessions (account_id)`), + index(11, "idx_provider_log_reports_account", `CREATE INDEX CONCURRENTLY idx_provider_log_reports_account ON provider_log_reports (account_id)`), + index(12, "idx_device_codes_account", `CREATE INDEX CONCURRENTLY idx_device_codes_account ON device_codes (account_id)`), + index(13, "idx_darkbloom_machine_sessions_account", `CREATE INDEX CONCURRENTLY idx_darkbloom_machine_sessions_account ON darkbloom_machine_sessions (account_id)`), + index(14, "idx_model_token_reservations_account", `CREATE INDEX CONCURRENTLY idx_model_token_reservations_account ON model_token_reservations (account_id)`), + index(15, "idx_inference_routes_consumer_key_hash", `CREATE INDEX CONCURRENTLY idx_inference_routes_consumer_key_hash ON inference_routes (consumer_key_hash)`), + index(16, "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 19 and 20 drop + // the old full-table unique constraint and index. + index(18, "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 { + return err + } + if !valid { + return fmt.Errorf("store: index %s did not become valid", name) + } + 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 ddcbe2fb1c..5e660fb5de 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) @@ -154,3 +154,9 @@ func (s *PostgresStore) goMigrations() []*goose.Migration { step(9, s.ensureStripeRefundIndex), } } + +// 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/model_token_promotions.go b/coordinator/store/postgres/model_token_promotions.go index 95f925790d..5a1ef9bc48 100644 --- a/coordinator/store/postgres/model_token_promotions.go +++ b/coordinator/store/postgres/model_token_promotions.go @@ -62,7 +62,7 @@ func (s *PostgresStore) ClaimModelTokenPromotion(account, model string, now time return nil, err } var user store.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, store.ErrPromotionIneligible } diff --git a/coordinator/store/postgres/provider_read.go b/coordinator/store/postgres/provider_read.go index a527e15eaa..f425d6f3d0 100644 --- a/coordinator/store/postgres/provider_read.go +++ b/coordinator/store/postgres/provider_read.go @@ -45,7 +45,7 @@ func scanProviderRecord(row rowScanner) (*store.ProviderRecord, error) { func (s *PostgresStore) GetProviderRecord(ctx context.Context, id string) (*store.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/postgres/provider_restore.go b/coordinator/store/postgres/provider_restore.go index 28c2ad5c3f..62011a5a14 100644 --- a/coordinator/store/postgres/provider_restore.go +++ b/coordinator/store/postgres/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 diff --git a/coordinator/store/postgres/providers.go b/coordinator/store/postgres/providers.go index aea17a52b7..0a06433675 100644 --- a/coordinator/store/postgres/providers.go +++ b/coordinator/store/postgres/providers.go @@ -111,6 +111,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 { @@ -150,7 +151,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/queries/api_keys.sql b/coordinator/store/postgres/queries/api_keys.sql index 6592dd6b9b..657cd2bcc6 100644 --- a/coordinator/store/postgres/queries/api_keys.sql +++ b/coordinator/store/postgres/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/postgres/schema/migrations/00017_soft_delete_columns.sql b/coordinator/store/postgres/schema/migrations/00017_soft_delete_columns.sql new file mode 100644 index 0000000000..2fe4e20f52 --- /dev/null +++ b/coordinator/store/postgres/schema/migrations/00017_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/postgres/schema/migrations/00019_users_privy_drop_unique_constraint.sql b/coordinator/store/postgres/schema/migrations/00019_users_privy_drop_unique_constraint.sql new file mode 100644 index 0000000000..2bf77aee1d --- /dev/null +++ b/coordinator/store/postgres/schema/migrations/00019_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/postgres/schema/migrations/00020_users_privy_drop_old_index.sql b/coordinator/store/postgres/schema/migrations/00020_users_privy_drop_old_index.sql new file mode 100644 index 0000000000..a3ed49875c --- /dev/null +++ b/coordinator/store/postgres/schema/migrations/00020_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/postgres/schema/migrations/00021_referrals_referrer_code_cascade.sql b/coordinator/store/postgres/schema/migrations/00021_referrals_referrer_code_cascade.sql new file mode 100644 index 0000000000..faacd6963e --- /dev/null +++ b/coordinator/store/postgres/schema/migrations/00021_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/postgres/schema/schema.sql b/coordinator/store/postgres/schema/schema.sql index f841fbb187..a56b14ee87 100644 --- a/coordinator/store/postgres/schema/schema.sql +++ b/coordinator/store/postgres/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 ); @@ -1324,7 +1325,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 ); @@ -1406,7 +1408,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 ); @@ -1854,7 +1857,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 ); @@ -2650,14 +2654,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: - -- @@ -2847,6 +2843,20 @@ CREATE INDEX idx_code_attest_push_budgets_due ON public.code_attest_push_budgets CREATE INDEX idx_consumer_settlements_referrer ON public.consumer_charge_settlements USING btree (referrer_account) WHERE (referrer_account <> ''::text); +-- +-- 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: - -- @@ -2882,6 +2892,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: - -- @@ -2945,6 +2962,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: - -- @@ -2994,6 +3018,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: - -- @@ -3008,6 +3039,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: - -- @@ -3134,6 +3172,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: - -- @@ -3247,10 +3292,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); -- @@ -3434,11 +3479,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/postgres/small_models_interest.go b/coordinator/store/postgres/small_models_interest.go index 5076af2610..6d86af9e04 100644 --- a/coordinator/store/postgres/small_models_interest.go +++ b/coordinator/store/postgres/small_models_interest.go @@ -34,7 +34,7 @@ func (s *PostgresStore) GetSmallModelsInterest(ctx context.Context, accountID st func (s *PostgresStore) ListSmallModelsInterest(ctx context.Context, after string, limit int) ([]store.SmallModelsInterestContact, error) { rows, err := s.pool.Query(ctx, `SELECT i.account_id,i.mac_type,i.chip,i.ram_gb,i.created_at,i.updated_at,u.email FROM small_models_interest i JOIN users u ON u.account_id=i.account_id - WHERE i.account_id > $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/store/postgres/storedb/api_keys.sql.go b/coordinator/store/postgres/storedb/api_keys.sql.go index 532dc54979..de468f56a2 100644 --- a/coordinator/store/postgres/storedb/api_keys.sql.go +++ b/coordinator/store/postgres/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/postgres/storedb/models.go b/coordinator/store/postgres/storedb/models.go index 48fbac1341..1bcaf93aee 100644 --- a/coordinator/store/postgres/storedb/models.go +++ b/coordinator/store/postgres/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/postgres/users.go b/coordinator/store/postgres/users.go index ef20abc8cd..da65e8e256 100644 --- a/coordinator/store/postgres/users.go +++ b/coordinator/store/postgres/users.go @@ -45,7 +45,7 @@ func (s *PostgresStore) GetUserByPrivyID(privyUserID string) (*store.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 { @@ -60,7 +60,7 @@ func (s *PostgresStore) GetUserByAccountID(accountID string) (*store.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 { @@ -114,7 +114,7 @@ func (s *PostgresStore) GetUserByStripeAccount(stripeAccountID string) (*store.U 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 { @@ -166,7 +166,7 @@ func (s *PostgresStore) GetUserByEmail(email string) (*store.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 { diff --git a/coordinator/store/provider_types.go b/coordinator/store/provider_types.go index 89620060f4..4eb6d8ca8f 100644 --- a/coordinator/store/provider_types.go +++ b/coordinator/store/provider_types.go @@ -37,6 +37,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/user_types.go b/coordinator/store/user_types.go index 1b33777c12..af1ac82b97 100644 --- a/coordinator/store/user_types.go +++ b/coordinator/store/user_types.go @@ -39,4 +39,7 @@ 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:"-"` } 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) 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..fb0e8d90f6 --- /dev/null +++ b/coordinator/tests/store/contracts/soft_delete_domain_reads_test.go @@ -0,0 +1,196 @@ +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/memory" + "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 TestUsageFlowsOmitDeletedProviderWithRegistryLocation(t *testing.T) { + for name, s := range storeBackends(t) { + t.Run(name, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + location := &store.ProviderLocation{City: "Provider", CountryCode: "US"} + p := store.ProviderRecord{ID: "flow-provider", AccountID: "owner", Location: location, + Hardware: json.RawMessage(`{}`), Models: json.RawMessage(`[]`), LastSeen: now} + if err := s.UpsertProvider(ctx, p); err != nil { + t.Fatal(err) + } + s.RecordUsage(store.UsageRecord{ProviderID: p.ID, ConsumerKey: "consumer", RequestID: "flow-request", Model: "model", + PromptTokens: 1, CompletionTokens: 1, RequestLocation: &store.ProviderLocation{City: "Consumer", CountryCode: "US"}}) + registryLocations := map[string]*store.ProviderLocation{p.ID: location} + rows, err := s.UsageFlowBuckets(now.Add(-time.Hour), registryLocations) + if err != nil || len(rows) != 1 || rows[0].ProviderCity != location.City || rows[0].Requests != 1 { + t.Fatalf("live provider flows = %+v, %v; want one flow", rows, err) + } + + p.DeletedAt = &now + if err := s.UpsertProvider(ctx, p); err != nil { + t.Fatal(err) + } + if _, ok := s.(*postgres.PostgresStore); ok { + softDeleteFixtureExec(t, `UPDATE providers SET deleted_at=$1 WHERE id=$2`, p.DeletedAt, p.ID) + } + // A registry snapshot captured before deletion must not override the tombstone. + rows, err = s.UsageFlowBuckets(now.Add(-time.Hour), registryLocations) + if err != nil || len(rows) != 0 { + t.Fatalf("deleted provider flows = %+v, %v; want none", rows, err) + } + }) + } +} + +func TestMemoryUsageFlowsIncludeUnpersistedRegistryProvider(t *testing.T) { + s := memory.NewMemory(store.Config{}) + s.RecordUsage(store.UsageRecord{ProviderID: "unpersisted", RequestID: "flow-request", + RequestLocation: &store.ProviderLocation{City: "Consumer", CountryCode: "US"}}) + rows, err := s.UsageFlowBuckets(time.Time{}, map[string]*store.ProviderLocation{ + "unpersisted": {City: "Provider", CountryCode: "US"}, + }) + if err != nil || len(rows) != 1 || rows[0].ProviderCity != "Provider" || rows[0].Requests != 1 { + t.Fatalf("unpersisted provider flows = %+v, %v; want one registry flow", rows, 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/coordinator/tests/store/postgres/migration_index_test.go b/coordinator/tests/store/postgres/migration_index_test.go index e79edda14f..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) { @@ -15,8 +18,8 @@ func TestMigrationsRefuseInvalidStripeRefundIndex(t *testing.T) { t.Fatal(err) } t.Cleanup(s.Close) + pendingFrom(t, s, 9) if _, err := s.pool.Exec(ctx, `DROP INDEX idx_ledger_stripe_refund; - DELETE FROM goose_db_version WHERE version_id = 9; INSERT INTO ledger_entries (account_id, entry_type, amount_micro_usd, balance_after, reference) VALUES ('same-account', 'stripe_payout', -1, 0, 'same-reference'), ('same-account', 'stripe_payout', -1, 0, 'same-reference')`); err != nil { @@ -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 28a5555147..37ff97cf44 100644 --- a/coordinator/tests/store/postgres/migrations_test.go +++ b/coordinator/tests/store/postgres/migrations_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "regexp" + "strconv" "strings" "sync" "testing" @@ -33,6 +34,23 @@ func captureLogs(t *testing.T) *bytes.Buffer { return &logs } +// migrationSourceCount returns the number of migration versions: the +// versions goose records on an empty database, without its version 0 row. +func migrationSourceCount(t *testing.T) int { + t.Helper() + ctx := context.Background() + s, err := openPostgresFixture(ctx, store.Config{DatabaseURL: newThrowawayTestDatabase(t)}) + if err != nil { + t.Fatalf("NewPostgres: %v", err) + } + defer s.Close() + var count int + if err := s.pool.QueryRow(ctx, `SELECT count(*) - 1 FROM `+gooseVersionTable).Scan(&count); err != nil { + t.Fatal(err) + } + return count +} + // A fresh database built by goose matches the current checked-in schema. func TestMigrationsBuildCheckedInSchema(t *testing.T) { ctx := context.Background() @@ -115,8 +133,13 @@ func testMigrationsUpgradeLegacyDatabase(t *testing.T, gooseBaseline bool) { } } versions := queryLines(t, pool, `SELECT version_id::text FROM `+gooseVersionTable+` ORDER BY id`) - if got := strings.Join(versions, " "); got != "0 1 2 3 4 5 6 7 8 9" { - t.Fatalf("goose versions = %q, want 0 through 9", got) + want := migrationSourceCount(t) + var expected []string + for version := 0; version <= want; version++ { + expected = append(expected, strconv.Itoa(version)) + } + if got := strings.Join(versions, " "); got != strings.Join(expected, " ") { + t.Fatalf("goose versions = %q, want 0 through %d", got, want) } } @@ -176,15 +199,20 @@ func TestConcurrentMigrationsApplyOnce(t *testing.T) { for _, m := range applied { got = append(got, m[1]+":"+m[2]) } - if want := "1:applied 2:applied 3:applied 4:applied 5:applied 6:applied 7:applied 8:applied 9:applied"; strings.Join(got, " ") != want { - t.Fatalf("migration results = %q, want each of the 9 versions applied once; logs:\n%s", got, logs.String()) + want := migrationSourceCount(t) + var expected []string + for version := 1; version <= want; version++ { + expected = append(expected, strconv.Itoa(version)+":applied") + } + if strings.Join(got, " ") != strings.Join(expected, " ") { + t.Fatalf("migration results = %q, want each of the %d versions applied once; logs:\n%s", got, want, logs.String()) } var rows, distinct int if err := pool.QueryRow(ctx, `SELECT count(*), count(DISTINCT version_id) FROM `+gooseVersionTable).Scan(&rows, &distinct); err != nil { t.Fatal(err) } - if rows != 10 || distinct != 10 { - t.Fatalf("goose version rows = %d (%d distinct), want 10", rows, distinct) + if rows != want+1 || distinct != want+1 { + t.Fatalf("goose version rows = %d (%d distinct), want %d", rows, distinct, want+1) } } diff --git a/coordinator/tests/store/postgres/soft_delete_reads_test.go b/coordinator/tests/store/postgres/soft_delete_reads_test.go new file mode 100644 index 0000000000..5f644053d4 --- /dev/null +++ b/coordinator/tests/store/postgres/soft_delete_reads_test.go @@ -0,0 +1,253 @@ +package postgres_test + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" +) + +// 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. + +// 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 *postgresFixture, table, key string) { + t.Helper() + column := map[string]string{"users": "account_id", "api_keys": "id", "providers": "id", "provider_tokens": "token_hash"}[table] + if column == "" { + t.Fatalf("unknown table %s", table) + } + tag, err := s.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) + } +} + +func TestSoftDeletedUserIsHidden(t *testing.T) { + s := testPostgresStore(t) + account := uniqueID("acct-gone") + privy := uniqueID("did:privy:gone") + email := uniqueID("gone") + "@example.com" + stripe := uniqueID("acct_stripe") + if err := s.CreateUser(&store.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, _ := store.As[store.ModelTokenPromotionStore](s) + now := time.Now().UTC().Truncate(time.Second) + model := uniqueID("promo/model") + if err := promotions.PutModelTokenPromotion(store.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, store.ErrNotFound) { + t.Fatalf("GetUserByAccountID: %v, want ErrNotFound", err) + } + if _, err := s.GetUserByPrivyID(privy); !errors.Is(err, store.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, store.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(&store.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(&store.User{AccountID: uniqueID("acct-dup"), PrivyUserID: privy}); err == nil { + t.Fatal("two live users hold the same Privy ID") + } +} + +func TestSoftDeletedAPIKeyIsHidden(t *testing.T) { + s := testPostgresStore(t) + account := uniqueID("acct-keys") + raw, gone, err := s.CreateAPIKey(account, store.APIKeyCreate{Name: "gone"}) + if err != nil { + t.Fatal(err) + } + _, live, err := s.CreateAPIKey(account, store.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) { + s := testPostgresStore(t) + raw := uniqueID("provider-token") + if err := s.CreateProviderToken(&store.ProviderToken{TokenHash: store.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", store.HashKey(raw)) + if pt, err := s.GetProviderToken(raw); err == nil { + t.Fatalf("GetProviderToken returned %+v", pt) + } +} + +func TestSoftDeletedProviderIsHidden(t *testing.T) { + s := testPostgresStore(t) + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Microsecond) + account := uniqueID("acct-providers") + serial := uniqueID("serial") + seKey := uniqueID("se") + location := &store.ProviderLocation{City: "Gone City", Region: "Region", RegionCode: "R", Country: "Country", CountryCode: "CC"} + live := store.ProviderRecord{ID: uniqueID("live"), AccountID: account, SerialNumber: serial, SEPublicKey: seKey, + MDACertChain: []byte(`["live"]`), Hardware: []byte(`{}`), Models: []byte(`[]`), LastSeen: now.Add(-2 * time.Hour)} + gone := store.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 []store.ProviderRecord{live, gone} { + if err := s.UpsertProvider(ctx, p); err != nil { + t.Fatal(err) + } + } + consumerLocation := &store.ProviderLocation{City: "Origin", Region: "Region", RegionCode: "R", Country: "Country", CountryCode: "CC"} + s.RecordUsage(store.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) { + backend := testPostgresStore(t) + ctx := context.Background() + now := time.Now().UTC() + inventory, _ := store.As[store.MachineInventoryStore](backend) + keys, _ := store.As[store.AppAttestShadowStore](backend) + continuity, _ := store.As[store.MachineOperationalStore](backend) + account := uniqueID("owner") + appKey := uniqueID("apple") + original, reconnect := uniqueID("original"), uniqueID("reconnect") + if _, err := keys.InsertAppAttestShadowKey(ctx, store.AppAttestShadowKey{KeyID: appKey, AccountID: account}); err != nil { + t.Fatal(err) + } + if _, err := inventory.ObserveMachine(ctx, store.MachineObservation{SessionID: original, AccountID: account, At: now, SEKey: uniqueID("se"), VerifiedAppAttestKey: appKey}); err != nil { + t.Fatal(err) + } + prior := store.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, store.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, store.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/docs/AGENTS.md b/docs/AGENTS.md index 7ed7ddebfd..e79bfc5860 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -176,6 +176,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/postgres/sqlc.yaml`, `coordinator/store/postgres/queries/`) | `reference/sqlc-type-mapping.md` for a new type or override; `developer/sqlc.md` for a workflow or convention change | | Coordinator package ownership, application assembly, or backend boundaries | `developer/navigation.md`, `architecture/components/coordinator.md`; retain the relevant API, configuration, storage, and telemetry rows for behavioral surfaces | | Provider version bump (`ProviderCore.version` ↔ `LatestProviderVersion`) | `operations/provider-release.md`; `CHANGELOG.md` | diff --git a/docs/README.md b/docs/README.md index ff8ce79b70..fb5b69591f 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. @@ -107,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/architecture/schema-lifecycle.md b/docs/architecture/schema-lifecycle.md index 2035a35e95..93431b1caf 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). @@ -74,11 +74,19 @@ Legend: blue = step, amber = decision, green = success, red = exit 1. | 7 | `coordinator/store/postgres/schema/migrations/00007_legacy_mdm_cohort.sql` | Adds the legacy MDM cohort and freeze tables; it does not freeze membership. | | 8 | `coordinator/store/postgres/schema/migrations/00008_small_models_interest.sql` | Adds saved small-model hardware interest, including the user foreign key and RAM constraint. | | 9 | `ensureStripeRefundIndex` (`coordinator/store/postgres/startup.go`) | Builds `idx_ledger_stripe_refund` concurrently through `ensureConcurrentIndex`. | +| 10–16 | `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`. | +| 17 | `coordinator/store/postgres/schema/migrations/00017_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. | +| 18 | `indexMigrations` | `CREATE UNIQUE INDEX CONCURRENTLY idx_users_privy_live ON users (privy_user_id) WHERE deleted_at IS NULL`. | +| 19 | `coordinator/store/postgres/schema/migrations/00019_users_privy_drop_unique_constraint.sql` | One transaction: drops `users_privy_user_id_key`. | +| 20 | `coordinator/store/postgres/schema/migrations/00020_users_privy_drop_old_index.sql` | `NO TRANSACTION`: `SET lock_timeout = '1min'`, then `DROP INDEX CONCURRENTLY IF EXISTS idx_users_privy`. | +| 21 | `coordinator/store/postgres/schema/migrations/00021_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 9 preserve later pre-goose schema additions; version 9 is also -a Go migration. +a Go migration. Versions 10 to 16 and 18 are Go migrations in `indexMigrations`; +`allGoMigrations` passes both lists to goose. Goose runs SQL and Go versions +in one sequence, so version 17 adds `deleted_at` before version 18 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 @@ -88,19 +96,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 | Versions 6 to 8 | -| 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 | Versions 6 to 8 and 19 | +| 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, 17, 20, 21 | | 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, 5 and 9 | +| 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 10 to 16 and 18 | +| 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, 5 and 9 | An SQL file must not contain `CREATE INDEX CONCURRENTLY` (`TestSQLMigrationsDoNotBuildIndexesConcurrently` in `coordinator/tests/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, 5 and 9) 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 @@ -112,7 +124,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 and 9 | 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 10 to 16 and 18 | `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 20 | `SET lock_timeout = '1min'` in the file | `00020_users_privy_drop_old_index.sql` | The same wait for older snapshots, inside an SQL migration. | | `--migrate-only` | `context.WithTimeout(..., 15*time.Minute)` | `Maintenance` | 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 @@ -213,6 +227,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 17). 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 18) keeps one + live user per Privy ID and ignores soft-deleted users. Versions 19 and 20 + 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 + 19 and 20 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 @@ -231,7 +295,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, 5 and 9 | +| `postgres startup phase` | `phase` (`connect` or an index name), `result`, `duration_ms` | After the ping, and after each index build in versions 3, 5, 9, 10 to 16 and 18 | | `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 | @@ -250,12 +314,15 @@ 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. **An SQL 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. `TestMigrationsBlockedLegacyColumnRemainsPending` verifies - a blocked legacy column is not marked applied and is restored after retry. - Go migration helpers use the serving pool and retain its URL timeouts. +4. **An SQL migration statement does not wait more than 3 s for a table lock,** + or 1 min for a `CONCURRENTLY` statement (versions 10 to 16, 18 and 20), + unless the database URL sets a longer `lock_timeout` for the SQL session + (`migrationLockTimeout`, `concurrentIndexLockTimeout`). + `TestMigrateRetriesLockTimeout` and + `TestConcurrentIndexMigrationWaitsForOlderSnapshot` cover both. + `TestMigrationsBlockedLegacyColumnRemainsPending` verifies a blocked legacy + column is not marked applied and is restored after retry. Go migration + helpers in `goMigrations` retain the serving pool's URL timeouts. 5. **Migrations build exactly `schema.sql`** on a fresh database (`TestMigrationsBuildCheckedInSchema`). 6. **The generated queries match `schema.sql` and the query files.** @@ -264,7 +331,16 @@ 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/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` + covers the Postgres reads). +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. @@ -277,6 +353,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, 5 or 9 was interrupted | `ensureConcurrentIndex` does not repair it; [runbook](../operations/schema-migration.md#invalid-index). | +| An index migration (10 to 16, 18) 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 18 fails with a unique violation | Two live users share a Privy ID; `users_privy_user_id_key` prevents that until version 19, 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/postgres/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. | @@ -288,7 +367,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/tests/store/postgres/soft_delete_reads_test.go` | +| Frozen pre-goose schema | `coordinator/tests/store/postgres/testdata/legacy_schema.sql` | | SQL migrations | `coordinator/store/postgres/schema/migrations/` | | Checked-in schema | `coordinator/store/postgres/schema/schema.sql` | | Concurrent index helper and startup log line | `coordinator/store/postgres/startup.go` (`ensureConcurrentIndex`, `logStartupMigration`) | @@ -297,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 @@ -305,5 +387,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/security/enrollment.md b/docs/architecture/security/enrollment.md index 237648c871..c1006120db 100644 --- a/docs/architecture/security/enrollment.md +++ b/docs/architecture/security/enrollment.md @@ -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/architecture/storage.md b/docs/architecture/storage.md index 3097274975..f15a589e0a 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -224,6 +224,14 @@ flowchart LR 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, 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 `RecordProviderEarning` and `CreditProviderAccount` maintain new summaries from @@ -365,7 +373,12 @@ KV blocks under a per-model key, not tokens. 3. **One-shot data migrations in the baseline commit their `schema_migrations` marker in the same statement or transaction as their update** (`coordinator/store/postgres/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` + ([soft-delete reference](../reference/soft-delete.md); + `coordinator/tests/store/postgres/soft_delete_reads_test.go` covers each + Postgres read). +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/postgres/migrations/dedupe_provider_earnings.sql` and @@ -376,16 +389,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/postgres/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`). @@ -394,6 +407,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 [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/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..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`). @@ -517,6 +522,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/database-migrations.md b/docs/developer/database-migrations.md index 28906f74e3..7b12807424 100644 --- a/docs/developer/database-migrations.md +++ b/docs/developer/database-migrations.md @@ -31,18 +31,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/postgres/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/postgres/schema/migrations/00019_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/postgres/schema/migrations/00017_soft_delete_columns.sql` | + | `VALIDATE CONSTRAINT` after a `NOT VALID` add | SQL file with `-- +goose NO TRANSACTION` | `coordinator/store/postgres/schema/migrations/00021_referrals_referrer_code_cascade.sql` | + | `DROP INDEX CONCURRENTLY` | SQL file with `-- +goose NO TRANSACTION` and `SET lock_timeout = '1min'` | `coordinator/store/postgres/schema/migrations/00020_users_privy_drop_old_index.sql` | + | Create an index on a table that has rows in production | Go migration in `indexMigrations` | Versions 10 to 16 and 18 (`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 | Compatible release phases; see [expand and contract](#change-a-column-while-preserving-rollback-compatibility) | — | | 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/postgres/migrations/`, applied under an approved operation | `coordinator/store/postgres/migrations/dedupe_provider_earnings.sql` | 2. **Pick the version.** Use one more than the highest version in - `coordinator/store/postgres/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/postgres/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. @@ -64,15 +67,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 21). 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 20 does. *Go migration.* Write a method on `PostgresStore` that takes a `context.Context` and returns an error, and add it to `goMigrations`: ```go - step(10, s.checkExampleRows), + step(22, s.checkExampleRows), ``` It runs on the store pool with no session timeouts unless the database URL @@ -80,20 +85,19 @@ in production is the [schema migration runbook](../operations/schema-migration.m 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: + `TestSQLMigrationsDoNotBuildIndexesConcurrently` fails. Add the index to + `indexMigrations` (`coordinator/store/postgres/migration_indexes.go`) + instead: ```go - step(10, 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)`) - }), + index(22, "idx_example_account", `CREATE INDEX CONCURRENTLY idx_example_account ON example (account_id)`), ``` - 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. + `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. 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)). @@ -140,7 +144,7 @@ in production is the [schema migration runbook](../operations/schema-migration.m ```bash go test ./coordinator/tests/store/postgres -count=1 \ - -run 'TestMigrations|TestConcurrentMigrations|TestMigrateRetries|TestSQLMigrations' + -run 'TestMigrations|TestConcurrent|TestMigrateRetries|TestSQLMigrations|TestIndexMigration' ``` | Test | Fails when | @@ -150,6 +154,11 @@ go test ./coordinator/tests/store/postgres -count=1 \ | `TestMigrationsBlockedLegacyColumnRemainsPending` | A blocked baseline is recorded as successful, or the missing column is not restored on retry | | `TestConcurrentMigrationsApplyOnce` | Two runs at once apply a version twice, or a run changes the schema while another session holds the goose advisory lock | | `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/tests/store/postgres/testdata/legacy_schema.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` @@ -226,13 +235,57 @@ Legend: blue = release, amber = required transition, grey = permitted fallback. to satisfy it before it is enforced; use `NOT VALID` and `VALIDATE` where PostgreSQL supports them. +## 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 17 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 18), drop the old constraint (version 19), then + drop the old index with `DROP INDEX CONCURRENTLY` (version 20). 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 + its `coordinator/store/*_types.go` file. +4. Add `AND deleted_at IS NULL` to every read that returns a live row: the + hand-written SQL in `coordinator/store/postgres/` and the queries in + `coordinator/store/postgres/queries/`. Find them with: + + ```bash + grep -n -E "(FROM|JOIN)\s+example\b" coordinator/store/postgres/*.go coordinator/store/postgres/queries/*.sql + ``` + + Make each `MemoryStore` read (`coordinator/store/memory/`) 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/tests/store/postgres/soft_delete_reads_test.go` and a test + that checks every filtered read. +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 20 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. @@ -245,12 +298,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, 5 and 9 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/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 0fc8cd5a3a..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: @@ -98,6 +106,16 @@ requires API-contract documentation as well as the release runbook. The guards 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, 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. @@ -1211,6 +1229,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 diff --git a/docs/operations/schema-migration.md b/docs/operations/schema-migration.md index 00ff8a6f19..959ffd64da 100644 --- a/docs/operations/schema-migration.md +++ b/docs/operations/schema-migration.md @@ -1,6 +1,6 @@ # Apply schema migrations in production -> Last updated: 2026-10-05 +> Last updated: 2026-10-06 Runbook for applying the goose migrations of a coordinator candidate to the production database (Cloud SQL for PostgreSQL 17 in `darkbloom-mainnet`, read @@ -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/postgres/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, 5 and 9 build; none when no such version is pending | +| `postgres startup phase` | `"phase":"","result":"applied"` | One per index that versions 3, 5, 9, 10 to 16 and 18 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: two `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 10 to 16 and 18 (`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, 5 and 9, `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 17 to 20, 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 20 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 17 to 21 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. @@ -249,8 +265,10 @@ this migration conversion was in review. Required baseline statement failures abort startup without recording version 1; a retry resumes the pending version. - [ ] Step 1 shows `relation "goose_db_version" does not exist`. -- [ ] The candidate's highest version is 9, so the pre-goose image stays a - safe fallback ([rollback rule 2](#rollback)). +- [ ] The candidate's highest version is 9: 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 10 to 21 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). @@ -262,8 +280,34 @@ abort startup without recording version 1; a retry resumes the pending version. - [ ] The `pg_dump` diff shows only hand-applied objects. Investigate any other difference before approving the cutover; repairs need separate approval. +## Soft-delete release + +The deploy that applies versions 10 to 21. Run it only after a goose build with +versions 1 to 9 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 9. +- [ ] 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 10 to 16 and 18, and `postgres migration` for + versions 10 to 21. +- [ ] `goose_db_version` lists 0 to 21, 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 17 to 21 change in the reads 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/README.md b/docs/reference/README.md index 4563152368..946542637c 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/postgres/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..8a7a13339a --- /dev/null +++ b/docs/reference/soft-delete.md @@ -0,0 +1,152 @@ +# Soft delete + +> Last updated: 2026-10-06 + +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/postgres/schema/migrations/00017_soft_delete_columns.sql` adds the +column; the Go field is `DeletedAt *time.Time` with `json:"-"` +(`coordinator/store/user_types.go`, `apikey_types.go`, `provider_types.go`, +`device_auth_types.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/postgres/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/tests/store/postgres/soft_delete_reads_test.go` +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` + +| Store method | PostgresStore | MemoryStore | Result for a soft-deleted user | +|---|---|---|---| +| `GetUserByAccountID` | `coordinator/store/postgres/users.go` | `coordinator/store/memory/users.go` | `ErrNotFound` | +| `GetUserByPrivyID` | `coordinator/store/postgres/users.go` | `coordinator/store/memory/users.go` | `ErrNotFound` | +| `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` + +PostgresStore methods are in `coordinator/store/postgres/apikey.go`; their +SQL is in `coordinator/store/postgres/queries/api_keys.sql`. MemoryStore +methods are in `coordinator/store/memory/apikey.go`. + +| Store method | Query (PostgresStore) | MemoryStore | Result for a soft-deleted key | +|---|---|---|---| +| `GetKeyAccount` | `GetActiveKeyAccount` | `coordinator/store/memory/apikey.go` | `""` | +| `AuthenticateKey` | `GetAPIKeyByHash` | `coordinator/store/memory/apikey.go` | error; the request is not authenticated | +| `ListAPIKeys` | `ListAPIKeysByOwner` | `coordinator/store/memory/apikey.go` | omitted | +| `GetAPIKeyByID` | `GetAPIKeyByID` | `coordinator/store/memory/apikey.go` | not found | +| `UpdateAPIKey` | `UpdateAPIKey` (`UPDATE ... AND deleted_at IS NULL`) | `coordinator/store/memory/apikey.go` | `key not found`; nothing changes | +| `RotateAPIKey` | `GetAPIKeyByIDForUpdate` | `coordinator/store/memory/apikey.go` | `key not found`; nothing changes | + +### `provider_tokens` + +| Store method | PostgresStore | MemoryStore | Result for a soft-deleted token | +|---|---|---|---| +| `GetProviderToken` | `coordinator/store/postgres/device_auth.go` | `coordinator/store/memory/device_auth.go` | `ErrProviderTokenInvalid` | + +### `providers` + +| Store method | PostgresStore | MemoryStore | Result for a soft-deleted record | +|---|---|---|---| +| `GetProviderRecord` | `coordinator/store/postgres/provider_read.go` | `coordinator/store/memory/providers.go` | not found | +| `GetMDAChainBySerial` | `coordinator/store/postgres/providers.go` | `coordinator/store/memory/providers.go` | its chain is not used | +| `ListProvidersByAccount` | `coordinator/store/postgres/providers.go` | `coordinator/store/memory/providers.go` | omitted | +| `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 | + +`MemoryStore.UsageFlowBuckets` checks the stored provider record for a tombstone +before using the supplied registry location map. A soft-deleted record suppresses +both the stored location and any stale registry-supplied location, so its usage +does not contribute a flow bucket (`coordinator/store/memory/analytics.go`). +Without a tombstone, registry locations still take precedence over stored locations. + +`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. + +| Table | Methods | +|---|---| +| `users` | `CreateUser` insert, `SetUserStripeAccount`, `SetUserRole`, `SetUserPlatformFeePercent` (`coordinator/store/postgres/users.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/device_auth.go`) | +| `providers` | `UpsertProvider`, `DeleteProvidersBySerial` (`coordinator/store/postgres/providers.go`), `UpsertProviderWithReputation` (`coordinator/store/postgres/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` | 18 (`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 19) and `idx_users_privy` (dropped by version 20). | +| `idx_provider_sessions_account` | `provider_sessions (account_id)` | 10 | Erasure finds rows by account | +| `idx_provider_log_reports_account` | `provider_log_reports (account_id)` | 11 | Erasure finds rows by account | +| `idx_device_codes_account` | `device_codes (account_id)` | 12 | Erasure finds rows by account | +| `idx_darkbloom_machine_sessions_account` | `darkbloom_machine_sessions (account_id)` | 13 | Erasure finds rows by account | +| `idx_model_token_reservations_account` | `model_token_reservations (account_id)` | 14 | Erasure finds rows by account | +| `idx_inference_routes_consumer_key_hash` | `inference_routes (consumer_key_hash)` | 15 | Erasure finds rows by hashed key | +| `idx_request_rejections_consumer_key_hash` | `request_rejections (consumer_key_hash)` | 16 | 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 21 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 | + +## Documentation coverage + +`scripts/docs-impact-rules.json` requires this reference when the current +live-row readers and writers listed above change, including the API-key SQL +source and generated adapter. This is a path-based guard, not SQL analysis: +a new reader or writer must be added to the rule as well as the tables above. +`scripts/test-docs-impact-check.py` verifies the mapping and keeps unrelated +history-table files and tests outside this gate. + +## 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 446c14c1fc..381e95dbfe 100644 --- a/docs/reference/sqlc-type-mapping.md +++ b/docs/reference/sqlc-type-mapping.md @@ -39,6 +39,7 @@ are in `coordinator/store/postgres/apikey.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 | diff --git a/docs/threat-model.yaml b/docs/threat-model.yaml index 97e0ee9be0..e86a2ae5dc 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. @@ -980,7 +981,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 a3883daaf2..126e053b91 100644 --- a/scripts/docs-impact-rules.json +++ b/scripts/docs-impact-rules.json @@ -216,13 +216,47 @@ "coordinator/store/postgres/startup.go", "coordinator/store/postgres/retired_backfills.go", "coordinator/store/postgres/provider_earnings_index.go", - "coordinator/store/postgres/earnings_window_index.go" + "coordinator/store/postgres/earnings_window_index.go", + "coordinator/store/postgres/migration_indexes.go" ], "docs_any_of": [ "docs/architecture/storage.md", "docs/architecture/schema-lifecycle.md" ] }, + { + "name": "soft-delete reads and writes", + "source_patterns": [ + "coordinator/store/memory/users.go", + "coordinator/store/memory/apikey.go", + "coordinator/store/memory/providers.go", + "coordinator/store/memory/device_auth.go", + "coordinator/store/memory/provider_restore.go", + "coordinator/store/memory/machine_continuity.go", + "coordinator/store/memory/model_token_promotions.go", + "coordinator/store/memory/analytics.go", + "coordinator/store/postgres/users.go", + "coordinator/store/postgres/apikey.go", + "coordinator/store/postgres/providers.go", + "coordinator/store/postgres/device_auth.go", + "coordinator/store/postgres/provider_read.go", + "coordinator/store/postgres/provider_record_write.go", + "coordinator/store/postgres/provider_restore.go", + "coordinator/store/postgres/machine_continuity.go", + "coordinator/store/postgres/machine_inventory_backfill.go", + "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/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" + ] + }, { "name": "sqlc queries and type mappings", "source_patterns": [ @@ -330,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/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-docs-impact-check.py b/scripts/test-docs-impact-check.py index 84b3789b38..3ce1ed0db6 100644 --- a/scripts/test-docs-impact-check.py +++ b/scripts/test-docs-impact-check.py @@ -64,12 +64,13 @@ def test_sqlc_changes_require_canonical_docs(self) -> None: documents = ("docs/developer/sqlc.md", "docs/reference/sqlc-type-mapping.md") for source in sources: with self.subTest(source=source): + related = ("docs/reference/soft-delete.md",) if source.endswith("queries/api_keys.sql") else () for unrelated in ((), ("docs/architecture/storage.md",)): - missing = self.run_check(source, *unrelated) + missing = self.run_check(source, *related, *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) + covered = self.run_check(source, *related, 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) @@ -80,6 +81,42 @@ def test_sqlc_changes_require_canonical_docs(self) -> None: ) self.assertEqual(ignored.returncode, 0, ignored.stdout + ignored.stderr) + 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", + "coordinator/store/postgres/device_auth.go", + "coordinator/store/memory/providers.go", + "coordinator/store/postgres/provider_read.go", + "coordinator/store/postgres/provider_record_write.go", + "coordinator/store/memory/apikey.go", + "coordinator/store/postgres/queries/api_keys.sql", + "coordinator/store/postgres/storedb/api_keys.sql.go", + ) + for source in sources: + with self.subTest(source=source): + 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) + covered = self.run_check(source, *related, "docs/reference/soft-delete.md") + self.assertEqual(covered.returncode, 0, covered.stdout + covered.stderr) + overridden = self.run_check(*sources, labels=["docs-not-needed"]) + self.assertEqual(overridden.returncode, 0, overridden.stdout + overridden.stderr) + ignored = self.run_check( + "coordinator/tests/store/postgres/soft_delete_reads_test.go", + "coordinator/store/postgres/users_test.go", + "coordinator/store/postgres/usage.go", + "coordinator/store/memory/ledger.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"), @@ -88,6 +125,7 @@ def test_reorganized_owners_keep_canonical_documentation_gates(self) -> None: ("coordinator/registry/selection/affinity.go", "docs/architecture/routing.md"), ("coordinator/app/startup_config.go", "docs/reference/configuration.md"), ("coordinator/store/postgres/migrations.go", "docs/architecture/storage.md"), + ("coordinator/store/postgres/migration_indexes.go", "docs/architecture/storage.md"), ("coordinator/store/postgres/schema/migrations/00010_example.sql", "docs/architecture/storage.md"), ("coordinator/store/postgres/schema/schema.sql", "docs/architecture/storage.md"), ("coordinator/store/postgres/example_schema.go", "docs/architecture/storage.md"), @@ -294,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", ), diff --git a/scripts/test-restack-after-squash.py b/scripts/test-restack-after-squash.py new file mode 100644 index 0000000000..21b6a56838 --- /dev/null +++ b/scripts/test-restack-after-squash.py @@ -0,0 +1,207 @@ +#!/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 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()