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(images): leave neither row nor file behind when a copy fails
Josh Corbett868ced169e25
diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.pyindex 665fcd8f42..55b6d03cec 100644--- a/invokeai/app/services/images/images_default.py+++ b/invokeai/app/services/images/images_default.py@@ -129,6 +129,15 @@ class ImageService(ImageServiceABC):The copy is never intermediate: an intermediate is a step in someone else's run, and acopy is a thing a person asked for. Starring is not copied either — callers that want ituse the same star route the gallery uses.++ Attaching to the board is checked *before* the file is written, where the video twin writes+ the file first and removes it again on discovering the attachment was lost. Both are fatal+ and both leave nothing behind; the orders differ because `create` — which the video path+ reuses — swallows a failed attachment, so there it can only be detected after the fact.++ Nothing partial survives a failure: the unwind covers everything after the record exists,+ including reading the DTO back, and removes the file as well as the row. A row whose file+ endpoints 404 is a broken gallery entry; a file with no row is disk nobody can reach."""try:record = self.__invoker.services.image_records.get(source_image_name)@@ -140,6 +149,7 @@ class ImageService(ImageServiceABC):image_subfolder = strategy.get_subfolder(image_name, record.image_category, False)record_saved = False+ file_copied = Falsetry:self.__invoker.services.image_records.save(image_name=image_name,@@ -170,9 +180,21 @@ class ImageService(ImageServiceABC):source_subfolder=record.image_subfolder or "",image_subfolder=image_subfolder,)+ file_copied = True++ image_dto = self.get_dto(image_name)+ self._on_changed(image_dto)+ return image_dtoexcept Exception:- # Unwind the record so a failed copy cannot leave the gallery holding a row whose- # file endpoints 404 — the board membership goes with it via the FK.+ # Unwind whatever exists, newest first. The board membership goes with the record+ # via the FK.+ if file_copied:+ try:+ self.__invoker.services.image_files.delete(image_name, image_subfolder=image_subfolder)+ except Exception as cleanup_error:+ self.__invoker.services.logger.error(+ f"Failed to roll back the file for copy {image_name}: {cleanup_error}"+ )if record_saved:try:self.__invoker.services.image_records.delete(image_name)@@ -181,10 +203,6 @@ class ImageService(ImageServiceABC):f"Failed to roll back the record for copy {image_name}: {cleanup_error}")raise-- image_dto = self.get_dto(image_name)- self._on_changed(image_dto)- return image_dtoexcept Exception:self.__invoker.services.logger.error(f"Failed to copy image {source_image_name}", exc_info=True)raisediff --git a/invokeai/app/services/videos/videos_default.py b/invokeai/app/services/videos/videos_default.pyindex d9461c61e1..f344f33f8b 100644--- a/invokeai/app/services/videos/videos_default.py+++ b/invokeai/app/services/videos/videos_default.py@@ -159,7 +159,14 @@ class VideoService(VideoServiceABC):raisedef copy(self, source_video_name: str, board_id: Optional[str] = None, user_id: Optional[str] = None) -> VideoDTO:- """Duplicate a video without moving the source or exposing partial attachment semantics."""+ """Duplicate a video without moving the source or exposing partial attachment semantics.++ A lost board attachment is fatal here as it is for images, but it is caught *after* the copy+ rather than before: this path goes through ``create``, which deliberately swallows a failed+ attachment so a freshly generated video is never lost to it. That leaves no way to refuse up+ front, so the copy is made and then withdrawn — through ``delete``, which takes the files+ with the record.+ """record = self.get_record(source_video_name)metadata = self.get_metadata(source_video_name)first_frame: Optional[Image.Image] = Nonediff --git a/tests/app/routers/test_media_copy.py b/tests/app/routers/test_media_copy.pyindex e55e7c3ff8..d7dc736927 100644--- a/tests/app/routers/test_media_copy.py+++ b/tests/app/routers/test_media_copy.py@@ -193,6 +193,34 @@ def test_a_failed_copy_leaves_no_ghost_record(assert set(mock_invoker.services.image_records.get_image_names().image_names) == before+def _files_under(image_files: DiskImageFileStorage) -> set[Path]:+ return {path for path in image_files.image_root.rglob("*") if path.is_file()}+++def test_a_copy_that_fails_after_its_file_landed_leaves_neither_row_nor_file(+ client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage, monkeypatch+):+ """The unwind has to cover everything after the record exists, not only the steps before the+ file is written. Reading the copy's DTO back is the last thing that can fail, and a failure+ there used to leave both the row and the bytes behind — the row unreachable through the copy+ route that reported the failure, and the file unreachable through anything at all."""+ user_id = _owner_id(client, user1_token)+ source = _create_source_image(mock_invoker, user_id)+ records_before = set(mock_invoker.services.image_records.get_image_names().image_names)+ files_before = _files_under(real_images)++ def explode(image_name: str):+ raise RuntimeError("the DTO read failed after the file was written")++ monkeypatch.setattr(mock_invoker.services.images, "get_dto", explode)++ response = _copy_images(client, user1_token, image_names=[source.image_name])++ assert response.json() == {"copied": [], "failed": [source.image_name]}+ assert set(mock_invoker.services.image_records.get_image_names().image_names) == records_before+ assert _files_under(real_images) == files_before++def test_copying_into_a_board_you_cannot_write_is_refused(client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str, real_images: DiskImageFileStorage):