Skip to content

chore(db): widen users, media_files, and media_folders ids to bigint [schema-hygiene 4/4] - #898

Closed
Quick104 wants to merge 3 commits into
schema/hygiene-standardizationfrom
schema/hygiene-bigint-ids
Closed

Quick104 wants to merge 3 commits into
schema/hygiene-standardizationfrom
schema/hygiene-bigint-ids

Conversation

@Quick104

@Quick104 Quick104 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Problem

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

users.id, media_files.id, and media_folders.id are integer, while eight newer foreign-key columns already declare bigint against them (invitations.invited_by, playback_v3_attempts.user_id, page_sections.library_id, and others). The parents are the narrow end of their own references, and the 1.0 squashed baseline should not freeze that inconsistency or the 2^31 ceiling on the three most-referenced identities in the schema.

Base branch: schema/hygiene-standardization (PR #893) — fourth and last of the pre-bridge hygiene PRs; only the top two commits are new here. The three ids are already GENERATED BY DEFAULT AS IDENTITY on that base.

Approach

One migration, 20260901204344_widen_core_ids_to_bigint.sql, alters the three parent columns to bigint. Verified on PostgreSQL 18: the identity sequence type follows the column automatically (integer → bigint, max 9223372036854775807), and reverts on the Down. Per the program plan the scope is the parents only; the migration header lists every integer child column with its rewrite cost so the maintainer can schedule the child sweep separately (Postgres permits int4 → int8 references, so nothing breaks in between).

The Down narrows back to integer behind a guard that reads min(id), max(id), and the sequence position for each table and raises a named error when any value is outside the int4 range. It never truncates.

Go-side changes are limited to what is actually wrong against a bigint id: the media_folders sweep cursor in internal/metadata/artwork_reconcile.go (was int32/ParseInt(..., 32)), and every ::int[] / ::int parameter cast bound against these columns or their children — in internal/catalog/filesplit, internal/scanner/file_repo.go, internal/sections/repo.go, internal/usercollections/listing.go, and (found by a second sweep after review) the eight media_file_id/last_file_id casts in internal/catalog/reattribute/reattribute.go, activity_log.user_id in internal/api/handlers/admin.go, and library_id casts in internal/catalog/library_collection_repo.go and internal/userstore/pgstore/setting_values.go. Ids are int everywhere else (fine on 64-bit); jellycompat encodes as uint64; the plugin SDK already uses int64. The remaining ::int/::integer casts in the tree were classified one by one: row counts, season/episode numbers, ordinals, locked-field enums, and NULL::int placeholders — none bind an id. Output-side casts on still-integer child columns (literaryworks, search_indexer, library_collection_repo array scans) and four int4 advisory-lock sites that narrow users.id are listed in the migration header for the child sweep.

internal/catalog/reattribute/reattribute_bigint_db_test.go (gated on SILO_TEST_DATABASE_URL) runs a real reattribution with a media_files id of 3,000,000,000 in the moved-file set and proves the subset queries accept it; it fails against the pre-fix code with pgx's unable to encode []int{3000000000, ...} into binary format for _int4.

migrations/widen_core_ids_to_bigint_test.go pins the three ALTERs, both guard bounds, and that no child is widened. internal/database/widen_core_ids_downguard_test.go (gated on SILO_TEST_DATABASE_URL, same skip convention as the neighbouring tests) proves the Down refuses an id above 2^31 and one below -2^31, and succeeds once they are removed.

Maintenance-window note (for the release notes)

This migration rewrites users, media_files, and media_folders (table plus every index: 3 tables, 28 indexes) and holds ACCESS EXCLUSIVE on every relation that references them — for users that is nearly every table in the schema, including the date-partitioned activity_log and operational_logs — for the duration. Children are not rewritten, but each referencing table is sequentially scanned once to revalidate its foreign key. Proportional to media_files row count × its 89 columns; needs free disk for a second copy plus index rebuilds. Raise SILO_MIGRATE_TIMEOUT above its 20-minute default on large libraries (the three ALTERs share one transaction, so a timeout aborts cleanly with nothing changed). A verified backup is required per docs/release-versioning.md. The generic operator guidance now lives in docs/wiki/deployment/docker.md ("Backups and updates").

Validation

  • Full chain from empty (pgvector pg18): applied; down to 20260901180726 and re-up: clean.
  • Widening test: rows seeded with FK children on each parent; after the migration every FK validates, every index is valid, sequence types are bigint; explicit ids above 2^31 inserted into each parent and into a bigint child FK succeed.
  • Down guard: with an out-of-range id present (above and below range) the Down raises the named error and the column stays bigint; after removal the Down succeeds and re-Up restores head. Reproduced independently by the destructive-safety reviewer on its own scratch DB.
  • make migrate-validate, 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 (includes the contract test). DB-gated TestMigrateDownToRefusesOutOfRangeCoreIDs run against a scratch database: pass.
  • Web: pnpm run lint, format:check, build, make test-web: pass. make verify-settings-bindings-all, verify-playback-fixtures, verify-local-paths: pass.

Risks

  • The rewrite window above. Mixed-version replicas during the migration are unsupported, as for the rest of this stack.
  • A pre-existing DB-gated failure, internal/catalog TestEpisodeSearchPostgresAndDocumentSource, reproduces at the base commit and is unrelated.

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-fable-5 (implementation, orchestration, 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 lenses (destructive-safety at maximum effort, Go type safety, migration discipline, test adequacy). Round 1 found the Down guard missed negative ids and that the header carried install-specific figures, and asked for an operator note and a DB-gated guard test; all applied. Round 2 (destructive-safety, closure/discipline) came back clean.

Quick104 and others added 2 commits September 1, 2026 18:11
…rite window

Adds the min(id) refusal to the Down guard, removes install-specific
figures from the migration header, lists the int4 advisory-lock follow-ups,
adds the operator note on large-table rewrites, and adds a DB-gated test
that the Down refuses out-of-range ids in both directions.

Co-Authored-By: Claude Fable 5 <[email protected]>
@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: c6efc34e-e817-4055-aecb-e9bb2fd5a9f6

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-02T01:04:31.607395Z f04a935 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: cfcedf13bc

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

updated_at = NOW()
WHERE content_id = $2
AND id = ANY($3::int[])
AND id = ANY($3::bigint[])

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 Carry bigint IDs through file reattribution

When a media_files.id exceeds the old int4 ceiling, this update succeeds, but the unconditional reattribute.Run call later passes the same IDs into internal/catalog/reattribute/reattribute.go, where every subset query still casts them to ::int[] (for example, lines 352 and 472–473). PostgreSQL therefore raises integer out of range even when no child-state row exists, rolling back admin splits and anchored-identity repairs for precisely the large IDs this migration now permits; use bigint arrays throughout the reattribution predicates.

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

Useful? React with 👍 / 👎.

@Quick104 Quick104 changed the title chore(db): widen users, media_files, and media_folders ids to bigint chore(db): widen users, media_files, and media_folders ids to bigint [schema-hygiene 4/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
Widens the ::int[] parameter casts still bound against media_files.id,
media_folders.id, and users.id in reattribute, admin activity, library
collections, and setting values, and adds a DB-gated test that
reattribution accepts a media_files id above the int4 range.

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

Quick104 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Verified the Codex P2 and it was right — the original cast sweep was incomplete. Fixed in f04a935, with a full classified sweep this time rather than only the cited lines.

Changed to ::bigint[] (bound against a widened id or a child of one): the eight media_file_id/last_file_id casts in internal/catalog/reattribute/reattribute.go (lines 352, 363, 375, 410, 426, 438, 472, 473); activity_log.user_id in internal/api/handlers/admin.go:652; library_collection_libraries.library_id in internal/catalog/library_collection_repo.go:614; user_setting_values.library_id in internal/userstore/pgstore/setting_values.go:116.

Left alone, with reason: every other ::int/::integer/::int[] in non-test Go is a row count, season/episode number, ordinal, runtime, locked-field enum, or NULL::int UNION placeholder — not an id. Output-side casts on still-integer child columns (literaryworks/repository.go MIN(media_folder_id)::int, the ARRAY[]::integer[] defaults scanned into []int32 in search_indexer.go and library_collection_repo.go) and the four int4 advisory-lock sites are correct until the child columns widen and are already listed in the migration header for that sweep.

Note on the symptom: with pgx the failure is client-side at encode time (unable to encode []int{3000000000, ...} into binary format for _int4), not a server integer out of range; same defect. A DB-gated test (reattribute_bigint_db_test.go) now exercises reattribute.Run with a 3,000,000,000 file id through all eight sites; it fails before the fix and passes after. Full gate re-run green (build, vet, lint 0 issues, make test-go, verify targets, DB-gated tests on a scratch database).

@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