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
fix(intermediates): protect child media and serialize video deletion
Josh Corbettc4885681bfc0
diff --git a/docs/src/content/docs/features/intermediates.mdx b/docs/src/content/docs/features/intermediates.mdxindex 9f28210183..173613574c 100644--- a/docs/src/content/docs/features/intermediates.mdx+++ b/docs/src/content/docs/features/intermediates.mdx@@ -17,7 +17,7 @@ Administrators start on their own account. **Show everyone** expands the view toA normal clear deletes only safe items. It always keeps:-- anything a pending, waiting or running job produced or uses as an input, including cached images and videos reused from an earlier job;+- anything a pending, waiting or running job produced or uses as an input, including cached images and videos reused from an earlier job and completed child-workflow media until the root workflow finishes;- anything created in the last 30 minutes, so an upload the browser is about to reference or enqueue is never collected;- anything the open webv2 editor still references, including unsaved edits and available undo history; the browser refreshes this temporary hold while it is open;- anything a saved project or library workflow still names, such as canvas staging candidates or cropped reference images;diff --git a/invokeai/app/services/intermediates/intermediates_default.py b/invokeai/app/services/intermediates/intermediates_default.pyindex 9d1f730a17..d1e9f8fd79 100644--- a/invokeai/app/services/intermediates/intermediates_default.py+++ b/invokeai/app/services/intermediates/intermediates_default.py@@ -6,8 +6,9 @@ re-applies the policy on the deleting transaction, so a target that became activdurable since the preview is kept. Operation receipts and unresolved targets persist; a restartmakes interrupted work retryable.-Lock order, for anyone adding a caller: image mutation lock (image service) → database lock. The-queue and document writers take only the database lock, so no cycle is possible.+Lock order, for anyone adding a caller: image mutation lock or video deletion lock → database+lock. Image and video deletion never hold each other's locks; queue and document writers take+only the database lock."""import jsondiff --git a/invokeai/app/services/intermediates/intermediates_records_sqlite.py b/invokeai/app/services/intermediates/intermediates_records_sqlite.pyindex a2b3423c9c..5289634b4c 100644--- a/invokeai/app/services/intermediates/intermediates_records_sqlite.py+++ b/invokeai/app/services/intermediates/intermediates_records_sqlite.py@@ -3,7 +3,8 @@One classification expression decides what every intermediate is under the cleanup policy, and itis the same SQL whether it aggregates a summary, freezes a preview's targets or guards a delete:-- ``active``: produced by, or named as an input of, a pending, waiting or running queue item.+- ``active``: produced or referenced by a pending, waiting or running queue item, or a+ completed child of an active root workflow.- ``recent``: created inside the grace window, so an in-flight browser upload is never collectedbefore it is promoted, referenced or enqueued.- ``referenced``: named by a saved project document or library workflow (`media_references`).@@ -34,6 +35,24 @@ Classification = Literal["safe", "referenced", "active", "recent"]ACTIVE_QUEUE_STATUSES = ("pending", "in_progress", "waiting")++def _protected_queue_items_sql() -> str:+ statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)+ # A child becomes completed before its outputs reach its waiting parent. Keep the+ # whole completed subtree protected until the root finishes, including nested calls.+ # CROSS JOIN pins the active roots first, then indexed child lookups, rather than+ # scanning all completed history. Session JSON is fetched only for changed rows.+ return f"""+ SELECT item_id, session_id, status, session_revision FROM session_queue+ WHERE status IN ({statuses})+ UNION ALL+ SELECT child.item_id, child.session_id, child.status, child.session_revision+ FROM session_queue root+ CROSS JOIN session_queue child ON child.root_item_id = root.item_id+ WHERE root.status IN ({statuses}) AND child.status = 'completed'+ """++# Keeps the OR-chain of a selection scope, and every IN list, under SQLITE_MAX_VARIABLE_NUMBER._MAX_SQL_VARIABLES = 500_TARGETS_PER_STATEMENT = 200@@ -94,10 +113,9 @@ class IntermediatesRecordsSqlite:"CREATE TEMP TABLE IF NOT EXISTS intermediates_session_media ""(session_id TEXT, kind TEXT, name TEXT, PRIMARY KEY(session_id, kind, name)) WITHOUT ROWID;")- statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)cursor.execute("DELETE FROM temp.intermediates_session_media WHERE session_id NOT IN "- f"(SELECT session_id FROM session_queue WHERE status IN ({statuses}));"+ f"(SELECT session_id FROM ({_protected_queue_items_sql()}));")def hold_cached_media(self, session_id: str, references: MediaReferences) -> bool:@@ -255,12 +273,11 @@ class IntermediatesRecordsSqlite:@staticmethoddef _classification_sql(kind: MediaKind) -> str:table, name_column, _ = _TABLES[kind]- statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)return f"""CASEWHEN (m.session_id IS NOT NULL- AND m.session_id IN (SELECT session_id FROM session_queue WHERE status IN ({statuses}))+ AND m.session_id IN (SELECT session_id FROM ({_protected_queue_items_sql()}))) OR m.{name_column} IN (SELECT name FROM temp.intermediates_active_media WHERE kind = '{kind}') OR EXISTS (@@ -293,11 +310,10 @@ class IntermediatesRecordsSqlite:) WITHOUT ROWID;""")- statuses = ", ".join(f"'{status}'" for status in ACTIVE_QUEUE_STATUSES)cursor.execute(f"""--sqlSELECT item_id, status || ':' || COALESCE(session_revision, 0)- FROM session_queue WHERE status IN ({statuses});+ FROM ({_protected_queue_items_sql()});""")active = {cast(int, row[0]): str(row[1]) for row in cursor.fetchall()}diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.pyindex a9fac6d417..e182986059 100644--- a/invokeai/app/services/session_queue/session_queue_sqlite.py+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py@@ -63,6 +63,16 @@ MAX_ENQUEUE_RECEIPTS_PER_OWNER = 100_000MAX_ENQUEUE_RECEIPT_BYTES_PER_OWNER = 128 * 1024 * 1024ACKNOWLEDGED_ENQUEUE_RECEIPT_RETENTION_DAYS = 7+# A completed child is still recovery state for its active root, including the interval+# before its returned media is persisted in its parent. Both history-pruning paths must+# retain it; intermediates cleanup also uses these rows to protect the root's media.+PRUNABLE_QUEUE_ITEMS_SQL = """+ status IN ('completed', 'failed', 'canceled')+ AND (root_item_id IS NULL OR root_item_id NOT IN (+ SELECT item_id FROM session_queue WHERE status IN ('pending', 'in_progress', 'waiting')+ ))+"""+# Round-robin dequeue (multiuser fairness): pick the next pending item from the user who was# least-recently served.#@@ -207,14 +217,10 @@ class SqliteSessionQueue(SessionQueueBase):def _prune_terminal_to_limit(self, queue_id: str, keep: int) -> int:"""Prune terminal items (completed/failed/canceled) to keep at most N most-recent items."""with self._db.transaction() as cursor:- where = """--sql+ where = f"""--sqlWHEREqueue_id = ?- AND (- status = 'completed'- OR status = 'failed'- OR status = 'canceled'- )+ AND {PRUNABLE_QUEUE_ITEMS_SQL}"""cursor.execute(f"""--sql@@ -1167,11 +1173,7 @@ class SqliteSessionQueue(SessionQueueBase):where = f"""--sqlWHEREqueue_id = ?- AND (- status = 'completed'- OR status = 'failed'- OR status = 'canceled'- )+ AND {PRUNABLE_QUEUE_ITEMS_SQL}{user_filter}"""params: list[Any] = [queue_id]diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex 7727babace..88ca309f57 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -706,7 +706,10 @@ This behavior is implemented in the runtime scheduler, not in the invocation bodWhen an invocation reuses cached media, `BaseInvocation.invoke_internal()` registers a temporary hold for the consumingqueue session before returning the cached output. The intermediates service checks that every referenced image/videorecord still exists and registers the hold under the same database lock as cleanup. If cleanup already deleted a-record, the invocation recomputes its output. Holds remain effective while the session is pending, running or waiting;+record, the invocation recomputes its output. Holds remain effective while the session is pending, running or waiting.+A completed child remains protected while its root workflow is active: completion precedes the transaction that records+its returned media in the parent. Cleanup protects both its cached references and its produced media through that+handoff, including nested calls. Queue history pruning retains these children until their root ends. Otherterminal/deleted sessions are pruned on the next cache hold or cleanup query. Holds share the cache's process lifetime;after restart, persisted queue sessions supply their own media references and the invocation cache is empty.diff --git a/invokeai/app/services/videos/videos_default.py b/invokeai/app/services/videos/videos_default.pyindex 08aec9314c..80419307f0 100644--- a/invokeai/app/services/videos/videos_default.py+++ b/invokeai/app/services/videos/videos_default.py@@ -1,4 +1,5 @@from pathlib import Path+from threading import RLockfrom typing import Optionalfrom PIL import Image@@ -35,6 +36,12 @@ from invokeai.app.services.videos.videos_common import VideoDTO, video_record_toclass VideoService(VideoServiceABC):__invoker: Invoker+ def __init__(self) -> None:+ super().__init__()+ # Lock order: video deletion, then database. Hold through staging, commit and+ # rollback so a concurrent cleanup cannot purge files a staged delete restores.+ self._delete_lock = RLock()+def start(self, invoker: Invoker) -> None:self.__invoker = invoker@@ -359,34 +366,37 @@ class VideoService(VideoServiceABC):raise edef delete(self, video_name: str) -> None:- token: object | None = None- record_deleted = False- try:- record = self.__invoker.services.video_records.get(video_name)- token = self.__invoker.services.video_files.stage_delete(video_name, video_subfolder=record.video_subfolder)- self.__invoker.services.video_records.delete(video_name)- record_deleted = True+ with self._delete_lock:+ token: object | None = None+ record_deleted = Falsetry:- self.__invoker.services.video_files.commit_delete(token)- except Exception as cleanup_error:- self.__invoker.services.logger.error(f"Failed to purge staged video files: {cleanup_error}")- self._on_deleted(video_name)- except VideoRecordDeleteException:- if token is not None:- self.__invoker.services.video_files.rollback_delete(token)- self.__invoker.services.logger.error("Failed to delete video record")- raise- except VideoFileDeleteException:- self.__invoker.services.logger.error("Failed to delete video file")- raise- except Exception as e:- if token is not None and not record_deleted:+ record = self.__invoker.services.video_records.get(video_name)+ token = self.__invoker.services.video_files.stage_delete(+ video_name, video_subfolder=record.video_subfolder+ )+ self.__invoker.services.video_records.delete(video_name)+ record_deleted = Truetry:+ self.__invoker.services.video_files.commit_delete(token)+ except Exception as cleanup_error:+ self.__invoker.services.logger.error(f"Failed to purge staged video files: {cleanup_error}")+ self._on_deleted(video_name)+ except VideoRecordDeleteException:+ if token is not None:self.__invoker.services.video_files.rollback_delete(token)- except Exception as rollback_error:- self.__invoker.services.logger.error(f"Failed to restore video files: {rollback_error}")- self.__invoker.services.logger.error("Problem deleting video record and file")- raise e+ self.__invoker.services.logger.error("Failed to delete video record")+ raise+ except VideoFileDeleteException:+ self.__invoker.services.logger.error("Failed to delete video file")+ raise+ except Exception as e:+ if token is not None and not record_deleted:+ try:+ self.__invoker.services.video_files.rollback_delete(token)+ except Exception as rollback_error:+ self.__invoker.services.logger.error(f"Failed to restore video files: {rollback_error}")+ self.__invoker.services.logger.error("Problem deleting video record and file")+ raise edef delete_videos_on_board(self, board_id: str, user_id: Optional[str] = None) -> tuple[list[str], list[str]]:# When ``user_id`` is set the lookup filters to videos owned by that user so the@@ -399,32 +409,33 @@ class VideoService(VideoServiceABC):def delete_intermediates_by_names(self, video_names: list[str], guard: Optional[IntermediateDeleteGuard] = None) -> IntermediateDeleteResult:- records = self.__invoker.services.video_records- files = self.__invoker.services.video_files- subfolders = records.get_subfolders(video_names)- if not subfolders:- return IntermediateDeleteResult()-- # Journal the live paths before deleting records. The guard decides inside that transaction- # which records still qualify; a promoted or newly protected video retains its files.- token = files.begin_delete(list(subfolders.items()))- try:- deleted = records.delete_intermediates_by_names(list(subfolders.keys()), guard=guard)- except Exception:+ with self._delete_lock:+ records = self.__invoker.services.video_records+ files = self.__invoker.services.video_files+ subfolders = records.get_subfolders(video_names)+ if not subfolders:+ return IntermediateDeleteResult()++ # Journal the live paths before deleting records. The guard decides inside that transaction+ # which records still qualify; a promoted or newly protected video retains its files.+ token = files.begin_delete(list(subfolders.items()))try:- files.abandon_delete(token)+ deleted = records.delete_intermediates_by_names(list(subfolders.keys()), guard=guard)+ except Exception:+ try:+ files.abandon_delete(token)+ except Exception as cleanup_error:+ self.__invoker.services.logger.error(f"Failed to discard pending video deletion: {cleanup_error}")+ raise+ result = IntermediateDeleteResult(deleted_names=deleted)+ try:+ files.commit_delete(token, video_names=deleted)except Exception as cleanup_error:- self.__invoker.services.logger.error(f"Failed to discard pending video deletion: {cleanup_error}")- raise- result = IntermediateDeleteResult(deleted_names=deleted)- try:- files.commit_delete(token, video_names=deleted)- except Exception as cleanup_error:- self.__invoker.services.logger.error(f"Failed to purge intermediate video files: {cleanup_error}")- result.purge_deferred = list(deleted)- for name in deleted:- self._on_deleted(name)- return result+ self.__invoker.services.logger.error(f"Failed to purge intermediate video files: {cleanup_error}")+ result.purge_deferred = list(deleted)+ for name in deleted:+ self._on_deleted(name)+ return resultdef delete_videos_by_names(self, video_names: list[str]) -> tuple[list[str], list[str]]:"""Delete exactly these videos, returning ``(deleted, failed)``.@@ -432,30 +443,31 @@ class VideoService(VideoServiceABC):Split from ``delete_videos_on_board`` so a caller that must decide whether the board may go*before* destroying anything can enumerate first and delete second."""- try:- records = self.__invoker.services.video_records- files = self.__invoker.services.video_files- return delete_media_by_names(- video_names,- StagedMediaDeleteAdapter(- kind="video",- stage=lambda name: files.stage_delete(name, video_subfolder=records.get(name).video_subfolder),- delete_records=records.delete_many,- rollback=files.rollback_delete,- commit=files.commit_delete,- notify_deleted=self._on_deleted,- log_error=self.__invoker.services.logger.error,- ),- )- except VideoRecordDeleteException:- self.__invoker.services.logger.error("Failed to delete video records")- raise- except VideoFileDeleteException:- self.__invoker.services.logger.error("Failed to delete video files")- raise- except Exception as e:- self.__invoker.services.logger.error(f"Problem deleting video records and files: {str(e)}")- raise e+ with self._delete_lock:+ try:+ records = self.__invoker.services.video_records+ files = self.__invoker.services.video_files+ return delete_media_by_names(+ video_names,+ StagedMediaDeleteAdapter(+ kind="video",+ stage=lambda name: files.stage_delete(name, video_subfolder=records.get(name).video_subfolder),+ delete_records=records.delete_many,+ rollback=files.rollback_delete,+ commit=files.commit_delete,+ notify_deleted=self._on_deleted,+ log_error=self.__invoker.services.logger.error,+ ),+ )+ except VideoRecordDeleteException:+ self.__invoker.services.logger.error("Failed to delete video records")+ raise+ except VideoFileDeleteException:+ self.__invoker.services.logger.error("Failed to delete video files")+ raise+ except Exception as e:+ self.__invoker.services.logger.error(f"Problem deleting video records and files: {str(e)}")+ raise edef get_video_names(self,diff --git a/tests/app/services/intermediates/test_intermediates_service.py b/tests/app/services/intermediates/test_intermediates_service.pyindex e9c71ec383..2f2ca91e58 100644--- a/tests/app/services/intermediates/test_intermediates_service.py+++ b/tests/app/services/intermediates/test_intermediates_service.py@@ -140,13 +140,21 @@ def _seed_video(invoker: Invoker, name: str, *, user_id: str = "alice", is_interdef _enqueue_row(- invoker: Invoker, *, session_id: str, status: str, user_id: str = "alice", session_json: str = "{}"+ invoker: Invoker,+ *,+ session_id: str,+ status: str,+ user_id: str = "alice",+ session_json: str = "{}",+ root_item_id: Optional[int] = None,+ parent_item_id: Optional[int] = None,) -> int:with invoker.services.image_records._db.transaction() as cursor:cursor.execute(- "INSERT INTO session_queue (queue_id, session, session_id, batch_id, priority, user_id, status)"- " VALUES ('default', ?, ?, ?, 0, ?, ?);",- (session_json, session_id, uuid.uuid4().hex, user_id, status),+ "INSERT INTO session_queue "+ "(queue_id, session, session_id, batch_id, priority, user_id, status, root_item_id, parent_item_id)"+ " VALUES ('default', ?, ?, ?, 0, ?, ?, ?, ?);",+ (session_json, session_id, uuid.uuid4().hex, user_id, status, root_item_id, parent_item_id),)return int(cursor.lastrowid or 0)@@ -1359,3 +1367,189 @@ def test_missing_cached_media_does_not_leave_a_partial_hold(invoker, service):)_, completed = _run(service, ALICE, _owner("alice"))assert completed.progress.deleted_images == 1++[email protected]("mode", ["safe", "force"])[email protected]("reload_records", [False, True])+def test_completed_child_media_survives_until_its_root_finishes(invoker, service, mode, reload_records):+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation+ from invokeai.app.invocations.fields import ImageField, VideoField+ from invokeai.app.invocations.workflow_return import WorkflowReturnOutput+ from invokeai.app.services.shared.graph import Graph, GraphExecutionState+ from invokeai.app.services.shared.media_references import MediaReferences++ queue = invoker.services.session_queue+ queue.start(invoker)+ _seed_image(invoker, "cached.png")+ _seed_video(invoker, "cached.mp4")+ frozen = service.create_preview(IntermediatesPreviewRequest(mode=mode, scope=_owner("alice")), ALICE)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="workflow"))+ root = GraphExecutionState(graph=graph)+ invocation = root.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)+ frame = root.build_workflow_call_frame(invocation.id, "workflow")+ root.begin_waiting_on_workflow_call(frame)+ children = [root.create_child_workflow_execution_state(Graph(), frame) for _ in range(2)]+ root.attach_waiting_workflow_call_child_sessions(children)+ root_id = _enqueue_row(invoker, session_id=root.id, status="in_progress", session_json=root.model_dump_json())+ queue.enqueue_workflow_call_children(queue.get_queue_item(root_id), [(session, None) for session in children])+ child = queue.dequeue()+ assert child is not None+ assert service.hold_cached_media(child.session_id, MediaReferences(images={"cached.png"}, videos={"cached.mp4"}))+ output = WorkflowReturnOutput(+ values={"image": ImageField(image_name="cached.png"), "video": VideoField(video_name="cached.mp4")}+ )+ child.session.results["return"] = output+ queue.save_queue_item_session(child.item_id, child.session)+ _seed_image(invoker, "produced.png", session_id=child.session_id)+ queue.complete_queue_item(child.item_id)+ # This is the real gap: the child is terminal, its sibling is pending, and the waiting+ # parent's persisted session does not contain the returned media yet.+ assert "cached.png" not in queue.get_queue_item(root_id).session.model_dump_json()++ # Clearing completed queue history must not discard an unconsumed child result.+ assert queue.prune("default").deleted == 0++ if reload_records:+ service.stop()+ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("DROP TABLE IF EXISTS temp.intermediates_session_media;")+ service = IntermediatesService(IntermediatesRecordsSqlite(invoker.services.image_records._db))+ 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)+ assert completed.progress.deleted_images == completed.progress.deleted_videos == 0+ preview, completed = _run(service, ALICE, _owner("alice"), mode=mode)+ assert preview.impact.keep_active_images == 2+ assert preview.impact.keep_active_videos == 1+ assert completed.progress.deleted_images == completed.progress.deleted_videos == 0+ assert _exists(invoker, "cached.png") and _exists(invoker, "produced.png")++ queue.record_workflow_call_child_completion(root_id, child.item_id, output.values)+ queue.cancel_queue_item(root_id)+ _, completed = _run(service, ALICE, _owner("alice"), mode=mode)+ assert completed.progress.deleted_images == 2+ assert completed.progress.deleted_videos == 1+ finally:+ if reload_records:+ service.stop()+++def test_completed_nested_child_keeps_media_while_its_root_is_active(invoker, service):+ from invokeai.app.services.shared.media_references import MediaReferences++ root = _enqueue_row(invoker, session_id="root", status="waiting")+ parent = _enqueue_row(invoker, session_id="parent", status="completed", root_item_id=root, parent_item_id=root)+ child = _enqueue_row(invoker, session_id="leaf", status="in_progress", root_item_id=root, parent_item_id=parent)+ _seed_image(invoker, "produced.png", session_id="leaf")+ _seed_video(invoker, "cached.mp4")+ assert service.hold_cached_media("leaf", MediaReferences(videos={"cached.mp4"}))+ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (child,))++ for mode in ("safe", "force"):+ preview, completed = _run(service, ALICE, _owner("alice"), mode=mode)+ assert preview.impact.keep_active_images == preview.impact.keep_active_videos == 1+ assert completed.progress.deleted_images == completed.progress.deleted_videos == 0++ with invoker.services.image_records._db.transaction() as cursor:+ cursor.execute("UPDATE session_queue SET status = 'completed' WHERE item_id = ?", (root,))+ _, completed = _run(service, ALICE, _owner("alice"))+ assert completed.progress.deleted_images == completed.progress.deleted_videos == 1+++def test_child_protection_does_not_scan_unrelated_completed_history(invoker, service):+ root = _enqueue_row(invoker, session_id="root", status="waiting")+ _enqueue_row(invoker, session_id="child", status="completed", root_item_id=root, parent_item_id=root)+ _seed_image(invoker, "produced.png", session_id="child")+ db = invoker.services.image_records._db++ def classify():+ instructions = 0++ def count_instructions():+ nonlocal instructions+ instructions += 100+ return 0++ db._conn.set_progress_handler(count_instructions, 100)+ try:+ candidates = service._records.list_candidates("image", user_id="alice", targets=None)+ assert [(item.name, item.classification) for item in candidates] == [("produced.png", "active")]+ return instructions+ finally:+ db._conn.set_progress_handler(None, 0)++ baseline = classify()+ with db.transaction() as cursor:+ cursor.executemany(+ "INSERT INTO session_queue (queue_id, session, session_id, batch_id, user_id, status) "+ "VALUES ('default', '{}', ?, 'history', 'alice', 'completed');",+ [(f"history-{index}",) for index in range(20_000)],+ )+ # 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 classify() < 3 * baseline++[email protected]("bulk", [False, True])+def test_video_cleanup_cannot_purge_files_during_staged_deletion(invoker, service, monkeypatch, bulk):+ from concurrent.futures import ThreadPoolExecutor, TimeoutError+ from threading import Event++ _seed_video(invoker, "racy.mp4")+ files = invoker.services.video_files+ video_path = files.get_path("racy.mp4")+ thumbnail_path = files.get_path("racy.mp4", thumbnail=True)+ thumbnail_path.parent.mkdir(parents=True, exist_ok=True)+ thumbnail_path.write_bytes(b"thumbnail")+ staging_paused = Event()+ resume_staging = Event()+ cleanup_started = Event()+ real_replace = Path.replace++ def pause_thumbnail_move(path, target):+ if path == thumbnail_path:+ staging_paused.set()+ assert resume_staging.wait(10)+ return real_replace(path, target)++ monkeypatch.setattr(Path, "replace", pause_thumbnail_move)++ def delete_video():+ if bulk:+ assert invoker.services.videos.delete_videos_by_names(["racy.mp4"]) == (["racy.mp4"], [])+ else:+ invoker.services.videos.delete("racy.mp4")++ def cleanup():+ cleanup_started.set()+ return _run(service, ALICE, _owner("alice"))[1]++ with ThreadPoolExecutor(max_workers=2) as executor:+ deletion = executor.submit(delete_video)+ try:+ assert staging_paused.wait(10)+ clearing = executor.submit(cleanup)+ assert cleanup_started.wait(10)+ # Without serialization, cleanup removes the thumbnail after stage_delete's+ # exists() check, making its replace() fail and roll the MP4 back as an orphan.+ with pytest.raises(TimeoutError):+ clearing.result(timeout=0.5)+ finally:+ resume_staging.set()+ deletion.result(timeout=10)+ completed = clearing.result(timeout=10)+ assert completed.progress.deleted_videos == 0+ with pytest.raises(VideoRecordNotFoundException):+ invoker.services.video_records.get("racy.mp4")+ assert not video_path.exists()+ assert not thumbnail_path.exists()+ assert not list(video_path.parent.glob(".delete_*"))diff --git a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.pyindex 291cf49f64..a7169f96c3 100644--- a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py@@ -540,6 +540,29 @@ def test_concurrent_workflow_call_child_completions_preserve_both_siblings(}[email protected]("limited", [False, True])+def test_history_pruning_retains_children_until_their_root_ends(session_queue, limited):+ root, _, child_sessions = _build_waiting_workflow_call_parent(session_queue, child_count=2)+ children = session_queue.enqueue_workflow_call_children(+ session_queue.get_queue_item(root), [(session, None) for session in child_sessions]+ )+ session_queue.complete_queue_item(children[0].item_id)+ old = _insert_queue_item(session_queue, session=GraphExecutionState(graph=Graph()), status="completed")++ def prune():+ if limited:+ return session_queue._prune_terminal_to_limit("default", keep=0)+ return session_queue.prune("default", user_id="user-1").deleted++ assert prune() == 1+ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(old)+ assert session_queue.get_queue_item(children[0].item_id).status == "completed"++ session_queue.cancel_queue_item(root)+ assert prune() == 3++def test_enqueue_workflow_call_child_rejects_full_pending_queue(session_queue: SqliteSessionQueue) -> None:parent_graph = Graph()parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))