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): add an intermediates cleanup service with a server-owned policy

Josh Corbettd4fbea054243
diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.py
index a0d0902816..ccd33068d1 100644
--- a/invokeai/app/api/dependencies.py
+++ b/invokeai/app/api/dependencies.py
@@ -33,6 +33,8 @@ from invokeai.app.services.image_index.image_index_records_sqlite import ImageIn
from invokeai.app.services.image_moves.image_moves_default import ImageMoveService
from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
from invokeai.app.services.images.images_default import ImageService
+from invokeai.app.services.intermediates.intermediates_default import IntermediatesService
+from invokeai.app.services.intermediates.intermediates_records_sqlite import IntermediatesRecordsSqlite
from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
from invokeai.app.services.invocation_services import InvocationServices
from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
@@ -208,6 +210,7 @@ class ApiDependencies:
users = UserService(db=db)
image_index_records = ImageIndexRecordsSqlite(db=db)
image_index = ImageIndexService()
+ intermediates = IntermediatesService(records=IntermediatesRecordsSqlite(db=db), logger=logger)
fonts = FontService(
db=db,
fonts_dir=configuration.fonts_path,
@@ -262,6 +265,7 @@ class ApiDependencies:
image_index_records=image_index_records,
image_index=image_index,
fonts=fonts,
+ intermediates=intermediates,
)
# Constructing the Invoker starts every service, including the session
diff --git a/invokeai/app/api/routers/_access.py b/invokeai/app/api/routers/_access.py
index ae57226217..79a0cc1855 100644
--- a/invokeai/app/api/routers/_access.py
+++ b/invokeai/app/api/routers/_access.py
@@ -13,6 +13,7 @@ from invokeai.app.services.board_records.board_records_common import (
BoardRecordNotFoundException,
BoardVisibility,
)
+from invokeai.app.services.project_records.project_records_common import ProjectRecordNotFoundError
def _get_board_record(board_id: str) -> BoardRecord:
@@ -242,3 +243,18 @@ def assert_board_read_access(board_id: str, current_user: CurrentUserOrDefault)
return
raise HTTPException(status_code=403, detail="Not authorized to access this board")
+
+
+def assert_project_owned(project_id: str | None, current_user: CurrentUserOrDefault) -> None:
+ """Raise 404 unless `project_id` names one of the caller's own projects.
+
+ Provenance is recorded only from a validated identity: an admin cannot attribute media to
+ someone else's project, and a project id nobody owns reads as absent rather than as a
+ permission decision, matching how the queue treats `Batch.project_id`.
+ """
+ if project_id is None:
+ return
+ try:
+ ApiDependencies.invoker.services.project_records.get_board_id(current_user.user_id, project_id)
+ except ProjectRecordNotFoundError:
+ raise HTTPException(status_code=404, detail="Project not found")
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index 49ec786a57..0832e2a02d 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -26,6 +26,7 @@ from invokeai.app.api.routers._access import (
from invokeai.app.api.routers._access import (
assert_image_read_access as _assert_image_read_access,
)
+from invokeai.app.api.routers._access import assert_project_owned
from invokeai.app.api.routers._access import (
board_share_recipients as _board_share_recipients,
)
@@ -47,6 +48,7 @@ from invokeai.app.services.images.images_common import (
StarredImagesResult,
UnstarredImagesResult,
)
+from invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller
from invokeai.app.services.shared.pagination import MAX_PAGE_SIZE, OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.util.controlnet_utils import heuristic_resize_fast
@@ -112,6 +114,12 @@ async def upload_image(
is_intermediate: bool = Query(description="Whether this is an intermediate image"),
board_id: Optional[str] = Query(default=None, description="The board to add this image to, if any"),
session_id: Optional[str] = Query(default=None, description="The session ID associated with this upload, if any"),
+ project_id: Optional[str] = Query(
+ default=None,
+ min_length=1,
+ max_length=255,
+ description="The caller's project this upload originates in, if any; recorded for intermediates cleanup",
+ ),
crop_visible: Optional[bool] = Query(default=False, description="Whether to crop the image"),
resize_to: Optional[str] = Body(
default=None,
@@ -128,6 +136,7 @@ async def upload_image(
# If uploading into a board, verify the user has write access.
# Public boards allow uploads from any authenticated user.
board = await asyncio.to_thread(_assert_board_write_access, board_id, current_user)
+ await asyncio.to_thread(assert_project_owned, project_id, current_user)
await asyncio.to_thread(assert_image_move_maintenance_inactive)
@@ -192,6 +201,7 @@ async def upload_image(
graph=extracted_metadata.invokeai_graph,
is_intermediate=is_intermediate,
user_id=current_user.user_id,
+ project_id=project_id,
)
except Exception:
ApiDependencies.invoker.services.logger.error(traceback.format_exc())
@@ -271,14 +281,19 @@ def delete_image(
def clear_intermediates(
current_user: CurrentUserOrDefault,
) -> int:
- """Clears all intermediates. Requires admin."""
+ """Clears every safe intermediate image, instance-wide. Requires admin.
+
+ Runs under the same policy as the intermediates manager: images that active work, a saved
+ document or the recency window protect are kept. Videos are not touched; use the manager.
+ """
if not current_user.is_admin:
raise HTTPException(status_code=403, detail="Only admins can clear all intermediates")
assert_image_move_maintenance_inactive()
try:
- count_deleted = ApiDependencies.invoker.services.images.delete_intermediates()
- return count_deleted
+ return ApiDependencies.invoker.services.intermediates.clear_all_images_now(
+ IntermediatesCaller(user_id=current_user.user_id, is_admin=current_user.is_admin)
+ )
except Exception:
raise HTTPException(status_code=500, detail="Failed to clear intermediates")
diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.py
index 87b2bed445..94fb7a8fc4 100644
--- a/invokeai/app/api/routers/videos.py
+++ b/invokeai/app/api/routers/videos.py
@@ -27,6 +27,7 @@ from invokeai.app.api.routers._access import (
from invokeai.app.api.routers._access import (
assert_board_write_access as _assert_board_write_access,
)
+from invokeai.app.api.routers._access import assert_project_owned
from invokeai.app.api.routers._access import (
assert_video_owner as _assert_video_owner,
)
@@ -442,10 +443,17 @@ async def upload_video(
is_intermediate: bool = Query(description="Whether this is an intermediate video"),
board_id: Optional[str] = Query(default=None, description="The board to add this video to, if any"),
session_id: Optional[str] = Query(default=None, description="The session ID associated with this upload, if any"),
+ project_id: Optional[str] = Query(
+ default=None,
+ min_length=1,
+ max_length=255,
+ description="The caller's project this upload originates in, if any; recorded for intermediates cleanup",
+ ),
) -> VideoDTO:
"""Uploads a video for the current user."""
# Check board access for uploads to a specific board.
board = await run_in_threadpool(_assert_board_write_access, board_id, current_user)
+ await run_in_threadpool(assert_project_owned, project_id, current_user)
# Stream the upload straight into a tmp file so we can probe it and then hand its path
# to the service. Reading the full body into memory first risked exhausting RAM on
@@ -546,6 +554,7 @@ async def upload_video(
graph=extracted.invokeai_graph,
is_intermediate=is_intermediate,
user_id=current_user.user_id,
+ project_id=project_id,
)
)
except Exception:
diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.py
index 7c6fa13757..1a5603fcab 100644
--- a/invokeai/app/services/events/events_base.py
+++ b/invokeai/app/services/events/events_base.py
@@ -19,6 +19,7 @@ from invokeai.app.services.events.events_common import (
ImageIndexUpdatedEvent,
ImageMapProjectionReadyEvent,
ImageUploadedEvent,
+ IntermediatesOperationChangedEvent,
InvocationCompleteEvent,
InvocationErrorEvent,
InvocationProgressEvent,
@@ -52,6 +53,7 @@ if TYPE_CHECKING:
from invokeai.app.services.board_records.board_records_common import BoardRecord
from invokeai.app.services.download.download_base import DownloadJob
from invokeai.app.services.images.images_common import ImageDTO
+ from invokeai.app.services.intermediates.intermediates_common import IntermediatesOperation
from invokeai.app.services.model_install.model_install_common import ModelInstallJob
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
from invokeai.app.services.session_queue.session_queue_common import (
@@ -360,6 +362,14 @@ class EventServiceBase:
# endregion
+ # region Intermediates
+
+ def emit_intermediates_operation_changed(self, operation: "IntermediatesOperation") -> None:
+ """Emitted whenever an intermediates cleanup operation is created, progresses or finishes"""
+ self.dispatch(IntermediatesOperationChangedEvent.build(operation))
+
+ # endregion
+
# region Media uploads
def emit_image_uploaded(
diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.py
index a604ef4d77..5b836c5ccc 100644
--- a/invokeai/app/services/events/events_common.py
+++ b/invokeai/app/services/events/events_common.py
@@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field
from invokeai.app.services.board_records.board_records_common import BoardVisibility
from invokeai.app.services.image_records.image_records_common import ImageCategory
+from invokeai.app.services.intermediates.intermediates_common import IntermediatesOperation
from invokeai.app.services.model_install.model_install_common import ModelInstallJob, ModelSource
from invokeai.app.services.session_processor.session_processor_common import ProgressImage
from invokeai.app.services.session_queue.session_queue_common import (
@@ -1039,6 +1040,28 @@ class VideoUploadedEvent(MediaUploadedEventBase):
)
+class IntermediatesEventBase(EventBase):
+ """Base class for intermediates cleanup events"""
+
+
+@payload_schema.register
+class IntermediatesOperationChangedEvent(IntermediatesEventBase):
+ """Event model for intermediates_operation_changed.
+
+ Routed to the confirming account's room and to admins: the operation's progress is that
+ account's business, and admins see every cleanup so open managers refresh their counts.
+ """
+
+ __event_name__ = "intermediates_operation_changed"
+
+ user_id: str = Field(description="The account that confirmed the operation")
+ operation: IntermediatesOperation = Field(description="The operation's current state")
+
+ @classmethod
+ def build(cls, operation: "IntermediatesOperation") -> "IntermediatesOperationChangedEvent":
+ return cls(user_id=operation.user_id, operation=operation)
+
+
class UserAccessChangedEvent(EventBase):
"""Event model for user_access_changed.
diff --git a/invokeai/app/services/image_files/image_files_base.py b/invokeai/app/services/image_files/image_files_base.py
index 36c63e4b4c..fe7d1a08b1 100644
--- a/invokeai/app/services/image_files/image_files_base.py
+++ b/invokeai/app/services/image_files/image_files_base.py
@@ -73,6 +73,11 @@ class ImageFileStorageBase(ABC):
"""
pass
+ @abstractmethod
+ def get_file_size_bytes(self, image_name: str, image_subfolder: str = "") -> Optional[int]:
+ """Bytes the image and its thumbnail occupy; None when the full-size file is missing."""
+ pass
+
@abstractmethod
def delete(self, image_name: str, image_subfolder: str = "") -> None:
"""Deletes an image and its thumbnail (if one exists)."""
diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.py
index 16c1bb6765..ae1a1dbb4f 100644
--- a/invokeai/app/services/image_files/image_files_disk.py
+++ b/invokeai/app/services/image_files/image_files_disk.py
@@ -461,6 +461,17 @@ class DiskImageFileStorage(ImageFileStorageBase):
finally:
os.close(dir_fd)
+ def get_file_size_bytes(self, image_name: str, image_subfolder: str = "") -> Optional[int]:
+ try:
+ size = self.get_path(image_name, image_subfolder=image_subfolder).stat().st_size
+ except FileNotFoundError:
+ return None
+ try:
+ size += self.get_path(image_name, thumbnail=True, image_subfolder=image_subfolder).stat().st_size
+ except FileNotFoundError:
+ pass
+ return size
+
def get_path(self, image_name: str, thumbnail: bool = False, image_subfolder: str = "") -> Path:
base_folder = self.__thumbnails_folder if thumbnail else self.__output_folder
filename = get_thumbnail_name(image_name) if thumbnail else image_name
diff --git a/invokeai/app/services/image_records/image_records_base.py b/invokeai/app/services/image_records/image_records_base.py
index 4d3cf01438..22972f2e49 100644
--- a/invokeai/app/services/image_records/image_records_base.py
+++ b/invokeai/app/services/image_records/image_records_base.py
@@ -10,6 +10,7 @@ from invokeai.app.services.image_records.image_records_common import (
ImageRecordChanges,
ResourceOrigin,
)
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.virtual_boards.virtual_boards_common import VirtualSubBoardDTO
@@ -90,12 +91,14 @@ class ImageRecordStorageBase(ABC):
pass
@abstractmethod
- def get_intermediates(self) -> list[tuple[str, str]]:
- """Gets all intermediate image records as (image_name, image_subfolder) tuples, without deleting them."""
+ def get_subfolders(self, image_names: list[str]) -> dict[str, str]:
+ """Maps each existing named image to its on-disk subfolder; absent names are omitted."""
pass
@abstractmethod
- def delete_intermediates_by_names(self, image_names: list[str]) -> list[str]:
+ def delete_intermediates_by_names(
+ self, image_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> list[str]:
"""Deletes the named image records, skipping any that are no longer intermediates.
Returns the names whose records this call actually removed. Names that were already gone, and
@@ -125,10 +128,21 @@ class ImageRecordStorageBase(ABC):
metadata: Optional[str] = None,
user_id: Optional[str] = None,
image_subfolder: str = "",
+ project_id: Optional[str] = None,
) -> datetime:
"""Saves an image record."""
pass
+ @abstractmethod
+ def set_file_size_bytes(self, image_name: str, file_size_bytes: Optional[int]) -> None:
+ """Records the measured on-disk size of an image and its thumbnail; None marks it unmeasured."""
+ pass
+
+ @abstractmethod
+ def set_file_sizes_bytes(self, sizes: dict[str, int]) -> None:
+ """Records many measured sizes in one transaction."""
+ pass
+
@abstractmethod
def get_user_id(self, image_name: str) -> Optional[str]:
"""Gets the user_id of the image owner. Returns None if image not found."""
diff --git a/invokeai/app/services/image_records/image_records_common.py b/invokeai/app/services/image_records/image_records_common.py
index d60cecf5b7..6436d1b003 100644
--- a/invokeai/app/services/image_records/image_records_common.py
+++ b/invokeai/app/services/image_records/image_records_common.py
@@ -129,6 +129,8 @@ IMAGE_DTO_COLS = ", ".join(
"deleted_at",
"starred",
"image_subfolder",
+ "project_id",
+ "file_size_bytes",
]
]
)
@@ -171,6 +173,12 @@ class ImageRecord(BaseModelExcludeNull):
"""Whether this image is starred."""
has_workflow: bool = Field(description="Whether this image has a workflow.")
image_subfolder: str = Field(default="", description="The subfolder where the image is stored on disk.")
+ project_id: Optional[str] = Field(
+ default=None, description="The project this image originated in, if it was made for one."
+ )
+ file_size_bytes: Optional[int] = Field(
+ default=None, description="Bytes the image and its thumbnail occupy on disk; null until measured."
+ )
class ImageRecordChanges(BaseModelExcludeNull, extra="allow"):
@@ -216,6 +224,8 @@ def deserialize_image_record(image_dict: dict) -> ImageRecord:
starred = image_dict.get("starred", False)
has_workflow = image_dict.get("has_workflow", False)
image_subfolder = image_dict.get("image_subfolder", "")
+ project_id = image_dict.get("project_id", None)
+ file_size_bytes = image_dict.get("file_size_bytes", None)
return ImageRecord(
image_name=image_name,
@@ -232,6 +242,8 @@ def deserialize_image_record(image_dict: dict) -> ImageRecord:
starred=starred,
has_workflow=has_workflow,
image_subfolder=image_subfolder,
+ project_id=project_id,
+ file_size_bytes=file_size_bytes,
)
diff --git a/invokeai/app/services/image_records/image_records_sqlite.py b/invokeai/app/services/image_records/image_records_sqlite.py
index 0f09e9efc1..85b240fb38 100644
--- a/invokeai/app/services/image_records/image_records_sqlite.py
+++ b/invokeai/app/services/image_records/image_records_sqlite.py
@@ -19,6 +19,7 @@ from invokeai.app.services.image_records.image_records_common import (
ResourceOrigin,
deserialize_image_record,
)
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
@@ -233,6 +234,28 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
return deserialize_image_record(dict(result))
+ def set_file_size_bytes(self, image_name: str, file_size_bytes: Optional[int]) -> None:
+ with self._db.transaction() as cursor:
+ try:
+ cursor.execute(
+ "UPDATE images SET file_size_bytes = ? WHERE image_name = ?;",
+ (file_size_bytes, image_name),
+ )
+ except sqlite3.Error as e:
+ raise ImageRecordSaveException from e
+
+ def set_file_sizes_bytes(self, sizes: dict[str, int]) -> None:
+ if not sizes:
+ return
+ with self._db.transaction() as cursor:
+ try:
+ cursor.executemany(
+ "UPDATE images SET file_size_bytes = ? WHERE image_name = ?;",
+ [(size, name) for name, size in sizes.items()],
+ )
+ except sqlite3.Error as e:
+ raise ImageRecordSaveException from e
+
def get_user_id(self, image_name: str) -> Optional[str]:
with self._db.transaction() as cursor:
cursor.execute(
@@ -447,22 +470,22 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
count = cast(int, cursor.fetchone()[0])
return count
- def get_intermediates(self) -> list[tuple[str, str]]:
- """Gets all intermediate image records without deleting them.
-
- Returns a list of (image_name, image_subfolder) tuples for staged file deletion.
- """
+ def get_subfolders(self, image_names: list[str]) -> dict[str, str]:
+ subfolders: dict[str, str] = {}
with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
- SELECT image_name, image_subfolder FROM images
- WHERE is_intermediate = TRUE;
- """
- )
- result = cast(list[sqlite3.Row], cursor.fetchall())
- return [(r[0], r[1]) for r in result]
+ for start in range(0, len(image_names), self._MAX_SQL_VARIABLES):
+ chunk = image_names[start : start + self._MAX_SQL_VARIABLES]
+ placeholders = ",".join("?" for _ in chunk)
+ cursor.execute(
+ f"SELECT image_name, image_subfolder FROM images WHERE image_name IN ({placeholders})", chunk
+ )
+ for row in cursor.fetchall():
+ subfolders[cast(str, row[0])] = cast(str, row[1])
+ return subfolders
- def delete_intermediates_by_names(self, image_names: list[str]) -> list[str]:
+ def delete_intermediates_by_names(
+ self, image_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> list[str]:
"""Deletes the named image records, skipping any that are no longer intermediates.
The ``is_intermediate`` predicate rides on the DELETE itself rather than on a preceding
@@ -473,6 +496,8 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
Returns the names whose records this call actually removed. Names that were already gone, and
names whose records survive because they are no longer intermediates, are both excluded — the
caller purges the files of exactly the returned names and touches nothing else.
+
+ ``guard`` narrows each chunk on this same transaction; see `IntermediateDeleteGuard`.
"""
deleted: list[str] = []
try:
@@ -481,6 +506,10 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
# transaction above.
for start in range(0, len(image_names), self._MAX_SQL_VARIABLES):
chunk = image_names[start : start + self._MAX_SQL_VARIABLES]
+ if guard is not None:
+ chunk = guard(cursor, chunk)
+ if not chunk:
+ continue
placeholders = ",".join("?" for _ in chunk)
select_query = f"SELECT image_name FROM images WHERE image_name IN ({placeholders})"
@@ -514,6 +543,7 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
metadata: Optional[str] = None,
user_id: Optional[str] = None,
image_subfolder: str = "",
+ project_id: Optional[str] = None,
) -> datetime:
with self._db.transaction() as cursor:
try:
@@ -532,9 +562,10 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
starred,
has_workflow,
user_id,
- image_subfolder
+ image_subfolder,
+ project_id
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
""",
(
image_name,
@@ -550,6 +581,7 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
has_workflow,
user_id or "system",
image_subfolder,
+ project_id,
),
)
diff --git a/invokeai/app/services/images/images_base.py b/invokeai/app/services/images/images_base.py
index 62b25e6691..a061cea11f 100644
--- a/invokeai/app/services/images/images_base.py
+++ b/invokeai/app/services/images/images_base.py
@@ -12,6 +12,7 @@ from invokeai.app.services.image_records.image_records_common import (
ResourceOrigin,
)
from invokeai.app.services.images.images_common import ImageDTO
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
@@ -56,6 +57,7 @@ class ImageServiceABC(ABC):
workflow: Optional[str] = None,
graph: Optional[str] = None,
user_id: Optional[str] = None,
+ project_id: Optional[str] = None,
) -> ImageDTO:
"""Creates an image, storing the file and its metadata."""
pass
@@ -158,8 +160,14 @@ class ImageServiceABC(ABC):
pass
@abstractmethod
- def delete_intermediates(self) -> int:
- """Deletes all intermediate images."""
+ def delete_intermediates_by_names(
+ self, image_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> IntermediateDeleteResult:
+ """Deletes the named images that are still intermediates, journalled, reporting the names removed.
+
+ ``guard`` is consulted on the deleting transaction so the cleanup policy's final check and
+ the record removal are one atomic step.
+ """
pass
@abstractmethod
diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.py
index b34c8c35b9..6bb0f679f8 100644
--- a/invokeai/app/services/images/images_default.py
+++ b/invokeai/app/services/images/images_default.py
@@ -27,6 +27,7 @@ from invokeai.app.services.images.images_base import ImageServiceABC
from invokeai.app.services.images.images_common import ImageDTO, image_record_to_dto
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.bulk_media_delete import StagedMediaDeleteAdapter, delete_media_by_names
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
@@ -70,6 +71,7 @@ class ImageService(ImageServiceABC):
workflow: Optional[str] = None,
graph: Optional[str] = None,
user_id: Optional[str] = None,
+ project_id: Optional[str] = None,
) -> ImageDTO:
if image_origin not in ResourceOrigin:
raise InvalidOriginException
@@ -112,6 +114,7 @@ class ImageService(ImageServiceABC):
session_id=session_id,
user_id=user_id,
image_subfolder=image_subfolder,
+ project_id=project_id,
)
if board_id is not None:
try:
@@ -128,6 +131,7 @@ class ImageService(ImageServiceABC):
graph=graph,
image_subfolder=image_subfolder,
)
+ self._record_file_size(image_name, image_subfolder)
image_dto = self.get_dto(image_name)
self._on_changed(image_dto)
@@ -143,6 +147,18 @@ class ImageService(ImageServiceABC):
self.__invoker.services.logger.error(f"Problem saving image record and file: {str(e)}")
raise e
+ def _record_file_size(self, image_name: str, image_subfolder: str) -> None:
+ """Measures the files just written so storage accounting never has to stat them again.
+
+ Best effort: the image exists whether or not its size is recorded, and an unmeasured row
+ reads as unknown rather than zero until the intermediates backfill measures it.
+ """
+ try:
+ size = self.__invoker.services.image_files.get_file_size_bytes(image_name, image_subfolder=image_subfolder)
+ self.__invoker.services.image_records.set_file_size_bytes(image_name, size)
+ except Exception as e:
+ self.__invoker.services.logger.warning(f"Failed to record the file size of image {image_name}: {e}")
+
def __clean_up_failed_save(self, image_name: str, image_subfolder: str) -> None:
"""Removes the half-created image left by a failed save, record first.
@@ -270,6 +286,7 @@ class ImageService(ImageServiceABC):
image_subfolder=image_subfolder,
)
file_copied = True
+ self._record_file_size(image_name, image_subfolder)
image_dto = self.get_dto(image_name)
self._on_changed(image_dto)
@@ -568,61 +585,15 @@ class ImageService(ImageServiceABC):
self.__invoker.services.logger.error(f"Problem deleting image records and files: {str(e)}")
raise e
- def delete_intermediates(self) -> int:
- # Records first, files second, with a durable journal spanning the two. An earlier revision
- # staged every file, then conditionally deleted the records, then restored the files of any
- # image that had been promoted out of intermediate status mid-operation. That restore is
- # unfixably racy: while a promoted image's files sit in a staging directory, a concurrent
- # single-image or board delete can stage-empty (it finds no files to move) and then remove
- # the record; the restore then puts the files back with no record referencing them and no
- # journal to recover from — permanent orphans (JPPhoto, PR #9361).
- #
- # Deleting the records first removes that hazard: the conditional DELETE is atomic and
- # reports exactly which rows it removed, and only the files of already-deleted rows are
- # touched. A promoted image is never deleted and its files are never moved, so a concurrent
- # delete of it operates on real files in the output folder and stays consistent. The
- # journal covers the window the reordering opens: if this process dies, or the filesystem
- # fails, between the commit and the purge, startup recovery finishes the purge for every
- # journalled image whose record is gone.
- #
- # The mutation lock spans the snapshot through the purge so a subfolder move cannot
- # relocate files between the two and leave the purge sweeping an abandoned path
- # (JPPhoto, PR #9361).
+ def delete_intermediates_by_names(
+ self, image_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> IntermediateDeleteResult:
with self._image_mutation_lock():
try:
- image_name_subfolder_pairs = self.__invoker.services.image_records.get_intermediates()
- if not image_name_subfolder_pairs:
- return 0
- subfolders = dict(image_name_subfolder_pairs)
- token = self.__invoker.services.image_files.begin_delete(list(subfolders.items()))
- try:
- # Conditional on the row still being an intermediate: an image promoted between the
- # snapshot above and this call keeps both its record and its files. Returns exactly
- # the names this call removed (already-absent and promoted rows are excluded).
- deleted_image_names = self.__invoker.services.image_records.delete_intermediates_by_names(
- list(subfolders.keys())
- )
- except Exception:
- try:
- self.__invoker.services.image_files.abandon_delete(token)
- except Exception as cleanup_error:
- self.__invoker.services.logger.error(
- f"Failed to discard the intermediates delete journal: {cleanup_error}"
- )
- raise
- try:
- # Only the names whose records this call removed are purged; a promoted image keeps
- # its files. The journal still lists it, which is harmless — recovery re-checks
- # every entry against the record store and skips the ones that survived.
- self.__invoker.services.image_files.commit_delete(token, image_names=deleted_image_names)
- except Exception as cleanup_error:
- # The records are committed as gone, so the deletion succeeded. A file that could
- # not be purged keeps its journal entry and is retried at the next startup; it must
- # neither fail the operation nor undo the committed deletions.
- self.__invoker.services.logger.error(f"Failed to purge intermediate image files: {cleanup_error}")
- for image_name in deleted_image_names:
- self._on_deleted(image_name)
- return len(deleted_image_names)
+ subfolders = self.__invoker.services.image_records.get_subfolders(image_names)
+ if not subfolders:
+ return IntermediateDeleteResult()
+ return self._delete_intermediates(subfolders, guard=guard)
except ImageRecordDeleteException:
self.__invoker.services.logger.error("Failed to delete image records")
raise
@@ -630,6 +601,61 @@ class ImageService(ImageServiceABC):
self.__invoker.services.logger.error("Problem deleting intermediate image records and files")
raise e
+ def _delete_intermediates(
+ self, subfolders: dict[str, str], guard: Optional[IntermediateDeleteGuard]
+ ) -> IntermediateDeleteResult:
+ """Deletes the given intermediates, records first, files second, with a durable journal spanning the two.
+
+ The caller holds the image mutation lock across the snapshot through the purge so a subfolder
+ move cannot relocate files between the two and leave the purge sweeping an abandoned path.
+
+ An earlier revision staged every file, then conditionally deleted the records, then restored
+ the files of any image that had been promoted out of intermediate status mid-operation. That
+ restore is unfixably racy: while a promoted image's files sit in a staging directory, a
+ concurrent single-image or board delete can stage-empty (it finds no files to move) and then
+ remove the record; the restore then puts the files back with no record referencing them and
+ no journal to recover from — permanent orphans (JPPhoto, PR #9361).
+
+ Deleting the records first removes that hazard: the conditional DELETE is atomic and reports
+ exactly which rows it removed, and only the files of already-deleted rows are touched. A
+ promoted image is never deleted and its files are never moved, so a concurrent delete of it
+ operates on real files in the output folder and stays consistent. The journal covers the
+ window the reordering opens: if this process dies, or the filesystem fails, between the
+ commit and the purge, startup recovery finishes the purge for every journalled image whose
+ record is gone.
+ """
+ token = self.__invoker.services.image_files.begin_delete(list(subfolders.items()))
+ try:
+ # Conditional on the row still being an intermediate (and on the guard's final check): an
+ # image promoted or protected between the snapshot above and this call keeps both its
+ # record and its files. Returns exactly the names this call removed.
+ deleted_image_names = self.__invoker.services.image_records.delete_intermediates_by_names(
+ list(subfolders.keys()), guard=guard
+ )
+ except Exception:
+ try:
+ self.__invoker.services.image_files.abandon_delete(token)
+ except Exception as cleanup_error:
+ self.__invoker.services.logger.error(
+ f"Failed to discard the intermediates delete journal: {cleanup_error}"
+ )
+ raise
+ result = IntermediateDeleteResult(deleted_names=deleted_image_names)
+ try:
+ # Only the names whose records this call removed are purged; a surviving image keeps its
+ # files. The journal still lists it, which is harmless — recovery re-checks every entry
+ # against the record store and skips the ones that survived.
+ self.__invoker.services.image_files.commit_delete(token, image_names=deleted_image_names)
+ except Exception as cleanup_error:
+ # The records are committed as gone, so the deletion succeeded. A file that could not be
+ # purged keeps its journal entry and is retried at the next startup; it must neither fail
+ # the operation nor undo the committed deletions.
+ self.__invoker.services.logger.error(f"Failed to purge intermediate image files: {cleanup_error}")
+ result.purge_deferred = list(deleted_image_names)
+ for image_name in deleted_image_names:
+ self._on_deleted(image_name)
+ return result
+
def get_intermediates_count(self, user_id: Optional[str] = None) -> int:
try:
return self.__invoker.services.image_records.get_intermediates_count(user_id=user_id)
diff --git a/invokeai/app/services/intermediates/__init__.py b/invokeai/app/services/intermediates/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/invokeai/app/services/intermediates/intermediates_base.py b/invokeai/app/services/intermediates/intermediates_base.py
new file mode 100644
index 0000000000..83fcf0a56a
--- /dev/null
+++ b/invokeai/app/services/intermediates/intermediates_base.py
@@ -0,0 +1,61 @@
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Optional
+
+from invokeai.app.services.intermediates.intermediates_common import (
+ IntermediatesOperation,
+ IntermediatesOperationRequest,
+ IntermediatesPreview,
+ IntermediatesPreviewRequest,
+ IntermediatesSummary,
+ IntermediatesSummarySort,
+)
+
+
+@dataclass(frozen=True)
+class IntermediatesCaller:
+ """Who is asking: the authenticated account and whether it administers the instance."""
+
+ user_id: str
+ is_admin: bool
+
+
+class IntermediatesServiceBase(ABC):
+ """Scoped cleanup of intermediate images and videos under one eligibility policy."""
+
+ @abstractmethod
+ def get_summary(
+ self,
+ caller: IntermediatesCaller,
+ *,
+ owner_id: Optional[str],
+ search: Optional[str],
+ sort: IntermediatesSummarySort,
+ descending: bool,
+ offset: int,
+ limit: int,
+ ) -> IntermediatesSummary:
+ pass
+
+ @abstractmethod
+ def create_preview(self, request: IntermediatesPreviewRequest, caller: IntermediatesCaller) -> IntermediatesPreview:
+ pass
+
+ @abstractmethod
+ def start_operation(
+ self, request: IntermediatesOperationRequest, caller: IntermediatesCaller
+ ) -> IntermediatesOperation:
+ pass
+
+ @abstractmethod
+ def get_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:
+ pass
+
+ @abstractmethod
+ def retry_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:
+ pass
+
+ @abstractmethod
+ def clear_all_images_now(self, caller: IntermediatesCaller) -> int:
+ """The legacy instance-wide clear: every safe intermediate image, synchronously. Admin only."""
+ pass
diff --git a/invokeai/app/services/intermediates/intermediates_common.py b/invokeai/app/services/intermediates/intermediates_common.py
new file mode 100644
index 0000000000..ea3a29834f
--- /dev/null
+++ b/invokeai/app/services/intermediates/intermediates_common.py
@@ -0,0 +1,217 @@
+"""Contracts of the intermediates manager: summaries, previews and cleanup operations."""
+
+from datetime import datetime
+from typing import Literal, Optional
+
+from pydantic import BaseModel, Field
+
+IntermediatesCleanupMode = Literal["safe", "force"]
+"""`safe` keeps everything a saved document still references; `force` deletes those too. Neither
+touches active work, recent uploads or durable media."""
+
+IntermediatesScopeKind = Literal["selection", "owner", "everyone"]
+IntermediatesOperationStatus = Literal["pending", "running", "completed", "failed"]
+IntermediatesSummarySort = Literal["reclaimable_bytes", "project_name"]
+
+# Intermediates younger than this are never collected: it covers the window between a browser
+# uploading an intermediate and either promoting it to a durable asset, saving a document that
+# references it, or enqueueing the job that consumes it.
+RECENT_GRACE_SECONDS = 30 * 60
+
+PREVIEW_TTL_SECONDS = 10 * 60
+
+
+class IntermediatesScopeTarget(BaseModel):
+ """One row of the manager: an owner's project, or their unassigned intermediates."""
+
+ user_id: str = Field(min_length=1, max_length=255, description="The owning account")
+ project_id: Optional[str] = Field(
+ default=None,
+ min_length=1,
+ max_length=255,
+ description="The originating project; null selects the owner's unassigned intermediates",
+ )
+
+
+class IntermediatesScope(BaseModel):
+ kind: IntermediatesScopeKind = Field(description="How the targets were chosen")
+ targets: list[IntermediatesScopeTarget] = Field(
+ default_factory=list, max_length=1000, description="The selected rows; only read for a `selection` scope"
+ )
+ user_id: Optional[str] = Field(
+ default=None,
+ min_length=1,
+ max_length=255,
+ description="The account whose rows are targeted by an `owner` scope",
+ )
+
+
+class IntermediatesKindCounts(BaseModel):
+ """How one media kind's intermediates split under the cleanup policy."""
+
+ safe: int = Field(default=0, description="Unreferenced, inactive and old enough: deleted by either mode")
+ referenced: int = Field(default=0, description="Named by a saved project or workflow: kept by safe mode")
+ active: int = Field(default=0, description="Produced or consumed by pending, waiting or running work: always kept")
+ recent: int = Field(default=0, description="Created inside the grace window: always kept")
+
+ @property
+ def total(self) -> int:
+ return self.safe + self.referenced + self.active + self.recent
+
+
+class IntermediatesRow(IntermediatesScopeTarget):
+ user_display_name: Optional[str] = Field(default=None, description="The owner's display name, if known")
+ user_email: Optional[str] = Field(default=None, description="The owner's email, if known")
+ project_name: Optional[str] = Field(default=None, description="The project's name; null for unassigned rows")
+ cover_image_name: Optional[str] = Field(
+ default=None, description="The newest durable image on the project's board, for a thumbnail"
+ )
+ images: IntermediatesKindCounts = Field(default_factory=IntermediatesKindCounts)
+ videos: IntermediatesKindCounts = Field(default_factory=IntermediatesKindCounts)
+ reclaimable_bytes: int = Field(default=0, description="Measured size of the safe items")
+ referenced_bytes: int = Field(default=0, description="Measured size of the referenced items a force clear adds")
+ unknown_size_count: int = Field(default=0, description="Safe or referenced items whose size is not yet measured")
+
+
+class IntermediatesSummaryTotals(BaseModel):
+ """Totals over every row that matches the request, not just the returned page."""
+
+ rows: int = Field(default=0)
+ safe_images: int = Field(default=0)
+ safe_videos: int = Field(default=0)
+ in_use_images: int = Field(default=0)
+ in_use_videos: int = Field(default=0)
+ reclaimable_bytes: int = Field(default=0)
+ unknown_size_count: int = Field(default=0)
+
+
+class IntermediatesSummary(BaseModel):
+ items: list[IntermediatesRow]
+ total: int = Field(description="Rows matching the request")
+ offset: int
+ limit: int
+ totals: IntermediatesSummaryTotals
+ recent_grace_seconds: int = Field(description="How long a new intermediate is protected")
+ measuring: bool = Field(description="Whether sizes are still being measured in the background")
+ can_manage_everyone: bool = Field(description="Whether the caller may target other accounts")
+
+
+class IntermediatesPreviewRequest(BaseModel):
+ mode: IntermediatesCleanupMode
+ scope: IntermediatesScope
+
+
+class IntermediatesImpact(BaseModel):
+ delete_images: int = Field(default=0)
+ delete_videos: int = Field(default=0)
+ keep_referenced_images: int = Field(default=0)
+ keep_referenced_videos: int = Field(default=0)
+ keep_active_images: int = Field(default=0)
+ keep_active_videos: int = Field(default=0)
+ keep_recent_images: int = Field(default=0)
+ keep_recent_videos: int = Field(default=0)
+ reclaimable_bytes: int = Field(default=0, description="Measured size of the items that would be deleted")
+ unknown_size_count: int = Field(default=0, description="Items to delete whose size is not yet measured")
+
+
+class IntermediatesAffectedDocument(BaseModel):
+ """A saved document a force clear would leave pointing at deleted media."""
+
+ kind: Literal["project", "workflow"]
+ user_id: str
+ owner_id: str = Field(description="The project or workflow id")
+ name: Optional[str] = Field(default=None, description="The document's name, if it still exists")
+ references: int = Field(description="How many of the targeted items the document names")
+
+
+class IntermediatesPreview(BaseModel):
+ preview_id: str
+ mode: IntermediatesCleanupMode
+ scope: IntermediatesScope
+ created_at: datetime
+ expires_at: datetime
+ target_rows: int = Field(description="Rows the scope resolved to")
+ impact: IntermediatesImpact
+ affected_documents: list[IntermediatesAffectedDocument] = Field(
+ default_factory=list,
+ description="Documents a force clear would break, limited to those the caller may see",
+ )
+ affected_documents_hidden: int = Field(
+ default=0, description="Affected documents belonging to accounts the caller may not inspect"
+ )
+
+
+class IntermediatesOperationRequest(BaseModel):
+ preview_id: str = Field(min_length=1, max_length=64)
+ idempotency_key: str = Field(min_length=1, max_length=255, description="Caller-owned retry key")
+
+
+class IntermediatesOperationProgress(BaseModel):
+ processed_images: int = Field(default=0)
+ processed_videos: int = Field(default=0)
+ deleted_images: int = Field(default=0)
+ deleted_videos: int = Field(default=0)
+ retained_images: int = Field(default=0, description="Targets the final check kept: promoted, protected or gone")
+ retained_videos: int = Field(default=0)
+ failed_images: int = Field(default=0, description="Targets whose deletion raised; retryable")
+ failed_videos: int = Field(default=0)
+ reclaimed_bytes: int = Field(default=0, description="Bytes whose files are confirmed removed")
+ unknown_size_count: int = Field(
+ default=0, description="Deleted items whose size was never measured; their bytes are not in reclaimed_bytes"
+ )
+ pending_disk_cleanup: int = Field(
+ default=0, description="Deleted records whose files could not be purged yet; the journal retries at startup"
+ )
+ unresolved_images: int = Field(default=0, description="Image targets that failed or were never attempted")
+ unresolved_videos: int = Field(default=0, description="Video targets that failed or were never attempted")
+
+
+class IntermediatesOperation(BaseModel):
+ operation_id: str
+ user_id: str = Field(description="The account that confirmed the operation")
+ mode: IntermediatesCleanupMode
+ scope: IntermediatesScope
+ status: IntermediatesOperationStatus
+ created_at: datetime
+ started_at: Optional[datetime] = None
+ completed_at: Optional[datetime] = None
+ error: Optional[str] = Field(default=None, description="Why the operation stopped, when it failed")
+ target_images: int = Field(description="Frozen image targets")
+ target_videos: int = Field(description="Frozen video targets")
+ progress: IntermediatesOperationProgress
+ retried_from_operation_id: Optional[str] = None
+ retried_by_operation_id: Optional[str] = Field(
+ default=None, description="The retry that took over this operation's unresolved targets, if any"
+ )
+
+ @property
+ def is_retryable(self) -> bool:
+ return (
+ self.status in ("completed", "failed")
+ and self.retried_by_operation_id is None
+ and (self.progress.unresolved_images > 0 or self.progress.unresolved_videos > 0)
+ )
+
+
+class IntermediatesPreviewNotFoundError(Exception):
+ """The preview expired, was consumed, or belongs to another caller."""
+
+
+class IntermediatesOperationNotFoundError(Exception):
+ pass
+
+
+class IntermediatesScopeForbiddenError(Exception):
+ """The caller may not target the requested rows."""
+
+
+class IntermediatesScopeInvalidError(Exception):
+ """The scope is malformed for its kind."""
+
+
+class IntermediatesIdempotencyConflictError(Exception):
+ """The idempotency key was already used with a different preview."""
+
+
+class IntermediatesUnavailableError(Exception):
+ """Cleanup cannot run right now, e.g. image storage maintenance is active."""
diff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.py
new file mode 100644
index 0000000000..f0374acd4d
--- /dev/null
+++ b/invokeai/app/services/intermediates/intermediates_default.py
@@ -0,0 +1,699 @@
+"""The intermediates cleanup engine.
+
+Previews freeze the exact targets a confirmation will act on; nothing created afterwards can join
+an operation. Operations run on one background worker in bounded batches, and every batch
+re-applies the policy on the deleting transaction, so a target that became active, referenced or
+durable since the preview is kept. Operation state lives in this process: a restart abandons an
+in-flight operation part-way, which cannot broaden it (the targets were frozen) and cannot lose a
+file (the image delete journal finishes any purge the crash interrupted).
+
+Lock order, for anyone adding a caller: image mutation lock (image service) → database lock. The
+queue and document writers take only the database lock, so no cycle is possible.
+"""
+
+import logging
+import queue
+import threading
+import time
+import uuid
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from typing import Callable, Optional, Sequence, cast
+
+from invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller, IntermediatesServiceBase
+from invokeai.app.services.intermediates.intermediates_common import (
+ PREVIEW_TTL_SECONDS,
+ RECENT_GRACE_SECONDS,
+ IntermediatesAffectedDocument,
+ IntermediatesCleanupMode,
+ IntermediatesIdempotencyConflictError,
+ IntermediatesImpact,
+ IntermediatesOperation,
+ IntermediatesOperationNotFoundError,
+ IntermediatesOperationProgress,
+ IntermediatesOperationRequest,
+ IntermediatesPreview,
+ IntermediatesPreviewNotFoundError,
+ IntermediatesPreviewRequest,
+ IntermediatesRow,
+ IntermediatesScope,
+ IntermediatesScopeForbiddenError,
+ IntermediatesScopeInvalidError,
+ IntermediatesScopeTarget,
+ IntermediatesSummary,
+ IntermediatesSummarySort,
+ IntermediatesSummaryTotals,
+ IntermediatesUnavailableError,
+)
+from invokeai.app.services.intermediates.intermediates_records_sqlite import (
+ IntermediateCandidate,
+ IntermediatesRecordsSqlite,
+ MediaKind,
+)
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
+
+DELETE_BATCH_SIZE = 200
+MEASURE_BATCH_SIZE = 200
+# A row is written before its file; measuring it a moment later would record a missing file.
+MEASURE_MIN_AGE_SECONDS = 10
+MAX_RETAINED_OPERATIONS = 100
+MAX_PREVIEWS = 200
+# Frozen (name, size) pairs held across every live preview; the oldest previews expire first.
+MAX_FROZEN_PREVIEW_TARGETS = 500_000
+PROGRESS_EVENT_INTERVAL_SECONDS = 1.0
+WORKER_STOP_TIMEOUT_SECONDS = 10.0
+
+
+def _now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+@dataclass
+class _Preview:
+ dto: IntermediatesPreview
+ caller_user_id: str
+ # Frozen targets with the size known at preview time; sizes are what an operation reclaims.
+ targets: dict[MediaKind, list[tuple[str, Optional[int]]]]
+ allowed_user_ids: Optional[frozenset[str]]
+
+
+@dataclass
+class _Operation:
+ dto: IntermediatesOperation
+ caller: IntermediatesCaller
+ targets: dict[MediaKind, list[tuple[str, Optional[int]]]]
+ allowed_user_ids: Optional[frozenset[str]]
+ # Names whose deletion raised, or that were never attempted; a retry takes exactly these.
+ unresolved: dict[MediaKind, dict[str, Optional[int]]] = field(default_factory=lambda: {"image": {}, "video": {}})
+ last_progress_event_at: float = 0.0
+
+
+class IntermediatesService(IntermediatesServiceBase):
+ def __init__(self, records: IntermediatesRecordsSqlite, logger: Optional[logging.Logger] = None) -> None:
+ self._records = records
+ self._logger = logger or logging.getLogger(__name__)
+ self._invoker: Optional[Invoker] = None
+ self._lock = threading.Lock()
+ self._previews: dict[str, _Preview] = {}
+ self._operations: dict[str, _Operation] = {}
+ self._operation_order: list[str] = []
+ self._idempotency: dict[tuple[str, str], tuple[str, str]] = {}
+ self._pending: "queue.Queue[str]" = queue.Queue()
+ self._measure_requested = threading.Event()
+ # Rows a measurement raised on; skipped for the rest of the process so one bad file cannot
+ # stall every later row.
+ self._measure_skipped: set[str] = set()
+ self._stop = threading.Event()
+ self._worker: Optional[threading.Thread] = None
+
+ # region lifecycle
+
+ def start(self, invoker: Invoker) -> None:
+ self._invoker = invoker
+ self._stop.clear()
+
+ def stop(self, invoker: Optional[Invoker] = None) -> None:
+ self._stop.set()
+ worker = self._worker
+ if worker is not None:
+ self._pending.put("")
+ worker.join(timeout=WORKER_STOP_TIMEOUT_SECONDS)
+ if worker.is_alive():
+ self._logger.warning("Intermediates worker did not stop in time")
+ else:
+ self._worker = None
+
+ def _ensure_worker(self) -> None:
+ """Spawned on first use: a process that never cleans up never pays for a polling thread."""
+ with self._lock:
+ if self._worker is not None and self._worker.is_alive():
+ return
+ if self._stop.is_set():
+ return
+ self._worker = threading.Thread(target=self._worker_loop, name="intermediates_worker", daemon=True)
+ self._worker.start()
+
+ @property
+ def _services(self):
+ assert self._invoker is not None, "IntermediatesService has not been started"
+ return self._invoker.services
+
+ # endregion
+
+ # region summary
+
+ def get_summary(
+ self,
+ caller: IntermediatesCaller,
+ *,
+ owner_id: Optional[str],
+ search: Optional[str],
+ sort: IntermediatesSummarySort,
+ descending: bool,
+ offset: int,
+ limit: int,
+ ) -> IntermediatesSummary:
+ owner_filter = self._resolve_owner_filter(caller, owner_id)
+ aggregated = self._records.summarize(owner_filter)
+ projects = self._records.get_projects(owner_filter)
+ users = self._services.users.get_many([user_id for user_id, _ in aggregated])
+
+ rows: list[IntermediatesRow] = []
+ for (user_id, project_id), kinds in aggregated.items():
+ user = users.get(user_id)
+ project = projects.get((user_id, project_id)) if project_id is not None else None
+ rows.append(
+ IntermediatesRow(
+ user_id=user_id,
+ project_id=project_id,
+ user_display_name=user.display_name if user is not None else None,
+ user_email=user.email if user is not None else None,
+ project_name=project[0] if project is not None else None,
+ cover_image_name=project[1] if project is not None else None,
+ images=kinds["image"].counts,
+ videos=kinds["video"].counts,
+ reclaimable_bytes=kinds["image"].safe_bytes + kinds["video"].safe_bytes,
+ referenced_bytes=kinds["image"].referenced_bytes + kinds["video"].referenced_bytes,
+ unknown_size_count=kinds["image"].unknown_size_count + kinds["video"].unknown_size_count,
+ )
+ )
+
+ if search:
+ needle = search.casefold()
+ rows = [row for row in rows if self._matches(row, needle, include_owner=caller.is_admin)]
+
+ rows.sort(key=lambda row: (row.project_name or "").casefold())
+ if sort == "reclaimable_bytes":
+ rows.sort(key=lambda row: row.reclaimable_bytes, reverse=descending)
+ elif descending:
+ rows.reverse()
+
+ totals = IntermediatesSummaryTotals(rows=len(rows))
+ for row in rows:
+ totals.safe_images += row.images.safe
+ totals.safe_videos += row.videos.safe
+ totals.in_use_images += row.images.total - row.images.safe
+ totals.in_use_videos += row.videos.total - row.videos.safe
+ totals.reclaimable_bytes += row.reclaimable_bytes
+ totals.unknown_size_count += row.unknown_size_count
+
+ measuring = self._records.has_unmeasured_intermediates()
+ if measuring:
+ self._measure_requested.set()
+ self._ensure_worker()
+
+ return IntermediatesSummary(
+ items=rows[offset : offset + limit],
+ total=len(rows),
+ offset=offset,
+ limit=limit,
+ totals=totals,
+ recent_grace_seconds=RECENT_GRACE_SECONDS,
+ measuring=measuring,
+ can_manage_everyone=caller.is_admin,
+ )
+
+ @staticmethod
+ def _matches(row: IntermediatesRow, needle: str, *, include_owner: bool) -> bool:
+ haystacks = [row.project_name or ""]
+ if include_owner:
+ haystacks.extend([row.user_display_name or "", row.user_email or ""])
+ return any(needle in value.casefold() for value in haystacks)
+
+ @staticmethod
+ def _resolve_owner_filter(caller: IntermediatesCaller, owner_id: Optional[str]) -> Optional[str]:
+ if not caller.is_admin:
+ if owner_id is not None and owner_id != caller.user_id:
+ raise IntermediatesScopeForbiddenError("Only administrators can inspect other accounts")
+ return caller.user_id
+ return owner_id
+
+ # endregion
+
+ # region previews
+
+ def create_preview(self, request: IntermediatesPreviewRequest, caller: IntermediatesCaller) -> IntermediatesPreview:
+ scope = request.scope
+ allowed = self._authorize_scope(scope, caller)
+ candidates = self._collect_candidates(scope)
+
+ impact = IntermediatesImpact()
+ targets: dict[MediaKind, list[tuple[str, Optional[int]]]] = {"image": [], "video": []}
+ for kind in ("image", "video"):
+ media_kind = cast(MediaKind, kind)
+ for candidate in candidates[media_kind]:
+ self._tally(impact, media_kind, candidate, request.mode, targets)
+
+ affected: list[IntermediatesAffectedDocument] = []
+ hidden = 0
+ if request.mode == "force":
+ affected, hidden = self._describe_affected(candidates, caller)
+
+ created = _now()
+ dto = IntermediatesPreview(
+ preview_id=uuid.uuid4().hex,
+ mode=request.mode,
+ scope=scope,
+ created_at=created,
+ expires_at=created + timedelta(seconds=PREVIEW_TTL_SECONDS),
+ target_rows=self._count_target_rows(scope, candidates),
+ impact=impact,
+ affected_documents=affected,
+ affected_documents_hidden=hidden,
+ )
+ with self._lock:
+ self._previews[dto.preview_id] = _Preview(
+ dto=dto, caller_user_id=caller.user_id, targets=targets, allowed_user_ids=allowed
+ )
+ self._expire_previews_locked(created)
+ return dto
+
+ def _authorize_scope(self, scope: IntermediatesScope, caller: IntermediatesCaller) -> Optional[frozenset[str]]:
+ """Returns the accounts the scope may touch, or None for every account."""
+ if scope.kind == "everyone":
+ if not caller.is_admin:
+ raise IntermediatesScopeForbiddenError("Only administrators can clear everyone's intermediates")
+ return None
+ if scope.kind == "owner":
+ if scope.user_id is None:
+ raise IntermediatesScopeInvalidError("An owner scope names the account to clear")
+ if scope.user_id != caller.user_id and not caller.is_admin:
+ raise IntermediatesScopeForbiddenError("Only administrators can clear another account's intermediates")
+ return frozenset({scope.user_id})
+ if not scope.targets:
+ raise IntermediatesScopeInvalidError("A selection scope names at least one row")
+ owners = frozenset(target.user_id for target in scope.targets)
+ if not caller.is_admin and owners != frozenset({caller.user_id}):
+ raise IntermediatesScopeForbiddenError("Only administrators can clear another account's intermediates")
+ return owners
+
+ def _collect_candidates(self, scope: IntermediatesScope) -> dict[MediaKind, list[IntermediateCandidate]]:
+ targets: Optional[Sequence[IntermediatesScopeTarget]] = None
+ user_id: Optional[str] = None
+ if scope.kind == "selection":
+ # Duplicate rows would double-count; the order is irrelevant to the SQL.
+ targets = list({(t.user_id, t.project_id): t for t in scope.targets}.values())
+ elif scope.kind == "owner":
+ user_id = scope.user_id
+ return {
+ "image": self._records.list_candidates("image", user_id=user_id, targets=targets),
+ "video": self._records.list_candidates("video", user_id=user_id, targets=targets),
+ }
+
+ @staticmethod
+ def _count_target_rows(scope: IntermediatesScope, candidates: dict[MediaKind, list[IntermediateCandidate]]) -> int:
+ """Rows (owner, project) the scope resolved to, counted the same way for every scope kind."""
+ if scope.kind == "selection":
+ return len({(t.user_id, t.project_id) for t in scope.targets})
+ return len({(candidate.user_id, candidate.project_id) for kind in candidates.values() for candidate in kind})
+
+ @staticmethod
+ def _tally(
+ impact: IntermediatesImpact,
+ kind: MediaKind,
+ candidate: IntermediateCandidate,
+ mode: IntermediatesCleanupMode,
+ targets: dict[MediaKind, list[tuple[str, Optional[int]]]],
+ ) -> None:
+ suffix = "images" if kind == "image" else "videos"
+ deletable = candidate.classification == "safe" or (mode == "force" and candidate.classification == "referenced")
+ if deletable:
+ setattr(impact, f"delete_{suffix}", getattr(impact, f"delete_{suffix}") + 1)
+ if candidate.file_size_bytes is None:
+ impact.unknown_size_count += 1
+ else:
+ impact.reclaimable_bytes += candidate.file_size_bytes
+ targets[kind].append((candidate.name, candidate.file_size_bytes))
+ else:
+ attribute = f"keep_{candidate.classification}_{suffix}"
+ setattr(impact, attribute, getattr(impact, attribute) + 1)
+
+ def _describe_affected(
+ self, candidates: dict[MediaKind, list[IntermediateCandidate]], caller: IntermediatesCaller
+ ) -> tuple[list[IntermediatesAffectedDocument], int]:
+ refs = []
+ for kind in ("image", "video"):
+ media_kind = cast(MediaKind, kind)
+ names = [c.name for c in candidates[media_kind] if c.classification == "referenced"]
+ refs.extend(self._records.affected_references(media_kind, names))
+ names = self._records.get_document_names(refs)
+ visible: list[IntermediatesAffectedDocument] = []
+ hidden = 0
+ for ref in refs:
+ if not caller.is_admin and ref.user_id != caller.user_id:
+ hidden += 1
+ continue
+ visible.append(
+ IntermediatesAffectedDocument(
+ kind=cast(str, ref.owner_kind), # type: ignore[arg-type]
+ user_id=ref.user_id,
+ owner_id=ref.owner_id,
+ name=names.get((ref.owner_kind, ref.user_id, ref.owner_id)),
+ references=ref.references,
+ )
+ )
+ visible.sort(key=lambda doc: (doc.kind, (doc.name or "").casefold(), doc.owner_id))
+ return visible, hidden
+
+ def _expire_previews_locked(self, now: datetime) -> None:
+ expired = [pid for pid, preview in self._previews.items() if preview.dto.expires_at <= now]
+ for pid in expired:
+ del self._previews[pid]
+ frozen = sum(len(p.targets["image"]) + len(p.targets["video"]) for p in self._previews.values())
+ # Oldest first; the newest preview always survives so the caller who just asked can confirm.
+ while len(self._previews) > 1 and (len(self._previews) > MAX_PREVIEWS or frozen > MAX_FROZEN_PREVIEW_TARGETS):
+ oldest = next(iter(self._previews))
+ frozen -= len(self._previews[oldest].targets["image"]) + len(self._previews[oldest].targets["video"])
+ del self._previews[oldest]
+
+ # endregion
+
+ # region operations
+
+ def start_operation(
+ self, request: IntermediatesOperationRequest, caller: IntermediatesCaller
+ ) -> IntermediatesOperation:
+ with self._lock:
+ key = (caller.user_id, request.idempotency_key)
+ settled = self._idempotency.get(key)
+ if settled is not None:
+ # A replay creates no work, so it is answered even while cleanup is unavailable.
+ settled_preview_id, operation_id = settled
+ if settled_preview_id != request.preview_id:
+ raise IntermediatesIdempotencyConflictError("Idempotency key was used for a different preview")
+ return self._operations[operation_id].dto.model_copy(deep=True)
+
+ self._require_cleanup_available()
+ self._expire_previews_locked(_now())
+ preview = self._previews.get(request.preview_id)
+ if preview is None or preview.caller_user_id != caller.user_id:
+ raise IntermediatesPreviewNotFoundError("Preview expired or unknown; request a new one")
+ # Single use: a second confirmation of the same preview must go through a new preview.
+ del self._previews[request.preview_id]
+
+ operation = self._register_operation_locked(
+ caller=caller,
+ mode=preview.dto.mode,
+ scope=preview.dto.scope,
+ targets=preview.targets,
+ allowed_user_ids=preview.allowed_user_ids,
+ retried_from=None,
+ )
+ self._idempotency[key] = (request.preview_id, operation.dto.operation_id)
+ self._enqueue(operation)
+ return operation.dto.model_copy(deep=True)
+
+ def get_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:
+ with self._lock:
+ operation = self._operations.get(operation_id)
+ if operation is None or (operation.caller.user_id != caller.user_id and not caller.is_admin):
+ raise IntermediatesOperationNotFoundError(operation_id)
+ return operation.dto.model_copy(deep=True)
+
+ def retry_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:
+ self._require_cleanup_available()
+ with self._lock:
+ original = self._operations.get(operation_id)
+ if original is None or (original.caller.user_id != caller.user_id and not caller.is_admin):
+ raise IntermediatesOperationNotFoundError(operation_id)
+ if original.dto.status not in ("completed", "failed"):
+ raise IntermediatesUnavailableError("The operation is still running")
+ if original.dto.retried_by_operation_id is not None:
+ # A duplicated retry request (lost response, double click) must not run the same
+ # targets twice; the retry that already took them over is the answer.
+ return self._operations[original.dto.retried_by_operation_id].dto.model_copy(deep=True)
+ unresolved = {kind: list(names.items()) for kind, names in original.unresolved.items()}
+ if not unresolved["image"] and not unresolved["video"]:
+ raise IntermediatesUnavailableError("The operation has nothing left to retry")
+ # A retry is authorized as the retrying caller, never as the original one.
+ self._authorize_scope(original.dto.scope, caller)
+ operation = self._register_operation_locked(
+ caller=caller,
+ mode=original.dto.mode,
+ scope=original.dto.scope,
+ targets=unresolved,
+ allowed_user_ids=original.allowed_user_ids,
+ retried_from=operation_id,
+ )
+ original.dto.retried_by_operation_id = operation.dto.operation_id
+ self._enqueue(operation)
+ return operation.dto.model_copy(deep=True)
+
+ def _register_operation_locked(
+ self,
+ *,
+ caller: IntermediatesCaller,
+ mode: IntermediatesCleanupMode,
+ scope: IntermediatesScope,
+ targets: dict[MediaKind, list[tuple[str, Optional[int]]]],
+ allowed_user_ids: Optional[frozenset[str]],
+ retried_from: Optional[str],
+ ) -> _Operation:
+ dto = IntermediatesOperation(
+ operation_id=uuid.uuid4().hex,
+ user_id=caller.user_id,
+ mode=mode,
+ scope=scope,
+ status="pending",
+ created_at=_now(),
+ target_images=len(targets["image"]),
+ target_videos=len(targets["video"]),
+ progress=IntermediatesOperationProgress(
+ unresolved_images=len(targets["image"]), unresolved_videos=len(targets["video"])
+ ),
+ retried_from_operation_id=retried_from,
+ )
+ operation = _Operation(
+ dto=dto,
+ caller=caller,
+ targets={"image": list(targets["image"]), "video": list(targets["video"])},
+ allowed_user_ids=allowed_user_ids,
+ unresolved={"image": dict(targets["image"]), "video": dict(targets["video"])},
+ )
+ self._operations[dto.operation_id] = operation
+ self._operation_order.append(dto.operation_id)
+ while len(self._operation_order) > MAX_RETAINED_OPERATIONS:
+ oldest = self._operation_order[0]
+ if self._operations[oldest].dto.status in ("pending", "running"):
+ break
+ self._operation_order.pop(0)
+ self._operations.pop(oldest, None)
+ self._idempotency = {k: v for k, v in self._idempotency.items() if v[1] != oldest}
+ return operation
+
+ def _enqueue(self, operation: _Operation) -> None:
+ self._ensure_worker()
+ self._pending.put(operation.dto.operation_id)
+ # Events carry snapshots: the worker mutates the live DTO as soon as it dequeues the id.
+ self._services.events.emit_intermediates_operation_changed(operation.dto.model_copy(deep=True))
+
+ def _require_cleanup_available(self) -> None:
+ image_moves = getattr(self._services, "image_moves", None)
+ if image_moves is not None and image_moves.is_maintenance_active():
+ raise IntermediatesUnavailableError("Image storage maintenance is active")
+
+ # endregion
+
+ # region legacy
+
+ def clear_all_images_now(self, caller: IntermediatesCaller) -> int:
+ if not caller.is_admin:
+ raise IntermediatesScopeForbiddenError("Only admins can clear all intermediates")
+ candidates = self._records.list_candidates("image", user_id=None, targets=None)
+ names = [c.name for c in candidates if c.classification == "safe"]
+ guard = self._records.make_delete_guard("image", mode="safe", allowed_user_ids=None)
+ deleted = 0
+ for start in range(0, len(names), DELETE_BATCH_SIZE):
+ result = self._services.images.delete_intermediates_by_names(
+ names[start : start + DELETE_BATCH_SIZE], guard
+ )
+ deleted += len(result.deleted_names)
+ return deleted
+
+ # endregion
+
+ # region worker
+
+ def _worker_loop(self) -> None:
+ while not self._stop.is_set():
+ try:
+ operation_id = self._pending.get(timeout=0.5)
+ except queue.Empty:
+ if self._measure_requested.is_set():
+ self._measure_once()
+ continue
+ if not operation_id:
+ continue
+ with self._lock:
+ operation = self._operations.get(operation_id)
+ if operation is not None:
+ try:
+ self._run(operation)
+ except Exception as error: # pragma: no cover - defensive: the worker must survive
+ self._logger.error(f"Intermediates operation {operation_id} crashed: {error}", exc_info=True)
+ self._finish(operation, error=str(error))
+
+ def _run(self, operation: _Operation) -> None:
+ with self._lock:
+ operation.dto.status = "running"
+ operation.dto.started_at = _now()
+ self._services.events.emit_intermediates_operation_changed(operation.dto.model_copy(deep=True))
+
+ deleters: dict[MediaKind, Callable[[list[str], IntermediateDeleteGuard], IntermediateDeleteResult]] = {
+ "image": self._services.images.delete_intermediates_by_names,
+ "video": self._services.videos.delete_intermediates_by_names,
+ }
+ for kind in ("image", "video"):
+ media_kind = cast(MediaKind, kind)
+ targets = operation.targets[media_kind]
+ guard = self._records.make_delete_guard(
+ media_kind, mode=operation.dto.mode, allowed_user_ids=operation.allowed_user_ids
+ )
+ for start in range(0, len(targets), DELETE_BATCH_SIZE):
+ batch = targets[start : start + DELETE_BATCH_SIZE]
+ halt = self._halt_reason(operation)
+ if halt is not None:
+ self._finish(operation, error=halt)
+ return
+ sizes = dict(batch)
+ names = [name for name, _ in batch]
+ try:
+ result = deleters[media_kind](names, guard)
+ except Exception as error:
+ self._logger.error(f"Intermediates cleanup batch failed ({kind}): {error}", exc_info=True)
+ self._record_batch(operation, media_kind, batch, deleted=[], deferred=[], failed=names, sizes=sizes)
+ continue
+ self._record_batch(
+ operation,
+ media_kind,
+ batch,
+ deleted=result.deleted_names,
+ deferred=result.purge_deferred,
+ failed=[],
+ sizes=sizes,
+ )
+ self._finish(operation, error=None)
+
+ def _halt_reason(self, operation: _Operation) -> Optional[str]:
+ if self._stop.is_set():
+ return "The server is shutting down"
+ image_moves = getattr(self._services, "image_moves", None)
+ if image_moves is not None and image_moves.is_maintenance_active():
+ return "Image storage maintenance started"
+ # Single-user mode has no accounts to re-check: every request is the local administrator,
+ # and the `system` row that names it is deliberately not an admin.
+ if not self._services.configuration.multiuser:
+ return None
+ # Authorization is re-read per batch: an account demoted, deactivated or deleted
+ # mid-operation stops deleting at the next batch boundary.
+ user = self._services.users.get(operation.caller.user_id)
+ if user is None or not user.is_active:
+ return "The confirming account is no longer active"
+ if operation.allowed_user_ids != frozenset({operation.caller.user_id}) and not user.is_admin:
+ return "The confirming account no longer administers this instance"
+ return None
+
+ def _record_batch(
+ self,
+ operation: _Operation,
+ kind: MediaKind,
+ batch: list[tuple[str, Optional[int]]],
+ *,
+ deleted: Sequence[str],
+ deferred: Sequence[str],
+ failed: Sequence[str],
+ sizes: dict[str, Optional[int]],
+ ) -> None:
+ suffix = "images" if kind == "image" else "videos"
+ deleted_set = set(deleted)
+ deferred_set = set(deferred)
+ failed_set = set(failed)
+ with self._lock:
+ progress = operation.dto.progress
+ names = [name for name, _ in batch]
+ setattr(progress, f"processed_{suffix}", getattr(progress, f"processed_{suffix}") + len(names))
+ setattr(progress, f"deleted_{suffix}", getattr(progress, f"deleted_{suffix}") + len(deleted_set))
+ setattr(progress, f"failed_{suffix}", getattr(progress, f"failed_{suffix}") + len(failed_set))
+ retained = len(names) - len(deleted_set) - len(failed_set)
+ setattr(progress, f"retained_{suffix}", getattr(progress, f"retained_{suffix}") + retained)
+ for name in deleted_set:
+ if name in deferred_set:
+ progress.pending_disk_cleanup += 1
+ continue
+ size = sizes.get(name)
+ if size is None:
+ progress.unknown_size_count += 1
+ else:
+ progress.reclaimed_bytes += size
+ unresolved = operation.unresolved[kind]
+ for name in names:
+ if name not in failed_set:
+ unresolved.pop(name, None)
+ setattr(progress, f"unresolved_{suffix}", len(unresolved))
+ # Progress events are coalesced; the final state always goes out from `_finish`.
+ now = time.monotonic()
+ if now - operation.last_progress_event_at < PROGRESS_EVENT_INTERVAL_SECONDS:
+ return
+ operation.last_progress_event_at = now
+ snapshot = operation.dto.model_copy(deep=True)
+ self._services.events.emit_intermediates_operation_changed(snapshot)
+
+ def _finish(self, operation: _Operation, *, error: Optional[str]) -> None:
+ with self._lock:
+ operation.dto.status = "failed" if error is not None else "completed"
+ operation.dto.error = error
+ operation.dto.completed_at = _now()
+ # Only the unresolved names matter after this point; the frozen list is the bulk of an
+ # operation's memory and would otherwise live for as long as the operation is retained.
+ operation.targets = {"image": [], "video": []}
+ snapshot = operation.dto.model_copy(deep=True)
+ self._services.events.emit_intermediates_operation_changed(snapshot)
+
+ def _measure_once(self) -> None:
+ """Measures a bounded batch of unmeasured intermediates; clears the request when none remain."""
+ self._measure_requested.clear()
+ image_moves = getattr(self._services, "image_moves", None)
+ if image_moves is not None and image_moves.is_maintenance_active():
+ # Files are being relocated; a measurement now could record a missing file as empty.
+ return
+ try:
+ remaining = False
+ for kind, files, records in (
+ ("image", self._services.image_files, self._services.image_records),
+ ("video", self._services.video_files, self._services.video_records),
+ ):
+ pending = self._records.next_unmeasured(
+ cast(MediaKind, kind),
+ MEASURE_BATCH_SIZE,
+ min_age_seconds=MEASURE_MIN_AGE_SECONDS,
+ exclude=sorted(self._measure_skipped),
+ )
+ sizes: dict[str, int] = {}
+ for name, subfolder in pending:
+ if self._stop.is_set():
+ return
+ if name in self._measure_skipped:
+ continue
+ try:
+ size = files.get_file_size_bytes(name, subfolder)
+ except Exception as error:
+ self._logger.warning(f"Could not measure {kind} {name}; skipping it until restart: {error}")
+ self._measure_skipped.add(name)
+ continue
+ # A missing file occupies nothing; recording 0 is a measurement, not a guess, and
+ # keeps the row from being re-measured forever.
+ sizes[name] = size if size is not None else 0
+ # One transaction per batch: a library of hundreds of thousands of intermediates is
+ # measured in a few thousand commits rather than one per file.
+ records.set_file_sizes_bytes(sizes)
+ if len(pending) == MEASURE_BATCH_SIZE and sizes:
+ remaining = True
+ if remaining:
+ self._measure_requested.set()
+ # Yield the database lock between batches so generation and saves keep flowing.
+ time.sleep(0.05)
+ except Exception as error:
+ self._logger.warning(f"Measuring intermediate file sizes failed; will retry on demand: {error}")
+
+ # endregion
diff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
new file mode 100644
index 0000000000..8a7665f732
--- /dev/null
+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
@@ -0,0 +1,424 @@
+"""Storage queries of the intermediates manager.
+
+One classification expression decides what every intermediate is under the cleanup policy, and it
+is the same SQL whether it aggregates a summary, freezes a preview's targets or guards a delete:
+
+- ``active``: produced by, or named as an input of, a pending, waiting or running queue item.
+- ``recent``: created inside the grace window, so an in-flight browser upload is never collected
+ before it is promoted, referenced or enqueued.
+- ``referenced``: named by a saved project document or library workflow (`media_references`).
+- ``safe``: none of the above.
+
+Queue inputs are found by scanning each active item's stored session for media-name keys; the
+scan is cached per item so a queue of a thousand pending items is parsed once, not per query.
+"""
+
+import re
+import sqlite3
+from collections import defaultdict
+from dataclasses import dataclass, field
+from typing import Iterable, Literal, Optional, Sequence, cast
+
+from invokeai.app.services.intermediates.intermediates_common import (
+ RECENT_GRACE_SECONDS,
+ IntermediatesCleanupMode,
+ IntermediatesKindCounts,
+ IntermediatesScopeTarget,
+)
+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
+
+MediaKind = Literal["image", "video"]
+Classification = Literal["safe", "referenced", "active", "recent"]
+
+ACTIVE_QUEUE_STATUSES = ("pending", "in_progress", "waiting")
+
+# Keeps the OR-chain of a selection scope, and every IN list, under SQLITE_MAX_VARIABLE_NUMBER.
+_MAX_SQL_VARIABLES = 500
+_TARGETS_PER_STATEMENT = 200
+
+_IMAGE_NAME_RE = re.compile(r'"(?:image_name|imageName)"\s*:\s*"([^"\\]{1,255})"')
+_VIDEO_NAME_RE = re.compile(r'"(?:video_name|videoName)"\s*:\s*"([^"\\]{1,255})"')
+
+_TABLES: dict[MediaKind, tuple[str, str, str]] = {
+ "image": ("images", "image_name", "image_subfolder"),
+ "video": ("videos", "video_name", "video_subfolder"),
+}
+
+
+@dataclass(frozen=True)
+class IntermediateCandidate:
+ name: str
+ classification: Classification
+ file_size_bytes: Optional[int]
+ user_id: str
+ # The row the candidate belongs to; None for the owner's unassigned row.
+ project_id: Optional[str]
+
+
+@dataclass
+class ScopeCounts:
+ """Aggregated intermediates of one (owner, project) row for one media kind."""
+
+ counts: IntermediatesKindCounts = field(default_factory=IntermediatesKindCounts)
+ safe_bytes: int = 0
+ referenced_bytes: int = 0
+ unknown_size_count: int = 0
+
+
+@dataclass(frozen=True)
+class AffectedReference:
+ owner_kind: str
+ user_id: str
+ owner_id: str
+ references: int
+
+
+class IntermediatesRecordsSqlite:
+ def __init__(self, db: SqliteDatabase) -> None:
+ self._db = db
+ # Media names an active queue item's session names, keyed by item id and stamped with the
+ # row's status, status sequence, session length and updated_at: a session rewritten while
+ # the item stays active (a workflow-call parent resuming with its child's outputs) is
+ # re-scanned. Entries live as long as the item is active. This cache is derived from committed
+ # rows only, so it is safe across a rolled-back transaction; the temp table is not, which is
+ # why it is rebuilt on every call rather than skipped on an unchanged set.
+ self._active_inputs: dict[int, tuple[str, set[str], set[str]]] = {}
+
+ # region policy expression
+
+ @staticmethod
+ def _classification_sql(kind: MediaKind) -> str:
+ table, name_column, _ = _TABLES[kind]
+ statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)
+ return f"""
+ CASE
+ WHEN (
+ m.session_id IS NOT NULL
+ AND m.session_id IN (SELECT session_id FROM session_queue WHERE status IN ({statuses}))
+ ) OR m.{name_column} IN (
+ SELECT name FROM temp.intermediates_active_media WHERE kind = '{kind}'
+ ) THEN 'active'
+ WHEN m.created_at > STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '-{RECENT_GRACE_SECONDS} seconds')
+ THEN 'recent'
+ WHEN EXISTS (
+ SELECT 1 FROM media_references r WHERE r.media_kind = '{kind}' AND r.media_name = m.{name_column}
+ ) THEN 'referenced'
+ ELSE 'safe'
+ END
+ """
+
+ def _prepare(self, cursor: sqlite3.Cursor) -> None:
+ """Makes the transaction's view of active work current.
+
+ Runs on the caller's transaction so a classification and the enqueue it might race are
+ ordered by the database lock, never by a stale cache.
+ """
+ cursor.execute(
+ """--sql
+ CREATE TEMP TABLE IF NOT EXISTS intermediates_active_media (
+ kind TEXT NOT NULL,
+ name TEXT NOT NULL,
+ PRIMARY KEY (kind, name)
+ ) WITHOUT ROWID;
+ """
+ )
+ statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)
+ cursor.execute(
+ f"""--sql
+ SELECT item_id, status || ':' || COALESCE(status_sequence, 0) || ':' || LENGTH(session) || ':' || updated_at
+ FROM session_queue WHERE status IN ({statuses});
+ """
+ )
+ active = {cast(int, row[0]): str(row[1]) for row in cursor.fetchall()}
+
+ for stale in [item_id for item_id in self._active_inputs if item_id not in active]:
+ del self._active_inputs[stale]
+ changed = [
+ item_id
+ for item_id, stamp in active.items()
+ if item_id not in self._active_inputs or self._active_inputs[item_id][0] != stamp
+ ]
+ for start in range(0, len(changed), _MAX_SQL_VARIABLES):
+ chunk = changed[start : start + _MAX_SQL_VARIABLES]
+ placeholders = ",".join("?" for _ in chunk)
+ cursor.execute(
+ f"""--sql
+ SELECT item_id,
+ status || ':' || COALESCE(status_sequence, 0) || ':' || LENGTH(session) || ':' || updated_at,
+ session
+ FROM session_queue WHERE item_id IN ({placeholders});
+ """,
+ chunk,
+ )
+ for item_id, stamp, session_json in cursor.fetchall():
+ session_text = session_json if isinstance(session_json, str) else ""
+ self._active_inputs[cast(int, item_id)] = (
+ str(stamp),
+ set(_IMAGE_NAME_RE.findall(session_text)),
+ set(_VIDEO_NAME_RE.findall(session_text)),
+ )
+
+ cursor.execute("DELETE FROM temp.intermediates_active_media;")
+ rows: set[tuple[str, str]] = set()
+ for _, images, videos in self._active_inputs.values():
+ rows.update(("image", name) for name in images)
+ rows.update(("video", name) for name in videos)
+ if rows:
+ cursor.executemany(
+ "INSERT OR IGNORE INTO temp.intermediates_active_media (kind, name) VALUES (?, ?);", sorted(rows)
+ )
+
+ # endregion
+
+ # region summary
+
+ def summarize(self, user_id: Optional[str]) -> dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]]:
+ """Aggregates every intermediate by (owner, project) and classification.
+
+ Media whose project no longer exists, or that never had one, fold into the owner's
+ unassigned row (``project_id`` None).
+ """
+ rows: dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]] = defaultdict(
+ lambda: {"image": ScopeCounts(), "video": ScopeCounts()}
+ )
+ with self._db.transaction() as cursor:
+ self._prepare(cursor)
+ for kind in ("image", "video"):
+ table, _, _ = _TABLES[cast(MediaKind, kind)]
+ owner_filter = "AND m.user_id = ?" if user_id is not None else ""
+ params: list[object] = [user_id] if user_id is not None else []
+ cursor.execute(
+ f"""--sql
+ SELECT user_id, project_key, cls, COUNT(*) AS n,
+ SUM(COALESCE(file_size_bytes, 0)) AS bytes,
+ SUM(CASE WHEN file_size_bytes IS NULL THEN 1 ELSE 0 END) AS unknown
+ FROM (
+ SELECT m.user_id AS user_id,
+ CASE WHEN p.project_id IS NULL THEN NULL ELSE m.project_id END AS project_key,
+ m.file_size_bytes AS file_size_bytes,
+ {self._classification_sql(cast(MediaKind, kind))} AS cls
+ FROM {table} m
+ LEFT JOIN projects p ON p.user_id = m.user_id AND p.project_id = m.project_id
+ WHERE m.is_intermediate = TRUE {owner_filter}
+ )
+ GROUP BY user_id, project_key, cls;
+ """,
+ params,
+ )
+ for owner, project_key, cls, n, total_bytes, unknown in cursor.fetchall():
+ scope = rows[(cast(str, owner), cast(Optional[str], project_key))][cast(MediaKind, kind)]
+ setattr(scope.counts, cls, cast(int, n))
+ if cls == "safe":
+ scope.safe_bytes += cast(int, total_bytes)
+ scope.unknown_size_count += cast(int, unknown)
+ elif cls == "referenced":
+ scope.referenced_bytes += cast(int, total_bytes)
+ scope.unknown_size_count += cast(int, unknown)
+ return dict(rows)
+
+ def get_projects(self, user_id: Optional[str]) -> dict[tuple[str, str], tuple[str, Optional[str]]]:
+ """Maps (owner, project) to (name, cover image): the newest durable image on the project's board."""
+ owner_filter = "WHERE p.user_id = ?" if user_id is not None else ""
+ params: list[object] = [user_id] if user_id is not None else []
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ f"""--sql
+ SELECT p.user_id, p.project_id, p.name,
+ (
+ SELECT bi.image_name FROM board_images bi
+ INNER JOIN images i ON i.image_name = bi.image_name
+ WHERE bi.board_id = p.board_id AND i.is_intermediate = FALSE
+ ORDER BY bi.created_at DESC LIMIT 1
+ )
+ FROM projects p {owner_filter};
+ """,
+ params,
+ )
+ return {
+ (cast(str, r[0]), cast(str, r[1])): (cast(str, r[2]), cast(Optional[str], r[3]))
+ for r in cursor.fetchall()
+ }
+
+ def has_unmeasured_intermediates(self) -> bool:
+ with self._db.transaction() as cursor:
+ for table, _, _ in _TABLES.values():
+ cursor.execute(
+ f"SELECT 1 FROM {table} WHERE is_intermediate = TRUE AND file_size_bytes IS NULL LIMIT 1;"
+ )
+ if cursor.fetchone() is not None:
+ return True
+ return False
+
+ def next_unmeasured(
+ self, kind: MediaKind, limit: int, *, min_age_seconds: int = 0, exclude: Sequence[str] = ()
+ ) -> list[tuple[str, str]]:
+ """Unmeasured intermediates in insertion order; rows younger than ``min_age_seconds`` are left for later.
+
+ A row is written before its file, so a brand-new one would measure as missing. ``exclude``
+ skips names a measurement already failed on, so they cannot pin the batch window.
+ """
+ table, name_column, subfolder_column = _TABLES[kind]
+ excluded = list(exclude[: _MAX_SQL_VARIABLES - 2])
+ placeholders = ",".join("?" for _ in excluded)
+ exclusion = f"AND {name_column} NOT IN ({placeholders})" if excluded else ""
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ f"""--sql
+ SELECT {name_column}, {subfolder_column} FROM {table}
+ WHERE is_intermediate = TRUE AND file_size_bytes IS NULL
+ AND created_at <= STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', ?)
+ {exclusion}
+ ORDER BY rowid ASC
+ LIMIT ?;
+ """,
+ [f"-{min_age_seconds} seconds", *excluded, limit],
+ )
+ return [(cast(str, r[0]), cast(str, r[1])) for r in cursor.fetchall()]
+
+ # endregion
+
+ # region candidates
+
+ @staticmethod
+ def _scope_predicate(targets: Sequence[IntermediatesScopeTarget]) -> tuple[str, list[object]]:
+ clauses: list[str] = []
+ params: list[object] = []
+ for target in targets:
+ if target.project_id is None:
+ clauses.append("(m.user_id = ? AND p.project_id IS NULL)")
+ params.append(target.user_id)
+ else:
+ clauses.append("(m.user_id = ? AND m.project_id = ? AND p.project_id IS NOT NULL)")
+ params.extend((target.user_id, target.project_id))
+ return " OR ".join(clauses), params
+
+ def list_candidates(
+ self,
+ kind: MediaKind,
+ *,
+ user_id: Optional[str],
+ targets: Optional[Sequence[IntermediatesScopeTarget]],
+ ) -> list[IntermediateCandidate]:
+ """Every intermediate in scope with its classification, for freezing a preview.
+
+ ``targets`` narrows to selected rows; otherwise ``user_id`` narrows to an owner, and None
+ means everyone.
+ """
+ table, name_column, _ = _TABLES[kind]
+ candidates: list[IntermediateCandidate] = []
+ with self._db.transaction() as cursor:
+ self._prepare(cursor)
+ select = f"""--sql
+ SELECT m.{name_column}, {self._classification_sql(kind)}, m.file_size_bytes, m.user_id,
+ CASE WHEN p.project_id IS NULL THEN NULL ELSE m.project_id END
+ FROM {table} m
+ LEFT JOIN projects p ON p.user_id = m.user_id AND p.project_id = m.project_id
+ WHERE m.is_intermediate = TRUE
+ """
+ if targets is not None:
+ for start in range(0, len(targets), _TARGETS_PER_STATEMENT):
+ predicate, params = self._scope_predicate(targets[start : start + _TARGETS_PER_STATEMENT])
+ if not predicate:
+ continue
+ cursor.execute(f"{select} AND ({predicate});", params)
+ candidates.extend(self._to_candidates(cursor.fetchall()))
+ elif user_id is not None:
+ cursor.execute(f"{select} AND m.user_id = ?;", (user_id,))
+ candidates.extend(self._to_candidates(cursor.fetchall()))
+ else:
+ cursor.execute(f"{select};")
+ candidates.extend(self._to_candidates(cursor.fetchall()))
+ return candidates
+
+ @staticmethod
+ def _to_candidates(rows: Iterable[sqlite3.Row]) -> list[IntermediateCandidate]:
+ return [
+ IntermediateCandidate(
+ name=cast(str, row[0]),
+ classification=cast(Classification, row[1]),
+ file_size_bytes=cast(Optional[int], row[2]),
+ user_id=cast(str, row[3]),
+ project_id=cast(Optional[str], row[4]),
+ )
+ for row in rows
+ ]
+
+ def affected_references(self, kind: MediaKind, names: Sequence[str]) -> list[AffectedReference]:
+ """The saved documents naming any of ``names``, with how many they name."""
+ counts: dict[tuple[str, str, str], int] = defaultdict(int)
+ with self._db.transaction() as cursor:
+ for start in range(0, len(names), _MAX_SQL_VARIABLES):
+ chunk = list(names[start : start + _MAX_SQL_VARIABLES])
+ placeholders = ",".join("?" for _ in chunk)
+ cursor.execute(
+ f"""--sql
+ SELECT owner_kind, user_id, owner_id, COUNT(*)
+ FROM media_references
+ WHERE media_kind = ? AND media_name IN ({placeholders})
+ GROUP BY owner_kind, user_id, owner_id;
+ """,
+ [kind, *chunk],
+ )
+ for owner_kind, owner_user, owner_id, n in cursor.fetchall():
+ counts[(cast(str, owner_kind), cast(str, owner_user), cast(str, owner_id))] += cast(int, n)
+ return [AffectedReference(owner_kind=k, user_id=u, owner_id=o, references=n) for (k, u, o), n in counts.items()]
+
+ def get_document_names(self, refs: Sequence[AffectedReference]) -> dict[tuple[str, str, str], str]:
+ names: dict[tuple[str, str, str], str] = {}
+ with self._db.transaction() as cursor:
+ for ref in refs:
+ if ref.owner_kind == "project":
+ cursor.execute(
+ "SELECT name FROM projects WHERE user_id = ? AND project_id = ?;", (ref.user_id, ref.owner_id)
+ )
+ else:
+ cursor.execute("SELECT name FROM workflow_library WHERE workflow_id = ?;", (ref.owner_id,))
+ row = cursor.fetchone()
+ if row is not None and row[0] is not None:
+ names[(ref.owner_kind, ref.user_id, ref.owner_id)] = cast(str, row[0])
+ return names
+
+ # endregion
+
+ # region delete guard
+
+ def make_delete_guard(
+ self, kind: MediaKind, *, mode: IntermediatesCleanupMode, allowed_user_ids: Optional[frozenset[str]]
+ ):
+ """The final check of a cleanup batch, run on the deleting transaction.
+
+ Re-applies the policy to the frozen targets at the moment of deletion: anything that became
+ active, referenced (safe mode) or non-intermediate since the preview is kept, as is anything
+ that left the authorized accounts. ``allowed_user_ids`` None means every account.
+ """
+ table, name_column, _ = _TABLES[kind]
+ deletable = "('safe')" if mode == "safe" else "('safe', 'referenced')"
+
+ def guard(cursor: sqlite3.Cursor, names: Sequence[str]) -> list[str]:
+ self._prepare(cursor)
+ kept: list[str] = []
+ for start in range(0, len(names), _MAX_SQL_VARIABLES):
+ chunk = list(names[start : start + _MAX_SQL_VARIABLES])
+ placeholders = ",".join("?" for _ in chunk)
+ cursor.execute(
+ f"""--sql
+ SELECT name, user_id FROM (
+ SELECT m.{name_column} AS name, m.user_id AS user_id, {self._classification_sql(kind)} AS cls
+ FROM {table} m
+ WHERE m.{name_column} IN ({placeholders}) AND m.is_intermediate = TRUE
+ )
+ WHERE cls IN {deletable};
+ """,
+ chunk,
+ )
+ # Ownership is re-read here rather than trusted from the preview.
+ kept.extend(
+ cast(str, row[0])
+ for row in cursor.fetchall()
+ if allowed_user_ids is None or cast(str, row[1]) in allowed_user_ids
+ )
+ return kept
+
+ return guard
+
+ # endregion
diff --git a/invokeai/app/services/invocation_services.py b/invokeai/app/services/invocation_services.py
index 589a747f6c..7c32a1c935 100644
--- a/invokeai/app/services/invocation_services.py
+++ b/invokeai/app/services/invocation_services.py
@@ -33,6 +33,7 @@ if TYPE_CHECKING:
from invokeai.app.services.image_moves.image_moves_default import ImageMoveService
from invokeai.app.services.image_records.image_records_base import ImageRecordStorageBase
from invokeai.app.services.images.images_base import ImageServiceABC
+ from invokeai.app.services.intermediates.intermediates_base import IntermediatesServiceBase
from invokeai.app.services.invocation_cache.invocation_cache_base import InvocationCacheBase
from invokeai.app.services.invocation_stats.invocation_stats_base import InvocationStatsServiceBase
from invokeai.app.services.model_images.model_images_base import ModelImageFileStorageBase
@@ -111,6 +112,7 @@ class InvocationServices:
image_moves: "ImageMoveService | None" = None,
progress_previews: "ProgressPreviewsBase | None" = None,
fonts: "FontService | None" = None,
+ intermediates: "IntermediatesServiceBase | None" = None,
):
self.board_images = board_images
self.board_image_records = board_image_records
@@ -160,3 +162,4 @@ class InvocationServices:
self.image_index_records = image_index_records
self.image_index = image_index
self.fonts = fonts
+ self.intermediates = intermediates
diff --git a/invokeai/app/services/session_queue/session_queue_common.py b/invokeai/app/services/session_queue/session_queue_common.py
index b9738c6c2e..b5b1c8a35f 100644
--- a/invokeai/app/services/session_queue/session_queue_common.py
+++ b/invokeai/app/services/session_queue/session_queue_common.py
@@ -278,6 +278,9 @@ class SessionQueueItem(BaseModel):
completed_at: Optional[Union[datetime.datetime, str]] = Field(description="When this queue item was completed")
queue_id: str = Field(description="The id of the queue with which this item is associated")
user_id: str = Field(default="system", description="The id of the user who created this queue item")
+ project_id: Optional[str] = Field(
+ default=None, description="The project this queue item was enqueued for, if any; its outputs inherit it"
+ )
user_display_name: Optional[str] = Field(
default=None, description="The display name of the user who created this queue item, if available"
)
@@ -681,6 +684,7 @@ ValueToInsertTuple: TypeAlias = tuple[
str | None, # destination (optional)
int | None, # retried_from_item_id (optional, this is always None for new items)
str, # user_id
+ str | None, # project_id (optional)
]
"""A type alias for the tuple of values to insert into the session queue table.
@@ -715,6 +719,7 @@ def prepare_values_to_insert(
- destination (optional)
- retried_from_item_id (optional, this is always None for new items)
- user_id
+ - project_id (optional)
"""
# A tuple is a fast and memory-efficient way to store the values to insert. Previously, we used a NamedTuple, but
@@ -745,6 +750,7 @@ def prepare_values_to_insert(
batch.destination,
None,
user_id,
+ batch.project_id,
)
)
return values_to_insert
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index 0f65a57846..2bce6a7e27 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -482,8 +482,8 @@ class SqliteSessionQueue(SessionQueueBase):
raise EnqueueReceiptLimitError("Unacknowledged enqueue receipts exceed the storage limit")
cursor.executemany(
"""--sql
- INSERT INTO session_queue (queue_id, session, session_id, batch_id, field_values, priority, workflow, origin, destination, retried_from_item_id, user_id)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO session_queue (queue_id, session, session_id, batch_id, field_values, priority, workflow, origin, destination, retried_from_item_id, user_id, project_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
values_to_insert,
)
@@ -1480,6 +1480,7 @@ class SqliteSessionQueue(SessionQueueBase):
destination,
retried_from_item_id,
user_id,
+ project_id,
workflow_call_id,
parent_item_id,
parent_session_id,
@@ -1487,7 +1488,7 @@ class SqliteSessionQueue(SessionQueueBase):
workflow_call_depth,
status
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
""",
(
parent_queue_item.queue_id,
@@ -1501,6 +1502,7 @@ class SqliteSessionQueue(SessionQueueBase):
parent_queue_item.destination,
None,
parent_queue_item.user_id,
+ parent_queue_item.project_id,
workflow_call_execution.id,
parent_queue_item.item_id,
parent_queue_item.session_id,
@@ -1954,6 +1956,7 @@ class SqliteSessionQueue(SessionQueueBase):
root_queue_item.destination,
retried_from_item_id,
root_queue_item.user_id,
+ root_queue_item.project_id,
)
values_to_insert.append(value_to_insert)
@@ -1962,8 +1965,8 @@ class SqliteSessionQueue(SessionQueueBase):
cursor.executemany(
"""--sql
- INSERT INTO session_queue (queue_id, session, session_id, batch_id, field_values, priority, workflow, origin, destination, retried_from_item_id, user_id)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO session_queue (queue_id, session, session_id, batch_id, field_values, priority, workflow, origin, destination, retried_from_item_id, user_id, project_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
values_to_insert,
)
diff --git a/invokeai/app/services/shared/intermediate_delete.py b/invokeai/app/services/shared/intermediate_delete.py
new file mode 100644
index 0000000000..e3ea321c6f
--- /dev/null
+++ b/invokeai/app/services/shared/intermediate_delete.py
@@ -0,0 +1,28 @@
+"""Contracts of a conditional intermediate delete shared by the image and video services.
+
+A guard runs on the deleting transaction's cursor, immediately before the `DELETE`, and returns
+the subset of the candidate names that may still go. Because the database serializes writers
+through one connection and lock, nothing — a project save, an enqueue, a promotion — can make a
+name protected between the guard's answer and the record's removal.
+"""
+
+import sqlite3
+from dataclasses import dataclass, field
+from typing import Protocol, Sequence
+
+
+class IntermediateDeleteGuard(Protocol):
+ def __call__(self, cursor: sqlite3.Cursor, names: Sequence[str]) -> list[str]: ...
+
+
+@dataclass
+class IntermediateDeleteResult:
+ """What a batch delete removed.
+
+ ``deleted_names`` are records that are committed as gone. ``purge_deferred`` names the subset
+ whose files could not be removed yet: the record deletion still stands, and the journal (images)
+ or a later recovery (videos) finishes the purge, so their bytes are not reclaimed yet.
+ """
+
+ deleted_names: list[str] = field(default_factory=list)
+ purge_deferred: list[str] = field(default_factory=list)
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 7f05af7f08..f3eb022e24 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -269,6 +269,7 @@ class ImagesInterface(InvocationContextInterface):
session_id=self._data.queue_item.session_id,
node_id=self._data.invocation.id,
user_id=self._data.queue_item.user_id,
+ project_id=self._data.queue_item.project_id,
)
def get_pil(self, image_name: str, mode: IMAGE_MODES | None = None) -> Image:
@@ -438,6 +439,7 @@ class VideosInterface(InvocationContextInterface):
session_id=self._data.queue_item.session_id,
node_id=self._data.invocation.id,
user_id=self._data.queue_item.user_id,
+ project_id=self._data.queue_item.project_id,
)
def get_dto(self, video_name: str) -> VideoDTO:
diff --git a/invokeai/app/services/video_files/video_files_base.py b/invokeai/app/services/video_files/video_files_base.py
index 287430995d..a26a443c72 100644
--- a/invokeai/app/services/video_files/video_files_base.py
+++ b/invokeai/app/services/video_files/video_files_base.py
@@ -42,6 +42,11 @@ class VideoFileStorageBase(ABC):
"""
pass
+ @abstractmethod
+ def get_file_size_bytes(self, video_name: str, video_subfolder: str = "") -> Optional[int]:
+ """Bytes the video, its thumbnail and sidecar occupy; None when the video file is missing."""
+ pass
+
@abstractmethod
def delete(self, video_name: str, video_subfolder: str = "") -> None:
"""Deletes a video file and its thumbnail (if one exists)."""
diff --git a/invokeai/app/services/video_files/video_files_disk.py b/invokeai/app/services/video_files/video_files_disk.py
index e9ff34236c..f0b99aa955 100644
--- a/invokeai/app/services/video_files/video_files_disk.py
+++ b/invokeai/app/services/video_files/video_files_disk.py
@@ -194,6 +194,21 @@ class DiskVideoFileStorage(VideoFileStorageBase):
except Exception as e:
raise VideoFileDeleteException from e
+ def get_file_size_bytes(self, video_name: str, video_subfolder: str = "") -> Optional[int]:
+ try:
+ size = self.get_path(video_name, video_subfolder=video_subfolder).stat().st_size
+ except FileNotFoundError:
+ return None
+ for companion in (
+ self.get_path(video_name, thumbnail=True, video_subfolder=video_subfolder),
+ self.__get_sidecar_path(video_name, video_subfolder=video_subfolder),
+ ):
+ try:
+ size += companion.stat().st_size
+ except FileNotFoundError:
+ pass
+ return size
+
def get_path(self, video_name: str, thumbnail: bool = False, video_subfolder: str = "") -> Path:
base_folder = self.__thumbnails_folder if thumbnail else self.__output_folder
filename = get_video_thumbnail_name(video_name) if thumbnail else video_name
diff --git a/invokeai/app/services/video_records/video_records_base.py b/invokeai/app/services/video_records/video_records_base.py
index a828371838..69421feeb8 100644
--- a/invokeai/app/services/video_records/video_records_base.py
+++ b/invokeai/app/services/video_records/video_records_base.py
@@ -4,6 +4,7 @@ from typing import Optional
from invokeai.app.invocations.fields import MetadataField
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.video_records.video_records_common import (
@@ -65,6 +66,22 @@ class VideoRecordStorageBase(ABC):
"""Deletes a video record."""
pass
+ @abstractmethod
+ def get_subfolders(self, video_names: list[str]) -> dict[str, str]:
+ """Maps each existing named video to its on-disk subfolder; absent names are omitted."""
+ pass
+
+ @abstractmethod
+ def delete_intermediates_by_names(
+ self, video_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> list[str]:
+ """Deletes the named records that are still intermediates, returning exactly the names removed.
+
+ Mirrors the image store: the `is_intermediate` predicate rides on the DELETE, and ``guard``
+ narrows each chunk on the deleting transaction.
+ """
+ pass
+
@abstractmethod
def delete_many(self, video_names: list[str]) -> None:
"""Deletes many video records."""
@@ -88,10 +105,21 @@ class VideoRecordStorageBase(ABC):
metadata: Optional[str] = None,
user_id: Optional[str] = None,
video_subfolder: str = "",
+ project_id: Optional[str] = None,
) -> datetime:
"""Saves a video record."""
pass
+ @abstractmethod
+ def set_file_size_bytes(self, video_name: str, file_size_bytes: Optional[int]) -> None:
+ """Records the measured on-disk size of a video and its companions; None marks it unmeasured."""
+ pass
+
+ @abstractmethod
+ def set_file_sizes_bytes(self, sizes: dict[str, int]) -> None:
+ """Records many measured sizes in one transaction."""
+ pass
+
@abstractmethod
def get_user_id(self, video_name: str) -> Optional[str]:
"""Gets the user_id of the video owner. Returns None if video not found."""
diff --git a/invokeai/app/services/video_records/video_records_common.py b/invokeai/app/services/video_records/video_records_common.py
index 29899c0f9e..5c8afcabf2 100644
--- a/invokeai/app/services/video_records/video_records_common.py
+++ b/invokeai/app/services/video_records/video_records_common.py
@@ -100,6 +100,8 @@ VIDEO_DTO_COLS = ", ".join(
"deleted_at",
"starred",
"video_subfolder",
+ "project_id",
+ "file_size_bytes",
]
]
# `media_origin` is not a column: it is the one key of the `metadata` JSON blob the
@@ -132,6 +134,12 @@ class VideoRecord(BaseModelExcludeNull):
starred: bool = Field(description="Whether this video is starred.")
has_workflow: bool = Field(description="Whether this video has a workflow associated.")
video_subfolder: str = Field(default="", description="The subfolder where the video is stored on disk.")
+ project_id: Optional[str] = Field(
+ default=None, description="The project this video originated in, if it was made for one."
+ )
+ file_size_bytes: Optional[int] = Field(
+ default=None, description="Bytes the video, its thumbnail and sidecar occupy on disk; null until measured."
+ )
media_origin: Optional[str] = Field(
default=None,
description="How this video entered the gallery, if it was marked: 'audio_upload' for an uploaded audio "
@@ -168,6 +176,8 @@ def deserialize_video_record(video_dict: dict) -> VideoRecord:
has_workflow = video_dict.get("has_workflow", False)
video_subfolder = video_dict.get("video_subfolder", "")
media_origin = coerce_media_origin(video_dict.get("media_origin", None))
+ project_id = video_dict.get("project_id", None)
+ file_size_bytes = video_dict.get("file_size_bytes", None)
return VideoRecord(
video_name=video_name,
@@ -187,6 +197,8 @@ def deserialize_video_record(video_dict: dict) -> VideoRecord:
has_workflow=has_workflow,
video_subfolder=video_subfolder,
media_origin=media_origin,
+ project_id=project_id,
+ file_size_bytes=file_size_bytes,
)
diff --git a/invokeai/app/services/video_records/video_records_sqlite.py b/invokeai/app/services/video_records/video_records_sqlite.py
index d7ca569be5..078d8cca3b 100644
--- a/invokeai/app/services/video_records/video_records_sqlite.py
+++ b/invokeai/app/services/video_records/video_records_sqlite.py
@@ -4,6 +4,7 @@ from typing import Optional, Union, cast
from invokeai.app.invocations.fields import MetadataField, MetadataFieldValidator
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
@@ -45,6 +46,70 @@ class SqliteVideoRecordStorage(VideoRecordStorageBase):
raise VideoRecordNotFoundException
return deserialize_video_record(dict(result))
+ _MAX_SQL_VARIABLES = 500
+
+ def get_subfolders(self, video_names: list[str]) -> dict[str, str]:
+ subfolders: dict[str, str] = {}
+ with self._db.transaction() as cursor:
+ for start in range(0, len(video_names), self._MAX_SQL_VARIABLES):
+ chunk = video_names[start : start + self._MAX_SQL_VARIABLES]
+ placeholders = ",".join("?" for _ in chunk)
+ cursor.execute(
+ f"SELECT video_name, video_subfolder FROM videos WHERE video_name IN ({placeholders})", chunk
+ )
+ for row in cursor.fetchall():
+ subfolders[cast(str, row[0])] = cast(str, row[1])
+ return subfolders
+
+ def delete_intermediates_by_names(
+ self, video_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> list[str]:
+ deleted: list[str] = []
+ try:
+ with self._db.transaction() as cursor:
+ for start in range(0, len(video_names), self._MAX_SQL_VARIABLES):
+ chunk = video_names[start : start + self._MAX_SQL_VARIABLES]
+ if guard is not None:
+ chunk = guard(cursor, chunk)
+ if not chunk:
+ continue
+ placeholders = ",".join("?" for _ in chunk)
+ select_query = f"SELECT video_name FROM videos WHERE video_name IN ({placeholders})"
+ cursor.execute(select_query, chunk)
+ present_before = {cast(str, r[0]) for r in cursor.fetchall()}
+ cursor.execute(
+ f"DELETE FROM videos WHERE video_name IN ({placeholders}) AND is_intermediate = TRUE",
+ chunk,
+ )
+ cursor.execute(select_query, chunk)
+ present_after = {cast(str, r[0]) for r in cursor.fetchall()}
+ deleted.extend(name for name in chunk if name in present_before and name not in present_after)
+ except sqlite3.Error as e:
+ raise VideoRecordDeleteException from e
+ return deleted
+
+ def set_file_size_bytes(self, video_name: str, file_size_bytes: Optional[int]) -> None:
+ with self._db.transaction() as cursor:
+ try:
+ cursor.execute(
+ "UPDATE videos SET file_size_bytes = ? WHERE video_name = ?;",
+ (file_size_bytes, video_name),
+ )
+ except sqlite3.Error as e:
+ raise VideoRecordSaveException from e
+
+ def set_file_sizes_bytes(self, sizes: dict[str, int]) -> None:
+ if not sizes:
+ return
+ with self._db.transaction() as cursor:
+ try:
+ cursor.executemany(
+ "UPDATE videos SET file_size_bytes = ? WHERE video_name = ?;",
+ [(size, name) for name, size in sizes.items()],
+ )
+ except sqlite3.Error as e:
+ raise VideoRecordSaveException from e
+
def get_user_id(self, video_name: str) -> Optional[str]:
with self._db.transaction() as cursor:
cursor.execute(
@@ -257,6 +322,7 @@ class SqliteVideoRecordStorage(VideoRecordStorageBase):
metadata: Optional[str] = None,
user_id: Optional[str] = None,
video_subfolder: str = "",
+ project_id: Optional[str] = None,
) -> datetime:
with self._db.transaction() as cursor:
try:
@@ -277,9 +343,10 @@ class SqliteVideoRecordStorage(VideoRecordStorageBase):
starred,
has_workflow,
user_id,
- video_subfolder
+ video_subfolder,
+ project_id
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
""",
(
video_name,
@@ -297,6 +364,7 @@ class SqliteVideoRecordStorage(VideoRecordStorageBase):
has_workflow,
user_id or "system",
video_subfolder,
+ project_id,
),
)
diff --git a/invokeai/app/services/videos/videos_base.py b/invokeai/app/services/videos/videos_base.py
index f1cb64fb2c..bd57780bf1 100644
--- a/invokeai/app/services/videos/videos_base.py
+++ b/invokeai/app/services/videos/videos_base.py
@@ -6,6 +6,7 @@ from PIL import Image
from invokeai.app.invocations.fields import MetadataField
from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.video_records.video_records_common import (
@@ -62,6 +63,7 @@ class VideoServiceABC(ABC):
user_id: Optional[str] = None,
first_frame: Optional[Image.Image] = None,
move_source: bool = True,
+ project_id: Optional[str] = None,
) -> VideoDTO:
"""Creates a video by moving the file at `source_path` into storage and recording it.
@@ -147,6 +149,17 @@ class VideoServiceABC(ABC):
"""Deletes a video."""
pass
+ @abstractmethod
+ def delete_intermediates_by_names(
+ self, video_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> IntermediateDeleteResult:
+ """Deletes the named videos that are still intermediates, reporting the names removed.
+
+ Files are staged before the conditional record delete and restored for every name the
+ delete (or ``guard``) kept, so a promoted or protected video is never damaged.
+ """
+ pass
+
@abstractmethod
def delete_videos_by_names(self, video_names: list[str]) -> tuple[list[str], list[str]]:
"""Deletes exactly these videos; returns ``(deleted_names, failed_names)``.
diff --git a/invokeai/app/services/videos/videos_default.py b/invokeai/app/services/videos/videos_default.py
index 80ffbbcdab..eb85e05cff 100644
--- a/invokeai/app/services/videos/videos_default.py
+++ b/invokeai/app/services/videos/videos_default.py
@@ -12,6 +12,7 @@ from invokeai.app.services.image_records.image_records_common import (
)
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.bulk_media_delete import StagedMediaDeleteAdapter, delete_media_by_names
+from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.video_files.video_files_common import (
@@ -56,6 +57,7 @@ class VideoService(VideoServiceABC):
user_id: Optional[str] = None,
first_frame: Optional[Image.Image] = None,
move_source: bool = True,
+ project_id: Optional[str] = None,
) -> VideoDTO:
if video_origin not in ResourceOrigin:
raise InvalidOriginException
@@ -89,6 +91,7 @@ class VideoService(VideoServiceABC):
session_id=session_id,
user_id=user_id,
video_subfolder=video_subfolder,
+ project_id=project_id,
)
record_saved = True
if board_id is not None:
@@ -118,6 +121,7 @@ class VideoService(VideoServiceABC):
duration=duration,
fps=fps,
)
+ self._record_file_size(video_name, video_subfolder)
video_dto = self.get_dto(video_name)
self._on_changed(video_dto)
@@ -160,6 +164,14 @@ class VideoService(VideoServiceABC):
self.__invoker.services.logger.error(f"Problem saving video record and file: {str(e)}")
raise
+ def _record_file_size(self, video_name: str, video_subfolder: str) -> None:
+ """Best-effort size accounting; an unmeasured row reads as unknown, never zero."""
+ try:
+ size = self.__invoker.services.video_files.get_file_size_bytes(video_name, video_subfolder=video_subfolder)
+ self.__invoker.services.video_records.set_file_size_bytes(video_name, size)
+ except Exception as e:
+ self.__invoker.services.logger.warning(f"Failed to record the file size of video {video_name}: {e}")
+
def copy(self, source_video_name: str, board_id: Optional[str] = None, user_id: Optional[str] = None) -> VideoDTO:
"""Duplicate a video without moving the source or exposing partial attachment semantics.
@@ -384,6 +396,33 @@ class VideoService(VideoServiceABC):
)
return self.delete_videos_by_names(video_names)
+ def delete_intermediates_by_names(
+ self, video_names: list[str], guard: Optional[IntermediateDeleteGuard] = None
+ ) -> IntermediateDeleteResult:
+ records = self.__invoker.services.video_records
+ files = self.__invoker.services.video_files
+ subfolders = records.get_subfolders(video_names)
+ if not subfolders:
+ return IntermediateDeleteResult()
+
+ # Records first, files second, like the image path: only the files of rows the conditional
+ # delete actually removed are touched, so a video promoted or protected between the preview
+ # and this call keeps both. There is no video delete journal, so a crash between the two
+ # steps leaves files without records — the exposure `delete_videos_by_names` already has.
+ deleted = records.delete_intermediates_by_names(list(subfolders.keys()), guard=guard)
+ result = IntermediateDeleteResult(deleted_names=deleted)
+ for name in deleted:
+ try:
+ files.delete(name, video_subfolder=subfolders[name])
+ except Exception as cleanup_error:
+ self.__invoker.services.logger.error(
+ f"Failed to purge intermediate video files for {name}: {cleanup_error}"
+ )
+ result.purge_deferred.append(name)
+ for name in deleted:
+ self._on_deleted(name)
+ return result
+
def delete_videos_by_names(self, video_names: list[str]) -> tuple[list[str], list[str]]:
"""Delete exactly these videos, returning ``(deleted, failed)``.
diff --git a/tests/app/api/test_video_upload_limits.py b/tests/app/api/test_video_upload_limits.py
index 56338d30ff..5aeaba32a8 100644
--- a/tests/app/api/test_video_upload_limits.py
+++ b/tests/app/api/test_video_upload_limits.py
@@ -551,6 +551,7 @@ def _run_upload(request: MagicMock) -> Any:
is_intermediate=False,
board_id=None,
session_id=None,
+ project_id=None,
)
)
diff --git a/tests/app/routers/test_media_upload_provenance.py b/tests/app/routers/test_media_upload_provenance.py
new file mode 100644
index 0000000000..7c8db27cb0
--- /dev/null
+++ b/tests/app/routers/test_media_upload_provenance.py
@@ -0,0 +1,148 @@
+"""Uploads record which of the caller's own projects they originate in, and nothing else."""
+
+import io
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin
+from invokeai.app.services.images.images_common import ImageDTO
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.videos.videos_common import VideoDTO
+from invokeai.app.util.video_ingest import MediaProbe
+
+
+def _auth(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+def _png_bytes() -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", (8, 8), (255, 0, 0)).save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def _image_dto() -> ImageDTO:
+ return ImageDTO(
+ image_name="upload.png",
+ image_origin=ResourceOrigin.EXTERNAL,
+ image_category=ImageCategory.USER,
+ width=8,
+ height=8,
+ created_at="None",
+ updated_at="None",
+ is_intermediate=True,
+ starred=False,
+ has_workflow=False,
+ image_url="/images/upload.png",
+ thumbnail_url="/thumbnails/upload.webp",
+ )
+
+
+def upload_ready(enable_multiuser: Any, mock_invoker: Invoker, monkeypatch: Any) -> None:
+ mock_invoker.services.image_moves = MagicMock()
+ mock_invoker.services.image_moves.is_maintenance_active.return_value = False
+ monkeypatch.setattr(mock_invoker.services.images, "create", MagicMock(return_value=_image_dto()))
+ mock_invoker.services.videos = MagicMock()
+
+
+def _own_project_id(mock_invoker: Invoker, client: TestClient, token: str) -> str:
+ response = client.post("/api/v1/projects/", json={"name": "Mine", "data": {}}, headers=_auth(token))
+ assert response.status_code == 201
+ return response.json()["project_id"]
+
+
+def test_image_upload_records_the_callers_project(
+ upload_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str
+) -> None:
+ project_id = _own_project_id(mock_invoker, client, user1_token)
+
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "other", "is_intermediate": True, "project_id": project_id},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ headers=_auth(user1_token),
+ )
+
+ assert response.status_code == 201
+ assert mock_invoker.services.images.create.call_args.kwargs["project_id"] == project_id
+
+
+def test_image_upload_refuses_a_project_the_caller_does_not_own(
+ upload_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str, user2_token: str, admin_token: str
+) -> None:
+ user2s = _own_project_id(mock_invoker, client, user2_token)
+
+ # Even an admin cannot attribute an upload to someone else's project.
+ for token, project_id in ((user1_token, user2s), (admin_token, user2s), (admin_token, "no-such-project")):
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "other", "is_intermediate": True, "project_id": project_id},
+ files={"file": ("upload.png", _png_bytes(), "image/png")},
+ headers=_auth(token),
+ )
+ assert response.status_code == 404, response.text
+
+ mock_invoker.services.images.create.assert_not_called()
+
+
+def test_video_upload_validates_the_project_before_reading_the_body(
+ upload_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str
+) -> None:
+ with patch("invokeai.app.api.routers.videos._stream_video_upload") as stream:
+ response = client.post(
+ "/api/v1/videos/upload",
+ params={"video_category": "general", "is_intermediate": True, "project_id": "not-mine"},
+ files={"file": ("video.mp4", b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 12, "video/mp4")},
+ headers=_auth(user1_token),
+ )
+
+ assert response.status_code == 404
+ stream.assert_not_called()
+ mock_invoker.services.videos.create.assert_not_called()
+
+
+def test_video_upload_records_the_callers_project(
+ upload_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str
+) -> None:
+ project_id = _own_project_id(mock_invoker, client, user1_token)
+ mock_invoker.services.videos.create.return_value = VideoDTO.model_validate(
+ {
+ "video_name": "uploaded.mp4",
+ "video_origin": "external",
+ "video_category": "general",
+ "width": 64,
+ "height": 64,
+ "duration": 1.0,
+ "fps": 8.0,
+ "created_at": "2026-01-01T00:00:00Z",
+ "updated_at": "2026-01-01T00:00:00Z",
+ "is_intermediate": True,
+ "starred": False,
+ "has_workflow": False,
+ "video_subfolder": "",
+ "video_url": "/api/v1/videos/i/uploaded.mp4/full",
+ "thumbnail_url": "/api/v1/videos/i/uploaded.mp4/thumbnail",
+ }
+ )
+
+ with (
+ patch(
+ "invokeai.app.api.routers.videos.probe_media_streams",
+ return_value=MediaProbe(video_codec="h264", audio_codec="aac"),
+ ),
+ patch("invokeai.app.api.routers.videos._probe_decodable_video", return_value=((64, 64, 1.0, 8.0), None)),
+ ):
+ response = client.post(
+ "/api/v1/videos/upload",
+ params={"video_category": "general", "is_intermediate": True, "project_id": project_id},
+ files={"file": ("video.mp4", b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 12, "video/mp4")},
+ headers=_auth(user1_token),
+ )
+
+ assert response.status_code == 201, response.text
+ assert mock_invoker.services.videos.create.call_args.kwargs["project_id"] == project_id
diff --git a/tests/app/services/image_records/test_image_records_sqlite.py b/tests/app/services/image_records/test_image_records_sqlite.py
index 8a2e0ff5a8..3c3e841889 100644
--- a/tests/app/services/image_records/test_image_records_sqlite.py
+++ b/tests/app/services/image_records/test_image_records_sqlite.py
@@ -1,7 +1,7 @@
"""DB-backed tests for SqliteImageRecordStorage.
Verifies that image_subfolder round-trips correctly through save(), get(),
-get_many(), and get_intermediates() against a real (in-memory) SQLite database,
+get_many(), and get_subfolders() against a real (in-memory) SQLite database,
and that get_many()/get_image_names() enforce per-user ownership isolation.
"""
@@ -124,38 +124,28 @@ class TestImageRecordExists:
assert store.exists("missing.png") is False
-class TestGetIntermediatesSubfolder:
- """get_intermediates() returns (name, subfolder) pairs without deleting rows."""
-
- def test_returns_subfolder_pairs(self, store: SqliteImageRecordStorage) -> None:
- _save(store, "keep.png", subfolder="general", is_intermediate=False)
- _save(store, "tmp1.png", subfolder="intermediate", is_intermediate=True)
- _save(store, "tmp2.png", subfolder="intermediate", is_intermediate=True)
-
- pairs = store.get_intermediates()
+def _intermediates(store: SqliteImageRecordStorage) -> list[tuple[str, str]]:
+ with store._db.transaction() as cursor:
+ cursor.execute("SELECT image_name, image_subfolder FROM images WHERE is_intermediate = TRUE;")
+ return [(row[0], row[1]) for row in cursor.fetchall()]
- # Should return only intermediate images with their subfolders
- assert len(pairs) == 2
- names_and_subs = set(pairs)
- assert ("tmp1.png", "intermediate") in names_and_subs
- assert ("tmp2.png", "intermediate") in names_and_subs
- # Non-intermediate image should still exist
- record = store.get("keep.png")
- assert record.image_subfolder == "general"
+class TestGetSubfolders:
+ """get_subfolders() maps the named rows to their on-disk subfolders without touching them."""
- def test_get_intermediates_does_not_delete(self, store: SqliteImageRecordStorage) -> None:
- _save(store, "tmp.png", subfolder="x", is_intermediate=True)
- store.get_intermediates()
+ def test_returns_subfolders_of_existing_rows_only(self, store: SqliteImageRecordStorage) -> None:
+ _save(store, "keep.png", subfolder="general", is_intermediate=False)
+ _save(store, "tmp1.png", subfolder="intermediate", is_intermediate=True)
- # Listing intermediates must not remove them.
- record = store.get("tmp.png")
- assert record.image_subfolder == "x"
+ assert store.get_subfolders(["keep.png", "tmp1.png", "missing.png"]) == {
+ "keep.png": "general",
+ "tmp1.png": "intermediate",
+ }
+ assert store.get("tmp1.png").image_subfolder == "intermediate"
def test_intermediates_are_deleted_via_delete_intermediates_by_names(self, store: SqliteImageRecordStorage) -> None:
_save(store, "tmp.png", subfolder="x", is_intermediate=True)
- pairs = store.get_intermediates()
- deleted = store.delete_intermediates_by_names([name for name, _ in pairs])
+ deleted = store.delete_intermediates_by_names([name for name, _ in _intermediates(store)])
assert deleted == ["tmp.png"]
with pytest.raises(ImageRecordNotFoundException):
@@ -201,7 +191,7 @@ class TestDeleteIntermediatesByNames:
"""An image promoted out of intermediate status after the snapshot must survive."""
_save(store, "tmp.png", subfolder="x", is_intermediate=True)
_save(store, "promoted.png", subfolder="x", is_intermediate=True)
- snapshot = [name for name, _ in store.get_intermediates()]
+ snapshot = [name for name, _ in _intermediates(store)]
assert set(snapshot) == {"tmp.png", "promoted.png"}
# Simulate the race: the image stops being an intermediate between the snapshot and delete.
@@ -224,7 +214,7 @@ class TestDeleteIntermediatesByNames:
"""
_save(store, "tmp.png", is_intermediate=True)
_save(store, "promoted.png", is_intermediate=True)
- snapshot = [name for name, _ in store.get_intermediates()]
+ snapshot = [name for name, _ in _intermediates(store)]
# Promote from inside the call, between the first SELECT and the DELETE.
real_execute = store._db._conn.execute
@@ -275,7 +265,7 @@ class TestDeleteIntermediatesByNames:
assert set(deleted) == set(names) - {survivor}
assert survivor not in deleted
assert store.get(survivor).is_intermediate is False
- assert store.get_intermediates() == []
+ assert _intermediates(store) == []
def test_chunking_stays_within_the_declared_variable_limit(self, store: SqliteImageRecordStorage) -> None:
"""No statement may bind more parameters than the declared limit."""
diff --git a/tests/app/services/images/test_images_default.py b/tests/app/services/images/test_images_default.py
index 3d8595d25f..ae6839a70a 100644
--- a/tests/app/services/images/test_images_default.py
+++ b/tests/app/services/images/test_images_default.py
@@ -2,7 +2,7 @@
Covers subfolder forwarding for all strategies, the delete_images_on_board
silent-failure contract (Points 2 & 3 from PR review), and the transactional
-staged-deletion contracts of delete() and delete_intermediates().
+staged-deletion contracts of delete() and delete_intermediates_by_names().
"""
import errno
@@ -50,7 +50,7 @@ def image_service() -> ImageService:
invoker.services.urls.get_image_url.return_value = "http://localhost/img.png"
invoker.services.configuration.image_subfolder_strategy = "flat"
# By default every named intermediate is still an intermediate when the delete runs.
- invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names: list(names)
+ invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names, guard=None: list(names)
svc.start(invoker)
return svc
@@ -285,18 +285,20 @@ class TestDeleteForwardsSubfolder:
def test_delete_intermediates_forwards_subfolder(self, image_service: ImageService):
invoker = image_service._ImageService__invoker # type: ignore
- invoker.services.image_records.get_intermediates.return_value = [
- ("img1.png", "intermediate"),
- ("img2.png", "intermediate"),
- ]
+ invoker.services.image_records.get_subfolders.return_value = {
+ "img1.png": "intermediate",
+ "img2.png": "intermediate",
+ }
- count = image_service.delete_intermediates()
+ result = image_service.delete_intermediates_by_names(["img1.png", "img2.png"])
- assert count == 2
+ assert result.deleted_names == ["img1.png", "img2.png"]
invoker.services.image_files.begin_delete.assert_called_once_with(
[("img1.png", "intermediate"), ("img2.png", "intermediate")]
)
- invoker.services.image_records.delete_intermediates_by_names.assert_called_once_with(["img1.png", "img2.png"])
+ invoker.services.image_records.delete_intermediates_by_names.assert_called_once_with(
+ ["img1.png", "img2.png"], guard=None
+ )
invoker.services.image_files.commit_delete.assert_called_once_with(
invoker.services.image_files.begin_delete.return_value, image_names=["img1.png", "img2.png"]
)
@@ -388,7 +390,7 @@ def disk_image_service(tmp_path: Path) -> ImageService:
invoker = MagicMock()
invoker.services.configuration.pil_compress_level = 1
# By default every named intermediate is still an intermediate when the delete runs.
- invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names: list(names)
+ invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names, guard=None: list(names)
storage = DiskImageFileStorage(tmp_path / "outputs")
invoker.services.image_files = storage
storage.start(invoker)
@@ -581,7 +583,7 @@ class TestDeleteTransactional:
class TestDeleteIntermediatesTransactional:
- """delete_intermediates() deletes records first, then purges the files of exactly the rows it
+ """delete_intermediates_by_names() deletes records first, then purges the files of exactly the rows it
removed. It never stages or restores a promoted image's files, so there is no restore step for a
concurrent delete to race (PR #9361, JPPhoto round 2)."""
@@ -591,17 +593,17 @@ class TestDeleteIntermediatesTransactional:
names = ["tmp1.png", "tmp2.png", "tmp3.png"]
for name in names:
_save_image_file(storage, name)
- invoker.services.image_records.get_intermediates.return_value = [(name, "") for name in names]
+ invoker.services.image_records.get_subfolders.return_value = dict.fromkeys(names, "")
deleted_callbacks: list[str] = []
disk_image_service.on_deleted(deleted_callbacks.append)
- count = disk_image_service.delete_intermediates()
+ result = disk_image_service.delete_intermediates_by_names(names)
- assert count == 3
+ assert result.deleted_names == names and result.purge_deferred == []
for name in names:
assert not storage.get_path(name).exists()
assert not storage.get_path(name, thumbnail=True).exists()
- invoker.services.image_records.delete_intermediates_by_names.assert_called_once_with(names)
+ invoker.services.image_records.delete_intermediates_by_names.assert_called_once_with(names, guard=None)
assert deleted_callbacks == names
assert _staging_dirs(storage) == []
@@ -611,21 +613,21 @@ class TestDeleteIntermediatesTransactional:
storage = invoker.services.image_files
for name in ("tmp1.png", "promoted.png", "tmp2.png"):
_save_image_file(storage, name)
- invoker.services.image_records.get_intermediates.return_value = [
- ("tmp1.png", ""),
- ("promoted.png", ""),
- ("tmp2.png", ""),
- ]
+ invoker.services.image_records.get_subfolders.return_value = {
+ "tmp1.png": "",
+ "promoted.png": "",
+ "tmp2.png": "",
+ }
# The store reports it removed everything except promoted.png, so that file is never purged.
- invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names: [
+ invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names, guard=None: [
name for name in names if name != "promoted.png"
]
deleted_callbacks: list[str] = []
disk_image_service.on_deleted(deleted_callbacks.append)
- count = disk_image_service.delete_intermediates()
+ result = disk_image_service.delete_intermediates_by_names(["tmp1.png", "promoted.png", "tmp2.png"])
- assert count == 2
+ assert result.deleted_names == ["tmp1.png", "tmp2.png"]
assert storage.get_path("promoted.png").exists()
assert storage.get_path("promoted.png", thumbnail=True).exists()
for name in ("tmp1.png", "tmp2.png"):
@@ -636,14 +638,16 @@ class TestDeleteIntermediatesTransactional:
def test_only_deleted_rows_are_purged_and_announced(self, image_service: ImageService):
invoker = image_service._ImageService__invoker # type: ignore
- invoker.services.image_records.get_intermediates.return_value = [("tmp1.png", ""), ("promoted.png", "")]
- invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names: ["tmp1.png"]
+ invoker.services.image_records.get_subfolders.return_value = {"tmp1.png": "", "promoted.png": ""}
+ invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names, guard=None: [
+ "tmp1.png"
+ ]
deleted_callbacks: list[str] = []
image_service.on_deleted(deleted_callbacks.append)
- count = image_service.delete_intermediates()
+ result = image_service.delete_intermediates_by_names(["tmp1.png", "promoted.png"])
- assert count == 1
+ assert result.deleted_names == ["tmp1.png"]
# The promoted row's file is never touched: only the deleted row is purged.
invoker.services.image_files.commit_delete.assert_called_once_with(
invoker.services.image_files.begin_delete.return_value, image_names=["tmp1.png"]
@@ -652,9 +656,9 @@ class TestDeleteIntermediatesTransactional:
def test_subfolder_is_forwarded_to_the_file_purge(self, image_service: ImageService):
invoker = image_service._ImageService__invoker # type: ignore
- invoker.services.image_records.get_intermediates.return_value = [("tmp1.png", "a/b")]
- invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names: list(names)
- image_service.delete_intermediates()
+ invoker.services.image_records.get_subfolders.return_value = {"tmp1.png": "a/b"}
+ invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names, guard=None: list(names)
+ image_service.delete_intermediates_by_names(["tmp1.png"])
invoker.services.image_files.begin_delete.assert_called_once_with([("tmp1.png", "a/b")])
@@ -662,15 +666,17 @@ class TestDeleteIntermediatesTransactional:
"""A filesystem failure must not undo the committed record deletions or raise: the records
are already gone, and the journal the purge leaves behind is retried at the next startup."""
invoker = image_service._ImageService__invoker # type: ignore
- invoker.services.image_records.get_intermediates.return_value = [("tmp1.png", ""), ("tmp2.png", "")]
- invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names: list(names)
+ invoker.services.image_records.get_subfolders.return_value = {"tmp1.png": "", "tmp2.png": ""}
+ invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names, guard=None: list(names)
invoker.services.image_files.commit_delete.side_effect = ImageFileDeleteException("purge failed")
deleted_callbacks: list[str] = []
image_service.on_deleted(deleted_callbacks.append)
- count = image_service.delete_intermediates()
+ result = image_service.delete_intermediates_by_names(["tmp1.png", "tmp2.png"])
- assert count == 2
+ assert result.deleted_names == ["tmp1.png", "tmp2.png"]
+ # The purge failure is reported, not raised: the caller counts these as pending disk cleanup.
+ assert result.purge_deferred == ["tmp1.png", "tmp2.png"]
# Both records were deleted, so both deletions are announced despite the file failure.
assert deleted_callbacks == ["tmp1.png", "tmp2.png"]
invoker.services.image_files.abandon_delete.assert_not_called()
@@ -678,13 +684,13 @@ class TestDeleteIntermediatesTransactional:
def test_db_failure_raises_and_purges_nothing(self, image_service: ImageService):
invoker = image_service._ImageService__invoker # type: ignore
- invoker.services.image_records.get_intermediates.return_value = [("tmp1.png", ""), ("tmp2.png", "")]
+ invoker.services.image_records.get_subfolders.return_value = {"tmp1.png": "", "tmp2.png": ""}
invoker.services.image_records.delete_intermediates_by_names.side_effect = ImageRecordDeleteException()
deleted_callbacks: list[str] = []
image_service.on_deleted(deleted_callbacks.append)
with pytest.raises(ImageRecordDeleteException):
- image_service.delete_intermediates()
+ image_service.delete_intermediates_by_names(["tmp1.png", "tmp2.png"])
# No record was removed, so no file may be purged and the journal must be discarded.
invoker.services.image_files.commit_delete.assert_not_called()
@@ -695,12 +701,12 @@ class TestDeleteIntermediatesTransactional:
def test_nothing_deleted_returns_zero_and_fires_no_callbacks(self, image_service: ImageService):
invoker = image_service._ImageService__invoker # type: ignore
- invoker.services.image_records.get_intermediates.return_value = [("promoted.png", "")]
- invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names: []
+ invoker.services.image_records.get_subfolders.return_value = {"promoted.png": ""}
+ invoker.services.image_records.delete_intermediates_by_names.side_effect = lambda names, guard=None: []
deleted_callbacks: list[str] = []
image_service.on_deleted(deleted_callbacks.append)
- assert image_service.delete_intermediates() == 0
+ assert image_service.delete_intermediates_by_names(["promoted.png"]).deleted_names == []
# The journal still lists the promoted image; the purge selects nothing.
invoker.services.image_files.commit_delete.assert_called_once_with(
@@ -710,11 +716,11 @@ class TestDeleteIntermediatesTransactional:
def test_empty_intermediates_is_a_noop(self, image_service: ImageService):
invoker = image_service._ImageService__invoker # type: ignore
- invoker.services.image_records.get_intermediates.return_value = []
+ invoker.services.image_records.get_subfolders.return_value = {}
deleted_callbacks: list[str] = []
image_service.on_deleted(deleted_callbacks.append)
- assert image_service.delete_intermediates() == 0
+ assert image_service.delete_intermediates_by_names(["gone.png"]).deleted_names == []
# Nothing to delete: no journal is written and the record store is never asked to delete.
invoker.services.image_records.delete_intermediates_by_names.assert_not_called()
@@ -723,7 +729,7 @@ class TestDeleteIntermediatesTransactional:
class TestDeleteIntermediatesAgainstRealRecords:
- """delete_intermediates() wired to a real record store, so no stub stands in for the DB decision.
+ """delete_intermediates_by_names() wired to a real record store, so no stub stands in for the DB decision.
The mocked tests above can only assert that the service honours whatever the store reports. These
exercise the real store, which is where the promoted-vs-already-gone distinction is actually made,
@@ -746,14 +752,14 @@ class TestDeleteIntermediatesAgainstRealRecords:
image that is in the snapshot yet is no longer an intermediate by the time the conditional
DELETE runs, so its record (and files) must survive.
"""
- real_get_intermediates = records.get_intermediates
+ real_get_subfolders = records.get_subfolders
- def snapshot_then_promote():
- pairs = real_get_intermediates()
+ def snapshot_then_promote(names: list[str]) -> dict[str, str]:
+ subfolders = real_get_subfolders(names)
records.update(image_name, ImageRecordChanges(is_intermediate=False))
- return pairs
+ return subfolders
- monkeypatch.setattr(records, "get_intermediates", snapshot_then_promote)
+ monkeypatch.setattr(records, "get_subfolders", snapshot_then_promote)
def test_all_intermediates_are_deleted(self, wired) -> None:
svc, records, storage = wired
@@ -762,7 +768,7 @@ class TestDeleteIntermediatesAgainstRealRecords:
deleted_callbacks: list[str] = []
svc.on_deleted(deleted_callbacks.append)
- assert svc.delete_intermediates() == 2
+ assert svc.delete_intermediates_by_names(["tmp1.png", "tmp2.png"]).deleted_names == ["tmp1.png", "tmp2.png"]
for name in ("tmp1.png", "tmp2.png"):
assert not storage.get_path(name).exists()
@@ -779,7 +785,7 @@ class TestDeleteIntermediatesAgainstRealRecords:
deleted_callbacks: list[str] = []
svc.on_deleted(deleted_callbacks.append)
- assert svc.delete_intermediates() == 1
+ assert svc.delete_intermediates_by_names(["tmp1.png", "promoted.png"]).deleted_names == ["tmp1.png"]
assert storage.get_path("promoted.png").exists()
assert records.get("promoted.png").is_intermediate is False
@@ -794,22 +800,22 @@ class TestDeleteIntermediatesAgainstRealRecords:
self._seed(records, storage, "tmp1.png")
self._seed(records, storage, "gone.png")
- real_get_intermediates = records.get_intermediates
+ real_get_subfolders = records.get_subfolders
- def snapshot_then_delete_gone():
- pairs = real_get_intermediates()
+ def snapshot_then_delete_gone(names: list[str]) -> dict[str, str]:
+ subfolders = real_get_subfolders(names)
# A single-image delete elsewhere removes gone.png (record and files) after our snapshot.
records.delete("gone.png")
storage.delete("gone.png")
- return pairs
+ return subfolders
- monkeypatch.setattr(records, "get_intermediates", snapshot_then_delete_gone)
+ monkeypatch.setattr(records, "get_subfolders", snapshot_then_delete_gone)
deleted_callbacks: list[str] = []
svc.on_deleted(deleted_callbacks.append)
- count = svc.delete_intermediates()
+ result = svc.delete_intermediates_by_names(["tmp1.png", "gone.png"])
- assert count == 1
+ assert result.deleted_names == ["tmp1.png"]
assert deleted_callbacks == ["tmp1.png"]
assert not storage.get_path("tmp1.png").exists()
# gone.png was purged by the other path; we neither resurrect nor re-report it.
@@ -828,8 +834,8 @@ class TestDeleteIntermediatesAgainstRealRecords:
real_delete_by_names = records.delete_intermediates_by_names
- def delete_then_lose_the_promoted_record(names: list[str]):
- deleted = real_delete_by_names(names)
+ def delete_then_lose_the_promoted_record(names: list[str], guard=None):
+ deleted = real_delete_by_names(names, guard=guard)
# A concurrent single-image delete removes the promoted image entirely, right after the
# conditional DELETE chose to keep it.
records.delete("promoted.png")
@@ -840,9 +846,9 @@ class TestDeleteIntermediatesAgainstRealRecords:
deleted_callbacks: list[str] = []
svc.on_deleted(deleted_callbacks.append)
- count = svc.delete_intermediates()
+ result = svc.delete_intermediates_by_names(["tmp1.png", "promoted.png"])
- assert count == 1
+ assert result.deleted_names == ["tmp1.png"]
assert deleted_callbacks == ["tmp1.png"]
assert not storage.get_path("tmp1.png").exists()
# promoted.png's files stay deleted — never resurrected into an orphan.
@@ -922,10 +928,11 @@ class TestDeleteJournalSurvivesFailedPurges:
svc.on_deleted(deleted_callbacks.append)
with patch.object(Path, "unlink", _unlink_always_fails):
- count = svc.delete_intermediates()
+ result = svc.delete_intermediates_by_names(["tmp1.png", "tmp2.png"])
# The records are committed as gone, so the deletion succeeded and is announced...
- assert count == 2
+ assert result.deleted_names == ["tmp1.png", "tmp2.png"]
+ assert result.purge_deferred == ["tmp1.png", "tmp2.png"]
assert sorted(deleted_callbacks) == ["tmp1.png", "tmp2.png"]
for name in ("tmp1.png", "tmp2.png"):
with pytest.raises(ImageRecordNotFoundException):
@@ -1145,7 +1152,7 @@ class TestDeleteVersusSubfolderMove:
wired_with_move_service: tuple[ImageService, SqliteImageRecordStorage, DiskImageFileStorage, ImageMoveService],
monkeypatch,
) -> None:
- """While delete_intermediates() runs its unit, a concurrent move_all_images() must wait.
+ """While delete_intermediates_by_names() runs its unit, a concurrent move_all_images() must wait.
Without the lock the move relocates the image mid-delete and the delete's purge sweeps
the abandoned path: the files survive at the new subfolder with no record and no journal.
@@ -1158,14 +1165,14 @@ class TestDeleteVersusSubfolderMove:
delete_may_finish = threading.Event()
real_delete_by_names = records.delete_intermediates_by_names
- def delete_after_pause(names: list[str]) -> list[str]:
+ def delete_after_pause(names: list[str], guard=None) -> list[str]:
delete_started.set()
assert delete_may_finish.wait(timeout=10), "the move never let the delete finish"
- return real_delete_by_names(names)
+ return real_delete_by_names(names, guard=guard)
monkeypatch.setattr(records, "delete_intermediates_by_names", delete_after_pause)
- delete_thread = threading.Thread(target=svc.delete_intermediates)
+ delete_thread = threading.Thread(target=lambda: svc.delete_intermediates_by_names(["raced.png"]))
delete_thread.start()
assert delete_started.wait(timeout=10), "the delete never reached its record deletion"
@@ -1341,3 +1348,62 @@ class TestDeleteVersusSubfolderMove:
assert not storage.get_path("raced.png", image_subfolder="old").exists()
assert storage.get_path("raced.png", thumbnail=True).exists()
assert _staging_dirs(storage) == []
+
+
+class TestStorageAccounting:
+ """Every write measures the files it produced so cleanup can report reclaimable space."""
+
+ def test_create_records_the_project_and_the_size_of_image_and_thumbnail(self, wired) -> None:
+ svc, records, storage = wired
+ invoker = svc._ImageService__invoker # type: ignore
+ invoker.services.names.create_image_name.return_value = "made.png"
+ invoker.services.urls.get_image_url.return_value = "/made.png"
+ invoker.services.board_image_records.get_board_for_image.return_value = None
+ invoker.services.configuration.image_subfolder_strategy = "flat"
+
+ dto = svc.create(
+ image=Image.new("RGB", (64, 64)),
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ is_intermediate=True,
+ project_id="project-1",
+ )
+
+ expected = (
+ storage.get_path("made.png").stat().st_size + storage.get_path("made.png", thumbnail=True).stat().st_size
+ )
+ assert dto.project_id == "project-1"
+ assert dto.file_size_bytes == expected
+ assert records.get("made.png").file_size_bytes == expected
+
+ def test_copy_measures_the_new_files(self, wired) -> None:
+ svc, records, storage = wired
+ invoker = svc._ImageService__invoker # type: ignore
+ invoker.services.names.create_image_name.return_value = "copy.png"
+ invoker.services.urls.get_image_url.return_value = "/copy.png"
+ invoker.services.board_image_records.get_board_for_image.return_value = None
+ invoker.services.configuration.image_subfolder_strategy = "flat"
+ _seed_record(records, "source.png", is_intermediate=False)
+ _save_image_file(storage, "source.png")
+
+ dto = svc.copy("source.png")
+
+ assert dto.file_size_bytes == (
+ storage.get_path("copy.png").stat().st_size + storage.get_path("copy.png", thumbnail=True).stat().st_size
+ )
+
+ def test_a_failed_measurement_leaves_the_size_unknown_and_the_image_intact(self, wired, monkeypatch) -> None:
+ svc, records, storage = wired
+ invoker = svc._ImageService__invoker # type: ignore
+ invoker.services.names.create_image_name.return_value = "made.png"
+ invoker.services.urls.get_image_url.return_value = "/made.png"
+ invoker.services.board_image_records.get_board_for_image.return_value = None
+ invoker.services.configuration.image_subfolder_strategy = "flat"
+ monkeypatch.setattr(storage, "get_file_size_bytes", MagicMock(side_effect=OSError("stat failed")))
+
+ dto = svc.create(
+ image=Image.new("RGB", (64, 64)), image_origin=ResourceOrigin.INTERNAL, image_category=ImageCategory.GENERAL
+ )
+
+ assert dto.file_size_bytes is None
+ assert storage.get_path("made.png").exists()
diff --git a/tests/app/services/intermediates/__init__.py b/tests/app/services/intermediates/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.py
new file mode 100644
index 0000000000..ecdcc1a1f6
--- /dev/null
+++ b/tests/app/services/intermediates/test_intermediates_service.py
@@ -0,0 +1,939 @@
+"""The intermediates cleanup engine against a real database, real files and the real queue tables.
+
+Every test drives the public service interface; the eligibility policy is exercised through the
+same SQL that production runs, never through a stub that decides what is safe.
+"""
+
+import time
+import uuid
+from pathlib import Path
+from typing import Optional
+from unittest.mock import MagicMock
+
+import pytest
+from PIL import Image
+
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
+from invokeai.app.services.image_records.image_records_common import (
+ ImageCategory,
+ ImageRecordChanges,
+ ImageRecordNotFoundException,
+ ResourceOrigin,
+)
+from invokeai.app.services.intermediates import intermediates_default
+from invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller
+from invokeai.app.services.intermediates.intermediates_common import (
+ IntermediatesIdempotencyConflictError,
+ IntermediatesOperation,
+ IntermediatesOperationNotFoundError,
+ IntermediatesOperationRequest,
+ IntermediatesPreviewNotFoundError,
+ IntermediatesPreviewRequest,
+ IntermediatesScope,
+ IntermediatesScopeForbiddenError,
+ IntermediatesScopeTarget,
+ IntermediatesUnavailableError,
+)
+from invokeai.app.services.intermediates.intermediates_default import IntermediatesService
+from invokeai.app.services.intermediates.intermediates_records_sqlite import IntermediatesRecordsSqlite
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue
+from invokeai.app.services.video_files.video_files_disk import DiskVideoFileStorage
+from invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundException
+from invokeai.app.services.videos.videos_default import VideoService
+
+ADMIN = IntermediatesCaller(user_id="admin", is_admin=True)
+ALICE = IntermediatesCaller(user_id="alice", is_admin=False)
+BOB = IntermediatesCaller(user_id="bob", is_admin=False)
+
+
+def invoker(mock_invoker: Invoker, tmp_path: Path) -> Invoker:
+ """The shared mock invoker with real image/video file storage and a real queue table."""
+ services = mock_invoker.services
+ services.image_files = DiskImageFileStorage(tmp_path / "outputs")
+ services.image_files.start(mock_invoker)
+ services.video_files = DiskVideoFileStorage(str(tmp_path / "outputs" / "videos"))
+ services.videos = VideoService()
+ services.videos.start(mock_invoker)
+ services.session_queue = SqliteSessionQueue(db=services.image_records._db)
+ services.image_moves = None
+ # These are multi-account scenarios; the single-user case is covered explicitly below.
+ services.configuration.multiuser = True
+ with services.image_records._db.transaction() as cursor:
+ cursor.executemany(
+ "INSERT INTO users (user_id, email, display_name, password_hash, is_admin, is_active)"
+ " VALUES (?, ?, ?, 'x', ?, 1);",
+ [
+ ("admin", "[email protected]", "Admin", 1),
+ ("alice", "[email protected]", "Alice", 0),
+ ("bob", "[email protected]", "Bob", 0),
+ ],
+ )
+ return mock_invoker
+
+
+def service(invoker: Invoker) -> IntermediatesService:
+ svc = IntermediatesService(records=IntermediatesRecordsSqlite(db=invoker.services.image_records._db))
+ invoker.services.intermediates = svc
+ svc.start(invoker)
+ yield svc
+ svc.stop()
+
+
+def _seed_image(
+ invoker: Invoker,
+ name: str,
+ *,
+ user_id: str = "alice",
+ project_id: Optional[str] = None,
+ session_id: Optional[str] = None,
+ is_intermediate: bool = True,
+ created_at: Optional[str] = "2020-01-01 00:00:00.000",
+ with_file: bool = True,
+ size: Optional[int] = None,
+) -> None:
+ records = invoker.services.image_records
+ records.save(
+ image_name=name,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=8,
+ height=8,
+ has_workflow=False,
+ is_intermediate=is_intermediate,
+ session_id=session_id,
+ user_id=user_id,
+ project_id=project_id,
+ )
+ if created_at is not None:
+ with records._db.transaction() as cursor:
+ cursor.execute("UPDATE images SET created_at = ? WHERE image_name = ?;", (created_at, name))
+ if with_file:
+ invoker.services.image_files.save(image=Image.new("RGB", (8, 8)), image_name=name)
+ measured = invoker.services.image_files.get_file_size_bytes(name)
+ records.set_file_size_bytes(name, size if size is not None else measured)
+
+
+def _seed_video(invoker: Invoker, name: str, *, user_id: str = "alice", is_intermediate: bool = True) -> None:
+ records = invoker.services.video_records
+ records.save(
+ video_name=name,
+ video_origin=ResourceOrigin.INTERNAL,
+ video_category=ImageCategory.GENERAL,
+ width=8,
+ height=8,
+ duration=1.0,
+ fps=8.0,
+ has_workflow=False,
+ is_intermediate=is_intermediate,
+ user_id=user_id,
+ )
+ with records._db.transaction() as cursor:
+ cursor.execute("UPDATE videos SET created_at = '2020-01-01 00:00:00.000' WHERE video_name = ?;", (name,))
+ files = invoker.services.video_files
+ path = files.get_path(name)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"\x00" * 64)
+ records.set_file_size_bytes(name, 64)
+
+
+def _enqueue_row(
+ invoker: Invoker, *, session_id: str, status: str, user_id: str = "alice", session_json: str = "{}"
+) -> int:
+ with invoker.services.image_records._db.transaction() as cursor:
+ cursor.execute(
+ "INSERT INTO session_queue (queue_id, session, session_id, batch_id, priority, user_id, status)"
+ " VALUES ('default', ?, ?, ?, 0, ?, ?);",
+ (session_json, session_id, uuid.uuid4().hex, user_id, status),
+ )
+ return int(cursor.lastrowid or 0)
+
+
+def _project(invoker: Invoker, user_id: str, name: str, data: dict) -> str:
+ return invoker.services.project_records.create(user_id, name, data).project_id
+
+
+def _wait(
+ service: IntermediatesService, operation_id: str, caller: IntermediatesCaller = ALICE
+) -> IntermediatesOperation:
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ operation = service.get_operation(operation_id, caller)
+ if operation.status in ("completed", "failed"):
+ return operation
+ time.sleep(0.02)
+ raise AssertionError("operation did not finish")
+
+
+def _run(service: IntermediatesService, caller: IntermediatesCaller, scope: IntermediatesScope, mode: str = "safe"):
+ preview = service.create_preview(IntermediatesPreviewRequest(mode=mode, scope=scope), caller)
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key=uuid.uuid4().hex), caller
+ )
+ return preview, _wait(service, started.operation_id, caller)
+
+
+def _owner(user_id: str) -> IntermediatesScope:
+ return IntermediatesScope(kind="owner", user_id=user_id)
+
+
+def _exists(invoker: Invoker, name: str) -> bool:
+ try:
+ invoker.services.image_records.get(name)
+ return True
+ except ImageRecordNotFoundException:
+ return False
+
+
+# ── summary ──
+
+
+def test_summary_groups_rows_and_classifies_under_the_policy(invoker: Invoker, service: IntermediatesService) -> None:
+ project = _project(
+ invoker, "alice", "Portraits", {"canvas": {"stagingArea": {"pendingImages": [{"imageName": "staged.png"}]}}}
+ )
+ _seed_image(invoker, "safe.png", project_id=project, size=100)
+ _seed_image(invoker, "staged.png", project_id=project, size=50)
+ _seed_image(invoker, "active-output.png", project_id=project, session_id="s-active")
+ _seed_image(invoker, "active-input.png", size=30)
+ _seed_image(invoker, "fresh.png", created_at=None)
+ _seed_image(invoker, "unmeasured.png", project_id=project, size=None)
+ invoker.services.image_records.set_file_size_bytes("unmeasured.png", None)
+ _seed_image(invoker, "deleted-project.png", project_id="gone", size=7)
+ _seed_image(invoker, "durable.png", project_id=project, is_intermediate=False)
+ invoker.services.board_image_records.add_image_to_board(
+ invoker.services.project_records.get_board_id("alice", project), "durable.png"
+ )
+ _seed_image(invoker, "bobs.png", user_id="bob", size=9)
+ _enqueue_row(invoker, session_id="s-active", status="in_progress")
+ _enqueue_row(
+ invoker,
+ session_id="s-pending",
+ status="pending",
+ session_json='{"graph": {"nodes": {"a": {"image": {"image_name": "active-input.png"}}}}}',
+ )
+ _enqueue_row(invoker, session_id="s-done", status="completed", session_json='{"image_name": "safe.png"}')
+
+ summary = service.get_summary(
+ ALICE, owner_id=None, search=None, sort="reclaimable_bytes", descending=True, offset=0, limit=50
+ )
+
+ rows = {(row.project_id, row.project_name): row for row in summary.items}
+ assert set(rows) == {(project, "Portraits"), (None, None)}
+ portraits = rows[(project, "Portraits")]
+ assert (portraits.images.safe, portraits.images.referenced, portraits.images.active, portraits.images.recent) == (
+ 2,
+ 1,
+ 1,
+ 0,
+ )
+ # The board's newest durable image is the row's thumbnail; intermediates never are.
+ assert portraits.cover_image_name == "durable.png"
+ assert portraits.reclaimable_bytes == 100
+ assert portraits.referenced_bytes == 50
+ assert portraits.unknown_size_count == 1
+ unassigned = rows[(None, None)]
+ assert (unassigned.images.safe, unassigned.images.active, unassigned.images.recent) == (1, 1, 1)
+ assert unassigned.reclaimable_bytes == 7
+ assert summary.totals.safe_images == 3
+ assert summary.totals.in_use_images == 4
+ assert summary.totals.reclaimable_bytes == 107
+ assert summary.can_manage_everyone is False
+ assert all(row.user_id == "alice" for row in summary.items)
+
+
+def test_summary_scopes_owners_search_sort_and_pages(invoker: Invoker, service: IntermediatesService) -> None:
+ alpha = _project(invoker, "alice", "Alpha", {})
+ beta = _project(invoker, "alice", "Beta", {})
+ _seed_image(invoker, "a.png", project_id=alpha, size=10)
+ _seed_image(invoker, "b.png", project_id=beta, size=20)
+ _seed_image(invoker, "bob.png", user_id="bob", size=30)
+
+ everyone = service.get_summary(
+ ADMIN, owner_id=None, search=None, sort="reclaimable_bytes", descending=True, offset=0, limit=50
+ )
+ assert [(row.user_id, row.project_name) for row in everyone.items] == [
+ ("bob", None),
+ ("alice", "Beta"),
+ ("alice", "Alpha"),
+ ]
+ assert everyone.items[0].user_display_name == "Bob"
+ assert everyone.can_manage_everyone is True
+
+ by_name = service.get_summary(
+ ADMIN, owner_id="alice", search=None, sort="project_name", descending=False, offset=1, limit=1
+ )
+ assert [row.project_name for row in by_name.items] == ["Beta"]
+ assert by_name.total == 2 and by_name.totals.reclaimable_bytes == 30
+
+ searched = service.get_summary(
+ ADMIN, owner_id=None, search="bo", sort="project_name", descending=False, offset=0, limit=50
+ )
+ assert [row.user_id for row in searched.items] == ["bob"]
+ # Owner names are not searchable for a non-admin, whose rows are all their own anyway.
+ assert (
+ service.get_summary(
+ ALICE, owner_id=None, search="alice", sort="project_name", descending=False, offset=0, limit=50
+ ).items
+ == []
+ )
+
+ with pytest.raises(IntermediatesScopeForbiddenError):
+ service.get_summary(
+ ALICE, owner_id="bob", search=None, sort="project_name", descending=False, offset=0, limit=50
+ )
+
+
+def test_summary_triggers_measurement_of_unmeasured_sizes(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_image(invoker, "later.png", size=None)
+ invoker.services.image_records.set_file_size_bytes("later.png", None)
+ _seed_image(invoker, "missing.png", with_file=False)
+
+ first = service.get_summary(
+ ALICE, owner_id=None, search=None, sort="project_name", descending=False, offset=0, limit=50
+ )
+ assert first.measuring is True
+
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ if not service._records.has_unmeasured_intermediates():
+ break
+ time.sleep(0.02)
+ expected = invoker.services.image_files.get_file_size_bytes("later.png")
+ assert invoker.services.image_records.get("later.png").file_size_bytes == expected
+ # A missing file measures as nothing on disk, not as unknown.
+ assert invoker.services.image_records.get("missing.png").file_size_bytes == 0
+
+
+# ── previews and policy ──
+
+
+def test_safe_cleanup_deletes_only_safe_items_and_reports_what_it_kept(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ project = _project(invoker, "alice", "P", {"layers": [{"imageName": "referenced.png"}]})
+ _seed_image(invoker, "safe.png", project_id=project, size=100)
+ _seed_image(invoker, "referenced.png", project_id=project)
+ _seed_image(invoker, "active.png", project_id=project, session_id="s1")
+ _seed_image(invoker, "fresh.png", project_id=project, created_at=None)
+ _seed_video(invoker, "safe.mp4")
+ _enqueue_row(invoker, session_id="s1", status="pending")
+ deleted_callbacks: list[str] = []
+ invoker.services.images.on_deleted(deleted_callbacks.append)
+
+ preview, operation = _run(service, ALICE, _owner("alice"))
+
+ assert (preview.impact.delete_images, preview.impact.delete_videos) == (1, 1)
+ assert (
+ preview.impact.keep_referenced_images,
+ preview.impact.keep_active_images,
+ preview.impact.keep_recent_images,
+ ) == (1, 1, 1)
+ assert preview.impact.reclaimable_bytes == 164
+ assert preview.affected_documents == []
+ assert operation.status == "completed"
+ assert (operation.progress.deleted_images, operation.progress.deleted_videos) == (1, 1)
+ assert operation.progress.reclaimed_bytes == 164
+ assert not _exists(invoker, "safe.png")
+ assert not invoker.services.image_files.get_path("safe.png").exists()
+ assert not invoker.services.video_files.get_path("safe.mp4").exists()
+ with pytest.raises(VideoRecordNotFoundException):
+ invoker.services.video_records.get("safe.mp4")
+ assert all(_exists(invoker, name) for name in ("referenced.png", "active.png", "fresh.png"))
+ assert deleted_callbacks == ["safe.png"]
+ assert list(invoker.services.image_files.image_root.glob(".delete_*")) == []
+
+
+def test_force_cleanup_deletes_referenced_items_but_never_active_or_recent(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ project = _project(invoker, "alice", "Drafts", {"stagingArea": {"pendingImages": [{"imageName": "staged.png"}]}})
+ workflow = invoker.services.workflow_records.create(_workflow_naming("staged.png"), user_id="bob")
+ _seed_image(invoker, "staged.png", project_id=project, size=40)
+ _seed_image(invoker, "active.png", project_id=project, session_id="s1")
+ _seed_image(invoker, "fresh.png", project_id=project, created_at=None)
+ _enqueue_row(invoker, session_id="s1", status="waiting")
+
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)
+ assert preview.impact.delete_images == 1
+ assert (preview.impact.keep_active_images, preview.impact.keep_recent_images) == (1, 1)
+ # Alice sees her own project; Bob's workflow is counted but not described.
+ assert [(doc.kind, doc.name, doc.references) for doc in preview.affected_documents] == [("project", "Drafts", 1)]
+ assert preview.affected_documents_hidden == 1
+
+ admin_preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ADMIN)
+ assert {(doc.kind, doc.owner_id) for doc in admin_preview.affected_documents} == {
+ ("project", project),
+ ("workflow", workflow.workflow_id),
+ }
+ assert admin_preview.affected_documents_hidden == 0
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ operation = _wait(service, started.operation_id)
+ assert operation.status == "completed"
+ assert not _exists(invoker, "staged.png")
+ assert _exists(invoker, "active.png") and _exists(invoker, "fresh.png")
+
+
+def _workflow_naming(image_name: str):
+ from invokeai.app.services.workflow_records.workflow_records_common import (
+ WorkflowCategory,
+ WorkflowMeta,
+ WorkflowWithoutID,
+ )
+
+ return WorkflowWithoutID(
+ name="W",
+ author="",
+ description="",
+ version="1.0.0",
+ contact="",
+ tags="",
+ notes="",
+ exposedFields=[],
+ meta=WorkflowMeta(version="3.0.0", category=WorkflowCategory.User),
+ nodes=[{"id": "n", "data": {"image": {"image_name": image_name}}}],
+ edges=[],
+ )
+
+
+def test_selection_scope_targets_exactly_the_chosen_rows(invoker: Invoker, service: IntermediatesService) -> None:
+ keep = _project(invoker, "alice", "Keep", {})
+ clear = _project(invoker, "alice", "Clear", {})
+ _seed_image(invoker, "keep.png", project_id=keep)
+ _seed_image(invoker, "clear.png", project_id=clear)
+ _seed_image(invoker, "unassigned.png")
+ _seed_image(invoker, "orphaned-project.png", project_id="gone")
+
+ scope = IntermediatesScope(
+ kind="selection",
+ targets=[
+ IntermediatesScopeTarget(user_id="alice", project_id=clear),
+ IntermediatesScopeTarget(user_id="alice", project_id=None),
+ IntermediatesScopeTarget(user_id="alice", project_id=None),
+ ],
+ )
+ preview, operation = _run(service, ALICE, scope)
+
+ assert preview.target_rows == 2
+ assert preview.impact.delete_images == 3
+ assert operation.progress.deleted_images == 3
+ assert _exists(invoker, "keep.png")
+ assert not any(_exists(invoker, n) for n in ("clear.png", "unassigned.png", "orphaned-project.png"))
+
+
+def test_a_preview_freezes_its_targets(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_image(invoker, "before.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ _seed_image(invoker, "after.png")
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ operation = _wait(service, started.operation_id)
+
+ assert operation.target_images == 1
+ assert not _exists(invoker, "before.png")
+ assert _exists(invoker, "after.png")
+
+
+def test_the_final_check_keeps_targets_protected_after_the_preview(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ project = _project(invoker, "alice", "P", {})
+ _seed_image(invoker, "promoted.png", project_id=project)
+ _seed_image(invoker, "now-referenced.png", project_id=project)
+ _seed_image(invoker, "now-active.png", project_id=project, session_id="s-late")
+ _seed_image(invoker, "still-safe.png", project_id=project)
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ assert preview.impact.delete_images == 4
+
+ invoker.services.image_records.update("promoted.png", ImageRecordChanges(is_intermediate=False))
+ invoker.services.project_records.update(
+ "alice", project, expected_revision=1, name="P", data={"imageName": "now-referenced.png"}
+ )
+ _enqueue_row(invoker, session_id="s-late", status="pending")
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ operation = _wait(service, started.operation_id)
+
+ assert operation.progress.deleted_images == 1
+ assert operation.progress.retained_images == 3
+ assert all(_exists(invoker, n) for n in ("promoted.png", "now-referenced.png", "now-active.png"))
+ assert not _exists(invoker, "still-safe.png")
+ assert invoker.services.image_files.get_path("promoted.png").exists()
+
+
+def test_a_promoted_video_keeps_its_file(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_video(invoker, "promoted.mp4")
+ _seed_video(invoker, "gone.mp4")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ from invokeai.app.services.video_records.video_records_common import VideoRecordChanges
+
+ invoker.services.video_records.update("promoted.mp4", VideoRecordChanges(is_intermediate=False))
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ operation = _wait(service, started.operation_id)
+
+ assert (operation.progress.deleted_videos, operation.progress.retained_videos) == (1, 1)
+ assert invoker.services.video_files.get_path("promoted.mp4").exists()
+ assert not invoker.services.video_files.get_path("gone.mp4").exists()
+ assert list(Path(invoker.services.video_files.get_path("gone.mp4")).parent.glob(".delete_*")) == []
+
+
+# ── authorization ──
+
+
+def test_non_admins_are_confined_to_their_own_account(invoker: Invoker, service: IntermediatesService) -> None:
+ with pytest.raises(IntermediatesScopeForbiddenError):
+ service.create_preview(
+ IntermediatesPreviewRequest(mode="safe", scope=IntermediatesScope(kind="everyone")), ALICE
+ )
+ with pytest.raises(IntermediatesScopeForbiddenError):
+ service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), ALICE)
+ with pytest.raises(IntermediatesScopeForbiddenError):
+ service.create_preview(
+ IntermediatesPreviewRequest(
+ mode="safe",
+ scope=IntermediatesScope(
+ kind="selection",
+ targets=[IntermediatesScopeTarget(user_id="alice"), IntermediatesScopeTarget(user_id="bob")],
+ ),
+ ),
+ ALICE,
+ )
+
+
+def test_admins_can_clear_everyone_and_a_chosen_account(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_image(invoker, "alice.png", user_id="alice")
+ _seed_image(invoker, "bob.png", user_id="bob")
+ _seed_image(invoker, "admin.png", user_id="admin")
+
+ _, first = _run(service, ADMIN, _owner("bob"))
+ assert first.progress.deleted_images == 1 and _exists(invoker, "alice.png")
+
+ _, second = _run(service, ADMIN, IntermediatesScope(kind="everyone"))
+ assert second.progress.deleted_images == 2
+ assert not any(_exists(invoker, n) for n in ("alice.png", "bob.png", "admin.png"))
+
+
+def test_a_demoted_admin_stops_at_the_next_batch(invoker: Invoker, service: IntermediatesService, monkeypatch) -> None:
+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)
+ for index in range(3):
+ _seed_image(invoker, f"bob-{index}.png", user_id="bob")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), ADMIN)
+ real_get = invoker.services.users.get
+ calls = {"n": 0}
+
+ def demote_after_first_batch(user_id: str):
+ user = real_get(user_id)
+ calls["n"] += 1
+ if user is not None and user_id == "admin" and calls["n"] > 1:
+ return user.model_copy(update={"is_admin": False})
+ return user
+
+ monkeypatch.setattr(invoker.services.users, "get", demote_after_first_batch)
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ADMIN
+ )
+ operation = _wait(service, started.operation_id, ADMIN)
+
+ assert operation.status == "failed"
+ assert "no longer administers" in (operation.error or "")
+ assert operation.progress.deleted_images == 1
+ assert sum(_exists(invoker, f"bob-{i}.png") for i in range(3)) == 2
+
+
+# ── operations: idempotency, retry, availability ──
+
+
+def test_operations_are_idempotent_single_use_and_private(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_image(invoker, "a.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ other = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+
+ with pytest.raises(IntermediatesPreviewNotFoundError):
+ service.start_operation(IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), BOB)
+
+ first = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ again = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ assert again.operation_id == first.operation_id
+
+ with pytest.raises(IntermediatesIdempotencyConflictError):
+ service.start_operation(IntermediatesOperationRequest(preview_id=other.preview_id, idempotency_key="k"), ALICE)
+ with pytest.raises(IntermediatesPreviewNotFoundError):
+ service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k2"), ALICE
+ )
+
+ _wait(service, first.operation_id)
+ with pytest.raises(IntermediatesOperationNotFoundError):
+ service.get_operation(first.operation_id, BOB)
+ assert service.get_operation(first.operation_id, ADMIN).status == "completed"
+
+
+def test_a_failed_batch_is_reported_and_retried_without_widening(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)
+ _seed_image(invoker, "ok.png")
+ _seed_image(invoker, "flaky.png")
+ real_delete = invoker.services.images.delete_intermediates_by_names
+
+ def fail_flaky_once(names, guard=None):
+ if "flaky.png" in names and not getattr(fail_flaky_once, "failed", False):
+ fail_flaky_once.failed = True # type: ignore[attr-defined]
+ raise OSError("disk hiccup")
+ return real_delete(names, guard)
+
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", fail_flaky_once)
+
+ _, operation = _run(service, ALICE, _owner("alice"))
+ assert operation.status == "completed"
+ assert (operation.progress.deleted_images, operation.progress.failed_images) == (1, 1)
+ assert _exists(invoker, "flaky.png")
+
+ _seed_image(invoker, "new-since.png")
+ retry = service.retry_operation(operation.operation_id, ALICE)
+ retried = _wait(service, retry.operation_id)
+ assert retried.retried_from_operation_id == operation.operation_id
+ assert retried.target_images == 1
+ assert retried.progress.deleted_images == 1
+ assert not _exists(invoker, "flaky.png")
+ assert _exists(invoker, "new-since.png")
+ with pytest.raises(IntermediatesUnavailableError):
+ service.retry_operation(retried.operation_id, ALICE)
+
+
+def test_a_purge_failure_counts_as_pending_disk_cleanup_not_reclaimed(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ _seed_image(invoker, "stuck.png", size=500)
+ monkeypatch.setattr(invoker.services.image_files, "commit_delete", MagicMock(side_effect=OSError("busy")))
+
+ _, operation = _run(service, ALICE, _owner("alice"))
+
+ assert operation.status == "completed"
+ assert operation.progress.deleted_images == 1
+ assert operation.progress.reclaimed_bytes == 0
+ assert operation.progress.pending_disk_cleanup == 1
+ assert not _exists(invoker, "stuck.png")
+ # The journal survives for the next startup to finish the purge.
+ assert len(list(invoker.services.image_files.image_root.glob(".delete_*"))) == 1
+
+
+def test_cleanup_refuses_to_start_or_continue_during_storage_maintenance(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)
+ _seed_image(invoker, "one.png")
+ _seed_image(invoker, "two.png")
+ moves = MagicMock()
+ moves.is_maintenance_active.return_value = True
+ invoker.services.image_moves = moves
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ with pytest.raises(IntermediatesUnavailableError):
+ service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+
+ invoker.services.image_moves = None
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ # Halt after the first batch: the second sees maintenance and stops with the rest unresolved.
+ real_delete = invoker.services.images.delete_intermediates_by_names
+
+ def delete_then_start_maintenance(names, guard=None):
+ result = real_delete(names, guard)
+ invoker.services.image_moves = moves
+ return result
+
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", delete_then_start_maintenance)
+ operation = _wait(service, started.operation_id)
+ assert operation.status == "failed"
+ assert operation.progress.deleted_images == 1
+ assert operation.progress.failed_images == 0
+ invoker.services.image_moves = None
+ retried = _wait(service, service.retry_operation(operation.operation_id, ALICE).operation_id)
+ assert retried.target_images == 1 and retried.progress.deleted_images == 1
+
+
+def test_operation_events_reach_the_bus(invoker: Invoker, service: IntermediatesService) -> None:
+ from invokeai.app.services.events.events_common import IntermediatesOperationChangedEvent
+
+ _seed_image(invoker, "a.png")
+ _, operation = _run(service, ALICE, _owner("alice"))
+
+ statuses = [
+ e.operation.status
+ for e in invoker.services.events.events # type: ignore[attr-defined]
+ if isinstance(e, IntermediatesOperationChangedEvent) and e.operation.operation_id == operation.operation_id
+ ]
+ assert statuses[0] == "pending" and statuses[-1] == "completed" and "running" in statuses
+ assert all(
+ e.user_id == "alice"
+ for e in invoker.services.events.events
+ if isinstance(e, IntermediatesOperationChangedEvent)
+ ) # type: ignore[attr-defined]
+
+
+# ── legacy ──
+
+
+def test_legacy_clear_all_deletes_every_safe_image_and_nothing_else(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ _project(invoker, "alice", "P", {"imageName": "referenced.png"})
+ _seed_image(invoker, "alice-safe.png", user_id="alice")
+ _seed_image(invoker, "bob-safe.png", user_id="bob")
+ _seed_image(invoker, "referenced.png")
+ _seed_image(invoker, "active.png", session_id="s1")
+ _seed_video(invoker, "video.mp4")
+ _enqueue_row(invoker, session_id="s1", status="pending")
+
+ with pytest.raises(IntermediatesScopeForbiddenError):
+ service.clear_all_images_now(ALICE)
+ assert service.clear_all_images_now(ADMIN) == 2
+
+ assert not _exists(invoker, "alice-safe.png") and not _exists(invoker, "bob-safe.png")
+ assert _exists(invoker, "referenced.png") and _exists(invoker, "active.png")
+ assert invoker.services.video_records.get("video.mp4").is_intermediate is True
+
+
+# ── review follow-ups ──
+
+
+def test_single_user_mode_clears_everyone_without_an_admin_row(invoker: Invoker, service: IntermediatesService) -> None:
+ """The default install: every request is the local administrator, but the `system` row is not an admin."""
+ invoker.services.configuration.multiuser = False
+ _seed_image(invoker, "one.png", user_id="system")
+ _seed_image(invoker, "two.png", user_id="alice")
+
+ _, operation = _run(
+ service, IntermediatesCaller(user_id="system", is_admin=True), IntermediatesScope(kind="everyone")
+ )
+
+ assert operation.status == "completed", operation.error
+ assert operation.progress.deleted_images == 2
+
+
+def test_inputs_added_to_an_active_session_after_it_was_scanned_are_protected(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ """A workflow-call parent is rewritten with its child's outputs while it stays active."""
+ _seed_image(invoker, "child-output.png")
+ item_id = _enqueue_row(invoker, session_id="parent", status="waiting", session_json='{"graph": {}}')
+ first = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ assert first.impact.delete_images == 1
+
+ with invoker.services.image_records._db.transaction() as cursor:
+ cursor.execute(
+ "UPDATE session_queue SET session = ?, status = 'pending' WHERE item_id = ?;",
+ ('{"results": {"n": {"image": {"image_name": "child-output.png"}}}}', item_id),
+ )
+
+ second = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ assert second.impact.delete_images == 0
+ assert second.impact.keep_active_images == 1
+
+
+def test_retries_are_authorized_as_the_retrying_caller(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)
+ _seed_image(invoker, "bob-flaky.png", user_id="bob")
+ real_delete = invoker.services.images.delete_intermediates_by_names
+
+ def fail_once(names, guard=None):
+ if not getattr(fail_once, "failed", False):
+ fail_once.failed = True # type: ignore[attr-defined]
+ raise OSError("disk hiccup")
+ return real_delete(names, guard)
+
+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", fail_once)
+ _, operation = _run(service, ADMIN, _owner("bob"))
+ assert operation.progress.unresolved_images == 1
+
+ # Another account cannot even see it; the demoted confirmer may see it but not widen to Bob.
+ with pytest.raises(IntermediatesOperationNotFoundError):
+ service.retry_operation(operation.operation_id, ALICE)
+ with pytest.raises(IntermediatesScopeForbiddenError):
+ service.retry_operation(operation.operation_id, IntermediatesCaller(user_id="admin", is_admin=False))
+ assert _exists(invoker, "bob-flaky.png")
+
+ retry = service.retry_operation(operation.operation_id, ADMIN)
+ assert _wait(service, retry.operation_id, ADMIN).progress.deleted_images == 1
+ # A duplicated retry request returns the retry that already took the targets over.
+ assert service.retry_operation(operation.operation_id, ADMIN).operation_id == retry.operation_id
+ assert service.get_operation(operation.operation_id, ADMIN).retried_by_operation_id == retry.operation_id
+
+
+def test_a_deactivated_caller_stops_at_the_next_batch(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)
+ for index in range(2):
+ _seed_image(invoker, f"a-{index}.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ real_get = invoker.services.users.get
+ calls = {"n": 0}
+
+ def deactivate_after_first_batch(user_id: str):
+ user = real_get(user_id)
+ calls["n"] += 1
+ return user.model_copy(update={"is_active": False}) if user is not None and calls["n"] > 1 else user
+
+ monkeypatch.setattr(invoker.services.users, "get", deactivate_after_first_batch)
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ operation = _wait(service, started.operation_id)
+
+ assert operation.status == "failed"
+ assert operation.progress.deleted_images == 1
+ assert operation.progress.unresolved_images == 1
+
+
+def test_unmeasured_targets_are_reported_rather_than_counted_as_free(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ _seed_image(invoker, "measured.png", size=10)
+ _seed_image(invoker, "unmeasured.png")
+ invoker.services.image_records.set_file_size_bytes("unmeasured.png", None)
+
+ preview, operation = _run(service, ALICE, _owner("alice"))
+
+ assert preview.impact.unknown_size_count == 1
+ assert operation.progress.reclaimed_bytes == 10
+ assert operation.progress.unknown_size_count == 1
+
+
+def test_a_replayed_start_is_answered_during_maintenance(invoker: Invoker, service: IntermediatesService) -> None:
+ _seed_image(invoker, "a.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ first = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ _wait(service, first.operation_id)
+ moves = MagicMock()
+ moves.is_maintenance_active.return_value = True
+ invoker.services.image_moves = moves
+
+ replay = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+
+ assert replay.operation_id == first.operation_id
+
+
+def test_a_save_cannot_slip_between_the_final_check_and_the_delete(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ """The guard and the DELETE share one transaction under the database lock, so a project save that
+ would protect a target either lands before the check (target kept) or after the commit."""
+ import threading
+
+ project = _project(invoker, "alice", "P", {})
+ _seed_image(invoker, "raced.png", project_id=project)
+ records = service._records
+ real_guard_factory = records.make_delete_guard
+ guard_entered = threading.Event()
+ guard_may_finish = threading.Event()
+ delete_committed_at: list[float] = []
+
+ def slow_guard_factory(kind, *, mode, allowed_user_ids):
+ guard = real_guard_factory(kind, mode=mode, allowed_user_ids=allowed_user_ids)
+
+ def paused(cursor, names):
+ guard_entered.set()
+ assert guard_may_finish.wait(timeout=10)
+ return guard(cursor, names)
+
+ return paused
+
+ monkeypatch.setattr(records, "make_delete_guard", slow_guard_factory)
+ real_record_delete = invoker.services.image_records.delete_intermediates_by_names
+
+ def timed_record_delete(names, guard=None):
+ result = real_record_delete(names, guard=guard)
+ delete_committed_at.append(time.monotonic())
+ return result
+
+ monkeypatch.setattr(invoker.services.image_records, "delete_intermediates_by_names", timed_record_delete)
+
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ assert guard_entered.wait(timeout=10)
+
+ save_finished_at: list[float] = []
+
+ def save_reference() -> None:
+ invoker.services.project_records.update(
+ "alice", project, expected_revision=1, name="P", data={"imageName": "raced.png"}
+ )
+ save_finished_at.append(time.monotonic())
+
+ saver = threading.Thread(target=save_reference)
+ saver.start()
+ saver.join(timeout=0.5)
+ assert saver.is_alive(), "the save committed while the delete's final check was in progress"
+
+ guard_may_finish.set()
+ saver.join(timeout=10)
+ operation = _wait(service, started.operation_id)
+
+ assert operation.progress.deleted_images == 1
+ assert save_finished_at[0] >= delete_committed_at[0]
+
+
+def test_active_inputs_survive_a_rolled_back_batch(
+ invoker: Invoker, service: IntermediatesService, monkeypatch
+) -> None:
+ """A failed batch rolls the temp table back; the next check must still see everything active."""
+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)
+ _seed_image(invoker, "first.png")
+ _seed_image(invoker, "consumed.png")
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ assert preview.impact.delete_images == 2
+ # Enqueued after the preview: only the final check can protect it.
+ _enqueue_row(invoker, session_id="s-late", status="pending", session_json='{"a": {"image_name": "consumed.png"}}')
+ real_delete = invoker.services.image_records.delete_intermediates_by_names
+ calls = {"n": 0}
+
+ def fail_first_batch_after_the_guard(names, guard=None):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ with invoker.services.image_records._db.transaction() as cursor:
+ if guard is not None:
+ guard(cursor, names)
+ raise RuntimeError("simulated I/O failure after the guard rebuilt the temp table")
+ return real_delete(names, guard=guard)
+
+ monkeypatch.setattr(
+ invoker.services.image_records, "delete_intermediates_by_names", fail_first_batch_after_the_guard
+ )
+
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ operation = _wait(service, started.operation_id)
+
+ assert operation.progress.failed_images == 1
+ assert _exists(invoker, "consumed.png"), "an input of pending work was deleted after a rolled-back batch"
diff --git a/tests/app/services/session_queue/test_session_queue_enqueue_idempotency.py b/tests/app/services/session_queue/test_session_queue_enqueue_idempotency.py
index d6c5e262f2..aa4e3182c6 100644
--- a/tests/app/services/session_queue/test_session_queue_enqueue_idempotency.py
+++ b/tests/app/services/session_queue/test_session_queue_enqueue_idempotency.py
@@ -465,3 +465,18 @@ def test_enqueue_batch_rejects_identity_reuse_for_another_origin(session_queue:
with pytest.raises(EnqueueIdempotencyConflictError):
asyncio.run(session_queue.enqueue_batch("default", _batch(origin="webv2:project-2:item-2"), False, "user-1"))
+
+
+def test_enqueued_items_carry_their_project(session_queue: SqliteSessionQueue, mock_invoker: Invoker) -> None:
+ mock_invoker.services.project_records.create("system", "Owned", {}, project_id="project-1")
+
+ asyncio.run(
+ session_queue.enqueue_batch(
+ "default", _batch(idempotency_key="scoped", project_id="project-1"), False, "system"
+ )
+ )
+ asyncio.run(session_queue.enqueue_batch("default", _batch(idempotency_key="unscoped"), False, "system"))
+
+ items = session_queue.list_all_queue_items("default")
+ assert sorted(item.project_id for item in items if item.project_id is not None) == ["project-1", "project-1"]
+ assert [item.project_id for item in items].count(None) == 2
diff --git a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
index edf678f0df..fc0124baa4 100644
--- a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
@@ -218,9 +218,10 @@ def test_enqueue_workflow_call_child_persists_pending_child_queue_item(session_q
destination,
retried_from_item_id,
user_id,
+ project_id,
status
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
"default",
@@ -234,6 +235,7 @@ def test_enqueue_workflow_call_child_persists_pending_child_queue_item(session_q
None,
None,
"user-1",
+ "project-1",
"in_progress",
),
)
@@ -243,6 +245,8 @@ def test_enqueue_workflow_call_child_persists_pending_child_queue_item(session_q
child_queue_item = session_queue.enqueue_workflow_call_child(parent_queue_item, child_session)
assert child_queue_item.status == "pending"
+ # Outputs of a child workflow belong to the project that enqueued the parent.
+ assert child_queue_item.project_id == "project-1"
assert child_queue_item.workflow_call_id == parent_session.waiting_workflow_call_execution.id
assert child_queue_item.parent_item_id == parent_item_id
assert child_queue_item.parent_session_id == parent_session.id
diff --git a/tests/app/services/session_queue/test_session_queue_workflow_call_retry.py b/tests/app/services/session_queue/test_session_queue_workflow_call_retry.py
index 3b9c85183d..ba1aeaddc8 100644
--- a/tests/app/services/session_queue/test_session_queue_workflow_call_retry.py
+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_retry.py
@@ -34,6 +34,7 @@ def _build_queue_item(
status: str,
root_item_id: int | None = None,
retried_from_item_id: int | None = None,
+ project_id: str | None = None,
) -> SessionQueueItem:
now = datetime.now()
return SessionQueueItem(
@@ -41,6 +42,7 @@ def _build_queue_item(
status=status,
priority=0,
batch_id=f"batch-{item_id}",
+ project_id=project_id,
origin=None,
destination=None,
session_id=session.id,
@@ -131,3 +133,17 @@ def test_retry_items_by_id_emits_unique_owner_ids_for_multiple_roots(
"user-1": [first_root_item.item_id],
"user-2": [second_root_item.item_id],
}
+
+
+def test_retried_items_inherit_the_project_of_the_root(
+ session_queue: SqliteSessionQueue, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ root_item = _build_queue_item(
+ item_id=20, session=GraphExecutionState(graph=Graph()), user_id="user-1", status="failed", project_id="p1"
+ )
+ monkeypatch.setattr(session_queue, "get_queue_item", lambda item_id: {root_item.item_id: root_item}[item_id])
+
+ session_queue.retry_items_by_id("default", [root_item.item_id])
+
+ retried = [item for item in session_queue.list_all_queue_items("default") if item.retried_from_item_id == 20]
+ assert [item.project_id for item in retried] == ["p1"]
diff --git a/tests/app/services/shared/test_invocation_context_images.py b/tests/app/services/shared/test_invocation_context_images.py
index f14b7b8d30..fd02c88376 100644
--- a/tests/app/services/shared/test_invocation_context_images.py
+++ b/tests/app/services/shared/test_invocation_context_images.py
@@ -16,6 +16,7 @@ def _make_interface(visibility: BoardVisibility, owner_id: str = "owner") -> tup
data.queue_item.workflow = None
data.queue_item.session.graph = None
data.queue_item.session_id = "session"
+ data.queue_item.project_id = "project-1"
data.invocation.is_intermediate = False
return ImagesInterface(services, data, MagicMock()), services
@@ -135,3 +136,11 @@ def test_image_save_allows_active_queue_user_without_board() -> None:
images.save(MagicMock())
services.images.create.assert_called_once()
+
+
+def test_images_save_attributes_the_output_to_the_queue_items_project() -> None:
+ images, services = _make_interface(BoardVisibility.Private, owner_id="queue-user")
+
+ images.save(MagicMock())
+
+ assert services.images.create.call_args.kwargs["project_id"] == "project-1"
diff --git a/tests/app/services/shared/test_invocation_context_videos.py b/tests/app/services/shared/test_invocation_context_videos.py
index 3d601c58c7..01c2e52560 100644
--- a/tests/app/services/shared/test_invocation_context_videos.py
+++ b/tests/app/services/shared/test_invocation_context_videos.py
@@ -16,6 +16,7 @@ def _make_interface(visibility: BoardVisibility, owner_id: str = "owner") -> tup
data.queue_item.workflow = None
data.queue_item.session.graph = None
data.queue_item.session_id = "session"
+ data.queue_item.project_id = "project-1"
data.invocation.is_intermediate = False
return VideosInterface(services, data, MagicMock()), services
@@ -97,3 +98,11 @@ def test_video_save_allows_active_queue_user_without_board() -> None:
videos.save(Path("output.mp4"), width=64, height=64, duration=1.0)
services.videos.create.assert_called_once()
+
+
+def test_videos_save_attributes_the_output_to_the_queue_items_project() -> None:
+ videos, services = _make_interface(BoardVisibility.Private, owner_id="queue-user")
+
+ videos.save(Path("output.mp4"), width=64, height=64, duration=1.0)
+
+ assert services.videos.create.call_args.kwargs["project_id"] == "project-1"
diff --git a/tests/app/services/videos/test_videos_default.py b/tests/app/services/videos/test_videos_default.py
index daf3dc870c..ebfd3fe2d6 100644
--- a/tests/app/services/videos/test_videos_default.py
+++ b/tests/app/services/videos/test_videos_default.py
@@ -326,3 +326,30 @@ class TestCreateBoardAttachFallback:
assert "deleted-board" in invoker.services.logger.warning.call_args.args[0]
# Nothing was attached, so nothing should be unwound.
invoker.services.board_video_records.remove_video_from_board.assert_not_called()
+
+
+def test_create_records_the_project_and_measured_size(video_service: VideoService, tmp_path) -> None:
+ invoker = video_service._VideoService__invoker # type: ignore[attr-defined]
+ invoker.services.configuration.image_subfolder_strategy = "flat"
+ invoker.services.names.create_video_name.return_value = "made.mp4"
+ invoker.services.video_files.get_file_size_bytes.return_value = 4096
+ invoker.services.video_records.get.return_value = _make_record(video_name="made.mp4")
+ invoker.services.board_video_records.get_board_for_video.return_value = None
+ invoker.services.urls.get_video_url.return_value = "http://localhost/videos/made.mp4"
+ source = tmp_path / "source.mp4"
+ source.write_bytes(b"\x00" * 16)
+
+ video_service.create(
+ source_path=source,
+ width=64,
+ height=64,
+ duration=1.0,
+ fps=8.0,
+ video_origin=ResourceOrigin.INTERNAL,
+ video_category=ImageCategory.GENERAL,
+ is_intermediate=True,
+ project_id="project-1",
+ )
+
+ assert invoker.services.video_records.save.call_args.kwargs["project_id"] == "project-1"
+ invoker.services.video_records.set_file_size_bytes.assert_called_once_with("made.mp4", 4096)
diff --git a/tests/conftest.py b/tests/conftest.py
index d54e098aad..38ab1820dc 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -24,6 +24,8 @@ from invokeai.app.services.image_index.image_index_default import ImageIndexServ
from invokeai.app.services.image_index.image_index_records_sqlite import ImageIndexRecordsSqlite
from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage
from invokeai.app.services.images.images_default import ImageService
+from invokeai.app.services.intermediates.intermediates_default import IntermediatesService
+from invokeai.app.services.intermediates.intermediates_records_sqlite import IntermediatesRecordsSqlite
from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache
from invokeai.app.services.invocation_services import InvocationServices
from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService
@@ -107,6 +109,7 @@ def mock_services() -> InvocationServices:
gallery=SqliteGalleryService(db=db),
image_index_records=ImageIndexRecordsSqlite(db=db),
image_index=ImageIndexService(),
+ intermediates=IntermediatesService(records=IntermediatesRecordsSqlite(db=db), logger=logger),
)