From d95ca18d4ac272a24f066ec677525c898009d337 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 23 Jul 2026 21:51:58 -0400 Subject: [PATCH] fix(backend): make roms_facets/collection migrations idempotent MariaDB/MySQL auto-commit each DDL statement, so a failure partway through 0100/0101/0103 committed the CREATE TABLE / ADD COLUMN but never advanced alembic_version. Every reboot then re-ran the migration from the top and died on "Table ... already exists", wedging the boot loop permanently. Guard the schema changes so a re-run after a partial failure recovers: - 0100: CREATE TABLE ... if_not_exists, catalog-check the index, make the backfill idempotent with an anti-join, DROP TRIGGER IF EXISTS before each CREATE TRIGGER (both MySQL and Postgres paths). - 0101: same treatment; backfill uses INSERT IGNORE / ON CONFLICT DO NOTHING, triggers dropped before recreation, view already drops first. - 0103: skip add_column for provider ids that are already present. 0102 already used if_not_exists / catalog checks; this brings the rest of the batch in line. Verified by reproducing the wedged state (version at 0099 with the later tables already present) and confirming upgrade head now recovers cleanly to 0103, plus the rom_facets and stats test suites. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../versions/0100_roms_facets_table.py | 24 +++++++++++--- .../versions/0101_virtual_collection_roms.py | 32 ++++++++++++++++--- .../versions/0103_roms_facets_provider_ids.py | 10 +++++- 3 files changed, 55 insertions(+), 11 deletions(-) diff --git a/backend/alembic/versions/0100_roms_facets_table.py b/backend/alembic/versions/0100_roms_facets_table.py index d47425de6..187d01c22 100644 --- a/backend/alembic/versions/0100_roms_facets_table.py +++ b/backend/alembic/versions/0100_roms_facets_table.py @@ -20,6 +20,7 @@ Create Date: 2026-07-22 00:00:00.000000 import sqlalchemy as sa from alembic import op # type: ignore[attr-defined] +from sqlalchemy import inspect from utils.database import CustomJSON, is_postgresql @@ -48,11 +49,12 @@ _MIRRORED_COLUMNS = [ _TARGET_COLUMNS = ", ".join(target for target, _ in _MIRRORED_COLUMNS) _SOURCE_COLUMNS = ", ".join(source for _, source in _MIRRORED_COLUMNS) -# Backfilled into the empty table before the triggers exist, so no row can -# conflict and no upsert guard is needed. +# Backfilled before the triggers exist. The anti-join keeps it idempotent so a +# re-run after a partial failure only fills the rows that are still missing. _BACKFILL_SQL = ( f"INSERT INTO roms_facets (rom_id, {_TARGET_COLUMNS})\n" # nosec B608 - f"SELECT id, {_SOURCE_COLUMNS} FROM roms" + f"SELECT id, {_SOURCE_COLUMNS} FROM roms\n" + "WHERE id NOT IN (SELECT rom_id FROM roms_facets)" ) _MYSQL_UPSERT_BODY = ( @@ -89,6 +91,11 @@ CREATE TRIGGER roms_facets_sync AFTER INSERT OR UPDATE ON roms def upgrade() -> None: + conn = op.get_bind() + + # Every step is guarded so a re-run after a partial failure recovers cleanly. + # MySQL/MariaDB auto-commit each DDL statement, so a crash mid-migration + # leaves objects behind without advancing the alembic version. op.create_table( "roms_facets", sa.Column( @@ -120,16 +127,23 @@ def upgrade() -> None: server_default=sa.func.now(), nullable=False, ), + if_not_exists=True, ) - op.create_index("idx_roms_facets_platform_id", "roms_facets", ["platform_id"]) + + # MySQL has no CREATE INDEX IF NOT EXISTS, so check the catalog instead. + existing_indexes = {idx["name"] for idx in inspect(conn).get_indexes("roms_facets")} + if "idx_roms_facets_platform_id" not in existing_indexes: + op.create_index("idx_roms_facets_platform_id", "roms_facets", ["platform_id"]) op.execute(_BACKFILL_SQL) - if is_postgresql(op.get_bind()): + if is_postgresql(conn): op.execute(_POSTGRES_SYNC_FN) + op.execute("DROP TRIGGER IF EXISTS roms_facets_sync ON roms") op.execute(_POSTGRES_TRIGGER) else: for name, timing in _MYSQL_TRIGGERS.items(): + op.execute(f"DROP TRIGGER IF EXISTS {name}") op.execute( f"CREATE TRIGGER {name} {timing} ON roms\n" f"FOR EACH ROW\n{_MYSQL_UPSERT_BODY}" diff --git a/backend/alembic/versions/0101_virtual_collection_roms.py b/backend/alembic/versions/0101_virtual_collection_roms.py index 2e4bc36a7..fe38145b2 100644 --- a/backend/alembic/versions/0101_virtual_collection_roms.py +++ b/backend/alembic/versions/0101_virtual_collection_roms.py @@ -32,6 +32,7 @@ Create Date: 2026-07-22 00:00:00.000000 import sqlalchemy as sa from alembic import op # type: ignore[attr-defined] +from sqlalchemy import inspect from utils.database import is_postgresql @@ -186,6 +187,9 @@ def upgrade() -> None: connection = op.get_bind() pg = is_postgresql(connection) + # Every step is guarded so a re-run after a partial failure recovers cleanly. + # MySQL/MariaDB auto-commit each DDL statement, so a crash mid-migration + # leaves objects behind without advancing the alembic version. collation = None if pg else "utf8mb4_general_ci" op.create_table( TABLE, @@ -202,21 +206,39 @@ def upgrade() -> None: sa.Column("updated_at", sa.TIMESTAMP(timezone=True), nullable=False), sa.ForeignKeyConstraint(["rom_id"], ["roms.id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("type", "name", "rom_id"), + if_not_exists=True, ) - op.create_index(f"idx_{TABLE}_rom_id", TABLE, ["rom_id"]) - op.execute( # nosec B608 - f"INSERT INTO {TABLE} ({_COLUMNS})\n" - + (_postgres_rows("r", True) if pg else _mysql_rows("r", True)) - ) + # MySQL has no CREATE INDEX IF NOT EXISTS, so check the catalog instead. + index_name = f"idx_{TABLE}_rom_id" + existing_indexes = { + index["name"] for index in inspect(connection).get_indexes(TABLE) + } + if index_name not in existing_indexes: + op.create_index(index_name, TABLE, ["rom_id"]) + + # The upsert semantics (INSERT IGNORE / ON CONFLICT DO NOTHING) keep the + # backfill idempotent so a re-run only fills the rows still missing. + if pg: + op.execute( # nosec B608 + f"INSERT INTO {TABLE} ({_COLUMNS})\n" + f"{_postgres_rows('r', True)}\nON CONFLICT DO NOTHING" + ) + else: + op.execute( # nosec B608 + f"INSERT IGNORE INTO {TABLE} ({_COLUMNS})\n{_mysql_rows('r', True)}" + ) if pg: op.execute(_postgres_trigger_function()) + op.execute("DROP TRIGGER IF EXISTS virtual_collection_roms_aiu ON roms") op.execute( "CREATE TRIGGER virtual_collection_roms_aiu AFTER INSERT OR UPDATE ON roms\n" "FOR EACH ROW EXECUTE FUNCTION romm_sync_virtual_collection_roms()" ) else: + op.execute("DROP TRIGGER IF EXISTS virtual_collection_roms_ai") + op.execute("DROP TRIGGER IF EXISTS virtual_collection_roms_au") for trigger in _mysql_triggers(): op.execute(trigger) diff --git a/backend/alembic/versions/0103_roms_facets_provider_ids.py b/backend/alembic/versions/0103_roms_facets_provider_ids.py index ae66f910b..111b58642 100644 --- a/backend/alembic/versions/0103_roms_facets_provider_ids.py +++ b/backend/alembic/versions/0103_roms_facets_provider_ids.py @@ -20,6 +20,7 @@ Create Date: 2026-07-23 00:00:00.000000 import sqlalchemy as sa from alembic import op # type: ignore[attr-defined] +from sqlalchemy import inspect from utils.database import is_postgresql @@ -133,8 +134,15 @@ def _backfill_sql() -> str: def upgrade() -> None: + # Guarded so a re-run after a partial failure skips columns already added. + # MySQL/MariaDB auto-commit each DDL, so a mid-migration crash can leave a + # subset of the columns behind without advancing the alembic version. + existing = { + col["name"] for col in inspect(op.get_bind()).get_columns("roms_facets") + } for name, column_type in _PROVIDER_COLUMNS: - op.add_column("roms_facets", sa.Column(name, column_type, nullable=True)) + if name not in existing: + op.add_column("roms_facets", sa.Column(name, column_type, nullable=True)) op.execute(_backfill_sql()) _recreate_triggers(_FULL_MIRRORED_COLUMNS)