Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(intermediates): run cleanups in memory over the live scope
Josh Corbettb8685a4a64de
diff --git a/invokeai/app/api/routers/intermediates.py b/invokeai/app/api/routers/intermediates.pyindex c43ded658a..768cc0cd52 100644--- a/invokeai/app/api/routers/intermediates.py+++ b/invokeai/app/api/routers/intermediates.py@@ -10,8 +10,8 @@ from invokeai.app.services.intermediates.intermediates_base import Intermediatesfrom invokeai.app.services.intermediates.intermediates_common import (BROWSER_HOLD_LEASE_ID_PATTERN,IntermediatesBrowserHoldRequest,- IntermediatesIdempotencyConflictError,IntermediatesOperation,+ IntermediatesOperationList,IntermediatesOperationNotFoundError,IntermediatesOperationRequest,IntermediatesPreview,@@ -39,7 +39,7 @@ def _translate(error: Exception) -> HTTPException:return HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(error))if isinstance(error, (IntermediatesPreviewNotFoundError, IntermediatesOperationNotFoundError)):return HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(error) or "Not found")- if isinstance(error, (IntermediatesIdempotencyConflictError, IntermediatesUnavailableError)):+ if isinstance(error, IntermediatesUnavailableError):return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error))raise error@@ -83,13 +83,23 @@ def create_intermediates_preview(current_user: CurrentUserOrDefault,request: IntermediatesPreviewRequest = Body(description="What to clear and how"),) -> IntermediatesPreview:- """Freezes the targets a cleanup would act on and reports its impact. Previews expire unused."""+ """Reports what a cleanup would delete and keep, and fixes the instant its recency is judged at. Previews expire unused."""try:return ApiDependencies.invoker.services.intermediates.create_preview(request, _caller(current_user))- except (IntermediatesScopeForbiddenError, IntermediatesScopeInvalidError, IntermediatesUnavailableError) as error:+ except (IntermediatesScopeForbiddenError, IntermediatesScopeInvalidError) as error:raise _translate(error)+@intermediates_router.get(+ "/operations", operation_id="list_intermediates_operations", response_model=IntermediatesOperationList+)+def list_intermediates_operations(current_user: CurrentUserOrDefault) -> IntermediatesOperationList:+ """The caller's running and recently settled cleanups, newest first. Operations do not survive a server restart."""+ return IntermediatesOperationList(+ items=ApiDependencies.invoker.services.intermediates.list_operations(_caller(current_user))+ )++@intermediates_router.post("/operations",operation_id="start_intermediates_operation",@@ -100,14 +110,10 @@ def start_intermediates_operation(current_user: CurrentUserOrDefault,request: IntermediatesOperationRequest = Body(description="The confirmed preview"),) -> IntermediatesOperation:- """Starts the cleanup a preview described. Repeating a request with its idempotency key returns the same operation."""+ """Starts the cleanup a preview described. A preview is confirmed at most once; list operations to find a run whose response was lost."""try:return ApiDependencies.invoker.services.intermediates.start_operation(request, _caller(current_user))- except (- IntermediatesPreviewNotFoundError,- IntermediatesIdempotencyConflictError,- IntermediatesUnavailableError,- ) as error:+ except (IntermediatesPreviewNotFoundError, IntermediatesUnavailableError) as error:raise _translate(error)@@ -124,27 +130,6 @@ def get_intermediates_operation(raise _translate(error)-@intermediates_router.post(- "/operations/{operation_id}/retry",- operation_id="retry_intermediates_operation",- response_model=IntermediatesOperation,- status_code=status.HTTP_202_ACCEPTED,-)-def retry_intermediates_operation(- current_user: CurrentUserOrDefault,- operation_id: str = Path(min_length=1, max_length=64),-) -> IntermediatesOperation:- """Retries exactly the targets a finished operation left unresolved, as a new operation."""- try:- return ApiDependencies.invoker.services.intermediates.retry_operation(operation_id, _caller(current_user))- except (- IntermediatesOperationNotFoundError,- IntermediatesScopeForbiddenError,- IntermediatesUnavailableError,- ) as error:- raise _translate(error)--@intermediates_router.put("/holds/{lease_id}",operation_id="replace_intermediates_browser_hold",diff --git a/invokeai/app/services/intermediates/intermediates_base.py b/invokeai/app/services/intermediates/intermediates_base.pyindex 9edbb02d59..4142bd3a99 100644--- a/invokeai/app/services/intermediates/intermediates_base.py+++ b/invokeai/app/services/intermediates/intermediates_base.py@@ -70,7 +70,8 @@ class IntermediatesServiceBase(ABC):pass@abstractmethod- def retry_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:+ def list_operations(self, caller: IntermediatesCaller) -> list[IntermediatesOperation]:+ """The caller's retained operations, newest first."""pass@abstractmethoddiff --git a/invokeai/app/services/intermediates/intermediates_common.py b/invokeai/app/services/intermediates/intermediates_common.pyindex 3ec1a1fdeb..f1402fafab 100644--- a/invokeai/app/services/intermediates/intermediates_common.py+++ b/invokeai/app/services/intermediates/intermediates_common.py@@ -11,7 +11,7 @@ IntermediatesCleanupMode = Literal["safe", "force"]"""`safe` keeps everything a saved document still references; `force` deletes those too. Neithertouches active work, recent uploads or durable media."""-IntermediatesScopeKind = Literal["selection", "owner", "everyone"]+IntermediatesScopeKind = Literal["selection", "owner", "everyone", "matching"]IntermediatesOperationStatus = Literal["pending", "running", "completed", "failed"]IntermediatesSummarySort = Literal["reclaimable_bytes", "project_name"]@@ -26,14 +26,15 @@ PREVIEW_TTL_SECONDS = 10 * 60# stops protecting its media after this long.BROWSER_HOLD_TTL_SECONDS = 15 * 60MAX_BROWSER_HOLD_NAMES = 50_000-# A lease id is `<holder>` or `<holder>.<part>`: one open editor (tab) is one holder, however many-# parts it splits its hold into.-BROWSER_HOLD_LEASE_ID_PATTERN = r"^[A-Za-z0-9_-]+(\.[A-Za-z0-9_.-]+)?$"-# Open editors one account can hold media for at once; past it every lease of the least recently-# refreshed editor lapses.-MAX_BROWSER_HOLD_EDITORS_PER_USER = 8+# One open editor (tab) holds one lease.+BROWSER_HOLD_LEASE_ID_PATTERN = r"^[A-Za-z0-9_-]+$"+# Leases one account can hold at once; past it the least recently refreshed lease lapses.+MAX_BROWSER_HOLD_LEASES_PER_USER = 8# A force preview lists at most this many broken documents; `affected_documents_total` counts them all.MAX_AFFECTED_DOCUMENTS = 200+# A force preview acknowledges every document it would break by identity; past this many the+# caller narrows the scope instead of the server holding an unbounded set per preview.+MAX_ACKNOWLEDGED_DOCUMENTS = 10_000MediaName = Annotated[str, Field(min_length=1, max_length=255)]@@ -56,6 +57,13 @@ class IntermediatesScopeTarget(BaseModel):class IntermediatesScope(BaseModel):+ """What a cleanup acts on.++ `selection` names rows; `owner` names an account; `everyone` is every account (administrators);+ `matching` is every row the summary filters match, minus `excluded`, resolved by the server so+ a client never has to enumerate rows it has not loaded.+ """+kind: IntermediatesScopeKind = Field(description="How the targets were chosen")targets: list[IntermediatesScopeTarget] = Field(default_factory=list, max_length=1000, description="The selected rows; only read for a `selection` scope"@@ -64,7 +72,17 @@ class IntermediatesScope(BaseModel):default=None,min_length=1,max_length=255,- description="The account whose rows are targeted by an `owner` scope",+ description=(+ "The account an `owner` scope targets, or the owner filter of a `matching` scope"+ " (null: the caller's account, or every account for administrators)"+ ),+ )+ project_id: Optional[str] = Field(+ default=None, min_length=1, max_length=255, description="`matching` only: the summary's project filter"+ )+ search: Optional[str] = Field(default=None, max_length=200, description="`matching` only: the summary's search")+ excluded: list[IntermediatesScopeTarget] = Field(+ default_factory=list, max_length=1000, description="`matching` only: matching rows to leave out")@@ -159,14 +177,13 @@ class IntermediatesPreview(BaseModel):created_at: datetimeexpires_at: datetimetarget_rows: int = Field(description="Rows the scope resolved to")- has_more_eligible: bool = Field(- default=False, description="More eligible intermediates remain outside this bounded preview batch"- )impact: IntermediatesImpactaffected_documents: list[IntermediatesAffectedDocument] = Field(default_factory=list,description=(- "Documents a force clear would break. A non-administrator's force clear keeps media other accounts'"+ "Documents a force clear would break. Confirming acknowledges these documents: the operation deletes"+ " referenced targets only while every document naming them is acknowledged, so a document saved after"+ " the preview keeps its media. A non-administrator's force clear keeps media other accounts'"" documents name, so these are always the caller's own. Bounded; see `affected_documents_total`"),)@@ -176,8 +193,7 @@ class IntermediatesPreview(BaseModel):class IntermediatesOperationRequest(BaseModel):- preview_id: str = Field(min_length=1, max_length=64)- idempotency_key: str = Field(min_length=1, max_length=255, description="Caller-owned retry key")+ preview_id: str = Field(min_length=1, max_length=64, description="A preview is confirmed at most once")class IntermediatesOperationProgress(BaseModel):@@ -187,7 +203,7 @@ class IntermediatesOperationProgress(BaseModel):deleted_videos: int = Field(default=0)retained_images: int = Field(default=0, description="Targets the final check kept: promoted, protected or gone")retained_videos: int = Field(default=0)- failed_images: int = Field(default=0, description="Targets whose deletion raised; retryable")+ failed_images: int = Field(default=0, description="Targets whose deletion raised; a new cleanup picks them up")failed_videos: int = Field(default=0)reclaimed_bytes: int = Field(default=0, description="Bytes whose files are confirmed removed")unknown_size_count: int = Field(@@ -196,35 +212,33 @@ class IntermediatesOperationProgress(BaseModel):pending_disk_cleanup: int = Field(default=0, description="Deleted records whose files could not be purged yet; the journal retries at startup")- unresolved_images: int = Field(default=0, description="Image targets that failed or were never attempted")- unresolved_videos: int = Field(default=0, description="Video targets that failed or were never attempted")class IntermediatesOperation(BaseModel):+ """A cleanup run. Operations live in server memory: a restart forgets them, and the live policy+ is the retry, so a new preview and confirmation picks up whatever an interrupted run left."""+operation_id: struser_id: str = Field(description="The account that confirmed the operation")mode: IntermediatesCleanupMode- scope: IntermediatesScope+ scope: IntermediatesScope = Field(description="The scope as requested, so a client can request it again")status: IntermediatesOperationStatuscreated_at: datetimestarted_at: Optional[datetime] = Nonecompleted_at: Optional[datetime] = Noneerror: Optional[str] = Field(default=None, description="Why the operation stopped, when it failed")- target_images: int = Field(description="Frozen image targets")- target_videos: int = Field(description="Frozen video targets")- progress: IntermediatesOperationProgress- retried_from_operation_id: Optional[str] = None- retried_by_operation_id: Optional[str] = Field(- default=None, description="The retry that took over this operation's unresolved targets, if any"+ target_images: int = Field(+ description=(+ "Image deletions the preview expected. The scope is paged live, so rows that became deletable"+ " since the preview are collected too and the deleted count may exceed this"+ ))+ target_videos: int = Field(description="Video deletions the preview expected; see `target_images`")+ progress: IntermediatesOperationProgress- @property- def is_retryable(self) -> bool:- return (- self.status in ("completed", "failed")- and self.retried_by_operation_id is None- and (self.progress.unresolved_images > 0 or self.progress.unresolved_videos > 0)- )++class IntermediatesOperationList(BaseModel):+ items: list[IntermediatesOperation] = Field(description="The caller's retained operations, newest first")class IntermediatesPreviewNotFoundError(Exception):@@ -243,9 +257,5 @@ class IntermediatesScopeInvalidError(Exception):"""The scope is malformed for its kind."""-class IntermediatesIdempotencyConflictError(Exception):- """The idempotency key was already used with a different preview."""--class IntermediatesUnavailableError(Exception):"""Cleanup cannot run right now, e.g. image storage maintenance is active."""diff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.pyindex ad9004e868..943da56f6d 100644--- a/invokeai/app/services/intermediates/intermediates_default.py+++ b/invokeai/app/services/intermediates/intermediates_default.py@@ -1,10 +1,12 @@"""The intermediates cleanup engine.-Previews freeze the exact targets a confirmation will act on; nothing created afterwards can join-an operation. Operations run on one background worker in bounded batches, and every batch-re-applies the policy on the deleting transaction, so a target that became active, referenced or-durable since the preview is kept. Operation receipts and unresolved targets persist; a restart-makes interrupted work retryable.+A preview classifies its scope once and freezes the instant recency is judged at; a confirmation+turns it into an operation that pages the same scope live, in bounded batches, on one background+worker. Every batch re-applies the policy on the deleting transaction with the preview's recency+cutoff, so nothing created after the preview is collected and a target that became active,+referenced or durable since the preview is kept. Operations live in memory: a restart forgets+them, and because the live scope is the retry, a new preview and confirmation finishes whatever an+interrupted run left.Lock order, for anyone adding a caller: image mutation lock or video deletion lock → databaselock. Image and video deletion never hold each other's locks; queue and document writers take@@ -17,19 +19,18 @@ import threadingimport timeimport uuidfrom collections import defaultdict-from dataclasses import dataclass, field+from dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom typing import Callable, Optional, Sequence, castfrom invokeai.app.services.intermediates.intermediates_base import IntermediatesCaller, IntermediatesServiceBasefrom invokeai.app.services.intermediates.intermediates_common import (+ MAX_ACKNOWLEDGED_DOCUMENTS,MAX_AFFECTED_DOCUMENTS,PREVIEW_TTL_SECONDS,RECENT_GRACE_SECONDS,IntermediatesAffectedDocument,IntermediatesBrowserHoldRequest,- IntermediatesCleanupMode,- IntermediatesIdempotencyConflictError,IntermediatesImpact,IntermediatesOperation,IntermediatesOperationNotFoundError,@@ -42,7 +43,6 @@ from invokeai.app.services.intermediates.intermediates_common import (IntermediatesScope,IntermediatesScopeForbiddenError,IntermediatesScopeInvalidError,- IntermediatesScopeTarget,IntermediatesSummary,IntermediatesSummarySort,IntermediatesSummaryTotals,@@ -52,30 +52,25 @@ from invokeai.app.services.intermediates.intermediates_measurement import Intermfrom invokeai.app.services.intermediates.intermediates_records_sqlite import (IntermediatesRecordsSqlite,MediaKind,- OperationReceipt,- OperationTarget,ReferenceOwner,- ReferenceOwners,+ ScopeTarget,)from invokeai.app.services.invoker import Invokerfrom invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuard, IntermediateDeleteResultfrom invokeai.app.services.shared.media_references import MediaReferenceOwnerKind, MediaReferencesDELETE_BATCH_SIZE = 200-# Receipts and unresolved targets are budgeted per confirming account. Up to the global ceiling,-# which bounds memory, one account's interrupted cleanups never block another's; past it, ten-# accounts at their full budget refuse new cleanup for everyone until they retry.-MAX_RETAINED_OPERATIONS_PER_CALLER = 50-MAX_RETAINED_TARGETS_PER_CALLER = 100_000-MAX_RETAINED_TARGETS = 1_000_000-# Operations run one at a time; the per-account share keeps one account from filling the queue.+# Operations run one at a time; one running cleanup per account keeps one account from filling+# the queue, and the UI offers no second Delete while one runs anyway.MAX_ACTIVE_OPERATIONS = 8-MAX_ACTIVE_OPERATIONS_PER_CALLER = 2-MAX_OPERATION_TARGETS = 50_000+MAX_ACTIVE_OPERATIONS_PER_CALLER = 1+# Settled operations stay readable for a while so a reopened manager can show the last result.+MAX_RETAINED_SETTLED_OPERATIONS_PER_CALLER = 5+MAX_RETAINED_OPERATIONS = 200MAX_PREVIEWS = 200MAX_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+# A `matching` scope resolves to explicit rows; past this many the filter is too wide to page.+MAX_RESOLVED_SCOPE_TARGETS = 10_000PROGRESS_EVENT_INTERVAL_SECONDS = 1.0WORKER_STOP_TIMEOUT_SECONDS = 10.0@@ -84,38 +79,34 @@ def _now() -> datetime:return datetime.now(timezone.utc)-def _own_references(references: ReferenceOwners, user_id: str) -> ReferenceOwners:- """Drops the confirmations of other accounts' documents, so the delete guard keeps their media."""- return {name: {owner for owner in owners if owner.user_id == user_id} for name, owners in references.items()}+@dataclass(frozen=True)+class _ResolvedScope:+ """What a scope pages over: an owner (None: everyone) or explicit rows, and whose media it may touch."""--@dataclass-class _KindImpact:- delete: int = 0- keep_referenced: int = 0- keep_active: int = 0- keep_recent: int = 0+ user_id: Optional[str]+ # Plain tuples: a resolved scope may hold thousands of rows and outlives its preview.+ targets: Optional[list[ScopeTarget]]+ allowed_user_ids: Optional[frozenset[str]]@dataclassclass _Preview:dto: IntermediatesPreviewcaller_user_id: str- # Frozen targets with the size known at preview time; sizes are what an operation reclaims.- targets: dict[MediaKind, list[tuple[str, Optional[int]]]]- allowed_user_ids: Optional[frozenset[str]]- confirmed_references: dict[MediaKind, ReferenceOwners]+ scope: _ResolvedScope+ # Recency is judged as of this instant for the whole operation the preview confirms.+ recent_cutoff: str+ # Force mode: the documents whose media the confirmer agreed to break.+ acknowledged: frozenset[ReferenceOwner]@dataclassclass _Operation:dto: IntermediatesOperationcaller: IntermediatesCaller- targets: dict[MediaKind, list[tuple[str, Optional[int]]]]- allowed_user_ids: Optional[frozenset[str]]- confirmed_references: dict[MediaKind, ReferenceOwners] = field(default_factory=lambda: {"image": {}, "video": {}})- # Names whose deletion raised, or that were never attempted; a retry takes exactly these.- unresolved: dict[MediaKind, dict[str, Optional[int]]] = field(default_factory=lambda: {"image": {}, "video": {}})+ scope: _ResolvedScope+ recent_cutoff: str+ acknowledged: frozenset[ReferenceOwner]last_progress_event_at: float = 0.0@@ -126,9 +117,8 @@ class IntermediatesService(IntermediatesServiceBase):self._invoker: Optional[Invoker] = Noneself._lock = threading.Lock()self._previews: dict[str, _Preview] = {}+ # Insertion order is age; retention drops the oldest settled operations first.self._operations: dict[str, _Operation] = {}- self._operation_order: list[str] = []- self._idempotency: dict[tuple[str, str], tuple[str, str]] = {}self._pending: "queue.Queue[str]" = queue.Queue()self._stop = threading.Event()self._measurer = IntermediatesSizeMeasurer(records, lambda: self._services, self._stop, self._logger)@@ -140,33 +130,6 @@ class IntermediatesService(IntermediatesServiceBase):self._invoker = invokerself._stop.clear()self._measurer.reset()- stored_operations, failures = self._records.load_operations()- for operation_id, error in failures:- self._logger.warning(f"Skipping unreadable intermediates operation {operation_id}: {error}")- with self._lock:- for stored in stored_operations:- receipt = stored.receipt- dto = receipt.dto- operation = _Operation(- dto=dto,- caller=IntermediatesCaller(user_id=stored.user_id, is_admin=receipt.caller_is_admin),- targets={"image": [], "video": []},- allowed_user_ids=(- frozenset(receipt.allowed_user_ids) if receipt.allowed_user_ids is not None else None- ),- confirmed_references=stored.confirmed_references,- unresolved=stored.unresolved,- )- if dto.status in ("pending", "running"):- dto.status = "failed"- dto.error = "Server restarted before cleanup finished; retry the remaining targets"- dto.completed_at = _now()- self._records.save_operation(stored.user_id, self._receipt(operation))- self._operations[dto.operation_id] = operation- self._operation_order.append(dto.operation_id)- if stored.idempotency_key is not None and stored.preview_id is not None:- self._idempotency[(stored.user_id, stored.idempotency_key)] = (stored.preview_id, dto.operation_id)- self._prune_operations_locked()def stop(self, invoker: Optional[Invoker] = None) -> None:self._stop.set()@@ -221,36 +184,7 @@ class IntermediatesService(IntermediatesServiceBase):limit: int,project_id: Optional[str] = None,) -> IntermediatesSummary:- owner_filter = self._resolve_owner_filter(caller, owner_id)- 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])-- rows: list[IntermediatesRow] = []- for (user_id, row_project_id), kinds in aggregated.items():- user = users.get(user_id)- project = projects.get((user_id, row_project_id)) if row_project_id is not None else None- rows.append(- IntermediatesRow(- user_id=user_id,- project_id=row_project_id,- user_display_name=user.display_name if user is not None else None,- user_email=user.email if user is not None else None,- project_name=project[0] if project is not None else None,- cover_image_name=project[1] if project is not None else None,- images=kinds["image"].counts,- videos=kinds["video"].counts,- reclaimable_bytes=kinds["image"].safe_bytes + kinds["video"].safe_bytes,- referenced_bytes=kinds["image"].referenced_bytes + kinds["video"].referenced_bytes,- unknown_size_count=kinds["image"].unknown_size_count + kinds["video"].unknown_size_count,- )- )-- if project_id is not None:- rows = [row for row in rows if row.project_id == project_id]- if search:- needle = search.casefold()- rows = [row for row in rows if self._matches(row, needle, include_owner=caller.is_admin)]+ rows = self._summary_rows(caller, owner_id=owner_id, project_id=project_id, search=search)rows.sort(key=lambda row: (row.project_name or "").casefold())if sort == "reclaimable_bytes":@@ -283,6 +217,42 @@ class IntermediatesService(IntermediatesServiceBase):can_manage_everyone=caller.is_admin,)+ def _summary_rows(+ self, caller: IntermediatesCaller, *, owner_id: Optional[str], project_id: Optional[str], search: Optional[str]+ ) -> list[IntermediatesRow]:+ """Every (owner, project) row the caller may see under the given filters, unordered."""+ owner_filter = self._resolve_owner_filter(caller, owner_id)+ 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])++ rows: list[IntermediatesRow] = []+ for (user_id, row_project_id), kinds in aggregated.items():+ user = users.get(user_id)+ project = projects.get((user_id, row_project_id)) if row_project_id is not None else None+ rows.append(+ IntermediatesRow(+ user_id=user_id,+ project_id=row_project_id,+ user_display_name=user.display_name if user is not None else None,+ user_email=user.email if user is not None else None,+ project_name=project[0] if project is not None else None,+ cover_image_name=project[1] if project is not None else None,+ images=kinds["image"].counts,+ videos=kinds["video"].counts,+ reclaimable_bytes=kinds["image"].safe_bytes + kinds["video"].safe_bytes,+ referenced_bytes=kinds["image"].referenced_bytes + kinds["video"].referenced_bytes,+ unknown_size_count=kinds["image"].unknown_size_count + kinds["video"].unknown_size_count,+ )+ )++ if project_id is not None:+ rows = [row for row in rows if row.project_id == project_id]+ if search:+ needle = search.casefold()+ rows = [row for row in rows if self._matches(row, needle, include_owner=caller.is_admin)]+ return rows+@staticmethoddef _matches(row: IntermediatesRow, needle: str, *, include_owner: bool) -> bool:haystacks = [row.project_name or ""]@@ -303,112 +273,100 @@ class IntermediatesService(IntermediatesServiceBase):# region previewsdef create_preview(self, request: IntermediatesPreviewRequest, caller: IntermediatesCaller) -> IntermediatesPreview:- scope = request.scope- allowed = self._authorize_scope(scope, caller)- selection: Optional[list[IntermediatesScopeTarget]] = None- if scope.kind == "selection":- # Duplicate rows would double-count; the order is irrelevant to the SQL.- selection = list({(t.user_id, t.project_id): t for t in scope.targets}.values())- classified = self._records.classify_scope(- user_id=scope.user_id if scope.kind == "owner" else None,- targets=selection,+ scope = self._resolve_scope(request.scope, caller)+ classified = self._records.preview_scope(+ user_id=scope.user_id,+ targets=scope.targets,mode=request.mode,- max_candidates=MAX_OPERATION_TARGETS,+ is_admin=caller.is_admin,+ caller_user_id=caller.user_id,+ max_acknowledged=MAX_ACKNOWLEDGED_DOCUMENTS,)+ if classified.acknowledged_overflow:+ raise IntermediatesScopeInvalidError(+ f"This force delete would break more than {MAX_ACKNOWLEDGED_DOCUMENTS} documents; narrow the scope"+ )- impact = IntermediatesImpact()- kind_impacts: dict[MediaKind, _KindImpact] = {"image": _KindImpact(), "video": _KindImpact()}- # 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, ReferenceOwners] = {"image": {}, "video": {}}- targets: dict[MediaKind, list[tuple[str, Optional[int]]]] = {"image": [], "video": []}- for media_kind, kind_impact in kind_impacts.items():- counts = classified.counts[media_kind]- kind_impact.keep_active = counts.active- kind_impact.keep_recent = counts.recent- if request.mode == "safe":- kind_impact.keep_referenced = counts.referenced- owners = classified.reference_owners[media_kind]- for candidate in classified.candidates[media_kind]:- references = owners.get(candidate.name, set())- if candidate.classification == "referenced" and not (- caller.is_admin or all(owner.user_id == caller.user_id for owner in references)- ):- kind_impact.keep_referenced += 1- continue- kind_impact.delete += 1- if candidate.file_size_bytes is None:- impact.unknown_size_count += 1- else:- impact.reclaimable_bytes += candidate.file_size_bytes- targets[media_kind].append((candidate.name, candidate.file_size_bytes))- if references:- confirmed_references[media_kind][candidate.name] = references- images, videos = kind_impacts["image"], kind_impacts["video"]- impact.delete_images, impact.delete_videos = images.delete, videos.delete- impact.keep_referenced_images, impact.keep_referenced_videos = images.keep_referenced, videos.keep_referenced- impact.keep_active_images, impact.keep_active_videos = images.keep_active, videos.keep_active- impact.keep_recent_images, impact.keep_recent_videos = images.keep_recent, videos.keep_recent- affected, affected_total = self._describe_affected(confirmed_references) if request.mode == "force" else ([], 0)+ images, videos = classified.counts["image"], classified.counts["video"]+ deletable_images, deletable_videos = classified.deletable["image"], classified.deletable["video"]+ impact = IntermediatesImpact(+ delete_images=deletable_images.count,+ delete_videos=deletable_videos.count,+ keep_referenced_images=images.referenced - deletable_images.referenced,+ keep_referenced_videos=videos.referenced - deletable_videos.referenced,+ keep_active_images=images.active,+ keep_active_videos=videos.active,+ keep_recent_images=images.recent,+ keep_recent_videos=videos.recent,+ reclaimable_bytes=deletable_images.measured_bytes + deletable_videos.measured_bytes,+ unknown_size_count=deletable_images.unknown_size_count + deletable_videos.unknown_size_count,+ )+ affected = self._describe_affected(classified.acknowledged) if request.mode == "force" else []created = _now()dto = IntermediatesPreview(preview_id=uuid.uuid4().hex,mode=request.mode,- scope=scope,+ scope=request.scope,created_at=created,expires_at=created + timedelta(seconds=PREVIEW_TTL_SECONDS),- target_rows=len(selection) if selection is not None else len(classified.rows),+ target_rows=len(scope.targets) if scope.targets is not None else len(classified.rows),impact=impact,- has_more_eligible=classified.has_more,affected_documents=affected,- affected_documents_total=affected_total,+ affected_documents_total=len(classified.acknowledged),)with self._lock:self._previews[dto.preview_id] = _Preview(dto=dto,caller_user_id=caller.user_id,- targets=targets,- allowed_user_ids=allowed,- confirmed_references=confirmed_references,+ scope=scope,+ recent_cutoff=classified.clock.recent_cutoff,+ acknowledged=frozenset(classified.acknowledged),)self._expire_previews_locked(created, keep=dto.preview_id)return dto- def _authorize_scope(self, scope: IntermediatesScope, caller: IntermediatesCaller) -> Optional[frozenset[str]]:- """Returns the accounts the scope may touch, or None for every account."""+ def _resolve_scope(self, scope: IntermediatesScope, caller: IntermediatesCaller) -> _ResolvedScope:+ """Authorizes a scope and turns it into what the records layer pages over."""if scope.kind == "everyone":if not caller.is_admin:raise IntermediatesScopeForbiddenError("Only administrators can delete everyone's intermediates")- return None+ return _ResolvedScope(user_id=None, targets=None, allowed_user_ids=None)if scope.kind == "owner":if scope.user_id is None:raise IntermediatesScopeInvalidError("An owner scope names the account whose intermediates to delete")if scope.user_id != caller.user_id and not caller.is_admin:raise IntermediatesScopeForbiddenError("Only administrators can delete another account's intermediates")- return frozenset({scope.user_id})- if not scope.targets:- raise IntermediatesScopeInvalidError("A selection scope names at least one row")- owners = frozenset(target.user_id for target in scope.targets)+ return _ResolvedScope(user_id=scope.user_id, targets=None, allowed_user_ids=frozenset({scope.user_id}))+ if scope.kind == "matching":+ owner_id = self._resolve_owner_filter(caller, scope.user_id)+ rows = self._summary_rows(caller, owner_id=owner_id, project_id=scope.project_id, search=scope.search)+ excluded = {(target.user_id, target.project_id) for target in scope.excluded}+ targets = [(row.user_id, row.project_id) for row in rows if (row.user_id, row.project_id) not in excluded]+ if not targets:+ raise IntermediatesScopeInvalidError("No rows match the filter")+ if len(targets) > MAX_RESOLVED_SCOPE_TARGETS:+ raise IntermediatesScopeInvalidError(+ f"More than {MAX_RESOLVED_SCOPE_TARGETS} rows match the filter; narrow it"+ )+ else:+ if not scope.targets:+ raise IntermediatesScopeInvalidError("A selection scope names at least one row")+ # Duplicate rows would double-count; the order is irrelevant to the SQL.+ targets = list(dict.fromkeys((t.user_id, t.project_id) for t in scope.targets))+ owners = frozenset(user_id for user_id, _ in targets)if not caller.is_admin and owners != frozenset({caller.user_id}):raise IntermediatesScopeForbiddenError("Only administrators can delete another account's intermediates")- return owners-- def _describe_affected(- self, confirmed_references: dict[MediaKind, ReferenceOwners]- ) -> tuple[list[IntermediatesAffectedDocument], int]:- """The documents a force clear breaks, bounded to the first few by kind and name, and how many there are."""- counts: dict[ReferenceOwner, int] = defaultdict(int)- for owners in confirmed_references.values():- for refs_for_name in owners.values():- for owner in refs_for_name:- counts[owner] += 1- names = self._records.get_document_names(counts)+ return _ResolvedScope(user_id=None, targets=targets, allowed_user_ids=owners)++ def _describe_affected(self, acknowledged: dict[ReferenceOwner, int]) -> list[IntermediatesAffectedDocument]:+ """The documents a force clear breaks, bounded to the first few by kind and name."""+ names = self._records.get_document_names(acknowledged)ordered = sorted(- counts, key=lambda owner: (owner.owner_kind, (names.get(owner) or "").casefold(), owner.owner_id)+ acknowledged, key=lambda owner: (owner.owner_kind, (names.get(owner) or "").casefold(), owner.owner_id))[:MAX_AFFECTED_DOCUMENTS]users = self._services.users.get_many(sorted({owner.user_id for owner in ordered}))- documents = [+ return [IntermediatesAffectedDocument(kind=cast(MediaReferenceOwnerKind, owner.owner_kind),user_id=owner.user_id,@@ -416,14 +374,17 @@ class IntermediatesService(IntermediatesServiceBase):user_email=users[owner.user_id].email if owner.user_id in users else None,owner_id=owner.owner_id,name=names.get(owner),- references=counts[owner],+ references=acknowledged[owner],)for owner in ordered]- return documents, len(counts)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."""+ """Drops expired previews, then each caller's oldest past their cap, then the oldest past the global cap.++ ``keep`` (the one just created) always survives. The per-caller cap is applied first, so+ one account previewing in a loop evicts only its own pending confirmations.+ """for pid in [pid for pid, preview in self._previews.items() if preview.dto.expires_at <= now]:del self._previews[pid]by_caller: dict[str, list[str]] = defaultdict(list)@@ -432,27 +393,9 @@ class IntermediatesService(IntermediatesServiceBase):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"])+ evictable = [pid for pid in self._previews if pid != keep]+ for pid in evictable[: max(0, len(self._previews) - MAX_PREVIEWS)]:+ del self._previews[pid]# endregion@@ -462,53 +405,42 @@ class IntermediatesService(IntermediatesServiceBase):self, request: IntermediatesOperationRequest, caller: IntermediatesCaller) -> IntermediatesOperation:with self._lock:- key = (caller.user_id, request.idempotency_key)- settled = self._idempotency.get(key)- if settled is not None:- # A replay creates no work, so it is answered even while cleanup is unavailable.- settled_preview_id, operation_id = settled- if settled_preview_id != request.preview_id:- raise IntermediatesIdempotencyConflictError("Idempotency key was used for a different preview")- return self._operations[operation_id].dto.model_copy(deep=True)-self._require_cleanup_available()- self._require_active_capacity_locked(caller.user_id)self._expire_previews_locked(_now())preview = self._previews.get(request.preview_id)+ # A consumed preview answers "not found" even while its run is still active, so a client+ # whose start response was lost learns to look the run up rather than to wait.if preview is None or preview.caller_user_id != caller.user_id:raise IntermediatesPreviewNotFoundError("Preview expired or unknown; request a new one")- self._require_operation_capacity(- caller.user_id, len(preview.targets["image"]) + len(preview.targets["video"])- )+ self._require_active_capacity_locked(caller.user_id)# Single use: a second confirmation of the same preview must go through a new preview.del self._previews[request.preview_id]-- operation = self._register_operation_locked(- caller=caller,+ dto = IntermediatesOperation(+ operation_id=uuid.uuid4().hex,+ user_id=caller.user_id,mode=preview.dto.mode,scope=preview.dto.scope,- targets=preview.targets,- allowed_user_ids=preview.allowed_user_ids,- confirmed_references=preview.confirmed_references,- retried_from=None,+ status="pending",+ created_at=_now(),+ target_images=preview.dto.impact.delete_images,+ target_videos=preview.dto.impact.delete_videos,+ progress=IntermediatesOperationProgress(),)- try:- self._records.save_operation(- caller.user_id,- self._receipt(operation),- preview_id=request.preview_id,- idempotency_key=request.idempotency_key,- targets=self._operation_target_rows(operation),- )- except Exception:- self._operations.pop(operation.dto.operation_id)- self._operation_order.remove(operation.dto.operation_id)- self._previews[request.preview_id] = preview- raise- self._idempotency[key] = (request.preview_id, operation.dto.operation_id)- self._prune_operations_locked()- self._enqueue(operation)- return operation.dto.model_copy(deep=True)+ operation = _Operation(+ dto=dto,+ caller=caller,+ scope=preview.scope,+ recent_cutoff=preview.recent_cutoff,+ acknowledged=preview.acknowledged,+ )+ self._operations[dto.operation_id] = operation+ self._retain_operations_locked()+ snapshot = dto.model_copy(deep=True)+ # The pending event goes out before the worker can see the id, so no later event precedes it.+ self._emit(snapshot)+ self._ensure_worker()+ self._pending.put(dto.operation_id)+ return snapshotdef get_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:with self._lock:@@ -517,214 +449,39 @@ class IntermediatesService(IntermediatesServiceBase):raise IntermediatesOperationNotFoundError(operation_id)return operation.dto.model_copy(deep=True)- def retry_operation(self, operation_id: str, caller: IntermediatesCaller) -> IntermediatesOperation:+ def list_operations(self, caller: IntermediatesCaller) -> list[IntermediatesOperation]:with self._lock:- original = self._operations.get(operation_id)- if original is None or (original.caller.user_id != caller.user_id and not caller.is_admin):- raise IntermediatesOperationNotFoundError(operation_id)- if original.dto.status not in ("completed", "failed"):- raise IntermediatesUnavailableError("The operation is still running")- existing_retry = (- self._operations.get(original.dto.retried_by_operation_id)- if original.dto.retried_by_operation_id is not None- else None- )- if existing_retry is not None:- # A duplicated retry request (lost response, double click) must not run the same- # targets twice; the retry that already took them over is the answer.- if existing_retry.caller.user_id != caller.user_id and not caller.is_admin:- raise IntermediatesUnavailableError("Another account already retried this operation")- return existing_retry.dto.model_copy(deep=True)- self._require_cleanup_available()- self._require_active_capacity_locked(caller.user_id)- unresolved = {kind: list(names.items()) for kind, names in original.unresolved.items()}- if not unresolved["image"] and not unresolved["video"]:- raise IntermediatesUnavailableError("The operation has nothing left to retry")- # A retry is authorized as the retrying caller, never as the original one.- self._authorize_scope(original.dto.scope, caller)- self._require_operation_capacity(- caller.user_id, len(unresolved["image"]) + len(unresolved["video"]), replacing=original- )- confirmed_references = original.confirmed_references- if not caller.is_admin:- confirmed_references = {- kind: _own_references(references, caller.user_id)- for kind, references in confirmed_references.items()- }- operation = self._register_operation_locked(- caller=caller,- mode=original.dto.mode,- scope=original.dto.scope,- targets=unresolved,- allowed_user_ids=original.allowed_user_ids,- confirmed_references=confirmed_references,- retried_from=operation_id,- )- original.dto.retried_by_operation_id = operation.dto.operation_id- try:- self._records.save_operation(- caller.user_id,- self._receipt(operation),- linked_operation=self._receipt(original),- targets=self._operation_target_rows(operation),- )- except Exception:- self._operations.pop(operation.dto.operation_id)- self._operation_order.remove(operation.dto.operation_id)- original.dto.retried_by_operation_id = None- raise- original.unresolved = {"image": {}, "video": {}}- original.confirmed_references = {"image": {}, "video": {}}- self._prune_operations_locked()- self._enqueue(operation)- return operation.dto.model_copy(deep=True)-- def _register_operation_locked(- self,- *,- caller: IntermediatesCaller,- mode: IntermediatesCleanupMode,- scope: IntermediatesScope,- targets: dict[MediaKind, list[tuple[str, Optional[int]]]],- allowed_user_ids: Optional[frozenset[str]],- confirmed_references: dict[MediaKind, ReferenceOwners],- retried_from: Optional[str],- ) -> _Operation:- dto = IntermediatesOperation(- operation_id=uuid.uuid4().hex,- user_id=caller.user_id,- mode=mode,- scope=scope,- status="pending",- created_at=_now(),- target_images=len(targets["image"]),- target_videos=len(targets["video"]),- progress=IntermediatesOperationProgress(- unresolved_images=len(targets["image"]), unresolved_videos=len(targets["video"])- ),- retried_from_operation_id=retried_from,- )- operation = _Operation(- dto=dto,- caller=caller,- targets={"image": list(targets["image"]), "video": list(targets["video"])},- allowed_user_ids=allowed_user_ids,- confirmed_references={kind: dict(owners) for kind, owners in confirmed_references.items()},- unresolved={"image": dict(targets["image"]), "video": dict(targets["video"])},- )- self._operations[dto.operation_id] = operation- self._operation_order.append(dto.operation_id)- return operation-- @staticmethod- def _receipt(operation: _Operation) -> OperationReceipt:- return OperationReceipt(- dto=operation.dto,- caller_is_admin=operation.caller.is_admin,- allowed_user_ids=sorted(operation.allowed_user_ids) if operation.allowed_user_ids is not None else None,- )-- @staticmethod- def _operation_target_rows(operation: _Operation) -> list[OperationTarget]:- return [- (kind, name, size, operation.confirmed_references[kind].get(name, set()))- for kind, names in operation.unresolved.items()- for name, size in names.items()- ]-- def _can_prune_operation_locked(self, operation: _Operation) -> bool:- if operation.dto.status not in ("completed", "failed") or any(operation.unresolved.values()):- return False- retry_id = operation.dto.retried_by_operation_id- retry = self._operations.get(retry_id) if retry_id is not None else None- return retry is None or retry.dto.status not in ("pending", "running")+ own = [op for op in self._operations.values() if op.caller.user_id == caller.user_id]+ return [op.dto.model_copy(deep=True) for op in reversed(own)]def _require_active_capacity_locked(self, caller_user_id: str) -> None:active = [op for op in self._operations.values() if op.dto.status in ("pending", "running")]if sum(op.caller.user_id == caller_user_id for op in active) >= MAX_ACTIVE_OPERATIONS_PER_CALLER:- raise IntermediatesUnavailableError("Wait for your running deletions to finish before starting another")+ raise IntermediatesUnavailableError("Wait for your running deletion to finish before starting another")if len(active) >= MAX_ACTIVE_OPERATIONS:raise IntermediatesUnavailableError("Too many cleanup operations are already running")- def _require_operation_capacity(- self, caller_user_id: str, incoming_targets: int, *, replacing: Optional[_Operation] = None- ) -> None:- """Refuses new work past the confirming account's budget; a retry hands its targets over rather than adding."""- outstanding = 0- caller_outstanding = 0- caller_operations: list[_Operation] = []- for operation in self._operations.values():- if operation is replacing:- continue- unresolved = len(operation.unresolved["image"]) + len(operation.unresolved["video"])- outstanding += unresolved- if operation.caller.user_id == caller_user_id:- caller_outstanding += unresolved- caller_operations.append(operation)- if (- caller_outstanding + incoming_targets > MAX_RETAINED_TARGETS_PER_CALLER- or outstanding + incoming_targets > MAX_RETAINED_TARGETS- ):- raise IntermediatesUnavailableError("Retry unresolved cleanup targets before starting more cleanup")- if (- replacing is None- and len(caller_operations) >= MAX_RETAINED_OPERATIONS_PER_CALLER- and not any(self._can_prune_operation_locked(operation) for operation in caller_operations)- ):- raise IntermediatesUnavailableError("Retry unresolved cleanup operations before starting more cleanup")-- def _prune_operations_locked(self) -> None:- """Drops each account's oldest settled receipts past its budget; unresolved ones stay retryable.-- A retry takes the operations it retried with it, even another account's: they point at it- and handed it everything they had left.- """- retained: dict[str, int] = defaultdict(int)- for operation in self._operations.values():- retained[operation.caller.user_id] += 1- evicted: list[str] = []- evicted_set: set[str] = set()- for operation_id in self._operation_order:- operation = self._operations[operation_id]- if (- operation_id in evicted_set- or retained[operation.caller.user_id] <= MAX_RETAINED_OPERATIONS_PER_CALLER- or not self._can_prune_operation_locked(operation)- ):- continue- chain = [operation]- previous_id = operation.dto.retried_from_operation_id- while previous_id is not None and previous_id not in evicted_set:- previous = self._operations.get(previous_id)- if previous is None:- break- chain.append(previous)- previous_id = previous.dto.retried_from_operation_id- if not all(self._can_prune_operation_locked(link) for link in chain):- continue- for link in chain:- retained[link.caller.user_id] -= 1- evicted.append(link.dto.operation_id)- evicted_set.add(link.dto.operation_id)- if not evicted:- return+ def _retain_operations_locked(self) -> None:+ """Drops each account's oldest settled operations past its budget, then the oldest past the global cap."""+ settled_by_caller: dict[str, list[str]] = defaultdict(list)+ for operation_id, operation in self._operations.items():+ if operation.dto.status in ("completed", "failed"):+ settled_by_caller[operation.caller.user_id].append(operation_id)+ for operation_ids in settled_by_caller.values():+ for operation_id in operation_ids[+ : max(0, len(operation_ids) - MAX_RETAINED_SETTLED_OPERATIONS_PER_CALLER)+ ]:+ del self._operations[operation_id]+ settled = [oid for oid, op in self._operations.items() if op.dto.status in ("completed", "failed")]+ for operation_id in settled[: max(0, len(self._operations) - MAX_RETAINED_OPERATIONS)]:+ del self._operations[operation_id]++ def _emit(self, snapshot: IntermediatesOperation) -> None:+ """Events carry snapshots taken under the lock; a failing bus must not take the worker down with it."""try:- self._records.delete_operations(evicted)- except Exception as error:- self._logger.warning(f"Could not prune old intermediates operations: {error}")- return- self._operation_order = [- operation_id for operation_id in self._operation_order if operation_id not in evicted_set- ]- for operation_id in evicted:- self._operations.pop(operation_id)- self._idempotency = {k: v for k, v in self._idempotency.items() if v[1] not in evicted_set}-- def _enqueue(self, operation: _Operation) -> None:- self._ensure_worker()- self._pending.put(operation.dto.operation_id)- # Events carry snapshots: the worker mutates the live DTO as soon as it dequeues the id.- self._services.events.emit_intermediates_operation_changed(operation.dto.model_copy(deep=True))+ self._services.events.emit_intermediates_operation_changed(snapshot)+ except Exception as error: # pragma: no cover - defensive: the worker must survive+ self._logger.error(f"Could not publish intermediates operation {snapshot.operation_id}: {error}")def _require_cleanup_available(self) -> None:image_moves = getattr(self._services, "image_moves", None)@@ -738,17 +495,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")- guard = self._records.make_delete_guard("image", mode="safe", allowed_user_ids=None)+ guard = self._records.make_delete_guard(+ "image", mode="safe", allowed_user_ids=None, caller_user_id=caller.user_id, is_admin=True+ )deleted = 0- 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- )- names = [candidate.name for candidate in page if candidate.classification == "safe"]- if names:+ # Bounded windows keep memory flat however many intermediates exist; the guard re-checks+ # each batch on the deleting transaction.+ for batch in self._records.iter_deletable_batches(+ "image",+ user_id=None,+ targets=None,+ mode="safe",+ is_admin=True,+ caller_user_id=caller.user_id,+ recent_cutoff=None,+ limit=DELETE_BATCH_SIZE,+ ):+ if batch:+ names = [name for name, _ in batch]deleted += len(self._services.images.delete_intermediates_by_names(names, guard).deleted_names)return deleted@@ -782,57 +546,65 @@ class IntermediatesService(IntermediatesServiceBase):self._run(operation)except Exception as error: # pragma: no cover - defensive: the worker must surviveself._logger.error(f"Intermediates operation {operation_id} crashed: {error}", exc_info=True)- try:- self._finish(operation, error=str(error))- except Exception as finish_error:- # A failed receipt write must not strand the rest of the accepted queue.- # The target rows remain durable and are retryable after a restart.- self._logger.error(- f"Could not persist failure for intermediates operation {operation_id}: {finish_error}",- exc_info=True,- )+ self._finish(operation, error=str(error))def _run(self, operation: _Operation) -> None:with self._lock:operation.dto.status = "running"operation.dto.started_at = _now()- self._records.save_operation(operation.caller.user_id, self._receipt(operation))- self._services.events.emit_intermediates_operation_changed(operation.dto.model_copy(deep=True))+ snapshot = operation.dto.model_copy(deep=True)+ self._emit(snapshot)deleters: dict[MediaKind, Callable[[list[str], IntermediateDeleteGuard], IntermediateDeleteResult]] = {"image": self._services.images.delete_intermediates_by_names,"video": self._services.videos.delete_intermediates_by_names,}for media_kind, deleter in deleters.items():- targets = operation.targets[media_kind]- for start in range(0, len(targets), DELETE_BATCH_SIZE):- batch = targets[start : start + DELETE_BATCH_SIZE]+ batches = self._records.iter_deletable_batches(+ media_kind,+ user_id=operation.scope.user_id,+ targets=operation.scope.targets,+ mode=operation.dto.mode,+ is_admin=operation.caller.is_admin,+ caller_user_id=operation.caller.user_id,+ recent_cutoff=operation.recent_cutoff,+ limit=DELETE_BATCH_SIZE,+ )+ for batch in batches:+ # Re-checked per window, including windows of only protected rows, so a stop or a+ # demotion is honoured within one window even across a long protected stretch.halt, is_admin = self._batch_authority(operation)if halt is not None:self._finish(operation, error=halt)return- sizes = dict(batch)- names = [name for name, _ in batch]- confirmed = operation.confirmed_references[media_kind]- batch_references = {name: confirmed[name] for name in names if name in confirmed}- if not is_admin:- batch_references = _own_references(batch_references, operation.caller.user_id)+ if not batch:+ continue+ acknowledged = (+ operation.acknowledged+ if is_admin+ else frozenset(o for o in operation.acknowledged if o.user_id == operation.caller.user_id)+ )guard = self._records.make_delete_guard(media_kind,mode=operation.dto.mode,- allowed_user_ids=operation.allowed_user_ids,- confirmed_references=batch_references,+ allowed_user_ids=operation.scope.allowed_user_ids,+ caller_user_id=operation.caller.user_id,+ is_admin=is_admin,+ recent_cutoff=operation.recent_cutoff,+ acknowledged=acknowledged,)+ names = [name for name, _ in batch]+ sizes = dict(batch)try:result = deleter(names, guard)except Exception as error:self._logger.error(f"Intermediates cleanup batch failed ({media_kind}): {error}", exc_info=True)- self._record_batch(operation, media_kind, batch, deleted=[], deferred=[], failed=names, sizes=sizes)+ self._record_batch(operation, media_kind, names, deleted=[], deferred=[], failed=names, sizes=sizes)continueself._record_batch(operation,media_kind,- batch,+ names,deleted=result.deleted_names,deferred=result.purge_deferred,failed=[],@@ -857,7 +629,7 @@ class IntermediatesService(IntermediatesServiceBase):user = self._services.users.get(operation.caller.user_id)if user is None or not user.is_active:return "The confirming account is no longer active", False- if operation.allowed_user_ids != frozenset({operation.caller.user_id}) and not user.is_admin:+ if operation.scope.allowed_user_ids != frozenset({operation.caller.user_id}) and not user.is_admin:return "The confirming account no longer administers this instance", Falsereturn None, operation.caller.is_admin and user.is_admin@@ -865,7 +637,7 @@ class IntermediatesService(IntermediatesServiceBase):self,operation: _Operation,kind: MediaKind,- batch: list[tuple[str, Optional[int]]],+ names: list[str],*,deleted: Sequence[str],deferred: Sequence[str],@@ -874,11 +646,9 @@ class IntermediatesService(IntermediatesServiceBase):) -> None:deleted_set = set(deleted)deferred_set = set(deferred)- failed_set = set(failed)with self._lock:progress = operation.dto.progress- names = [name for name, _ in batch]- retained = len(names) - len(deleted_set) - len(failed_set)+ retained = len(names) - len(deleted_set) - len(failed)for name in deleted_set:if name in deferred_set:progress.pending_disk_cleanup += 1@@ -888,47 +658,31 @@ class IntermediatesService(IntermediatesServiceBase):progress.unknown_size_count += 1else:progress.reclaimed_bytes += size- unresolved = operation.unresolved[kind]- for name in names:- if name not in failed_set:- unresolved.pop(name, None)- operation.confirmed_references[kind].pop(name, None)if kind == "image":progress.processed_images += len(names)progress.deleted_images += len(deleted_set)- progress.failed_images += len(failed_set)+ progress.failed_images += len(failed)progress.retained_images += retained- progress.unresolved_images = len(unresolved)else:progress.processed_videos += len(names)progress.deleted_videos += len(deleted_set)- progress.failed_videos += len(failed_set)+ progress.failed_videos += len(failed)progress.retained_videos += retained- progress.unresolved_videos = len(unresolved)- self._records.save_operation(- operation.caller.user_id,- self._receipt(operation),- resolved_targets=(kind, [name for name in names if name not in failed_set]),- )# Progress events are coalesced; the final state always goes out from `_finish`.now = time.monotonic()if now - operation.last_progress_event_at < PROGRESS_EVENT_INTERVAL_SECONDS:returnoperation.last_progress_event_at = nowsnapshot = operation.dto.model_copy(deep=True)- self._services.events.emit_intermediates_operation_changed(snapshot)+ self._emit(snapshot)def _finish(self, operation: _Operation, *, error: Optional[str]) -> None:with self._lock:operation.dto.status = "failed" if error is not None else "completed"operation.dto.error = erroroperation.dto.completed_at = _now()- # Only the unresolved names matter after this point; the frozen list is the bulk of an- # operation's memory and would otherwise live for as long as the operation is retained.- operation.targets = {"image": [], "video": []}- self._records.save_operation(operation.caller.user_id, self._receipt(operation))- self._prune_operations_locked()+ self._retain_operations_locked()snapshot = operation.dto.model_copy(deep=True)- self._services.events.emit_intermediates_operation_changed(snapshot)+ self._emit(snapshot)# endregiondiff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.pyindex 30a0edd503..82fee29ab2 100644--- a/invokeai/app/services/intermediates/intermediates_records_sqlite.py+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py@@ -1,7 +1,8 @@"""Storage queries of the intermediates manager.One classification expression decides what every intermediate is under the cleanup policy, and it-is the same SQL whether it aggregates a summary, freezes a preview's targets or guards a delete:+is the same SQL whether it aggregates a summary, describes a preview, pages an operation or guards+a delete:- ``active``: produced or referenced by a pending, waiting or running queue item, or acompleted child of an active root workflow.@@ -11,28 +12,30 @@ is the same SQL whether it aggregates a summary, freezes a preview's targets or- ``referenced``: named by a saved document (`media_references`).- ``safe``: none of the above.+A preview freezes the instant its recency is judged at; the operation it confirms and the guard+on every deleting transaction classify with that same recency cutoff and a live clock for+everything else. Anything created after the preview is newer than its cutoff, so it stays+``recent`` for the whole operation. Cached-output holds are judged the same way by the operation+itself, but the hold table is shared with live-clock callers (summaries, cache hits) that may+sweep a hold once its grace has passed live; that only ever drops a row whose grace is over.+Queue inputs are found by scanning each active item's stored session for media-name keys; thescan is cached per item so a queue of a thousand pending items is parsed once, not per query."""-import jsonimport reimport sqlite3from collections import defaultdictfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezone-from typing import Collection, Iterable, Iterator, Literal, NamedTuple, Optional, Sequence, cast--from pydantic import BaseModel+from typing import Collection, Iterator, Literal, NamedTuple, Optional, Sequence, castfrom invokeai.app.services.intermediates.intermediates_common import (BROWSER_HOLD_TTL_SECONDS,- MAX_BROWSER_HOLD_EDITORS_PER_USER,+ MAX_BROWSER_HOLD_LEASES_PER_USER,RECENT_GRACE_SECONDS,IntermediatesCleanupMode,IntermediatesKindCounts,- IntermediatesOperation,- IntermediatesScopeTarget,)from invokeai.app.services.shared.intermediate_delete import IntermediateDeleteGuardfrom invokeai.app.services.shared.media_references import IMAGE_NAME_KEYS, VIDEO_NAME_KEYS, MediaReferences@@ -40,6 +43,8 @@ from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabaseMediaKind = Literal["image", "video"]Classification = Literal["safe", "referenced", "active", "recent"]+# One row of the manager: (owner, project), project None for the owner's unassigned intermediates.+ScopeTarget = tuple[str, Optional[str]]ACTIVE_QUEUE_STATUSES = ("pending", "in_progress", "waiting")@@ -96,17 +101,11 @@ class _Clock(NamedTuple):recent_cutoff: str-def _clock() -> _Clock:+def _clock(recent_cutoff: Optional[str] = None) -> _Clock:+ """The live clock, or the live clock judging recency as of an earlier preview."""now = _utc_now()- return _Clock(_sql_timestamp(now), _sql_timestamp(now - timedelta(seconds=RECENT_GRACE_SECONDS)))---def _lease_holder(lease_id: str) -> str:- """The editor a lease belongs to: one tab holds several leases named `<holder>.<part>`."""- return lease_id.split(".", 1)[0]---_HOLDER_SQL = "CASE WHEN INSTR(lease_id, '.') > 0 THEN SUBSTR(lease_id, 1, INSTR(lease_id, '.') - 1) ELSE lease_id END"+ live_cutoff = _sql_timestamp(now - timedelta(seconds=RECENT_GRACE_SECONDS))+ return _Clock(_sql_timestamp(now), min(live_cutoff, recent_cutoff) if recent_cutoff is not None else live_cutoff)class ReferenceOwner(NamedTuple):@@ -121,13 +120,6 @@ class ReferenceOwner(NamedTuple):ReferenceOwners = dict[str, set[ReferenceOwner]]-@dataclass(frozen=True)-class IntermediateCandidate:- name: str- classification: Classification- file_size_bytes: Optional[int]--def _add_count(counts: IntermediatesKindCounts, classification: Classification, n: int) -> None:if classification == "safe":counts.safe += n@@ -150,43 +142,29 @@ class ScopeCounts:@dataclass-class ScopeClassification:- """A preview's scope classified once, on one transaction, so its counts and targets agree."""+class DeletableTotals:+ count: int = 0+ referenced: int = 0+ measured_bytes: int = 0+ unknown_size_count: int = 0+++@dataclass+class ScopePreview:+ """A preview's scope classified once, on one transaction and one clock, so its figures agree."""+ clock: _Clock# (owner, project) rows holding any intermediate in scope.rows: set[tuple[str, Optional[str]]] = field(default_factory=set)counts: dict[MediaKind, IntermediatesKindCounts] = field(default_factory=lambda: {"image": IntermediatesKindCounts(), "video": IntermediatesKindCounts()})- # Eligible intermediates, bounded; ``has_more`` says whether the bound cut any off.- candidates: dict[MediaKind, list[IntermediateCandidate]] = field(default_factory=lambda: {"image": [], "video": []})- has_more: bool = False- # Documents naming each referenced candidate; only read for a force clear.- reference_owners: dict[MediaKind, ReferenceOwners] = field(default_factory=lambda: {"image": {}, "video": {}})---class OperationReceipt(BaseModel):- """The persisted receipt of an operation (`intermediates_operations.state_json`)."""-- dto: IntermediatesOperation- caller_is_admin: bool- allowed_user_ids: Optional[list[str]]---@dataclass-class StoredOperation:- """An operation restored at startup: its receipt and the targets it left unresolved."""-- user_id: str- preview_id: Optional[str]- idempotency_key: Optional[str]- receipt: OperationReceipt- unresolved: dict[MediaKind, dict[str, Optional[int]]]- confirmed_references: dict[MediaKind, ReferenceOwners]---# (kind, name, size, confirmed reference owners) of one unresolved operation target.-OperationTarget = tuple[MediaKind, str, Optional[int], set[ReferenceOwner]]+ deletable: dict[MediaKind, DeletableTotals] = field(+ default_factory=lambda: {"image": DeletableTotals(), "video": DeletableTotals()}+ )+ # Force mode: the documents naming the deletable referenced items, with how many each names.+ acknowledged: dict[ReferenceOwner, int] = field(default_factory=dict)+ acknowledged_overflow: bool = Falseclass IntermediatesRecordsSqlite:@@ -278,28 +256,25 @@ class IntermediatesRecordsSqlite:""",(user_id, lease_id, kind, user_id),)- # Past the cap, every lease of the editors refreshed longest ago stops protecting its- # media; an editor that is still open restores its leases on its next refresh. Leases- # are grouped on the user's primary-key range first, so only their ids reach the holder- # grouping.+ # Past the cap, the leases refreshed longest ago stop protecting their media; an editor+ # that is still open restores its lease on its next refresh.cursor.execute(- f"""--sql+ """--sqlWITH leases AS (- SELECT lease_id, {_HOLDER_SQL} AS holder, MAX(expires_at) AS refreshed+ SELECT lease_id, MAX(expires_at) AS refreshedFROM intermediates_browser_holdsWHERE user_id = ?GROUP BY lease_id), lapsed AS (- SELECT holder FROM leases- WHERE holder != ?- GROUP BY holder- ORDER BY MAX(refreshed) DESC, holder+ SELECT lease_id FROM leases+ WHERE lease_id != ?+ ORDER BY refreshed DESC, lease_idLIMIT -1 OFFSET ?)DELETE FROM intermediates_browser_holds- WHERE user_id = ? AND lease_id IN (SELECT lease_id FROM leases WHERE holder IN lapsed);+ WHERE user_id = ? AND lease_id IN (SELECT lease_id FROM lapsed);""",- (user_id, _lease_holder(lease_id), MAX_BROWSER_HOLD_EDITORS_PER_USER - 1, user_id),+ (user_id, lease_id, MAX_BROWSER_HOLD_LEASES_PER_USER - 1, user_id),)def release_browser_hold(self, user_id: str, lease_id: str) -> None:@@ -308,122 +283,6 @@ class IntermediatesRecordsSqlite:"DELETE FROM intermediates_browser_holds WHERE user_id = ? AND lease_id = ?;", (user_id, lease_id))- def load_operations(self) -> tuple[list[StoredOperation], list[tuple[str, Exception]]]:- """Every persisted operation, and the ids of rows that could not be read with why.-- An unreadable row is reported rather than raised, so one bad receipt cannot stop startup;- its rows stay in place for inspection.- """- with self._db.transaction() as cursor:- cursor.execute(- "SELECT operation_id, caller_user_id, preview_id, idempotency_key, state_json "- "FROM intermediates_operations ORDER BY created_at, operation_id;"- )- operations = cursor.fetchall()- cursor.execute(- "SELECT operation_id, media_kind, media_name, size_bytes, confirmed_refs_json "- "FROM intermediates_operation_targets;"- )- targets: dict[str, list[tuple[str, str, Optional[int], str]]] = defaultdict(list)- for operation_id, kind, name, size, refs in cursor.fetchall():- targets[str(operation_id)].append((str(kind), str(name), size, str(refs)))- loaded: list[StoredOperation] = []- failures: list[tuple[str, Exception]] = []- for operation_id, user, preview, key, state_json in operations:- try:- stored = StoredOperation(- user_id=str(user),- preview_id=preview,- idempotency_key=key,- receipt=OperationReceipt.model_validate_json(state_json),- unresolved={"image": {}, "video": {}},- confirmed_references={"image": {}, "video": {}},- )- for kind, name, size, refs_json in targets.get(str(operation_id), []):- if kind not in ("image", "video"):- raise ValueError(f"Unknown media kind {kind!r}")- media_kind = cast(MediaKind, kind)- stored.unresolved[media_kind][name] = size- refs = {ReferenceOwner(*ref) for ref in json.loads(refs_json)}- if refs:- stored.confirmed_references[media_kind][name] = refs- except (ValueError, TypeError) as error:- failures.append((str(operation_id), error))- continue- loaded.append(stored)- return loaded, failures-- def save_operation(- self,- caller_user_id: str,- receipt: OperationReceipt,- *,- preview_id: Optional[str] = None,- idempotency_key: Optional[str] = None,- linked_operation: Optional[OperationReceipt] = None,- targets: Optional[Sequence[OperationTarget]] = None,- resolved_targets: Optional[tuple[MediaKind, Sequence[str]]] = None,- ) -> None:- operation_id = receipt.dto.operation_id- state = receipt.model_dump(mode="json")- target_rows = (- [(operation_id, kind, name, size, json.dumps(sorted(refs))) for kind, name, size, refs in targets]- if targets is not None- else None- )- linked = (- (linked_operation.dto.operation_id, linked_operation.model_dump_json())- if linked_operation is not None- else None- )- with self._db.transaction() as cursor:- cursor.execute(- "INSERT INTO intermediates_operations "- "(operation_id, caller_user_id, preview_id, idempotency_key, state_json, created_at) "- "VALUES (?, ?, ?, ?, ?, ?) "- "ON CONFLICT(operation_id) DO UPDATE SET state_json = excluded.state_json;",- (- operation_id,- caller_user_id,- preview_id,- idempotency_key,- json.dumps(state),- state["dto"]["created_at"],- ),- )- if target_rows is not None:- cursor.executemany(- "INSERT INTO intermediates_operation_targets "- "(operation_id, media_kind, media_name, size_bytes, confirmed_refs_json) VALUES (?, ?, ?, ?, ?);",- target_rows,- )- if resolved_targets is not None:- kind, names = resolved_targets- cursor.executemany(- "DELETE FROM intermediates_operation_targets "- "WHERE operation_id = ? AND media_kind = ? AND media_name = ?;",- [(operation_id, kind, name) for name in names],- )- if linked is not None:- linked_id, linked_state_json = linked- cursor.execute(- "UPDATE intermediates_operations SET state_json = ? WHERE operation_id = ?;",- (linked_state_json, linked_id),- )- cursor.execute("DELETE FROM intermediates_operation_targets WHERE operation_id = ?;", (linked_id,))-- def delete_operations(self, operation_ids: Sequence[str]) -> None:- if not operation_ids:- return- with self._db.transaction() as cursor:- cursor.executemany(- "DELETE FROM intermediates_operation_targets WHERE operation_id = ?;",- [(name,) for name in operation_ids],- )- cursor.executemany(- "DELETE FROM intermediates_operations WHERE operation_id = ?;", [(name,) for name in operation_ids]- )-# region policy expression@staticmethod@@ -454,13 +313,33 @@ class IntermediatesRecordsSqlite:END"""- def _prepare(self, cursor: sqlite3.Cursor) -> _Clock:+ @staticmethod+ def _deletable_sql(+ kind: MediaKind, mode: IntermediatesCleanupMode, *, is_admin: bool, caller_user_id: str+ ) -> tuple[str, list[object]]:+ """What a cleanup may delete, over the classified rows of `_scoped_sql`.++ Force mode adds referenced items, but another account's document is never the caller's to+ break unless the caller administers the instance. Applied in SQL so a bounded page or+ batch is a page of what the caller can actually delete.+ """+ if mode == "safe":+ return "cls = 'safe'", []+ if is_admin:+ return "cls IN ('safe', 'referenced')", []+ return (+ "(cls = 'safe' OR (cls = 'referenced' AND NOT EXISTS ("+ "SELECT 1 FROM media_references r WHERE r.media_kind = ? AND r.media_name = name AND r.user_id != ?)))",+ [kind, caller_user_id],+ )++ def _prepare(self, cursor: sqlite3.Cursor, clock: Optional[_Clock] = None) -> _Clock:"""Makes the transaction's view of active work current, and returns the instant its classifications use.Runs on the caller's transaction so a classification and the enqueue it might race areordered by the database lock, never by a stale cache."""- clock = _clock()+ clock = clock or _clock()self._prepare_session_holds(cursor, clock)cursor.execute("""--sql@@ -532,7 +411,7 @@ class IntermediatesRecordsSqlite:"""table, name_column, _ = _TABLES[kind]return f"""- SELECT m.{name_column} AS name, m.user_id AS user_id,+ SELECT m.rowid AS rowid, m.{name_column} AS name, m.user_id AS user_id,CASE WHEN p.project_id IS NULL THEN NULL ELSE m.project_id END AS project_key,m.file_size_bytes AS file_size_bytes,{cls._classification_sql(kind)} AS cls@@ -681,17 +560,21 @@ class IntermediatesRecordsSqlite:# endregion- # region candidates+ # region scope@classmethoddef _scope_clauses(- cls, *, user_id: Optional[str], targets: Optional[Sequence[IntermediatesScopeTarget]]+ cls,+ *,+ user_id: Optional[str],+ targets: Optional[Sequence[ScopeTarget]],+ per_statement: int = _TARGETS_PER_STATEMENT,) -> list[tuple[str, list[object]]]:"""``AND`` filters (with their parameters) that together cover a scope; each stays under the variable limit."""if targets is not None:clauses: list[tuple[str, list[object]]] = []- for start in range(0, len(targets), _TARGETS_PER_STATEMENT):- predicate, params = cls._scope_predicate(targets[start : start + _TARGETS_PER_STATEMENT])+ for start in range(0, len(targets), per_statement):+ predicate, params = cls._scope_predicate(targets[start : start + per_statement])if predicate:clauses.append((f"AND ({predicate})", params))return clauses@@ -700,98 +583,132 @@ class IntermediatesRecordsSqlite:return [("", [])]@staticmethod- def _scope_predicate(targets: Sequence[IntermediatesScopeTarget]) -> tuple[str, list[object]]:+ def _scope_predicate(targets: Sequence[ScopeTarget]) -> tuple[str, list[object]]:clauses: list[str] = []params: list[object] = []- for target in targets:- if target.project_id is None:+ for user_id, project_id in targets:+ if project_id is None:clauses.append("(m.user_id = ? AND p.project_id IS NULL)")- params.append(target.user_id)+ params.append(user_id)else:clauses.append("(m.user_id = ? AND m.project_id = ? AND p.project_id IS NOT NULL)")- params.extend((target.user_id, target.project_id))+ params.extend((user_id, project_id))return " OR ".join(clauses), params- def classify_scope(+ def preview_scope(self,*,user_id: Optional[str],- targets: Optional[Sequence[IntermediatesScopeTarget]],+ targets: Optional[Sequence[ScopeTarget]],mode: IntermediatesCleanupMode,- max_candidates: int,- ) -> ScopeClassification:- """Counts every intermediate in scope and freezes up to ``max_candidates`` eligible ones, images first.+ is_admin: bool,+ caller_user_id: str,+ max_acknowledged: int,+ ) -> ScopePreview:+ """Counts every intermediate in scope and what a cleanup of ``mode`` may delete.``targets`` narrows to selected rows; otherwise ``user_id`` narrows to an owner, and None- means everyone. One transaction, one instant and one view of active work serve every figure, so a- preview's kept counts and its targets cannot disagree.+ means everyone. One transaction, one instant and one view of active work serve every+ figure, so the kept counts, the deletable totals and the acknowledged documents agree."""clauses = self._scope_clauses(user_id=user_id, targets=targets)- eligible = "('safe', 'referenced')" if mode == "force" else "('safe')"- result = ScopeClassification()- remaining = max_candidateswith self._db.transaction() as cursor:- clock = self._prepare(cursor)- for media_kind in _TABLES:- candidates = result.candidates[media_kind]+ result = ScopePreview(clock=self._prepare(cursor))+ for kind in _TABLES:+ deletable_sql, deletable_params = self._deletable_sql(+ kind, mode, is_admin=is_admin, caller_user_id=caller_user_id+ )+ totals = result.deletable[kind]for clause, params in clauses:- for owner, project_key, cls, n, _, _ in self._aggregate(cursor, clock, media_kind, clause, params):- result.rows.add((owner, project_key))- _add_count(result.counts[media_kind], cls, n)- if len(candidates) > remaining:- continue+ # Parameters bind by textual position: the deletable predicate sits in the+ # SELECT list, ahead of the classified subquery's clock and scope parameters.cursor.execute(- f"SELECT name, cls, file_size_bytes FROM ({self._scoped_sql(media_kind)} {clause}) "- f"WHERE cls IN {eligible} LIMIT ?;",- [*clock, *params, remaining + 1 - len(candidates)],- )- candidates.extend(self._to_candidates(cursor.fetchall()))- if len(candidates) > remaining:- result.has_more = True- del candidates[remaining:]- remaining -= len(candidates)- if mode == "force":- result.reference_owners[media_kind] = self._reference_owners(- cursor, media_kind, [c.name for c in candidates if c.classification == "referenced"]+ f"""--sql+ SELECT user_id, project_key, cls, {deletable_sql} AS deletable, COUNT(*),+ SUM(COALESCE(file_size_bytes, 0)),+ SUM(CASE WHEN file_size_bytes IS NULL THEN 1 ELSE 0 END)+ FROM ({self._scoped_sql(kind)} {clause})+ GROUP BY user_id, project_key, cls, deletable;+ """,+ [*deletable_params, *result.clock, *params],)+ for owner, project_key, cls, deletable, n, total_bytes, unknown in cursor.fetchall():+ result.rows.add((cast(str, owner), cast(Optional[str], project_key)))+ _add_count(result.counts[kind], cast(Classification, cls), cast(int, n))+ if deletable:+ totals.count += cast(int, n)+ totals.measured_bytes += cast(int, total_bytes)+ totals.unknown_size_count += cast(int, unknown)+ if cls == "referenced":+ totals.referenced += cast(int, n)+ if mode == "force":+ cursor.execute(+ f"""--sql+ SELECT r.owner_kind, r.user_id, r.owner_id, COUNT(*)+ FROM ({self._scoped_sql(kind)} {clause}) s+ JOIN media_references r ON r.media_kind = ? AND r.media_name = s.name+ WHERE s.cls = 'referenced' AND {deletable_sql}+ GROUP BY r.owner_kind, r.user_id, r.owner_id;+ """,+ [*result.clock, *params, kind, *deletable_params],+ )+ for owner_kind, owner_user, owner_id, n in cursor.fetchall():+ owner = ReferenceOwner(str(owner_kind), str(owner_user), str(owner_id))+ if owner not in result.acknowledged and len(result.acknowledged) >= max_acknowledged:+ result.acknowledged_overflow = True+ continue+ result.acknowledged[owner] = result.acknowledged.get(owner, 0) + cast(int, n)return result- 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.+ @classmethod+ def _window_sql(cls, kind: MediaKind, scope_clause: str, deletable_sql: str) -> str:+ """One window of classified rows in insertion order. Binds ``[*deletable, *clock, *scope, after_rowid, limit]``."""+ return f"""--sql+ SELECT rowid, name, file_size_bytes, {deletable_sql} AS deletable+ FROM ({cls._scoped_sql(kind)} {scope_clause})+ WHERE rowid > ?+ ORDER BY rowid+ LIMIT ?;"""- table, name_column, _ = _TABLES[kind]- with self._db.transaction() as cursor:- clock = self._prepare(cursor)- cursor.execute(- f"""--sql- SELECT m.rowid, m.{name_column}, {self._classification_sql(kind)}, m.file_size_bytes- FROM {table} m- WHERE m.is_intermediate = TRUE AND m.rowid > ?- ORDER BY m.rowid- LIMIT ?;- """,- (*clock, 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[Sequence[object]]) -> list[IntermediateCandidate]:- return [- IntermediateCandidate(- name=cast(str, row[0]),- classification=cast(Classification, row[1]),- file_size_bytes=cast(Optional[int], row[2]),- )- for row in rows- ]+ def iter_deletable_batches(+ self,+ kind: MediaKind,+ *,+ user_id: Optional[str],+ targets: Optional[Sequence[ScopeTarget]],+ mode: IntermediatesCleanupMode,+ is_admin: bool,+ caller_user_id: str,+ recent_cutoff: Optional[str],+ limit: int,+ ) -> Iterator[list[tuple[str, Optional[int]]]]:+ """The deletable intermediates of a scope in insertion order, a bounded window at a time.++ Each window classifies ``limit`` rows on one short transaction and yields the deletable+ ones (possibly none, so the caller can re-check its authority between windows), so a long+ protected stretch never holds the database for more than one window, and a row is+ classified once per operation however many are kept. Explicit rows are paged one at a+ time: one (owner, project) per statement is an index seek in rowid order, where an OR over+ many rows would sort the whole remaining scope on every window. ``recent_cutoff`` freezes+ recency at the preview that was confirmed; None judges it live.+ """+ deletable_sql, deletable_params = self._deletable_sql(+ kind, mode, is_admin=is_admin, caller_user_id=caller_user_id+ )+ window_sql = None+ for clause, params in self._scope_clauses(user_id=user_id, targets=targets, per_statement=1):+ window_sql = self._window_sql(kind, clause, deletable_sql)+ after_rowid = 0+ while True:+ with self._db.transaction() as cursor:+ clock = self._prepare(cursor, _clock(recent_cutoff))+ cursor.execute(window_sql, [*deletable_params, *clock, *params, after_rowid, limit])+ rows = cursor.fetchall()+ if not rows:+ break+ after_rowid = cast(int, rows[-1][0])+ yield [(cast(str, row[1]), cast(Optional[int], row[2])) for row in rows if row[3]]@staticmethoddef _reference_owners(cursor: sqlite3.Cursor, kind: MediaKind, names: Sequence[str]) -> ReferenceOwners:@@ -808,7 +725,7 @@ class IntermediatesRecordsSqlite:owners.setdefault(str(name), set()).add(ReferenceOwner(str(owner_kind), str(user_id), str(owner_id)))return owners- def get_document_names(self, owners: Iterable[ReferenceOwner]) -> dict[ReferenceOwner, str]:+ def get_document_names(self, owners: Collection[ReferenceOwner]) -> dict[ReferenceOwner, str]:"""Names of the referencing documents, one query per kind and chunk; client state has none."""queries = {"project": "SELECT user_id, project_id, name FROM projects WHERE project_id IN ({});",@@ -849,19 +766,27 @@ class IntermediatesRecordsSqlite:*,mode: IntermediatesCleanupMode,allowed_user_ids: Optional[frozenset[str]],- confirmed_references: Optional[ReferenceOwners] = None,+ caller_user_id: str,+ is_admin: bool,+ recent_cutoff: Optional[str] = None,+ acknowledged: Optional[frozenset[ReferenceOwner]] = None,) -> IntermediateDeleteGuard:"""The final check of a cleanup batch, run on the deleting transaction.- Re-applies the policy to the frozen targets at the moment of deletion: anything that became- active, referenced (safe mode) or non-intermediate since the preview is kept, as is anything- that left the authorized accounts. ``allowed_user_ids`` None means every account.+ Re-applies the policy at the moment of deletion, judging recency as of ``recent_cutoff``:+ anything that became active, referenced (safe mode), non-intermediate or another+ account's since the batch was read is kept. A force clear deletes a referenced item only+ while every document naming it is in ``acknowledged``. ``allowed_user_ids`` None means+ every account."""table, name_column, _ = _TABLES[kind]- deletable = "('safe')" if mode == "safe" else "('safe', 'referenced')"+ deletable_sql, deletable_params = self._deletable_sql(+ kind, mode, is_admin=is_admin, caller_user_id=caller_user_id+ )+ acknowledged_documents = acknowledged or frozenset()def guard(cursor: sqlite3.Cursor, names: Sequence[str]) -> list[str]:- clock = self._prepare(cursor)+ clock = self._prepare(cursor, _clock(recent_cutoff))kept: list[str] = []for start in range(0, len(names), _MAX_SQL_VARIABLES):chunk = list(names[start : start + _MAX_SQL_VARIABLES])@@ -874,19 +799,16 @@ class IntermediatesRecordsSqlite:{self._classification_sql(kind)} AS clsFROM {table} mWHERE m.{name_column} IN ({placeholders}) AND m.is_intermediate = TRUE- ) WHERE cls IN {deletable};+ ) WHERE {deletable_sql};""",- [*clock, *chunk],+ [*clock, *chunk, *deletable_params],)# Ownership is re-read here rather than trusted from the preview.kept.extend(cast(str, row[0])for row in cursor.fetchall()if allowed_user_ids is None or cast(str, row[1]) in allowed_user_ids- if mode != "force"- or current_references.get(cast(str, row[0]), set()).issubset(- (confirmed_references or {}).get(cast(str, row[0]), set())- )+ if current_references.get(cast(str, row[0]), set()).issubset(acknowledged_documents))return keptdiff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_24_drop_intermediates_operations.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_24_drop_intermediates_operations.pynew file mode 100644index 0000000000..4fd4412b4f--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_24_drop_intermediates_operations.py@@ -0,0 +1,22 @@+"""Cleanup operations no longer persist: a run lives in server memory and the live policy is its retry.++The applied `2026_09_22_add_intermediates_management` migration still creates these tables and is+left untouched; this one removes them wherever it ran.+"""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++def _drop_intermediates_operations(cursor: sqlite3.Cursor) -> None:+ cursor.execute("DROP TABLE IF EXISTS intermediates_operation_targets;")+ cursor.execute("DROP TABLE IF EXISTS intermediates_operations;")+++def build_migration() -> Migration:+ return Migration(+ id="2026_09_24_drop_intermediates_operations",+ depends_on="2026_09_23_index_client_state_references",+ callback=_drop_intermediates_operations,+ )diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex edafc21d9d..5b09006c06 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -7661,7 +7661,7 @@"post": {"tags": ["intermediates"],"summary": "Create Intermediates Preview",- "description": "Freezes the targets a cleanup would act on and reports its impact. Previews expire unused.",+ "description": "Reports what a cleanup would delete and keep, and fixes the instant its recency is judged at. Previews expire unused.","operationId": "create_intermediates_preview","requestBody": {"content": {@@ -7704,10 +7704,33 @@}},"/api/v1/intermediates/operations": {+ "get": {+ "tags": ["intermediates"],+ "summary": "List Intermediates Operations",+ "description": "The caller's running and recently settled cleanups, newest first. Operations do not survive a server restart.",+ "operationId": "list_intermediates_operations",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/IntermediatesOperationList"+ }+ }+ }+ }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]+ },"post": {"tags": ["intermediates"],"summary": "Start Intermediates Operation",- "description": "Starts the cleanup a preview described. Repeating a request with its idempotency key returns the same operation.",+ "description": "Starts the cleanup a preview described. A preview is confirmed at most once; list operations to find a run whose response was lost.","operationId": "start_intermediates_operation","requestBody": {"content": {@@ -7796,54 +7819,6 @@}}},- "/api/v1/intermediates/operations/{operation_id}/retry": {- "post": {- "tags": ["intermediates"],- "summary": "Retry Intermediates Operation",- "description": "Retries exactly the targets a finished operation left unresolved, as a new operation.",- "operationId": "retry_intermediates_operation",- "security": [- {- "HTTPBearer": []- }- ],- "parameters": [- {- "name": "operation_id",- "in": "path",- "required": true,- "schema": {- "type": "string",- "minLength": 1,- "maxLength": 64,- "title": "Operation Id"- }- }- ],- "responses": {- "202": {- "description": "Successful Response",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/IntermediatesOperation"- }- }- }- },- "422": {- "description": "Validation Error",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/HTTPValidationError"- }- }- }- }- }- }- },"/api/v1/intermediates/holds/{lease_id}": {"put": {"tags": ["intermediates"],@@ -7864,7 +7839,7 @@"type": "string","minLength": 1,"maxLength": 64,- "pattern": "^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_.-]+)?$",+ "pattern": "^[A-Za-z0-9_-]+$","title": "Lease Id"}}@@ -7913,7 +7888,7 @@"type": "string","minLength": 1,"maxLength": 64,- "pattern": "^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_.-]+)?$",+ "pattern": "^[A-Za-z0-9_-]+$","title": "Lease Id"}}@@ -49419,7 +49394,8 @@"title": "Mode"},"scope": {- "$ref": "#/components/schemas/IntermediatesScope"+ "$ref": "#/components/schemas/IntermediatesScope",+ "description": "The scope as requested, so a client can request it again"},"status": {"type": "string",@@ -49470,38 +49446,15 @@"target_images": {"type": "integer","title": "Target Images",- "description": "Frozen image targets"+ "description": "Image deletions the preview expected. The scope is paged live, so rows that became deletable since the preview are collected too and the deleted count may exceed this"},"target_videos": {"type": "integer","title": "Target Videos",- "description": "Frozen video targets"+ "description": "Video deletions the preview expected; see `target_images`"},"progress": {"$ref": "#/components/schemas/IntermediatesOperationProgress"- },- "retried_from_operation_id": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "title": "Retried From Operation Id"- },- "retried_by_operation_id": {- "anyOf": [- {- "type": "string"- },- {- "type": "null"- }- ],- "title": "Retried By Operation Id",- "description": "The retry that took over this operation's unresolved targets, if any"}},"type": "object",@@ -49516,7 +49469,8 @@"target_videos","progress"],- "title": "IntermediatesOperation"+ "title": "IntermediatesOperation",+ "description": "A cleanup run. Operations live in server memory: a restart forgets them, and the live policy\nis the retry, so a new preview and confirmation picks up whatever an interrupted run left."},"IntermediatesOperationChangedEvent": {"description": "Event model for intermediates_operation_changed.\n\nRouted to the confirming account's room and to admins: the operation's progress is that\naccount's business, and admins see every cleanup so open managers refresh their counts.",@@ -49540,6 +49494,21 @@"title": "IntermediatesOperationChangedEvent","type": "object"},+ "IntermediatesOperationList": {+ "properties": {+ "items": {+ "items": {+ "$ref": "#/components/schemas/IntermediatesOperation"+ },+ "type": "array",+ "title": "Items",+ "description": "The caller's retained operations, newest first"+ }+ },+ "type": "object",+ "required": ["items"],+ "title": "IntermediatesOperationList"+ },"IntermediatesOperationProgress": {"properties": {"processed_images": {@@ -49576,7 +49545,7 @@"failed_images": {"type": "integer","title": "Failed Images",- "description": "Targets whose deletion raised; retryable",+ "description": "Targets whose deletion raised; a new cleanup picks them up","default": 0},"failed_videos": {@@ -49601,18 +49570,6 @@"title": "Pending Disk Cleanup","description": "Deleted records whose files could not be purged yet; the journal retries at startup","default": 0- },- "unresolved_images": {- "type": "integer",- "title": "Unresolved Images",- "description": "Image targets that failed or were never attempted",- "default": 0- },- "unresolved_videos": {- "type": "integer",- "title": "Unresolved Videos",- "description": "Video targets that failed or were never attempted",- "default": 0}},"type": "object",@@ -49624,18 +49581,12 @@"type": "string","maxLength": 64,"minLength": 1,- "title": "Preview Id"- },- "idempotency_key": {- "type": "string",- "maxLength": 255,- "minLength": 1,- "title": "Idempotency Key",- "description": "Caller-owned retry key"+ "title": "Preview Id",+ "description": "A preview is confirmed at most once"}},"type": "object",- "required": ["preview_id", "idempotency_key"],+ "required": ["preview_id"],"title": "IntermediatesOperationRequest"},"IntermediatesPreview": {@@ -49667,12 +49618,6 @@"title": "Target Rows","description": "Rows the scope resolved to"},- "has_more_eligible": {- "type": "boolean",- "title": "Has More Eligible",- "description": "More eligible intermediates remain outside this bounded preview batch",- "default": false- },"impact": {"$ref": "#/components/schemas/IntermediatesImpact"},@@ -49682,7 +49627,7 @@},"type": "array","title": "Affected Documents",- "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. Bounded; see `affected_documents_total`"+ "description": "Documents a force clear would break. Confirming acknowledges these documents: the operation deletes referenced targets only while every document naming them is acknowledged, so a document saved after the preview keeps its media. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own. Bounded; see `affected_documents_total`"},"affected_documents_total": {"type": "integer",@@ -49814,7 +49759,7 @@"properties": {"kind": {"type": "string",- "enum": ["selection", "owner", "everyone"],+ "enum": ["selection", "owner", "everyone", "matching"],"title": "Kind","description": "How the targets were chosen"},@@ -49839,12 +49784,49 @@}],"title": "User Id",- "description": "The account whose rows are targeted by an `owner` scope"+ "description": "The account an `owner` scope targets, or the owner filter of a `matching` scope (null: the caller's account, or every account for administrators)"+ },+ "project_id": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 255,+ "minLength": 1+ },+ {+ "type": "null"+ }+ ],+ "title": "Project Id",+ "description": "`matching` only: the summary's project filter"+ },+ "search": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 200+ },+ {+ "type": "null"+ }+ ],+ "title": "Search",+ "description": "`matching` only: the summary's search"+ },+ "excluded": {+ "items": {+ "$ref": "#/components/schemas/IntermediatesScopeTarget"+ },+ "type": "array",+ "maxItems": 1000,+ "title": "Excluded",+ "description": "`matching` only: matching rows to leave out"}},"type": "object","required": ["kind"],- "title": "IntermediatesScope"+ "title": "IntermediatesScope",+ "description": "What a cleanup acts on.\n\n`selection` names rows; `owner` names an account; `everyone` is every account (administrators);\n`matching` is every row the summary filters match, minus `excluded`, resolved by the server so\na client never has to enumerate rows it has not loaded."},"IntermediatesScopeTarget": {"properties": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 88062379a2..39b1f1310a 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1853,7 +1853,7 @@ export type paths = {put?: never;/*** Create Intermediates Preview- * @description Freezes the targets a cleanup would act on and reports its impact. Previews expire unused.+ * @description Reports what a cleanup would delete and keep, and fixes the instant its recency is judged at. Previews expire unused.*/post: operations["create_intermediates_preview"];delete?: never;@@ -1869,11 +1869,15 @@ export type paths = {path?: never;cookie?: never;};- get?: never;+ /**+ * List Intermediates Operations+ * @description The caller's running and recently settled cleanups, newest first. Operations do not survive a server restart.+ */+ get: operations["list_intermediates_operations"];put?: never;/*** Start Intermediates Operation- * @description Starts the cleanup a preview described. Repeating a request with its idempotency key returns the same operation.+ * @description Starts the cleanup a preview described. A preview is confirmed at most once; list operations to find a run whose response was lost.*/post: operations["start_intermediates_operation"];delete?: never;@@ -1899,26 +1903,6 @@ export type paths = {patch?: never;trace?: never;};- "/api/v1/intermediates/operations/{operation_id}/retry": {- parameters: {- query?: never;- header?: never;- path?: never;- cookie?: never;- };- get?: never;- put?: never;- /**- * Retry Intermediates Operation- * @description Retries exactly the targets a finished operation left unresolved, as a new operation.- */- post: operations["retry_intermediates_operation"];- delete?: never;- options?: never;- head?: never;- patch?: never;- trace?: never;- };"/api/v1/intermediates/holds/{lease_id}": {parameters: {query?: never;@@ -20754,7 +20738,11 @@ export type components = {*/recent?: number;};- /** IntermediatesOperation */+ /**+ * IntermediatesOperation+ * @description A cleanup run. Operations live in server memory: a restart forgets them, and the live policy+ * is the retry, so a new preview and confirmation picks up whatever an interrupted run left.+ */IntermediatesOperation: {/** Operation Id */operation_id: string;@@ -20768,6 +20756,7 @@ export type components = {* @enum {string}*/mode: "safe" | "force";+ /** @description The scope as requested, so a client can request it again */scope: components["schemas"]["IntermediatesScope"];/*** Status@@ -20790,22 +20779,15 @@ export type components = {error?: string | null;/*** Target Images- * @description Frozen image targets+ * @description Image deletions the preview expected. The scope is paged live, so rows that became deletable since the preview are collected too and the deleted count may exceed this*/target_images: number;/*** Target Videos- * @description Frozen video targets+ * @description Video deletions the preview expected; see `target_images`*/target_videos: number;progress: components["schemas"]["IntermediatesOperationProgress"];- /** Retried From Operation Id */- retried_from_operation_id?: string | null;- /**- * Retried By Operation Id- * @description The retry that took over this operation's unresolved targets, if any- */- retried_by_operation_id?: string | null;};/*** IntermediatesOperationChangedEvent@@ -20828,6 +20810,14 @@ export type components = {/** @description The operation's current state */operation: components["schemas"]["IntermediatesOperation"];};+ /** IntermediatesOperationList */+ IntermediatesOperationList: {+ /**+ * Items+ * @description The caller's retained operations, newest first+ */+ items: components["schemas"]["IntermediatesOperation"][];+ };/** IntermediatesOperationProgress */IntermediatesOperationProgress: {/**@@ -20863,7 +20853,7 @@ export type components = {retained_videos?: number;/*** Failed Images- * @description Targets whose deletion raised; retryable+ * @description Targets whose deletion raised; a new cleanup picks them up* @default 0*/failed_images?: number;@@ -20890,28 +20880,14 @@ export type components = {* @default 0*/pending_disk_cleanup?: number;- /**- * Unresolved Images- * @description Image targets that failed or were never attempted- * @default 0- */- unresolved_images?: number;- /**- * Unresolved Videos- * @description Video targets that failed or were never attempted- * @default 0- */- unresolved_videos?: number;};/** IntermediatesOperationRequest */IntermediatesOperationRequest: {- /** Preview Id */- preview_id: string;/**- * Idempotency Key- * @description Caller-owned retry key+ * Preview Id+ * @description A preview is confirmed at most once*/- idempotency_key: string;+ preview_id: string;};/** IntermediatesPreview */IntermediatesPreview: {@@ -20938,16 +20914,10 @@ export type components = {* @description Rows the scope resolved to*/target_rows: number;- /**- * Has More Eligible- * @description More eligible intermediates remain outside this bounded preview batch- * @default false- */- has_more_eligible?: boolean;impact: components["schemas"]["IntermediatesImpact"];/*** Affected Documents- * @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. Bounded; see `affected_documents_total`+ * @description Documents a force clear would break. Confirming acknowledges these documents: the operation deletes referenced targets only while every document naming them is acknowledged, so a document saved after the preview keeps its media. A non-administrator's force clear keeps media other accounts' documents name, so these are always the caller's own. Bounded; see `affected_documents_total`*/affected_documents?: components["schemas"]["IntermediatesAffectedDocument"][];/**@@ -21019,14 +20989,21 @@ export type components = {*/unknown_size_count?: number;};- /** IntermediatesScope */+ /**+ * IntermediatesScope+ * @description What a cleanup acts on.+ *+ * `selection` names rows; `owner` names an account; `everyone` is every account (administrators);+ * `matching` is every row the summary filters match, minus `excluded`, resolved by the server so+ * a client never has to enumerate rows it has not loaded.+ */IntermediatesScope: {/*** Kind* @description How the targets were chosen* @enum {string}*/- kind: "selection" | "owner" | "everyone";+ kind: "selection" | "owner" | "everyone" | "matching";/*** Targets* @description The selected rows; only read for a `selection` scope@@ -21034,9 +21011,24 @@ export type components = {targets?: components["schemas"]["IntermediatesScopeTarget"][];/*** User Id- * @description The account whose rows are targeted by an `owner` scope+ * @description The account an `owner` scope targets, or the owner filter of a `matching` scope (null: the caller's account, or every account for administrators)*/user_id?: string | null;+ /**+ * Project Id+ * @description `matching` only: the summary's project filter+ */+ project_id?: string | null;+ /**+ * Search+ * @description `matching` only: the summary's search+ */+ search?: string | null;+ /**+ * Excluded+ * @description `matching` only: matching rows to leave out+ */+ excluded?: components["schemas"]["IntermediatesScopeTarget"][];};/*** IntermediatesScopeTarget@@ -53401,52 +53393,41 @@ export interface operations {};};};- start_intermediates_operation: {+ list_intermediates_operations: {parameters: {query?: never;header?: never;path?: never;cookie?: never;};- requestBody: {- content: {- "application/json": components["schemas"]["IntermediatesOperationRequest"];- };- };+ requestBody?: never;responses: {/** @description Successful Response */- 202: {- headers: {- [name: string]: unknown;- };- content: {- "application/json": components["schemas"]["IntermediatesOperation"];- };- };- /** @description Validation Error */- 422: {+ 200: {headers: {[name: string]: unknown;};content: {- "application/json": components["schemas"]["HTTPValidationError"];+ "application/json": components["schemas"]["IntermediatesOperationList"];};};};};- get_intermediates_operation: {+ start_intermediates_operation: {parameters: {query?: never;header?: never;- path: {- operation_id: string;- };+ path?: never;cookie?: never;};- requestBody?: never;+ requestBody: {+ content: {+ "application/json": components["schemas"]["IntermediatesOperationRequest"];+ };+ };responses: {/** @description Successful Response */- 200: {+ 202: {headers: {[name: string]: unknown;};@@ -53465,7 +53446,7 @@ export interface operations {};};};- retry_intermediates_operation: {+ get_intermediates_operation: {parameters: {query?: never;header?: never;@@ -53477,7 +53458,7 @@ export interface operations {requestBody?: never;responses: {/** @description Successful Response */- 202: {+ 200: {headers: {[name: string]: unknown;};diff --git a/tests/app/routers/test_intermediates.py b/tests/app/routers/test_intermediates.pyindex 18373a4e23..3552533e8d 100644--- a/tests/app/routers/test_intermediates.py+++ b/tests/app/routers/test_intermediates.py@@ -72,12 +72,12 @@ def test_every_route_requires_authentication(enable_multiuser: Any, client: Testclient.post("/api/v1/intermediates/previews", json={"mode": "safe", "scope": {"kind": "everyone"}}).status_code== status.HTTP_401_UNAUTHORIZED)+ assert client.get("/api/v1/intermediates/operations").status_code == status.HTTP_401_UNAUTHORIZEDassert (- client.post("/api/v1/intermediates/operations", json={"preview_id": "x", "idempotency_key": "k"}).status_code+ client.post("/api/v1/intermediates/operations", json={"preview_id": "x"}).status_code== status.HTTP_401_UNAUTHORIZED)assert client.get("/api/v1/intermediates/operations/x").status_code == status.HTTP_401_UNAUTHORIZED- assert client.post("/api/v1/intermediates/operations/x/retry").status_code == status.HTTP_401_UNAUTHORIZEDassert client.put("/api/v1/intermediates/holds/tab", json={"images": ["x.png"]}).status_code == 401assert client.delete("/api/v1/intermediates/holds/tab").status_code == 401@@ -98,7 +98,7 @@ def test_non_admins_see_only_their_rows_and_cannot_widen_scope(client.get("/api/v1/intermediates/summary", params={"owner_id": other}, headers=_auth(user1_token)).status_code== status.HTTP_403_FORBIDDEN)- for scope in ({"kind": "everyone"}, {"kind": "owner", "user_id": other}):+ for scope in ({"kind": "everyone"}, {"kind": "owner", "user_id": other}, {"kind": "matching", "user_id": other}):response = client.post("/api/v1/intermediates/previews", json={"mode": "safe", "scope": scope}, headers=_auth(user1_token))@@ -109,15 +109,14 @@ def test_non_admins_see_only_their_rows_and_cannot_widen_scope(headers=_auth(user1_token),)assert forged.status_code == status.HTTP_403_FORBIDDEN- malformed = client.post(- "/api/v1/intermediates/previews",- json={"mode": "safe", "scope": {"kind": "owner"}},- headers=_auth(user1_token),- )- assert malformed.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT+ for malformed in ({"kind": "owner"}, {"kind": "matching", "search": "no such project"}):+ response = client.post(+ "/api/v1/intermediates/previews", json={"mode": "safe", "scope": malformed}, headers=_auth(user1_token)+ )+ assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT, response.text-def test_preview_operation_and_retry_flow(+def test_preview_operation_and_list_flow(storage_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str, user2_token: str, admin_token: str) -> None:user1 = _user_id(mock_invoker, "[email protected]")@@ -125,45 +124,43 @@ def test_preview_operation_and_retry_flow(preview = client.post("/api/v1/intermediates/previews",- json={"mode": "safe", "scope": {"kind": "owner", "user_id": user1}},+ json={"mode": "safe", "scope": {"kind": "matching", "excluded": []}},headers=_auth(user1_token),)assert preview.status_code == status.HTTP_201_CREATED, preview.textassert preview.json()["impact"]["delete_images"] == 1+ assert preview.json()["scope"]["kind"] == "matching"preview_id = preview.json()["preview_id"]stolen = client.post(- "/api/v1/intermediates/operations",- json={"preview_id": preview_id, "idempotency_key": "k"},- headers=_auth(user2_token),+ "/api/v1/intermediates/operations", json={"preview_id": preview_id}, headers=_auth(user2_token))assert stolen.status_code == status.HTTP_404_NOT_FOUNDstarted = client.post(- "/api/v1/intermediates/operations",- json={"preview_id": preview_id, "idempotency_key": "k"},- headers=_auth(user1_token),+ "/api/v1/intermediates/operations", json={"preview_id": preview_id}, headers=_auth(user1_token))assert started.status_code == status.HTTP_202_ACCEPTED, started.textoperation_id = started.json()["operation_id"]+ # A preview is confirmed once; a client whose response was lost finds the run in the list.repeated = client.post(- "/api/v1/intermediates/operations",- json={"preview_id": preview_id, "idempotency_key": "k"},- headers=_auth(user1_token),+ "/api/v1/intermediates/operations", json={"preview_id": preview_id}, headers=_auth(user1_token))- assert repeated.status_code == status.HTTP_202_ACCEPTED and repeated.json()["operation_id"] == operation_id+ assert repeated.status_code == status.HTTP_404_NOT_FOUND+ listed = client.get("/api/v1/intermediates/operations", headers=_auth(user1_token))+ assert [item["operation_id"] for item in listed.json()["items"]] == [operation_id]+ assert client.get("/api/v1/intermediates/operations", headers=_auth(user2_token)).json() == {"items": []}finished = _wait(client, user1_token, operation_id)assert finished["status"] == "completed"assert finished["progress"]["deleted_images"] == 1+ assert finished["scope"] == preview.json()["scope"]assert (client.get(f"/api/v1/intermediates/operations/{operation_id}", headers=_auth(user2_token)).status_code== status.HTTP_404_NOT_FOUND)assert client.get(f"/api/v1/intermediates/operations/{operation_id}", headers=_auth(admin_token)).status_code == 200- nothing_to_retry = client.post(f"/api/v1/intermediates/operations/{operation_id}/retry", headers=_auth(user1_token))- assert nothing_to_retry.status_code == status.HTTP_409_CONFLICTdef test_mutations_are_refused_during_image_storage_maintenance(@@ -179,35 +176,13 @@ def test_mutations_are_refused_during_image_storage_maintenance(started = client.post("/api/v1/intermediates/operations",- json={"preview_id": preview.json()["preview_id"], "idempotency_key": "k"},+ json={"preview_id": preview.json()["preview_id"]},headers=_auth(user1_token),)assert started.status_code == status.HTTP_409_CONFLICTassert started.json()["detail"] == "Image storage maintenance is active"-def test_replayed_start_succeeds_during_image_storage_maintenance(- storage_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str-) -> None:- user1 = _user_id(mock_invoker, "[email protected]")- _seed_intermediate(mock_invoker, "replay.png", user1)- preview = client.post(- "/api/v1/intermediates/previews",- json={"mode": "safe", "scope": {"kind": "owner", "user_id": user1}},- headers=_auth(user1_token),- ).json()- request = {"preview_id": preview["preview_id"], "idempotency_key": "replay-maintenance"}- first = client.post("/api/v1/intermediates/operations", json=request, headers=_auth(user1_token))- assert first.status_code == 202- _wait(client, user1_token, first.json()["operation_id"])- mock_invoker.services.image_moves.is_maintenance_active.return_value = True-- replay = client.post("/api/v1/intermediates/operations", json=request, headers=_auth(user1_token))-- assert replay.status_code == 202- assert replay.json()["operation_id"] == first.json()["operation_id"]--def test_hold_is_account_scoped_at_the_http_boundary(storage_ready: None, mock_invoker: Invoker, client: TestClient, user1_token: str, user2_token: str) -> None:@@ -224,15 +199,13 @@ def test_hold_is_account_scoped_at_the_http_boundary(assert summary["items"][0]["images"]["active"] == 1-def test_hold_lease_ids_name_one_editor_and_an_optional_part(- storage_ready: None, client: TestClient, user1_token: str-) -> None:- for lease_id in ("tab.0-0", "tab"):+def test_hold_lease_ids_are_single_tokens(storage_ready: None, client: TestClient, user1_token: str) -> None:+ for lease_id in ("tab", "tab-1_x"):assert (client.put(f"/api/v1/intermediates/holds/{lease_id}", json={}, headers=_auth(user1_token)).status_code== 204)- for lease_id in (".0-0", "tab x", "tab/.."):+ for lease_id in ("tab.0-0", ".0-0", "tab x", "tab/.."):assert (client.put(f"/api/v1/intermediates/holds/{lease_id}", json={}, headers=_auth(user1_token)).status_code!= 204diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.pyindex 76a24e9f0e..cd286df071 100644--- a/tests/app/services/intermediates/test_intermediates_service.py+++ b/tests/app/services/intermediates/test_intermediates_service.py@@ -7,7 +7,7 @@ same SQL that production runs, never through a stub that decides what is safe.import timeimport uuidfrom pathlib import Path-from typing import Optional+from typing import Callable, Optionalfrom unittest.mock import MagicMockimport pytest@@ -23,14 +23,15 @@ from invokeai.app.services.image_records.image_records_common import (from invokeai.app.services.intermediates import intermediates_default, intermediates_measurementfrom invokeai.app.services.intermediates.intermediates_base import IntermediatesCallerfrom invokeai.app.services.intermediates.intermediates_common import (- IntermediatesIdempotencyConflictError,IntermediatesOperation,IntermediatesOperationNotFoundError,IntermediatesOperationRequest,+ IntermediatesPreview,IntermediatesPreviewNotFoundError,IntermediatesPreviewRequest,IntermediatesScope,IntermediatesScopeForbiddenError,+ IntermediatesScopeInvalidError,IntermediatesScopeTarget,IntermediatesUnavailableError,)@@ -185,12 +186,37 @@ def _wait(raise AssertionError("operation did not finish")+def _start(+ service: IntermediatesService, preview: IntermediatesPreview, caller: IntermediatesCaller = ALICE+) -> IntermediatesOperation:+ return service.start_operation(IntermediatesOperationRequest(preview_id=preview.preview_id), caller)++def _run(service: IntermediatesService, caller: IntermediatesCaller, scope: IntermediatesScope, mode: str = "safe"):preview = service.create_preview(IntermediatesPreviewRequest(mode=mode, scope=scope), caller)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key=uuid.uuid4().hex), caller- )- return preview, _wait(service, started.operation_id, caller)+ return preview, _wait(service, _start(service, preview, caller).operation_id, caller)+++def _before_first_delete(+ invoker: Invoker, monkeypatch: pytest.MonkeyPatch, mutate: Callable[[], None], *, kind: str = "image"+) -> None:+ """Runs ``mutate`` between the first batch's page read and its final check.++ Batches are paged live, so a change made before the operation starts is simply never paged;+ this window is the one only the guard on the deleting transaction covers.+ """+ owner = invoker.services.images if kind == "image" else invoker.services.videos+ real = owner.delete_intermediates_by_names+ done = False++ def wrapped(names, guard=None):+ nonlocal done+ if not done:+ done = True+ mutate()+ return real(names, guard)++ monkeypatch.setattr(owner, "delete_intermediates_by_names", wrapped)def _owner(user_id: str) -> IntermediatesScope:@@ -383,6 +409,7 @@ def test_safe_cleanup_deletes_only_safe_items_and_reports_what_it_kept(assert preview.impact.reclaimable_bytes == 164assert preview.affected_documents == []assert operation.status == "completed"+ assert (operation.target_images, operation.target_videos) == (1, 1)assert (operation.progress.deleted_images, operation.progress.deleted_videos) == (1, 1)assert operation.progress.reclaimed_bytes == 164assert not _exists(invoker, "safe.png")@@ -415,6 +442,7 @@ def test_force_cleanup_deletes_referenced_items_but_never_active_or_recent(# 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)+ assert preview.impact.reclaimable_bytes == 40assert [(doc.kind, doc.name, doc.references) for doc in preview.affected_documents] == [("project", "Drafts", 1)]admin_preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ADMIN)@@ -426,28 +454,26 @@ def test_force_cleanup_deletes_referenced_items_but_never_active_or_recent(("workflow", workflow.workflow_id, 1, "Bob"),}- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- operation = _wait(service, started.operation_id)+ operation = _wait(service, _start(service, preview).operation_id)assert operation.status == "completed"assert not _exists(invoker, "staged.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+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> 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+ _before_first_delete(+ invoker,+ monkeypatch,+ lambda: invoker.services.workflow_records.create(_workflow_naming("staged.png"), user_id="bob"),)- operation = _wait(service, started.operation_id)++ operation = _wait(service, _start(service, preview).operation_id)assert operation.progress.retained_images == 1assert _exists(invoker, "staged.png")@@ -500,23 +526,45 @@ def test_selection_scope_targets_exactly_the_chosen_rows(invoker: Invoker, serviassert not any(_exists(invoker, n) for n in ("clear.png", "unassigned.png", "orphaned-project.png"))-def test_a_preview_freezes_its_targets(invoker: Invoker, service: IntermediatesService) -> None:+def test_media_created_during_the_run_is_never_collected(invoker: Invoker, service: IntermediatesService) -> None:_seed_image(invoker, "before.png")preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- _seed_image(invoker, "after.png")+ _seed_image(invoker, "after.png", created_at=None)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- operation = _wait(service, started.operation_id)+ operation = _wait(service, _start(service, preview).operation_id)assert operation.target_images == 1+ assert (operation.progress.deleted_images, operation.progress.retained_images) == (1, 0)assert not _exists(invoker, "before.png")assert _exists(invoker, "after.png")-def test_the_final_check_keeps_targets_protected_after_the_preview(- invoker: Invoker, service: IntermediatesService+def test_a_row_that_was_recent_at_preview_time_stays_recent_for_the_operation(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ from datetime import datetime, timedelta, timezone++ from invokeai.app.services.intermediates import intermediates_records_sqlite+ from invokeai.app.services.intermediates.intermediates_common import RECENT_GRACE_SECONDS++ start = datetime(2030, 1, 1, tzinfo=timezone.utc)+ readings = iter([start] + [start + timedelta(hours=1)] * 100)+ monkeypatch.setattr(intermediates_records_sqlite, "_utc_now", lambda: next(readings))+ crossing = start - timedelta(seconds=RECENT_GRACE_SECONDS - 1)+ _seed_image(invoker, "crossing.png", created_at=crossing.strftime("%Y-%m-%d %H:%M:%S.000"))+ _seed_image(invoker, "old.png")++ preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)+ assert (preview.impact.keep_recent_images, preview.impact.delete_images) == (1, 1)++ # An hour later the row would be safe under a live clock; the operation judges recency as of its preview.+ operation = _wait(service, _start(service, preview).operation_id)+ assert operation.progress.deleted_images == 1+ assert _exists(invoker, "crossing.png") and not _exists(invoker, "old.png")+++def test_the_final_check_keeps_targets_protected_after_the_page_read(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:project = _project(invoker, "alice", "P", {})_seed_image(invoker, "promoted.png", project_id=project)@@ -526,16 +574,15 @@ def test_the_final_check_keeps_targets_protected_after_the_preview(preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)assert preview.impact.delete_images == 4- invoker.services.image_records.update("promoted.png", ImageRecordChanges(is_intermediate=False))- invoker.services.project_records.update(- "alice", project, expected_revision=1, name="P", data={"imageName": "now-referenced.png"}- )- _enqueue_row(invoker, session_id="s-late", status="pending")+ def protect_three() -> None:+ invoker.services.image_records.update("promoted.png", ImageRecordChanges(is_intermediate=False))+ invoker.services.project_records.update(+ "alice", project, expected_revision=1, name="P", data={"imageName": "now-referenced.png"}+ )+ _enqueue_row(invoker, session_id="s-late", status="pending")- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- operation = _wait(service, started.operation_id)+ _before_first_delete(invoker, monkeypatch, protect_three)+ operation = _wait(service, _start(service, preview).operation_id)assert operation.progress.deleted_images == 1assert operation.progress.retained_images == 3@@ -544,18 +591,22 @@ def test_the_final_check_keeps_targets_protected_after_the_preview(assert invoker.services.image_files.get_path("promoted.png").exists()-def test_a_promoted_video_keeps_its_file(invoker: Invoker, service: IntermediatesService) -> None:+def test_a_promoted_video_keeps_its_file(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ from invokeai.app.services.video_records.video_records_common import VideoRecordChanges+_seed_video(invoker, "promoted.mp4")_seed_video(invoker, "gone.mp4")preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- from invokeai.app.services.video_records.video_records_common import VideoRecordChanges-- invoker.services.video_records.update("promoted.mp4", VideoRecordChanges(is_intermediate=False))-- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE+ _before_first_delete(+ invoker,+ monkeypatch,+ lambda: invoker.services.video_records.update("promoted.mp4", VideoRecordChanges(is_intermediate=False)),+ kind="video",)- operation = _wait(service, started.operation_id)++ operation = _wait(service, _start(service, preview).operation_id)assert (operation.progress.deleted_videos, operation.progress.retained_videos) == (1, 1)assert invoker.services.video_files.get_path("promoted.mp4").exists()@@ -584,6 +635,10 @@ def test_non_admins_are_confined_to_their_own_account(invoker: Invoker, service:),ALICE,)+ with pytest.raises(IntermediatesScopeForbiddenError):+ service.create_preview(+ IntermediatesPreviewRequest(mode="safe", scope=IntermediatesScope(kind="matching", user_id="bob")), ALICE+ )def test_admins_can_clear_everyone_and_a_chosen_account(invoker: Invoker, service: IntermediatesService) -> None:@@ -618,10 +673,7 @@ def test_a_demoted_admin_stops_at_the_next_batch(monkeypatch.setattr(invoker.services.users, "get", demote_after_first_batch)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ADMIN- )- operation = _wait(service, started.operation_id, ADMIN)+ operation = _wait(service, _start(service, preview, ADMIN).operation_id, ADMIN)assert operation.status == "failed"assert "no longer administers" in (operation.error or "")@@ -645,69 +697,48 @@ def test_a_demoted_admin_keeps_media_other_accounts_documents_name_in_its_own_scmonkeypatch.setattr(invoker.services.users, "get", demoted)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ADMIN- )- operation = _wait(service, started.operation_id, ADMIN)+ operation = _wait(service, _start(service, preview, ADMIN).operation_id, ADMIN)assert operation.status == "completed"- assert operation.progress.retained_images == 1+ assert operation.progress.deleted_images == 0assert _exists(invoker, "admin-own.png")-def test_a_retry_by_a_demoted_admin_keeps_media_other_accounts_documents_name(- invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch-) -> None:- _seed_image(invoker, "admin-own.png", user_id="admin")- invoker.services.workflow_records.create(_workflow_naming("admin-own.png"), user_id="bob")- real_delete = invoker.services.images.delete_intermediates_by_names- monkeypatch.setattr(- invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))- )- _, failed = _run(service, ADMIN, _owner("admin"), mode="force")- assert failed.progress.unresolved_images == 1- monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)-- retry = service.retry_operation(failed.operation_id, IntermediatesCaller(user_id="admin", is_admin=False))- retried = _wait(service, retry.operation_id, ADMIN)-- assert retried.progress.retained_images == 1- assert _exists(invoker, "admin-own.png")-+# ── operations ──-# ── operations: idempotency, retry, availability ──--def test_operations_are_idempotent_single_use_and_private(invoker: Invoker, service: IntermediatesService) -> None:+def test_operations_are_single_use_and_private(invoker: Invoker, service: IntermediatesService) -> None:_seed_image(invoker, "a.png")preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- other = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)with pytest.raises(IntermediatesPreviewNotFoundError):- service.start_operation(IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), BOB)-- first = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- again = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- assert again.operation_id == first.operation_id+ _start(service, preview, BOB)- with pytest.raises(IntermediatesIdempotencyConflictError):- service.start_operation(IntermediatesOperationRequest(preview_id=other.preview_id, idempotency_key="k"), ALICE)+ first = _start(service, preview)+ _wait(service, first.operation_id)with pytest.raises(IntermediatesPreviewNotFoundError):- service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k2"), ALICE- )+ _start(service, preview)- _wait(service, first.operation_id)with pytest.raises(IntermediatesOperationNotFoundError):service.get_operation(first.operation_id, BOB)assert service.get_operation(first.operation_id, ADMIN).status == "completed"-def test_a_failed_batch_is_reported_and_retried_without_widening(+def test_operations_are_listed_newest_first_and_only_to_their_caller(+ invoker: Invoker, service: IntermediatesService+) -> None:+ _seed_image(invoker, "a.png")+ _seed_image(invoker, "b.png", user_id="bob")+ _, first = _run(service, ALICE, _owner("alice"))+ _, second = _run(service, ALICE, _owner("alice"))+ _, bobs = _run(service, BOB, _owner("bob"))++ assert [op.operation_id for op in service.list_operations(ALICE)] == [second.operation_id, first.operation_id]+ assert [op.operation_id for op in service.list_operations(BOB)] == [bobs.operation_id]+ assert service.list_operations(ADMIN) == []+++def test_a_failed_batch_is_reported_and_a_later_run_finishes_it(invoker: Invoker, service: IntermediatesService, monkeypatch) -> None:monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)@@ -728,16 +759,12 @@ def test_a_failed_batch_is_reported_and_retried_without_widening(assert (operation.progress.deleted_images, operation.progress.failed_images) == (1, 1)assert _exists(invoker, "flaky.png")- _seed_image(invoker, "new-since.png")- retry = service.retry_operation(operation.operation_id, ALICE)- retried = _wait(service, retry.operation_id)- assert retried.retried_from_operation_id == operation.operation_id- assert retried.target_images == 1- assert retried.progress.deleted_images == 1+ _seed_image(invoker, "new-since.png", created_at=None)+ second, finished = _run(service, ALICE, _owner("alice"))+ assert second.impact.delete_images == 1+ assert finished.progress.deleted_images == 1assert not _exists(invoker, "flaky.png")assert _exists(invoker, "new-since.png")- with pytest.raises(IntermediatesUnavailableError):- service.retry_operation(retried.operation_id, ALICE)def test_a_purge_failure_counts_as_pending_disk_cleanup_not_reclaimed(@@ -792,15 +819,11 @@ def test_cleanup_refuses_to_start_or_continue_during_storage_maintenance(invoker.services.image_moves = movespreview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)with pytest.raises(IntermediatesUnavailableError):- service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )+ _start(service, preview)invoker.services.image_moves = None- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- # Halt after the first batch: the second sees maintenance and stops with the rest unresolved.+ started = _start(service, preview)+ # Halt after the first batch: the second sees maintenance and stops with the rest untouched.real_delete = invoker.services.images.delete_intermediates_by_namesdef delete_then_start_maintenance(names, guard=None):@@ -814,8 +837,9 @@ def test_cleanup_refuses_to_start_or_continue_during_storage_maintenance(assert operation.progress.deleted_images == 1assert operation.progress.failed_images == 0invoker.services.image_moves = None- retried = _wait(service, service.retry_operation(operation.operation_id, ALICE).operation_id)- assert retried.target_images == 1 and retried.progress.deleted_images == 1+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)+ second, finished = _run(service, ALICE, _owner("alice"))+ assert second.impact.delete_images == 1 and finished.progress.deleted_images == 1def test_operation_events_reach_the_bus(invoker: Invoker, service: IntermediatesService) -> None:@@ -837,6 +861,113 @@ def test_operation_events_reach_the_bus(invoker: Invoker, service: Intermediates) # type: ignore[attr-defined]+def test_a_restart_forgets_operations_and_a_fresh_run_finishes_the_work(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ _seed_image(invoker, "restart-flaky.png")+ real_delete = invoker.services.images.delete_intermediates_by_names+ monkeypatch.setattr(+ invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))+ )+ _, failed = _run(service, ALICE, _owner("alice"))+ assert failed.progress.failed_images == 1+ service.stop()++ restored = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))+ invoker.services.intermediates = restored+ restored.start(invoker)+ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)+ try:+ with pytest.raises(IntermediatesOperationNotFoundError):+ restored.get_operation(failed.operation_id, ALICE)+ assert restored.list_operations(ALICE) == []+ _, finished = _run(restored, ALICE, _owner("alice"))+ assert finished.progress.deleted_images == 1+ assert not _exists(invoker, "restart-flaky.png")+ finally:+ restored.stop()+++def test_settled_operations_are_retained_per_caller_and_running_ones_are_never_dropped(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ import threading++ monkeypatch.setattr(intermediates_default, "MAX_RETAINED_SETTLED_OPERATIONS_PER_CALLER", 1)+ monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS", 2)+ _seed_image(invoker, "bob.png", user_id="bob")+ release = threading.Event()+ real_delete = invoker.services.images.delete_intermediates_by_names++ def blocked_delete(names, guard=None):+ release.wait(10)+ return real_delete(names, guard)++ monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", blocked_delete)+ empty = IntermediatesScope(+ kind="selection",+ targets=[IntermediatesScopeTarget(user_id="alice", project_id=_project(invoker, "alice", "E", {}))],+ )++ _, first = _run(service, ALICE, empty)+ _, second = _run(service, ALICE, empty)+ with pytest.raises(IntermediatesOperationNotFoundError):+ service.get_operation(first.operation_id, ALICE)+ assert [op.operation_id for op in service.list_operations(ALICE)] == [second.operation_id]++ try:+ running = _start(+ service, service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), BOB), BOB+ )+ # The worker is busy with Bob's run, so this one waits behind it: unsettled, never a candidate.+ queued = _start(+ service,+ service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("admin")), ADMIN),+ ADMIN,+ )+ # Past the global cap the oldest settled operation goes, whoever it belongs to.+ with pytest.raises(IntermediatesOperationNotFoundError):+ service.get_operation(second.operation_id, ALICE)+ assert service.get_operation(running.operation_id, BOB).status in ("pending", "running")+ assert service.get_operation(queued.operation_id, ADMIN).status == "pending"+ finally:+ release.set()+ assert _wait(service, running.operation_id, BOB).status == "completed"+ assert _wait(service, queued.operation_id, ADMIN).status == "completed"+++def test_a_crashing_page_read_does_not_strand_the_accepted_queue(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ original_ensure_worker = service._ensure_worker+ monkeypatch.setattr(service, "_ensure_worker", lambda: None)+ _seed_image(invoker, "alice.png")+ _seed_image(invoker, "bob.png", user_id="bob")+ operation_ids = [+ _start(+ service, service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner(c.user_id)), c), c+ ).operation_id+ for c in (ALICE, BOB)+ ]++ real_iter = service._records.iter_deletable_batches+ crashed = False++ def crash_once(*args, **kwargs):+ nonlocal crashed+ if not crashed:+ crashed = True+ raise OSError("storage temporarily unavailable")+ return real_iter(*args, **kwargs)++ monkeypatch.setattr(service._records, "iter_deletable_batches", crash_once)+ monkeypatch.setattr(service, "_ensure_worker", original_ensure_worker)+ service._ensure_worker()++ assert _wait(service, operation_ids[0]).status == "failed"+ assert _wait(service, operation_ids[1], BOB).status == "completed"++# ── legacy ──@@ -898,7 +1029,7 @@ def test_inputs_added_to_an_active_session_after_it_was_scanned_are_protected(def test_cleanup_rechecks_same_length_active_session_rewrites_with_an_unchanged_timestamp(- invoker: Invoker, service: IntermediatesService+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:_seed_image(invoker, "old.png")_seed_image(invoker, "new.png")@@ -906,50 +1037,20 @@ def test_cleanup_rechecks_same_length_active_session_rewrites_with_an_unchanged_preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)assert preview.impact.delete_images == 1- # The queue timestamp has millisecond precision. Suppress its trigger to make the- # same-millisecond, same-length rewrite deterministic instead of timing dependent.- with invoker.services.image_records._db.transaction() as cursor:- cursor.execute("DROP TRIGGER tg_session_queue_updated_at;")- cursor.execute("UPDATE session_queue SET session = ? WHERE item_id = ?;", ('{"image_name":"new.png"}', item_id))+ def rewrite_session() -> None:+ # The queue timestamp has millisecond precision. Suppress its trigger to make the+ # same-millisecond, same-length rewrite deterministic instead of timing dependent.+ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("DROP TRIGGER tg_session_queue_updated_at;")+ cursor.execute(+ "UPDATE session_queue SET session = ? WHERE item_id = ?;", ('{"image_name":"new.png"}', item_id)+ )- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="same-stamp"), ALICE- )- assert _wait(service, started.operation_id).progress.retained_images == 1+ _before_first_delete(invoker, monkeypatch, rewrite_session)+ assert _wait(service, _start(service, preview).operation_id).progress.retained_images == 1assert _exists(invoker, "new.png")-def test_retries_are_authorized_as_the_retrying_caller(- invoker: Invoker, service: IntermediatesService, monkeypatch-) -> None:- monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)- _seed_image(invoker, "bob-flaky.png", user_id="bob")- real_delete = invoker.services.images.delete_intermediates_by_names-- def fail_once(names, guard=None):- if not getattr(fail_once, "failed", False):- fail_once.failed = True # type: ignore[attr-defined]- raise OSError("disk hiccup")- return real_delete(names, guard)-- monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", fail_once)- _, operation = _run(service, ADMIN, _owner("bob"))- assert operation.progress.unresolved_images == 1-- # Another account cannot even see it; the demoted confirmer may see it but not widen to Bob.- with pytest.raises(IntermediatesOperationNotFoundError):- service.retry_operation(operation.operation_id, ALICE)- with pytest.raises(IntermediatesScopeForbiddenError):- service.retry_operation(operation.operation_id, IntermediatesCaller(user_id="admin", is_admin=False))- assert _exists(invoker, "bob-flaky.png")-- retry = service.retry_operation(operation.operation_id, ADMIN)- assert _wait(service, retry.operation_id, ADMIN).progress.deleted_images == 1- # A duplicated retry request returns the retry that already took the targets over.- assert service.retry_operation(operation.operation_id, ADMIN).operation_id == retry.operation_id- assert service.get_operation(operation.operation_id, ADMIN).retried_by_operation_id == retry.operation_id--def test_a_deactivated_caller_stops_at_the_next_batch(invoker: Invoker, service: IntermediatesService, monkeypatch) -> None:@@ -967,14 +1068,11 @@ def test_a_deactivated_caller_stops_at_the_next_batch(monkeypatch.setattr(invoker.services.users, "get", deactivate_after_first_batch)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- operation = _wait(service, started.operation_id)+ operation = _wait(service, _start(service, preview).operation_id)assert operation.status == "failed"assert operation.progress.deleted_images == 1- assert operation.progress.unresolved_images == 1+ assert sum(_exists(invoker, f"a-{index}.png") for index in range(2)) == 1def test_unmeasured_targets_are_reported_rather_than_counted_as_free(@@ -991,24 +1089,6 @@ def test_unmeasured_targets_are_reported_rather_than_counted_as_free(assert operation.progress.unknown_size_count == 1-def test_a_replayed_start_is_answered_during_maintenance(invoker: Invoker, service: IntermediatesService) -> None:- _seed_image(invoker, "a.png")- preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- first = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- _wait(service, first.operation_id)- moves = MagicMock()- moves.is_maintenance_active.return_value = True- invoker.services.image_moves = moves-- replay = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )-- assert replay.operation_id == first.operation_id--def test_a_save_cannot_slip_between_the_final_check_and_the_delete(invoker: Invoker, service: IntermediatesService, monkeypatch) -> None:@@ -1024,10 +1104,8 @@ def test_a_save_cannot_slip_between_the_final_check_and_the_delete(guard_may_finish = threading.Event()delete_committed_at: list[float] = []- def slow_guard_factory(kind, *, mode, allowed_user_ids, confirmed_references=None):- guard = real_guard_factory(- kind, mode=mode, allowed_user_ids=allowed_user_ids, confirmed_references=confirmed_references- )+ def slow_guard_factory(kind, **kwargs):+ guard = real_guard_factory(kind, **kwargs)def paused(cursor, names):guard_entered.set()@@ -1047,9 +1125,7 @@ def test_a_save_cannot_slip_between_the_final_check_and_the_delete(monkeypatch.setattr(invoker.services.image_records, "delete_intermediates_by_names", timed_record_delete)preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )+ started = _start(service, preview)assert guard_entered.wait(timeout=10)save_finished_at: list[float] = []@@ -1082,8 +1158,6 @@ def test_active_inputs_survive_a_rolled_back_batch(_seed_image(invoker, "consumed.png")preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)assert preview.impact.delete_images == 2- # Enqueued after the preview: only the final check can protect it.- _enqueue_row(invoker, session_id="s-late", status="pending", session_json='{"a": {"image_name": "consumed.png"}}')real_delete = invoker.services.image_records.delete_intermediates_by_namescalls = {"n": 0}@@ -1094,76 +1168,106 @@ def test_active_inputs_survive_a_rolled_back_batch(if guard is not None:guard(cursor, names)raise RuntimeError("simulated I/O failure after the guard rebuilt the temp table")+ # Enqueued after the second batch was paged: only its final check can protect it.+ _enqueue_row(+ invoker, session_id="s-late", status="pending", session_json='{"a": {"image_name": "consumed.png"}}'+ )return real_delete(names, guard=guard)monkeypatch.setattr(invoker.services.image_records, "delete_intermediates_by_names", fail_first_batch_after_the_guard)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="k"), ALICE- )- operation = _wait(service, started.operation_id)+ operation = _wait(service, _start(service, preview).operation_id)assert operation.progress.failed_images == 1+ assert operation.progress.retained_images == 1assert _exists(invoker, "consumed.png"), "an input of pending work was deleted after a rolled-back batch"-def test_force_clear_keeps_a_newly_referenced_target(invoker: Invoker, service: IntermediatesService) -> None:+def test_force_clear_keeps_a_newly_referenced_target(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:_seed_image(invoker, "force-race.png")preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)assert preview.affected_documents == []- _project(invoker, "alice", "Saved after preview", {"imageName": "force-race.png"})-- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="force-race"), ALICE+ _before_first_delete(+ invoker, monkeypatch, lambda: _project(invoker, "alice", "Saved after preview", {"imageName": "force-race.png"}))- finished = _wait(service, started.operation_id)++ finished = _wait(service, _start(service, preview).operation_id)assert finished.progress.retained_images == 1assert _exists(invoker, "force-race.png")-def test_an_account_holds_media_for_a_bounded_number_of_editors(- invoker: Invoker, service: IntermediatesService+def test_the_acknowledged_documents_bound_what_a_force_clear_may_break(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:+ """Confirming acknowledges documents, not (document, item) pairs: an acknowledged document that names+ another target during the run does not protect it, while a document saved after the preview does."""+ acknowledged = _project(invoker, "alice", "Acknowledged", {"imageName": "t1.png"})+ for name in ("t1.png", "t2.png", "t3.png"):+ _seed_image(invoker, name)+ preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)+ assert [doc.name for doc in preview.affected_documents] == ["Acknowledged"]+ assert preview.impact.delete_images == 3++ def reference_more() -> None:+ invoker.services.project_records.update(+ "alice",+ acknowledged,+ expected_revision=1,+ name="Acknowledged",+ data={"images": [{"imageName": "t1.png"}, {"imageName": "t2.png"}]},+ )+ _project(invoker, "alice", "New", {"imageName": "t3.png"})++ _before_first_delete(invoker, monkeypatch, reference_more)+ finished = _wait(service, _start(service, preview).operation_id)++ assert (finished.progress.deleted_images, finished.progress.retained_images) == (2, 1)+ assert not _exists(invoker, "t1.png") and not _exists(invoker, "t2.png")+ assert _exists(invoker, "t3.png")+++def test_a_force_preview_refuses_more_acknowledged_documents_than_the_bound(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(intermediates_default, "MAX_ACKNOWLEDGED_DOCUMENTS", 2)+ for index in range(3):+ _seed_image(invoker, f"doc-{index}.png")+ _project(invoker, "alice", f"Doc {index}", {"imageName": f"doc-{index}.png"})++ with pytest.raises(IntermediatesScopeInvalidError, match="narrow the scope"):+ service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)+ assert service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)+++def test_an_account_holds_media_for_a_bounded_number_of_leases(invoker: Invoker, service: IntermediatesService) -> None:from invokeai.app.services.intermediates.intermediates_common import (- MAX_BROWSER_HOLD_EDITORS_PER_USER,+ MAX_BROWSER_HOLD_LEASES_PER_USER,IntermediatesBrowserHoldRequest,)_seed_image(invoker, "bobs-held.png", user_id="bob")service.replace_browser_hold(BOB, "bob-tab", IntermediatesBrowserHoldRequest(images=["bobs-held.png"]))- # Each editor splits its hold into two leases; the cap counts editors, not leases.- for editor in range(MAX_BROWSER_HOLD_EDITORS_PER_USER + 1):- for part in range(2):- _seed_image(invoker, f"held-{editor}-{part}.png")- service.replace_browser_hold(- ALICE, f"tab-{editor}.{part}-0", IntermediatesBrowserHoldRequest(images=[f"held-{editor}-{part}.png"])- )- # Refresh order decides which editor lapses; stagger it so the first editor is the stalest.+ for tab in range(MAX_BROWSER_HOLD_LEASES_PER_USER + 1):+ _seed_image(invoker, f"held-{tab}.png")+ service.replace_browser_hold(ALICE, f"tab-{tab}", IntermediatesBrowserHoldRequest(images=[f"held-{tab}.png"]))+ # Refresh order decides which lease lapses; stagger it so the first tab is the stalest.with invoker.services.image_records._db.transaction() as cursor:cursor.execute("UPDATE intermediates_browser_holds SET expires_at = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', ?)"- " WHERE user_id = 'alice' AND lease_id LIKE ?;",- (f"+{60 + editor} seconds", f"tab-{editor}.%"),+ " WHERE user_id = 'alice' AND lease_id = ?;",+ (f"+{60 + tab} seconds", f"tab-{tab}"),)alice, operation = _run(service, ALICE, _owner("alice"))- assert (alice.impact.keep_active_images, alice.impact.delete_images) == (- 2 * MAX_BROWSER_HOLD_EDITORS_PER_USER,- 2,- )- assert operation.progress.deleted_images == 2- survivors = {- f"held-{editor}-{part}.png"- for editor in range(MAX_BROWSER_HOLD_EDITORS_PER_USER + 1)- for part in range(2)- if _exists(invoker, f"held-{editor}-{part}.png")- }- assert survivors == {- f"held-{editor}-{part}.png" for editor in range(1, MAX_BROWSER_HOLD_EDITORS_PER_USER + 1) for part in range(2)- }+ assert (alice.impact.keep_active_images, alice.impact.delete_images) == (MAX_BROWSER_HOLD_LEASES_PER_USER, 1)+ assert operation.progress.deleted_images == 1+ assert not _exists(invoker, "held-0.png")+ assert all(_exists(invoker, f"held-{tab}.png") for tab in range(1, MAX_BROWSER_HOLD_LEASES_PER_USER + 1))bob = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), BOB)assert (bob.impact.keep_active_images, bob.impact.delete_images) == (1, 0)@@ -1201,102 +1305,15 @@ def test_browser_hold_protects_unsaved_and_undo_references(invoker: Invoker, serassert available.impact.delete_images == 1-def test_operation_receipt_and_retry_survive_restart(- invoker: Invoker, service: IntermediatesService, monkeypatch-) -> None:- _seed_image(invoker, "restart-flaky.png")- real_delete = invoker.services.images.delete_intermediates_by_names- monkeypatch.setattr(- invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))- )- preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="restart-key"), ALICE- )- finished = _wait(service, started.operation_id)- assert finished.progress.unresolved_images == 1- service.stop()-- restored = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))- invoker.services.intermediates = restored- restored.start(invoker)- try:- assert restored.get_operation(finished.operation_id, ALICE).progress.unresolved_images == 1- replay = restored.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="restart-key"), ALICE- )- assert replay.operation_id == finished.operation_id- monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)- retry = restored.retry_operation(finished.operation_id, ALICE)- assert _wait(restored, retry.operation_id).progress.deleted_images == 1- assert restored.retry_operation(finished.operation_id, ALICE).operation_id == retry.operation_id- assert not _exists(invoker, "restart-flaky.png")- finally:- restored.stop()---def test_receipt_pruning_keeps_unresolved_targets_retryable(- invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch-) -> None:- monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS_PER_CALLER", 2)- _seed_image(invoker, "flaky.png")- real_delete = invoker.services.images.delete_intermediates_by_names- monkeypatch.setattr(- invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))- )- _, failed = _run(service, ALICE, _owner("alice"))- assert failed.progress.unresolved_images == 1- monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)-- # New successful receipts may be pruned; the failed operation's exact target must not be.- empty = IntermediatesScope(- kind="selection",- targets=[IntermediatesScopeTarget(user_id="alice", project_id=_project(invoker, "alice", "E", {}))],- )- _, oldest_settled = _run(service, ALICE, empty)- for _ in range(2):- _run(service, ALICE, empty)-- with pytest.raises(IntermediatesOperationNotFoundError):- service.get_operation(oldest_settled.operation_id, ALICE)- assert service.get_operation(failed.operation_id, ALICE).progress.unresolved_images == 1- retry = service.retry_operation(failed.operation_id, ALICE)- assert _wait(service, retry.operation_id).progress.deleted_images == 1---def test_pruning_another_accounts_retry_prunes_the_operation_it_retried(- invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch-) -> None:- monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS_PER_CALLER", 2)- _seed_image(invoker, "flaky.png")- real_delete = invoker.services.images.delete_intermediates_by_names- monkeypatch.setattr(- invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))- )- _, failed = _run(service, ALICE, _owner("alice"))- monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)- retry = service.retry_operation(failed.operation_id, ADMIN)- assert _wait(service, retry.operation_id, ADMIN).progress.deleted_images == 1-- # The admin's later cleanups push its retry out of its budget; Alice's original goes with it- # rather than pointing at a receipt that no longer exists.- for _ in range(3):- _run(service, ADMIN, _owner("admin"))-- for operation_id in (retry.operation_id, failed.operation_id):- with pytest.raises(IntermediatesOperationNotFoundError):- service.get_operation(operation_id, ADMIN)- with pytest.raises(IntermediatesOperationNotFoundError):- service.retry_operation(failed.operation_id, ALICE)--def test_one_account_cannot_fill_the_cleanup_queue(invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:import threading+ monkeypatch.setattr(intermediates_default, "MAX_ACTIVE_OPERATIONS", 2)_seed_image(invoker, "alice.png")_seed_image(invoker, "bob.png", user_id="bob")+ _seed_image(invoker, "admin.png", user_id="admin")release = threading.Event()real_delete = invoker.services.images.delete_intermediates_by_names@@ -1308,118 +1325,169 @@ def test_one_account_cannot_fill_the_cleanup_queue(def start(caller: IntermediatesCaller) -> IntermediatesOperation:preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner(caller.user_id)), caller)- return service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key=uuid.uuid4().hex), caller- )+ return _start(service, preview, caller)try:- started = [start(ALICE) for _ in range(intermediates_default.MAX_ACTIVE_OPERATIONS_PER_CALLER)]- with pytest.raises(IntermediatesUnavailableError, match="your running deletions"):- start(ALICE)+ confirmed = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)+ started = [_start(service, confirmed)]+ # A lost-response replay learns the preview is consumed rather than waiting for capacity.+ with pytest.raises(IntermediatesPreviewNotFoundError):+ _start(service, confirmed)+ waiting = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)+ with pytest.raises(IntermediatesUnavailableError, match="your running deletion"):+ _start(service, waiting)started.append(start(BOB))+ with pytest.raises(IntermediatesUnavailableError, match="Too many"):+ start(ADMIN)finally:release.set()for operation in started:assert _wait(service, operation.operation_id, ADMIN).status == "completed"assert not _exists(invoker, "alice.png") and not _exists(invoker, "bob.png")+ assert _exists(invoker, "admin.png")+ # A capacity refusal keeps the preview for once the running deletion finishes.+ assert _wait(service, _start(service, waiting).operation_id).status == "completed"-def test_a_preview_classifies_its_counts_and_targets_at_one_instant(+def test_the_final_check_judges_cached_media_recency_as_of_the_preview(invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:+ """The guard shares the connection's session-hold table: judged live, it would sweep a hold the preview+ counted recent, and the next page would then collect the row the preview promised to keep."""from datetime import datetime, timedelta, timezonefrom invokeai.app.services.intermediates import intermediates_records_sqlite- from invokeai.app.services.intermediates.intermediates_common import RECENT_GRACE_SECONDS+ from invokeai.app.services.shared.media_references import MediaReferences+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)start = datetime(2030, 1, 1, tzinfo=timezone.utc)- readings = iter([start] + [start + timedelta(hours=1)] * 100)+ release_time = start - timedelta(minutes=29)+ readings = iter([release_time, release_time, start] + [start + timedelta(hours=1)] * 100)monkeypatch.setattr(intermediates_records_sqlite, "_utc_now", lambda: next(readings))- crossing = start - timedelta(seconds=RECENT_GRACE_SECONDS - 1)- _seed_image(invoker, "crossing.png", created_at=crossing.strftime("%Y-%m-%d %H:%M:%S.000"))+ _seed_image(invoker, "old.png")+ _seed_image(invoker, "cached.png")+ consumer = _enqueue_row(invoker, session_id="consumer", status="in_progress")+ assert service.hold_cached_media("consumer", MediaReferences(images={"cached.png"}))+ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?;", (consumer,))+ service._records.summarize(None)preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)+ assert (preview.impact.keep_recent_images, preview.impact.delete_images) == (1, 1)- # Still inside the grace window at the preview's single instant; an hour later it would be safe.- assert (preview.impact.keep_recent_images, preview.impact.delete_images) == (1, 0)+ operation = _wait(service, _start(service, preview).operation_id)+ assert operation.progress.deleted_images == 1+ assert _exists(invoker, "cached.png") and not _exists(invoker, "old.png")-def test_unresolved_work_blocks_only_its_own_accounts_new_cleanups(+def test_an_unconfirmed_preview_expires(invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(intermediates_default, "MAX_RETAINED_OPERATIONS_PER_CALLER", 1)- _seed_image(invoker, "flaky.png")- _seed_image(invoker, "bobs.png", user_id="bob")- real_delete = invoker.services.images.delete_intermediates_by_names- monkeypatch.setattr(- invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))- )- _, failed = _run(service, ALICE, _owner("alice"))- assert failed.progress.unresolved_images == 1- monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)+ from datetime import timedelta++ from invokeai.app.services.intermediates.intermediates_common import PREVIEW_TTL_SECONDS+ _seed_image(invoker, "a.png")preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- with pytest.raises(IntermediatesUnavailableError, match="Retry unresolved"):- service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="another"), ALICE- )- _, bobs = _run(service, BOB, _owner("bob"))- assert bobs.progress.deleted_images == 1+ later = preview.created_at + timedelta(seconds=PREVIEW_TTL_SECONDS + 1)+ monkeypatch.setattr(intermediates_default, "_now", lambda: later)- assert service.get_operation(failed.operation_id, ALICE).progress.unresolved_images == 1- retry = service.retry_operation(failed.operation_id, ALICE)- assert _wait(service, retry.operation_id).progress.deleted_images == 1+ with pytest.raises(IntermediatesPreviewNotFoundError):+ _start(service, preview)+ assert _exists(invoker, "a.png")-def test_an_unreadable_operation_receipt_does_not_stop_startup(invoker: Invoker, service: IntermediatesService) -> None:- _seed_image(invoker, "a.png")- _, finished = _run(service, ALICE, _owner("alice"))- service.stop()- with invoker.services.image_records._db.transaction() as cursor:- cursor.executemany(- "INSERT INTO intermediates_operations (operation_id, caller_user_id, state_json, created_at)"- " VALUES (?, 'alice', ?, '2020-01-01T00:00:00Z');",- [("not-json", "{truncated"), ("not-a-receipt", '{"dto": {}}')],+def test_matching_scope_resolves_filtered_rows_minus_exclusions(+ invoker: Invoker, service: IntermediatesService+) -> None:+ alpha = _project(invoker, "alice", "Alpha", {})+ beta = _project(invoker, "alice", "Beta", {})+ _seed_image(invoker, "alpha.png", project_id=alpha)+ _seed_image(invoker, "beta.png", project_id=beta)+ _seed_image(invoker, "unassigned.png")+ _seed_image(invoker, "bob.png", user_id="bob")++ everyone = service.create_preview(+ IntermediatesPreviewRequest(mode="safe", scope=IntermediatesScope(kind="matching")), ADMIN+ )+ assert everyone.target_rows == 4+ searched = service.create_preview(+ IntermediatesPreviewRequest(mode="safe", scope=IntermediatesScope(kind="matching", search="alp")), ADMIN+ )+ assert (searched.target_rows, searched.impact.delete_images) == (1, 1)+ with pytest.raises(IntermediatesScopeInvalidError):+ service.create_preview(+ IntermediatesPreviewRequest(mode="safe", scope=IntermediatesScope(kind="matching", search="nothing")),+ ADMIN,)- restored = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))- invoker.services.intermediates = restored- restored.start(invoker)- try:- assert restored.get_operation(finished.operation_id, ALICE).status == "completed"- with pytest.raises(IntermediatesOperationNotFoundError):- restored.get_operation("not-json", ALICE)- finally:- restored.stop()+ scope = IntermediatesScope(kind="matching", excluded=[IntermediatesScopeTarget(user_id="alice", project_id=beta)])+ preview, operation = _run(service, ALICE, scope)++ assert preview.scope == scope and operation.scope == scope+ assert (preview.target_rows, preview.impact.delete_images) == (2, 2)+ assert operation.progress.deleted_images == 2+ assert not _exists(invoker, "alpha.png") and not _exists(invoker, "unassigned.png")+ assert _exists(invoker, "beta.png") and _exists(invoker, "bob.png")-def test_force_confirmation_guard_survives_failed_batch_and_restart(+def test_selection_paging_seeks_each_row_without_sorting_the_scope(invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:- _seed_image(invoker, "force-retry.png")- preview = service.create_preview(IntermediatesPreviewRequest(mode="force", scope=_owner("alice")), ALICE)- real_delete = invoker.services.images.delete_intermediates_by_names- monkeypatch.setattr(- invoker.services.images, "delete_intermediates_by_names", MagicMock(side_effect=OSError("busy"))- )- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="force-retry"), ALICE+ """A window of an explicit-row scope is an index seek in rowid order. One OR over many rows would make+ SQLite sort the whole remaining scope on every window, holding the database lock for the run."""+ records = service._records+ targets = [("alice", _project(invoker, "alice", f"P{index}", {})) for index in range(3)] + [("alice", None)]+ for index in range(len(targets)):+ _seed_image(invoker, f"row-{index}.png", project_id=targets[index][1])+ real_scope_clauses = records._scope_clauses+ paging_clauses: list[list[tuple[str, list[object]]]] = []++ def recording_scope_clauses(**kwargs):+ clauses = real_scope_clauses(**kwargs)+ if kwargs.get("per_statement") == 1:+ paging_clauses.append(clauses)+ return clauses++ monkeypatch.setattr(records, "_scope_clauses", recording_scope_clauses)+ batches = list(+ records.iter_deletable_batches(+ "image",+ user_id=None,+ targets=targets,+ mode="safe",+ is_admin=False,+ caller_user_id="alice",+ recent_cutoff=None,+ limit=10,+ ))- assert _wait(service, started.operation_id).progress.unresolved_images == 1- service.stop()- _project(invoker, "alice", "New reference", {"imageName": "force-retry.png"})+ assert sorted(name for batch in batches for name, _ in batch) == [f"row-{index}.png" for index in range(4)]+ assert len(paging_clauses) == 1 and len(paging_clauses[0]) == len(targets)- restored = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))- invoker.services.intermediates = restored- restored.start(invoker)- monkeypatch.setattr(invoker.services.images, "delete_intermediates_by_names", real_delete)- try:- retry = restored.retry_operation(started.operation_id, ALICE)- result = _wait(restored, retry.operation_id)- assert result.progress.retained_images == 1- assert _exists(invoker, "force-retry.png")- finally:- restored.stop()+ deletable_sql, deletable_params = records._deletable_sql("image", "safe", is_admin=False, caller_user_id="alice")+ with invoker.services.image_records._db.transaction() as cursor:+ clock = records._prepare(cursor)+ for clause, params in paging_clauses[0]:+ cursor.execute(+ "EXPLAIN QUERY PLAN " + records._window_sql("image", clause, deletable_sql),+ [*deletable_params, *clock, *params, 0, 10],+ )+ plan = " ".join(str(row[-1]) for row in cursor.fetchall())+ assert "B-TREE FOR ORDER BY" not in plan, plan+++def test_a_matching_scope_over_too_many_rows_is_refused(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(intermediates_default, "MAX_RESOLVED_SCOPE_TARGETS", 1)+ _seed_image(invoker, "a.png", project_id=_project(invoker, "alice", "A", {}))+ _seed_image(invoker, "b.png")++ with pytest.raises(IntermediatesScopeInvalidError, match="narrow"):+ service.create_preview(+ IntermediatesPreviewRequest(mode="safe", scope=IntermediatesScope(kind="matching")), ALICE+ )def test_measurement_skip_set_does_not_starve_later_rows(invoker: Invoker, service: IntermediatesService) -> None:@@ -1435,57 +1503,20 @@ def test_measurement_skip_set_does_not_starve_later_rows(invoker: Invoker, serviassert records.next_unmeasured("image", 1) == [("later-measurable.png", "")]-def test_receipt_write_failure_does_not_strand_the_accepted_queue(+def test_eligible_rows_behind_protected_ones_are_not_starved(invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch) -> None:- original_ensure_worker = service._ensure_worker- monkeypatch.setattr(service, "_ensure_worker", lambda: None)- operation_ids = []- for index in range(2):- _seed_image(invoker, f"queued-{index}.png")- preview = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("alice")), ALICE)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key=f"queued-{index}"), ALICE- )- operation_ids.append(started.operation_id)-- real_save = service._records.save_operation- failures = 0-- def fail_two_writes(*args, **kwargs):- nonlocal failures- if failures < 2:- failures += 1- raise OSError("storage temporarily unavailable")- return real_save(*args, **kwargs)-- monkeypatch.setattr(service._records, "save_operation", fail_two_writes)- monkeypatch.setattr(service, "_ensure_worker", original_ensure_worker)- service._ensure_worker()-- assert _wait(service, operation_ids[0]).status == "failed"- assert _wait(service, operation_ids[1]).status == "completed"---def test_large_single_row_clears_in_bounded_batches_past_protected_items(- invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch-) -> None:- monkeypatch.setattr(intermediates_default, "MAX_OPERATION_TARGETS", 2)+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)_seed_image(invoker, "protected-first.png")_project(invoker, "alice", "Uses image", {"imageName": "protected-first.png"})for index in range(3):_seed_image(invoker, f"eligible-{index}.png")- first, first_result = _run(service, ALICE, _owner("alice"))- assert first.has_more_eligible- assert first.impact.delete_images == 2- assert first.impact.keep_referenced_images == 1- assert first_result.progress.deleted_images == 2+ preview, result = _run(service, ALICE, _owner("alice"))- second, second_result = _run(service, ALICE, _owner("alice"))- assert not second.has_more_eligible- assert second.impact.delete_images == 1- assert second_result.progress.deleted_images == 1+ assert preview.impact.delete_images == 3+ assert preview.impact.keep_referenced_images == 1+ assert result.progress.deleted_images == 3assert _exists(invoker, "protected-first.png")@@ -1586,7 +1617,7 @@ def test_running_graph_keeps_cached_media_or_recomputes_if_cleanup_won(@pytest.mark.parametrize("mode", ["safe", "force"])-def test_cached_media_holds_guard_frozen_targets_until_all_consuming_sessions_end(+def test_cached_media_holds_keep_rows_out_of_a_running_cleanup_until_all_consuming_sessions_end(invoker: Invoker, service: IntermediatesService, mode: str) -> None:from invokeai.app.services.shared.media_references import MediaReferences@@ -1599,11 +1630,9 @@ def test_cached_media_holds_guard_frozen_targets_until_all_consuming_sessions_enreferences = MediaReferences(images={"cached.png"}, videos={"cached.mp4"})assert service.hold_cached_media("first-consumer", references)assert service.hold_cached_media("second-consumer", references)- started = service.start_operation(- IntermediatesOperationRequest(preview_id=preview.preview_id, idempotency_key="before-cache-hit"), ALICE- )- protected = _wait(service, started.operation_id)- assert protected.progress.retained_images == protected.progress.retained_videos == 1+ protected = _wait(service, _start(service, preview).operation_id)+ assert protected.progress.deleted_images == protected.progress.deleted_videos == 0+ assert _exists(invoker, "cached.png")with invoker.services.image_records._db.transaction() as cursor:cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (first,))@@ -1646,7 +1675,7 @@ def test_completed_child_media_survives_until_its_root_finishes(queue.start(invoker)_seed_image(invoker, "cached.png")_seed_video(invoker, "cached.mp4")- frozen = service.create_preview(IntermediatesPreviewRequest(mode=mode, scope=_owner("alice")), ALICE)+ early = service.create_preview(IntermediatesPreviewRequest(mode=mode, scope=_owner("alice")), ALICE)graph = Graph()graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="workflow"))@@ -1684,10 +1713,7 @@ def test_completed_child_media_survives_until_its_root_finishes(service.start(invoker)try:if not reload_records:- operation = service.start_operation(- IntermediatesOperationRequest(preview_id=frozen.preview_id, idempotency_key="handoff"), ALICE- )- completed = _wait(service, operation.operation_id)+ completed = _wait(service, _start(service, early).operation_id)assert completed.progress.deleted_images == completed.progress.deleted_videos == 0preview, completed = _run(service, ALICE, _owner("alice"), mode=mode)assert preview.impact.keep_active_images == 2@@ -1750,8 +1776,10 @@ def test_child_protection_does_not_scan_unrelated_completed_history(db._conn.set_progress_handler(count_instructions, 100)try:- candidates, _ = service._records.page_intermediates("image", after_rowid=0, limit=10)- assert [(item.name, item.classification) for item in candidates] == [("produced.png", "active")]+ classified = service._records.preview_scope(+ user_id=None, targets=None, mode="safe", is_admin=True, caller_user_id="admin", max_acknowledged=10+ )+ assert (classified.counts["image"].active, classified.deletable["image"].count) == (1, 0)return instructionsfinally:db._conn.set_progress_handler(None, 0)@@ -1765,7 +1793,7 @@ def test_child_protection_does_not_scan_unrelated_completed_history()# Count SQLite VM work instead of machine-dependent elapsed time. A scan of# completed rows grows by orders of magnitude; indexed active-root lookups do not.- assert 0 < baseline < 5_000+ assert 0 < baseline < 10_000assert classify() < 3 * baseline@@ -1898,20 +1926,28 @@ def test_quarantined_projects_are_named_when_a_force_clear_would_break_them(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)+ per_caller = intermediates_default.MAX_PREVIEWS_PER_CALLER+ monkeypatch.setattr(intermediates_default, "MAX_PREVIEWS", per_caller + 1)_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)+ for _ in range(per_caller + 2)]- service.start_operation(IntermediatesOperationRequest(preview_id=pending.preview_id, idempotency_key="a"), ADMIN)+ # Alice's loop evicts only her own oldest previews; the administrator's pending one survives.+ _wait(service, _start(service, pending, ADMIN).operation_id, ADMIN)+ for evicted in alice_previews[:2]:+ with pytest.raises(IntermediatesPreviewNotFoundError):+ _start(service, evicted)+ monkeypatch.setattr(intermediates_default, "MAX_PREVIEWS", 2)+ bobs = service.create_preview(IntermediatesPreviewRequest(mode="safe", scope=_owner("bob")), BOB)+ # Past the global cap the oldest previews go, whoever made them.with pytest.raises(IntermediatesPreviewNotFoundError):- service.start_operation(- IntermediatesOperationRequest(preview_id=alice_previews[0].preview_id, idempotency_key="b"), ALICE- )+ _start(service, alice_previews[-2])+ assert _start(service, alice_previews[-1]).status == "pending"+ assert bobs.preview_id in service._previewsdef test_legacy_clear_deletes_every_safe_image_in_bounded_batches(@@ -1964,3 +2000,35 @@ def test_browser_holds_expire_shortly_after_their_last_refresh(invoker: Invoker,)remaining = cursor.fetchone()[0]assert remaining == pytest.approx(BROWSER_HOLD_TTL_SECONDS, abs=60)+++def test_a_non_admin_force_preview_is_not_starved_by_foreign_referenced_rows(+ invoker: Invoker, service: IntermediatesService, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Items another account's document names are kept before any window or batch is bounded, so they never crowd+ out the caller's own eligible items: the old code capped candidates first and could offer nothing."""+ monkeypatch.setattr(intermediates_default, "DELETE_BATCH_SIZE", 1)+ foreign = [f"shared-{index}.png" for index in range(2)]+ for name in foreign:+ _seed_image(invoker, name)+ invoker.services.workflow_records.create(_workflow_naming(name), user_id="bob")+ _seed_image(invoker, "own-referenced.png")+ _project(invoker, "alice", "Drafts", {"imageName": "own-referenced.png"})+ batches: list[list[str]] = []+ real_delete = invoker.services.images.delete_intermediates_by_names+ monkeypatch.setattr(+ invoker.services.images,+ "delete_intermediates_by_names",+ lambda names, guard=None: batches.append(list(names)) or real_delete(names, guard),+ )++ preview, operation = _run(service, ALICE, _owner("alice"), mode="force")++ assert preview.impact.delete_images == 1+ assert preview.impact.keep_referenced_images == len(foreign)+ assert [(doc.kind, doc.name) for doc in preview.affected_documents] == [("project", "Drafts")]+ # The kept rows are never offered to a batch, so the final check has nothing to retain.+ assert batches == [["own-referenced.png"]]+ assert (operation.progress.deleted_images, operation.progress.retained_images) == (1, 0)+ assert not _exists(invoker, "own-referenced.png")+ assert all(_exists(invoker, name) for name in foreign)diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_24_drop_intermediates_operations.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_24_drop_intermediates_operations.pynew file mode 100644index 0000000000..1008b64991--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_24_drop_intermediates_operations.py@@ -0,0 +1,33 @@+"""Persisted cleanup operations are removed; browser holds stay."""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_24_drop_intermediates_operations import (+ build_migration,+)+++def _tables(cursor: sqlite3.Cursor) -> set[str]:+ cursor.execute("SELECT name FROM sqlite_master WHERE type = 'table';")+ return {row[0] for row in cursor.fetchall()}+++def test_drops_operation_tables_and_keeps_browser_holds() -> None:+ cursor = sqlite3.connect(":memory:").cursor()+ cursor.execute("CREATE TABLE intermediates_operations (operation_id TEXT PRIMARY KEY, state_json TEXT);")+ cursor.execute("CREATE TABLE intermediates_operation_targets (operation_id TEXT, media_name TEXT);")+ cursor.execute("CREATE TABLE intermediates_browser_holds (user_id TEXT, lease_id TEXT, media_name TEXT);")+ cursor.execute("INSERT INTO intermediates_browser_holds VALUES ('alice', 'tab', 'held.png');")++ build_migration().callback(cursor)++ assert _tables(cursor) == {"intermediates_browser_holds"}+ cursor.execute("SELECT COUNT(*) FROM intermediates_browser_holds;")+ assert cursor.fetchone()[0] == 1+++def test_runs_on_databases_with_or_without_the_tables() -> None:+ cursor = sqlite3.connect(":memory:").cursor()+ build_migration().callback(cursor)+ build_migration().callback(cursor)+ assert _tables(cursor) == set()