Skip to content

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.

fix(wildcards): cascade wildcards when their owner is deleted

joshistoast20c80eb2ffd9
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_27_wildcards.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_27_wildcards.py
index 1e35681434..7f4873ff26 100644
--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_27_wildcards.py
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_27_wildcards.py
@@ -16,7 +16,10 @@ class WildcardsMigrationCallback:
values_json TEXT NOT NULL DEFAULT '[]',
user_id TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),
- updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW'))
+ updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),
+ -- `delete_user` is a bare DELETE FROM users; every user-owned table created
+ -- since migration_27 leans on the cascade to take its rows with it.
+ FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE
);
"""
)
@@ -49,6 +52,7 @@ def build_migration() -> Migration:
"""
return Migration(
id="2026_07_27_wildcards",
- depends_on="migration_9",
+ # migration_27 created the users table this one's owner column references.
+ depends_on="migration_27",
callback=WildcardsMigrationCallback(),
)
diff --git a/invokeai/app/services/wildcard_records/wildcard_records_sqlite.py b/invokeai/app/services/wildcard_records/wildcard_records_sqlite.py
index df578de960..c598b09cb6 100644
--- a/invokeai/app/services/wildcard_records/wildcard_records_sqlite.py
+++ b/invokeai/app/services/wildcard_records/wildcard_records_sqlite.py
@@ -13,6 +13,15 @@ from invokeai.app.services.wildcard_records.wildcard_records_common import (
from invokeai.app.util.misc import uuid_string
+def _is_name_conflict(error: sqlite3.IntegrityError) -> bool:
+ """Whether an integrity failure is the duplicate name and not, say, an unknown owner.
+
+ The table also carries a users foreign key, and reporting a missing owner as
+ "that name is taken" would send the caller chasing the wrong thing.
+ """
+ return "UNIQUE constraint failed" in str(error)
+
+
class SqliteWildcardRecordsStorage(WildcardRecordsStorageBase):
def __init__(self, db: SqliteDatabase) -> None:
super().__init__()
@@ -47,6 +56,8 @@ class SqliteWildcardRecordsStorage(WildcardRecordsStorageBase):
except sqlite3.IntegrityError as e:
# The (user_id, name) unique index is the authority on uniqueness, so a concurrent
# create loses here rather than in a check-then-insert race.
+ if not _is_name_conflict(e):
+ raise
raise WildcardNameConflictError(f"A wildcard named '{wildcard.name}' already exists") from e
return self.get(wildcard_id)
@@ -68,6 +79,8 @@ class SqliteWildcardRecordsStorage(WildcardRecordsStorageBase):
(json.dumps(changes.values), wildcard_id),
)
except sqlite3.IntegrityError as e:
+ if not _is_name_conflict(e):
+ raise
raise WildcardNameConflictError(f"A wildcard named '{changes.name}' already exists") from e
return self.get(wildcard_id)
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_07_27_wildcards.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_07_27_wildcards.py
new file mode 100644
index 0000000000..21db87d23d
--- /dev/null
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_07_27_wildcards.py
@@ -0,0 +1,101 @@
+import sqlite3
+
+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_07_27_wildcards import (
+ WildcardsMigrationCallback,
+ build_migration,
+)
+
+
+def _migrated_db() -> sqlite3.Connection:
+ db = sqlite3.connect(":memory:")
+ db.execute("PRAGMA foreign_keys = ON;")
+ # Created by migration_27, which this migration depends on.
+ db.execute("CREATE TABLE users (user_id TEXT NOT NULL PRIMARY KEY);")
+
+ WildcardsMigrationCallback()(db.cursor())
+
+ return db
+
+
+def _insert_wildcard(db: sqlite3.Connection, wildcard_id: str, name: str, user_id: str) -> None:
+ db.execute(
+ "INSERT INTO wildcards (id, name, values_json, user_id) VALUES (?, ?, '[]', ?);",
+ (wildcard_id, name, user_id),
+ )
+
+
+def test_creates_the_wildcards_table_with_a_unique_name_per_owner() -> None:
+ db = _migrated_db()
+ db.execute("INSERT INTO users VALUES ('u1');")
+ db.execute("INSERT INTO users VALUES ('u2');")
+
+ _insert_wildcard(db, "w1", "colors", "u1")
+ # The same name is free for a different owner.
+ _insert_wildcard(db, "w2", "colors", "u2")
+
+ try:
+ _insert_wildcard(db, "w3", "colors", "u1")
+ raise AssertionError("expected a unique constraint failure")
+ except sqlite3.IntegrityError as e:
+ assert "UNIQUE constraint failed" in str(e)
+
+ db.close()
+
+
+def test_wildcards_cascade_when_their_owner_is_deleted() -> None:
+ db = _migrated_db()
+ db.execute("INSERT INTO users VALUES ('u1');")
+ _insert_wildcard(db, "w1", "colors", "u1")
+
+ db.execute("DELETE FROM users WHERE user_id = 'u1';")
+
+ assert db.execute("SELECT COUNT(*) FROM wildcards;").fetchone()[0] == 0
+
+ db.close()
+
+
+def test_an_unknown_owner_is_rejected() -> None:
+ db = _migrated_db()
+
+ try:
+ _insert_wildcard(db, "w1", "colors", "ghost")
+ raise AssertionError("expected a foreign key failure")
+ except sqlite3.IntegrityError as e:
+ assert "FOREIGN KEY constraint failed" in str(e)
+
+ db.close()
+
+
+def test_the_updated_at_trigger_fires_on_update() -> None:
+ db = _migrated_db()
+ db.execute("INSERT INTO users VALUES ('u1');")
+ db.execute(
+ "INSERT INTO wildcards (id, name, values_json, user_id, updated_at)"
+ " VALUES ('w1', 'colors', '[]', 'u1', '2000-01-01 00:00:00.000');"
+ )
+
+ db.execute("UPDATE wildcards SET name = 'shades' WHERE id = 'w1';")
+
+ assert db.execute("SELECT updated_at FROM wildcards WHERE id = 'w1';").fetchone()[0] != "2000-01-01 00:00:00.000"
+
+ db.close()
+
+
+def test_migration_is_idempotent() -> None:
+ db = _migrated_db()
+
+ WildcardsMigrationCallback()(db.cursor())
+
+ assert db.execute("SELECT COUNT(*) FROM wildcards;").fetchone()[0] == 0
+
+ db.close()
+
+
+def test_build_migration_declares_stable_id_and_dependency() -> None:
+ migration = build_migration()
+
+ assert migration.id == "2026_07_27_wildcards"
+ # migration_27 creates the users table the foreign key points at.
+ assert migration.depends_on == "migration_27"
+ assert migration.from_version is None
+ assert migration.to_version is None
diff --git a/tests/app/services/test_wildcard_records.py b/tests/app/services/test_wildcard_records.py
index d06247c2ff..ea594b4e0f 100644
--- a/tests/app/services/test_wildcard_records.py
+++ b/tests/app/services/test_wildcard_records.py
@@ -1,9 +1,11 @@
import logging
+import sqlite3
import pytest
from dynamicprompts.generators import CombinatorialPromptGenerator
from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.wildcard_records.wildcard_records_common import (
WildcardChanges,
WildcardNameConflictError,
@@ -17,8 +19,21 @@ from tests.fixtures.sqlite_database import create_mock_sqlite_database
@pytest.fixture
-def store() -> SqliteWildcardRecordsStorage:
- db = create_mock_sqlite_database(InvokeAIAppConfig(use_memory_db=True), logging.getLogger(__name__))
+def db() -> SqliteDatabase:
+ database = create_mock_sqlite_database(InvokeAIAppConfig(use_memory_db=True), logging.getLogger(__name__))
+ # Wildcards cascade from their owner, so the owners have to exist. Inserted
+ # directly rather than through UserService: these tests are about storage, and
+ # the only columns the foreign key needs are the ones without a default.
+ with database.transaction() as cursor:
+ cursor.executemany(
+ "INSERT INTO users (user_id, email, password_hash) VALUES (?, ?, ?);",
+ [(user_id, f"{user_id}@example.com", "unused") for user_id in ("user-1", "user-2")],
+ )
+ return database
+
+
+def store(db: SqliteDatabase) -> SqliteWildcardRecordsStorage:
return SqliteWildcardRecordsStorage(db=db)
@@ -72,6 +87,29 @@ def test_delete_removes_the_record(store: SqliteWildcardRecordsStorage) -> None:
store.get(created.id)
+def test_deleting_the_owner_takes_their_wildcards_with_it(
+ db: SqliteDatabase, store: SqliteWildcardRecordsStorage
+) -> None:
+ # `UserService.delete` is a bare DELETE FROM users; without the cascade these
+ # rows would survive their owner, unreachable but forever.
+ kept = store.create(WildcardWithoutId(name="colors", values=["red"]), user_id="user-2")
+ orphaned = store.create(WildcardWithoutId(name="colors", values=["red"]), user_id="user-1")
+
+ with db.transaction() as cursor:
+ cursor.execute("DELETE FROM users WHERE user_id = ?;", ("user-1",))
+
+ with pytest.raises(WildcardNotFoundError):
+ store.get(orphaned.id)
+ assert [w.id for w in store.get_many("user-2")] == [kept.id]
+
+
+def test_an_unknown_owner_is_not_reported_as_a_name_conflict(store: SqliteWildcardRecordsStorage) -> None:
+ # The name is free; it is the owner that does not exist. Mapping this to a
+ # conflict would send the caller renaming a wildcard that is fine.
+ with pytest.raises(sqlite3.IntegrityError):
+ store.create(WildcardWithoutId(name="colors", values=["red"]), user_id="ghost")
+
+
@pytest.mark.parametrize(
"name",
[