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 image move recovery for unsupported thumbnail modes (#9497)
Jonathan1a4277322028
diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.pyindex dcac3f56b0..133c71ab05 100644--- a/invokeai/app/services/image_files/image_files_disk.py+++ b/invokeai/app/services/image_files/image_files_disk.py@@ -134,9 +134,14 @@ class DiskImageFileStorage(ImageFileStorageBase):thumbnail_size: int = 256,image_subfolder: str = "",) -> None:+ image_path: Optional[Path] = None+ thumbnail_path: Optional[Path] = None+ image_existed = False+ thumbnail_existed = Falsetry:self.__validate_storage_folders()image_path = self.get_path(image_name, image_subfolder=image_subfolder)+ image_existed = image_path.exists()# Ensure subfolder directories existimage_path.parent.mkdir(parents=True, exist_ok=True)@@ -154,6 +159,14 @@ class DiskImageFileStorage(ImageFileStorageBase):info_dict["invokeai_graph"] = graphpnginfo.add_text("invokeai_graph", graph)+ thumbnail_path = self.get_path(image_name, thumbnail=True, image_subfolder=image_subfolder)+ thumbnail_existed = thumbnail_path.exists()++ # Build the thumbnail before replacing image.info with Invoke metadata. PIL stores+ # palette transparency there, and it must remain available to make_thumbnail().+ thumbnail_path.parent.mkdir(parents=True, exist_ok=True)+ thumbnail_image = make_thumbnail(image, thumbnail_size)+# When saving the image, the image object's info field is not populated. We need to set itimage.info = info_dictcompress_level = self.__invoker.services.configuration.pil_compress_level@@ -167,17 +180,21 @@ class DiskImageFileStorage(ImageFileStorageBase):**save_options,)- thumbnail_path = self.get_path(image_name, thumbnail=True, image_subfolder=image_subfolder)-- # Ensure thumbnail subfolder directories exist- thumbnail_path.parent.mkdir(parents=True, exist_ok=True)-- thumbnail_image = make_thumbnail(image, thumbnail_size)thumbnail_image.save(thumbnail_path)self.__set_cache(image_path, image)self.__set_cache(thumbnail_path, thumbnail_image)except Exception as e:+ # A thumbnail failure must not leave a full-size image with no thumbnail. The+ # names are normally new, but preserve any pre-existing files when save() is+ # used to overwrite an existing image.+ for path, existed in ((image_path, image_existed), (thumbnail_path, thumbnail_existed)):+ if path is not None and not existed:+ try:+ path.unlink(missing_ok=True)+ except OSError:+ pass+ self.evict_cache_paths([path for path in (image_path, thumbnail_path) if path is not None])raise ImageFileSaveException from edef delete(self, image_name: str, image_subfolder: str = "") -> None:diff --git a/invokeai/app/services/image_moves/image_moves_default.py b/invokeai/app/services/image_moves/image_moves_default.pyindex 1ced4ef1b4..5005e9a952 100644--- a/invokeai/app/services/image_moves/image_moves_default.py+++ b/invokeai/app/services/image_moves/image_moves_default.py@@ -491,6 +491,14 @@ class ImageMoveService:)continueraise RuntimeError(f"Neither old nor new image file exists for {item.image_name}")++ old_thumbnail_exists = old_thumbnail_path.exists()+ new_thumbnail_exists = new_thumbnail_path.exists()+ if old_exists and not new_exists and not old_thumbnail_exists and not new_thumbnail_exists:+ # Generate the thumbnail while the source is still available. If this fails,+ # leave the source untouched so recovery can retry the complete operation.+ self._regenerate_thumbnail(old_path, new_thumbnail_path)+if old_exists:new_path.parent.mkdir(parents=True, exist_ok=True)os.replace(old_path, new_path)diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.pyindex 9fded083cb..63b8f3d153 100644--- a/invokeai/app/services/images/images_default.py+++ b/invokeai/app/services/images/images_default.py@@ -106,6 +106,20 @@ class ImageService(ImageServiceABC):raiseexcept ImageFileSaveException:self.__invoker.services.logger.error("Failed to save image file")+ 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 clean up image files after save failure: {str(cleanup_error)}"+ )+ try:+ # Deleting the record also removes any board association through the database+ # foreign key cascade. Both cleanup operations are attempted independently.+ self.__invoker.services.image_records.delete(image_name)+ except Exception as cleanup_error:+ self.__invoker.services.logger.error(+ f"Failed to clean up image record after save failure: {str(cleanup_error)}"+ )raiseexcept Exception as e:self.__invoker.services.logger.error(f"Problem saving image record and file: {str(e)}")diff --git a/invokeai/app/util/thumbnails.py b/invokeai/app/util/thumbnails.pyindex ad722f197e..394150704f 100644--- a/invokeai/app/util/thumbnails.py+++ b/invokeai/app/util/thumbnails.py@@ -11,6 +11,9 @@ def get_thumbnail_name(image_name: str) -> str:def make_thumbnail(image: Image.Image, size: int = 256) -> Image.Image:"""Makes a thumbnail from a PIL Image"""- thumbnail = image.copy()+ # Pillow cannot resize some source modes (notably large ``I;16`` images). Convert to+ # a mode supported by the WEBP thumbnail writer while preserving transparency.+ has_alpha = "A" in image.getbands() or "transparency" in image.info+ thumbnail = image.convert("RGBA" if has_alpha else "RGB")thumbnail.thumbnail(size=(size, size))return thumbnaildiff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex 6b9cbf59dc..3ecdb66818 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -2049,6 +2049,7 @@"imageSavingFailed": "Image Saving Failed","imageUploaded": "Image Uploaded","imageUploadFailed": "Image Upload Failed",+ "imageStorageMaintenanceActive": "Image storage maintenance is active. Recover it before retrying the upload.","videoUploaded": "Video Uploaded","videoUploadFailed": "Video Upload Failed","videoPlaybackFailed": "Unable to Play Video",diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploadFailedDescription.test.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploadFailedDescription.test.tsnew file mode 100644index 0000000000..900f47a83a--- /dev/null+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploadFailedDescription.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { getImageUploadFailedDescription } from './imageUploadFailedDescription';++describe('getImageUploadFailedDescription', () => {+ it('explains that image maintenance blocked the upload', () => {+ expect(+ getImageUploadFailedDescription(+ 'Rejected',+ { status: 409, data: { detail: 'Image storage maintenance is active' } },+ 'Recover image storage maintenance before retrying the upload.'+ )+ ).toBe('Recover image storage maintenance before retrying the upload.');+ });++ it('preserves unrelated upload errors', () => {+ expect(getImageUploadFailedDescription('Request failed with status code 500', { status: 500 }, 'maintenance')).toBe(+ 'Request failed with status code 500'+ );+ });+});diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploadFailedDescription.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploadFailedDescription.tsnew file mode 100644index 0000000000..4e6c8921e1--- /dev/null+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploadFailedDescription.ts@@ -0,0 +1,16 @@+const IMAGE_STORAGE_MAINTENANCE_ACTIVE_DETAIL = 'Image storage maintenance is active';++const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;++export const getImageUploadFailedDescription = (+ errorMessage: string | undefined,+ payload: unknown,+ maintenanceMessage: string+): string | undefined => {+ if (isRecord(payload) && payload.status === 409 && isRecord(payload.data)) {+ if (payload.data.detail === IMAGE_STORAGE_MAINTENANCE_ACTIVE_DETAIL) {+ return maintenanceMessage;+ }+ }+ return errorMessage;+};diff --git a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploaded.ts b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploaded.tsindex f421009030..5db628d2e4 100644--- a/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploaded.ts+++ b/invokeai/frontend/web/src/app/store/middleware/listenerMiddleware/listeners/imageUploaded.ts@@ -8,6 +8,9 @@ import { t } from 'i18next';import { boardsApi } from 'services/api/endpoints/boards';import { imagesApi } from 'services/api/endpoints/images';import type { ImageDTO } from 'services/api/types';++import { getImageUploadFailedDescription } from './imageUploadFailedDescription';+const log = logger('gallery');/**@@ -104,7 +107,11 @@ export const addImageUploadedFulfilledListener = (startAppListening: AppStartLislog.error({ ...sanitizedData }, 'Image upload failed');toast({title: t('toast.imageUploadFailed'),- description: action.error.message,+ description: getImageUploadFailedDescription(+ action.error.message,+ action.payload,+ t('toast.imageStorageMaintenanceActive')+ ),status: 'error',});},diff --git a/tests/app/services/image_files/test_image_files_disk.py b/tests/app/services/image_files/test_image_files_disk.pyindex 75e5938091..caccb34739 100644--- a/tests/app/services/image_files/test_image_files_disk.py+++ b/tests/app/services/image_files/test_image_files_disk.py@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patchimport pytestfrom PIL import Image+from invokeai.app.services.image_files.image_files_common import ImageFileSaveExceptionfrom invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage, _should_use_png_rlefrom invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundExceptionfrom invokeai.app.util.thumbnails import get_thumbnail_name@@ -157,6 +158,73 @@ def test_level_one_png_round_trip_from_disk(tmp_path: Path, mode: str):image.close()+def test_large_16_bit_png_save_creates_thumbnail(tmp_path: Path):+ storage = DiskImageFileStorage(tmp_path)+ mock_invoker = MagicMock()+ mock_invoker.services.configuration.pil_compress_level = 6+ storage._DiskImageFileStorage__invoker = mock_invoker # type: ignore+ image_name = "large-16-bit.png"+ image = Image.new("I;16", (1024, 1024), 32768)++ try:+ storage.save(image=image, image_name=image_name)++ image_path = storage.get_path(image_name)+ thumbnail_path = storage.get_path(image_name, thumbnail=True)+ assert image_path.exists()+ assert thumbnail_path.exists()+ with Image.open(thumbnail_path) as thumbnail:+ thumbnail.load()+ assert thumbnail.format == "WEBP"+ assert thumbnail.mode == "RGB"+ finally:+ image.close()+++def test_palette_transparency_survives_thumbnail_save(tmp_path: Path):+ storage = DiskImageFileStorage(tmp_path)+ mock_invoker = MagicMock()+ mock_invoker.services.configuration.pil_compress_level = 6+ storage._DiskImageFileStorage__invoker = mock_invoker # type: ignore+ image = Image.new("P", (32, 32), 0)+ image.putpalette([255, 0, 0] * 256)+ image.info["transparency"] = 0++ try:+ storage.save(image=image, image_name="transparent-palette.png")++ with Image.open(storage.get_path("transparent-palette.png", thumbnail=True)) as thumbnail:+ thumbnail.load()+ assert thumbnail.mode == "RGBA"+ assert thumbnail.getpixel((0, 0))[3] == 0+ finally:+ image.close()+++def test_save_removes_partial_files_when_thumbnail_save_fails(tmp_path: Path):+ storage = DiskImageFileStorage(tmp_path)+ mock_invoker = MagicMock()+ mock_invoker.services.configuration.pil_compress_level = 6+ storage._DiskImageFileStorage__invoker = mock_invoker # type: ignore+ image_name = "thumbnail-failure.png"+ image = Image.new("RGB", (32, 32), "red")+ broken_thumbnail = MagicMock()+ broken_thumbnail.save.side_effect = OSError("thumbnail filesystem failure")++ try:+ with patch(+ "invokeai.app.services.image_files.image_files_disk.make_thumbnail",+ return_value=broken_thumbnail,+ ):+ with pytest.raises(ImageFileSaveException):+ storage.save(image=image, image_name=image_name)++ assert not storage.get_path(image_name).exists()+ assert not storage.get_path(image_name, thumbnail=True).exists()+ finally:+ image.close()++# ── Subfolder validation tests (Point 1) ──diff --git a/tests/app/services/image_moves/test_image_moves_default.py b/tests/app/services/image_moves/test_image_moves_default.pyindex e9ec55d101..802496556b 100644--- a/tests/app/services/image_moves/test_image_moves_default.py+++ b/tests/app/services/image_moves/test_image_moves_default.py@@ -23,7 +23,7 @@ from invokeai.backend.util.logging import InvokeAILoggerdef _build_db(tmp_path: Path) -> SqliteDatabase:logger = InvokeAILogger.get_logger()- config = InvokeAIAppConfig(use_memory_db=False)+ config = InvokeAIAppConfig(use_memory_db=True)config._root = tmp_pathimage_files = DiskImageFileStorage(tmp_path / "images")return init_db(config=config, logger=logger, image_files=image_files)@@ -197,6 +197,62 @@ def test_move_all_images_continues_after_missing_non_intermediate_source_file(tmassert "committed" in _job_states(service).values()+def test_move_recovers_existing_16_bit_destination_without_thumbnail(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_name = "large-16-bit.png"+ _save_record(records, image_name=image_name, subfolder="", created_at="2024-02-04 04:05:06.000")+ old_path = service.image_files.get_path(image_name)+ old_path.parent.mkdir(parents=True, exist_ok=True)+ image = Image.new("I;16", (1024, 1024), 32768)++ try:+ image.save(old_path, format="PNG")+ move = service.plan_batch(last_image_name="", limit=100)[0]+ job_id = service.create_move_job([move])+ move.new_path.parent.mkdir(parents=True, exist_ok=True)+ move.old_path.replace(move.new_path)++ recovered = service.startup_recovery()++ assert recovered.committed == 1+ assert recovered.errors == 0+ assert records.get(image_name).image_subfolder == "2024/02/04"+ assert move.new_path.exists()+ assert move.new_thumbnail_path.exists()+ assert service.get_job(job_id).state == "committed"+ finally:+ image.close()+++def test_move_does_not_relocate_source_when_thumbnail_generation_fails(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_name = "thumbnail-retry.png"+ _save_record(records, image_name=image_name, subfolder="", created_at="2024-02-05 04:05:06.000")+ old_path = service.image_files.get_path(image_name)+ old_path.parent.mkdir(parents=True, exist_ok=True)+ Image.new("RGB", (32, 32), "red").save(old_path, format="PNG")+ move = service.plan_batch(last_image_name="", limit=100)[0]+ job_id = service.create_move_job([move])++ with patch.object(service, "_regenerate_thumbnail", side_effect=OSError("thumbnail unavailable")):+ with pytest.raises(OSError, match="thumbnail unavailable"):+ service.perform_filesystem_moves(job_id)++ assert move.old_path.exists()+ assert not move.new_path.exists()+ assert records.get(image_name).image_subfolder == ""+ assert service.get_job(job_id).state == "moving"++ recovered = service.startup_recovery()++ assert recovered.committed == 1+ assert recovered.errors == 0+ assert records.get(image_name).image_subfolder == "2024/02/05"+ assert move.new_path.exists()+ assert move.new_thumbnail_path.exists()+ assert service.get_job(job_id).state == "committed"++def test_recovery_treats_missing_intermediate_source_file_as_success(tmp_path: Path) -> None:service, records = _service(tmp_path, strategy="date")image_name = "missing-intermediate-recovery.png"diff --git a/tests/app/services/images/test_images_default.py b/tests/app/services/images/test_images_default.pyindex c97916dd13..c10a43edc5 100644--- a/tests/app/services/images/test_images_default.py+++ b/tests/app/services/images/test_images_default.py@@ -4,18 +4,28 @@ Covers subfolder forwarding for all strategies and the delete_images_on_boardsilent-failure contract (Points 2 & 3 from PR review)."""-from unittest.mock import MagicMock+from pathlib import Path+from unittest.mock import MagicMock, patchimport pytestfrom PIL import Image+from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.image_files.image_files_common import (+ ImageFileSaveException,+)+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStoragefrom invokeai.app.services.image_records.image_records_common import (ImageCategory,ImageRecord,+ ImageRecordNotFoundException,ResourceOrigin,)+from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStoragefrom invokeai.app.services.images.images_default import ImageService+from invokeai.app.services.shared.sqlite.sqlite_util import init_dbfrom invokeai.app.util.misc import get_iso_timestamp+from invokeai.backend.util.logging import InvokeAILogger@pytest.fixture@@ -55,6 +65,79 @@ def _make_record()+def real_image_service(tmp_path: Path) -> tuple[ImageService, SqliteImageRecordStorage, DiskImageFileStorage]:+ logger = InvokeAILogger.get_logger()+ config = InvokeAIAppConfig(use_memory_db=True, image_subfolder_strategy="flat")+ config._root = tmp_path+ storage = DiskImageFileStorage(tmp_path / "images")+ invoker = MagicMock()+ invoker.services.configuration.pil_compress_level = 6+ storage.start(invoker)+ db = init_db(config=config, logger=logger, image_files=storage)+ records = SqliteImageRecordStorage(db=db)++ invoker.services.configuration.image_subfolder_strategy = "flat"+ invoker.services.names.create_image_name.return_value = "uploaded.png"+ invoker.services.image_records = records+ invoker.services.image_files = storage+ invoker.services.board_image_records.get_board_for_image.return_value = None+ invoker.services.urls.get_image_url.return_value = "/api/v1/images/i/uploaded.png"+ invoker.services.logger = MagicMock()++ service = ImageService()+ service.start(invoker)+ return service, records, storage+++def test_create_rolls_back_record_and_files_when_thumbnail_save_fails(+ real_image_service: tuple[ImageService, SqliteImageRecordStorage, DiskImageFileStorage],+) -> None:+ service, records, storage = real_image_service+ image = Image.new("RGB", (32, 32), "red")+ broken_thumbnail = MagicMock()+ broken_thumbnail.save.side_effect = OSError("thumbnail filesystem failure")++ try:+ with patch(+ "invokeai.app.services.image_files.image_files_disk.make_thumbnail",+ return_value=broken_thumbnail,+ ):+ with pytest.raises(ImageFileSaveException):+ service.create(+ image=image,+ image_origin=ResourceOrigin.EXTERNAL,+ image_category=ImageCategory.GENERAL,+ )++ with pytest.raises(ImageRecordNotFoundException):+ records.get("uploaded.png")+ assert not storage.get_path("uploaded.png").exists()+ assert not storage.get_path("uploaded.png", thumbnail=True).exists()+ finally:+ image.close()+++def test_create_accepts_large_16_bit_image(+ real_image_service: tuple[ImageService, SqliteImageRecordStorage, DiskImageFileStorage],+) -> None:+ service, records, storage = real_image_service+ image = Image.new("I;16", (1024, 1024), 32768)++ try:+ service.create(+ image=image,+ image_origin=ResourceOrigin.EXTERNAL,+ image_category=ImageCategory.GENERAL,+ )++ assert records.get("uploaded.png").image_subfolder == ""+ assert storage.get_path("uploaded.png").exists()+ assert storage.get_path("uploaded.png", thumbnail=True).exists()+ finally:+ image.close()++# ── Point 2: subfolder forwarding tests ──