{"record":{"id":"0da7d512758df9d2","repo":"invoke-ai/InvokeAI","slug":"database-contains-inconsistent-applied-migration-s-0da7d5","errorCode":null,"errorMessage":"Database contains inconsistent applied migration state: {migration_id} is recorded with legacy version {legacy_version}, expected {migration.to_version}","messagePattern":"Database contains inconsistent applied migration state: (.+?) is recorded with legacy version (.+?), expected (.+?)","errorType":"exception","errorClass":"MigrationError","httpStatus":null,"severity":"error","filePath":"invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py","lineNumber":253,"sourceCode":"                raise MigrationError(f\"Database contains unknown legacy migration version: {legacy_version}\")\n\n    def _validate_existing_applied_legacy_migrations(self, cursor: sqlite3.Cursor) -> None:\n        \"\"\"Validates applied IDs for legacy migrations against legacy numeric rows.\"\"\"\n        registered_migrations = self._migration_set.migrations_by_id\n        cursor.execute(\"SELECT migration_id, legacy_version FROM applied_migrations;\")\n        applied_rows = cursor.fetchall()\n\n        cursor.execute(\"SELECT version FROM migrations WHERE version > 0;\")\n        legacy_versions = {row[0] for row in cursor.fetchall()}\n\n        for row in applied_rows:\n            migration_id = row[0]\n            legacy_version = row[1]\n            migration = registered_migrations[migration_id]\n            if migration.to_version is None:\n                continue\n            if legacy_version != migration.to_version:\n                raise MigrationError(\n                    \"Database contains inconsistent applied migration state: \"\n                    f\"{migration_id} is recorded with legacy version {legacy_version}, \"\n                    f\"expected {migration.to_version}\"\n                )\n            if legacy_version not in legacy_versions:\n                raise MigrationError(\n                    \"Database contains inconsistent applied migration state: \"\n                    f\"{migration_id} is applied, but legacy version {legacy_version} is missing\"\n                )\n\n    def _needs_applied_migrations_bootstrap(self, cursor: sqlite3.Cursor) -> bool:\n        \"\"\"Checks whether legacy numeric rows need to be written to applied_migrations.\"\"\"\n        cursor.execute(\"SELECT version FROM migrations WHERE version > 0;\")\n        legacy_versions = {row[0] for row in cursor.fetchall()}\n        if len(legacy_versions) == 0:\n            return False\n\n        cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='applied_migrations';\")","sourceCodeStart":235,"sourceCodeEnd":271,"githubUrl":"https://github.com/invoke-ai/InvokeAI/blob/0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py#L235-L271","documentation":"A migration recorded in applied_migrations carries a legacy_version that does not match the to_version declared by its registered Migration. The two migration bookkeeping stores disagree, so the migrator halts to avoid applying migrations on top of inconsistent state.","triggerScenarios":"run_migrations() -> _validate_existing_applied_legacy_migrations: for an applied row, migration.to_version is not None and legacy_version != migration.to_version.","commonSituations":"The applied_migrations or migrations table was hand-edited; a partially failed/aborted migration run left rows partially updated; the DB was copied mid-migration or modified by a different app version.","solutions":["Restore the database from a backup taken before the corruption.","Correct the mismatched legacy_version value in applied_migrations to match the expected to_version, after verifying the actual schema state.","Delete both stores and re-initialize the database if it is disposable (e.g. regenerate the DB and re-import models)."],"exampleFix":"// before: hand-edited row disagrees\n-- applied_migrations: ('migration_4', 3)\n// after: align with the migration's declared to_version\nUPDATE applied_migrations SET legacy_version = 4 WHERE migration_id = 'migration_4';","handlingStrategy":"validation","validationCode":"import sqlite3\nconn = sqlite3.connect(db_path)\nrows = conn.execute(\n    \"SELECT migration_id, legacy_version FROM applied_migrations WHERE legacy_version IS NOT NULL\"\n).fetchall()\nfor mid, lv in rows:\n    print(mid, lv)  # cross-check each against the migration's declared to_version before launching","typeGuard":null,"tryCatchPattern":"try:\n    migrator.run_migrations()\nexcept MigrationError as e:\n    if \"inconsistent applied migration state\" in str(e):\n        # restore from backup rather than patching live\n        raise SystemExit(f\"Restore DB from backup: {e}\")\n    raise","preventionTips":["Never hand-edit the migrations or applied_migrations tables.","Take a DB backup before any manual schema intervention.","Avoid killing the process during a migration run.","Copy the whole DB file, never individual tables, when moving installs."],"tags":["database","sqlite","migration","data-corruption"],"backgroundTag":"migration-state-inconsistent","analyzedSha":"0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06","analyzedAt":"2026-08-29T04:46:49.967Z","schemaVersion":2},"datasetVersion":"2026-08-29T07:17:48.351Z"}