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.

feat(app): index the media that saved projects and workflows reference

Josh Corbettcab427120e32
diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.py
index 8bc9e4cc92..4ecf26c93d 100644
--- a/invokeai/app/services/project_records/project_records_sqlite.py
+++ b/invokeai/app/services/project_records/project_records_sqlite.py
@@ -26,6 +26,11 @@ from invokeai.app.services.project_records.project_records_common import (
ProjectRecordNotFoundError,
ProjectSummaryDTO,
)
+from invokeai.app.services.shared.media_references import (
+ delete_media_references,
+ extract_media_references,
+ replace_media_references,
+)
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.util.misc import uuid_string
@@ -112,6 +117,15 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
minimum_canvas_schema_version,
),
)
+ # Indexed on the same transaction as the document: a reader can never see a saved
+ # project whose referenced media the intermediates cleanup does not know about.
+ replace_media_references(
+ cursor,
+ owner_kind="project",
+ user_id=user_id,
+ owner_id=project_id,
+ references=extract_media_references(data),
+ )
record = self._fetch_record(cursor, user_id=user_id, project_id=project_id)
except sqlite3.IntegrityError as e:
# The board insert/rename rolls back with the project insert, so a rejected create never
@@ -272,6 +286,13 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
""",
(name[:BOARD_NAME_MAX_LENGTH], user_id, project_id),
)
+ replace_media_references(
+ cursor,
+ owner_kind="project",
+ user_id=user_id,
+ owner_id=project_id,
+ references=extract_media_references(data),
+ )
record = self._fetch_record(cursor, user_id=user_id, project_id=project_id)
if record is None:
@@ -330,6 +351,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):
""",
(user_id, project_id),
)
+ delete_media_references(cursor, owner_kind="project", user_id=user_id, owner_id=project_id)
# Only after the project is gone: the board FK is RESTRICT, so a claimed board cannot be
# deleted. Deleting the board cascades its memberships, returning the media to
# Uncategorized; the image and video records and their files are untouched.
diff --git a/invokeai/app/services/shared/media_references.py b/invokeai/app/services/shared/media_references.py
new file mode 100644
index 0000000000..1c83562a69
--- /dev/null
+++ b/invokeai/app/services/shared/media_references.py
@@ -0,0 +1,122 @@
+"""Media references named by saved documents.
+
+Project documents and library workflows are opaque JSON to the server, but the assets they name
+are not opaque to cleanup: an intermediate a saved document still points at (a canvas staging
+candidate, a cropped reference image) must not be collected as garbage. The `media_references`
+table is that index. It is written in the same transaction as the document it describes, so a
+save and its references are never observed apart, and the extractor here is the one definition of
+"names a media asset" for both writers and the migration that backfills existing documents.
+
+Extraction is deliberately over-inclusive: every string under an image- or video-name key counts,
+history included. A false reference retains a file; a missed one deletes something in use.
+"""
+
+import sqlite3
+from dataclasses import dataclass, field
+from typing import Literal
+
+MediaReferenceOwnerKind = Literal["project", "workflow"]
+MediaKind = Literal["image", "video"]
+
+IMAGE_NAME_KEYS = frozenset({"imageName", "image_name"})
+VIDEO_NAME_KEYS = frozenset({"videoName", "video_name"})
+
+# Bounds a pathological document: names are generated UUID filenames, so anything longer is not
+# one and is not worth a row.
+_MAX_NAME_LENGTH = 255
+
+
+@dataclass
+class MediaReferences:
+ images: set[str] = field(default_factory=set)
+ videos: set[str] = field(default_factory=set)
+
+ def is_empty(self) -> bool:
+ return not self.images and not self.videos
+
+
+def extract_media_references(document: object) -> MediaReferences:
+ """Collects every image and video name a JSON-like document names, at any depth."""
+ references = MediaReferences()
+ # Iterative: project documents nest deeply enough that recursion depth is not a bound worth
+ # trusting.
+ pending: list[object] = [document]
+ while pending:
+ node = pending.pop()
+ if isinstance(node, list):
+ pending.extend(node)
+ continue
+ if not isinstance(node, dict):
+ continue
+ for key, value in node.items():
+ if isinstance(value, str):
+ if not value or len(value) > _MAX_NAME_LENGTH:
+ continue
+ if key in IMAGE_NAME_KEYS:
+ references.images.add(value)
+ elif key in VIDEO_NAME_KEYS:
+ references.videos.add(value)
+ continue
+ if isinstance(value, (dict, list)):
+ pending.append(value)
+ return references
+
+
+def replace_media_references(
+ cursor: sqlite3.Cursor,
+ *,
+ owner_kind: MediaReferenceOwnerKind,
+ user_id: str,
+ owner_id: str,
+ references: MediaReferences,
+) -> None:
+ """Makes the index for one owner equal to `references`, on the caller's transaction."""
+ delete_media_references(cursor, owner_kind=owner_kind, user_id=user_id, owner_id=owner_id)
+ rows: list[tuple[str, str, str, str, str]] = []
+ rows.extend((owner_kind, user_id, owner_id, "image", name) for name in sorted(references.images))
+ rows.extend((owner_kind, user_id, owner_id, "video", name) for name in sorted(references.videos))
+ if rows:
+ cursor.executemany(
+ """--sql
+ INSERT OR IGNORE INTO media_references (owner_kind, user_id, owner_id, media_kind, media_name)
+ VALUES (?, ?, ?, ?, ?);
+ """,
+ rows,
+ )
+
+
+def delete_media_references(
+ cursor: sqlite3.Cursor, *, owner_kind: MediaReferenceOwnerKind, user_id: str, owner_id: str
+) -> None:
+ cursor.execute(
+ """--sql
+ DELETE FROM media_references
+ WHERE owner_kind = ? AND user_id = ? AND owner_id = ?;
+ """,
+ (owner_kind, user_id, owner_id),
+ )
+
+
+def create_media_references_table(cursor: sqlite3.Cursor) -> None:
+ """DDL shared by the migration and tests that need the table without the whole chain."""
+ cursor.execute(
+ """--sql
+ CREATE TABLE IF NOT EXISTS media_references (
+ -- 'project' or 'workflow'
+ owner_kind TEXT NOT NULL,
+ -- The owning account; project ids are unique per user, not globally.
+ user_id TEXT NOT NULL,
+ owner_id TEXT NOT NULL,
+ -- 'image' or 'video'
+ media_kind TEXT NOT NULL,
+ media_name TEXT NOT NULL,
+ PRIMARY KEY (owner_kind, user_id, owner_id, media_kind, media_name)
+ );
+ """
+ )
+ cursor.execute(
+ """--sql
+ CREATE INDEX IF NOT EXISTS idx_media_references_media
+ ON media_references(media_kind, media_name);
+ """
+ )
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_22_add_intermediates_management.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_22_add_intermediates_management.py
new file mode 100644
index 0000000000..c287fd0778
--- /dev/null
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_22_add_intermediates_management.py
@@ -0,0 +1,122 @@
+"""Schema for the intermediates manager.
+
+Intermediates could only ever be cleared instance-wide, and nothing recorded which project made a
+file, how large it is, or whether a saved document still needs it. This migration adds:
+
+- `session_queue.project_id`: the project a batch was enqueued for. `Batch.project_id` was validated
+ at enqueue and then dropped; persisting it lets outputs inherit it.
+- `images.project_id` / `videos.project_id`: where the media originated. Existing rows stay NULL
+ ("unassigned"): board membership and free-form queue origins are not provenance, so nothing is
+ inferred.
+- `images.file_size_bytes` / `videos.file_size_bytes`: on-disk size of the media file plus its
+ thumbnail (and video sidecar). NULL means not yet measured, never zero.
+- `media_references`: the assets every saved project document and library workflow names, backfilled
+ here from the existing rows and kept current by their writers from now on.
+"""
+
+import json
+import sqlite3
+from logging import Logger
+
+from invokeai.app.services.shared.media_references import (
+ create_media_references_table,
+ extract_media_references,
+)
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration
+
+
+class AddIntermediatesManagementCallback:
+ def __init__(self, logger: Logger) -> None:
+ self._logger = logger
+
+ def __call__(self, cursor: sqlite3.Cursor) -> None:
+ self._add_column(cursor, "session_queue", "project_id", "TEXT")
+ for table in ("images", "videos"):
+ if not _table_exists(cursor, table):
+ continue
+ self._add_column(cursor, table, "project_id", "TEXT")
+ self._add_column(cursor, table, "file_size_bytes", "INTEGER")
+ # Summaries group intermediates by owner and project; the partial index keeps that off
+ # the far larger durable population.
+ cursor.execute(
+ f"""--sql
+ CREATE INDEX IF NOT EXISTS idx_{table}_intermediate_scope
+ ON {table}(user_id, project_id)
+ WHERE is_intermediate = TRUE;
+ """
+ )
+ create_media_references_table(cursor)
+ self._backfill_references(cursor)
+
+ @staticmethod
+ def _add_column(cursor: sqlite3.Cursor, table: str, column: str, declaration: str) -> None:
+ cursor.execute(f"PRAGMA table_info({table});")
+ if any(row[1] == column for row in cursor.fetchall()):
+ return
+ cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration};")
+
+ def _backfill_references(self, cursor: sqlite3.Cursor) -> None:
+ # Only a database that has never had the table needs the backfill; on one that already
+ # migrated, the writers have kept it current and re-deriving would only race them.
+ cursor.execute("SELECT COUNT(*) FROM media_references;")
+ if cursor.fetchone()[0] != 0:
+ return
+
+ indexed = 0
+ if _table_exists(cursor, "projects"):
+ indexed += self._index_rows(
+ cursor,
+ owner_kind="project",
+ select="SELECT user_id, project_id, data FROM projects ORDER BY rowid ASC;",
+ )
+ if _table_exists(cursor, "workflow_library"):
+ indexed += self._index_rows(
+ cursor,
+ owner_kind="workflow",
+ select="SELECT user_id, workflow_id, workflow FROM workflow_library ORDER BY rowid ASC;",
+ )
+ if indexed:
+ self._logger.info(f"Intermediates management migration: indexed media references of {indexed} document(s)")
+
+ def _index_rows(self, cursor: sqlite3.Cursor, *, owner_kind: str, select: str) -> int:
+ # A second cursor streams the documents one at a time: `data` is a whole project document,
+ # and the writes below run on `cursor`, which would discard a result set being iterated.
+ reader = cursor.connection.cursor()
+ reader.execute(select)
+ indexed = 0
+ for user_id, owner_id, document_json in reader:
+ try:
+ document = json.loads(document_json)
+ except (TypeError, ValueError):
+ self._logger.warning(
+ f"Intermediates management migration: {owner_kind} {owner_id} of {user_id} is not valid JSON;"
+ " its media references are not indexed"
+ )
+ continue
+ references = extract_media_references(document)
+ rows = [(owner_kind, user_id or "system", owner_id, "image", name) for name in sorted(references.images)]
+ rows += [(owner_kind, user_id or "system", owner_id, "video", name) for name in sorted(references.videos)]
+ if rows:
+ cursor.executemany(
+ """--sql
+ INSERT OR IGNORE INTO media_references (owner_kind, user_id, owner_id, media_kind, media_name)
+ VALUES (?, ?, ?, ?, ?);
+ """,
+ rows,
+ )
+ indexed += 1
+ reader.close()
+ return indexed
+
+
+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 build_migration(logger: Logger) -> Migration:
+ return Migration(
+ id="2026_09_22_add_intermediates_management",
+ depends_on="2026_09_16_add_qwen3_vl_encoder_variant",
+ callback=AddIntermediatesManagementCallback(logger),
+ )
diff --git a/invokeai/app/services/users/users_default.py b/invokeai/app/services/users/users_default.py
index 4babdd586c..328abf70fc 100644
--- a/invokeai/app/services/users/users_default.py
+++ b/invokeai/app/services/users/users_default.py
@@ -263,6 +263,10 @@ class UserService(UserServiceBase):
cursor.execute("BEGIN IMMEDIATE")
self._assert_not_last_admin(cursor, user_id, is_deleting=True)
cursor.execute("DELETE FROM users WHERE user_id = ?", (user_id,))
+ # Projects cascade with the account; the media references their documents held would
+ # otherwise protect a departed account's intermediates from every cleanup forever.
+ # Workflows do not cascade, so their references stay with them.
+ cursor.execute("DELETE FROM media_references WHERE user_id = ? AND owner_kind = 'project'", (user_id,))
def authenticate(self, email: str, password: str) -> UserDTO | None:
"""Authenticate user credentials."""
diff --git a/invokeai/app/services/workflow_records/workflow_records_sqlite.py b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
index b8edf6feaf..12cbe28b63 100644
--- a/invokeai/app/services/workflow_records/workflow_records_sqlite.py
+++ b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
@@ -1,7 +1,12 @@
+import sqlite3
from pathlib import Path
from typing import Optional
from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.media_references import (
+ extract_media_references,
+ replace_media_references,
+)
from invokeai.app.services.shared.pagination import PaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
@@ -71,6 +76,7 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
""",
(workflow_with_id.id, workflow_with_id.model_dump_json(), user_id, is_public),
)
+ self._index_references(cursor, workflow_with_id, user_id=user_id)
return self.get(workflow_with_id.id)
def update(self, workflow: Workflow, user_id: Optional[str] = None) -> WorkflowRecordDTO:
@@ -96,6 +102,10 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
""",
(workflow.model_dump_json(), workflow.id),
)
+ if cursor.rowcount:
+ self._index_references(
+ cursor, workflow, user_id=user_id if user_id is not None else self._owner_of(cursor, workflow.id)
+ )
return self.get(workflow.id)
def delete(self, workflow_id: str, user_id: Optional[str] = None) -> None:
@@ -119,6 +129,13 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
""",
(workflow_id,),
)
+ if cursor.rowcount:
+ # The row is gone, so its owner is the only fact left to delete by; every owner's
+ # rows for this id are dropped since workflow ids are globally unique.
+ cursor.execute(
+ "DELETE FROM media_references WHERE owner_kind = 'workflow' AND owner_id = ?;",
+ (workflow_id,),
+ )
return None
def update_is_public(self, workflow_id: str, is_public: bool, user_id: Optional[str] = None) -> WorkflowRecordDTO:
@@ -156,6 +173,22 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
)
return self.get(workflow_id)
+ def _index_references(self, cursor: sqlite3.Cursor, workflow: Workflow, *, user_id: str) -> None:
+ """Records the media a library workflow names, on the caller's transaction."""
+ replace_media_references(
+ cursor,
+ owner_kind="workflow",
+ user_id=user_id,
+ owner_id=workflow.id,
+ references=extract_media_references(workflow.model_dump(mode="json")),
+ )
+
+ @staticmethod
+ def _owner_of(cursor: sqlite3.Cursor, workflow_id: str) -> str:
+ cursor.execute("SELECT user_id FROM workflow_library WHERE workflow_id = ?;", (workflow_id,))
+ row = cursor.fetchone()
+ return str(row[0]) if row is not None and row[0] is not None else WORKFLOW_LIBRARY_DEFAULT_USER_ID
+
def get_many(
self,
order_by: WorkflowRecordOrderBy,
diff --git a/tests/app/services/project_records/test_project_records.py b/tests/app/services/project_records/test_project_records.py
index 3872809dd1..aebea1ffbf 100644
--- a/tests/app/services/project_records/test_project_records.py
+++ b/tests/app/services/project_records/test_project_records.py
@@ -749,3 +749,53 @@ def test_snapshotting_someone_elses_project_is_not_found(
with pytest.raises(ProjectRecordNotFoundError):
project_records.get_board_snapshot(other_user_id, created.project_id)
+
+
+def _media_references(db: SqliteDatabase, project_id: str) -> set[tuple[str, str]]:
+ with db.transaction() as cursor:
+ cursor.execute(
+ "SELECT media_kind, media_name FROM media_references WHERE owner_kind = 'project' AND owner_id = ?;",
+ (project_id,),
+ )
+ return {tuple(row) for row in cursor.fetchall()}
+
+
+def test_saving_a_project_indexes_the_media_it_references(
+ db: SqliteDatabase, project_records: ProjectRecordsSqlite
+) -> None:
+ created = project_records.create(
+ SYSTEM_USER_ID,
+ "Refs",
+ {"canvas": {"stagingArea": {"pendingImages": [{"imageName": "staged.png"}]}}, "video": {"video_name": "a.mp4"}},
+ )
+ assert _media_references(db, created.project_id) == {("image", "staged.png"), ("video", "a.mp4")}
+
+ project_records.update(
+ SYSTEM_USER_ID,
+ created.project_id,
+ expected_revision=1,
+ name="Refs",
+ data={"layers": [{"image_name": "layer.png"}]},
+ )
+ assert _media_references(db, created.project_id) == {("image", "layer.png")}
+
+
+def test_a_refused_save_leaves_the_reference_index_untouched(
+ db: SqliteDatabase, project_records: ProjectRecordsSqlite
+) -> None:
+ created = project_records.create(SYSTEM_USER_ID, "Refs", {"image_name": "first.png"})
+
+ with pytest.raises(ProjectRecordConflictError):
+ project_records.update(
+ SYSTEM_USER_ID, created.project_id, expected_revision=99, name="Refs", data={"image_name": "second.png"}
+ )
+
+ assert _media_references(db, created.project_id) == {("image", "first.png")}
+
+
+def test_deleting_a_project_drops_its_references(db: SqliteDatabase, project_records: ProjectRecordsSqlite) -> None:
+ created = project_records.create(SYSTEM_USER_ID, "Refs", {"image_name": "first.png"})
+
+ project_records.delete(SYSTEM_USER_ID, created.project_id)
+
+ assert _media_references(db, created.project_id) == set()
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_22_add_intermediates_management.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_22_add_intermediates_management.py
new file mode 100644
index 0000000000..764564ec29
--- /dev/null
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_22_add_intermediates_management.py
@@ -0,0 +1,102 @@
+"""The intermediates-management schema: provenance/size columns and the media reference index."""
+
+import json
+import sqlite3
+from logging import getLogger
+
+import pytest
+
+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_22_add_intermediates_management import (
+ build_migration,
+)
+
+
+def cursor() -> sqlite3.Cursor:
+ connection = sqlite3.connect(":memory:")
+ connection.execute("CREATE TABLE users (user_id TEXT NOT NULL PRIMARY KEY);")
+ connection.execute(
+ "CREATE TABLE images (image_name TEXT NOT NULL PRIMARY KEY, user_id TEXT DEFAULT 'system',"
+ " is_intermediate BOOLEAN DEFAULT FALSE);"
+ )
+ connection.execute(
+ "CREATE TABLE videos (video_name TEXT NOT NULL PRIMARY KEY, user_id TEXT NOT NULL DEFAULT 'system',"
+ " is_intermediate BOOLEAN DEFAULT FALSE);"
+ )
+ connection.execute(
+ "CREATE TABLE session_queue (item_id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL);"
+ )
+ connection.execute(
+ "CREATE TABLE projects (project_id TEXT NOT NULL, user_id TEXT NOT NULL, data TEXT NOT NULL,"
+ " PRIMARY KEY (user_id, project_id));"
+ )
+ connection.execute(
+ "CREATE TABLE workflow_library (workflow_id TEXT NOT NULL PRIMARY KEY, workflow TEXT NOT NULL,"
+ " user_id TEXT DEFAULT 'system');"
+ )
+ return connection.cursor()
+
+
+def _run(cursor: sqlite3.Cursor) -> None:
+ build_migration(getLogger(__name__)).callback(cursor) # type: ignore[misc]
+
+
+def _columns(cursor: sqlite3.Cursor, table: str) -> set[str]:
+ cursor.execute(f"PRAGMA table_info({table});")
+ return {row[1] for row in cursor.fetchall()}
+
+
+def _references(cursor: sqlite3.Cursor) -> set[tuple[str, str, str, str, str]]:
+ cursor.execute("SELECT owner_kind, user_id, owner_id, media_kind, media_name FROM media_references;")
+ return set(cursor.fetchall())
+
+
+def test_adds_provenance_and_size_columns(cursor: sqlite3.Cursor) -> None:
+ _run(cursor)
+
+ assert {"project_id", "file_size_bytes"} <= _columns(cursor, "images")
+ assert {"project_id", "file_size_bytes"} <= _columns(cursor, "videos")
+ assert "project_id" in _columns(cursor, "session_queue")
+
+ # Existing media stays unassigned and unmeasured rather than guessed.
+ cursor.execute("INSERT INTO images (image_name) VALUES ('old.png');")
+ cursor.execute("SELECT project_id, file_size_bytes FROM images WHERE image_name = 'old.png';")
+ assert cursor.fetchone() == (None, None)
+
+
+def test_backfills_references_from_projects_and_workflows(cursor: sqlite3.Cursor) -> None:
+ project = {
+ "canvas": {
+ "stagingArea": {"pendingImages": [{"imageName": "staged.png"}, {"imageName": "staged.png"}]},
+ "layers": [{"image": {"image_name": "layer.png"}}],
+ },
+ "video": {"clips": [{"video_name": "clip.mp4"}]},
+ "unrelated": {"imageName": "", "name": "not-a-ref.png"},
+ }
+ workflow = {"nodes": [{"data": {"inputs": {"image": {"value": {"image_name": "input.png"}}}}}]}
+ cursor.execute("INSERT INTO projects VALUES ('p1', 'u1', ?);", (json.dumps(project),))
+ cursor.execute("INSERT INTO projects VALUES ('p2', 'u2', 'not json');")
+ cursor.execute("INSERT INTO workflow_library VALUES ('w1', ?, 'u1');", (json.dumps(workflow),))
+
+ _run(cursor)
+
+ assert _references(cursor) == {
+ ("project", "u1", "p1", "image", "staged.png"),
+ ("project", "u1", "p1", "image", "layer.png"),
+ ("project", "u1", "p1", "video", "clip.mp4"),
+ ("workflow", "u1", "w1", "image", "input.png"),
+ }
+
+
+def test_rerunning_does_not_disturb_a_maintained_index(cursor: sqlite3.Cursor) -> None:
+ cursor.execute("INSERT INTO projects VALUES ('p1', 'u1', ?);", (json.dumps({"imageName": "a.png"}),))
+ _run(cursor)
+ # The writer has since replaced the project's references; a second run must not resurrect the old
+ # ones from the document nor fail on the existing columns.
+ cursor.execute("DELETE FROM media_references;")
+ cursor.execute("INSERT INTO media_references VALUES ('project', 'u1', 'p1', 'image', 'b.png');")
+
+ _run(cursor)
+
+ assert _references(cursor) == {("project", "u1", "p1", "image", "b.png")}
+ assert {"project_id", "file_size_bytes"} <= _columns(cursor, "images")
diff --git a/tests/app/services/shared/test_media_references.py b/tests/app/services/shared/test_media_references.py
new file mode 100644
index 0000000000..9043bc56f3
--- /dev/null
+++ b/tests/app/services/shared/test_media_references.py
@@ -0,0 +1,90 @@
+"""The media reference extractor and index writer shared by project, workflow and migration code."""
+
+import sqlite3
+
+import pytest
+
+from invokeai.app.services.shared.media_references import (
+ MediaReferences,
+ create_media_references_table,
+ delete_media_references,
+ extract_media_references,
+ replace_media_references,
+)
+
+
+def test_collects_names_under_image_and_video_keys_at_any_depth() -> None:
+ document = {
+ "layers": [{"image": {"image_name": "layer.png"}}, {"reference": {"imageName": "ref.png"}}],
+ "queue": {"items": [{"outputs": [{"imageName": "staged.png"}, {"videoName": "clip.mp4"}]}]},
+ "video": {"video_name": "source.mp4", "poster": {"image_name": "poster.png"}},
+ "ignored": {"name": "not-a-ref.png", "image_name": "", "video_name": "x" * 300, "imageName": 12},
+ }
+
+ references = extract_media_references(document)
+
+ assert references.images == {"layer.png", "ref.png", "staged.png", "poster.png"}
+ assert references.videos == {"clip.mp4", "source.mp4"}
+
+
+def test_non_object_documents_reference_nothing() -> None:
+ for document in ("image_name", 3, None, ["image_name"], {"nested": [None, 1, "image_name"]}):
+ assert extract_media_references(document).is_empty()
+
+
+def cursor() -> sqlite3.Cursor:
+ connection = sqlite3.connect(":memory:")
+ cursor = connection.cursor()
+ create_media_references_table(cursor)
+ return cursor
+
+
+def _rows(cursor: sqlite3.Cursor) -> set[tuple[str, str, str, str, str]]:
+ cursor.execute("SELECT owner_kind, user_id, owner_id, media_kind, media_name FROM media_references;")
+ return set(cursor.fetchall())
+
+
+def test_replace_makes_the_owner_rows_equal_to_the_new_references(cursor: sqlite3.Cursor) -> None:
+ replace_media_references(
+ cursor,
+ owner_kind="project",
+ user_id="u1",
+ owner_id="p1",
+ references=MediaReferences(images={"old.png", "kept.png"}, videos={"old.mp4"}),
+ )
+ replace_media_references(
+ cursor,
+ owner_kind="project",
+ user_id="u2",
+ owner_id="p1",
+ references=MediaReferences(images={"other-account.png"}),
+ )
+
+ replace_media_references(
+ cursor,
+ owner_kind="project",
+ user_id="u1",
+ owner_id="p1",
+ references=MediaReferences(images={"kept.png", "new.png"}),
+ )
+
+ # The other account's project with the same id is untouched: project ids are per user.
+ assert _rows(cursor) == {
+ ("project", "u1", "p1", "image", "kept.png"),
+ ("project", "u1", "p1", "image", "new.png"),
+ ("project", "u2", "p1", "image", "other-account.png"),
+ }
+
+
+def test_delete_removes_only_that_owner(cursor: sqlite3.Cursor) -> None:
+ replace_media_references(
+ cursor, owner_kind="project", user_id="u1", owner_id="p1", references=MediaReferences(images={"a.png"})
+ )
+ replace_media_references(
+ cursor, owner_kind="workflow", user_id="u1", owner_id="p1", references=MediaReferences(images={"a.png"})
+ )
+
+ delete_media_references(cursor, owner_kind="project", user_id="u1", owner_id="p1")
+
+ assert _rows(cursor) == {("workflow", "u1", "p1", "image", "a.png")}
diff --git a/tests/app/services/users/test_last_admin_invariant.py b/tests/app/services/users/test_last_admin_invariant.py
index 050e1d01dc..10ecda6e26 100644
--- a/tests/app/services/users/test_last_admin_invariant.py
+++ b/tests/app/services/users/test_last_admin_invariant.py
@@ -23,6 +23,7 @@ from logging import Logger
import pytest
from invokeai.app.services.auth.password_utils import hash_password
+from invokeai.app.services.shared.media_references import create_media_references_table
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.users.users_common import (
SYSTEM_USER_ID,
@@ -53,6 +54,8 @@ def db() -> SqliteDatabase:
token_epoch INTEGER NOT NULL DEFAULT 0
);
""")
+ # Deleting an account also drops the media references its documents held.
+ create_media_references_table(db._conn.cursor())
db._conn.commit()
return db
diff --git a/tests/app/services/users/test_user_service.py b/tests/app/services/users/test_user_service.py
index 3db1f379a8..6099ac4c4e 100644
--- a/tests/app/services/users/test_user_service.py
+++ b/tests/app/services/users/test_user_service.py
@@ -5,6 +5,7 @@ from logging import Logger
import pytest
+from invokeai.app.services.shared.media_references import create_media_references_table
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
from invokeai.app.services.users import users_default
from invokeai.app.services.users.users_common import UserCreateRequest, UserUpdateRequest
@@ -36,6 +37,8 @@ def db(logger: Logger) -> SqliteDatabase:
token_epoch INTEGER NOT NULL DEFAULT 0
);
""")
+ # Deleting an account also drops the media references its documents held.
+ create_media_references_table(db._conn.cursor())
db._conn.commit()
return db
diff --git a/tests/app/services/workflow_records/test_workflow_media_references.py b/tests/app/services/workflow_records/test_workflow_media_references.py
new file mode 100644
index 0000000000..2f7571f78f
--- /dev/null
+++ b/tests/app/services/workflow_records/test_workflow_media_references.py
@@ -0,0 +1,61 @@
+"""Library workflows keep the media reference index current, like project documents do."""
+
+import pytest
+
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.workflow_records.workflow_records_common import (
+ Workflow,
+ WorkflowCategory,
+ WorkflowMeta,
+ WorkflowWithoutID,
+)
+from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
+
+
+def workflow_records(mock_invoker: Invoker) -> SqliteWorkflowRecordsStorage:
+ return mock_invoker.services.workflow_records
+
+
+def _workflow(image_name: str) -> WorkflowWithoutID:
+ return WorkflowWithoutID(
+ name="Refs",
+ author="",
+ description="",
+ version="1.0.0",
+ contact="",
+ tags="",
+ notes="",
+ exposedFields=[],
+ meta=WorkflowMeta(version="3.0.0", category=WorkflowCategory.User),
+ nodes=[{"id": "n1", "data": {"inputs": {"image": {"value": {"image_name": image_name}}}}}],
+ edges=[],
+ )
+
+
+def _references(records: SqliteWorkflowRecordsStorage, workflow_id: str) -> set[tuple[str, str, str]]:
+ with records._db.transaction() as cursor:
+ cursor.execute(
+ "SELECT user_id, media_kind, media_name FROM media_references WHERE owner_kind = 'workflow' AND owner_id = ?;",
+ (workflow_id,),
+ )
+ return {tuple(row) for row in cursor.fetchall()}
+
+
+def test_create_update_and_delete_keep_the_index_current(workflow_records: SqliteWorkflowRecordsStorage) -> None:
+ created = workflow_records.create(_workflow("input.png"), user_id="user-1")
+ assert _references(workflow_records, created.workflow_id) == {("user-1", "image", "input.png")}
+
+ workflow_records.update(Workflow(**_workflow("replaced.png").model_dump(), id=created.workflow_id))
+ assert _references(workflow_records, created.workflow_id) == {("user-1", "image", "replaced.png")}
+
+ workflow_records.delete(created.workflow_id, user_id="user-1")
+ assert _references(workflow_records, created.workflow_id) == set()
+
+
+def test_an_update_refused_by_ownership_leaves_the_index_alone(workflow_records: SqliteWorkflowRecordsStorage) -> None:
+ created = workflow_records.create(_workflow("input.png"), user_id="user-1")
+
+ workflow_records.update(Workflow(**_workflow("stolen.png").model_dump(), id=created.workflow_id), user_id="user-2")
+
+ assert _references(workflow_records, created.workflow_id) == {("user-1", "image", "input.png")}