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 truncated image moves (#9545)
Jonathan0b6a024f2ff6
diff --git a/docs/src/content/docs/features/image-storage-maintenance.mdx b/docs/src/content/docs/features/image-storage-maintenance.mdxindex 180ac6dcc3..7f5ca0e97c 100644--- a/docs/src/content/docs/features/image-storage-maintenance.mdx+++ b/docs/src/content/docs/features/image-storage-maintenance.mdx@@ -23,11 +23,11 @@ The UI shows the move or recovery state until the job is complete or requires maThe move process is crash-recoverable. InvokeAI records each move job in its database before moving files, moves full-size images and thumbnails on disk, and updates `images.image_subfolder` only after the filesystem move succeeds.-If InvokeAI stops during a move, recovery resumes incomplete jobs. If recovery finds an ambiguous filesystem state, such as both the old and new full-size image files existing or neither file existing, it halts the job for manual repair instead of blindly updating the database.+If InvokeAI stops during a move, recovery resumes incomplete jobs. If recovery finds an ambiguous filesystem state, such as both the old and new full-size image files existing or neither file existing, it halts that item for manual repair instead of blindly updating the database. Other items in the same job are still finalized, and the maintenance lock is released when the job is recorded as failed.Recovery finalizes jobs that were already recorded before the stop. Images that had not yet been planned into a move job are not moved by recovery itself. The Settings panel reports how many images still need moving; run **Start Move** again to continue.-Missing intermediate image files are treated as already cleaned up and do not halt the move. Missing non-intermediate image files still require operator attention.+Missing intermediate image files are treated as already cleaned up and do not halt the move. Missing non-intermediate image files, unreadable images, and truncated images are recorded as failed items. When the full-size file is still at its original path, recovery leaves it there so it can be repaired or removed safely. If a previous filesystem move already placed the full-size file at its destination, recovery keeps that destination and reconciles the database before recording the item as failed. After recovery releases the lock, back up the failed file and either replace it with a valid image or delete its image record from the gallery, then run **Start Move** again if images still need moving. Do not delete an active journal row or edit `images.image_subfolder` while maintenance is active.For the `date` strategy, existing images are moved according to their original image creation timestamp stored in the database, not according to the time the maintenance job is run.diff --git a/invokeai/app/services/image_moves/image_moves_default.py b/invokeai/app/services/image_moves/image_moves_default.pyindex 5005e9a952..03077a84a6 100644--- a/invokeai/app/services/image_moves/image_moves_default.py+++ b/invokeai/app/services/image_moves/image_moves_default.py@@ -7,7 +7,7 @@ from datetime import datetimefrom pathlib import Pathfrom typing import Literal, Sequence, cast-from PIL import Image+from PIL import Image, UnidentifiedImageErrorfrom invokeai.app.services.config import InvokeAIAppConfigfrom invokeai.app.services.image_files.image_files_base import ImageFileStorageBase@@ -64,6 +64,10 @@ class ImageMoveQueueActive(Exception):pass+class UnreadableImageError(Exception):+ pass++class ImageMoveService:def __init__(self,@@ -215,8 +219,8 @@ class ImageMoveService:planned += len(moves)try:self.perform_filesystem_moves(job_id)- self.commit_database_updates(job_id)- committed += len(moves)+ committed += self.commit_database_updates(job_id)+ errors += self._count_job_errors(job_id)except Exception as e:errors += 1self.record_job_error_message(job_id, str(e))@@ -242,14 +246,16 @@ class ImageMoveService:try:self.complete_partial_filesystem_moves(job_id)self.cleanup_empty_source_dirs(job_id)- self.commit_database_updates(job_id)- committed += len(self._get_items(job_id))+ committed += self.commit_database_updates(job_id)except Exception as e:- errors += 1if self._is_unrecoverable_error(e):self.mark_job_unrecoverable(job_id, str(e))+ errors += max(1, self._count_job_errors(job_id))else:+ errors += 1self.record_job_error_message(job_id, str(e))+ else:+ errors += self._count_job_errors(job_id)return ImageMoveResult(committed=committed, errors=errors)def plan_batch(self, last_image_name: str, limit: int) -> list[PlannedImageMove]:@@ -463,66 +469,104 @@ class ImageMoveService:self._set_job_state(job_id, "moved")def complete_partial_filesystem_moves(self, job_id: int) -> None:- items = self._get_items(job_id)+ items = self._get_items(job_id, include_terminal=False)if not items:- raise ValueError(f"Image move job {job_id} has no items")+ if self._get_items(job_id):+ return+ raise RuntimeError(f"Image move job {job_id} has no items")for item in items:- old_path = self.image_files.get_path(item.image_name, image_subfolder=item.old_subfolder)- new_path = self.image_files.get_path(item.image_name, image_subfolder=item.new_subfolder)- old_thumbnail_path = self.image_files.get_path(- item.image_name, thumbnail=True, image_subfolder=item.old_subfolder- )- new_thumbnail_path = self.image_files.get_path(- item.image_name, thumbnail=True, image_subfolder=item.new_subfolder- )- old_exists = old_path.exists()- new_exists = new_path.exists()- if old_exists and new_exists:- raise RuntimeError(f"Both old and new image files exist for {item.image_name}")- if not old_exists and not new_exists:- if item.is_intermediate:- self._mark_missing_intermediate_moved(- job_id=job_id,- image_name=item.image_name,- old_path=old_path,- new_path=new_path,- old_thumbnail_path=old_thumbnail_path,- new_thumbnail_path=new_thumbnail_path,- )- continue- raise 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)- self._fsync_file(new_path)- self._fsync_dir(new_path.parent)- self._fsync_dir(old_path.parent)-- old_thumbnail_exists = old_thumbnail_path.exists()- new_thumbnail_exists = new_thumbnail_path.exists()- if old_thumbnail_exists and new_thumbnail_exists:- self._regenerate_thumbnail(new_path, new_thumbnail_path)- old_thumbnail_path.unlink()- self._fsync_dir(old_thumbnail_path.parent)- elif old_thumbnail_exists and not new_thumbnail_exists:- new_thumbnail_path.parent.mkdir(parents=True, exist_ok=True)- os.replace(old_thumbnail_path, new_thumbnail_path)- self._fsync_file(new_thumbnail_path)- self._fsync_dir(new_thumbnail_path.parent)- self._fsync_dir(old_thumbnail_path.parent)- elif not new_thumbnail_exists:- self._regenerate_thumbnail(new_path, new_thumbnail_path)-- self.image_files.evict_cache_paths([old_path, new_path, old_thumbnail_path, new_thumbnail_path])- self.mark_item_moved(job_id, item.image_name)+ try:+ self._complete_partial_filesystem_move(job_id, item)+ except Exception as e:+ if not self._is_unrecoverable_error(e):+ raise+ self._reconcile_destination_subfolder(item)+ self.mark_item_unrecoverable(job_id, item.image_name, f"{item.image_name}: {e}")+ self._logger.error("Image move skipped unrecoverable item %s: %s", item.image_name, e)++ def _complete_partial_filesystem_move(self, job_id: int, item: PlannedImageMove) -> None:+ old_path = self.image_files.get_path(item.image_name, image_subfolder=item.old_subfolder)+ new_path = self.image_files.get_path(item.image_name, image_subfolder=item.new_subfolder)+ old_thumbnail_path = self.image_files.get_path(+ item.image_name, thumbnail=True, image_subfolder=item.old_subfolder+ )+ new_thumbnail_path = self.image_files.get_path(+ item.image_name, thumbnail=True, image_subfolder=item.new_subfolder+ )+ old_exists = old_path.exists()+ new_exists = new_path.exists()+ if old_exists and new_exists:+ raise RuntimeError(f"Both old and new image files exist for {item.image_name}")+ if not old_exists and not new_exists:+ if item.is_intermediate:+ self._mark_missing_intermediate_moved(+ job_id=job_id,+ image_name=item.image_name,+ old_path=old_path,+ new_path=new_path,+ old_thumbnail_path=old_thumbnail_path,+ new_thumbnail_path=new_thumbnail_path,+ )+ return+ raise 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)+ or (old_thumbnail_exists and new_thumbnail_exists)+ )+ ):+ # Generate the thumbnail while the source is still available. If this fails,+ # leave the source untouched so transient failures can be retried and corrupt+ # images can be repaired or removed by the operator.+ self._regenerate_thumbnail(old_path, new_thumbnail_path)++ if not old_exists and new_exists and not old_thumbnail_exists and not new_thumbnail_exists:+ self._regenerate_thumbnail(new_path, new_thumbnail_path)++ if old_exists:+ new_path.parent.mkdir(parents=True, exist_ok=True)+ os.replace(old_path, new_path)+ self._fsync_file(new_path)+ self._fsync_dir(new_path.parent)+ self._fsync_dir(old_path.parent)++ old_thumbnail_exists = old_thumbnail_path.exists()+ new_thumbnail_exists = new_thumbnail_path.exists()+ if old_thumbnail_exists and new_thumbnail_exists:+ old_thumbnail_path.unlink()+ self._fsync_dir(old_thumbnail_path.parent)+ elif old_thumbnail_exists and not new_thumbnail_exists:+ new_thumbnail_path.parent.mkdir(parents=True, exist_ok=True)+ os.replace(old_thumbnail_path, new_thumbnail_path)+ self._fsync_file(new_thumbnail_path)+ self._fsync_dir(new_thumbnail_path.parent)+ self._fsync_dir(old_thumbnail_path.parent)+ elif not new_thumbnail_exists:+ self._regenerate_thumbnail(new_path, new_thumbnail_path)++ self.image_files.evict_cache_paths([old_path, new_path, old_thumbnail_path, new_thumbnail_path])+ self.mark_item_moved(job_id, item.image_name)++ def _reconcile_destination_subfolder(self, item: PlannedImageMove) -> None:+ old_path = self.image_files.get_path(item.image_name, image_subfolder=item.old_subfolder)+ new_path = self.image_files.get_path(item.image_name, image_subfolder=item.new_subfolder)+ if old_path.exists() or not new_path.exists():+ return+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ UPDATE images+ SET image_subfolder = ?+ WHERE image_name = ?+ AND image_subfolder = ?;+ """,+ (item.new_subfolder, item.image_name, item.old_subfolder),+ )def cleanup_empty_source_dirs(self, job_id: int) -> None:for item in self._get_items(job_id):@@ -535,7 +579,7 @@ class ImageMoveService:self.image_files.thumbnail_root,)- def commit_database_updates(self, job_id: int) -> None:+ def commit_database_updates(self, job_id: int) -> int:with self._db.transaction() as cursor:cursor.execute("""--sql@@ -567,6 +611,7 @@ class ImageMoveService:FROM image_subfolder_move_items AS itemLEFT JOIN images ON images.image_name = item.image_nameWHERE item.job_id = ?+ AND item.state = 'moved'AND (images.image_name IS NULLOR images.deleted_at IS NOT NULL@@ -579,13 +624,44 @@ class ImageMoveService:if invalid_count:raise RuntimeError(f"Image move job {job_id} failed commit validation")cursor.execute(- "UPDATE image_subfolder_move_items SET state = 'committed' WHERE job_id = ?;",+ "SELECT COUNT(*) FROM image_subfolder_move_items WHERE job_id = ? AND state = 'moved';",(job_id,),)+ moved_count = cast(int, cursor.fetchone()[0])cursor.execute(- "UPDATE image_subfolder_move_jobs SET state = 'committed', error_message = NULL WHERE id = ?;",+ """--sql+ SELECT error_message+ FROM image_subfolder_move_items+ WHERE job_id = ? AND state = 'error'+ ORDER BY image_name;+ """,(job_id,),)+ error_rows = cursor.fetchall()+ error_messages = [cast(str, row[0]) for row in error_rows if row[0]]+ cursor.execute(+ "UPDATE image_subfolder_move_items SET state = 'committed' WHERE job_id = ? AND state = 'moved';",+ (job_id,),+ )+ if not error_rows:+ cursor.execute(+ "UPDATE image_subfolder_move_jobs SET state = 'committed', error_message = NULL WHERE id = ?;",+ (job_id,),+ )+ else:+ cursor.execute(+ "UPDATE image_subfolder_move_jobs SET state = 'error', error_message = ? WHERE id = ?;",+ ("\n".join(error_messages) or "One or more image move items could not be completed", job_id),+ )+ return moved_count++ def _count_job_errors(self, job_id: int) -> int:+ with self._db.transaction() as cursor:+ cursor.execute(+ "SELECT COUNT(*) FROM image_subfolder_move_items WHERE job_id = ? AND state = 'error';",+ (job_id,),+ )+ return cast(int, cursor.fetchone()[0])def mark_item_moved(self, job_id: int, image_name: str) -> None:with self._db.transaction() as cursor:@@ -601,6 +677,17 @@ class ImageMoveService:(message, job_id),)+ def mark_item_unrecoverable(self, job_id: int, image_name: str, message: str) -> None:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ UPDATE image_subfolder_move_items+ SET state = 'error', error_message = ?+ WHERE job_id = ? AND image_name = ?;+ """,+ (message, job_id, image_name),+ )+def mark_job_unrecoverable(self, job_id: int, message: str) -> None:with self._db.transaction() as cursor:cursor.execute(@@ -657,17 +744,18 @@ class ImageMoveService:return f"{timestamp.year}/{timestamp.month:02d}/{timestamp.day:02d}"raise ValueError(f"Unknown image subfolder strategy: {strategy}")- def _get_items(self, job_id: int) -> list[PlannedImageMove]:+ def _get_items(self, job_id: int, include_terminal: bool = True) -> list[PlannedImageMove]:with self._db.transaction() as cursor:- cursor.execute(- """--sql+ query = """--sqlSELECT image_name, old_subfolder, new_subfolder, is_intermediateFROM image_subfolder_move_itemsWHERE job_id = ?- ORDER BY image_name;- """,- (job_id,),- )+ """+ params: tuple[object, ...] = (job_id,)+ if not include_terminal:+ query += " AND state NOT IN ('committed', 'error')"+ query += " ORDER BY image_name;"+ cursor.execute(query, params)rows = cursor.fetchall()return [PlannedImageMove(@@ -737,20 +825,23 @@ class ImageMoveService:def _regenerate_thumbnail(self, image_path: Path, thumbnail_path: Path) -> None:thumbnail_path.parent.mkdir(parents=True, exist_ok=True)- with Image.open(image_path) as image:- thumbnail = make_thumbnail(image)- with tempfile.NamedTemporaryFile(- dir=thumbnail_path.parent, prefix=f".{thumbnail_path.name}.", suffix=".tmp", delete=False- ) as temp_file:- temp_path = Path(temp_file.name)- try:- thumbnail.save(temp_path, format="WEBP")- self._fsync_file(temp_path)- os.replace(temp_path, thumbnail_path)- self._fsync_file(thumbnail_path)- self._fsync_dir(thumbnail_path.parent)- finally:- temp_path.unlink(missing_ok=True)+ try:+ with Image.open(image_path) as image:+ thumbnail = make_thumbnail(image)+ except (UnidentifiedImageError, Image.DecompressionBombError, OSError) as e:+ raise UnreadableImageError(f"Unable to decode image {image_path}: {e}") from e+ with tempfile.NamedTemporaryFile(+ dir=thumbnail_path.parent, prefix=f".{thumbnail_path.name}.", suffix=".tmp", delete=False+ ) as temp_file:+ temp_path = Path(temp_file.name)+ try:+ thumbnail.save(temp_path, format="WEBP")+ self._fsync_file(temp_path)+ os.replace(temp_path, thumbnail_path)+ self._fsync_file(thumbnail_path)+ self._fsync_dir(thumbnail_path.parent)+ finally:+ temp_path.unlink(missing_ok=True)def _mark_missing_intermediate_moved(self,@@ -816,6 +907,8 @@ class ImageMoveService:self._logger.debug("Unable to close directory fsync handle: %s: %s", path, e)def _is_unrecoverable_error(self, error: Exception) -> bool:+ if isinstance(error, UnreadableImageError):+ return Truereturn isinstance(error, RuntimeError) and (str(error).startswith("Both old and new image files exist")or str(error).startswith("Neither old nor new image file exists")diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageStorageMaintenance.tsx b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageStorageMaintenance.tsxindex 2da533e990..1ca8200a70 100644--- a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageStorageMaintenance.tsx+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsImageStorageMaintenance.tsx@@ -12,6 +12,8 @@ import {} from 'services/api/endpoints/imageMoves';import type { S } from 'services/api/types';+import { isTerminalImageMoveJobState } from './imageStorageMaintenanceUtils';+const getOperationKey = (operation: S['ImageMoveStatusResponse']['operation']) => {if (operation === 'move_all') {return 'settings.imageStorageMaintenanceOperationMove';@@ -66,7 +68,7 @@ export const SettingsImageStorageMaintenance = memo(() => {}, [canAccess, isRunning]);useEffect(() => {- if (!latestJob || latestJob.state !== 'committed' || isRunning) {+ if (!latestJob || !isTerminalImageMoveJobState(latestJob.state) || isRunning) {return;}if (invalidatedImageMoveJobIds.has(latestJob.id)) {diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/imageStorageMaintenanceUtils.test.ts b/invokeai/frontend/web/src/features/system/components/SettingsModal/imageStorageMaintenanceUtils.test.tsnew file mode 100644index 0000000000..e69a20892f--- /dev/null+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/imageStorageMaintenanceUtils.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { isTerminalImageMoveJobState } from './imageStorageMaintenanceUtils';++describe(isTerminalImageMoveJobState.name, () => {+ it('recognizes committed and partial-success jobs as terminal', () => {+ expect(isTerminalImageMoveJobState('committed')).toBe(true);+ expect(isTerminalImageMoveJobState('error')).toBe(true);+ });++ it('does not recognize active jobs as terminal', () => {+ expect(isTerminalImageMoveJobState('planned')).toBe(false);+ expect(isTerminalImageMoveJobState('moving')).toBe(false);+ expect(isTerminalImageMoveJobState('moved')).toBe(false);+ expect(isTerminalImageMoveJobState(undefined)).toBe(false);+ });+});diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/imageStorageMaintenanceUtils.ts b/invokeai/frontend/web/src/features/system/components/SettingsModal/imageStorageMaintenanceUtils.tsnew file mode 100644index 0000000000..5d48f522d0--- /dev/null+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/imageStorageMaintenanceUtils.ts@@ -0,0 +1,4 @@+import type { S } from 'services/api/types';++export const isTerminalImageMoveJobState = (state: S['ImageMoveJobResponse']['state'] | undefined): boolean =>+ state === 'committed' || state === 'error';diff --git a/tests/app/services/image_moves/test_image_moves_default.py b/tests/app/services/image_moves/test_image_moves_default.pyindex 802496556b..e0d29dd4c8 100644--- a/tests/app/services/image_moves/test_image_moves_default.py+++ b/tests/app/services/image_moves/test_image_moves_default.py@@ -12,6 +12,7 @@ from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorfrom invokeai.app.services.image_moves.image_moves_default import (ImageMoveQueueActive,ImageMoveService,+ UnreadableImageError,)from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage@@ -69,6 +70,13 @@ def _save_image(service.image_files.save(Image.new("RGB", (16, 16), color), image_name=image_name, image_subfolder=subfolder)+def _corrupt_png_idat(path: Path) -> None:+ data = bytearray(path.read_bytes())+ idat_data_offset = data.index(b"IDAT") + 4+ data[idat_data_offset + 1] ^= 0xFF+ path.write_bytes(data)++def _service(tmp_path: Path, strategy: str = "date") -> tuple[ImageMoveService, SqliteImageRecordStorage]:db = _build_db(tmp_path)records = SqliteImageRecordStorage(db=db)@@ -224,6 +232,46 @@ def test_move_recovers_existing_16_bit_destination_without_thumbnail(tmp_path: Pimage.close()+def test_regenerate_thumbnail_closes_temp_file_before_writing(tmp_path: Path) -> None:+ service, _records = _service(tmp_path, strategy="date")++ class TrackingTempFile:+ name = str(tmp_path / "thumbnail.tmp")++ def __init__(self) -> None:+ self.closed = False++ def __enter__(self) -> "TrackingTempFile":+ return self++ def __exit__(self, *_args) -> None:+ self.closed = True++ temp_file = TrackingTempFile()+ thumbnail = MagicMock()++ def save(_path: Path, format: str) -> None:+ assert temp_file.closed++ thumbnail.save.side_effect = save+ source_image = MagicMock()+ source_image.__enter__.return_value = source_image++ with (+ patch("invokeai.app.services.image_moves.image_moves_default.Image.open", return_value=source_image),+ patch("invokeai.app.services.image_moves.image_moves_default.make_thumbnail", return_value=thumbnail),+ patch(+ "invokeai.app.services.image_moves.image_moves_default.tempfile.NamedTemporaryFile", return_value=temp_file+ ),+ patch.object(service, "_fsync_file"),+ patch.object(service, "_fsync_dir"),+ patch("invokeai.app.services.image_moves.image_moves_default.os.replace"),+ ):+ service._regenerate_thumbnail(tmp_path / "source.png", tmp_path / "thumbnail.webp")++ assert temp_file.closed++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"@@ -679,6 +727,177 @@ def test_startup_recovery_marks_error_when_neither_old_nor_new_full_size_file_exassert _job_item_states(service, job_id) == {image_name: "error"}+def test_startup_recovery_isolates_corrupt_image_and_commits_other_items(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ good_image_name = "image-a-good.png"+ corrupt_image_name = "image-b-corrupt.png"+ _save_image(service, records, good_image_name, "", "2024-09-10 11:12:13.000", "white")+ _save_image(service, records, corrupt_image_name, "", "2024-09-11 11:12:13.000", "black")++ moves = service.plan_batch(last_image_name="", limit=100)+ corrupt_move = next(move for move in moves if move.image_name == corrupt_image_name)+ corrupt_move.old_thumbnail_path.unlink()+ corrupt_move.old_path.write_bytes(b"")+ job_id = service.create_move_job(moves)++ recovered = service.startup_recovery()++ assert recovered.committed == 1+ assert recovered.errors == 1+ assert service.is_maintenance_active() is False+ assert service.get_job(job_id).state == "error"+ assert corrupt_image_name in (service.get_job(job_id).error_message or "")+ assert _job_item_states(service, job_id) == {+ good_image_name: "committed",+ corrupt_image_name: "error",+ }+ assert records.get(good_image_name).image_subfolder == "2024/09/10"+ assert records.get(corrupt_image_name).image_subfolder == ""+ assert service.image_files.get_path(good_image_name, image_subfolder="2024/09/10").exists()+ assert not service.image_files.get_path(good_image_name, image_subfolder="").exists()+ assert corrupt_move.old_path.exists()+ assert not corrupt_move.new_path.exists()+++def test_startup_recovery_marks_truncated_image_error_without_retrying_forever(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_name = "image-truncated.png"+ _save_image(service, records, image_name, "", "2024-09-12 11:12:13.000", "white")+ move = service.plan_batch(last_image_name="", limit=100)[0]+ move.old_thumbnail_path.unlink()+ job_id = service.create_move_job([move])++ with patch.object(+ service,+ "_regenerate_thumbnail",+ side_effect=UnreadableImageError("image file is truncated (0 bytes not processed)"),+ ):+ recovered = service.startup_recovery()++ assert recovered.committed == 0+ assert recovered.errors == 1+ assert service.is_maintenance_active() is False+ assert service.get_job(job_id).state == "error"+ assert _job_item_states(service, job_id) == {image_name: "error"}+ assert records.get(image_name).image_subfolder == ""+ assert move.old_path.exists()+ assert not move.new_path.exists()+++def test_move_all_images_marks_corrupt_idat_as_unrecoverable(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_name = "image-corrupt-idat.png"+ _save_image(service, records, image_name, "", "2024-09-16 11:12:13.000", "white")+ move = service.plan_batch(last_image_name="", limit=100)[0]+ move.old_thumbnail_path.unlink()+ _corrupt_png_idat(move.old_path)++ result = service.move_all_images()++ assert result.committed == 0+ assert result.errors == 1+ assert service.is_maintenance_active() is False+ assert service.get_latest_job().state == "error"+ assert records.get(image_name).image_subfolder == ""+ assert move.old_path.exists()+ assert not move.new_path.exists()+++def test_move_all_images_counts_and_reports_each_unrecoverable_item(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_names = ["image-corrupt-a.png", "image-corrupt-b.png"]+ for index, image_name in enumerate(image_names):+ _save_image(+ service,+ records,+ image_name,+ "",+ f"2024-09-{17 + index:02d} 11:12:13.000",+ "white",+ )++ moves = service.plan_batch(last_image_name="", limit=100)+ for move in moves:+ move.old_thumbnail_path.unlink()+ _corrupt_png_idat(move.old_path)++ result = service.move_all_images()++ assert result.committed == 0+ assert result.errors == len(image_names)+ error_message = service.get_latest_job().error_message or ""+ assert all(image_name in error_message for image_name in image_names)+ assert all(records.get(image_name).image_subfolder == "" for image_name in image_names)+++def test_startup_recovery_keeps_db_consistent_when_thumbnail_regeneration_fails(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_name = "image-thumbnail-recovery.png"+ _save_image(service, records, image_name, "", "2024-09-13 11:12:13.000", "white")+ move = service.plan_batch(last_image_name="", limit=100)[0]+ move.new_thumbnail_path.parent.mkdir(parents=True, exist_ok=True)+ copy2(move.old_thumbnail_path, move.new_thumbnail_path)+ job_id = service.create_move_job([move])++ with patch.object(+ service,+ "_regenerate_thumbnail",+ side_effect=UnreadableImageError("image file is truncated (0 bytes not processed)"),+ ):+ recovered = service.startup_recovery()++ assert recovered.committed == 0+ assert recovered.errors == 1+ assert service.get_job(job_id).state == "error"+ assert records.get(image_name).image_subfolder == ""+ assert move.old_path.exists()+ assert not move.new_path.exists()+++def test_startup_recovery_reconciles_db_after_destination_thumbnail_failure(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_name = "image-destination-recovery.png"+ _save_image(service, records, image_name, "", "2024-09-15 11:12:13.000", "white")+ move = service.plan_batch(last_image_name="", limit=100)[0]+ move.old_thumbnail_path.unlink()+ move.new_path.parent.mkdir(parents=True, exist_ok=True)+ move.old_path.replace(move.new_path)+ job_id = service.create_move_job([move])++ with patch.object(+ service,+ "_regenerate_thumbnail",+ side_effect=UnreadableImageError("image file is truncated (0 bytes not processed)"),+ ):+ recovered = service.startup_recovery()++ assert recovered.committed == 0+ assert recovered.errors == 1+ assert service.is_maintenance_active() is False+ assert service.get_job(job_id).state == "error"+ assert _job_item_states(service, job_id) == {image_name: "error"}+ assert records.get(image_name).image_subfolder == "2024/09/15"+ assert not move.old_path.exists()+ assert move.new_path.exists()+++def test_startup_recovery_finalizes_job_after_item_error_was_recorded(tmp_path: Path) -> None:+ service, records = _service(tmp_path, strategy="date")+ image_name = "image-recorded-error.png"+ _save_image(service, records, image_name, "", "2024-09-14 11:12:13.000", "white")+ move = service.plan_batch(last_image_name="", limit=100)[0]+ job_id = service.create_move_job([move])+ service.mark_item_unrecoverable(job_id, image_name, "image is corrupt")++ recovered = service.startup_recovery()++ assert recovered.committed == 0+ assert recovered.errors == 1+ assert service.is_maintenance_active() is False+ assert service.get_job(job_id).state == "error"+ assert _job_item_states(service, job_id) == {image_name: "error"}++def test_startup_recovery_keeps_job_recoverable_after_ordinary_exception(tmp_path: Path) -> None:service, records = _service(tmp_path, strategy="date")image_name = "image-k.png"