# 2.20.0 — File data storage object foreign key Runbook for the release that moves the file data storage pointer out of `file_data.metadata->>'storage-ref-id'` and into a column, `file_data.storage_object_id`, with a foreign key to `storage_object(id)`. ## When to run this The migration `0159-add-file-data-storage-object-id` does the whole job on a fresh database and on small instances: it adds the column, backfills the pointer, creates the index and the foreign key. A large instance builds everything online and keeps the stopped window as short as possible: - the column, the index and the foreign key are built online, without stopping the service; - the backfill runs in the stopped window **only if** the metadata pointer exists; when the storage backend was never enabled there is nothing to backfill and the new binaries roll out like any other deploy; - the step is then marked as applied in the `migrations` table, so the migration body does not run at startup. The coordinated restart is required only when the instance uses the storage backend (`PENPOT_FILE_DATA_BACKEND=storage`) or still has rows that carry the metadata pointer. The previous code writes and reads `metadata.storage-ref-id`, the new code reads the column, and a rolling deploy would mix both. With the default `db` backend and no row carrying the pointer (see the pre-flight query), the previous and the new code read the same `file_data.data` column, so a rolling deploy is safe. **Do not run the backfill while the previous version is serving** when `PENPOT_FILE_DATA_BACKEND` is configured to `storage`, or when the table still has rows with the metadata pointer. The previous code writes the pointer only to `metadata.storage-ref-id`, and its storage GC reads the reference from there. Removing the key while that code runs leaves the rows it writes without a pointer (unreadable after the deploy), and it can make the GC delete an object that a live row still references. When the pre-flight query returns 0 there is nothing to backfill and this risk does not apply. ## 0. Pre-flight ```sql SELECT version(); -- 16.x: `NOT VALID` foreign keys on a partitioned table need 18 SELECT count(*) FROM pg_inherits WHERE inhparent = 'file_data'::regclass; -- 16 -- Whether the storage backend was ever enabled. When this is 0 there is no -- pointer in the metadata and step 6 is skipped. SELECT count(*) FROM file_data WHERE backend = 'storage' AND jsonb_exists(metadata, 'storage-ref-id'); -- Every online ALTER uses a short lock timeout and is retried, so a long -- transaction cannot make it queue and block the table behind it. SELECT pid, state, now() - xact_start AS age, left(query, 60) FROM pg_stat_activity WHERE xact_start IS NOT NULL AND now() - xact_start > interval '1 minute'; ``` ## 1. Column ```sql BEGIN; SET LOCAL lock_timeout = '3s'; ALTER TABLE file_data ADD COLUMN storage_object_id uuid NULL; COMMIT; ``` Skip this step if the column already exists. The change is catalog-only (a nullable column without a default), so it takes `ACCESS EXCLUSIVE` for an instant. If it fails with `lock timeout`, wait for a quieter moment and retry: it did not block anything. ## 2. One index per partition, concurrently ```sql CREATE INDEX CONCURRENTLY file_data_00__storage_object_id__idx ON file_data_00 (storage_object_id); -- ... up to file_data_15 ``` Run each statement in autocommit: `CREATE INDEX CONCURRENTLY` cannot run inside a transaction block. An interrupted build leaves the index `INVALID`: drop it and retry. ```sql SELECT c.relname, i.indisvalid FROM pg_index AS i JOIN pg_class AS c ON c.oid = i.indexrelid WHERE c.relname LIKE 'file_data_%storage_object_id%' ORDER BY c.relname; ``` ## 3. Parent index and partition attachment ```sql CREATE INDEX file_data__storage_object_id__idx ON ONLY file_data (storage_object_id); ALTER INDEX file_data__storage_object_id__idx ATTACH PARTITION file_data_00__storage_object_id__idx; -- ... up to file_data_15 ``` The step creates the index unconditionally: if an index with that name already exists, drop it and rebuild it. Verify the result before continuing: ```sql SELECT i.indisvalid, i.indpred IS NULL AS plain, i.indexprs IS NULL AS no_expression FROM pg_index AS i WHERE i.indexrelid = 'file_data__storage_object_id__idx'::regclass; -- t | t | t SELECT count(*) FROM pg_inherits WHERE inhparent = 'file_data__storage_object_id__idx'::regclass; -- 16 ``` ## 4. Foreign key, online ```sql BEGIN; SET LOCAL lock_timeout = '3s'; ALTER TABLE file_data ADD CONSTRAINT file_data_storage_object_id_fkey FOREIGN KEY (storage_object_id) REFERENCES storage_object(id) ON DELETE NO ACTION DEFERRABLE INITIALLY IMMEDIATE; COMMIT; ``` The column is NULL until step 6, so the validation finds nothing to check and the `SHARE ROW EXCLUSIVE` lock (it blocks writes, not reads) is brief. Retry on `lock timeout`. If the constraint already exists, do not add it again: verify its shape with the query in step 7. Drop it first only if the shape is wrong. Creating it here, before the backfill, keeps the full validation scan out of the stopped window: the backfill validates each row it writes. `INITIALLY IMMEDIATE` is required. The storage GC catches the violation inside the chunk transaction and retries the chunk; an `INITIALLY DEFERRED` check fires at commit, outside that transaction, and the GC would never move past a blocked chunk. ## 5. Stop every instance Coordinated restart when the pre-flight count is not 0: stop all of them before the next step. No rolling deploy. When the count is 0 there is nothing to backfill: run steps 1-4 online, run the verification (step 7) and mark the step as applied (step 8) without stopping the service. ## 6. Backfill, only if the metadata pointer exists Skip this step when the pre-flight count is 0: the storage backend was never enabled, no row carries the pointer, and the new code reads all file data from the `data` column. ```sql WITH candidates AS MATERIALIZED ( SELECT file_id, id, (metadata->>'storage-ref-id')::uuid AS soid FROM file_data WHERE backend = 'storage' AND storage_object_id IS NULL AND (metadata->>'storage-ref-id') ~* '^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$' ) UPDATE file_data AS fd SET storage_object_id = c.soid, metadata = fd.metadata - 'storage-ref-id' FROM candidates AS c WHERE fd.file_id = c.file_id AND fd.id = c.id AND EXISTS (SELECT 1 FROM storage_object AS so WHERE so.id = c.soid); ``` The `MATERIALIZED` CTE keeps the uuid cast away from values that did not pass the regex: without it PostgreSQL can inline the subquery and cast a corrupt value, aborting the statement. The foreign key already exists, so every written row is validated here instead of in a separate full scan. ## 7. Verify Do not mark the migration as applied until every check passes. ```sql -- Column. SELECT data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'file_data' AND column_name = 'storage_object_id'; -- uuid | YES -- Rows that will be unreadable. Must be 0. The backfill only fills pointers it -- can resolve, so a non-zero count means pointers that were already corrupt or -- orphan: inspect them and accept them before continuing. With the backfill -- skipped this must still be 0, or the storage backend was enabled after all. -- A row pointing at a storage_object with deleted_at set is legitimate and -- restorable, not unreadable: the backfill fills it on purpose and the -- restore flow revives the object, so it is not counted here. SELECT count(*) FROM file_data WHERE backend = 'storage' AND storage_object_id IS NULL; -- Index: valid, plain, with every partition attached. SELECT i.indisvalid, i.indpred IS NULL AS plain, i.indexprs IS NULL AS no_expression FROM pg_index AS i WHERE i.indexrelid = 'file_data__storage_object_id__idx'::regclass; SELECT count(*) FROM pg_inherits WHERE inhparent = 'file_data__storage_object_id__idx'::regclass; -- 16 -- Foreign key: deferrable, checked immediately, no action, validated. SELECT condeferrable, condeferred, confdeltype, convalidated FROM pg_constraint WHERE conname = 'file_data_storage_object_id_fkey' AND conrelid = 'file_data'::regclass; -- t | f | a | t ``` ## 8. Mark the migration as applied Only after step 7 passes: ```sql INSERT INTO migrations (module, step) VALUES ('main', '0159-add-file-data-storage-object-id') ON CONFLICT (module, step) DO NOTHING; ``` Check it: ```sql SELECT module, step, created_at FROM migrations WHERE module = 'main' AND step = '0159-add-file-data-storage-object-id'; ``` The row is the only thing that skips the migration at startup. Without it, the migration runs at the next start and repeats the backfill and the foreign key. ## 9. Start the new instances Start every instance you stopped in step 5. When the pre-flight count was 0 nothing was stopped, and the rolling deploy simply finishes. ## Post-deploy checks ```sql SELECT conname, condeferrable, condeferred, confdeltype, convalidated FROM pg_constraint WHERE conname = 'file_data_storage_object_id_fkey'; SELECT count(*) FROM file_data WHERE backend = 'storage' AND storage_object_id IS NULL; -- The delete check must use the index, not a sequential scan. BEGIN; EXPLAIN (ANALYZE, BUFFERS) DELETE FROM storage_object WHERE id = ''; ROLLBACK; ``` ## Rollback Before step 8: ```sql ALTER TABLE file_data DROP CONSTRAINT IF EXISTS file_data_storage_object_id_fkey; -- A partitioned index cannot be dropped with CONCURRENTLY; the plain drop -- takes a brief ACCESS EXCLUSIVE. DROP INDEX file_data__storage_object_id__idx; ALTER TABLE file_data DROP COLUMN storage_object_id; ``` After step 8 the backfill has already removed the metadata key that the previous code reads, so a rollback to the previous binaries is **not supported** when the instance uses the storage backend: the files offloaded by the new code would be unreadable, and the recovery is a data restore, not a binary switch. With the default `db` backend and no storage rows, the previous binaries read the same `data` column and the rollback is a plain binary switch.