Skip to content

chore(db): add missing user FKs, FK leading indexes, and users role/enabled NOT NULL [schema-hygiene 2/4] - #889

Closed
Quick104 wants to merge 3 commits into
schema/hygiene-drop-dead-tablesfrom
schema/hygiene-integrity
Closed

Quick104 wants to merge 3 commits into
schema/hygiene-drop-dead-tablesfrom
schema/hygiene-integrity

Conversation

@Quick104

@Quick104 Quick104 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Problem

Related issue: #135 (schema workstream: #888)

Account deletion is a bare DELETE FROM users WHERE id=$1, but 17 user-referencing columns had no foreign key — every deletion leaks rows (live push routes, webhooks, notification prefs, cached recommendations, in-flight Discord link state, and more). Separately, 46 FK leading columns had no usable index (so FK cascade checks sequential-scan child tables, worst on auth_sessions.user_id and downloads.media_file_id), and users.role/users.enabled allowed NULL that no code path writes or handles. The 1.0 squashed baseline should not inherit any of this.

Base branch: schema/hygiene-drop-dead-tables (PR #879) — second PR in the schema-hygiene stack; only the last two commits are new here.

Approach

Three migrations, all derived from an empirical audit of the migrated schema (audit queries are committed in the migration comments):

  1. 20260901161657_fk_leading_indexes.sql — 57 CREATE INDEX CONCURRENTLY (-- +goose NO TRANSACTION), covering the 46 audited unindexed FK leading columns, 10 newly constrained columns, and 2 columns whose only leading index is partial with a predicate on a different column (watch_provider_scrobble_sessions.connection_id, page_sections.library_id). The audit rule is strict: partial indexes never count as FK coverage unless their predicate is <column> IS NOT NULL (nine such documented exceptions, argued in the migration).
  2. 20260901161700_user_fk_integrity.sql — 17 FKs to users(id): 14 ON DELETE CASCADE (row belongs to the account) and 3 ON DELETE SET NULL (attribution on records that outlive the account: activity_log.impersonator_user_id, subtitle_ai_jobs.requested_by, metadata_translation_jobs.requested_by). auth_sessions.impersonator_user_id is deliberately CASCADE — SET NULL would silently convert a live impersonation session into an ordinary session for the impersonated user. Each ADD CONSTRAINT is preceded by an orphan sweep scoped exactly to rows whose parent no longer exists (targeted DELETE, or UPDATE … SET NULL for the attribution columns). Documented exclusions: policy_decisions* (per program plan: hottest write path, rows are historical evidence), notification_server_channels.created_by_user_id (informational-only by that table's recorded convention), foreign-system identity columns, and two text-typed Silo user-id columns that need a retype first (noted in Schema workstream: 1.0 hygiene and migration reset (umbrella) #888).
  3. 20260901161702_users_role_enabled_not_null.sql — backfills role='user' / enabled=true (the code-side defaults), then SET NOT NULL.

migrations/schema_integrity_test.go (new, in the established migrations contract-test style) pins the 17 exact ON DELETE actions, each paired orphan sweep, the backfill values, the 57 index names, and that no CREATE INDEX statement gains a WHERE predicate (case-insensitive) — mutation-tested: flipping a CASCADE or lowercasing a predicate fails the test.

Validation

Risks

  • The FK migration runs transactionally and holds SHARE ROW EXCLUSIVE on users and each child during validation — on large tables that blocks writes for the duration. Accepted as documented maintenance-window behavior per the program's upgrade posture (a NOT VALID/VALIDATE split was considered and declined for pre-1.0 simplicity; the migration comments note it).
  • The index migration uses CONCURRENTLY outside a transaction; the Up includes recovery handling for invalid leftover indexes if a run is interrupted.
  • Orphan sweeps delete garbage rows (unreachable by any code path since their account is gone) and null out attribution for deleted accounts; the Down restores constraints/nullability but deleted rows are not restorable — restore from backup, as the migration states.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code (orchestrator session driving implementation and review subagents)
  • Model(s): claude-opus-5 (implementation), claude-fable-5 (orchestration and all review agents)
  • Involvement: Fully AI-generated; maintainer review pending (opened by the orchestrating agent under the maintainer's program instruction)
  • Adversarial review: two rounds of independent blind panels (destructive-safety at maximum effort, migration discipline, audit fidelity, test adequacy). Round 1 found one major (the index audit counted partial indexes as FK coverage — watch_provider_scrobble_sessions.connection_id was uncovered on an unboundedly-growing table) and three minors; all fixed. Round 2 verified closure and mutation-tested the new contract tests, yielding two minor prescriptions (partition-aware audit-count comment; case-insensitive predicate guard), both applied. The NOT VALID lock-window suggestion was declined with a written reason (documented maintenance-window posture).

Quick104 and others added 2 commits September 1, 2026 13:10
Adds the two partial-index-only FK indexes the audit rule now requires,
documents the partition-aware audit count, and adds contract tests pinning
ON DELETE actions, orphan sweeps, backfills, and the index list.

Co-Authored-By: Claude Fable 5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-01T17:59:56.774315Z 9205137 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 920513712b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

UPDATE public.users SET role = 'user' WHERE role IS NULL;
UPDATE public.users SET enabled = true WHERE enabled IS NULL;

ALTER TABLE public.users ALTER COLUMN role SET NOT NULL;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Supply a role in the plan-store fixture

When SILO_TEST_DATABASE_URL points to a database with this migration applied, newPlanstoreFixture still executes INSERT INTO users (username) VALUES ($1) in internal/playback/planstore/postgres_test.go:95. Because role deliberately has no default, setting it NOT NULL makes fixture creation fail with a not-null violation, so TestPostgresPlanStore can no longer run against the current schema; update the fixture to provide a role rather than relying on the environment-dependent skip.

AGENTS.md reference: AGENTS.md:L147-L150

Useful? React with 👍 / 👎.

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: 17650c77-f8e8-4f89-8c48-1f8c50f760be

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Comment @coderabbitai help to get the list of available commands.

users.role is NOT NULL after the integrity migration and deliberately has
no default, so the fixture must provide one.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Verified the Codex P2: newPlanstoreFixture inserted a user without a role, so the DB-gated TestPostgresPlanStore would fail a not-null violation once this migration is applied. Fixed in 5bad725 (the fixture now supplies role = 'user'); this was the only test-file user insert in the tree without a role.

@Quick104 Quick104 changed the title chore(db): add missing user FKs, FK leading indexes, and users role/enabled NOT NULL chore(db): add missing user FKs, FK leading indexes, and users role/enabled NOT NULL [schema-hygiene 2/4] Sep 1, 2026
@Quick104 Quick104 added schema-1.0 1.0 schema hygiene and migration-reset workstream (#888); independent of api-v2 stacked Base is another open PR; merge in stack order named in the body maintenance-window Migration rewrites large tables or holds long locks; needs downtime and a verified backup labels Sep 1, 2026
@Quick104

Copy link
Copy Markdown
Contributor Author

Closing as superseded by the merged schema-hygiene replacement.

@Quick104 Quick104 closed this Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintenance-window Migration rewrites large tables or holds long locks; needs downtime and a verified backup schema-1.0 1.0 schema hygiene and migration-reset workstream (#888); independent of api-v2 stacked Base is another open PR; merge in stack order named in the body

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant