Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(intermediates): protect every saved reference and isolate force clears

Josh Corbett834f25b97136
diff --git a/docs/src/content/docs/features/intermediates.mdx b/docs/src/content/docs/features/intermediates.mdx
index 173613574c..2ff2e7f467 100644
--- a/docs/src/content/docs/features/intermediates.mdx
+++ b/docs/src/content/docs/features/intermediates.mdx
@@ -9,7 +9,7 @@ Generation produces intermediate images and videos: canvas composites, filter pr
Each row is one of your projects, or **Unassigned** for intermediates without a known project. Deleted projects' leftovers appear under Unassigned. A row shows the project's cover, its **Used** count (intermediates a cleanup keeps) and its **Unused** count (intermediates nothing needs any more), with the measured reclaimable size underneath. Sizes are measured in the background after upgrading; the section says so while measurement is still running and never counts an unmeasured file as empty.
-Select rows, or **Select all**, and press **Delete**. The confirmation explains why kept items are kept: referenced by a saved project or workflow, used by queued or running work, or created recently.
+Select rows, or **Select all**, and press **Delete**. The confirmation explains why kept items are kept: referenced by a saved document, used by queued or running work, or created recently.
Administrators start on their own account. **Show everyone** expands the view to every account; they can search accounts as well as project names and can open one account from the Users page. Opening the section from a project action shows that project directly, even when it is outside the first results page.
@@ -18,18 +18,18 @@ Administrators start on their own account. **Show everyone** expands the view to
A normal clear deletes only safe items. It always keeps:
- anything a pending, waiting or running job produced or uses as an input, including cached images and videos reused from an earlier job and completed child-workflow media until the root workflow finishes;
-- anything created in the last 30 minutes, so an upload the browser is about to reference or enqueue is never collected;
+- anything created in the last 30 minutes, so an upload the browser is about to reference or enqueue is never collected, and cached media for 30 minutes after the job that reused it ends;
- anything the open webv2 editor still references, including unsaved edits and available undo history; the browser refreshes this temporary hold while it is open;
-- anything a saved project or library workflow still names, such as canvas staging candidates or cropped reference images;
+- anything a saved document still names: a project or library workflow (canvas staging candidates, cropped reference images), the legacy editor's saved canvas and reference images, or a project set aside for repair when project boards were introduced;
- anything that is no longer an intermediate.
-The advanced option in the confirmation, **also delete items that saved projects or workflows still reference**, turns the delete into a force clear. Those projects will show missing images and undo may no longer restore them. Force clearing never touches active, browser-held or recent work and cannot be undone; it asks for an acknowledgement and for the word `CLEAR` to be typed. A new saved reference added after the preview is kept until a new preview is confirmed.
+The advanced option in the confirmation, **also delete items that saved projects or workflows still reference**, turns the delete into a force clear. The confirmation lists every document it would break; those projects will show missing images and undo may no longer restore them. Force clearing never touches active, browser-held or recent work and cannot be undone; it asks for an acknowledgement and for the word `CLEAR` to be typed. A regular user's force clear also keeps anything another account's document names, such as a shared workflow. A new saved reference added after the preview is kept until a new preview is confirmed.
A single preview includes at most 50,000 eligible items. If more remain, the confirmation says so; run Clear again after that batch finishes. Protected items do not use up the batch limit.
Every confirmation is based on a fresh server preview that freezes exactly which files the cleanup will act on. Files created after the preview are never included, and every batch re-checks its targets at the moment of deletion: an intermediate that was promoted, referenced or picked up by a job in the meantime is kept.
-An open editor refreshes its browser hold every five minutes and when the tab becomes visible. It releases names removed from the current projects and undo history. The hold expires one day after the last refresh if the tab closes or crashes. If you have an unsaved browser-only draft that has stayed closed longer than a day, reopen it before clearing old intermediates.
+An open editor refreshes its browser hold every five minutes and when the tab becomes visible again. It releases names removed from the current projects and undo history, and releases the whole hold when the tab closes or you sign out. If the tab crashes instead, the hold expires 15 minutes after its last refresh. Reopen an unsaved browser-only draft before clearing old intermediates.
## Progress and results
@@ -44,10 +44,10 @@ The server accepts at most eight active operations at a time. Wait for one to fi
| Clear a project's intermediates | Own projects | Any project |
| Clear an account's intermediates | Own account | Any account |
| Clear everyone's intermediates | No | Yes |
-| Force clear referenced intermediates | Own files | Any authorized scope |
+| Force clear referenced intermediates | Own files that only your own documents name | Any authorized scope |
Cleanup is refused while [image storage maintenance](/features/image-storage-maintenance/) is active.
## Legacy endpoint
-The older `DELETE /api/v1/images/intermediates` route remains available to administrators. It now applies the same safety policy as a normal clear, so it keeps referenced, active and recent images and returns the number of images it deleted. It does not touch videos.
+The older `DELETE /api/v1/images/intermediates` route remains available to administrators. It now applies the same safety policy as a normal clear, so it keeps referenced, active and recent images and returns the number of images it deleted. It does not touch videos. `GET /api/v1/images/intermediates` counts exactly the images that route would delete, so the legacy button settles at zero after a clear.
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index 0832e2a02d..6968dde977 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -302,11 +302,15 @@ def clear_intermediates(
def get_intermediates_count(
current_user: CurrentUserOrDefault,
) -> int:
- """Gets the count of intermediate images. Non-admin users only see their own intermediates."""
+ """Counts the intermediate images a clear would delete. Non-admin users only see their own intermediates.
+
+ Active, recent and referenced images are left out, as `DELETE /intermediates` keeps them.
+ """
try:
- user_id = None if current_user.is_admin else current_user.user_id
- return ApiDependencies.invoker.services.images.get_intermediates_count(user_id=user_id)
+ return ApiDependencies.invoker.services.intermediates.count_safe_images(
+ IntermediatesCaller(user_id=current_user.user_id, is_admin=current_user.is_admin)
+ )
except Exception:
raise HTTPException(status_code=500, detail="Failed to get intermediates")
diff --git a/invokeai/app/services/client_state_persistence/client_state_persistence_sqlite.py b/invokeai/app/services/client_state_persistence/client_state_persistence_sqlite.py
index 7605de829d..b27237c2e7 100644
--- a/invokeai/app/services/client_state_persistence/client_state_persistence_sqlite.py
+++ b/invokeai/app/services/client_state_persistence/client_state_persistence_sqlite.py
@@ -1,5 +1,10 @@
from invokeai.app.services.client_state_persistence.client_state_persistence_base import ClientStatePersistenceABC
from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.media_references import (
+ delete_media_references,
+ extract_media_references_from_json,
+ replace_media_references,
+)
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
@@ -17,6 +22,10 @@ class ClientStatePersistenceSqlite(ClientStatePersistenceABC):
self._invoker = invoker
def set_by_key(self, user_id: str, key: str, value: str) -> str:
+ # The legacy editor keeps its canvas layers and reference images only here, as
+ # intermediates; indexing them keeps cleanup from treating them as unused. Parsed before
+ # taking the database lock, which every other writer shares.
+ references = extract_media_references_from_json(value)
with self._db.transaction() as cursor:
cursor.execute(
"""
@@ -27,6 +36,9 @@ class ClientStatePersistenceSqlite(ClientStatePersistenceABC):
""",
(user_id, key, value),
)
+ replace_media_references(
+ cursor, owner_kind="client_state", user_id=user_id, owner_id=key, references=references
+ )
return value
@@ -68,6 +80,7 @@ class ClientStatePersistenceSqlite(ClientStatePersistenceABC):
""",
(user_id, key),
)
+ delete_media_references(cursor, owner_kind="client_state", user_id=user_id, owner_id=key)
def delete(self, user_id: str) -> None:
with self._db.transaction() as cursor:
@@ -78,3 +91,6 @@ class ClientStatePersistenceSqlite(ClientStatePersistenceABC):
""",
(user_id,),
)
+ cursor.execute(
+ "DELETE FROM media_references WHERE owner_kind = 'client_state' AND user_id = ?;", (user_id,)
+ )
diff --git a/invokeai/app/services/image_records/image_records_base.py b/invokeai/app/services/image_records/image_records_base.py
index 22972f2e49..f3161e75ca 100644
--- a/invokeai/app/services/image_records/image_records_base.py
+++ b/invokeai/app/services/image_records/image_records_base.py
@@ -107,11 +107,6 @@ class ImageRecordStorageBase(ABC):
"""
pass
- @abstractmethod
- def get_intermediates_count(self, user_id: Optional[str] = None) -> int:
- """Gets a count of intermediate images. If user_id is provided, only counts that user's intermediates."""
- pass
-
@abstractmethod
def save(
self,
@@ -140,7 +135,7 @@ class ImageRecordStorageBase(ABC):
@abstractmethod
def set_file_sizes_bytes(self, sizes: dict[str, int]) -> None:
- """Records many measured sizes in one transaction."""
+ """Records many measured sizes in one transaction, leaving rows that already have a size."""
pass
@abstractmethod
diff --git a/invokeai/app/services/image_records/image_records_sqlite.py b/invokeai/app/services/image_records/image_records_sqlite.py
index 85b240fb38..16e7546ef1 100644
--- a/invokeai/app/services/image_records/image_records_sqlite.py
+++ b/invokeai/app/services/image_records/image_records_sqlite.py
@@ -249,8 +249,10 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
return
with self._db.transaction() as cursor:
try:
+ # Backfill only fills gaps: the writer's own measurement, taken after the file exists,
+ # wins over one taken before it was written.
cursor.executemany(
- "UPDATE images SET file_size_bytes = ? WHERE image_name = ?;",
+ "UPDATE images SET file_size_bytes = ? WHERE image_name = ? AND file_size_bytes IS NULL;",
[(size, name) for name, size in sizes.items()],
)
except sqlite3.Error as e:
@@ -459,17 +461,6 @@ class SqliteImageRecordStorage(ImageRecordStorageBase):
except sqlite3.Error as e:
raise ImageRecordDeleteException from e
- def get_intermediates_count(self, user_id: Optional[str] = None) -> int:
- with self._db.transaction() as cursor:
- query = "SELECT COUNT(*) FROM images WHERE is_intermediate = TRUE"
- params: list[str] = []
- if user_id is not None:
- query += " AND user_id = ?"
- params.append(user_id)
- cursor.execute(query, params)
- count = cast(int, cursor.fetchone()[0])
- return count
-
def get_subfolders(self, image_names: list[str]) -> dict[str, str]:
subfolders: dict[str, str] = {}
with self._db.transaction() as cursor:
diff --git a/invokeai/app/services/images/images_base.py b/invokeai/app/services/images/images_base.py
index a061cea11f..422e6706e8 100644
--- a/invokeai/app/services/images/images_base.py
+++ b/invokeai/app/services/images/images_base.py
@@ -170,11 +170,6 @@ class ImageServiceABC(ABC):
"""
pass
- @abstractmethod
- def get_intermediates_count(self, user_id: Optional[str] = None) -> int:
- """Gets the number of intermediate images. If user_id is provided, only counts that user's intermediates."""
- pass
-
@abstractmethod
def delete_images_by_names(self, image_names: list[str]) -> tuple[list[str], list[str]]:
"""Deletes exactly these images; returns ``(deleted_names, failed_names)``.
diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.py
index 6bb0f679f8..9276b3b4a5 100644
--- a/invokeai/app/services/images/images_default.py
+++ b/invokeai/app/services/images/images_default.py
@@ -27,7 +27,12 @@ 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.intermediate_delete import (
+ IntermediateDeleteGuard,
+ IntermediateDeleteResult,
+ JournaledDeleteAdapter,
+ delete_journaled_intermediates,
+)
from invokeai.app.services.shared.pagination import OffsetPaginatedResults
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
@@ -593,7 +598,21 @@ class ImageService(ImageServiceABC):
subfolders = self.__invoker.services.image_records.get_subfolders(image_names)
if not subfolders:
return IntermediateDeleteResult()
- return self._delete_intermediates(subfolders, guard=guard)
+ files = self.__invoker.services.image_files
+ records = self.__invoker.services.image_records
+ return delete_journaled_intermediates(
+ subfolders,
+ guard,
+ JournaledDeleteAdapter(
+ kind="image",
+ begin=files.begin_delete,
+ delete_records=lambda names, g: records.delete_intermediates_by_names(names, guard=g),
+ abandon=files.abandon_delete,
+ commit=lambda token, names: files.commit_delete(token, image_names=names),
+ notify_deleted=self._on_deleted,
+ log_error=self.__invoker.services.logger.error,
+ ),
+ )
except ImageRecordDeleteException:
self.__invoker.services.logger.error("Failed to delete image records")
raise
@@ -601,68 +620,6 @@ 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)
- except Exception as e:
- self.__invoker.services.logger.error("Problem getting intermediates count")
- raise e
-
def get_image_names(
self,
starred_first: bool = True,
diff --git a/invokeai/app/services/intermediates/intermediates_base.py b/invokeai/app/services/intermediates/intermediates_base.py
index f09a50ed1f..9edbb02d59 100644
--- a/invokeai/app/services/intermediates/intermediates_base.py
+++ b/invokeai/app/services/intermediates/intermediates_base.py
@@ -77,3 +77,8 @@ class IntermediatesServiceBase(ABC):
def clear_all_images_now(self, caller: IntermediatesCaller) -> int:
"""The legacy instance-wide clear: every safe intermediate image, synchronously. Admin only."""
pass
+
+ @abstractmethod
+ def count_safe_images(self, caller: IntermediatesCaller) -> int:
+ """The legacy count: the intermediate images `clear_all_images_now` would delete, within the caller's view."""
+ pass
diff --git a/invokeai/app/services/intermediates/intermediates_common.py b/invokeai/app/services/intermediates/intermediates_common.py
index 3b46ccadb4..4ede34a109 100644
--- a/invokeai/app/services/intermediates/intermediates_common.py
+++ b/invokeai/app/services/intermediates/intermediates_common.py
@@ -5,6 +5,8 @@ from typing import Annotated, Literal, Optional
from pydantic import BaseModel, Field
+from invokeai.app.services.shared.media_references import MediaReferenceOwnerKind
+
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."""
@@ -20,12 +22,17 @@ RECENT_GRACE_SECONDS = 30 * 60
PREVIEW_TTL_SECONDS = 10 * 60
+# An open editor refreshes its hold every few minutes; a tab that closes without releasing it
+# stops protecting its media after this long.
+BROWSER_HOLD_TTL_SECONDS = 15 * 60
+MAX_BROWSER_HOLD_NAMES = 50_000
+
MediaName = Annotated[str, Field(min_length=1, max_length=255)]
class IntermediatesBrowserHoldRequest(BaseModel):
- images: list[MediaName] = Field(default_factory=list, max_length=50_000)
- videos: list[MediaName] = Field(default_factory=list, max_length=50_000)
+ images: list[MediaName] = Field(default_factory=list, max_length=MAX_BROWSER_HOLD_NAMES)
+ videos: list[MediaName] = Field(default_factory=list, max_length=MAX_BROWSER_HOLD_NAMES)
class IntermediatesScopeTarget(BaseModel):
@@ -57,7 +64,7 @@ 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")
+ referenced: int = Field(default=0, description="Named by a saved document: 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")
@@ -124,9 +131,15 @@ class IntermediatesImpact(BaseModel):
class IntermediatesAffectedDocument(BaseModel):
"""A saved document a force clear would leave pointing at deleted media."""
- kind: Literal["project", "workflow"]
+ kind: MediaReferenceOwnerKind = Field(
+ description=(
+ "`client_state` is the legacy editor's persisted state; `quarantined_project` is a project kept for repair"
+ )
+ )
user_id: str
- owner_id: str = Field(description="The project or workflow id")
+ 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")
+ owner_id: str = Field(description="The project or workflow id, or the client state key")
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")
@@ -144,10 +157,10 @@ class IntermediatesPreview(BaseModel):
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"
+ description=(
+ "Documents a force clear would break. A non-administrator's force clear keeps media other accounts'"
+ " documents name, so these are always the caller's own"
+ ),
)
diff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.py
index d1e9f8fd79..aec6f62b1d 100644
--- a/invokeai/app/services/intermediates/intermediates_default.py
+++ b/invokeai/app/services/intermediates/intermediates_default.py
@@ -17,6 +17,7 @@ import queue
import threading
import time
import uuid
+from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Callable, Optional, Sequence, cast
@@ -47,6 +48,7 @@ from invokeai.app.services.intermediates.intermediates_common import (
IntermediatesSummaryTotals,
IntermediatesUnavailableError,
)
+from invokeai.app.services.intermediates.intermediates_measurement import IntermediatesSizeMeasurer
from invokeai.app.services.intermediates.intermediates_records_sqlite import (
AffectedReference,
IntermediateCandidate,
@@ -56,18 +58,16 @@ from invokeai.app.services.intermediates.intermediates_records_sqlite import (
)
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResult
-from invokeai.app.services.shared.media_references import MediaReferences
+from invokeai.app.services.shared.media_references import MediaReferenceOwnerKind, MediaReferences
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_RETAINED_TARGETS = 500_000
MAX_ACTIVE_OPERATIONS = 8
MAX_OPERATION_TARGETS = 50_000
MAX_PREVIEWS = 200
-# Frozen (name, size) pairs held across every live preview; the oldest previews expire first.
+MAX_PREVIEWS_PER_CALLER = 4
+# Frozen (name, size) pairs held across every live preview; the heaviest caller gives up previews first.
MAX_FROZEN_PREVIEW_TARGETS = 500_000
PROGRESS_EVENT_INTERVAL_SECONDS = 1.0
WORKER_STOP_TIMEOUT_SECONDS = 10.0
@@ -112,9 +112,8 @@ class IntermediatesService(IntermediatesServiceBase):
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()
- self._measure_due_at: Optional[float] = None
self._stop = threading.Event()
+ self._measurer = IntermediatesSizeMeasurer(records, lambda: self._services, self._stop, self._logger)
self._worker: Optional[threading.Thread] = None
# region lifecycle
@@ -122,7 +121,7 @@ class IntermediatesService(IntermediatesServiceBase):
def start(self, invoker: Invoker) -> None:
self._invoker = invoker
self._stop.clear()
- self._measure_due_at = None
+ self._measurer.reset()
with self._lock:
for user_id, preview_id, key, state in self._records.load_operations():
dto = IntermediatesOperation.model_validate(state["dto"])
@@ -208,7 +207,7 @@ class IntermediatesService(IntermediatesServiceBase):
project_id: Optional[str] = None,
) -> IntermediatesSummary:
owner_filter = self._resolve_owner_filter(caller, owner_id)
- aggregated = self._records.summarize(owner_filter)
+ aggregated = self._records.summarize([owner_filter] if owner_filter is not None else None)
projects = self._records.get_projects(owner_filter)
users = self._services.users.get_many([user_id for user_id, _ in aggregated])
@@ -255,7 +254,7 @@ class IntermediatesService(IntermediatesServiceBase):
measuring = self._records.has_unmeasured_intermediates()
if measuring:
- self._measure_requested.set()
+ self._measurer.request()
self._ensure_worker()
return IntermediatesSummary(
@@ -292,7 +291,7 @@ class IntermediatesService(IntermediatesServiceBase):
scope = request.scope
allowed = self._authorize_scope(scope, caller)
candidates, has_more_eligible = self._collect_candidates(scope, request.mode)
- counts = self._records.summarize(scope.user_id if scope.kind == "owner" else None)
+ counts = self._records.summarize(allowed)
if scope.kind == "selection":
selected_rows = {(target.user_id, target.project_id) for target in scope.targets}
counts = {row: kinds for row, kinds in counts.items() if row in selected_rows}
@@ -310,22 +309,28 @@ class IntermediatesService(IntermediatesServiceBase):
f"keep_referenced_{suffix}",
getattr(impact, f"keep_referenced_{suffix}") + scope_counts.referenced,
)
+ # Force mode confirms the documents it breaks. Another account's document is never the
+ # caller's to break unless the caller administers the instance, so its media is kept.
+ confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]] = {"image": {}, "video": {}}
targets: dict[MediaKind, list[tuple[str, Optional[int]]]] = {"image": [], "video": []}
for kind in ("image", "video"):
media_kind = cast(MediaKind, kind)
+ owners: dict[str, set[tuple[str, str, str]]] = {}
+ if request.mode == "force":
+ owners = self._records.reference_owners(
+ media_kind, [c.name for c in candidates[media_kind] if c.classification == "referenced"]
+ )
for candidate in candidates[media_kind]:
- self._tally(impact, media_kind, candidate, request.mode, targets)
-
- confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]] = {"image": {}, "video": {}}
- affected: list[IntermediatesAffectedDocument] = []
- hidden = 0
- if request.mode == "force":
- for kind in ("image", "video"):
- media_kind = cast(MediaKind, kind)
- confirmed_references[media_kind] = self._records.reference_owners(
- media_kind, [name for name, _ in targets[media_kind]]
+ references = owners.get(candidate.name, set())
+ deletable = candidate.classification == "safe" or (
+ request.mode == "force"
+ and candidate.classification == "referenced"
+ and (caller.is_admin or all(user_id == caller.user_id for _, user_id, _ in references))
)
- affected, hidden = self._describe_affected(confirmed_references, caller)
+ self._tally(impact, media_kind, candidate, deletable, targets)
+ if deletable and references:
+ confirmed_references[media_kind][candidate.name] = references
+ affected = self._describe_affected(confirmed_references) if request.mode == "force" else []
created = _now()
dto = IntermediatesPreview(
@@ -338,7 +343,6 @@ class IntermediatesService(IntermediatesServiceBase):
impact=impact,
has_more_eligible=has_more_eligible,
affected_documents=affected,
- affected_documents_hidden=hidden,
)
with self._lock:
self._previews[dto.preview_id] = _Preview(
@@ -348,7 +352,7 @@ class IntermediatesService(IntermediatesServiceBase):
allowed_user_ids=allowed,
confirmed_references=confirmed_references,
)
- self._expire_previews_locked(created)
+ self._expire_previews_locked(created, keep=dto.preview_id)
return dto
def _authorize_scope(self, scope: IntermediatesScope, caller: IntermediatesCaller) -> Optional[frozenset[str]]:
@@ -406,11 +410,10 @@ class IntermediatesService(IntermediatesServiceBase):
impact: IntermediatesImpact,
kind: MediaKind,
candidate: IntermediateCandidate,
- mode: IntermediatesCleanupMode,
+ deletable: bool,
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:
@@ -423,10 +426,8 @@ class IntermediatesService(IntermediatesServiceBase):
setattr(impact, attribute, getattr(impact, attribute) + 1)
def _describe_affected(
- self,
- confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]],
- caller: IntermediatesCaller,
- ) -> tuple[list[IntermediatesAffectedDocument], int]:
+ self, confirmed_references: dict[MediaKind, dict[str, set[tuple[str, str, str]]]]
+ ) -> list[IntermediatesAffectedDocument]:
counts: dict[tuple[str, str, str], int] = {}
for owners in confirmed_references.values():
for refs_for_name in owners.values():
@@ -436,34 +437,53 @@ class IntermediatesService(IntermediatesServiceBase):
AffectedReference(kind, user_id, owner_id, count) for (kind, user_id, owner_id), count in counts.items()
]
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,
- )
+ users = self._services.users.get_many(sorted({ref.user_id for ref in refs}))
+ documents = [
+ IntermediatesAffectedDocument(
+ kind=cast(MediaReferenceOwnerKind, ref.owner_kind),
+ user_id=ref.user_id,
+ user_display_name=users[ref.user_id].display_name if ref.user_id in users else None,
+ user_email=users[ref.user_id].email if ref.user_id in users else None,
+ 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
+ for ref in refs
+ ]
+ documents.sort(key=lambda doc: (doc.kind, (doc.name or "").casefold(), doc.owner_id))
+ return documents
- 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:
+ def _expire_previews_locked(self, now: datetime, *, keep: Optional[str] = None) -> None:
+ """Drops expired previews, then enforces the caps; ``keep`` (the one just created) always survives."""
+ for pid in [pid for pid, preview in self._previews.items() if preview.dto.expires_at <= now]:
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]
+ by_caller: dict[str, list[str]] = defaultdict(list)
+ for pid, preview in self._previews.items():
+ by_caller[preview.caller_user_id].append(pid)
+ for pids in by_caller.values():
+ for pid in [pid for pid in pids if pid != keep][: max(0, len(pids) - MAX_PREVIEWS_PER_CALLER)]:
+ del self._previews[pid]
+
+ # Past the global caps, the caller holding the most frozen targets gives up its oldest
+ # preview first, so no account can evict another's pending confirmation by previewing.
+ frozen: dict[str, int] = defaultdict(int)
+ for preview in self._previews.values():
+ frozen[preview.caller_user_id] += len(preview.targets["image"]) + len(preview.targets["video"])
+ keep_caller = self._previews[keep].caller_user_id if keep in self._previews else None
+ while len(self._previews) > MAX_PREVIEWS or sum(frozen.values()) > MAX_FROZEN_PREVIEW_TARGETS:
+ evictable = [pid for pid in self._previews if pid != keep]
+ if not evictable:
+ break
+ victim = max(
+ evictable,
+ key=lambda pid: (
+ frozen[self._previews[pid].caller_user_id],
+ # On a tie, the caller whose request overflowed the cap pays for it.
+ self._previews[pid].caller_user_id == keep_caller,
+ ),
+ )
+ preview = self._previews.pop(victim)
+ frozen[preview.caller_user_id] -= len(preview.targets["image"]) + len(preview.targets["video"])
# endregion
@@ -711,17 +731,24 @@ class IntermediatesService(IntermediatesServiceBase):
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
+ after_rowid: Optional[int] = 0
+ # Bounded pages keep memory flat however many intermediates exist; the guard re-checks each
+ # batch on the deleting transaction.
+ while after_rowid is not None:
+ page, after_rowid = self._records.page_intermediates(
+ "image", after_rowid=after_rowid, limit=DELETE_BATCH_SIZE
)
- deleted += len(result.deleted_names)
+ names = [candidate.name for candidate in page if candidate.classification == "safe"]
+ if names:
+ deleted += len(self._services.images.delete_intermediates_by_names(names, guard).deleted_names)
return deleted
+ def count_safe_images(self, caller: IntermediatesCaller) -> int:
+ counts = self._records.summarize(None if caller.is_admin else [caller.user_id])
+ return sum(kinds["image"].counts.safe for kinds in counts.values())
+
# endregion
# region worker
@@ -731,10 +758,8 @@ class IntermediatesService(IntermediatesServiceBase):
try:
operation_id = self._pending.get(timeout=0.5)
except queue.Empty:
- if self._measure_requested.is_set() or (
- self._measure_due_at is not None and time.monotonic() >= self._measure_due_at
- ):
- self._measure_once()
+ if self._measurer.is_due():
+ self._measurer.measure_once()
continue
if not operation_id:
continue
@@ -888,57 +913,4 @@ class IntermediatesService(IntermediatesServiceBase):
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()
- self._measure_due_at = None
- 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
- retry_young = 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,
- )
- sizes: dict[str, int] = {}
- unmeasurable: list[str] = []
- for name, subfolder in pending:
- if self._stop.is_set():
- return
- 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}")
- unmeasurable.append(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
- self._records.mark_unmeasurable(cast(MediaKind, kind), unmeasurable)
- # 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:
- remaining = True
- elif self._records.next_unmeasured(cast(MediaKind, kind), 1):
- # All older rows were measured or skipped; a new row still needs its file
- # to be written before measuring it. Wake after the minimum age has elapsed.
- retry_young = True
- if remaining:
- self._measure_requested.set()
- # Yield the database lock between batches so generation and saves keep flowing.
- time.sleep(0.05)
- elif retry_young:
- self._measure_due_at = time.monotonic() + MEASURE_MIN_AGE_SECONDS
- 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_measurement.py b/invokeai/app/services/intermediates/intermediates_measurement.py
new file mode 100644
index 0000000000..21f04f8d52
--- /dev/null
+++ b/invokeai/app/services/intermediates/intermediates_measurement.py
@@ -0,0 +1,99 @@
+"""Background measurement of intermediate file sizes.
+
+Media written before size accounting existed, or whose writer could not stat its file, has a NULL
+size. The measurer fills those gaps in bounded batches on the intermediates worker thread while it
+has no cleanup to run, and only on request, so an instance that never opens the manager never pays
+for a scan.
+"""
+
+import logging
+import threading
+import time
+from typing import TYPE_CHECKING, Callable, Optional, cast
+
+from invokeai.app.services.intermediates.intermediates_records_sqlite import IntermediatesRecordsSqlite, MediaKind
+
+if TYPE_CHECKING:
+ from invokeai.app.services.invocation_services import InvocationServices
+
+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
+
+
+class IntermediatesSizeMeasurer:
+ def __init__(
+ self,
+ records: IntermediatesRecordsSqlite,
+ services: Callable[[], "InvocationServices"],
+ stop: threading.Event,
+ logger: logging.Logger,
+ ) -> None:
+ self._records = records
+ self._services = services
+ self._stop = stop
+ self._logger = logger
+ self._requested = threading.Event()
+ self._due_at: Optional[float] = None
+
+ def reset(self) -> None:
+ self._requested.clear()
+ self._due_at = None
+
+ def request(self) -> None:
+ self._requested.set()
+
+ def is_due(self) -> bool:
+ return self._requested.is_set() or (self._due_at is not None and time.monotonic() >= self._due_at)
+
+ def measure_once(self) -> None:
+ """Measures a bounded batch of unmeasured intermediates; clears the request when none remain."""
+ self.reset()
+ services = self._services()
+ image_moves = getattr(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
+ retry_young = False
+ for kind, files, records in (
+ ("image", services.image_files, services.image_records),
+ ("video", services.video_files, services.video_records),
+ ):
+ pending = self._records.next_unmeasured(
+ cast(MediaKind, kind), MEASURE_BATCH_SIZE, min_age_seconds=MEASURE_MIN_AGE_SECONDS
+ )
+ sizes: dict[str, int] = {}
+ unmeasurable: list[str] = []
+ for name, subfolder in pending:
+ if self._stop.is_set():
+ return
+ 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}")
+ unmeasurable.append(name)
+ continue
+ # A missing file occupies nothing; recording 0 is a measurement, not a guess, and
+ # keeps the row from being re-measured forever. The writer's own measurement
+ # still replaces it if the file lands afterwards.
+ sizes[name] = size if size is not None else 0
+ self._records.mark_unmeasurable(cast(MediaKind, kind), unmeasurable)
+ # 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:
+ remaining = True
+ elif self._records.next_unmeasured(cast(MediaKind, kind), 1):
+ # All older rows were measured or skipped; a new row still needs its file to be
+ # written before measuring it. Wake after the minimum age has elapsed.
+ retry_young = True
+ if remaining:
+ self._requested.set()
+ # Yield the database lock between batches so generation and saves keep flowing.
+ time.sleep(0.05)
+ elif retry_young:
+ self._due_at = time.monotonic() + MEASURE_MIN_AGE_SECONDS
+ except Exception as error:
+ self._logger.warning(f"Measuring intermediate file sizes failed; will retry on demand: {error}")
diff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
index 5289634b4c..f25ad90cf8 100644
--- a/invokeai/app/services/intermediates/intermediates_records_sqlite.py
+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py
@@ -6,8 +6,9 @@ is the same SQL whether it aggregates a summary, freezes a preview's targets or
- ``active``: produced or referenced by a pending, waiting or running queue item, or a
completed child of an active root workflow.
- ``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`).
+ before it is promoted, referenced or enqueued; or a cached output whose consuming session ended
+ inside that window, since a cache hit reuses an old row.
+- ``referenced``: named by a saved document (`media_references`).
- ``safe``: none of the above.
Queue inputs are found by scanning each active item's stored session for media-name keys; the
@@ -19,15 +20,16 @@ import re
import sqlite3
from collections import defaultdict
from dataclasses import dataclass, field
-from typing import Iterable, Literal, Optional, Sequence, cast
+from typing import Collection, Iterable, Literal, Optional, Sequence, cast
from invokeai.app.services.intermediates.intermediates_common import (
+ BROWSER_HOLD_TTL_SECONDS,
RECENT_GRACE_SECONDS,
IntermediatesCleanupMode,
IntermediatesKindCounts,
IntermediatesScopeTarget,
)
-from invokeai.app.services.shared.media_references import MediaReferences
+from invokeai.app.services.shared.media_references import IMAGE_NAME_KEYS, VIDEO_NAME_KEYS, MediaReferences
from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabase
MediaKind = Literal["image", "video"]
@@ -57,8 +59,14 @@ def _protected_queue_items_sql() -> str:
_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})"')
+
+def _name_pattern(keys: frozenset[str]) -> re.Pattern[str]:
+ alternatives = "|".join(sorted(re.escape(key) for key in keys))
+ return re.compile(rf'"(?:{alternatives})"\s*:\s*"([^"\\]{{1,255}})"')
+
+
+_IMAGE_NAME_RE = _name_pattern(IMAGE_NAME_KEYS)
+_VIDEO_NAME_RE = _name_pattern(VIDEO_NAME_KEYS)
_TABLES: dict[MediaKind, tuple[str, str, str]] = {
"image": ("images", "image_name", "image_subfolder"),
@@ -109,14 +117,22 @@ class IntermediatesRecordsSqlite:
def _prepare_session_holds(cursor: sqlite3.Cursor) -> None:
# These holds share the cache's process lifetime. After restart the cache is empty and
# recovered queue sessions protect their serialized inputs through the normal scan.
+ # A cache hit reuses an old row, so the recency grace a fresh output gets is counted from
+ # when the consuming session is first seen finished instead.
cursor.execute(
"CREATE TEMP TABLE IF NOT EXISTS intermediates_session_media "
- "(session_id TEXT, kind TEXT, name TEXT, PRIMARY KEY(session_id, kind, name)) WITHOUT ROWID;"
+ "(session_id TEXT, kind TEXT, name TEXT, released_at TEXT, PRIMARY KEY(session_id, kind, name)) "
+ "WITHOUT ROWID;"
)
cursor.execute(
- "DELETE FROM temp.intermediates_session_media WHERE session_id NOT IN "
+ "UPDATE temp.intermediates_session_media SET released_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') "
+ "WHERE released_at IS NULL AND session_id NOT IN "
f"(SELECT session_id FROM ({_protected_queue_items_sql()}));"
)
+ cursor.execute(
+ "DELETE FROM temp.intermediates_session_media "
+ f"WHERE released_at <= STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '-{RECENT_GRACE_SECONDS} seconds');"
+ )
def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:
if references.is_empty():
@@ -144,11 +160,12 @@ class IntermediatesRecordsSqlite:
held.extend((session_id, kind, name) for name in ordered)
# The existence check and hold commit share the deleting transaction's lock. Cleanup
# either deletes first (a cache miss), or observes this active session's hold.
- cursor.executemany("INSERT OR IGNORE INTO temp.intermediates_session_media VALUES (?, ?, ?);", held)
+ cursor.executemany("INSERT OR REPLACE INTO temp.intermediates_session_media VALUES (?, ?, ?, NULL);", held)
return True
def replace_browser_hold(self, user_id: str, lease_id: str, images: Sequence[str], videos: Sequence[str]) -> None:
with self._db.transaction() as cursor:
+ # Indexed on expires_at, so the sweep touches only what expired.
cursor.execute(
"DELETE FROM intermediates_browser_holds WHERE expires_at <= STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW');"
)
@@ -167,7 +184,8 @@ class IntermediatesRecordsSqlite:
f"""--sql
INSERT INTO intermediates_browser_holds
(user_id, lease_id, media_kind, media_name, expires_at)
- SELECT ?, ?, ?, m.{name_column}, STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '+1 day')
+ SELECT ?, ?, ?, m.{name_column},
+ STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '+{BROWSER_HOLD_TTL_SECONDS} seconds')
FROM {table} m
JOIN temp.intermediates_hold_names h ON h.name = m.{name_column}
WHERE m.user_id = ? AND m.is_intermediate = TRUE;
@@ -286,7 +304,10 @@ class IntermediatesRecordsSqlite:
AND h.expires_at > STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')
) THEN 'active'
WHEN m.created_at > STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', '-{RECENT_GRACE_SECONDS} seconds')
- THEN 'recent'
+ OR m.{name_column} IN (
+ SELECT name FROM temp.intermediates_session_media
+ WHERE kind = '{kind}' AND released_at IS NOT NULL
+ ) THEN 'recent'
WHEN EXISTS (
SELECT 1 FROM media_references r WHERE r.media_kind = '{kind}' AND r.media_name = m.{name_column}
) THEN 'referenced'
@@ -356,15 +377,17 @@ class IntermediatesRecordsSqlite:
)
cursor.execute(
"INSERT OR IGNORE INTO temp.intermediates_active_media (kind, name) "
- "SELECT kind, name FROM temp.intermediates_session_media;"
+ "SELECT kind, name FROM temp.intermediates_session_media WHERE released_at IS NULL;"
)
# 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.
+ def summarize(
+ self, user_ids: Optional[Collection[str]]
+ ) -> dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]]:
+ """Aggregates the intermediates of ``user_ids`` (None: everyone) 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).
@@ -372,12 +395,19 @@ class IntermediatesRecordsSqlite:
rows: dict[tuple[str, Optional[str]], dict[MediaKind, ScopeCounts]] = defaultdict(
lambda: {"image": ScopeCounts(), "video": ScopeCounts()}
)
+ owners = sorted(user_ids) if user_ids is not None else None
+ # Owner chunks partition the GROUP BY, so their rows never need merging.
+ owner_chunks: list[Optional[list[str]]] = (
+ [owners[start : start + _MAX_SQL_VARIABLES] for start in range(0, len(owners), _MAX_SQL_VARIABLES)]
+ if owners is not None
+ else [None]
+ )
with self._db.transaction() as cursor:
self._prepare(cursor)
- for kind in ("image", "video"):
+ for kind, chunk in ((kind, chunk) for kind in ("image", "video") for chunk in owner_chunks):
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 []
+ owner_filter = f"AND m.user_id IN ({','.join('?' for _ in chunk)})" if chunk is not None else ""
+ params: list[object] = list(chunk) if chunk is not None else []
cursor.execute(
f"""--sql
SELECT user_id, project_key, cls, COUNT(*) AS n,
@@ -561,8 +591,34 @@ class IntermediatesRecordsSqlite:
candidates.extend(self._to_candidates(cursor.fetchall()))
return candidates
+ def page_intermediates(
+ self, kind: MediaKind, *, after_rowid: int, limit: int
+ ) -> tuple[list[IntermediateCandidate], Optional[int]]:
+ """One page of every intermediate in insertion order, classified, and the rowid to resume after.
+
+ Paging by rowid classifies each row once however many are kept, where re-querying for the
+ next safe batch would re-classify every kept row in front of it. None means no rows remain.
+ """
+ table, name_column, _ = _TABLES[kind]
+ with self._db.transaction() as cursor:
+ self._prepare(cursor)
+ cursor.execute(
+ f"""--sql
+ SELECT m.rowid, m.{name_column}, {self._classification_sql(kind)}, m.file_size_bytes, m.user_id, NULL
+ FROM {table} m
+ WHERE m.is_intermediate = TRUE AND m.rowid > ?
+ ORDER BY m.rowid
+ LIMIT ?;
+ """,
+ (after_rowid, limit),
+ )
+ rows = cursor.fetchall()
+ if not rows:
+ return [], None
+ return self._to_candidates(row[1:] for row in rows), cast(int, rows[-1][0])
+
@staticmethod
- def _to_candidates(rows: Iterable[sqlite3.Row]) -> list[IntermediateCandidate]:
+ def _to_candidates(rows: Iterable[Sequence[object]]) -> list[IntermediateCandidate]:
return [
IntermediateCandidate(
name=cast(str, row[0]),
@@ -610,15 +666,19 @@ class IntermediatesRecordsSqlite:
return owners
def get_document_names(self, refs: Sequence[AffectedReference]) -> dict[tuple[str, str, str], str]:
+ """Names of the referencing documents; client state has none."""
+ queries = {
+ "project": "SELECT name FROM projects WHERE user_id = ? AND project_id = ?;",
+ "quarantined_project": "SELECT name FROM orphaned_projects_2026_08_06 WHERE user_id = ? AND project_id = ?;",
+ "workflow": "SELECT name FROM workflow_library WHERE workflow_id = ?;",
+ }
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,))
+ query = queries.get(ref.owner_kind)
+ if query is None:
+ continue
+ cursor.execute(query, (ref.owner_id,) if ref.owner_kind == "workflow" else (ref.user_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])
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 88ca309f57..3981d688dc 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -706,12 +706,15 @@ This behavior is implemented in the runtime scheduler, not in the invocation bod
When an invocation reuses cached media, `BaseInvocation.invoke_internal()` registers a temporary hold for the consuming
queue session before returning the cached output. The intermediates service checks that every referenced image/video
record still exists and registers the hold under the same database lock as cleanup. If cleanup already deleted a
-record, the invocation recomputes its output. Holds remain effective while the session is pending, running or waiting.
+record, the invocation recomputes its output. Holds remain effective while the session is pending, running or
+waiting. A cache hit reuses an old row, so its media is then treated as recent for the usual grace window, counted from
+when cleanup first sees the session ended.
A completed child remains protected while its root workflow is active: completion precedes the transaction that records
its returned media in the parent. Cleanup protects both its cached references and its produced media through that
handoff, including nested calls. Queue history pruning retains these children until their root ends. Other
-terminal/deleted sessions are pruned on the next cache hold or cleanup query. Holds share the cache's process lifetime;
-after restart, persisted queue sessions supply their own media references and the invocation cache is empty.
+terminal/deleted sessions' holds are released on the next cache hold or cleanup query and dropped after that grace.
+Holds share the cache's process lifetime; after restart, persisted queue sessions supply their own media references and
+the invocation cache is empty.
In normal execution, all runtime expansion occurs in `execution_graph` with traceability back to source nodes.
diff --git a/invokeai/app/services/shared/intermediate_delete.py b/invokeai/app/services/shared/intermediate_delete.py
index e3ea321c6f..7c1f75bf3c 100644
--- a/invokeai/app/services/shared/intermediate_delete.py
+++ b/invokeai/app/services/shared/intermediate_delete.py
@@ -1,14 +1,21 @@
-"""Contracts of a conditional intermediate delete shared by the image and video services.
+"""Conditional intermediate deletion 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.
+
+Records go first and files second, with a durable journal spanning the two. Staging files before
+a conditional record delete would need a restore for every survivor, and a concurrent delete of a
+survivor while its files sit staged leaves permanent orphans (PR #9361). Here only the files of
+rows this call removed are touched; if the process dies between the commit and the purge, startup
+recovery finishes the purge for every journalled name whose record is gone.
"""
import sqlite3
+from collections.abc import Callable
from dataclasses import dataclass, field
-from typing import Protocol, Sequence
+from typing import Optional, Protocol, Sequence
class IntermediateDeleteGuard(Protocol):
@@ -20,9 +27,52 @@ 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.
+ whose files could not be removed yet: the record deletion still stands and startup recovery
+ finishes the purge from the journal, so their bytes are not reclaimed yet.
"""
deleted_names: list[str] = field(default_factory=list)
purge_deferred: list[str] = field(default_factory=list)
+
+
+@dataclass(frozen=True)
+class JournaledDeleteAdapter:
+ kind: str
+ begin: Callable[[list[tuple[str, str]]], object]
+ delete_records: Callable[[list[str], Optional[IntermediateDeleteGuard]], list[str]]
+ abandon: Callable[[object], None]
+ commit: Callable[[object, list[str]], None]
+ notify_deleted: Callable[[str], None]
+ log_error: Callable[[str], None]
+
+
+def delete_journaled_intermediates(
+ subfolders: dict[str, str], guard: Optional[IntermediateDeleteGuard], adapter: JournaledDeleteAdapter
+) -> IntermediateDeleteResult:
+ """Deletes the intermediates in ``subfolders`` (name → subfolder) that the guard still allows.
+
+ The caller holds its media kind's deletion lock across the call so a subfolder move or a
+ staged single delete cannot relocate files between the journal and the purge.
+ """
+ token = adapter.begin(list(subfolders.items()))
+ try:
+ deleted = adapter.delete_records(list(subfolders.keys()), guard)
+ except Exception:
+ try:
+ adapter.abandon(token)
+ except Exception as cleanup_error:
+ adapter.log_error(f"Failed to discard the intermediate {adapter.kind} delete journal: {cleanup_error}")
+ raise
+ result = IntermediateDeleteResult(deleted_names=deleted)
+ try:
+ # The journal still lists survivors, which is harmless: recovery re-checks every entry
+ # against the record store.
+ adapter.commit(token, deleted)
+ except Exception as cleanup_error:
+ # The records are committed as gone; a failed purge is retried at startup and must neither
+ # fail the operation nor undo the deletions.
+ adapter.log_error(f"Failed to purge intermediate {adapter.kind} files: {cleanup_error}")
+ result.purge_deferred = list(deleted)
+ for name in deleted:
+ adapter.notify_deleted(name)
+ return result
diff --git a/invokeai/app/services/shared/media_references.py b/invokeai/app/services/shared/media_references.py
index 1c83562a69..ed4c224cdd 100644
--- a/invokeai/app/services/shared/media_references.py
+++ b/invokeai/app/services/shared/media_references.py
@@ -1,9 +1,10 @@
"""Media references named by saved documents.
-Project documents and library workflows are opaque JSON to the server, but the assets they name
-are not opaque to cleanup: an intermediate a saved document still points at (a canvas staging
-candidate, a cropped reference image) must not be collected as garbage. The `media_references`
-table is that index. It is written in the same transaction as the document it describes, so a
+Project documents, library workflows, persisted client state (the legacy editor keeps its canvas
+and reference images only there) and quarantined project documents are opaque JSON to the server,
+but the assets they name are not opaque to cleanup: an intermediate a saved document still points
+at (a canvas staging candidate, a cropped reference image) must not be collected as garbage. The
+`media_references` table is that index. It is written in the same transaction as the document it describes, so a
save and its references are never observed apart, and the extractor here is the one definition of
"names a media asset" for both writers and the migration that backfills existing documents.
@@ -11,11 +12,12 @@ Extraction is deliberately over-inclusive: every string under an image- or video
history included. A false reference retains a file; a missed one deletes something in use.
"""
+import json
import sqlite3
from dataclasses import dataclass, field
from typing import Literal
-MediaReferenceOwnerKind = Literal["project", "workflow"]
+MediaReferenceOwnerKind = Literal["project", "workflow", "client_state", "quarantined_project"]
MediaKind = Literal["image", "video"]
IMAGE_NAME_KEYS = frozenset({"imageName", "image_name"})
@@ -25,6 +27,8 @@ VIDEO_NAME_KEYS = frozenset({"videoName", "video_name"})
# one and is not worth a row.
_MAX_NAME_LENGTH = 255
+_NAME_KEY_MARKERS = tuple(f'"{key}"' for key in (*IMAGE_NAME_KEYS, *VIDEO_NAME_KEYS))
+
@dataclass
class MediaReferences:
@@ -62,6 +66,17 @@ def extract_media_references(document: object) -> MediaReferences:
return references
+def extract_media_references_from_json(document_json: str) -> MediaReferences:
+ """Like `extract_media_references` for serialized JSON; malformed JSON names nothing."""
+ # Most client-state values name no media; skip parsing them.
+ if not any(marker in document_json for marker in _NAME_KEY_MARKERS):
+ return MediaReferences()
+ try:
+ return extract_media_references(json.loads(document_json))
+ except ValueError:
+ return MediaReferences()
+
+
def replace_media_references(
cursor: sqlite3.Cursor,
*,
@@ -102,7 +117,7 @@ def create_media_references_table(cursor: sqlite3.Cursor) -> None:
cursor.execute(
"""--sql
CREATE TABLE IF NOT EXISTS media_references (
- -- 'project' or 'workflow'
+ -- A MediaReferenceOwnerKind
owner_kind TEXT NOT NULL,
-- The owning account; project ids are unique per user, not globally.
user_id TEXT NOT NULL,
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_23_index_client_state_references.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_23_index_client_state_references.py
new file mode 100644
index 0000000000..bd34f3fc54
--- /dev/null
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_23_index_client_state_references.py
@@ -0,0 +1,72 @@
+"""Index the media that persisted client state and quarantined projects name.
+
+The legacy editor keeps its canvas layers and reference images only in `client_state`, as
+intermediates, and `orphaned_projects_2026_08_06` holds project documents kept for repair. Both are
+now `media_references` owners, so cleanup no longer classifies their media as unused. Replacing
+each owner's rows makes a re-run harmless. Expired browser holds are swept on every hold write, so
+they get an index of their own.
+"""
+
+import sqlite3
+from logging import Logger
+
+from invokeai.app.services.shared.media_references import (
+ MediaReferenceOwnerKind,
+ extract_media_references_from_json,
+ replace_media_references,
+)
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration
+
+
+class IndexClientStateReferencesCallback:
+ def __init__(self, logger: Logger) -> None:
+ self._logger = logger
+
+ def __call__(self, cursor: sqlite3.Cursor) -> None:
+ cursor.execute(
+ "CREATE INDEX IF NOT EXISTS idx_intermediates_browser_holds_expires_at "
+ "ON intermediates_browser_holds(expires_at);"
+ )
+ indexed = 0
+ if _table_exists(cursor, "client_state"):
+ # Rows of a departed account (a cascade that never fired) would pin their media forever:
+ # only account deletion clears client-state references.
+ live = " WHERE user_id IN (SELECT user_id FROM users)" if _table_exists(cursor, "users") else ""
+ indexed += self._index_rows(cursor, "client_state", f"SELECT user_id, key, value FROM client_state{live};")
+ if _table_exists(cursor, "orphaned_projects_2026_08_06"):
+ indexed += self._index_rows(
+ cursor, "quarantined_project", "SELECT user_id, project_id, data FROM orphaned_projects_2026_08_06;"
+ )
+ if indexed:
+ self._logger.info(f"Indexed media references of {indexed} client state value(s) and quarantined project(s)")
+
+ @staticmethod
+ def _index_rows(cursor: sqlite3.Cursor, owner_kind: MediaReferenceOwnerKind, select: str) -> int:
+ # A second cursor streams the rows; the writes run on `cursor`, which would discard a
+ # result set being iterated.
+ reader = cursor.connection.cursor()
+ reader.execute(select)
+ indexed = 0
+ for user_id, owner_id, document_json in reader:
+ references = extract_media_references_from_json(document_json if isinstance(document_json, str) else "")
+ if references.is_empty():
+ continue
+ replace_media_references(
+ cursor, owner_kind=owner_kind, user_id=user_id, owner_id=owner_id, references=references
+ )
+ indexed += 1
+ reader.close()
+ return indexed
+
+
+def _table_exists(cursor: sqlite3.Cursor, name: str) -> bool:
+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?;", (name,))
+ return cursor.fetchone() is not None
+
+
+def build_migration(logger: Logger) -> Migration:
+ return Migration(
+ id="2026_09_23_index_client_state_references",
+ depends_on="2026_09_23_track_queue_session_revision",
+ callback=IndexClientStateReferencesCallback(logger),
+ )
diff --git a/invokeai/app/services/users/users_default.py b/invokeai/app/services/users/users_default.py
index 328abf70fc..bc3ac08f33 100644
--- a/invokeai/app/services/users/users_default.py
+++ b/invokeai/app/services/users/users_default.py
@@ -263,10 +263,13 @@ class UserService(UserServiceBase):
cursor.execute("BEGIN IMMEDIATE")
self._assert_not_last_admin(cursor, user_id, is_deleting=True)
cursor.execute("DELETE FROM users WHERE user_id = ?", (user_id,))
- # Projects cascade with the account; the media references their documents held would
- # otherwise protect a departed account's intermediates from every cleanup forever.
- # Workflows do not cascade, so their references stay with them.
- cursor.execute("DELETE FROM media_references WHERE user_id = ? AND owner_kind = 'project'", (user_id,))
+ # Projects and client state cascade with the account; the media references they held
+ # would otherwise protect a departed account's intermediates from every cleanup forever.
+ # Workflows and quarantined projects do not cascade, so their references stay with them.
+ cursor.execute(
+ "DELETE FROM media_references WHERE user_id = ? AND owner_kind IN ('project', 'client_state')",
+ (user_id,),
+ )
def authenticate(self, email: str, password: str) -> UserDTO | None:
"""Authenticate user credentials."""
diff --git a/invokeai/app/services/video_records/video_records_base.py b/invokeai/app/services/video_records/video_records_base.py
index 69421feeb8..fd3dd0d067 100644
--- a/invokeai/app/services/video_records/video_records_base.py
+++ b/invokeai/app/services/video_records/video_records_base.py
@@ -117,7 +117,7 @@ class VideoRecordStorageBase(ABC):
@abstractmethod
def set_file_sizes_bytes(self, sizes: dict[str, int]) -> None:
- """Records many measured sizes in one transaction."""
+ """Records many measured sizes in one transaction, leaving rows that already have a size."""
pass
@abstractmethod
diff --git a/invokeai/app/services/video_records/video_records_sqlite.py b/invokeai/app/services/video_records/video_records_sqlite.py
index 078d8cca3b..d5c6df6801 100644
--- a/invokeai/app/services/video_records/video_records_sqlite.py
+++ b/invokeai/app/services/video_records/video_records_sqlite.py
@@ -103,8 +103,10 @@ class SqliteVideoRecordStorage(VideoRecordStorageBase):
return
with self._db.transaction() as cursor:
try:
+ # Backfill only fills gaps: the writer's own measurement, taken after the file exists,
+ # wins over one taken before it was written.
cursor.executemany(
- "UPDATE videos SET file_size_bytes = ? WHERE video_name = ?;",
+ "UPDATE videos SET file_size_bytes = ? WHERE video_name = ? AND file_size_bytes IS NULL;",
[(size, name) for name, size in sizes.items()],
)
except sqlite3.Error as e:
diff --git a/invokeai/app/services/videos/videos_default.py b/invokeai/app/services/videos/videos_default.py
index 80419307f0..b24cd772e9 100644
--- a/invokeai/app/services/videos/videos_default.py
+++ b/invokeai/app/services/videos/videos_default.py
@@ -13,7 +13,12 @@ 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.intermediate_delete import (
+ IntermediateDeleteGuard,
+ IntermediateDeleteResult,
+ JournaledDeleteAdapter,
+ delete_journaled_intermediates,
+)
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 (
@@ -415,27 +420,19 @@ class VideoService(VideoServiceABC):
subfolders = records.get_subfolders(video_names)
if not subfolders:
return IntermediateDeleteResult()
-
- # Journal the live paths before deleting records. The guard decides inside that transaction
- # which records still qualify; a promoted or newly protected video retains its files.
- token = files.begin_delete(list(subfolders.items()))
- try:
- deleted = records.delete_intermediates_by_names(list(subfolders.keys()), guard=guard)
- except Exception:
- try:
- files.abandon_delete(token)
- except Exception as cleanup_error:
- self.__invoker.services.logger.error(f"Failed to discard pending video deletion: {cleanup_error}")
- raise
- result = IntermediateDeleteResult(deleted_names=deleted)
- try:
- files.commit_delete(token, video_names=deleted)
- except Exception as cleanup_error:
- self.__invoker.services.logger.error(f"Failed to purge intermediate video files: {cleanup_error}")
- result.purge_deferred = list(deleted)
- for name in deleted:
- self._on_deleted(name)
- return result
+ return delete_journaled_intermediates(
+ subfolders,
+ guard,
+ JournaledDeleteAdapter(
+ kind="video",
+ begin=files.begin_delete,
+ delete_records=lambda names, g: records.delete_intermediates_by_names(names, guard=g),
+ abandon=files.abandon_delete,
+ commit=lambda token, names: files.commit_delete(token, video_names=names),
+ notify_deleted=self._on_deleted,
+ log_error=self.__invoker.services.logger.error,
+ ),
+ )
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/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 3cff674f35..fd9267803f 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -5995,7 +5995,7 @@
"get": {
"tags": ["images"],
"summary": "Get Intermediates Count",
- "description": "Gets the count of intermediate images. Non-admin users only see their own intermediates.",
+ "description": "Counts the intermediate images a clear would delete. Non-admin users only see their own intermediates.\n\nActive, recent and referenced images are left out, as `DELETE /intermediates` keeps them.",
"operationId": "get_intermediates_count",
"responses": {
"200": {
@@ -49225,17 +49225,42 @@
"properties": {
"kind": {
"type": "string",
- "enum": ["project", "workflow"],
- "title": "Kind"
+ "enum": ["project", "workflow", "client_state", "quarantined_project"],
+ "title": "Kind",
+ "description": "`client_state` is the legacy editor's persisted state; `quarantined_project` is a project kept for repair"
},
"user_id": {
"type": "string",
"title": "User Id"
},
+ "user_display_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "User Display Name",
+ "description": "The owner's display name, if known"
+ },
+ "user_email": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "User Email",
+ "description": "The owner's email, if known"
+ },
"owner_id": {
"type": "string",
"title": "Owner Id",
- "description": "The project or workflow id"
+ "description": "The project or workflow id, or the client state key"
},
"name": {
"anyOf": [
@@ -49355,7 +49380,7 @@
"referenced": {
"type": "integer",
"title": "Referenced",
- "description": "Named by a saved project or workflow: kept by safe mode",
+ "description": "Named by a saved document: kept by safe mode",
"default": 0
},
"active": {
@@ -49655,13 +49680,7 @@
},
"type": "array",
"title": "Affected Documents",
- "description": "Documents a force clear would break, limited to those the caller may see"
- },
- "affected_documents_hidden": {
- "type": "integer",
- "title": "Affected Documents Hidden",
- "description": "Affected documents belonging to accounts the caller may not inspect",
- "default": 0
+ "description": "Documents a force clear would break. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own"
}
},
"type": "object",
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index ef8000032c..a23d20e0cc 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -1295,7 +1295,9 @@ export type paths = {
};
/**
* Get Intermediates Count
- * @description Gets the count of intermediate images. Non-admin users only see their own intermediates.
+ * @description Counts the intermediate images a clear would delete. Non-admin users only see their own intermediates.
+ *
+ * Active, recent and referenced images are left out, as `DELETE /intermediates` keeps them.
*/
get: operations["get_intermediates_count"];
put?: never;
@@ -20628,14 +20630,25 @@ export type components = {
IntermediatesAffectedDocument: {
/**
* Kind
+ * @description `client_state` is the legacy editor's persisted state; `quarantined_project` is a project kept for repair
* @enum {string}
*/
- kind: "project" | "workflow";
+ kind: "project" | "workflow" | "client_state" | "quarantined_project";
/** User Id */
user_id: string;
+ /**
+ * User Display Name
+ * @description The owner's display name, if known
+ */
+ user_display_name?: string | null;
+ /**
+ * User Email
+ * @description The owner's email, if known
+ */
+ user_email?: string | null;
/**
* Owner Id
- * @description The project or workflow id
+ * @description The project or workflow id, or the client state key
*/
owner_id: string;
/**
@@ -20724,7 +20737,7 @@ export type components = {
safe?: number;
/**
* Referenced
- * @description Named by a saved project or workflow: kept by safe mode
+ * @description Named by a saved document: kept by safe mode
* @default 0
*/
referenced?: number;
@@ -20934,15 +20947,9 @@ export type components = {
impact: components["schemas"]["IntermediatesImpact"];
/**
* Affected Documents
- * @description Documents a force clear would break, limited to those the caller may see
+ * @description Documents a force clear would break. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own
*/
affected_documents?: components["schemas"]["IntermediatesAffectedDocument"][];
- /**
- * Affected Documents Hidden
- * @description Affected documents belonging to accounts the caller may not inspect
- * @default 0
- */
- affected_documents_hidden?: number;
};
/** IntermediatesPreviewRequest */
IntermediatesPreviewRequest: {
diff --git a/tests/app/routers/test_intermediates.py b/tests/app/routers/test_intermediates.py
index 5e8cf4d88c..904020ea7c 100644
--- a/tests/app/routers/test_intermediates.py
+++ b/tests/app/routers/test_intermediates.py
@@ -232,7 +232,8 @@ def test_legacy_clear_keeps_its_shape_and_the_safety_policy(
_seed_intermediate(mock_invoker, "referenced.png", user1)
mock_invoker.services.project_records.create(user1, "P", {"imageName": "referenced.png"})
- assert client.get("/api/v1/images/intermediates", headers=_auth(user1_token)).json() == 2
+ # The count is what the clear would delete, so the legacy button settles at zero.
+ assert client.get("/api/v1/images/intermediates", headers=_auth(user1_token)).json() == 1
assert (
client.delete("/api/v1/images/intermediates", headers=_auth(user1_token)).status_code
== status.HTTP_403_FORBIDDEN
@@ -241,4 +242,5 @@ def test_legacy_clear_keeps_its_shape_and_the_safety_policy(
cleared = client.delete("/api/v1/images/intermediates", headers=_auth(admin_token))
assert cleared.status_code == 200
assert cleared.json() == 1
- assert client.get("/api/v1/images/intermediates", headers=_auth(user1_token)).json() == 1
+ assert client.get("/api/v1/images/intermediates", headers=_auth(user1_token)).json() == 0
+ assert mock_invoker.services.image_records.get("referenced.png").is_intermediate
diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.py
index 2f2ca91e58..586f46f719 100644
--- a/tests/app/services/intermediates/test_intermediates_service.py
+++ b/tests/app/services/intermediates/test_intermediates_service.py
@@ -20,7 +20,7 @@ from invokeai.app.services.image_records.image_records_common import (
ImageRecordNotFoundException,
ResourceOrigin,
)
-from invokeai.app.services.intermediates import intermediates_default
+from invokeai.app.services.intermediates import intermediates_default, intermediates_measurement
from invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller
from invokeai.app.services.intermediates.intermediates_common import (
IntermediatesIdempotencyConflictError,
@@ -163,6 +163,16 @@ 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 _end_cached_media_grace(service: IntermediatesService, invoker: Invoker) -> None:
+ """Lets the recency grace of cached media whose consuming sessions have ended run out."""
+ service._records.summarize(None)
+ with invoker.services.image_records._db.transaction() as cursor:
+ cursor.execute(
+ "UPDATE temp.intermediates_session_media SET released_at = '2000-01-01 00:00:00.000' "
+ "WHERE released_at IS NOT NULL;"
+ )
+
+
def _wait(
service: IntermediatesService, operation_id: str, caller: IntermediatesCaller = ALICE
) -> IntermediatesOperation:
@@ -331,7 +341,7 @@ def test_summary_triggers_measurement_of_unmeasured_sizes(invoker: Invoker, serv
def test_measurement_retries_when_an_unmeasured_file_is_still_too_new(
invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
) -> None:
- monkeypatch.setattr(intermediates_default, "MEASURE_MIN_AGE_SECONDS", 1)
+ monkeypatch.setattr(intermediates_measurement, "MEASURE_MIN_AGE_SECONDS", 1)
_seed_image(invoker, "young.png", created_at=None)
invoker.services.image_records.set_file_size_bytes("young.png", None)
@@ -388,26 +398,33 @@ def test_safe_cleanup_deletes_only_safe_items_and_reports_what_it_kept(
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")
+ project = _project(
+ invoker,
+ "alice",
+ "Drafts",
+ {"stagingArea": {"pendingImages": [{"imageName": "staged.png"}, {"imageName": "shared.png"}]}},
+ )
+ workflow = invoker.services.workflow_records.create(_workflow_naming("shared.png"), user_id="bob")
_seed_image(invoker, "staged.png", project_id=project, size=40)
+ _seed_image(invoker, "shared.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
+ # Bob's workflow is not Alice's to break: the media it names is kept, not merely undescribed.
+ assert (preview.impact.delete_images, preview.impact.keep_referenced_images) == (1, 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.impact.delete_images == 2
+ assert {
+ (doc.kind, doc.owner_id, doc.references, doc.user_display_name) for doc in admin_preview.affected_documents
+ } == {
+ ("project", project, 2, "Alice"),
+ ("workflow", workflow.workflow_id, 1, "Bob"),
}
- assert admin_preview.affected_documents_hidden == 0
started = service.start_operation(
IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
@@ -415,7 +432,25 @@ def test_force_cleanup_deletes_referenced_items_but_never_active_or_recent(
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")
+ assert all(_exists(invoker, name) for name in ("shared.png", "active.png", "fresh.png"))
+
+
+def test_force_cleanup_keeps_media_another_account_references_after_the_preview(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ project = _project(invoker, "alice", "Drafts", {"layers": [{"imageName": "staged.png"}]})
+ _seed_image(invoker, "staged.png", project_id=project)
+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)
+ assert preview.impact.delete_images == 1
+
+ invoker.services.workflow_records.create(_workflow_naming("staged.png"), user_id="bob")
+ started = service.start_operation(
+ IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE
+ )
+ operation = _wait(service, started.operation_id)
+
+ assert operation.progress.retained_images == 1
+ assert _exists(invoker, "staged.png")
def _workflow_naming(image_name: str):
@@ -564,7 +599,9 @@ def test_admins_can_clear_everyone_and_a_chosen_account(invoker: Invoker, servic
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:
+def test_a_demoted_admin_stops_at_the_next_batch(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.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")
@@ -1236,8 +1273,8 @@ def test_large_single_row_clears_in_bounded_batches_past_protected_items(
@pytest.mark.parametrize("cleanup_wins_race", [False, True])
def test_running_graph_keeps_cached_media_or_recomputes_if_cleanup_won(
- invoker, service, monkeypatch, cleanup_wins_race
-):
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch, cleanup_wins_race: bool
+) -> None:
from threading import Event
from invokeai.app.invocations.image import BlankImageInvocation, ImageCropInvocation
@@ -1325,12 +1362,15 @@ def test_running_graph_keeps_cached_media_or_recomputes_if_cleanup_won(
with services.image_records._db.transaction() as cursor:
cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (second.item_id,))
if not cleanup_wins_race:
+ _end_cached_media_grace(service, invoker)
_, completed = _run(service, ALICE, _owner("alice"))
assert completed.progress.deleted_images == 1
@pytest.mark.parametrize("mode", ["safe", "force"])
-def test_cached_media_holds_guard_frozen_targets_until_all_consuming_sessions_end(invoker, service, mode):
+def test_cached_media_holds_guard_frozen_targets_until_all_consuming_sessions_end(
+ invoker: Invoker, service: IntermediatesService, mode: str
+) -> None:
from invokeai.app.services.shared.media_references import MediaReferences
_seed_image(invoker, "cached.png")
@@ -1353,11 +1393,15 @@ def test_cached_media_holds_guard_frozen_targets_until_all_consuming_sessions_en
assert preview.impact.keep_active_images == preview.impact.keep_active_videos == 1
with invoker.services.image_records._db.transaction() as cursor:
cursor.execute("UPDATE session_queue SET status = 'canceled' WHERE item_id = ?", (second,))
+ preview, _ = _run(service, ALICE, _owner("alice"), mode=mode)
+ # A cache hit reused old rows; the grace a fresh output gets now runs from the session's end.
+ assert preview.impact.keep_recent_images == preview.impact.keep_recent_videos == 1
+ _end_cached_media_grace(service, invoker)
_, completed = _run(service, ALICE, _owner("alice"), mode=mode)
assert completed.progress.deleted_images == completed.progress.deleted_videos == 1
-def test_missing_cached_media_does_not_leave_a_partial_hold(invoker, service):
+def test_missing_cached_media_does_not_leave_a_partial_hold(invoker: Invoker, service: IntermediatesService) -> None:
from invokeai.app.services.shared.media_references import MediaReferences
_seed_image(invoker, "survivor.png")
@@ -1371,7 +1415,9 @@ def test_missing_cached_media_does_not_leave_a_partial_hold(invoker, service):
@pytest.mark.parametrize("mode", ["safe", "force"])
@pytest.mark.parametrize("reload_records", [False, True])
-def test_completed_child_media_survives_until_its_root_finishes(invoker, service, mode, reload_records):
+def test_completed_child_media_survives_until_its_root_finishes(
+ invoker: Invoker, service: IntermediatesService, mode: str, reload_records: bool
+) -> None:
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
from invokeai.app.invocations.fields import ImageField, VideoField
from invokeai.app.invocations.workflow_return import WorkflowReturnOutput
@@ -1433,6 +1479,7 @@ def test_completed_child_media_survives_until_its_root_finishes(invoker, service
queue.record_workflow_call_child_completion(root_id, child.item_id, output.values)
queue.cancel_queue_item(root_id)
+ _end_cached_media_grace(service, invoker)
_, completed = _run(service, ALICE, _owner("alice"), mode=mode)
assert completed.progress.deleted_images == 2
assert completed.progress.deleted_videos == 1
@@ -1441,7 +1488,9 @@ def test_completed_child_media_survives_until_its_root_finishes(invoker, service
service.stop()
-def test_completed_nested_child_keeps_media_while_its_root_is_active(invoker, service):
+def test_completed_nested_child_keeps_media_while_its_root_is_active(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
from invokeai.app.services.shared.media_references import MediaReferences
root = _enqueue_row(invoker, session_id="root", status="waiting")
@@ -1460,11 +1509,14 @@ def test_completed_nested_child_keeps_media_while_its_root_is_active(invoker, se
with invoker.services.image_records._db.transaction() as cursor:
cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (root,))
+ _end_cached_media_grace(service, invoker)
_, completed = _run(service, ALICE, _owner("alice"))
assert completed.progress.deleted_images == completed.progress.deleted_videos == 1
-def test_child_protection_does_not_scan_unrelated_completed_history(invoker, service):
+def test_child_protection_does_not_scan_unrelated_completed_history(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
root = _enqueue_row(invoker, session_id="root", status="waiting")
_enqueue_row(invoker, session_id="child", status="completed", root_item_id=root, parent_item_id=root)
_seed_image(invoker, "produced.png", session_id="child")
@@ -1500,7 +1552,9 @@ def test_child_protection_does_not_scan_unrelated_completed_history(invoker, ser
@pytest.mark.parametrize("bulk", [False, True])
-def test_video_cleanup_cannot_purge_files_during_staged_deletion(invoker, service, monkeypatch, bulk):
+def test_video_cleanup_cannot_purge_files_during_staged_deletion(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch, bulk: bool
+) -> None:
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from threading import Event
@@ -1553,3 +1607,142 @@ def test_video_cleanup_cannot_purge_files_during_staged_deletion(invoker, servic
assert not video_path.exists()
assert not thumbnail_path.exists()
assert not list(video_path.parent.glob(".delete_*"))
+
+
+# ── documents outside projects and workflows ──
+
+
+def test_legacy_client_state_protects_its_canvas_media_until_it_changes(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ client_state = invoker.services.client_state_persistence
+ client_state.set_by_key("alice", "canvas", '{"layers": [{"image": {"image_name": "layer.png"}}]}')
+ _seed_image(invoker, "layer.png")
+
+ preview, operation = _run(service, ALICE, _owner("alice"))
+ assert (preview.impact.delete_images, preview.impact.keep_referenced_images) == (0, 1)
+ force = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)
+ assert [(doc.kind, doc.owner_id, doc.name) for doc in force.affected_documents] == [
+ ("client_state", "canvas", None)
+ ]
+
+ client_state.set_by_key("alice", "canvas", '{"layers": []}')
+ _, operation = _run(service, ALICE, _owner("alice"))
+ assert operation.progress.deleted_images == 1
+
+
[email protected]("forget", ["key", "account"])
+def test_forgetting_client_state_releases_its_media(
+ invoker: Invoker, service: IntermediatesService, forget: str
+) -> None:
+ client_state = invoker.services.client_state_persistence
+ client_state.set_by_key("alice", "canvas", '{"image_name": "layer.png"}')
+ _seed_image(invoker, "layer.png")
+
+ if forget == "key":
+ client_state.delete_by_key("alice", "canvas")
+ else:
+ client_state.delete("alice")
+
+ _, operation = _run(service, ALICE, _owner("alice"))
+ assert operation.progress.deleted_images == 1
+
+
+def test_quarantined_projects_are_named_when_a_force_clear_would_break_them(
+ invoker: Invoker, service: IntermediatesService
+) -> None:
+ from invokeai.app.services.shared.media_references import MediaReferences, replace_media_references
+
+ _seed_image(invoker, "recovered.png")
+ with invoker.services.image_records._db.transaction() as cursor:
+ cursor.execute(
+ "CREATE TABLE IF NOT EXISTS orphaned_projects_2026_08_06 (project_id TEXT, user_id TEXT, name TEXT,"
+ " data TEXT, PRIMARY KEY (user_id, project_id));"
+ )
+ cursor.execute("INSERT INTO orphaned_projects_2026_08_06 VALUES ('p1', 'alice', 'Before boards', '{}');")
+ replace_media_references(
+ cursor,
+ owner_kind="quarantined_project",
+ user_id="alice",
+ owner_id="p1",
+ references=MediaReferences(images={"recovered.png"}),
+ )
+
+ safe, _ = _run(service, ALICE, _owner("alice"))
+ assert safe.impact.keep_referenced_images == 1
+ force = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ADMIN)
+ assert [(doc.kind, doc.name) for doc in force.affected_documents] == [("quarantined_project", "Before boards")]
+
+
+# ── bounds ──
+
+
+def test_previewing_in_a_loop_cannot_evict_another_accounts_pending_preview(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "MAX_PREVIEWS", 3)
+ _seed_image(invoker, "safe.png")
+ pending = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ADMIN)
+
+ alice_previews = [
+ service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)
+ for _ in range(intermediates_default.MAX_PREVIEWS_PER_CALLER + 2)
+ ]
+
+ service.start_operation(IntermediatesOperationRequest(preview_id=pending.preview_id, idempotency_key="a"), ADMIN)
+ with pytest.raises(IntermediatesPreviewNotFoundError):
+ service.start_operation(
+ IntermediatesOperationRequest(preview_id=alice_previews[0].preview_id, idempotency_key="b"), ALICE
+ )
+
+
+def test_legacy_clear_deletes_every_safe_image_in_bounded_batches(
+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 2)
+ # A whole page of kept rows in front must neither stop the clear nor be re-read per batch.
+ _project(invoker, "alice", "P", {"images": [{"imageName": "kept.png"}, {"imageName": "also-kept.png"}]})
+ _seed_image(invoker, "kept.png")
+ _seed_image(invoker, "also-kept.png")
+ for index in range(5):
+ _seed_image(invoker, f"safe-{index}.png")
+
+ batch_sizes: list[int] = []
+ delete = invoker.services.images.delete_intermediates_by_names
+ monkeypatch.setattr(
+ invoker.services.images,
+ "delete_intermediates_by_names",
+ lambda names, guard: batch_sizes.append(len(names)) or delete(names, guard),
+ )
+
+ assert service.count_safe_images(ADMIN) == 5
+ assert service.clear_all_images_now(ADMIN) == 5
+ assert batch_sizes == [2, 2, 1]
+ assert service.count_safe_images(ADMIN) == 0
+ assert _exists(invoker, "kept.png") and _exists(invoker, "also-kept.png")
+
+
+def test_background_measurement_never_overwrites_the_writers_size(invoker: Invoker) -> None:
+ _seed_image(invoker, "written.png", size=10)
+
+ invoker.services.image_records.set_file_sizes_bytes({"written.png": 0})
+
+ assert invoker.services.image_records.get("written.png").file_size_bytes == 10
+
+
+def test_browser_holds_expire_shortly_after_their_last_refresh(invoker: Invoker, service: IntermediatesService) -> None:
+ from invokeai.app.services.intermediates.intermediates_common import (
+ BROWSER_HOLD_TTL_SECONDS,
+ IntermediatesBrowserHoldRequest,
+ )
+
+ _seed_image(invoker, "held.png")
+ service.replace_browser_hold(ALICE, "tab", IntermediatesBrowserHoldRequest(images=["held.png"]))
+
+ with invoker.services.image_records._db.transaction() as cursor:
+ cursor.execute(
+ "SELECT (JULIANDAY(expires_at) - JULIANDAY('now')) * 86400 FROM intermediates_browser_holds"
+ " WHERE media_name = 'held.png';"
+ )
+ remaining = cursor.fetchone()[0]
+ assert remaining == pytest.approx(BROWSER_HOLD_TTL_SECONDS, abs=60)
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_23_index_client_state_references.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_23_index_client_state_references.py
new file mode 100644
index 0000000000..fd885c5eeb
--- /dev/null
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_23_index_client_state_references.py
@@ -0,0 +1,72 @@
+"""Client state and quarantined projects become media reference owners on existing databases."""
+
+import json
+import sqlite3
+from logging import getLogger
+
+from invokeai.app.services.shared.media_references import create_media_references_table
+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_23_index_client_state_references import (
+ build_migration,
+)
+
+
+def _database() -> sqlite3.Cursor:
+ connection = sqlite3.connect(":memory:")
+ cursor = connection.cursor()
+ create_media_references_table(cursor)
+ cursor.execute(
+ "CREATE TABLE intermediates_browser_holds (user_id TEXT, lease_id TEXT, media_kind TEXT, media_name TEXT,"
+ " expires_at TEXT);"
+ )
+ cursor.execute("CREATE TABLE client_state (user_id TEXT, key TEXT, value TEXT, PRIMARY KEY (user_id, key));")
+ cursor.execute("CREATE TABLE users (user_id TEXT PRIMARY KEY);")
+ cursor.executemany("INSERT INTO users VALUES (?);", [("alice",), ("bob",)])
+ cursor.execute(
+ "CREATE TABLE orphaned_projects_2026_08_06 (project_id TEXT, user_id TEXT, name TEXT, data TEXT,"
+ " PRIMARY KEY (user_id, project_id));"
+ )
+ return cursor
+
+
+def _rows(cursor: sqlite3.Cursor) -> set[tuple[str, ...]]:
+ cursor.execute("SELECT owner_kind, user_id, owner_id, media_kind, media_name FROM media_references;")
+ return set(cursor.fetchall())
+
+
+def test_indexes_legacy_canvas_state_and_quarantined_projects_idempotently() -> None:
+ cursor = _database()
+ canvas = {"rasterLayers": [{"objects": [{"image": {"image_name": "layer.png"}}]}]}
+ cursor.executemany(
+ "INSERT INTO client_state VALUES (?, ?, ?);",
+ [
+ ("alice", "canvas", json.dumps(canvas)),
+ ("alice", "ui", '{"panel": "left"}'),
+ ("bob", "broken", "{"),
+ ("departed", "canvas", json.dumps(canvas)),
+ ],
+ )
+ cursor.execute(
+ "INSERT INTO orphaned_projects_2026_08_06 VALUES ('p1', 'gone', 'Old', ?);",
+ (json.dumps({"layers": [{"videoName": "clip.mp4"}]}),),
+ )
+
+ build_migration(getLogger(__name__)).callback(cursor)
+ build_migration(getLogger(__name__)).callback(cursor)
+
+ assert _rows(cursor) == {
+ ("client_state", "alice", "canvas", "image", "layer.png"),
+ ("quarantined_project", "gone", "p1", "video", "clip.mp4"),
+ }
+ cursor.execute("SELECT name FROM sqlite_master WHERE name = 'idx_intermediates_browser_holds_expires_at';")
+ assert cursor.fetchone() is not None
+
+
+def test_databases_without_either_table_migrate() -> None:
+ connection = sqlite3.connect(":memory:")
+ cursor = connection.cursor()
+ create_media_references_table(cursor)
+ cursor.execute("CREATE TABLE intermediates_browser_holds (media_kind TEXT, media_name TEXT, expires_at TEXT);")
+
+ build_migration(getLogger(__name__)).callback(cursor)
+
+ assert _rows(cursor) == set()
diff --git a/tests/app/services/users/test_user_service.py b/tests/app/services/users/test_user_service.py
index 6099ac4c4e..11b58390a1 100644
--- a/tests/app/services/users/test_user_service.py
+++ b/tests/app/services/users/test_user_service.py
@@ -182,6 +182,21 @@ def test_delete_user(user_service: UserService):
assert retrieved_user is None
+def test_delete_user_drops_references_only_of_documents_that_cascade(user_service: UserService, db: SqliteDatabase):
+ user = user_service.create(
+ UserCreateRequest(email="[email protected]", display_name="T", password="TestPassword123")
+ )
+ db._conn.executemany(
+ "INSERT INTO media_references VALUES (?, ?, 'owner', 'image', 'a.png');",
+ [(kind, user.user_id) for kind in ("project", "client_state", "workflow", "quarantined_project")],
+ )
+
+ user_service.delete(user.user_id)
+
+ rows = db._conn.execute("SELECT owner_kind FROM media_references ORDER BY owner_kind;").fetchall()
+ assert [row[0] for row in rows] == ["quarantined_project", "workflow"]
+
+
def test_authenticate_valid_credentials(user_service: UserService):
"""Test authenticating with valid credentials."""
user_data = UserCreateRequest(