Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
8109162
Apply the coordinator schema as goose migrations
davidtai Oct 3, 2026
13ccc72
Name the new migration file without citing a missing path
davidtai Oct 3, 2026
e634061
Generate the api_keys store queries with sqlc
davidtai Oct 3, 2026
b79afa9
Add soft-delete columns and erase-path indexes
davidtai Oct 3, 2026
04cad10
Show the schema test result in the sqlc-check log
davidtai Oct 3, 2026
1475925
Merge branch 'feat/store-sqlc-api-keys' into feat/store-soft-delete-s…
davidtai Oct 3, 2026
7a634a6
Keep the CI Postgres service on 16
davidtai Oct 3, 2026
7bc34e8
Merge branch 'feat/store-sqlc-api-keys' into feat/store-soft-delete-s…
davidtai Oct 3, 2026
c776d80
Build migration indexes only through ensureConcurrentIndex
davidtai Oct 3, 2026
27582c7
Merge branch 'feat/store-goose-migrations' into feat/store-sqlc-api-keys
davidtai Oct 3, 2026
f829983
Build the erase-path indexes as Go migrations
davidtai Oct 3, 2026
c258bf6
Merge branch 'feat/store-sqlc-api-keys' into feat/store-soft-delete-s…
davidtai Oct 3, 2026
24bd04f
Document the goose schema lifecycle, migration how-to and runbook
davidtai Oct 4, 2026
643704d
Merge branch 'feat/store-goose-migrations' into feat/store-sqlc-api-keys
davidtai Oct 4, 2026
33050f7
Document the sqlc workflow and its type mapping
davidtai Oct 4, 2026
496bc02
Merge branch 'feat/store-sqlc-api-keys' into feat/store-soft-delete-s…
davidtai Oct 4, 2026
f51f8e1
Document soft delete, the index migrations and the soft-delete release
davidtai Oct 4, 2026
5bf78d5
refactor: share one line-query helper in the migration tests
davidtai Oct 4, 2026
806f824
Merge branch 'feat/store-goose-migrations' into feat/store-sqlc-api-keys
davidtai Oct 4, 2026
1bdf5bc
refactor: report index validity and inspect errors apart
davidtai Oct 4, 2026
f22b05a
Merge commit '806f8240' into feat/store-soft-delete-schema
davidtai Oct 4, 2026
1cb6cdf
Merge master into feat/store-goose-migrations
davidtai Oct 5, 2026
48f7935
Merge feat/store-goose-migrations into feat/store-sqlc-api-keys
davidtai Oct 5, 2026
8ba1958
Merge feat/store-sqlc-api-keys (on master 5b7a675c) into feat/store-s…
davidtai Oct 5, 2026
ec350b0
Merge master into the sqlc API-key branch
Gajesh2007 Oct 6, 2026
1e45080
Verify API-key sqlc null and rotation contracts
Gajesh2007 Oct 6, 2026
6e3fe88
Require canonical docs for sqlc changes
Gajesh2007 Oct 6, 2026
1ccdc80
Merge updated sqlc parent and reconcile soft-delete migrations
Gajesh2007 Oct 6, 2026
c5824c2
Group concurrent index migration tests by responsibility
Gajesh2007 Oct 6, 2026
5f85d43
Exclude soft-deleted contacts and initial MDM cohort evidence
Gajesh2007 Oct 6, 2026
209e651
Merge master into soft-delete schema and fence stale registry locations
Gajesh2007 Oct 6, 2026
e4b2fdf
test: format verification priorities for Go 1.26
Gajesh2007 Oct 6, 2026
e42e5d5
feat(dev): add safe post-squash stack restacking
Gajesh2007 Oct 6, 2026
cd29e84
test: remove unused restacking test import
Gajesh2007 Oct 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions coordinator/store/apikey_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions coordinator/store/device_auth_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:"-"`
}
8 changes: 6 additions & 2 deletions coordinator/store/memory/analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 6 additions & 6 deletions coordinator/store/memory/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 ""
Expand All @@ -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 {
Expand Down Expand Up @@ -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))
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/memory/device_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/memory/legacy_mdm_cohort.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/memory/machine_continuity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/memory/model_token_promotions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/memory/provider_restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions coordinator/store/memory/providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/memory/small_models_interest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down
12 changes: 7 additions & 5 deletions coordinator/store/memory/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 &copy, nil
}
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/postgres/analytics_flows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/postgres/device_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions coordinator/store/postgres/legacy_mdm_cohort.go
Original file line number Diff line number Diff line change
Expand Up @@ -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<f.cutoff AND p.registered_at<f.cutoff
AND ((r.mda_udid<>'' 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<f.cutoff)
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/postgres/machine_continuity.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (s *PostgresStore) ResolveMachineContinuity(ctx context.Context, sessionID,
// Never restore through serial or SE claims, and never cross account history
// even when an Apple-verified MDA serial associates two account-scoped aliases.
result.Previous, err = scanProviderRecord(tx.QueryRow(ctx, `SELECT `+providerRecordColumns+`
FROM providers WHERE account_id=$2 AND id<>$3 AND id<>ALL($4::text[])
FROM providers WHERE account_id=$2 AND id<>$3 AND id<>ALL($4::text[]) AND deleted_at IS NULL
AND id IN (SELECT session_id FROM darkbloom_machine_sessions WHERE machine_id=$1 AND account_id=$2)
ORDER BY last_seen DESC,id DESC LIMIT 1`, result.Machine.ID, account, sessionID, excluded))
if errors.Is(err, pgx.ErrNoRows) {
Expand Down
2 changes: 1 addition & 1 deletion coordinator/store/postgres/machine_inventory_backfill.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading