Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Add database migration discovery and graph-based precedence (#9319)
Jonathanb831b2de848d
diff --git a/docs/src/content/docs/development/Guides/sqlite-migrations.mdx b/docs/src/content/docs/development/Guides/sqlite-migrations.mdxnew file mode 100644index 0000000000..edc300d630--- /dev/null+++ b/docs/src/content/docs/development/Guides/sqlite-migrations.mdx@@ -0,0 +1,170 @@+---+title: SQLite Database Migrations+lastUpdated: 2026-06-30+---++InvokeAI uses a custom SQLite migrator for the main application database. Migrations live in `invokeai/app/services/shared/sqlite_migrator/migrations/` and are discovered automatically when the database is initialized.++Use a migration when a change modifies persisted database schema or persisted database data in a way that existing installs must receive on startup.++## Naming++New migration modules should use a date-stamped descriptive name:++```text+invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_06_30_add_example_table.py+```++Date-stamped migration modules must expose a `build_migration()` builder:++```py+def build_migration() -> Migration:+ ...+```++The date prefix should be the date the migration is authored or merged, in `YYYY_MM_DD` format. Add a short snake_case description after the date.++Legacy numeric migration modules are still supported:++```text+invokeai/app/services/shared/sqlite_migrator/migrations/migration_33.py+```++Numeric migration modules must expose the matching legacy builder:++```py+def build_migration_33() -> Migration:+ ...+```++The loader discovers both naming styles. Numeric modules are imported in numeric order for legacy compatibility. Date-stamped modules are imported in lexical order, but dependency metadata drives execution order. Non-matching migration module names, missing builders, unknown builder dependencies, and builders that do not return `Migration` fail at startup.++## IDs and Dependencies++Every migration has a stable `id`. For new date-stamped migrations, use the module name without the `migration_` prefix:++```py+id="2026_06_30_add_example_table"+```++The loader enforces this match. If `migration_2026_06_30_add_example_table.py` returns a different ID, startup fails instead of persisting a typo that could later cause the migration to run again.++Existing numeric migrations use IDs matching their file number:++```py+id="migration_33"+```++Legacy numeric migrations that define `from_version` and `to_version` may only depend on other legacy numeric migrations. New migrations should usually be date-stamped graph-only migrations, and should not define legacy versions unless a specific legacy compatibility requirement exists.++For a migration that only needs an older schema point, depend on the migration that introduced the required schema or data:++```py+depends_on="migration_27"+```++New production migrations should always set `depends_on`. Only a true root migration should use `depends_on=None`. A migration with no dependency is considered independently runnable, so omitting `depends_on` for a normal schema or data change can allow it to run before the schema it expects exists.++Dependencies drive execution order. If two migrations both depend on `migration_27`, either may run after `migration_27` unless one explicitly depends on the other. Do not rely on filename or lexical ordering to express a real dependency.++Single-parent dependencies are currently supported. If a migration truly requires two independent branches, add a real dependency between those branches only when that ordering is semantically correct. Otherwise, update the migrator design and tests to support multiple dependencies.++## Template++```py+import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++class AddExampleTableCallback:+ def __call__(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute("ALTER TABLE images ADD COLUMN example TEXT;")+++def build_migration() -> Migration:+ return Migration(+ id="2026_06_30_add_example_table",+ depends_on="migration_32",+ callback=AddExampleTableCallback(),+ )+```++Keep the callback self-contained. It receives an open SQLite cursor and must not commit or roll back the transaction. The migrator commits the migration and records it as applied only after the callback succeeds. If the callback raises, the migration transaction is rolled back and the migration is not recorded.++## Builder Dependencies++Migration builders may request known application dependencies by parameter name. The loader inspects the builder signature and passes only the dependencies requested.++Supported dependency names:++- `app_config` or `config`+- `logger`+- `image_files`++Example:++```py+def build_migration(app_config: InvokeAIAppConfig, logger: Logger) -> Migration:+ return Migration(+ id="2026_06_30_normalize_model_paths",+ depends_on="2026_06_30_add_example_table",+ callback=NormalizeModelPathsCallback(app_config=app_config, logger=logger),+ )+```++Do not use `*args`, `**kwargs`, or positional-only parameters in migration builders.++## Registration++Do not manually import or register migrations in `sqlite_util.py`.++Database initialization builds a `MigrationBuildContext`, discovers migration modules, calls their builders, and registers the resulting `Migration` objects with `SqliteMigrator`.++Manual registration is still available for tests:++```py+migrator.register_migration(Migration(...))+```++## Applied State and Compatibility++The migrator records stable migration IDs in the `applied_migrations` table. Legacy numeric versions are still written to the existing `migrations` table for migrations that define `to_version`.++New date-stamped migrations should not define `from_version` or `to_version` unless there is a specific legacy compatibility reason. Use `id` and `depends_on` to define execution.++Existing databases are bootstrapped from legacy numeric rows:++- legacy version `1` maps to `migration_1`+- legacy version `2` maps to `migration_2`+- and so on++If a database contains an applied migration ID or legacy numeric version unknown to the current code, startup fails before running migrations. This prevents older code from running against a newer schema. Downgrading to an InvokeAI version that does not know about migrations already applied by a newer version is not supported.++For legacy migrations, the two metadata tables must agree. For example, `applied_migrations` may only record `migration_2` with `legacy_version = 2` if the legacy `migrations` table also contains version `2`. If these records are inconsistent, startup fails before user migration callbacks run.++When opening a file-backed legacy database for the first time after this migration system change, the migrator may need to create and populate `applied_migrations` even if no user migration callbacks need to run. This metadata bootstrap is backed up before the new metadata table is written.++## Tests++Add focused tests for each migration callback under:++```text+tests/app/services/shared/sqlite_migrator/migrations/+```++At minimum, cover:++- the schema or data change performed by the callback+- idempotent or already-migrated behavior when relevant+- missing optional source tables or columns when the migration is expected to tolerate them+- the builder's `id` and `depends_on`+- legacy `from_version` and `to_version`, if the migration defines them++Also run the migrator tests:++```bash+pytest tests/app/services/shared/sqlite_migrator tests/test_sqlite_migrator.py+```++These tests use in-memory databases or pytest temporary directories. They should not touch a real InvokeAI database.diff --git a/invokeai/app/services/shared/sqlite/sqlite_util.py b/invokeai/app/services/shared/sqlite/sqlite_util.pyindex 14b6c61a85..5ef006f489 100644--- a/invokeai/app/services/shared/sqlite/sqlite_util.py+++ b/invokeai/app/services/shared/sqlite/sqlite_util.py@@ -3,39 +3,7 @@ from logging import Loggerfrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.image_files.image_files_base import ImageFileStorageBasefrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_1 import build_migration_1-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2 import build_migration_2-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_3 import build_migration_3-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_4 import build_migration_4-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_5 import build_migration_5-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_6 import build_migration_6-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_7 import build_migration_7-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_8 import build_migration_8-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_9 import build_migration_9-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_10 import build_migration_10-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_11 import build_migration_11-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_12 import build_migration_12-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_13 import build_migration_13-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_14 import build_migration_14-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_15 import build_migration_15-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_16 import build_migration_16-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_17 import build_migration_17-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_18 import build_migration_18-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_19 import build_migration_19-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_20 import build_migration_20-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_21 import build_migration_21-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_22 import build_migration_22-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_23 import build_migration_23-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_24 import build_migration_24-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_25 import build_migration_25-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_26 import build_migration_26-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_27 import build_migration_27-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_28 import build_migration_28-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_29 import build_migration_29-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_30 import build_migration_30-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_31 import build_migration_31-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_32 import build_migration_32-from invokeai.app.services.shared.sqlite_migrator.migrations.migration_33 import build_migration_33+from invokeai.app.services.shared.sqlite_migrator.migration_loader import MigrationBuildContext, build_migrationsfrom invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import SqliteMigrator@@ -56,39 +24,9 @@ def init_db(config: InvokeAIAppConfig, logger: Logger, image_files: ImageFileStodb = SqliteDatabase(db_path=db_path, logger=logger, verbose=config.log_sql)migrator = SqliteMigrator(db=db)- migrator.register_migration(build_migration_1())- migrator.register_migration(build_migration_2(image_files=image_files, logger=logger))- migrator.register_migration(build_migration_3(app_config=config, logger=logger))- migrator.register_migration(build_migration_4())- migrator.register_migration(build_migration_5())- migrator.register_migration(build_migration_6())- migrator.register_migration(build_migration_7())- migrator.register_migration(build_migration_8(app_config=config))- migrator.register_migration(build_migration_9())- migrator.register_migration(build_migration_10())- migrator.register_migration(build_migration_11(app_config=config, logger=logger))- migrator.register_migration(build_migration_12(app_config=config))- migrator.register_migration(build_migration_13())- migrator.register_migration(build_migration_14())- migrator.register_migration(build_migration_15())- migrator.register_migration(build_migration_16())- migrator.register_migration(build_migration_17())- migrator.register_migration(build_migration_18())- migrator.register_migration(build_migration_19(app_config=config))- migrator.register_migration(build_migration_20())- migrator.register_migration(build_migration_21())- migrator.register_migration(build_migration_22(app_config=config, logger=logger))- migrator.register_migration(build_migration_23(app_config=config, logger=logger))- migrator.register_migration(build_migration_24(app_config=config, logger=logger))- migrator.register_migration(build_migration_25(app_config=config, logger=logger))- migrator.register_migration(build_migration_26(app_config=config, logger=logger))- migrator.register_migration(build_migration_27())- migrator.register_migration(build_migration_28())- migrator.register_migration(build_migration_29())- migrator.register_migration(build_migration_30())- migrator.register_migration(build_migration_31())- migrator.register_migration(build_migration_32())- migrator.register_migration(build_migration_33())+ migration_context = MigrationBuildContext(app_config=config, logger=logger, image_files=image_files)+ for migration in build_migrations(migration_context):+ migrator.register_migration(migration)migrator.run_migrations()return dbdiff --git a/invokeai/app/services/shared/sqlite_migrator/migration_loader.py b/invokeai/app/services/shared/sqlite_migrator/migration_loader.pynew file mode 100644index 0000000000..c32e829892--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migration_loader.py@@ -0,0 +1,136 @@+import importlib+import inspect+import pkgutil+import re+from collections.abc import Callable+from dataclasses import dataclass+from logging import Logger+from types import ModuleType+from typing import Any++from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.image_files.image_files_base import ImageFileStorageBase+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration++DEFAULT_MIGRATIONS_PACKAGE = "invokeai.app.services.shared.sqlite_migrator.migrations"+_MIGRATION_MODULE_RE = re.compile(r"^migration_(\d+)$")+_DATED_MIGRATION_MODULE_RE = re.compile(r"^migration_(\d{4}_\d{2}_\d{2}_[a-z0-9][a-z0-9_]*)$")+++class MigrationLoaderError(RuntimeError):+ """Raised when migration discovery or construction fails."""+++@dataclass(frozen=True)+class MigrationBuildContext:+ app_config: InvokeAIAppConfig+ logger: Logger+ image_files: ImageFileStorageBase++ def get_dependency(self, name: str) -> Any:+ if name == "app_config":+ return self.app_config+ if name == "config":+ return self.app_config+ if name == "logger":+ return self.logger+ if name == "image_files":+ return self.image_files+ raise MigrationLoaderError(f"Migration builder requested unknown dependency '{name}'")+++MigrationBuilder = Callable[..., Migration]+++@dataclass(frozen=True)+class DiscoveredMigrationBuilder:+ module_name: str+ sort_key: tuple[int, int | str]+ expected_migration_id: str+ builder: MigrationBuilder+++def discover_migration_builders(package_name: str = DEFAULT_MIGRATIONS_PACKAGE) -> list[DiscoveredMigrationBuilder]:+ try:+ package = importlib.import_module(package_name)+ except Exception as e:+ raise MigrationLoaderError(f"Unable to import migrations package '{package_name}': {e}") from e++ package_path = getattr(package, "__path__", None)+ if package_path is None:+ raise MigrationLoaderError(f"Migrations package '{package_name}' is not a package")++ discovered: list[DiscoveredMigrationBuilder] = []+ for module_info in pkgutil.iter_modules(package_path):+ module_short_name = module_info.name+ if not module_short_name.startswith("migration_"):+ continue+ numeric_match = _MIGRATION_MODULE_RE.match(module_short_name)+ dated_match = _DATED_MIGRATION_MODULE_RE.match(module_short_name)+ if numeric_match is None and dated_match is None:+ raise MigrationLoaderError(f"Malformed migration module name '{module_short_name}'")++ if numeric_match is not None:+ sort_key: tuple[int, int | str] = (0, int(numeric_match.group(1)))+ expected_builder_name = f"build_migration_{numeric_match.group(1)}"+ expected_migration_id = f"migration_{numeric_match.group(1)}"+ else:+ sort_key = (1, module_short_name)+ expected_builder_name = "build_migration"+ expected_migration_id = module_short_name.removeprefix("migration_")++ full_module_name = f"{package_name}.{module_short_name}"+ try:+ module = importlib.import_module(full_module_name)+ except Exception as e:+ raise MigrationLoaderError(f"Unable to import migration module '{full_module_name}': {e}") from e++ builder = _get_builder(module, expected_builder_name)+ discovered.append(DiscoveredMigrationBuilder(full_module_name, sort_key, expected_migration_id, builder))++ return sorted(discovered, key=lambda discovered_builder: discovered_builder.sort_key)+++def build_migrations(context: MigrationBuildContext, package_name: str = DEFAULT_MIGRATIONS_PACKAGE) -> list[Migration]:+ migrations: list[Migration] = []+ for discovered_builder in discover_migration_builders(package_name):+ kwargs = _get_builder_kwargs(discovered_builder.builder, context, discovered_builder.module_name)+ migration = discovered_builder.builder(**kwargs)+ if not isinstance(migration, Migration):+ raise MigrationLoaderError(+ f"Migration builder '{discovered_builder.builder.__name__}' in "+ f"'{discovered_builder.module_name}' must return Migration"+ )+ if migration.id != discovered_builder.expected_migration_id:+ raise MigrationLoaderError(+ f"Migration builder '{discovered_builder.builder.__name__}' in "+ f"'{discovered_builder.module_name}' must return migration id "+ f"'{discovered_builder.expected_migration_id}', got '{migration.id}'"+ )+ migrations.append(migration)+ return migrations+++def _get_builder(module: ModuleType, builder_name: str) -> MigrationBuilder:+ builder = getattr(module, builder_name, None)+ if builder is None:+ raise MigrationLoaderError(f"Migration module '{module.__name__}' must define '{builder_name}'")+ if not callable(builder):+ raise MigrationLoaderError(f"Migration builder '{module.__name__}.{builder_name}' is not callable")+ return builder+++def _get_builder_kwargs(builder: MigrationBuilder, context: MigrationBuildContext, module_name: str) -> dict[str, Any]:+ signature = inspect.signature(builder)+ kwargs: dict[str, Any] = {}+ for parameter in signature.parameters.values():+ if parameter.kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD):+ raise MigrationLoaderError(+ f"Migration builder '{module_name}.{builder.__name__}' must not use *args or **kwargs"+ )+ if parameter.kind == inspect.Parameter.POSITIONAL_ONLY:+ raise MigrationLoaderError(+ f"Migration builder '{module_name}.{builder.__name__}' must not use positional-only parameters"+ )+ kwargs[parameter.name] = context.get_dependency(parameter.name)+ return kwargsdiff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_1.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_1.pyindex 574afb472f..af8946833c 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_1.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_1.py@@ -364,6 +364,8 @@ def build_migration_1() -> Migration:"""migration_1 = Migration(+ id="migration_1",+ depends_on=None,from_version=0,to_version=1,callback=Migration1Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_10.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_10.pyindex ce2cd2e965..f33844f29a 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_10.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_10.py@@ -27,6 +27,8 @@ def build_migration_10() -> Migration:- Renames the `error` column to `error_traceback`."""migration_10 = Migration(+ id="migration_10",+ depends_on="migration_9",from_version=9,to_version=10,callback=Migration10Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_11.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_11.pyindex 17e61334f0..bbdf867b11 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_11.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_11.py@@ -67,6 +67,8 @@ def build_migration_11(app_config: InvokeAIAppConfig, logger: Logger) -> Migrati- Renames "models/.cache" to "models/.convert_cache"."""migration_11 = Migration(+ id="migration_11",+ depends_on="migration_10",from_version=10,to_version=11,callback=Migration11Callback(app_config=app_config, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_12.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_12.pyindex f81632445c..cf1b7cf602 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_12.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_12.py@@ -27,6 +27,8 @@ def build_migration_12(app_config: InvokeAIAppConfig) -> Migration:This migration removes the now-unused model convert cache directory."""migration_12 = Migration(+ id="migration_12",+ depends_on="migration_11",from_version=11,to_version=12,callback=Migration12Callback(app_config),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_13.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_13.pyindex 401c0a4866..83f8fab020 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_13.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_13.py@@ -23,6 +23,8 @@ def build_migration_13() -> Migration:- Adds `archived` columns to the board table."""migration_13 = Migration(+ id="migration_13",+ depends_on="migration_12",from_version=12,to_version=13,callback=Migration13Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_14.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_14.pyindex 399f5a71d2..59b4725132 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_14.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_14.py@@ -53,6 +53,8 @@ def build_migration_14() -> Migration:- Create the table used to store style presets."""migration_14 = Migration(+ id="migration_14",+ depends_on="migration_13",from_version=13,to_version=14,callback=Migration14Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_15.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_15.pyindex 455ff71ab5..88243a7779 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_15.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_15.py@@ -26,6 +26,8 @@ def build_migration_15() -> Migration:- Adds `destination` column to the session queue table."""migration_15 = Migration(+ id="migration_15",+ depends_on="migration_14",from_version=14,to_version=15,callback=Migration15Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_16.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_16.pyindex d401247b92..d8533c2366 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_16.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_16.py@@ -23,6 +23,8 @@ def build_migration_16() -> Migration:- Adds `retried_from_item_id` column to the session queue table."""migration_16 = Migration(+ id="migration_16",+ depends_on="migration_15",from_version=15,to_version=16,callback=Migration16Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_17.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_17.pyindex 8e2e788a8f..1225e45277 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_17.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_17.py@@ -27,6 +27,8 @@ def build_migration_17() -> Migration:workflow JSON."""migration_17 = Migration(+ id="migration_17",+ depends_on="migration_16",from_version=16,to_version=17,callback=Migration17Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_18.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_18.pyindex 7879ddc378..cc1c28edff 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_18.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_18.py@@ -39,6 +39,8 @@ def build_migration_18() -> Migration:- Adding a new `idx_workflow_library_opened_at` index on the `opened_at` column"""migration_18 = Migration(+ id="migration_18",+ depends_on="migration_17",from_version=17,to_version=18,callback=Migration18Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_19.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_19.pyindex 363cd2e8d8..ef8c041675 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_19.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_19.py@@ -31,6 +31,8 @@ class Migration19Callback:def build_migration_19(app_config: InvokeAIAppConfig) -> Migration:return Migration(+ id="migration_19",+ depends_on="migration_18",from_version=18,to_version=19,callback=Migration19Callback(app_config),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2.pyindex f290fe6159..175d21d74c 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2.py@@ -158,6 +158,8 @@ def build_migration_2(image_files: ImageFileStorageBase, logger: Logger) -> Migr- Populates the `has_workflow` column in the `images` table (requires `image_files` & `logger` dependencies)"""migration_2 = Migration(+ id="migration_2",+ depends_on="migration_1",from_version=1,to_version=2,callback=Migration2Callback(image_files=image_files, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_20.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_20.pyindex 420b383570..86b0f4a315 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_20.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_20.py@@ -31,6 +31,8 @@ class Migration20Callback:def build_migration_20() -> Migration:return Migration(+ id="migration_20",+ depends_on="migration_19",from_version=19,to_version=20,callback=Migration20Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_21.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_21.pyindex 82f63772c7..fe7cc974eb 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_21.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_21.py@@ -34,6 +34,8 @@ def build_migration_21() -> Migration:- Adding a trigger to update the `updated_at` field on updates."""return Migration(+ id="migration_21",+ depends_on="migration_20",from_version=20,to_version=21,callback=Migration21Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_22.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_22.pyindex bf97cbd00a..419b09c69e 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_22.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_22.py@@ -83,6 +83,8 @@ def build_migration_22(app_config: InvokeAIAppConfig, logger: Logger) -> Migrati"""return Migration(+ id="migration_22",+ depends_on="migration_21",from_version=21,to_version=22,callback=Migration22Callback(app_config=app_config, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_23.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_23.pyindex 3b5dc467b3..de84feaa32 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_23.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_23.py@@ -187,6 +187,8 @@ def build_migration_23(app_config: InvokeAIAppConfig, logger: Logger) -> Migrati"""return Migration(+ id="migration_23",+ depends_on="migration_22",from_version=22,to_version=23,callback=Migration23Callback(app_config=app_config, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.pyindex 5ae8563b3e..6aa76991fc 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.py@@ -234,6 +234,8 @@ def build_migration_24(app_config: InvokeAIAppConfig, logger: Logger) -> Migrati"""return Migration(+ id="migration_24",+ depends_on="migration_23",from_version=23,to_version=24,callback=Migration24Callback(app_config=app_config, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_25.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_25.pyindex 0ce8a8ff6a..95e68cb335 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_25.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_25.py@@ -55,6 +55,8 @@ def build_migration_25(app_config: InvokeAIAppConfig, logger: Logger) -> Migrati"""return Migration(+ id="migration_25",+ depends_on="migration_24",from_version=24,to_version=25,callback=Migration25Callback(app_config=app_config, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_26.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_26.pyindex d392d28413..84c9cfdaac 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_26.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_26.py@@ -109,6 +109,8 @@ def build_migration_26(app_config: InvokeAIAppConfig, logger: Logger) -> Migrati"""return Migration(+ id="migration_26",+ depends_on="migration_25",from_version=25,to_version=26,callback=Migration26Callback(app_config=app_config, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_27.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_27.pyindex b80ea073ef..d2f3551674 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_27.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_27.py@@ -360,6 +360,8 @@ def build_migration_27() -> Migration:(including a JWT secret) to the database schema."""return Migration(+ id="migration_27",+ depends_on="migration_26",from_version=26,to_version=27,callback=Migration27Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_28.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_28.pyindex 60e5d8f19b..24c54f5c38 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_28.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_28.py@@ -42,6 +42,8 @@ def build_migration_28() -> Migration:- is_public column: controls whether a workflow is shared with all users"""return Migration(+ id="migration_28",+ depends_on="migration_27",from_version=27,to_version=28,callback=Migration28Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_29.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_29.pyindex c9eb7c901b..30a5ec57eb 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_29.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_29.py@@ -47,6 +47,8 @@ def build_migration_29() -> Migration:supporting 'private', 'shared', and 'public' visibility levels."""return Migration(+ id="migration_29",+ depends_on="migration_28",from_version=28,to_version=29,callback=Migration29Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_3.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_3.pyindex 48eb1db854..f570463cdd 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_3.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_3.py@@ -62,6 +62,8 @@ def build_migration_3(app_config: InvokeAIAppConfig, logger: Logger) -> Migratio- Migrates data from `models.yaml` into the `model_config` table"""migration_3 = Migration(+ id="migration_3",+ depends_on="migration_2",from_version=2,to_version=3,callback=Migration3Callback(app_config=app_config, logger=logger),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_30.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_30.pyindex d60270bfa1..aed406d797 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_30.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_30.py@@ -27,6 +27,8 @@ class Migration30Callback:def build_migration_30() -> Migration:return Migration(+ id="migration_30",+ depends_on="migration_29",from_version=29,to_version=30,callback=Migration30Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_31.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_31.pyindex 9f5b36a5f2..48a890ce9f 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_31.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_31.py@@ -35,6 +35,8 @@ def build_migration_31() -> Migration:This migration adds an image_subfolder column to the images table."""return Migration(+ id="migration_31",+ depends_on="migration_30",from_version=30,to_version=31,callback=Migration31Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_32.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_32.pyindex 5e06d634e7..9036048bce 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_32.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_32.py@@ -85,6 +85,8 @@ def build_migration_32() -> Migration:broken by migration 22 rebuilding the models table."""return Migration(+ id="migration_32",+ depends_on="migration_31",from_version=31,to_version=32,callback=Migration32Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_4.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_4.pyindex b8dc4dd83b..ed4c7ff34f 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_4.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_4.py@@ -75,6 +75,8 @@ def build_migration_4() -> Migration:Adds the tables needed to store model metadata and tags."""migration_4 = Migration(+ id="migration_4",+ depends_on="migration_3",from_version=3,to_version=4,callback=Migration4Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_5.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_5.pyindex b2e8c206d8..0292acdb63 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_5.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_5.py@@ -26,6 +26,8 @@ def build_migration_5() -> Migration:to be purely in-memory."""migration_5 = Migration(+ id="migration_5",+ depends_on="migration_4",from_version=4,to_version=5,callback=Migration5Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_6.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_6.pyindex 1f9ac56518..0ae63cbe12 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_6.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_6.py@@ -54,6 +54,8 @@ def build_migration_6() -> Migration:update with the correct image processor model."""migration_6 = Migration(+ id="migration_6",+ depends_on="migration_5",from_version=5,to_version=6,callback=Migration6Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_7.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_7.pyindex fa573d63a6..c4ab98fa70 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_7.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_7.py@@ -80,6 +80,8 @@ def build_migration_7() -> Migration:- TODO(MM2): Migrates model names and descriptions from `models.yaml` to the new table (?)."""migration_7 = Migration(+ id="migration_7",+ depends_on="migration_6",from_version=6,to_version=7,callback=Migration7Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_8.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_8.pyindex 154a5236ca..56f8634538 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_8.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_8.py@@ -83,6 +83,8 @@ def build_migration_8(app_config: InvokeAIAppConfig) -> Migration:- Migrates absolute model & legacy config paths to be relative to the models directory."""migration_8 = Migration(+ id="migration_8",+ depends_on="migration_7",from_version=7,to_version=8,callback=Migration8Callback(app_config),diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_9.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_9.pyindex acc4ef5017..16ee73299d 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_9.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_9.py@@ -21,6 +21,8 @@ def build_migration_9() -> Migration:- Empties the session queue. This is done to prevent any lingering session queue items from causing pydantic errors due to changed schemas."""migration_9 = Migration(+ id="migration_9",+ depends_on="migration_8",from_version=8,to_version=9,callback=Migration9Callback(),diff --git a/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_common.py b/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_common.pyindex 9b2444dae4..1bbb8d6f1e 100644--- a/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_common.py+++ b/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_common.py@@ -32,10 +32,16 @@ class Migration(BaseModel):"""Represents a migration for a SQLite database.- :param from_version: The database version on which this migration may be run- :param to_version: The database version that results from this migration+ :param from_version: The legacy database version on which this migration may be run+ :param to_version: The legacy database version that results from this migration+ :param id: The stable migration ID. Legacy migrations default to ``migration_{to_version}``.+ :param depends_on: The stable ID of the migration that must run first.:param migrate_callback: The callback to run to perform the migration+ Migrations are executed according to their stable ID dependencies. Existing legacy migrations also keep+ ``from_version`` and ``to_version`` so older numeric migration state can be mapped to applied migration IDs.+ New graph-only migrations may omit legacy versions, but must provide an explicit ``id``.+Migration callbacks will be provided an open cursor to the database. They should not commit theirtransaction; this is handled by the migrator.@@ -88,20 +94,47 @@ class Migration(BaseModel):```"""- from_version: int = Field(ge=0, strict=True, description="The database version on which this migration may be run")- to_version: int = Field(ge=1, strict=True, description="The database version that results from this migration")+ from_version: Optional[int] = Field(+ default=None, ge=0, strict=True, description="The database version on which this migration may be run"+ )+ to_version: Optional[int] = Field(+ default=None, ge=1, strict=True, description="The database version that results from this migration"+ )+ id: Optional[str] = Field(default=None, description="Stable migration ID")+ depends_on: Optional[str] = Field(default=None, description="Stable ID of the migration dependency")callback: MigrateCallback = Field(description="The callback to run to perform the migration")@model_validator(mode="after")- def validate_to_version(self) -> "Migration":- """Validates that to_version is one greater than from_version."""- if self.to_version != self.from_version + 1:+ def validate_versions_and_ids(self) -> "Migration":+ """Validates legacy versions and derives stable IDs for legacy migrations."""+ has_from_version = self.from_version is not None+ has_to_version = self.to_version is not None+ if has_from_version != has_to_version:+ raise MigrationVersionError("from_version and to_version must both be provided for legacy migrations")+ if self.from_version is not None and self.to_version is not None and self.to_version != self.from_version + 1:raise MigrationVersionError("to_version must be one greater than from_version")+ if self.id is None and self.to_version is not None:+ self.id = f"migration_{self.to_version}"+ if self.id is None:+ raise MigrationVersionError("id is required for graph-only migrations")+ if self.depends_on is None and self.from_version is not None and self.from_version > 0:+ self.depends_on = f"migration_{self.from_version}"+ if self.depends_on == self.id:+ raise MigrationVersionError("migration cannot depend on itself")return selfdef __hash__(self) -> int:# Callables are not hashable, so we need to implement our own __hash__ function to use this class in a set.- return hash((self.from_version, self.to_version))+ if self.from_version is not None and self.to_version is not None:+ return hash((self.from_version, self.to_version))+ return hash(self.id)++ @property+ def sort_key(self) -> tuple[int, int, str]:+ """Deterministic sort key for runnable migrations."""+ if self.to_version is None:+ return (1, 0, self.id or "")+ return (0, self.to_version, self.id or "")model_config = ConfigDict(arbitrary_types_allowed=True)@@ -110,8 +143,9 @@ class MigrationSet:"""A set of Migrations. Performs validation during migration registration and provides utility methods.- Migrations should be registered with `register()`. Once all are registered, `validate_migration_chain()`- should be called to ensure that the migrations form a single chain of migrations from version 0 to the latest version.+ Migrations should be registered with `register()`. Once all are registered, `validate_dependency_graph()`+ should be called to ensure that dependencies are complete and acyclic. `validate_migration_chain()` is retained for+ legacy chain validation tests and compatibility checks."""def __init__(self) -> None:@@ -119,10 +153,17 @@ class MigrationSet:def register(self, migration: Migration) -> None:"""Registers a migration."""- migration_from_already_registered = any(m.from_version == migration.from_version for m in self._migrations)- migration_to_already_registered = any(m.to_version == migration.to_version for m in self._migrations)+ migration_from_already_registered = migration.from_version is not None and any(+ m.from_version == migration.from_version for m in self._migrations if m.from_version is not None+ )+ migration_to_already_registered = migration.to_version is not None and any(+ m.to_version == migration.to_version for m in self._migrations if m.to_version is not None+ )if migration_from_already_registered or migration_to_already_registered:raise MigrationVersionError("Migration with from_version or to_version already registered")+ migration_id_already_registered = any(m.id == migration.id for m in self._migrations)+ if migration_id_already_registered:+ raise MigrationVersionError("Migration with id already registered")self._migrations.add(migration)def get(self, from_version: int) -> Optional[Migration]:@@ -150,6 +191,74 @@ class MigrationSet:if touched_count != self.count:raise MigrationError("Migration chain is fragmented")+ def validate_dependency_graph(self) -> None:+ """Validates migration ID dependencies."""+ migration_ids = {migration.id for migration in self._migrations}+ migrations_by_id = self.migrations_by_id+ for migration in self._migrations:+ if migration.depends_on is not None and migration.depends_on not in migration_ids:+ raise MigrationError(+ f"Migration '{migration.id}' depends on unknown migration '{migration.depends_on}'"+ )+ if migration.to_version is not None and migration.depends_on is not None:+ dependency = migrations_by_id[migration.depends_on]+ if dependency.to_version is None:+ raise MigrationError(+ f"Legacy migration '{migration.id}' cannot depend on graph-only migration '{dependency.id}'"+ )++ visiting: set[str] = set()+ visited: set[str] = set()++ def visit(migration: Migration) -> None:+ migration_id = migration.id+ if migration_id is None:+ raise MigrationError("Migration is missing id")+ if migration_id in visited:+ return+ if migration_id in visiting:+ raise MigrationError("Migration dependency graph contains a cycle")+ visiting.add(migration_id)+ if migration.depends_on is not None:+ visit(migrations_by_id[migration.depends_on])+ visiting.remove(migration_id)+ visited.add(migration_id)++ for migration in self._migrations:+ visit(migration)++ def get_migration_plan(self, applied_migration_ids: set[str]) -> list[Migration]:+ """Gets a deterministic migration plan from the set of applied migration IDs."""+ self.validate_dependency_graph()+ known_migration_ids = set(self.migrations_by_id)+ unknown_applied_ids = applied_migration_ids - known_migration_ids+ if unknown_applied_ids:+ unknown_ids = ", ".join(sorted(unknown_applied_ids))+ raise MigrationError(f"Database contains unknown applied migration IDs: {unknown_ids}")++ plan: list[Migration] = []+ planned_or_applied_ids = set(applied_migration_ids)+ remaining = {+ migration.id: migration for migration in self._migrations if migration.id not in applied_migration_ids+ }++ while remaining:+ runnable = sorted(+ (+ migration+ for migration in remaining.values()+ if migration.depends_on is None or migration.depends_on in planned_or_applied_ids+ ),+ key=lambda migration: migration.sort_key,+ )+ if not runnable:+ raise MigrationError("Migration dependency graph cannot be resolved")+ migration = runnable[0]+ plan.append(migration)+ planned_or_applied_ids.add(migration.id or "")+ del remaining[migration.id]+ return plan+@propertydef count(self) -> int:"""The count of registered migrations."""@@ -160,4 +269,16 @@ class MigrationSet:"""Gets latest to_version among registered migrations. Returns 0 if there are no migrations registered."""if self.count == 0:return 0- return sorted(self._migrations, key=lambda m: m.to_version)[-1].to_version+ legacy_migrations = [migration for migration in self._migrations if migration.to_version is not None]+ if len(legacy_migrations) == 0:+ return 0+ latest_version = sorted(legacy_migrations, key=lambda m: m.to_version or 0)[-1].to_version+ return latest_version or 0++ @property+ def migrations(self) -> tuple[Migration, ...]:+ return tuple(sorted(self._migrations, key=lambda migration: migration.sort_key))++ @property+ def migrations_by_id(self) -> dict[str, Migration]:+ return {migration.id or "": migration for migration in self._migrations}diff --git a/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py b/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.pyindex 310abf0520..6842813a8e 100644--- a/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py+++ b/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py@@ -14,7 +14,9 @@ class SqliteMigrator::param db: The instance of :class:`SqliteDatabase` to migrate.- Migrations should be registered with :meth:`register_migration`.+ Migrations should be registered with :meth:`register_migration`, either directly or via the migration loader.+ They are planned by stable migration ID dependencies and recorded in the ``applied_migrations`` table.+ Legacy numeric versions are still written for migrations that define ``to_version``.Each migration is run in a transaction. If a migration fails, the transaction is rolled back.@@ -44,38 +46,49 @@ class SqliteMigrator:def run_migrations(self) -> bool:"""Migrates the database to the latest version."""# This throws if there is a problem.- self._migration_set.validate_migration_chain()+ self._migration_set.validate_dependency_graph()cursor = self._db._conn.cursor()+ self._validate_existing_applied_migrations(cursor=cursor)self._create_migrations_table(cursor=cursor)+ self._validate_existing_legacy_migrations(cursor=cursor)+ if self._needs_applied_migrations_bootstrap(cursor=cursor):+ self._backup_db()+ self._create_applied_migrations_table(cursor=cursor)+ self._validate_existing_applied_legacy_migrations(cursor=cursor)+ self._bootstrap_applied_migrations_from_legacy_versions(cursor=cursor)if self._migration_set.count == 0:self._logger.debug("No migrations registered")return False- if self._get_current_version(cursor=cursor) == self._migration_set.latest_version:+ applied_migration_ids = self._get_applied_migration_ids(cursor=cursor)+ migration_plan = self._migration_set.get_migration_plan(applied_migration_ids=applied_migration_ids)+ if len(migration_plan) == 0:self._logger.debug("Database is up to date, no migrations to run")return Falseself._logger.info("Database update needed")- # Make a backup of the db if it needs to be updated and is a file db+ self._backup_db()++ for migration in migration_plan:+ self._run_migration(migration)+ self._logger.info("Database updated successfully")+ return True++ def _backup_db(self) -> None:+ """Makes a backup of the db if it is a file db and a backup has not already been made."""+ if self._backup_path is not None:+ returnif self._db._db_path is not None:timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")self._backup_path = self._db._db_path.parent / f"{self._db._db_path.stem}_backup_{timestamp}.db"self._logger.info(f"Backing up database to {str(self._backup_path)}")- # Use SQLite to do the backupwith closing(sqlite3.connect(self._backup_path)) as backup_conn:self._db._conn.backup(backup_conn)else:self._logger.info("Using in-memory database, no backup needed")- next_migration = self._migration_set.get(from_version=self._get_current_version(cursor))- while next_migration is not None:- self._run_migration(next_migration)- next_migration = self._migration_set.get(self._get_current_version(cursor))- self._logger.info("Database updated successfully")- return True-def _run_migration(self, migration: Migration) -> None:"""Runs a single migration."""try:@@ -83,25 +96,28 @@ class SqliteMigrator:# exception is raised.with self._db._conn as conn:cursor = conn.cursor()- if self._get_current_version(cursor) != migration.from_version:+ self._create_applied_migrations_table(cursor)+ if migration.from_version is not None and self._get_current_version(cursor) != migration.from_version:raise MigrationError(f"Database is at version {self._get_current_version(cursor)}, expected {migration.from_version}")- self._logger.debug(f"Running migration from {migration.from_version} to {migration.to_version}")+ self._logger.debug(f"Running migration '{migration.id}'")# Run the actual migrationmigration.callback(cursor)- # Update the version- cursor.execute("INSERT INTO migrations (version) VALUES (?);", (migration.to_version,))-- self._logger.debug(- f"Successfully migrated database from {migration.from_version} to {migration.to_version}"+ if migration.to_version is not None:+ cursor.execute("INSERT INTO migrations (version) VALUES (?);", (migration.to_version,))+ cursor.execute(+ "INSERT INTO applied_migrations (migration_id, legacy_version) VALUES (?, ?);",+ (migration.id, migration.to_version),)++ self._logger.debug(f"Successfully ran migration '{migration.id}'")# We want to catch *any* error, mirroring the behaviour of the sqlite3 module.except Exception as e:# The connection context manager has already rolled back the migration, so we don't need to do anything.- msg = f"Error migrating database from {migration.from_version} to {migration.to_version}: {e}"+ msg = f"Error running migration '{migration.id}': {e}"self._logger.error(msg)raise MigrationError(msg) from e@@ -128,6 +144,149 @@ class SqliteMigrator:cursor.connection.rollback()raise MigrationError(msg) from e+ def _create_applied_migrations_table(self, cursor: sqlite3.Cursor) -> None:+ """Creates the applied migrations table for stable migration IDs."""+ try:+ cursor.execute(+ """--sql+ CREATE TABLE IF NOT EXISTS applied_migrations (+ migration_id TEXT PRIMARY KEY,+ legacy_version INTEGER UNIQUE,+ migrated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))+ );+ """+ )+ except sqlite3.Error as e:+ msg = f"Problem creating applied_migrations table: {e}"+ self._logger.error(msg)+ cursor.connection.rollback()+ raise MigrationError(msg) from e++ def _bootstrap_applied_migrations_from_legacy_versions(self, cursor: sqlite3.Cursor) -> None:+ """Backfills applied migration IDs from legacy numeric migration rows."""+ try:+ cursor.execute("SELECT version FROM migrations WHERE version > 0 ORDER BY version;")+ legacy_versions = [row[0] for row in cursor.fetchall()]+ registered_migration_ids = self._migration_set.migrations_by_id+ for legacy_version in legacy_versions:+ migration_id = f"migration_{legacy_version}"+ if migration_id not in registered_migration_ids:+ cursor.connection.rollback()+ raise MigrationError(f"Database contains unknown legacy migration version: {legacy_version}")+ cursor.execute(+ "SELECT legacy_version FROM applied_migrations WHERE migration_id = ?;",+ (migration_id,),+ )+ migration_row = cursor.fetchone()+ if migration_row is not None and migration_row[0] != legacy_version:+ cursor.connection.rollback()+ raise MigrationError(+ "Database contains inconsistent applied migration state: "+ f"{migration_id} is recorded with legacy version {migration_row[0]}, "+ f"expected {legacy_version}"+ )+ cursor.execute(+ "SELECT migration_id FROM applied_migrations WHERE legacy_version = ?;",+ (legacy_version,),+ )+ legacy_row = cursor.fetchone()+ if legacy_row is not None and legacy_row[0] != migration_id:+ cursor.connection.rollback()+ raise MigrationError(+ "Database contains inconsistent applied migration state: "+ f"legacy version {legacy_version} is recorded for {legacy_row[0]}, expected {migration_id}"+ )+ cursor.execute(+ "INSERT OR IGNORE INTO applied_migrations (migration_id, legacy_version) VALUES (?, ?);",+ (migration_id, legacy_version),+ )+ cursor.connection.commit()+ except sqlite3.Error as e:+ msg = f"Problem bootstrapping applied migrations: {e}"+ self._logger.error(msg)+ cursor.connection.rollback()+ raise MigrationError(msg) from e++ def _validate_existing_applied_migrations(self, cursor: sqlite3.Cursor) -> None:+ """Validates existing applied migration IDs before creating or mutating migrator metadata."""+ applied_migration_ids = self._get_applied_migration_ids(cursor=cursor)+ if len(applied_migration_ids) == 0:+ return+ known_migration_ids = set(self._migration_set.migrations_by_id)+ unknown_applied_ids = applied_migration_ids - known_migration_ids+ if unknown_applied_ids:+ unknown_ids = ", ".join(sorted(unknown_applied_ids))+ raise MigrationError(f"Database contains unknown applied migration IDs: {unknown_ids}")++ def _validate_existing_legacy_migrations(self, cursor: sqlite3.Cursor) -> None:+ """Validates existing legacy migration versions before creating applied migration metadata."""+ try:+ cursor.execute("SELECT version FROM migrations WHERE version > 0 ORDER BY version;")+ except sqlite3.OperationalError as e:+ if "no such table" in str(e):+ return+ raise++ registered_migration_ids = self._migration_set.migrations_by_id+ for row in cursor.fetchall():+ legacy_version = row[0]+ migration_id = f"migration_{legacy_version}"+ if migration_id not in registered_migration_ids:+ raise MigrationError(f"Database contains unknown legacy migration version: {legacy_version}")++ def _validate_existing_applied_legacy_migrations(self, cursor: sqlite3.Cursor) -> None:+ """Validates applied IDs for legacy migrations against legacy numeric rows."""+ registered_migrations = self._migration_set.migrations_by_id+ cursor.execute("SELECT migration_id, legacy_version FROM applied_migrations;")+ applied_rows = cursor.fetchall()++ cursor.execute("SELECT version FROM migrations WHERE version > 0;")+ legacy_versions = {row[0] for row in cursor.fetchall()}++ for row in applied_rows:+ migration_id = row[0]+ legacy_version = row[1]+ migration = registered_migrations[migration_id]+ if migration.to_version is None:+ continue+ if legacy_version != migration.to_version:+ raise MigrationError(+ "Database contains inconsistent applied migration state: "+ f"{migration_id} is recorded with legacy version {legacy_version}, "+ f"expected {migration.to_version}"+ )+ if legacy_version not in legacy_versions:+ raise MigrationError(+ "Database contains inconsistent applied migration state: "+ f"{migration_id} is applied, but legacy version {legacy_version} is missing"+ )++ def _needs_applied_migrations_bootstrap(self, cursor: sqlite3.Cursor) -> bool:+ """Checks whether legacy numeric rows need to be written to applied_migrations."""+ cursor.execute("SELECT version FROM migrations WHERE version > 0;")+ legacy_versions = {row[0] for row in cursor.fetchall()}+ if len(legacy_versions) == 0:+ return False++ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='applied_migrations';")+ if cursor.fetchone() is None:+ return True++ cursor.execute("SELECT legacy_version FROM applied_migrations WHERE legacy_version IS NOT NULL;")+ applied_legacy_versions = {row[0] for row in cursor.fetchall()}+ return not legacy_versions.issubset(applied_legacy_versions)++ @classmethod+ def _get_applied_migration_ids(cls, cursor: sqlite3.Cursor) -> set[str]:+ """Gets applied stable migration IDs."""+ try:+ cursor.execute("SELECT migration_id FROM applied_migrations;")+ return {row[0] for row in cursor.fetchall()}+ except sqlite3.OperationalError as e:+ if "no such table" in str(e):+ return set()+ raise+@classmethoddef _get_current_version(cls, cursor: sqlite3.Cursor) -> int:"""Gets the current version of the database, or 0 if the migrations table does not exist."""diff --git a/tests/app/services/shared/sqlite_migrator/test_migration_loader.py b/tests/app/services/shared/sqlite_migrator/test_migration_loader.pynew file mode 100644index 0000000000..01768ad3ba--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/test_migration_loader.py@@ -0,0 +1,252 @@+import importlib+from logging import Logger+from pathlib import Path++import pytest++from invokeai.app.services.shared.sqlite_migrator.migration_loader import (+ MigrationBuildContext,+ MigrationLoaderError,+ build_migrations,+)+++def _write_package(tmp_path: Path, package_name: str, modules: dict[str, str]) -> str:+ package_path = tmp_path / package_name+ package_path.mkdir()+ (package_path / "__init__.py").write_text("", encoding="utf-8")+ for module_name, module_source in modules.items():+ (package_path / f"{module_name}.py").write_text(module_source, encoding="utf-8")+ importlib.invalidate_caches()+ return package_name+++def test_build_migrations_discovers_modules_in_numeric_order(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_order",+ {+ "migration_2": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration_2():+ return Migration(from_version=1, to_version=2, callback=lambda cursor: None)+""",+ "migration_1": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration_1():+ return Migration(from_version=0, to_version=1, callback=lambda cursor: None)+""",+ "not_a_migration": "VALUE = 1",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ migrations = build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )++ assert [migration.id for migration in migrations] == ["migration_1", "migration_2"]+++def test_build_migrations_injects_requested_dependencies(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_injection",+ {+ "migration_1": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration_1(app_config, logger, image_files):+ assert app_config == "config"+ assert logger.name == "test"+ assert image_files == "images"+ return Migration(from_version=0, to_version=1, callback=lambda cursor: None)+""",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ migrations = build_migrations(+ MigrationBuildContext(app_config="config", logger=Logger("test"), image_files="images"),+ package_name=package_name,+ )++ assert [migration.id for migration in migrations] == ["migration_1"]+++def test_build_migrations_supports_dated_descriptive_modules(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_dated",+ {+ "migration_2026_06_30_add_example_table": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration():+ return Migration(+ id="2026_06_30_add_example_table",+ depends_on="migration_1",+ callback=lambda cursor: None,+ )+""",+ "migration_1": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration_1():+ return Migration(from_version=0, to_version=1, callback=lambda cursor: None)+""",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ migrations = build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )++ assert [migration.id for migration in migrations] == ["migration_1", "2026_06_30_add_example_table"]+++def test_build_migrations_rejects_dated_module_id_mismatch(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_dated_id_mismatch",+ {+ "migration_2026_06_30_add_example_table": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration():+ return Migration(+ id="2026_06_30_typo",+ depends_on="migration_1",+ callback=lambda cursor: None,+ )+""",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ with pytest.raises(MigrationLoaderError, match="must return migration id"):+ build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )+++def test_build_migrations_rejects_numeric_module_id_mismatch(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_numeric_id_mismatch",+ {+ "migration_1": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration_1():+ return Migration(id="wrong", from_version=0, to_version=1, callback=lambda cursor: None)+""",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ with pytest.raises(MigrationLoaderError, match="must return migration id"):+ build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )+++def test_build_migrations_rejects_unknown_builder_dependency(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_unknown_dependency",+ {+ "migration_1": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_migration_1(unknown_service):+ return Migration(from_version=0, to_version=1, callback=lambda cursor: None)+""",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ with pytest.raises(MigrationLoaderError, match="unknown dependency"):+ build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )+++def test_build_migrations_rejects_missing_expected_builder(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_missing_builder",+ {+ "migration_1": """+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+def build_something_else():+ return Migration(from_version=0, to_version=1, callback=lambda cursor: None)+""",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ with pytest.raises(MigrationLoaderError, match="build_migration_1"):+ build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )+++def test_build_migrations_rejects_non_migration_return(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_bad_return",+ {+ "migration_1": """+def build_migration_1():+ return object()+""",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ with pytest.raises(MigrationLoaderError, match="must return Migration"):+ build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )+++def test_build_migrations_rejects_malformed_migration_module(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ package_name = _write_package(+ tmp_path,+ "test_migrations_malformed",+ {+ "migration_latest": "VALUE = 1",+ },+ )+ monkeypatch.syspath_prepend(str(tmp_path))++ with pytest.raises(MigrationLoaderError, match="Malformed migration module"):+ build_migrations(+ MigrationBuildContext(app_config=object(), logger=Logger("test"), image_files=object()),+ package_name=package_name,+ )+++def test_build_migrations_discovers_production_migrations(tmp_path: Path) -> None:+ class FakeConfig:+ root_path = tmp_path+ models_path = tmp_path / "models"+ convert_cache_path = tmp_path / "models" / ".cache"+ legacy_conf_path = tmp_path / "models.yaml"+ legacy_conf_dir = tmp_path++ migrations = build_migrations(+ MigrationBuildContext(app_config=FakeConfig(), logger=Logger("test"), image_files=object())+ )+ legacy_migrations = [migration for migration in migrations if migration.to_version is not None]+ latest_legacy_version = max(migration.to_version or 0 for migration in legacy_migrations)++ assert [migration.id for migration in legacy_migrations] == [+ f"migration_{i}" for i in range(1, latest_legacy_version + 1)+ ]+ assert [migration.depends_on for migration in legacy_migrations] == [None] + [+ f"migration_{i}" for i in range(1, latest_legacy_version)+ ]diff --git a/tests/test_sqlite_migrator.py b/tests/test_sqlite_migrator.pyindex e03224b5a9..d99f2b7dcf 100644--- a/tests/test_sqlite_migrator.py+++ b/tests/test_sqlite_migrator.py@@ -111,6 +111,29 @@ def test_migration_hash(no_op_migrate_callback: MigrateCallback) -> None:assert hash(migration) == hash((0, 1))+def test_legacy_migration_gets_stable_id_and_dependency(no_op_migrate_callback: MigrateCallback) -> None:+ first_migration = Migration(from_version=0, to_version=1, callback=no_op_migrate_callback)+ second_migration = Migration(from_version=1, to_version=2, callback=no_op_migrate_callback)++ assert first_migration.id == "migration_1"+ assert first_migration.depends_on is None+ assert second_migration.id == "migration_2"+ assert second_migration.depends_on == "migration_1"+++def test_explicit_migration_id_and_dependency_are_preserved(no_op_migrate_callback: MigrateCallback) -> None:+ migration = Migration(+ id="2026_06_29_add_test_table",+ depends_on="migration_1",+ callback=no_op_migrate_callback,+ )++ assert migration.id == "2026_06_29_add_test_table"+ assert migration.depends_on == "migration_1"+ assert migration.from_version is None+ assert migration.to_version is None++def test_migration_set_add_migration(migrator: SqliteMigrator, migration_no_op: Migration) -> None:migration = migration_no_opmigrator._migration_set.register(migration)@@ -132,6 +155,14 @@ def test_migration_set_may_not_register_dupes(migrator._migration_set.register(migrate_1_to_2_b)+def test_migration_set_may_not_register_duplicate_ids(no_op_migrate_callback: MigrateCallback) -> None:+ migration_set = MigrationSet()+ migration_set.register(Migration(id="same_id", callback=no_op_migrate_callback))++ with pytest.raises(MigrationVersionError, match="Migration with id already registered"):+ migration_set.register(Migration(id="same_id", callback=no_op_migrate_callback))++def test_migration_set_gets_migration(migration_no_op: Migration) -> None:migration_set = MigrationSet()migration_set.register(migration_no_op)@@ -155,6 +186,66 @@ def test_migration_set_validates_migration_chain(no_op_migrate_callback: Migratemigration_set.validate_migration_chain()+def test_migration_set_validates_dependency_graph(no_op_migrate_callback: MigrateCallback) -> None:+ migration_set = MigrationSet()+ migration_set.register(Migration(id="a", callback=no_op_migrate_callback))+ migration_set.register(Migration(id="b", depends_on="a", callback=no_op_migrate_callback))+ migration_set.register(Migration(id="c", depends_on="a", callback=no_op_migrate_callback))+ migration_set.register(Migration(id="d", depends_on="c", callback=no_op_migrate_callback))++ migration_set.validate_dependency_graph()+++def test_migration_set_rejects_missing_dependency(no_op_migrate_callback: MigrateCallback) -> None:+ migration_set = MigrationSet()+ migration_set.register(Migration(id="a", depends_on="missing", callback=no_op_migrate_callback))++ with pytest.raises(MigrationError, match="depends on unknown migration"):+ migration_set.validate_dependency_graph()+++def test_migration_set_rejects_dependency_cycle(no_op_migrate_callback: MigrateCallback) -> None:+ migration_set = MigrationSet()+ migration_set.register(Migration(id="a", depends_on="b", callback=no_op_migrate_callback))+ migration_set.register(Migration(id="b", depends_on="a", callback=no_op_migrate_callback))++ with pytest.raises(MigrationError, match="cycle"):+ migration_set.validate_dependency_graph()+++def test_migration_set_rejects_legacy_migration_depending_on_graph_only_migration(+ no_op_migrate_callback: MigrateCallback,+) -> None:+ migration_set = MigrationSet()+ migration_set.register(Migration(id="2026_06_30_graph_only", callback=no_op_migrate_callback))+ migration_set.register(+ Migration(+ id="migration_2",+ depends_on="2026_06_30_graph_only",+ from_version=1,+ to_version=2,+ callback=no_op_migrate_callback,+ )+ )++ with pytest.raises(MigrationError, match="cannot depend on graph-only migration"):+ migration_set.validate_dependency_graph()+++def test_migration_set_plans_branching_migrations(no_op_migrate_callback: MigrateCallback) -> None:+ migration_set = MigrationSet()+ migration_a = Migration(id="a", callback=no_op_migrate_callback)+ migration_b = Migration(id="b", depends_on="a", callback=no_op_migrate_callback)+ migration_c = Migration(id="c", depends_on="a", callback=no_op_migrate_callback)+ migration_d = Migration(id="d", depends_on="c", callback=no_op_migrate_callback)+ migration_set.register(migration_d)+ migration_set.register(migration_c)+ migration_set.register(migration_b)+ migration_set.register(migration_a)++ assert migration_set.get_migration_plan(applied_migration_ids={"a", "b"}) == [migration_c, migration_d]++def test_migration_set_counts_migrations(no_op_migrate_callback: MigrateCallback) -> None:migration_set = MigrationSet()assert migration_set.count == 0@@ -197,6 +288,13 @@ def test_migrator_creates_migrations_table(migrator: SqliteMigrator) -> None:assert cursor.fetchone() is not None+def test_migrator_creates_applied_migrations_table(migrator: SqliteMigrator) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_applied_migrations_table(cursor)+ cursor.execute("SELECT * FROM sqlite_master WHERE type='table' AND name='applied_migrations';")+ assert cursor.fetchone() is not None++def test_migrator_migration_sets_version(migrator: SqliteMigrator, migration_no_op: Migration) -> None:cursor = migrator._db._conn.cursor()migrator._create_migrations_table(cursor)@@ -234,6 +332,199 @@ def test_migrator_runs_all_migrations_in_memory(migrator: SqliteMigrator) -> Nonassert migrator._get_current_version(cursor) == 3+def test_migrator_bootstraps_applied_migrations_from_legacy_versions(+ migrator: SqliteMigrator, no_op_migrate_callback: MigrateCallback+) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_migrations_table(cursor)+ cursor.execute("INSERT INTO migrations (version) VALUES (1);")+ cursor.execute("INSERT INTO migrations (version) VALUES (2);")+ cursor.connection.commit()+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))+ migrator.register_migration(Migration(from_version=1, to_version=2, callback=no_op_migrate_callback))+ migrator.register_migration(Migration(from_version=2, to_version=3, callback=no_op_migrate_callback))++ migrator.run_migrations()++ cursor.execute("SELECT migration_id FROM applied_migrations ORDER BY migration_id;")+ assert [row[0] for row in cursor.fetchall()] == ["migration_1", "migration_2", "migration_3"]+ assert migrator._get_current_version(cursor) == 3+++def test_migrator_backs_up_file_db_before_metadata_only_bootstrap(+ logger: Logger, no_op_migrate_callback: MigrateCallback+) -> None:+ with TemporaryDirectory() as tempdir:+ original_db_path = Path(tempdir) / "invokeai.db"+ db = SqliteDatabase(db_path=original_db_path, logger=logger, verbose=False)+ cursor = db._conn.cursor()+ cursor.execute("CREATE TABLE test (id INTEGER PRIMARY KEY);")+ cursor.execute(+ """--sql+ CREATE TABLE migrations (+ version INTEGER PRIMARY KEY,+ migrated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))+ );+ """+ )+ cursor.execute("INSERT INTO migrations (version) VALUES (0);")+ cursor.execute("INSERT INTO migrations (version) VALUES (1);")+ db._conn.commit()++ migrator = SqliteMigrator(db=db)+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))++ assert migrator.run_migrations() is False++ db._conn.close()+ assert migrator._backup_path is not None+ with closing(sqlite3.connect(migrator._backup_path)) as backup_db_conn:+ backup_db_cursor = backup_db_conn.cursor()+ backup_db_cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='test';")+ assert backup_db_cursor.fetchone() is not None+ backup_db_cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='applied_migrations';")+ assert backup_db_cursor.fetchone() is None+++def test_migrator_runs_branching_graph_migrations(migrator: SqliteMigrator) -> None:+ cursor = migrator._db._conn.cursor()+ executed: list[str] = []++ def create_migration(migration_id: str, depends_on: str | None) -> Migration:+ def migrate(cursor: sqlite3.Cursor) -> None:+ executed.append(migration_id)+ cursor.execute(f"CREATE TABLE {migration_id} (id INTEGER PRIMARY KEY);")++ return Migration(id=migration_id, depends_on=depends_on, callback=migrate)++ for migration in [+ create_migration("d", "c"),+ create_migration("c", "a"),+ create_migration("b", "a"),+ create_migration("a", None),+ ]:+ migrator.register_migration(migration)++ migrator.run_migrations()++ assert executed == ["a", "b", "c", "d"]+ cursor.execute("SELECT migration_id FROM applied_migrations ORDER BY migration_id;")+ assert [row[0] for row in cursor.fetchall()] == ["a", "b", "c", "d"]+++def test_migrator_rejects_unknown_applied_migration(+ migrator: SqliteMigrator, no_op_migrate_callback: MigrateCallback+) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_migrations_table(cursor)+ migrator._create_applied_migrations_table(cursor)+ cursor.execute("INSERT INTO applied_migrations (migration_id) VALUES ('future_migration');")+ cursor.connection.commit()+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))++ with pytest.raises(MigrationError, match="unknown applied migration"):+ migrator.run_migrations()+++def test_migrator_rejects_unknown_applied_migration_before_creating_legacy_table(+ migrator: SqliteMigrator, no_op_migrate_callback: MigrateCallback+) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_applied_migrations_table(cursor)+ cursor.execute("INSERT INTO applied_migrations (migration_id) VALUES ('future_migration');")+ cursor.connection.commit()+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))++ with pytest.raises(MigrationError, match="unknown applied migration"):+ migrator.run_migrations()++ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='migrations';")+ assert cursor.fetchone() is None+++def test_migrator_rejects_inconsistent_applied_legacy_version(+ migrator: SqliteMigrator, no_op_migrate_callback: MigrateCallback+) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_migrations_table(cursor)+ migrator._create_applied_migrations_table(cursor)+ cursor.execute("INSERT INTO migrations (version) VALUES (1);")+ cursor.execute("INSERT INTO migrations (version) VALUES (2);")+ cursor.execute("INSERT INTO applied_migrations (migration_id, legacy_version) VALUES ('migration_1', 2);")+ cursor.connection.commit()+ callback_ran = False++ def migration_callback(cursor: sqlite3.Cursor) -> None:+ nonlocal callback_ran+ callback_ran = True++ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))+ migrator.register_migration(Migration(from_version=1, to_version=2, callback=migration_callback))++ with pytest.raises(MigrationError, match="inconsistent applied migration state"):+ migrator.run_migrations()++ assert callback_ran is False+++def test_migrator_rejects_applied_legacy_migration_missing_legacy_row(+ migrator: SqliteMigrator, no_op_migrate_callback: MigrateCallback+) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_migrations_table(cursor)+ migrator._create_applied_migrations_table(cursor)+ cursor.execute("INSERT INTO migrations (version) VALUES (1);")+ cursor.execute("INSERT INTO applied_migrations (migration_id, legacy_version) VALUES ('migration_2', 2);")+ cursor.connection.commit()+ callback_ran = False++ def graph_migration_callback(cursor: sqlite3.Cursor) -> None:+ nonlocal callback_ran+ callback_ran = True++ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))+ migrator.register_migration(Migration(from_version=1, to_version=2, callback=no_op_migrate_callback))+ migrator.register_migration(+ Migration(id="2026_06_30_graph_migration", depends_on="migration_2", callback=graph_migration_callback)+ )++ with pytest.raises(MigrationError, match="inconsistent applied migration state"):+ migrator.run_migrations()++ assert callback_ran is False+++def test_migrator_rejects_unknown_legacy_version(+ migrator: SqliteMigrator, no_op_migrate_callback: MigrateCallback+) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_migrations_table(cursor)+ cursor.execute("INSERT INTO migrations (version) VALUES (1);")+ cursor.execute("INSERT INTO migrations (version) VALUES (2);")+ cursor.connection.commit()+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))++ with pytest.raises(MigrationError, match="unknown legacy migration version"):+ migrator.run_migrations()+++def test_migrator_rejects_unknown_legacy_version_before_creating_applied_table(+ migrator: SqliteMigrator, no_op_migrate_callback: MigrateCallback+) -> None:+ cursor = migrator._db._conn.cursor()+ migrator._create_migrations_table(cursor)+ cursor.execute("INSERT INTO migrations (version) VALUES (1);")+ cursor.execute("INSERT INTO migrations (version) VALUES (2);")+ cursor.connection.commit()+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))++ with pytest.raises(MigrationError, match="unknown legacy migration version"):+ migrator.run_migrations()++ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='applied_migrations';")+ assert cursor.fetchone() is None++def test_migrator_runs_all_migrations_file(logger: Logger) -> None:with TemporaryDirectory() as tempdir:original_db_path = Path(tempdir) / "invokeai.db"@@ -287,6 +578,8 @@ def test_migrator_makes_no_changes_on_failed_migration(with pytest.raises(MigrationError, match="Bad migration"):migrator.run_migrations()assert migrator._get_current_version(cursor) == 1+ cursor.execute("SELECT migration_id FROM applied_migrations ORDER BY migration_id;")+ assert [row[0] for row in cursor.fetchall()] == ["migration_1"]def test_idempotent_migrations(migrator: SqliteMigrator, migration_create_test_table: Migration) -> None: