Skip to content

chore(db): convert serial ids to identity, widen notification varchars, rename tables [schema-hygiene 3/4] - #893

Closed
Quick104 wants to merge 1 commit into
schema/hygiene-integrityfrom
schema/hygiene-standardization
Closed

Quick104 wants to merge 1 commit into
schema/hygiene-integrityfrom
schema/hygiene-standardization

Conversation

@Quick104

@Quick104 Quick104 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Problem

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

Before the 1.0 schema baseline freezes the shape of every table, three inconsistencies are still cheap to fix: 32 id columns use legacy serial defaults while 20 newer tables already use identity columns; the notifications/push tables carry 14 varchar(n) columns whose limits the application already enforces (and duplicates) in Go; and three tables break the schema's naming convention (oauth_session, oauth_completion singular in a plural schema; playback_history_admin puts the scope qualifier last where every sibling — admin_jobs, admin_dashboard_layouts, user_watch_history — puts it first).

Base branch: schema/hygiene-integrity (PR #889) — third PR in the schema-hygiene stack; only the top commit is new here.

Approach

Three migrations, lists derived empirically from a migrated scratch database (audit queries in the migration comments):

  1. 20260901180714_serial_ids_to_identity.sql — converts the 32 serial id columns (36 with the four activity_log partitions that inherit) to GENERATED BY DEFAULT AS IDENTITY. BY DEFAULT keeps serial parity: explicit-id inserts (used by tests and id-carrying restores) keep working. One DO loop handles every table through a single code path: lock via DROP DEFAULT, read the old sequence position, drop it, add identity, setval the new sequence — so no table can restart at 1. The Down mirrors it (recreating the sequence AS <column type>) and takes an explicit ACCESS EXCLUSIVE lock before reading the position.
  2. 20260901180715_notification_varchar_to_text.sql — the 14 varchar(n) columns to text; metadata-only (relfilenodes verified unchanged). Every length rule survives in Go (validateChannelName ≤64, device_id ≤128, left($n, 256) on failure messages, etc.); no code depends on SQLSTATE 22001.
  3. 20260901180726_rename_tables_for_consistency.sql — oauth_session → oauth_sessions, oauth_completion → oauth_completions, playback_history_admin → admin_playback_history, with every index/constraint renamed and a catalog-driven sweep for the named NOT NULL constraints Postgres 18 leaves behind on RENAME TABLE (no-op on older servers). All Go, test, and doc references updated; repo-wide grep clean.

Encryption safety of the renames (checked before any rename stood): secret.RowAAD has no call site on these tables; oauth_completion.token_ciphertext derives its key from a fixed label and uses code_hash as AAD — no table identifier anywhere. Proven by a survival test: a token encrypted into oauth_completion decrypts through the real GetAndDeleteCompletion path after the rename.

Frozen-v1 wire check: the touched web widget and docs/admin-api.md edits are comment/prose only; no JSON field, query parameter, or TS type carried the old table name. No /api/v1 wire change.

migrations/schema_standardization_test.go pins the 32-table list in both directions, the BY DEFAULT choice, the ordered continuity steps, the 14 columns with their restore lengths, the rename pairs with every index/constraint rename, and the NOT NULL sweep — mutation-tested (20 mutations, all caught).

Validation

  • Full chain from empty (pgvector pg18): 364 versions applied; migrate-down-to 20260901161702 then re-up clean; each migration cycled down/up individually; goose validate clean.
  • Sequence continuity: rows seeded across users (with a deleted-row gap), media_files, activity_log, task_triggers, stream_nodes, plus advanced-but-empty sequences and an uncalled one; the 46-sequence snapshot was byte-identical across Up and Down; post-Up/post-Down/re-Up inserts continued without collision. Independently reproduced by the destructive-safety reviewer.
  • Encrypted-row survival across the rename: pass (above).
  • make embed-stub, go build ./..., gofmt (empty), go vet: pass. golangci-lint run --new-from-merge-base="origin/main": 0 issues.
  • make test-go: all ok. Web: pnpm run lint, format:check, build, make test-web: pass.
  • make verify-settings-bindings-all, verify-playback-fixtures, verify-local-paths: pass.
  • Focused DB-gated runs with SILO_TEST_DATABASE_URL on the scratch DB: internal/auth, internal/catalog/reattribute, internal/metadata, internal/api, internal/api/handlers: pass.

Risks

  • The identity conversion takes ACCESS EXCLUSIVE per table for a catalog-only change (no rewrite); brief, but it is a maintenance-window migration like the rest of the stack.
  • Renames are all-or-nothing within one transaction; the Down reverses them and the NOT NULL sweep.
  • Two pre-existing failures noted, not introduced or fixed here: internal/notifications push-device tests (their TEMP shadow table lacks fcm_token_ciphertext) and internal/catalog TestEpisodeSearchPostgresAndDocumentSource. Both reproduce at the base commit.

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 (initial draft), claude-fable-5 (draft verification and completion, orchestration, all review agents)
  • Involvement: Fully AI-generated; maintainer review pending (opened by the orchestrating agent under the maintainer's program instruction)
  • Adversarial review: four independent blind lenses (destructive-safety/encryption at maximum effort, migration discipline, rename-and-wire correctness, test adequacy). One major found and fixed: the Down read the sequence position before taking the table lock (fixed with an explicit lock). Two minors: cosmetic edits to two already-dead notification tests were reverted; a DB-gated continuity test was deferred in favor of the text-pinned contract test. Discipline and rename/wire lenses were clean.

@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: ddbb0bec-1aee-4978-ae99-e04f27862cf4

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.

@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-01T20:35:01.754505Z 87fdda6 New commits
ℹ️ 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: e2f9e521a6

ℹ️ 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".

-- ALTER TABLE ... RENAME does not rename the indexes and constraints that were
-- named after the table, so each one is renamed explicitly; leaving them would
-- trade one inconsistency for a worse one.
ALTER TABLE public.oauth_session RENAME TO oauth_sessions;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve old table names through rolling upgrades

In a multi-replica integrated/API deployment, the first new replica applies this rename while the old replicas are still serving, because cmd/silo/main.go runs migrations during each new primary replica's startup without stopping existing application traffic. Those old replicas continue issuing SQL against oauth_session, oauth_completion, and playback_history_admin, so new or uncached statements fail with relation does not exist; this breaks OAuth flows and can lose finalized playback-history writes for the rest of the rollout, rather than only during the brief migration lock. Keep compatibility views for the old names or perform the rename as an expand/contract change across releases.

AGENTS.md reference: AGENTS.md:L12-L17

Useful? React with 👍 / 👎.

…s, rename tables

Converts 32 serial id columns to GENERATED BY DEFAULT AS IDENTITY with
sequence continuity in both directions, widens the 14 varchar(n) columns in
the notifications/push tables to text, and renames oauth_session,
oauth_completion, and playback_history_admin to schema-consistent names.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 force-pushed the schema/hygiene-standardization branch from e2f9e52 to 87fdda6 Compare September 1, 2026 20:31
@Quick104

Quick104 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Re the Codex P1 (preserve old table names through rolling upgrades): verified the mechanics — the first upgraded primary applies the rename at startup while any not-yet-upgraded replica keeps issuing SQL against the old names — and declining the compatibility-view/expand-contract approach with reasons, same as the drop migration in #879:

  • Mixed-version API replicas during a migration have never been supported for any shape-changing migration in this chain (drops, NOT NULL, renames all fail the same way), and the documented posture is a verified-backup maintenance-window update (docs/release-versioning.md Backups and rollback; docs/wiki/deployment/docker.md Backups and updates), not a zero-downtime rolling upgrade of API replicas.
  • The rename is a single transaction, so the switch is atomic: an old replica fails closed with relation does not exist rather than writing to a wrong table. OAuth sessions are short-lived and restart cleanly; playback history writes on an old replica error rather than being silently lost.
  • Compatibility views would have to be carried into the squashed 1.0 baseline or removed by yet another migration inside the bridge, working against the point of this workstream (a clean schema before the bridge freeze).

If the maintainer prefers expand/contract for renames specifically, the alternative is to ship the Go-side dual-name support one release before the rename; happy to restructure. Recorded on #888.

@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: 87fdda6223

ℹ️ 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".

ALTER TABLE public.oauth_session RENAME TO oauth_sessions;
ALTER INDEX public.oauth_session_pkey RENAME TO oauth_sessions_pkey;
ALTER INDEX public.oauth_session_expires_idx RENAME TO oauth_sessions_expires_idx;

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 Rename the primary-key constraints, not only their indexes

On PostgreSQL, ALTER INDEX ... RENAME changes the backing index name but leaves the associated primary-key constraint's pg_constraint.conname unchanged. After this migration, all three tables therefore retain old constraint names such as oauth_session_pkey, so later migrations referring to the expected oauth_sessions_pkey constraint will fail. Use ALTER TABLE ... RENAME CONSTRAINT in both directions; PostgreSQL will rename the backing index with it.

Useful? React with 👍 / 👎.

@Quick104

Quick104 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Re the Codex P2 (rename the primary-key constraints, not only their indexes): verified and dismissed as incorrect for PostgreSQL. ALTER INDEX ... RENAME on an index that backs a UNIQUE / PRIMARY KEY / EXCLUDE constraint renames the constraint as well (PostgreSQL docs, ALTER INDEX, RENAME form). Reproduced on the deployed engine version:

PostgreSQL 18.6
CREATE TABLE t(id int PRIMARY KEY, u text UNIQUE);
ALTER INDEX t_pkey RENAME TO t2_pkey; ALTER INDEX t_u_key RENAME TO t2_u_key;
SELECT conname, conindid::regclass FROM pg_constraint WHERE conrelid='t'::regclass;
   conname  |  index
 t2_pkey    | t2_pkey
 t2_u_key   | t2_u_key

And on the scratch database after this migration ran, pg_constraint reports oauth_sessions_pkey, oauth_completions_pkey, and admin_playback_history_pkey as the constraint names. The catalog-driven sweep in the migration exists for the one thing RENAME TABLE and ALTER INDEX RENAME do leave behind on PG 18: the named NOT NULL constraints.

@Quick104 Quick104 changed the title chore(db): convert serial ids to identity, widen notification varchars, rename tables chore(db): convert serial ids to identity, widen notification varchars, rename tables [schema-hygiene 3/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 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

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