{"record":{"id":"a421f31b0c501763","repo":"invoke-ai/InvokeAI","slug":"database-is-at-version-version-expected-expect","errorCode":null,"errorMessage":"Database is at version {version}, expected {expected}","messagePattern":"Database is at version (.+?), expected (.+?)","errorType":"exception","errorClass":"MigrationError","httpStatus":null,"severity":"critical","filePath":"invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py","lineNumber":101,"sourceCode":"        if self._db._db_path is not None:\n            timestamp = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n            self._backup_path = self._db._db_path.parent / f\"{self._db._db_path.stem}_backup_{timestamp}.db\"\n            self._logger.info(f\"Backing up database to {str(self._backup_path)}\")\n            with closing(sqlite3.connect(self._backup_path)) as backup_conn:\n                self._db._conn.backup(backup_conn)\n        else:\n            self._logger.info(\"Using in-memory database, no backup needed\")\n\n    def _run_migration(self, migration: Migration) -> None:\n        \"\"\"Runs a single migration.\"\"\"\n        try:\n            # Using sqlite3.Connection as a context manager commits a the transaction on exit, or rolls it back if an\n            # exception is raised.\n            with self._db._conn as conn:\n                cursor = conn.cursor()\n                self._create_applied_migrations_table(cursor)\n                if migration.from_version is not None and self._get_current_version(cursor) != migration.from_version:\n                    raise MigrationError(\n                        f\"Database is at version {self._get_current_version(cursor)}, expected {migration.from_version}\"\n                    )\n                self._logger.debug(f\"Running migration '{migration.id}'\")\n\n                # Run the actual migration\n                migration.callback(cursor)\n\n                if migration.to_version is not None:\n                    cursor.execute(\"INSERT INTO migrations (version) VALUES (?);\", (migration.to_version,))\n                cursor.execute(\n                    \"INSERT INTO applied_migrations (migration_id, legacy_version) VALUES (?, ?);\",\n                    (migration.id, migration.to_version),\n                )\n\n                self._logger.debug(f\"Successfully ran migration '{migration.id}'\")\n        # We want to catch *any* error, mirroring the behaviour of the sqlite3 module.\n        except Exception as e:\n            # The connection context manager has already rolled back the migration, so we don't need to do anything.","sourceCodeStart":83,"sourceCodeEnd":119,"githubUrl":"https://github.com/invoke-ai/InvokeAI/blob/0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py#L83-L119","documentation":"_run_migration wraps each migration in a transaction and verifies the database's current user_version matches the migration's declared from_version before executing. If the DB is at a different version, the migration's assumptions are violated and a MigrationError is raised, aborting (and rolling back) the migration.","triggerScenarios":"run_migrations applying a migration whose from_version is set but the sqlite PRAGMA user_version differs — e.g. DB already partially migrated, migrated by a different version, or starting from a non-zero DB created elsewhere.","commonSituations":"Running an older InvokeAI binary against a DB migrated by a newer one; restoring an old DB snapshot mid-migration; copying a DB between installs with divergent histories.","solutions":["Bring the InvokeAI install to the version matching the DB's migration state","Restore a DB backup whose version matches the expected from_version","Check PRAGMA user_version on the DB and confirm which build should run it","Back up the DB before retrying migrations"],"exampleFix":"# inspect version\nsqlite3 /data/invokeai/invokeai.db 'PRAGMA user_version;'\n# before: running mismatched build\n# after: upgrade so app version == db version\npip install -U invokeai && invokeai-web --root /data/invokeai","handlingStrategy":"try-catch","validationCode":"import sqlite3\ncursor = sqlite3.connect(db_path).cursor()\nversion = cursor.execute(\"PRAGMA user_version\").fetchone()[0]\nassert version == expected_from_version, f\"db at {version}, migration expects {expected_from_version}\"","typeGuard":null,"tryCatchPattern":"try:\n    services.run_migrations()\nexcept MigrationError as e:\n    if \"expected\" in str(e) and \"Database is at version\" in str(e):\n        logger.critical(\"Version mismatch between app and DB: %s\", e)\n        raise\n    raise","preventionTips":["Back up the DB before running migrations","Keep the InvokeAI build version aligned with the DB history","Verify PRAGMA user_version when restoring DB snapshots"],"tags":["database","migrations","sqlite"],"backgroundTag":"migration-version-mismatch","analyzedSha":"0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06","analyzedAt":"2026-08-29T04:46:49.967Z","schemaVersion":2},"datasetVersion":"2026-08-29T07:17:48.351Z"}