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
fix(migrations): keep an unmigrated shared root openable
Josh Corbettae753451d6bb
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_30_repair_projects_table.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_30_repair_projects_table.pyindex bd101fd31f..1399a031b2 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_30_repair_projects_table.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_30_repair_projects_table.py@@ -68,7 +68,13 @@ def build_migration() -> Migration:# migration_33 is where `projects` should have been created. Depending on it is correct in# both cases: on a fork database it genuinely ran, and on an upstream-originated database# its id is recorded (by upstream's unrelated migration), so the dependency still resolves.- # It also transitively guarantees migration_27's `users` table, which the FK references.+ #+ # It does *not* guarantee migration_27's `users` table, for exactly the reason this+ # migration exists: an upstream-originated database has migration_27's id recorded too,+ # against upstream's unrelated migration of that number, so the fork's never runs there.+ # The FK below survives that because SQLite does not resolve a foreign key until DML — but+ # anything that *reads* `users` has to check first, which is what+ # `2026_08_06_add_project_boards` does.depends_on="migration_33",callback=RepairProjectsTableMigrationCallback(),)diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.pyindex 929407df02..1ffdeb94af 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py@@ -22,8 +22,9 @@ project that adopts the wrong board takes ownership of media it does not own.Nothing is moved between boards. `board_images` and `board_videos` are read but never written, so noimage or video changes hands here. The projects table gains a column, boards may gain rows and a new-name, and an FK-free quarantine table is created only when a legacy project refers to a user row-that no longer exists.+name, and an FK-free quarantine table is created only when a legacy project refers to a user row it+cannot reach — either because that account is gone, or because the database has no `users` table at+all. See `_quarantine_every_project` for how the second case arises."""import json@@ -48,8 +49,16 @@ class AddProjectBoardsMigrationCallback:self._logger = loggerdef __call__(self, cursor: sqlite3.Cursor) -> None:- self._quarantine_orphaned_projects(cursor)- assignments = self._assign_boards(cursor)+ if _table_exists(cursor, "users"):+ self._quarantine_orphaned_projects(cursor)+ assignments = self._assign_boards(cursor)+ else:+ # No project can survive a rebuild whose foreign key has no table to point at, so every+ # one of them is quarantined and none is assigned a board. See+ # `_quarantine_every_project` for why a database can reach this migration in that state.+ self._quarantine_every_project(cursor)+ assignments = []+self._rebuild_projects_table(cursor, assignments)def _quarantine_orphaned_projects(self, cursor: sqlite3.Cursor) -> None:@@ -74,21 +83,7 @@ class AddProjectBoardsMigrationCallback:if not orphans:return- cursor.execute(- """--sql- CREATE TABLE IF NOT EXISTS orphaned_projects_2026_08_06 (- project_id TEXT NOT NULL,- user_id TEXT NOT NULL,- name TEXT NOT NULL,- data TEXT NOT NULL,- revision INTEGER NOT NULL,- created_at DATETIME NOT NULL,- updated_at DATETIME NOT NULL,- quarantined_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),- PRIMARY KEY (user_id, project_id)- );- """- )+ self._create_quarantine_table(cursor)cursor.execute("""--sqlINSERT OR IGNORE INTO orphaned_projects_2026_08_06@@ -111,6 +106,67 @@ class AddProjectBoardsMigrationCallback:""")+ def _quarantine_every_project(self, cursor: sqlite3.Cursor) -> None:+ """The same rescue, for a database that has no `users` table at all.++ `users` is created by *this fork's* `migration_27`. A root last opened by an upstream build+ at schema version 27 or later already has that id recorded, against upstream's unrelated+ migration of the same number, so the fork's version never runs there — the same shared-root+ divergence `2026_07_30_repair_projects_table` exists to handle for `projects`. Every earlier+ reference to `users` was a foreign key clause, which SQLite does not resolve until DML, so+ such a root opened without complaint until this migration became the first to read the table.++ Note what is *not* done here: the rows are copied out but never deleted. With the foreign key+ enforced and its target missing, SQLite refuses any DML against `projects` — including a+ `DELETE`. Dropping the table in the rebuild is what removes them, and that needs no+ resolution.+ """+ cursor.execute(+ """--sql+ SELECT project_id, user_id FROM projects;+ """+ )+ projects = cursor.fetchall()++ if not projects:+ return++ self._create_quarantine_table(cursor)+ cursor.execute(+ """--sql+ INSERT OR IGNORE INTO orphaned_projects_2026_08_06+ (project_id, user_id, name, data, revision, created_at, updated_at)+ SELECT project_id, user_id, name, data, revision, created_at, updated_at+ FROM projects;+ """+ )++ for project_id, user_id in projects:+ self._logger.warning(+ f"Project boards migration: quarantining project {project_id} in"+ " orphaned_projects_2026_08_06. This database has no users table, so its owner"+ f" {user_id} cannot be resolved — it was last opened by an upstream build and this"+ " fork's multiuser migration never ran on it."+ )++ def _create_quarantine_table(self, cursor: sqlite3.Cursor) -> None:+ """Deliberately free of foreign keys, so it can hold rows the live table cannot."""+ cursor.execute(+ """--sql+ CREATE TABLE IF NOT EXISTS orphaned_projects_2026_08_06 (+ project_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ name TEXT NOT NULL,+ data TEXT NOT NULL,+ revision INTEGER NOT NULL,+ created_at DATETIME NOT NULL,+ updated_at DATETIME NOT NULL,+ quarantined_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),+ PRIMARY KEY (user_id, project_id)+ );+ """+ )+def _assign_boards(self, cursor: sqlite3.Cursor) -> list[tuple[int, str]]:"""Resolve one board per project, creating boards as needed.@@ -252,6 +308,12 @@ class AddProjectBoardsMigrationCallback:# body out from under us.cursor.execute("DROP TRIGGER IF EXISTS tg_projects_updated_at;")+ # The migrator runs this whole callback in one transaction, so a half-finished rebuild is+ # not reachable through it. This is for the database that met a build predating that+ # guarantee: without it such a database fails forever on `table projects_with_boards+ # already exists`, and the scratch table is worthless in every other case anyway.+ cursor.execute("DROP TABLE IF EXISTS projects_with_boards;")+cursor.execute("""--sqlCREATE TABLE projects_with_boards (@@ -308,6 +370,11 @@ class AddProjectBoardsMigrationCallback:)+def _table_exists(cursor: sqlite3.Cursor, name: str) -> bool:+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?;", (name,))+ return cursor.fetchone() is not None++def _collect_board_candidates(data: str) -> set[str]:"""Every distinct non-empty `projectBoardId` a project document names.diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.pyindex 96ef0e28f3..b6f3a20d69 100644--- a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py@@ -357,6 +357,50 @@ def test_a_project_whose_owner_is_gone_is_quarantined_before_the_live_table_is_rassert any("orphan" in warning for warning in warnings)+def test_a_database_with_no_users_table_migrates_instead_of_refusing_to_open() -> None:+ """A root last opened by an upstream build has this fork's `migration_27` recorded against+ upstream's unrelated migration of that number, so `users` was never created. Reading it+ unguarded turns the first start on such a root into a `MigrationError` that no restart clears —+ and the root opened fine before this migration existed, because a foreign key alone is not+ resolved until DML."""+ db = _make_db()+ db.execute("DROP TABLE users;")+ db.commit()++ logger = Logger("migration-test")+ warnings: list[str] = []+ logger.warning = warnings.append # type: ignore[method-assign]+ AddProjectBoardsMigrationCallback(logger)(db.cursor())++ columns = {row[1] for row in db.execute("PRAGMA table_info(projects);").fetchall()}+ assert "board_id" in columns+ assert db.execute("SELECT COUNT(*) FROM projects;").fetchone()[0] == 0+ assert warnings == []+++def test_a_project_on_a_database_with_no_users_table_is_quarantined_rather_than_dropped() -> None:+ """No row can satisfy the rebuilt table's foreign key when its target does not exist, so every+ project is an orphan — but its document is still the only copy of someone's work."""+ db = _make_db()+ db.execute("PRAGMA foreign_keys = OFF;")+ _add_project(db, "stranded", name="Stranded")+ db.commit()+ db.execute("DROP TABLE users;")+ db.commit()+ db.execute("PRAGMA foreign_keys = ON;")++ logger = Logger("migration-test")+ warnings: list[str] = []+ logger.warning = warnings.append # type: ignore[method-assign]+ AddProjectBoardsMigrationCallback(logger)(db.cursor())++ assert db.execute("SELECT COUNT(*) FROM projects;").fetchone()[0] == 0+ assert db.execute("SELECT project_id, name FROM orphaned_projects_2026_08_06;").fetchall() == [+ ("stranded", "Stranded")+ ]+ assert any("no users table" in warning for warning in warnings)++def test_a_long_project_name_is_truncated_to_what_the_board_api_accepts() -> None:db = _make_db()_add_user(db, "u1")@@ -544,3 +588,31 @@ def test_it_runs_once_through_the_real_migrator_and_is_not_reapplied(tmp_path: Pfor migration in all_migrations:again.register_migration(migration)assert again.run_migrations() is False+++def test_it_runs_through_the_real_migrator_on_a_database_with_no_projects(tmp_path: Path) -> None:+ """The install that has never made a project is the majority of installs, and it is the one the+ seeded end-to-end test above cannot speak for: with no project there is no `INSERT`, so the+ rebuild is pure DDL and its atomicity depends on the migrator rather than on luck."""+ logger = Logger("test")+ context = MigrationBuildContext(app_config=MagicMock(), logger=logger, image_files=MagicMock())+ all_migrations = build_migrations(context)++ db = SqliteDatabase(db_path=tmp_path / "projects.db", logger=logger, verbose=False)+ migrator = SqliteMigrator(db=db)+ for migration in all_migrations:+ migrator.register_migration(migration)+ assert migrator.run_migrations() is True++ cursor = db._conn.cursor()+ columns = {row[1] for row in cursor.execute("PRAGMA table_info(projects);").fetchall()}+ assert "board_id" in columns+ cursor.execute("SELECT COUNT(*) FROM projects;")+ assert cursor.fetchone()[0] == 0+ # The scratch table must not outlive the rebuild, and the trigger must be back.+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='projects_with_boards';")+ assert cursor.fetchone() is None+ cursor.execute("SELECT name FROM sqlite_master WHERE type='trigger' AND name='tg_projects_updated_at';")+ assert cursor.fetchone() is not None+ cursor.execute("PRAGMA foreign_key_check;")+ assert cursor.fetchall() == []